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

client-cache-state.ts

87 lines2.6 KB

1import type { EnvironmentId } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import { Atom } from "effect/unstable/reactivity";
4​
5import { type ClientCacheKind, MobileDatabase } from "../persistence/mobile-database";
6import * as Runtime from "../lib/runtime";
7​
8export interface EnvironmentClientCacheSummary {
9 readonly environmentId: EnvironmentId;
10 readonly recordCount: number;
11 readonly payloadBytes: number;
12 readonly kinds: Readonly<Partial<Record<ClientCacheKind, number>>>;
14​
15export interface ClientCacheSummary {
16 readonly recordCount: number;
17 readonly payloadBytes: number;
18 readonly environments: ReadonlyArray<EnvironmentClientCacheSummary>;
20​
21export type ClientCacheClearScope =
22 | { readonly type: "all" }
23 | { readonly type: "environment"; readonly environmentId: EnvironmentId };
24​
25function aggregateCacheSummary(
26 rows: ReadonlyArray<{
27 readonly environmentId: EnvironmentId;
28 readonly kind: ClientCacheKind;
29 readonly recordCount: number;
30 readonly payloadBytes: number;
31 }>,
32): ClientCacheSummary {
33 const environments = new Map<EnvironmentId, EnvironmentClientCacheSummary>();
34 let recordCount = 0;
35 let payloadBytes = 0;
36​
37 for (const row of rows) {
38 recordCount += row.recordCount;
39 payloadBytes += row.payloadBytes;
40 const current = environments.get(row.environmentId) ?? {
41 environmentId: row.environmentId,
42 recordCount: 0,
43 payloadBytes: 0,
44 kinds: {},
45 };
46 environments.set(row.environmentId, {
47 environmentId: row.environmentId,
48 recordCount: current.recordCount + row.recordCount,
49 payloadBytes: current.payloadBytes + row.payloadBytes,
50 kinds: { ...current.kinds, [row.kind]: row.recordCount },
51 });
52 }
53​
54 return {
55 recordCount,
56 payloadBytes,
57 environments: [...environments.values()],
58 };
60​
61const clientCacheRuntime = Atom.runtime(Runtime.runtimeContextLayer);
62​
63export const clientCacheSummaryAtom = clientCacheRuntime
64 .atom(
65 MobileDatabase.pipe(
66 Effect.flatMap((database) => database.inspectCaches),
67 Effect.map(aggregateCacheSummary),
68 ),
69 )
70 .pipe(Atom.withLabel("mobile:client-cache:summary"));
71​
72export const clearClientCacheAtom = clientCacheRuntime
73 .fn((scope: ClientCacheClearScope, get) =>
74 MobileDatabase.pipe(
75 Effect.flatMap((database) =>
76 scope.type === "all"
77 ? database.clearAllCaches
78 : database.clearEnvironmentCache(scope.environmentId),
79 ),
80 Effect.tap(() =>
81 Effect.sync(() => {
82 get.refresh(clientCacheSummaryAtom);
83 }),
84 ),
85 ),
86 )
87 .pipe(Atom.withLabel("mobile:client-cache:clear"));