@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 354 lines 11.5 KB
Raw
1 import * as cloudsupport from "@distilled.cloud/gcp/cloudsupport_v2";
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 Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 COLLECTION,
12 deleteManagedTopic,
13 ensureTopic,
14 expandTopic,
15 findOwnedSubscription,
16 getByName,
17 getDeletedByName,
18 getTopic,
19 isDeleted,
20 lastSegment,
21 listOwnedSubscriptions,
22 listOrganizationParents,
23 organizationParent,
24 ownedByTopicLabels,
25 ownershipLabels,
26 parentOfName,
27 resolveOrganization,
28 sameTopic,
29 subscriptionIdOf,
30 toPhysicalId,
31 toSubscriptionName,
32 undeleteSubscription,
33 } from "./internal.ts";
34
35 export type SupportEventSubscriptionProps = {
36 /**
37 * Parent organization (`organizations/{organization}` or the numeric
38 * id). Defaults to `GOOGLE_ORGANIZATION_ID` or the project's Resource
39 * Manager ancestor. Immutable — changing it replaces the subscription.
40 */
41 organization?: string;
42 /**
43 * Resource name
44 * `organizations/{organization}/supportEventSubscriptions/{subscription}`
45 * or the `{subscription}` id. Server-assigned on create. Immutable —
46 * changing it replaces the subscription.
47 */
48 subscriptionId?: string;
49 /**
50 * Pub/Sub topic that receives Cloud Support events
51 * (`projects/{project}/topics/{topic}` or a topic id). Created with
52 * Alchemy ownership labels when omitted. Updating this value patches
53 * the subscription in place. The topic must live in the same GCP
54 * organization as `organization`.
55 */
56 pubSubTopic?: string;
57 };
58
59 export type SupportEventSubscription = Resource<
60 "GCP.CloudSupport.SupportEventSubscription",
61 SupportEventSubscriptionProps,
62 {
63 /** Full resource name `organizations/{organization}/supportEventSubscriptions/{subscription}`. */
64 name: string;
65 /** Server-assigned subscription id (last path segment). */
66 subscriptionId: string;
67 /** Parent resource `organizations/{organization}`. */
68 parent: string;
69 /** Organization resource name. */
70 organization: string;
71 /** Organization id (last path segment). */
72 organizationId: string;
73 /** Project id used when the subscription was reconciled. */
74 project: string;
75 /** Pub/Sub topic that receives events. */
76 pubSubTopic: string | undefined;
77 /** Server-reported state (`WORKING`, `FAILING`, `DELETED`). */
78 state: string | undefined;
79 /** Reason the subscription is failing, if `state` is `FAILING`. */
80 failureReason: string | undefined;
81 /** RFC3339 creation timestamp. */
82 createTime: string | undefined;
83 /** RFC3339 last-update timestamp. */
84 updateTime: string | undefined;
85 /** RFC3339 soft-delete timestamp. */
86 deleteTime: string | undefined;
87 /** RFC3339 purge timestamp. */
88 purgeTime: string | undefined;
89 /** Whether Alchemy created the Pub/Sub topic. */
90 managedTopic: boolean;
91 },
92 never,
93 Providers
94 >;
95
96 /**
97 * A Cloud Support event subscription that publishes case events to a
98 * Pub/Sub topic.
99 *
100 * Support event subscriptions have no labels field, so Alchemy stamps
101 * ownership onto the destination Pub/Sub topic for `list` / nuke and
102 * grants `roles/pubsub.publisher` to
103 * `cloud-support-apievents@system.gserviceaccount.com`. Organization and
104 * subscription id are identity — changing either replaces the
105 * subscription. The Pub/Sub topic updates in place. Creating a
106 * subscription requires the Cloud Support API and Cloud Customer Care on
107 * the organization.
108 *
109 * ### Creating a Support Event Subscription
110 * **Example:** Generated topic
111 * ```typescript
112 * const sub = yield* GCP.CloudSupport.SupportEventSubscription("Events", {
113 * organization: "organizations/123",
114 * });
115 * ```
116 *
117 * **Example:** Existing Pub/Sub topic
118 * ```typescript
119 * const topic = yield* GCP.PubSub.Topic("SupportEvents", {});
120 * const sub = yield* GCP.CloudSupport.SupportEventSubscription("Events", {
121 * organization: "organizations/123",
122 * pubSubTopic: topic.name,
123 * });
124 * ```
125 *
126 * ### Updating a Support Event Subscription
127 * **Example:** Point at a new topic
128 * ```typescript
129 * // Same logical id as before; only the topic changes.
130 * const sub = yield* GCP.CloudSupport.SupportEventSubscription("Events", {
131 * organization: "organizations/123",
132 * pubSubTopic: otherTopic.name,
133 * });
134 * ```
135 *
136 * @resource
137 * @category CloudSupport
138 */
139 export const SupportEventSubscription = Resource<SupportEventSubscription>(
140 "GCP.CloudSupport.SupportEventSubscription",
141 );
142
143 export class SupportEventSubscriptionNotResolved extends Data.TaggedError(
144 "GCP.CloudSupport.SupportEventSubscriptionNotResolved",
145 )<{
146 resourceName: string;
147 }> {}
148
149 const lookupName = (
150 parent: string,
151 subscriptionId: string | undefined,
152 existingName: string | undefined,
153 ) => {
154 if (existingName !== undefined && existingName.length > 0) {
155 return existingName;
156 }
157 if (subscriptionId !== undefined && subscriptionId.length > 0) {
158 return toSubscriptionName(parent, subscriptionId);
159 }
160 return "";
161 };
162
163 const toAttrs = (
164 subscription: cloudsupport.SupportEventSubscription,
165 project: string,
166 managedTopic: boolean,
167 ) => {
168 const name = subscription.name ?? "";
169 const parent = parentOfName(name);
170 const organization = parent.startsWith("organizations/")
171 ? parent
172 : parent.length > 0
173 ? organizationParent(parent)
174 : "";
175 return {
176 name,
177 subscriptionId: subscriptionIdOf(name),
178 parent: parent || organization,
179 organization,
180 organizationId: lastSegment(organization),
181 project,
182 pubSubTopic: subscription.pubSubTopic,
183 state: subscription.state,
184 failureReason: subscription.failureReason,
185 createTime: subscription.createTime,
186 updateTime: subscription.updateTime,
187 deleteTime: subscription.deleteTime,
188 purgeTime: subscription.purgeTime,
189 managedTopic,
190 };
191 };
192
193 export const SupportEventSubscriptionProvider = () =>
194 Provider.succeed(SupportEventSubscription, {
195 stables: [
196 "name",
197 "subscriptionId",
198 "parent",
199 "organization",
200 "organizationId",
201 "project",
202 "createTime",
203 ],
204
205 diff: Effect.fn(function* ({ news, olds, output }) {
206 if (!isResolved(news)) return undefined;
207 const previousOrg = olds?.organization ?? output?.organization;
208 if (
209 news.organization !== undefined &&
210 previousOrg !== undefined &&
211 organizationParent(news.organization) !== organizationParent(previousOrg)
212 ) {
213 return { action: "replace" as const, deleteFirst: false };
214 }
215 const previousId = olds?.subscriptionId ?? output?.subscriptionId;
216 if (
217 previousId !== undefined &&
218 news.subscriptionId !== undefined &&
219 toSubscriptionName("", news.subscriptionId) !== toSubscriptionName("", previousId) &&
220 news.subscriptionId !== output?.subscriptionId &&
221 news.subscriptionId !== output?.name
222 ) {
223 return { action: "replace" as const, deleteFirst: false };
224 }
225 return undefined;
226 }),
227
228 read: Effect.fn(function* ({ id, olds, output }) {
229 const env = yield* GcpEnvironment.current;
230 const parent = yield* resolveOrganization(
231 olds?.organization ?? output?.organization,
232 output?.parent,
233 );
234 const name = lookupName(parent, olds?.subscriptionId ?? output?.subscriptionId, output?.name);
235 let existing = yield* getByName(name);
236 if (existing === undefined) {
237 existing = yield* findOwnedSubscription(
238 parent,
239 id,
240 name,
241 olds?.pubSubTopic ?? output?.pubSubTopic,
242 );
243 }
244 if (existing === undefined || isDeleted(existing)) return undefined;
245 const topic = yield* getTopic(existing.pubSubTopic ?? "");
246 const attrs = toAttrs(existing, env.project, output?.managedTopic === true);
247 const owned = (yield* ownedByTopicLabels(id, topic?.labels)) || output?.name === attrs.name;
248 return owned ? attrs : Unowned(attrs);
249 }),
250
251 list: () =>
252 Effect.gen(function* () {
253 const env = yield* GcpEnvironment.current;
254 const parents = yield* listOrganizationParents();
255 const pages = yield* Effect.forEach(parents, listOwnedSubscriptions, {
256 concurrency: 2,
257 });
258 return pages.flat().map((subscription) => toAttrs(subscription, env.project, false));
259 }),
260
261 reconcile: Effect.fn(function* ({ id, news, output }) {
262 const env = yield* GcpEnvironment.current;
263 const parent = yield* resolveOrganization(
264 news.organization ?? output?.organization,
265 output?.parent,
266 );
267 const labels = yield* ownershipLabels(id);
268 const managedTopic = news.pubSubTopic === undefined;
269 const topicName = news.pubSubTopic
270 ? expandTopic(news.pubSubTopic, env.project)
271 : expandTopic(
272 output?.pubSubTopic ?? (yield* toPhysicalId(id, undefined, undefined)),
273 env.project,
274 );
275
276 yield* ensureTopic(topicName, labels);
277
278 const lookup = lookupName(
279 parent,
280 news.subscriptionId ?? output?.subscriptionId,
281 output?.name,
282 );
283 let current = yield* findOwnedSubscription(parent, id, lookup, topicName);
284
285 if (isDeleted(current) && current?.name) {
286 current = (yield* undeleteSubscription(current.name)) ?? current;
287 if (isDeleted(current) && current.name) {
288 current = (yield* getByName(current.name)) ?? current;
289 }
290 }
291
292 if (current === undefined || isDeleted(current)) {
293 const created = yield* cloudsupport
294 .createOrganizationsSupportEventSubscriptions({
295 parent,
296 body: {
297 pubSubTopic: topicName,
298 },
299 })
300 .pipe(
301 Effect.catchTag("Conflict", () => findOwnedSubscription(parent, id, lookup, topicName)),
302 );
303 current = created ?? undefined;
304 if (current?.name) {
305 current = (yield* getDeletedByName(current.name)) ?? current;
306 }
307 }
308
309 if (current === undefined || current.name === undefined) {
310 return yield* new SupportEventSubscriptionNotResolved({
311 resourceName: lookup || `${parent}/${COLLECTION}`,
312 });
313 }
314
315 if (isDeleted(current)) {
316 current =
317 (yield* undeleteSubscription(current.name)) ??
318 (yield* getByName(current.name)) ??
319 current;
320 }
321
322 if (current === undefined || current.name === undefined) {
323 return yield* new SupportEventSubscriptionNotResolved({
324 resourceName: lookup || `${parent}/${COLLECTION}`,
325 });
326 }
327
328 const name = current.name;
329 if (!sameTopic(current.pubSubTopic, topicName)) {
330 current = yield* cloudsupport.patchOrganizationsSupportEventSubscriptions({
331 name,
332 updateMask: "pub_sub_topic",
333 body: {
334 pubSubTopic: topicName,
335 },
336 });
337 }
338
339 const fresh = (yield* getDeletedByName(name)) ?? current;
340 return toAttrs(fresh, env.project, managedTopic);
341 }),
342
343 delete: Effect.fn(function* ({ output }) {
344 const name = output.name || toSubscriptionName(output.parent, output.subscriptionId);
345 if (name.length > 0) {
346 yield* cloudsupport
347 .deleteOrganizationsSupportEventSubscriptions({ name })
348 .pipe(Effect.catchTag("NotFound", () => Effect.void));
349 }
350 if (output.managedTopic === true) {
351 yield* deleteManagedTopic(output.pubSubTopic);
352 }
353 }),
354 });