2022-09-17 11:27:08 -07:00
|
|
|
import { Inject, Injectable } from '@nestjs/common';
|
2022-09-20 13:33:11 -07:00
|
|
|
import type { InstancesRepository } from '@/models/index.js';
|
2022-09-17 11:27:08 -07:00
|
|
|
import type { Instance } from '@/models/entities/Instance.js';
|
2023-04-03 23:56:47 -07:00
|
|
|
import { MemoryKVCache } from '@/misc/cache.js';
|
2022-09-17 11:27:08 -07:00
|
|
|
import { IdService } from '@/core/IdService.js';
|
|
|
|
import { DI } from '@/di-symbols.js';
|
2022-12-03 17:16:03 -08:00
|
|
|
import { UtilityService } from '@/core/UtilityService.js';
|
2022-12-03 22:03:09 -08:00
|
|
|
import { bindThis } from '@/decorators.js';
|
2022-09-17 11:27:08 -07:00
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class FederatedInstanceService {
|
2023-04-03 23:56:47 -07:00
|
|
|
private cache: MemoryKVCache<Instance>;
|
2022-09-17 11:27:08 -07:00
|
|
|
|
|
|
|
constructor(
|
|
|
|
@Inject(DI.instancesRepository)
|
|
|
|
private instancesRepository: InstancesRepository,
|
|
|
|
|
|
|
|
private utilityService: UtilityService,
|
|
|
|
private idService: IdService,
|
|
|
|
) {
|
2023-04-03 23:56:47 -07:00
|
|
|
this.cache = new MemoryKVCache<Instance>(1000 * 60 * 60);
|
2022-09-17 11:27:08 -07:00
|
|
|
}
|
|
|
|
|
2022-12-03 22:03:09 -08:00
|
|
|
@bindThis
|
2023-01-02 16:32:36 -08:00
|
|
|
public async fetch(host: string): Promise<Instance> {
|
2022-09-17 11:27:08 -07:00
|
|
|
host = this.utilityService.toPuny(host);
|
|
|
|
|
2022-09-18 11:11:50 -07:00
|
|
|
const cached = this.cache.get(host);
|
2022-09-17 11:27:08 -07:00
|
|
|
if (cached) return cached;
|
|
|
|
|
|
|
|
const index = await this.instancesRepository.findOneBy({ host });
|
|
|
|
|
|
|
|
if (index == null) {
|
|
|
|
const i = await this.instancesRepository.insert({
|
|
|
|
id: this.idService.genId(),
|
|
|
|
host,
|
2023-01-15 12:02:38 -08:00
|
|
|
firstRetrievedAt: new Date(),
|
2022-09-17 11:27:08 -07:00
|
|
|
}).then(x => this.instancesRepository.findOneByOrFail(x.identifiers[0]));
|
|
|
|
|
2022-09-18 11:11:50 -07:00
|
|
|
this.cache.set(host, i);
|
2022-09-17 11:27:08 -07:00
|
|
|
return i;
|
|
|
|
} else {
|
2022-09-18 11:11:50 -07:00
|
|
|
this.cache.set(host, index);
|
2022-09-17 11:27:08 -07:00
|
|
|
return index;
|
|
|
|
}
|
|
|
|
}
|
2023-01-02 16:32:36 -08:00
|
|
|
|
|
|
|
@bindThis
|
|
|
|
public async updateCachePartial(host: string, data: Partial<Instance>): Promise<void> {
|
|
|
|
host = this.utilityService.toPuny(host);
|
|
|
|
|
|
|
|
const cached = this.cache.get(host);
|
|
|
|
if (cached == null) return;
|
|
|
|
|
|
|
|
this.cache.set(host, {
|
|
|
|
...cached,
|
|
|
|
...data,
|
|
|
|
});
|
|
|
|
}
|
2022-09-17 11:27:08 -07:00
|
|
|
}
|