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

mobile-preferences.ts

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