@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 228 lines 8.5 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 * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import type * as Redacted from "effect/Redacted";
10 import { toRedactedString } from "../IAM/common.ts";
11 import type { Providers } from "../Providers.ts";
12 import { retryWhileThrottled, syncIvsTags, toTagRecord } from "./internal.ts";
13
14 export interface StreamKeyProps {
15 /**
16 * ARN of the channel the stream key authorizes broadcasts to.
17 * Changing the channel replaces the stream key.
18 */
19 channelArn: string;
20 /**
21 * Tags to apply to the stream key. Merged with internal Alchemy tags.
22 */
23 tags?: Record<string, string>;
24 }
25
26 export interface StreamKey extends Resource<
27 "AWS.IVS.StreamKey",
28 StreamKeyProps,
29 {
30 /**
31 * ARN of the stream key.
32 */
33 streamKeyArn: string;
34 /**
35 * ARN of the channel the stream key authorizes broadcasts to.
36 */
37 channelArn: string;
38 /**
39 * The secret stream key value used by broadcast software to
40 * authenticate against the channel's ingest endpoint.
41 */
42 value: Redacted.Redacted<string> | undefined;
43 },
44 never,
45 Providers
46 > {}
47
48 /**
49 * An Amazon IVS stream key — the secret credential broadcast software
50 * uses to authenticate against a channel's ingest endpoint.
51 *
52 * IVS allows at most one stream key per channel, and `CreateChannel`
53 * provisions one automatically. This resource therefore *manages the
54 * channel's stream key*: if the channel already has its auto-created key,
55 * the resource takes ownership of it (tagging it with Alchemy's internal
56 * tags) instead of failing the per-channel quota.
57 * ### Creating Stream Keys
58 * **Example:** Stream Key for a Channel
59 * ```typescript
60 * import * as IVS from "@alchemy.run/aws/IVS";
61 *
62 * const channel = yield* IVS.Channel("LiveChannel");
63 * const streamKey = yield* IVS.StreamKey("LiveKey", {
64 * channelArn: channel.channelArn,
65 * });
66 * ```
67 *
68 * @resource
69 */
70 export const StreamKey = Resource<StreamKey>("AWS.IVS.StreamKey");
71
72 /**
73 * Raised when the IVS API returns a stream key missing its ARN or channel
74 * ARN.
75 */
76 export class IvsStreamKeyIncomplete extends Data.TaggedError("IvsStreamKeyIncomplete")<{
77 message: string;
78 }> {}
79
80 export const StreamKeyProvider = () =>
81 Provider.effect(
82 StreamKey,
83 Effect.gen(function* () {
84 const toAttrs = Effect.fn(function* (streamKey: ivs.StreamKey) {
85 if (!streamKey.arn || !streamKey.channelArn) {
86 return yield* new IvsStreamKeyIncomplete({
87 message: "IVS stream key is missing its ARN or channel ARN",
88 });
89 }
90 return {
91 streamKeyArn: streamKey.arn,
92 channelArn: streamKey.channelArn,
93 value: toRedactedString(streamKey.value),
94 };
95 });
96
97 const getByArn = Effect.fn(function* (arn: string) {
98 const response = yield* ivs.getStreamKey({ arn }).pipe(
99 retryWhileThrottled,
100 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
101 );
102 return response?.streamKey;
103 });
104
105 /**
106 * A channel has at most one stream key, so "the channel's stream
107 * key" is a well-defined lookup. Tolerates a deleted channel (the
108 * key is gone with it).
109 */
110 const findByChannel = Effect.fn(function* (channelArn: string) {
111 const page = yield* ivs.listStreamKeys({ channelArn }).pipe(
112 retryWhileThrottled,
113 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
114 );
115 const arn = page?.streamKeys.find((s) => s.arn !== undefined)?.arn;
116 return arn === undefined ? undefined : yield* getByArn(arn);
117 });
118
119 return {
120 stables: ["streamKeyArn", "channelArn"],
121
122 read: Effect.fn(function* ({ id, olds, output }) {
123 const streamKey = output?.streamKeyArn
124 ? yield* getByArn(output.streamKeyArn)
125 : olds?.channelArn
126 ? yield* findByChannel(olds.channelArn)
127 : undefined;
128 if (streamKey === undefined) return undefined;
129 const attrs = yield* toAttrs(streamKey);
130 const tags = toTagRecord(streamKey.tags);
131 if (yield* hasAlchemyTags(id, tags)) return attrs;
132 // CreateChannel provisions an untagged default key before the
133 // engine can resolve this resource's channelArn. It belongs to the
134 // channel lifecycle, so an owned channel may claim its default key.
135 // Keys carrying user or ownership tags still require explicit adoption.
136 if (
137 output === undefined &&
138 olds?.channelArn !== undefined &&
139 Object.keys(tags).length === 0
140 ) {
141 const response = yield* ivs.getChannel({ arn: olds.channelArn }).pipe(
142 retryWhileThrottled,
143 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
144 );
145 const channelTags = toTagRecord(response?.channel?.tags);
146 const channelId = channelTags["alchemy::id"];
147 if (channelId !== undefined && (yield* hasAlchemyTags(channelId, channelTags))) {
148 return attrs;
149 }
150 }
151 return Unowned(attrs);
152 }),
153
154 diff: Effect.fn(function* ({ news, olds }) {
155 if (!isResolved(news)) return undefined;
156 // A stream key is bound to its channel at create time — moving
157 // it to another channel requires a replacement.
158 if (olds.channelArn !== news.channelArn) {
159 return { action: "replace" } as const;
160 }
161 }),
162
163 reconcile: Effect.fn(function* ({ id, news, output, session }) {
164 const internalTags = yield* createInternalTags(id);
165 const desiredTags = { ...internalTags, ...news.tags };
166
167 // 1. Observe — prefer the cached ARN; fall back to the channel's
168 // (at most one) existing key.
169 let observed = output?.streamKeyArn
170 ? yield* getByArn(output.streamKeyArn)
171 : yield* findByChannel(news.channelArn);
172 // A cached ARN can belong to a previous channel after a failed
173 // replacement — only trust keys on the desired channel.
174 if (observed !== undefined && observed.channelArn !== news.channelArn) {
175 observed = undefined;
176 }
177
178 // 2. Ensure — create if missing. The per-channel quota is 1 and
179 // CreateChannel auto-provisions a key, so a quota rejection means
180 // the channel already has its key: adopt it (tags are converged
181 // below).
182 if (observed === undefined) {
183 observed = yield* ivs
184 .createStreamKey({ channelArn: news.channelArn, tags: desiredTags })
185 .pipe(
186 retryWhileThrottled,
187 Effect.map((r) => r.streamKey),
188 Effect.catchTag("ServiceQuotaExceededException", () =>
189 findByChannel(news.channelArn),
190 ),
191 );
192 }
193 const arn = observed?.arn;
194 if (observed === undefined || arn === undefined) {
195 return yield* new IvsStreamKeyIncomplete({
196 message: `IVS channel '${news.channelArn}' has no stream key and one could not be created`,
197 });
198 }
199
200 // 3. Sync tags — the only mutable aspect. Diff against OBSERVED
201 // cloud tags so adopting the auto-created key converges.
202 yield* syncIvsTags(arn, desiredTags);
203
204 // 4. Return fresh attributes (GetStreamKey carries the secret
205 // value; the ListStreamKeys summary does not).
206 const final = yield* getByArn(arn);
207 if (final === undefined) {
208 return yield* new IvsStreamKeyIncomplete({
209 message: `IVS stream key '${arn}' vanished during reconcile`,
210 });
211 }
212 yield* session.note(arn);
213 return yield* toAttrs(final);
214 }),
215
216 delete: Effect.fn(function* ({ output }) {
217 yield* ivs.deleteStreamKey({ arn: output.streamKeyArn }).pipe(
218 retryWhileThrottled,
219 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
220 );
221 }),
222
223 // Stream keys are sub-resources keyed by their parent channel —
224 // there is no account-level enumeration to reconcile against.
225 list: () => Effect.succeed([]),
226 };
227 }),
228 );