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

providerStatusCache.ts

153 lines5.4 KB

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