@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 363 lines 12.3 KB
Raw
1 import * as pubsublite from "@distilled.cloud/gcp/pubsublite_v1";
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 * as Effect from "effect/Effect";
7 import { GcpEnvironment } from "../Environment.ts";
8 import type { Providers } from "../Providers.ts";
9 import {
10 DEFAULT_ZONE,
11 ResourceNotResolved,
12 expandName,
13 fieldMask,
14 getSubscription,
15 hasOwnershipMarker,
16 ignoreMissing,
17 jsonEqual,
18 lastSegment,
19 listOwnedSubscriptions,
20 normalizeLocation,
21 ownedByAlchemy,
22 parentOf,
23 parseName,
24 replaceOnIdentity,
25 resourceName,
26 retryInUse,
27 sameRef,
28 sameText,
29 toResourceId,
30 waitUntilGone,
31 } from "./internal.ts";
32
33 export type SubscriptionDeliveryConfig = {
34 /**
35 * When messages become available to subscribers.
36 * `DELIVER_IMMEDIATELY` or `DELIVER_AFTER_STORED`.
37 */
38 deliveryRequirement?: pubsublite.DeliveryConfigDeliveryRequirementEnum | (string & {});
39 };
40
41 export type SubscriptionPubSubConfig = {
42 /**
43 * Destination Pub/Sub topic
44 * (`projects/{project}/topics/{topic}`).
45 */
46 topic?: string;
47 };
48
49 export type SubscriptionExportConfig = {
50 /**
51 * Desired export state. Only `ACTIVE` and `PAUSED` are settable.
52 */
53 desiredState?: pubsublite.ExportConfigDesiredStateEnum | (string & {});
54 /**
55 * Optional Pub/Sub Lite topic that receives messages that cannot be
56 * exported. Must be in the same project and location.
57 */
58 deadLetterTopic?: string;
59 /**
60 * Export messages to a Pub/Sub topic. User subscriber clients must
61 * not connect to an export subscription.
62 */
63 pubsubConfig?: SubscriptionPubSubConfig;
64 };
65
66 export type AdminSubscriptionProps = {
67 /**
68 * Subscription id (the `{subscription}` segment of
69 * `projects/{project}/locations/{location}/subscriptions/{subscription}`).
70 * If omitted, a unique name is generated from the stack, stage, and
71 * logical id. Pub/Sub Lite has no labels field, so Alchemy stamps
72 * ownership into a `+alc.{stack}.{stage}.{id}` suffix. Immutable —
73 * changing it replaces the subscription.
74 */
75 subscriptionId?: string;
76 /**
77 * Zone or region. Must match the topic. If omitted, inferred from
78 * `topic` when it is a full resource name, otherwise `us-central1-a`.
79 * Immutable — changing it replaces the subscription.
80 */
81 location?: string;
82 /**
83 * Topic this subscription reads from. Accepts a full resource name or
84 * a topic id. Immutable — changing it replaces the subscription.
85 */
86 topic: string;
87 /**
88 * Message delivery settings.
89 */
90 deliveryConfig?: SubscriptionDeliveryConfig;
91 /**
92 * Optional export that writes messages to a Pub/Sub topic. User
93 * subscribers must not attach to an export subscription.
94 */
95 exportConfig?: SubscriptionExportConfig;
96 /**
97 * When true, the new subscription only receives messages published
98 * after it is created. Create-only.
99 * @default false
100 */
101 skipBacklog?: boolean;
102 };
103
104 export type AdminSubscription = Resource<
105 "GCP.PubSubLite.AdminSubscription",
106 AdminSubscriptionProps,
107 {
108 /** Full resource name `projects/{project}/locations/{location}/subscriptions/{subscription}`. */
109 name: string;
110 /** Subscription id (last path segment, including the Alchemy ownership suffix). */
111 subscriptionId: string;
112 /** Project id. */
113 project: string;
114 /** Zone or region id. */
115 location: string;
116 /** Topic this subscription is attached to. */
117 topic: string | undefined;
118 /** Delivery settings currently applied. */
119 deliveryConfig: pubsublite.DeliveryConfig | undefined;
120 /** Export configuration currently applied. */
121 exportConfig: pubsublite.ExportConfig | undefined;
122 },
123 never,
124 Providers
125 >;
126
127 /**
128 * A Pub/Sub Lite subscription — a named consumer of a Lite topic.
129 *
130 * Pub/Sub Lite subscriptions have no labels. Alchemy stamps
131 * `alchemy-stack` / `alchemy-stage` / `alchemy-id` into the
132 * subscription id so `list` / `pnpm nuke:gcp` can find them.
133 * `subscriptionId`, `location`, and `topic` replace the subscription.
134 * Delivery and export settings update in place. `skipBacklog` is
135 * create-only.
136 *
137 * ### Creating a Subscription
138 * **Example:** Pull subscription on a topic
139 * ```typescript
140 * const topic = yield* GCP.PubSubLite.AdminTopic("Events", {});
141 * const subscription = yield* GCP.PubSubLite.AdminSubscription("Inbox", {
142 * topic: topic.name,
143 * });
144 * ```
145 *
146 * **Example:** Deliver after stored
147 * ```typescript
148 * const subscription = yield* GCP.PubSubLite.AdminSubscription("Inbox", {
149 * topic: topic.name,
150 * deliveryConfig: { deliveryRequirement: "DELIVER_AFTER_STORED" },
151 * });
152 * ```
153 *
154 * ### Exporting to Pub/Sub
155 * **Example:** Export subscription
156 * ```typescript
157 * const lite = yield* GCP.PubSubLite.AdminTopic("Events", {});
158 * const classic = yield* GCP.PubSub.Topic("Mirror", {});
159 * const exported = yield* GCP.PubSubLite.AdminSubscription("Export", {
160 * topic: lite.name,
161 * exportConfig: {
162 * desiredState: "ACTIVE",
163 * pubsubConfig: { topic: classic.name },
164 * },
165 * });
166 * ```
167 *
168 * @resource
169 * @category PubSubLite
170 */
171 export const AdminSubscription = Resource<AdminSubscription>("GCP.PubSubLite.AdminSubscription");
172
173 const COLLECTION = "subscriptions";
174 const TOPIC_COLLECTION = "topics";
175
176 const locationOfTopic = (topic: string, fallback: string) => {
177 if (!topic.includes("/locations/")) return fallback;
178 return parseName(topic, TOPIC_COLLECTION).location || fallback;
179 };
180
181 const desiredDelivery = (news: AdminSubscriptionProps): pubsublite.DeliveryConfig | undefined => {
182 if (news.deliveryConfig === undefined) return undefined;
183 return {
184 deliveryRequirement: news.deliveryConfig.deliveryRequirement,
185 };
186 };
187
188 const desiredExport = (
189 news: AdminSubscriptionProps,
190 project: string,
191 location: string,
192 ): pubsublite.ExportConfig | undefined => {
193 if (news.exportConfig === undefined) return undefined;
194 const deadLetter =
195 news.exportConfig.deadLetterTopic !== undefined && news.exportConfig.deadLetterTopic.length > 0
196 ? expandName(news.exportConfig.deadLetterTopic, project, location, TOPIC_COLLECTION)
197 : news.exportConfig.deadLetterTopic;
198 const pubsubTopic = news.exportConfig.pubsubConfig?.topic;
199 return {
200 desiredState: news.exportConfig.desiredState,
201 deadLetterTopic: deadLetter,
202 pubsubConfig:
203 pubsubTopic === undefined
204 ? news.exportConfig.pubsubConfig
205 : {
206 topic: pubsubTopic.startsWith("projects/")
207 ? pubsubTopic
208 : `projects/${project}/topics/${lastSegment(pubsubTopic)}`,
209 },
210 };
211 };
212
213 const toAttrs = (
214 subscription: pubsublite.Subscription,
215 project: string,
216 ): AdminSubscription["Attributes"] => {
217 const name = subscription.name ?? "";
218 const parsed = parseName(name, COLLECTION);
219 return {
220 name,
221 subscriptionId: parsed.id,
222 project: parsed.project || project,
223 location: parsed.location || DEFAULT_ZONE,
224 topic: subscription.topic,
225 deliveryConfig: subscription.deliveryConfig,
226 exportConfig: subscription.exportConfig,
227 };
228 };
229
230 export const AdminSubscriptionProvider = () =>
231 Provider.succeed(AdminSubscription, {
232 stables: ["name", "subscriptionId", "project", "location", "topic"],
233
234 diff: Effect.fn(function* ({ news, olds, output }) {
235 if (!isResolved(news)) return undefined;
236 const previousTopic = olds?.topic ?? output?.topic;
237 const topicChanged = previousTopic !== undefined && !sameRef(previousTopic, news.topic);
238 const inferred = locationOfTopic(
239 news.topic,
240 normalizeLocation(news.location ?? olds?.location ?? output?.location, DEFAULT_ZONE),
241 );
242 return replaceOnIdentity({
243 previousId: olds?.subscriptionId ?? output?.subscriptionId,
244 nextId: news.subscriptionId ?? olds?.subscriptionId ?? output?.subscriptionId,
245 previousLocation: normalizeLocation(olds?.location ?? output?.location, DEFAULT_ZONE),
246 nextLocation: normalizeLocation(news.location ?? inferred, DEFAULT_ZONE),
247 extra: topicChanged,
248 });
249 }),
250
251 read: Effect.fn(function* ({ id, olds, output }) {
252 const env = yield* GcpEnvironment.current;
253 const subscriptionId = yield* toResourceId(id, olds?.subscriptionId, output?.subscriptionId);
254 const location = normalizeLocation(
255 olds?.location ??
256 output?.location ??
257 (olds?.topic ? locationOfTopic(olds.topic, DEFAULT_ZONE) : undefined),
258 DEFAULT_ZONE,
259 );
260 const name = output?.name ?? resourceName(env.project, location, COLLECTION, subscriptionId);
261 const existing = yield* getSubscription(name);
262 if (existing === undefined) return undefined;
263 const attrs = toAttrs(existing, env.project);
264 const owned = yield* ownedByAlchemy(id, attrs.subscriptionId);
265 if (owned) return attrs;
266 return hasOwnershipMarker(attrs.subscriptionId) ? undefined : Unowned(attrs);
267 }),
268
269 list: () =>
270 Effect.gen(function* () {
271 const env = yield* GcpEnvironment.current;
272 const items = yield* listOwnedSubscriptions();
273 return items.map((item) => toAttrs(item, env.project));
274 }),
275
276 reconcile: Effect.fn(function* ({ id, news, output }) {
277 const env = yield* GcpEnvironment.current;
278 const subscriptionId = yield* toResourceId(id, news.subscriptionId, output?.subscriptionId);
279 const topicName = expandName(
280 news.topic,
281 env.project,
282 normalizeLocation(
283 news.location ?? output?.location ?? locationOfTopic(news.topic, DEFAULT_ZONE),
284 DEFAULT_ZONE,
285 ),
286 TOPIC_COLLECTION,
287 );
288 const location = normalizeLocation(
289 news.location ?? output?.location ?? locationOfTopic(topicName, DEFAULT_ZONE),
290 DEFAULT_ZONE,
291 );
292 const name = resourceName(env.project, location, COLLECTION, subscriptionId);
293 const deliveryConfig = desiredDelivery(news);
294 const exportConfig = desiredExport(news, env.project, location);
295
296 let current = yield* getSubscription(output?.name ?? name);
297
298 if (current === undefined) {
299 const body: pubsublite.Subscription = {
300 topic: topicName,
301 };
302 if (deliveryConfig !== undefined) body.deliveryConfig = deliveryConfig;
303 if (exportConfig !== undefined) body.exportConfig = exportConfig;
304 const created = yield* pubsublite
305 .createAdminProjectsLocationsSubscriptions({
306 parent: parentOf(env.project, location),
307 subscriptionId,
308 skipBacklog: news.skipBacklog,
309 body,
310 })
311 .pipe(Effect.catchTag("Conflict", () => getSubscription(name)));
312 current = created ?? undefined;
313 }
314
315 if (current === undefined) {
316 return yield* new ResourceNotResolved({ resourceName: name });
317 }
318
319 const observedName = current.name ?? name;
320 const deliveryChanged =
321 deliveryConfig !== undefined &&
322 !sameText(current.deliveryConfig?.deliveryRequirement, deliveryConfig.deliveryRequirement);
323 const exportChanged =
324 exportConfig !== undefined &&
325 !jsonEqual(
326 {
327 desiredState: exportConfig.desiredState ?? "",
328 deadLetterTopic: exportConfig.deadLetterTopic ?? "",
329 pubsubTopic: exportConfig.pubsubConfig?.topic ?? "",
330 },
331 {
332 desiredState: current.exportConfig?.desiredState ?? "",
333 deadLetterTopic: current.exportConfig?.deadLetterTopic ?? "",
334 pubsubTopic: current.exportConfig?.pubsubConfig?.topic ?? "",
335 },
336 );
337 const mask = fieldMask([
338 deliveryChanged && "deliveryConfig",
339 exportChanged && "exportConfig",
340 ]);
341 if (mask.length > 0) {
342 const body: pubsublite.Subscription = { name: observedName };
343 if (deliveryConfig !== undefined) body.deliveryConfig = deliveryConfig;
344 if (exportConfig !== undefined) body.exportConfig = exportConfig;
345 current = yield* pubsublite.patchAdminProjectsLocationsSubscriptions({
346 name: observedName,
347 updateMask: mask,
348 body,
349 });
350 }
351
352 return toAttrs(current, env.project);
353 }),
354
355 delete: Effect.fn(function* ({ output }) {
356 yield* pubsublite
357 .deleteAdminProjectsLocationsSubscriptions({
358 name: output.name,
359 })
360 .pipe(ignoreMissing, retryInUse);
361 yield* waitUntilGone(getSubscription(output.name));
362 }),
363 });