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

main
ts 364 lines 11.6 KB
Raw
1 import * as retail from "@distilled.cloud/gcp/retail_v2";
2 import { unownedUnlessPrevious } 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 type { Providers } from "../Providers.ts";
11 import {
12 MAX_MODEL_ID_LENGTH,
13 expandCatalog,
14 normalizeLocation,
15 parseResourceName,
16 replaceOnIdentity,
17 sameText,
18 slugNoDigits,
19 toPhysical,
20 updateMaskOf,
21 } from "./internal.ts";
22 import { resourceNameFromOperation, waitForOperation } from "./operations.ts";
23
24 export type CatalogsModelProps = {
25 /**
26 * Parent catalog resource name
27 * `projects/{project}/locations/{location}/catalogs/{catalog}` or a
28 * catalog id (combined with `location`). Immutable — changing it
29 * replaces the model.
30 * @default "default_catalog"
31 */
32 catalog?: string;
33 /**
34 * Location used when `catalog` is a bare id. Immutable.
35 * @default "global"
36 */
37 location?: string;
38 /**
39 * Model id (4-40 characters). If omitted, a unique id is generated.
40 * Immutable — changing it replaces the model.
41 */
42 modelId?: string;
43 /**
44 * Human-readable name (max 1,024 characters). Display name is set at create
45 * time and is not updated in place.
46 */
47 displayName?: string;
48 /**
49 * Model type. Immutable.
50 * @default "recommended-for-you"
51 */
52 type?: string;
53 /**
54 * Optimization objective (`ctr`, `cvr`, `revenue-per-order`). Immutable
55 * after create.
56 */
57 optimizationObjective?: string;
58 /**
59 * Training state. Synced via pause/resume after create.
60 * @default "PAUSED"
61 */
62 trainingState?: "TRAINING_STATE_UNSPECIFIED" | "PAUSED" | "TRAINING" | (string & {});
63 /**
64 * Periodic tuning state. Patchable.
65 */
66 periodicTuningState?:
67 | "PERIODIC_TUNING_STATE_UNSPECIFIED"
68 | "PERIODIC_TUNING_DISABLED"
69 | "ALL_TUNING_DISABLED"
70 | "PERIODIC_TUNING_ENABLED"
71 | (string & {});
72 /**
73 * Recommendation attribute filtering.
74 */
75 filteringOption?:
76 | "RECOMMENDATIONS_FILTERING_OPTION_UNSPECIFIED"
77 | "RECOMMENDATIONS_FILTERING_DISABLED"
78 | "RECOMMENDATIONS_FILTERING_ENABLED"
79 | (string & {});
80 };
81
82 export type CatalogsModel = Resource<
83 "GCP.Retail.CatalogsModel",
84 CatalogsModelProps,
85 {
86 /** Full resource name. */
87 name: string;
88 /** Model id. */
89 modelId: string;
90 /** Parent catalog resource name. */
91 catalog: string;
92 /** Project id. */
93 project: string;
94 /** Location id. */
95 location: string;
96 /** Display name. */
97 displayName: string | undefined;
98 /** Model type. */
99 type: string | undefined;
100 /** Optimization objective. */
101 optimizationObjective: string | undefined;
102 /** Training state. */
103 trainingState: string | undefined;
104 /** Serving state. */
105 servingState: string | undefined;
106 /** Data state. */
107 dataState: string | undefined;
108 /** Periodic tuning state. */
109 periodicTuningState: string | undefined;
110 /** Filtering option. */
111 filteringOption: string | undefined;
112 /** RFC3339 create time. */
113 createTime: string | undefined;
114 /** RFC3339 update time. */
115 updateTime: string | undefined;
116 },
117 never,
118 Providers
119 >;
120
121 /**
122 * A Retail recommendation model on a catalog.
123 *
124 * Without labels, ownership rests on the deterministic id: `read` reports a
125 * resource it finds without prior state as unowned (adopt it with `--adopt`).
126 * Parent, model id, type, and optimization objective are immutable.
127 * `filteringOption` and `periodicTuningState` patch in place; `trainingState`
128 * is synced with pause/resume.
129 *
130 * Creating a model requires Retail Recommendations and enough catalog
131 * and user-event data. Create is a long-running operation.
132 *
133 * ### Creating a Model
134 * **Example:** Recommended-for-you model, paused
135 * ```typescript
136 * const model = yield* GCP.Retail.CatalogsModel("Homepage", {
137 * displayName: "homepage recs",
138 * type: "recommended-for-you",
139 * trainingState: "PAUSED",
140 * });
141 * ```
142 *
143 * @resource
144 * @category Retail
145 */
146 export const CatalogsModel = Resource<CatalogsModel>("GCP.Retail.CatalogsModel");
147
148 export class CatalogsModelNotResolved extends Data.TaggedError(
149 "GCP.Retail.CatalogsModelNotResolved",
150 )<{
151 resourceName: string;
152 }> {}
153
154 const toAttrs = (model: retail.GoogleCloudRetailV2Model, project: string) => {
155 const name = model.name ?? "";
156 const parsed = parseResourceName(name, "models");
157 return {
158 name,
159 modelId: parsed.id,
160 catalog: parsed.catalog,
161 project: parsed.project || project,
162 location: parsed.location,
163 displayName: model.displayName,
164 type: model.type,
165 optimizationObjective: model.optimizationObjective,
166 trainingState: model.trainingState,
167 servingState: model.servingState,
168 dataState: model.dataState,
169 periodicTuningState: model.periodicTuningState,
170 filteringOption: model.filteringOption,
171 createTime: model.createTime,
172 updateTime: model.updateTime,
173 };
174 };
175
176 const resourceName = (catalog: string, modelId: string) => `${catalog}/models/${modelId}`;
177
178 const getByName = (name: string) =>
179 name.length === 0
180 ? Effect.undefined
181 : retail
182 .getProjectsLocationsCatalogsModels({ name })
183 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
184
185 const refresh = (name: string) =>
186 getByName(name).pipe(
187 Effect.filterOrFail(
188 (model): model is retail.GoogleCloudRetailV2Model => model !== undefined,
189 () => new CatalogsModelNotResolved({ resourceName: name }),
190 ),
191 Effect.retry({
192 while: (error) => error._tag === "GCP.Retail.CatalogsModelNotResolved",
193 times: 5,
194 schedule: Schedule.exponential("250 millis"),
195 }),
196 );
197
198 export const CatalogsModelProvider = () =>
199 Provider.succeed(CatalogsModel, {
200 stables: ["name", "modelId", "catalog", "project", "location", "type", "createTime"],
201
202 diff: Effect.fn(function* ({ news, olds, output }) {
203 if (!isResolved(news)) return undefined;
204 const env = yield* GcpEnvironment.current;
205 const previousParent = olds?.catalog ?? output?.catalog;
206 const nextParent = expandCatalog(
207 news.catalog,
208 env.project,
209 normalizeLocation(news.location ?? output?.location),
210 );
211 const previousType = olds?.type ?? output?.type;
212 const nextType = news.type ?? previousType;
213 const previousObjective = olds?.optimizationObjective ?? output?.optimizationObjective;
214 const nextObjective = news.optimizationObjective ?? previousObjective;
215 const identity = replaceOnIdentity({
216 previousId: olds?.modelId ?? output?.modelId,
217 nextId: news.modelId,
218 previousParent,
219 nextParent,
220 });
221 if (
222 identity !== undefined ||
223 (previousType !== undefined && nextType !== undefined && previousType !== nextType) ||
224 (previousObjective !== undefined &&
225 nextObjective !== undefined &&
226 previousObjective !== nextObjective)
227 ) {
228 return (
229 identity ?? {
230 action: "replace" as const,
231 deleteFirst: true,
232 }
233 );
234 }
235 return undefined;
236 }),
237
238 read: Effect.fn(function* ({ id, olds, output, previous }) {
239 const env = yield* GcpEnvironment.current;
240 const catalog = olds?.catalog ?? output?.catalog;
241 const modelId = yield* toPhysical(
242 id,
243 olds?.modelId,
244 output?.modelId,
245 (name) => slugNoDigits(name, MAX_MODEL_ID_LENGTH),
246 MAX_MODEL_ID_LENGTH,
247 );
248 const name =
249 output?.name ??
250 (catalog !== undefined
251 ? resourceName(
252 expandCatalog(catalog, env.project, normalizeLocation(output?.location)),
253 modelId,
254 )
255 : undefined);
256 if (name === undefined) return undefined;
257 const existing = yield* getByName(name);
258 if (existing === undefined) return undefined;
259 const attrs = toAttrs(existing, env.project);
260 // No labels field: without prior state it may not be ours.
261 return output !== undefined ? attrs : unownedUnlessPrevious(attrs, previous, "name");
262 }),
263
264 reconcile: Effect.fn(function* ({ id, news, output }) {
265 const env = yield* GcpEnvironment.current;
266 const location = normalizeLocation(news.location ?? output?.location);
267 const catalog = expandCatalog(news.catalog, env.project, location);
268 const modelId = yield* toPhysical(
269 id,
270 news.modelId,
271 output?.modelId,
272 (name) => slugNoDigits(name, MAX_MODEL_ID_LENGTH),
273 MAX_MODEL_ID_LENGTH,
274 );
275 const name = resourceName(catalog, modelId);
276 const displayName = news.displayName ?? modelId;
277 const type = news.type ?? "recommended-for-you";
278 const desiredTraining = news.trainingState ?? "PAUSED";
279
280 let current = yield* getByName(output?.name ?? name);
281
282 if (current === undefined) {
283 const operation = yield* retail
284 .createProjectsLocationsCatalogsModels({
285 parent: catalog,
286 body: {
287 name,
288 displayName,
289 type,
290 optimizationObjective: news.optimizationObjective,
291 trainingState: "TRAINING",
292 periodicTuningState: news.periodicTuningState,
293 filteringOption: news.filteringOption,
294 },
295 })
296 .pipe(
297 Effect.catchTag("Conflict", () =>
298 Effect.succeed<retail.GoogleLongrunningOperation>({
299 name: "",
300 done: true,
301 }),
302 ),
303 );
304 yield* waitForOperation(operation);
305 const createdName = resourceNameFromOperation(operation) ?? name;
306 current = yield* getByName(createdName).pipe(
307 Effect.flatMap((model) =>
308 model !== undefined ? Effect.succeed(model) : getByName(name),
309 ),
310 );
311 if (current === undefined) {
312 current = yield* refresh(name).pipe(
313 Effect.catchTag("GCP.Retail.CatalogsModelNotResolved", () => Effect.undefined),
314 );
315 }
316 }
317
318 if (current === undefined) {
319 return yield* new CatalogsModelNotResolved({ resourceName: name });
320 }
321
322 const resource = current.name ?? name;
323 const mask = updateMaskOf(
324 sameText(current.filteringOption, news.filteringOption) ? undefined : "filtering_option",
325 sameText(current.periodicTuningState, news.periodicTuningState)
326 ? undefined
327 : "periodic_tuning_state",
328 );
329 if (mask.length > 0) {
330 current = yield* retail.patchProjectsLocationsCatalogsModels({
331 name: resource,
332 updateMask: mask,
333 body: {
334 name: resource,
335 filteringOption: news.filteringOption,
336 periodicTuningState: news.periodicTuningState,
337 },
338 });
339 }
340
341 const observedTraining = current.trainingState ?? "TRAINING";
342 if (desiredTraining === "PAUSED" && observedTraining !== "PAUSED") {
343 current = yield* retail.pauseProjectsLocationsCatalogsModels({
344 name: resource,
345 body: {},
346 });
347 } else if (desiredTraining === "TRAINING" && observedTraining !== "TRAINING") {
348 current = yield* retail.resumeProjectsLocationsCatalogsModels({
349 name: resource,
350 body: {},
351 });
352 }
353
354 return toAttrs(current, env.project);
355 }),
356
357 delete: Effect.fn(function* ({ output }) {
358 yield* retail
359 .deleteProjectsLocationsCatalogsModels({
360 name: output.name,
361 })
362 .pipe(Effect.catchTag("NotFound", () => Effect.void));
363 }),
364 });