@microagi/alchemy-gcp 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +54 -2
  3. package/lib/Container/Cluster.d.ts +25 -0
  4. package/lib/Container/Cluster.d.ts.map +1 -1
  5. package/lib/Container/Cluster.js.map +1 -1
  6. package/lib/Providers.d.ts.map +1 -1
  7. package/lib/Providers.js +5 -1
  8. package/lib/Providers.js.map +1 -1
  9. package/lib/Run/IamMember.d.ts +70 -0
  10. package/lib/Run/IamMember.d.ts.map +1 -0
  11. package/lib/Run/IamMember.js +65 -0
  12. package/lib/Run/IamMember.js.map +1 -0
  13. package/lib/Run/IamSync.d.ts +80 -0
  14. package/lib/Run/IamSync.d.ts.map +1 -0
  15. package/lib/Run/IamSync.js +73 -0
  16. package/lib/Run/IamSync.js.map +1 -0
  17. package/lib/Run/Job.d.ts +167 -0
  18. package/lib/Run/Job.d.ts.map +1 -0
  19. package/lib/Run/Job.js +199 -0
  20. package/lib/Run/Job.js.map +1 -0
  21. package/lib/Run/Operations.d.ts +47 -0
  22. package/lib/Run/Operations.d.ts.map +1 -0
  23. package/lib/Run/Operations.js +46 -0
  24. package/lib/Run/Operations.js.map +1 -0
  25. package/lib/Run/Service.d.ts +193 -0
  26. package/lib/Run/Service.d.ts.map +1 -0
  27. package/lib/Run/Service.js +247 -0
  28. package/lib/Run/Service.js.map +1 -0
  29. package/lib/Run/Validation.d.ts +54 -0
  30. package/lib/Run/Validation.d.ts.map +1 -0
  31. package/lib/Run/Validation.js +129 -0
  32. package/lib/Run/Validation.js.map +1 -0
  33. package/lib/Run/index.d.ts +51 -0
  34. package/lib/Run/index.d.ts.map +1 -0
  35. package/lib/Run/index.js +4 -0
  36. package/lib/Run/index.js.map +1 -0
  37. package/lib/index.d.ts +1 -0
  38. package/lib/index.d.ts.map +1 -1
  39. package/lib/index.js +1 -0
  40. package/lib/index.js.map +1 -1
  41. package/package.json +5 -4
  42. package/src/Container/Cluster.ts +25 -0
  43. package/src/Providers.ts +6 -0
  44. package/src/Run/IamMember.ts +79 -0
  45. package/src/Run/IamSync.ts +134 -0
  46. package/src/Run/Job.ts +453 -0
  47. package/src/Run/Operations.ts +77 -0
  48. package/src/Run/Service.ts +541 -0
  49. package/src/Run/Validation.ts +153 -0
  50. package/src/Run/index.ts +52 -0
  51. package/src/index.ts +1 -0
