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

environment-cache-store.ts

241 lines9.4 KB

1import {
2 ORCHESTRATION_CACHE_SCHEMA_VERSION,
3 StoredOrchestrationThreadSnapshot,
4 Persistence,
5} from "@t3tools/client-runtime/platform";
6import { type EnvironmentId, ServerConfig, VcsListRefsResult } from "@t3tools/contracts";
7import * as Effect from "effect/Effect";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Schema from "effect/Schema";
11​
12import * as MobileDatabase from "../persistence/mobile-database";
13import { makeStoredShellSnapshotEncoder } from "./shell-cache-encoding";
14import {
15 attachProjectFaviconDatabase,
16 projectFaviconDatabaseCache,
17} from "../lib/projectFaviconDatabaseCache";
18import { decodeStoredShellSnapshot } from "./shell-cache-decoding";
19​
20const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1;
21const VCS_REFS_CACHE_SCHEMA_VERSION = 1;
22​
23const StoredServerConfig = Schema.Struct({
24 schemaVersion: Schema.Literal(SERVER_CONFIG_CACHE_SCHEMA_VERSION),
25 environmentId: Schema.String,
26 config: ServerConfig,
27});
28const StoredVcsRefs = Schema.Struct({
29 schemaVersion: Schema.Literal(VCS_REFS_CACHE_SCHEMA_VERSION),
30 environmentId: Schema.String,
31 cwd: Schema.String,
32 refs: VcsListRefsResult,
33});
34​
35const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(
36 Schema.fromJsonString(StoredOrchestrationThreadSnapshot),
37);
38const encodeStoredThreadSnapshot = Schema.encodeEffect(
39 Schema.fromJsonString(StoredOrchestrationThreadSnapshot),
40);
41const decodeStoredServerConfig = Schema.decodeUnknownEffect(
42 Schema.fromJsonString(StoredServerConfig),
43);
44const encodeStoredServerConfig = Schema.encodeEffect(Schema.fromJsonString(StoredServerConfig));
45const decodeStoredVcsRefs = Schema.decodeUnknownEffect(Schema.fromJsonString(StoredVcsRefs));
46const encodeStoredVcsRefs = Schema.encodeEffect(Schema.fromJsonString(StoredVcsRefs));
47​
48type CacheOperation = Persistence.ConnectionPersistenceError["operation"];
49​
50function persistenceError(operation: CacheOperation, cause: unknown) {
51 return new Persistence.ConnectionPersistenceError({
52 operation,
53 message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
54 });
56​
57function mapDatabaseError(operation: CacheOperation) {
58 return (error: MobileDatabase.MobileDatabaseError) => persistenceError(operation, error);
60​
61function loadDecodedCache<A, B>(input: {
62 readonly database: MobileDatabase.MobileDatabase["Service"];
63 readonly environmentId: EnvironmentId;
64 readonly kind: MobileDatabase.ClientCacheKind;
65 readonly cacheKey: string;
66 readonly operation: CacheOperation;
67 readonly decode: (raw: string) => Effect.Effect<A, unknown>;
68 readonly select: (value: A) => Option.Option<B>;
69}): Effect.Effect<Option.Option<B>, Persistence.ConnectionPersistenceError> {
70 return input.database.loadCache(input.environmentId, input.kind, input.cacheKey).pipe(
71 Effect.mapError(mapDatabaseError(input.operation)),
72 Effect.flatMap(
73 Option.match({
74 onNone: () => Effect.succeed(Option.none<B>()),
75 onSome: (raw) =>
76 input.decode(raw).pipe(
77 Effect.map(input.select),
78 Effect.catch((cause) =>
79 Effect.logWarning("Discarding corrupt mobile client cache record.", {
80 environmentId: input.environmentId,
81 kind: input.kind,
82 cacheKey: input.cacheKey,
83 cause: String(cause),
84 }).pipe(
85 Effect.andThen(
86 input.database
87 .removeCache(input.environmentId, input.kind, input.cacheKey)
88 .pipe(Effect.catch(() => Effect.void)),
89 ),
90 Effect.as(Option.none<B>()),
91 ),
92 ),
93 ),
94 }),
95 ),
96 );
98​
99export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () {
100 const database = yield* MobileDatabase.MobileDatabase;
101 attachProjectFaviconDatabase(database);
102 const encodeStoredShellSnapshot = makeStoredShellSnapshotEncoder();
103 return Persistence.EnvironmentCacheStore.of({
104 loadShell: Effect.fn("MobileEnvironmentCache.loadShell")((environmentId) =>
105 loadDecodedCache({
106 database,
107 environmentId,
108 kind: "shell",
109 cacheKey: "snapshot",
110 operation: "load-shell",
111 decode: decodeStoredShellSnapshot,
112 select: (stored) =>
113 stored.environmentId === environmentId ? Option.some(stored.snapshot) : Option.none(),
114 }).pipe(
115 // Read cached project icons in parallel with the shell so the first rows can show
116 // them, instead of making the thread list wait for the icon read after the decode.
117 Effect.zipWith(
118 Effect.promise(() => projectFaviconDatabaseCache.hydrate()),
119 (snapshot) => snapshot,
120 { concurrent: true },
121 ),
122 ),
123 ),
124 saveShell: Effect.fn("MobileEnvironmentCache.saveShell")(function* (environmentId, snapshot) {
125 const payload = yield* encodeStoredShellSnapshot({
126 schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
127 environmentId,
128 snapshot,
129 }).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
130 yield* database
131 .saveCache(environmentId, "shell", "snapshot", ORCHESTRATION_CACHE_SCHEMA_VERSION, payload)
132 .pipe(Effect.mapError(mapDatabaseError("save-shell")));
133 }),
134 loadThread: Effect.fn("MobileEnvironmentCache.loadThread")((environmentId, threadId) =>
135 loadDecodedCache({
136 database,
137 environmentId,
138 kind: "thread",
139 cacheKey: threadId,
140 operation: "load-thread",
141 decode: decodeStoredThreadSnapshot,
142 select: (stored) =>
143 stored.environmentId === environmentId && stored.threadId === threadId
144 ? Option.some(stored.snapshot)
145 : Option.none(),
146 }),
147 ),
148 saveThread: Effect.fn("MobileEnvironmentCache.saveThread")(function* (environmentId, snapshot) {
149 const threadId = snapshot.projection.thread.id;
150 const payload = yield* encodeStoredThreadSnapshot({
151 schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
152 environmentId,
153 threadId,
154 snapshot,
155 }).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
156 yield* database
157 .saveCache(environmentId, "thread", threadId, ORCHESTRATION_CACHE_SCHEMA_VERSION, payload)
158 .pipe(Effect.mapError(mapDatabaseError("save-thread")));
159 }),
160 removeThread: Effect.fn("MobileEnvironmentCache.removeThread")((environmentId, threadId) =>
161 database
162 .removeCache(environmentId, "thread", threadId)
163 .pipe(Effect.mapError(mapDatabaseError("remove-thread"))),
164 ),
165 loadServerConfig: Effect.fn("MobileEnvironmentCache.loadServerConfig")((environmentId) =>
166 loadDecodedCache({
167 database,
168 environmentId,
169 kind: "server-config",
170 cacheKey: "config",
171 operation: "load-server-config",
172 decode: decodeStoredServerConfig,
173 select: (stored) =>
174 stored.environmentId === environmentId ? Option.some(stored.config) : Option.none(),
175 }),
176 ),
177 saveServerConfig: Effect.fn("MobileEnvironmentCache.saveServerConfig")(
178 function* (environmentId, config) {
179 const payload = yield* encodeStoredServerConfig({
180 schemaVersion: SERVER_CONFIG_CACHE_SCHEMA_VERSION,
181 environmentId,
182 config,
183 }).pipe(Effect.mapError((cause) => persistenceError("save-server-config", cause)));
184 yield* database
185 .saveCache(
186 environmentId,
187 "server-config",
188 "config",
189 SERVER_CONFIG_CACHE_SCHEMA_VERSION,
190 payload,
191 )
192 .pipe(Effect.mapError(mapDatabaseError("save-server-config")));
193 },
194 ),
195 loadVcsRefs: Effect.fn("MobileEnvironmentCache.loadVcsRefs")((environmentId, cwd) =>
196 loadDecodedCache({
197 database,
198 environmentId,
199 kind: "vcs-refs",
200 cacheKey: cwd,
201 operation: "load-vcs-refs",
202 decode: decodeStoredVcsRefs,
203 select: (stored) =>
204 stored.environmentId === environmentId && stored.cwd === cwd
205 ? Option.some(stored.refs)
206 : Option.none(),
207 }),
208 ),
209 saveVcsRefs: Effect.fn("MobileEnvironmentCache.saveVcsRefs")(
210 function* (environmentId, cwd, refs) {
211 const payload = yield* encodeStoredVcsRefs({
212 schemaVersion: VCS_REFS_CACHE_SCHEMA_VERSION,
213 environmentId,
214 cwd,
215 refs,
216 }).pipe(Effect.mapError((cause) => persistenceError("save-vcs-refs", cause)));
217 yield* database
218 .saveCache(environmentId, "vcs-refs", cwd, VCS_REFS_CACHE_SCHEMA_VERSION, payload)
219 .pipe(Effect.mapError(mapDatabaseError("save-vcs-refs")));
220 },
221 ),
222 removeVcsRefs: Effect.fn("MobileEnvironmentCache.removeVcsRefs")((environmentId, cwd) =>
223 database
224 .removeCache(environmentId, "vcs-refs", cwd)
225 .pipe(Effect.mapError(mapDatabaseError("remove-vcs-refs"))),
226 ),
227 clearVcsRefs: Effect.fn("MobileEnvironmentCache.clearVcsRefs")((environmentId) =>
228 database
229 .clearCacheKind(environmentId, "vcs-refs")
230 .pipe(Effect.mapError(mapDatabaseError("clear-vcs-refs"))),
231 ),
232 clear: Effect.fn("MobileEnvironmentCache.clear")((environmentId) =>
233 Effect.promise(() => projectFaviconDatabaseCache.clearEnvironment(environmentId)).pipe(
234 Effect.andThen(database.clearEnvironmentCache(environmentId)),
235 Effect.mapError(mapDatabaseError("clear-environment")),
236 ),
237 ),
238 });
239});
240​
241export const layer = Layer.effect(Persistence.EnvironmentCacheStore, make());