98 lines
3.5 KiB
TypeScript
98 lines
3.5 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
||
import { type Catalog, mergeIntoCatalog, type RunReport, type RunTrigger, withoutExamples } from "../domain/internship.js";
|
||
import type { CatalogStore } from "../store/catalogStore.js";
|
||
import type { SearchProvider } from "./provider.js";
|
||
|
||
export class SearchAlreadyRunningError extends Error {
|
||
constructor() {
|
||
super("Поиск уже идёт");
|
||
this.name = "SearchAlreadyRunningError";
|
||
}
|
||
}
|
||
|
||
export interface SearchServiceOptions {
|
||
store: CatalogStore;
|
||
provider: SearchProvider;
|
||
now?: () => Date;
|
||
onError?: (error: unknown) => void;
|
||
}
|
||
|
||
/** Запускает поиск (не более одного одновременно) и вливает результаты в каталог. */
|
||
export class SearchService {
|
||
private current: Promise<RunReport> | null = null;
|
||
private currentStartedAt: string | null = null;
|
||
|
||
constructor(private readonly options: SearchServiceOptions) {}
|
||
|
||
get running(): boolean {
|
||
return this.current !== null;
|
||
}
|
||
|
||
/** Когда начался идущий поиск; null — поиск не идёт. */
|
||
get runningSince(): string | null {
|
||
return this.currentStartedAt;
|
||
}
|
||
|
||
/** Начинает поиск и возвращает промис отчёта; бросает SearchAlreadyRunningError, если поиск идёт. */
|
||
start(trigger: RunTrigger = "manual", after?: (report: RunReport) => Promise<void>): Promise<RunReport> {
|
||
if (this.current) throw new SearchAlreadyRunningError();
|
||
this.currentStartedAt = (this.options.now ?? (() => new Date()))().toISOString();
|
||
// `after` выполняется внутри блокировки: другой запуск не вклинится между поиском и его последствиями.
|
||
this.current = this.run(trigger)
|
||
.then(async (report) => {
|
||
await after?.(report);
|
||
return report;
|
||
})
|
||
.finally(() => {
|
||
this.current = null;
|
||
this.currentStartedAt = null;
|
||
});
|
||
return this.current;
|
||
}
|
||
|
||
private async run(trigger: RunTrigger): Promise<RunReport> {
|
||
const { store, provider, onError } = this.options;
|
||
const now = this.options.now ?? (() => new Date());
|
||
const id = randomUUID();
|
||
const startedAt = now().toISOString();
|
||
|
||
let candidates: unknown[];
|
||
try {
|
||
candidates = await provider.search();
|
||
} catch (error) {
|
||
onError?.(error);
|
||
const report: RunReport = {
|
||
id,
|
||
startedAt,
|
||
finishedAt: now().toISOString(),
|
||
status: "error",
|
||
found: 0,
|
||
added: 0,
|
||
rejected: 0,
|
||
error: (error as Error).message || "Неизвестная ошибка",
|
||
};
|
||
const catalog = await store.load();
|
||
await store.save({ ...catalog, lastRun: report });
|
||
return report;
|
||
}
|
||
|
||
// Настоящий поиск не оставляет в каталоге примеров, накопленных без него.
|
||
const loaded = await store.load();
|
||
const catalog = provider.name === "mock" ? loaded : withoutExamples(loaded);
|
||
const finishedAt = now().toISOString();
|
||
const merged = mergeIntoCatalog(catalog, candidates, id, finishedAt, trigger);
|
||
const report: RunReport = {
|
||
id,
|
||
startedAt,
|
||
finishedAt,
|
||
status: "ok",
|
||
found: merged.found,
|
||
added: merged.added,
|
||
rejected: merged.rejected,
|
||
};
|
||
const next: Catalog = { ...merged.catalog, lastRun: report, lastSuccessfulRunId: id };
|
||
await store.save(next);
|
||
return report;
|
||
}
|
||
}
|