Skip to content

Commit

Permalink
Merge pull request #563 from aternosorg/prevent-parallel-safe-search-…
Browse files Browse the repository at this point in the history
…requests

prevent sending the same image to safe search twice if it's sent in q…
  • Loading branch information
JulianVennen authored Mar 18, 2023
2 parents 4b5db2c + fdb0328 commit 91bba78
Showing 1 changed file with 32 additions and 4 deletions.
36 changes: 32 additions & 4 deletions src/automod/SafeSearch.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,19 @@ import vision from '@google-cloud/vision';
import Cache from '../bot/Cache.js';
import Request from '../bot/Request.js';
import database from '../bot/Database.js';
import logger from '../bot/Logger.js';

const CACHE_DURATION = 60 * 60 * 1000;

export default class SafeSearch {
#cache = new Cache();

/**
* A map of hashes to resolve functions that are currently waiting for a response from the api
* @type {Map<string, function[]>}
*/
#requesting = new Map();

constructor() {
if (this.isEnabled) {
this.annotatorClient = new vision.ImageAnnotatorClient({
Expand Down Expand Up @@ -79,11 +86,32 @@ export default class SafeSearch {
return cached;
}

const [{safeSearchAnnotation}] = await this.annotatorClient.safeSearchDetection(image.url);
if (safeSearchAnnotation) {
this.#cache.set(hash, safeSearchAnnotation, CACHE_DURATION);
await database.query('INSERT INTO safeSearch (hash, data) VALUES (?, ?)', hash, JSON.stringify(safeSearchAnnotation));
if (this.#requesting.has(hash)) {
return await new Promise(resolve => {
this.#requesting.get(hash).push(resolve);
});
}

this.#requesting.set(hash, []);

let safeSearchAnnotation = null;
try {
[{safeSearchAnnotation}] = await this.annotatorClient.safeSearchDetection(image.url);

if (safeSearchAnnotation) {
this.#cache.set(hash, safeSearchAnnotation, CACHE_DURATION);
await database.query('INSERT INTO safeSearch (hash, data) VALUES (?, ?)', hash, JSON.stringify(safeSearchAnnotation));
}
}
catch (error) {
await logger.error(error);
}

for (const resolve of this.#requesting.get(hash)) {
resolve(safeSearchAnnotation);
}
this.#requesting.delete(hash);

return safeSearchAnnotation;
}

Expand Down

0 comments on commit 91bba78

Please sign in to comment.