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

import * as spanner from "@distilled.cloud/gcp/spanner_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 type { Providers } from "../Providers.ts";
import { waitForOperation } from "./operations.ts";

const DEFAULT_PROCESSING_UNITS = 100;
const DEFAULT_INSTANCE_TYPE = "PROVISIONED";
const DEFAULT_EDITION = "STANDARD";
const DEFAULT_BACKUP_SCHEDULE = "NONE";
const MAX_INSTANCE_ID_LENGTH = 64;
const MAX_DISPLAY_NAME_LENGTH = 30;
const MIN_DISPLAY_NAME_LENGTH = 4;

export type InstanceType = spanner.InstanceInstanceTypeEnum | (string & {});
export type InstanceEdition = spanner.InstanceEditionEnum | (string & {});
export type InstanceDefaultBackupScheduleType =
  | spanner.InstanceDefaultBackupScheduleTypeEnum
  | (string & {});

export type AutoscalingLimits = {
  /** Minimum nodes. Mutually exclusive with processing-unit limits. */
  minNodes?: number;
  /** Minimum processing units (multiples of 1000). */
  minProcessingUnits?: number;
  /** Maximum nodes. */
  maxNodes?: number;
  /** Maximum processing units (multiples of 1000). */
  maxProcessingUnits?: number;
};

export type AutoscalingTargets = {
  /** Target high-priority CPU percent (`10`–`90`). */
  highPriorityCpuUtilizationPercent?: number;
  /** Target total CPU percent (`10`–`90`). */
  totalCpuUtilizationPercent?: number;
  /** Target storage percent (`10`–`99`). */
  storageUtilizationPercent?: number;
};

export type AutoscalingConfig = {
  /** Min/max compute capacity. */
  autoscalingLimits?: AutoscalingLimits;
  /** CPU and storage targets. */
  autoscalingTargets?: AutoscalingTargets;
};

export type ReplicaComputeCapacity = {
  /** Replica location (e.g. `us-central1`). */
  location?: string;
  /** Nodes allocated to this replica selection. */
  nodeCount?: number;
  /** Processing units allocated to this replica selection. */
  processingUnits?: number;
};

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

	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	.repos/alchemy-effect/packages/gcp/src/Spanner/Instance.ts at main · sailfork/t3code-github · Sailfork
	
		