package/src/Run/Job.ts ADDED
@@ -0,0 +1,453 @@
1
+ import * as run from "@distilled.cloud/gcp/run-v2";
2
+ import { Resource } from "alchemy";
3
+ import { Unowned } from "alchemy/AdoptPolicy";
4
+ import type { ScopedPlanStatusSession } from "alchemy/Cli/Cli";
5
+ import { deepEqual, isResolved, somePropsAreDifferent } from "alchemy/Diff";
6
+ import { createPhysicalName } from "alchemy/PhysicalName";
7
+ import * as Provider from "alchemy/Provider";
8
+ import { diffTags } from "alchemy/Tags";
9
+ import * as Duration from "effect/Duration";
10
+ import * as Effect from "effect/Effect";
11
+ import * as Schedule from "effect/Schedule";
12
+ import type * as GCP from "../Providers.ts";
13
+ import { gcpInternalLabels, hasAlchemyLabels } from "../Tags.ts";
14
+ import { makeSyncIam, type RunIamBindingContract } from "./IamSync.ts";
15
+ import { makeAwaitOperation } from "./Operations.ts";
16
+ import {
17
+ reshapeBadRequest,
18
+ validateAnnotations,
19
+ validateContainers,
20
+ validateLabels,
21
+ validateRunName,
22
+ } from "./Validation.ts";
23
+
24
+ /**
25
+ * A Cloud Run v2 Job — a managed batch workload. A Job holds an
26
+ * `ExecutionTemplate` (parallelism + a `TaskTemplate` containing
27
+ * containers); invoking the Job via `runProjectsLocationsJobs` creates
28
+ * an immutable Execution that runs the configured number of tasks to
29
+ * completion.
30
+ *
31
+ * **Declarative vs imperative.** This resource models the Job
32
+ * *definition* — its template, parallelism, task count, IAM. The act
33
+ * of *running* the Job is event-shaped (does not fit the
34
+ * converge-to-desired-state model) and is left to user-side code:
35
+ *
36
+ * ```typescript
37
+ * import * as run from "@distilled.cloud/gcp/run-v2";
38
+ * const job = yield* GCP.Job("Nightly", { ... });
39
+ * const runJob = yield* run.runProjectsLocationsJobs;
40
+ * yield* runJob({
41
+ * name: `projects/${job.project}/locations/${job.location}/jobs/${job.name}`,
42
+ * });
43
+ * // returns an LRO; poll if you want to wait for completion
44
+ * ```
45
+ *
46
+ * **Lifecycle.** observe → ensure (create, retrying the API-enable
47
+ * race) → sync (patch full body if anything changed; Job's patch has
48
+ * no `updateMask` — server diffs the body itself) → sync IAM bindings
49
+ * → return.
50
+ *
51
+ * **Replace triggers.** Only identity fields (project, location, name)
52
+ * force replacement. Everything else is in-place via `patch`. New
53
+ * Executions are created independently by `runProjectsLocationsJobs`.
54
+ *
55
+ * **Optimistic concurrency.** Delete passes through the observed
56
+ * `etag`; patch passes etag in the body so concurrent edits surface
57
+ * as `Conflict` instead of silently overwriting.
58
+ *
59
+ * **Adoption.** Label-gated, same as {@link import("./Service.ts").Service}.
60
+ *
61
+ * **IAM.** Use {@link import("./IamMember.ts").jobIamMember} to bind
62
+ * `(role, member)` grants — typically `roles/run.invoker` on the
63
+ * service account that triggers the job.
64
+ *
65
+ * @section Creating a Cloud Run Job
66
+ * @example Single-shot batch job
67
+ * ```typescript
68
+ * const job = yield* GCP.Job("ProcessBatch", {
69
+ * project: project.projectId,
70
+ * location: "europe-west4",
71
+ * template: {
72
+ * taskCount: 1,
73
+ * template: {
74
+ * maxRetries: 3,
75
+ * containers: [{
76
+ * image: "europe-west4-docker.pkg.dev/proj/repo/worker:latest",
77
+ * }],
78
+ * },
79
+ * },
80
+ * });
81
+ * ```
82
+ *
83
+ * @example Parallel job with custom service account and GPU
84
+ * ```typescript
85
+ * const train = yield* GCP.Job("Train", {
86
+ * project: project.projectId,
87
+ * location: "europe-west4",
88
+ * launchStage: "BETA",
89
+ * template: {
90
+ * taskCount: 8,
91
+ * parallelism: 8,
92
+ * template: {
93
+ * serviceAccount: sa.email,
94
+ * maxRetries: 0,
95
+ * timeout: "21600s",
96
+ * containers: [{
97
+ * image: "europe-west4-docker.pkg.dev/proj/repo/train:v2",
98
+ * resources: { limits: { cpu: "4", memory: "16Gi", "nvidia.com/gpu": "1" } },
99
+ * }],
100
+ * nodeSelector: { accelerator: "nvidia-l4" },
101
+ * },
102
+ * },
103
+ * });
104
+ * ```
105
+ */
106
+ export type JobProps = {
107
+ /** GCP project ID hosting the Job. Immutable — replace if changed. */
108
+ project: string;
109
+ /** Cloud Run region. Immutable — replace if changed. */
110
+ location: string;
111
+ /**
112
+ * Job name. Defaults to `createPhysicalName({ id, lowercase: true,
113
+ * maxLength: 49 })`. Lowercase letters/digits/hyphens; must begin
114
+ * with a letter and not end with a hyphen; **fewer than 50 characters**.
115
+ * Immutable — replace if changed.
116
+ */
117
+ name?: string;
118
+ /** User-visible description. Mutable via `patch`. */
119
+ description?: string;
120
+ /**
121
+ * Resource labels. Alchemy internal labels are merged on top
122
+ * automatically. Cloud Run rejects reserved namespaces (same as
123
+ * Service). Mutable via `patch`.
124
+ */
125
+ labels?: Record<string, string>;
126
+ /** Free-form annotations. Mutable via `patch`. */
127
+ annotations?: Record<string, string>;
128
+ /**
129
+ * Launch stage — `BETA` (or higher) required for preview features
130
+ * (GPU node selectors, Direct VPC). Mutable via `patch`.
131
+ */
132
+ launchStage?:
133
+ | "ALPHA"
134
+ | "BETA"
135
+ | "GA"
136
+ | "EARLY_ACCESS"
137
+ | "PRELAUNCH"
138
+ | "DEPRECATED";
139
+ /** Binary Authorization policy. Mutable via `patch`. */
140
+ binaryAuthorization?: run.GoogleCloudRunV2BinaryAuthorization;
141
+ /**
142
+ * Token-suffix used to compose Execution names when the Job is
143
+ * started via the GCP UI or `gcloud run jobs execute`. Required to
144
+ * keep distinct from Job name + 63 chars. Mutable.
145
+ */
146
+ startExecutionToken?: string;
147
+ /** Same as `startExecutionToken` but used on run completion. Mutable. */
148
+ runExecutionToken?: string;
149
+ /**
150
+ * The Execution template — describes parallelism, task count, and
151
+ * the inner `TaskTemplate` (containers, volumes, retry policy).
152
+ * **Required at create.** Mutable via `patch`.
153
+ */
154
+ template: run.GoogleCloudRunV2ExecutionTemplate;
155
+ };
156
+
157
+ export type JobAttributes = {
158
+ /** Job name (bare). */
159
+ name: string;
160
+ /** Server-assigned UID. */
161
+ uid: string;
162
+ /** Fully-qualified resource name. */
163
+ resourceName: string;
164
+ /** GCP project ID. */
165
+ project: string;
166
+ /** Region. */
167
+ location: string;
168
+ /** Monotonically increasing generation, bumped on every patch. */
169
+ generation: string | undefined;
170
+ /** Generation reflected in the latest reconciled state. */
171
+ observedGeneration: string | undefined;
172
+ /** Overall readiness condition. */
173
+ terminalCondition: run.GoogleCloudRunV2Condition | undefined;
174
+ /** Number of Executions created for this Job. */
175
+ executionCount: number | undefined;
176
+ /** Reference to the most recently created Execution, if any. */
177
+ latestCreatedExecution: run.GoogleCloudRunV2ExecutionReference | undefined;
178
+ /** True while Cloud Run is reconciling toward the desired state. */
179
+ reconciling: boolean | undefined;
180
+ /** Optimistic-concurrency etag. */
181
+ etag: string | undefined;
182
+ /** Labels currently set, including internals. */
183
+ labels: Record<string, string>;
184
+ /** Creation time. */
185
+ createTime: string | undefined;
186
+ /** Last-modified time. */
187
+ updateTime: string | undefined;
188
+ };
189
+
190
+ export type Job = Resource<
191
+ "GCP.Job",
192
+ JobProps,
193
+ JobAttributes,
194
+ RunIamBindingContract,
195
+ GCP.Providers
196
+ >;
197
+ export const Job = Resource<Job>("GCP.Job");
198
+
199
+ const fqName = (project: string, location: string, name: string) =>
200
+ `projects/${project}/locations/${location}/jobs/${name}`;
201
+
202
+ const toJobBody = (
203
+ news: JobProps,
204
+ desiredLabels: Record<string, string>,
205
+ ): run.GoogleCloudRunV2Job => ({
206
+ labels: desiredLabels,
207
+ ...(news.annotations ? { annotations: news.annotations } : {}),
208
+ ...(news.launchStage ? { launchStage: news.launchStage } : {}),
209
+ ...(news.binaryAuthorization
210
+ ? { binaryAuthorization: news.binaryAuthorization }
211
+ : {}),
212
+ ...(news.startExecutionToken
213
+ ? { startExecutionToken: news.startExecutionToken }
214
+ : {}),
215
+ ...(news.runExecutionToken
216
+ ? { runExecutionToken: news.runExecutionToken }
217
+ : {}),
218
+ template: news.template,
219
+ });
220
+
221
+ const toAttributes = (
222
+ j: run.GoogleCloudRunV2Job,
223
+ parent: { project: string; location: string; name: string },
224
+ ): JobAttributes => ({
225
+ name: parent.name,
226
+ uid: j.uid ?? "",
227
+ resourceName: j.name ?? fqName(parent.project, parent.location, parent.name),
228
+ project: parent.project,
229
+ location: parent.location,
230
+ generation: j.generation,
231
+ observedGeneration: j.observedGeneration,
232
+ terminalCondition: j.terminalCondition,
233
+ executionCount: j.executionCount,
234
+ latestCreatedExecution: j.latestCreatedExecution,
235
+ reconciling: j.reconciling,
236
+ etag: j.etag,
237
+ labels: { ...(j.labels ?? {}) },
238
+ createTime: j.createTime,
239
+ updateTime: j.updateTime,
240
+ });
241
+
242
+ /**
243
+ * Decide whether anything mutable on the Job changed since the last
244
+ * reconcile. Job's `patch` has no `updateMask` parameter — the server
245
+ * diffs the full body — so we just emit a single "changed / unchanged"
246
+ * verdict and re-send the whole body if it differs.
247
+ *
248
+ * Labels go through `diffTags` (consistent with every other GCP
249
+ * resource here); everything else is a `deepEqual` on the relevant
250
+ * field. The `template` deep-equal is the load-bearing check —
251
+ * Cloud Run injects server-side defaults into `template.template`
252
+ * (e.g. `maxRetries: 3` when omitted), so the observed template may
253
+ * have keys we never sent. Deep-equal on the OBSERVED side ⊆ NEWS
254
+ * side is too strict; we rely on the user re-sending equivalent
255
+ * inputs across reconciles so observed==news after the first patch.
256
+ */
257
+ const jobMutated = (
258
+ observed: run.GoogleCloudRunV2Job,
259
+ news: JobProps,
260
+ desiredLabels: Record<string, string>,
261
+ ): boolean => {
262
+ const labelDiff = diffTags(
263
+ { ...(observed.labels ?? {}) },
264
+ desiredLabels,
265
+ );
266
+ if (labelDiff.removed.length > 0 || labelDiff.upsert.length > 0) return true;
267
+ if (!deepEqual(observed.annotations ?? {}, news.annotations ?? {})) return true;
268
+ if (news.launchStage !== undefined && observed.launchStage !== news.launchStage) {
269
+ return true;
270
+ }
271
+ if (
272
+ news.binaryAuthorization &&
273
+ !deepEqual(observed.binaryAuthorization, news.binaryAuthorization)
274
+ ) {
275
+ return true;
276
+ }
277
+ if (
278
+ news.startExecutionToken !== undefined &&
279
+ observed.startExecutionToken !== news.startExecutionToken
280
+ ) {
281
+ return true;
282
+ }
283
+ if (
284
+ news.runExecutionToken !== undefined &&
285
+ observed.runExecutionToken !== news.runExecutionToken
286
+ ) {
287
+ return true;
288
+ }
289
+ if (!deepEqual(observed.template, news.template)) return true;
290
+ return false;
291
+ };
292
+
293
+ export const JobProvider = () =>
294
+ Provider.effect(
295
+ Job,
296
+ Effect.gen(function* () {
297
+ const getJob = yield* run.getProjectsLocationsJobs;
298
+ const createJob = yield* run.createProjectsLocationsJobs;
299
+ const patchJob = yield* run.patchProjectsLocationsJobs;
300
+ const deleteJob = yield* run.deleteProjectsLocationsJobs;
301
+ const getOperation = yield* run.getProjectsLocationsOperations;
302
+ const getIamPolicy = yield* run.getIamPolicyProjectsLocationsJobs;
303
+ const setIamPolicy = yield* run.setIamPolicyProjectsLocationsJobs;
304
+ const awaitOperation = makeAwaitOperation(getOperation);
305
+ const syncIam = makeSyncIam({ getIamPolicy, setIamPolicy });
306
+
307
+ const observe = (project: string, location: string, name: string) =>
308
+ getJob({ name: fqName(project, location, name) }).pipe(
309
+ Effect.catchTag("NotFound", () =>
310
+ Effect.succeed(undefined as run.GoogleCloudRunV2Job | undefined),
311
+ ),
312
+ Effect.catchTag("Forbidden", () =>
313
+ Effect.succeed(undefined as run.GoogleCloudRunV2Job | undefined),
314
+ ),
315
+ );
316
+
317
+ const syncMutable = Effect.fn(function* (args: {
318
+ name: string;
319
+ observed: run.GoogleCloudRunV2Job;
320
+ news: JobProps;
321
+ desiredLabels: Record<string, string>;
322
+ session: ScopedPlanStatusSession;
323
+ }) {
324
+ if (!jobMutated(args.observed, args.news, args.desiredLabels)) return;
325
+ const bodyWithEtag: run.GoogleCloudRunV2Job = {
326
+ ...toJobBody(args.news, args.desiredLabels),
327
+ ...(args.observed.etag ? { etag: args.observed.etag } : {}),
328
+ };
329
+ const op = yield* patchJob({
330
+ name: args.name,
331
+ body: bodyWithEtag,
332
+ }).pipe(
333
+ Effect.catchTag("BadRequest", reshapeBadRequest("Job", "patch")),
334
+ );
335
+ if (op.name) yield* awaitOperation(op.name, args.session);
336
+ });
337
+
338
+ return {
339
+ stables: ["name", "uid", "resourceName", "project", "location"],
340
+ diff: Effect.fn(function* ({ news, olds = {} }) {
341
+ if (!isResolved(news)) return undefined;
342
+ if (
343
+ somePropsAreDifferent(olds as JobProps, news, [
344
+ "project",
345
+ "location",
346
+ "name",
347
+ ])
348
+ ) {
349
+ return { action: "replace" } as const;
350
+ }
351
+ return undefined;
352
+ }),
353
+ reconcile: Effect.fn(function* ({ id, news, session, bindings }) {
354
+ const internalLabels = yield* gcpInternalLabels(id);
355
+ const desiredName =
356
+ news.name ??
357
+ (yield* createPhysicalName({ id, maxLength: 49 })).toLowerCase();
358
+
359
+ yield* validateRunName("Job", desiredName);
360
+ yield* validateLabels(news.labels);
361
+ yield* validateAnnotations(news.annotations);
362
+ // Job container constraint lives one level deeper (inside the
363
+ // ExecutionTemplate's TaskTemplate).
364
+ yield* validateContainers("Job", news.template.template?.containers);
365
+
366
+ const parent = `projects/${news.project}/locations/${news.location}`;
367
+ const name = fqName(news.project, news.location, desiredName);
368
+ const desiredLabels: Record<string, string> = {
369
+ ...(news.labels ?? {}),
370
+ ...internalLabels,
371
+ };
372
+
373
+ let observed = yield* observe(news.project, news.location, desiredName);
374
+
375
+ if (!observed) {
376
+ const op = yield* createJob({
377
+ parent,
378
+ jobId: desiredName,
379
+ body: toJobBody(news, desiredLabels),
380
+ }).pipe(
381
+ Effect.retry({
382
+ while: (e: { _tag?: string; message?: string }) =>
383
+ e?._tag === "Forbidden" &&
384
+ /enabled this API recently|has not been used/i.test(
385
+ e.message ?? "",
386
+ ),
387
+ schedule: Schedule.spaced(Duration.seconds(15)).pipe(
388
+ Schedule.both(Schedule.recurs(20)),
389
+ Schedule.tapOutput(() =>
390
+ session.note(
391
+ "Waiting for Cloud Run API enablement to propagate…",
392
+ ),
393
+ ),
394
+ ),
395
+ }),
396
+ Effect.catchTag("Conflict", () =>
397
+ Effect.succeed(
398
+ undefined as run.GoogleLongrunningOperation | undefined,
399
+ ),
400
+ ),
401
+ Effect.catchTag("BadRequest", reshapeBadRequest("Job", "create")),
402
+ );
403
+ if (op?.name) yield* awaitOperation(op.name, session);
404
+ observed = yield* getJob({ name });
405
+ }
406
+
407
+ yield* syncMutable({
408
+ name,
409
+ observed,
410
+ news,
411
+ desiredLabels,
412
+ session,
413
+ });
414
+
415
+ yield* syncIam({ resource: name, bindings });
416
+
417
+ const final = yield* getJob({ name });
418
+ return toAttributes(final, {
419
+ project: news.project,
420
+ location: news.location,
421
+ name: desiredName,
422
+ });
423
+ }),
424
+ delete: Effect.fn(function* ({ output, session }) {
425
+ const name = fqName(output.project, output.location, output.name);
426
+ yield* deleteJob({
427
+ name,
428
+ ...(output.etag ? { etag: output.etag } : {}),
429
+ }).pipe(
430
+ Effect.flatMap((op) =>
431
+ op.name ? awaitOperation(op.name, session) : Effect.succeed(op),
432
+ ),
433
+ Effect.catchTag("NotFound", () => Effect.void),
434
+ );
435
+ }),
436
+ read: Effect.fn(function* ({ id, output, olds }) {
437
+ const project = output?.project ?? olds?.project;
438
+ const location = output?.location ?? olds?.location;
439
+ if (!project || !location) return undefined;
440
+ const name =
441
+ output?.name ??
442
+ olds?.name ??
443
+ (yield* createPhysicalName({ id, maxLength: 49 })).toLowerCase();
444
+ const observed = yield* observe(project, location, name);
445
+ if (!observed) return undefined;
446
+ const attrs = toAttributes(observed, { project, location, name });
447
+ return (yield* hasAlchemyLabels(id, observed.labels))
448
+ ? attrs
449
+ : Unowned(attrs);
450
+ }),
451
+ };
452
+ }),
453
+ );
@@ -0,0 +1,77 @@
1
+ import { ConfigError } from "@distilled.cloud/gcp";
2
+ import * as run from "@distilled.cloud/gcp/run-v2";
3
+ import type { ScopedPlanStatusSession } from "alchemy/Cli/Cli";
4
+ import * as Duration from "effect/Duration";
5
+ import * as Effect from "effect/Effect";
6
+ import * as Schedule from "effect/Schedule";
7
+
8
+ /**
9
+ * Resolved callable signature of `run.getProjectsLocationsOperations`.
10
+ *
11
+ * `run.getProjectsLocationsOperations` is itself an
12
+ * `Effect<callable, never, Credentials | HttpClient>`, so `Effect.Success`
13
+ * extracts the callable type — what you get back from
14
+ * `yield* run.getProjectsLocationsOperations`. Using a derived alias
15
+ * keeps the helper aligned with the SDK without us hand-writing the
16
+ * input/output/error union, which would drift if the patch set changes.
17
+ */
18
+ type GetOperations = Effect.Success<typeof run.getProjectsLocationsOperations>;
19
+
20
+ /**
21
+ * Build the Cloud Run long-running-operation polling helper.
22
+ *
23
+ * Cloud Run `Operation`s use the standard `GoogleLongrunningOperation`
24
+ * shape — doneness is `.done === true` (NOT `.status === "DONE"` like
25
+ * the GKE Container API). Verified at
26
+ * `vendor/distilled/packages/gcp/src/services/run-v2.ts:2880–2900`.
27
+ *
28
+ * Operation names returned by run-v2 (`createProjectsLocationsServices`,
29
+ * `patchProjectsLocationsServices`, `deleteProjectsLocationsServices`)
30
+ * are already fully qualified
31
+ * (`projects/{p}/locations/{l}/operations/{id}`), so callers pass them
32
+ * straight through to `getProjectsLocationsOperations` — no `qualifyOp`
33
+ * dance needed (unlike Container, which returns bare ids).
34
+ *
35
+ * Schedule: exponential 1s → 1.5× growth, capped per-poll at 10s via
36
+ * `Schedule.either`, then a hard count cap of 60 retries via
37
+ * `Schedule.both(Schedule.recurs(60))` → ~10 min wall ceiling. Cloud
38
+ * Run create/patch typically completes in seconds to a couple minutes,
39
+ * with the long pole being container image pulls.
40
+ *
41
+ * The helper is a factory — the caller resolves
42
+ * `run.getProjectsLocationsOperations` once at provider construction
43
+ * (see `Container/Operations.ts` for the same idiom) and passes the
44
+ * resulting callable here, so we never re-resolve services on each
45
+ * await.
46
+ */
47
+ export const makeAwaitOperation = (getOperations: GetOperations) =>
48
+ Effect.fn(function* (
49
+ operationName: string,
50
+ session: ScopedPlanStatusSession,
51
+ ) {
52
+ const op = yield* getOperations({ name: operationName }).pipe(
53
+ Effect.flatMap((current) =>
54
+ current.done === true
55
+ ? Effect.succeed(current)
56
+ : Effect.fail({ _tag: "OperationPending" as const }),
57
+ ),
58
+ Effect.retry({
59
+ while: (e: { _tag?: string }) => e?._tag === "OperationPending",
60
+ schedule: Schedule.exponential(Duration.seconds(1), 1.5).pipe(
61
+ Schedule.either(Schedule.spaced(Duration.seconds(10))),
62
+ Schedule.both(Schedule.recurs(60)),
63
+ Schedule.tapOutput(() =>
64
+ session.note(`Waiting for Cloud Run operation ${operationName}…`),
65
+ ),
66
+ ),
67
+ }),
68
+ );
69
+ if (op.error) {
70
+ return yield* new ConfigError({
71
+ message: `Cloud Run operation ${operationName} failed: ${
72
+ op.error.message ?? JSON.stringify(op.error)
73
+ }`,
74
+ });
75
+ }
76
+ return op;
77
+ });