@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 306 lines 10.8 KB
Raw
1 import * as integrations from "@distilled.cloud/gcp/integrations_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 { GcpEnvironment } from "../Environment.ts";
9 import { createInternalLabels } from "../Labels.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 findSfdcChannelByDescription,
13 listOwnedSfdcChannels,
14 parseResourceName,
15 } from "./internal.ts";
16 import {
17 encodeOwnership,
18 expandSfdcInstance,
19 hasOwnershipMarker,
20 isDeleted,
21 lastSegment,
22 locationOf,
23 normalizeLocation,
24 ownedByAlchemy,
25 parseOwnership,
26 withProjectId,
27 replaceOnIdentity,
28 sameText,
29 toResourceId,
30 updateMaskOf,
31 } from "./ownership.ts";
32
33 export type SfdcInstancesSfdcChannelProps = {
34 /**
35 * Parent SFDC instance resource name
36 * `projects/{project}/locations/{location}/sfdcInstances/{sfdcInstance}`
37 * or a bare instance id (combined with `location`). Immutable —
38 * changing it replaces the channel.
39 */
40 sfdcInstance: string;
41 /**
42 * Channel id (the `{sfdcChannel}` segment). Server-assigned on create
43 * when omitted. Immutable — changing it replaces the channel.
44 */
45 sfdcChannelId?: string;
46 /**
47 * Location used when `sfdcInstance` is a bare id.
48 * @default the stack's GCP region (`GCP.Region`, else the profile
49 * region, else `us-central1`)
50 */
51 location?: string;
52 /**
53 * Client-level unique alias for the channel.
54 */
55 displayName?: string;
56 /**
57 * Human-readable description. Channels have no labels field, so Alchemy
58 * stamps ownership into a `[alchemy …]` prefix and strips it from
59 * attributes.
60 */
61 description?: string;
62 /**
63 * Salesforce channel topic assigned when the channel is opened (CDC
64 * or Platform Event).
65 */
66 channelTopic: string;
67 };
68
69 export type SfdcInstancesSfdcChannel = Resource<
70 "GCP.Integrations.SfdcInstancesSfdcChannel",
71 SfdcInstancesSfdcChannelProps,
72 {
73 /** Full resource name `.../sfdcInstances/{instance}/sfdcChannels/{channel}`. */
74 name: string;
75 /** Channel id (last path segment). */
76 sfdcChannelId: string;
77 /** Parent SFDC instance resource name. */
78 sfdcInstance: string;
79 /** Location id. */
80 location: string;
81 /** Project id. */
82 project: string;
83 /** User-selected alias. */
84 displayName: string | undefined;
85 /** User description with the Alchemy ownership prefix stripped. */
86 description: string | undefined;
87 /** Salesforce channel topic. */
88 channelTopic: string | undefined;
89 /** Whether any published integration references this channel. */
90 isActive: boolean;
91 /** Last Salesforce message replay id. */
92 lastReplayId: string | undefined;
93 /** RFC3339 creation timestamp. */
94 createTime: string | undefined;
95 /** RFC3339 last-update timestamp. */
96 updateTime: string | undefined;
97 },
98 never,
99 Providers
100 >;
101
102 /**
103 * A Salesforce CDC or Platform Event channel under an Application
104 * Integration SFDC instance.
105 *
106 * Channels have no labels field, so Alchemy stamps ownership into the
107 * description for `list` / nuke. Parent instance and id are identity —
108 * changing them replaces the channel. Display name, description, and
109 * channel topic update in place.
110 *
111 * ### Creating an SFDC Channel
112 * **Example:** Platform Event channel
113 * ```typescript
114 * const channel = yield* GCP.Integrations.SfdcInstancesSfdcChannel("Events", {
115 * sfdcInstance: instance.name,
116 * displayName: "account-events",
117 * channelTopic: "/event/AlchemyTest__e",
118 * });
119 * ```
120 *
121 * ### Updating an SFDC Channel
122 * Re-declare the same logical id with changed props; the engine keeps the
123 * physical resource and updates it in place.
124 *
125 * **Example:** Rename the alias
126 * ```typescript
127 * const channel = yield* GCP.Integrations.SfdcInstancesSfdcChannel("Events", {
128 * sfdcInstance: instance.name,
129 * displayName: "account-events-v2",
130 * channelTopic: "/event/AlchemyTest__e",
131 * });
132 * ```
133 *
134 * @resource
135 * @category Integrations
136 */
137 export const SfdcInstancesSfdcChannel = Resource<SfdcInstancesSfdcChannel>(
138 "GCP.Integrations.SfdcInstancesSfdcChannel",
139 );
140
141 export class SfdcInstancesSfdcChannelNotResolved extends Data.TaggedError(
142 "GCP.Integrations.SfdcInstancesSfdcChannelNotResolved",
143 )<{
144 resourceName: string;
145 }> {}
146
147 const resourceName = (sfdcInstance: string, sfdcChannelId: string) =>
148 `${sfdcInstance}/sfdcChannels/${sfdcChannelId}`;
149
150 const toAttrs = (
151 channel: integrations.GoogleCloudIntegrationsV1alphaSfdcChannel,
152 project: string,
153 region: string,
154 instanceHint?: string,
155 ) => {
156 const name = withProjectId(channel.name ?? "", project);
157 const parsed = parseResourceName(name, "sfdcChannels", region);
158 return {
159 name,
160 sfdcChannelId: lastSegment(name),
161 sfdcInstance: name.includes("/sfdcChannels/")
162 ? parsed.sfdcInstance
163 : (instanceHint ?? parsed.parent),
164 location: locationOf(name, region),
165 project,
166 displayName: channel.displayName,
167 description: parseOwnership(channel.description).text,
168 channelTopic: channel.channelTopic,
169 isActive: channel.isActive === true,
170 lastReplayId: channel.lastReplayId,
171 createTime: channel.createTime,
172 updateTime: channel.updateTime,
173 };
174 };
175
176 const getByName = (name: string) =>
177 name.length === 0
178 ? Effect.undefined
179 : integrations.getProjectsLocationsSfdcInstancesSfdcChannels({ name }).pipe(
180 Effect.map((channel) => (isDeleted(channel) ? undefined : channel)),
181 Effect.catchTag("NotFound", () => Effect.undefined),
182 );
183
184 export const SfdcInstancesSfdcChannelProvider = () =>
185 Provider.succeed(SfdcInstancesSfdcChannel, {
186 stables: ["name", "sfdcChannelId", "sfdcInstance", "location", "project", "createTime"],
187
188 diff: Effect.fn(function* ({ news, olds, output }) {
189 if (!isResolved(news)) return undefined;
190 const env = yield* GcpEnvironment.current;
191 const previousInstance = olds?.sfdcInstance ?? output?.sfdcInstance;
192 const instanceChanged =
193 previousInstance !== undefined &&
194 lastSegment(news.sfdcInstance) !== lastSegment(previousInstance);
195 const previousId = olds?.sfdcChannelId ?? output?.sfdcChannelId;
196 const idChanged =
197 previousId !== undefined &&
198 news.sfdcChannelId !== undefined &&
199 news.sfdcChannelId !== previousId;
200 const previousLocation = olds?.location ?? output?.location;
201 const locationChanged =
202 previousLocation !== undefined &&
203 news.location !== undefined &&
204 normalizeLocation(news.location, env.region) !==
205 normalizeLocation(previousLocation, env.region);
206 return replaceOnIdentity(instanceChanged || idChanged || locationChanged);
207 }),
208
209 read: Effect.fn(function* ({ id, olds, output }) {
210 const env = yield* GcpEnvironment.current;
211 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
212 const sfdcInstance = olds?.sfdcInstance
213 ? expandSfdcInstance(olds.sfdcInstance, env.project, location)
214 : output?.sfdcInstance;
215 const sfdcChannelId = yield* toResourceId(id, olds?.sfdcChannelId, output?.sfdcChannelId);
216 const name =
217 output?.name ??
218 (sfdcInstance !== undefined ? resourceName(sfdcInstance, sfdcChannelId) : "");
219 let existing = yield* getByName(name);
220 if (existing === undefined && sfdcInstance !== undefined && output?.name === undefined) {
221 const ownership = yield* createInternalLabels(id);
222 existing = yield* findSfdcChannelByDescription(
223 sfdcInstance,
224 encodeOwnership(ownership, olds?.description),
225 );
226 }
227 if (existing === undefined) return undefined;
228 const attrs = toAttrs(existing, env.project, env.region, sfdcInstance);
229 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
230 }),
231
232 list: () =>
233 Effect.gen(function* () {
234 const env = yield* GcpEnvironment.current;
235 const items = yield* listOwnedSfdcChannels(env.project, env.region);
236 return items
237 .filter((channel) => hasOwnershipMarker(channel.description))
238 .map((channel) => toAttrs(channel, env.project, env.region));
239 }),
240
241 reconcile: Effect.fn(function* ({ id, news, output }) {
242 const env = yield* GcpEnvironment.current;
243 const location = normalizeLocation(news.location ?? output?.location, env.region);
244 const sfdcInstance = expandSfdcInstance(news.sfdcInstance, env.project, location);
245 const sfdcChannelId = yield* toResourceId(id, news.sfdcChannelId, output?.sfdcChannelId);
246 const name = output?.name ?? resourceName(sfdcInstance, sfdcChannelId);
247 const ownership = yield* createInternalLabels(id);
248 const description = encodeOwnership(ownership, news.description);
249 const displayName = news.displayName ?? sfdcChannelId;
250 const body: integrations.GoogleCloudIntegrationsV1alphaSfdcChannel = {
251 displayName,
252 description,
253 channelTopic: news.channelTopic,
254 };
255
256 let current = yield* getByName(output?.name ?? name);
257 if (current === undefined) {
258 current = yield* findSfdcChannelByDescription(sfdcInstance, description);
259 }
260
261 if (current === undefined) {
262 const created = yield* integrations
263 .createProjectsLocationsSfdcInstancesSfdcChannels({
264 parent: sfdcInstance,
265 body,
266 })
267 .pipe(
268 Effect.catchTag("Conflict", () =>
269 findSfdcChannelByDescription(sfdcInstance, description),
270 ),
271 );
272 current = created ?? undefined;
273 }
274
275 if (current === undefined) {
276 return yield* new SfdcInstancesSfdcChannelNotResolved({ resourceName: name });
277 }
278
279 const currentName = withProjectId(current.name ?? name, env.project);
280 const displayChanged = !sameText(current.displayName, displayName);
281 const descriptionChanged = (current.description ?? "") !== description;
282 const topicChanged = !sameText(current.channelTopic, news.channelTopic);
283
284 if (displayChanged || descriptionChanged || topicChanged) {
285 current = yield* integrations.patchProjectsLocationsSfdcInstancesSfdcChannels({
286 name: currentName,
287 updateMask: updateMaskOf(
288 displayChanged ? "displayName" : undefined,
289 descriptionChanged ? "description" : undefined,
290 topicChanged ? "channelTopic" : undefined,
291 ),
292 body: { ...body, name: currentName },
293 });
294 }
295
296 return toAttrs(current, env.project, env.region, sfdcInstance);
297 }),
298
299 delete: Effect.fn(function* ({ output }) {
300 yield* integrations
301 .deleteProjectsLocationsSfdcInstancesSfdcChannels({
302 name: output.name,
303 })
304 .pipe(Effect.catchTag("NotFound", () => Effect.void));
305 }),
306 });