summaryrefslogtreecommitdiff
path: root/packages/backend/src/core/FederatedInstanceService.ts
blob: b85791e43f12f37969cf08f1265eee6db957646f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { Inject, Injectable } from '@nestjs/common';
import type { InstancesRepository } from '@/models/index.js';
import type { Instance } from '@/models/entities/Instance.js';
import { KVCache } from '@/misc/cache.js';
import { IdService } from '@/core/IdService.js';
import { DI } from '@/di-symbols.js';
import { UtilityService } from '@/core/UtilityService.js';
import { bindThis } from '@/decorators.js';

@Injectable()
export class FederatedInstanceService {
	private cache: KVCache<Instance>;

	constructor(
		@Inject(DI.instancesRepository)
		private instancesRepository: InstancesRepository,

		private utilityService: UtilityService,
		private idService: IdService,
	) {
		this.cache = new KVCache<Instance>(1000 * 60 * 60);
	}

	@bindThis
	public async fetch(host: string): Promise<Instance> {
		host = this.utilityService.toPuny(host);
	
		const cached = this.cache.get(host);
		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,
				firstRetrievedAt: new Date(),
			}).then(x => this.instancesRepository.findOneByOrFail(x.identifiers[0]));
	
			this.cache.set(host, i);
			return i;
		} else {
			this.cache.set(host, index);
			return index;
		}
	}

	@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,
		});
	}
}