@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 224 lines 7.78 KB
Raw
1 import * as devopsguru from "@distilled.cloud/aws/devops-guru";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Schedule from "effect/Schedule";
7 import type { Providers } from "../Providers.ts";
8
9 export interface ServiceIntegrationProps {
10 /**
11 * Create an AWS Systems Manager OpsItem for each new insight so incidents
12 * flow into OpsCenter.
13 * @default false
14 */
15 opsCenter?: boolean;
16 /**
17 * Analyze CloudWatch log groups in the resource collection for log
18 * anomalies and surface them on insights.
19 * @default false
20 */
21 logsAnomalyDetection?: boolean;
22 /**
23 * Encrypt DevOps Guru data with this customer-managed KMS key instead of
24 * the AWS-owned default key. Omit to use the AWS-owned key.
25 */
26 kmsKeyId?: string;
27 }
28
29 export interface ServiceIntegration extends Resource<
30 "AWS.DevOpsGuru.ServiceIntegration",
31 ServiceIntegrationProps,
32 {
33 /** Whether an OpsItem is created for each new insight. */
34 opsCenter: boolean;
35 /** Whether CloudWatch log groups are analyzed for anomalies. */
36 logsAnomalyDetection: boolean;
37 /** Server-side encryption key type (`AWS_OWNED_KMS_KEY` or `CUSTOMER_MANAGED_KEY`). */
38 encryptionType: devopsguru.ServerSideEncryptionType;
39 /** Customer-managed KMS key id, when `encryptionType` is `CUSTOMER_MANAGED_KEY`. */
40 kmsKeyId: string | undefined;
41 },
42 never,
43 Providers
44 > {}
45
46 /**
47 * The DevOps Guru service integration — the account/region singleton that
48 * controls how DevOps Guru integrates with other AWS services: creating a
49 * Systems Manager OpsItem for each insight, analyzing CloudWatch log groups
50 * for anomalies, and encrypting DevOps Guru data with a customer-managed
51 * KMS key.
52 *
53 * An account has exactly one integration configuration, so this resource is
54 * a capture-and-restore singleton: adopting a non-default configuration that
55 * Alchemy did not create requires `--adopt`. Destroying the resource
56 * restores the account defaults (everything disabled, AWS-owned key).
57 *
58 * ### Configuring the Integration
59 * **Example:** Enable Log Anomaly Detection
60 * ```typescript
61 * const integration = yield* DevOpsGuru.ServiceIntegration("Integration", {
62 * logsAnomalyDetection: true,
63 * });
64 * ```
65 *
66 * **Example:** File an OpsItem for Every Insight
67 * ```typescript
68 * const integration = yield* DevOpsGuru.ServiceIntegration("Integration", {
69 * opsCenter: true,
70 * logsAnomalyDetection: true,
71 * });
72 * ```
73 *
74 * **Example:** Encrypt with a Customer-Managed Key
75 * ```typescript
76 * const integration = yield* DevOpsGuru.ServiceIntegration("Integration", {
77 * kmsKeyId: key.keyId,
78 * });
79 * ```
80 *
81 * @resource
82 */
83 export const ServiceIntegration = Resource<ServiceIntegration>("AWS.DevOpsGuru.ServiceIntegration");
84
85 interface ObservedIntegration {
86 opsCenter: boolean;
87 logsAnomalyDetection: boolean;
88 encryptionType: devopsguru.ServerSideEncryptionType;
89 kmsKeyId: string | undefined;
90 }
91
92 const isDefault = (observed: ObservedIntegration) =>
93 !observed.opsCenter &&
94 !observed.logsAnomalyDetection &&
95 observed.encryptionType === "AWS_OWNED_KMS_KEY";
96
97 /**
98 * Concurrent `UpdateServiceIntegration` calls conflict server-side — retry
99 * the typed conflict tag on a short bounded schedule.
100 *
101 * Explicitly typed: inlining `Effect.retry` with options in provider
102 * lifecycle code can widen the provider layer to `unknown` in declaration
103 * emit.
104 *
105 * @internal
106 */
107 const retryUpdateConflict = <A, E extends { readonly _tag: string }, R>(
108 self: Effect.Effect<A, E, R>,
109 ): Effect.Effect<A, E, R> =>
110 Effect.retry(self, {
111 while: (e) => e._tag === "ConflictException",
112 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(8)]),
113 });
114
115 export const ServiceIntegrationProvider = () =>
116 Provider.effect(
117 ServiceIntegration,
118 Effect.gen(function* () {
119 // Observe the live account configuration. Absent sections and absent
120 // opt-in statuses mean "account default" (disabled / AWS-owned key).
121 const observe = Effect.gen(function* () {
122 const { ServiceIntegration: config } = yield* devopsguru.describeServiceIntegration({});
123 const kms = config?.KMSServerSideEncryption;
124 const encryptionType: devopsguru.ServerSideEncryptionType =
125 kms?.Type ?? "AWS_OWNED_KMS_KEY";
126 return {
127 opsCenter: config?.OpsCenter?.OptInStatus === "ENABLED",
128 logsAnomalyDetection: config?.LogsAnomalyDetection?.OptInStatus === "ENABLED",
129 encryptionType,
130 kmsKeyId: encryptionType === "CUSTOMER_MANAGED_KEY" ? kms?.KMSKeyId : undefined,
131 } satisfies ObservedIntegration;
132 });
133
134 const update = Effect.fn(function* (config: devopsguru.UpdateServiceIntegrationConfig) {
135 yield* retryUpdateConflict(
136 devopsguru.updateServiceIntegration({ ServiceIntegration: config }),
137 );
138 });
139
140 // Converge the live configuration to the desired shape, one section
141 // per update call so a partial failure leaves the others converged.
142 const converge = Effect.fn(function* (
143 observed: ObservedIntegration,
144 desired: ServiceIntegrationProps,
145 ) {
146 const wantOpsCenter = desired.opsCenter ?? false;
147 if (observed.opsCenter !== wantOpsCenter) {
148 yield* update({
149 OpsCenter: {
150 OptInStatus: wantOpsCenter ? "ENABLED" : "DISABLED",
151 },
152 });
153 }
154
155 const wantLogs = desired.logsAnomalyDetection ?? false;
156 if (observed.logsAnomalyDetection !== wantLogs) {
157 yield* update({
158 LogsAnomalyDetection: {
159 OptInStatus: wantLogs ? "ENABLED" : "DISABLED",
160 },
161 });
162 }
163
164 if (desired.kmsKeyId !== undefined) {
165 if (
166 observed.encryptionType !== "CUSTOMER_MANAGED_KEY" ||
167 observed.kmsKeyId !== desired.kmsKeyId
168 ) {
169 yield* update({
170 KMSServerSideEncryption: {
171 Type: "CUSTOMER_MANAGED_KEY",
172 KMSKeyId: desired.kmsKeyId,
173 OptInStatus: "ENABLED",
174 },
175 });
176 }
177 } else if (observed.encryptionType === "CUSTOMER_MANAGED_KEY") {
178 yield* update({
179 KMSServerSideEncryption: {
180 Type: "AWS_OWNED_KMS_KEY",
181 OptInStatus: "ENABLED",
182 },
183 });
184 }
185 });
186
187 return {
188 // Account/region singleton — surfaced only when non-default.
189 list: () => observe.pipe(Effect.map((observed) => (isDefault(observed) ? [] : [observed]))),
190
191 read: Effect.fn(function* ({ output }) {
192 const observed = yield* observe;
193 if (isDefault(observed)) {
194 return undefined;
195 }
196 // The integration can't carry ownership tags — a non-default
197 // configuration we have no record of belongs to someone else
198 // until explicitly adopted.
199 return output !== undefined ? observed : Unowned(observed);
200 }),
201
202 reconcile: Effect.fn(function* ({ news, session }) {
203 // 1. OBSERVE — the live account configuration is authoritative.
204 const observed = yield* observe;
205
206 // 2. SYNC — apply only the changed sections.
207 yield* converge(observed, news);
208
209 // 3. RETURN fresh attributes.
210 const final = yield* observe;
211 yield* session.note(
212 `opsCenter: ${final.opsCenter}, logsAnomalyDetection: ${final.logsAnomalyDetection}, encryption: ${final.encryptionType}`,
213 );
214 return final;
215 }),
216
217 // "Deleting" the singleton restores the account defaults.
218 delete: Effect.fn(function* () {
219 const observed = yield* observe;
220 yield* converge(observed, {});
221 }),
222 };
223 }),
224 );