@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 346 lines 12.7 KB
Raw
1 import * as licensemanager from "@distilled.cloud/aws/license-manager";
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, createTagsList, diffTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import type { Providers } from "../Providers.ts";
10
11 /**
12 * Dimension used to track license inventory.
13 */
14 export type LicenseCountingType = "vCPU" | "Instance" | "Core" | "Socket";
15
16 export interface LicenseConfigurationProps {
17 /**
18 * Name of the license configuration.
19 * @default ${app}-${stage}-${id}
20 */
21 name?: string;
22 /**
23 * Description of the license configuration.
24 */
25 description?: string;
26 /**
27 * Dimension used to track the license inventory: `vCPU`, `Instance`,
28 * `Core`, or `Socket`. Cannot be changed after creation — changing it
29 * replaces the license configuration.
30 */
31 licenseCountingType: LicenseCountingType;
32 /**
33 * Number of licenses managed by the license configuration.
34 */
35 licenseCount?: number;
36 /**
37 * Whether the number of licenses is a hard limit. A hard limit blocks
38 * new instance launches once the license count is consumed.
39 * @default false
40 */
41 licenseCountHardLimit?: boolean;
42 /**
43 * License rules (e.g. `#allowedTenancy=EC2-DedicatedHost`,
44 * `#licenseAffinityToHost=30`). The rules allowed depend on the
45 * license counting type.
46 */
47 licenseRules?: string[];
48 /**
49 * When true, disassociates a resource from the license configuration
50 * when the resource is no longer found (e.g. the instance was
51 * terminated).
52 * @default false
53 */
54 disassociateWhenNotFound?: boolean;
55 /**
56 * Tags to apply to the license configuration. Merged with internal
57 * Alchemy tags.
58 */
59 tags?: Record<string, string>;
60 }
61
62 export interface LicenseConfiguration extends Resource<
63 "AWS.LicenseManager.LicenseConfiguration",
64 LicenseConfigurationProps,
65 {
66 /**
67 * Unique ID of the license configuration, e.g. `lic-0123abcd...`.
68 */
69 licenseConfigurationId: string;
70 /**
71 * ARN of the license configuration.
72 */
73 licenseConfigurationArn: string;
74 /**
75 * Name of the license configuration.
76 */
77 name: string;
78 /**
79 * Dimension used to track the license inventory.
80 */
81 licenseCountingType: string;
82 },
83 never,
84 Providers
85 > {}
86
87 /**
88 * An AWS License Manager license configuration — an abstraction of a
89 * customer license agreement that License Manager can track and enforce.
90 *
91 * A license configuration specifies the licensing dimension (vCPUs,
92 * instances, cores, or sockets), an optional license count, and whether
93 * the count is a hard limit that blocks new launches once consumed.
94 * ### Creating License Configurations
95 * **Example:** Track licenses by vCPU
96 * ```typescript
97 * import * as LicenseManager from "@alchemy.run/aws/LicenseManager";
98 *
99 * const licenses = yield* LicenseManager.LicenseConfiguration("Licenses", {
100 * licenseCountingType: "vCPU",
101 * });
102 * ```
103 *
104 * **Example:** Enforce a hard license limit
105 * ```typescript
106 * const licenses = yield* LicenseManager.LicenseConfiguration("Licenses", {
107 * licenseCountingType: "Instance",
108 * licenseCount: 10,
109 * licenseCountHardLimit: true,
110 * });
111 * ```
112 *
113 * **Example:** Socket licensing with dedicated-host rules
114 * ```typescript
115 * const licenses = yield* LicenseManager.LicenseConfiguration("Licenses", {
116 * licenseCountingType: "Socket",
117 * licenseCount: 4,
118 * licenseRules: ["#allowedTenancy=EC2-DedicatedHost"],
119 * description: "Oracle DB socket licenses",
120 * });
121 * ```
122 *
123 * @resource
124 */
125 export const LicenseConfiguration = Resource<LicenseConfiguration>(
126 "AWS.LicenseManager.LicenseConfiguration",
127 );
128
129 /**
130 * `DeleteLicenseConfiguration` soft-deletes: the configuration remains
131 * visible with `Status: "DELETED"` for a while. Treat those as gone.
132 */
133 const isLive = (status: string | undefined) => status !== "DELETED";
134
135 export const LicenseConfigurationProvider = () =>
136 Provider.effect(
137 LicenseConfiguration,
138 Effect.gen(function* () {
139 const createName = Effect.fn(function* (id: string, props: { name?: string }) {
140 return props.name ?? (yield* createPhysicalName({ id, maxLength: 96 }));
141 });
142
143 // Enumerate all license configurations (bounded manual pagination —
144 // distilled exposes no `.pages` for this operation).
145 const listAll = Effect.gen(function* () {
146 const items: licensemanager.LicenseConfiguration[] = [];
147 let nextToken: string | undefined;
148 for (let page = 0; page < 50; page++) {
149 const response = yield* licensemanager.listLicenseConfigurations({
150 MaxResults: 100,
151 ...(nextToken ? { NextToken: nextToken } : {}),
152 });
153 items.push(...(response.LicenseConfigurations ?? []));
154 // Empty-string markers are terminal.
155 if (!response.NextToken) break;
156 nextToken = response.NextToken;
157 }
158 return items.filter((item) => isLive(item.Status));
159 });
160
161 const findByName = Effect.fn(function* (name: string) {
162 const items = yield* listAll;
163 return items.find((item) => item.Name === name);
164 });
165
166 // Observe a configuration by its ARN; a deleted/nonexistent ARN
167 // surfaces as the typed not-found tag and maps to `undefined`.
168 const getByArn = Effect.fn(function* (arn: string) {
169 const found = yield* licensemanager
170 .getLicenseConfiguration({ LicenseConfigurationArn: arn })
171 .pipe(Effect.catchTag("LicenseConfigurationNotFound", () => Effect.undefined));
172 if (found === undefined || !isLive(found.Status)) return undefined;
173 return found;
174 });
175
176 // Distilled's `Tag` has optional `Key`/`Value`; narrow to a plain
177 // record, dropping any entries the API returned without both fields.
178 const toTagRecord = (tags: licensemanager.Tag[] | undefined): Record<string, string> => {
179 const record: Record<string, string> = {};
180 for (const tag of tags ?? []) {
181 if (tag.Key !== undefined && tag.Value !== undefined) {
182 record[tag.Key] = tag.Value;
183 }
184 }
185 return record;
186 };
187
188 const toAttributes = (observed: {
189 LicenseConfigurationId?: string;
190 LicenseConfigurationArn?: string;
191 Name?: string;
192 LicenseCountingType?: string;
193 }) => ({
194 licenseConfigurationId: observed.LicenseConfigurationId!,
195 licenseConfigurationArn: observed.LicenseConfigurationArn!,
196 name: observed.Name!,
197 licenseCountingType: observed.LicenseCountingType!,
198 });
199
200 return LicenseConfiguration.Provider.of({
201 stables: ["licenseConfigurationId", "licenseConfigurationArn", "licenseCountingType"],
202
203 list: () =>
204 Effect.gen(function* () {
205 const items = yield* listAll;
206 return items.map(toAttributes);
207 }),
208
209 read: Effect.fn(function* ({ id, olds, output }) {
210 let observed: licensemanager.GetLicenseConfigurationResponse | undefined;
211 if (output?.licenseConfigurationArn) {
212 observed = yield* getByArn(output.licenseConfigurationArn);
213 } else {
214 const name = yield* createName(id, olds ?? {});
215 const summary = yield* findByName(name);
216 if (summary?.LicenseConfigurationArn) {
217 observed = yield* getByArn(summary.LicenseConfigurationArn);
218 }
219 }
220 if (observed === undefined) return undefined;
221 const attrs = toAttributes(observed);
222 const tags = toTagRecord(observed.Tags);
223 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
224 }),
225
226 diff: Effect.fn(function* ({ news, olds }) {
227 if (!isResolved(news)) return undefined;
228 if (olds.licenseCountingType !== news.licenseCountingType) {
229 return { action: "replace" } as const;
230 }
231 // Everything else (name, description, count, hard limit, rules,
232 // tags) updates in place via the default update path.
233 }),
234
235 reconcile: Effect.fn(function* ({ id, news, output, session }) {
236 const name = yield* createName(id, news);
237 const internalTags = yield* createInternalTags(id);
238 const desiredTags: Record<string, string> = {
239 ...news.tags,
240 ...internalTags,
241 };
242
243 // 1. OBSERVE — output is only an ARN cache; cloud state decides.
244 let observed = output?.licenseConfigurationArn
245 ? yield* getByArn(output.licenseConfigurationArn)
246 : undefined;
247 if (observed === undefined) {
248 // State may have been lost (or this is an adoption without a
249 // persisted ARN) — search by name before creating a duplicate.
250 const summary = yield* findByName(name);
251 if (summary?.LicenseConfigurationArn) {
252 observed = yield* getByArn(summary.LicenseConfigurationArn);
253 }
254 }
255
256 // 2. ENSURE — create when missing.
257 if (observed === undefined) {
258 const created = yield* licensemanager.createLicenseConfiguration({
259 Name: name,
260 Description: news.description,
261 LicenseCountingType: news.licenseCountingType,
262 LicenseCount: news.licenseCount,
263 LicenseCountHardLimit: news.licenseCountHardLimit,
264 LicenseRules: news.licenseRules,
265 DisassociateWhenNotFound: news.disassociateWhenNotFound,
266 Tags: createTagsList(desiredTags),
267 });
268 observed = yield* licensemanager.getLicenseConfiguration({
269 LicenseConfigurationArn: created.LicenseConfigurationArn!,
270 });
271 }
272 const arn = observed.LicenseConfigurationArn!;
273
274 // 3. SYNC — diff each mutable aspect against OBSERVED cloud state
275 // and send only the delta.
276 const update: Omit<
277 licensemanager.UpdateLicenseConfigurationRequest,
278 "LicenseConfigurationArn"
279 > = {};
280 if (observed.Name !== name) {
281 update.Name = name;
282 }
283 if (news.description !== undefined && observed.Description !== news.description) {
284 update.Description = news.description;
285 }
286 if (news.licenseCount !== undefined && observed.LicenseCount !== news.licenseCount) {
287 update.LicenseCount = news.licenseCount;
288 }
289 const desiredHardLimit = news.licenseCountHardLimit ?? false;
290 if ((observed.LicenseCountHardLimit ?? false) !== desiredHardLimit) {
291 update.LicenseCountHardLimit = desiredHardLimit;
292 }
293 if (
294 news.licenseRules !== undefined &&
295 JSON.stringify(observed.LicenseRules ?? []) !== JSON.stringify(news.licenseRules)
296 ) {
297 update.LicenseRules = news.licenseRules;
298 }
299 const desiredDisassociate = news.disassociateWhenNotFound ?? false;
300 if ((observed.DisassociateWhenNotFound ?? false) !== desiredDisassociate) {
301 update.DisassociateWhenNotFound = desiredDisassociate;
302 }
303 if (Object.keys(update).length > 0) {
304 yield* licensemanager.updateLicenseConfiguration({
305 LicenseConfigurationArn: arn,
306 ...update,
307 });
308 }
309
310 // 3b. SYNC TAGS — against observed cloud tags, never olds/output.
311 const observedTags = toTagRecord(observed.Tags);
312 const { upsert, removed } = diffTags(observedTags, desiredTags);
313 if (upsert.length > 0) {
314 yield* licensemanager.tagResource({
315 ResourceArn: arn,
316 Tags: upsert,
317 });
318 }
319 if (removed.length > 0) {
320 yield* licensemanager.untagResource({
321 ResourceArn: arn,
322 TagKeys: removed,
323 });
324 }
325
326 yield* session.note(arn);
327 return {
328 licenseConfigurationId: observed.LicenseConfigurationId!,
329 licenseConfigurationArn: arn,
330 name,
331 licenseCountingType: observed.LicenseCountingType!,
332 };
333 }),
334
335 // Idempotent: deleting an already-deleted (or never-existing)
336 // configuration surfaces the typed not-found tag and is a no-op.
337 delete: Effect.fn(function* ({ output }) {
338 yield* licensemanager
339 .deleteLicenseConfiguration({
340 LicenseConfigurationArn: output.licenseConfigurationArn,
341 })
342 .pipe(Effect.catchTag("LicenseConfigurationNotFound", () => Effect.void));
343 }),
344 });
345 }),
346 );