@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 910 lines 31.7 KB
Raw
1 import * as redis from "@distilled.cloud/gcp/redis_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { tagRecord } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import { GcpEnvironment } from "../Environment.ts";
13 import {
14 createInternalLabels,
15 diffLabels,
16 hasAlchemyLabels,
17 stripInternalLabels,
18 toLabels,
19 } from "../Labels.ts";
20 import { waitForOperation as waitForGcpOperation } from "../Operation.ts";
21 import type { Providers } from "../Providers.ts";
22
23 const DEFAULT_TIER = "BASIC";
24 const DEFAULT_CONNECT_MODE = "DIRECT_PEERING";
25 const DEFAULT_TRANSIT_ENCRYPTION = "DISABLED";
26 const DEFAULT_MEMORY_SIZE_GB = 1;
27
28 /**
29 * Memorystore create, delete, and resize operations take minutes (a BASIC
30 * 1 GiB create is ~4 minutes). Poll every 10s for up to 12 minutes.
31 */
32 const LONG_POLL = { times: 72, schedule: Schedule.spaced("10 seconds") };
33 const MAX_NAME_LENGTH = 40;
34
35 export type RedisTimeOfDay = {
36 /** Hours of day in 24-hour format (`0`–`23`). */
37 hours?: number;
38 /** Minutes of hour (`0`–`59`). */
39 minutes?: number;
40 /** Seconds of minute (`0`–`59`). */
41 seconds?: number;
42 /** Fractional seconds, in nanoseconds. */
43 nanos?: number;
44 };
45
46 export type WeeklyMaintenanceWindow = {
47 /** Day of week that maintenance occurs (`MONDAY` … `SUNDAY`). */
48 day?: redis.WeeklyMaintenanceWindowDayEnum | (string & {});
49 /** Start time of the window in UTC. */
50 startTime?: RedisTimeOfDay;
51 };
52
53 export type MaintenancePolicy = {
54 /** Description of the policy. Max 512 characters. */
55 description?: string;
56 /** Weekly windows. Current API maximum is one window. */
57 weeklyMaintenanceWindow?: WeeklyMaintenanceWindow[];
58 };
59
60 export type PersistenceConfig = {
61 /**
62 * Persistence mode. `DISABLED` deletes existing snapshots; `RDB` enables
63 * RDB snapshots.
64 */
65 persistenceMode?: redis.PersistenceConfigPersistenceModeEnum | (string & {});
66 /**
67 * Period between RDB snapshots (`ONE_HOUR`, `SIX_HOURS`, `TWELVE_HOURS`,
68 * `TWENTY_FOUR_HOURS`).
69 */
70 rdbSnapshotPeriod?: redis.PersistenceConfigRdbSnapshotPeriodEnum | (string & {});
71 /**
72 * Alignment timestamp for snapshots (RFC3339). If omitted, the current
73 * time is used.
74 */
75 rdbSnapshotStartTime?: string;
76 };
77
78 export type InstanceProps = {
79 /**
80 * Instance id (the `{instance}` segment of
81 * `projects/{project}/locations/{location}/instances/{instance}`).
82 * If omitted, a unique name is generated from the stack, stage, and
83 * logical id. Must match `^[a-z][a-z0-9-]{0,38}[a-z0-9]$` (1-40
84 * characters). Immutable — changing it replaces the instance.
85 */
86 instanceId?: string;
87 /**
88 * Region (`us-central1`, `us-east1`, …). Immutable — changing it
89 * replaces the instance. `US-CENTRAL1` is accepted and normalized to
90 * `us-central1`.
91 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
92 */
93 location?: string;
94 /**
95 * Zone to provision the primary node in (e.g. `us-central1-a`).
96 * Immutable. If omitted, Memorystore picks a zone.
97 */
98 locationId?: string;
99 /**
100 * Additional zone for STANDARD_HA. Immutable. Must differ from
101 * `locationId`.
102 */
103 alternativeLocationId?: string;
104 /**
105 * User-facing display name.
106 */
107 displayName?: string;
108 /**
109 * User labels. Alchemy ownership labels are merged in automatically.
110 */
111 labels?: Record<string, string>;
112 /**
113 * Redis software version (`REDIS_7_0`, `REDIS_7_2`, …). Upgrading uses
114 * `instances.upgrade`; downgrading replaces the instance.
115 */
116 redisVersion?: string;
117 /**
118 * Reserved IP CIDR (`DIRECT_PEERING`) or allocated range name
119 * (`PRIVATE_SERVICE_ACCESS`). Immutable.
120 */
121 reservedIpRange?: string;
122 /**
123 * Extra IP range used when enabling read replicas (`auto` or a CIDR /
124 * allocated range name).
125 */
126 secondaryIpRange?: string;
127 /**
128 * Redis config parameters (`maxmemory-policy`, `notify-keyspace-events`,
129 * …). See Memorystore supported parameters.
130 */
131 redisConfigs?: Record<string, string>;
132 /**
133 * Service tier. Immutable — changing it replaces the instance.
134 * @default "BASIC"
135 */
136 tier?: redis.InstanceTierEnum | (string & {});
137 /**
138 * Memory size in GiB.
139 * @default 1
140 */
141 memorySizeGb?: number;
142 /**
143 * VPC network
144 * (`projects/{project}/global/networks/{network}`). Immutable. Defaults
145 * to the project `default` network.
146 */
147 authorizedNetwork?: string;
148 /**
149 * Network connect mode. Immutable.
150 * @default "DIRECT_PEERING"
151 */
152 connectMode?: redis.InstanceConnectModeEnum | (string & {});
153 /**
154 * Enable OSS Redis AUTH.
155 * @default false
156 */
157 authEnabled?: boolean;
158 /**
159 * In-transit TLS mode. Immutable.
160 * @default "DISABLED"
161 */
162 transitEncryptionMode?: redis.InstanceTransitEncryptionModeEnum | (string & {});
163 /**
164 * Maintenance policy. If omitted, Memorystore may perform maintenance
165 * at any time.
166 */
167 maintenancePolicy?: MaintenancePolicy;
168 /**
169 * Replica count. BASIC is `0`. STANDARD_HA without read replicas is
170 * `1`. STANDARD_HA with read replicas is `1`–`5`.
171 */
172 replicaCount?: number;
173 /**
174 * Read replica mode. Create-time only — changing it replaces the
175 * instance.
176 */
177 readReplicasMode?: redis.InstanceReadReplicasModeEnum | (string & {});
178 /**
179 * Customer-managed KMS key for at-rest encryption
180 * (`projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}`). Immutable.
181 */
182 customerManagedKey?: string;
183 /**
184 * RDB persistence configuration.
185 */
186 persistenceConfig?: PersistenceConfig;
187 /**
188 * Self-service maintenance version (e.g. `"20210712_00_00"`).
189 */
190 maintenanceVersion?: string;
191 };
192
193 export type Instance = Resource<
194 "GCP.Redis.Instance",
195 InstanceProps,
196 {
197 /** Full resource name `projects/{project}/locations/{location}/instances/{instance}`. */
198 name: string;
199 /** Instance id (last path segment). */
200 instanceId: string;
201 /** Project id. */
202 project: string;
203 /** Region id (`us-central1`, …). */
204 location: string;
205 /** User-facing display name. */
206 displayName: string | undefined;
207 /** User labels (Alchemy ownership labels stripped). */
208 labels: Record<string, string>;
209 /** Provisioned primary zone. */
210 locationId: string | undefined;
211 /** Additional STANDARD_HA zone. */
212 alternativeLocationId: string | undefined;
213 /** Current primary zone (may change after failover). */
214 currentLocationId: string | undefined;
215 /** Redis software version. */
216 redisVersion: string | undefined;
217 /** Reserved IP CIDR or allocated range name. */
218 reservedIpRange: string | undefined;
219 /** Extra IP range for read replicas. */
220 secondaryIpRange: string | undefined;
221 /** Redis endpoint hostname or IP. */
222 host: string | undefined;
223 /** Redis endpoint port. */
224 port: number | undefined;
225 /** Server-reported state (`READY`, `CREATING`, …). */
226 state: string | undefined;
227 /** Extra status text, if any. */
228 statusMessage: string | undefined;
229 /** Redis config parameters currently applied. */
230 redisConfigs: Record<string, string>;
231 /** Service tier (`BASIC`, `STANDARD_HA`). */
232 tier: string;
233 /** Memory size in GiB. */
234 memorySizeGb: number;
235 /** Authorized VPC network. */
236 authorizedNetwork: string | undefined;
237 /** IAM identity used for import/export. */
238 persistenceIamIdentity: string | undefined;
239 /** Network connect mode. */
240 connectMode: string | undefined;
241 /** Whether OSS Redis AUTH is enabled. */
242 authEnabled: boolean;
243 /** In-transit TLS mode. */
244 transitEncryptionMode: string | undefined;
245 /** Replica count. */
246 replicaCount: number | undefined;
247 /** Per-node info. */
248 nodes: redis.NodeInfo[];
249 /** Read replica endpoint hostname (STANDARD_HA). */
250 readEndpoint: string | undefined;
251 /** Read replica endpoint port. */
252 readEndpointPort: number | undefined;
253 /** Read replica mode. */
254 readReplicasMode: string | undefined;
255 /** Customer-managed KMS key, if any. */
256 customerManagedKey: string | undefined;
257 /** Persistence configuration currently applied. */
258 persistenceConfig: PersistenceConfig | undefined;
259 /** Self-service maintenance version. */
260 maintenanceVersion: string | undefined;
261 /** RFC3339 creation timestamp. */
262 createTime: string | undefined;
263 },
264 never,
265 Providers
266 >;
267
268 /**
269 * A Memorystore for Redis instance.
270 *
271 * Changing `instanceId`, `location`, `tier`, `connectMode`,
272 * `authorizedNetwork`, `reservedIpRange`, `locationId`,
273 * `alternativeLocationId`, `transitEncryptionMode`, `customerManagedKey`,
274 * or `readReplicasMode` replaces the instance. Redis version upgrades use
275 * `instances.upgrade`; a downgrade replaces the instance.
276 *
277 * Provisioning typically takes several minutes.
278 *
279 * ### Creating an Instance
280 * **Example:** Generated name, BASIC 1 GiB
281 * ```typescript
282 * const cache = yield* GCP.Redis.Instance("Cache", {});
283 * ```
284 *
285 * **Example:** Explicit id, labels, and AUTH
286 * ```typescript
287 * const cache = yield* GCP.Redis.Instance("Cache", {
288 * instanceId: "app-cache",
289 * location: "us-central1",
290 * memorySizeGb: 1,
291 * authEnabled: true,
292 * labels: { env: "prod" },
293 * });
294 * ```
295 *
296 * ### Binding from a Function
297 * **Example:** ReadWriteRedis from a Function
298 * ```typescript
299 * export class Api extends GCP.Function<Api>()(
300 * "Api",
301 * { main: import.meta.url },
302 * Effect.gen(function* () {
303 * const cache = yield* GCP.Redis.Instance("Cache", { memorySizeGb: 1 });
304 * const redis = yield* GCP.Redis.ReadWriteRedis(cache);
305 * return {
306 * fetch: Effect.gen(function* () {
307 * yield* redis.set("k", "v").pipe(Effect.orDie);
308 * return HttpServerResponse.text("ok");
309 * }),
310 * };
311 * }).pipe(Effect.provide([GCP.Redis.ReadWriteRedisHttp])),
312 * ) {}
313 * ```
314 *
315 * ### Destroying an Instance
316 * **Example:** Delete waits out CREATING
317 * ```typescript
318 * const cache = yield* GCP.Redis.Instance("Cache", { memorySizeGb: 1 });
319 * ```
320 * `alchemy destroy` waits for `CREATING` to finish, then retries `Conflict` until the instance is gone.
321 *
322 * ### High Availability
323 * **Example:** STANDARD_HA across two zones
324 * ```typescript
325 * const cache = yield* GCP.Redis.Instance("Cache", {
326 * tier: "STANDARD_HA",
327 * locationId: "us-central1-a",
328 * alternativeLocationId: "us-central1-f",
329 * memorySizeGb: 1,
330 * });
331 * ```
332 *
333 * @resource
334 * @category Redis
335 */
336 export const Instance = Resource<Instance>("GCP.Redis.Instance");
337
338 export class InstanceNotResolved extends Data.TaggedError("GCP.Redis.InstanceNotResolved")<{
339 resourceName: string;
340 }> {}
341
342 export class InstanceNotReady extends Data.TaggedError("GCP.Redis.InstanceNotReady")<{
343 resourceName: string;
344 state: string;
345 }> {}
346
347 export class InstanceOperationPending extends Data.TaggedError(
348 "GCP.Redis.InstanceOperationPending",
349 )<{
350 operation: string;
351 }> {}
352
353 export class InstanceStillExists extends Data.TaggedError("GCP.Redis.InstanceStillExists")<{
354 resourceName: string;
355 }> {}
356
357 const lastSegment = (value: string) => {
358 const trimmed = value.replace(/\/+$/, "");
359 const parts = trimmed.split("/");
360 return parts[parts.length - 1] || trimmed;
361 };
362
363 const normalizeLocation = (location: string | undefined, fallback: string) =>
364 lastSegment(location ?? fallback).toLowerCase();
365
366 const normalizeTier = (tier: string | undefined) => {
367 const value = (tier ?? DEFAULT_TIER).toUpperCase();
368 return value === "TIER_UNSPECIFIED" ? DEFAULT_TIER : value;
369 };
370
371 const normalizeConnectMode = (mode: string | undefined) => {
372 const value = (mode ?? DEFAULT_CONNECT_MODE).toUpperCase();
373 return value === "CONNECT_MODE_UNSPECIFIED" ? DEFAULT_CONNECT_MODE : value;
374 };
375
376 const normalizeTransit = (mode: string | undefined) => {
377 const value = (mode ?? DEFAULT_TRANSIT_ENCRYPTION).toUpperCase();
378 return value === "TRANSIT_ENCRYPTION_MODE_UNSPECIFIED" ? DEFAULT_TRANSIT_ENCRYPTION : value;
379 };
380
381 const normalizeReadReplicas = (mode: string | undefined) =>
382 (mode ?? "READ_REPLICAS_DISABLED").toUpperCase();
383
384 const rfc1035 = (name: string): string => {
385 let next = name
386 .toLowerCase()
387 .replace(/[^a-z0-9-]/g, "-")
388 .replace(/-+/g, "-")
389 .replace(/^-+|-+$/g, "");
390 if (!/^[a-z]/.test(next)) next = `r${next}`;
391 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, "");
392 if (next.length === 0) return "instance";
393 if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`;
394 return next.slice(0, MAX_NAME_LENGTH);
395 };
396
397 const resourceName = (project: string, location: string, instanceId: string) =>
398 `projects/${project}/locations/${location}/instances/${instanceId}`;
399
400 const parseName = (name: string, fallbackLocation: string) => {
401 const parts = name.split("/").filter((part) => part.length > 0);
402 const instancesAt = parts.lastIndexOf("instances");
403 const locationsAt = parts.lastIndexOf("locations");
404 const projectsAt = parts.lastIndexOf("projects");
405 return {
406 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
407 location:
408 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation,
409 instanceId:
410 instancesAt >= 0 && parts[instancesAt + 1] ? parts[instancesAt + 1]! : lastSegment(name),
411 };
412 };
413
414 const userLabels = (
415 labels: Record<string, string | undefined> | null | undefined,
416 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
417
418 const toId = (id: string, instanceId: string | undefined, existing?: string) =>
419 Effect.gen(function* () {
420 return (
421 instanceId ??
422 existing ??
423 rfc1035(
424 yield* createPhysicalName({
425 id,
426 maxLength: MAX_NAME_LENGTH,
427 lowercase: true,
428 }),
429 )
430 );
431 });
432
433 const configsOf = (
434 configs: Record<string, string | undefined> | null | undefined,
435 ): Record<string, string> =>
436 Object.fromEntries(
437 Object.entries(configs ?? {}).filter(
438 (entry): entry is [string, string] => entry[1] !== undefined,
439 ),
440 );
441
442 const configsKey = (configs: Record<string, string | undefined> | null | undefined) =>
443 JSON.stringify(
444 Object.fromEntries(Object.entries(configsOf(configs)).sort(([a], [b]) => a.localeCompare(b))),
445 );
446
447 const persistenceOf = (
448 config: redis.PersistenceConfig | PersistenceConfig | undefined,
449 ): PersistenceConfig | undefined => {
450 if (config === undefined) return undefined;
451 return {
452 persistenceMode: config.persistenceMode,
453 rdbSnapshotPeriod: config.rdbSnapshotPeriod,
454 rdbSnapshotStartTime: config.rdbSnapshotStartTime,
455 };
456 };
457
458 const persistenceKey = (config: redis.PersistenceConfig | PersistenceConfig | undefined) => {
459 const value = persistenceOf(config);
460 return JSON.stringify({
461 persistenceMode: (value?.persistenceMode ?? "").toUpperCase(),
462 rdbSnapshotPeriod: (value?.rdbSnapshotPeriod ?? "").toUpperCase(),
463 rdbSnapshotStartTime: value?.rdbSnapshotStartTime ?? "",
464 });
465 };
466
467 const windowKey = (window: WeeklyMaintenanceWindow) =>
468 JSON.stringify({
469 day: (window.day ?? "").toUpperCase(),
470 hours: window.startTime?.hours ?? 0,
471 minutes: window.startTime?.minutes ?? 0,
472 seconds: window.startTime?.seconds ?? 0,
473 nanos: window.startTime?.nanos ?? 0,
474 });
475
476 const maintenanceKey = (policy: MaintenancePolicy | undefined) =>
477 JSON.stringify({
478 description: policy?.description ?? "",
479 windows: (policy?.weeklyMaintenanceWindow ?? []).map(windowKey),
480 });
481
482 const parseRedisVersion = (version: string | undefined) => {
483 if (version === undefined) return undefined;
484 const match = version.toUpperCase().match(/^REDIS_(\d+)_(\d+|X)$/);
485 if (!match) return undefined;
486 const minor = match[2] === "X" ? 99 : Number(match[2]);
487 return Number(match[1]) * 100 + minor;
488 };
489
490 const versionDecreasing = (previous: string | undefined, next: string) => {
491 const oldN = parseRedisVersion(previous);
492 const newN = parseRedisVersion(next);
493 if (oldN === undefined || newN === undefined) return previous !== next;
494 return newN < oldN;
495 };
496
497 const toAttrs = (instance: redis.Instance, project: string, region: string) => {
498 const name = instance.name ?? "";
499 const parsed = parseName(name, region);
500 return {
501 name,
502 instanceId: parsed.instanceId,
503 project: parsed.project || project,
504 location: parsed.location,
505 displayName: instance.displayName,
506 labels: userLabels(instance.labels),
507 locationId: instance.locationId,
508 alternativeLocationId: instance.alternativeLocationId,
509 currentLocationId: instance.currentLocationId,
510 redisVersion: instance.redisVersion,
511 reservedIpRange: instance.reservedIpRange,
512 secondaryIpRange: instance.secondaryIpRange,
513 host: instance.host,
514 port: instance.port,
515 state: instance.state,
516 statusMessage: instance.statusMessage,
517 redisConfigs: configsOf(instance.redisConfigs),
518 tier: normalizeTier(instance.tier),
519 memorySizeGb: instance.memorySizeGb ?? DEFAULT_MEMORY_SIZE_GB,
520 authorizedNetwork: instance.authorizedNetwork,
521 persistenceIamIdentity: instance.persistenceIamIdentity,
522 connectMode: instance.connectMode,
523 authEnabled: instance.authEnabled === true,
524 transitEncryptionMode: instance.transitEncryptionMode,
525 replicaCount: instance.replicaCount,
526 nodes: instance.nodes ?? [],
527 readEndpoint: instance.readEndpoint,
528 readEndpointPort: instance.readEndpointPort,
529 readReplicasMode: instance.readReplicasMode,
530 customerManagedKey: instance.customerManagedKey,
531 persistenceConfig: persistenceOf(instance.persistenceConfig),
532 maintenanceVersion: instance.maintenanceVersion,
533 createTime: instance.createTime,
534 };
535 };
536
537 const isPlaceholder = (instance: redis.Instance) => {
538 const name = instance.name ?? "";
539 return name.endsWith("/instances/-") || name.endsWith("/instances/");
540 };
541
542 const getByName = (name: string) =>
543 redis
544 .getProjectsLocationsInstances({ name })
545 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
546
547 /** Wait for an operation through the shared GCP waiter. */
548 const waitForOperation = (operation: redis.Operation, options?: { notFoundOk?: boolean }) =>
549 waitForGcpOperation(
550 operation,
551 (name) =>
552 redis
553 .getProjectsLocationsOperations({ name })
554 .pipe(
555 Effect.catchTag("NotFound", (error) =>
556 options?.notFoundOk === true
557 ? Effect.succeed<redis.Operation>({ name, done: true })
558 : Effect.fail(error),
559 ),
560 ),
561 { budget: "30 minutes" },
562 ).pipe(
563 // ALREADY_EXISTS (6): a concurrent create won the race. NOT_FOUND (5)
564 // is success for a delete.
565 Effect.catchIf(
566 (error) =>
567 error._tag === "GCP.OperationFailed" &&
568 (error.code === 6 || (options?.notFoundOk === true && error.code === 5)),
569 () => Effect.void,
570 ),
571 );
572
573 const waitUntilExists = (name: string) =>
574 getByName(name).pipe(
575 Effect.flatMap((instance) =>
576 instance
577 ? Effect.succeed(instance)
578 : Effect.fail(new InstanceNotResolved({ resourceName: name })),
579 ),
580 Effect.retry({
581 while: (error) => error._tag === "GCP.Redis.InstanceNotResolved",
582 times: 8,
583 schedule: Schedule.spaced("1 second"),
584 }),
585 );
586
587 const waitUntilReady = (name: string) =>
588 getByName(name).pipe(
589 Effect.filterOrFail(
590 (instance): instance is redis.Instance => instance !== undefined,
591 () => new InstanceNotResolved({ resourceName: name }),
592 ),
593 Effect.filterOrFail(
594 (instance) => (instance.state ?? "STATE_UNSPECIFIED") === "READY",
595 (instance) =>
596 new InstanceNotReady({
597 resourceName: name,
598 state: instance.state ?? "STATE_UNSPECIFIED",
599 }),
600 ),
601 Effect.retry({
602 while: (error) =>
603 error._tag === "GCP.Redis.InstanceNotReady" ||
604 error._tag === "GCP.Redis.InstanceNotResolved",
605 ...LONG_POLL,
606 }),
607 );
608
609 const waitUntilGone = (name: string) =>
610 getByName(name).pipe(
611 Effect.flatMap((instance) =>
612 instance === undefined
613 ? Effect.void
614 : Effect.fail(new InstanceStillExists({ resourceName: name })),
615 ),
616 Effect.retry({
617 while: (error) => error._tag === "GCP.Redis.InstanceStillExists",
618 ...LONG_POLL,
619 }),
620 );
621
622 const toCreateBody = (
623 news: InstanceProps,
624 desiredLabels: Record<string, string>,
625 tier: string,
626 connectMode: string,
627 transitEncryptionMode: string,
628 memorySizeGb: number,
629 authEnabled: boolean,
630 ): redis.Instance => ({
631 displayName: news.displayName,
632 labels: desiredLabels,
633 locationId: news.locationId,
634 alternativeLocationId: news.alternativeLocationId,
635 redisVersion: news.redisVersion,
636 reservedIpRange: news.reservedIpRange,
637 secondaryIpRange: news.secondaryIpRange,
638 redisConfigs: news.redisConfigs,
639 tier,
640 memorySizeGb,
641 authorizedNetwork: news.authorizedNetwork,
642 connectMode,
643 authEnabled,
644 transitEncryptionMode,
645 maintenancePolicy: news.maintenancePolicy,
646 replicaCount: news.replicaCount,
647 readReplicasMode: news.readReplicasMode,
648 customerManagedKey: news.customerManagedKey,
649 persistenceConfig: news.persistenceConfig,
650 });
651
652 export const InstanceProvider = () =>
653 Provider.succeed(Instance, {
654 stables: ["name", "instanceId", "project", "location", "createTime"],
655
656 diff: Effect.fn(function* ({ news, olds, output }) {
657 if (!isResolved(news)) return undefined;
658 const env = yield* GcpEnvironment.current;
659
660 const previousId = olds?.instanceId ?? output?.instanceId;
661 const nextId = news.instanceId ?? previousId;
662 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
663 const nextLocation = normalizeLocation(news.location ?? output?.location, env.region);
664 const previousTier = normalizeTier(olds?.tier ?? output?.tier);
665 const nextTier = normalizeTier(news.tier ?? output?.tier);
666 const previousConnect = normalizeConnectMode(olds?.connectMode ?? output?.connectMode);
667 const nextConnect = normalizeConnectMode(news.connectMode ?? output?.connectMode);
668 const previousTransit = normalizeTransit(
669 olds?.transitEncryptionMode ?? output?.transitEncryptionMode,
670 );
671 const nextTransit = normalizeTransit(
672 news.transitEncryptionMode ?? output?.transitEncryptionMode,
673 );
674 const previousNetwork = olds?.authorizedNetwork ?? output?.authorizedNetwork ?? "";
675 const nextNetwork = news.authorizedNetwork ?? previousNetwork;
676 const previousRange = olds?.reservedIpRange ?? output?.reservedIpRange ?? "";
677 const nextRange = news.reservedIpRange ?? previousRange;
678 const previousZone = olds?.locationId ?? output?.locationId ?? "";
679 const nextZone = news.locationId ?? previousZone;
680 const previousAlt = olds?.alternativeLocationId ?? output?.alternativeLocationId ?? "";
681 const nextAlt = news.alternativeLocationId ?? previousAlt;
682 const previousCmek = olds?.customerManagedKey ?? output?.customerManagedKey ?? "";
683 const nextCmek = news.customerManagedKey ?? previousCmek;
684 const previousReplicas = normalizeReadReplicas(
685 olds?.readReplicasMode ?? output?.readReplicasMode,
686 );
687 const nextReplicas = normalizeReadReplicas(news.readReplicasMode ?? output?.readReplicasMode);
688 const previousVersion = olds?.redisVersion ?? output?.redisVersion;
689 const nextVersion = news.redisVersion;
690 const downgrade =
691 nextVersion !== undefined &&
692 previousVersion !== undefined &&
693 versionDecreasing(previousVersion, nextVersion);
694
695 const replace =
696 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
697 previousLocation !== nextLocation ||
698 previousTier !== nextTier ||
699 previousConnect !== nextConnect ||
700 previousTransit !== nextTransit ||
701 previousNetwork !== nextNetwork ||
702 previousRange !== nextRange ||
703 previousZone !== nextZone ||
704 previousAlt !== nextAlt ||
705 previousCmek !== nextCmek ||
706 previousReplicas !== nextReplicas ||
707 downgrade;
708
709 if (!replace) return undefined;
710 return {
711 action: "replace" as const,
712 deleteFirst:
713 previousLocation === nextLocation && previousId !== undefined && nextId === previousId,
714 };
715 }),
716
717 read: Effect.fn(function* ({ id, olds, output }) {
718 const env = yield* GcpEnvironment.current;
719 const instanceId = yield* toId(id, olds?.instanceId, output?.instanceId);
720 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
721 const name = output?.name ?? resourceName(env.project, location, instanceId);
722 const existing = yield* getByName(name);
723 if (existing === undefined) return undefined;
724 const attrs = toAttrs(existing, env.project, env.region);
725 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
726 }),
727
728 list: () =>
729 Effect.gen(function* () {
730 const env = yield* GcpEnvironment.current;
731 return yield* redis.listProjectsLocationsInstances
732 .pages({
733 parent: `projects/${env.project}/locations/-`,
734 pageSize: 1000,
735 })
736 .pipe(
737 Stream.flatMap((page) => Stream.fromIterable(page.instances ?? [])),
738 Stream.filter(
739 (instance) =>
740 !isPlaceholder(instance) &&
741 Object.keys(instance.labels ?? {}).some((key) => key.startsWith("alchemy-")),
742 ),
743 Stream.map((instance) => toAttrs(instance, env.project, env.region)),
744 Stream.runCollect,
745 Effect.map((chunk) => Array.from(chunk)),
746 Effect.catchTag("NotFound", () => Effect.succeed([])),
747 );
748 }),
749
750 reconcile: Effect.fn(function* ({ id, news, output }) {
751 const env = yield* GcpEnvironment.current;
752 const instanceId = yield* toId(id, news.instanceId, output?.instanceId);
753 const location = normalizeLocation(news.location ?? output?.location, env.region);
754 const name = resourceName(env.project, location, instanceId);
755 const tier = normalizeTier(news.tier);
756 const connectMode = normalizeConnectMode(news.connectMode);
757 const transitEncryptionMode = normalizeTransit(news.transitEncryptionMode);
758 const memorySizeGb = news.memorySizeGb ?? DEFAULT_MEMORY_SIZE_GB;
759 const authEnabled = news.authEnabled === true;
760 const desiredLabels = {
761 ...toLabels(news.labels),
762 ...(yield* createInternalLabels(id)),
763 };
764
765 let current = yield* getByName(output?.name ?? name);
766
767 if (current === undefined) {
768 const created = yield* redis
769 .createProjectsLocationsInstances({
770 parent: `projects/${env.project}/locations/${location}`,
771 instanceId,
772 body: toCreateBody(
773 news,
774 desiredLabels,
775 tier,
776 connectMode,
777 transitEncryptionMode,
778 memorySizeGb,
779 authEnabled,
780 ),
781 })
782 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
783 if (created !== undefined) {
784 yield* waitForOperation(created);
785 }
786 current = yield* waitUntilExists(name);
787 }
788
789 if (current === undefined) {
790 return yield* new InstanceNotResolved({ resourceName: name });
791 }
792
793 if ((current.state ?? "") !== "READY") {
794 current = yield* waitUntilReady(name);
795 }
796
797 const desiredVersion = news.redisVersion;
798 const currentVersion = current.redisVersion;
799 if (
800 desiredVersion !== undefined &&
801 currentVersion !== undefined &&
802 desiredVersion !== currentVersion &&
803 !versionDecreasing(currentVersion, desiredVersion)
804 ) {
805 const upgraded = yield* redis.upgradeProjectsLocationsInstances({
806 name,
807 body: { redisVersion: desiredVersion },
808 });
809 yield* waitForOperation(upgraded);
810 current = yield* waitUntilReady(name);
811 }
812
813 const observedLabels = tagRecord(current.labels);
814 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
815 const labelsChanged = upsert.length > 0 || removed.length > 0;
816 const displayNameChanged = (current.displayName ?? "") !== (news.displayName ?? "");
817 const memoryChanged = (current.memorySizeGb ?? DEFAULT_MEMORY_SIZE_GB) !== memorySizeGb;
818 const authChanged = (current.authEnabled === true) !== authEnabled;
819 const configsChanged =
820 news.redisConfigs !== undefined &&
821 configsKey(current.redisConfigs) !== configsKey(news.redisConfigs);
822 const persistenceChanged =
823 news.persistenceConfig !== undefined &&
824 persistenceKey(current.persistenceConfig) !== persistenceKey(news.persistenceConfig);
825 const maintenanceChanged =
826 news.maintenancePolicy !== undefined &&
827 maintenanceKey(current.maintenancePolicy) !== maintenanceKey(news.maintenancePolicy);
828 const replicaChanged =
829 news.replicaCount !== undefined && (current.replicaCount ?? 0) !== news.replicaCount;
830 const secondaryChanged =
831 news.secondaryIpRange !== undefined &&
832 (current.secondaryIpRange ?? "") !== news.secondaryIpRange;
833 const maintenanceVersionChanged =
834 news.maintenanceVersion !== undefined &&
835 (current.maintenanceVersion ?? "") !== news.maintenanceVersion;
836
837 if (
838 labelsChanged ||
839 displayNameChanged ||
840 memoryChanged ||
841 authChanged ||
842 configsChanged ||
843 persistenceChanged ||
844 maintenanceChanged ||
845 replicaChanged ||
846 secondaryChanged ||
847 maintenanceVersionChanged
848 ) {
849 const updateMask = [
850 labelsChanged ? "labels" : undefined,
851 displayNameChanged ? "displayName" : undefined,
852 memoryChanged ? "memorySizeGb" : undefined,
853 authChanged ? "authEnabled" : undefined,
854 configsChanged ? "redisConfig" : undefined,
855 persistenceChanged ? "persistenceConfig" : undefined,
856 maintenanceChanged ? "maintenancePolicy" : undefined,
857 replicaChanged ? "replica_count" : undefined,
858 secondaryChanged ? "secondaryIpRange" : undefined,
859 maintenanceVersionChanged ? "maintenanceVersion" : undefined,
860 ].filter((field): field is string => field !== undefined);
861
862 const patched = yield* redis.patchProjectsLocationsInstances({
863 name,
864 updateMask: updateMask.join(","),
865 body: {
866 name,
867 labels: desiredLabels,
868 displayName: news.displayName,
869 memorySizeGb,
870 authEnabled,
871 redisConfigs: news.redisConfigs,
872 persistenceConfig: news.persistenceConfig,
873 maintenancePolicy: news.maintenancePolicy,
874 replicaCount: news.replicaCount,
875 secondaryIpRange: news.secondaryIpRange,
876 maintenanceVersion: news.maintenanceVersion,
877 },
878 });
879 yield* waitForOperation(patched);
880 current = yield* waitUntilReady(name);
881 }
882
883 return toAttrs(current, env.project, env.region);
884 }),
885
886 delete: Effect.fn(function* ({ output }) {
887 yield* getByName(output.name).pipe(
888 Effect.filterOrFail(
889 (instance) => instance === undefined || (instance.state ?? "") !== "CREATING",
890 () => new InstanceOperationPending({ operation: output.name }),
891 ),
892 Effect.retry({
893 while: (error) => error._tag === "GCP.Redis.InstanceOperationPending",
894 ...LONG_POLL,
895 }),
896 );
897 const operation = yield* redis.deleteProjectsLocationsInstances({ name: output.name }).pipe(
898 Effect.catchTag("NotFound", () => Effect.undefined),
899 Effect.retry({
900 while: (error) => error._tag === "Conflict",
901 times: 24,
902 schedule: Schedule.spaced("8 seconds"),
903 }),
904 );
905 if (operation !== undefined) {
906 yield* waitForOperation(operation, { notFoundOk: true });
907 }
908 yield* waitUntilGone(output.name);
909 }),
910 });