Skip to content

Commit

Permalink
use apikey for delay checks
Browse files Browse the repository at this point in the history
  • Loading branch information
InventivetalentDev committed Jun 9, 2024
1 parent 3ab9f84 commit 07c98ca
Show file tree
Hide file tree
Showing 6 changed files with 49 additions and 15 deletions.
6 changes: 6 additions & 0 deletions src/database/schemas/Traffic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ TrafficSchema.statics.findForIp = function (this: ITrafficModel, ip: string): Pr
}).lean().exec();
};

TrafficSchema.statics.findForKey = function (this: ITrafficModel, key: string): Promise<LeanDocumentOrArray<ITrafficDocument | null>> {
return this.findOne({key: key}, null, {
sort: {lastRequest: -1}
}).lean().exec();
}

TrafficSchema.statics.updateRequestTime = function (this: ITrafficModel, ip: string, key: string | null, time: Date = new Date()): Promise<any> {
return this.updateOne({
ip: ip,
Expand Down
19 changes: 19 additions & 0 deletions src/generator/Caching.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,14 @@ export class Caching {
return traffic?.lastRequest;
});

protected static readonly trafficByKeyCache: AsyncLoadingCache<string, Date> = Caches.builder()
.expireAfterWrite(Time.seconds(5))
.expirationInterval(Time.seconds(1))
.buildAsync<string, Date>(async (key) => {
const traffic = await Traffic.findForKey(key);
return traffic?.lastRequest;
});

protected static readonly skinByIdCache: AsyncLoadingCache<number, ISkinDocument> = Caches.builder()
.expireAfterWrite(Time.minutes(1))
.expirationInterval(Time.seconds(30))
Expand Down Expand Up @@ -292,8 +300,19 @@ export class Caching {
return this.trafficByIpCache.get(ip);
}

public static getTrafficRequestTimeByApiKey(key: IApiKeyDocument): Promise<Maybe<Date>> {
return this.trafficByKeyCache.get(key._id);
}

public static getTrafficRequestTimeByKey(key: string): Promise<Maybe<Date>> {
return this.trafficByKeyCache.get(key);
}

public static async updateTrafficRequestTime(ip: string, key: string | null, time: Date): Promise<any> {
this.trafficByIpCache.put(ip, time);
if (key) {
this.trafficByKeyCache.put(key, time);
}
return await Traffic.updateRequestTime(ip, key, time);
}

Expand Down
14 changes: 8 additions & 6 deletions src/routes/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export const register = (app: Application) => {
}

const skin = await Generator.generateFromUrlAndSave(url, options, client);
await sendSkin(req, res, skin);
await sendSkin(req, res, skin, client);
})


Expand Down Expand Up @@ -113,7 +113,7 @@ export const register = (app: Application) => {
}

const skin = await Generator.generateFromUploadAndSave(file, options, client);
await sendSkin(req, res, skin);
await sendSkin(req, res, skin, client);
})


Expand Down Expand Up @@ -155,7 +155,7 @@ export const register = (app: Application) => {
console.log(debug(`${ options.breadcrumb } USER: ${ uuids.long }`))

const skin = await Generator.generateFromUserAndSave(uuids.long, options, client);
await sendSkin(req, res, skin);
await sendSkin(req, res, skin, client);
})

// TODO: remove at some point
Expand Down Expand Up @@ -195,18 +195,19 @@ export const register = (app: Application) => {
console.log(debug(`${ options.breadcrumb } USER: ${ uuids.long }`))

const skin = await Generator.generateFromUserAndSave(uuids.long, options, client);
await sendSkin(req, res, skin);
await sendSkin(req, res, skin, client);
})

///

async function sendSkin(req: Request, res: Response, skin: SavedSkin): Promise<void> {
async function sendSkin(req: Request, res: Response, skin: SavedSkin, client: ClientInfo): Promise<void> {
const delayInfo = await Generator.getDelay(await getAndValidateRequestApiKey(req));
const json = await skin.toResponseJson(skin.duplicate ? { seconds: 0, millis: 100 } : delayInfo); //TODO: adjust delay for duplicate
res.json(json);

if (skin.duplicate) {
await updateTraffic(req, new Date(Date.now() - delayInfo.millis))
// reset traffic for duplicates
await updateTraffic(client, new Date(Date.now() - delayInfo.millis))
}

getUserFromRequest(req, res, false).then(user => {
Expand Down Expand Up @@ -268,6 +269,7 @@ export const register = (app: Application) => {
const breadcrumb = nextBreadColor()(breadcrumbId);
req.breadcrumb = breadcrumb;
res.header("X-MineSkin-Breadcrumb", breadcrumbId);
res.header("X-MineSkin-Timestamp", `${ Date.now() }`);

console.log(debug(`${ breadcrumb } Type: ${ type }`))
console.log(debug(`${ breadcrumb } Variant: ${ variant }`));
Expand Down
9 changes: 7 additions & 2 deletions src/routes/get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ export const register = (app: Application) => {
app.use("/get", corsWithAuthMiddleware);

app.get("/get/delay", async (req: Request, res: Response) => {
const delayInfo = await Generator.getDelay(await getAndValidateRequestApiKey(req));
const lastRequest = await Caching.getTrafficRequestTimeByIp(getIp(req));
const apiKey = await getAndValidateRequestApiKey(req);
const delayInfo = await Generator.getDelay(apiKey);
const lastRequest = apiKey ? await Caching.getTrafficRequestTimeByApiKey(apiKey) : await Caching.getTrafficRequestTimeByIp(getIp(req));
if (lastRequest) {
res.json({
delay: delayInfo.seconds, // deprecated
Expand All @@ -26,6 +27,10 @@ export const register = (app: Application) => {
nextRequest: {
time: Math.round(lastRequest.getTime() + delayInfo.millis),
relative: Math.round(Math.max(100, ((lastRequest.getTime()) + delayInfo.millis) - Date.now()))
},

lastRequest: {
time: lastRequest.getTime()
}
});
} else {
Expand Down
2 changes: 2 additions & 0 deletions src/typings/db/ITrafficDocument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,7 @@ export interface ITrafficDocument extends Document {
export interface ITrafficModel extends Model<ITrafficDocument> {
findForIp(ip: string): Promise<Maybe<ITrafficDocument>>;

findForKey(key: string): Promise<Maybe<ITrafficDocument>>;

updateRequestTime(ip: string, key: string | null, time?: Date): Promise<any>;
}
14 changes: 7 additions & 7 deletions src/util/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,6 @@ export async function checkTraffic(req: Request, res: Response): Promise<boolean
ip_address: ip
});

const lastRequest = await Caching.getTrafficRequestTimeByIp(ip);
if (!lastRequest) { // First request
span?.finish();
return true;
}
const time = Date.now();

const apiKey = await getAndValidateRequestApiKey(req);
if (apiKey) {
Sentry.setUser({
Expand All @@ -49,6 +42,13 @@ export async function checkTraffic(req: Request, res: Response): Promise<boolean
});
}

const lastRequest = apiKey ? await Caching.getTrafficRequestTimeByApiKey(apiKey) : await Caching.getTrafficRequestTimeByIp(ip);
if (!lastRequest) { // First request
span?.finish();
return true;
}
const time = Date.now();

const delayInfo = await Generator.getDelay(apiKey);

if (lastRequest.getTime() > time - delayInfo.millis) {
Expand Down

0 comments on commit 07c98ca

Please sign in to comment.