@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, 06:00 UTC

main
ts 706 lines 26.2 KB
Raw
1 import * as mq from "@distilled.cloud/aws/mq";
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 type * as Redacted from "effect/Redacted";
11 import * as Schedule from "effect/Schedule";
12 import * as Stream from "effect/Stream";
13 import type { Providers } from "../Providers.ts";
14 import { syncMqTags, toTagRecord } from "./internal.ts";
15
16 export class BrokerConflict extends Data.TaggedError("BrokerConflict")<{
17 readonly message: string;
18 readonly cause?: unknown;
19 }> {}
20
21 export class BrokerOperationFailed extends Data.TaggedError("BrokerOperationFailed")<{
22 readonly message: string;
23 readonly cause?: unknown;
24 }> {}
25
26 export class BrokerUnexpectedResponse extends Data.TaggedError("BrokerUnexpectedResponse")<{
27 readonly message: string;
28 readonly cause?: unknown;
29 }> {}
30
31 /**
32 * An ActiveMQ or RabbitMQ user provisioned on the broker at creation.
33 */
34 export interface BrokerUser {
35 /**
36 * Username (2-100 chars, `a-z A-Z 0-9 _ ~ . -`). Must not contain commas,
37 * colons, equals signs, or the string `tag:`.
38 */
39 username: string;
40 /**
41 * Password (12-250 printable chars, no commas, colons, or equals signs).
42 */
43 password: Redacted.Redacted<string>;
44 /**
45 * Whether the user can access the ActiveMQ Web Console. Ignored for
46 * RabbitMQ.
47 * @default false
48 */
49 consoleAccess?: boolean;
50 /**
51 * ActiveMQ groups the user belongs to. Ignored for RabbitMQ.
52 */
53 groups?: string[];
54 }
55
56 /**
57 * Reference to a specific {@link Configuration} revision to apply to the
58 * broker.
59 */
60 export interface BrokerConfigurationRef {
61 /** The configuration id (`configurationId` attribute of a Configuration). */
62 id: string;
63 /** The revision number to apply. */
64 revision?: number;
65 }
66
67 /**
68 * CloudWatch log exports to enable for the broker.
69 */
70 export interface BrokerLogs {
71 /** Enable audit logging (ActiveMQ only). */
72 audit?: boolean;
73 /** Enable general logging. */
74 general?: boolean;
75 }
76
77 /**
78 * Weekly maintenance window during which the broker applies pending changes.
79 */
80 export interface BrokerMaintenanceWindow {
81 /** Day of week, e.g. `"SUNDAY"`. */
82 dayOfWeek: "MONDAY" | "TUESDAY" | "WEDNESDAY" | "THURSDAY" | "FRIDAY" | "SATURDAY" | "SUNDAY";
83 /** Start time in 24h `HH:mm` format, e.g. `"03:00"`. */
84 timeOfDay: string;
85 /** IANA time zone, e.g. `"UTC"`. */
86 timeZone?: string;
87 }
88
89 /**
90 * At-rest encryption options for the broker.
91 */
92 export interface BrokerEncryptionOptions {
93 /** Customer-managed KMS key id/ARN. Omit to use an AWS-owned key. */
94 kmsKeyId?: string;
95 /** Use an AWS-owned key rather than a customer-managed one. */
96 useAwsOwnedKey?: boolean;
97 }
98
99 export interface BrokerProps {
100 /**
101 * Name of the broker (1-50 chars, `a-z A-Z 0-9 _ ~ -`). If omitted a
102 * deterministic physical name is generated. Immutable — changing it
103 * replaces the broker.
104 */
105 brokerName?: string;
106 /**
107 * Broker engine. Immutable — changing it replaces the broker.
108 */
109 engineType: "ACTIVEMQ" | "RABBITMQ";
110 /**
111 * Broker engine version (e.g. `"5.18"` for ActiveMQ, `"3.13"` for
112 * RabbitMQ). Mutable — a change is applied as a pending broker update.
113 */
114 engineVersion?: string;
115 /**
116 * Broker instance type, e.g. `"mq.t3.micro"` (the cheapest) or
117 * `"mq.m5.large"`. Mutable — a change is applied as a pending broker
118 * update.
119 */
120 hostInstanceType: string;
121 /**
122 * Deployment topology. `SINGLE_INSTANCE` is a single broker (cheapest,
123 * no HA); `ACTIVE_STANDBY_MULTI_AZ` (ActiveMQ) and `CLUSTER_MULTI_AZ`
124 * (RabbitMQ) provide HA. Immutable — changing it replaces the broker.
125 * @default "SINGLE_INSTANCE"
126 */
127 deploymentMode?: "SINGLE_INSTANCE" | "ACTIVE_STANDBY_MULTI_AZ" | "CLUSTER_MULTI_AZ";
128 /**
129 * Broker users. ActiveMQ requires at least one; RabbitMQ requires exactly
130 * one. Users are provisioned at creation and are not reconciled on update.
131 */
132 users: BrokerUser[];
133 /**
134 * Whether the broker is reachable over the public internet. Immutable —
135 * changing it replaces the broker.
136 * @default false
137 */
138 publiclyAccessible?: boolean;
139 /**
140 * Subnet ids to deploy the broker into. `SINGLE_INSTANCE` needs one
141 * subnet; multi-AZ needs two (ActiveMQ) or three (RabbitMQ cluster). If
142 * omitted, a default-VPC subnet is chosen. Immutable — changing it
143 * replaces the broker.
144 */
145 subnetIds?: string[];
146 /**
147 * Security group ids controlling access to the broker. Mutable — a change
148 * is applied as a pending broker update.
149 */
150 securityGroups?: string[];
151 /**
152 * Authentication strategy. Mutable — a change is applied as a pending
153 * broker update.
154 * @default "SIMPLE"
155 */
156 authenticationStrategy?: "SIMPLE" | "LDAP";
157 /**
158 * Whether to automatically apply minor engine version upgrades during the
159 * maintenance window. RabbitMQ and newer ActiveMQ versions require `true`.
160 * Mutable.
161 * @default true
162 */
163 autoMinorVersionUpgrade?: boolean;
164 /**
165 * Storage type. `EBS` (durable, default) or `EFS` (ActiveMQ multi-AZ
166 * only). Immutable — changing it replaces the broker.
167 */
168 storageType?: "EBS" | "EFS";
169 /**
170 * A {@link Configuration} revision to apply. Mutable — a change is applied
171 * as a pending broker update.
172 */
173 configuration?: BrokerConfigurationRef;
174 /**
175 * CloudWatch log exports. Mutable.
176 */
177 logs?: BrokerLogs;
178 /**
179 * Weekly maintenance window. Mutable.
180 */
181 maintenanceWindow?: BrokerMaintenanceWindow;
182 /**
183 * At-rest encryption options. Immutable — changing it replaces the broker.
184 */
185 encryptionOptions?: BrokerEncryptionOptions;
186 /**
187 * User-defined tags for the broker.
188 */
189 tags?: Record<string, string>;
190 }
191
192 export interface Broker extends Resource<
193 "AWS.MQ.Broker",
194 BrokerProps,
195 {
196 /** Server-assigned unique id of the broker (e.g. `b-1234...`). */
197 brokerId: string;
198 /** ARN of the broker. */
199 brokerArn: string;
200 /** Name of the broker. */
201 brokerName: string;
202 /** Current lifecycle state (e.g. `CREATION_IN_PROGRESS`, `RUNNING`). */
203 brokerState: string;
204 /** Wire-level connection endpoints (protocol URIs) for the broker. */
205 endpoints: string[] | undefined;
206 /** ActiveMQ Web Console URL (undefined for RabbitMQ). */
207 consoleUrl: string | undefined;
208 },
209 never,
210 Providers
211 > {}
212
213 /**
214 * An Amazon MQ broker — a managed message broker running Apache ActiveMQ or
215 * RabbitMQ. Amazon MQ handles provisioning, patching, and (for multi-AZ
216 * deployments) failover, exposing standard wire protocols (OpenWire, AMQP,
217 * MQTT, STOMP, WSS) so existing clients connect unchanged.
218 *
219 * Broker creation and deletion are asynchronous and take several minutes;
220 * the provider waits (bounded) for the broker to reach `RUNNING` before
221 * returning, and waits for it to disappear on delete.
222 *
223 * ### Creating a Broker
224 * **Example:** Single-instance ActiveMQ (cheapest)
225 * ```typescript
226 * const broker = yield* MQ.Broker("Orders", {
227 * engineType: "ACTIVEMQ",
228 * engineVersion: "5.18",
229 * hostInstanceType: "mq.t3.micro",
230 * deploymentMode: "SINGLE_INSTANCE",
231 * publiclyAccessible: true,
232 * users: [{ username: "admin", password: Redacted.make("SuperSecretPassw0rd") }],
233 * });
234 * // broker.endpoints -> ["ssl://b-xxxx-1.mq.us-west-2.amazonaws.com:61617", ...]
235 * ```
236 *
237 * **Example:** Single-instance RabbitMQ
238 * ```typescript
239 * const broker = yield* MQ.Broker("Events", {
240 * engineType: "RABBITMQ",
241 * engineVersion: "3.13",
242 * hostInstanceType: "mq.t3.micro",
243 * publiclyAccessible: true,
244 * users: [{ username: "admin", password: Redacted.make("SuperSecretPassw0rd") }],
245 * });
246 * ```
247 *
248 * ### Networking and Encryption
249 * **Example:** Private broker in specific subnets with a customer KMS key
250 * ```typescript
251 * const broker = yield* MQ.Broker("Orders", {
252 * engineType: "ACTIVEMQ",
253 * engineVersion: "5.18",
254 * hostInstanceType: "mq.m5.large",
255 * deploymentMode: "ACTIVE_STANDBY_MULTI_AZ",
256 * publiclyAccessible: false,
257 * subnetIds: [subnetA.subnetId, subnetB.subnetId],
258 * securityGroups: [group.groupId],
259 * encryptionOptions: { kmsKeyId: key.keyArn },
260 * users: [{ username: "admin", password: Redacted.make("SuperSecretPassw0rd") }],
261 * });
262 * ```
263 *
264 * ### Logging and Maintenance
265 * **Example:** Enable CloudWatch logs and pin a maintenance window
266 * ```typescript
267 * const broker = yield* MQ.Broker("Orders", {
268 * engineType: "ACTIVEMQ",
269 * engineVersion: "5.18",
270 * hostInstanceType: "mq.t3.micro",
271 * users: [{ username: "admin", password: Redacted.make("SuperSecretPassw0rd") }],
272 * logs: { general: true, audit: true },
273 * maintenanceWindow: {
274 * dayOfWeek: "SUNDAY",
275 * timeOfDay: "03:00",
276 * timeZone: "UTC",
277 * },
278 * });
279 * ```
280 *
281 * ### Consuming Messages
282 * Subscribe a Lambda function to broker queues from the init phase via
283 * {@link consumeBrokerMessages}. The event-source mapping, IAM grants, and
284 * runtime dispatch are created automatically (provide
285 * `Lambda.BrokerEventSource` on the function).
286 *
287 * **Example:** Process queue messages in a Lambda function
288 * ```typescript
289 * // init
290 * yield* MQ.consumeBrokerMessages(
291 * broker,
292 * {
293 * queues: ["orders"],
294 * credentialsSecretArn: secret.secretArn,
295 * },
296 * (messages) =>
297 * messages.pipe(
298 * Stream.runForEach((message) =>
299 * Effect.log(`received: ${message.data}`),
300 * ),
301 * ),
302 * );
303 * ```
304 *
305 * @resource
306 */
307 export const Broker = Resource<Broker>("AWS.MQ.Broker");
308
309 class BrokerNotSettled extends Data.TaggedError("BrokerNotSettled")<{
310 readonly brokerId: string;
311 readonly state: string;
312 }> {}
313
314 const sameArray = (a: readonly string[] | undefined, b: readonly string[] | undefined): boolean => {
315 const as = [...(a ?? [])].sort();
316 const bs = [...(b ?? [])].sort();
317 return as.length === bs.length && as.every((v, i) => v === bs[i]);
318 };
319
320 const toWireUsers = (users: BrokerUser[]): mq.User[] =>
321 users.map((u) => ({
322 Username: u.username,
323 // distilled marks Password sensitive — pass the Redacted value through so
324 // it stays redacted until wire encoding.
325 Password: u.password,
326 ConsoleAccess: u.consoleAccess,
327 Groups: u.groups,
328 }));
329
330 export const BrokerProvider = () =>
331 Provider.effect(
332 Broker,
333 Effect.gen(function* () {
334 const toName = (id: string, props: Partial<BrokerProps>) =>
335 props.brokerName
336 ? Effect.succeed(props.brokerName)
337 : createPhysicalName({ id, maxLength: 50 });
338
339 /** Describe a broker by id; a missing broker reads as absent. */
340 const readBroker = Effect.fn(function* (brokerId: string) {
341 return yield* mq
342 .describeBroker({ BrokerId: brokerId })
343 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
344 });
345
346 /** Find a live broker by name (listBrokers has no name filter). */
347 const findByName = Effect.fn(function* (name: string) {
348 const summary = yield* mq.listBrokers.pages({}).pipe(
349 Stream.runCollect,
350 Effect.map((chunk) =>
351 Array.from(chunk)
352 .flatMap((page) => page.BrokerSummaries ?? [])
353 .find((s) => s.BrokerName === name && s.BrokerId),
354 ),
355 );
356 if (!summary?.BrokerId) return undefined;
357 return yield* readBroker(summary.BrokerId);
358 });
359
360 // Broker creation is asynchronous and typically takes 5-10 minutes;
361 // budget ~12 min (72 * 10s). Wait until the broker leaves a transient
362 // state (CREATION_IN_PROGRESS / REBOOT_IN_PROGRESS).
363 const waitForSettled = Effect.fn(function* (brokerId: string) {
364 return yield* readBroker(brokerId).pipe(
365 Effect.flatMap((broker) => {
366 const state = broker?.BrokerState;
367 if (state === "CREATION_IN_PROGRESS" || state === "REBOOT_IN_PROGRESS") {
368 return Effect.fail(new BrokerNotSettled({ brokerId, state }));
369 }
370 return Effect.succeed(broker);
371 }),
372 Effect.retry({
373 while: (e) => e instanceof BrokerNotSettled,
374 schedule: Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(72)]),
375 }),
376 );
377 });
378
379 // Deletion is asynchronous too; wait until the broker is gone so
380 // networking dependencies (subnets, security groups) can be removed.
381 const waitUntilGone = Effect.fn(function* (brokerId: string) {
382 yield* readBroker(brokerId).pipe(
383 Effect.flatMap((broker) => {
384 if (broker === undefined) return Effect.void;
385 return Effect.fail(
386 new BrokerNotSettled({
387 brokerId,
388 state: broker.BrokerState ?? "UNKNOWN",
389 }),
390 );
391 }),
392 Effect.retry({
393 while: (e) => e instanceof BrokerNotSettled,
394 schedule: Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(72)]),
395 }),
396 );
397 });
398
399 /**
400 * Delete the configuration Amazon MQ auto-generated for a broker
401 * created without one. Only that default is touched — a user-managed
402 * `Configuration` (its own resource) is identified by name + the
403 * service's "Auto-generated default for <broker>-configuration" revision description
404 * and left alone. Best-effort and bounded: the broker delete has
405 * already completed, so failures only log a warning.
406 */
407 const reapAutoGeneratedConfiguration = (configurationId: string, brokerName: string) =>
408 Effect.gen(function* () {
409 const config = yield* mq.describeConfiguration({ ConfigurationId: configurationId });
410 const defaultName = `${brokerName}-configuration`;
411 if (
412 config.Name !== defaultName ||
413 !config.LatestRevision?.Description?.startsWith(
414 `Auto-generated default for ${defaultName} `,
415 )
416 ) {
417 return;
418 }
419 yield* mq.deleteConfiguration({ ConfigurationId: configurationId }).pipe(
420 // Still referenced while the broker deletion propagates.
421 Effect.retry({
422 while: (e) => e._tag === "ConflictException",
423 schedule: Schedule.exponential("1 second"),
424 times: 6,
425 }),
426 );
427 }).pipe(
428 Effect.catchTag("NotFoundException", () => Effect.void),
429 Effect.catch((e) =>
430 Effect.logWarning(
431 `Failed to delete auto-generated MQ configuration ${configurationId}: ${e._tag}`,
432 ),
433 ),
434 );
435
436 const toAttrs = (broker: mq.DescribeBrokerResponse) => ({
437 brokerId: broker.BrokerId!,
438 brokerArn: broker.BrokerArn!,
439 brokerName: broker.BrokerName!,
440 brokerState: broker.BrokerState!,
441 endpoints: broker.BrokerInstances?.[0]?.Endpoints,
442 consoleUrl: broker.BrokerInstances?.[0]?.ConsoleURL,
443 });
444
445 return {
446 stables: ["brokerId", "brokerArn", "brokerName"],
447
448 diff: Effect.fn(function* ({ id, olds, news }) {
449 if (!isResolved(news)) return undefined;
450 const replaced = (yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}));
451 if (replaced) return { action: "replace" } as const;
452 // Create-only properties.
453 if ((news.engineType ?? undefined) !== (olds?.engineType ?? undefined))
454 return { action: "replace" } as const;
455 if (
456 (news.deploymentMode ?? "SINGLE_INSTANCE") !==
457 (olds?.deploymentMode ?? "SINGLE_INSTANCE")
458 )
459 return { action: "replace" } as const;
460 if ((news.publiclyAccessible ?? false) !== (olds?.publiclyAccessible ?? false))
461 return { action: "replace" } as const;
462 if ((news.storageType ?? undefined) !== (olds?.storageType ?? undefined))
463 return { action: "replace" } as const;
464 if (news.subnetIds !== undefined && !sameArray(news.subnetIds, olds?.subnetIds))
465 return { action: "replace" } as const;
466 if (
467 (news.encryptionOptions?.kmsKeyId ?? undefined) !==
468 (olds?.encryptionOptions?.kmsKeyId ?? undefined) ||
469 (news.encryptionOptions?.useAwsOwnedKey ?? undefined) !==
470 (olds?.encryptionOptions?.useAwsOwnedKey ?? undefined)
471 )
472 return { action: "replace" } as const;
473 }),
474
475 read: Effect.fn(function* ({ id, olds, output }) {
476 const broker = output?.brokerId
477 ? yield* readBroker(output.brokerId)
478 : yield* findByName(yield* toName(id, olds ?? {}));
479 if (broker === undefined) return undefined;
480 const attrs = toAttrs(broker);
481 const tags = toTagRecord(broker.Tags);
482 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
483 }),
484
485 reconcile: Effect.fn(function* ({ id, news, output, session }) {
486 const name = output?.brokerName ?? (yield* toName(id, news));
487 const internalTags = yield* createInternalTags(id);
488 const desiredTags = { ...internalTags, ...news.tags };
489
490 // 1. Observe — cloud state is authoritative.
491 let observed = output?.brokerId ? yield* readBroker(output.brokerId) : undefined;
492 if (observed === undefined) {
493 observed = yield* findByName(name);
494 }
495
496 // 2. Ensure — create if missing. The deterministic CreatorRequestId
497 // makes a retried create idempotent. Tolerate a ConflictException
498 // race by re-finding the broker by name.
499 if (observed === undefined) {
500 const created = yield* mq
501 .createBroker({
502 BrokerName: name,
503 EngineType: news.engineType,
504 EngineVersion: news.engineVersion,
505 HostInstanceType: news.hostInstanceType,
506 DeploymentMode: news.deploymentMode ?? "SINGLE_INSTANCE",
507 PubliclyAccessible: news.publiclyAccessible ?? false,
508 AutoMinorVersionUpgrade: news.autoMinorVersionUpgrade ?? true,
509 AuthenticationStrategy: news.authenticationStrategy,
510 StorageType: news.storageType,
511 SubnetIds: news.subnetIds,
512 SecurityGroups: news.securityGroups,
513 Users: toWireUsers(news.users),
514 Configuration: news.configuration
515 ? {
516 Id: news.configuration.id,
517 Revision: news.configuration.revision,
518 }
519 : undefined,
520 Logs: news.logs
521 ? { Audit: news.logs.audit, General: news.logs.general }
522 : undefined,
523 MaintenanceWindowStartTime: news.maintenanceWindow
524 ? {
525 DayOfWeek: news.maintenanceWindow.dayOfWeek,
526 TimeOfDay: news.maintenanceWindow.timeOfDay,
527 TimeZone: news.maintenanceWindow.timeZone,
528 }
529 : undefined,
530 EncryptionOptions: news.encryptionOptions
531 ? {
532 KmsKeyId: news.encryptionOptions.kmsKeyId,
533 UseAwsOwnedKey: news.encryptionOptions.useAwsOwnedKey,
534 }
535 : undefined,
536 CreatorRequestId: name,
537 Tags: desiredTags,
538 })
539 .pipe(
540 Effect.catchTag("ConflictException", () =>
541 Effect.gen(function* () {
542 const existing = yield* findByName(name);
543 if (existing?.BrokerId) {
544 return { BrokerId: existing.BrokerId };
545 }
546 return yield* new BrokerConflict({
547 message: `MQ broker '${name}' create conflicted but no broker was found`,
548 });
549 }),
550 ),
551 );
552 observed = yield* readBroker(created.BrokerId!);
553 }
554
555 if (observed?.BrokerId === undefined) {
556 return yield* new BrokerUnexpectedResponse({
557 message: `MQ broker '${name}' could not be reconciled`,
558 });
559 }
560 const brokerId = observed.BrokerId;
561
562 // Wait (bounded) for the broker to settle before mutating it.
563 const settled = yield* waitForSettled(brokerId);
564 if (settled === undefined) {
565 return yield* new BrokerUnexpectedResponse({
566 message: `MQ broker '${name}' disappeared while reconciling`,
567 });
568 }
569 observed = settled;
570 if (observed.BrokerState === "CREATION_FAILED") {
571 return yield* new BrokerOperationFailed({
572 message: `MQ broker '${name}' failed to create (state: CREATION_FAILED)`,
573 });
574 }
575
576 // 3. Sync mutable settings — compute an updateBroker request with
577 // only the drifted fields (each mutation becomes a pending change).
578 const update: Omit<mq.UpdateBrokerRequest, "BrokerId"> = {};
579 if (
580 news.engineVersion !== undefined &&
581 news.engineVersion !== observed.EngineVersion &&
582 news.engineVersion !== observed.PendingEngineVersion
583 ) {
584 update.EngineVersion = news.engineVersion;
585 }
586 if (
587 news.hostInstanceType !== observed.HostInstanceType &&
588 news.hostInstanceType !== observed.PendingHostInstanceType
589 ) {
590 update.HostInstanceType = news.hostInstanceType;
591 }
592 if (
593 news.autoMinorVersionUpgrade !== undefined &&
594 news.autoMinorVersionUpgrade !== observed.AutoMinorVersionUpgrade
595 ) {
596 update.AutoMinorVersionUpgrade = news.autoMinorVersionUpgrade;
597 }
598 if (
599 news.securityGroups !== undefined &&
600 !sameArray(news.securityGroups, observed.SecurityGroups)
601 ) {
602 update.SecurityGroups = news.securityGroups;
603 }
604 if (
605 news.logs !== undefined &&
606 (news.logs.audit !== observed.Logs?.Audit ||
607 news.logs.general !== observed.Logs?.General)
608 ) {
609 update.Logs = {
610 Audit: news.logs.audit,
611 General: news.logs.general,
612 };
613 }
614 if (
615 news.configuration !== undefined &&
616 (news.configuration.id !== observed.Configurations?.Current?.Id ||
617 news.configuration.revision !== observed.Configurations?.Current?.Revision)
618 ) {
619 update.Configuration = {
620 Id: news.configuration.id,
621 Revision: news.configuration.revision,
622 };
623 }
624 if (
625 news.maintenanceWindow !== undefined &&
626 (news.maintenanceWindow.dayOfWeek !== observed.MaintenanceWindowStartTime?.DayOfWeek ||
627 news.maintenanceWindow.timeOfDay !== observed.MaintenanceWindowStartTime?.TimeOfDay ||
628 news.maintenanceWindow.timeZone !== observed.MaintenanceWindowStartTime?.TimeZone)
629 ) {
630 update.MaintenanceWindowStartTime = {
631 DayOfWeek: news.maintenanceWindow.dayOfWeek,
632 TimeOfDay: news.maintenanceWindow.timeOfDay,
633 TimeZone: news.maintenanceWindow.timeZone,
634 };
635 }
636 if (
637 news.authenticationStrategy !== undefined &&
638 news.authenticationStrategy !== observed.AuthenticationStrategy &&
639 news.authenticationStrategy !== observed.PendingAuthenticationStrategy
640 ) {
641 update.AuthenticationStrategy = news.authenticationStrategy;
642 }
643 if (Object.keys(update).length > 0) {
644 yield* mq.updateBroker({ BrokerId: brokerId, ...update });
645 }
646
647 // 3b. Sync tags — diff against OBSERVED cloud tags.
648 yield* syncMqTags(observed.BrokerArn!, toTagRecord(observed.Tags), desiredTags);
649
650 // 4. Re-read for fresh attributes (endpoints appear once RUNNING).
651 const final = (yield* readBroker(brokerId)) ?? observed;
652 yield* session.note(name);
653 return toAttrs(final);
654 }),
655
656 delete: Effect.fn(function* ({ output }) {
657 // A broker mid-operation rejects deletion — wait for it to settle.
658 yield* waitForSettled(output.brokerId).pipe(Effect.catch(() => Effect.void));
659 // Every configuration the broker has referenced. A broker created
660 // without `configuration` gets one auto-generated by Amazon MQ
661 // (`<brokerName>-configuration`), which outlives the broker.
662 const observed = yield* readBroker(output.brokerId);
663 const configurationIds = [
664 observed?.Configurations?.Current?.Id,
665 observed?.Configurations?.Pending?.Id,
666 ...(observed?.Configurations?.History ?? []).map((c) => c.Id),
667 ].filter((id, i, all): id is string => id !== undefined && all.indexOf(id) === i);
668 yield* mq
669 .deleteBroker({ BrokerId: output.brokerId })
670 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
671 yield* waitUntilGone(output.brokerId);
672 yield* Effect.forEach(
673 configurationIds,
674 (configurationId) => reapAutoGeneratedConfiguration(configurationId, output.brokerName),
675 { discard: true },
676 );
677 }),
678
679 list: () =>
680 mq.listBrokers.pages({}).pipe(
681 Stream.runCollect,
682 Effect.map((chunk) =>
683 Array.from(chunk)
684 .flatMap((page) => page.BrokerSummaries ?? [])
685 .flatMap((s) =>
686 s.BrokerId !== undefined &&
687 s.BrokerArn !== undefined &&
688 s.BrokerName !== undefined &&
689 s.BrokerState !== undefined
690 ? [
691 {
692 brokerId: s.BrokerId,
693 brokerArn: s.BrokerArn,
694 brokerName: s.BrokerName,
695 brokerState: s.BrokerState,
696 endpoints: undefined,
697 consoleUrl: undefined,
698 },
699 ]
700 : [],
701 ),
702 ),
703 ),
704 };
705 }),
706 );