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

mobile-storage.ts

266 lines8.6 KB

1import { EnvironmentId } from "@t3tools/contracts";
2import * as Arr from "effect/Array";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import { pipe } from "effect/Function";
6import * as Layer from "effect/Layer";
7import * as Schema from "effect/Schema";
8import * as Semaphore from "effect/Semaphore";
9​
10import {
11 isRelayManagedConnection,
12 type SavedRemoteConnection,
13 toStableSavedRemoteConnection,
14} from "../lib/connection";
15import * as MobileSecureStorage from "./mobile-secure-storage";
16​
17const CONNECTIONS_KEY = "t3code.connections";
18const AGENT_AWARENESS_DEVICE_ID_KEY = "t3code.agent-awareness.device-id";
19const AGENT_AWARENESS_REGISTRATION_KEY = "t3code.agent-awareness.registration";
20const RECENT_THREAD_SHORTCUTS_KEY = "t3code.recent-thread-shortcuts";
21​
22export class MobileStorageDecodeError extends Schema.TaggedError<MobileStorageDecodeError>()(
23 "MobileStorageDecodeError",
24 {
25 key: Schema.String,
26 cause: Schema.Defect(),
27 },
28) {
29 override get message(): string {
30 return `Failed to decode mobile storage value for key ${this.key}.`;
31 }
33​
34export class MobileStorageEncodeError extends Schema.TaggedError<MobileStorageEncodeError>()(
35 "MobileStorageEncodeError",
36 {
37 key: Schema.String,
38 cause: Schema.Defect(),
39 },
40) {
41 override get message(): string {
42 return `Failed to encode mobile storage value for key ${this.key}.`;
43 }
45​
46export class MobileDeviceIdGenerationError extends Schema.TaggedError<MobileDeviceIdGenerationError>()(
47 "MobileDeviceIdGenerationError",
48 { cause: Schema.Defect() },
49) {
50 override get message(): string {
51 return "Failed to generate the mobile agent-awareness device id.";
52 }
54​
55export interface AgentAwarenessRegistrationRecord {
56 readonly identity: string;
57 readonly signature: string;
58 readonly pushToStartToken?: string;
60​
61export interface RecentThreadShortcut {
62 readonly environmentId: string;
63 readonly threadId: string;
64 readonly title: string;
66​
67export class MobileStorage extends Context.Service<
68 MobileStorage,
69 {
70 readonly loadSavedConnections: Effect.Effect<
71 ReadonlyArray<SavedRemoteConnection>,
72 MobileSecureStorage.MobileSecureStorageError
73 >;
74 readonly saveConnection: (
75 connection: SavedRemoteConnection,
76 ) => Effect.Effect<
77 void,
78 MobileSecureStorage.MobileSecureStorageError | MobileStorageEncodeError
79 >;
80 readonly clearSavedConnection: (
81 environmentId: EnvironmentId,
82 ) => Effect.Effect<
83 void,
84 MobileSecureStorage.MobileSecureStorageError | MobileStorageEncodeError
85 >;
86 readonly loadOrCreateAgentAwarenessDeviceId: Effect.Effect<
87 string,
88 MobileSecureStorage.MobileSecureStorageError | MobileDeviceIdGenerationError
89 >;
90 readonly loadAgentAwarenessDeviceId: Effect.Effect<
91 string | null,
92 MobileSecureStorage.MobileSecureStorageError
93 >;
94 readonly loadAgentAwarenessRegistrationRecord: Effect.Effect<
95 AgentAwarenessRegistrationRecord | null,
96 MobileSecureStorage.MobileSecureStorageError
97 >;
98 readonly saveAgentAwarenessRegistrationRecord: (
99 record: AgentAwarenessRegistrationRecord,
100 ) => Effect.Effect<
101 void,
102 MobileSecureStorage.MobileSecureStorageError | MobileStorageEncodeError
103 >;
104 readonly clearAgentAwarenessRegistrationRecord: Effect.Effect<
105 void,
106 MobileSecureStorage.MobileSecureStorageError
107 >;
108 readonly loadRecentThreadShortcuts: Effect.Effect<
109 ReadonlyArray<RecentThreadShortcut>,
110 MobileSecureStorage.MobileSecureStorageError
111 >;
112 readonly saveRecentThreadShortcuts: (
113 threads: ReadonlyArray<RecentThreadShortcut>,
114 ) => Effect.Effect<
115 void,
116 MobileSecureStorage.MobileSecureStorageError | MobileStorageEncodeError
117 >;
118 }
119>()("@t3tools/mobile/persistence/MobileStorage") {}
120​
121export const make = Effect.fn("MobileStorage.make")(function* () {
122 const secureStorage = yield* MobileSecureStorage.MobileSecureStorage;
123 const deviceIdLock = yield* Semaphore.make(1);
124​
125 const parseJson = <A>(key: string, raw: string): A | null => {
126 if (!raw.trim()) return null;
127 try {
128 return JSON.parse(raw) as A;
129 } catch (cause) {
130 console.warn(
131 "[mobile-storage] ignored invalid JSON",
132 new MobileStorageDecodeError({ key, cause }),
133 );
134 return null;
135 }
136 };
137​
138 const readJson = Effect.fn("MobileStorage.readJson")(function* <A>(key: string) {
139 const raw = (yield* secureStorage.getItem(key)) ?? "";
140 return parseJson<A>(key, raw);
141 });
142​
143 const writeJson = Effect.fn("MobileStorage.writeJson")(function* (key: string, value: unknown) {
144 const encoded = yield* Effect.try({
145 try: () => JSON.stringify(value),
146 catch: (cause) => new MobileStorageEncodeError({ key, cause }),
147 });
148 yield* secureStorage.setItem(key, encoded);
149 });
150​
151 const loadSavedConnections = readJson<{
152 readonly connections?: ReadonlyArray<SavedRemoteConnection>;
153 }>(CONNECTIONS_KEY).pipe(
154 Effect.map((parsed) =>
155 pipe(
156 parsed?.connections ?? [],
157 Arr.filter(
158 (connection) =>
159 !!connection.environmentId &&
160 (!!connection.bearerToken?.trim() || isRelayManagedConnection(connection)),
161 ),
162 ),
163 ),
164 );
165​
166 const saveConnection = Effect.fn("MobileStorage.saveConnection")(function* (
167 connection: SavedRemoteConnection,
168 ) {
169 const current = yield* loadSavedConnections;
170 const stableConnection = toStableSavedRemoteConnection(connection);
171 const next = current.some((entry) => entry.environmentId === connection.environmentId)
172 ? pipe(
173 current,
174 Arr.map((entry) =>
175 entry.environmentId === connection.environmentId ? stableConnection : entry,
176 ),
177 )
178 : pipe(current, Arr.append(stableConnection));
179 yield* writeJson(CONNECTIONS_KEY, { connections: next });
180 });
181​
182 const clearSavedConnection = Effect.fn("MobileStorage.clearSavedConnection")(function* (
183 environmentId: EnvironmentId,
184 ) {
185 const current = yield* loadSavedConnections;
186 const next = pipe(
187 current,
188 Arr.filter((entry) => entry.environmentId !== environmentId),
189 );
190 yield* writeJson(CONNECTIONS_KEY, { connections: next });
191 });
192​
193 const loadOrCreateAgentAwarenessDeviceId = Effect.gen(function* () {
194 const existing = yield* secureStorage.getItem(AGENT_AWARENESS_DEVICE_ID_KEY);
195 if (existing?.trim()) return existing;
196 const deviceId = yield* Effect.tryPromise({
197 try: () => import("../lib/uuid").then(({ uuidv4 }) => uuidv4()),
198 catch: (cause) => new MobileDeviceIdGenerationError({ cause }),
199 });
200 yield* secureStorage.setItem(AGENT_AWARENESS_DEVICE_ID_KEY, deviceId);
201 return deviceId;
202 }).pipe(deviceIdLock.withPermits(1));
203​
204 const loadAgentAwarenessDeviceId = secureStorage
205 .getItem(AGENT_AWARENESS_DEVICE_ID_KEY)
206 .pipe(Effect.map((existing) => (existing?.trim() ? existing : null)));
207​
208 const loadAgentAwarenessRegistrationRecord = readJson<AgentAwarenessRegistrationRecord>(
209 AGENT_AWARENESS_REGISTRATION_KEY,
210 ).pipe(
211 Effect.map((parsed) => {
212 if (
213 !parsed ||
214 typeof parsed !== "object" ||
215 typeof parsed.identity !== "string" ||
216 typeof parsed.signature !== "string"
217 ) {
218 return null;
219 }
220 return {
221 identity: parsed.identity,
222 signature: parsed.signature,
223 ...(typeof parsed.pushToStartToken === "string" && parsed.pushToStartToken
224 ? { pushToStartToken: parsed.pushToStartToken }
225 : {}),
226 };
227 }),
228 );
229​
230 const loadRecentThreadShortcuts = readJson<{
231 readonly threads?: ReadonlyArray<RecentThreadShortcut>;
232 }>(RECENT_THREAD_SHORTCUTS_KEY).pipe(
233 Effect.map((parsed) =>
234 pipe(
235 parsed?.threads ?? [],
236 Arr.filter(
237 (thread) =>
238 typeof thread?.environmentId === "string" &&
239 thread.environmentId.length > 0 &&
240 typeof thread.threadId === "string" &&
241 thread.threadId.length > 0 &&
242 typeof thread.title === "string",
243 ),
244 ),
245 ),
246 );
247​
248 return MobileStorage.of({
249 loadSavedConnections,
250 saveConnection,
251 clearSavedConnection,
252 loadOrCreateAgentAwarenessDeviceId,
253 loadAgentAwarenessDeviceId,
254 loadAgentAwarenessRegistrationRecord,
255 saveAgentAwarenessRegistrationRecord: (record) =>
256 writeJson(AGENT_AWARENESS_REGISTRATION_KEY, record),
257 clearAgentAwarenessRegistrationRecord: secureStorage.setItem(
258 AGENT_AWARENESS_REGISTRATION_KEY,
259 "",
260 ),
261 loadRecentThreadShortcuts,
262 saveRecentThreadShortcuts: (threads) => writeJson(RECENT_THREAD_SHORTCUTS_KEY, { threads }),
263 });
264});
265​
266export const layer = Layer.effect(MobileStorage, make());