@microagi/alchemy-gcp 0.2.1 → 0.5.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 (107) hide show
  1. package/CHANGELOG.md +165 -0
  2. package/README.md +54 -2
  3. package/lib/ArtifactRegistry/Operations.d.ts +47 -0
  4. package/lib/ArtifactRegistry/Operations.d.ts.map +1 -0
  5. package/lib/ArtifactRegistry/Operations.js +47 -0
  6. package/lib/ArtifactRegistry/Operations.js.map +1 -0
  7. package/lib/ArtifactRegistry/Repository.d.ts +263 -0
  8. package/lib/ArtifactRegistry/Repository.d.ts.map +1 -0
  9. package/lib/ArtifactRegistry/Repository.js +257 -0
  10. package/lib/ArtifactRegistry/Repository.js.map +1 -0
  11. package/lib/ArtifactRegistry/Types.d.ts +32 -0
  12. package/lib/ArtifactRegistry/Types.d.ts.map +1 -0
  13. package/lib/ArtifactRegistry/Types.js +12 -0
  14. package/lib/ArtifactRegistry/Types.js.map +1 -0
  15. package/lib/ArtifactRegistry/Validation.d.ts +43 -0
  16. package/lib/ArtifactRegistry/Validation.d.ts.map +1 -0
  17. package/lib/ArtifactRegistry/Validation.js +95 -0
  18. package/lib/ArtifactRegistry/Validation.js.map +1 -0
  19. package/lib/ArtifactRegistry/index.d.ts +4 -0
  20. package/lib/ArtifactRegistry/index.d.ts.map +1 -0
  21. package/lib/ArtifactRegistry/index.js +2 -0
  22. package/lib/ArtifactRegistry/index.js.map +1 -0
  23. package/lib/Providers.d.ts.map +1 -1
  24. package/lib/Providers.js +13 -1
  25. package/lib/Providers.js.map +1 -1
  26. package/lib/Run/IamMember.d.ts +70 -0
  27. package/lib/Run/IamMember.d.ts.map +1 -0
  28. package/lib/Run/IamMember.js +65 -0
  29. package/lib/Run/IamMember.js.map +1 -0
  30. package/lib/Run/IamSync.d.ts +80 -0
  31. package/lib/Run/IamSync.d.ts.map +1 -0
  32. package/lib/Run/IamSync.js +73 -0
  33. package/lib/Run/IamSync.js.map +1 -0
  34. package/lib/Run/Job.d.ts +167 -0
  35. package/lib/Run/Job.d.ts.map +1 -0
  36. package/lib/Run/Job.js +199 -0
  37. package/lib/Run/Job.js.map +1 -0
  38. package/lib/Run/Operations.d.ts +47 -0
  39. package/lib/Run/Operations.d.ts.map +1 -0
  40. package/lib/Run/Operations.js +46 -0
  41. package/lib/Run/Operations.js.map +1 -0
  42. package/lib/Run/Service.d.ts +193 -0
  43. package/lib/Run/Service.d.ts.map +1 -0
  44. package/lib/Run/Service.js +247 -0
  45. package/lib/Run/Service.js.map +1 -0
  46. package/lib/Run/Validation.d.ts +54 -0
  47. package/lib/Run/Validation.d.ts.map +1 -0
  48. package/lib/Run/Validation.js +129 -0
  49. package/lib/Run/Validation.js.map +1 -0
  50. package/lib/Run/index.d.ts +51 -0
  51. package/lib/Run/index.d.ts.map +1 -0
  52. package/lib/Run/index.js +4 -0
  53. package/lib/Run/index.js.map +1 -0
  54. package/lib/Sqladmin/Database.d.ts +82 -0
  55. package/lib/Sqladmin/Database.d.ts.map +1 -0
  56. package/lib/Sqladmin/Database.js +87 -0
  57. package/lib/Sqladmin/Database.js.map +1 -0
  58. package/lib/Sqladmin/Instance.d.ts +234 -0
  59. package/lib/Sqladmin/Instance.d.ts.map +1 -0
  60. package/lib/Sqladmin/Instance.js +251 -0
  61. package/lib/Sqladmin/Instance.js.map +1 -0
  62. package/lib/Sqladmin/Operations.d.ts +41 -0
  63. package/lib/Sqladmin/Operations.d.ts.map +1 -0
  64. package/lib/Sqladmin/Operations.js +42 -0
  65. package/lib/Sqladmin/Operations.js.map +1 -0
  66. package/lib/Sqladmin/Types.d.ts +82 -0
  67. package/lib/Sqladmin/Types.d.ts.map +1 -0
  68. package/lib/Sqladmin/Types.js +28 -0
  69. package/lib/Sqladmin/Types.js.map +1 -0
  70. package/lib/Sqladmin/User.d.ts +110 -0
  71. package/lib/Sqladmin/User.d.ts.map +1 -0
  72. package/lib/Sqladmin/User.js +156 -0
  73. package/lib/Sqladmin/User.js.map +1 -0
  74. package/lib/Sqladmin/Validation.d.ts +60 -0
  75. package/lib/Sqladmin/Validation.d.ts.map +1 -0
  76. package/lib/Sqladmin/Validation.js +125 -0
  77. package/lib/Sqladmin/Validation.js.map +1 -0
  78. package/lib/Sqladmin/index.d.ts +9 -0
  79. package/lib/Sqladmin/index.d.ts.map +1 -0
  80. package/lib/Sqladmin/index.js +5 -0
  81. package/lib/Sqladmin/index.js.map +1 -0
  82. package/lib/index.d.ts +3 -0
  83. package/lib/index.d.ts.map +1 -1
  84. package/lib/index.js +3 -0
  85. package/lib/index.js.map +1 -1
  86. package/package.json +5 -4
  87. package/src/ArtifactRegistry/Operations.ts +79 -0
  88. package/src/ArtifactRegistry/Repository.ts +624 -0
  89. package/src/ArtifactRegistry/Types.ts +49 -0
  90. package/src/ArtifactRegistry/Validation.ts +112 -0
  91. package/src/ArtifactRegistry/index.ts +10 -0
  92. package/src/Providers.ts +21 -0
  93. package/src/Run/IamMember.ts +79 -0
  94. package/src/Run/IamSync.ts +134 -0
  95. package/src/Run/Job.ts +453 -0
  96. package/src/Run/Operations.ts +77 -0
  97. package/src/Run/Service.ts +541 -0
  98. package/src/Run/Validation.ts +153 -0
  99. package/src/Run/index.ts +52 -0
  100. package/src/Sqladmin/Database.ts +209 -0
  101. package/src/Sqladmin/Instance.ts +620 -0
  102. package/src/Sqladmin/Operations.ts +73 -0
  103. package/src/Sqladmin/Types.ts +101 -0
  104. package/src/Sqladmin/User.ts +333 -0
  105. package/src/Sqladmin/Validation.ts +148 -0
  106. package/src/Sqladmin/index.ts +19 -0
  107. package/src/index.ts +3 -0
