sailfork / t3code-github / .repos/ alchemy-effect/ packages/ gcp/ src/ Apigee/ Environment.ts

import * as apigee from "@distilled.cloud/gcp/apigee_v1";
import { Unowned } from "alchemy/AdoptPolicy";
import { isResolved } from "alchemy/Diff";
import * as Provider from "alchemy/Provider";
import { Resource } from "alchemy/Resource";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import { GcpEnvironment } from "../Environment.ts";
import type { Providers } from "../Providers.ts";
import {
  createOwnership,
  defaultOrgName,
  desiredAttributes,
  encodeDescription,
  hasOwnershipMarker,
  jsonEqual,
  lastSegment,
  letterPrefixedId,
  listOrgNames,
  orgIdOf,
  orgNameOf,
  ownedBy,
  parseDescription,
  propertiesToRecord,
  recordToProperties,
  sameRecord,
  userProperties,
  waitForOperation,
} from "./operations.ts";

export type EnvironmentType = apigee.GoogleCloudApigeeV1EnvironmentTypeEnum | (string & {});
export type EnvironmentApiProxyType =
  | apigee.GoogleCloudApigeeV1EnvironmentApiProxyTypeEnum
  | (string & {});
export type EnvironmentDeploymentType =
  | apigee.GoogleCloudApigeeV1EnvironmentDeploymentTypeEnum
  | (string & {});

export type EnvironmentClientIPResolutionConfig =
  apigee.GoogleCloudApigeeV1EnvironmentClientIPResolutionConfig;
export type EnvironmentNodeConfig = apigee.GoogleCloudApigeeV1NodeConfig;

