@microagi/alchemy-gcp 0.5.1 → 0.7.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 (80) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/lib/Auth/Credentials.d.ts +10 -4
  3. package/lib/Auth/Credentials.d.ts.map +1 -1
  4. package/lib/Auth/Credentials.js +13 -4
  5. package/lib/Auth/Credentials.js.map +1 -1
  6. package/lib/Compute/Address.d.ts +97 -0
  7. package/lib/Compute/Address.d.ts.map +1 -0
  8. package/lib/Compute/Address.js +143 -0
  9. package/lib/Compute/Address.js.map +1 -0
  10. package/lib/Compute/Firewall.d.ts +108 -0
  11. package/lib/Compute/Firewall.d.ts.map +1 -0
  12. package/lib/Compute/Firewall.js +163 -0
  13. package/lib/Compute/Firewall.js.map +1 -0
  14. package/lib/Compute/ForwardingRule.d.ts +106 -0
  15. package/lib/Compute/ForwardingRule.d.ts.map +1 -0
  16. package/lib/Compute/ForwardingRule.js +152 -0
  17. package/lib/Compute/ForwardingRule.js.map +1 -0
  18. package/lib/Compute/index.d.ts +3 -0
  19. package/lib/Compute/index.d.ts.map +1 -1
  20. package/lib/Compute/index.js +3 -0
  21. package/lib/Compute/index.js.map +1 -1
  22. package/lib/Container/Cluster.d.ts +20 -0
  23. package/lib/Container/Cluster.d.ts.map +1 -1
  24. package/lib/Container/Cluster.js +5 -2
  25. package/lib/Container/Cluster.js.map +1 -1
  26. package/lib/Container/NodePool.d.ts +26 -1
  27. package/lib/Container/NodePool.d.ts.map +1 -1
  28. package/lib/Container/NodePool.js +45 -8
  29. package/lib/Container/NodePool.js.map +1 -1
  30. package/lib/Kubernetes/KubernetesManifest.d.ts +100 -0
  31. package/lib/Kubernetes/KubernetesManifest.d.ts.map +1 -0
  32. package/lib/Kubernetes/KubernetesManifest.js +131 -0
  33. package/lib/Kubernetes/KubernetesManifest.js.map +1 -0
  34. package/lib/Kubernetes/Secret.d.ts +96 -0
  35. package/lib/Kubernetes/Secret.d.ts.map +1 -0
  36. package/lib/Kubernetes/Secret.js +173 -0
  37. package/lib/Kubernetes/Secret.js.map +1 -0
  38. package/lib/Kubernetes/client.d.ts +62 -0
  39. package/lib/Kubernetes/client.d.ts.map +1 -0
  40. package/lib/Kubernetes/client.js +233 -0
  41. package/lib/Kubernetes/client.js.map +1 -0
  42. package/lib/Kubernetes/connection.d.ts +48 -0
  43. package/lib/Kubernetes/connection.d.ts.map +1 -0
  44. package/lib/Kubernetes/connection.js +93 -0
  45. package/lib/Kubernetes/connection.js.map +1 -0
  46. package/lib/Kubernetes/index.d.ts +3 -0
  47. package/lib/Kubernetes/index.d.ts.map +1 -0
  48. package/lib/Kubernetes/index.js +3 -0
  49. package/lib/Kubernetes/index.js.map +1 -0
  50. package/lib/ManagedLustre/Instance.d.ts.map +1 -1
  51. package/lib/ManagedLustre/Instance.js +25 -5
  52. package/lib/ManagedLustre/Instance.js.map +1 -1
  53. package/lib/Providers.d.ts +1 -1
  54. package/lib/Providers.d.ts.map +1 -1
  55. package/lib/Providers.js +11 -1
  56. package/lib/Providers.js.map +1 -1
  57. package/lib/Sqladmin/Instance.d.ts.map +1 -1
  58. package/lib/Sqladmin/Instance.js +28 -6
  59. package/lib/Sqladmin/Instance.js.map +1 -1
  60. package/lib/index.d.ts +1 -0
  61. package/lib/index.d.ts.map +1 -1
  62. package/lib/index.js +1 -0
  63. package/lib/index.js.map +1 -1
  64. package/package.json +3 -1
  65. package/src/Auth/Credentials.ts +15 -5
  66. package/src/Compute/Address.ts +288 -0
  67. package/src/Compute/Firewall.ts +330 -0
  68. package/src/Compute/ForwardingRule.ts +301 -0
  69. package/src/Compute/index.ts +3 -0
  70. package/src/Container/Cluster.ts +25 -2
  71. package/src/Container/NodePool.ts +87 -13
  72. package/src/Kubernetes/KubernetesManifest.ts +301 -0
  73. package/src/Kubernetes/Secret.ts +348 -0
  74. package/src/Kubernetes/client.ts +386 -0
  75. package/src/Kubernetes/connection.ts +180 -0
  76. package/src/Kubernetes/index.ts +2 -0
  77. package/src/ManagedLustre/Instance.ts +35 -6
  78. package/src/Providers.ts +24 -0
  79. package/src/Sqladmin/Instance.ts +36 -7
  80. package/src/index.ts +1 -0