@@ -0,0 +1,620 @@
1
+ import * as sql from "@distilled.cloud/gcp/sqladmin-v1";
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 Redacted from "effect/Redacted";
12
+ import * as Schedule from "effect/Schedule";
13
+ import type * as GCP from "../Providers.ts";
14
+ import { gcpInternalLabels, hasAlchemyLabels } from "../Tags.ts";
15
+ import { makeAwaitOperation } from "./Operations.ts";
16
+ import type {
17
+ PostgresVersion,
18
+ SqlActivationPolicy,
19
+ SqlAvailabilityType,
20
+ SqlDataDiskType,
21
+ SqlEdition,
22
+ } from "./Types.ts";
23
+ import { reshapeBadRequest, validateInstanceName } from "./Validation.ts";
24
+
25
+ /**
26
+ * A Cloud SQL for Postgres instance.
27
+ *
28
+ * **Resource model.** A Cloud SQL instance bundles the storage volume,
29
+ * compute tier, networking (public IP / VPC private IP via PSA), and
30
+ * managed backups. Databases (`GCP.SqlDatabase`) and users
31
+ * (`GCP.SqlUser`) hang off it and are modelled as separate resources.
32
+ *
33
+ * **Lifecycle.** observe → ensure (insert; retry on the "API not yet
34
+ * enabled" 403 propagation race) → sync (patch top-level fields, with
35
+ * `settingsVersion` round-trip for optimistic concurrency) → return.
36
+ *
37
+ * **Replace triggers.** `project`, `region`, `name`, `databaseVersion`.
38
+ * Everything else — tier, disk size, IP config, backup config — is
39
+ * in-place via `patch`.
40
+ *
41
+ * **Optimistic concurrency.** Cloud SQL uses `settings.settingsVersion`
42
+ * (NOT `etag` — etag is deprecated). Every patch reads the live
43
+ * instance and threads the observed `settingsVersion` through the
44
+ * body. Concurrent edits surface as `Conflict`.
45
+ *
46
+ * **Adoption.** Label-gated: an instance whose `settings.userLabels`
47
+ * lack our `alchemy_*` keys is wrapped in `Unowned(attrs)` from
48
+ * `read`, forcing `--adopt` before takeover.
49
+ *
50
+ * **Deletion protection.** When `settings.deletionProtectionEnabled`
51
+ * is `true`, alchemy `destroy` will fail with a `BadRequest`. Set the
52
+ * flag to `false` in a separate deploy (which patches the instance),
53
+ * then re-run destroy.
54
+ *
55
+ * @example Minimal private-IP Postgres 17 instance on a Shared VPC
56
+ * ```typescript
57
+ * const db = yield* GCP.SqlInstance("Primary", {
58
+ * project: project.projectId,
59
+ * region: "europe-west4",
60
+ * databaseVersion: "POSTGRES_17",
61
+ * settings: {
62
+ * tier: "db-custom-2-7680",
63
+ * edition: "ENTERPRISE",
64
+ * dataDiskSizeGb: 50,
65
+ * ipConfiguration: {
66
+ * ipv4Enabled: false,
67
+ * privateNetwork: hostVpc.selfLink,
68
+ * },
69
+ * backupConfiguration: { enabled: true, pointInTimeRecoveryEnabled: true },
70
+ * },
71
+ * });
72
+ * ```
73
+ *
74
+ * @see https://cloud.google.com/sql/docs/postgres/admin-api/rest/v1/instances
75
+ */
76
+ export type SqlInstanceProps = {
77
+ /**
78
+ * GCP project ID hosting the instance. Immutable — replace if changed.
79
+ * @see https://cloud.google.com/sql/docs/postgres/admin-api/rest/v1/instances#SqlInstance
80
+ */
81
+ project: string;
82
+ /**
83
+ * Cloud SQL region (e.g. `europe-west4`). Cloud SQL is regional;
84
+ * zonality is configured inside `settings.availabilityType`.
85
+ * Immutable — replace if changed.
86
+ * @see https://cloud.google.com/sql/docs/postgres/locations
87
+ */
88
+ region: string;
89
+ /**
90
+ * Instance name. Defaults to `createPhysicalName({ id, lowercase:
91
+ * true, maxLength: 98 })`. Lowercase letters/digits/hyphens; begin
92
+ * with a letter, no trailing hyphen; 1–98 chars. Immutable — replace.
93
+ * @see https://cloud.google.com/sql/docs/postgres/admin-api/rest/v1/instances#SqlInstance
94
+ */
95
+ name?: string;
96
+ /**
97
+ * Postgres engine version. Immutable — Cloud SQL exposes major
98
+ * version *upgrades* via a separate `upgrade` operation, not via
99
+ * `patch`. Surfacing it as immutable here forces an explicit replace
100
+ * (or out-of-band upgrade) for clarity.
101
+ * @see https://cloud.google.com/sql/docs/postgres/db-versions
102
+ */
103
+ databaseVersion: PostgresVersion;
104
+ /**
105
+ * Initial Postgres `postgres` superuser password. Only set on
106
+ * insert; ignored on subsequent patches (Cloud SQL silently drops
107
+ * `rootPassword` on patch). Typically omitted on IAM-only stacks
108
+ * since the `postgres` role is unused.
109
+ * @see https://cloud.google.com/sql/docs/postgres/create-manage-users#user-root
110
+ */
111
+ rootPassword?: Redacted.Redacted<string>;
112
+ /**
113
+ * Resource labels. Alchemy internal labels (`alchemy_app`,
114
+ * `alchemy_stage`, `alchemy_id`) are merged on top automatically.
115
+ * Cloud SQL stores user labels under `settings.userLabels`; we
116
+ * surface them at the top level for symmetry with other GCP
117
+ * resources. Mutable via `patch`.
118
+ * @see https://cloud.google.com/sql/docs/postgres/label-instance
119
+ */
120
+ labels?: Record<string, string>;
121
+ /** Instance settings (tier, disk, IP, backups, …). Mostly mutable via `patch`. */
122
+ settings: {
123
+ /**
124
+ * Machine tier (`db-custom-{vCPU}-{memMiB}`, `db-f1-micro`,
125
+ * `db-perf-optimized-*`). Mutable via `patch` (causes a restart).
126
+ * @see https://cloud.google.com/sql/docs/postgres/instance-settings
127
+ */
128
+ tier: string;
129
+ /**
130
+ * Cloud SQL edition. `ENTERPRISE_PLUS` is required for
131
+ * Data Cache + the `db-perf-optimized-*` tiers. Mutable via
132
+ * `patch` (some transitions require a restart).
133
+ * @see https://cloud.google.com/sql/docs/postgres/editions-intro
134
+ */
135
+ edition?: SqlEdition;
136
+ /**
137
+ * Storage size in GB. Mutable via `patch`; can only grow, not
138
+ * shrink (shrink requires a side-channel operation).
139
+ * @see https://cloud.google.com/sql/docs/postgres/instance-settings#storage-capacity-2ndgen
140
+ */
141
+ dataDiskSizeGb?: number;
142
+ /**
143
+ * Disk type. `PD_SSD` is the default; `PD_HDD` is legacy.
144
+ * Immutable in practice — Cloud SQL rejects type changes on patch.
145
+ * @see https://cloud.google.com/sql/docs/postgres/instance-settings#storage-type-2ndgen
146
+ */
147
+ dataDiskType?: SqlDataDiskType;
148
+ /** Auto-grow the data disk when nearing full. Mutable via `patch`. */
149
+ diskAutoresize?: boolean;
150
+ /** Cap on auto-grown size, in GB. Mutable via `patch`. */
151
+ diskAutoresizeLimit?: number;
152
+ /** Networking — public IP, private IP via PSA, or both. Mutable via `patch`. */
153
+ ipConfiguration?: {
154
+ /**
155
+ * VPC selfLink (`https://www.googleapis.com/compute/v1/projects/{p}/global/networks/{n}`)
156
+ * to attach the private IP to. The VPC must already have a PSA
157
+ * peering with `servicenetworking.googleapis.com`. Immutable
158
+ * after first set (Cloud SQL refuses to change the private network).
159
+ * @see https://cloud.google.com/sql/docs/postgres/private-ip
160
+ */
161
+ privateNetwork?: string;
162
+ /** Enable a public IPv4 endpoint. Mutable via `patch`. */
163
+ ipv4Enabled?: boolean;
164
+ /**
165
+ * Allow Google-managed services (BigQuery, Vertex AI, etc.) to
166
+ * reach the private IP over Google's backbone. Mutable via `patch`.
167
+ */
168
+ enablePrivatePathForGoogleCloudServices?: boolean;
169
+ /** Require SSL/TLS on all connections. Mutable via `patch`. */
170
+ requireSsl?: boolean;
171
+ };
172
+ /** Backup window + retention settings. Mutable via `patch`. */
173
+ backupConfiguration?: {
174
+ /** Enable automated daily backups. Mutable via `patch`. */
175
+ enabled?: boolean;
176
+ /** Enable PITR (write-ahead log archiving). Mutable via `patch`. */
177
+ pointInTimeRecoveryEnabled?: boolean;
178
+ /** Backup start time in UTC, `HH:MM` 24-hour. Mutable via `patch`. */
179
+ startTime?: string;
180
+ /** WAL retention window (1–7 days). Mutable via `patch`. */
181
+ transactionLogRetentionDays?: number;
182
+ };
183
+ /**
184
+ * Postgres flags (e.g. `shared_buffers`, `max_connections`).
185
+ * Mutable via `patch`; some flags trigger a restart.
186
+ * @see https://cloud.google.com/sql/docs/postgres/flags
187
+ */
188
+ databaseFlags?: ReadonlyArray<{ name: string; value: string }>;
189
+ /**
190
+ * Block alchemy from deleting the instance via the API. Disable
191
+ * before running destroy.
192
+ * @see https://cloud.google.com/sql/docs/postgres/deletion-protection
193
+ */
194
+ deletionProtectionEnabled?: boolean;
195
+ /** Park (`NEVER`) or run (`ALWAYS`) the instance. Mutable via `patch`. */
196
+ activationPolicy?: SqlActivationPolicy;
197
+ /**
198
+ * `ZONAL` = single zone; `REGIONAL` = HA standby in a second zone.
199
+ * Mutable via `patch` (transitions to/from `REGIONAL` take ~10 min).
200
+ * @see https://cloud.google.com/sql/docs/postgres/high-availability
201
+ */
202
+ availabilityType?: SqlAvailabilityType;
203
+ };
204
+ };
205
+
206
+ export type SqlInstanceIpAddress = {
207
+ /** Address class — `PRIMARY` (public), `PRIVATE`, or `OUTGOING`. */
208
+ type: string | undefined;
209
+ /** The IP itself. */
210
+ ipAddress: string | undefined;
211
+ };
212
+
213
+ export type SqlInstanceAttributes = {
214
+ /** Bare instance name (no `projects/.../instances/` prefix). */
215
+ name: string;
216
+ /** Server-defined URL for the instance. */
217
+ selfLink: string;
218
+ /** GCP project ID. */
219
+ project: string;
220
+ /** Region. */
221
+ region: string;
222
+ /**
223
+ * `project:region:name` — the canonical identifier the Cloud SQL
224
+ * Auth Proxy and the IAM authn token exchange both consume.
225
+ */
226
+ connectionName: string;
227
+ /** Echoed Postgres version (e.g. `POSTGRES_17`). */
228
+ databaseVersion: string;
229
+ /** Lifecycle state — `RUNNABLE` once ready. */
230
+ state: string;
231
+ /** All IPs Cloud SQL has assigned. */
232
+ ipAddresses: ReadonlyArray<SqlInstanceIpAddress>;
233
+ /** Convenience: first `PRIVATE` IP, if any. */
234
+ privateIpAddress: string | undefined;
235
+ /** Convenience: first `PRIMARY` (public) IP, if any. */
236
+ publicIpAddress: string | undefined;
237
+ /** Server CA cert; useful for pinning TLS roots from a client. */
238
+ serverCaCert:
239
+ | {
240
+ cert: string | undefined;
241
+ commonName: string | undefined;
242
+ expirationTime: string | undefined;
243
+ sha1Fingerprint: string | undefined;
244
+ }
245
+ | undefined;
246
+ /** Monotonic optimistic-concurrency token — round-tripped on patch. */
247
+ settingsVersion: string | undefined;
248
+ /** Labels currently set, including alchemy internals. */
249
+ labels: Record<string, string>;
250
+ };
251
+
252
+ export type SqlInstance = Resource<
253
+ "GCP.SqlInstance",
254
+ SqlInstanceProps,
255
+ SqlInstanceAttributes,
256
+ never,
257
+ GCP.Providers
258
+ >;
259
+ export const SqlInstance = Resource<SqlInstance>("GCP.SqlInstance");
260
+
261
+ const toAddress = (m: sql.IpMapping): SqlInstanceIpAddress => ({
262
+ type: m.type,
263
+ ipAddress: m.ipAddress,
264
+ });
265
+
266
+ const toAttributes = (
267
+ i: sql.DatabaseInstance,
268
+ parent: { project: string; region: string; name: string },
269
+ ): SqlInstanceAttributes => {
270
+ const ipAddresses = (i.ipAddresses ?? []).map(toAddress);
271
+ return {
272
+ name: parent.name,
273
+ selfLink: i.selfLink ?? "",
274
+ project: parent.project,
275
+ region: parent.region,
276
+ connectionName:
277
+ i.connectionName ?? `${parent.project}:${parent.region}:${parent.name}`,
278
+ databaseVersion: i.databaseVersion ?? "",
279
+ state: i.state ?? "",
280
+ ipAddresses,
281
+ privateIpAddress: ipAddresses.find((a) => a.type === "PRIVATE")?.ipAddress,
282
+ publicIpAddress: ipAddresses.find((a) => a.type === "PRIMARY")?.ipAddress,
283
+ serverCaCert: i.serverCaCert
284
+ ? {
285
+ cert: i.serverCaCert.cert,
286
+ commonName: i.serverCaCert.commonName,
287
+ expirationTime: i.serverCaCert.expirationTime,
288
+ sha1Fingerprint: i.serverCaCert.sha1Fingerprint,
289
+ }
290
+ : undefined,
291
+ settingsVersion: i.settings?.settingsVersion,
292
+ labels: { ...(i.settings?.userLabels ?? {}) },
293
+ };
294
+ };
295
+
296
+ /**
297
+ * Build the `Settings` body sent to the API.
298
+ *
299
+ * Only sets fields the user has populated, so distinct from a settings
300
+ * stanza diff: server-injected defaults aren't overwritten by an
301
+ * `undefined` from us.
302
+ */
303
+ const toSettingsBody = (
304
+ s: SqlInstanceProps["settings"],
305
+ userLabels: Record<string, string>,
306
+ settingsVersion?: string,
307
+ ): sql.Settings => ({
308
+ tier: s.tier,
309
+ userLabels,
310
+ ...(s.edition ? { edition: s.edition } : {}),
311
+ ...(s.dataDiskSizeGb !== undefined
312
+ ? { dataDiskSizeGb: String(s.dataDiskSizeGb) }
313
+ : {}),
314
+ ...(s.dataDiskType ? { dataDiskType: s.dataDiskType } : {}),
315
+ ...(s.diskAutoresize !== undefined
316
+ ? { storageAutoResize: s.diskAutoresize }
317
+ : {}),
318
+ ...(s.diskAutoresizeLimit !== undefined
319
+ ? { storageAutoResizeLimit: String(s.diskAutoresizeLimit) }
320
+ : {}),
321
+ ...(s.ipConfiguration
322
+ ? {
323
+ ipConfiguration: {
324
+ ...(s.ipConfiguration.ipv4Enabled !== undefined
325
+ ? { ipv4Enabled: s.ipConfiguration.ipv4Enabled }
326
+ : {}),
327
+ ...(s.ipConfiguration.privateNetwork
328
+ ? { privateNetwork: s.ipConfiguration.privateNetwork }
329
+ : {}),
330
+ ...(s.ipConfiguration.enablePrivatePathForGoogleCloudServices !==
331
+ undefined
332
+ ? {
333
+ enablePrivatePathForGoogleCloudServices:
334
+ s.ipConfiguration.enablePrivatePathForGoogleCloudServices,
335
+ }
336
+ : {}),
337
+ ...(s.ipConfiguration.requireSsl !== undefined
338
+ ? { requireSsl: s.ipConfiguration.requireSsl }
339
+ : {}),
340
+ },
341
+ }
342
+ : {}),
343
+ ...(s.backupConfiguration ? { backupConfiguration: s.backupConfiguration } : {}),
344
+ ...(s.databaseFlags ? { databaseFlags: s.databaseFlags } : {}),
345
+ ...(s.deletionProtectionEnabled !== undefined
346
+ ? { deletionProtectionEnabled: s.deletionProtectionEnabled }
347
+ : {}),
348
+ ...(s.activationPolicy ? { activationPolicy: s.activationPolicy } : {}),
349
+ ...(s.availabilityType ? { availabilityType: s.availabilityType } : {}),
350
+ ...(settingsVersion !== undefined ? { settingsVersion } : {}),
351
+ });
352
+
353
+ export const SqlInstanceProvider = () =>
354
+ Provider.effect(
355
+ SqlInstance,
356
+ Effect.gen(function* () {
357
+ const getInstances = yield* sql.getInstances;
358
+ const insertInstances = yield* sql.insertInstances;
359
+ const patchInstances = yield* sql.patchInstances;
360
+ const deleteInstances = yield* sql.deleteInstances;
361
+ const getOperations = yield* sql.getOperations;
362
+ const awaitOperation = makeAwaitOperation(getOperations);
363
+
364
+ const observe = (project: string, name: string) =>
365
+ getInstances({ project, instance: name }).pipe(
366
+ Effect.catchTag("NotFound", () =>
367
+ Effect.succeed(undefined as sql.DatabaseInstance | undefined),
368
+ ),
369
+ Effect.catchTag("Forbidden", () =>
370
+ Effect.succeed(undefined as sql.DatabaseInstance | undefined),
371
+ ),
372
+ );
373
+
374
+ const syncMutable = Effect.fn(function* (args: {
375
+ project: string;
376
+ name: string;
377
+ observed: sql.DatabaseInstance;
378
+ news: SqlInstanceProps;
379
+ desiredLabels: Record<string, string>;
380
+ session: ScopedPlanStatusSession;
381
+ }) {
382
+ const obsSettings = args.observed.settings ?? {};
383
+ const desiredSettingsForCompare = toSettingsBody(
384
+ args.news.settings,
385
+ args.desiredLabels,
386
+ );
387
+
388
+ // Per-field diff — settingsVersion is added below only if we
389
+ // actually need to patch, so it's not part of the no-op check.
390
+ let needPatch = false;
391
+ const reasons: string[] = [];
392
+ const compare = (key: string, a: unknown, b: unknown) => {
393
+ if (!deepEqual(a, b)) {
394
+ needPatch = true;
395
+ reasons.push(key);
396
+ }
397
+ };
398
+ compare("tier", obsSettings.tier, desiredSettingsForCompare.tier);
399
+ compare(
400
+ "edition",
401
+ obsSettings.edition,
402
+ desiredSettingsForCompare.edition,
403
+ );
404
+ compare(
405
+ "dataDiskSizeGb",
406
+ obsSettings.dataDiskSizeGb,
407
+ desiredSettingsForCompare.dataDiskSizeGb,
408
+ );
409
+ compare(
410
+ "dataDiskType",
411
+ obsSettings.dataDiskType,
412
+ desiredSettingsForCompare.dataDiskType,
413
+ );
414
+ compare(
415
+ "storageAutoResize",
416
+ obsSettings.storageAutoResize,
417
+ desiredSettingsForCompare.storageAutoResize,
418
+ );
419
+ compare(
420
+ "storageAutoResizeLimit",
421
+ obsSettings.storageAutoResizeLimit,
422
+ desiredSettingsForCompare.storageAutoResizeLimit,
423
+ );
424
+ compare(
425
+ "ipConfiguration",
426
+ obsSettings.ipConfiguration,
427
+ desiredSettingsForCompare.ipConfiguration,
428
+ );
429
+ compare(
430
+ "backupConfiguration",
431
+ obsSettings.backupConfiguration,
432
+ desiredSettingsForCompare.backupConfiguration,
433
+ );
434
+ compare(
435
+ "databaseFlags",
436
+ obsSettings.databaseFlags ?? [],
437
+ desiredSettingsForCompare.databaseFlags ?? [],
438
+ );
439
+ compare(
440
+ "deletionProtectionEnabled",
441
+ obsSettings.deletionProtectionEnabled,
442
+ desiredSettingsForCompare.deletionProtectionEnabled,
443
+ );
444
+ compare(
445
+ "activationPolicy",
446
+ obsSettings.activationPolicy,
447
+ desiredSettingsForCompare.activationPolicy,
448
+ );
449
+ compare(
450
+ "availabilityType",
451
+ obsSettings.availabilityType,
452
+ desiredSettingsForCompare.availabilityType,
453
+ );
454
+
455
+ const labelDiff = diffTags(
456
+ { ...(obsSettings.userLabels ?? {}) },
457
+ args.desiredLabels,
458
+ );
459
+ if (labelDiff.removed.length > 0 || labelDiff.upsert.length > 0) {
460
+ needPatch = true;
461
+ reasons.push("userLabels");
462
+ }
463
+
464
+ if (!needPatch) return;
465
+
466
+ // Thread the observed settingsVersion through the patch body
467
+ // — Cloud SQL uses it as the optimistic-concurrency token
468
+ // (etag is deprecated on this resource).
469
+ const body: sql.DatabaseInstance = {
470
+ settings: toSettingsBody(
471
+ args.news.settings,
472
+ args.desiredLabels,
473
+ obsSettings.settingsVersion,
474
+ ),
475
+ };
476
+ const op = yield* patchInstances({
477
+ project: args.project,
478
+ instance: args.name,
479
+ body,
480
+ }).pipe(
481
+ Effect.catchTag("BadRequest", reshapeBadRequest("Instance", "patch")),
482
+ );
483
+ if (op.name) yield* awaitOperation(args.project, op.name, args.session);
484
+ });
485
+
486
+ return {
487
+ stables: ["name", "selfLink", "project", "region", "connectionName"],
488
+ diff: Effect.fn(function* ({ news, olds = {} }) {
489
+ if (!isResolved(news)) return undefined;
490
+ if (
491
+ somePropsAreDifferent(olds as SqlInstanceProps, news, [
492
+ "project",
493
+ "region",
494
+ "name",
495
+ "databaseVersion",
496
+ ])
497
+ ) {
498
+ return { action: "replace" } as const;
499
+ }
500
+ return undefined;
501
+ }),
502
+ reconcile: Effect.fn(function* ({ id, news, session }) {
503
+ const internalLabels = yield* gcpInternalLabels(id);
504
+ const desiredName =
505
+ news.name ??
506
+ (yield* createPhysicalName({ id, maxLength: 98 })).toLowerCase();
507
+ yield* validateInstanceName(desiredName);
508
+
509
+ const desiredLabels: Record<string, string> = {
510
+ ...(news.labels ?? {}),
511
+ ...internalLabels,
512
+ };
513
+
514
+ // 1. Observe — collapse 403 to "missing" alongside 404.
515
+ let observed = yield* observe(news.project, desiredName);
516
+
517
+ // 2. Ensure — insert. Like Cloud Run / GKE, sqladmin can 403
518
+ // with "Cloud SQL Admin API has not been used in project
519
+ // ... If you enabled this API recently, wait …" for ~1–2
520
+ // minutes after ApiEnable lands. Retry the insert on that
521
+ // specific 403; other Forbidden cases propagate.
522
+ if (!observed) {
523
+ const op = yield* insertInstances({
524
+ project: news.project,
525
+ body: {
526
+ name: desiredName,
527
+ region: news.region,
528
+ databaseVersion: news.databaseVersion,
529
+ ...(news.rootPassword
530
+ ? { rootPassword: Redacted.value(news.rootPassword) }
531
+ : {}),
532
+ settings: toSettingsBody(news.settings, desiredLabels),
533
+ },
534
+ }).pipe(
535
+ Effect.retry({
536
+ while: (e: { _tag?: string; message?: string }) =>
537
+ e?._tag === "Forbidden" &&
538
+ /enabled this API recently|has not been used/i.test(
539
+ e.message ?? "",
540
+ ),
541
+ schedule: Schedule.spaced(Duration.seconds(15)).pipe(
542
+ Schedule.both(Schedule.recurs(20)),
543
+ Schedule.tapOutput(() =>
544
+ session.note(
545
+ "Waiting for Cloud SQL Admin API enablement to propagate…",
546
+ ),
547
+ ),
548
+ ),
549
+ }),
550
+ Effect.catchTag("Conflict", () =>
551
+ Effect.succeed(undefined as sql.Operation | undefined),
552
+ ),
553
+ Effect.catchTag(
554
+ "BadRequest",
555
+ reshapeBadRequest("Instance", "insert"),
556
+ ),
557
+ );
558
+ if (op?.name) yield* awaitOperation(news.project, op.name, session);
559
+ observed = yield* getInstances({
560
+ project: news.project,
561
+ instance: desiredName,
562
+ });
563
+ }
564
+
565
+ // 3. Sync — single patch with the full settings body when any
566
+ // field drifts. settingsVersion threaded through for OCC.
567
+ yield* syncMutable({
568
+ project: news.project,
569
+ name: desiredName,
570
+ observed,
571
+ news,
572
+ desiredLabels,
573
+ session,
574
+ });
575
+
576
+ const final = yield* getInstances({
577
+ project: news.project,
578
+ instance: desiredName,
579
+ });
580
+ return toAttributes(final, {
581
+ project: news.project,
582
+ region: news.region,
583
+ name: desiredName,
584
+ });
585
+ }),
586
+ delete: Effect.fn(function* ({ output, session }) {
587
+ yield* deleteInstances({
588
+ project: output.project,
589
+ instance: output.name,
590
+ }).pipe(
591
+ Effect.flatMap((op) =>
592
+ op.name
593
+ ? awaitOperation(output.project, op.name, session)
594
+ : Effect.succeed(op),
595
+ ),
596
+ Effect.catchTag("NotFound", () => Effect.void),
597
+ Effect.catchTag(
598
+ "BadRequest",
599
+ reshapeBadRequest("Instance", "delete"),
600
+ ),
601
+ );
602
+ }),
603
+ read: Effect.fn(function* ({ id, output, olds }) {
604
+ const project = output?.project ?? olds?.project;
605
+ const region = output?.region ?? olds?.region;
606
+ if (!project || !region) return undefined;
607
+ const name =
608
+ output?.name ??
609
+ olds?.name ??
610
+ (yield* createPhysicalName({ id, maxLength: 98 })).toLowerCase();
611
+ const observed = yield* observe(project, name);
612
+ if (!observed) return undefined;
613
+ const attrs = toAttributes(observed, { project, region, name });
614
+ return (yield* hasAlchemyLabels(id, observed.settings?.userLabels))
615
+ ? attrs
616
+ : Unowned(attrs);
617
+ }),
618
+ };
619
+ }),
620
+ );
@@ -0,0 +1,73 @@
1
+ import { ConfigError } from "@distilled.cloud/gcp";
2
+ import * as sql from "@distilled.cloud/gcp/sqladmin-v1";
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 `sql.getOperations`.
10
+ *
11
+ * `sql.getOperations` is itself an `Effect<callable, never, Credentials |
12
+ * HttpClient>`, so `Effect.Success` extracts the callable. Using a
13
+ * derived alias keeps the helper aligned with the SDK without us
14
+ * hand-writing the input/output/error union, which would drift if the
15
+ * patch set changes.
16
+ */
17
+ type GetOperations = Effect.Success<typeof sql.getOperations>;
18
+
19
+ /**
20
+ * Build the Cloud SQL Admin long-running-operation polling helper.
21
+ *
22
+ * Sqladmin `Operation`s carry `.status: "PENDING" | "RUNNING" | "DONE"`
23
+ * (NOT `.done: boolean` like Cloud Resource Manager / Cloud Run, and
24
+ * NOT `.status === "DONE"` against a different enum). Verified at
25
+ * `vendor/distilled/packages/gcp/src/services/sqladmin-v1.ts:606–612`.
26
+ *
27
+ * Unlike Cloud Run, Sqladmin operations are NOT fully-qualified path
28
+ * names — the API returns a bare operation id (e.g. `e9e88dca-...`),
29
+ * and `getOperations` takes `{ project, operation }`. Callers therefore
30
+ * pass the bare id alongside the parent project context.
31
+ *
32
+ * Schedule: exponential 1s → 1.5× growth, capped via the count cap of
33
+ * 60 retries → roughly a few minutes wall ceiling. Most Cloud SQL
34
+ * operations (CREATE_USER, CREATE_DATABASE, UPDATE settings) finish
35
+ * in 1–30 s; instance CREATE / patch involving a restart are the long
36
+ * pole at 4–10 min, so callers running those should be aware that
37
+ * recurs(60) may bottom out and surface as a retry budget exhaustion.
38
+ *
39
+ * @see https://cloud.google.com/sql/docs/postgres/admin-api/rest/v1/operations
40
+ */
41
+ export const makeAwaitOperation = (getOperations: GetOperations) =>
42
+ Effect.fn(function* (
43
+ project: string,
44
+ operationName: string,
45
+ session: ScopedPlanStatusSession,
46
+ ) {
47
+ const op = yield* getOperations({ project, operation: operationName }).pipe(
48
+ Effect.flatMap((current) =>
49
+ current.status === "DONE"
50
+ ? Effect.succeed(current)
51
+ : Effect.fail({ _tag: "OperationPending" as const }),
52
+ ),
53
+ Effect.retry({
54
+ while: (e: { _tag?: string }) => e?._tag === "OperationPending",
55
+ schedule: Schedule.exponential(Duration.seconds(1), 1.5).pipe(
56
+ Schedule.either(Schedule.spaced(Duration.seconds(10))),
57
+ Schedule.both(Schedule.recurs(60)),
58
+ Schedule.tapOutput(() =>
59
+ session.note(`Waiting for Cloud SQL operation ${operationName}…`),
60
+ ),
61
+ ),
62
+ }),
63
+ );
64
+ if (op.error) {
65
+ const firstErr = op.error.errors?.[0];
66
+ return yield* new ConfigError({
67
+ message: `Cloud SQL operation ${operationName} failed: ${
68
+ firstErr?.message ?? JSON.stringify(op.error)
69
+ }`,
70
+ });
71
+ }
72
+ return op;
73
+ });