misskey/packages/backend/src/core/MetaService.ts

89 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-09-17 20:27:08 +02:00
import { Inject, Injectable } from '@nestjs/common';
import { DataSource } from 'typeorm';
import Redis from 'ioredis';
2022-09-17 20:27:08 +02:00
import { DI } from '@/di-symbols.js';
import { Meta } from '@/models/entities/Meta.js';
import type { OnApplicationShutdown } from '@nestjs/common';
@Injectable()
export class MetaService implements OnApplicationShutdown {
2022-09-18 20:11:50 +02:00
private cache: Meta | undefined;
private intervalId: NodeJS.Timer;
2022-09-17 20:27:08 +02:00
constructor(
@Inject(DI.redisSubscriber)
private redisSubscriber: Redis.Redis,
2022-09-17 20:27:08 +02:00
@Inject(DI.db)
private db: DataSource,
) {
this.onMessage = this.onMessage.bind(this);
2022-09-17 20:27:08 +02:00
if (process.env.NODE_ENV !== 'test') {
2022-09-18 20:11:50 +02:00
this.intervalId = setInterval(() => {
2022-09-17 20:27:08 +02:00
this.fetch(true).then(meta => {
// fetch内でもセットしてるけど仕様変更の可能性もあるため一応
2022-09-18 20:11:50 +02:00
this.cache = meta;
2022-09-17 20:27:08 +02:00
});
}, 1000 * 60 * 5);
2022-09-17 20:27:08 +02:00
}
this.redisSubscriber.on('message', this.onMessage);
2022-09-17 20:27:08 +02:00
}
public async fetch(noCache = false): Promise<Meta> {
2022-09-18 20:11:50 +02:00
if (!noCache && this.cache) return this.cache;
2022-09-17 20:27:08 +02:00
return await this.db.transaction(async transactionalEntityManager => {
// 過去のバグでレコードが複数出来てしまっている可能性があるので新しいIDを優先する
const metas = await transactionalEntityManager.find(Meta, {
order: {
id: 'DESC',
},
});
const meta = metas[0];
if (meta) {
2022-09-18 20:11:50 +02:00
this.cache = meta;
2022-09-17 20:27:08 +02:00
return meta;
} else {
// metaが空のときfetchMetaが同時に呼ばれるとここが同時に呼ばれてしまうことがあるのでフェイルセーフなupsertを使う
const saved = await transactionalEntityManager
.upsert(
Meta,
{
id: 'x',
},
['id'],
)
.then((x) => transactionalEntityManager.findOneByOrFail(Meta, x.identifiers[0]));
2022-09-18 20:11:50 +02:00
this.cache = saved;
2022-09-17 20:27:08 +02:00
return saved;
}
});
}
private async onMessage(_, data) {
const obj = JSON.parse(data);
if (obj.channel === 'internal') {
const { type, body } = obj.message;
switch (type) {
case 'metaUpdated': {
this.cache = body;
break;
}
default:
break;
}
}
}
2022-09-17 20:27:08 +02:00
public onApplicationShutdown(signal?: string | undefined) {
2022-09-18 20:11:50 +02:00
clearInterval(this.intervalId);
this.redisSubscriber.off('message', this.onMessage);
2022-09-17 20:27:08 +02:00
}
}