Open History to see the last commit
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";
6import { msg, plural, part } from "gt-react-native";
7
8import { connectionAtomRuntime } from "../../connection/runtime";
9import { m } from "../../i18n/messages";
10import { archiveCloudComposerDrafts } from "../../state/use-composer-drafts";
11
12export class CloudDraftArchiveError extends Schema.TaggedError<CloudDraftArchiveError>()(
13 "CloudDraftArchiveError",
14 {
15 environmentCount: Schema.Number,
16 hasAccountId: Schema.Boolean,
17 cause: Schema.Defect(),
18 },
19) {
20 override get message(): string {
21 return m(
22 msg`${plural(
23 { count: this.environmentCount },
24 {
25 other: part`Could not preserve local drafts for ${{ count: this.environmentCount }} cloud environments before sign-out.`,
26 },
27 )}`,
28 );
29 }
30}
31
32export const removeCloudEnvironments = createRuntimeCommand(connectionAtomRuntime, {
33 label: "cloud:preserve-drafts-and-remove-environments",
34 execute: Effect.fn("removeCloudEnvironments")(function* (accountId: string | null) {
35 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
36 const entries = yield* SubscriptionRef.get(registry.entries);
37 const environmentIds = new Set(
38 [...entries.values()].filter(removedWithRelay).map((entry) => entry.target.environmentId),
39 );
40 // Backup failure must retain local file owners so a later sign-in can retry.
41 yield* Effect.tryPromise({
42 // Resolve draft owners against every environment, not just the removed ones.
43 try: () =>
44 archiveCloudComposerDrafts(
45 accountId,
46 environmentIds,
47 [...entries.values()].map((entry) => entry.target.environmentId),
48 ),
49 catch: (cause) =>
50 new CloudDraftArchiveError({
51 environmentCount: environmentIds.size,
52 hasAccountId: accountId !== null,
53 cause,
54 }),
55 });
56 yield* registry.removeRelayEnvironments();
57 }),
58});