export type EnvironmentProps = {
  /**
   * Apigee organization id or `organizations/{org}`. Defaults to the
   * current GCP project id. Immutable — changing it replaces the
   * environment.
   */
  organization?: string;
  /**
   * Environment id (the `{env}` segment of
   * `organizations/{org}/environments/{env}`). Must match
   * `^[.\\p{Alnum}-_]{1,255}

	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	.repos/alchemy-effect/packages/gcp/src/Apigee/Environment.ts at main · sailfork/t3code-github · Sailfork
	
		
. If omitted, a unique name is generated. * Immutable — changing it replaces the environment. */ environmentId?: string; /** * Display name. */ displayName?: string; /** * Human-readable description. Alchemy ownership is stored in a * `[alchemy …]` prefix and stripped from attributes. */ description?: string; /** * Environment type. Immutable — changing it replaces the environment. */ type?: EnvironmentType; /** * API proxy type. Immutable — changing it replaces the environment. */ apiProxyType?: EnvironmentApiProxyType; /** * Deployment type. Immutable — changing it replaces the environment. */ deploymentType?: EnvironmentDeploymentType; /** * Forward proxy URI (`http://{hostname}:{port}`). Empty string removes * the setting. */ forwardProxyUri?: string; /** * Client IP resolution algorithm used by analytics and API security. */ clientIpResolutionConfig?: EnvironmentClientIPResolutionConfig; /** * Custom properties (name/value pairs). Alchemy ownership properties * are merged in automatically. */ properties?: Record<string, string>; /** * Gateway node reservation. */ nodeConfig?: EnvironmentNodeConfig; }; export type Environment = Resource< "GCP.Apigee.Environment", EnvironmentProps, { /** Full resource name `organizations/{org}/environments/{env}`. */ name: string; /** Environment id (last path segment). */ environmentId: string; /** Apigee organization id. */ organization: string; /** Display name. */ displayName: string | undefined; /** User description with the Alchemy ownership prefix stripped. */ description: string | undefined; /** Environment type. */ type: string | undefined; /** API proxy type. */ apiProxyType: string | undefined; /** Deployment type. */ deploymentType: string | undefined; /** Forward proxy URI. */ forwardProxyUri: string | undefined; /** Client IP resolution config. */ clientIpResolutionConfig: EnvironmentClientIPResolutionConfig | undefined; /** User properties (Alchemy ownership properties stripped). */ properties: Record<string, string>; /** Gateway node reservation. */ nodeConfig: EnvironmentNodeConfig | undefined; /** Whether flow hooks are attached. */ hasAttachedFlowHooks: boolean | undefined; /** Server-reported state (`CREATING`, `ACTIVE`, …). */ state: string | undefined; /** Creation time in milliseconds since epoch. */ createdAt: string | undefined; /** Last modification time in milliseconds since epoch. */ lastModifiedAt: string | undefined; }, never, Providers >; /** * An Apigee environment that hosts API proxies and shared flows. * * Apigee environments have no labels field, so Alchemy stamps ownership * into the description (and properties) for `list` / nuke. Name, type, * API proxy type, and deployment type are identity — changing them * replaces the environment. Display name, description, forward proxy, * IP resolution, properties, and node config update in place. * * ### Creating an Environment * **Example:** Generated name * ```typescript * const environment = yield* GCP.Apigee.Environment("Runtime", { * displayName: "runtime", * }); * ``` * * **Example:** Named environment with description * ```typescript * const environment = yield* GCP.Apigee.Environment("Runtime", { * environmentId: "prod", * displayName: "Production", * description: "production API runtime", * apiProxyType: "PROGRAMMABLE", * }); * ``` * * @resource * @category Apigee */ export const Environment = Resource<Environment>("GCP.Apigee.Environment"); export class EnvironmentNotResolved extends Data.TaggedError("GCP.Apigee.EnvironmentNotResolved")<{ resourceName: string; }> {} const resourceName = (organization: string, environmentId: string) => `${orgNameOf(organization)}/environments/${environmentId}`; const toAttrs = (environment: apigee.GoogleCloudApigeeV1Environment, organization: string) => { const name = environment.name ?? ""; const parsed = parseDescription(environment.description); return { name, environmentId: lastSegment(name), organization: orgIdOf(organization), displayName: environment.displayName, description: parsed.description, type: environment.type, apiProxyType: environment.apiProxyType, deploymentType: environment.deploymentType, forwardProxyUri: environment.forwardProxyUri, clientIpResolutionConfig: environment.clientIpResolutionConfig, properties: userProperties(environment.properties), nodeConfig: environment.nodeConfig, hasAttachedFlowHooks: environment.hasAttachedFlowHooks, state: environment.state, createdAt: environment.createdAt, lastModifiedAt: environment.lastModifiedAt, }; }; const getByName = (name: string) => apigee .getOrganizationsEnvironments({ name }) .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined)); export const EnvironmentProvider = () => Provider.succeed(Environment, { stables: [ "name", "environmentId", "organization", "type", "apiProxyType", "deploymentType", "createdAt", ], diff: Effect.fn(function* ({ news, olds, output }) { if (!isResolved(news)) return undefined; const previousId = olds?.environmentId ?? output?.environmentId; const previousOrg = olds?.organization ?? output?.organization; const previousType = olds?.type ?? output?.type; const previousProxy = olds?.apiProxyType ?? output?.apiProxyType; const previousDeploy = olds?.deploymentType ?? output?.deploymentType; const idChanged = previousId !== undefined && news.environmentId !== undefined && news.environmentId !== previousId; const orgChanged = previousOrg !== undefined && news.organization !== undefined && orgIdOf(news.organization) !== orgIdOf(previousOrg); const typeChanged = previousType !== undefined && news.type !== undefined && news.type !== previousType; const proxyChanged = previousProxy !== undefined && news.apiProxyType !== undefined && news.apiProxyType !== previousProxy; const deployChanged = previousDeploy !== undefined && news.deploymentType !== undefined && news.deploymentType !== previousDeploy; if (idChanged || orgChanged || typeChanged || proxyChanged || deployChanged) { return { action: "replace" as const, deleteFirst: idChanged && !orgChanged, }; } return undefined; }), read: Effect.fn(function* ({ id, olds, output }) { const env = yield* GcpEnvironment.current; const organization = defaultOrgName(env.project, olds?.organization ?? output?.organization); const environmentId = yield* letterPrefixedId( id, olds?.environmentId, output?.environmentId, 255, ); const name = output?.name ?? resourceName(organization, environmentId); const existing = yield* getByName(name); if (existing === undefined) return undefined; const attrs = toAttrs(existing, organization); const { labels } = parseDescription(existing.description); return (yield* ownedBy(id, labels)) ? attrs : Unowned(attrs); }), list: () => Effect.gen(function* () { const orgs = yield* listOrgNames(); const rows: Environment["Attributes"][] = []; for (const organization of orgs) { const org = yield* apigee .getOrganizations({ name: organization }) .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined)); for (const environmentId of org?.environments ?? []) { const existing = yield* getByName(`${organization}/environments/${environmentId}`); if (existing !== undefined && hasOwnershipMarker(existing.description)) { rows.push(toAttrs(existing, organization)); } } } return rows; }), reconcile: Effect.fn(function* ({ id, news, output }) { const env = yield* GcpEnvironment.current; const organization = defaultOrgName(env.project, news.organization); const environmentId = yield* letterPrefixedId( id, news.environmentId, output?.environmentId, 255, ); const name = resourceName(organization, environmentId); const ownership = yield* createOwnership(id); const desiredDescription = encodeDescription(ownership, news.description); const properties = desiredAttributes(news.properties, ownership); let current = yield* getByName(output?.name ?? name); if (current === undefined) { const operation = yield* apigee .createOrganizationsEnvironments({ parent: organization, name: environmentId, body: { name: environmentId, displayName: news.displayName, description: desiredDescription, type: news.type, apiProxyType: news.apiProxyType, deploymentType: news.deploymentType, forwardProxyUri: news.forwardProxyUri, clientIpResolutionConfig: news.clientIpResolutionConfig, properties: recordToProperties(properties), nodeConfig: news.nodeConfig, }, }) .pipe(Effect.catchTag("Conflict", () => Effect.undefined)); if (operation !== undefined) { yield* waitForOperation(operation); } current = yield* getByName(name); } if (current === undefined) { return yield* new EnvironmentNotResolved({ resourceName: name }); } const observedProperties = propertiesToRecord(current.properties); const displayChanged = (current.displayName ?? "") !== (news.displayName ?? ""); const descriptionChanged = (current.description ?? "") !== desiredDescription; const proxyUriChanged = (current.forwardProxyUri ?? "") !== (news.forwardProxyUri ?? ""); const ipChanged = !jsonEqual(current.clientIpResolutionConfig, news.clientIpResolutionConfig); const propertiesChanged = !sameRecord(observedProperties, properties); const nodeChanged = !jsonEqual(current.nodeConfig, news.nodeConfig); if ( displayChanged || descriptionChanged || proxyUriChanged || ipChanged || propertiesChanged || nodeChanged ) { current = yield* apigee.updateOrganizationsEnvironments({ name, body: { name: environmentId, displayName: news.displayName, description: desiredDescription, type: current.type, apiProxyType: current.apiProxyType, deploymentType: current.deploymentType, forwardProxyUri: news.forwardProxyUri, clientIpResolutionConfig: news.clientIpResolutionConfig, properties: recordToProperties(properties), nodeConfig: news.nodeConfig ?? current.nodeConfig, }, }); } return toAttrs(current, organization); }), delete: Effect.fn(function* ({ output }) { const operation = yield* apigee .deleteOrganizationsEnvironments({ name: output.name }) .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined)); if (operation !== undefined) { yield* waitForOperation(operation, { notFoundOk: true }); } }), });
.repos/alchemy-effect/packages/gcp/src/Apigee/Environment.ts at main · sailfork/t3code-github · Sailfork
. If omitted, a unique name is generated.\n * Immutable — changing it replaces the environment.\n */\n environmentId?: string;\n /**\n * Display name.\n */\n displayName?: string;\n /**\n * Human-readable description. Alchemy ownership is stored in a\n * `[alchemy …]` prefix and stripped from attributes.\n */\n description?: string;\n /**\n * Environment type. Immutable — changing it replaces the environment.\n */\n type?: EnvironmentType;\n /**\n * API proxy type. Immutable — changing it replaces the environment.\n */\n apiProxyType?: EnvironmentApiProxyType;\n /**\n * Deployment type. Immutable — changing it replaces the environment.\n */\n deploymentType?: EnvironmentDeploymentType;\n /**\n * Forward proxy URI (`http://{hostname}:{port}`). Empty string removes\n * the setting.\n */\n forwardProxyUri?: string;\n /**\n * Client IP resolution algorithm used by analytics and API security.\n */\n clientIpResolutionConfig?: EnvironmentClientIPResolutionConfig;\n /**\n * Custom properties (name/value pairs). Alchemy ownership properties\n * are merged in automatically.\n */\n properties?: Record\u003cstring, string>;\n /**\n * Gateway node reservation.\n */\n nodeConfig?: EnvironmentNodeConfig;\n};\n\nexport type Environment = Resource\u003c\n \"GCP.Apigee.Environment\",\n EnvironmentProps,\n {\n /** Full resource name `organizations/{org}/environments/{env}`. */\n name: string;\n /** Environment id (last path segment). */\n environmentId: string;\n /** Apigee organization id. */\n organization: string;\n /** Display name. */\n displayName: string | undefined;\n /** User description with the Alchemy ownership prefix stripped. */\n description: string | undefined;\n /** Environment type. */\n type: string | undefined;\n /** API proxy type. */\n apiProxyType: string | undefined;\n /** Deployment type. */\n deploymentType: string | undefined;\n /** Forward proxy URI. */\n forwardProxyUri: string | undefined;\n /** Client IP resolution config. */\n clientIpResolutionConfig: EnvironmentClientIPResolutionConfig | undefined;\n /** User properties (Alchemy ownership properties stripped). */\n properties: Record\u003cstring, string>;\n /** Gateway node reservation. */\n nodeConfig: EnvironmentNodeConfig | undefined;\n /** Whether flow hooks are attached. */\n hasAttachedFlowHooks: boolean | undefined;\n /** Server-reported state (`CREATING`, `ACTIVE`, …). */\n state: string | undefined;\n /** Creation time in milliseconds since epoch. */\n createdAt: string | undefined;\n /** Last modification time in milliseconds since epoch. */\n lastModifiedAt: string | undefined;\n },\n never,\n Providers\n>;\n\n/**\n * An Apigee environment that hosts API proxies and shared flows.\n *\n * Apigee environments have no labels field, so Alchemy stamps ownership\n * into the description (and properties) for `list` / nuke. Name, type,\n * API proxy type, and deployment type are identity — changing them\n * replaces the environment. Display name, description, forward proxy,\n * IP resolution, properties, and node config update in place.\n *\n * ### Creating an Environment\n * **Example:** Generated name\n * ```typescript\n * const environment = yield* GCP.Apigee.Environment(\"Runtime\", {\n * displayName: \"runtime\",\n * });\n * ```\n *\n * **Example:** Named environment with description\n * ```typescript\n * const environment = yield* GCP.Apigee.Environment(\"Runtime\", {\n * environmentId: \"prod\",\n * displayName: \"Production\",\n * description: \"production API runtime\",\n * apiProxyType: \"PROGRAMMABLE\",\n * });\n * ```\n *\n * @resource\n * @category Apigee\n */\nexport const Environment = Resource\u003cEnvironment>(\"GCP.Apigee.Environment\");\n\nexport class EnvironmentNotResolved extends Data.TaggedError(\"GCP.Apigee.EnvironmentNotResolved\")\u003c{\n resourceName: string;\n}> {}\n\nconst resourceName = (organization: string, environmentId: string) =>\n `${orgNameOf(organization)}/environments/${environmentId}`;\n\nconst toAttrs = (environment: apigee.GoogleCloudApigeeV1Environment, organization: string) => {\n const name = environment.name ?? \"\";\n const parsed = parseDescription(environment.description);\n return {\n name,\n environmentId: lastSegment(name),\n organization: orgIdOf(organization),\n displayName: environment.displayName,\n description: parsed.description,\n type: environment.type,\n apiProxyType: environment.apiProxyType,\n deploymentType: environment.deploymentType,\n forwardProxyUri: environment.forwardProxyUri,\n clientIpResolutionConfig: environment.clientIpResolutionConfig,\n properties: userProperties(environment.properties),\n nodeConfig: environment.nodeConfig,\n hasAttachedFlowHooks: environment.hasAttachedFlowHooks,\n state: environment.state,\n createdAt: environment.createdAt,\n lastModifiedAt: environment.lastModifiedAt,\n };\n};\n\nconst getByName = (name: string) =>\n apigee\n .getOrganizationsEnvironments({ name })\n .pipe(Effect.catchTag([\"NotFound\", \"ApigeeResourceNotFound\"], () => Effect.undefined));\n\nexport const EnvironmentProvider = () =>\n Provider.succeed(Environment, {\n stables: [\n \"name\",\n \"environmentId\",\n \"organization\",\n \"type\",\n \"apiProxyType\",\n \"deploymentType\",\n \"createdAt\",\n ],\n\n diff: Effect.fn(function* ({ news, olds, output }) {\n if (!isResolved(news)) return undefined;\n const previousId = olds?.environmentId ?? output?.environmentId;\n const previousOrg = olds?.organization ?? output?.organization;\n const previousType = olds?.type ?? output?.type;\n const previousProxy = olds?.apiProxyType ?? output?.apiProxyType;\n const previousDeploy = olds?.deploymentType ?? output?.deploymentType;\n const idChanged =\n previousId !== undefined &&\n news.environmentId !== undefined &&\n news.environmentId !== previousId;\n const orgChanged =\n previousOrg !== undefined &&\n news.organization !== undefined &&\n orgIdOf(news.organization) !== orgIdOf(previousOrg);\n const typeChanged =\n previousType !== undefined && news.type !== undefined && news.type !== previousType;\n const proxyChanged =\n previousProxy !== undefined &&\n news.apiProxyType !== undefined &&\n news.apiProxyType !== previousProxy;\n const deployChanged =\n previousDeploy !== undefined &&\n news.deploymentType !== undefined &&\n news.deploymentType !== previousDeploy;\n if (idChanged || orgChanged || typeChanged || proxyChanged || deployChanged) {\n return {\n action: \"replace\" as const,\n deleteFirst: idChanged && !orgChanged,\n };\n }\n return undefined;\n }),\n\n read: Effect.fn(function* ({ id, olds, output }) {\n const env = yield* GcpEnvironment.current;\n const organization = defaultOrgName(env.project, olds?.organization ?? output?.organization);\n const environmentId = yield* letterPrefixedId(\n id,\n olds?.environmentId,\n output?.environmentId,\n 255,\n );\n const name = output?.name ?? resourceName(organization, environmentId);\n const existing = yield* getByName(name);\n if (existing === undefined) return undefined;\n const attrs = toAttrs(existing, organization);\n const { labels } = parseDescription(existing.description);\n return (yield* ownedBy(id, labels)) ? attrs : Unowned(attrs);\n }),\n\n list: () =>\n Effect.gen(function* () {\n const orgs = yield* listOrgNames();\n const rows: Environment[\"Attributes\"][] = [];\n for (const organization of orgs) {\n const org = yield* apigee\n .getOrganizations({ name: organization })\n .pipe(Effect.catchTag([\"NotFound\", \"ApigeeResourceNotFound\"], () => Effect.undefined));\n for (const environmentId of org?.environments ?? []) {\n const existing = yield* getByName(`${organization}/environments/${environmentId}`);\n if (existing !== undefined && hasOwnershipMarker(existing.description)) {\n rows.push(toAttrs(existing, organization));\n }\n }\n }\n return rows;\n }),\n\n reconcile: Effect.fn(function* ({ id, news, output }) {\n const env = yield* GcpEnvironment.current;\n const organization = defaultOrgName(env.project, news.organization);\n const environmentId = yield* letterPrefixedId(\n id,\n news.environmentId,\n output?.environmentId,\n 255,\n );\n const name = resourceName(organization, environmentId);\n const ownership = yield* createOwnership(id);\n const desiredDescription = encodeDescription(ownership, news.description);\n const properties = desiredAttributes(news.properties, ownership);\n\n let current = yield* getByName(output?.name ?? name);\n\n if (current === undefined) {\n const operation = yield* apigee\n .createOrganizationsEnvironments({\n parent: organization,\n name: environmentId,\n body: {\n name: environmentId,\n displayName: news.displayName,\n description: desiredDescription,\n type: news.type,\n apiProxyType: news.apiProxyType,\n deploymentType: news.deploymentType,\n forwardProxyUri: news.forwardProxyUri,\n clientIpResolutionConfig: news.clientIpResolutionConfig,\n properties: recordToProperties(properties),\n nodeConfig: news.nodeConfig,\n },\n })\n .pipe(Effect.catchTag(\"Conflict\", () => Effect.undefined));\n if (operation !== undefined) {\n yield* waitForOperation(operation);\n }\n current = yield* getByName(name);\n }\n\n if (current === undefined) {\n return yield* new EnvironmentNotResolved({ resourceName: name });\n }\n\n const observedProperties = propertiesToRecord(current.properties);\n const displayChanged = (current.displayName ?? \"\") !== (news.displayName ?? \"\");\n const descriptionChanged = (current.description ?? \"\") !== desiredDescription;\n const proxyUriChanged = (current.forwardProxyUri ?? \"\") !== (news.forwardProxyUri ?? \"\");\n const ipChanged = !jsonEqual(current.clientIpResolutionConfig, news.clientIpResolutionConfig);\n const propertiesChanged = !sameRecord(observedProperties, properties);\n const nodeChanged = !jsonEqual(current.nodeConfig, news.nodeConfig);\n\n if (\n displayChanged ||\n descriptionChanged ||\n proxyUriChanged ||\n ipChanged ||\n propertiesChanged ||\n nodeChanged\n ) {\n current = yield* apigee.updateOrganizationsEnvironments({\n name,\n body: {\n name: environmentId,\n displayName: news.displayName,\n description: desiredDescription,\n type: current.type,\n apiProxyType: current.apiProxyType,\n deploymentType: current.deploymentType,\n forwardProxyUri: news.forwardProxyUri,\n clientIpResolutionConfig: news.clientIpResolutionConfig,\n properties: recordToProperties(properties),\n nodeConfig: news.nodeConfig ?? current.nodeConfig,\n },\n });\n }\n\n return toAttrs(current, organization);\n }),\n\n delete: Effect.fn(function* ({ output }) {\n const operation = yield* apigee\n .deleteOrganizationsEnvironments({ name: output.name })\n .pipe(Effect.catchTag([\"NotFound\", \"ApigeeResourceNotFound\"], () => Effect.undefined));\n if (operation !== undefined) {\n yield* waitForOperation(operation, { notFoundOk: true });\n }\n }),\n });\n","preview":null,"history":null,"version":"812d061e9588c1af2f43c1edba4da3e28217bdf4"},"/_session?shell=1":null}