@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 208 lines 8.13 KB
Raw
1 import * as analytics from "@distilled.cloud/aws/kinesis-analytics-v2";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import type { Providers } from "../Providers.ts";
9
10 export interface ApplicationCloudWatchLoggingOptionProps {
11 /**
12 * Name of the Managed Service for Apache Flink application to attach the
13 * logging option to. Changing the application replaces the option.
14 */
15 applicationName: string;
16 /**
17 * ARN of the CloudWatch Logs log stream that receives application
18 * messages. Changing the log stream replaces the option.
19 */
20 logStreamArn: string;
21 }
22
23 export interface ApplicationCloudWatchLoggingOption extends Resource<
24 "AWS.KinesisAnalyticsV2.ApplicationCloudWatchLoggingOption",
25 ApplicationCloudWatchLoggingOptionProps,
26 {
27 /**
28 * Name of the application the option is attached to.
29 */
30 applicationName: string;
31 /**
32 * ARN of the CloudWatch Logs log stream receiving application messages.
33 */
34 logStreamArn: string;
35 /**
36 * Service-assigned ID of the logging option within the application.
37 */
38 cloudWatchLoggingOptionId: string | undefined;
39 },
40 never,
41 Providers
42 > {}
43
44 /**
45 * Attaches an Amazon CloudWatch Logs log stream to a Managed Service for
46 * Apache Flink application so application messages (errors, job lifecycle
47 * events) are delivered to CloudWatch.
48 *
49 * The option is identified by the log stream it delivers to — changing
50 * either the application or the log stream replaces the option. The
51 * application's service execution role must be allowed to call
52 * `logs:PutLogEvents` / `logs:DescribeLogStreams` (the role auto-created by
53 * `Application` already is).
54 * ### Attaching Logging
55 * **Example:** Deliver application messages to a log stream
56 * ```typescript
57 * import * as AWS from "@alchemy.run/aws";
58 *
59 * const logGroup = yield* AWS.Logs.LogGroup("FlinkLogs");
60 * const logStream = yield* AWS.Logs.LogStream("FlinkLogStream", {
61 * logGroupName: logGroup.logGroupName,
62 * });
63 * const logging = yield* AWS.KinesisAnalyticsV2.ApplicationCloudWatchLoggingOption(
64 * "AppLogging",
65 * {
66 * applicationName: app.applicationName,
67 * logStreamArn: logStream.logStreamArn.as<string>(),
68 * },
69 * );
70 * ```
71 *
72 * @resource
73 */
74 export const ApplicationCloudWatchLoggingOption = Resource<ApplicationCloudWatchLoggingOption>(
75 "AWS.KinesisAnalyticsV2.ApplicationCloudWatchLoggingOption",
76 );
77
78 /**
79 * The logging option could not be observed on the application after it was
80 * added — the add call succeeded but the option never appeared.
81 */
82 export class LoggingOptionNotFound extends Data.TaggedError("LoggingOptionNotFound")<{
83 readonly applicationName: string;
84 readonly logStreamArn: string;
85 }> {}
86
87 /**
88 * Retries `ResourceInUseException` / `ConcurrentModificationException`
89 * (application transitioning between statuses, or a concurrent operation in
90 * flight) on a bounded schedule. Explicit return annotation for the same
91 * declaration-emit reason as `retryThroughRolePropagation` in
92 * `Application.ts`.
93 */
94 const retryWhileInUse = <A, E extends { _tag: string }, R>(
95 self: Effect.Effect<A, E, R>,
96 ): Effect.Effect<A, E, R> =>
97 Effect.retry(self, {
98 while: (e) =>
99 e._tag === "ResourceInUseException" || e._tag === "ConcurrentModificationException",
100 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(30)]),
101 });
102
103 const describeApplicationDetail = Effect.fn(function* (applicationName: string) {
104 const response = yield* analytics
105 .describeApplication({ ApplicationName: applicationName })
106 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
107 return response?.ApplicationDetail;
108 });
109
110 const findOption = (detail: analytics.ApplicationDetail | undefined, logStreamArn: string) =>
111 detail?.CloudWatchLoggingOptionDescriptions?.find(
112 (option) => option.LogStreamARN === logStreamArn,
113 );
114
115 export const ApplicationCloudWatchLoggingOptionProvider = () =>
116 Provider.effect(
117 ApplicationCloudWatchLoggingOption,
118 Effect.gen(function* () {
119 return ApplicationCloudWatchLoggingOption.Provider.of({
120 stables: ["applicationName", "logStreamArn", "cloudWatchLoggingOptionId"],
121
122 // Sub-resource keyed by its parent application — there is no
123 // account-level enumeration of logging options, so `list` is empty
124 // and refresh flows through `read` on known instances.
125 list: () => Effect.succeed([]),
126
127 read: Effect.fn(function* ({ olds, output }) {
128 const applicationName = output?.applicationName ?? olds?.applicationName;
129 const logStreamArn = output?.logStreamArn ?? olds?.logStreamArn;
130 if (!applicationName || !logStreamArn) return undefined;
131 const detail = yield* describeApplicationDetail(applicationName);
132 const option = findOption(detail, logStreamArn);
133 if (!option) return undefined;
134 return {
135 applicationName,
136 logStreamArn,
137 cloudWatchLoggingOptionId: option.CloudWatchLoggingOptionId,
138 };
139 }),
140
141 diff: Effect.fn(function* ({ news, olds }) {
142 if (!isResolved(news)) return undefined;
143 // The option's identity is (application, log stream) — the only
144 // way to change either is to delete and re-add.
145 if (
146 olds?.applicationName !== news?.applicationName ||
147 olds?.logStreamArn !== news?.logStreamArn
148 ) {
149 return { action: "replace" } as const;
150 }
151 }),
152
153 // Existence-only sub-resource: observe → if missing, add. The add
154 // uses the freshly observed application version id as its
155 // compare-and-set token and is retried through concurrent
156 // modifications with a re-read.
157 reconcile: Effect.fn(function* ({ news, session }) {
158 const applicationName = news.applicationName;
159 const logStreamArn = news.logStreamArn;
160
161 const ensureOption = Effect.gen(function* () {
162 const detail = yield* describeApplicationDetail(applicationName);
163 const existing = findOption(detail, logStreamArn);
164 if (existing || !detail) return existing;
165 const response = yield* analytics.addApplicationCloudWatchLoggingOption({
166 ApplicationName: applicationName,
167 CurrentApplicationVersionId: detail.ApplicationVersionId,
168 CloudWatchLoggingOption: { LogStreamARN: logStreamArn },
169 });
170 return response.CloudWatchLoggingOptionDescriptions?.find(
171 (option) => option.LogStreamARN === logStreamArn,
172 );
173 });
174 const option = yield* retryWhileInUse(ensureOption);
175 if (!option) {
176 return yield* new LoggingOptionNotFound({ applicationName, logStreamArn });
177 }
178
179 yield* session.note(
180 `CloudWatch logging option ${option.CloudWatchLoggingOptionId ?? logStreamArn}`,
181 );
182 return {
183 applicationName,
184 logStreamArn,
185 cloudWatchLoggingOptionId: option.CloudWatchLoggingOptionId,
186 };
187 }),
188
189 delete: Effect.fn(function* ({ output }) {
190 // A missing application means the option is already gone.
191 const removeOption = Effect.gen(function* () {
192 const detail = yield* describeApplicationDetail(output.applicationName);
193 const option = findOption(detail, output.logStreamArn);
194 const optionId = option?.CloudWatchLoggingOptionId ?? output.cloudWatchLoggingOptionId;
195 if (!detail || !option || !optionId) return;
196 yield* analytics
197 .deleteApplicationCloudWatchLoggingOption({
198 ApplicationName: output.applicationName,
199 CurrentApplicationVersionId: detail.ApplicationVersionId,
200 CloudWatchLoggingOptionId: optionId,
201 })
202 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
203 });
204 yield* retryWhileInUse(removeOption);
205 }),
206 });
207 }),
208 );