The best way to control Claude Code, Codex and more from any computer or phone

main
ts 254 lines 7.93 KB
Raw
1 import * as essentialcontacts from "@distilled.cloud/gcp/essentialcontacts_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 type { Providers } from "../Providers.ts";
10 import {
11 desiredCategories,
12 desiredLanguage,
13 encodeEmail,
14 findOwnedContact,
15 hasOwnershipMarker,
16 listContacts,
17 normalizeEmail,
18 ownedByAlchemy,
19 ownershipLabels,
20 projectParent,
21 sameCategories,
22 sameText,
23 toCoreAttrs,
24 toCreateBody,
25 toEmail,
26 UPDATE_MASK,
27 type NotificationCategory,
28 } from "./internal.ts";
29
30 export type ContactProps = {
31 /**
32 * Email address that receives Google Cloud notifications. Does not
33 * need to be a Google Account. Immutable — changing it replaces the
34 * contact. If omitted, a unique `example.com` address is generated.
35 * Essential Contacts have no labels field, so Alchemy stamps
36 * ownership into a `+alc.{stack}.{stage}.{id}` plus-tag and strips it
37 * from attributes.
38 */
39 email?: string;
40 /**
41 * Preferred notification language as a BCP-47 / ISO 639-1 tag
42 * (`en-US`, `en-GB`, `ja`, …).
43 * @default "en-US"
44 */
45 languageTag?: string;
46 /**
47 * Notification categories this contact subscribes to.
48 * @default ["ALL"]
49 */
50 notificationCategorySubscriptions?: NotificationCategory[];
51 };
52
53 export type Contact = Resource<
54 "GCP.EssentialContacts.Contact",
55 ContactProps,
56 {
57 /** Full resource name `projects/{project}/contacts/{contact}`. */
58 name: string;
59 /** Server-assigned contact id (last path segment). */
60 contactId: string;
61 /** Parent resource `projects/{project}`. */
62 parent: string;
63 /** Project id used when the contact was reconciled. */
64 project: string;
65 /** User email with the Alchemy plus-tag stripped. */
66 email: string;
67 /** Preferred notification language. */
68 languageTag: string;
69 /** Subscribed notification categories. */
70 notificationCategorySubscriptions: NotificationCategory[];
71 /** Server-reported validation state. */
72 validationState: string | undefined;
73 /** RFC3339 time the validation state was last updated. */
74 validateTime: string | undefined;
75 },
76 never,
77 Providers
78 >;
79
80 /**
81 * A project-level Google Cloud Essential Contact.
82 *
83 * Essential Contacts have no labels field, so Alchemy stamps ownership
84 * into the email plus-tag for `list` / nuke. Email is identity —
85 * changing it replaces the contact. Language and notification
86 * categories update in place.
87 *
88 * ### Creating a Contact
89 * **Example:** Technical contact
90 * ```typescript
91 * const contact = yield* GCP.EssentialContacts.Contact("Ops", {
92 * email: "ops@example.com",
93 * languageTag: "en-US",
94 * notificationCategorySubscriptions: ["TECHNICAL"],
95 * });
96 * ```
97 *
98 * **Example:** Subscribe to every category
99 * ```typescript
100 * const contact = yield* GCP.EssentialContacts.Contact("Ops", {
101 * email: "ops@example.com",
102 * notificationCategorySubscriptions: ["ALL"],
103 * });
104 * ```
105 *
106 * ### Updating a Contact
107 * **Example:** Change language and categories
108 * ```typescript
109 * const contact = yield* GCP.EssentialContacts.Contact("Ops", {
110 * email: "ops@example.com",
111 * languageTag: "en-GB",
112 * notificationCategorySubscriptions: ["SECURITY", "TECHNICAL"],
113 * });
114 * ```
115 *
116 * @resource
117 * @category EssentialContacts
118 */
119 export const Contact = Resource<Contact>("GCP.EssentialContacts.Contact");
120
121 export class ContactNotResolved extends Data.TaggedError(
122 "GCP.EssentialContacts.ContactNotResolved",
123 )<{
124 resourceName: string;
125 }> {}
126
127 const getByName = (name: string) =>
128 name.length === 0
129 ? Effect.undefined
130 : essentialcontacts
131 .getProjectsContacts({ name })
132 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
133
134 const listAt = (parent: string) =>
135 parent.length === 0
136 ? Effect.succeed([])
137 : listContacts(
138 essentialcontacts.listProjectsContacts.pages({
139 parent,
140 pageSize: 200,
141 }),
142 );
143
144 export const ContactProvider = () =>
145 Provider.succeed(Contact, {
146 stables: ["name", "contactId", "parent", "project", "email"],
147
148 diff: Effect.fn(function* ({ news, olds, output }) {
149 if (!isResolved(news)) return undefined;
150 const previousEmail = olds?.email ?? output?.email;
151 if (
152 news.email !== undefined &&
153 previousEmail !== undefined &&
154 normalizeEmail(news.email) !== normalizeEmail(previousEmail)
155 ) {
156 return { action: "replace" as const, deleteFirst: false };
157 }
158 return undefined;
159 }),
160
161 read: Effect.fn(function* ({ id, olds, output }) {
162 const env = yield* GcpEnvironment.current;
163 const parent = projectParent(env.project);
164 let existing = yield* getByName(output?.name ?? "");
165 if (existing === undefined) {
166 existing = yield* findOwnedContact(
167 yield* listAt(parent),
168 id,
169 output?.name,
170 olds?.email ?? output?.email,
171 );
172 }
173 if (existing === undefined) return undefined;
174 const attrs = toCoreAttrs(existing, parent, env.project);
175 return (yield* ownedByAlchemy(id, existing.email)) ? attrs : Unowned(attrs);
176 }),
177
178 list: () =>
179 Effect.gen(function* () {
180 const env = yield* GcpEnvironment.current;
181 const parent = projectParent(env.project);
182 const contacts = yield* listAt(parent);
183 return contacts
184 .filter((contact) => hasOwnershipMarker(contact.email))
185 .map((contact) => toCoreAttrs(contact, parent, env.project));
186 }),
187
188 reconcile: Effect.fn(function* ({ id, news, output }) {
189 const env = yield* GcpEnvironment.current;
190 const parent = projectParent(env.project);
191 const ownership = yield* ownershipLabels(id);
192 const userEmail = yield* toEmail(id, news.email, output?.email);
193 const stampedEmail = encodeEmail(ownership, userEmail);
194 const languageTag = desiredLanguage(news.languageTag);
195 const categories = desiredCategories(news.notificationCategorySubscriptions);
196 const body = toCreateBody({
197 email: stampedEmail,
198 languageTag,
199 notificationCategorySubscriptions: categories,
200 });
201
202 let current = yield* getByName(output?.name ?? "");
203 if (current === undefined) {
204 current = yield* findOwnedContact(yield* listAt(parent), id, output?.name, userEmail);
205 }
206
207 if (current === undefined) {
208 const created = yield* essentialcontacts
209 .createProjectsContacts({ parent, body })
210 .pipe(
211 Effect.catchTag("Conflict", () =>
212 listAt(parent).pipe(
213 Effect.flatMap((contacts) => findOwnedContact(contacts, id, undefined, userEmail)),
214 ),
215 ),
216 );
217 current = created ?? undefined;
218 if (current?.name) {
219 current = (yield* getByName(current.name)) ?? current;
220 }
221 }
222
223 if (current === undefined) {
224 return yield* new ContactNotResolved({
225 resourceName: output?.name ?? `${parent}/contacts`,
226 });
227 }
228
229 const languageChanged = !sameText(current.languageTag, languageTag);
230 const categoriesChanged = !sameCategories(
231 current.notificationCategorySubscriptions,
232 categories,
233 );
234 if (languageChanged || categoriesChanged) {
235 current = yield* essentialcontacts.patchProjectsContacts({
236 name: current.name ?? "",
237 updateMask: UPDATE_MASK,
238 body: {
239 languageTag,
240 notificationCategorySubscriptions: categories,
241 },
242 });
243 }
244
245 return toCoreAttrs(current, parent, env.project);
246 }),
247
248 delete: Effect.fn(function* ({ output }) {
249 if (!output.name) return;
250 yield* essentialcontacts
251 .deleteProjectsContacts({ name: output.name })
252 .pipe(Effect.catchTag("NotFound", () => Effect.void));
253 }),
254 });