@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 214 lines 8 KB
Raw
1 import * as mi from "@distilled.cloud/aws/iot-managed-integrations";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import { syncManagedIntegrationsTags, toTagRecord, unwrapSensitive } from "./internal.ts";
13
14 export class CredentialLockerUnexpectedResponse extends Data.TaggedError(
15 "CredentialLockerUnexpectedResponse",
16 )<{
17 readonly message: string;
18 readonly cause?: unknown;
19 }> {}
20
21 export class CredentialLockerOperationFailed extends Data.TaggedError(
22 "CredentialLockerOperationFailed",
23 )<{
24 readonly message: string;
25 readonly cause?: unknown;
26 }> {}
27
28 export interface CredentialLockerProps {
29 /**
30 * Name of the credential locker. If omitted, a unique name is generated
31 * from the app, stage, and logical ID. Changing the name replaces the
32 * locker (there is no update API).
33 */
34 name?: string;
35 /**
36 * User-defined tags to apply to the credential locker.
37 */
38 tags?: Record<string, string>;
39 }
40
41 export interface CredentialLocker extends Resource<
42 "AWS.IoTManagedIntegrations.CredentialLocker",
43 CredentialLockerProps,
44 {
45 /** Service-generated identifier of the credential locker. */
46 credentialLockerId: string;
47 /** ARN of the credential locker. */
48 credentialLockerArn: string;
49 /** Name of the credential locker. */
50 credentialLockerName: string;
51 /** Tags applied to the credential locker (user + internal). */
52 tags: Record<string, string>;
53 },
54 never,
55 Providers
56 > {}
57
58 /**
59 * An AWS IoT Managed Integrations credential locker — a secured store for the
60 * credentials that devices use to onboard and authenticate with Managed
61 * integrations.
62 *
63 * IoT Managed Integrations is a regional service available in a limited set
64 * of regions (e.g. `eu-west-1`, `ca-central-1`).
65 *
66 * ### Creating Credential Lockers
67 * **Example:** Basic Credential Locker
68 * ```typescript
69 * const locker = yield* CredentialLocker("DeviceCredentials", {});
70 * ```
71 *
72 * **Example:** Named Credential Locker with Tags
73 * ```typescript
74 * const locker = yield* CredentialLocker("DeviceCredentials", {
75 * name: "my-device-credentials",
76 * tags: { team: "iot" },
77 * });
78 * ```
79 *
80 * @resource
81 */
82 export const CredentialLocker = Resource<CredentialLocker>(
83 "AWS.IoTManagedIntegrations.CredentialLocker",
84 );
85
86 export const CredentialLockerProvider = () =>
87 Provider.effect(
88 CredentialLocker,
89 Effect.gen(function* () {
90 const toName = (id: string, props: CredentialLockerProps = {}) =>
91 props.name ? Effect.succeed(props.name) : createPhysicalName({ id, maxLength: 64 });
92
93 // Observe by service-generated Id.
94 const observeById = (identifier: string) =>
95 mi
96 .getCredentialLocker({ Identifier: identifier })
97 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
98
99 // Recover an existing locker by name when no Id is cached (e.g. after a
100 // state persistence failure). Names are not unique server-side, so take
101 // the first match.
102 const findByName = Effect.fn(function* (name: string) {
103 const summary = yield* mi.listCredentialLockers.items({}).pipe(
104 Stream.filter((item) => unwrapSensitive(item.Name) === name),
105 Stream.take(1),
106 Stream.runCollect,
107 Effect.map((chunk) => Array.from(chunk)[0]),
108 );
109 if (summary?.Id === undefined) return undefined;
110 return yield* observeById(summary.Id);
111 });
112
113 const toAttributes = Effect.fn(function* (locker: mi.GetCredentialLockerResponse) {
114 const name = unwrapSensitive(locker.Name);
115 if (locker.Id === undefined || locker.Arn === undefined || name === undefined) {
116 return yield* new CredentialLockerUnexpectedResponse({
117 message: "credential locker response is missing Id, Arn, or Name",
118 });
119 }
120 return {
121 credentialLockerId: locker.Id,
122 credentialLockerArn: locker.Arn,
123 credentialLockerName: name,
124 tags: toTagRecord(locker.Tags),
125 };
126 });
127
128 return {
129 stables: ["credentialLockerId", "credentialLockerArn", "credentialLockerName"],
130 diff: Effect.fn(function* ({ id, olds, news }) {
131 if (!isResolved(news)) return;
132 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
133 return { action: "replace" } as const;
134 }
135 }),
136 read: Effect.fn(function* ({ id, olds, output }) {
137 const locker =
138 output?.credentialLockerId !== undefined
139 ? yield* observeById(output.credentialLockerId)
140 : yield* findByName(yield* toName(id, olds ?? {}));
141 if (locker === undefined) return undefined;
142 const attrs = yield* toAttributes(locker);
143 return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs);
144 }),
145 reconcile: Effect.fn(function* ({ id, news, output, session }) {
146 const name = yield* toName(id, news);
147 const internalTags = yield* createInternalTags(id);
148 const desiredTags = { ...internalTags, ...news.tags };
149
150 // Observe — cloud state is authoritative; output is only an Id cache.
151 let locker =
152 output?.credentialLockerId !== undefined
153 ? yield* observeById(output.credentialLockerId)
154 : yield* findByName(name);
155
156 // Ensure — create if missing (there is no name-uniqueness conflict
157 // to race against; creation is idempotent via ClientToken).
158 if (locker === undefined) {
159 const created = yield* mi.createCredentialLocker({
160 Name: name,
161 Tags: desiredTags,
162 });
163 if (created.Id === undefined) {
164 return yield* new CredentialLockerOperationFailed({
165 message: `failed to create credential locker '${name}'`,
166 });
167 }
168 locker = yield* observeById(created.Id);
169 if (locker === undefined) {
170 return yield* new CredentialLockerUnexpectedResponse({
171 message: `credential locker '${created.Id}' vanished after create`,
172 });
173 }
174 }
175
176 // Sync tags — diff against OBSERVED cloud tags.
177 if (locker.Arn !== undefined) {
178 yield* syncManagedIntegrationsTags(locker.Arn, toTagRecord(locker.Tags), desiredTags);
179 }
180
181 const attrs = yield* toAttributes(locker);
182 yield* session.note(attrs.credentialLockerArn);
183 return { ...attrs, tags: desiredTags };
184 }),
185 // Enumerate every credential locker in the account/region. Fetch each
186 // locker to resolve its tags (summaries omit them).
187 list: () =>
188 Effect.gen(function* () {
189 const summaries = yield* mi.listCredentialLockers.items({}).pipe(
190 Stream.runCollect,
191 Effect.map((chunk) => Array.from(chunk)),
192 );
193 const lockers = yield* Effect.forEach(
194 summaries.filter(
195 (s): s is mi.CredentialLockerSummary & { Id: string } => s.Id !== undefined,
196 ),
197 (summary) => observeById(summary.Id),
198 { concurrency: 5 },
199 );
200 return yield* Effect.forEach(
201 lockers.filter(
202 (locker): locker is mi.GetCredentialLockerResponse => locker !== undefined,
203 ),
204 toAttributes,
205 );
206 }),
207 delete: Effect.fn(function* ({ output }) {
208 yield* mi
209 .deleteCredentialLocker({ Identifier: output.credentialLockerId })
210 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
211 }),
212 };
213 }),
214 );