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

environment-owned-data-cleanup.ts

48 lines1.9 KB

1import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
2import { Persistence } from "@t3tools/client-runtime/platform";
3import type { EnvironmentId } from "@t3tools/contracts";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Schema from "effect/Schema";
7​
8import { clearThreadComposerErrorsForEnvironment } from "../state/thread-composer-error";
9import { clearThreadOutboxEnvironment } from "../state/thread-outbox-removal";
10import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";
11​
12class EnvironmentOwnedDataClearError extends Schema.TaggedError<EnvironmentOwnedDataClearError>()(
13 "EnvironmentOwnedDataClearError",
14 { cause: Schema.Defect() },
15) {}
16​
17export const layer = Layer.succeed(
18 Persistence.EnvironmentOwnedDataCleanup,
19 Persistence.EnvironmentOwnedDataCleanup.of({
20 clear: Effect.fn("Persistence.EnvironmentOwnedDataCleanup.clear")(function (environmentId) {
21 // Each clear settles on its own: a failure must not interrupt a clear that is still running.
22 const settle = (
23 operation: "outbox" | "drafts",
24 clear: (environmentId: EnvironmentId) => Promise<void>,
25 ) =>
26 Effect.tryPromise({
27 try: () => clear(environmentId),
28 catch: (cause) => new EnvironmentOwnedDataClearError({ cause }),
29 }).pipe(
30 Effect.catch((error) =>
31 Effect.logWarning("Could not clear mobile environment-owned data.", {
32 environmentId,
33 operation,
34 ...safeErrorLogAttributes(error.cause),
35 }),
36 ),
37 );
38 return Effect.all(
39 [
40 settle("outbox", clearThreadOutboxEnvironment),
41 settle("drafts", clearComposerDraftsEnvironment),
42 Effect.sync(() => clearThreadComposerErrorsForEnvironment(environmentId)),
43 ],
44 { concurrency: "unbounded", discard: true },
45 );
46 }),
47 }),
48);