@@ -0,0 +1,288 @@
1
+ import * as compute from "@distilled.cloud/gcp/compute-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 * as Effect from "effect/Effect";
9
+ import { gcpInternalLabels, hasAlchemyLabels } from "../Tags.ts";
10
+ import type * as GCP from "../Providers.ts";
11
+ import { makeAwaitRegionOperation } from "./Operations.ts";
12
+
13
+ /**
14
+ * A regional compute Address. The intended use here is a **Private
15
+ * Service Connect consumer endpoint IP** — a single internal address
16
+ * reserved in a subnet (`addressType=INTERNAL`, `purpose=GCE_ENDPOINT`)
17
+ * that a `ForwardingRule` then binds to a producer service attachment
18
+ * (e.g. a Cloud SQL instance in another VPC).
19
+ *
20
+ * For global PSA *ranges* (`purpose=VPC_PEERING`) use
21
+ * {@link GlobalAddress} — that is a different API surface
22
+ * (`globalAddresses` vs regional `addresses`).
23
+ *
24
+ * Adoption uses the labels field (Address carries `labels` +
25
+ * `labelFingerprint`).
26
+ *
27
+ * @section Reserving a PSC endpoint IP
28
+ * @example Internal address inside a subnet for a PSC forwarding rule
29
+ * ```typescript
30
+ * const endpointIp = yield* GCP.Address("DbPscAddress", {
31
+ * project: hostProject.projectId,
32
+ * region: "europe-west1",
33
+ * subnetwork: pscSubnet.selfLink,
34
+ * address: "10.0.16.5",
35
+ * });
36
+ * ```
37
+ */
38
+ export type AddressProps = {
39
+ /** GCP project ID hosting the address. Immutable — replace if changed. */
40
+ project: string;
41
+ /** GCP region. Addresses are regional — a different region requires replace. */
42
+ region: string;
43
+ /**
44
+ * Address name. Defaults to `createPhysicalName({ id, lowercase: true,
45
+ * maxLength: 63 })`. Immutable — replace if changed.
46
+ */
47
+ name?: string;
48
+ /** Description (free-form). Set on create; immutable. */
49
+ description?: string;
50
+ /**
51
+ * Internal vs external. Defaults to `INTERNAL` (the only value that
52
+ * makes sense for a PSC endpoint IP). Immutable — replace.
53
+ */
54
+ addressType?: "INTERNAL" | "EXTERNAL";
55
+ /**
56
+ * Address purpose. For a PSC endpoint IP use `GCE_ENDPOINT` (the
57
+ * default GCP assigns to plain internal addresses). Immutable — replace.
58
+ */
59
+ purpose?: "GCE_ENDPOINT" | "SHARED_LOADBALANCER_VIP" | "DNS_RESOLVER";
60
+ /**
61
+ * URL of the subnetwork the address is allocated from. Pass
62
+ * `subnet.selfLink` from a `GCP.Subnetwork` to make alchemy sequence
63
+ * the address after the subnet. Required for INTERNAL addresses.
64
+ * Immutable — replace.
65
+ */
66
+ subnetwork: string;
67
+ /**
68
+ * Explicit IP to reserve inside the subnet's range. If omitted, GCP
69
+ * picks one. Immutable — replace.
70
+ */
71
+ address?: string;
72
+ /**
73
+ * Resource labels. Alchemy internal labels (`alchemy_app`,
74
+ * `alchemy_stage`, `alchemy_id`) are merged on top automatically and
75
+ * are reserved. Mutable via `setLabels`.
76
+ */
77
+ labels?: Record<string, string>;
78
+ };
79
+
80
+ export type AddressAttributes = {
81
+ /** Address name. */
82
+ name: string;
83
+ /** GCP project ID, threaded through from props for delete/read. */
84
+ project: string;
85
+ /** GCP region, threaded through from props for delete/read. */
86
+ region: string;
87
+ /** Server-defined URL. */
88
+ selfLink: string;
89
+ /** Server-assigned numeric id. */
90
+ id: string;
91
+ /** The reserved IP. */
92
+ address: string;
93
+ /** Address type. */
94
+ addressType: string | undefined;
95
+ /** Purpose. */
96
+ purpose: string | undefined;
97
+ /** Subnetwork URL. */
98
+ subnetwork: string | undefined;
99
+ /** Status: `RESERVING`, `RESERVED`, `IN_USE`. */
100
+ status: string | undefined;
101
+ /** Labels currently set, including the alchemy internals. */
102
+ labels: Record<string, string>;
103
+ };
104
+
105
+ export type Address = Resource<
106
+ "GCP.Address",
107
+ AddressProps,
108
+ AddressAttributes,
109
+ never,
110
+ GCP.Providers
111
+ >;
112
+ export const Address = Resource<Address>("GCP.Address");
113
+
114
+ const toAddressAttributes = (
115
+ a: compute.Address,
116
+ parent: { project: string; region: string },
117
+ ): AddressAttributes => ({
118
+ name: a.name ?? "",
119
+ project: parent.project,
120
+ region: parent.region,
121
+ selfLink: a.selfLink ?? "",
122
+ id: a.id ?? "",
123
+ address: a.address ?? "",
124
+ addressType: a.addressType,
125
+ purpose: a.purpose,
126
+ subnetwork: a.subnetwork,
127
+ status: a.status,
128
+ labels: { ...(a.labels ?? {}) },
129
+ });
130
+
131
+ export const AddressProvider = () =>
132
+ Provider.effect(
133
+ Address,
134
+ Effect.gen(function* () {
135
+ const getAddresses = yield* compute.getAddresses;
136
+ const insertAddresses = yield* compute.insertAddresses;
137
+ const deleteAddresses = yield* compute.deleteAddresses;
138
+ const setLabelsAddresses = yield* compute.setLabelsAddresses;
139
+ const getRegionOperations = yield* compute.getRegionOperations;
140
+ const awaitOp = makeAwaitRegionOperation(getRegionOperations);
141
+
142
+ const observe = (project: string, region: string, name: string) =>
143
+ getAddresses({ project, region, address: name }).pipe(
144
+ Effect.catchTag("NotFound", () =>
145
+ Effect.succeed(undefined as compute.Address | undefined),
146
+ ),
147
+ Effect.catchTag("Forbidden", () =>
148
+ Effect.succeed(undefined as compute.Address | undefined),
149
+ ),
150
+ );
151
+
152
+ const syncLabels = Effect.fn(function* (args: {
153
+ project: string;
154
+ region: string;
155
+ observed: compute.Address;
156
+ desired: Record<string, string>;
157
+ session: ScopedPlanStatusSession;
158
+ }) {
159
+ if (deepEqual(args.observed.labels ?? {}, args.desired)) return;
160
+ const op = yield* setLabelsAddresses({
161
+ project: args.project,
162
+ region: args.region,
163
+ resource: args.observed.name ?? "",
164
+ body: {
165
+ labels: args.desired,
166
+ labelFingerprint: args.observed.labelFingerprint,
167
+ },
168
+ });
169
+ if (op.name) {
170
+ yield* awaitOp(args.project, args.region, op.name, args.session);
171
+ }
172
+ });
173
+
174
+ return {
175
+ stables: ["name", "project", "region", "selfLink", "id", "address"],
176
+ diff: Effect.fn(function* ({ news, olds = {} }) {
177
+ if (!isResolved(news)) return undefined;
178
+ if (
179
+ somePropsAreDifferent(olds as AddressProps, news, [
180
+ "project",
181
+ "region",
182
+ "name",
183
+ "addressType",
184
+ "purpose",
185
+ "subnetwork",
186
+ "address",
187
+ ])
188
+ ) {
189
+ return { action: "replace" } as const;
190
+ }
191
+ return undefined;
192
+ }),
193
+ reconcile: Effect.fn(function* ({ id, news, session }) {
194
+ const internalLabels = yield* gcpInternalLabels(id);
195
+ const desiredName =
196
+ news.name ??
197
+ (yield* createPhysicalName({ id, maxLength: 63 })).toLowerCase();
198
+ const desiredLabels: Record<string, string> = {
199
+ ...(news.labels ?? {}),
200
+ ...internalLabels,
201
+ };
202
+
203
+ let observed = yield* observe(news.project, news.region, desiredName);
204
+
205
+ if (!observed) {
206
+ const body: compute.Address = {
207
+ name: desiredName,
208
+ ...(news.description ? { description: news.description } : {}),
209
+ addressType: news.addressType ?? "INTERNAL",
210
+ ...(news.purpose ? { purpose: news.purpose } : {}),
211
+ subnetwork: news.subnetwork,
212
+ ...(news.address ? { address: news.address } : {}),
213
+ labels: desiredLabels,
214
+ };
215
+ const op = yield* insertAddresses({
216
+ project: news.project,
217
+ region: news.region,
218
+ body,
219
+ }).pipe(
220
+ Effect.catchTag("Conflict", () =>
221
+ Effect.succeed(undefined as compute.Operation | undefined),
222
+ ),
223
+ );
224
+ if (op?.name) {
225
+ yield* awaitOp(news.project, news.region, op.name, session);
226
+ }
227
+ observed = yield* getAddresses({
228
+ project: news.project,
229
+ region: news.region,
230
+ address: desiredName,
231
+ });
232
+ }
233
+
234
+ yield* syncLabels({
235
+ project: news.project,
236
+ region: news.region,
237
+ observed,
238
+ desired: desiredLabels,
239
+ session,
240
+ });
241
+
242
+ const final = yield* getAddresses({
243
+ project: news.project,
244
+ region: news.region,
245
+ address: desiredName,
246
+ });
247
+ return toAddressAttributes(final, {
248
+ project: news.project,
249
+ region: news.region,
250
+ });
251
+ }),
252
+ delete: Effect.fn(function* ({ output, session }) {
253
+ yield* deleteAddresses({
254
+ project: output.project,
255
+ region: output.region,
256
+ address: output.name,
257
+ }).pipe(
258
+ Effect.flatMap((op) =>
259
+ op.name
260
+ ? awaitOp(output.project, output.region, op.name, session)
261
+ : Effect.succeed(op),
262
+ ),
263
+ Effect.catchTag("NotFound", () => Effect.void),
264
+ // 400 "is being used by ..." comes back while a forwarding
265
+ // rule still references the address. The rule must be
266
+ // deleted first (alchemy's dep order handles this when the
267
+ // rule consumes `address.selfLink`); surface the error
268
+ // rather than silently swallowing.
269
+ );
270
+ }),
271
+ read: Effect.fn(function* ({ id, output, olds }) {
272
+ const project = output?.project ?? olds?.project;
273
+ const region = output?.region ?? olds?.region;
274
+ if (!project || !region) return undefined;
275
+ const name =
276
+ output?.name ??
277
+ olds?.name ??
278
+ (yield* createPhysicalName({ id, maxLength: 63 })).toLowerCase();
279
+ const observed = yield* observe(project, region, name);
280
+ if (!observed) return undefined;
281
+ const attrs = toAddressAttributes(observed, { project, region });
282
+ return (yield* hasAlchemyLabels(id, observed.labels))
283
+ ? attrs
284
+ : Unowned(attrs);
285
+ }),
286
+ };
287
+ }),
288
+ );
@@ -0,0 +1,330 @@
1
+ import * as compute from "@distilled.cloud/gcp/compute-v1";
2
+ import { Resource } from "alchemy";
3
+ import { Unowned } from "alchemy/AdoptPolicy";
4
+ import { deepEqual, isResolved, somePropsAreDifferent } from "alchemy/Diff";
5
+ import { createPhysicalName } from "alchemy/PhysicalName";
6
+ import * as Provider from "alchemy/Provider";
7
+ import * as Effect from "effect/Effect";
8
+ import {
9
+ descriptionHasAlchemyMarker,
10
+ gcpAlchemyDescription,
11
+ stripAlchemyMarker,
12
+ } from "../Tags.ts";
13
+ import type * as GCP from "../Providers.ts";
14
+ import { makeAwaitGlobalOperation } from "./Operations.ts";
15
+
16
+ /** One allow entry: a protocol plus optional port list. */
17
+ export type FirewallAllowed = {
18
+ /** `tcp` | `udp` | `icmp` | `esp` | `ah` | `sctp` | protocol number. */
19
+ IPProtocol: string;
20
+ /** Ports / ranges (`"8000"`, `"8000-8100"`). Omit = all ports. */
21
+ ports?: ReadonlyArray<string>;
22
+ };
23
+
24
+ /**
25
+ * A VPC firewall rule (allow rules only — `denied` is not modelled;
26
+ * add it when a consumer needs it).
27
+ *
28
+ * Firewalls have no `labels` field, so adoption gating uses the
29
+ * alchemy marker embedded in `description` (same as `GCP.Network`).
30
+ * Unlike Network, firewall `description` IS mutable, and the sync step
31
+ * keeps the marker prefix in place on every reconcile.
32
+ *
33
+ * GCP rejects rules carrying BOTH `targetTags` and
34
+ * `targetServiceAccounts` — prefer service accounts for GKE node
35
+ * targeting: node tags embed a per-cluster random suffix and go stale
36
+ * on every cluster rebuild, while the compute default SA is stable.
37
+ *
38
+ * @section Creating a firewall rule
39
+ * @example GCLB health checks → GKE pods on 8000
40
+ * ```typescript
41
+ * yield* GCP.Firewall("LbHealthChecks", {
42
+ * project: host.projectId,
43
+ * network: vpc.selfLink,
44
+ * name: "k8s-app-hc",
45
+ * sourceRanges: ["130.211.0.0/22", "35.191.0.0/16"],
46
+ * allowed: [{ IPProtocol: "tcp", ports: ["8000"] }],
47
+ * targetServiceAccounts: [nodeSa],
48
+ * });
49
+ * ```
50
+ */
51
+ export type FirewallProps = {
52
+ /** GCP project ID hosting the rule. Immutable — replace if changed. */
53
+ project: string;
54
+ /**
55
+ * Rule name. Defaults to `createPhysicalName({ id, lowercase: true,
56
+ * maxLength: 63 })`. Immutable — replace if changed.
57
+ */
58
+ name?: string;
59
+ /**
60
+ * VPC the rule attaches to — short name or selfLink. Immutable —
61
+ * replace if changed.
62
+ */
63
+ network: string;
64
+ /** User-visible description (stored after the alchemy marker). Mutable. */
65
+ description?: string;
66
+ /** INGRESS (default) or EGRESS. Immutable — replace if changed. */
67
+ direction?: "INGRESS" | "EGRESS";
68
+ /** 0–65535, lower wins. GCP default 1000. Mutable. */
69
+ priority?: number;
70
+ /** Source CIDRs (INGRESS). Mutable. */
71
+ sourceRanges?: ReadonlyArray<string>;
72
+ /** Destination CIDRs (EGRESS). Mutable. */
73
+ destinationRanges?: ReadonlyArray<string>;
74
+ /** Allow entries. Required — this resource models allow rules only. Mutable. */
75
+ allowed: ReadonlyArray<FirewallAllowed>;
76
+ /**
77
+ * Instance network tags the rule applies to. Mutually exclusive with
78
+ * `targetServiceAccounts`. Mutable.
79
+ */
80
+ targetTags?: ReadonlyArray<string>;
81
+ /**
82
+ * Service accounts whose instances the rule applies to. Preferred
83
+ * over tags for GKE nodes (stable across cluster rebuilds). Mutually
84
+ * exclusive with `targetTags`. Mutable.
85
+ */
86
+ targetServiceAccounts?: ReadonlyArray<string>;
87
+ /** Rule disabled (kept but not enforced). Mutable. */
88
+ disabled?: boolean;
89
+ };
90
+
91
+ export type FirewallAttributes = {
92
+ /** Rule name. */
93
+ name: string;
94
+ /** GCP project ID, threaded through from props for delete/read. */
95
+ project: string;
96
+ /** Server-defined URL. */
97
+ selfLink: string;
98
+ /** Server-assigned numeric id. */
99
+ id: string;
100
+ /** VPC selfLink the rule is attached to. */
101
+ network: string;
102
+ /** INGRESS / EGRESS. */
103
+ direction: string | undefined;
104
+ /** Effective priority. */
105
+ priority: number | undefined;
106
+ /** Source CIDRs. */
107
+ sourceRanges: ReadonlyArray<string> | undefined;
108
+ /** Allow entries. */
109
+ allowed: ReadonlyArray<FirewallAllowed> | undefined;
110
+ /** Target network tags. */
111
+ targetTags: ReadonlyArray<string> | undefined;
112
+ /** Target service accounts. */
113
+ targetServiceAccounts: ReadonlyArray<string> | undefined;
114
+ /** User description (alchemy marker stripped). */
115
+ description: string | undefined;
116
+ /** Disabled flag. */
117
+ disabled: boolean | undefined;
118
+ };
119
+
120
+ export type Firewall = Resource<
121
+ "GCP.Firewall",
122
+ FirewallProps,
123
+ FirewallAttributes,
124
+ never,
125
+ GCP.Providers
126
+ >;
127
+ export const Firewall = Resource<Firewall>("GCP.Firewall");
128
+
129
+ const toFirewallAttributes = (
130
+ f: compute.Firewall,
131
+ parent: { project: string },
132
+ ): FirewallAttributes => ({
133
+ name: f.name ?? "",
134
+ project: parent.project,
135
+ selfLink: f.selfLink ?? "",
136
+ id: f.id ?? "",
137
+ network: f.network ?? "",
138
+ direction: f.direction,
139
+ priority: f.priority,
140
+ sourceRanges: f.sourceRanges,
141
+ allowed: f.allowed as ReadonlyArray<FirewallAllowed> | undefined,
142
+ targetTags: f.targetTags,
143
+ targetServiceAccounts: f.targetServiceAccounts,
144
+ description: stripAlchemyMarker(f.description),
145
+ disabled: f.disabled,
146
+ });
147
+
148
+ /**
149
+ * Normalize for drift comparison: GCP reorders list fields and the
150
+ * `allowed` entries' ports — compare order-insensitively so a
151
+ * cosmetic reordering doesn't trigger a PATCH every reconcile.
152
+ */
153
+ const normalized = (f: {
154
+ priority?: number | undefined;
155
+ sourceRanges?: ReadonlyArray<string> | undefined;
156
+ destinationRanges?: ReadonlyArray<string> | undefined;
157
+ // `IPProtocol` is optional here because the SDK's observed Firewall
158
+ // type marks every field optional — desired props always set it.
159
+ allowed?: ReadonlyArray<{ IPProtocol?: string; ports?: ReadonlyArray<string> }> | undefined;
160
+ targetTags?: ReadonlyArray<string> | undefined;
161
+ targetServiceAccounts?: ReadonlyArray<string> | undefined;
162
+ disabled?: boolean | undefined;
163
+ description?: string | undefined;
164
+ }) => ({
165
+ priority: f.priority ?? 1000,
166
+ sourceRanges: [...(f.sourceRanges ?? [])].sort(),
167
+ destinationRanges: [...(f.destinationRanges ?? [])].sort(),
168
+ allowed: [...(f.allowed ?? [])]
169
+ .map((a) => ({
170
+ IPProtocol: (a.IPProtocol ?? "").toLowerCase(),
171
+ ports: [...(a.ports ?? [])].sort(),
172
+ }))
173
+ .sort((x, y) => x.IPProtocol.localeCompare(y.IPProtocol)),
174
+ targetTags: [...(f.targetTags ?? [])].sort(),
175
+ targetServiceAccounts: [...(f.targetServiceAccounts ?? [])].sort(),
176
+ disabled: f.disabled ?? false,
177
+ description: f.description,
178
+ });
179
+
180
+ export const FirewallProvider = () =>
181
+ Provider.effect(
182
+ Firewall,
183
+ Effect.gen(function* () {
184
+ const getFirewalls = yield* compute.getFirewalls;
185
+ const insertFirewalls = yield* compute.insertFirewalls;
186
+ const patchFirewalls = yield* compute.patchFirewalls;
187
+ const deleteFirewalls = yield* compute.deleteFirewalls;
188
+ const getGlobalOperations = yield* compute.getGlobalOperations;
189
+ const awaitOp = makeAwaitGlobalOperation(getGlobalOperations);
190
+
191
+ const observe = (project: string, name: string) =>
192
+ getFirewalls({ project, firewall: name }).pipe(
193
+ Effect.catchTag("NotFound", () =>
194
+ Effect.succeed(undefined as compute.Firewall | undefined),
195
+ ),
196
+ Effect.catchTag("Forbidden", () =>
197
+ Effect.succeed(undefined as compute.Firewall | undefined),
198
+ ),
199
+ );
200
+
201
+ return {
202
+ stables: ["name", "project", "selfLink", "id", "network"],
203
+ diff: Effect.fn(function* ({ news, olds = {} }) {
204
+ if (!isResolved(news)) return undefined;
205
+ if (
206
+ somePropsAreDifferent(olds as FirewallProps, news, [
207
+ "project",
208
+ "name",
209
+ "network",
210
+ "direction",
211
+ ])
212
+ ) {
213
+ return { action: "replace" } as const;
214
+ }
215
+ return undefined;
216
+ }),
217
+ reconcile: Effect.fn(function* ({ id, news, session }) {
218
+ if (news.targetTags?.length && news.targetServiceAccounts?.length) {
219
+ return yield* Effect.fail(
220
+ new Error(
221
+ "Firewall: targetTags and targetServiceAccounts are mutually exclusive (GCP rejects rules with both)",
222
+ ),
223
+ );
224
+ }
225
+ const desiredName =
226
+ news.name ??
227
+ (yield* createPhysicalName({ id, maxLength: 63 })).toLowerCase();
228
+ const desiredDescription = yield* gcpAlchemyDescription(
229
+ id,
230
+ news.description,
231
+ );
232
+
233
+ const mutableBody = (): compute.Firewall => ({
234
+ description: desiredDescription,
235
+ ...(news.priority !== undefined ? { priority: news.priority } : {}),
236
+ ...(news.sourceRanges
237
+ ? { sourceRanges: [...news.sourceRanges] }
238
+ : {}),
239
+ ...(news.destinationRanges
240
+ ? { destinationRanges: [...news.destinationRanges] }
241
+ : {}),
242
+ allowed: news.allowed.map((a) => ({
243
+ IPProtocol: a.IPProtocol,
244
+ ...(a.ports ? { ports: [...a.ports] } : {}),
245
+ })),
246
+ // Always send both target fields: switching tags → service
247
+ // accounts must CLEAR the other side, and PATCH leaves
248
+ // omitted fields untouched.
249
+ targetTags: [...(news.targetTags ?? [])],
250
+ targetServiceAccounts: [...(news.targetServiceAccounts ?? [])],
251
+ disabled: news.disabled ?? false,
252
+ });
253
+
254
+ // 1. Observe — collapse 403 to "missing" alongside 404.
255
+ let observed = yield* observe(news.project, desiredName);
256
+
257
+ // 2. Ensure — create if missing. `Conflict` covers concurrent
258
+ // creates and state-persistence races.
259
+ if (!observed) {
260
+ const op = yield* insertFirewalls({
261
+ project: news.project,
262
+ body: {
263
+ name: desiredName,
264
+ network: news.network,
265
+ ...(news.direction ? { direction: news.direction } : {}),
266
+ ...mutableBody(),
267
+ },
268
+ }).pipe(
269
+ Effect.catchTag("Conflict", () =>
270
+ Effect.succeed(undefined as compute.Operation | undefined),
271
+ ),
272
+ );
273
+ if (op?.name) yield* awaitOp(news.project, op.name, session);
274
+ observed = yield* getFirewalls({
275
+ project: news.project,
276
+ firewall: desiredName,
277
+ });
278
+ }
279
+
280
+ // 3. Sync — everything except name/network/direction is
281
+ // PATCHable. Diff against OBSERVED state (cloud is
282
+ // authoritative), order-insensitively.
283
+ const desired = mutableBody();
284
+ if (!deepEqual(normalized(observed), normalized(desired))) {
285
+ const op = yield* patchFirewalls({
286
+ project: news.project,
287
+ firewall: desiredName,
288
+ body: desired,
289
+ });
290
+ if (op.name) yield* awaitOp(news.project, op.name, session);
291
+ }
292
+
293
+ const final = yield* getFirewalls({
294
+ project: news.project,
295
+ firewall: desiredName,
296
+ });
297
+ return toFirewallAttributes(final, { project: news.project });
298
+ }),
299
+ delete: Effect.fn(function* ({ output, session }) {
300
+ yield* deleteFirewalls({
301
+ project: output.project,
302
+ firewall: output.name,
303
+ }).pipe(
304
+ Effect.flatMap((op) =>
305
+ op.name
306
+ ? awaitOp(output.project, op.name, session)
307
+ : Effect.succeed(op),
308
+ ),
309
+ Effect.catchTag("NotFound", () => Effect.void),
310
+ );
311
+ }),
312
+ read: Effect.fn(function* ({ id, output, olds }) {
313
+ const project = output?.project ?? olds?.project;
314
+ if (!project) return undefined;
315
+ const name =
316
+ output?.name ??
317
+ olds?.name ??
318
+ (yield* createPhysicalName({ id, maxLength: 63 })).toLowerCase();
319
+ const observed = yield* observe(project, name);
320
+ if (!observed) return undefined;
321
+ const attrs = toFirewallAttributes(observed, { project });
322
+ // Adoption gate via the description marker — firewalls have
323
+ // no labels field (same situation as GCP.Network).
324
+ return (yield* descriptionHasAlchemyMarker(id, observed.description))
325
+ ? attrs
326
+ : Unowned(attrs);
327
+ }),
328
+ };
329
+ }),
330
+ );