perf(server): refactor and performance improvements

This commit is contained in:
syuilo 2022-03-25 16:27:41 +09:00
parent 22b56ac65c
commit ac8c66f5ab
71 changed files with 289 additions and 189 deletions

View file

@ -1,7 +1,12 @@
import isNativeToken from './common/is-native-token.js';
import { User } from '@/models/entities/user.js';
import { CacheableLocalUser, ILocalUser } from '@/models/entities/user.js';
import { Users, AccessTokens, Apps } from '@/models/index.js';
import { AccessToken } from '@/models/entities/access-token.js';
import { Cache } from '@/misc/cache.js';
import { App } from '@/models/entities/app.js';
import { localUserByIdCache, localUserByNativeTokenCache } from '@/services/user-cache.js';
const appCache = new Cache<App>(Infinity);
export class AuthenticationError extends Error {
constructor(message: string) {
@ -10,15 +15,15 @@ export class AuthenticationError extends Error {
}
}
export default async (token: string | null): Promise<[User | null | undefined, AccessToken | null | undefined]> => {
export default async (token: string | null): Promise<[CacheableLocalUser | null | undefined, AccessToken | null | undefined]> => {
if (token == null) {
return [null, null];
}
if (isNativeToken(token)) {
// Fetch user
const user = await Users
.findOne({ token });
// TODO: typeorm 3.0にしたら .then(x => x || null) は消せる
const user = await localUserByNativeTokenCache.fetch(token,
() => Users.findOne({ token }).then(x => x || null) as Promise<ILocalUser | null>);
if (user == null) {
throw new AuthenticationError('user not found');
@ -42,14 +47,14 @@ export default async (token: string | null): Promise<[User | null | undefined, A
lastUsedAt: new Date(),
});
const user = await Users
.findOne({
const user = await localUserByIdCache.fetch(accessToken.userId,
() => Users.findOne({
id: accessToken.userId, // findOne(accessToken.userId) のように書かないのは後方互換性のため
});
}) as Promise<ILocalUser>);
if (accessToken.appId) {
const app = await Apps
.findOneOrFail(accessToken.appId);
const app = await appCache.fetch(accessToken.appId,
() => Apps.findOneOrFail(accessToken.appId!));
return [user, {
id: accessToken.id,