Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

providerStatusCache.ts

141 lines5.0 KB

1import {
2 type ProviderInstanceId,
3 type ServerProvider,
4 ServerProvider as ServerProviderSchema,
5} from "@t3tools/contracts";
6import { causeErrorTag } from "@t3tools/shared/observability";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Path from "effect/Path";
10import * as Schema from "effect/Schema";
11​
12import { writeFileStringAtomically } from "../atomicWrite.ts";
13​
14const decodeProviderStatusCache = Schema.decodeUnknownEffect(
15 Schema.fromJsonString(ServerProviderSchema),
16);
17​
18const mergeProviderModels = (
19 fallbackModels: ReadonlyArray<ServerProvider["models"][number]>,
20 cachedModels: ReadonlyArray<ServerProvider["models"][number]>,
21): ReadonlyArray<ServerProvider["models"][number]> => {
22 const fallbackSlugs = new Set(fallbackModels.map((model) => model.slug));
23 // The fallback snapshot is built from current settings and already carries
24 // every custom model, so cached custom rows that are not in it were removed
25 // while the cache was stale and must not come back.
26 return [
27 ...fallbackModels,
28 ...cachedModels.filter((model) => !model.isCustom && !fallbackSlugs.has(model.slug)),
29 ];
30};
31​
32export const orderProviderSnapshots = (
33 providers: ReadonlyArray<ServerProvider>,
34): ReadonlyArray<ServerProvider> =>
35 [...providers].toSorted(
36 (left, right) =>
37 (left.displayName ?? "").localeCompare(right.displayName ?? "") ||
38 left.driver.localeCompare(right.driver) ||
39 left.instanceId.localeCompare(right.instanceId),
40 );
41​
42export const isCachedProviderCorrelated = (input: {
43 readonly cachedProvider: ServerProvider;
44 readonly fallbackProvider: ServerProvider;
45}): boolean =>
46 input.cachedProvider.instanceId === input.fallbackProvider.instanceId &&
47 input.cachedProvider.driver === input.fallbackProvider.driver;
48​
49export const hydrateCachedProvider = (input: {
50 readonly cachedProvider: ServerProvider;
51 readonly fallbackProvider: ServerProvider;
52}): ServerProvider => {
53 if (!isCachedProviderCorrelated(input)) {
54 return input.fallbackProvider;
55 }
56​
57 if (
58 !input.fallbackProvider.enabled ||
59 input.cachedProvider.enabled !== input.fallbackProvider.enabled
60 ) {
61 return input.fallbackProvider;
62 }
63​
64 const { message: _fallbackMessage, ...fallbackWithoutMessage } = input.fallbackProvider;
65 const hydratedProvider: ServerProvider = {
66 ...fallbackWithoutMessage,
67 models: mergeProviderModels(input.fallbackProvider.models, input.cachedProvider.models),
68 installed: input.cachedProvider.installed,
69 version: input.cachedProvider.version,
70 status: input.cachedProvider.status,
71 auth: input.cachedProvider.auth,
72 checkedAt: input.cachedProvider.checkedAt,
73 slashCommands: input.cachedProvider.slashCommands,
74 skills: input.cachedProvider.skills,
75 };
76​
77 return input.cachedProvider.message
78 ? { ...hydratedProvider, message: input.cachedProvider.message }
79 : hydratedProvider;
80};
81​
82/**
83 * Resolve the on-disk cache path for a provider instance snapshot.
84 *
85 * File naming: `<cacheDir>/<instanceId>.json`. For the default instance of
86 * a built-in kind this equals the legacy `<kind>.json` path (because
87 * `defaultInstanceIdForDriver(kind).toString() === kind`), so existing
88 * cached snapshots remain readable without any rename step.
89 *
90 * Non-default instances (e.g. `codex_personal`) land in their own files and
91 * never collide with other instances.
92 *
93 * Cache contents must still carry matching `instanceId` + `driver` identity
94 * before hydration. The filename alone is not trusted as a routing key.
95 */
96export const resolveProviderStatusCachePath = Effect.fn("resolveProviderStatusCachePath")(
97 function* (input: {
98 readonly cacheDir: string;
99 readonly instanceId: ProviderInstanceId;
100 }): Effect.fn.Return<string, never, Path.Path> {
101 const path = yield* Path.Path;
102 return path.join(input.cacheDir, `${input.instanceId}.json`);
103 },
104);
105​
106export const readProviderStatusCache = (filePath: string) =>
107 Effect.gen(function* () {
108 const fs = yield* FileSystem.FileSystem;
109 const exists = yield* fs.exists(filePath).pipe(Effect.orElseSucceed(() => false));
110 if (!exists) {
111 return undefined;
112 }
113​
114 const raw = yield* fs.readFileString(filePath).pipe(Effect.orElseSucceed(() => ""));
115 const trimmed = raw.trim();
116 if (trimmed.length === 0) {
117 return undefined;
118 }
119​
120 return yield* decodeProviderStatusCache(trimmed).pipe(
121 Effect.matchCauseEffect({
122 onFailure: (cause) =>
123 Effect.logWarning("failed to parse provider status cache, ignoring", {
124 path: filePath,
125 errorTag: causeErrorTag(cause),
126 }).pipe(Effect.as(undefined)),
127 onSuccess: Effect.succeed,
128 }),
129 );
130 });
131​
132export const writeProviderStatusCache = (input: {
133 readonly filePath: string;
134 readonly provider: ServerProvider;
135}) => {
136 const { updateState: _updateState, ...cacheableProvider } = input.provider;
137 return writeFileStringAtomically({
138 filePath: input.filePath,
139 contents: `${JSON.stringify(cacheableProvider, null, 2)}\n`,
140 });
141};