Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 129 additions & 0 deletions lexicons/gcp/src/api/read-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/**
* GCP read transport (#1209) — the applier's own REST client, pointed at the
* read side.
*
* GCP applies cluster-free over direct REST (#706) and, until this, observed
* through a Config Connector cluster: `kubectl get <cnrm-gvk> -o json` per
* entity, on both the thin and the deep path. That split is what #1085's
* principle forbids — a lexicon should be observed on the transport it is
* applied with, or the two can disagree about what a resource even is — and it
* is what made GCP the heaviest of the three O slots.
*
* ## The URL comes from the applier, not from here
*
* Every GET is built by the same `ResourceMapper.plan()` the applier uses, and
* this module reads `plan().getUrl` rather than composing its own URL. That is
* deliberate: a reader that builds its own paths is a second, silently
* divergent opinion about where a resource lives, and the first symptom is a
* read that reports absent for something the applier just wrote. Reusing the
* mapper makes the two structurally incapable of disagreeing.
*
* ## What that bounds
*
* Coverage is exactly the applier's dispatch table (`MAPPERS`) — StorageBucket,
* PubSubTopic, PubSubSubscription, SecretManagerSecret, IAMServiceAccount,
* RunService. The kubectl path could fetch any CNRM kind the cluster knew
* about, so this is narrower on paper. It is not narrower in practice for
* anything chant can act on: a kind with no mapper cannot be applied either, so
* observing it produced a live tree nothing could ever reconcile against.
*
* A kind outside the table reports NOT-OBSERVED with `unsupported-kind` rather
* than being dropped, so the estate says "chant did not look at this" instead of
* quietly implying it is not there. Widening the table is #1209's stated
* non-goal and belongs with the applier.
*/
import { MAPPERS, type GcpResource, type ResourceMapper } from "../op/activities/gcp-apply";

/** Where to read, and as whom. */
export interface GcpReadClientOptions {
/** Endpoint override for every kind (floci-gcp `http://localhost:4588`). Omit for real GCP. */
endpoint?: string;
/** GCP project the resources live in. */
project: string;
/** Injectable HTTP, so tests never touch the network. */
http?: GcpReadHttp;
}

/** Injectable HTTP client — mirrors the applier's `GcpHttp`. */
export type GcpReadHttp = (method: string, url: string) => Promise<{ status: number; text: string }>;

const defaultHttp: GcpReadHttp = async (method, url) => {
const res = await fetch(url, { method });
return { status: res.status, text: await res.text() };
};

/**
* A read that failed for a reason the caller must classify — carries the HTTP
* status so a 404 (absent) is told apart from a 401/403 (no credentials) and a
* 5xx/network error (could not look). Mirrors `AzureReadError`.
*/
export class GcpReadError extends Error {
constructor(
message: string,
readonly status?: number,
) {
super(message);
this.name = "GcpReadError";
}
}

/** A 404 — the resource is genuinely absent, which is an answer, not a failure. */
export function isNotFound(err: unknown): boolean {
return err instanceof GcpReadError && err.status === 404;
}

/** The mapper for a CNRM kind, or undefined when chant cannot act on it. */
export function mapperForKind(kind: string): ResourceMapper | undefined {
return MAPPERS[kind];
}

