1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-02-14 00:19:16 +01:00
unleash.unleash/src/lib/services/edge-service.ts
Gastón Fournier 067d130a8b
chore: memoizee active tokens (#6135)
## About the changes
getAllActive from api-tokens store is the second most frequent query

![image](https://github.com/Unleash/unleash/assets/455064/63c5ae76-bb62-41b2-95b4-82aca59a7c16)

To prevent starving our db connections, we can cache this data that
rarely changes and clear the cache when we see changes. Because we will
only clear changes in the node receiving the change we're only caching
the data for 1 minute.

This should give us some room to test if this solution will work

---------

Co-authored-by: Nuno Góis <github@nunogois.com>
2024-02-06 15:14:08 +01:00

41 lines
1.4 KiB
TypeScript

import { IUnleashConfig } from '../types';
import { Logger } from '../logger';
import { EdgeTokenSchema } from '../openapi/spec/edge-token-schema';
import { constantTimeCompare } from '../util/constantTimeCompare';
import { ValidatedEdgeTokensSchema } from '../openapi/spec/validated-edge-tokens-schema';
import { ApiTokenService } from './api-token-service';
export default class EdgeService {
private logger: Logger;
private apiTokenService: ApiTokenService;
constructor(
{ apiTokenService }: { apiTokenService: ApiTokenService },
{ getLogger }: Pick<IUnleashConfig, 'getLogger'>,
) {
this.logger = getLogger('lib/services/edge-service.ts');
this.apiTokenService = apiTokenService;
}
async getValidTokens(tokens: string[]): Promise<ValidatedEdgeTokensSchema> {
const activeTokens = await this.apiTokenService.getAllActiveTokens();
const edgeTokens = tokens.reduce((result: EdgeTokenSchema[], token) => {
const dbToken = activeTokens.find((activeToken) =>
constantTimeCompare(activeToken.secret, token),
);
if (dbToken) {
result.push({
token: token,
type: dbToken.type,
projects: dbToken.projects,
});
}
return result;
}, []);
return { tokens: edgeTokens };
}
}
module.exports = EdgeService;