sailfork / t3code-github / .repos/ alchemy-effect/ packages/ gcp/ src/ Redis/ Instance.ts

import * as redis from "@distilled.cloud/gcp/redis_v1";
import { Unowned } from "alchemy/AdoptPolicy";
import { isResolved } from "alchemy/Diff";
import { createPhysicalName } from "alchemy/PhysicalName";
import * as Provider from "alchemy/Provider";
import { Resource } from "alchemy/Resource";
import { tagRecord } from "alchemy/Tags";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schedule from "effect/Schedule";
import * as Stream from "effect/Stream";
import { GcpEnvironment } from "../Environment.ts";
import {
  createInternalLabels,
  diffLabels,
  hasAlchemyLabels,
  stripInternalLabels,
  toLabels,
} from "../Labels.ts";
import { waitForOperation as waitForGcpOperation } from "../Operation.ts";
import type { Providers } from "../Providers.ts";

const DEFAULT_TIER = "BASIC";
const DEFAULT_CONNECT_MODE = "DIRECT_PEERING";
const DEFAULT_TRANSIT_ENCRYPTION = "DISABLED";
const DEFAULT_MEMORY_SIZE_GB = 1;

/**
 * Memorystore create, delete, and resize operations take minutes (a BASIC
 * 1 GiB create is ~4 minutes). Poll every 10s for up to 12 minutes.
 */
const LONG_POLL = { times: 72, schedule: Schedule.spaced("10 seconds") };
const MAX_NAME_LENGTH = 40;

export type RedisTimeOfDay = {
  /** Hours of day in 24-hour format (`0`–`23`). */
  hours?: number;
  /** Minutes of hour (`0`–`59`). */
  minutes?: number;
  /** Seconds of minute (`0`–`59`). */
  seconds?: number;
  /** Fractional seconds, in nanoseconds. */
  nanos?: number;
};

export type WeeklyMaintenanceWindow = {
  /** Day of week that maintenance occurs (`MONDAY` … `SUNDAY`). */
  day?: redis.WeeklyMaintenanceWindowDayEnum | (string & {});
  /** Start time of the window in UTC. */
  startTime?: RedisTimeOfDay;
};

export type MaintenancePolicy = {
  /** Description of the policy. Max 512 characters. */
  description?: string;
  /** Weekly windows. Current API maximum is one window. */
  weeklyMaintenanceWindow?: WeeklyMaintenanceWindow[];
};

export type PersistenceConfig = {
  /**
   * Persistence mode. `DISABLED` deletes existing snapshots; `RDB` enables
   * RDB snapshots.
   */
  persistenceMode?: redis.PersistenceConfigPersistenceModeEnum | (string & {});
  /**
   * Period between RDB snapshots (`ONE_HOUR`, `SIX_HOURS`, `TWELVE_HOURS`,
   * `TWENTY_FOUR_HOURS`).
   */
  rdbSnapshotPeriod?: redis.PersistenceConfigRdbSnapshotPeriodEnum | (string & {});
  /**
   * Alignment timestamp for snapshots (RFC3339). If omitted, the current
   * time is used.
   */
  rdbSnapshotStartTime?: string;
};