/**
* GET one resource on the applier's transport.
*
* `declared` is the entity's own declared spec, which is what `plan()` needs to
* build a URL — the same input the applier hands it. Returns the parsed body,
* or throws {@link GcpReadError} carrying the status.
*/
export async function getResource(
client: GcpReadClientOptions,
kind: string,
name: string,
declared?: Record<string, unknown>,
): Promise<Record<string, unknown>> {
const mapper = mapperForKind(kind);
if (!mapper) throw new GcpReadError(`no REST mapper for kind ${kind}`);

const base = (client.endpoint ?? mapper.defaultHost).replace(/\/$/, "");
const resource: GcpResource = {
kind,
metadata: { name },
spec: (declared?.spec as Record<string, unknown> | undefined) ?? declared ?? {},
};

let getUrl: string;
try {
getUrl = mapper.plan(resource, { base, project: client.project }).getUrl;
} catch (err) {
// A mapper that cannot plan from the declared spec cannot produce a URL, so
// there is nothing to read — a hole, never an absence.
throw new GcpReadError(`could not build a read URL for ${kind}/${name}: ${err instanceof Error ? err.message : String(err)}`);
}

const http = client.http ?? defaultHttp;
let res: { status: number; text: string };
try {
res = await http("GET", getUrl);
} catch (err) {
throw new GcpReadError(err instanceof Error ? err.message : String(err));
}

if (res.status === 404) throw new GcpReadError(`${kind}/${name} not found`, 404);
if (res.status < 200 || res.status >= 300) {
throw new GcpReadError(`GET ${kind}/${name} failed with ${res.status}: ${res.text.slice(0, 200)}`, res.status);
}
try {
return JSON.parse(res.text) as Record<string, unknown>;
} catch {
throw new GcpReadError(`GET ${kind}/${name} returned a non-JSON body`, res.status);
}
}
172 changes: 112 additions & 60 deletions lexicons/gcp/src/deep-observe-hooks.ts
Original file line number Diff line number Diff line change
@@ -1,79 +1,131 @@
/**
* The gcp lexicon's *static* deep-observation noise rules (#1087, epic #1073).
* GCP deep-observation noise rules (#1209) — for REST payloads, not Config
* Connector objects.
*
* Split out from `./deep-observe.ts` for the same reason chant #1076 split
* the k8s lexicon's rules into `lexicons/k8s/src/deep-observe-hooks.ts`: this
* file must be safe to import from `plugin.ts` at module load time, because
* `LexiconPlugin.deepNormalizationHooks` is plain data core reads to
* normalize the *declared* tree — the half of the contract that runs whether
* or not a cluster is ever touched (`lifecycle diff` without `--live`,
* `chant build`, tests that only exercise normalization). `./deep-observe.ts`
* imports `./describe-resources.ts` for the live kubectl transport, which
* pulls in `node:child_process`; nothing this file exports may pull that in,
* directly or transitively, so `chant build` never resolves a process-
* spawning module just to normalize a declared tree.
* ## What this replaced, and why it had to
*
* What lives here is entirely reused from `@intentius/chant/managed-fields`
* (chant #1087's module doc explains why that lives in core rather than the
* k8s lexicon) plus GCP/Config-Connector-specific annotation noise. Nothing
* here needs a live object in hand — the per-resource managed-fields prune
* (which does) is computed in `./deep-observe.ts` and layered on top.
* Until #1209 the deep reader read Config Connector custom resources through
* kubectl, and suppressed noise two ways: this module's static rules (the k8s
* object envelope plus CNRM's own observed-state annotations) and, in
* `./deep-observe.ts`, a per-resource prune driven by `metadata.managedFields`
* — Kubernetes records which manager owns which field, so everything the CNRM
* controller owned was subtracted before the diff ran.
*
* Reading GCP's own REST APIs removes both. **A GCP payload never says who
* wrote a field**, so there is no managed-fields attribution to prune by, and
* it is not a Kubernetes object, so the k8s envelope and CNRM annotation rules
* match nothing in it. Audited every rule that was here: all of them were
* CNRM-shaped, none applies.
*
* So the noise story is re-answered rather than re-pointed, in the shape the
* other two cloud lexicons already use — a static table naming what the
* provider populates. It is hand-maintained, which is the honest cost: a
* server-set field nobody has listed reads as drift until it is. That is
* visible and fixable, where an over-broad rule silently hides real drift.
*/

import type { DeepNode, DeepNormalizationHooks } from "@intentius/chant/lexicon";
import { K8S_OBJECT_ENVELOPE_PRUNE_PATTERNS, k8sListMapOrderKey } from "@intentius/chant/managed-fields";
import type { DeepNode, DeepNormalizationHooks } from "@intentius/chant/deep-observation";

