@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 374 lines 12.1 KB
Raw
1 import * as cloudasset from "@distilled.cloud/gcp/cloudasset_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 Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 encodeDescription,
14 grantCloudAssetPublisher,
15 hasOwnershipMarker,
16 lastSegment,
17 listFeeds,
18 NO_OP_EXPRESSION,
19 ownedByAlchemy,
20 parentOf,
21 parseDescription,
22 replaceOn,
23 scopeParent,
24 sameJson,
25 sameStringList,
26 sameText,
27 toPhysicalId,
28 updateMaskOf,
29 } from "./internal.ts";
30
31 export type FeedContentType = cloudasset.FeedContentTypeEnum | (string & {});
32
33 export type FeedCondition = {
34 /**
35 * CEL expression evaluated against a `TemporalAsset` named
36 * `temporal_asset`. Example: `temporal_asset.deleted == true`.
37 */
38 expression?: string;
39 /**
40 * Short title shown in UIs that edit the expression.
41 */
42 title?: string;
43 /**
44 * Longer description of the expression. Feeds have no labels field, so
45 * Alchemy ownership is stored in a `[alchemy …]` prefix here and
46 * stripped from attributes.
47 */
48 description?: string;
49 /**
50 * Source location of the expression for error reporting.
51 */
52 location?: string;
53 };
54
55 export type FeedProps = {
56 /**
57 * Feed id (the `{feed}` segment of
58 * `projects/{project}/feeds/{feed}`). If omitted, a unique RFC1035
59 * name is generated. Immutable — changing it replaces the feed.
60 */
61 feedId?: string;
62 /**
63 * Parent project, folder, or organization
64 * (`projects/{project}`, `folders/{folder}`,
65 * `organizations/{organization}`). Defaults to the current project.
66 * Immutable — changing it replaces the feed.
67 */
68 parent?: string;
69 /**
70 * Full resource names to subscribe to. Specify `assetNames` and/or
71 * `assetTypes`. Example:
72 * `//compute.googleapis.com/projects/p/zones/z/instances/i`.
73 */
74 assetNames?: string[];
75 /**
76 * Asset types to subscribe to. Example: `storage.googleapis.com/Bucket`.
77 */
78 assetTypes?: string[];
79 /**
80 * Asset content included in updates (`RESOURCE`, `IAM_POLICY`,
81 * `ORG_POLICY`, `ACCESS_POLICY`, `OS_INVENTORY`, `RELATIONSHIP`).
82 * Omitted returns name and type only.
83 */
84 contentType?: FeedContentType;
85 /**
86 * Relationship types to emit when `contentType` is `RELATIONSHIP`.
87 */
88 relationshipTypes?: string[];
89 /**
90 * Pub/Sub topic that receives asset updates
91 * (`projects/{project}/topics/{topic}`). Alchemy grants the Cloud
92 * Asset service agent `roles/pubsub.publisher` on the topic.
93 */
94 pubsubTopic: string;
95 /**
96 * CEL condition that filters published updates. When omitted, Alchemy
97 * still stamps ownership into a no-op `true` condition.
98 */
99 condition?: FeedCondition;
100 };
101
102 export type Feed = Resource<
103 "GCP.CloudAsset.Feed",
104 FeedProps,
105 {
106 /** Full resource name `projects/{project}/feeds/{feed}`. */
107 name: string;
108 /** Feed id (last path segment). */
109 feedId: string;
110 /** Parent project, folder, or organization. */
111 parent: string;
112 /** Project id used when the feed was reconciled. */
113 project: string;
114 /** Full resource names the feed watches. */
115 assetNames: string[];
116 /** Asset types the feed watches. */
117 assetTypes: string[];
118 /** Content type included in updates. */
119 contentType: string | undefined;
120 /** Relationship types when `contentType` is `RELATIONSHIP`. */
121 relationshipTypes: string[];
122 /** Destination Pub/Sub topic. */
123 pubsubTopic: string | undefined;
124 /** User condition with the Alchemy ownership prefix stripped. */
125 condition: FeedCondition | undefined;
126 },
127 never,
128 Providers
129 >;
130
131 /**
132 * A Cloud Asset Inventory feed that publishes asset updates to Pub/Sub.
133 *
134 * Feeds have no labels field — Alchemy stamps ownership into
135 * `condition.description` so `list` / nuke can find them. Feed id and
136 * parent are identity. Asset filters, content type, destination topic,
137 * and condition update in place.
138 *
139 * ### Creating a Feed
140 * **Example:** Watch storage buckets
141 * ```typescript
142 * const topic = yield* GCP.PubSub.Topic("AssetEvents", {});
143 * const feed = yield* GCP.CloudAsset.Feed("Buckets", {
144 * pubsubTopic: topic.name,
145 * assetTypes: ["storage.googleapis.com/Bucket"],
146 * contentType: "RESOURCE",
147 * });
148 * ```
149 *
150 * **Example:** Named feed with a deletion filter
151 * ```typescript
152 * const feed = yield* GCP.CloudAsset.Feed("Buckets", {
153 * feedId: "bucket-deletes",
154 * pubsubTopic: topic.name,
155 * assetTypes: ["storage.googleapis.com/Bucket"],
156 * contentType: "RESOURCE",
157 * condition: {
158 * expression: "temporal_asset.deleted == true",
159 * title: "deletes",
160 * description: "publish deletions only",
161 * },
162 * });
163 * ```
164 *
165 * ### Updating a Feed
166 * **Example:** Also watch Pub/Sub topics
167 * ```typescript
168 * // Same logical id, changed props: the feed is patched in place.
169 * const feed = yield* GCP.CloudAsset.Feed("Buckets", {
170 * pubsubTopic: topic.name,
171 * assetTypes: [
172 * "storage.googleapis.com/Bucket",
173 * "pubsub.googleapis.com/Topic",
174 * ],
175 * contentType: "RESOURCE",
176 * });
177 * ```
178 *
179 * @resource
180 * @category CloudAsset
181 */
182 export const Feed = Resource<Feed>("GCP.CloudAsset.Feed");
183
184 export class FeedNotResolved extends Data.TaggedError("GCP.CloudAsset.FeedNotResolved")<{
185 resourceName: string;
186 }> {}
187
188 const resourceName = (parent: string, feedId: string) => `${parent}/feeds/${feedId}`;
189
190 const contentTypeOf = (value: string | undefined) =>
191 !value || value === "CONTENT_TYPE_UNSPECIFIED" ? undefined : value;
192
193 const toUserCondition = (condition: cloudasset.Expr | undefined): FeedCondition | undefined => {
194 if (condition === undefined) return undefined;
195 const { description } = parseDescription(condition.description);
196 const isInternalOnly =
197 (condition.expression === undefined || condition.expression === NO_OP_EXPRESSION) &&
198 condition.title === undefined &&
199 condition.location === undefined &&
200 description === undefined;
201 if (isInternalOnly) return undefined;
202 return {
203 expression: condition.expression,
204 title: condition.title,
205 description,
206 location: condition.location,
207 };
208 };
209
210 const desiredCondition = (
211 ownership: Record<string, string>,
212 condition: FeedCondition | undefined,
213 ): cloudasset.Expr => ({
214 expression: condition?.expression ?? NO_OP_EXPRESSION,
215 title: condition?.title,
216 location: condition?.location,
217 description: encodeDescription(ownership, condition?.description),
218 });
219
220 const toAttrs = (feed: cloudasset.Feed, project: string) => {
221 const name = feed.name ?? "";
222 return {
223 name,
224 feedId: lastSegment(name),
225 parent: parentOf(name, "feeds"),
226 project,
227 assetNames: feed.assetNames ?? [],
228 assetTypes: feed.assetTypes ?? [],
229 contentType: contentTypeOf(feed.contentType),
230 relationshipTypes: feed.relationshipTypes ?? [],
231 pubsubTopic: feed.feedOutputConfig?.pubsubDestination?.topic,
232 condition: toUserCondition(feed.condition),
233 };
234 };
235
236 const getByName = (name: string) =>
237 name.length === 0
238 ? Effect.undefined
239 : cloudasset.getFeeds({ name }).pipe(Effect.catchTag("NotFound", () => Effect.undefined));
240
241 const observe = (project: string, feedId: string, outputName?: string) =>
242 Effect.gen(function* () {
243 const parent = yield* scopeParent(project);
244 const candidates = [outputName, resourceName(parent, feedId)].filter(
245 (name): name is string => name !== undefined && name.length > 0,
246 );
247 for (const name of candidates) {
248 const found = yield* getByName(name);
249 if (found !== undefined) return found;
250 }
251 const feeds = yield* listFeeds(parent);
252 return feeds.find((feed) => lastSegment(feed.name ?? "") === feedId);
253 });
254
255 const toFeedBody = (news: FeedProps, condition: cloudasset.Expr): cloudasset.Feed => ({
256 assetNames: news.assetNames,
257 assetTypes: news.assetTypes,
258 contentType: news.contentType,
259 relationshipTypes: news.relationshipTypes,
260 feedOutputConfig: {
261 pubsubDestination: { topic: news.pubsubTopic },
262 },
263 condition,
264 });
265
266 export const FeedProvider = () =>
267 Provider.succeed(Feed, {
268 stables: ["name", "feedId", "parent", "project"],
269
270 diff: Effect.fn(function* ({ news, olds, output }) {
271 if (!isResolved(news)) return undefined;
272 return (
273 replaceOn(olds?.feedId ?? output?.feedId, news.feedId) ??
274 replaceOn(olds?.parent, news.parent)
275 );
276 }),
277
278 read: Effect.fn(function* ({ id, olds, output }) {
279 const env = yield* GcpEnvironment.current;
280 const feedId = yield* toPhysicalId(id, olds?.feedId, output?.feedId);
281 const existing = yield* observe(env.project, feedId, output?.name);
282 if (existing === undefined) return undefined;
283 const attrs = toAttrs(existing, env.project);
284 return (yield* ownedByAlchemy(id, existing.condition?.description)) ? attrs : Unowned(attrs);
285 }),
286
287 list: () =>
288 Effect.gen(function* () {
289 const env = yield* GcpEnvironment.current;
290 const parent = yield* scopeParent(env.project);
291 const feeds = yield* listFeeds(parent);
292 return feeds
293 .filter((feed) => hasOwnershipMarker(feed.condition?.description))
294 .map((feed) => toAttrs(feed, env.project));
295 }),
296
297 reconcile: Effect.fn(function* ({ id, news, output }) {
298 const env = yield* GcpEnvironment.current;
299 const feedId = yield* toPhysicalId(id, news.feedId, output?.feedId);
300 const parent = yield* scopeParent(env.project, news.parent);
301 const name = resourceName(parent, feedId);
302 const ownership = yield* createInternalLabels(id);
303 const condition = desiredCondition(ownership, news.condition);
304 const body = toFeedBody(news, condition);
305 yield* grantCloudAssetPublisher(env.project, news.pubsubTopic);
306
307 let current = yield* observe(env.project, feedId, output?.name);
308
309 if (current === undefined) {
310 const created = yield* cloudasset
311 .createFeeds({
312 parent,
313 body: { feedId, feed: body },
314 })
315 .pipe(
316 Effect.retry({
317 while: (error) => error._tag === "BadRequest",
318 times: 8,
319 schedule: Schedule.spaced("2 seconds"),
320 }),
321 Effect.catchTag("Conflict", () => observe(env.project, feedId, output?.name)),
322 );
323 current = created ?? undefined;
324 }
325
326 if (current === undefined) {
327 return yield* new FeedNotResolved({ resourceName: name });
328 }
329
330 const currentName = current.name ?? name;
331 const namesChanged = !sameStringList(current.assetNames, news.assetNames);
332 const typesChanged = !sameStringList(current.assetTypes, news.assetTypes);
333 const contentChanged = !sameText(
334 contentTypeOf(current.contentType),
335 contentTypeOf(news.contentType),
336 );
337 const relationshipsChanged = !sameStringList(
338 current.relationshipTypes,
339 news.relationshipTypes,
340 );
341 const topicChanged = !sameText(
342 current.feedOutputConfig?.pubsubDestination?.topic,
343 news.pubsubTopic,
344 );
345 const conditionChanged = !sameJson(current.condition, condition);
346 const updateMask = updateMaskOf(
347 namesChanged ? "asset_names" : undefined,
348 typesChanged ? "asset_types" : undefined,
349 contentChanged ? "content_type" : undefined,
350 relationshipsChanged ? "relationship_types" : undefined,
351 topicChanged ? "feed_output_config" : undefined,
352 conditionChanged ? "condition" : undefined,
353 );
354
355 if (updateMask.length > 0) {
356 current = yield* cloudasset.patchFeeds({
357 name: currentName,
358 body: {
359 updateMask,
360 feed: { ...body, name: currentName },
361 },
362 });
363 }
364
365 return toAttrs(current, env.project);
366 }),
367
368 delete: Effect.fn(function* ({ output }) {
369 if (!output.name) return;
370 yield* cloudasset
371 .deleteFeeds({ name: output.name })
372 .pipe(Effect.catchTag(["NotFound", "BadRequest"], () => Effect.void));
373 }),
374 });