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

mobile-preferences.ts

305 lines10.7 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Option from "effect/Option";
5import * as Ref from "effect/Ref";
6import * as Schema from "effect/Schema";
7import * as Semaphore from "effect/Semaphore";
8​
9import * as MobileDatabase from "./mobile-database";
10import * as MobileSecureStorage from "./mobile-secure-storage";
11import { MobileStorageDecodeError, MobileStorageEncodeError } from "./mobile-storage";
12​
13const PREFERENCES_KEY = "t3code.preferences";
14const PREFERENCES_FALLBACK_KEY = "t3code.preferences.fallback";
15​
16export interface Preferences {
17 readonly liveActivitiesEnabled?: boolean;
18 readonly baseFontSize?: number;
19 readonly terminalFontSize?: number | null;
20 readonly markdownFontSize?: number;
21 readonly codeFontSize?: number | null;
22 readonly codeWordBreak?: boolean;
23 readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
24 readonly collapsedProjectGroups?: readonly string[];
26​
27export class MobilePreferencesLoadError extends Schema.TaggedErrorClass<MobilePreferencesLoadError>()(
28 "MobilePreferencesLoadError",
29 { cause: Schema.Defect() },
30) {
31 override get message(): string {
32 return "Failed to load mobile preferences.";
33 }
35​
36export class MobilePreferencesSaveError extends Schema.TaggedErrorClass<MobilePreferencesSaveError>()(
37 "MobilePreferencesSaveError",
38 { cause: Schema.Defect() },
39) {
40 override get message(): string {
41 return "Failed to save mobile preferences.";
42 }
44​
45interface PreferencesFallback {
46 readonly payload: string;
47 readonly updatedAt: number;
48 readonly preferences: Preferences;
50​
51export class MobilePreferencesStore extends Context.Service<
52 MobilePreferencesStore,
53 {
54 readonly load: Effect.Effect<Preferences, MobilePreferencesLoadError>;
55 readonly savePatch: (
56 patch: Partial<Preferences>,
57 ) => Effect.Effect<Preferences, MobilePreferencesSaveError>;
58 readonly update: (
59 transform: (current: Preferences) => Partial<Preferences>,
60 ) => Effect.Effect<Preferences, MobilePreferencesSaveError>;
61 }
62>()("@t3tools/mobile/persistence/MobilePreferencesStore") {}
63​
64function sanitizePreferences(parsed: Preferences): Preferences {
65 const preferences: {
66 liveActivitiesEnabled?: boolean;
67 baseFontSize?: number;
68 terminalFontSize?: number | null;
69 markdownFontSize?: number;
70 codeFontSize?: number | null;
71 codeWordBreak?: boolean;
72 connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
73 collapsedProjectGroups?: readonly string[];
74 } = {};
75​
76 if (typeof parsed.liveActivitiesEnabled === "boolean") {
77 preferences.liveActivitiesEnabled = parsed.liveActivitiesEnabled;
78 }
79 if (typeof parsed.baseFontSize === "number") preferences.baseFontSize = parsed.baseFontSize;
80 if (typeof parsed.terminalFontSize === "number" || parsed.terminalFontSize === null) {
81 preferences.terminalFontSize = parsed.terminalFontSize;
82 }
83 if (typeof parsed.markdownFontSize === "number") {
84 preferences.markdownFontSize = parsed.markdownFontSize;
85 }
86 if (typeof parsed.codeFontSize === "number" || parsed.codeFontSize === null) {
87 preferences.codeFontSize = parsed.codeFontSize;
88 }
89 if (typeof parsed.codeWordBreak === "boolean") preferences.codeWordBreak = parsed.codeWordBreak;
90 if (Array.isArray(parsed.connectOnboardingOptOutAccounts)) {
91 preferences.connectOnboardingOptOutAccounts = parsed.connectOnboardingOptOutAccounts.filter(
92 (account): account is string => typeof account === "string",
93 );
94 }
95 if (Array.isArray(parsed.collapsedProjectGroups)) {
96 preferences.collapsedProjectGroups = parsed.collapsedProjectGroups.filter(
97 (key): key is string => typeof key === "string",
98 );
99 }
100 return preferences;
102​
103export const make = Effect.fn("MobilePreferencesStore.make")(function* () {
104 const database = yield* MobileDatabase.MobileDatabase;
105 const secureStorage = yield* MobileSecureStorage.MobileSecureStorage;
106 const lock = yield* Semaphore.make(1);
107 const lastUpdatedAt = yield* Ref.make(0);
108​
109 const parsePayload = (raw: string | null): Preferences | null => {
110 if (raw === null || !raw.trim()) return null;
111 let parsed: unknown;
112 try {
113 parsed = JSON.parse(raw);
114 } catch (cause) {
115 console.warn(
116 "[mobile-storage] ignored invalid JSON",
117 new MobileStorageDecodeError({ key: PREFERENCES_KEY, cause }),
118 );
119 return null;
120 }
121 return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
122 ? (parsed as Preferences)
123 : null;
124 };
125​
126 const parseFallback = (raw: string | null): PreferencesFallback | null => {
127 if (raw === null || !raw.trim()) return null;
128 let parsed: unknown;
129 try {
130 parsed = JSON.parse(raw);
131 } catch (cause) {
132 console.warn(
133 "[mobile-storage] ignored invalid JSON",
134 new MobileStorageDecodeError({ key: PREFERENCES_FALLBACK_KEY, cause }),
135 );
136 return null;
137 }
138 if (
139 typeof parsed !== "object" ||
140 parsed === null ||
141 !("payload" in parsed) ||
142 typeof parsed.payload !== "string" ||
143 !("updatedAt" in parsed) ||
144 typeof parsed.updatedAt !== "number"
145 ) {
146 return null;
147 }
148 const preferences = parsePayload(parsed.payload);
149 return preferences === null
150 ? null
151 : { payload: parsed.payload, updatedAt: parsed.updatedAt, preferences };
152 };
153​
154 const encode = Effect.fn("MobilePreferencesStore.encode")(function* (
155 key: string,
156 value: unknown,
157 ) {
158 return yield* Effect.try({
159 try: () => JSON.stringify(value),
160 catch: (cause) => new MobileStorageEncodeError({ key, cause }),
161 });
162 });
163​
164 const nextUpdatedAt = Ref.modify(lastUpdatedAt, (last) => {
165 const next = Math.max(Date.now(), last + 1);
166 return [next, next] as const;
167 });
168​
169 const saveJson = Effect.fn("MobilePreferencesStore.saveJson")(function* (
170 payload: string,
171 updatedAt?: number,
172 ) {
173 const timestamp = updatedAt ?? (yield* nextUpdatedAt);
174 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, timestamp));
175 const databaseResult = yield* Effect.result(database.savePreferencesJson(payload, timestamp));
176 if (databaseResult._tag === "Failure") {
177 yield* Effect.logWarning("Database unavailable; saving preferences to secure storage.").pipe(
178 Effect.annotateLogs({ cause: databaseResult.failure }),
179 );
180 const fallback = yield* encode(PREFERENCES_FALLBACK_KEY, { payload, updatedAt: timestamp });
181 yield* secureStorage.setItem(PREFERENCES_FALLBACK_KEY, fallback);
182 return;
183 }
184 yield* secureStorage
185 .removeItem(PREFERENCES_FALLBACK_KEY)
186 .pipe(
187 Effect.catch((error) =>
188 Effect.logWarning("Could not remove the mobile preferences fallback.").pipe(
189 Effect.annotateLogs({ error }),
190 ),
191 ),
192 );
193 });
194​
195 const loadUnlocked = Effect.gen(function* () {
196 const databaseResult = yield* Effect.result(database.loadPreferencesJson);
197 const databaseAvailable = databaseResult._tag === "Success";
198 const storedJson = databaseAvailable
199 ? databaseResult.success
200 : Option.none<MobileDatabase.StoredPreferencesJson>();
201 if (databaseResult._tag === "Failure") {
202 yield* Effect.logWarning("Database unavailable; loading fallback preferences.").pipe(
203 Effect.annotateLogs({ cause: databaseResult.failure }),
204 );
205 }
206​
207 const fallbackResult = yield* Effect.result(secureStorage.getItem(PREFERENCES_FALLBACK_KEY));
208 let fallbackJson: string | null = null;
209 if (fallbackResult._tag === "Success") {
210 fallbackJson = fallbackResult.success;
211 } else if (Option.isNone(storedJson)) {
212 return yield* fallbackResult.failure;
213 } else {
214 yield* Effect.logWarning("Could not inspect the mobile preferences fallback.").pipe(
215 Effect.annotateLogs({ error: fallbackResult.failure }),
216 );
217 }
218​
219 const fallback = parseFallback(fallbackJson);
220 const storedPreferences = Option.isSome(storedJson)
221 ? parsePayload(storedJson.value.payload)
222 : null;
223 const fallbackIsNewer =
224 fallback !== null &&
225 (storedPreferences === null ||
226 (Option.isSome(storedJson) && fallback.updatedAt > storedJson.value.updatedAt));
227​
228 let parsed: Preferences | null = null;
229 if (fallbackIsNewer) {
230 parsed = fallback.preferences;
231 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, fallback.updatedAt));
232 if (databaseAvailable) yield* saveJson(fallback.payload, fallback.updatedAt);
233 } else if (storedPreferences !== null && Option.isSome(storedJson)) {
234 parsed = storedPreferences;
235 yield* Ref.update(lastUpdatedAt, (last) => Math.max(last, storedJson.value.updatedAt));
236 if (fallbackJson !== null) {
237 yield* secureStorage
238 .removeItem(PREFERENCES_FALLBACK_KEY)
239 .pipe(
240 Effect.catch((error) =>
241 Effect.logWarning("Could not remove a stale mobile preferences fallback.").pipe(
242 Effect.annotateLogs({ error }),
243 ),
244 ),
245 );
246 }
247 }
248​
249 if (parsed === null) {
250 const legacyJson = yield* secureStorage.getItem(PREFERENCES_KEY);
251 const legacyPreferences = parsePayload(legacyJson);
252 parsed = legacyPreferences;
253 if (legacyJson !== null && legacyPreferences !== null && databaseAvailable) {
254 yield* saveJson(legacyJson);
255 yield* secureStorage
256 .removeItem(PREFERENCES_KEY)
257 .pipe(
258 Effect.catch((error) =>
259 Effect.logWarning("Could not remove migrated mobile preferences.").pipe(
260 Effect.annotateLogs({ error }),
261 ),
262 ),
263 );
264 }
265 }
266​
267 return parsed === null ? {} : sanitizePreferences(parsed);
268 });
269​
270 const load = lock
271 .withPermits(1)(loadUnlocked)
272 .pipe(Effect.mapError((cause) => new MobilePreferencesLoadError({ cause })));
273​
274 const update = Effect.fn("MobilePreferencesStore.update")((transform) =>
275 lock
276 .withPermits(1)(
277 Effect.gen(function* () {
278 const current = yield* loadUnlocked;
279 const patch = yield* Effect.try({
280 try: () => transform(current),
281 catch: (cause) => new MobilePreferencesSaveError({ cause }),
282 });
283 const next: Preferences = { ...current, ...patch };
284 const payload = yield* encode(PREFERENCES_KEY, next);
285 yield* saveJson(payload);
286 return next;
287 }),
288 )
289 .pipe(
290 Effect.mapError((cause) =>
291 cause instanceof MobilePreferencesSaveError
292 ? cause
293 : new MobilePreferencesSaveError({ cause }),
294 ),
295 ),
296 );
297​
298 return MobilePreferencesStore.of({
299 load,
300 update,
301 savePatch: (patch) => update(() => patch),
302 });
303});
304​
305export const layer = Layer.effect(MobilePreferencesStore, make());