Skip to content
Source
Sign inSign up

cloud-drafts.ts

49 lines1.9 KB

1import { EnvironmentRegistry, removedWithRelay } from "@t3tools/client-runtime/connection";
2import { createRuntimeCommand } from "@t3tools/client-runtime/state/runtime";
3import * as Effect from "effect/Effect";
4import * as Schema from "effect/Schema";
5import * as SubscriptionRef from "effect/SubscriptionRef";
6​
7import { connectionAtomRuntime } from "../../connection/runtime";
8import { archiveCloudComposerDrafts } from "../../state/use-composer-drafts";
9​
10export class CloudDraftArchiveError extends Schema.TaggedError<CloudDraftArchiveError>()(
11 "CloudDraftArchiveError",
12 {
13 environmentCount: Schema.Number,
14 hasAccountId: Schema.Boolean,
15 cause: Schema.Defect(),
16 },
17) {
18 override get message(): string {
19 return `Could not preserve local drafts for ${this.environmentCount} cloud environments before sign-out.`;
20 }
22​
23export const removeCloudEnvironments = createRuntimeCommand(connectionAtomRuntime, {
24 label: "cloud:preserve-drafts-and-remove-environments",
25 execute: Effect.fn("removeCloudEnvironments")(function* (accountId: string | null) {
26 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
27 const entries = yield* SubscriptionRef.get(registry.entries);
28 const environmentIds = new Set(
29 [...entries.values()].filter(removedWithRelay).map((entry) => entry.target.environmentId),
30 );
31 // Backup failure must retain local file owners so a later sign-in can retry.
32 yield* Effect.tryPromise({
33 // Resolve draft owners against every environment, not just the removed ones.
34 try: () =>
35 archiveCloudComposerDrafts(
36 accountId,
37 environmentIds,
38 [...entries.values()].map((entry) => entry.target.environmentId),
39 ),
40 catch: (cause) =>
41 new CloudDraftArchiveError({
42 environmentCount: environmentIds.size,
43 hasAccountId: accountId !== null,
44 cause,
45 }),
46 });
47 yield* registry.removeRelayEnvironments();
48 }),
49});