Compare commits
26 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4a7ae664a6 | |||
| eaace5bd10 | |||
| 174e030dad | |||
| 1305f2b9e9 | |||
| d6fcfc62d9 | |||
| ed5d57d061 | |||
| bcee3f866f | |||
| a57afc7d69 | |||
| 7a9ce01064 | |||
| 37f38f3e54 | |||
| ace9f98072 | |||
| 51e15753eb | |||
| b5e1c11c4a | |||
| db743a4b3d | |||
| 68a6da2388 | |||
| f514936c9c | |||
| 654fe9d306 | |||
| b3799be2fa | |||
| 229ad5bfe7 | |||
| afe83a6fd2 | |||
| 86a9060418 | |||
| d11e749428 | |||
| 4c2620c68b | |||
| 41622c54e0 | |||
| 48e7f943d9 | |||
| 472ac551c2 |
@@ -50,6 +50,8 @@ Start with one file. Optional features use the same loading and inspection model
|
||||
references and choose which configuration fields to hide in inspection output.
|
||||
- [Inspect a load](docs/config.md#layered-metadata): examine sources, presence,
|
||||
history, safe YAML output, or [changes between two loads](docs/config.md#effective-configuration-diffs).
|
||||
- [Hand settings to libraries](docs/consumers/README.md#component-handoff): share
|
||||
one result and let each consumer select its own settings and reporting scope.
|
||||
|
||||
The [consumer guide](docs/consumers/README.md) walks through these tasks and links
|
||||
to maintained examples. The [configuration reference](docs/config.md) defines the
|
||||
|
||||
6
diff.go
6
diff.go
@@ -40,6 +40,10 @@ func Diff[T any](left, right *Result[T]) ([]Difference, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return fromEngineDifferences(values), nil
|
||||
}
|
||||
|
||||
func fromEngineDifferences(values []engine.Difference) []Difference {
|
||||
differences := make([]Difference, len(values))
|
||||
for index, value := range values {
|
||||
differences[index] = Difference{
|
||||
@@ -49,5 +53,5 @@ func Diff[T any](left, right *Result[T]) ([]Difference, error) {
|
||||
HiddenChanged: value.HiddenChanged,
|
||||
}
|
||||
}
|
||||
return differences, nil
|
||||
return differences
|
||||
}
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
|
||||
## Status
|
||||
|
||||
Accepted and implemented. The
|
||||
Accepted and implemented. Extended by
|
||||
[ADR 0024](0024-compare-inspection-views-across-application-types.md) for inspection
|
||||
view comparison across application Go types. The existing same-type comparison
|
||||
API continues to follow this decision. The
|
||||
[configuration contract](../config.md#effective-configuration-diffs) owns current
|
||||
behavior. Completed planning and remediation records are preserved in Git
|
||||
history at `1c2610c` under `docs/roadmap/`.
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
# ADR 0024: Compare Inspection Views Across Application Types
|
||||
|
||||
## Status
|
||||
|
||||
Accepted.
|
||||
|
||||
## Date
|
||||
|
||||
2026-11-20
|
||||
|
||||
## Context
|
||||
|
||||
An application can load configuration once and share the result with libraries.
|
||||
Each library needs to inspect its own section while the application chooses the
|
||||
Go type that holds the complete configuration.
|
||||
|
||||
[ADR 0010](0010-effective-configuration-diff.md) provides comparison between
|
||||
results with the same Go configuration type. A shared inspection view lets a
|
||||
library compare configurations without knowing that application type.
|
||||
|
||||
## Decision
|
||||
|
||||
Provide inspection views that compare saved configuration values from successful
|
||||
loads regardless of the original application Go types. Views being compared
|
||||
select the same location within their respective configurations.
|
||||
|
||||
ConfigKit owns comparison and redaction. Use the saved load snapshots and the
|
||||
equality, sequence comparison, and sensitive-value handling established by
|
||||
ADR 0010. Report changes that overlap the selected location, retaining original
|
||||
application paths and any containing changes.
|
||||
|
||||
This decision extends ADR 0010. The existing same-type comparison API continues
|
||||
to follow that decision.
|
||||
|
||||
## Alternatives Considered
|
||||
|
||||
- **Require matching application Go types.** This follows the existing API's
|
||||
restriction but adds type checks or application-specific adapters to a shared
|
||||
inspection view.
|
||||
- **Let libraries implement comparison.** This gives libraries control but
|
||||
duplicates ConfigKit's comparison and redaction rules.
|
||||
|
||||
## Consequences
|
||||
|
||||
Libraries can offer configuration comparison through one inspection interface
|
||||
across applications. Applications retain ownership of their Go configuration
|
||||
types and presentation.
|
||||
|
||||
A reported change to a containing value may include configuration outside the
|
||||
selected section. The view provides a reporting focus, with the existing
|
||||
redaction rules applied to all returned values.
|
||||
@@ -226,6 +226,13 @@ describe the configuration as it was when the load finished. Returned source,
|
||||
diagnostic, and metadata records are copies; changing them cannot change later
|
||||
queries. Separate loads return independently owned configuration and records.
|
||||
|
||||
`Result.Value` selects trusted current Go values by configuration path, including
|
||||
resolved secrets and zero values without input. It uses ordinary Go assignment:
|
||||
maps, slices, and pointers can share state with `Config`. Availability does not
|
||||
establish input presence; use metadata for that distinction. Capture owned
|
||||
runtime settings before later mutations invalidate the relationship to saved
|
||||
inspection evidence. A manually constructed result also supports value lookup.
|
||||
|
||||
Every source, options, schema, version, defaults, decode, resolution, or
|
||||
validation failure returns a nil result and a `*LoadError`. Successful results
|
||||
contain caller-owned `Config`, detached `Metadata`, a defensive source list,
|
||||
@@ -750,6 +757,7 @@ Use inspection to understand a completed load without reading the files again:
|
||||
| Inspect earlier values as safe YAML | `Explain` or `WriteExplanation` |
|
||||
| Show the saved final configuration as safe YAML | `WriteEffective` |
|
||||
| Compare final values from two loads | `Diff` |
|
||||
| Focus reporting on one location | `InspectSubtree` |
|
||||
|
||||
For example, suppose a typed default sets `workers` to `2`, the main input
|
||||
supplies `workers: 3`, and an overlay supplies `workers: 4`. The final value is
|
||||
@@ -758,6 +766,16 @@ earlier default and main contributions. `History` returns attribution records;
|
||||
`Explain` adds their before/after values. Changing `result.Config.Workers` later
|
||||
does not change any of these saved inspection results.
|
||||
|
||||
An `Inspection` view focuses reporting on a canonical JSON Pointer location.
|
||||
Its `HistoricalPaths` includes observed paths at or below that location and
|
||||
`WriteEffective` renders the selected frozen value with original sensitivity.
|
||||
An absent scope can be selected, but has no effective output. Explicit metadata
|
||||
and explanation queries keep native application paths and may address values
|
||||
outside the focus; source catalogs and resource contexts remain available for
|
||||
the whole load. This is a reporting focus, not a confidentiality boundary. Numeric
|
||||
key and index spellings with the same pointer select the same focus, while
|
||||
explicit queries preserve their normal path intent.
|
||||
|
||||
#### Presence, origins, and historical paths
|
||||
|
||||
`Result.Metadata()` describes every final configuration path. Queries retain explicit
|
||||
@@ -1011,6 +1029,14 @@ uninitialized results return an error with no records. A failed `Load` retains
|
||||
its normal nil-result/`LoadError` behavior, which callers handle before invoking
|
||||
`Diff`.
|
||||
|
||||
`Inspection.Diff` compares focused views at the same canonical location, even
|
||||
when their application root Go types differ. It compares the complete frozen
|
||||
snapshots with the same paired redaction and retains records at, below, or above
|
||||
the focus. Because sequences and structural replacements can be atomic, an
|
||||
ancestor record may reflect a change outside the selected value. Different
|
||||
scopes or unavailable views return an error and no records. Whole-result
|
||||
`Diff[T]` remains restricted to results of the same Go type.
|
||||
|
||||
## Typed secret references
|
||||
|
||||
There are three separate tasks when working with credentials:
|
||||
|
||||
@@ -28,8 +28,24 @@ Start with one file, then choose the tasks your application needs:
|
||||
| Reuse settings or combine record lists | [Inheritance](#named-sibling-inheritance) and [identified sequences](#identified-prompt-sequences) |
|
||||
| Handle credentials | [Typed-secret reference](../config.md#typed-secret-references), [configured startup](#configured-secrets-startup), and the [direct-directory example](../../examples/consumers/consumers_test.go) |
|
||||
| Inspect sources, earlier values, or changes | [Inspect a completed load](#inspect-a-completed-load) and [diffs](#effective-configuration-diffs) |
|
||||
| Hand one result to library consumers | [Component handoff](#component-handoff) |
|
||||
| Upgrade an existing consumer | [Migration guidance](#intentional-migration-changes) |
|
||||
|
||||
## Component handoff
|
||||
|
||||
Register application and library rules in one definition, then load once and
|
||||
pass the whole result to each consumer. A consumer can select its named settings
|
||||
with `Value`, assert its own type, and follow effective field origins through
|
||||
`Metadata` and `SourceContext` to capture resources. It owns any runtime copy it
|
||||
needs. The maintained [one-library example](../../examples/consumers/result_component.go)
|
||||
shows registration, underlay defaults, handoff, and a focused inspection facade;
|
||||
the [two-library example](../../examples/consumers/result_composition.go) composes
|
||||
callbacks and identity registrations for two consumers.
|
||||
|
||||
Views focus reports while explicit metadata and explanation queries retain native
|
||||
application-root paths. See the [configuration contract](../config.md#layered-metadata)
|
||||
for ownership, scope, and frozen inspection behavior.
|
||||
|
||||
## Choosing a loading entry point
|
||||
|
||||
- Use [`Load`](../../lifecycle.go) with one source for an ordinary configuration.
|
||||
|
||||
@@ -58,6 +58,7 @@ Accepted decisions:
|
||||
- [Explicit overrides and safe explanation](adr/0005-explicit-overrides-and-safe-explanation.md)
|
||||
- [Keep the public facade root-owned](adr/0006-public-facade.md)
|
||||
- [Compare frozen effective configuration snapshots](adr/0010-effective-configuration-diff.md)
|
||||
- [Compare inspection views across application types](adr/0024-compare-inspection-views-across-application-types.md)
|
||||
- [Place inputs at literal application mapping paths](adr/0011-input-destinations.md)
|
||||
- [Share dependency-ready ordering](adr/0015-shared-dependency-ready-ordering.md)
|
||||
- [Separate import selection controls](adr/0016-independent-import-controls.md)
|
||||
@@ -68,186 +69,16 @@ Accepted decisions:
|
||||
- [Match registered records during resolution inspection](adr/0021-sequence-resolution-correspondence.md)
|
||||
- [Bind companion contexts after main selection](adr/0022-main-relative-context.md)
|
||||
|
||||
For cross-cutting changes, follow every applicable row. Completed implementation
|
||||
and remediation plans are preserved in Git history at `cb5b435`; use current
|
||||
contracts and the component overview for ongoing work. For example:
|
||||
|
||||
```sh
|
||||
git show cb5b435:docs/roadmap/remediation.md
|
||||
```
|
||||
For cross-cutting changes, follow every applicable row. Use current contracts
|
||||
and the component overview for ongoing work.
|
||||
|
||||
Release-candidate, publication, and verification work follows the operational
|
||||
[release procedure](release.md). Its module-selected ReleaseKit `publish`
|
||||
invocation validates the committed candidate and publishes only the intended
|
||||
tag; those release checks remain distinct from the everyday development check.
|
||||
|
||||
The completed string-and-integer schema-version implementation and remediation
|
||||
records are preserved in Git history at `244104f`. The
|
||||
[configuration contract](config.md#application-schema-versions) owns current behavior.
|
||||
|
||||
The completed source-origins and public-facade roadmaps, implementation plan, and
|
||||
resolved review findings are preserved in Git history at `5760614`, for example
|
||||
`git show 5760614:docs/roadmap/remediation.md`. The earlier source-origins staged
|
||||
plan remains at `28e7fc5:docs/roadmap/implementation.md`. Current resolution
|
||||
behavior belongs to the [configuration contract](config.md#recorded-application-resolution),
|
||||
and current facade ownership belongs to the [component overview](internal/overview.md).
|
||||
|
||||
## Baseline validation
|
||||
|
||||
The completed main-relative companion roadmap, Audita request, implementation
|
||||
plan, and remediation report are preserved in Git history at `47547bc` under
|
||||
`docs/roadmap/`. The [layered loading contract](config.md#layered-loading)
|
||||
describes current behavior, and [ADR 0022](adr/0022-main-relative-context.md)
|
||||
records the context binding decision.
|
||||
|
||||
The completed field-level sequence resolution roadmap, implementation plan, and
|
||||
resolved audit findings are preserved in Git history at `7e53863` under
|
||||
`docs/roadmap/`. For example:
|
||||
|
||||
```sh
|
||||
git show 7e53863:docs/roadmap/implementation.md
|
||||
git show 7e53863:docs/roadmap/remediation.md
|
||||
```
|
||||
|
||||
The [configuration contract](config.md#recorded-application-resolution) owns
|
||||
current resolution behavior, and [ADR 0021](adr/0021-sequence-resolution-correspondence.md)
|
||||
records the correspondence decision.
|
||||
|
||||
The completed filesystem-source and underlay roadmap, original feature request,
|
||||
implementation plan, and resolved remediation record are preserved in Git history
|
||||
at `b604aa1` under `docs/roadmap/`. Current behavior belongs to the
|
||||
[configuration contract](config.md#layered-loading). Built-in sibling
|
||||
inheritance is now part of the [configuration contract](config.md#sibling-inheritance).
|
||||
The completed request, roadmap, plan, and resolved review findings are preserved
|
||||
in Git history at `83c59ea` under `docs/roadmap/`.
|
||||
|
||||
The completed overlay rename plan and release-workflow simplification record are
|
||||
preserved in Git history at `73ce6e9` under `docs/roadmap/`. Current overlay
|
||||
behavior belongs to the [configuration contract](config.md#selected-overlays),
|
||||
and release operations belong to the [release procedure](release.md).
|
||||
|
||||
The completed ReleaseKit adoption, startup performance request and experiments,
|
||||
benchmark evidence, performance audit, implementation plan, and remediation
|
||||
record are preserved in Git history at `8e91a2b` under `docs/roadmap/`. For example:
|
||||
|
||||
```sh
|
||||
git show 8e91a2b:docs/roadmap/startup-benchmark.md
|
||||
```
|
||||
|
||||
Remaining optimization candidates belong to
|
||||
[future performance experiments](roadmap/future.md#3-performance-experiments).
|
||||
|
||||
The completed effective-configuration diff roadmap, implementation plan, and
|
||||
resolved review findings are preserved in Git history at `1c2610c` under
|
||||
`docs/roadmap/`. The
|
||||
[configuration contract](config.md#effective-configuration-diffs) owns current
|
||||
comparison and disclosure behavior, and
|
||||
[ADR 0010](adr/0010-effective-configuration-diff.md) records the decision.
|
||||
|
||||
The completed input-destination, relative-import-destination, and shared
|
||||
source-version roadmaps, associated consumer request, implementation plan, and
|
||||
resolved review findings are preserved in Git history at `e4270c9` under
|
||||
`docs/roadmap/`. For example:
|
||||
|
||||
```sh
|
||||
git show e4270c9:docs/roadmap/implementation.md
|
||||
git show e4270c9:docs/roadmap/remediation.md
|
||||
```
|
||||
|
||||
Current behavior belongs to the configuration contract's
|
||||
[input destinations](config.md#input-destinations),
|
||||
[imports](config.md#explicit-imports), and
|
||||
[shared source-version checks](config.md#shared-source-version-checks) sections.
|
||||
Explicit sequence-item placement, collection operations, identity registration,
|
||||
and final registered-identity validation are owned by the
|
||||
[strict composition](config.md#strict-document-composition) section;
|
||||
[imports](config.md#explicit-imports) owns acquisition and scheduling. The
|
||||
[maintained sequence catalog](consumers/README.md#identified-prompt-sequences)
|
||||
shows the consumer boundary, and [ADR 0017](adr/0017-collection-sequence-policy.md)
|
||||
records the collection decision.
|
||||
|
||||
The completed sequence-composition roadmap, implementation plan, and resolved
|
||||
remediation record are preserved in Git history at `008d2ba` under
|
||||
`docs/roadmap/`. For example:
|
||||
|
||||
```sh
|
||||
git show 008d2ba:docs/roadmap/sequence-composition.md
|
||||
git show 008d2ba:docs/roadmap/implementation.md
|
||||
git show 008d2ba:docs/roadmap/remediation.md
|
||||
```
|
||||
|
||||
The completed import-discovery roadmap, implementation plan, and resolved
|
||||
remediation record are preserved in Git history at `5747ec4` under
|
||||
`docs/roadmap/`. For example:
|
||||
|
||||
```sh
|
||||
git show 5747ec4:docs/roadmap/imports.md
|
||||
git show 5747ec4:docs/roadmap/implementation.md
|
||||
git show 5747ec4:docs/roadmap/remediation.md
|
||||
```
|
||||
|
||||
The subsequent import-integration audit and completed remediation record are
|
||||
preserved at `6903c9e:docs/roadmap/remediation.md`; retrieve them with
|
||||
`git show 6903c9e:docs/roadmap/remediation.md`.
|
||||
|
||||
The completed sequence-identity/collection-policy roadmap and implementation
|
||||
plan are preserved in Git history at `d0a605a`:
|
||||
|
||||
```sh
|
||||
git show d0a605a:docs/roadmap/sequences.md
|
||||
git show d0a605a:docs/roadmap/implementation.md
|
||||
```
|
||||
|
||||
Current behavior belongs to the configuration contract's
|
||||
[strict composition](config.md#strict-document-composition),
|
||||
[sibling inheritance](config.md#sibling-inheritance), and
|
||||
[CLI overrides](config.md#explicit-cli-overrides) sections.
|
||||
The completed remediation record, including the algorithm-audit findings, is
|
||||
preserved at `ea46001:docs/roadmap/remediation.md`.
|
||||
|
||||
The completed configuration-discovery roadmap, implementation plan, and
|
||||
remediation record are preserved in Git history at `0369111`, for example
|
||||
`git show 0369111:docs/roadmap/remediation.md`. Current behavior belongs to
|
||||
[configuration discovery](config.md#configuration-discovery); the public
|
||||
[discovery declarations](../discovery.go) own the Go API.
|
||||
|
||||
The completed consolidation proposal, implementation plan, and resolved audit
|
||||
findings are preserved in Git history at `34cbc0d` under `docs/roadmap/`. For
|
||||
example:
|
||||
|
||||
```sh
|
||||
git show 34cbc0d:docs/roadmap/implementation.md
|
||||
git show 34cbc0d:docs/roadmap/remediation.md
|
||||
```
|
||||
|
||||
Potential enhancements are tracked in [future features](roadmap/future.md).
|
||||
The completed audit-remediation, internal-boundary simplification, shared-history,
|
||||
and public API cleanup roadmaps, reviews, and resolved findings are preserved at
|
||||
`68400ff` under `docs/roadmap/`. For example:
|
||||
|
||||
```sh
|
||||
git show 68400ff:docs/roadmap/api.md
|
||||
git show 68400ff:docs/roadmap/remediation.md
|
||||
```
|
||||
|
||||
Their earlier completed implementation plans are preserved at
|
||||
`bb5540b:docs/roadmap/implementation.md` (audit remediation),
|
||||
`f6d54a0:docs/roadmap/implementation.md` (internal-boundary simplification), and
|
||||
`07e4ae5:docs/roadmap/implementation.md` (shared history). The plan at
|
||||
`68400ff:docs/roadmap/implementation.md` records the public API cleanup.
|
||||
Current behavior and migration information belong to the
|
||||
[configuration contract](config.md), public declaration comments, and
|
||||
[consumer guide](consumers/README.md#pre-v1-public-api-cleanup).
|
||||
|
||||
The consolidated audit, including
|
||||
findings, evidence, and settled scope decisions, is preserved at
|
||||
`453da68:docs/roadmap/audit.md`; the original nine reports are preserved at
|
||||
`ecd5d5d` under `docs/roadmap/`. Retrieve the consolidated record with:
|
||||
|
||||
```sh
|
||||
git show 453da68:docs/roadmap/audit.md
|
||||
```
|
||||
|
||||
Install the Go version required by `go.mod` or a compatible newer toolchain.
|
||||
Acquire declared dependencies explicitly before entering an offline
|
||||
development or validation environment:
|
||||
@@ -309,6 +140,7 @@ code changes. Use the component overview to find the corresponding implementatio
|
||||
| Input and relative-import destinations, mounted sources, and source ownership | [Destination engine tests](../internal/engine/destination_test.go), [tier tests](../internal/engine/destination_tiers_test.go), [import traversal and version tests](../internal/engine/destination_import_test.go), [accounting tests](../internal/engine/destination_accounting_test.go), [lifecycle inspection tests](../internal/engine/destination_import_lifecycle_test.go), [public source/error tests](../facade_destination_test.go), [resource contexts](../facade_resource_context_test.go), and [consumer examples](../examples/consumers/destinations_test.go) | `go test ./internal/engine -run 'Destination\|Import\|Glob\|Mounted'`, `go test . -run 'Destination\|Import\|SourceContext\|FacadeMounted'`, and `go test ./examples/consumers` |
|
||||
| Shared source-version modes and evidence | [Engine source-version tests](../internal/engine/source_version_test.go), [public facade tests](../facade_source_version_mode_test.go), and [consumer example tests](../examples/consumers/layered_test.go) | `go test ./internal/engine -run 'SourceVersion'`, `go test . -run 'SourceVersion'`, and `go test ./examples/consumers` |
|
||||
| Schema, defaults, projection, cloning | [Implementation flow](internal/overview.md#implementation-flow), [schema](../internal/engine/schema_test.go), [decoding](../internal/engine/decode_test.go), [projection and typed cloning](../internal/engine/projection_test.go) | `go test ./internal/engine -run 'Schema\|Decode\|Projection\|Clone\|Inline\|CompareDocument'` |
|
||||
| Current values and focused inspection | [Value tests](../facade_result_value_test.go), [view tests](../facade_inspection_view_test.go), [comparison tests](../facade_inspection_diff_test.go), and [history integration](../facade_inspection_history_test.go) | `go test . -run 'TestResultValue\|TestInspectionView'` and `go test ./internal/engine -run 'TestResultValue\|Diff\|History'` |
|
||||
| Lifecycle, resolution, validation, callback ownership | [Loading](../internal/engine/load_test.go), [resolution](../internal/engine/resolution_test.go), [validation](../internal/engine/validation_test.go), [ownership](../internal/engine/callback_ownership_test.go), [independence](../internal/engine/independence_test.go) | `go test ./internal/engine -run 'Load\|Resolution\|Validation\|Validator\|Hook\|Callback\|Parallel'` |
|
||||
| Resolution sequence matching and inspection | [Correspondence](../internal/engine/resolution_correspondence_test.go), [auditing and history](../internal/engine/resolution_compare_test.go), [public integration](../facade_resolution_sequences_test.go) | `go test ./internal/engine -run 'Resolution\|History\|Explain\|Sensitivity'` and `go test . -run 'Resolution\|SequenceIdentity\|Diff'` |
|
||||
| Paths, metadata, provenance | [Paths](../internal/engine/path_test.go), [metadata](../internal/engine/metadata_test.go), [provenance](../internal/engine/provenance_test.go) | `go test ./internal/engine -run 'Path\|Metadata\|Provenance\|Queries'` |
|
||||
|
||||
@@ -45,6 +45,10 @@ Implemented component owners:
|
||||
- Root `Diff` and `Difference` provide the public comparison boundary and
|
||||
convert detached engine records to root-owned paths and snapshots; consumer
|
||||
examples own presentation of the safe changed regions.
|
||||
- `Result.Value` delegates current Go-value navigation to an operation-local
|
||||
engine schema builder and existing field/path bindings. Root `Inspection`
|
||||
wraps an engine view borrowing the frozen inspection and canonical scope;
|
||||
it reuses history enumeration, document redaction, and whole-result diff.
|
||||
- `internal/document` owns the parser-independent ordered tree and cloning.
|
||||
`internal/yaml` is the sole upstream YAML adapter and parser/dumper boundary.
|
||||
- Engine mechanism tests own source, composition, inheritance, decoding,
|
||||
|
||||
@@ -316,12 +316,14 @@ See [ADR 0005](../adr/0005-explicit-overrides-and-safe-explanation.md).
|
||||
Detailed syntax and operation tables belong to the
|
||||
[current configuration contract](../config.md).
|
||||
|
||||
The frozen inspection boundary also supports comparing completed same-type
|
||||
results without reopening sources or rerunning the load lifecycle. The
|
||||
The frozen inspection boundary supports comparing completed same-type results
|
||||
and focused views across application root types without reopening sources or
|
||||
rerunning the load lifecycle. The
|
||||
[configuration contract](../config.md#effective-configuration-diffs) owns
|
||||
comparison and disclosure behavior, the [component overview](../internal/overview.md)
|
||||
owns implementation responsibility, and [ADR 0010](../adr/0010-effective-configuration-diff.md)
|
||||
records the accepted decision.
|
||||
and [ADR 0024](../adr/0024-compare-inspection-views-across-application-types.md)
|
||||
record the accepted decisions.
|
||||
|
||||
## Collection Identity And Combination
|
||||
|
||||
|
||||
58
docs/releases/v1.4.0.md
Normal file
58
docs/releases/v1.4.0.md
Normal file
@@ -0,0 +1,58 @@
|
||||
# ConfigKit v1.4.0
|
||||
|
||||
Applications can now load configuration once and pass the complete result to
|
||||
libraries that select their own typed settings and reporting scope. The new APIs
|
||||
reuse the original load's provenance, resource contexts, and frozen inspection
|
||||
state.
|
||||
|
||||
## Current typed values
|
||||
|
||||
`Result.Value(path)` selects a current Go value without requiring the consumer
|
||||
to know the application's root configuration type. It uses ConfigKit's existing
|
||||
field bindings and semantic paths, preserving named types, terminal pointers,
|
||||
and resolved `Secret` values. A present nil value succeeds; unavailable paths
|
||||
return false. Lookup also works with manually constructed results and returns
|
||||
terminal values without conversion or revalidation.
|
||||
|
||||
This is trusted access with ordinary Go assignment semantics: maps, slices, and
|
||||
pointers can share state with `Result.Config`. Later caller changes are visible
|
||||
to lookup, while inspection continues to describe the completed load. Consumers
|
||||
remain responsible for capturing any owned runtime settings they need.
|
||||
[Value API](../../result_value.go) · [Ownership contract](../config.md#completion-and-resource-lifetime)
|
||||
|
||||
## Focused inspection
|
||||
|
||||
`Result.InspectSubtree(path)` returns a non-generic `Inspection` view. It renders
|
||||
the selected frozen value with existing redaction, enumerates observed paths
|
||||
within the scope, and forwards explanations, metadata, source records, and
|
||||
resource contexts using native application paths.
|
||||
|
||||
A valid absent scope can be selected for history and comparison. Rendering an
|
||||
absent effective value returns an error without output; explicit null renders
|
||||
normally. Numeric key and index spellings with the same canonical JSON Pointer
|
||||
select the same reporting location. Explicit queries retain their normal path
|
||||
intent and can address values outside the focus. Source catalogs and ancestor
|
||||
evidence remain available: the view is a reporting focus, not an isolation
|
||||
boundary. Scoped path enumeration avoids copying unrelated effective metadata.
|
||||
[Inspection API](../../inspection_view.go) · [Inspection contract](../config.md#layered-metadata)
|
||||
|
||||
`Inspection.Diff` compares views selecting the same location, including views
|
||||
from different application root Go types. It uses the existing whole-snapshot
|
||||
comparison and paired redaction, then retains differences at, below, or above
|
||||
the focus. Sequences remain atomic: a retained ancestor difference can reflect
|
||||
changes outside the selected descendant. Uninitialized views and mismatched
|
||||
scopes return an error without records. Existing same-type `Diff[T]` is unchanged.
|
||||
[Comparison contract](../config.md#effective-configuration-diffs)
|
||||
|
||||
The maintained [one-library](../../examples/consumers/result_component.go) and
|
||||
[two-library](../../examples/consumers/result_composition.go) examples demonstrate
|
||||
registration, one-load handoff, owned settings capture, and resource lookup from
|
||||
effective source origins. [Consumer guidance](../consumers/README.md#component-handoff)
|
||||
|
||||
## Compatibility
|
||||
|
||||
These APIs are additive. Existing loading, composition, inspection, and shared
|
||||
source-version behavior remains unchanged; existing callers need no migration.
|
||||
The Go consumer minimum remains 1.27.0.
|
||||
|
||||
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.4.0/COPYRIGHT) | [LICENSE](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.4.0/LICENSE) | [ATTRIBUTION](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.4.0/docs/oss/attribution.md)
|
||||
122
examples/consumers/result_component.go
Normal file
122
examples/consumers/result_component.go
Normal file
@@ -0,0 +1,122 @@
|
||||
package consumers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"io/fs"
|
||||
"path"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
// ComponentSettings is a library-owned configuration type embedded by an application.
|
||||
type ComponentSettings struct {
|
||||
Name string `yaml:"name"`
|
||||
Resource string `yaml:"resource"`
|
||||
Token string `yaml:"token"`
|
||||
Entries []ComponentItem `yaml:"entries"`
|
||||
}
|
||||
|
||||
// ComponentItem is one identified library setting.
|
||||
type ComponentItem struct {
|
||||
ID string `yaml:"id"`
|
||||
Resource string `yaml:"resource"`
|
||||
}
|
||||
|
||||
// ComponentApplication is the application-owned root for this example.
|
||||
type ComponentApplication struct {
|
||||
Component ComponentSettings `yaml:"component"`
|
||||
}
|
||||
|
||||
// ComponentResult is the small interface required by the library at handoff.
|
||||
type ComponentResult interface {
|
||||
Value(configkit.Path) (any, bool)
|
||||
Metadata() configkit.Metadata
|
||||
SourceContext(string) (configkit.ResourceContext, bool)
|
||||
}
|
||||
|
||||
// ComponentRuntime contains settings and captured resource data owned by the library.
|
||||
type ComponentRuntime struct {
|
||||
Settings ComponentSettings
|
||||
Resource []byte
|
||||
}
|
||||
|
||||
// ComponentDefinition registers library behavior through an application field selector.
|
||||
func ComponentDefinition[T any](selectSettings func(*T) *ComponentSettings) configkit.Definition[T] {
|
||||
component := configkit.Keys("component")
|
||||
return configkit.Definition[T]{
|
||||
SequenceIdentities: []configkit.SequenceIdentity{configkit.SequenceIdentityAt(component.Key("entries"), "id")},
|
||||
Resolve: func(root *T, resolution *configkit.Resolution) error {
|
||||
settings := selectSettings(root)
|
||||
configkit.Default(resolution, component.Key("name"), &settings.Name, "default component", "use component default")
|
||||
configkit.Normalize(resolution, component.Key("name"), &settings.Name, strings.TrimSpace(settings.Name), "trim component name")
|
||||
return nil
|
||||
},
|
||||
Validate: func(root *T, validation *configkit.Validation) {
|
||||
if selectSettings(root).Name == "" {
|
||||
validation.Error(component.Key("name"), "component name is required")
|
||||
}
|
||||
},
|
||||
Sensitive: func(path configkit.Path) bool { return path.String() == "/component/token" },
|
||||
}
|
||||
}
|
||||
|
||||
// LoadComponentApplication assembles one application load with bundled underlay defaults.
|
||||
func LoadComponentApplication(source configkit.Source) (*configkit.Result[ComponentApplication], error) {
|
||||
return configkit.LoadLayered(configkit.Input{Source: source}, configkit.LayeredOptions[ComponentApplication]{
|
||||
Underlays: []configkit.Underlay{{Inputs: []configkit.Input{{Source: configkit.Bytes("component defaults", []byte("component: {entries: [{id: default}]}\n"))}}}},
|
||||
Definition: ComponentDefinition(func(root *ComponentApplication) *ComponentSettings { return &root.Component }),
|
||||
})
|
||||
}
|
||||
|
||||
// NewComponent accepts the entire result, selects library settings, and captures
|
||||
// a resource relative to the effective field's original source.
|
||||
func NewComponent(result ComponentResult) (ComponentRuntime, error) {
|
||||
value, ok := result.Value(configkit.Keys("component"))
|
||||
settings, typed := value.(ComponentSettings)
|
||||
if !ok || !typed {
|
||||
return ComponentRuntime{}, errors.New("component settings unavailable")
|
||||
}
|
||||
settings.Entries = slices.Clone(settings.Entries)
|
||||
info, ok := result.Metadata().Lookup(configkit.Keys("component", "resource"))
|
||||
if !ok || len(info.Origin.Locations) != 1 {
|
||||
return ComponentRuntime{}, errors.New("component resource origin unavailable")
|
||||
}
|
||||
context, ok := result.SourceContext(info.Origin.Locations[0].SourceID)
|
||||
if !ok {
|
||||
return ComponentRuntime{}, errors.New("component resource context unavailable")
|
||||
}
|
||||
data, err := fs.ReadFile(context.FS, path.Join(context.BaseDir, settings.Resource))
|
||||
if err != nil {
|
||||
return ComponentRuntime{}, err
|
||||
}
|
||||
return ComponentRuntime{Settings: settings, Resource: data}, nil
|
||||
}
|
||||
|
||||
// ComponentInspection is a library-owned facade over one selected reporting view.
|
||||
type ComponentInspection struct{ view configkit.Inspection }
|
||||
|
||||
// InspectComponent selects the library's conventional reporting scope once.
|
||||
func InspectComponent(result interface {
|
||||
InspectSubtree(configkit.Path) (configkit.Inspection, bool)
|
||||
}) (ComponentInspection, bool) {
|
||||
view, ok := result.InspectSubtree(configkit.Keys("component"))
|
||||
return ComponentInspection{view: view}, ok
|
||||
}
|
||||
|
||||
// WriteEffective renders the frozen component safely.
|
||||
func (i ComponentInspection) WriteEffective(output io.Writer) error {
|
||||
return i.view.WriteEffective(output)
|
||||
}
|
||||
|
||||
// Explain forwards native application paths without changing their meaning.
|
||||
func (i ComponentInspection) Explain(path configkit.Path) (configkit.Explanation, bool) {
|
||||
return i.view.Explain(path)
|
||||
}
|
||||
|
||||
// Diff compares two frozen component views.
|
||||
func (i ComponentInspection) Diff(other ComponentInspection) ([]configkit.Difference, error) {
|
||||
return i.view.Diff(other.view)
|
||||
}
|
||||
57
examples/consumers/result_component_test.go
Normal file
57
examples/consumers/result_component_test.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package consumers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func TestComponentHandoff(t *testing.T) {
|
||||
filesystem := configkit.NewFilesystem("application", fstest.MapFS{
|
||||
"config/main.yml": &fstest.MapFile{Data: []byte("component: {name: ' example ', resource: asset.txt, token: disposable-canary}\n")},
|
||||
"config/asset.txt": &fstest.MapFile{Data: []byte("resource data")},
|
||||
})
|
||||
result, err := LoadComponentApplication(filesystem.File("config/main.yml"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runtime, err := NewComponent(result)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if runtime.Settings.Name != "example" || len(runtime.Settings.Entries) != 1 || runtime.Settings.Entries[0].ID != "default" || string(runtime.Resource) != "resource data" {
|
||||
t.Fatalf("component runtime = %#v", runtime)
|
||||
}
|
||||
runtime.Settings.Entries[0].ID = "runtime change"
|
||||
if result.Config.Component.Entries[0].ID != "default" {
|
||||
t.Fatal("runtime settings share the result's slice")
|
||||
}
|
||||
entries, found := result.Metadata().Lookup(configkit.Keys("component", "entries"))
|
||||
if !result.Metadata().IsExplicit(configkit.Keys("component", "resource")) || !found || entries.Origin.Layer != configkit.LayerUnderlay {
|
||||
t.Fatal("presence did not retain source distinction")
|
||||
}
|
||||
view, ok := InspectComponent(result)
|
||||
if !ok {
|
||||
t.Fatal("component view unavailable")
|
||||
}
|
||||
var output bytes.Buffer
|
||||
if err := view.WriteEffective(&output); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(output.String(), "disposable-canary") || !strings.Contains(output.String(), "example") {
|
||||
t.Fatalf("unsafe report: %s", output.String())
|
||||
}
|
||||
if _, ok := view.Explain(configkit.Keys("component", "resource")); !ok {
|
||||
t.Fatal("resource explanation unavailable")
|
||||
}
|
||||
if diff, err := view.Diff(view); err != nil || len(diff) != 0 {
|
||||
t.Fatalf("view diff = %#v, %v", diff, err)
|
||||
}
|
||||
_, err = LoadComponentApplication(configkit.Bytes("invalid.yml", []byte("component: {name: ' '}\n")))
|
||||
if err == nil {
|
||||
t.Fatal("component validation did not fail")
|
||||
}
|
||||
}
|
||||
86
examples/consumers/result_composition.go
Normal file
86
examples/consumers/result_composition.go
Normal file
@@ -0,0 +1,86 @@
|
||||
package consumers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
// AuditSettings is a second library's independent configuration type.
|
||||
type AuditSettings struct {
|
||||
Enabled bool `yaml:"enabled"`
|
||||
Rules []AuditRule `yaml:"rules"`
|
||||
}
|
||||
|
||||
// AuditRule has an identity used by the application's assembly policy.
|
||||
type AuditRule struct {
|
||||
ID string `yaml:"id"`
|
||||
}
|
||||
|
||||
// ComposedApplication combines application and two library settings.
|
||||
type ComposedApplication struct {
|
||||
Label string `yaml:"label"`
|
||||
Component ComponentSettings `yaml:"component"`
|
||||
Audit AuditSettings `yaml:"audit"`
|
||||
}
|
||||
|
||||
// AuditResult is the smaller interface needed by the audit consumer.
|
||||
type AuditResult interface {
|
||||
Value(configkit.Path) (any, bool)
|
||||
}
|
||||
|
||||
// NewAuditSettings takes a copy of the second library's settings.
|
||||
func NewAuditSettings(result AuditResult) (AuditSettings, error) {
|
||||
value, ok := result.Value(configkit.Keys("audit"))
|
||||
settings, typed := value.(AuditSettings)
|
||||
if !ok || !typed {
|
||||
return AuditSettings{}, errors.New("audit settings unavailable")
|
||||
}
|
||||
settings.Rules = append([]AuditRule(nil), settings.Rules...)
|
||||
return settings, nil
|
||||
}
|
||||
|
||||
func auditDefinition[T any](selectSettings func(*T) *AuditSettings) configkit.Definition[T] {
|
||||
audit := configkit.Keys("audit")
|
||||
return configkit.Definition[T]{
|
||||
SequenceIdentities: []configkit.SequenceIdentity{configkit.SequenceIdentityAt(audit.Key("rules"), "id")},
|
||||
Resolve: func(root *T, resolution *configkit.Resolution) error {
|
||||
configkit.Default(resolution, audit.Key("enabled"), &selectSettings(root).Enabled, true, "enable audit by default")
|
||||
return nil
|
||||
},
|
||||
Validate: func(root *T, validation *configkit.Validation) {
|
||||
if selectSettings(root).Enabled && len(selectSettings(root).Rules) == 0 {
|
||||
validation.Error(audit.Key("rules"), "enabled audit requires a rule")
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// LoadComposedApplication applies application and library callbacks in order in
|
||||
// one load. A placed component input remains an ordinary underlay.
|
||||
func LoadComposedApplication(main, component configkit.Input) (*configkit.Result[ComposedApplication], error) {
|
||||
componentRules := ComponentDefinition(func(root *ComposedApplication) *ComponentSettings { return &root.Component })
|
||||
auditRules := auditDefinition(func(root *ComposedApplication) *AuditSettings { return &root.Audit })
|
||||
identities := append(componentRules.SequenceIdentities, auditRules.SequenceIdentities...)
|
||||
definition := configkit.Definition[ComposedApplication]{
|
||||
SequenceIdentities: identities,
|
||||
Sensitive: componentRules.Sensitive,
|
||||
Resolve: func(root *ComposedApplication, resolution *configkit.Resolution) error {
|
||||
configkit.Normalize(resolution, configkit.Keys("label"), &root.Label, strings.TrimSpace(root.Label), "trim application label")
|
||||
if err := componentRules.Resolve(root, resolution); err != nil {
|
||||
return err
|
||||
}
|
||||
return auditRules.Resolve(root, resolution)
|
||||
},
|
||||
Validate: func(root *ComposedApplication, validation *configkit.Validation) {
|
||||
if root.Label == "" {
|
||||
validation.Error(configkit.Keys("label"), "application label is required")
|
||||
}
|
||||
componentRules.Validate(root, validation)
|
||||
auditRules.Validate(root, validation)
|
||||
},
|
||||
}
|
||||
component.Destination = configkit.Keys("component")
|
||||
return configkit.LoadLayered(main, configkit.LayeredOptions[ComposedApplication]{Underlays: []configkit.Underlay{{Inputs: []configkit.Input{component}}}, Definition: definition})
|
||||
}
|
||||
69
examples/consumers/result_composition_test.go
Normal file
69
examples/consumers/result_composition_test.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package consumers
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"path"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func TestComposedConsumersShareOneLoad(t *testing.T) {
|
||||
filesystem := configkit.NewFilesystem("components", fstest.MapFS{
|
||||
"config/component.yml": &fstest.MapFile{Data: []byte("name: ' component '\nresource: asset.txt\nentries:\n - {id: parent, resource: asset.txt}\n - {id: child, extends: {id: parent}}\n")},
|
||||
"config/asset.txt": &fstest.MapFile{Data: []byte("shared asset")},
|
||||
})
|
||||
component := configkit.Input{Source: filesystem.File("config/component.yml")}
|
||||
load := func(main string) *configkit.Result[ComposedApplication] {
|
||||
t.Helper()
|
||||
result, err := LoadComposedApplication(configkit.Input{Source: configkit.Bytes("app.yml", []byte(main))}, component)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
first := load("label: ' app '\naudit: {enabled: false, rules: [{id: first}]}\n")
|
||||
second := load("label: second\naudit: {rules: [{id: second}]}\n")
|
||||
componentRuntime, err := NewComponent(first)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
audit, err := NewAuditSettings(first)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first.Config.Label != "app" || componentRuntime.Settings.Name != "component" || string(componentRuntime.Resource) != "shared asset" || audit.Enabled || audit.Rules[0].ID != "first" {
|
||||
t.Fatalf("first result = %#v %#v", componentRuntime, audit)
|
||||
}
|
||||
secondAudit, err := NewAuditSettings(second)
|
||||
if err != nil || !secondAudit.Enabled || secondAudit.Rules[0].ID != "second" || audit.Enabled {
|
||||
t.Fatalf("second audit = %#v, %v", secondAudit, err)
|
||||
}
|
||||
resource := configkit.Keys("component", "entries").Index(1).Key("resource")
|
||||
info, ok := first.Metadata().Lookup(resource)
|
||||
if !ok || len(info.Origin.Inheritance) == 0 || len(info.Origin.Locations) == 0 {
|
||||
t.Fatalf("inherited origin = %#v, %v", info, ok)
|
||||
}
|
||||
context, ok := first.SourceContext(info.Origin.Locations[0].SourceID)
|
||||
if !ok {
|
||||
t.Fatal("resource context unavailable")
|
||||
}
|
||||
data, err := fs.ReadFile(context.FS, path.Join(context.BaseDir, first.Config.Component.Entries[1].Resource))
|
||||
if err != nil || string(data) != "shared asset" {
|
||||
t.Fatalf("inherited resource = %q, %v", data, err)
|
||||
}
|
||||
_, err = LoadComposedApplication(configkit.Input{Source: configkit.Bytes("invalid.yml", []byte("label: app\naudit: {rules: [{id: same}, {id: same}]}\n"))}, component)
|
||||
if err == nil {
|
||||
t.Fatal("duplicate audit identities accepted")
|
||||
}
|
||||
badComponent := configkit.Input{Source: configkit.Bytes("bad-component.yml", []byte("name: good\nentries: [{id: duplicate}, {id: duplicate}]\n"))}
|
||||
_, err = LoadComposedApplication(configkit.Input{Source: configkit.Bytes("app.yml", []byte("label: app\naudit: {rules: [{id: valid}]}\n"))}, badComponent)
|
||||
if err == nil {
|
||||
t.Fatal("duplicate component identities accepted")
|
||||
}
|
||||
_, err = LoadComposedApplication(configkit.Input{Source: configkit.Bytes("invalid.yml", []byte("label: ' '\naudit: {rules: [{id: valid}]}\n"))}, component)
|
||||
if err == nil {
|
||||
t.Fatal("application validation did not run")
|
||||
}
|
||||
}
|
||||
96
facade_inspection_diff_test.go
Normal file
96
facade_inspection_diff_test.go
Normal file
@@ -0,0 +1,96 @@
|
||||
package configkit_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func TestInspectionViewDiff(t *testing.T) {
|
||||
type first struct {
|
||||
Component map[string]any `yaml:"component"`
|
||||
Sibling string `yaml:"sibling"`
|
||||
Items []string `yaml:"items"`
|
||||
}
|
||||
type second struct {
|
||||
Component map[string]any `yaml:"component"`
|
||||
Sibling string `yaml:"sibling"`
|
||||
Items []string `yaml:"items"`
|
||||
}
|
||||
left, err := configkit.Load[first](configkit.Bytes("left.yml", []byte("component: {name: before, gone: null}\nsibling: old\nitems: [a, b]\n")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
right, err := configkit.Load[second](configkit.Bytes("right.yml", []byte("component: {name: after, added: null}\nsibling: new\nitems: [a, c]\n")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lv, _ := left.InspectSubtree(configkit.Keys("component"))
|
||||
rv, _ := right.InspectSubtree(configkit.Keys("component"))
|
||||
diff, err := lv.Diff(rv)
|
||||
if err != nil || len(diff) != 3 || diff[0].Path.String() != "/component/added" || diff[1].Path.String() != "/component/gone" || diff[2].Path.String() != "/component/name" {
|
||||
t.Fatalf("component diff = %#v, %v", diff, err)
|
||||
}
|
||||
if diff[0].Left.Present || !diff[0].Right.Present || !diff[1].Left.Present || diff[1].Right.Present {
|
||||
t.Fatalf("null and absence = %#v", diff)
|
||||
}
|
||||
sequenceLeft, _ := left.InspectSubtree(configkit.Keys("items").Index(0))
|
||||
sequenceRight, _ := right.InspectSubtree(configkit.Keys("items", "0"))
|
||||
diff, err = sequenceLeft.Diff(sequenceRight)
|
||||
if err != nil || len(diff) != 1 || diff[0].Path.String() != "/items" {
|
||||
t.Fatalf("sequence ancestor = %#v, %v", diff, err)
|
||||
}
|
||||
missingLeft, _ := left.InspectSubtree(configkit.Keys("absent"))
|
||||
missingRight, _ := right.InspectSubtree(configkit.Keys("absent"))
|
||||
if diff, err = missingLeft.Diff(missingRight); err != nil || len(diff) != 0 {
|
||||
t.Fatalf("absent diff = %#v, %v", diff, err)
|
||||
}
|
||||
if diff, err = lv.Diff(missingRight); err == nil || diff != nil {
|
||||
t.Fatalf("mismatched diff = %#v, %v", diff, err)
|
||||
}
|
||||
if diff, err = (configkit.Inspection{}).Diff(lv); err == nil || diff != nil {
|
||||
t.Fatalf("zero diff = %#v, %v", diff, err)
|
||||
}
|
||||
rootLeft, _ := left.InspectSubtree(configkit.Path{})
|
||||
rootRight, _ := right.InspectSubtree(configkit.Path{})
|
||||
if diff, err = rootLeft.Diff(rootRight); err != nil || len(diff) != 5 {
|
||||
t.Fatalf("root diff = %#v, %v", diff, err)
|
||||
}
|
||||
if diff, err = lv.Diff(lv); err != nil || len(diff) != 0 {
|
||||
t.Fatalf("equal diff = %#v, %v", diff, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInspectionViewDiffRedactionAndShape(t *testing.T) {
|
||||
load := func(input string, sensitive bool) *configkit.Result[map[string]any] {
|
||||
t.Helper()
|
||||
result, err := configkit.Load(configkit.Bytes("view.yml", []byte(input)), configkit.Options[map[string]any]{Definition: configkit.Definition[map[string]any]{Sensitive: func(path configkit.Path) bool { return sensitive && path.String() == "/component" }}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
left := load("component: {token: disposable-canary-left}\n", true)
|
||||
right := load("component: {token: disposable-canary-right}\n", false)
|
||||
lv, _ := left.InspectSubtree(configkit.Keys("component", "token"))
|
||||
rv, _ := right.InspectSubtree(configkit.Keys("component", "token"))
|
||||
diff, err := lv.Diff(rv)
|
||||
if err != nil || len(diff) != 1 || !diff[0].Left.Redacted || !diff[0].Right.Redacted || !diff[0].HiddenChanged || strings.Contains(diff[0].Left.YAML+diff[0].Right.YAML, "disposable-canary") {
|
||||
t.Fatalf("sensitive diff = %#v, %v", diff, err)
|
||||
}
|
||||
removed := load("other: public\n", false)
|
||||
removedView, _ := removed.InspectSubtree(configkit.Keys("component", "token"))
|
||||
diff, err = lv.Diff(removedView)
|
||||
if err != nil || len(diff) != 1 || diff[0].Right.Present || !diff[0].Left.Redacted || strings.Contains(diff[0].Left.YAML, "disposable-canary") {
|
||||
t.Fatalf("sensitive removal = %#v, %v", diff, err)
|
||||
}
|
||||
left = load("component: {'0': old}\n", false)
|
||||
right = load("component: [new]\n", false)
|
||||
lv, _ = left.InspectSubtree(configkit.Keys("component", "0"))
|
||||
rv, _ = right.InspectSubtree(configkit.Keys("component").Index(0))
|
||||
diff, err = lv.Diff(rv)
|
||||
if err != nil || len(diff) != 1 || diff[0].Path.String() != "/component" {
|
||||
t.Fatalf("shape diff = %#v, %v", diff, err)
|
||||
}
|
||||
}
|
||||
134
facade_inspection_history_test.go
Normal file
134
facade_inspection_history_test.go
Normal file
@@ -0,0 +1,134 @@
|
||||
package configkit_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/fs"
|
||||
"path"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func TestInspectionViewHistoryAndResourceOwnership(t *testing.T) {
|
||||
filesystem := configkit.NewFilesystem("component", fstest.MapFS{
|
||||
"config/settings.yml": &fstest.MapFile{Data: []byte("entries:\n parent: {resource: asset.txt, removed: old}\n child: {extends: parent}\nsibling: retained\n")},
|
||||
"config/asset.txt": &fstest.MapFile{Data: []byte("asset contents")},
|
||||
})
|
||||
load := func() *configkit.Result[map[string]any] {
|
||||
t.Helper()
|
||||
result, err := configkit.LoadLayered(configkit.Input{Source: filesystem.File("config/settings.yml"), Destination: configkit.Keys("component")}, configkit.LayeredOptions[map[string]any]{Definition: configkit.Definition[map[string]any]{
|
||||
Resolve: func(current *map[string]any, resolution *configkit.Resolution) error {
|
||||
child := (*current)["component"].(map[string]any)["entries"].(map[string]any)["child"].(map[string]any)
|
||||
delete(child, "removed")
|
||||
resolution.RecordNormalization(configkit.Keys("component", "entries", "child", "removed"), "remove old setting")
|
||||
return nil
|
||||
},
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
result, other := load(), load()
|
||||
scope := configkit.Keys("component", "entries", "child")
|
||||
view, ok := result.InspectSubtree(scope)
|
||||
if !ok {
|
||||
t.Fatal("view unavailable")
|
||||
}
|
||||
removed := scope.Key("removed")
|
||||
resource := scope.Key("resource")
|
||||
paths := []string{}
|
||||
for _, p := range view.HistoricalPaths() {
|
||||
paths = append(paths, p.String())
|
||||
}
|
||||
if !strings.Contains(strings.Join(paths, ","), removed.String()) {
|
||||
t.Fatalf("removed history missing: %v", paths)
|
||||
}
|
||||
if _, ok := view.Metadata().Lookup(removed); ok {
|
||||
t.Fatal("removed value is effective")
|
||||
}
|
||||
explanation, ok := view.Explain(removed)
|
||||
if !ok || explanation.Effective.Present || len(explanation.History) == 0 {
|
||||
t.Fatalf("removed explanation = %#v, %v", explanation, ok)
|
||||
}
|
||||
if len(view.Metadata().History(removed)) == 0 {
|
||||
t.Fatal("removed history missing")
|
||||
}
|
||||
info, ok := view.Metadata().Lookup(resource)
|
||||
if !ok || len(info.Origin.Locations) == 0 || len(info.Origin.Inheritance) == 0 {
|
||||
t.Fatalf("inherited origin = %#v, %v", info, ok)
|
||||
}
|
||||
id := info.Origin.Locations[0].SourceID
|
||||
context, ok := view.SourceContext(id)
|
||||
if !ok {
|
||||
t.Fatal("source context missing")
|
||||
}
|
||||
data, err := fs.ReadFile(context.FS, path.Join(context.BaseDir, "asset.txt"))
|
||||
if err != nil || string(data) != "asset contents" {
|
||||
t.Fatalf("resource = %q, %v", data, err)
|
||||
}
|
||||
if _, ok := view.Source(id); !ok {
|
||||
t.Fatal("source containing sibling missing")
|
||||
}
|
||||
before := bytes.Buffer{}
|
||||
if err := view.WriteEffective(&before); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
otherView, _ := other.InspectSubtree(scope)
|
||||
child := result.Config["component"].(map[string]any)["entries"].(map[string]any)["child"].(map[string]any)
|
||||
child["resource"] = "changed"
|
||||
if value, _ := result.Value(resource); value != "changed" {
|
||||
t.Fatalf("current value = %v", value)
|
||||
}
|
||||
after := bytes.Buffer{}
|
||||
if err := view.WriteEffective(&after); err != nil || !bytes.Equal(before.Bytes(), after.Bytes()) {
|
||||
t.Fatalf("view changed = %q, %v", after.String(), err)
|
||||
}
|
||||
if diff, err := view.Diff(otherView); err != nil || len(diff) != 0 {
|
||||
t.Fatalf("frozen diff = %#v, %v", diff, err)
|
||||
}
|
||||
info.Origin.Locations[0].SourceID = "changed"
|
||||
again, _ := view.Metadata().Lookup(resource)
|
||||
if again.Origin.Locations[0].SourceID != id {
|
||||
t.Fatal("metadata was not detached")
|
||||
}
|
||||
explanation.Effective.YAML = "changed"
|
||||
againExplanation, _ := view.Explain(removed)
|
||||
if reflect.DeepEqual(explanation, againExplanation) {
|
||||
t.Fatal("explanation was not detached")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInspectionViewHistoricalNumericScope(t *testing.T) {
|
||||
result, err := configkit.Load(configkit.Bytes("shape.yml", []byte("component: {'0': {old: value}}\n")), configkit.Options[map[string]any]{Definition: configkit.Definition[map[string]any]{
|
||||
Resolve: func(current *map[string]any, resolution *configkit.Resolution) error {
|
||||
(*current)["component"] = []any{map[string]any{"new": "value"}}
|
||||
resolution.RecordNormalization(configkit.Keys("component"), "change shape")
|
||||
return nil
|
||||
},
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key, _ := result.InspectSubtree(configkit.Keys("component", "0"))
|
||||
index, _ := result.InspectSubtree(configkit.Keys("component").Index(0))
|
||||
if !reflect.DeepEqual(key.HistoricalPaths(), index.HistoricalPaths()) {
|
||||
t.Fatal("numeric reporting scopes differ")
|
||||
}
|
||||
var paths []string
|
||||
for _, p := range key.HistoricalPaths() {
|
||||
paths = append(paths, p.String())
|
||||
}
|
||||
if !strings.Contains(strings.Join(paths, ","), "/component/0/old") || !strings.Contains(strings.Join(paths, ","), "/component/0/new") {
|
||||
t.Fatalf("shape history = %v", paths)
|
||||
}
|
||||
if _, ok := key.Metadata().Lookup(configkit.Keys("component", "0", "new")); ok {
|
||||
t.Fatal("explicit key query changed intent")
|
||||
}
|
||||
if _, ok := key.Metadata().Lookup(configkit.Keys("component").Index(0).Key("new")); !ok {
|
||||
t.Fatal("index query failed")
|
||||
}
|
||||
}
|
||||
153
facade_inspection_view_test.go
Normal file
153
facade_inspection_view_test.go
Normal file
@@ -0,0 +1,153 @@
|
||||
package configkit_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func TestInspectionViewScopeAndQueries(t *testing.T) {
|
||||
result, err := configkit.Load[map[string]any](configkit.Bytes("view.yml", []byte("a: {child: one}\nab: two\nitems: [{name: first}]\n'a/b': {'': value}\n")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
view, ok := result.InspectSubtree(configkit.Keys("a"))
|
||||
if !ok {
|
||||
t.Fatal("view unavailable")
|
||||
}
|
||||
var paths []string
|
||||
for _, path := range view.HistoricalPaths() {
|
||||
paths = append(paths, path.String())
|
||||
}
|
||||
if !reflect.DeepEqual(paths, []string{"/a", "/a/child"}) {
|
||||
t.Fatalf("scope paths = %#v", paths)
|
||||
}
|
||||
if _, ok := view.Metadata().Lookup(configkit.Keys("ab")); !ok {
|
||||
t.Fatal("metadata filtered")
|
||||
}
|
||||
if _, ok := view.Explain(configkit.Keys("ab")); !ok {
|
||||
t.Fatal("native query filtered")
|
||||
}
|
||||
var output bytes.Buffer
|
||||
if err := view.WriteExplanation(&output, configkit.Keys("ab")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(view.Sources()) != len(result.Sources()) || len(view.Sources()) == 0 {
|
||||
t.Fatal("sources filtered")
|
||||
}
|
||||
if _, ok := view.Source(view.Sources()[0].ID); !ok {
|
||||
t.Fatal("source unavailable")
|
||||
}
|
||||
if _, ok := result.InspectSubtree(configkit.Keys("absent")); !ok {
|
||||
t.Fatal("absent scope rejected")
|
||||
}
|
||||
if _, ok := result.InspectSubtree(configkit.Path{}.Index(-1)); ok {
|
||||
t.Fatal("invalid scope accepted")
|
||||
}
|
||||
keyScope, _ := result.InspectSubtree(configkit.Keys("items", "0"))
|
||||
indexScope, _ := result.InspectSubtree(configkit.Keys("items").Index(0))
|
||||
if !reflect.DeepEqual(keyScope.HistoricalPaths(), indexScope.HistoricalPaths()) {
|
||||
t.Fatal("numeric scope differs")
|
||||
}
|
||||
escaped, _ := result.InspectSubtree(configkit.Keys("a/b", ""))
|
||||
if got := escaped.HistoricalPaths(); len(got) != 1 || got[0].String() != "/a~1b/" {
|
||||
t.Fatalf("escaped scope = %#v", got)
|
||||
}
|
||||
root, _ := result.InspectSubtree(configkit.Path{})
|
||||
if !reflect.DeepEqual(root.HistoricalPaths(), result.Metadata().HistoricalPaths()) {
|
||||
t.Fatal("root scope filtered")
|
||||
}
|
||||
}
|
||||
|
||||
type viewFailWriter struct{}
|
||||
|
||||
func (viewFailWriter) Write([]byte) (int, error) { return 0, errors.New("write failed") }
|
||||
|
||||
func TestInspectionViewWriteEffective(t *testing.T) {
|
||||
options := configkit.Options[map[string]any]{Definition: configkit.Definition[map[string]any]{
|
||||
Sensitive: func(path configkit.Path) bool { return path.String() == "/private" || path.String() == "/nested/token" },
|
||||
Resolve: func(current *map[string]any, resolution *configkit.Resolution) error {
|
||||
delete(*current, "removed")
|
||||
resolution.RecordNormalization(configkit.Keys("removed"), "remove")
|
||||
return nil
|
||||
},
|
||||
}}
|
||||
result, err := configkit.Load(configkit.Bytes("view.yml", []byte("private: {child: canary-private}\nnested: {token: canary-token, name: public}\nitems: [zero, one]\n'0': numeric\n'null': null\nremoved: earlier\n")), options)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
path configkit.Path
|
||||
contains string
|
||||
absent string
|
||||
fails bool
|
||||
}{
|
||||
{configkit.Path{}, "public", "canary-token", false},
|
||||
{configkit.Keys("nested"), "public", "canary-token", false},
|
||||
{configkit.Keys("private", "child"), "REDACTED", "canary-private", false},
|
||||
{configkit.Keys("items"), "one", "", false},
|
||||
{configkit.Keys("items").Index(1), "one", "", false},
|
||||
{configkit.Path{}.Index(0), "numeric", "", false},
|
||||
{configkit.Keys("null"), "null", "", false},
|
||||
{configkit.Keys("removed"), "", "", true},
|
||||
{configkit.Keys("missing"), "", "", true},
|
||||
} {
|
||||
view, ok := result.InspectSubtree(tc.path)
|
||||
if !ok {
|
||||
t.Fatal("view unavailable")
|
||||
}
|
||||
var out bytes.Buffer
|
||||
err := view.WriteEffective(&out)
|
||||
if (err != nil) != tc.fails || (tc.fails && out.Len() != 0) || (tc.contains != "" && !strings.Contains(out.String(), tc.contains)) || (tc.absent != "" && strings.Contains(out.String(), tc.absent)) {
|
||||
t.Errorf("%s: %q, %v", tc.path.String(), out.String(), err)
|
||||
}
|
||||
}
|
||||
view, _ := result.InspectSubtree(configkit.Keys("nested"))
|
||||
result.Config["nested"] = "changed"
|
||||
var out bytes.Buffer
|
||||
if err := view.WriteEffective(&out); err != nil || !strings.Contains(out.String(), "public") {
|
||||
t.Fatalf("frozen output = %q, %v", out.String(), err)
|
||||
}
|
||||
if err := view.WriteEffective(viewFailWriter{}); err == nil {
|
||||
t.Fatal("writer error lost")
|
||||
}
|
||||
if err := view.WriteEffective(nil); err == nil {
|
||||
t.Fatal("nil writer accepted")
|
||||
}
|
||||
if err := (configkit.Inspection{}).WriteEffective(&bytes.Buffer{}); err == nil {
|
||||
t.Fatal("zero view accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInspectionViewUnavailable(t *testing.T) {
|
||||
var result *configkit.Result[map[string]any]
|
||||
if _, ok := result.InspectSubtree(configkit.Path{}); ok {
|
||||
t.Fatal("nil result accepted")
|
||||
}
|
||||
if _, ok := (&configkit.Result[map[string]any]{}).InspectSubtree(configkit.Path{}); ok {
|
||||
t.Fatal("manual result accepted")
|
||||
}
|
||||
var view configkit.Inspection
|
||||
if len(view.HistoricalPaths()) != 0 || view.Sources() != nil {
|
||||
t.Fatal("zero view returned records")
|
||||
}
|
||||
if _, ok := view.Metadata().Lookup(configkit.Path{}); ok {
|
||||
t.Fatal("zero metadata")
|
||||
}
|
||||
if _, ok := view.Source("source-1"); ok {
|
||||
t.Fatal("zero source")
|
||||
}
|
||||
if _, ok := view.SourceContext("source-1"); ok {
|
||||
t.Fatal("zero source context")
|
||||
}
|
||||
if _, ok := view.Explain(configkit.Path{}); ok {
|
||||
t.Fatal("zero explanation")
|
||||
}
|
||||
if err := view.WriteExplanation(&bytes.Buffer{}, configkit.Path{}); err == nil {
|
||||
t.Fatal("zero explanation rendering")
|
||||
}
|
||||
}
|
||||
187
facade_result_value_test.go
Normal file
187
facade_result_value_test.go
Normal file
@@ -0,0 +1,187 @@
|
||||
package configkit_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
type valueName string
|
||||
type valueKey string
|
||||
type valueEmbedded struct{ Label valueName }
|
||||
type valueCodec struct{ Text string }
|
||||
|
||||
func (valueCodec) MarshalText() ([]byte, error) { panic("codec called during lookup") }
|
||||
func (*valueCodec) UnmarshalText([]byte) error { panic("codec called during lookup") }
|
||||
|
||||
type valueConfig struct {
|
||||
Embedded *valueEmbedded `yaml:",inline"`
|
||||
Extra map[valueKey]any `yaml:",inline"`
|
||||
List []string `yaml:"list"`
|
||||
Array [2]int `yaml:"array"`
|
||||
Dynamic any `yaml:"dynamic"`
|
||||
Codec valueCodec `yaml:"codec"`
|
||||
Pointer *valueEmbedded `yaml:"pointer"`
|
||||
Nil *valueEmbedded `yaml:"nil"`
|
||||
Ignored string `yaml:"-"`
|
||||
private string
|
||||
}
|
||||
|
||||
func TestResultValueCurrentNavigation(t *testing.T) {
|
||||
var missing *configkit.Result[valueConfig]
|
||||
if _, ok := missing.Value(configkit.Path{}); ok {
|
||||
t.Fatal("nil result")
|
||||
}
|
||||
var nilMap map[string]int
|
||||
result := &configkit.Result[valueConfig]{Config: valueConfig{
|
||||
Embedded: &valueEmbedded{Label: "named"}, Extra: map[valueKey]any{"a/b": nil, "": nilMap, "0": 7},
|
||||
List: []string{"first"}, Array: [2]int{1, 2}, Dynamic: map[string]any{"list": []any{valueEmbedded{Label: "dynamic"}}}, Pointer: &valueEmbedded{Label: "pointer"},
|
||||
}}
|
||||
parsed, _ := configkit.ParsePath("/dynamic/list/0/label")
|
||||
parsedKey, _ := configkit.ParsePath("/0")
|
||||
if got, ok := result.Value(configkit.Path{}); !ok || !reflect.DeepEqual(got, result.Config) {
|
||||
t.Fatalf("root = %#v, %v", got, ok)
|
||||
}
|
||||
pointer, ok := result.Value(configkit.Keys("dynamic", "list").Index(0))
|
||||
if !ok || pointer.(valueEmbedded).Label != "dynamic" {
|
||||
t.Fatalf("struct terminal = %#v, %v", pointer, ok)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
path configkit.Path
|
||||
want any
|
||||
ok bool
|
||||
}{
|
||||
{configkit.Keys("label"), valueName("named"), true},
|
||||
{configkit.Keys("a/b"), nil, true}, {configkit.Keys(""), nilMap, true},
|
||||
{parsedKey, 7, true}, {configkit.Path{}.Index(0), nil, false},
|
||||
{configkit.Keys("list").Index(0), "first", true}, {configkit.Keys("list", "0"), nil, false},
|
||||
{configkit.Keys("list").Index(1), nil, false}, {configkit.Keys("list").Index(-1), nil, false},
|
||||
{parsed, valueName("dynamic"), true}, {configkit.Keys("ignored"), nil, false}, {configkit.Keys("private"), nil, false},
|
||||
{configkit.Keys("codec"), valueCodec{}, true}, {configkit.Keys("codec", "text"), nil, false},
|
||||
{configkit.Keys("nil"), (*valueEmbedded)(nil), true}, {configkit.Keys("nil", "label"), nil, false},
|
||||
{configkit.Keys("pointer", "label"), valueName("pointer"), true},
|
||||
} {
|
||||
got, ok := result.Value(tc.path)
|
||||
if ok != tc.ok || !reflect.DeepEqual(got, tc.want) {
|
||||
t.Errorf("%s: got %#v, %v; want %#v, %v", tc.path.String(), got, ok, tc.want, tc.ok)
|
||||
}
|
||||
}
|
||||
copyValue, _ := result.Value(configkit.Keys("array"))
|
||||
array := copyValue.([2]int)
|
||||
array[0] = 9
|
||||
listValue, _ := result.Value(configkit.Keys("list"))
|
||||
listValue.([]string)[0] = "changed"
|
||||
mapValue, _ := result.Value(configkit.Keys("dynamic"))
|
||||
mapValue.(map[string]any)["added"] = true
|
||||
pointerValue, _ := result.Value(configkit.Keys("pointer"))
|
||||
pointerValue.(*valueEmbedded).Label = "changed"
|
||||
if result.Config.Array[0] != 1 || result.Config.List[0] != "changed" {
|
||||
t.Fatal("assignment ownership differs")
|
||||
}
|
||||
if result.Config.Dynamic.(map[string]any)["added"] != true {
|
||||
t.Fatal("map assignment did not preserve alias")
|
||||
}
|
||||
if result.Config.Pointer.Label != "changed" {
|
||||
t.Fatal("pointer assignment did not preserve alias")
|
||||
}
|
||||
result.Config.Embedded = nil
|
||||
if _, ok := result.Value(configkit.Keys("label")); ok {
|
||||
t.Fatal("nil inline pointer")
|
||||
}
|
||||
result.Config.Dynamic = make(chan int)
|
||||
if _, ok := result.Value(configkit.Keys("dynamic")); !ok {
|
||||
t.Fatal("unsupported terminal unavailable")
|
||||
}
|
||||
if _, ok := result.Value(configkit.Keys("dynamic", "x")); ok {
|
||||
t.Fatal("unsupported value traversed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResultValueFrozenInspectionAndSecret(t *testing.T) {
|
||||
t.Setenv("CONFIGKIT_VALUE_TEST_SECRET", "disposable-value-canary")
|
||||
type settings struct {
|
||||
Name string `yaml:"name"`
|
||||
Count int `yaml:"count"`
|
||||
Token configkit.Secret `yaml:"token"`
|
||||
}
|
||||
result, err := configkit.Load[settings](configkit.Bytes("settings.yml", []byte("name: before\ntoken: CONFIGKIT_VALUE_TEST_SECRET\n")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, ok := result.Value(configkit.Keys("count")); !ok || got != 0 || result.Metadata().IsExplicit(configkit.Keys("count")) {
|
||||
t.Fatalf("default = %#v, %v", got, ok)
|
||||
}
|
||||
secret, ok := result.Value(configkit.Keys("token"))
|
||||
if !ok || secret.(configkit.Secret).Value() != "disposable-value-canary" {
|
||||
t.Fatal("resolved secret unavailable")
|
||||
}
|
||||
result.Config.Name = "after"
|
||||
if got, _ := result.Value(configkit.Keys("name")); got != "after" {
|
||||
t.Fatalf("current value = %v", got)
|
||||
}
|
||||
var output bytes.Buffer
|
||||
if err := result.WriteEffective(&output); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(output.String(), "before") || strings.Contains(output.String(), "after") || strings.Contains(output.String(), "disposable-value-canary") {
|
||||
t.Fatalf("frozen output = %s", output.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestResultValueReturnsTerminalsWithoutSchemaValidation(t *testing.T) {
|
||||
type terminal struct {
|
||||
A int `yaml:"same"`
|
||||
B int `yaml:"same"`
|
||||
}
|
||||
want := terminal{A: 1, B: 2}
|
||||
cases := []struct {
|
||||
name string
|
||||
lookup func(configkit.Path) (any, bool)
|
||||
path configkit.Path
|
||||
}{
|
||||
{"map", (&configkit.Result[map[string]terminal]{Config: map[string]terminal{"item": want}}).Value, configkit.Keys("item")},
|
||||
{"slice", (&configkit.Result[[]terminal]{Config: []terminal{want}}).Value, configkit.Path{}.Index(0)},
|
||||
{"array", (&configkit.Result[[1]terminal]{Config: [1]terminal{want}}).Value, configkit.Path{}.Index(0)},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got, ok := tc.lookup(tc.path)
|
||||
if !ok || got != want {
|
||||
t.Fatalf("terminal = %#v, %v", got, ok)
|
||||
}
|
||||
if _, ok := tc.lookup(tc.path.Key("same")); ok {
|
||||
t.Fatal("ambiguous containing bindings accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
// A post-load replacement need not itself satisfy the load-time schema.
|
||||
result, err := configkit.Load[map[string]any](configkit.Bytes("dynamic.yml", []byte("{}")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result.Config["dynamic"] = struct {
|
||||
Child terminal `yaml:"child"`
|
||||
Good int `yaml:"good"`
|
||||
}{Child: want, Good: 3}
|
||||
for _, tc := range []struct {
|
||||
path configkit.Path
|
||||
want any
|
||||
}{
|
||||
{configkit.Keys("dynamic", "child"), want},
|
||||
{configkit.Keys("dynamic", "good"), 3},
|
||||
} {
|
||||
got, ok := result.Value(tc.path)
|
||||
if !ok || got != tc.want {
|
||||
t.Fatalf("%s = %#v, %v", tc.path.String(), got, ok)
|
||||
}
|
||||
}
|
||||
if _, ok := result.Value(configkit.Keys("dynamic", "child", "same")); ok {
|
||||
t.Fatal("ambiguous dynamic child accepted navigation")
|
||||
}
|
||||
if _, err := configkit.Load[map[string]terminal](configkit.NoSource()); err == nil {
|
||||
t.Fatal("Load accepted an invalid element schema")
|
||||
}
|
||||
}
|
||||
88
inspection_view.go
Normal file
88
inspection_view.go
Normal file
@@ -0,0 +1,88 @@
|
||||
package configkit
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
"go.maximumdirect.net/configkit/internal/engine"
|
||||
)
|
||||
|
||||
// Inspection is a reporting view of a completed load. Its scope filters
|
||||
// enumeration; explicit queries and source records retain their native paths.
|
||||
type Inspection struct{ view engine.InspectionView }
|
||||
|
||||
// InspectSubtree selects a canonical JSON Pointer reporting location, including
|
||||
// an absent location. Equivalent key and index spellings select the same scope.
|
||||
// Nil, manually constructed results and invalid paths cannot produce a view.
|
||||
func (r *Result[T]) InspectSubtree(path Path) (Inspection, bool) {
|
||||
if r == nil {
|
||||
return Inspection{}, false
|
||||
}
|
||||
view, ok := engine.NewInspectionView(r.inspection, toEnginePath(path))
|
||||
return Inspection{view: view}, ok
|
||||
}
|
||||
|
||||
// Metadata returns the unfiltered metadata of the completed load.
|
||||
func (i Inspection) Metadata() Metadata { return Metadata{value: i.view.Inspection().Metadata()} }
|
||||
|
||||
// HistoricalPaths returns observed paths at or beneath the reporting scope.
|
||||
func (i Inspection) HistoricalPaths() []Path {
|
||||
values := i.view.HistoricalPaths()
|
||||
paths := make([]Path, len(values))
|
||||
for index := range values {
|
||||
paths[index] = fromEnginePath(values[index])
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
// WriteEffective renders the saved value at the reporting scope with its
|
||||
// original sensitivity. Unavailable values and nil writers return an error;
|
||||
// writer errors can leave partial output.
|
||||
func (i Inspection) WriteEffective(output io.Writer) error { return i.view.WriteEffective(output) }
|
||||
|
||||
// Diff compares frozen views at the same canonical scope, including differences
|
||||
// at an ancestor when the existing comparison treats that ancestor atomically.
|
||||
// Views may come from different root Go types. Unavailable or mismatched views
|
||||
// return an error without records.
|
||||
func (i Inspection) Diff(other Inspection) ([]Difference, error) {
|
||||
values, err := i.view.Diff(other.view)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return fromEngineDifferences(values), nil
|
||||
}
|
||||
|
||||
// Sources returns the full detached source catalog.
|
||||
func (i Inspection) Sources() []SourceInfo {
|
||||
values := i.view.Inspection().Sources()
|
||||
if values == nil {
|
||||
return nil
|
||||
}
|
||||
result := make([]SourceInfo, len(values))
|
||||
for index := range values {
|
||||
result[index] = fromEngineSourceInfo(values[index])
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// Source returns a detached record from the full source catalog.
|
||||
func (i Inspection) Source(id string) (SourceInfo, bool) {
|
||||
value, ok := i.view.Inspection().Source(id)
|
||||
return fromEngineSourceInfo(value), ok
|
||||
}
|
||||
|
||||
// SourceContext returns the borrowed resource context for an acquired source.
|
||||
func (i Inspection) SourceContext(id string) (ResourceContext, bool) {
|
||||
value, ok := i.view.Inspection().SourceContext(id)
|
||||
return ResourceContext{FS: value.FS, BaseDir: value.BaseDir}, ok
|
||||
}
|
||||
|
||||
// Explain queries a native path, whether or not it lies within the scope.
|
||||
func (i Inspection) Explain(path Path) (Explanation, bool) {
|
||||
value, ok := i.view.Inspection().Explain(toEnginePath(path))
|
||||
return fromEngineExplanation(value), ok
|
||||
}
|
||||
|
||||
// WriteExplanation renders an explicit native path using the frozen load.
|
||||
func (i Inspection) WriteExplanation(output io.Writer, path Path) error {
|
||||
return i.view.Inspection().WriteExplanation(output, toEnginePath(path))
|
||||
}
|
||||
68
internal/engine/inspection_view.go
Normal file
68
internal/engine/inspection_view.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
|
||||
yamladapter "go.maximumdirect.net/configkit/internal/yaml"
|
||||
)
|
||||
|
||||
// InspectionView borrows an inspection and selects a canonical reporting scope.
|
||||
type InspectionView struct {
|
||||
inspection *Inspection
|
||||
scope Path
|
||||
}
|
||||
|
||||
func NewInspectionView(inspection *Inspection, scope Path) (InspectionView, bool) {
|
||||
if inspection == nil || !scope.valid() {
|
||||
return InspectionView{}, false
|
||||
}
|
||||
normalized, err := ParsePath(scope.String())
|
||||
if err != nil {
|
||||
return InspectionView{}, false
|
||||
}
|
||||
return InspectionView{inspection: inspection, scope: normalized}, true
|
||||
}
|
||||
|
||||
func (v InspectionView) Inspection() *Inspection { return v.inspection }
|
||||
|
||||
func (v InspectionView) Diff(other InspectionView) ([]Difference, error) {
|
||||
if v.inspection == nil || other.inspection == nil || v.scope.String() != other.scope.String() {
|
||||
return nil, errors.New("configkit: diff inspection scope unavailable or mismatched")
|
||||
}
|
||||
values, err := Diff(v.inspection, other.inspection)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var result []Difference
|
||||
for _, value := range values {
|
||||
if pathContains(v.scope, value.Path) || pathContains(value.Path, v.scope) {
|
||||
result = append(result, value)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (v InspectionView) WriteEffective(output io.Writer) error {
|
||||
if v.inspection == nil || v.inspection.final == nil || output == nil {
|
||||
return errEffectiveUnavailable
|
||||
}
|
||||
node, ok := documentAtPathWithLookup(v.inspection.final, v.scope, v.inspection.documentLookup())
|
||||
if !ok {
|
||||
return errEffectiveUnavailable
|
||||
}
|
||||
return yamladapter.Write(output, redactedDocument(node, v.inspection.secrets, v.scope))
|
||||
}
|
||||
|
||||
func (v InspectionView) HistoricalPaths() []Path {
|
||||
if v.inspection == nil {
|
||||
return nil
|
||||
}
|
||||
var paths []Path
|
||||
for _, path := range v.inspection.metadata.HistoricalPaths() {
|
||||
if pathContains(v.scope, path) {
|
||||
paths = append(paths, path)
|
||||
}
|
||||
}
|
||||
return paths
|
||||
}
|
||||
99
internal/engine/result_value.go
Normal file
99
internal/engine/result_value.go
Normal file
@@ -0,0 +1,99 @@
|
||||
package engine
|
||||
|
||||
import "reflect"
|
||||
|
||||
// ResultValue navigates the current Go value without projecting or copying it.
|
||||
func ResultValue(root any, path Path, secrets SecretBinding) (any, bool) {
|
||||
if !path.valid() {
|
||||
return nil, false
|
||||
}
|
||||
current := reflect.ValueOf(root)
|
||||
if len(path.segments) == 0 {
|
||||
return root, true
|
||||
}
|
||||
builder := schemaBuilder{cache: make(map[reflect.Type]*typeDescriptor), building: make(map[reflect.Type]bool), secrets: secrets, lookup: true}
|
||||
for _, segment := range path.segments {
|
||||
seen := make(map[valueVisit]bool)
|
||||
for current.IsValid() && (current.Kind() == reflect.Pointer || current.Kind() == reflect.Interface) {
|
||||
if current.IsNil() {
|
||||
return nil, false
|
||||
}
|
||||
if current.Kind() == reflect.Pointer {
|
||||
visit := valueVisit{typeOf: current.Type(), kind: current.Kind(), ptr: current.Pointer()}
|
||||
if seen[visit] {
|
||||
return nil, false
|
||||
}
|
||||
seen[visit] = true
|
||||
}
|
||||
current = current.Elem()
|
||||
}
|
||||
if !current.IsValid() {
|
||||
return nil, false
|
||||
}
|
||||
descriptor, issue := builder.describe(current.Type(), Path{})
|
||||
if issue != nil {
|
||||
return nil, false
|
||||
}
|
||||
switch descriptor.kind {
|
||||
case descriptorStruct:
|
||||
if segment.kind == pathSegmentIndex {
|
||||
return nil, false
|
||||
}
|
||||
if position, ok := descriptor.fieldByName[segment.key]; ok {
|
||||
current = resultField(current, descriptor.fields[position].index)
|
||||
} else if descriptor.inlineMap != nil {
|
||||
current = resultMapEntry(resultField(current, descriptor.inlineMap.index), segment.key)
|
||||
} else {
|
||||
return nil, false
|
||||
}
|
||||
case descriptorMap:
|
||||
if segment.kind == pathSegmentIndex {
|
||||
return nil, false
|
||||
}
|
||||
current = resultMapEntry(current, segment.key)
|
||||
case descriptorSlice, descriptorArray:
|
||||
index, ok := schemaIndex(segment)
|
||||
if !ok || index >= current.Len() {
|
||||
return nil, false
|
||||
}
|
||||
current = current.Index(index)
|
||||
default:
|
||||
return nil, false
|
||||
}
|
||||
if !current.IsValid() {
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
if !current.CanInterface() {
|
||||
return nil, false
|
||||
}
|
||||
return current.Interface(), true
|
||||
}
|
||||
|
||||
func resultField(root reflect.Value, index []int) reflect.Value {
|
||||
current := root
|
||||
for position, field := range index {
|
||||
if current.Kind() != reflect.Struct {
|
||||
return reflect.Value{}
|
||||
}
|
||||
current = current.Field(field)
|
||||
if position < len(index)-1 {
|
||||
for current.Kind() == reflect.Pointer {
|
||||
if current.IsNil() {
|
||||
return reflect.Value{}
|
||||
}
|
||||
current = current.Elem()
|
||||
}
|
||||
}
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
func resultMapEntry(value reflect.Value, name string) reflect.Value {
|
||||
if !value.IsValid() || value.Kind() != reflect.Map {
|
||||
return reflect.Value{}
|
||||
}
|
||||
key := reflect.New(value.Type().Key()).Elem()
|
||||
key.SetString(name)
|
||||
return value.MapIndex(key)
|
||||
}
|
||||
67
internal/engine/result_value_test.go
Normal file
67
internal/engine/result_value_test.go
Normal file
@@ -0,0 +1,67 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestResultValueNavigation(t *testing.T) {
|
||||
type key string
|
||||
type embedded struct{ Name string }
|
||||
type root struct {
|
||||
Embedded *embedded `yaml:",inline"`
|
||||
Extra map[key]any `yaml:",inline"`
|
||||
List []int `yaml:"list"`
|
||||
Any any `yaml:"any"`
|
||||
}
|
||||
value := root{Embedded: &embedded{Name: "named"}, Extra: map[key]any{"a/b": nil}, List: []int{3}, Any: map[string]any{"n": []any{"ok"}}}
|
||||
parsed, _ := ParsePath("/any/n/0")
|
||||
for _, tc := range []struct {
|
||||
path Path
|
||||
want any
|
||||
ok bool
|
||||
}{
|
||||
{Keys("name"), "named", true},
|
||||
{Keys("a/b"), nil, true},
|
||||
{Keys("missing"), nil, false},
|
||||
{Keys("list").Index(0), 3, true},
|
||||
{Keys("list").Key("0"), nil, false},
|
||||
{parsed, "ok", true},
|
||||
{Keys("list").Index(2), nil, false},
|
||||
{Path{}.Index(-1), nil, false},
|
||||
} {
|
||||
got, ok := ResultValue(value, tc.path, SecretBinding{})
|
||||
if ok != tc.ok || !reflect.DeepEqual(got, tc.want) {
|
||||
t.Errorf("%s: got %#v, %v; want %#v, %v", tc.path.String(), got, ok, tc.want, tc.ok)
|
||||
}
|
||||
}
|
||||
value.Embedded = nil
|
||||
if _, ok := ResultValue(value, Keys("name"), SecretBinding{}); ok {
|
||||
t.Fatal("nil inline pointer was traversed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResultValueTerminalAndPointerCycle(t *testing.T) {
|
||||
type pointer *pointer
|
||||
var cycle pointer
|
||||
cycle = &cycle
|
||||
var nilSlice []string
|
||||
for _, value := range []any{nil, nilSlice, make(chan int), cycle} {
|
||||
got, ok := ResultValue(value, Path{}, SecretBinding{})
|
||||
if !ok || reflect.TypeOf(got) != reflect.TypeOf(value) {
|
||||
t.Fatalf("terminal %#v: got %#v, %v", value, got, ok)
|
||||
}
|
||||
}
|
||||
if _, ok := ResultValue(cycle, Keys("x"), SecretBinding{}); ok {
|
||||
t.Fatal("pointer cycle was traversed")
|
||||
}
|
||||
channel := make(chan int)
|
||||
value := struct{ Channel chan int }{Channel: channel}
|
||||
got, ok := ResultValue(value, Keys("channel"), SecretBinding{})
|
||||
if !ok || got != channel {
|
||||
t.Fatalf("unsupported terminal: got %#v, %v", got, ok)
|
||||
}
|
||||
if _, ok := ResultValue(value, Keys("channel", "x"), SecretBinding{}); ok {
|
||||
t.Fatal("unsupported terminal accepted navigation")
|
||||
}
|
||||
}
|
||||
@@ -115,6 +115,9 @@ type schemaBuilder struct {
|
||||
building map[reflect.Type]bool
|
||||
journal []reflect.Type
|
||||
secrets SecretBinding
|
||||
// lookup describes only the current container and its flattened inline fields.
|
||||
// Ordinary descendants are described only when navigation continues into them.
|
||||
lookup bool
|
||||
}
|
||||
|
||||
func (b *schemaBuilder) describe(current reflect.Type, path Path) (*typeDescriptor, *schemaIssue) {
|
||||
@@ -134,6 +137,9 @@ func (b *schemaBuilder) describe(current reflect.Type, path Path) (*typeDescript
|
||||
|
||||
if current.Kind() == reflect.Pointer {
|
||||
descriptor.kind = descriptorPointer
|
||||
if b.lookup {
|
||||
return descriptor, nil
|
||||
}
|
||||
element, issue := b.describe(current.Elem(), path)
|
||||
if issue != nil {
|
||||
return nil, issue
|
||||
@@ -171,6 +177,9 @@ func (b *schemaBuilder) describe(current reflect.Type, path Path) (*typeDescript
|
||||
return fail(CodeSchemaUnsupportedType, "configuration maps must have string keys")
|
||||
}
|
||||
descriptor.kind = descriptorMap
|
||||
if b.lookup {
|
||||
return descriptor, nil
|
||||
}
|
||||
element, issue := b.describe(current.Elem(), path)
|
||||
if issue != nil {
|
||||
return nil, issue
|
||||
@@ -178,6 +187,9 @@ func (b *schemaBuilder) describe(current reflect.Type, path Path) (*typeDescript
|
||||
descriptor.element = element
|
||||
case reflect.Slice:
|
||||
descriptor.kind = descriptorSlice
|
||||
if b.lookup {
|
||||
return descriptor, nil
|
||||
}
|
||||
element, issue := b.describe(current.Elem(), path.Index(0))
|
||||
if issue != nil {
|
||||
return nil, issue
|
||||
@@ -186,6 +198,9 @@ func (b *schemaBuilder) describe(current reflect.Type, path Path) (*typeDescript
|
||||
case reflect.Array:
|
||||
descriptor.kind = descriptorArray
|
||||
descriptor.length = current.Len()
|
||||
if b.lookup {
|
||||
return descriptor, nil
|
||||
}
|
||||
element, issue := b.describe(current.Elem(), path.Index(0))
|
||||
if issue != nil {
|
||||
return nil, issue
|
||||
|
||||
@@ -4,10 +4,14 @@ import "reflect"
|
||||
|
||||
func (b *schemaBuilder) describeOrdinaryField(owner *typeDescriptor, field reflect.StructField, index int, name string, secret bool, path Path) *schemaIssue {
|
||||
fieldPath := path.Key(name)
|
||||
fieldType, issue := b.describe(field.Type, fieldPath)
|
||||
var fieldType *typeDescriptor
|
||||
if !b.lookup {
|
||||
var issue *schemaIssue
|
||||
fieldType, issue = b.describe(field.Type, fieldPath)
|
||||
if issue != nil {
|
||||
return issue
|
||||
}
|
||||
}
|
||||
if issue := addField(owner, fieldDescriptor{name: name, index: []int{index}, descriptor: fieldType, secret: secret}, path); issue != nil {
|
||||
return issue
|
||||
}
|
||||
|
||||
31
result_value.go
Normal file
31
result_value.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package configkit
|
||||
|
||||
import "go.maximumdirect.net/configkit/internal/engine"
|
||||
|
||||
// Value returns the current Config value at path. The root [Path] selects Config.
|
||||
// A non-nil result supports lookup even when constructed manually without load
|
||||
// or inspection state. Success means value availability, not input presence or
|
||||
// validation; use Metadata to inspect presence in the completed load.
|
||||
//
|
||||
// Navigation follows the shared YAML field names, inline bindings and supported
|
||||
// shapes described in docs/config.md#application-schema-binding, with [Path]'s
|
||||
// key/index rules. It follows non-nil intermediate pointers and interfaces,
|
||||
// checks map membership and sequence bounds, and never allocates missing values.
|
||||
// Scalars, including text-codec types and Secret, remain leaves.
|
||||
// A nil receiver, invalid path, missing value, or unavailable traversal returns
|
||||
// (nil, false). A present nil succeeds: a nil interface returns (nil, true), while
|
||||
// typed nil pointers, maps and slices retain their types in the returned any.
|
||||
//
|
||||
// The terminal retains its actual Go type, including named types and pointers;
|
||||
// terminal pointers are not dereferenced. Lookup performs no conversion or
|
||||
// revalidation of the terminal and does not invoke codecs or resolve secrets.
|
||||
// Values are trusted application data and may include resolved Secret values.
|
||||
// Ordinary Go assignment applies: structs and arrays are copied, while maps,
|
||||
// slices and pointers can alias Config. Inspection methods continue to report
|
||||
// the frozen completed load, not later caller mutations.
|
||||
func (r *Result[T]) Value(path Path) (any, bool) {
|
||||
if r == nil {
|
||||
return nil, false
|
||||
}
|
||||
return engine.ResultValue(r.Config, toEnginePath(path), secretBinding())
|
||||
}
|
||||
Reference in New Issue
Block a user