@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 170 lines 6.22 KB
Raw
1 import type { Credentials } from "@distilled.cloud/aws/Credentials";
2 import * as obs from "@distilled.cloud/aws/observabilityadmin";
3 import type { Region } from "@distilled.cloud/aws/Region";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import type * as HttpClient from "effect/http/HttpClient";
9 import * as Schedule from "effect/Schedule";
10 import type { Providers } from "../Providers.ts";
11
12 export interface TelemetryConfigProps {
13 /**
14 * Whether the CloudWatch telemetry config feature (telemetry evaluation)
15 * is onboarded for this account. Set `false` to keep the resource in the
16 * stack while the feature is off.
17 * @default true
18 */
19 enabled?: boolean;
20 }
21
22 export interface TelemetryConfig extends Resource<
23 "AWS.ObservabilityAdmin.TelemetryConfig",
24 TelemetryConfigProps,
25 {
26 /**
27 * The onboarding status of the telemetry config feature after
28 * reconciliation (`RUNNING` or `STOPPED`).
29 */
30 status: string;
31 /**
32 * The status observed before this stack first managed the feature
33 * (`NOT_STARTED`, `RUNNING`, `STOPPED`, ...). Destroy restores this —
34 * a feature that was already running when the stack adopted it is left
35 * running.
36 */
37 priorStatus: string;
38 },
39 never,
40 Providers
41 > {}
42
43 /**
44 * Account-level CloudWatch **telemetry config** (Observability Admin
45 * telemetry evaluation) — an account singleton that audits which AWS
46 * resources (VPCs, Lambda functions, ...) have telemetry such as flow
47 * logs enabled.
48 *
49 * This is an always-present account *setting*, not a discrete resource:
50 * deploying it onboards the account, and destroying it restores whatever
51 * onboarding state the account had before the stack first managed it.
52 *
53 * ### Managing telemetry config
54 * **Example:** Onboard the account
55 * ```typescript
56 * import * as ObservabilityAdmin from "@alchemy.run/aws/ObservabilityAdmin";
57 *
58 * const telemetry = yield* ObservabilityAdmin.TelemetryConfig("Telemetry");
59 * ```
60 *
61 * **Example:** Keep the resource but switch the feature off
62 * ```typescript
63 * const telemetry = yield* ObservabilityAdmin.TelemetryConfig("Telemetry", {
64 * enabled: false,
65 * });
66 * ```
67 *
68 * @resource
69 */
70 export const TelemetryConfig = Resource<TelemetryConfig>("AWS.ObservabilityAdmin.TelemetryConfig");
71
72 /**
73 * Raised when the telemetry config feature reports `FAILED_START` /
74 * `FAILED_STOP`, or fails to converge within the bounded wait.
75 */
76 export class TelemetryConfigTransitionFailed extends Data.TaggedError(
77 "TelemetryConfigTransitionFailed",
78 )<{ message: string; status: string }> {}
79
80 type ObsRequirements = Credentials | Region | HttpClient.HttpClient;
81
82 const readStatus: Effect.Effect<string, obs.GetTelemetryEvaluationStatusError, ObsRequirements> =
83 obs.getTelemetryEvaluationStatus({}).pipe(Effect.map((r) => r.Status ?? "NOT_STARTED"));
84
85 const ON_STATES = ["RUNNING", "STARTING"];
86
87 /**
88 * Poll the evaluation status on a bounded schedule until it reaches a
89 * settled state (start/stop completed in ~1s in probing; the bound is
90 * defensive). Explicitly typed at module scope so the conditional types of
91 * `Effect.repeat` never leak into the provider layer's declaration emit.
92 */
93 const awaitSettledStatus: Effect.Effect<
94 string,
95 obs.GetTelemetryEvaluationStatusError,
96 ObsRequirements
97 > = readStatus.pipe(
98 Effect.repeat({
99 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(10)]),
100 until: (status) => status !== "STARTING" && status !== "STOPPING",
101 }),
102 );
103
104 const failIfUnsettled = (status: string, transition: "start" | "stop") =>
105 status === "STARTING" || status === "STOPPING" || status.startsWith("FAILED")
106 ? Effect.fail(
107 new TelemetryConfigTransitionFailed({
108 message: `telemetry evaluation did not settle after ${transition} (status: ${status})`,
109 status,
110 }),
111 )
112 : Effect.succeed(status);
113
114 /**
115 * One idempotent convergence step shared by reconcile and delete-restore:
116 * observe the live status and start/stop only on an actual delta.
117 */
118 const convergeTo = Effect.fn(function* (desiredOn: boolean) {
119 const observed = yield* awaitSettledStatus;
120 const isOn = ON_STATES.includes(observed);
121 if (desiredOn && !isOn) {
122 yield* obs.startTelemetryEvaluation({});
123 return yield* failIfUnsettled(yield* awaitSettledStatus, "start");
124 }
125 if (!desiredOn && isOn) {
126 yield* obs.stopTelemetryEvaluation({});
127 return yield* failIfUnsettled(yield* awaitSettledStatus, "stop");
128 }
129 return observed;
130 });
131
132 export const TelemetryConfigProvider = () =>
133 Provider.effect(
134 TelemetryConfig,
135 Effect.gen(function* () {
136 return TelemetryConfig.Provider.of({
137 // Account singleton setting — deleting only restores the prior
138 // onboarding state; nuke must not toggle it.
139 nuke: { singleton: true },
140 stables: ["priorStatus"],
141 // No enumeration API — the singleton is always present as account
142 // configuration, never a discrete listable resource.
143 list: () => Effect.succeed([]),
144 read: Effect.fn(function* ({ output }) {
145 const status = yield* readStatus;
146 return {
147 status,
148 priorStatus: output?.priorStatus ?? status,
149 };
150 }),
151 reconcile: Effect.fn(function* ({ news, output, session }) {
152 // Capture the pre-management status exactly once so destroy can
153 // restore it; on later updates the persisted capture wins.
154 const priorStatus = output?.priorStatus ?? (yield* readStatus);
155 const desiredOn = news.enabled !== false;
156 const status = yield* convergeTo(desiredOn);
157 yield* session.note(`telemetry evaluation ${status}`);
158 return { status, priorStatus };
159 }),
160 delete: Effect.fn(function* ({ output, session }) {
161 // Restore the captured pre-management state instead of blindly
162 // stopping: an account that was already onboarded before this
163 // stack managed it stays onboarded.
164 const priorOn = ON_STATES.includes(output.priorStatus);
165 const status = yield* convergeTo(priorOn);
166 yield* session.note(`telemetry evaluation restored to ${status}`);
167 }),
168 });
169 }),
170 );