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

main
ts 249 lines 9.13 KB
Raw
1 import * as ivs from "@distilled.cloud/aws/ivs";
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 * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import type { Providers } from "../Providers.ts";
13 import { retryWhileThrottled, syncIvsTags, toTagRecord } from "./internal.ts";
14
15 export interface PlaybackKeyPairProps {
16 /**
17 * The PEM-encoded ECDSA P-384 public key to import. The corresponding
18 * private key is held by the caller and used to sign viewer playback
19 * authorization tokens for private channels. Changing the key material
20 * replaces the key pair (the fingerprint and ARN change).
21 */
22 publicKeyMaterial: string;
23 /**
24 * Name of the playback key pair. If omitted, a deterministic physical
25 * name is generated. Key pairs have no update operation, so changing
26 * the name replaces the key pair.
27 */
28 playbackKeyPairName?: string;
29 /**
30 * Tags to apply to the key pair. Merged with internal Alchemy tags.
31 */
32 tags?: Record<string, string>;
33 }
34
35 export interface PlaybackKeyPair extends Resource<
36 "AWS.IVS.PlaybackKeyPair",
37 PlaybackKeyPairProps,
38 {
39 /**
40 * The key pair's physical name.
41 */
42 playbackKeyPairName: string;
43 /**
44 * ARN of the imported playback key pair.
45 */
46 playbackKeyPairArn: string;
47 /**
48 * Fingerprint of the imported public key.
49 */
50 fingerprint: string | undefined;
51 },
52 never,
53 Providers
54 > {}
55
56 /**
57 * An Amazon IVS playback key pair for private channels.
58 *
59 * Import the public half of an ECDSA P-384 key pair; sign viewer playback
60 * authorization tokens with the private half. Channels created with
61 * `authorized: true` require viewers to present a token signed by an
62 * imported key pair.
63 * ### Importing a Key Pair
64 * **Example:** Private Channel Playback Authorization
65 * ```typescript
66 * import * as IVS from "@alchemy.run/aws/IVS";
67 *
68 * const keyPair = yield* IVS.PlaybackKeyPair("ViewerAuth", {
69 * publicKeyMaterial: PUBLIC_KEY_PEM, // ECDSA P-384 public key
70 * });
71 * const channel = yield* IVS.Channel("PrivateChannel", {
72 * authorized: true,
73 * });
74 * ```
75 *
76 * @resource
77 */
78 export const PlaybackKeyPair = Resource<PlaybackKeyPair>("AWS.IVS.PlaybackKeyPair");
79
80 /**
81 * Raised when the IVS API returns a playback key pair missing its ARN or
82 * name.
83 */
84 export class IvsPlaybackKeyPairIncomplete extends Data.TaggedError("IvsPlaybackKeyPairIncomplete")<{
85 message: string;
86 }> {}
87
88 /**
89 * DeletePlaybackKeyPair intermittently returns InternalServerException even
90 * though a subsequent attempt succeeds. Retry only that typed transient error
91 * on a bounded schedule; other delete errors still fail immediately.
92 */
93 const retryDeleteInternalServer = <A, E extends { readonly _tag: string }, R>(
94 self: Effect.Effect<A, E, R>,
95 ): Effect.Effect<A, E, R> =>
96 Effect.retry(self, {
97 while: (error) => error._tag === "InternalServerException",
98 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
99 });
100
101 export const PlaybackKeyPairProvider = () =>
102 Provider.effect(
103 PlaybackKeyPair,
104 Effect.gen(function* () {
105 const toName = (id: string, props: { playbackKeyPairName?: string | undefined }) =>
106 props.playbackKeyPairName
107 ? Effect.succeed(props.playbackKeyPairName)
108 : createPhysicalName({ id, maxLength: 128 });
109
110 const toAttrs = Effect.fn(function* (keyPair: ivs.PlaybackKeyPair) {
111 if (!keyPair.arn || !keyPair.name) {
112 return yield* new IvsPlaybackKeyPairIncomplete({
113 message: "IVS playback key pair is missing its ARN or name",
114 });
115 }
116 return {
117 playbackKeyPairName: keyPair.name,
118 playbackKeyPairArn: keyPair.arn,
119 fingerprint: keyPair.fingerprint,
120 };
121 });
122
123 const getByArn = Effect.fn(function* (arn: string) {
124 const response = yield* ivs.getPlaybackKeyPair({ arn }).pipe(
125 retryWhileThrottled,
126 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
127 );
128 return response?.keyPair;
129 });
130
131 /**
132 * ListPlaybackKeyPairs has no name filter — enumerate and match
133 * exactly (key pair names are unique per account/region).
134 */
135 const findByName = Effect.fn(function* (name: string) {
136 const summaries = yield* ivs.listPlaybackKeyPairs.pages({}).pipe(
137 Stream.runCollect,
138 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.keyPairs)),
139 retryWhileThrottled,
140 );
141 const match = summaries.find((s) => s.name === name && s.arn);
142 return match?.arn ? yield* getByArn(match.arn) : undefined;
143 });
144
145 return {
146 stables: ["playbackKeyPairName", "playbackKeyPairArn", "fingerprint"],
147
148 read: Effect.fn(function* ({ id, olds, output }) {
149 const keyPair = output?.playbackKeyPairArn
150 ? yield* getByArn(output.playbackKeyPairArn)
151 : yield* findByName(yield* toName(id, olds ?? {}));
152 if (keyPair === undefined) return undefined;
153 const attrs = yield* toAttrs(keyPair);
154 return (yield* hasAlchemyTags(id, toTagRecord(keyPair.tags))) ? attrs : Unowned(attrs);
155 }),
156
157 diff: Effect.fn(function* ({ id, news, olds }) {
158 if (!isResolved(news)) return undefined;
159 // There is no UpdatePlaybackKeyPair — both the key material and
160 // the name are immutable. Key pair names are unique, so replacing
161 // the material under the SAME name must delete the old key pair
162 // first (create-before-delete would find the old one by name and
163 // wrongly adopt it).
164 if (olds.publicKeyMaterial !== news.publicKeyMaterial) {
165 const sameName = (yield* toName(id, olds)) === (yield* toName(id, news));
166 return { action: "replace", deleteFirst: sameName } as const;
167 }
168 if ((yield* toName(id, olds)) !== (yield* toName(id, news))) {
169 return { action: "replace" } as const;
170 }
171 }),
172
173 reconcile: Effect.fn(function* ({ id, news, output, session }) {
174 const name = yield* toName(id, news);
175 const internalTags = yield* createInternalTags(id);
176 const desiredTags = { ...internalTags, ...news.tags };
177
178 // 1. Observe.
179 let observed = output?.playbackKeyPairArn
180 ? yield* getByArn(output.playbackKeyPairArn)
181 : yield* findByName(name);
182
183 // 2. Ensure — import if missing. A ConflictException means the
184 // name already exists (a race with a peer reconciler or a
185 // state-persistence failure): adopt it by name.
186 if (observed === undefined) {
187 observed = yield* ivs
188 .importPlaybackKeyPair({
189 publicKeyMaterial: news.publicKeyMaterial,
190 name,
191 tags: desiredTags,
192 })
193 .pipe(
194 retryWhileThrottled,
195 Effect.map((r) => r.keyPair),
196 Effect.catchTag("ConflictException", () => findByName(name)),
197 );
198 }
199 const arn = observed?.arn;
200 if (observed === undefined || arn === undefined) {
201 return yield* new IvsPlaybackKeyPairIncomplete({
202 message: `IVS playback key pair '${name}' could not be imported or found`,
203 });
204 }
205
206 // 3. Sync tags — the only mutable aspect.
207 yield* syncIvsTags(arn, desiredTags);
208
209 // 4. Return fresh attributes.
210 const final = yield* getByArn(arn);
211 if (final === undefined) {
212 return yield* new IvsPlaybackKeyPairIncomplete({
213 message: `IVS playback key pair '${arn}' vanished during reconcile`,
214 });
215 }
216 yield* session.note(arn);
217 return yield* toAttrs(final);
218 }),
219
220 delete: Effect.fn(function* ({ output }) {
221 yield* ivs.deletePlaybackKeyPair({ arn: output.playbackKeyPairArn }).pipe(
222 retryWhileThrottled,
223 retryDeleteInternalServer,
224 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
225 );
226 }),
227
228 list: () =>
229 ivs.listPlaybackKeyPairs.pages({}).pipe(
230 Stream.runCollect,
231 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.keyPairs)),
232 Effect.flatMap(
233 Effect.forEach(
234 (summary) =>
235 summary.arn === undefined
236 ? Effect.undefined
237 : getByArn(summary.arn).pipe(
238 Effect.flatMap((keyPair) =>
239 keyPair === undefined ? Effect.undefined : toAttrs(keyPair),
240 ),
241 ),
242 { concurrency: 5 },
243 ),
244 ),
245 Effect.map((items) => items.filter((item) => item !== undefined)),
246 ),
247 };
248 }),
249 );