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
2 changes: 1 addition & 1 deletion docs/src/content/docs/cli/graph.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ Edge reconstruction is only as rich as the observed node attributes. AWS's plain

#### `rootReads`: which read answered each root

A lexicon with more than one read path says which one answered each root on the IR's top-level `rootReads` ([#4452](https://github.com/INTENTIUS/chant/issues/4452)). The terraform lexicon is the one that does today. A stock root is read from state, or at the plan depth with `CHANT_TERRAFORM_OBSERVE=plan`, and a choudoufu live root is read with `live-plan` alone or with the plan beside it. Keys are the lexicon's root keys, `terraform.roots.<root>` for terraform. `depth` is the read asked for, `plan` or `live+plan`. `fellBackTo` and `reason` are set only when that read failed. `fellBackTo` is the read that answered instead (`state`, `live`, or `declared` when none did), and `reason` is a short machine-stable cause such as `no-credentials`, `needs-init`, `backend-unreachable` or `plan-failed`. The read that answered a root is `fellBackTo` when it is set, and `depth` otherwise.
A lexicon with more than one read path says which one answered each root on the IR's top-level `rootReads` ([#4452](https://github.com/INTENTIUS/chant/issues/4452)). The terraform and pulumi lexicons do. A stock root is read from state, or at the plan depth with `CHANT_TERRAFORM_OBSERVE=plan`, and a choudoufu live root is read with `live-plan` alone or with the plan beside it. A pulumi member is read from its export, or with `CHANT_PULUMI_OBSERVE=preview` from its engine's preview ([the preview depth](/chant/lexicons/pulumi/member/#the-preview-depth)). Keys are the lexicon's root keys, `terraform.roots.<root>` for terraform and `pulumi.members.<member>` for pulumi. `depth` is the read asked for, `plan`, `live+plan` or `preview`. `fellBackTo` and `reason` are set only when that read failed. `fellBackTo` is the read that answered instead (`state`, `live`, or `declared` when none did), and `reason` is a short machine-stable cause such as `no-credentials`, `needs-init`, `backend-unreachable` or `plan-failed`. The read that answered a root is `fellBackTo` when it is set, and `depth` otherwise.

```json
"rootReads": {
Expand Down
52 changes: 52 additions & 0 deletions lexicons/pulumi/docs/pages/member.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,58 @@ under `ambiguous`.
With no export, or one that is not JSON, the member has no nodes and the
graph's `meta.pulumiMember` is `{ exported: false, reason }`.

### The preview depth

`CHANT_PULUMI_OBSERVE=preview` reads the member one step further, with its
engine's preview: `pulumi preview --json --show-sames`, or `plunge preview`
for a member on plunge. It changes nothing and is off unless set. The
variable takes `state` (the default) or `preview`; `describeResources` also
takes `depth`, which wins over the variable.

Each node the graph holds gets the attributes the terraform plan depth uses
(`CHANT_TERRAFORM_OBSERVE=plan`), so one reader serves both:

| attribute | holds |
|---|---|
| `planAction` | `create`, `update`, `replace`, `delete`, `no-op`, `read` or `forget`; a replace is one action whichever order its steps run in |
| `planActions` | the ops the preview printed, by URN |
| `planActionReason` | `delete-before-replace` or `import`, when either applies |
| `planReplacePaths` | the inputs that force a replacement |
| `planAfterUnknown` | the inputs known only after apply |
| `planChanges` | `{ path, before, after }` for each leaf that differs on an update or a replace; an unknown after value reads `(known after apply)` |

A resource the graph does not hold becomes a node of its own with status
`planned`, carrying the inputs an export's node carries beside the plan
attributes. A stack with no export is drawn this way. A declared node the
preview lists no step for is not observed (`not-reached`); a preview narrowed
with `--target` lists only its targets.

The filter that keeps secrets off a node read from an export applies here
too. A secret, a value under a key that reads as a credential, the `data` of a
Kubernetes Secret or ConfigMap and a string longer than 1024 characters are
left out of the inputs, `planChanges` and `planReplacePaths`; a change under
such a key is not listed.

The IR's `rootReads` names the read for each member, `pulumi.members.<member>`,
with `depth: "preview"`. When the preview does not answer, `fellBackTo` is
`state` if plunge's records answered and `declared` if nothing did, and
`reason` is one of:

| reason | meaning |
|---|---|
| `no-credentials` | the cloud provider or the backend refused the engine's credentials, or none were found |
| `needs-install` | the program's dependencies or a provider plugin are not installed; chant never runs `pulumi install` on a read |
| `no-stack` | the member names no stack and the engine has none selected, or the stack does not exist |
| `no-binary` | the engine binary is not on PATH |
| `preview-failed` | the preview failed for another reason; the engine's first error line is in the run's notes |

```json
"rootReads": {
"pulumi.members.shop": { "depth": "preview" },
"pulumi.members.edge": { "depth": "preview", "fellBackTo": "declared", "reason": "no-credentials" }
}
```

## The change set

The member's part of the change set is `pulumi preview --json`, planner
Expand Down
5 changes: 5 additions & 0 deletions lexicons/pulumi/src/change-set.ts
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,11 @@ function statesOf(steps: PulumiStep[]): { before?: PulumiStepState; after?: Pulu
return { ...(before ? { before } : {}), ...(after ? { after } : {}) };
}

/** {@link statesOf} for the preview observation (`./preview-observation.ts`, #5332): one parse of the steps, not a second. */
export function pulumiStepStates(steps: PulumiStep[]): { before?: PulumiStepState; after?: PulumiStepState } {
return statesOf(steps);
}

function attributesOf(steps: PulumiStep[], action: ChangeSetAction, states: { before?: PulumiStepState; after?: PulumiStepState }): ChangeSetAttribute[] {
if (action !== "create" && action !== "update" && action !== "replace") return [];
const before = isObject(states.before?.inputs) ? states.before!.inputs! : {};
Expand Down
5 changes: 5 additions & 0 deletions lexicons/pulumi/src/chant-floors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,8 @@ export const PULUMI_REFERENCE_CATALOG_FLOOR = NEXT_RELEASE;
* The first pulumi lexicon release with `pulumiCostHold` (`./cost-hold`) and a `planJson` on `pulumi-up`'s artifact: the preview JSON a wave's cost hold hands a user-named command as `{planJson}` (#5341).
*/
export const PULUMI_COST_HOLD_FLOOR = NEXT_RELEASE;

/**
* The first pulumi lexicon release with the preview depth of `describeResources` (`CHANT_PULUMI_OBSERVE=preview`, `./preview-observation`): `pulumi preview --json` (or plunge's) marks each node with its planned operation in the terraform plan observation's attribute names, a stack with no export gets its nodes from the preview marked `planned`, and `rootReads["pulumi.members.<member>"]` says why a preview did not answer (#5332).
*/
export const PULUMI_PREVIEW_OBSERVATION_FLOOR = NEXT_RELEASE;
94 changes: 91 additions & 3 deletions lexicons/pulumi/src/describe-resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,37 @@
* A run that fails leaves every declared entity not-observed with the
* reason, never absent. That includes a plunge older than `plunge graph`
* (INTENTIUS/plunge#40).
*
* ## The preview depth (#5332)
*
* `CHANT_PULUMI_OBSERVE=preview` (or `depth: "preview"` from a caller) reads
* any member, stock or plunge, with its engine's preview instead
* (`./preview-observation.ts`): each resource gets the plan attributes the
* terraform plan depth uses, and a resource the graph does not hold becomes
* a node marked `planned`, which is every resource of a stack with no
* export. The member's `rootReads` entry, `pulumi.members.<member>`, says
* `depth: "preview"`. When the preview fails, the read above answers
* instead (`fellBackTo` `state` when plunge's records did, `declared` when
* nothing did) and `reason` is one of `PREVIEW_READ_REASONS`.
*/
import { basename, dirname, isAbsolute, resolve } from "node:path";
import type { ResourceMetadata } from "@intentius/chant/lexicon";
import { observation, unobservedAll, type DescribeResourcesResult } from "@intentius/chant/observation";
import { normalizeObservation, observation, unobservedAll, type DescribeResourcesResult, type RootRead } from "@intentius/chant/observation";
import { isPulumiNodeless, pulumiNodeKey } from "@intentius/chant/pulumi-urn";
import type { PulumiConfig } from "./config";
import { readPlungeEngineGraph } from "./engine-graph";
import { pulumiMemberEngine } from "./member-engine";
import { plungeMemberGraph, type PulumiRunner } from "./run";
import { observePreview, previewReadReason, PULUMI_OBSERVE_ENV, type PulumiObserveDepth } from "./preview-observation";
import { plungeMemberGraph, previewPulumiMemberRead, type PulumiRunner } from "./run";
import type { PulumiMemberConfig } from "./workspace-member";
import type { SnapshotStore } from "@intentius/chant/lifecycle/snapshot-store";

/** The `describeResources` options this read uses. */
export interface DescribePulumiOptions {
entities: Map<string, { entityType: string; props: Record<string, unknown> }>;
owned?: boolean;
/** Read at this depth, over `CHANT_PULUMI_OBSERVE` (#5332). */
depth?: PulumiObserveDepth;
}

/** Injectable for tests: the member (else read from the project's config) and the plunge runner. */
Expand All @@ -51,6 +67,12 @@ export interface DescribePulumiDeps {
/** Where the config search starts. Default: the process cwd. */
cwd?: string;
plunge?: PulumiRunner;
/** Runs stock pulumi, for the preview depth. */
run?: PulumiRunner;
/** The index store the preview depth reads the member's export from. Default: the project's; `null` reads the checked-in file only. */
exportStore?: SnapshotStore | null;
/** The environment the depth is read from. Default: `process.env`. */
env?: Record<string, string | undefined>;
}

/** The `sources` value on each entity this read answered. */
Expand All @@ -67,8 +89,74 @@ async function configuredMember(cwd: string): Promise<PulumiMemberConfig | undef

/** `LexiconPlugin.describeResources` for the pulumi lexicon. */
export async function describePulumiResources(options: DescribePulumiOptions, deps: DescribePulumiDeps = {}): Promise<DescribeResourcesResult> {
const names = [...options.entities.keys()];
const notes: string[] = [];
const depth = observeDepth(options.depth, deps.env ?? process.env, notes);
const member = deps.member ?? (await configuredMember(resolve(deps.cwd ?? process.cwd())));
if (depth !== "preview" || !member) {
const result = await describeFromRecords(options, deps, member);
return notes.length > 0 ? addNotes(result, notes) : result;
}
return describeFromPreview(options, deps, member, notes);
}

/** The depth asked for: the caller's, then `CHANT_PULUMI_OBSERVE`, else `state`. */
function observeDepth(asked: PulumiObserveDepth | undefined, env: Record<string, string | undefined>, notes: string[]): PulumiObserveDepth {
if (asked) return asked;
const value = env[PULUMI_OBSERVE_ENV];
if (value === "preview" || value === "state") return value;
if (value) notes.push(`${PULUMI_OBSERVE_ENV}=${JSON.stringify(value)} is neither "state" nor "preview" and was ignored`);
return "state";
}

function addNotes(result: DescribeResourcesResult, notes: string[]): DescribeResourcesResult {
const n = normalizeObservation(result);
return observation(n.resources, n.unobserved, n.queried, [...n.notes, ...notes], n.stackExports, n.sources, n.annotations, n.rootReads, n.edges);
}

/** The first line of an engine error, for a note. */
const firstLine = (text: string): string => text.split("\n").find((l) => l.trim() !== "")?.trim() ?? text;

/**
* The preview depth: the member's preview, and when it fails the records
* read below, with the reason on `rootReads`.
*/
async function describeFromPreview(options: DescribePulumiOptions, deps: DescribePulumiDeps, member: PulumiMemberConfig, notes: string[]): Promise<DescribeResourcesResult> {
const label = member.label ?? basename(member.dir);
const rootKey = `pulumi.members.${label}`;
const engine = pulumiMemberEngine(member.dir, member.engine).engine;
const read = await previewPulumiMemberRead({
member: label,
dir: member.dir,
...(member.stack ? { stack: member.stack } : {}),
engine,
...(deps.run ? { run: deps.run } : {}),
...(deps.plunge ? { plunge: deps.plunge } : {}),
...(deps.exportStore !== undefined ? { exportStore: deps.exportStore } : {}),
});
const failure = read.part.member.status === "failed" ? (read.part.member.error ?? "the preview failed") : undefined;
const observed = failure === undefined ? observePreview({ label, preview: read.preview, declared: options.entities as Map<string, { entityType: string }> }) : undefined;
if (observed) {
const note = `${rootKey}: the ${engine} preview answered${observed.unmapped > 0 ? `; ${observed.unmapped} URN(s) had an op the change set has no action for` : ""}`;
return observation(observed.resources, observed.unobserved, observed.queried, [...notes, note], undefined, observed.sources, undefined, { [rootKey]: { depth: "preview" } });
}

const error = failure ?? `${engine} preview --json printed no steps`;
const reason = previewReadReason(error);
const result = await describeFromRecords(options, deps, member);
const answered = normalizeObservation(result);
const fellBackTo: RootRead["fellBackTo"] = Object.keys(answered.resources).length > 0 ? "state" : "declared";
const withReason = addNotes(result, [
...notes,
`${rootKey}: the ${engine} preview failed (${reason}: ${firstLine(error)}), so ${fellBackTo === "state" ? "plunge's records answered" : "no read answered, declared only"}; plan attributes are absent`,
]);
const n = normalizeObservation(withReason);
return observation(n.resources, n.unobserved, n.queried, n.notes, n.stackExports, n.sources, n.annotations, { ...n.rootReads, [rootKey]: { depth: "preview", fellBackTo, reason } }, n.edges);
}

/** The records read: plunge's graph for a member on plunge, nothing for a stock member. */
async function describeFromRecords(options: DescribePulumiOptions, deps: DescribePulumiDeps, configured: PulumiMemberConfig | undefined): Promise<DescribeResourcesResult> {
const names = [...options.entities.keys()];
const member = configured;
if (!member) {
return observation({}, unobservedAll(names, "no-binding", "pulumi.member names no member; chant workspace graph writes it into a pulumi member's reader project", options.entities));
}
Expand Down
3 changes: 2 additions & 1 deletion lexicons/pulumi/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
export { pulumiPlugin } from "./plugin";
export { PULUMI_REFERENCE_CATALOG, CATALOGUED_KINDS, REFERENCES_NOTHING, isUnresolvedKind } from "./reference-catalog";
export { PULUMI_REFERENCE_CATALOG_FLOOR, PULUMI_COST_HOLD_FLOOR } from "./chant-floors";
export { PULUMI_REFERENCE_CATALOG_FLOOR, PULUMI_COST_HOLD_FLOOR, PULUMI_PREVIEW_OBSERVATION_FLOOR } from "./chant-floors";
export { pulumiCostHold, type PulumiCostHold } from "./cost-hold";
export { observePreview, PLANNED_STATUS, PREVIEW_ATTRIBUTE_NAMES, PREVIEW_READ_REASONS, PREVIEW_SOURCE, previewReadReason, PULUMI_OBSERVE_ENV, type PulumiObserveDepth, type PreviewReadReason } from "./preview-observation";
export { pulumiSerializer } from "./serializer";
export { pulumiConfigSchema, pulumiMemberConfigSchema, type PulumiConfig } from "./config";
export { readPulumiMember, PULUMI_EXPORT_FILE, type PulumiMemberConfig, type PulumiMemberReport } from "./workspace-member";
Expand Down
Loading