(2–64 characters). Immutable — changing * it replaces the instance. */ instanceId?: string; /** * Instance configuration id (`regional-us-central1`) or full name * (`projects/{project}/instanceConfigs/{config}`). Immutable — * changing it replaces the instance. * @default `regional-{region}` for the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`) */ config?: string; /** * User-facing display name. Must be unique per project and 4–30 * characters. Defaults to a truncated instance id. */ displayName?: string; /** * User labels. Alchemy ownership labels are merged in automatically. */ labels?: Record<string, string>; /** * Processing units. Mutually exclusive with `nodeCount`. Ignored when * autoscaling is enabled or `instanceType` is `FREE_INSTANCE`. * @default 100 */ processingUnits?: number; /** * Node count. Mutually exclusive with `processingUnits`. Ignored when * autoscaling is enabled or `instanceType` is `FREE_INSTANCE`. */ nodeCount?: number; /** * Autoscaling configuration. When set, `nodeCount` and * `processingUnits` become output-only. */ autoscalingConfig?: AutoscalingConfig; /** * Instance type. Immutable — changing it replaces the instance. * @default "PROVISIONED" */ instanceType?: InstanceType; /** * Edition (`STANDARD`, `ENTERPRISE`, `ENTERPRISE_PLUS`). * @default "STANDARD" */ edition?: InstanceEdition; /** * Default backup schedule for new databases. `NONE` skips automatic * schedules (required for free instances). * @default "NONE" */ defaultBackupScheduleType?: InstanceDefaultBackupScheduleType; }; export type Instance = Resource< "GCP.Spanner.Instance", InstanceProps, { /** Full resource name `projects/{project}/instances/{instance}`. */ name: string; /** Instance id (last path segment). */ instanceId: string; /** Project id. */ project: string; /** Full instance config name. */ config: string; /** User-facing display name. */ displayName: string | undefined; /** User labels (Alchemy ownership labels stripped). */ labels: Record<string, string>; /** Processing units currently allocated. */ processingUnits: number | undefined; /** Nodes currently allocated. */ nodeCount: number | undefined; /** Autoscaling configuration, if enabled. */ autoscalingConfig: AutoscalingConfig | undefined; /** Compute capacity per replica selection. */ replicaComputeCapacity: ReplicaComputeCapacity[]; /** Instance type (`PROVISIONED`, `FREE_INSTANCE`). */ instanceType: string | undefined; /** Edition (`STANDARD`, `ENTERPRISE`, `ENTERPRISE_PLUS`). */ edition: string | undefined; /** Default backup schedule type. */ defaultBackupScheduleType: string | undefined; /** Current instance state (`CREATING`, `READY`). */ state: string | undefined; /** RFC3339 creation timestamp. */ createTime: string | undefined; /** RFC3339 last-update timestamp. */ updateTime: string | undefined; }, never, Providers >; /** * A Cloud Spanner instance. * * Changing `instanceId`, `config`, or `instanceType` replaces the * instance. Display name, labels, compute capacity, edition, backup * schedule, and autoscaling update in place. Create, update, and delete * are long-running operations — a 100 processing-unit regional instance * typically takes one to two minutes. * * ### Creating an Instance * **Example:** Generated name, 100 processing units * ```typescript * const instance = yield* GCP.Spanner.Instance("App", {}); * ``` * * **Example:** Explicit id, config, and labels * ```typescript * const instance = yield* GCP.Spanner.Instance("App", { * instanceId: "app-spanner", * config: "regional-us-central1", * displayName: "app-spanner", * processingUnits: 100, * labels: { env: "prod" }, * }); * ``` * * ### Observing Instances * **Example:** Read the bound instance * ```typescript * const getInstance = yield* GCP.Spanner.GetInstance(instance); * const live = yield* getInstance(); * ``` * * @resource * @category Spanner */ export const Instance = Resource<Instance>("GCP.Spanner.Instance"); export class InstanceNotResolved extends Data.TaggedError("GCP.Spanner.InstanceNotResolved")<{ resourceName: string; }> {} export class InstanceNotReady extends Data.TaggedError("GCP.Spanner.InstanceNotReady")<{ resourceName: string; state: string; }> {} export class InstanceStillExists extends Data.TaggedError("GCP.Spanner.InstanceStillExists")<{ resourceName: string; }> {} const lastSegment = (value: string) => { const trimmed = value.replace(/\/+$/, ""); const parts = trimmed.split("/"); return parts[parts.length - 1] || trimmed; }; const normalizeEnum = (value: string | undefined, fallback: string) => { const next = (value ?? fallback).toUpperCase(); return next.endsWith("_UNSPECIFIED") ? fallback : next; }; const normalizeInstanceType = (value: string | undefined) => normalizeEnum(value, DEFAULT_INSTANCE_TYPE); const normalizeEdition = (value: string | undefined) => normalizeEnum(value, DEFAULT_EDITION); const normalizeBackupSchedule = (value: string | undefined) => normalizeEnum(value, DEFAULT_BACKUP_SCHEDULE); const defaultConfigId = (region: string) => `regional-${region}`; const configIdOf = (config: string | undefined, region: string) => lastSegment(config ?? defaultConfigId(region)).toLowerCase(); const configNameOf = (project: string, config: string | undefined, region: string) => { const raw = (config ?? defaultConfigId(region)).trim(); if (raw.includes("/")) return raw; return `projects/${project}/instanceConfigs/${raw}`; }; const resourceName = (project: string, instanceId: string) => `projects/${project}/instances/${instanceId}`; const parseName = (name: string) => { const parts = name.split("/").filter((part) => part.length > 0); const instancesAt = parts.lastIndexOf("instances"); const projectsAt = parts.lastIndexOf("projects"); return { project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", instanceId: instancesAt >= 0 && parts[instancesAt + 1] ? parts[instancesAt + 1]! : lastSegment(name), }; }; const toSpannerId = (name: string) => { let next = name .toLowerCase() .replace(/[^a-z0-9-]/g, "-") .replace(/-+/g, "-"); next = next.replace(/^-+/, "").replace(/-+$/g, ""); if (!/^[a-z]/.test(next)) next = `s${next}`; next = next.slice(0, MAX_INSTANCE_ID_LENGTH).replace(/-+$/g, ""); if (next.length < 2) next = `${next}xx`.slice(0, MAX_INSTANCE_ID_LENGTH); return next; }; const toId = (id: string, instanceId: string | undefined, existing?: string) => Effect.gen(function* () { if (instanceId !== undefined) return instanceId; if (existing !== undefined) return existing; return toSpannerId( yield* createPhysicalName({ id, maxLength: MAX_INSTANCE_ID_LENGTH, lowercase: true, }), ); }); const displayNameOf = (instanceId: string, displayName?: string) => { const source = (displayName ?? instanceId).trim(); let next = source.slice(0, MAX_DISPLAY_NAME_LENGTH); if (next.length < MIN_DISPLAY_NAME_LENGTH) { next = `${next}inst`.slice(0, MAX_DISPLAY_NAME_LENGTH); } return next; }; const userLabels = ( labels: Record<string, string | undefined> | null | undefined, ): Record<string, string> => stripInternalLabels(tagRecord(labels)); const autoscalingOf = ( config: spanner.AutoscalingConfig | undefined, ): AutoscalingConfig | undefined => { if (config === undefined) return undefined; return { autoscalingLimits: config.autoscalingLimits ? { minNodes: config.autoscalingLimits.minNodes, minProcessingUnits: config.autoscalingLimits.minProcessingUnits, maxNodes: config.autoscalingLimits.maxNodes, maxProcessingUnits: config.autoscalingLimits.maxProcessingUnits, } : undefined, autoscalingTargets: config.autoscalingTargets ? { highPriorityCpuUtilizationPercent: config.autoscalingTargets.highPriorityCpuUtilizationPercent, totalCpuUtilizationPercent: config.autoscalingTargets.totalCpuUtilizationPercent, storageUtilizationPercent: config.autoscalingTargets.storageUtilizationPercent, } : undefined, }; }; const replicaCapacityOf = ( items: spanner.ReplicaComputeCapacityList | undefined, ): ReplicaComputeCapacity[] => (items ?? []).map((item) => ({ location: item.replicaSelection?.location, nodeCount: item.nodeCount, processingUnits: item.processingUnits, })); const autoscalingKey = (config: AutoscalingConfig | undefined) => JSON.stringify(config ?? null); const toAttrs = (instance: spanner.Instance, project: string): Instance["Attributes"] => { const name = instance.name ?? ""; const parsed = parseName(name); return { name, instanceId: parsed.instanceId, project: parsed.project || project, config: instance.config ?? "", displayName: instance.displayName, labels: userLabels(instance.labels), processingUnits: instance.processingUnits, nodeCount: instance.nodeCount, autoscalingConfig: autoscalingOf(instance.autoscalingConfig), replicaComputeCapacity: replicaCapacityOf(instance.replicaComputeCapacity), instanceType: instance.instanceType, edition: instance.edition, defaultBackupScheduleType: instance.defaultBackupScheduleType, state: instance.state, createTime: instance.createTime, updateTime: instance.updateTime, }; }; const getByName = (name: string) => spanner.getProjectsInstances({ name }).pipe(Effect.catchTag("NotFound", () => Effect.undefined)); 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.Spanner.InstanceNotResolved", times: 8, schedule: Schedule.spaced("2 seconds"), }), ); const waitUntilReady = (name: string) => getByName(name).pipe( Effect.filterOrFail( (instance): instance is spanner.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.Spanner.InstanceNotReady" || error._tag === "GCP.Spanner.InstanceNotResolved", times: 10, schedule: Schedule.spaced("8 seconds"), }), ); 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.Spanner.InstanceStillExists", times: 10, schedule: Schedule.spaced("8 seconds"), }), ); const retryConcurrentChanges = <A, E extends { readonly _tag: string }, R>( effect: Effect.Effect<A, E, R>, ) => effect.pipe( Effect.retry({ while: (error) => error._tag === "Conflict", times: 8, schedule: Schedule.spaced("5 seconds"), }), ); const toCreateInstance = ( name: string, news: InstanceProps, project: string, region: string, desiredLabels: Record<string, string>, instanceType: string, displayName: string, ): spanner.Instance => { const free = instanceType === "FREE_INSTANCE"; const autoscaling = news.autoscalingConfig; const body: spanner.Instance = { name, config: configNameOf(project, news.config, region), displayName, labels: desiredLabels, instanceType, }; if (!free) { body.edition = news.edition ? normalizeEdition(news.edition) : DEFAULT_EDITION; body.defaultBackupScheduleType = news.defaultBackupScheduleType ? normalizeBackupSchedule(news.defaultBackupScheduleType) : DEFAULT_BACKUP_SCHEDULE; } if (autoscaling !== undefined) { body.autoscalingConfig = autoscaling; } else if (!free) { if (news.nodeCount !== undefined) { body.nodeCount = news.nodeCount; } else { body.processingUnits = news.processingUnits ?? DEFAULT_PROCESSING_UNITS; } } return body; }; export const InstanceProvider = () => Provider.succeed(Instance, { stables: ["name", "instanceId", "project", "config", "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 previousConfig = configIdOf(olds?.config ?? output?.config, env.region); const nextConfig = configIdOf(news.config ?? output?.config, env.region); const previousType = normalizeInstanceType(olds?.instanceType ?? output?.instanceType); const nextType = normalizeInstanceType(news.instanceType ?? output?.instanceType); const replace = (previousId !== undefined && nextId !== undefined && nextId !== previousId) || previousConfig !== nextConfig || previousType !== nextType; if (!replace) return undefined; return { action: "replace" as const, deleteFirst: previousConfig !== nextConfig || previousType !== nextType || (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 name = output?.name ?? resourceName(env.project, instanceId); const existing = yield* getByName(name); if (existing === undefined) return undefined; const attrs = toAttrs(existing, env.project); return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs); }), list: () => Effect.gen(function* () { const env = yield* GcpEnvironment.current; return yield* spanner.listProjectsInstances .pages({ parent: `projects/${env.project}`, pageSize: 1000, }) .pipe( Stream.flatMap((page) => Stream.fromIterable(page.instances ?? [])), Stream.filter((instance) => Object.keys(instance.labels ?? {}).some((key) => key.startsWith("alchemy-")), ), Stream.map((instance) => toAttrs(instance, env.project)), 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 name = resourceName(env.project, instanceId); const instanceType = normalizeInstanceType(news.instanceType); const displayName = displayNameOf(instanceId, news.displayName); const desiredLabels = { ...toLabels(news.labels), ...(yield* createInternalLabels(id)), }; let current = yield* getByName(output?.name ?? name); if (current === undefined) { const created = yield* spanner .createProjectsInstances({ parent: `projects/${env.project}`, body: { instanceId, instance: toCreateInstance( name, news, env.project, env.region, desiredLabels, instanceType, displayName, ), }, }) .pipe(Effect.catchTag("Conflict", () => Effect.undefined)); if (created !== undefined) { yield* waitForOperation(created, { alreadyExistsOk: true }); } current = yield* waitUntilExists(name); } if (current === undefined) { return yield* new InstanceNotResolved({ resourceName: name }); } if ((current.state ?? "") !== "READY") { 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 ?? "") !== displayName; const editionChanged = news.edition !== undefined && normalizeEdition(current.edition) !== normalizeEdition(news.edition); const backupChanged = news.defaultBackupScheduleType !== undefined && normalizeBackupSchedule(current.defaultBackupScheduleType) !== normalizeBackupSchedule(news.defaultBackupScheduleType); const autoscalingChanged = news.autoscalingConfig !== undefined && autoscalingKey(autoscalingOf(current.autoscalingConfig)) !== autoscalingKey(news.autoscalingConfig); const processingUnitsChanged = news.autoscalingConfig === undefined && news.nodeCount === undefined && news.processingUnits !== undefined && (current.processingUnits ?? 0) !== news.processingUnits; const nodeCountChanged = news.autoscalingConfig === undefined && news.nodeCount !== undefined && (current.nodeCount ?? 0) !== news.nodeCount; if ( labelsChanged || displayNameChanged || editionChanged || backupChanged || autoscalingChanged || processingUnitsChanged || nodeCountChanged ) { const fieldMask = [ labelsChanged ? "labels" : undefined, displayNameChanged ? "display_name" : undefined, editionChanged ? "edition" : undefined, backupChanged ? "default_backup_schedule_type" : undefined, autoscalingChanged ? "autoscaling_config" : undefined, processingUnitsChanged ? "processing_units" : undefined, nodeCountChanged ? "node_count" : undefined, ].filter((field): field is string => field !== undefined); const patchBody: spanner.Instance = { name, labels: desiredLabels, displayName, }; if (editionChanged && news.edition !== undefined) { patchBody.edition = normalizeEdition(news.edition); } if (backupChanged && news.defaultBackupScheduleType !== undefined) { patchBody.defaultBackupScheduleType = normalizeBackupSchedule( news.defaultBackupScheduleType, ); } if (autoscalingChanged) { patchBody.autoscalingConfig = news.autoscalingConfig; } if (processingUnitsChanged) { patchBody.processingUnits = news.processingUnits; } if (nodeCountChanged) { patchBody.nodeCount = news.nodeCount; } const patched = yield* retryConcurrentChanges( spanner.patchProjectsInstances({ name, body: { instance: patchBody, fieldMask: fieldMask.join(","), }, }), ); yield* waitForOperation(patched); current = yield* waitUntilReady(name); } return toAttrs(current, env.project); }), delete: Effect.fn(function* ({ output }) { yield* spanner.deleteProjectsInstances({ name: output.name }).pipe( Effect.catchTag("NotFound", () => Effect.void), Effect.retry({ while: (error) => error._tag === "Conflict", times: 8, schedule: Schedule.spaced("5 seconds"), }), ); yield* waitUntilGone(output.name); }), });
.repos/alchemy-effect/packages/gcp/src/Spanner/Instance.ts at main · sailfork/t3code-github · Sailfork
(2–64 characters). Immutable — changing\n * it replaces the instance.\n */\n instanceId?: string;\n /**\n * Instance configuration id (`regional-us-central1`) or full name\n * (`projects/{project}/instanceConfigs/{config}`). Immutable —\n * changing it replaces the instance.\n * @default `regional-{region}` for the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)\n */\n config?: string;\n /**\n * User-facing display name. Must be unique per project and 4–30\n * characters. Defaults to a truncated instance id.\n */\n displayName?: string;\n /**\n * User labels. Alchemy ownership labels are merged in automatically.\n */\n labels?: Record\u003cstring, string>;\n /**\n * Processing units. Mutually exclusive with `nodeCount`. Ignored when\n * autoscaling is enabled or `instanceType` is `FREE_INSTANCE`.\n * @default 100\n */\n processingUnits?: number;\n /**\n * Node count. Mutually exclusive with `processingUnits`. Ignored when\n * autoscaling is enabled or `instanceType` is `FREE_INSTANCE`.\n */\n nodeCount?: number;\n /**\n * Autoscaling configuration. When set, `nodeCount` and\n * `processingUnits` become output-only.\n */\n autoscalingConfig?: AutoscalingConfig;\n /**\n * Instance type. Immutable — changing it replaces the instance.\n * @default \"PROVISIONED\"\n */\n instanceType?: InstanceType;\n /**\n * Edition (`STANDARD`, `ENTERPRISE`, `ENTERPRISE_PLUS`).\n * @default \"STANDARD\"\n */\n edition?: InstanceEdition;\n /**\n * Default backup schedule for new databases. `NONE` skips automatic\n * schedules (required for free instances).\n * @default \"NONE\"\n */\n defaultBackupScheduleType?: InstanceDefaultBackupScheduleType;\n};\n\nexport type Instance = Resource\u003c\n \"GCP.Spanner.Instance\",\n InstanceProps,\n {\n /** Full resource name `projects/{project}/instances/{instance}`. */\n name: string;\n /** Instance id (last path segment). */\n instanceId: string;\n /** Project id. */\n project: string;\n /** Full instance config name. */\n config: string;\n /** User-facing display name. */\n displayName: string | undefined;\n /** User labels (Alchemy ownership labels stripped). */\n labels: Record\u003cstring, string>;\n /** Processing units currently allocated. */\n processingUnits: number | undefined;\n /** Nodes currently allocated. */\n nodeCount: number | undefined;\n /** Autoscaling configuration, if enabled. */\n autoscalingConfig: AutoscalingConfig | undefined;\n /** Compute capacity per replica selection. */\n replicaComputeCapacity: ReplicaComputeCapacity[];\n /** Instance type (`PROVISIONED`, `FREE_INSTANCE`). */\n instanceType: string | undefined;\n /** Edition (`STANDARD`, `ENTERPRISE`, `ENTERPRISE_PLUS`). */\n edition: string | undefined;\n /** Default backup schedule type. */\n defaultBackupScheduleType: string | undefined;\n /** Current instance state (`CREATING`, `READY`). */\n state: string | undefined;\n /** RFC3339 creation timestamp. */\n createTime: string | undefined;\n /** RFC3339 last-update timestamp. */\n updateTime: string | undefined;\n },\n never,\n Providers\n>;\n\n/**\n * A Cloud Spanner instance.\n *\n * Changing `instanceId`, `config`, or `instanceType` replaces the\n * instance. Display name, labels, compute capacity, edition, backup\n * schedule, and autoscaling update in place. Create, update, and delete\n * are long-running operations — a 100 processing-unit regional instance\n * typically takes one to two minutes.\n *\n * ### Creating an Instance\n * **Example:** Generated name, 100 processing units\n * ```typescript\n * const instance = yield* GCP.Spanner.Instance(\"App\", {});\n * ```\n *\n * **Example:** Explicit id, config, and labels\n * ```typescript\n * const instance = yield* GCP.Spanner.Instance(\"App\", {\n * instanceId: \"app-spanner\",\n * config: \"regional-us-central1\",\n * displayName: \"app-spanner\",\n * processingUnits: 100,\n * labels: { env: \"prod\" },\n * });\n * ```\n *\n * ### Observing Instances\n * **Example:** Read the bound instance\n * ```typescript\n * const getInstance = yield* GCP.Spanner.GetInstance(instance);\n * const live = yield* getInstance();\n * ```\n *\n * @resource\n * @category Spanner\n */\nexport const Instance = Resource\u003cInstance>(\"GCP.Spanner.Instance\");\n\nexport class InstanceNotResolved extends Data.TaggedError(\"GCP.Spanner.InstanceNotResolved\")\u003c{\n resourceName: string;\n}> {}\n\nexport class InstanceNotReady extends Data.TaggedError(\"GCP.Spanner.InstanceNotReady\")\u003c{\n resourceName: string;\n state: string;\n}> {}\n\nexport class InstanceStillExists extends Data.TaggedError(\"GCP.Spanner.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 normalizeEnum = (value: string | undefined, fallback: string) => {\n const next = (value ?? fallback).toUpperCase();\n return next.endsWith(\"_UNSPECIFIED\") ? fallback : next;\n};\n\nconst normalizeInstanceType = (value: string | undefined) =>\n normalizeEnum(value, DEFAULT_INSTANCE_TYPE);\n\nconst normalizeEdition = (value: string | undefined) => normalizeEnum(value, DEFAULT_EDITION);\n\nconst normalizeBackupSchedule = (value: string | undefined) =>\n normalizeEnum(value, DEFAULT_BACKUP_SCHEDULE);\n\nconst defaultConfigId = (region: string) => `regional-${region}`;\n\nconst configIdOf = (config: string | undefined, region: string) =>\n lastSegment(config ?? defaultConfigId(region)).toLowerCase();\n\nconst configNameOf = (project: string, config: string | undefined, region: string) => {\n const raw = (config ?? defaultConfigId(region)).trim();\n if (raw.includes(\"/\")) return raw;\n return `projects/${project}/instanceConfigs/${raw}`;\n};\n\nconst resourceName = (project: string, instanceId: string) =>\n `projects/${project}/instances/${instanceId}`;\n\nconst parseName = (name: string) => {\n const parts = name.split(\"/\").filter((part) => part.length > 0);\n const instancesAt = parts.lastIndexOf(\"instances\");\n const projectsAt = parts.lastIndexOf(\"projects\");\n return {\n project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : \"\",\n instanceId:\n instancesAt >= 0 && parts[instancesAt + 1] ? parts[instancesAt + 1]! : lastSegment(name),\n };\n};\n\nconst toSpannerId = (name: string) => {\n let next = name\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, \"-\")\n .replace(/-+/g, \"-\");\n next = next.replace(/^-+/, \"\").replace(/-+$/g, \"\");\n if (!/^[a-z]/.test(next)) next = `s${next}`;\n next = next.slice(0, MAX_INSTANCE_ID_LENGTH).replace(/-+$/g, \"\");\n if (next.length \u003c 2) next = `${next}xx`.slice(0, MAX_INSTANCE_ID_LENGTH);\n return next;\n};\n\nconst toId = (id: string, instanceId: string | undefined, existing?: string) =>\n Effect.gen(function* () {\n if (instanceId !== undefined) return instanceId;\n if (existing !== undefined) return existing;\n return toSpannerId(\n yield* createPhysicalName({\n id,\n maxLength: MAX_INSTANCE_ID_LENGTH,\n lowercase: true,\n }),\n );\n });\n\nconst displayNameOf = (instanceId: string, displayName?: string) => {\n const source = (displayName ?? instanceId).trim();\n let next = source.slice(0, MAX_DISPLAY_NAME_LENGTH);\n if (next.length \u003c MIN_DISPLAY_NAME_LENGTH) {\n next = `${next}inst`.slice(0, MAX_DISPLAY_NAME_LENGTH);\n }\n return next;\n};\n\nconst userLabels = (\n labels: Record\u003cstring, string | undefined> | null | undefined,\n): Record\u003cstring, string> => stripInternalLabels(tagRecord(labels));\n\nconst autoscalingOf = (\n config: spanner.AutoscalingConfig | undefined,\n): AutoscalingConfig | undefined => {\n if (config === undefined) return undefined;\n return {\n autoscalingLimits: config.autoscalingLimits\n ? {\n minNodes: config.autoscalingLimits.minNodes,\n minProcessingUnits: config.autoscalingLimits.minProcessingUnits,\n maxNodes: config.autoscalingLimits.maxNodes,\n maxProcessingUnits: config.autoscalingLimits.maxProcessingUnits,\n }\n : undefined,\n autoscalingTargets: config.autoscalingTargets\n ? {\n highPriorityCpuUtilizationPercent:\n config.autoscalingTargets.highPriorityCpuUtilizationPercent,\n totalCpuUtilizationPercent: config.autoscalingTargets.totalCpuUtilizationPercent,\n storageUtilizationPercent: config.autoscalingTargets.storageUtilizationPercent,\n }\n : undefined,\n };\n};\n\nconst replicaCapacityOf = (\n items: spanner.ReplicaComputeCapacityList | undefined,\n): ReplicaComputeCapacity[] =>\n (items ?? []).map((item) => ({\n location: item.replicaSelection?.location,\n nodeCount: item.nodeCount,\n processingUnits: item.processingUnits,\n }));\n\nconst autoscalingKey = (config: AutoscalingConfig | undefined) => JSON.stringify(config ?? null);\n\nconst toAttrs = (instance: spanner.Instance, project: string): Instance[\"Attributes\"] => {\n const name = instance.name ?? \"\";\n const parsed = parseName(name);\n return {\n name,\n instanceId: parsed.instanceId,\n project: parsed.project || project,\n config: instance.config ?? \"\",\n displayName: instance.displayName,\n labels: userLabels(instance.labels),\n processingUnits: instance.processingUnits,\n nodeCount: instance.nodeCount,\n autoscalingConfig: autoscalingOf(instance.autoscalingConfig),\n replicaComputeCapacity: replicaCapacityOf(instance.replicaComputeCapacity),\n instanceType: instance.instanceType,\n edition: instance.edition,\n defaultBackupScheduleType: instance.defaultBackupScheduleType,\n state: instance.state,\n createTime: instance.createTime,\n updateTime: instance.updateTime,\n };\n};\n\nconst getByName = (name: string) =>\n spanner.getProjectsInstances({ name }).pipe(Effect.catchTag(\"NotFound\", () => Effect.undefined));\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.Spanner.InstanceNotResolved\",\n times: 8,\n schedule: Schedule.spaced(\"2 seconds\"),\n }),\n );\n\nconst waitUntilReady = (name: string) =>\n getByName(name).pipe(\n Effect.filterOrFail(\n (instance): instance is spanner.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.Spanner.InstanceNotReady\" ||\n error._tag === \"GCP.Spanner.InstanceNotResolved\",\n times: 10,\n schedule: Schedule.spaced(\"8 seconds\"),\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.Spanner.InstanceStillExists\",\n times: 10,\n schedule: Schedule.spaced(\"8 seconds\"),\n }),\n );\n\nconst retryConcurrentChanges = \u003cA, E extends { readonly _tag: string }, R>(\n effect: Effect.Effect\u003cA, E, R>,\n) =>\n effect.pipe(\n Effect.retry({\n while: (error) => error._tag === \"Conflict\",\n times: 8,\n schedule: Schedule.spaced(\"5 seconds\"),\n }),\n );\n\nconst toCreateInstance = (\n name: string,\n news: InstanceProps,\n project: string,\n region: string,\n desiredLabels: Record\u003cstring, string>,\n instanceType: string,\n displayName: string,\n): spanner.Instance => {\n const free = instanceType === \"FREE_INSTANCE\";\n const autoscaling = news.autoscalingConfig;\n const body: spanner.Instance = {\n name,\n config: configNameOf(project, news.config, region),\n displayName,\n labels: desiredLabels,\n instanceType,\n };\n if (!free) {\n body.edition = news.edition ? normalizeEdition(news.edition) : DEFAULT_EDITION;\n body.defaultBackupScheduleType = news.defaultBackupScheduleType\n ? normalizeBackupSchedule(news.defaultBackupScheduleType)\n : DEFAULT_BACKUP_SCHEDULE;\n }\n if (autoscaling !== undefined) {\n body.autoscalingConfig = autoscaling;\n } else if (!free) {\n if (news.nodeCount !== undefined) {\n body.nodeCount = news.nodeCount;\n } else {\n body.processingUnits = news.processingUnits ?? DEFAULT_PROCESSING_UNITS;\n }\n }\n return body;\n};\n\nexport const InstanceProvider = () =>\n Provider.succeed(Instance, {\n stables: [\"name\", \"instanceId\", \"project\", \"config\", \"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 previousConfig = configIdOf(olds?.config ?? output?.config, env.region);\n const nextConfig = configIdOf(news.config ?? output?.config, env.region);\n const previousType = normalizeInstanceType(olds?.instanceType ?? output?.instanceType);\n const nextType = normalizeInstanceType(news.instanceType ?? output?.instanceType);\n\n const replace =\n (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||\n previousConfig !== nextConfig ||\n previousType !== nextType;\n\n if (!replace) return undefined;\n return {\n action: \"replace\" as const,\n deleteFirst:\n previousConfig !== nextConfig ||\n previousType !== nextType ||\n (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 name = output?.name ?? resourceName(env.project, instanceId);\n const existing = yield* getByName(name);\n if (existing === undefined) return undefined;\n const attrs = toAttrs(existing, env.project);\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* spanner.listProjectsInstances\n .pages({\n parent: `projects/${env.project}`,\n pageSize: 1000,\n })\n .pipe(\n Stream.flatMap((page) => Stream.fromIterable(page.instances ?? [])),\n Stream.filter((instance) =>\n Object.keys(instance.labels ?? {}).some((key) => key.startsWith(\"alchemy-\")),\n ),\n Stream.map((instance) => toAttrs(instance, env.project)),\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 name = resourceName(env.project, instanceId);\n const instanceType = normalizeInstanceType(news.instanceType);\n const displayName = displayNameOf(instanceId, news.displayName);\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* spanner\n .createProjectsInstances({\n parent: `projects/${env.project}`,\n body: {\n instanceId,\n instance: toCreateInstance(\n name,\n news,\n env.project,\n env.region,\n desiredLabels,\n instanceType,\n displayName,\n ),\n },\n })\n .pipe(Effect.catchTag(\"Conflict\", () => Effect.undefined));\n if (created !== undefined) {\n yield* waitForOperation(created, { alreadyExistsOk: true });\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 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 ?? \"\") !== displayName;\n const editionChanged =\n news.edition !== undefined &&\n normalizeEdition(current.edition) !== normalizeEdition(news.edition);\n const backupChanged =\n news.defaultBackupScheduleType !== undefined &&\n normalizeBackupSchedule(current.defaultBackupScheduleType) !==\n normalizeBackupSchedule(news.defaultBackupScheduleType);\n const autoscalingChanged =\n news.autoscalingConfig !== undefined &&\n autoscalingKey(autoscalingOf(current.autoscalingConfig)) !==\n autoscalingKey(news.autoscalingConfig);\n const processingUnitsChanged =\n news.autoscalingConfig === undefined &&\n news.nodeCount === undefined &&\n news.processingUnits !== undefined &&\n (current.processingUnits ?? 0) !== news.processingUnits;\n const nodeCountChanged =\n news.autoscalingConfig === undefined &&\n news.nodeCount !== undefined &&\n (current.nodeCount ?? 0) !== news.nodeCount;\n\n if (\n labelsChanged ||\n displayNameChanged ||\n editionChanged ||\n backupChanged ||\n autoscalingChanged ||\n processingUnitsChanged ||\n nodeCountChanged\n ) {\n const fieldMask = [\n labelsChanged ? \"labels\" : undefined,\n displayNameChanged ? \"display_name\" : undefined,\n editionChanged ? \"edition\" : undefined,\n backupChanged ? \"default_backup_schedule_type\" : undefined,\n autoscalingChanged ? \"autoscaling_config\" : undefined,\n processingUnitsChanged ? \"processing_units\" : undefined,\n nodeCountChanged ? \"node_count\" : undefined,\n ].filter((field): field is string => field !== undefined);\n\n const patchBody: spanner.Instance = {\n name,\n labels: desiredLabels,\n displayName,\n };\n if (editionChanged && news.edition !== undefined) {\n patchBody.edition = normalizeEdition(news.edition);\n }\n if (backupChanged && news.defaultBackupScheduleType !== undefined) {\n patchBody.defaultBackupScheduleType = normalizeBackupSchedule(\n news.defaultBackupScheduleType,\n );\n }\n if (autoscalingChanged) {\n patchBody.autoscalingConfig = news.autoscalingConfig;\n }\n if (processingUnitsChanged) {\n patchBody.processingUnits = news.processingUnits;\n }\n if (nodeCountChanged) {\n patchBody.nodeCount = news.nodeCount;\n }\n\n const patched = yield* retryConcurrentChanges(\n spanner.patchProjectsInstances({\n name,\n body: {\n instance: patchBody,\n fieldMask: fieldMask.join(\",\"),\n },\n }),\n );\n yield* waitForOperation(patched);\n current = yield* waitUntilReady(name);\n }\n\n return toAttrs(current, env.project);\n }),\n\n delete: Effect.fn(function* ({ output }) {\n yield* spanner.deleteProjectsInstances({ name: output.name }).pipe(\n Effect.catchTag(\"NotFound\", () => Effect.void),\n Effect.retry({\n while: (error) => error._tag === \"Conflict\",\n times: 8,\n schedule: Schedule.spaced(\"5 seconds\"),\n }),\n );\n yield* waitUntilGone(output.name);\n }),\n });\n","preview":null,"history":null,"version":"dfd283e269d4c4c7474a946f09775afbf3b372d9"},"/_session?shell=1":null}