@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 359 lines 12 KB
Raw
1 import * as resourcemanager from "@distilled.cloud/gcp/cloudresourcemanager_v3";
2 import * as cloudsupport from "@distilled.cloud/gcp/cloudsupport_v2";
3 import * as pubsub from "@distilled.cloud/gcp/pubsub_v1";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import { tagRecord } from "alchemy/Tags";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import { createInternalLabels, hasAlchemyLabels, sanitizeLabelValue } from "../Labels.ts";
12
13 export const COLLECTION = "supportEventSubscriptions";
14 export const MAX_TOPIC_ID_LENGTH = 255;
15 export const PUBLISHER_ROLE = "roles/pubsub.publisher";
16 export const CLOUD_SUPPORT_EVENTS_MEMBER =
17 "serviceAccount:cloud-support-apievents@system.gserviceaccount.com";
18
19 export class OrganizationRequired extends Data.TaggedError(
20 "GCP.CloudSupport.OrganizationRequired",
21 )<{
22 project: string;
23 }> {}
24
25 export const lastSegment = (value: string) => {
26 const trimmed = value.replace(/\/+$/, "");
27 const parts = trimmed.split("/");
28 return parts[parts.length - 1] || trimmed;
29 };
30
31 export const organizationParent = (value: string) =>
32 value.startsWith("organizations/") ? value : `organizations/${lastSegment(value)}`;
33
34 export const parentOfName = (name: string) => {
35 const parts = name.split("/").filter((part) => part.length > 0);
36 const index = parts.lastIndexOf(COLLECTION);
37 if (index <= 0) return "";
38 return parts.slice(0, index).join("/");
39 };
40
41 export const subscriptionIdOf = (name: string) => lastSegment(name);
42
43 export const toSubscriptionName = (parent: string, value: string) => {
44 if (value.length === 0) return "";
45 if (value.includes(`/${COLLECTION}/`)) return value;
46 if (parent.length === 0) return value;
47 return `${parent}/${COLLECTION}/${lastSegment(value)}`;
48 };
49
50 export const sameText = (left: string | undefined, right: string | undefined) =>
51 (left ?? "") === (right ?? "");
52
53 export const isDeleted = (subscription: cloudsupport.SupportEventSubscription | undefined) =>
54 subscription?.state === "DELETED";
55
56 export const expandTopic = (value: string, project: string) => {
57 const trimmed = value.replace(/\/+$/, "");
58 if (trimmed.includes("/topics/")) return trimmed;
59 return `projects/${project}/topics/${lastSegment(trimmed)}`;
60 };
61
62 export const sameTopic = (left: string | undefined, right: string | undefined) => {
63 if (left === undefined || right === undefined) return left === right;
64 return left === right || lastSegment(left) === lastSegment(right);
65 };
66
67 export const rfc1035 = (
68 name: string,
69 fallback = "topic",
70 maxLength = MAX_TOPIC_ID_LENGTH,
71 ): string => {
72 let next = name
73 .toLowerCase()
74 .replace(/[^a-z0-9-]/g, "-")
75 .replace(/-+/g, "-")
76 .replace(/^-+/, "")
77 .replace(/-+$/, "");
78 if (!/^[a-z]/.test(next)) next = `t${next}`;
79 next = next.slice(0, maxLength).replace(/-+$/, "");
80 if (next.length < 3) {
81 next = `${next}${fallback}`.slice(0, maxLength);
82 }
83 if (!/[a-z0-9]$/.test(next)) {
84 next = `${next.slice(0, maxLength - 1)}0`;
85 }
86 return next.slice(0, maxLength);
87 };
88
89 export const toPhysicalId = (
90 id: string,
91 explicit: string | undefined,
92 existing: string | undefined,
93 ) =>
94 Effect.gen(function* () {
95 if (explicit !== undefined && explicit.length > 0) {
96 return rfc1035(explicit);
97 }
98 if (existing !== undefined && existing.length > 0) {
99 return lastSegment(existing);
100 }
101 return rfc1035(
102 yield* createPhysicalName({
103 id,
104 maxLength: MAX_TOPIC_ID_LENGTH,
105 lowercase: true,
106 }),
107 );
108 });
109
110 const emptyList = <A>() => Effect.succeed([] as A[]);
111
112 const parentOfResource = (name: string) =>
113 name.startsWith("projects/")
114 ? resourcemanager.getProjects({ name }).pipe(
115 Effect.map((resource) => resource.parent),
116 Effect.catchTag("NotFound", () => Effect.undefined),
117 )
118 : name.startsWith("folders/")
119 ? resourcemanager.getFolders({ name }).pipe(
120 Effect.map((folder) => folder.parent),
121 Effect.catchTag("NotFound", () => Effect.undefined),
122 )
123 : Effect.undefined;
124
125 export const tryResolveOrganization = () =>
126 Effect.gen(function* () {
127 const env = yield* GcpEnvironment.current;
128 let current: string | undefined = `projects/${env.project}`;
129 for (let i = 0; i < 8; i++) {
130 if (current === undefined) return undefined;
131 if (current.startsWith("organizations/")) return current;
132 current = yield* parentOfResource(current);
133 }
134 return undefined;
135 });
136
137 export const resolveOrganization = (explicit: string | undefined, existing: string | undefined) =>
138 Effect.gen(function* () {
139 if (explicit !== undefined && explicit.length > 0) {
140 return organizationParent(explicit);
141 }
142 if (existing !== undefined && existing.length > 0) {
143 return organizationParent(existing);
144 }
145 const resolved = yield* tryResolveOrganization();
146 if (resolved === undefined) {
147 const env = yield* GcpEnvironment.current;
148 return yield* new OrganizationRequired({ project: env.project });
149 }
150 return resolved;
151 });
152
153 export const listOrganizationParents = () =>
154 Effect.gen(function* () {
155 const resolved = yield* tryResolveOrganization();
156 return resolved === undefined ? [] : [resolved];
157 });
158
159 export const getByName = (name: string) =>
160 name.length === 0
161 ? Effect.undefined
162 : cloudsupport.getOrganizationsSupportEventSubscriptions({ name }).pipe(
163 Effect.catchTag("NotFound", () => Effect.undefined),
164 Effect.map((subscription) => (isDeleted(subscription) ? undefined : subscription)),
165 );
166
167 export const getDeletedByName = (name: string) =>
168 name.length === 0
169 ? Effect.undefined
170 : cloudsupport
171 .getOrganizationsSupportEventSubscriptions({ name })
172 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
173
174 export const getTopic = (name: string) =>
175 name.length === 0
176 ? Effect.undefined
177 : pubsub
178 .getProjectsTopics({ topic: name })
179 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
180
181 export const grantCloudSupportPublisher = (topic: string) =>
182 Effect.gen(function* () {
183 if (topic.length === 0) return;
184 const policy = yield* pubsub.getIamPolicyProjectsTopics({
185 resource: topic,
186 });
187 const bindings = (policy.bindings ?? []).map((binding) => ({
188 ...binding,
189 members: [...(binding.members ?? [])],
190 }));
191 const publisher = bindings.find((binding) => binding.role === PUBLISHER_ROLE);
192 if (publisher?.members?.includes(CLOUD_SUPPORT_EVENTS_MEMBER)) return;
193 if (publisher) {
194 publisher.members = [...(publisher.members ?? []), CLOUD_SUPPORT_EVENTS_MEMBER];
195 } else {
196 bindings.push({
197 role: PUBLISHER_ROLE,
198 members: [CLOUD_SUPPORT_EVENTS_MEMBER],
199 });
200 }
201 yield* pubsub.setIamPolicyProjectsTopics({
202 resource: topic,
203 body: { policy: { ...policy, bindings } },
204 });
205 }).pipe(
206 Effect.retry({
207 while: (error) => error._tag === "Conflict",
208 times: 5,
209 schedule: Schedule.spaced("2 seconds"),
210 }),
211 );
212
213 export const ensureTopic = (name: string, labels: Record<string, string>) =>
214 Effect.gen(function* () {
215 let current = yield* getTopic(name);
216 if (current === undefined) {
217 const created = yield* pubsub
218 .createProjectsTopics({
219 name,
220 body: { labels },
221 })
222 .pipe(Effect.catchTag("Conflict", () => getTopic(name)));
223 current = created ?? undefined;
224 }
225 if (current === undefined) return undefined;
226 const observed = tagRecord(current.labels);
227 const desired = { ...observed, ...labels };
228 const changed = Object.entries(desired).some(([key, value]) => observed[key] !== value);
229 if (changed) {
230 current = yield* pubsub
231 .patchProjectsTopics({
232 name,
233 body: {
234 topic: { name, labels: desired },
235 updateMask: "labels",
236 },
237 })
238 .pipe(Effect.catchTag("Conflict", () => Effect.succeed(current)));
239 }
240 yield* grantCloudSupportPublisher(name);
241 return current;
242 });
243
244 export const deleteManagedTopic = (name: string | undefined) => {
245 if (name === undefined || name.length === 0) return Effect.void;
246 return pubsub
247 .deleteProjectsTopics({ topic: name })
248 .pipe(Effect.catchTag("NotFound", () => Effect.void));
249 };
250
251 export const ownershipLabels = (id: string) =>
252 Effect.gen(function* () {
253 const internal = yield* createInternalLabels(id);
254 return {
255 ...internal,
256 "alchemy-cloudsupport": sanitizeLabelValue("subscription"),
257 };
258 });
259
260 export const hasOwnershipLabels = (labels: Record<string, string | undefined> | null | undefined) =>
261 Object.keys(labels ?? {}).some(
262 (key) => key.startsWith("alchemy-cloudsupport") || key.startsWith("alchemy-"),
263 );
264
265 export const ownedByTopicLabels = (
266 id: string,
267 labels: Record<string, string | undefined> | null | undefined,
268 ) =>
269 Effect.gen(function* () {
270 if (!hasOwnershipLabels(labels)) return false;
271 return yield* hasAlchemyLabels(id, tagRecord(labels));
272 });
273
274 export const listSubscriptions = (
275 parent: string,
276 options?: { showDeleted?: boolean; filter?: string },
277 ) =>
278 parent.length === 0
279 ? emptyList<cloudsupport.SupportEventSubscription>()
280 : cloudsupport.listOrganizationsSupportEventSubscriptions
281 .pages({
282 parent,
283 pageSize: 200,
284 showDeleted: options?.showDeleted,
285 filter: options?.filter,
286 })
287 .pipe(
288 Stream.flatMap((page) => Stream.fromIterable(page.supportEventSubscriptions ?? [])),
289 Stream.runCollect,
290 Effect.map((chunk) => Array.from(chunk)),
291 Effect.catchTag("NotFound", () => emptyList<cloudsupport.SupportEventSubscription>()),
292 );
293
294 export const listOwnedSubscriptions = (parent: string) =>
295 Effect.gen(function* () {
296 const subscriptions = yield* listSubscriptions(parent);
297 const owned: cloudsupport.SupportEventSubscription[] = [];
298 for (const subscription of subscriptions) {
299 if (isDeleted(subscription)) continue;
300 const topic = subscription.pubSubTopic;
301 if (topic === undefined || topic.length === 0) continue;
302 const observed = yield* getTopic(topic);
303 if (hasOwnershipLabels(observed?.labels)) {
304 owned.push(subscription);
305 }
306 }
307 return owned;
308 });
309
310 export const findOwnedSubscription = (
311 parent: string,
312 id: string,
313 name: string | undefined,
314 topicName: string | undefined,
315 ) =>
316 Effect.gen(function* () {
317 const existing = yield* getByName(name ?? "");
318 if (existing !== undefined) return existing;
319 const deleted = yield* getDeletedByName(name ?? "");
320 const listed = yield* listSubscriptions(parent, {
321 showDeleted: true,
322 filter:
323 topicName !== undefined && topicName.length > 0
324 ? `pub_sub_topic="${topicName}"`
325 : undefined,
326 });
327 const candidates = [...(deleted !== undefined ? [deleted] : []), ...listed];
328 const seen = new Set<string>();
329 for (const subscription of candidates) {
330 const key = subscription.name ?? "";
331 if (key.length > 0) {
332 if (seen.has(key)) continue;
333 seen.add(key);
334 }
335 if (name !== undefined && name.length > 0 && subscription.name === name) {
336 return subscription;
337 }
338 if (topicName !== undefined && sameTopic(subscription.pubSubTopic, topicName)) {
339 const topic = yield* getTopic(subscription.pubSubTopic ?? "");
340 if (yield* ownedByTopicLabels(id, topic?.labels)) {
341 return subscription;
342 }
343 }
344 }
345 const all = yield* listSubscriptions(parent, { showDeleted: true });
346 for (const subscription of all) {
347 const topic = yield* getTopic(subscription.pubSubTopic ?? "");
348 if (yield* ownedByTopicLabels(id, topic?.labels)) {
349 return subscription;
350 }
351 }
352 return undefined;
353 });
354
355 export const undeleteSubscription = (name: string) =>
356 cloudsupport.undeleteOrganizationsSupportEventSubscriptions({ name, body: {} }).pipe(
357 // Already live or already gone: observe instead.
358 Effect.catchTag(["NotFound", "Conflict"], () => getDeletedByName(name)),
359 );