Documentation
¶
Overview ¶
Package json provides JSON encoding and decoding for the operation graph.
Index ¶
- Constants
- type Provider
- type Resource
- func (r *Resource) Addressing() op.AddressingMode
- func (r *Resource) Digest() (op.Digest, error)
- func (r *Resource) Equal(other any) bool
- func (r *Resource) Pack() ([]byte, error)
- func (r *Resource) Parsed() any
- func (r *Resource) String() string
- func (r *Resource) UnmarshalJSON(data []byte) error
- func (r *Resource) UnmarshalText(text []byte) error
- func (r *Resource) UnmarshalYAML(unmarshal func(any) error) error
- func (r *Resource) Unpack(runtimeEnvironment *op.RuntimeEnvironment, uri string, content []byte) (op.Resource, error)
- func (r *Resource) Validate(schemaJSON string) (ValidationResult, error)
- type ValidationResult
Constants ¶
const ( Decode op.ActionName = "json.decode" Encode op.ActionName = "json.encode" EncodeIndent op.ActionName = "json.encode_indent" Parse op.ActionName = "json.parse" )
Action-name constants for the json provider's plan-mode actions.
Each constant is the short dotted action label its method dispatches under. Pass these to plan.Plan, op.ReceiverRegistry().BuildAction, RuntimeEnvironment.ActionByName, or WithActionNamed in place of a string literal so a typo is a compile error and rename / find-references work through the constant.
const SchemeJSON = "json"
SchemeJSON is the URI scheme for JSON resources.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Provider ¶
type Provider struct {
op.ProviderBase
}
Provider provides JSON encoding and decoding operations.
+devlore:access=both
func NewProvider ¶
func NewProvider(runtimeEnvironment *op.RuntimeEnvironment) *Provider
NewProvider creates a JSON provider bound to the given context.
func (*Provider) Decode ¶
Decode parses a JSON string into a Go value.
Parameters:
- `data`: the JSON text to parse.
Returns:
- `any`: the decoded Go value (maps, slices, and scalars per encoding/json).
- `error`: non-nil when `data` is not valid JSON.
func (*Provider) Encode ¶
Encode marshals a Go value to a compact JSON string.
Parameters:
- `value`: the Go value to marshal.
Returns:
- `string`: the compact JSON encoding of `value`.
- `error`: non-nil when `value` cannot be marshaled to JSON.
func (*Provider) EncodeIndent ¶
EncodeIndent marshals a Go value to an indented JSON string.
Parameters:
- `value`: the Go value to marshal.
- `indent`: the per-level indentation string (e.g., " " or "\t").
Returns:
- `string`: the indented JSON encoding of `value`.
- `error`: non-nil when `value` cannot be marshaled to JSON.
func (*Provider) Parse ¶
Parse decodes a JSON string into a Resource that holds the parsed Go value.
Unlike Decode, which returns a bare Go value (marshaled to a Starlark dict), Parse returns a Resource whose internal representation can be validated against a JSON Schema or re-encoded without Starlark↔Go round-trips.
Parse is content-keyed — two calls with the same input produce the same URI and share a single canonical catalog entry. The first caller's `Unit.ID()` stamps producerID; subsequent same-content callers get the existing entry unchanged. NewResource handles the parse, hash, and catalog interning in one step.
Parameters:
- `activationRecord`: the per-dispatch activation; its `Unit` stamps the produced Resource's producerID.
- `data`: the JSON text to parse.
Returns:
- `*Resource`: the canonical catalog entry holding the parsed value.
- `error`: non-nil when `data` is not valid JSON or catalog interning fails.
type Resource ¶
type Resource struct {
op.ResourceBase
// Data is the canonical JSON bytes (sorted-key, whitespace-free re-marshal of the parsed input). Identity
// bearing — `SHA-256(Data)` is encoded in the URI <specific> as `json:<Hash>`.
Data []byte `json:"data,omitempty"`
// Hash is the lowercase hex SHA-256 of Data, identity-bearing. Also encoded in the URI <specific>.
Hash string `json:"hash,omitempty"`
// contains filtered or unexported fields
}
Resource represents a parsed JSON document held in memory, identified by the SHA-256 of its canonical form.
Unlike [mem.Resource] which holds opaque bytes, json.Resource carries a parsed Go value (map[string]any, []any, scalars) that can be validated against a JSON Schema or re-encoded without Starlark↔Go round trips.
Identity is content-addressed via canonicalization: the input bytes are parsed with encoding/json and re-marshaled to produce a canonical byte form (map keys sorted, no whitespace, stable scalar serialization). The SHA-256 of those canonical bytes drives the URI-specific (`json:<hex>`) and the Hash field. Two semantically equal inputs — `{"a":1,"b":2}` and `{"b":2,"a":1}` — produce identical URIs by construction.
Canonicalization Warnings:
- Not RFC 8785 (JCS) compliant. Within-Go determinism only; cross-language portability not in scope.
- Numbers larger than 2^53 lose precision via `float64` round trip — two distinct large integers can collide.
- Object key sort is UTF-8 byte order (Go's encoding/json default), not the UTF-16 order JCS specifies. Agrees with JCS for ASCII keys; diverges for the supplementary plane.
func DiscoverResource ¶
func DiscoverResource(runtimeEnvironment *op.RuntimeEnvironment, value any) (*Resource, error)
DiscoverResource constructs a json.Resource and registers it without claiming production.
Used by the framework's resource registry adapter for slot coercion (when starlark supplies a string and the slot expects a *json.Resource) and by callers holding a reference handle without claiming production. UnmarshalJSON / UnmarshalText / UnmarshalYAML rehydration is the canonical use case.
Discover does not stamp a producer, so unlike NewResource it takes only `runtimeEnvironment` — no unit reference is needed.
Same value-shape dispatch as NewResource: raw JSON bytes, an io.Reader, or a canonical tag URI string.
Nil-Catalog tolerance: returns the unlinked candidate when no catalog is present.
Parameters:
- `runtimeEnvironment`: the session runtime environment.
- `value`: raw JSON bytes ([]byte), an io.Reader, or a canonical tag URI string; same dispatch as NewResource.
Returns:
- `*Resource`: canonical catalog entry, or the unlinked candidate when no catalog is present.
- `error`: unsupported value type, JSON parse failure, malformed URI, or identity construction failure.
func NewResource ¶
func NewResource(runtimeEnvironment *op.RuntimeEnvironment, producerID string, value any) (*Resource, error)
NewResource constructs a json.Resource and claims production via op.ResourceCatalog.GetOrCreate.
The json.Resource is content-keyed — the URI is `json:<sha256-hex>` derived from the canonical form of the input, so two callers with semantically equal inputs produce the same URI and share a single catalog entry. The first caller's `Unit.ID()` stamps producerID; later calls for the same content get the existing entry unchanged.
Use NewResource from a producer dispatch context. Use DiscoverResource instead when the caller is not claiming production (rehydration, the framework's slot-coercion adapter).
Nil-Catalog tolerance: returns the unlinked candidate when no catalog is present.
Parameters:
- `runtimeEnvironment`: the session runtime environment.
- `producerID`: the producing caller's id (`activationRecord.CallerID`), or "" for caller-less dispatch. for non-graph dispatch.
- `value`: raw JSON bytes ([]byte), an io.Reader streaming JSON, or a canonical tag URI string. Bytes and streams are parsed and canonicalized during construction; an invalid JSON document errors here.
Returns:
- `*Resource`: canonical catalog entry, or the unlinked candidate when no catalog is present.
- `error`: unsupported value type, JSON parse failure, malformed URI, or identity construction failure.
func (*Resource) Addressing ¶
func (r *Resource) Addressing() op.AddressingMode
Addressing reports that json.Resource is content-addressed.
Overrides op.ResourceBase.Addressing's op.AddressingUnknown default.
Returns:
- `op.AddressingMode`: op.AddressingContent — identity is the SHA-256 of the canonical JSON bytes.
func (*Resource) Digest ¶
Digest returns the content digest of the canonical bytes.
The SHA-256 was computed during construction (or parsed from the URI on rehydration) and stamped on Hash. Reassembles the canonical `sha256:<hex>` form via op.ParseDigest, producing the strict op.Digest shape. Overrides op.ResourceBase.Digest's op.ErrUnimplemented default.
Returns:
- `op.Digest`: {Algorithm: "sha256", Bytes: decoded Hash}.
- `error`: non-nil if Hash is malformed; should not occur post-construction or post-rehydration.
func (*Resource) Equal ¶
Equal reports whether r and other identify the same json.Resource.
Strict equality: the `other` must be a *json.Resource. URI comparison is delegated to op.ResourceBase.Equal.
Parameters:
- `other`: candidate value; nil or any non-*json.Resource value returns false.
Returns:
- `bool`: true when other is a *json.Resource with the same URI as r.
func (*Resource) Pack ¶
Pack implements op.Packer.
The transportable content is the canonical JSON bytes — the exact bytes whose SHA-256 the URI carries, so pack → unpack → pack round-trips byte-identical.
Returns:
- `[]byte`: the canonical JSON bytes (Data).
- `error`: non-nil when the resource holds no content (a URI-only rehydrated resource).
func (*Resource) Parsed ¶
Parsed returns the decoded Go value cached during construction.
Returns nil when the Resource was rehydrated from a URI (parsed is not reconstructed from URI alone. Call NewResource([]byte) to reparse from canonical bytes if needed).
Returns:
- `any`: the parsed Go value (map[string]any / []any / scalar), or nil for URI-rehydrated Resources.
func (*Resource) String ¶
String returns the compact JSON encoding of the Resource for debug output. Delegates to op.ResourceBase.Format.
Returns:
- `string`: the compact JSON encoding of r.
func (*Resource) UnmarshalJSON ¶
UnmarshalJSON populates the receiver from its JSON document (a bare URI string).
The caller pre-seeds the receiver's embedded op.ResourceBase with a valid op.RuntimeEnvironment before invocation. The URI alone reconstructs the Resource metadata; Data and parsed are left empty — call NewResource([]byte) if the canonical bytes are needed.
Parameters:
- `data`: JSON bytes encoding a single bare URI string.
Returns:
- `error`: missing RuntimeEnvironment on receiver, malformed JSON, or rehydration failure.
func (*Resource) UnmarshalText ¶
UnmarshalText populates the receiver from raw UTF-8 bytes containing the URI.
Same prerequisites and semantics as Resource.UnmarshalJSON.
Parameters:
- `text`: UTF-8 bytes containing the canonical tag URI.
Returns:
- `error`: missing RuntimeEnvironment on receiver, or rehydration failure.
func (*Resource) UnmarshalYAML ¶
UnmarshalYAML populates the receiver from its YAML document (a bare URI scalar).
Same prerequisites and semantics as Resource.UnmarshalJSON.
Parameters:
- `unmarshal`: YAML decode hook supplied by the YAML library; called with a *string target.
Returns:
- `error`: missing RuntimeEnvironment on receiver, decode failure, or rehydration failure.
func (*Resource) Unpack ¶
func (r *Resource) Unpack(runtimeEnvironment *op.RuntimeEnvironment, uri string, content []byte) (op.Resource, error)
Unpack implements op.Unpacker.
Rebuilds the resource from its canonical JSON bytes — the inverse of Resource.Pack. The receiver carries no state (graph load dispatches Unpack on a zero value resolved from the URI fragment's type id). The rebuilt URI must equal `uri`: the URI's digest is covered by the graph checksum and signature, so the equality check is what catches tampered content bytes.
Parameters:
- `runtimeEnvironment`: the session runtime environment threaded into the rebuilt resource.
- `uri`: the canonical tag URI recorded in the document.
- `content`: the canonical JSON bytes produced by Resource.Pack.
Returns:
- `op.Resource`: the reconstructed *json.Resource, not interned in any catalog.
- `error`: parse or canonicalization failure, identity construction failure, or a URI mismatch (integrity failure).
func (*Resource) Validate ¶
func (r *Resource) Validate(schemaJSON string) (ValidationResult, error)
Validate checks the parsed document against a JSON Schema.
Operates on the cached parsed Go value — no re-serialization needed. Returns an error only on schema compilation failures; validation outcomes are returned in the ValidationResult.
Parameters:
- `schemaJSON`: a JSON string containing the JSON Schema to validate against.
Returns:
- `ValidationResult`: the validation outcome with Valid bool and Errors []string.
- `error`: schema compilation errors (NOT validation errors — those go in ValidationResult.Errors).
type ValidationResult ¶
type ValidationResult struct {
// Valid is true when the document conforms to the schema.
Valid bool `json:"valid" starlark:"valid"`
// Errors is the list of validation error messages; empty when Valid is true.
Errors []string `json:"errors" starlark:"errors"`
}
ValidationResult holds the outcome of a JSON Schema validation.