/**
* Config Connector's own observed-state annotations — written by
* `cnrm-controller-manager` after reconciling, mirroring GCP-side state the
* CRD schema has no field for (e.g. secret version pins). Never authored by
* a chant manifest, so pruning them unconditionally cannot hide declared
* config the way blindly pruning every `cnrm.cloud.google.com/*` annotation
* would — several of that family (`state-into-spec`, `deletion-policy`,
* `management-conflict-prevention-policy`) are themselves user-authored
* configuration, not observed state, and pruning those would hide genuine
* drift on them.
* Fields GCP populates on essentially anything, wherever they appear.
*
* Sparse and evidence-based (Config Connector's own docs), the same posture
* every other lexicon's noise table takes. Widening it is additive and needs
* no contract change.
*
* Most CNRM-controller noise doesn't need this list at all — it's already
* pruned by the reused managed-fields ownership rule in `./deep-observe.ts`,
* since `cnrm-controller-manager` is a foreign, undeclared owner of whatever
* it touches. This list only covers the narrow, evidence-based case worth
* pruning even were managedFields attribution ever missing for it.
* Pruned on BOTH sides and regardless of whether source declared them: these
* are server-assigned identity and bookkeeping, and a user who writes one is
* writing something the API will overwrite anyway.
*/
const CNRM_OBSERVED_STATE_ANNOTATION_KEYS: ReadonlySet<string> = new Set([
"cnrm.cloud.google.com/observed-secret-versions",
export const GCP_READ_ONLY_NAMES: ReadonlySet<string> = new Set([
"etag",
"selfLink",
"id",
"projectNumber",
"timeCreated",
"updated",
"createTime",
"updateTime",
"generation",
"metageneration",
"uid",
"state",
"reconciling",
"observedGeneration",
]);

const ANNOTATIONS_PREFIX = "metadata.annotations.";
/**
* Per-kind values GCP fills in when the request omits them.
*
* Unlike {@link GCP_READ_ONLY_NAMES} these are only noise where **source never
* declared the property** — a default somebody explicitly wrote is a fact worth
* diffing, and pruning it would hide a real change away from it. The
* `counterpart === "absent"` gate below is what enforces that, and it is the
* same rule the AWS and Azure hooks apply.
*/
export const GCP_SERVICE_DEFAULTS: Readonly<Record<string, Readonly<Record<string, unknown>>>> = {
StorageBucket: {
storageClass: "STANDARD",
locationType: "multi-region",
"iamConfiguration.publicAccessPrevention": "inherited",
"iamConfiguration.uniformBucketLevelAccess.enabled": false,
"softDeletePolicy.retentionDurationSeconds": "604800",
kind: "storage#bucket",
},
PubSubTopic: {
"messageStoragePolicy.enforceInTransit": false,
},
PubSubSubscription: {
ackDeadlineSeconds: 10,
"expirationPolicy.ttl": "2678400s",
enableMessageOrdering: false,
"retryPolicy.minimumBackoff": "10s",
},
SecretManagerSecret: {
etag: undefined, // covered by READ_ONLY; listed for readers looking here first
},
RunService: {
ingress: "INGRESS_TRAFFIC_ALL",
launchStage: "GA",
},
IAMServiceAccount: {
disabled: false,
},
};

/** chant's own ownership labels, as the applier stamps them. */
const CHANT_OWNERSHIP_LABEL_PATTERNS: ReadonlySet<string> = new Set([
"metadata.labels.managed-by",
"metadata.labels.chant-stack",
"metadata.labels.chant-env",
]);

function isCnrmObservedStateAnnotation(node: DeepNode): boolean {
if (!node.pattern.startsWith(ANNOTATIONS_PREFIX)) return false;
return CNRM_OBSERVED_STATE_ANNOTATION_KEYS.has(node.pattern.slice(ANNOTATIONS_PREFIX.length));
/** Last dotted segment of a path pattern — `spec.foo.etag` -> `etag`. */
function lastSegment(pattern: string): string {
const i = pattern.lastIndexOf(".");
return i === -1 ? pattern : pattern.slice(i + 1);
}

/**
* GCP's static deep-observation noise rules — the entity-agnostic half,
* applied to the *declared* tree by core (`gcpPlugin.deepNormalizationHooks`)
* exactly like the other three rows, and layered under the per-resource
* managed-fields prune in `./deep-observe.ts` for the live tree.
*
* A Config Connector custom resource *is* a Kubernetes object (see
* `./deep-observe.ts`'s module doc), so the generic envelope
* (`K8S_OBJECT_ENVELOPE_PRUNE_PATTERNS`) and Kubernetes' own list-map-key
* ordering conventions (`k8sListMapOrderKey` — needed because some CNRM kinds
* embed genuinely k8s-shaped substructures, e.g. Cloud Run's `RunService`)
* are reused verbatim from `@intentius/chant/managed-fields` rather than
* restated. The one GCP-specific rule is CNRM's own observed-state
* annotation noise.
* GCP's static deep-observation noise rules, applied by core to the declared
* tree and the live tree alike so the two are compared in the same shape.
*/
export const gcpDeepNormalizationHooks: DeepNormalizationHooks = {
prune(node: DeepNode): boolean {
if (K8S_OBJECT_ENVELOPE_PRUNE_PATTERNS.has(node.pattern)) return true;
return isCnrmObservedStateAnnotation(node);
// Server-assigned, wherever it appears, on either side.
if (GCP_READ_ONLY_NAMES.has(lastSegment(node.pattern))) return true;

// chant's own ownership marker is not drift. The applier stamps these, so
// reporting them back is chant showing its own signature to itself — the
// same correction #1301 made for AWS after the emulator began applying tags.
if (CHANT_OWNERSHIP_LABEL_PATTERNS.has(node.pattern)) return true;

// A provider default is noise only where source never declared the
// property. `counterpart` is a tri-state; only `absent` licenses this.
if (node.side !== "live" || node.counterpart !== "absent") return false;
const kindDefaults = GCP_SERVICE_DEFAULTS[shortKind(node.entityType)];
if (!kindDefaults) return false;
return Object.prototype.hasOwnProperty.call(kindDefaults, node.pattern) && kindDefaults[node.pattern] === node.value;
},
orderKey: k8sListMapOrderKey,
};

/** `GCP::Storage::Bucket` -> `StorageBucket`, the key `GCP_SERVICE_DEFAULTS` uses. */
function shortKind(entityType: string): string {
const parts = entityType.split("::");
return parts.length === 3 ? `${parts[1]}${parts[2]}` : entityType;
}
Loading