The best way to control Claude Code, Codex and more from any computer or phone

main
ts 176 lines 6.54 KB
Raw
1 import * as shield from "@distilled.cloud/aws/shield";
2 import { Unowned } from "alchemy/AdoptPolicy";
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 type { Providers } from "../Providers.ts";
8
9 export class ShieldSubscriptionUnexpectedResponse extends Data.TaggedError(
10 "ShieldSubscriptionUnexpectedResponse",
11 )<{
12 readonly message: string;
13 readonly cause?: unknown;
14 }> {}
15
16 /** Whether the Shield Advanced subscription renews automatically. */
17 export type SubscriptionAutoRenew = "ENABLED" | "DISABLED";
18
19 export interface SubscriptionProps {
20 /**
21 * Whether the subscription renews automatically at the end of the 1-year
22 * commitment. Mutable — but AWS only allows changing it in the 30 days
23 * before the current period ends.
24 * @default "ENABLED"
25 */
26 autoRenew?: SubscriptionAutoRenew;
27 }
28
29 export interface Subscription extends Resource<
30 "AWS.Shield.Subscription",
31 SubscriptionProps,
32 {
33 /** ARN of the subscription. */
34 subscriptionArn: string | undefined;
35 /** Start of the current subscription period (ISO timestamp). */
36 startTime: string | undefined;
37 /** End of the current subscription period (ISO timestamp). */
38 endTime: string | undefined;
39 /** Length of the commitment, in seconds (1 year). */
40 timeCommitmentInSeconds: number | undefined;
41 /** Whether the subscription auto-renews. */
42 autoRenew: string | undefined;
43 /** Whether proactive engagement by the Shield Response Team is enabled. */
44 proactiveEngagementStatus: string | undefined;
45 },
46 never,
47 Providers
48 > {}
49
50 /**
51 * The account-level AWS Shield Advanced subscription.
52 *
53 * :::caution
54 * Creating this resource subscribes the account to Shield Advanced at
55 * **$3,000/month with a mandatory 1-year commitment** (billed to the
56 * Organizations payer account). AWS refuses `DeleteSubscription` until the
57 * commitment ends, so destroying this resource before then leaves the
58 * subscription in place (a warning is logged); after the commitment it is
59 * cancelled for real.
60 * :::
61 *
62 * ### Subscribing to Shield Advanced
63 * **Example:** Subscribe with Auto-Renew
64 * ```typescript
65 * const subscription = yield* Shield.Subscription("Shield", {});
66 * ```
67 *
68 * **Example:** Subscribe and Disable Auto-Renew
69 * ```typescript
70 * const subscription = yield* Shield.Subscription("Shield", {
71 * autoRenew: "DISABLED",
72 * });
73 * ```
74 */
75 const SubscriptionResource = Resource<Subscription>("AWS.Shield.Subscription");
76
77 export { SubscriptionResource as Subscription };
78
79 // `describeSubscription` fails with the (patched) typed `SubscriptionNotFound`
80 // when the account is not subscribed — collapse it to `undefined`.
81 const observeSubscription = shield.describeSubscription({}).pipe(
82 Effect.map((r) => r.Subscription),
83 Effect.catchTag("SubscriptionNotFound", () => Effect.undefined),
84 );
85
86 const buildAttrs = (subscription: shield.Subscription) => ({
87 subscriptionArn: subscription.SubscriptionArn,
88 startTime: subscription.StartTime?.toISOString(),
89 endTime: subscription.EndTime?.toISOString(),
90 timeCommitmentInSeconds: subscription.TimeCommitmentInSeconds,
91 autoRenew: subscription.AutoRenew,
92 proactiveEngagementStatus: subscription.ProactiveEngagementStatus,
93 });
94
95 export const SubscriptionProvider = () =>
96 Provider.effect(
97 SubscriptionResource,
98 Effect.gen(function* () {
99 return {
100 stables: ["subscriptionArn"],
101
102 read: Effect.fn(function* ({ output }) {
103 const subscription = yield* observeSubscription;
104 if (!subscription) return undefined;
105 const attrs = buildAttrs(subscription);
106 // Shield subscriptions carry no tags, so ownership cannot be
107 // verified from cloud state alone. Treat it as ours only when we
108 // have prior state; otherwise gate adoption behind --adopt.
109 return output ? attrs : Unowned(attrs);
110 }),
111
112 // Account-level singleton — report the single subscription, if any.
113 list: () =>
114 observeSubscription.pipe(
115 Effect.map((subscription) => (subscription ? [buildAttrs(subscription)] : [])),
116 ),
117
118 reconcile: Effect.fn(function* ({ news, session }) {
119 // 1. OBSERVE — cloud state is authoritative.
120 let subscription = yield* observeSubscription;
121
122 // 2. ENSURE — subscribe if not already; tolerate the AlreadyExists
123 // race.
124 if (!subscription) {
125 yield* shield
126 .createSubscription({})
127 .pipe(Effect.catchTag("ResourceAlreadyExistsException", () => Effect.void));
128 subscription = yield* shield
129 .describeSubscription({})
130 .pipe(Effect.map((r) => r.Subscription));
131 if (!subscription) {
132 return yield* new ShieldSubscriptionUnexpectedResponse({
133 message: "Failed to create or read the Shield Advanced subscription",
134 });
135 }
136 }
137
138 // 3. SYNC auto-renew — observed ↔ desired; AWS only accepts the
139 // change within 30 days of the period end, so skip the call on
140 // a no-op.
141 const desiredAutoRenew = news.autoRenew ?? "ENABLED";
142 if (subscription.AutoRenew !== desiredAutoRenew) {
143 yield* shield.updateSubscription({ AutoRenew: desiredAutoRenew });
144 const refreshed = yield* shield
145 .describeSubscription({})
146 .pipe(Effect.map((r) => r.Subscription));
147 subscription = refreshed ?? subscription;
148 }
149
150 // 4. RETURN fresh attributes.
151 if (subscription.SubscriptionArn !== undefined) {
152 yield* session.note(subscription.SubscriptionArn);
153 }
154 return buildAttrs(subscription);
155 }),
156
157 delete: Effect.fn(function* () {
158 // AWS refuses to cancel a Shield Advanced subscription before the
159 // 1-year commitment ends (LockedSubscriptionException). Warn and
160 // leave it in place rather than wedging the destroy.
161 yield* shield.deleteSubscription({}).pipe(
162 Effect.catchTag(
163 ["SubscriptionNotFound", "ResourceNotFoundException"],
164 () => Effect.void,
165 ),
166 Effect.catchTag("LockedSubscriptionException", (error) =>
167 Effect.logWarning(
168 "Shield Advanced subscription is locked for its 1-year commitment and cannot be cancelled yet; leaving it in place.",
169 error,
170 ),
171 ),
172 );
173 }),
174 };
175 }),
176 );