sailfork / t3code-github / .repos/ alchemy-effect/ packages/ gcp/ src/ Redis/ AclPolicy.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 * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schedule from "effect/Schedule";
import { GcpEnvironment } from "../Environment.ts";
import { waitForOperation as waitForGcpOperation } from "../Operation.ts";
import type { Providers } from "../Providers.ts";

const MAX_NAME_LENGTH = 63;

export type AclRule = {
  /**
   * Redis ACL username. For IAM auth this is an IAM user or service
   * account; otherwise any Redis ACL username.
   */
  username?: string;
  /**
   * Redis OSS ACL rule string (e.g. `"on ~keys:* +get"`). See
   * https://redis.io/docs/latest/operate/oss_and_stack/management/security/acl/
   */
  rule?: string;
};

export type AclPolicyProps = {
  /**
   * ACL policy id (the `{acl_policy}` segment of
   * `projects/{project}/locations/{location}/aclPolicies/{acl_policy}`).
   * If omitted, a unique name is generated from the stack, stage, and
   * logical id. Must match `^[a-z]([a-z0-9-]{0,61}[a-z0-9])?

	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	.repos/alchemy-effect/packages/gcp/src/Redis/AclPolicy.ts at main · sailfork/t3code-github · Sailfork
	
		
(1-63 * characters). Immutable — changing it replaces the policy. */ aclPolicyId?: string; /** * Region (`us-central1`, `us-east1`, …). Immutable — changing it * replaces the policy. `US-CENTRAL1` is accepted and normalized to * `us-central1`. * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`) */ location?: string; /** * Redis ACL rules applied to clusters that attach this policy. */ rules?: AclRule[]; }; export type AclPolicy = Resource< "GCP.Redis.AclPolicy", AclPolicyProps, { /** Full resource name `projects/{project}/locations/{location}/aclPolicies/{acl_policy}`. */ name: string; /** ACL policy id (last path segment). */ aclPolicyId: string; /** Project id. */ project: string; /** Region id (`us-central1`, …). */ location: string; /** ACL rules. */ rules: AclRule[]; /** Server-reported state (`ACTIVE`, `UPDATING`, `DELETING`, …). */ state: string | undefined; /** Server etag for optimistic concurrency. */ etag: string | undefined; /** Deprecated drift-resolution version string, if present. */ version: string | undefined; }, never, Providers >; /** * A Memorystore for Redis Cluster ACL policy. * * ACL policies have no labels field, so Alchemy identifies a policy by * its id: a policy found under the generated id is adopted, one found * under an explicit `aclPolicyId` without state is reported as unowned. * `aclPolicyId` and `location` are identity — changing either replaces * the policy. `rules` update in place. Create is synchronous; patch and * delete return long-running operations. * * Attach the policy to a Redis Cluster with the cluster's `aclPolicy` * field. A policy cannot be deleted while it is attached to a cluster. * * ### Creating an ACL Policy * **Example:** Generated name * ```typescript * const policy = yield* GCP.Redis.AclPolicy("AppAcl", { * rules: [{ username: "app", rule: "on ~keys:* +get" }], * }); * ``` * * **Example:** Explicit id, location, and rules * ```typescript * const policy = yield* GCP.Redis.AclPolicy("AppAcl", { * aclPolicyId: "app-acl", * location: "us-central1", * rules: [ * { username: "app", rule: "on ~keys:* +get" }, * { username: "readonly", rule: "off ~* -@all" }, * ], * }); * ``` * * ### Updating Rules * Change props on the same logical id; the engine keeps the physical id. * * **Example:** Add a command to an existing user * ```typescript * const policy = yield* GCP.Redis.AclPolicy("AppAcl", { * location: "us-central1", * rules: [{ username: "app", rule: "on ~keys:* +get +set" }], * }); * ``` * * @resource * @category Redis */ export const AclPolicy = Resource<AclPolicy>("GCP.Redis.AclPolicy"); export class AclPolicyNotResolved extends Data.TaggedError("GCP.Redis.AclPolicyNotResolved")<{ resourceName: string; }> {} export class AclPolicyNotReady extends Data.TaggedError("GCP.Redis.AclPolicyNotReady")<{ resourceName: string; state: string; }> {} export class AclPolicyStillExists extends Data.TaggedError("GCP.Redis.AclPolicyStillExists")<{ 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 rfc1035 = (name: string): string => { let next = name .toLowerCase() .replace(/[^a-z0-9-]/g, "-") .replace(/-+/g, "-") .replace(/^-+|-+$/g, ""); if (!/^[a-z]/.test(next)) next = `a${next}`; next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, ""); if (next.length === 0) return "aclpolicy"; 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, aclPolicyId: string) => `projects/${project}/locations/${location}/aclPolicies/${aclPolicyId}`; const parseName = (name: string, fallbackLocation: string) => { const parts = name.split("/").filter((part) => part.length > 0); const policiesAt = parts.lastIndexOf("aclPolicies"); 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, aclPolicyId: policiesAt >= 0 && parts[policiesAt + 1] ? parts[policiesAt + 1]! : lastSegment(name), }; }; const toId = (id: string, aclPolicyId: string | undefined, existing?: string) => Effect.gen(function* () { return ( aclPolicyId ?? existing ?? rfc1035( yield* createPhysicalName({ id, maxLength: MAX_NAME_LENGTH, lowercase: true, }), ) ); }); const ruleOf = (rule: redis.AclRule | AclRule): AclRule => ({ username: rule.username, rule: rule.rule, }); const userRulesOf = (rules: readonly (redis.AclRule | AclRule)[] | undefined): AclRule[] => (rules ?? []).map(ruleOf); const rulesKey = (rules: readonly AclRule[]) => JSON.stringify( [...rules] .map((rule) => ({ username: rule.username ?? "", rule: rule.rule ?? "", })) .sort( (left, right) => left.username.localeCompare(right.username) || left.rule.localeCompare(right.rule), ), ); const desiredRules = (news: AclPolicyProps): redis.AclRule[] => userRulesOf(news.rules); const toAttrs = (policy: redis.AclPolicy, project: string, region: string) => { const name = policy.name ?? ""; const parsed = parseName(name, region); return { name, aclPolicyId: parsed.aclPolicyId, project: parsed.project || project, location: parsed.location, rules: userRulesOf(policy.rules), state: policy.state, etag: policy.etag, version: policy.version, }; }; const isPlaceholder = (policy: redis.AclPolicy) => { const name = policy.name ?? ""; return name.endsWith("/aclPolicies/-") || name.endsWith("/aclPolicies/"); }; const getByName = (name: string) => redis .getProjectsLocationsAclPolicies({ 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: "10 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((policy) => policy ? Effect.succeed(policy) : Effect.fail(new AclPolicyNotResolved({ resourceName: name })), ), Effect.retry({ while: (error) => error._tag === "GCP.Redis.AclPolicyNotResolved", times: 8, schedule: Schedule.spaced("1 second"), }), ); const waitUntilActive = (name: string) => getByName(name).pipe( Effect.filterOrFail( (policy): policy is redis.AclPolicy => policy !== undefined, () => new AclPolicyNotResolved({ resourceName: name }), ), Effect.filterOrFail( (policy) => { const state = policy.state ?? "ACTIVE"; return state === "ACTIVE" || state === "STATE_UNSPECIFIED"; }, (policy) => new AclPolicyNotReady({ resourceName: name, state: policy.state ?? "STATE_UNSPECIFIED", }), ), Effect.retry({ while: (error) => error._tag === "GCP.Redis.AclPolicyNotReady" || error._tag === "GCP.Redis.AclPolicyNotResolved", times: 10, schedule: Schedule.spaced("3 seconds"), }), ); const waitUntilGone = (name: string) => getByName(name).pipe( Effect.flatMap((policy) => policy === undefined ? Effect.void : Effect.fail(new AclPolicyStillExists({ resourceName: name })), ), Effect.retry({ while: (error) => error._tag === "GCP.Redis.AclPolicyStillExists", times: 10, schedule: Schedule.spaced("3 seconds"), }), ); export const AclPolicyProvider = () => Provider.succeed(AclPolicy, { stables: ["name", "aclPolicyId", "project", "location"], diff: Effect.fn(function* ({ news, olds, output }) { if (!isResolved(news)) return undefined; const env = yield* GcpEnvironment.current; const previousId = olds?.aclPolicyId ?? output?.aclPolicyId; const nextId = news.aclPolicyId ?? previousId; const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region); const nextLocation = normalizeLocation(news.location ?? output?.location, env.region); const replace = (previousId !== undefined && nextId !== undefined && nextId !== previousId) || previousLocation !== nextLocation; if (!replace) return undefined; return { action: "replace" as const, deleteFirst: false }; }), read: Effect.fn(function* ({ id, olds, output }) { const env = yield* GcpEnvironment.current; const aclPolicyId = yield* toId(id, olds?.aclPolicyId, output?.aclPolicyId); const location = normalizeLocation(olds?.location ?? output?.location, env.region); const name = output?.name ?? resourceName(env.project, location, aclPolicyId); const existing = yield* getByName(name); if (existing === undefined) return undefined; const attrs = toAttrs(existing, env.project, env.region); // No labels: state or the generated id proves ownership. return output !== undefined || olds?.aclPolicyId === undefined ? attrs : Unowned(attrs); }), reconcile: Effect.fn(function* ({ id, news, output }) { const env = yield* GcpEnvironment.current; const aclPolicyId = yield* toId(id, news.aclPolicyId, output?.aclPolicyId); const location = normalizeLocation(news.location ?? output?.location, env.region); const name = resourceName(env.project, location, aclPolicyId); const bodyRules = desiredRules(news); let current = yield* getByName(output?.name ?? name); if (current !== undefined && (current.state ?? "") === "DELETING") { yield* waitUntilGone(name); current = undefined; } if (current === undefined) { const created = yield* redis .createProjectsLocationsAclPolicies({ parent: `projects/${env.project}/locations/${location}`, aclPolicyId, body: { rules: bodyRules }, }) .pipe(Effect.catchTag("Conflict", () => Effect.undefined)); current = created && created.name && !isPlaceholder(created) ? created : yield* waitUntilExists(name); } if (current === undefined) { return yield* new AclPolicyNotResolved({ resourceName: name }); } const state = current.state ?? "ACTIVE"; if (state === "UPDATING" || state === "DELETING") { current = yield* waitUntilActive(name); } const rulesChanged = rulesKey(userRulesOf(current.rules)) !== rulesKey(userRulesOf(news.rules)); if (rulesChanged) { const patched = yield* redis .patchProjectsLocationsAclPolicies({ name, updateMask: "rules", body: { name, rules: bodyRules }, }) .pipe( Effect.retry({ while: (error) => error._tag === "Conflict", times: 8, schedule: Schedule.spaced("2 seconds"), }), ); yield* waitForOperation(patched); current = yield* waitUntilActive(name); } return toAttrs(current, env.project, env.region); }), delete: Effect.fn(function* ({ output }) { const operation = yield* redis .deleteProjectsLocationsAclPolicies({ name: output.name, }) .pipe( Effect.catchTag("NotFound", () => Effect.undefined), Effect.retry({ while: (error) => error._tag === "Conflict", times: 8, schedule: Schedule.spaced("2 seconds"), }), ); if (operation !== undefined) { yield* waitForOperation(operation, { notFoundOk: true }); } yield* waitUntilGone(output.name); }), });
.repos/alchemy-effect/packages/gcp/src/Redis/AclPolicy.ts at main · sailfork/t3code-github · Sailfork
(1-63\n * characters). Immutable — changing it replaces the policy.\n */\n aclPolicyId?: string;\n /**\n * Region (`us-central1`, `us-east1`, …). Immutable — changing it\n * replaces the policy. `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 * Redis ACL rules applied to clusters that attach this policy.\n */\n rules?: AclRule[];\n};\n\nexport type AclPolicy = Resource\u003c\n \"GCP.Redis.AclPolicy\",\n AclPolicyProps,\n {\n /** Full resource name `projects/{project}/locations/{location}/aclPolicies/{acl_policy}`. */\n name: string;\n /** ACL policy id (last path segment). */\n aclPolicyId: string;\n /** Project id. */\n project: string;\n /** Region id (`us-central1`, …). */\n location: string;\n /** ACL rules. */\n rules: AclRule[];\n /** Server-reported state (`ACTIVE`, `UPDATING`, `DELETING`, …). */\n state: string | undefined;\n /** Server etag for optimistic concurrency. */\n etag: string | undefined;\n /** Deprecated drift-resolution version string, if present. */\n version: string | undefined;\n },\n never,\n Providers\n>;\n\n/**\n * A Memorystore for Redis Cluster ACL policy.\n *\n * ACL policies have no labels field, so Alchemy identifies a policy by\n * its id: a policy found under the generated id is adopted, one found\n * under an explicit `aclPolicyId` without state is reported as unowned.\n * `aclPolicyId` and `location` are identity — changing either replaces\n * the policy. `rules` update in place. Create is synchronous; patch and\n * delete return long-running operations.\n *\n * Attach the policy to a Redis Cluster with the cluster's `aclPolicy`\n * field. A policy cannot be deleted while it is attached to a cluster.\n *\n * ### Creating an ACL Policy\n * **Example:** Generated name\n * ```typescript\n * const policy = yield* GCP.Redis.AclPolicy(\"AppAcl\", {\n * rules: [{ username: \"app\", rule: \"on ~keys:* +get\" }],\n * });\n * ```\n *\n * **Example:** Explicit id, location, and rules\n * ```typescript\n * const policy = yield* GCP.Redis.AclPolicy(\"AppAcl\", {\n * aclPolicyId: \"app-acl\",\n * location: \"us-central1\",\n * rules: [\n * { username: \"app\", rule: \"on ~keys:* +get\" },\n * { username: \"readonly\", rule: \"off ~* -@all\" },\n * ],\n * });\n * ```\n *\n * ### Updating Rules\n * Change props on the same logical id; the engine keeps the physical id.\n *\n * **Example:** Add a command to an existing user\n * ```typescript\n * const policy = yield* GCP.Redis.AclPolicy(\"AppAcl\", {\n * location: \"us-central1\",\n * rules: [{ username: \"app\", rule: \"on ~keys:* +get +set\" }],\n * });\n * ```\n *\n * @resource\n * @category Redis\n */\nexport const AclPolicy = Resource\u003cAclPolicy>(\"GCP.Redis.AclPolicy\");\n\nexport class AclPolicyNotResolved extends Data.TaggedError(\"GCP.Redis.AclPolicyNotResolved\")\u003c{\n resourceName: string;\n}> {}\n\nexport class AclPolicyNotReady extends Data.TaggedError(\"GCP.Redis.AclPolicyNotReady\")\u003c{\n resourceName: string;\n state: string;\n}> {}\n\nexport class AclPolicyStillExists extends Data.TaggedError(\"GCP.Redis.AclPolicyStillExists\")\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 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 = `a${next}`;\n next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, \"\");\n if (next.length === 0) return \"aclpolicy\";\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, aclPolicyId: string) =>\n `projects/${project}/locations/${location}/aclPolicies/${aclPolicyId}`;\n\nconst parseName = (name: string, fallbackLocation: string) => {\n const parts = name.split(\"/\").filter((part) => part.length > 0);\n const policiesAt = parts.lastIndexOf(\"aclPolicies\");\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 aclPolicyId:\n policiesAt >= 0 && parts[policiesAt + 1] ? parts[policiesAt + 1]! : lastSegment(name),\n };\n};\n\nconst toId = (id: string, aclPolicyId: string | undefined, existing?: string) =>\n Effect.gen(function* () {\n return (\n aclPolicyId ??\n existing ??\n rfc1035(\n yield* createPhysicalName({\n id,\n maxLength: MAX_NAME_LENGTH,\n lowercase: true,\n }),\n )\n );\n });\n\nconst ruleOf = (rule: redis.AclRule | AclRule): AclRule => ({\n username: rule.username,\n rule: rule.rule,\n});\n\nconst userRulesOf = (rules: readonly (redis.AclRule | AclRule)[] | undefined): AclRule[] =>\n (rules ?? []).map(ruleOf);\n\nconst rulesKey = (rules: readonly AclRule[]) =>\n JSON.stringify(\n [...rules]\n .map((rule) => ({\n username: rule.username ?? \"\",\n rule: rule.rule ?? \"\",\n }))\n .sort(\n (left, right) =>\n left.username.localeCompare(right.username) || left.rule.localeCompare(right.rule),\n ),\n );\n\nconst desiredRules = (news: AclPolicyProps): redis.AclRule[] => userRulesOf(news.rules);\n\nconst toAttrs = (policy: redis.AclPolicy, project: string, region: string) => {\n const name = policy.name ?? \"\";\n const parsed = parseName(name, region);\n return {\n name,\n aclPolicyId: parsed.aclPolicyId,\n project: parsed.project || project,\n location: parsed.location,\n rules: userRulesOf(policy.rules),\n state: policy.state,\n etag: policy.etag,\n version: policy.version,\n };\n};\n\nconst isPlaceholder = (policy: redis.AclPolicy) => {\n const name = policy.name ?? \"\";\n return name.endsWith(\"/aclPolicies/-\") || name.endsWith(\"/aclPolicies/\");\n};\n\nconst getByName = (name: string) =>\n redis\n .getProjectsLocationsAclPolicies({ 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: \"10 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((policy) =>\n policy\n ? Effect.succeed(policy)\n : Effect.fail(new AclPolicyNotResolved({ resourceName: name })),\n ),\n Effect.retry({\n while: (error) => error._tag === \"GCP.Redis.AclPolicyNotResolved\",\n times: 8,\n schedule: Schedule.spaced(\"1 second\"),\n }),\n );\n\nconst waitUntilActive = (name: string) =>\n getByName(name).pipe(\n Effect.filterOrFail(\n (policy): policy is redis.AclPolicy => policy !== undefined,\n () => new AclPolicyNotResolved({ resourceName: name }),\n ),\n Effect.filterOrFail(\n (policy) => {\n const state = policy.state ?? \"ACTIVE\";\n return state === \"ACTIVE\" || state === \"STATE_UNSPECIFIED\";\n },\n (policy) =>\n new AclPolicyNotReady({\n resourceName: name,\n state: policy.state ?? \"STATE_UNSPECIFIED\",\n }),\n ),\n Effect.retry({\n while: (error) =>\n error._tag === \"GCP.Redis.AclPolicyNotReady\" ||\n error._tag === \"GCP.Redis.AclPolicyNotResolved\",\n times: 10,\n schedule: Schedule.spaced(\"3 seconds\"),\n }),\n );\n\nconst waitUntilGone = (name: string) =>\n getByName(name).pipe(\n Effect.flatMap((policy) =>\n policy === undefined\n ? Effect.void\n : Effect.fail(new AclPolicyStillExists({ resourceName: name })),\n ),\n Effect.retry({\n while: (error) => error._tag === \"GCP.Redis.AclPolicyStillExists\",\n times: 10,\n schedule: Schedule.spaced(\"3 seconds\"),\n }),\n );\n\nexport const AclPolicyProvider = () =>\n Provider.succeed(AclPolicy, {\n stables: [\"name\", \"aclPolicyId\", \"project\", \"location\"],\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?.aclPolicyId ?? output?.aclPolicyId;\n const nextId = news.aclPolicyId ?? previousId;\n const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);\n const nextLocation = normalizeLocation(news.location ?? output?.location, env.region);\n const replace =\n (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||\n previousLocation !== nextLocation;\n if (!replace) return undefined;\n return { action: \"replace\" as const, deleteFirst: false };\n }),\n\n read: Effect.fn(function* ({ id, olds, output }) {\n const env = yield* GcpEnvironment.current;\n const aclPolicyId = yield* toId(id, olds?.aclPolicyId, output?.aclPolicyId);\n const location = normalizeLocation(olds?.location ?? output?.location, env.region);\n const name = output?.name ?? resourceName(env.project, location, aclPolicyId);\n const existing = yield* getByName(name);\n if (existing === undefined) return undefined;\n const attrs = toAttrs(existing, env.project, env.region);\n // No labels: state or the generated id proves ownership.\n return output !== undefined || olds?.aclPolicyId === undefined ? attrs : Unowned(attrs);\n }),\n\n reconcile: Effect.fn(function* ({ id, news, output }) {\n const env = yield* GcpEnvironment.current;\n const aclPolicyId = yield* toId(id, news.aclPolicyId, output?.aclPolicyId);\n const location = normalizeLocation(news.location ?? output?.location, env.region);\n const name = resourceName(env.project, location, aclPolicyId);\n const bodyRules = desiredRules(news);\n\n let current = yield* getByName(output?.name ?? name);\n if (current !== undefined && (current.state ?? \"\") === \"DELETING\") {\n yield* waitUntilGone(name);\n current = undefined;\n }\n\n if (current === undefined) {\n const created = yield* redis\n .createProjectsLocationsAclPolicies({\n parent: `projects/${env.project}/locations/${location}`,\n aclPolicyId,\n body: { rules: bodyRules },\n })\n .pipe(Effect.catchTag(\"Conflict\", () => Effect.undefined));\n current =\n created && created.name && !isPlaceholder(created)\n ? created\n : yield* waitUntilExists(name);\n }\n\n if (current === undefined) {\n return yield* new AclPolicyNotResolved({ resourceName: name });\n }\n\n const state = current.state ?? \"ACTIVE\";\n if (state === \"UPDATING\" || state === \"DELETING\") {\n current = yield* waitUntilActive(name);\n }\n\n const rulesChanged =\n rulesKey(userRulesOf(current.rules)) !== rulesKey(userRulesOf(news.rules));\n\n if (rulesChanged) {\n const patched = yield* redis\n .patchProjectsLocationsAclPolicies({\n name,\n updateMask: \"rules\",\n body: { name, rules: bodyRules },\n })\n .pipe(\n Effect.retry({\n while: (error) => error._tag === \"Conflict\",\n times: 8,\n schedule: Schedule.spaced(\"2 seconds\"),\n }),\n );\n yield* waitForOperation(patched);\n current = yield* waitUntilActive(name);\n }\n\n return toAttrs(current, env.project, env.region);\n }),\n\n delete: Effect.fn(function* ({ output }) {\n const operation = yield* redis\n .deleteProjectsLocationsAclPolicies({\n name: output.name,\n })\n .pipe(\n Effect.catchTag(\"NotFound\", () => Effect.undefined),\n Effect.retry({\n while: (error) => error._tag === \"Conflict\",\n times: 8,\n schedule: Schedule.spaced(\"2 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":"c31a890c5425da3a23e46a7b1fbc516a7ca597d9"},"/_session?shell=1":null}