export type InstanceProps = {
  /**
   * Instance id (the `{instance}` segment of
   * `projects/{project}/locations/{location}/instances/{instance}`).
   * If omitted, a unique name is generated from the stack, stage, and
   * logical id. Must match `^[a-z][a-z0-9-]{0,38}[a-z0-9]

	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	.repos/alchemy-effect/packages/gcp/src/Redis/Instance.ts at main · sailfork/t3code-github · Sailfork
	
		
(1-40 * characters). Immutable — changing it replaces the instance. */ instanceId?: string; /** * Region (`us-central1`, `us-east1`, …). Immutable — changing it * replaces the instance. `US-CENTRAL1` is accepted and normalized to * `us-central1`. * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`) */ location?: string; /** * Zone to provision the primary node in (e.g. `us-central1-a`). * Immutable. If omitted, Memorystore picks a zone. */ locationId?: string; /** * Additional zone for STANDARD_HA. Immutable. Must differ from * `locationId`. */ alternativeLocationId?: string; /** * User-facing display name. */ displayName?: string; /** * User labels. Alchemy ownership labels are merged in automatically. */ labels?: Record<string, string>; /** * Redis software version (`REDIS_7_0`, `REDIS_7_2`, …). Upgrading uses * `instances.upgrade`; downgrading replaces the instance. */ redisVersion?: string; /** * Reserved IP CIDR (`DIRECT_PEERING`) or allocated range name * (`PRIVATE_SERVICE_ACCESS`). Immutable. */ reservedIpRange?: string; /** * Extra IP range used when enabling read replicas (`auto` or a CIDR / * allocated range name). */ secondaryIpRange?: string; /** * Redis config parameters (`maxmemory-policy`, `notify-keyspace-events`, * …). See Memorystore supported parameters. */ redisConfigs?: Record<string, string>; /** * Service tier. Immutable — changing it replaces the instance. * @default "BASIC" */ tier?: redis.InstanceTierEnum | (string & {}); /** * Memory size in GiB. * @default 1 */ memorySizeGb?: number; /** * VPC network * (`projects/{project}/global/networks/{network}`). Immutable. Defaults * to the project `default` network. */ authorizedNetwork?: string; /** * Network connect mode. Immutable. * @default "DIRECT_PEERING" */ connectMode?: redis.InstanceConnectModeEnum | (string & {}); /** * Enable OSS Redis AUTH. * @default false */ authEnabled?: boolean; /** * In-transit TLS mode. Immutable. * @default "DISABLED" */ transitEncryptionMode?: redis.InstanceTransitEncryptionModeEnum | (string & {}); /** * Maintenance policy. If omitted, Memorystore may perform maintenance * at any time. */ maintenancePolicy?: MaintenancePolicy; /** * Replica count. BASIC is `0`. STANDARD_HA without read replicas is * `1`. STANDARD_HA with read replicas is `1`–`5`. */ replicaCount?: number; /** * Read replica mode. Create-time only — changing it replaces the * instance. */ readReplicasMode?: redis.InstanceReadReplicasModeEnum | (string & {}); /** * Customer-managed KMS key for at-rest encryption * (`projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}`). Immutable. */ customerManagedKey?: string; /** * RDB persistence configuration. */ persistenceConfig?: PersistenceConfig; /** * Self-service maintenance version (e.g. `"20210712_00_00"`). */ maintenanceVersion?: string; }; export type Instance = Resource< "GCP.Redis.Instance", InstanceProps, { /** Full resource name `projects/{project}/locations/{location}/instances/{instance}`. */ name: string; /** Instance id (last path segment). */ instanceId: string; /** Project id. */ project: string; /** Region id (`us-central1`, …). */ location: string; /** User-facing display name. */ displayName: string | undefined; /** User labels (Alchemy ownership labels stripped). */ labels: Record<string, string>; /** Provisioned primary zone. */ locationId: string | undefined; /** Additional STANDARD_HA zone. */ alternativeLocationId: string | undefined; /** Current primary zone (may change after failover). */ currentLocationId: string | undefined; /** Redis software version. */ redisVersion: string | undefined; /** Reserved IP CIDR or allocated range name. */ reservedIpRange: string | undefined; /** Extra IP range for read replicas. */ secondaryIpRange: string | undefined; /** Redis endpoint hostname or IP. */ host: string | undefined; /** Redis endpoint port. */ port: number | undefined; /** Server-reported state (`READY`, `CREATING`, …). */ state: string | undefined; /** Extra status text, if any. */ statusMessage: string | undefined; /** Redis config parameters currently applied. */ redisConfigs: Record<string, string>; /** Service tier (`BASIC`, `STANDARD_HA`). */ tier: string; /** Memory size in GiB. */ memorySizeGb: number; /** Authorized VPC network. */ authorizedNetwork: string | undefined; /** IAM identity used for import/export. */ persistenceIamIdentity: string | undefined; /** Network connect mode. */ connectMode: string | undefined; /** Whether OSS Redis AUTH is enabled. */ authEnabled: boolean; /** In-transit TLS mode. */ transitEncryptionMode: string | undefined; /** Replica count. */ replicaCount: number | undefined; /** Per-node info. */ nodes: redis.NodeInfo[]; /** Read replica endpoint hostname (STANDARD_HA). */ readEndpoint: string | undefined; /** Read replica endpoint port. */ readEndpointPort: number | undefined; /** Read replica mode. */ readReplicasMode: string | undefined; /** Customer-managed KMS key, if any. */ customerManagedKey: string | undefined; /** Persistence configuration currently applied. */ persistenceConfig: PersistenceConfig | undefined; /** Self-service maintenance version. */ maintenanceVersion: string | undefined; /** RFC3339 creation timestamp. */ createTime: string | undefined; }, never, Providers >; /** * A Memorystore for Redis instance. * * Changing `instanceId`, `location`, `tier`, `connectMode`, * `authorizedNetwork`, `reservedIpRange`, `locationId`, * `alternativeLocationId`, `transitEncryptionMode`, `customerManagedKey`, * or `readReplicasMode` replaces the instance. Redis version upgrades use * `instances.upgrade`; a downgrade replaces the instance. * * Provisioning typically takes several minutes. * * ### Creating an Instance * **Example:** Generated name, BASIC 1 GiB * ```typescript * const cache = yield* GCP.Redis.Instance("Cache", {}); * ``` * * **Example:** Explicit id, labels, and AUTH * ```typescript * const cache = yield* GCP.Redis.Instance("Cache", { * instanceId: "app-cache", * location: "us-central1", * memorySizeGb: 1, * authEnabled: true, * labels: { env: "prod" }, * }); * ``` * * ### Binding from a Function * **Example:** ReadWriteRedis from a Function * ```typescript * export class Api extends GCP.Function<Api>()( * "Api", * { main: import.meta.url }, * Effect.gen(function* () { * const cache = yield* GCP.Redis.Instance("Cache", { memorySizeGb: 1 }); * const redis = yield* GCP.Redis.ReadWriteRedis(cache); * return { * fetch: Effect.gen(function* () { * yield* redis.set("k", "v").pipe(Effect.orDie); * return HttpServerResponse.text("ok"); * }), * }; * }).pipe(Effect.provide([GCP.Redis.ReadWriteRedisHttp])), * ) {} * ``` * * ### Destroying an Instance * **Example:** Delete waits out CREATING * ```typescript * const cache = yield* GCP.Redis.Instance("Cache", { memorySizeGb: 1 }); * ``` * `alchemy destroy` waits for `CREATING` to finish, then retries `Conflict` until the instance is gone. * * ### High Availability * **Example:** STANDARD_HA across two zones * ```typescript * const cache = yield* GCP.Redis.Instance("Cache", { * tier: "STANDARD_HA", * locationId: "us-central1-a", * alternativeLocationId: "us-central1-f", * memorySizeGb: 1, * }); * ``` * * @resource * @category Redis */ export const Instance = Resource<Instance>("GCP.Redis.Instance"); export class InstanceNotResolved extends Data.TaggedError("GCP.Redis.InstanceNotResolved")<{ resourceName: string; }> {} export class InstanceNotReady extends Data.TaggedError("GCP.Redis.InstanceNotReady")<{ resourceName: string; state: string; }> {} export class InstanceOperationPending extends Data.TaggedError( "GCP.Redis.InstanceOperationPending", )<{ operation: string; }> {} export class InstanceStillExists extends Data.TaggedError("GCP.Redis.InstanceStillExists")<{ resourceName: string; }> {} const lastSegment = (value: string) => { const trimmed = value.replace(/\/+$/, ""); const parts = trimmed.split("/"); return parts[parts.length - 1] || trimmed; }; const normalizeLocation = (location: string | undefined, fallback: string) => lastSegment(location ?? fallback).toLowerCase(); const normalizeTier = (tier: string | undefined) => { const value = (tier ?? DEFAULT_TIER).toUpperCase(); return value === "TIER_UNSPECIFIED" ? DEFAULT_TIER : value; }; const normalizeConnectMode = (mode: string | undefined) => { const value = (mode ?? DEFAULT_CONNECT_MODE).toUpperCase(); return value === "CONNECT_MODE_UNSPECIFIED" ? DEFAULT_CONNECT_MODE : value; }; const normalizeTransit = (mode: string | undefined) => { const value = (mode ?? DEFAULT_TRANSIT_ENCRYPTION).toUpperCase(); return value === "TRANSIT_ENCRYPTION_MODE_UNSPECIFIED" ? DEFAULT_TRANSIT_ENCRYPTION : value; }; const normalizeReadReplicas = (mode: string | undefined) => (mode ?? "READ_REPLICAS_DISABLED").toUpperCase(); const rfc1035 = (name: string): string => { let next = name .toLowerCase() .replace(/[^a-z0-9-]/g, "-") .replace(/-+/g, "-") .replace(/^-+|-+$/g, ""); if (!/^[a-z]/.test(next)) next = `r${next}`; next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, ""); if (next.length === 0) return "instance"; if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`; return next.slice(0, MAX_NAME_LENGTH); }; const resourceName = (project: string, location: string, instanceId: string) => `projects/${project}/locations/${location}/instances/${instanceId}`; const parseName = (name: string, fallbackLocation: string) => { const parts = name.split("/").filter((part) => part.length > 0); const instancesAt = parts.lastIndexOf("instances"); const locationsAt = parts.lastIndexOf("locations"); const projectsAt = parts.lastIndexOf("projects"); return { project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation, instanceId: instancesAt >= 0 && parts[instancesAt + 1] ? parts[instancesAt + 1]! : lastSegment(name), }; }; const userLabels = ( labels: Record<string, string | undefined> | null | undefined, ): Record<string, string> => stripInternalLabels(tagRecord(labels)); const toId = (id: string, instanceId: string | undefined, existing?: string) => Effect.gen(function* () { return ( instanceId ?? existing ?? rfc1035( yield* createPhysicalName({ id, maxLength: MAX_NAME_LENGTH, lowercase: true, }), ) ); }); const configsOf = ( configs: Record<string, string | undefined> | null | undefined, ): Record<string, string> => Object.fromEntries( Object.entries(configs ?? {}).filter( (entry): entry is [string, string] => entry[1] !== undefined, ), ); const configsKey = (configs: Record<string, string | undefined> | null | undefined) => JSON.stringify( Object.fromEntries(Object.entries(configsOf(configs)).sort(([a], [b]) => a.localeCompare(b))), ); const persistenceOf = ( config: redis.PersistenceConfig | PersistenceConfig | undefined, ): PersistenceConfig | undefined => { if (config === undefined) return undefined; return { persistenceMode: config.persistenceMode, rdbSnapshotPeriod: config.rdbSnapshotPeriod, rdbSnapshotStartTime: config.rdbSnapshotStartTime, }; }; const persistenceKey = (config: redis.PersistenceConfig | PersistenceConfig | undefined) => { const value = persistenceOf(config); return JSON.stringify({ persistenceMode: (value?.persistenceMode ?? "").toUpperCase(), rdbSnapshotPeriod: (value?.rdbSnapshotPeriod ?? "").toUpperCase(), rdbSnapshotStartTime: value?.rdbSnapshotStartTime ?? "", }); }; const windowKey = (window: WeeklyMaintenanceWindow) => JSON.stringify({ day: (window.day ?? "").toUpperCase(), hours: window.startTime?.hours ?? 0, minutes: window.startTime?.minutes ?? 0, seconds: window.startTime?.seconds ?? 0, nanos: window.startTime?.nanos ?? 0, }); const maintenanceKey = (policy: MaintenancePolicy | undefined) => JSON.stringify({ description: policy?.description ?? "", windows: (policy?.weeklyMaintenanceWindow ?? []).map(windowKey), }); const parseRedisVersion = (version: string | undefined) => { if (version === undefined) return undefined; const match = version.toUpperCase().match(/^REDIS_(\d+)_(\d+|X)$/); if (!match) return undefined; const minor = match[2] === "X" ? 99 : Number(match[2]); return Number(match[1]) * 100 + minor; }; const versionDecreasing = (previous: string | undefined, next: string) => { const oldN = parseRedisVersion(previous); const newN = parseRedisVersion(next); if (oldN === undefined || newN === undefined) return previous !== next; return newN < oldN; }; const toAttrs = (instance: redis.Instance, project: string, region: string) => { const name = instance.name ?? ""; const parsed = parseName(name, region); return { name, instanceId: parsed.instanceId, project: parsed.project || project, location: parsed.location, displayName: instance.displayName, labels: userLabels(instance.labels), locationId: instance.locationId, alternativeLocationId: instance.alternativeLocationId, currentLocationId: instance.currentLocationId, redisVersion: instance.redisVersion, reservedIpRange: instance.reservedIpRange, secondaryIpRange: instance.secondaryIpRange, host: instance.host, port: instance.port, state: instance.state, statusMessage: instance.statusMessage, redisConfigs: configsOf(instance.redisConfigs), tier: normalizeTier(instance.tier), memorySizeGb: instance.memorySizeGb ?? DEFAULT_MEMORY_SIZE_GB, authorizedNetwork: instance.authorizedNetwork, persistenceIamIdentity: instance.persistenceIamIdentity, connectMode: instance.connectMode, authEnabled: instance.authEnabled === true, transitEncryptionMode: instance.transitEncryptionMode, replicaCount: instance.replicaCount, nodes: instance.nodes ?? [], readEndpoint: instance.readEndpoint, readEndpointPort: instance.readEndpointPort, readReplicasMode: instance.readReplicasMode, customerManagedKey: instance.customerManagedKey, persistenceConfig: persistenceOf(instance.persistenceConfig), maintenanceVersion: instance.maintenanceVersion, createTime: instance.createTime, }; }; const isPlaceholder = (instance: redis.Instance) => { const name = instance.name ?? ""; return name.endsWith("/instances/-") || name.endsWith("/instances/"); }; const getByName = (name: string) => redis .getProjectsLocationsInstances({ name }) .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); /** Wait for an operation through the shared GCP waiter. */ const waitForOperation = (operation: redis.Operation, options?: { notFoundOk?: boolean }) => waitForGcpOperation( operation, (name) => redis .getProjectsLocationsOperations({ name }) .pipe( Effect.catchTag("NotFound", (error) => options?.notFoundOk === true ? Effect.succeed<redis.Operation>({ name, done: true }) : Effect.fail(error), ), ), { budget: "30 minutes" }, ).pipe( // ALREADY_EXISTS (6): a concurrent create won the race. NOT_FOUND (5) // is success for a delete. Effect.catchIf( (error) => error._tag === "GCP.OperationFailed" && (error.code === 6 || (options?.notFoundOk === true && error.code === 5)), () => Effect.void, ), ); const waitUntilExists = (name: string) => getByName(name).pipe( Effect.flatMap((instance) => instance ? Effect.succeed(instance) : Effect.fail(new InstanceNotResolved({ resourceName: name })), ), Effect.retry({ while: (error) => error._tag === "GCP.Redis.InstanceNotResolved", times: 8, schedule: Schedule.spaced("1 second"), }), ); const waitUntilReady = (name: string) => getByName(name).pipe( Effect.filterOrFail( (instance): instance is redis.Instance => instance !== undefined, () => new InstanceNotResolved({ resourceName: name }), ), Effect.filterOrFail( (instance) => (instance.state ?? "STATE_UNSPECIFIED") === "READY", (instance) => new InstanceNotReady({ resourceName: name, state: instance.state ?? "STATE_UNSPECIFIED", }), ), Effect.retry({ while: (error) => error._tag === "GCP.Redis.InstanceNotReady" || error._tag === "GCP.Redis.InstanceNotResolved", ...LONG_POLL, }), ); const waitUntilGone = (name: string) => getByName(name).pipe( Effect.flatMap((instance) => instance === undefined ? Effect.void : Effect.fail(new InstanceStillExists({ resourceName: name })), ), Effect.retry({ while: (error) => error._tag === "GCP.Redis.InstanceStillExists", ...LONG_POLL, }), ); const toCreateBody = ( news: InstanceProps, desiredLabels: Record<string, string>, tier: string, connectMode: string, transitEncryptionMode: string, memorySizeGb: number, authEnabled: boolean, ): redis.Instance => ({ displayName: news.displayName, labels: desiredLabels, locationId: news.locationId, alternativeLocationId: news.alternativeLocationId, redisVersion: news.redisVersion, reservedIpRange: news.reservedIpRange, secondaryIpRange: news.secondaryIpRange, redisConfigs: news.redisConfigs, tier, memorySizeGb, authorizedNetwork: news.authorizedNetwork, connectMode, authEnabled, transitEncryptionMode, maintenancePolicy: news.maintenancePolicy, replicaCount: news.replicaCount, readReplicasMode: news.readReplicasMode, customerManagedKey: news.customerManagedKey, persistenceConfig: news.persistenceConfig, }); export const InstanceProvider = () => Provider.succeed(Instance, { stables: ["name", "instanceId", "project", "location", "createTime"], diff: Effect.fn(function* ({ news, olds, output }) { if (!isResolved(news)) return undefined; const env = yield* GcpEnvironment.current; const previousId = olds?.instanceId ?? output?.instanceId; const nextId = news.instanceId ?? previousId; const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region); const nextLocation = normalizeLocation(news.location ?? output?.location, env.region); const previousTier = normalizeTier(olds?.tier ?? output?.tier); const nextTier = normalizeTier(news.tier ?? output?.tier); const previousConnect = normalizeConnectMode(olds?.connectMode ?? output?.connectMode); const nextConnect = normalizeConnectMode(news.connectMode ?? output?.connectMode); const previousTransit = normalizeTransit( olds?.transitEncryptionMode ?? output?.transitEncryptionMode, ); const nextTransit = normalizeTransit( news.transitEncryptionMode ?? output?.transitEncryptionMode, ); const previousNetwork = olds?.authorizedNetwork ?? output?.authorizedNetwork ?? ""; const nextNetwork = news.authorizedNetwork ?? previousNetwork; const previousRange = olds?.reservedIpRange ?? output?.reservedIpRange ?? ""; const nextRange = news.reservedIpRange ?? previousRange; const previousZone = olds?.locationId ?? output?.locationId ?? ""; const nextZone = news.locationId ?? previousZone; const previousAlt = olds?.alternativeLocationId ?? output?.alternativeLocationId ?? ""; const nextAlt = news.alternativeLocationId ?? previousAlt; const previousCmek = olds?.customerManagedKey ?? output?.customerManagedKey ?? ""; const nextCmek = news.customerManagedKey ?? previousCmek; const previousReplicas = normalizeReadReplicas( olds?.readReplicasMode ?? output?.readReplicasMode, ); const nextReplicas = normalizeReadReplicas(news.readReplicasMode ?? output?.readReplicasMode); const previousVersion = olds?.redisVersion ?? output?.redisVersion; const nextVersion = news.redisVersion; const downgrade = nextVersion !== undefined && previousVersion !== undefined && versionDecreasing(previousVersion, nextVersion); const replace = (previousId !== undefined && nextId !== undefined && nextId !== previousId) || previousLocation !== nextLocation || previousTier !== nextTier || previousConnect !== nextConnect || previousTransit !== nextTransit || previousNetwork !== nextNetwork || previousRange !== nextRange || previousZone !== nextZone || previousAlt !== nextAlt || previousCmek !== nextCmek || previousReplicas !== nextReplicas || downgrade; if (!replace) return undefined; return { action: "replace" as const, deleteFirst: previousLocation === nextLocation && previousId !== undefined && nextId === previousId, }; }), read: Effect.fn(function* ({ id, olds, output }) { const env = yield* GcpEnvironment.current; const instanceId = yield* toId(id, olds?.instanceId, output?.instanceId); const location = normalizeLocation(olds?.location ?? output?.location, env.region); const name = output?.name ?? resourceName(env.project, location, instanceId); const existing = yield* getByName(name); if (existing === undefined) return undefined; const attrs = toAttrs(existing, env.project, env.region); return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs); }), list: () => Effect.gen(function* () { const env = yield* GcpEnvironment.current; return yield* redis.listProjectsLocationsInstances .pages({ parent: `projects/${env.project}/locations/-`, pageSize: 1000, }) .pipe( Stream.flatMap((page) => Stream.fromIterable(page.instances ?? [])), Stream.filter( (instance) => !isPlaceholder(instance) && Object.keys(instance.labels ?? {}).some((key) => key.startsWith("alchemy-")), ), Stream.map((instance) => toAttrs(instance, env.project, env.region)), Stream.runCollect, Effect.map((chunk) => Array.from(chunk)), Effect.catchTag("NotFound", () => Effect.succeed([])), ); }), reconcile: Effect.fn(function* ({ id, news, output }) { const env = yield* GcpEnvironment.current; const instanceId = yield* toId(id, news.instanceId, output?.instanceId); const location = normalizeLocation(news.location ?? output?.location, env.region); const name = resourceName(env.project, location, instanceId); const tier = normalizeTier(news.tier); const connectMode = normalizeConnectMode(news.connectMode); const transitEncryptionMode = normalizeTransit(news.transitEncryptionMode); const memorySizeGb = news.memorySizeGb ?? DEFAULT_MEMORY_SIZE_GB; const authEnabled = news.authEnabled === true; const desiredLabels = { ...toLabels(news.labels), ...(yield* createInternalLabels(id)), }; let current = yield* getByName(output?.name ?? name); if (current === undefined) { const created = yield* redis .createProjectsLocationsInstances({ parent: `projects/${env.project}/locations/${location}`, instanceId, body: toCreateBody( news, desiredLabels, tier, connectMode, transitEncryptionMode, memorySizeGb, authEnabled, ), }) .pipe(Effect.catchTag("Conflict", () => Effect.undefined)); if (created !== undefined) { yield* waitForOperation(created); } current = yield* waitUntilExists(name); } if (current === undefined) { return yield* new InstanceNotResolved({ resourceName: name }); } if ((current.state ?? "") !== "READY") { current = yield* waitUntilReady(name); } const desiredVersion = news.redisVersion; const currentVersion = current.redisVersion; if ( desiredVersion !== undefined && currentVersion !== undefined && desiredVersion !== currentVersion && !versionDecreasing(currentVersion, desiredVersion) ) { const upgraded = yield* redis.upgradeProjectsLocationsInstances({ name, body: { redisVersion: desiredVersion }, }); yield* waitForOperation(upgraded); current = yield* waitUntilReady(name); } const observedLabels = tagRecord(current.labels); const { upsert, removed } = diffLabels(observedLabels, desiredLabels); const labelsChanged = upsert.length > 0 || removed.length > 0; const displayNameChanged = (current.displayName ?? "") !== (news.displayName ?? ""); const memoryChanged = (current.memorySizeGb ?? DEFAULT_MEMORY_SIZE_GB) !== memorySizeGb; const authChanged = (current.authEnabled === true) !== authEnabled; const configsChanged = news.redisConfigs !== undefined && configsKey(current.redisConfigs) !== configsKey(news.redisConfigs); const persistenceChanged = news.persistenceConfig !== undefined && persistenceKey(current.persistenceConfig) !== persistenceKey(news.persistenceConfig); const maintenanceChanged = news.maintenancePolicy !== undefined && maintenanceKey(current.maintenancePolicy) !== maintenanceKey(news.maintenancePolicy); const replicaChanged = news.replicaCount !== undefined && (current.replicaCount ?? 0) !== news.replicaCount; const secondaryChanged = news.secondaryIpRange !== undefined && (current.secondaryIpRange ?? "") !== news.secondaryIpRange; const maintenanceVersionChanged = news.maintenanceVersion !== undefined && (current.maintenanceVersion ?? "") !== news.maintenanceVersion; if ( labelsChanged || displayNameChanged || memoryChanged || authChanged || configsChanged || persistenceChanged || maintenanceChanged || replicaChanged || secondaryChanged || maintenanceVersionChanged ) { const updateMask = [ labelsChanged ? "labels" : undefined, displayNameChanged ? "displayName" : undefined, memoryChanged ? "memorySizeGb" : undefined, authChanged ? "authEnabled" : undefined, configsChanged ? "redisConfig" : undefined, persistenceChanged ? "persistenceConfig" : undefined, maintenanceChanged ? "maintenancePolicy" : undefined, replicaChanged ? "replica_count" : undefined, secondaryChanged ? "secondaryIpRange" : undefined, maintenanceVersionChanged ? "maintenanceVersion" : undefined, ].filter((field): field is string => field !== undefined); const patched = yield* redis.patchProjectsLocationsInstances({ name, updateMask: updateMask.join(","), body: { name, labels: desiredLabels, displayName: news.displayName, memorySizeGb, authEnabled, redisConfigs: news.redisConfigs, persistenceConfig: news.persistenceConfig, maintenancePolicy: news.maintenancePolicy, replicaCount: news.replicaCount, secondaryIpRange: news.secondaryIpRange, maintenanceVersion: news.maintenanceVersion, }, }); yield* waitForOperation(patched); current = yield* waitUntilReady(name); } return toAttrs(current, env.project, env.region); }), delete: Effect.fn(function* ({ output }) { yield* getByName(output.name).pipe( Effect.filterOrFail( (instance) => instance === undefined || (instance.state ?? "") !== "CREATING", () => new InstanceOperationPending({ operation: output.name }), ), Effect.retry({ while: (error) => error._tag === "GCP.Redis.InstanceOperationPending", ...LONG_POLL, }), ); const operation = yield* redis.deleteProjectsLocationsInstances({ name: output.name }).pipe( Effect.catchTag("NotFound", () => Effect.undefined), Effect.retry({ while: (error) => error._tag === "Conflict", times: 24, schedule: Schedule.spaced("8 seconds"), }), ); if (operation !== undefined) { yield* waitForOperation(operation, { notFoundOk: true }); } yield* waitUntilGone(output.name); }), });
.repos/alchemy-effect/packages/gcp/src/Redis/Instance.ts at main · sailfork/t3code-github · Sailfork
(1-40\n * characters). Immutable — changing it replaces the instance.\n */\n instanceId?: string;\n /**\n * Region (`us-central1`, `us-east1`, …). Immutable — changing it\n * replaces the instance. `US-CENTRAL1` is accepted and normalized to\n * `us-central1`.\n * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)\n */\n location?: string;\n /**\n * Zone to provision the primary node in (e.g. `us-central1-a`).\n * Immutable. If omitted, Memorystore picks a zone.\n */\n locationId?: string;\n /**\n * Additional zone for STANDARD_HA. Immutable. Must differ from\n * `locationId`.\n */\n alternativeLocationId?: string;\n /**\n * User-facing display name.\n */\n displayName?: string;\n /**\n * User labels. Alchemy ownership labels are merged in automatically.\n */\n labels?: Record\u003cstring, string>;\n /**\n * Redis software version (`REDIS_7_0`, `REDIS_7_2`, …). Upgrading uses\n * `instances.upgrade`; downgrading replaces the instance.\n */\n redisVersion?: string;\n /**\n * Reserved IP CIDR (`DIRECT_PEERING`) or allocated range name\n * (`PRIVATE_SERVICE_ACCESS`). Immutable.\n */\n reservedIpRange?: string;\n /**\n * Extra IP range used when enabling read replicas (`auto` or a CIDR /\n * allocated range name).\n */\n secondaryIpRange?: string;\n /**\n * Redis config parameters (`maxmemory-policy`, `notify-keyspace-events`,\n * …). See Memorystore supported parameters.\n */\n redisConfigs?: Record\u003cstring, string>;\n /**\n * Service tier. Immutable — changing it replaces the instance.\n * @default \"BASIC\"\n */\n tier?: redis.InstanceTierEnum | (string & {});\n /**\n * Memory size in GiB.\n * @default 1\n */\n memorySizeGb?: number;\n /**\n * VPC network\n * (`projects/{project}/global/networks/{network}`). Immutable. Defaults\n * to the project `default` network.\n */\n authorizedNetwork?: string;\n /**\n * Network connect mode. Immutable.\n * @default \"DIRECT_PEERING\"\n */\n connectMode?: redis.InstanceConnectModeEnum | (string & {});\n /**\n * Enable OSS Redis AUTH.\n * @default false\n */\n authEnabled?: boolean;\n /**\n * In-transit TLS mode. Immutable.\n * @default \"DISABLED\"\n */\n transitEncryptionMode?: redis.InstanceTransitEncryptionModeEnum | (string & {});\n /**\n * Maintenance policy. If omitted, Memorystore may perform maintenance\n * at any time.\n */\n maintenancePolicy?: MaintenancePolicy;\n /**\n * Replica count. BASIC is `0`. STANDARD_HA without read replicas is\n * `1`. STANDARD_HA with read replicas is `1`–`5`.\n */\n replicaCount?: number;\n /**\n * Read replica mode. Create-time only — changing it replaces the\n * instance.\n */\n readReplicasMode?: redis.InstanceReadReplicasModeEnum | (string & {});\n /**\n * Customer-managed KMS key for at-rest encryption\n * (`projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}`). Immutable.\n */\n customerManagedKey?: string;\n /**\n * RDB persistence configuration.\n */\n persistenceConfig?: PersistenceConfig;\n /**\n * Self-service maintenance version (e.g. `\"20210712_00_00\"`).\n */\n maintenanceVersion?: string;\n};\n\nexport type Instance = Resource\u003c\n \"GCP.Redis.Instance\",\n InstanceProps,\n {\n /** Full resource name `projects/{project}/locations/{location}/instances/{instance}`. */\n name: string;\n /** Instance id (last path segment). */\n instanceId: string;\n /** Project id. */\n project: string;\n /** Region id (`us-central1`, …). */\n location: string;\n /** User-facing display name. */\n displayName: string | undefined;\n /** User labels (Alchemy ownership labels stripped). */\n labels: Record\u003cstring, string>;\n /** Provisioned primary zone. */\n locationId: string | undefined;\n /** Additional STANDARD_HA zone. */\n alternativeLocationId: string | undefined;\n /** Current primary zone (may change after failover). */\n currentLocationId: string | undefined;\n /** Redis software version. */\n redisVersion: string | undefined;\n /** Reserved IP CIDR or allocated range name. */\n reservedIpRange: string | undefined;\n /** Extra IP range for read replicas. */\n secondaryIpRange: string | undefined;\n /** Redis endpoint hostname or IP. */\n host: string | undefined;\n /** Redis endpoint port. */\n port: number | undefined;\n /** Server-reported state (`READY`, `CREATING`, …). */\n state: string | undefined;\n /** Extra status text, if any. */\n statusMessage: string | undefined;\n /** Redis config parameters currently applied. */\n redisConfigs: Record\u003cstring, string>;\n /** Service tier (`BASIC`, `STANDARD_HA`). */\n tier: string;\n /** Memory size in GiB. */\n memorySizeGb: number;\n /** Authorized VPC network. */\n authorizedNetwork: string | undefined;\n /** IAM identity used for import/export. */\n persistenceIamIdentity: string | undefined;\n /** Network connect mode. */\n connectMode: string | undefined;\n /** Whether OSS Redis AUTH is enabled. */\n authEnabled: boolean;\n /** In-transit TLS mode. */\n transitEncryptionMode: string | undefined;\n /** Replica count. */\n replicaCount: number | undefined;\n /** Per-node info. */\n nodes: redis.NodeInfo[];\n /** Read replica endpoint hostname (STANDARD_HA). */\n readEndpoint: string | undefined;\n /** Read replica endpoint port. */\n readEndpointPort: number | undefined;\n /** Read replica mode. */\n readReplicasMode: string | undefined;\n /** Customer-managed KMS key, if any. */\n customerManagedKey: string | undefined;\n /** Persistence configuration currently applied. */\n persistenceConfig: PersistenceConfig | undefined;\n /** Self-service maintenance version. */\n maintenanceVersion: string | undefined;\n /** RFC3339 creation timestamp. */\n createTime: string | undefined;\n },\n never,\n Providers\n>;\n\n/**\n * A Memorystore for Redis instance.\n *\n * Changing `instanceId`, `location`, `tier`, `connectMode`,\n * `authorizedNetwork`, `reservedIpRange`, `locationId`,\n * `alternativeLocationId`, `transitEncryptionMode`, `customerManagedKey`,\n * or `readReplicasMode` replaces the instance. Redis version upgrades use\n * `instances.upgrade`; a downgrade replaces the instance.\n *\n * Provisioning typically takes several minutes.\n *\n * ### Creating an Instance\n * **Example:** Generated name, BASIC 1 GiB\n * ```typescript\n * const cache = yield* GCP.Redis.Instance(\"Cache\", {});\n * ```\n *\n * **Example:** Explicit id, labels, and AUTH\n * ```typescript\n * const cache = yield* GCP.Redis.Instance(\"Cache\", {\n * instanceId: \"app-cache\",\n * location: \"us-central1\",\n * memorySizeGb: 1,\n * authEnabled: true,\n * labels: { env: \"prod\" },\n * });\n * ```\n *\n * ### Binding from a Function\n * **Example:** ReadWriteRedis from a Function\n * ```typescript\n * export class Api extends GCP.Function\u003cApi>()(\n * \"Api\",\n * { main: import.meta.url },\n * Effect.gen(function* () {\n * const cache = yield* GCP.Redis.Instance(\"Cache\", { memorySizeGb: 1 });\n * const redis = yield* GCP.Redis.ReadWriteRedis(cache);\n * return {\n * fetch: Effect.gen(function* () {\n * yield* redis.set(\"k\", \"v\").pipe(Effect.orDie);\n * return HttpServerResponse.text(\"ok\");\n * }),\n * };\n * }).pipe(Effect.provide([GCP.Redis.ReadWriteRedisHttp])),\n * ) {}\n * ```\n *\n * ### Destroying an Instance\n * **Example:** Delete waits out CREATING\n * ```typescript\n * const cache = yield* GCP.Redis.Instance(\"Cache\", { memorySizeGb: 1 });\n * ```\n * `alchemy destroy` waits for `CREATING` to finish, then retries `Conflict` until the instance is gone.\n *\n * ### High Availability\n * **Example:** STANDARD_HA across two zones\n * ```typescript\n * const cache = yield* GCP.Redis.Instance(\"Cache\", {\n * tier: \"STANDARD_HA\",\n * locationId: \"us-central1-a\",\n * alternativeLocationId: \"us-central1-f\",\n * memorySizeGb: 1,\n * });\n * ```\n *\n * @resource\n * @category Redis\n */\nexport const Instance = Resource\u003cInstance>(\"GCP.Redis.Instance\");\n\nexport class InstanceNotResolved extends Data.TaggedError(\"GCP.Redis.InstanceNotResolved\")\u003c{\n resourceName: string;\n}> {}\n\nexport class InstanceNotReady extends Data.TaggedError(\"GCP.Redis.InstanceNotReady\")\u003c{\n resourceName: string;\n state: string;\n}> {}\n\nexport class InstanceOperationPending extends Data.TaggedError(\n \"GCP.Redis.InstanceOperationPending\",\n)\u003c{\n operation: string;\n}> {}\n\nexport class InstanceStillExists extends Data.TaggedError(\"GCP.Redis.InstanceStillExists\")\u003c{\n resourceName: string;\n}> {}\n\nconst lastSegment = (value: string) => {\n const trimmed = value.replace(/\\/+$/, \"\");\n const parts = trimmed.split(\"/\");\n return parts[parts.length - 1] || trimmed;\n};\n\nconst normalizeLocation = (location: string | undefined, fallback: string) =>\n lastSegment(location ?? fallback).toLowerCase();\n\nconst normalizeTier = (tier: string | undefined) => {\n const value = (tier ?? DEFAULT_TIER).toUpperCase();\n return value === \"TIER_UNSPECIFIED\" ? DEFAULT_TIER : value;\n};\n\nconst normalizeConnectMode = (mode: string | undefined) => {\n const value = (mode ?? DEFAULT_CONNECT_MODE).toUpperCase();\n return value === \"CONNECT_MODE_UNSPECIFIED\" ? DEFAULT_CONNECT_MODE : value;\n};\n\nconst normalizeTransit = (mode: string | undefined) => {\n const value = (mode ?? DEFAULT_TRANSIT_ENCRYPTION).toUpperCase();\n return value === \"TRANSIT_ENCRYPTION_MODE_UNSPECIFIED\" ? DEFAULT_TRANSIT_ENCRYPTION : value;\n};\n\nconst normalizeReadReplicas = (mode: string | undefined) =>\n (mode ?? \"READ_REPLICAS_DISABLED\").toUpperCase();\n\nconst rfc1035 = (name: string): string => {\n let next = name\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n if (!/^[a-z]/.test(next)) next = `r${next}`;\n next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, \"\");\n if (next.length === 0) return \"instance\";\n if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`;\n return next.slice(0, MAX_NAME_LENGTH);\n};\n\nconst resourceName = (project: string, location: string, instanceId: string) =>\n `projects/${project}/locations/${location}/instances/${instanceId}`;\n\nconst parseName = (name: string, fallbackLocation: string) => {\n const parts = name.split(\"/\").filter((part) => part.length > 0);\n const instancesAt = parts.lastIndexOf(\"instances\");\n const locationsAt = parts.lastIndexOf(\"locations\");\n const projectsAt = parts.lastIndexOf(\"projects\");\n return {\n project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : \"\",\n location:\n locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation,\n instanceId:\n instancesAt >= 0 && parts[instancesAt + 1] ? parts[instancesAt + 1]! : lastSegment(name),\n };\n};\n\nconst userLabels = (\n labels: Record\u003cstring, string | undefined> | null | undefined,\n): Record\u003cstring, string> => stripInternalLabels(tagRecord(labels));\n\nconst toId = (id: string, instanceId: string | undefined, existing?: string) =>\n Effect.gen(function* () {\n return (\n instanceId ??\n existing ??\n rfc1035(\n yield* createPhysicalName({\n id,\n maxLength: MAX_NAME_LENGTH,\n lowercase: true,\n }),\n )\n );\n });\n\nconst configsOf = (\n configs: Record\u003cstring, string | undefined> | null | undefined,\n): Record\u003cstring, string> =>\n Object.fromEntries(\n Object.entries(configs ?? {}).filter(\n (entry): entry is [string, string] => entry[1] !== undefined,\n ),\n );\n\nconst configsKey = (configs: Record\u003cstring, string | undefined> | null | undefined) =>\n JSON.stringify(\n Object.fromEntries(Object.entries(configsOf(configs)).sort(([a], [b]) => a.localeCompare(b))),\n );\n\nconst persistenceOf = (\n config: redis.PersistenceConfig | PersistenceConfig | undefined,\n): PersistenceConfig | undefined => {\n if (config === undefined) return undefined;\n return {\n persistenceMode: config.persistenceMode,\n rdbSnapshotPeriod: config.rdbSnapshotPeriod,\n rdbSnapshotStartTime: config.rdbSnapshotStartTime,\n };\n};\n\nconst persistenceKey = (config: redis.PersistenceConfig | PersistenceConfig | undefined) => {\n const value = persistenceOf(config);\n return JSON.stringify({\n persistenceMode: (value?.persistenceMode ?? \"\").toUpperCase(),\n rdbSnapshotPeriod: (value?.rdbSnapshotPeriod ?? \"\").toUpperCase(),\n rdbSnapshotStartTime: value?.rdbSnapshotStartTime ?? \"\",\n });\n};\n\nconst windowKey = (window: WeeklyMaintenanceWindow) =>\n JSON.stringify({\n day: (window.day ?? \"\").toUpperCase(),\n hours: window.startTime?.hours ?? 0,\n minutes: window.startTime?.minutes ?? 0,\n seconds: window.startTime?.seconds ?? 0,\n nanos: window.startTime?.nanos ?? 0,\n });\n\nconst maintenanceKey = (policy: MaintenancePolicy | undefined) =>\n JSON.stringify({\n description: policy?.description ?? \"\",\n windows: (policy?.weeklyMaintenanceWindow ?? []).map(windowKey),\n });\n\nconst parseRedisVersion = (version: string | undefined) => {\n if (version === undefined) return undefined;\n const match = version.toUpperCase().match(/^REDIS_(\\d+)_(\\d+|X)$/);\n if (!match) return undefined;\n const minor = match[2] === \"X\" ? 99 : Number(match[2]);\n return Number(match[1]) * 100 + minor;\n};\n\nconst versionDecreasing = (previous: string | undefined, next: string) => {\n const oldN = parseRedisVersion(previous);\n const newN = parseRedisVersion(next);\n if (oldN === undefined || newN === undefined) return previous !== next;\n return newN \u003c oldN;\n};\n\nconst toAttrs = (instance: redis.Instance, project: string, region: string) => {\n const name = instance.name ?? \"\";\n const parsed = parseName(name, region);\n return {\n name,\n instanceId: parsed.instanceId,\n project: parsed.project || project,\n location: parsed.location,\n displayName: instance.displayName,\n labels: userLabels(instance.labels),\n locationId: instance.locationId,\n alternativeLocationId: instance.alternativeLocationId,\n currentLocationId: instance.currentLocationId,\n redisVersion: instance.redisVersion,\n reservedIpRange: instance.reservedIpRange,\n secondaryIpRange: instance.secondaryIpRange,\n host: instance.host,\n port: instance.port,\n state: instance.state,\n statusMessage: instance.statusMessage,\n redisConfigs: configsOf(instance.redisConfigs),\n tier: normalizeTier(instance.tier),\n memorySizeGb: instance.memorySizeGb ?? DEFAULT_MEMORY_SIZE_GB,\n authorizedNetwork: instance.authorizedNetwork,\n persistenceIamIdentity: instance.persistenceIamIdentity,\n connectMode: instance.connectMode,\n authEnabled: instance.authEnabled === true,\n transitEncryptionMode: instance.transitEncryptionMode,\n replicaCount: instance.replicaCount,\n nodes: instance.nodes ?? [],\n readEndpoint: instance.readEndpoint,\n readEndpointPort: instance.readEndpointPort,\n readReplicasMode: instance.readReplicasMode,\n customerManagedKey: instance.customerManagedKey,\n persistenceConfig: persistenceOf(instance.persistenceConfig),\n maintenanceVersion: instance.maintenanceVersion,\n createTime: instance.createTime,\n };\n};\n\nconst isPlaceholder = (instance: redis.Instance) => {\n const name = instance.name ?? \"\";\n return name.endsWith(\"/instances/-\") || name.endsWith(\"/instances/\");\n};\n\nconst getByName = (name: string) =>\n redis\n .getProjectsLocationsInstances({ name })\n .pipe(Effect.catchTag(\"NotFound\", () => Effect.undefined));\n\n/** Wait for an operation through the shared GCP waiter. */\nconst waitForOperation = (operation: redis.Operation, options?: { notFoundOk?: boolean }) =>\n waitForGcpOperation(\n operation,\n (name) =>\n redis\n .getProjectsLocationsOperations({ name })\n .pipe(\n Effect.catchTag(\"NotFound\", (error) =>\n options?.notFoundOk === true\n ? Effect.succeed\u003credis.Operation>({ name, done: true })\n : Effect.fail(error),\n ),\n ),\n { budget: \"30 minutes\" },\n ).pipe(\n // ALREADY_EXISTS (6): a concurrent create won the race. NOT_FOUND (5)\n // is success for a delete.\n Effect.catchIf(\n (error) =>\n error._tag === \"GCP.OperationFailed\" &&\n (error.code === 6 || (options?.notFoundOk === true && error.code === 5)),\n () => Effect.void,\n ),\n );\n\nconst waitUntilExists = (name: string) =>\n getByName(name).pipe(\n Effect.flatMap((instance) =>\n instance\n ? Effect.succeed(instance)\n : Effect.fail(new InstanceNotResolved({ resourceName: name })),\n ),\n Effect.retry({\n while: (error) => error._tag === \"GCP.Redis.InstanceNotResolved\",\n times: 8,\n schedule: Schedule.spaced(\"1 second\"),\n }),\n );\n\nconst waitUntilReady = (name: string) =>\n getByName(name).pipe(\n Effect.filterOrFail(\n (instance): instance is redis.Instance => instance !== undefined,\n () => new InstanceNotResolved({ resourceName: name }),\n ),\n Effect.filterOrFail(\n (instance) => (instance.state ?? \"STATE_UNSPECIFIED\") === \"READY\",\n (instance) =>\n new InstanceNotReady({\n resourceName: name,\n state: instance.state ?? \"STATE_UNSPECIFIED\",\n }),\n ),\n Effect.retry({\n while: (error) =>\n error._tag === \"GCP.Redis.InstanceNotReady\" ||\n error._tag === \"GCP.Redis.InstanceNotResolved\",\n ...LONG_POLL,\n }),\n );\n\nconst waitUntilGone = (name: string) =>\n getByName(name).pipe(\n Effect.flatMap((instance) =>\n instance === undefined\n ? Effect.void\n : Effect.fail(new InstanceStillExists({ resourceName: name })),\n ),\n Effect.retry({\n while: (error) => error._tag === \"GCP.Redis.InstanceStillExists\",\n ...LONG_POLL,\n }),\n );\n\nconst toCreateBody = (\n news: InstanceProps,\n desiredLabels: Record\u003cstring, string>,\n tier: string,\n connectMode: string,\n transitEncryptionMode: string,\n memorySizeGb: number,\n authEnabled: boolean,\n): redis.Instance => ({\n displayName: news.displayName,\n labels: desiredLabels,\n locationId: news.locationId,\n alternativeLocationId: news.alternativeLocationId,\n redisVersion: news.redisVersion,\n reservedIpRange: news.reservedIpRange,\n secondaryIpRange: news.secondaryIpRange,\n redisConfigs: news.redisConfigs,\n tier,\n memorySizeGb,\n authorizedNetwork: news.authorizedNetwork,\n connectMode,\n authEnabled,\n transitEncryptionMode,\n maintenancePolicy: news.maintenancePolicy,\n replicaCount: news.replicaCount,\n readReplicasMode: news.readReplicasMode,\n customerManagedKey: news.customerManagedKey,\n persistenceConfig: news.persistenceConfig,\n});\n\nexport const InstanceProvider = () =>\n Provider.succeed(Instance, {\n stables: [\"name\", \"instanceId\", \"project\", \"location\", \"createTime\"],\n\n diff: Effect.fn(function* ({ news, olds, output }) {\n if (!isResolved(news)) return undefined;\n const env = yield* GcpEnvironment.current;\n\n const previousId = olds?.instanceId ?? output?.instanceId;\n const nextId = news.instanceId ?? previousId;\n const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);\n const nextLocation = normalizeLocation(news.location ?? output?.location, env.region);\n const previousTier = normalizeTier(olds?.tier ?? output?.tier);\n const nextTier = normalizeTier(news.tier ?? output?.tier);\n const previousConnect = normalizeConnectMode(olds?.connectMode ?? output?.connectMode);\n const nextConnect = normalizeConnectMode(news.connectMode ?? output?.connectMode);\n const previousTransit = normalizeTransit(\n olds?.transitEncryptionMode ?? output?.transitEncryptionMode,\n );\n const nextTransit = normalizeTransit(\n news.transitEncryptionMode ?? output?.transitEncryptionMode,\n );\n const previousNetwork = olds?.authorizedNetwork ?? output?.authorizedNetwork ?? \"\";\n const nextNetwork = news.authorizedNetwork ?? previousNetwork;\n const previousRange = olds?.reservedIpRange ?? output?.reservedIpRange ?? \"\";\n const nextRange = news.reservedIpRange ?? previousRange;\n const previousZone = olds?.locationId ?? output?.locationId ?? \"\";\n const nextZone = news.locationId ?? previousZone;\n const previousAlt = olds?.alternativeLocationId ?? output?.alternativeLocationId ?? \"\";\n const nextAlt = news.alternativeLocationId ?? previousAlt;\n const previousCmek = olds?.customerManagedKey ?? output?.customerManagedKey ?? \"\";\n const nextCmek = news.customerManagedKey ?? previousCmek;\n const previousReplicas = normalizeReadReplicas(\n olds?.readReplicasMode ?? output?.readReplicasMode,\n );\n const nextReplicas = normalizeReadReplicas(news.readReplicasMode ?? output?.readReplicasMode);\n const previousVersion = olds?.redisVersion ?? output?.redisVersion;\n const nextVersion = news.redisVersion;\n const downgrade =\n nextVersion !== undefined &&\n previousVersion !== undefined &&\n versionDecreasing(previousVersion, nextVersion);\n\n const replace =\n (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||\n previousLocation !== nextLocation ||\n previousTier !== nextTier ||\n previousConnect !== nextConnect ||\n previousTransit !== nextTransit ||\n previousNetwork !== nextNetwork ||\n previousRange !== nextRange ||\n previousZone !== nextZone ||\n previousAlt !== nextAlt ||\n previousCmek !== nextCmek ||\n previousReplicas !== nextReplicas ||\n downgrade;\n\n if (!replace) return undefined;\n return {\n action: \"replace\" as const,\n deleteFirst:\n previousLocation === nextLocation && previousId !== undefined && nextId === previousId,\n };\n }),\n\n read: Effect.fn(function* ({ id, olds, output }) {\n const env = yield* GcpEnvironment.current;\n const instanceId = yield* toId(id, olds?.instanceId, output?.instanceId);\n const location = normalizeLocation(olds?.location ?? output?.location, env.region);\n const name = output?.name ?? resourceName(env.project, location, instanceId);\n const existing = yield* getByName(name);\n if (existing === undefined) return undefined;\n const attrs = toAttrs(existing, env.project, env.region);\n return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);\n }),\n\n list: () =>\n Effect.gen(function* () {\n const env = yield* GcpEnvironment.current;\n return yield* redis.listProjectsLocationsInstances\n .pages({\n parent: `projects/${env.project}/locations/-`,\n pageSize: 1000,\n })\n .pipe(\n Stream.flatMap((page) => Stream.fromIterable(page.instances ?? [])),\n Stream.filter(\n (instance) =>\n !isPlaceholder(instance) &&\n Object.keys(instance.labels ?? {}).some((key) => key.startsWith(\"alchemy-\")),\n ),\n Stream.map((instance) => toAttrs(instance, env.project, env.region)),\n Stream.runCollect,\n Effect.map((chunk) => Array.from(chunk)),\n Effect.catchTag(\"NotFound\", () => Effect.succeed([])),\n );\n }),\n\n reconcile: Effect.fn(function* ({ id, news, output }) {\n const env = yield* GcpEnvironment.current;\n const instanceId = yield* toId(id, news.instanceId, output?.instanceId);\n const location = normalizeLocation(news.location ?? output?.location, env.region);\n const name = resourceName(env.project, location, instanceId);\n const tier = normalizeTier(news.tier);\n const connectMode = normalizeConnectMode(news.connectMode);\n const transitEncryptionMode = normalizeTransit(news.transitEncryptionMode);\n const memorySizeGb = news.memorySizeGb ?? DEFAULT_MEMORY_SIZE_GB;\n const authEnabled = news.authEnabled === true;\n const desiredLabels = {\n ...toLabels(news.labels),\n ...(yield* createInternalLabels(id)),\n };\n\n let current = yield* getByName(output?.name ?? name);\n\n if (current === undefined) {\n const created = yield* redis\n .createProjectsLocationsInstances({\n parent: `projects/${env.project}/locations/${location}`,\n instanceId,\n body: toCreateBody(\n news,\n desiredLabels,\n tier,\n connectMode,\n transitEncryptionMode,\n memorySizeGb,\n authEnabled,\n ),\n })\n .pipe(Effect.catchTag(\"Conflict\", () => Effect.undefined));\n if (created !== undefined) {\n yield* waitForOperation(created);\n }\n current = yield* waitUntilExists(name);\n }\n\n if (current === undefined) {\n return yield* new InstanceNotResolved({ resourceName: name });\n }\n\n if ((current.state ?? \"\") !== \"READY\") {\n current = yield* waitUntilReady(name);\n }\n\n const desiredVersion = news.redisVersion;\n const currentVersion = current.redisVersion;\n if (\n desiredVersion !== undefined &&\n currentVersion !== undefined &&\n desiredVersion !== currentVersion &&\n !versionDecreasing(currentVersion, desiredVersion)\n ) {\n const upgraded = yield* redis.upgradeProjectsLocationsInstances({\n name,\n body: { redisVersion: desiredVersion },\n });\n yield* waitForOperation(upgraded);\n current = yield* waitUntilReady(name);\n }\n\n const observedLabels = tagRecord(current.labels);\n const { upsert, removed } = diffLabels(observedLabels, desiredLabels);\n const labelsChanged = upsert.length > 0 || removed.length > 0;\n const displayNameChanged = (current.displayName ?? \"\") !== (news.displayName ?? \"\");\n const memoryChanged = (current.memorySizeGb ?? DEFAULT_MEMORY_SIZE_GB) !== memorySizeGb;\n const authChanged = (current.authEnabled === true) !== authEnabled;\n const configsChanged =\n news.redisConfigs !== undefined &&\n configsKey(current.redisConfigs) !== configsKey(news.redisConfigs);\n const persistenceChanged =\n news.persistenceConfig !== undefined &&\n persistenceKey(current.persistenceConfig) !== persistenceKey(news.persistenceConfig);\n const maintenanceChanged =\n news.maintenancePolicy !== undefined &&\n maintenanceKey(current.maintenancePolicy) !== maintenanceKey(news.maintenancePolicy);\n const replicaChanged =\n news.replicaCount !== undefined && (current.replicaCount ?? 0) !== news.replicaCount;\n const secondaryChanged =\n news.secondaryIpRange !== undefined &&\n (current.secondaryIpRange ?? \"\") !== news.secondaryIpRange;\n const maintenanceVersionChanged =\n news.maintenanceVersion !== undefined &&\n (current.maintenanceVersion ?? \"\") !== news.maintenanceVersion;\n\n if (\n labelsChanged ||\n displayNameChanged ||\n memoryChanged ||\n authChanged ||\n configsChanged ||\n persistenceChanged ||\n maintenanceChanged ||\n replicaChanged ||\n secondaryChanged ||\n maintenanceVersionChanged\n ) {\n const updateMask = [\n labelsChanged ? \"labels\" : undefined,\n displayNameChanged ? \"displayName\" : undefined,\n memoryChanged ? \"memorySizeGb\" : undefined,\n authChanged ? \"authEnabled\" : undefined,\n configsChanged ? \"redisConfig\" : undefined,\n persistenceChanged ? \"persistenceConfig\" : undefined,\n maintenanceChanged ? \"maintenancePolicy\" : undefined,\n replicaChanged ? \"replica_count\" : undefined,\n secondaryChanged ? \"secondaryIpRange\" : undefined,\n maintenanceVersionChanged ? \"maintenanceVersion\" : undefined,\n ].filter((field): field is string => field !== undefined);\n\n const patched = yield* redis.patchProjectsLocationsInstances({\n name,\n updateMask: updateMask.join(\",\"),\n body: {\n name,\n labels: desiredLabels,\n displayName: news.displayName,\n memorySizeGb,\n authEnabled,\n redisConfigs: news.redisConfigs,\n persistenceConfig: news.persistenceConfig,\n maintenancePolicy: news.maintenancePolicy,\n replicaCount: news.replicaCount,\n secondaryIpRange: news.secondaryIpRange,\n maintenanceVersion: news.maintenanceVersion,\n },\n });\n yield* waitForOperation(patched);\n current = yield* waitUntilReady(name);\n }\n\n return toAttrs(current, env.project, env.region);\n }),\n\n delete: Effect.fn(function* ({ output }) {\n yield* getByName(output.name).pipe(\n Effect.filterOrFail(\n (instance) => instance === undefined || (instance.state ?? \"\") !== \"CREATING\",\n () => new InstanceOperationPending({ operation: output.name }),\n ),\n Effect.retry({\n while: (error) => error._tag === \"GCP.Redis.InstanceOperationPending\",\n ...LONG_POLL,\n }),\n );\n const operation = yield* redis.deleteProjectsLocationsInstances({ name: output.name }).pipe(\n Effect.catchTag(\"NotFound\", () => Effect.undefined),\n Effect.retry({\n while: (error) => error._tag === \"Conflict\",\n times: 24,\n schedule: Schedule.spaced(\"8 seconds\"),\n }),\n );\n if (operation !== undefined) {\n yield* waitForOperation(operation, { notFoundOk: true });\n }\n yield* waitUntilGone(output.name);\n }),\n });\n","preview":null,"history":null,"version":"26bb36e602a1c5e68a11bd4578c7c4d56844a470"},"/_session?shell=1":null}