@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 151 lines 5.63 KB
Raw
1 import * as aoss from "@distilled.cloud/aws/opensearchserverless";
2 import * as Data from "effect/Data";
3 import * as Effect from "effect/Effect";
4 import * as Schedule from "effect/Schedule";
5
6 /**
7 * Raised when a collection (or VPC endpoint) provisioning terminates in a
8 * `FAILED` state or never reaches `ACTIVE` within the bounded polling budget.
9 */
10 export class OpenSearchServerlessProvisioningFailed extends Data.TaggedError(
11 "OpenSearchServerlessProvisioningFailed",
12 )<{
13 readonly resource: string;
14 readonly id: string;
15 readonly status: string | undefined;
16 readonly failureCode: string | undefined;
17 readonly failureMessage: string | undefined;
18 }> {
19 override get message() {
20 return `${this.resource} ${this.id} did not reach ACTIVE (status: ${this.status ?? "unknown"}${
21 this.failureCode !== undefined ? `, ${this.failureCode}` : ""
22 }${this.failureMessage !== undefined ? `: ${this.failureMessage}` : ""})`;
23 }
24 }
25
26 /**
27 * Serialize a security/access policy document to the compact JSON string the
28 * OpenSearch Serverless API expects. Passing through a string is a no-op so
29 * callers may interpolate `Output`-derived collection names into the policy
30 * themselves.
31 */
32 export const stringifyPolicy = (
33 policy: string | Record<string, unknown> | readonly unknown[],
34 ): string => (typeof policy === "string" ? policy : JSON.stringify(policy));
35
36 /**
37 * Normalize a policy document (string or object) to a stable JSON string for
38 * drift comparison — parse-then-stringify so key ordering differences between
39 * the desired document and the API's echoed document do not force a spurious
40 * update.
41 */
42 export const canonicalizePolicy = (
43 policy: string | Record<string, unknown> | readonly unknown[] | undefined,
44 ): string => {
45 if (policy === undefined) {
46 return "";
47 }
48 try {
49 const parsed = typeof policy === "string" ? JSON.parse(policy) : policy;
50 return JSON.stringify(parsed);
51 } catch {
52 return typeof policy === "string" ? policy : JSON.stringify(policy);
53 }
54 };
55
56 /** Convert the API's `[{ key, value }]` tag list into a plain record. */
57 export const tagsToRecord = (tags: aoss.Tag[] | undefined): Record<string, string> =>
58 Object.fromEntries((tags ?? []).map((t) => [t.key, t.value]));
59
60 /** Convert a plain record into the API's `[{ key, value }]` tag list. */
61 export const recordToTagList = (tags: Record<string, string>): aoss.Tag[] =>
62 Object.entries(tags).map(([key, value]) => ({ key, value }));
63
64 /**
65 * Poll `batchGetCollection` (bounded, spaced 10s, ~5 min budget) until the
66 * collection reaches a terminal status. Explicitly typed so `Effect.repeat`'s
67 * conditional return type does not widen the provider layer in declaration
68 * emit (see PATTERNS §7).
69 */
70 const untilCollectionTerminal = <E, R>(
71 self: Effect.Effect<aoss.BatchGetCollectionResponse, E, R>,
72 ): Effect.Effect<aoss.CollectionDetail | undefined, E, R> =>
73 Effect.repeat(
74 Effect.map(self, (response) => response.collectionDetails?.[0]),
75 {
76 schedule: Schedule.spaced("10 seconds"),
77 until: (detail) => detail?.status === "ACTIVE" || detail?.status === "FAILED",
78 times: 30,
79 },
80 );
81
82 /**
83 * Await a collection reaching `ACTIVE`, failing with
84 * `OpenSearchServerlessProvisioningFailed` on a `FAILED` terminal status or a
85 * budget timeout.
86 */
87 export const awaitCollectionActive = Effect.fn("AWS.OpenSearchServerless.awaitCollectionActive")(
88 function* (id: string) {
89 const detail = yield* untilCollectionTerminal(aoss.batchGetCollection({ ids: [id] }));
90 if (detail?.status !== "ACTIVE") {
91 return yield* new OpenSearchServerlessProvisioningFailed({
92 resource: "Collection",
93 id,
94 status: detail?.status,
95 failureCode: detail?.failureCode,
96 failureMessage: detail?.failureMessage,
97 });
98 }
99 return detail;
100 },
101 );
102
103 const untilVpcEndpointTerminal = <E, R>(
104 self: Effect.Effect<aoss.BatchGetVpcEndpointResponse, E, R>,
105 ): Effect.Effect<aoss.VpcEndpointDetail | undefined, E, R> =>
106 Effect.repeat(
107 Effect.map(self, (response) => response.vpcEndpointDetails?.[0]),
108 {
109 schedule: Schedule.spaced("10 seconds"),
110 until: (detail) => detail?.status === "ACTIVE" || detail?.status === "FAILED",
111 times: 30,
112 },
113 );
114
115 /**
116 * Await a VPC endpoint reaching `ACTIVE`, failing with
117 * `OpenSearchServerlessProvisioningFailed` on a `FAILED` terminal status or a
118 * budget timeout.
119 */
120 export const awaitVpcEndpointActive = Effect.fn("AWS.OpenSearchServerless.awaitVpcEndpointActive")(
121 function* (id: string) {
122 const detail = yield* untilVpcEndpointTerminal(aoss.batchGetVpcEndpoint({ ids: [id] }));
123 if (detail?.status !== "ACTIVE") {
124 return yield* new OpenSearchServerlessProvisioningFailed({
125 resource: "VpcEndpoint",
126 id,
127 status: detail?.status,
128 failureCode: detail?.failureCode,
129 failureMessage: detail?.failureMessage,
130 });
131 }
132 return detail;
133 },
134 );
135
136 /**
137 * Bounded retry through the `ConflictException` window that AOSS raises while a
138 * dependent resource is still tearing down — e.g. deleting an encryption
139 * `SecurityPolicy` while its `Collection` deletion is still propagating.
140 * Explicitly typed for the same declaration-emit reason as above.
141 */
142 export const retryWhileConflict = <A, E extends { _tag: string }, R>(
143 self: Effect.Effect<A, E, R>,
144 ): Effect.Effect<A, E, R> =>
145 Effect.retry(self, {
146 while: (e) => e._tag === "ConflictException",
147 // ~3 min budget: a security policy cannot be deleted until every
148 // collection it covers is FULLY deleted (not merely DELETING), which can
149 // take a couple of minutes after deleteCollection returns.
150 schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(36)]),
151 });