Open History to see the last commit
1import { CommandId, EnvironmentId, ThreadId } from "@t3tools/contracts";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Exit from "effect/Exit";
5import * as Schema from "effect/Schema";
6import * as Semaphore from "effect/Semaphore";
7
8export const PendingThreadTriage = Schema.Struct({
9 environmentId: EnvironmentId,
10 threadId: ThreadId,
11 commandId: CommandId,
12 action: Schema.Union([
13 Schema.Struct({ type: Schema.Literal("settle") }),
14 Schema.Struct({ type: Schema.Literal("snooze"), snoozedUntil: Schema.String }),
15 ]),
16 queuedAt: Schema.DateTimeUtcFromString,
17 /** The thread as the user saw it; if it shows otherwise on reconnect, the change is dropped. */
18 seen: Schema.String,
19});
20export type PendingThreadTriage = typeof PendingThreadTriage.Type;
21export type PendingThreadTriages = ReadonlyArray<PendingThreadTriage>;
22
23const Stored = Schema.fromJsonString(Schema.Struct({ entries: Schema.Array(PendingThreadTriage) }));
24const decodeStored = Schema.decodeUnknownExit(Stored);
25const encodeStored = Schema.encodeSync(Stored);
26
27export class ThreadTriageOutboxStorageError extends Schema.TaggedError<ThreadTriageOutboxStorageError>()(
28 "ThreadTriageOutboxStorageError",
29 { cause: Schema.Defect() },
30) {
31 override get message(): string {
32 return "Could not save the change for later sync.";
33 }
34}
35
36/**
37 * Settle and snooze taken while an environment is offline, kept apart from the environment
38 * cache so clearing the cache does not drop them. Removing the environment does.
39 */
40export interface ThreadTriageOutboxStoreShape {
41 /** Stores `change(stored)` in one step and returns it. Returning `stored` itself only reads. */
42 readonly update: (
43 change: (stored: PendingThreadTriages) => PendingThreadTriages,
44 ) => Effect.Effect<PendingThreadTriages, ThreadTriageOutboxStorageError>;
45 readonly clearEnvironment: (
46 environmentId: EnvironmentId,
47 ) => Effect.Effect<void, ThreadTriageOutboxStorageError>;
48}
49
50/**
51 * `modify` replaces the stored text with `next(stored)`, or keeps it when that is null. Text that
52 * no longer decodes reads as empty.
53 */
54export function makeThreadTriageOutboxStore(
55 modify: (
56 next: (stored: string | null) => string | null,
57 ) => Effect.Effect<void, ThreadTriageOutboxStorageError>,
58): ThreadTriageOutboxStoreShape {
59 // Platforms whose `modify` reads and writes in separate steps rely on this to not interleave.
60 const lock = Semaphore.makeUnsafe(1);
61 const update: ThreadTriageOutboxStoreShape["update"] = (change) =>
62 lock.withPermits(1)(
63 Effect.suspend(() => {
64 let result: PendingThreadTriages = [];
65 return modify((raw) => {
66 const decoded = raw === null ? undefined : decodeStored(raw);
67 const stored =
68 decoded !== undefined && Exit.isSuccess(decoded) ? decoded.value.entries : [];
69 result = change(stored);
70 return result === stored ? null : encodeStored({ entries: result });
71 }).pipe(Effect.map(() => result));
72 }),
73 );
74 return {
75 update,
76 clearEnvironment: (environmentId) =>
77 update((stored) =>
78 stored.some((entry) => entry.environmentId === environmentId)
79 ? stored.filter((entry) => entry.environmentId !== environmentId)
80 : stored,
81 ).pipe(Effect.asVoid),
82 };
83}
84
85export class ThreadTriageOutboxStore extends Context.Reference<ThreadTriageOutboxStoreShape>(
86 "@t3tools/client-runtime/state/ThreadTriageOutboxStore",
87 {
88 defaultValue: () => {
89 let value: string | null = null;
90 return makeThreadTriageOutboxStore((next) =>
91 Effect.sync(() => {
92 value = next(value) ?? value;
93 }),
94 );
95 },
96 },
97) {}