Documentation
¶
Overview ¶
Package wire defines a compact TLV binary form of a ClassAd with attribute-key interning and a hot-attribute header, plus the encoder/decoder that convert to and from the fully-public ast.ClassAd representation.
The package depends only on the ast package (and the standard library): Encode takes an *ast.ClassAd and Decode returns one, so wire stays decoupled from the higher-level classad.ClassAd wrapper. Bridging classad.ClassAd <-> ast.ClassAd lives in the store layer.
Index ¶
- Constants
- Variables
- func AppendAdInlineFromInternedResealed(dst []byte, src Ad, resolve func(uint32) (string, bool), ...) (out []byte, resealed int, ok bool)deprecated
- func AppendAdInlineFromInternedResealedErr(dst []byte, src Ad, resolve func(uint32) (string, bool), ...) (out []byte, resealed int, err error)
- func AppendAdMergedInline(dst []byte, base Ad, overlays []Ad, sc *MergeScratch) ([]byte, bool)
- func AppendAdPatchedInline(dst []byte, base Ad, overlays []Ad, removed []string, sc *MergeScratch) ([]byte, bool)
- func AppendAdSubsetInline(dst []byte, src Ad, keep func(name, node []byte) bool, open Sealer) ([]byte, bool)
- func AppendAdSubsetInlineFromInterned(dst []byte, src Ad, resolve func(uint32) (string, bool), ...) ([]byte, bool)
- func AppendAdSubsetInlineHotFirst(dst []byte, src Ad, keep func(name, node []byte) bool, needed int, open Sealer, ...) ([]byte, bool)
- func AppendAdSubsetInlineRefs(dst []byte, src Ad, keep func(name []byte, h uint32, node []byte) bool, ...) ([]byte, bool)
- func AppendBoolNode(dst []byte, b bool) []byte
- func AppendInlineFromInternedUnopened(dst []byte, src Ad, resolve func(uint32) (string, bool)) ([]byte, bool)
- func AppendIntNode(dst []byte, v int64) []byte
- func AppendInternedFromInline(dst []byte, src Ad, t *InternTable, hot map[uint32]struct{}) ([]byte, bool)
- func AppendInternedFromInlineWith(dst []byte, src Ad, in NameInterner) ([]byte, bool)
- func AppendKey(dst []byte, inline bool, id uint32, name string) []byte
- func AppendListHeader(dst []byte, n int) []byte
- func AppendNodeRefIDs(node []byte, dst []uint32) []uint32
- func AppendNodeRefNames(node []byte, dst [][]byte) [][]byte
- func AppendNodeRefsExact(node []byte, inline bool, r *NodeRefs, isEval func(uint32) bool) bool
- func AppendNodeText(dst, node []byte, t *InternTable) ([]byte, error)
- func AppendNodeTextInline(dst, node []byte) ([]byte, error)
- func AppendNodeTextInlineOld(dst, node []byte) ([]byte, error)
- func AppendNodeTextInlineOldEnc(dst, node []byte, open Sealer, redactSealed bool) ([]byte, error)
- func AppendNodeTextOld(dst, node []byte, t *InternTable) ([]byte, error)
- func AppendNodeTextOldEnc(dst, node []byte, t *InternTable, open Sealer, redactSealed bool) ([]byte, error)
- func AppendRealNode(dst []byte, f float64) []byte
- func AppendStringNode(dst []byte, s string) []byte
- func AppendUndefinedNode(dst []byte) []byte
- func BuildAd(dst, header []byte, n int, entries []byte) []byte
- func CheckDepth(ad *ast.ClassAd) error
- func CheckExprDepth(name string, v ast.Expr) error
- func Decode(b []byte, t *InternTable) (*ast.ClassAd, error)
- func DecodeInline(b []byte) (*ast.ClassAd, error)
- func DecodeInlineEnc(b []byte, open Sealer) (*ast.ClassAd, error)
- func DecodeInlineRedact(b []byte) (*ast.ClassAd, error)
- func DecodeNode(node []byte, t *InternTable) (ast.Expr, error)
- func DecodeNodeInline(node []byte) (ast.Expr, error)
- func DecodeNodeInlineEnc(node []byte, open Sealer) (ast.Expr, error)
- func DecodeNodeResolve(node []byte, resolve func(uint32) (string, bool)) (ast.Expr, error)
- func DecodeNodeResolveEnc(node []byte, resolve func(uint32) (string, bool), open Sealer) (ast.Expr, error)
- func DecodeResolve(b []byte, resolve func(uint32) (string, bool)) (*ast.ClassAd, error)
- func DecodeResolveEnc(b []byte, resolve func(uint32) (string, bool), open Sealer) (*ast.ClassAd, error)
- func DecodeResolveEncRedact(b []byte, resolve func(uint32) (string, bool), open Sealer) (*ast.ClassAd, error)
- func DecodeStandalone(b []byte) (*ast.ClassAd, error)
- func Encode(dst []byte, ad *ast.ClassAd, t *InternTable) []byte
- func EncodeInline(dst []byte, ad *ast.ClassAd) []byte
- func EncodeInlineDelta(dst []byte, ad *ast.ClassAd, hot map[string]struct{}, ...) []bytedeprecated
- func EncodeInlineDeltaSealed(dst []byte, ad *ast.ClassAd, hot map[string]struct{}, ...) ([]byte, error)
- func EncodeInlineWithHot(dst []byte, ad *ast.ClassAd, hot map[string]struct{}) []byte
- func EncodeInlineWithHotEnc(dst []byte, ad *ast.ClassAd, hot map[string]struct{}, ...) []bytedeprecated
- func EncodeInlineWithHotSealed(dst []byte, ad *ast.ClassAd, hot map[string]struct{}, ...) ([]byte, error)
- func EncodeStandalone(ad *ast.ClassAd) []byte
- func EncodeWithHot(dst []byte, ad *ast.ClassAd, t *InternTable, hot map[uint32]struct{}) []byte
- func EncodeWithHotClosure(dst []byte, ad *ast.ClassAd, t *InternTable, hot map[uint32]struct{}, ...) []byte
- func EncodeWithHotEnc(dst []byte, ad *ast.ClassAd, t *InternTable, hot map[uint32]struct{}, ...) []bytedeprecated
- func EncodeWithHotSealed(dst []byte, ad *ast.ClassAd, t *InternTable, hot map[uint32]struct{}, ...) ([]byte, error)
- func ExprDepth(v ast.Expr) int
- func FoldEqualBytes(b []byte, name string) bool
- func FoldEqualNames(a, b []byte) bool
- func IsDelta(rec []byte) bool
- func IsEncryptedNode(node []byte) bool
- func IsLiteralNode(node []byte) bool
- func NameHash32(name string) uint32
- func NameHash32Bytes(name []byte) uint32
- func NodeLen(b []byte) (int, bool)
- func NodeLenKeyed(b []byte, inline bool) (int, bool)
- func OpenEncryptedNode(node []byte, open Sealer) ([]byte, bool)
- func ParseExprToWire(input string, t *InternTable, dst []byte) ([]byte, error)
- func RecordMemberID(node []byte, id uint32) ([]byte, bool)
- func RecordMemberName(node []byte, name string) ([]byte, bool)
- func ScalarListElems(node []byte, fn func(elem []byte) bool) (int, bool)
- func SealedInlineFormRecoveries() int64
- func StringLiteralValue(node []byte) ([]byte, bool)
- type Ad
- func (a Ad) AttrCount() int
- func (a Ad) ForEach(fn func(id uint32, node []byte) bool) bool
- func (a Ad) ForEachHot(fn func(id uint32, node []byte) bool) bool
- func (a Ad) ForEachHotBuf(scratch []uint32, fn func(id uint32, node []byte) bool) ([]uint32, bool)
- func (a Ad) ForEachHotInlineBuf(scratch []uint32, fn func(hash uint32, name, node []byte) bool) ([]uint32, bool)
- func (a Ad) ForEachIDNode(fn func(id uint32, node []byte) bool) bool
- func (a Ad) ForEachNameNode(fn func(name, node []byte) bool) bool
- func (a Ad) ForEachNamed(t *InternTable, fn func(name string, node []byte) bool) bool
- func (a Ad) ForEachNamedRedact(t *InternTable, fn func(name string, node []byte) bool) bool
- func (a Ad) ForEachRaw(fn func(id uint32, name string, node []byte) bool) bool
- func (a Ad) HotClosureComplete() bool
- func (a Ad) Interned() bool
- func (a Ad) Lookup(id uint32) ([]byte, bool)
- func (a Ad) LookupByName(name string) ([]byte, bool)
- func (a Ad) SplitBody() (header, entries []byte, n int, inline, ok bool)
- type DepthError
- type InternTable
- func (t *InternTable) Intern(name string) uint32
- func (t *InternTable) InternBytes(name []byte) uint32
- func (t *InternTable) InternName(name []byte) (uint32, bool)
- func (t *InternTable) IsPrivate(id uint32) bool
- func (t *InternTable) Len() int
- func (t *InternTable) LookupID(name string) (uint32, bool)
- func (t *InternTable) Name(id uint32) (string, bool)
- func (t *InternTable) Names() []string
- type LitKind
- type Literal
- type MergeScratch
- type NameInterner
- type NodeClass
- type NodeEmitter
- func (e *NodeEmitter) AttrRef(scope byte, name string)
- func (e *NodeEmitter) Bool(v bool)
- func (e *NodeEmitter) Bytes() []byte
- func (e *NodeEmitter) Err()
- func (e *NodeEmitter) FoldNegate(mark int)
- func (e *NodeEmitter) FuncNameID(name string) uint32
- func (e *NodeEmitter) Int(v int64)
- func (e *NodeEmitter) Mark() int
- func (e *NodeEmitter) Real(v float64)
- func (e *NodeEmitter) RecordKey(name string)
- func (e *NodeEmitter) Reset()
- func (e *NodeEmitter) Str(v string)
- func (e *NodeEmitter) UnOp(op string)
- func (e *NodeEmitter) Undef()
- func (e *NodeEmitter) WrapBinOp(mark int, op string)
- func (e *NodeEmitter) WrapCond(mark int)
- func (e *NodeEmitter) WrapElvis(mark int)
- func (e *NodeEmitter) WrapFuncID(mark int, name string, id uint32, argc int)
- func (e *NodeEmitter) WrapList(mark, count int)
- func (e *NodeEmitter) WrapParen(mark int)
- func (e *NodeEmitter) WrapRecord(mark, attrCount int)
- func (e *NodeEmitter) WrapSelect(mark int, attr string)
- func (e *NodeEmitter) WrapSubscript(mark int)
- type NodeRefs
- type Sealer
- type StreamEncoder
- func (s *StreamEncoder) Bool(name string, v bool)
- func (s *StreamEncoder) Bytes(dst []byte) []byte
- func (s *StreamEncoder) Count() int
- func (s *StreamEncoder) Err() error
- func (s *StreamEncoder) Error(name string)
- func (s *StreamEncoder) Expr(name string, e ast.Expr)
- func (s *StreamEncoder) ExprWire(name, val string) error
- func (s *StreamEncoder) Int(name string, v int64)
- func (s *StreamEncoder) Real(name string, v float64)
- func (s *StreamEncoder) Reset()
- func (s *StreamEncoder) SetHot(hot map[uint32]struct{})
- func (s *StreamEncoder) String(name, v string)
- func (s *StreamEncoder) StringBytes(name string, v []byte)
- func (s *StreamEncoder) Undefined(name string)
- type SubsetScratch
Constants ¶
const MaxDepth = 1000
MaxDepth is how deeply a stored value may nest, and the ONE bound every reader and the write side share. Readers stop past it so a crafted deeply nested input cannot overflow the goroutine stack; the write side refuses past it so nothing is stored that a reader would then refuse.
Depth is counted the same way by every reader: an attribute's value is at depth 0, whether the reader starts from the whole ad (Decode and its variants) or from the value's node (DecodeNode, the renderers, the reference walkers, the transcoders); each operand, element, argument, condition branch, selected record or subscript part is one deeper than its parent; a record literal's body, and with it each member's value, is one deeper than the record. A sealed (encrypted) value is transparent: its plaintext is read at the sealed node's depth, so whether an attribute is encrypted at rest never changes whether it fits. A value fits when no part of it is deeper than MaxDepth.
A chain of one binary operator, `a || b || c || ...`, parses left-nested: N terms reach depth N-1. So the longest chain an attribute can hold, with no parentheses at all, is 1001 terms.
const TagExternalRef = 0xFF
TagExternalRef is a node tag this package never writes and never accepts: every decoder and skipper here rejects it as malformed. It is reserved for a storage layer that replaces a node, in place, with a reference into a table it keeps elsewhere, and that expands every such reference back into the original node bytes before any of this package's readers sees the ad. Reserving it here keeps a future node type from being assigned the same byte, which would make such a layer read a real node as a reference.
const TagListRef = 0xFE
TagListRef is a second reserved node tag, with the same contract as TagExternalRef: this package never writes it, and every decoder and skipper here rejects it as malformed. It is the placeholder a storage layer leaves where it took a list literal out of a record into a typed column, so a record that reaches one of this package's readers without the list put back fails to read rather than reading as a record without the attribute.
Variables ¶
var ErrMalformed = errors.New("wire: malformed encoding")
ErrMalformed is returned when the input is not a well-formed wire ad.
var ErrSealFailed = errors.New("wire: sealing a value failed")
ErrSealFailed is returned (wrapped, with the Sealer's own error) by the encoders that report errors when a value the caller's predicate names for sealing could not be sealed. Nothing is encoded for such an ad: a value that was meant to be encrypted at rest is never written in the clear in its place.
var ErrSealed = errors.New("attribute is sealed and no decryption key is available")
ErrSealed reports that an attribute is sealed and this decoder has no key for it. It wraps into the error DecodeResolveEnc returns, so a caller distinguishes "not entitled to this value" from "this ad is corrupt" with errors.Is -- the two used to be the same ErrMalformed.
var ErrTooDeep = errors.New("wire: value nests too deeply to store")
ErrTooDeep reports a value that nests deeper than MaxDepth, refused when it is written because no reader could read it back. It is permanent: the same value is refused every time, so a caller must drop or change it rather than retry. Match it with errors.Is; the error carrying it is a *DepthError naming the attribute.
var ErrUnsupported = errors.New("wire: expression construct not handled by the native parser")
ErrUnsupported signals the wire-native parser hit a construct it does not handle (a record literal, an int64-min magnitude, a computed select, ...). The caller should fall back to the reference parser, which is the source of truth.
Functions ¶
func AppendAdInlineFromInternedResealed
deprecated
added in
v0.37.0
func AppendAdInlineFromInternedResealed(dst []byte, src Ad, resolve func(uint32) (string, bool), keep func(name, node []byte) bool, s Sealer, sc *SubsetScratch) (out []byte, resealed int, ok bool)
AppendAdInlineFromInternedResealed is AppendAdInlineFromInternedResealedErr reporting only whether it succeeded. ok=false for every error that one returns, and dst is then returned as it was passed.
Deprecated: use AppendAdInlineFromInternedResealedErr, whose error tells a value that would not seal (wire.ErrSealFailed) from one that would not open or a src that is malformed. A writer reports the two differently.
func AppendAdInlineFromInternedResealedErr ¶ added in v0.37.0
func AppendAdInlineFromInternedResealedErr(dst []byte, src Ad, resolve func(uint32) (string, bool), keep func(name, node []byte) bool, s Sealer, sc *SubsetScratch) (out []byte, resealed int, err error)
AppendAdInlineFromInternedResealedErr is AppendAdSubsetInlineFromInterned for a WRITER that has to carry an interned ad's sealed values into an inline-names record it will store. A sealed value's plaintext is its node encoding in the key form of the ad it was sealed in, so one sealed in src holds src's ids and cannot be moved unopened (see AppendInlineFromInternedUnopened). Here each sealed value keep selects is opened with s, its plaintext rewritten to the inline-names form, and sealed again with s; the entry is emitted sealed, never in the clear.
The plaintext exists only inside that step (resealInline): it is never appended to dst, returned, or put in an error, and both the opened buffer and its rewritten form are zeroed once the new ciphertext exists. A sealed value keep rejects is skipped before it is opened, so a caller that drops the values it does not need opens only the ones it carries.
resealed counts the values opened and re-sealed. On any error dst is returned as it was passed and the caller must not store anything in its place:
- an error wrapping ErrSealFailed: a carried value opened but would not seal again, or s is nil. The only record that could be produced holds that value in the clear, so none is.
- an error wrapping ErrMalformed: everything AppendAdSubsetInlineFromInterned refuses, and a carried sealed value that does not open (tampered, or another key) or whose plaintext does not parse. A writer that dropped it would lose the value, and one that copied it would store bytes no reader can parse.
An inline-names src is refused (ErrMalformed): its sealed values are already in the form an inline record needs, and the caller copies them unopened instead.
func AppendAdMergedInline ¶ added in v0.30.0
AppendAdMergedInline appends to dst the ad formed by applying overlays, in order, over base, and returns the extended buffer. A later overlay's attribute wins over an earlier one's, and any overlay's wins over base's; an attribute no overlay mentions is copied from base byte for byte.
Every participant must be an inline-names ad that is not standalone (no embedded intern table): entries are copied between ads, so the names have to be IN the entries. It reports false when that does not hold, or when any participant is malformed, so the caller can fall back to decoding -- which is the source of truth.
The result carries NO hot header. The hot header stores absolute offsets into the entries region, which a merge invalidates, and every reader treats it as a guarded fast path that falls back to a linear walk when it comes up short (see rawprojected.go) or refuses a merged ad outright (hotClosureMatch requires flagHotClosure, which this does not set). AppendAdSubsetInline emits none for the same reason.
func AppendAdPatchedInline ¶ added in v0.35.0
func AppendAdPatchedInline(dst []byte, base Ad, overlays []Ad, removed []string, sc *MergeScratch) ([]byte, bool)
AppendAdPatchedInline is AppendAdMergedInline that also removes the attributes named in removed (compared case-insensitively) wherever they appear, in base or in an overlay. It is what a write that sets some attributes and deletes others composes a whole record with, when the record must be built without opening the sealed values it carries: every attribute the write does not name is copied from base or an overlay byte for byte, ciphertext included.
func AppendAdSubsetInline ¶ added in v0.16.4
func AppendAdSubsetInline(dst []byte, src Ad, keep func(name, node []byte) bool, open Sealer) ([]byte, bool)
AppendAdSubsetInline assembles a self-contained inline-names ad holding the subset of src's attribute entries keep selects, appending it to dst and returning the extended slice. It is the relay primitive for shipping stored ads across a trust/process boundary in wire form: an inline entry is a contiguous (name, node) byte range, so the subset is assembled by slice copies -- no value is decoded, rendered or re-encoded.
An entry whose node is at-rest encrypted (nEncrypted) is emitted with its value OPENED via open when non-nil -- the consumer holds no data key -- and skipped entirely when open is nil or fails (matching the fast paths, which treat an unopenable value as absent). The emitted ad carries no hot header (its consumer renders linearly). Returns ok=false when src is not a well-formed inline-names ad; keep=nil keeps every entry.
func AppendAdSubsetInlineFromInterned ¶ added in v0.33.2
func AppendAdSubsetInlineFromInterned(dst []byte, src Ad, resolve func(uint32) (string, bool), keep func(name, node []byte) bool, open Sealer, sc *SubsetScratch) ([]byte, bool)
AppendAdSubsetInlineFromInterned is AppendAdSubsetInline for a src whose attribute keys are INTERNED ids: it assembles the same self-contained inline-names subset ad, resolving each id through resolve and rewriting the name-carrying nodes. The emitted ad carries no hot header.
An inline-names src is passed straight to AppendAdSubsetInline, so a caller holding a mixed population (an in-memory store whose records are interned, a converted segment record that is already inline) can call this unconditionally.
keep is called with the resolved attribute name and the attribute's node bytes AS STORED -- i.e. the INTERNED node, before rewriting. A keep that only inspects the name (what the collection's wire-subset selector does) behaves identically on both forms; one that inspects node bytes must account for the encoding.
Returns ok=false when src is malformed, when it is standalone (its ids index an embedded table, not resolve's), or when an id does not resolve -- the same contract AppendAdSubsetInline has, so a caller discards the partial append and falls back. keep=nil keeps every entry. sc carries the reusable name buffer; it must not be shared across goroutines.
func AppendAdSubsetInlineHotFirst ¶ added in v0.16.4
func AppendAdSubsetInlineHotFirst(dst []byte, src Ad, keep func(name, node []byte) bool, needed int, open Sealer, sc *SubsetScratch) ([]byte, bool)
AppendAdSubsetInlineHotFirst is AppendAdSubsetInline with the hot-header shortcut: entries reachable through the ad's hot pairs are copied first via their stored offsets, and when that satisfies the whole selection (kept == needed) the linear walk is skipped entirely -- the projected relay's fast path, mirroring the projected text scan's. Anything short of full satisfaction falls back to the walk, which skips the entries the hot phase already copied. needed <= 0 disables the shortcut (a whole-ad selection must walk everything).
func AppendAdSubsetInlineRefs ¶ added in v0.33.2
func AppendAdSubsetInlineRefs(dst []byte, src Ad, keep func(name []byte, h uint32, node []byte) bool, note func(node []byte) bool, pending func() int, needed int, open Sealer, sc *SubsetScratch) ([]byte, bool)
AppendAdSubsetInlineRefs is AppendAdSubsetInlineHotFirst whose selection is CLOSED under the emitted expressions' own attribute references, so the assembled row evaluates self-contained at the far end.
keep is the caller's membership test, consulted per entry; note is called with every node that was emitted, except a sealed one (which refers to nothing), right after keep accepted it, and collects that node's unscoped/MY.-scoped references into the caller's wanted set, reporting true when it surfaced a name the set did not already hold. keep must accept those names on a later pass -- the two callbacks share the caller's set, and that sharing is the whole mechanism.
The hot-header shortcut still applies, and still exits early when the projection was satisfied from the hot header alone AND nothing it emitted referenced anything new. Past that it walks the entries, repeating the walk while a pass surfaces new names: a referenced attribute may sit EARLIER in the ad than the expression that named it, so one pass is not enough. Each pass either grows the wanted set or ends the loop, and the set is bounded by the ad's own attribute count, so the repetition terminates.
needed <= 0 (a whole-ad selection) ships everything and has no closure to compute; it is handed to AppendAdSubsetInline unchanged.
func AppendBoolNode ¶ added in v0.22.0
func AppendInlineFromInternedUnopened ¶ added in v0.35.0
func AppendInlineFromInternedUnopened(dst []byte, src Ad, resolve func(uint32) (string, bool)) ([]byte, bool)
AppendInlineFromInternedUnopened appends to dst the inline-names form of src, an interned ad whose ids resolve names, and returns the extended buffer. Every entry is kept, in order, with a header of flagInlineNames plus src's delta flag and no hot header; names and name-carrying nodes are rewritten as AppendAdSubsetInlineFromInterned rewrites them.
A sealed value is copied UNOPENED, so this needs no key and never holds a plaintext. That is also its limit: a sealed value's plaintext is its node encoding in the key form of the ad it was sealed in, so a value sealed in src keeps src's ids inside its ciphertext, and an inline-names reader that opened it would parse those ids as inline names. The result is therefore only for a reader that never opens a sealed value -- one with no key, or one that reads literals and treats a sealed value as opaque. To such a reader a copied sealed value is exactly what any other sealed value is.
Returns ok=false when src is malformed, standalone, already inline-names, or carries an id resolve does not know -- the cases a keyed decode of src refuses too.
func AppendIntNode ¶ added in v0.22.0
func AppendInternedFromInline ¶ added in v0.30.0
func AppendInternedFromInline(dst []byte, src Ad, t *InternTable, hot map[uint32]struct{}) ([]byte, bool)
AppendInternedFromInline appends to dst the INTERNED form of src, an inline-names ad, and returns the extended buffer. Names are interned into t; ids present in hot get a hot-header entry, matching EncodeWithHotEnc.
It reports false when src is not a plain inline-names ad -- standalone (carrying its own intern table) or already interned -- when it carries a sealed value (see the note at the top of this file), or when it is malformed. The caller falls back to decoding, which is the source of truth.
func AppendInternedFromInlineWith ¶ added in v0.46.0
func AppendInternedFromInlineWith(dst []byte, src Ad, in NameInterner) ([]byte, bool)
AppendInternedFromInlineWith is AppendInternedFromInline with no hot header, taking its ids from in. It reports false where AppendInternedFromInline does, and also when in refuses a name; either way dst is returned as it was passed. Names in interned before the refusal stay interned: a caller that wants them gone undoes them itself.
func AppendKey ¶ added in v0.28.0
AppendKey writes an attribute key in the encoding the ad's flags declare: the interned id, or the name inline.
func AppendListHeader ¶ added in v0.38.0
AppendListHeader appends the head of a list literal node of n elements: the node's tag and its element count, exactly as the encoder writes them. The n element nodes follow it.
func AppendNodeRefIDs ¶ added in v0.16.3
AppendNodeRefIDs appends to dst the interned id of every attribute reference inside node that could resolve against the enclosing ad -- unscoped and MY.-scoped references (TARGET./PARENT. refer to a different ad) -- returning the extended slice. It walks the node's TLV structure directly (the same walk as skipNode), so collecting a node's references costs no decode, no name resolution and no allocation beyond dst's growth; a caller building a projection's reference closure recycles dst across nodes and passes.
The collection is a superset: references inside nested record literals are included even though record-member resolution could shadow them, a `.`-path select contributes its member name (which chains out to the enclosing ad when the record does not define it), and duplicate ids are appended as-is (the caller's wanted-set absorbs both). An encrypted node is opaque and contributes nothing. Returns dst unchanged (beyond any partial appends) with no error indication on a malformed node -- the caller's subsequent render of the same bytes surfaces the corruption.
node must come from an interned (id-keyed) ad, the only kind whose references are ids: a nested record literal's members are keyed the way the enclosing ad is.
func AppendNodeRefNames ¶ added in v0.24.1
AppendNodeRefNames is AppendNodeRefIDs for an INLINE-NAME ad: it appends the inline name of every attribute reference inside node that could resolve against the enclosing ad -- unscoped and MY.-scoped -- returning the extended slice.
A persistent (inline-name) collection stores references as names rather than interned ids, so the id collector finds nothing in one; this is what lets a projection over such a collection build the same reference closure. The appended names are sub-slices of node, valid for as long as node is, and are NOT copied -- a caller that retains them past the record's buffer must copy.
Same superset semantics as AppendNodeRefIDs: nested record members and a select's member name are included even though member resolution could shadow them, duplicates are appended as-is, and an encrypted node contributes nothing.
A nested record literal's members are keyed the way the enclosing ad's attributes are, so they are inline names here. Walking them as ids misreads the first member's name as its value and stops the walk there, losing every reference the node makes from that point on -- including ones outside the record, such as Baz in `[a = Foo].a + Baz`.
func AppendNodeRefsExact ¶ added in v0.33.3
AppendNodeRefsExact appends node's unscoped and MY. references to r and reports whether the set is complete. It is not complete when the node calls eval(), whose string argument names an attribute only at run time, or when it does not parse. A sealed value, which by contract refers to nothing, sets r.Sealed and contributes nothing. inline is the enclosing ad's key encoding, which a nested record literal's members share. isEval reports whether an interned function-name id is eval; nil means no interned id is (an inline-keyed ad names its functions inline).
References inside nested record literals are included, as the lenient walks include them: a superset errs toward keeping more, which is the safe direction for a completeness test.
func AppendNodeText ¶
func AppendNodeText(dst, node []byte, t *InternTable) ([]byte, error)
AppendNodeText appends the canonical ClassAd text of a wire node to dst and returns the extended slice. It is byte-for-byte identical to DecodeNode(node, t).String(), but renders straight from the wire with no ast.Expr and no per-node string: the AST-free query-result path uses it for the non-scalar values (lists, records, computed expressions) that LiteralValue cannot format directly. Interned name ids resolve via t.
func AppendNodeTextInline ¶
AppendNodeTextInline is AppendNodeText for inline-names nodes (self-contained, no intern table) — the form stored by the persistent store.
func AppendNodeTextInlineOld ¶ added in v0.24.1
AppendNodeTextInlineOld is AppendNodeTextInline with old-ClassAd string quoting; see AppendNodeTextOld for why the dialect has to be chosen explicitly.
func AppendNodeTextInlineOldEnc ¶ added in v0.28.0
AppendNodeTextInlineOldEnc is AppendNodeTextInlineOld for wire that may carry SEALED values.
open renders the real value; a nil open with redactSealed renders `undefined` instead -- by node, so it covers any sealed attribute rather than only the ones a private-name list knows about. A nil open without redactSealed keeps the old behaviour and errors, which a caller must want deliberately: every raw caller treats a render error as "skip this ad".
func AppendNodeTextOld ¶ added in v0.24.1
func AppendNodeTextOld(dst, node []byte, t *InternTable) ([]byte, error)
AppendNodeTextOld is AppendNodeText rendering string literals for OLD-ClassAd text, whose tokenizer does no escape processing (C++ Lexer::tokenizeStringOld: only a backslash before the closing quote is a sequence).
The distinction is not cosmetic. AppendNodeText mirrors ast.Expr.String(), which escapes backslashes, tabs and newlines for the new-ClassAd reader that unescapes them. Feeding that text to an old-ClassAd reader, as every raw-projection consumer does, doubles a backslash on each round trip -- so a caller emitting old text must use this.
func AppendNodeTextOldEnc ¶ added in v0.28.0
func AppendNodeTextOldEnc(dst, node []byte, t *InternTable, open Sealer, redactSealed bool) ([]byte, error)
AppendNodeTextOldEnc is AppendNodeTextOld for wire that may carry sealed values; see AppendNodeTextInlineOldEnc.
func AppendRealNode ¶ added in v0.22.0
func AppendStringNode ¶ added in v0.22.0
func AppendUndefinedNode ¶ added in v0.34.0
AppendBoolNode, AppendIntNode, AppendRealNode, and AppendStringNode append a scalar literal wire node to dst and return the extended slice -- the inverse of LiteralValue. They let a caller reconstruct a wire node from a typed value (e.g. the per-segment schema decoder rebuilding a node from a fixed-layout field), producing bytes LiteralValue reads back exactly. AppendUndefinedNode appends the UNDEFINED literal node.
func BuildAd ¶ added in v0.28.0
BuildAd assembles an ad from a header (as SplitBody returns) and a sequence of already-encoded attribute entries, writing an empty hot header. entries must be key+node pairs in the same key encoding the header's flags declare.
The hot header is left empty deliberately: it indexes offsets into the entry region, and a rebuilt region invalidates them. Nothing is lost -- it is regenerated where it matters.
func CheckDepth ¶ added in v0.34.3
CheckDepth reports the first attribute of ad whose value is deeper than MaxDepth, as a *DepthError, or nil when every attribute fits. A nil ad fits.
It reads the ad's syntax tree, not its encoding, so a write path can refuse BEFORE it touches anything: an encoder has no error to return, and several write paths change state (the delta tracker, the shard) before or while they encode.
func CheckExprDepth ¶ added in v0.34.3
CheckExprDepth is CheckDepth for one attribute's value.
func Decode ¶
func Decode(b []byte, t *InternTable) (*ast.ClassAd, error)
Decode parses an ad encoded with Encode or EncodeInline. Interned ads resolve names via t; inline-names ads (flagInlineNames) are self-contained and t may be nil.
func DecodeInline ¶
DecodeInline parses a self-contained inline-names ad (EncodeInline), requiring no intern table.
func DecodeInlineEnc ¶ added in v0.7.0
DecodeInlineEnc is DecodeInline for an ad that may contain nEncrypted attributes: open supplies the segment's key so encrypted values decrypt to their real nodes. A nil open leaves encrypted attributes opaque and DecodeInline errors on them -- use DecodeInlineEnc only on the DAEMON read path that holds the key.
func DecodeInlineRedact ¶ added in v0.28.0
DecodeInlineRedact is DecodeInlineEnc with no key that substitutes undefined for a sealed attribute instead of failing the ad -- the inline-names counterpart of DecodeResolveEncRedact, for a reader that is not entitled to sealed values.
func DecodeNode ¶
func DecodeNode(node []byte, t *InternTable) (ast.Expr, error)
DecodeNode decodes raw node bytes (as returned by Lookup/ForEach) into an ast.Expr, resolving interned ids via t.
func DecodeNodeInline ¶
DecodeNodeInline decodes raw node bytes from an inline-names ad (as returned by LookupByName), which need no intern table.
func DecodeNodeInlineEnc ¶ added in v0.7.0
DecodeNodeInlineEnc decodes raw node bytes from an inline-names ad (as returned by LookupByName), opening an nEncrypted node with open. A nil open leaves an encrypted node an error (the fast path treats that as absent).
func DecodeNodeResolve ¶ added in v0.23.0
DecodeNodeResolve decodes raw node bytes from an interned ad (as returned by Lookup), resolving interned ids via `resolve` instead of an *InternTable -- e.g. backed by a sealed segment's mmap dictionary. Counterpart to DecodeNode for the per-segment interned path.
func DecodeNodeResolveEnc ¶ added in v0.23.0
func DecodeNodeResolveEnc(node []byte, resolve func(uint32) (string, bool), open Sealer) (ast.Expr, error)
DecodeNodeResolveEnc is DecodeNodeResolve that opens an nEncrypted node with open (the per-segment interned analog of DecodeNodeInlineEnc). A nil open leaves an encrypted node an error.
func DecodeResolve ¶ added in v0.23.0
DecodeResolve parses an interned ad (Encode/EncodeWithHot), resolving attribute ids to names via `resolve` instead of an *InternTable -- e.g. backed by a sealed segment's mmap dictionary (id -> name), so no in-memory table is materialized to read the segment. The ad must be interned (not inline -- those are self-contained, use DecodeInline; not standalone). The resolver is inherited by nested ad decoders, so it covers sub-ads too.
func DecodeResolveEnc ¶ added in v0.23.0
func DecodeResolveEnc(b []byte, resolve func(uint32) (string, bool), open Sealer) (*ast.ClassAd, error)
DecodeResolveEnc is DecodeResolve for an interned ad that may contain nEncrypted attributes: open supplies the segment's key so sealed values decrypt to their real (interned) nodes, which then resolve their ids via resolve. A nil open leaves encrypted attributes opaque and decode errors on them -- so pass the sealer only on the daemon read path that holds the key.
func DecodeResolveEncRedact ¶ added in v0.28.0
func DecodeResolveEncRedact(b []byte, resolve func(uint32) (string, bool), open Sealer) (*ast.ClassAd, error)
DecodeResolveEncRedact is DecodeResolveEnc that SUBSTITUTES undefined for any attribute it cannot open, instead of failing the ad. For a read path serving a client not entitled to a value: the ad is readable, one attribute of it is not, and undefined is what an absent attribute yields.
It must never be used where the decoded ad is re-encoded (compaction, dict retraining): substituting undefined there would write the substitution back and destroy the secret.
func DecodeStandalone ¶
DecodeStandalone parses a self-contained ad written by EncodeStandalone.
func Encode ¶
func Encode(dst []byte, ad *ast.ClassAd, t *InternTable) []byte
Encode appends the binary form of ad to dst and returns the extended slice, using the shared intern table t (mutating it to add any new names). The resulting bytes are NOT self-contained: decoding requires the same table.
func EncodeInline ¶
EncodeInline encodes ad with inline attribute names (no interning), producing a fully self-contained ad that DecodeInline reads with no InternTable. Used by the persistent store so on-disk records are recoverable without a shared table.
func EncodeInlineDelta
deprecated
added in
v0.30.0
func EncodeInlineDelta(dst []byte, ad *ast.ClassAd, hot map[string]struct{}, encrypt func(name string) bool, seal Sealer) []byte
EncodeInlineDelta is EncodeInlineDeltaSealed for a caller that cannot handle an error. It panics if a value cannot be sealed, rather than store it in the clear.
Deprecated: use EncodeInlineDeltaSealed, which reports a Seal failure as an error.
func EncodeInlineDeltaSealed ¶ added in v0.37.0
func EncodeInlineDeltaSealed(dst []byte, ad *ast.ClassAd, hot map[string]struct{}, encrypt func(name string) bool, seal Sealer) ([]byte, error)
EncodeInlineDeltaSealed encodes ad as a DELTA record: byte-identical to an ordinary inline ad except that flagDelta is set, so a reader knows these are only the attributes one write changed and that the rest must be merged in from older versions of the key. The caller is responsible for having built ad from exactly the changed attributes. A Seal failure is reported as for EncodeInlineWithHotSealed.
func EncodeInlineWithHot ¶
EncodeInlineWithHot is EncodeInline with a populated hot header: attributes whose (case-folded) name is in hot are indexed by a (nameHash32, entries-relative offset-to-entry) pair, so Ad.LookupByName finds them without scanning. hot keys must be lower-cased. hot may be nil.
func EncodeInlineWithHotEnc
deprecated
added in
v0.7.0
func EncodeInlineWithHotEnc(dst []byte, ad *ast.ClassAd, hot map[string]struct{}, encrypt func(name string) bool, seal Sealer) []byte
EncodeInlineWithHotEnc is EncodeInlineWithHotSealed for a caller that cannot handle an error. It panics if a value cannot be sealed, rather than store it in the clear.
Deprecated: use EncodeInlineWithHotSealed, which reports a Seal failure as an error.
func EncodeInlineWithHotSealed ¶ added in v0.37.0
func EncodeInlineWithHotSealed(dst []byte, ad *ast.ClassAd, hot map[string]struct{}, encrypt func(name string) bool, seal Sealer) ([]byte, error)
EncodeInlineWithHotSealed is EncodeInlineWithHot with at-rest encryption: the value of any attribute for which encrypt(name) is true is sealed with seal and stored as an nEncrypted node (decodable only with the matching Opener). A predicate (rather than a set) lets the caller encrypt by rule -- e.g. HTCondor's private-attribute prefix -- not just an enumerable list. An encrypted attribute is never hot: it is opaque to the index/match fast path, so it is excluded from the hot header even if listed in hot. encrypt and seal must both be non-nil to encrypt anything.
If any value cannot be sealed it returns dst unchanged and an error wrapping ErrSealFailed: the ad is not encoded at all, and in particular that value is never written in the clear.
func EncodeStandalone ¶
EncodeStandalone returns a self-contained encoding that embeds a minimal intern table, so it can be decoded with DecodeStandalone alone (e.g. for transport out of a collection).
func EncodeWithHot ¶
EncodeWithHot is Encode with a populated hot header: attributes whose interned id is in hot are indexed by a (id, entries-relative offset) pair written before the body, so Ad.Lookup finds them in O(1) instead of scanning. The body layout is otherwise identical to Encode, so the result decodes with Decode and the hot header is a pure read-time accelerator. hot may be nil (equivalent to Encode).
func EncodeWithHotClosure ¶ added in v0.6.0
func EncodeWithHotClosure(dst []byte, ad *ast.ClassAd, t *InternTable, hot map[uint32]struct{}, closureComplete bool) []byte
EncodeWithHotClosure is EncodeWithHot that, when closureComplete, marks the ad with flagHotClosure -- a promise that hot holds the complete match closure, so a matcher can read it via ForEachHot without scanning. Set closureComplete only when hot truly contains every attribute the match reads from ad (see collections' astClosure).
func EncodeWithHotEnc
deprecated
added in
v0.23.0
func EncodeWithHotEnc(dst []byte, ad *ast.ClassAd, t *InternTable, hot map[uint32]struct{}, encrypt func(name string) bool, seal Sealer) []byte
EncodeWithHotEnc is EncodeWithHotSealed for a caller that cannot handle an error. It panics if a value cannot be sealed, rather than store it in the clear.
Deprecated: use EncodeWithHotSealed, which reports a Seal failure as an error.
func EncodeWithHotSealed ¶ added in v0.37.0
func EncodeWithHotSealed(dst []byte, ad *ast.ClassAd, t *InternTable, hot map[uint32]struct{}, encrypt func(name string) bool, seal Sealer) ([]byte, error)
EncodeWithHotSealed is EncodeWithHot for at-rest encryption: any attribute for which encrypt(name) is true is sealed with seal and stored as an nEncrypted node (its value's interned node encoding, sealed), exactly as EncodeInlineWithHotSealed does for inline ads. Encrypted attributes are never hot (never indexed), so they never enter the hot header. encrypt and seal must both be non-nil to encrypt anything; with seal nil this is EncodeWithHot.
If any value cannot be sealed it returns dst unchanged and an error wrapping ErrSealFailed: the ad is not encoded at all, and in particular that value is never written in the clear. Names the ad carries may already have been interned into t; an unused name there is harmless.
func ExprDepth ¶ added in v0.34.3
ExprDepth is the depth of v stored as an attribute's value: the deepest depth a reader reaches reading it, counted as MaxDepth counts it (a literal is 0). It follows the encoder rather than the syntax tree where the two differ -- a minus folded into the literal it negates is stored as that literal, depth 0 -- so it is exactly the depth the readers will meet.
func FoldEqualBytes ¶ added in v0.16.3
FoldEqualBytes reports whether the raw attribute-name bytes equal name case-insensitively (ASCII fold, matching ClassAd attribute-name semantics).
func FoldEqualNames ¶ added in v0.33.2
FoldEqualNames is FoldEqualBytes between two raw name byte slices, for a caller whose wanted names are themselves sub-slices of a record (a per-record reference closure) and would otherwise have to allocate a string per name to compare them.
func IsDelta ¶ added in v0.30.0
IsDelta reports whether a decoded (decompressed) record holds only changed attributes rather than a whole ad. A record too short to carry a header is not a delta -- callers treat anything unrecognized as a full record, which is the safe direction: a full record read as a delta would send the reader hunting for a base that does not exist.
func IsEncryptedNode ¶ added in v0.16.4
IsEncryptedNode reports whether node is an nEncrypted (at-rest sealed) node.
func IsLiteralNode ¶ added in v0.41.1
LiteralValue decodes node as a scalar literal, returning (lit, true) if node is one, or (_, false) if it is a list, record, or computed expression (which must be decoded via DecodeNode and evaluated). It is allocation-free except for the string case, which copies the string bytes. IsLiteralNode reports whether node is a scalar literal, WITHOUT decoding its value.
It answers exactly what `_, ok := LiteralValue(node)` answers -- same tags, same payload validity checks -- and for a STRING that is the whole difference: LiteralValue copies the string out of the node to return it, so asking "is this a literal?" through LiteralValue allocated the string and threw it away. On a grouped scan that is one allocation per record for a question whose answer is in the first byte.
Any tag it does not recognise falls through to NumberValue, which is the other half of what the scan calls a scalar (a parenthesised or signed number), so the two agree on every input.
func NameHash32 ¶ added in v0.16.3
NameHash32 exposes the case-insensitive 32-bit hash used by inline hot-header pairs, so a projected reader can precompute its wanted-name hashes.
func NameHash32Bytes ¶ added in v0.16.3
NameHash32Bytes is NameHash32 over raw name bytes (no string conversion).
func NodeLen ¶ added in v0.22.0
NodeLen returns the byte length of the single wire node at the start of b -- a scalar literal (int/real/bool/string/undefined/error) or a computed expression (op/ref/list/ record/func). It lets a caller that stores concatenated uvarint(id)+node entries (e.g. the per-segment schema's cold tail) split them without a separate length prefix. ok is false if b does not begin with a well-formed node.
b must come from an INTERNED (id-keyed) ad: a nested record literal's members are keyed the way the enclosing ad's attributes are, and nothing in the node itself says which, so a node from an inline-keyed ad is measured with NodeLenKeyed(b, true).
func NodeLenKeyed ¶ added in v0.33.3
NodeLenKeyed is NodeLen for a node from an ad of either key encoding: inline is the enclosing ad's (flagInlineNames), which every nested record literal inside the node shares. Measuring an inline-keyed node as id-keyed reads each member name's length as an id and the name's bytes as the member's value, so a node holding a record literal comes back malformed or mis-sized.
func OpenEncryptedNode ¶ added in v0.16.4
OpenEncryptedNode returns the plain node bytes sealed inside an nEncrypted node -- the sealed payload IS the value's ordinary node encoding, so opening it needs no re-encode. Returns (nil, false) if node is not an nEncrypted node, open is nil, or authentication fails. A relay that ships wire-form rows to a consumer without the data key uses this to emit the entry with its value in the clear (the consumer cannot open it).
func ParseExprToWire ¶ added in v0.3.0
func ParseExprToWire(input string, t *InternTable, dst []byte) ([]byte, error)
ParseExprToWire parses a standalone ClassAd expression from input and appends its wire node bytes to dst (interning names into t), returning the extended buffer. Output is byte-identical to encoding the reference-parsed ast.Expr. It returns ErrUnsupported for constructs it does not handle (so the caller can fall back to parser.ParseExpr), or a syntax error for malformed input.
func RecordMemberID ¶ added in v0.38.0
RecordMemberID returns the raw node bytes of the member with interned id `id` inside the record-literal node `node` (an nRecord node as returned by Lookup/ForEach), or (nil, false) if node is not a record literal, has no such member, or is malformed.
node must come from an ID-KEYED ad: a nested record's members are keyed the way the enclosing ad's attributes are and nothing in the node says which, exactly as NodeLenKeyed documents. An inline-keyed record is read with RecordMemberName. Reading one as the other takes a name's length for an id and its bytes for a value, which surfaces as a missing member or a malformed node rather than as another member's value -- but the caller is what knows the encoding, so it is the caller that must choose.
The hot header is skipped rather than consulted: it is an offset index into the entries that follow, so the linear walk finds every member either way, and a nested body's header is empty in everything this package writes.
func RecordMemberName ¶ added in v0.38.0
RecordMemberName is RecordMemberID for a record literal from an INLINE-KEYED ad, matching the member name case-insensitively as attribute names compare.
func ScalarListElems ¶ added in v0.38.0
ScalarListElems walks a list literal whose every element is a plain scalar literal -- UNDEFINED, a boolean, an integer, a real or a string, each in the one tag the encoder writes for it -- calling fn with each element's node in order. It reports the element count and true when node is exactly one such list, and false for anything else: not a list, a malformed one, trailing bytes, or any element that is not one of those literals (ERROR, a nested list or ad, an expression, a number spelled as a sign over a literal). fn returning false stops the walk, which then reports false.
It is the test a list must pass to be copied into a typed list column: what it accepts has one value per element, read without evaluating anything.
func SealedInlineFormRecoveries ¶ added in v0.34.0
func SealedInlineFormRecoveries() int64
SealedInlineFormRecoveries reports how many sealed values, since the process started, were read from an interned ad in the inline-names key form because they did not parse in the interned form (see readSealedPlain). Each is a value an earlier build copied unopened from an inline-names record into an interned one. It counts reads, not records: a record read twice counts twice, and a record stops counting once a rewrite re-seals it in the interned form.
func StringLiteralValue ¶
StringLiteralValue returns the raw value bytes of a string-literal node as a subslice of node (no copy), with ok=true, or (nil, false) if node is not a string literal. The returned bytes alias node and are valid only while node is. It lets a caller quote a string value straight from the wire (via ast.AppendQuoteStringBytes) without the string allocation LiteralValue's Str field would incur, and equally lets one COMPARE or HASH the bytes for nothing: a map lookup keyed `m[string(b)]` does not allocate, the compiler elides it, so a grouped scan can go from these bytes to its own table without the per-record copy LiteralValue's Str forces.
THE SLICE ALIASES node, which for a scan aliases a block's decompressed region. It is valid only until that region is reused, so a caller that RETAINS the value must copy it -- which is what interning does, and only on insert.
Types ¶
type Ad ¶
type Ad []byte
Ad is a zero-copy view over an encoded ad (the non-standalone in-store form: magic/version/flags header followed by the ad body). Lookup and ForEach walk the bytes without allocating ast nodes, resolving attributes by interned id.
func (Ad) AttrCount ¶ added in v0.6.0
AttrCount returns the number of attributes stored in the ad (0 if malformed). It reads only the header (past the hot index), so it is cheap enough to gate width- dependent decode strategies.
func (Ad) ForEach ¶
ForEach calls fn with each attribute's interned id and raw node bytes, in stored order, until fn returns false or the ad ends. It skips the hot header (which only duplicates body entries). Returns false if the ad is malformed.
func (Ad) ForEachHot ¶ added in v0.6.0
func (Ad) ForEachHotBuf ¶ added in v0.16.3
ForEachHot calls fn with the interned id and raw node bytes of each attribute recorded in the hot header, in header order, resolving each via its stored entries-relative offset (no scan). Returns false if fn stopped early or the ad is malformed. Cost is O(hotCount), independent of the total attribute count -- so a collection whose hot set is the match closure can read exactly the match-relevant attributes of a very wide ad without touching the cold ones. ForEachHotBuf is ForEachHot with caller-provided scratch for the header's (id, offset) pairs, grown as needed and returned for reuse -- a scan calling it once per ad performs no per-ad allocation (ForEachHot allocates two slices per call). scratch holds the pairs interleaved: id, offset, id, offset, ... Interned ads only: an inline ad's hot pairs are (nameHash32, offset-to-ENTRY) -- see ForEachHotInlineBuf -- so it reports false rather than mis-parse.
func (Ad) ForEachHotInlineBuf ¶ added in v0.16.3
func (a Ad) ForEachHotInlineBuf(scratch []uint32, fn func(hash uint32, name, node []byte) bool) ([]uint32, bool)
ForEachHotInlineBuf is ForEachHotBuf's inline-names counterpart: an inline ad's hot pairs are (nameHash32, offset) where the offset points at the whole attribute ENTRY (inline name, then node). It yields the folded name hash, the raw name bytes and the node bytes; the caller must verify the name (hashes can collide) with foldEqualBytes before trusting a match. scratch as in ForEachHotBuf. Reports false for an interned ad.
func (Ad) ForEachIDNode ¶ added in v0.16.3
ForEachIDNode iterates the ad's attribute entries as raw (interned id, node bytes) pairs, resolving nothing: the caller filters by id -- a projection's wanted-set test, a privacy flag -- before paying for name resolution or value rendering. Skipped entries cost one uvarint plus a TLV length hop. Returns false (calling fn for nothing) for an inline-names ad, whose entries carry no interned ids; fn returning false stops the walk early.
func (Ad) ForEachNameNode ¶ added in v0.16.3
ForEachNameNode iterates an inline-names ad's attribute entries as raw (name bytes, node bytes) pairs, allocating nothing -- the projection walk for a persistent collection filters on the name bytes before rendering anything. Reports false (calling fn for nothing) for an interned ad.
func (Ad) ForEachNamed ¶ added in v0.6.0
ForEachNamed calls fn with each attribute's name and raw node bytes. Inline-name ads (flagInlineNames, written by a persistent collection) yield their stored names directly; interned ads resolve each id to a name via t (an id t cannot resolve is skipped). Unlike ForEach -- which always reads the key as an interned id and so is wrong for inline ads -- this works for both encodings. Returns false if fn stopped early or the ad is malformed.
func (Ad) ForEachNamedRedact ¶ added in v0.16.3
ForEachNamedRedact is ForEachNamed except attributes whose name the table classified as private (see NewInternTableWithPrivacy) are skipped -- their nodes are never decoded and fn never sees them. Interned attributes are filtered by their precomputed per-id flag (O(1), no name resolution); inline attributes fall back to the table's privacy predicate on the stored name.
func (Ad) ForEachRaw ¶ added in v0.28.0
ForEachRaw calls fn with each attribute's interned id (0 for an inline ad), its name (empty for an interned ad), and its raw node bytes.
The two encodings key attributes differently, and a caller REWRITING an ad has to preserve whichever it was given -- ForEach reads the key as an id and is wrong for inline ads, while ForEachNamed resolves names through a table the rewriter may not want to touch.
func (Ad) HotClosureComplete ¶ added in v0.6.0
HotClosureComplete reports whether the ad's hot header holds the complete match closure (flagHotClosure): ForEachHot then yields every attribute the match reads, so the matcher can trust it without scanning the ad body.
func (Ad) Interned ¶ added in v0.46.0
Interned reports whether the ad is a well-formed header whose keys are interned ids rather than inline names, so reading it needs the table the ids index.
func (Ad) Lookup ¶
Lookup returns the raw node bytes for the attribute with the given interned id, or (nil, false) if absent or malformed. The returned slice aliases a; it can be decoded with DecodeNode or handed to the vm.
A popular ("hot") attribute is found in O(1) via the hot header: its node offset (relative to the start of the attribute-entries region) is read directly, skipping the linear scan of the body. Non-hot attributes fall back to a linear skip-scan.
func (Ad) LookupByName ¶
LookupByName returns the raw node bytes for the named attribute in an inline-names ad, or (nil, false) if absent, not an inline ad, or malformed. Attribute names are compared case-insensitively. A hot attribute is found in O(1) via the hot header (keyed by a case-folded name hash, verified against the stored name); others fall back to a linear scan.
func (Ad) SplitBody ¶ added in v0.28.0
SplitBody returns an ad's attribute-entry region and how many entries it holds, plus the header bytes that precede the body (magic, version, flags, and a standalone name table if present).
For a caller that needs to REBUILD an ad from parts rather than read one. The hot header is not returned: it is an index of (id, offset) pairs into the entry region, so any change to that region invalidates it, and it is a pure read accelerator that the store repopulates.
type DepthError ¶ added in v0.34.3
type DepthError struct {
Attr string // the top-level attribute holding the value
Depth int // the value's depth, counted as MaxDepth counts it
}
DepthError is the refusal of an attribute whose value nests deeper than MaxDepth. It unwraps to ErrTooDeep.
func (*DepthError) Error ¶ added in v0.34.3
func (e *DepthError) Error() string
func (*DepthError) Unwrap ¶ added in v0.34.3
func (e *DepthError) Unwrap() error
type InternTable ¶
type InternTable struct {
// contains filtered or unexported fields
}
InternTable maps attribute (and function) names to small integer ids so the wire form can reference names by uvarint id instead of repeating bytes.
Names are case-insensitive but case-preserving, matching ClassAd attribute semantics: "Owner", "owner" and "OWNER" all intern to the same id, and the id resolves back to the first-seen casing. The table is append-only: an id is stable for the life of the table (a collection compaction may build a fresh table with a remap, but never mutates ids in place).
func NewInternTable ¶
func NewInternTable() *InternTable
NewInternTable returns an empty table. Id 0 is a valid id (the first name interned); callers that need a sentinel should track presence separately.
func NewInternTableWithPrivacy ¶ added in v0.16.3
func NewInternTableWithPrivacy(privacy func(string) bool) *InternTable
NewInternTableWithPrivacy returns an empty table whose entries are flagged private when privacy(name) is true, evaluated once per unique name at intern time. Redacting iterators (Ad.ForEachNamedRedact) skip flagged ids, so a serialization path can strip secrets in O(1) per attribute instead of re-classifying every attribute name of every ad. A nil privacy flags nothing.
func (*InternTable) Intern ¶
func (t *InternTable) Intern(name string) uint32
Intern returns the id for name, allocating a new id (and recording name's casing) the first time a fold-equal name is seen.
func (*InternTable) InternBytes ¶ added in v0.30.0
func (t *InternTable) InternBytes(name []byte) uint32
InternBytes is Intern for a caller holding the name as bytes -- a wire-level transcode, which never has it as a string. Taking the string conversion at the call site would allocate per attribute per record; indexing the map with string(name) directly does not, because the compiler elides the copy for a map index. Only a name never seen before pays for one, in Intern.
func (*InternTable) InternName ¶ added in v0.46.0
func (t *InternTable) InternName(name []byte) (uint32, bool)
InternName is InternBytes as a NameInterner. It never refuses.
func (*InternTable) IsPrivate ¶ added in v0.16.3
func (t *InternTable) IsPrivate(id uint32) bool
IsPrivate reports whether id's name was classified private by the table's privacy predicate when it was interned. Lock-free; an unallocated id is not private. O(1) -- this is the point of precomputing the flag: a redacting serializer checks one bool per attribute instead of re-classifying its name.
func (*InternTable) Len ¶
func (t *InternTable) Len() int
Len returns the number of interned names (== the next id to be allocated).
func (*InternTable) LookupID ¶
func (t *InternTable) LookupID(name string) (uint32, bool)
LookupID returns the id for name if it has already been interned, without allocating a new one (a read-only counterpart to Intern). Used by the query fast path to resolve an attribute name to its id without polluting the table with names that are not attributes.
func (*InternTable) Name ¶
func (t *InternTable) Name(id uint32) (string, bool)
Name returns the canonical (first-seen) casing for id, or ("", false) if id was never allocated.
func (*InternTable) Names ¶ added in v0.23.0
func (t *InternTable) Names() []string
snapshotNames returns a copy of the id->name slice, for embedding a standalone intern table into a self-contained ad. Names returns the canonical (first-seen casing) names in id order, so Names()[id] is the name for id. Re-interning these in order into an empty table reproduces the exact id assignment -- the basis for serializing/reloading the table.
type Literal ¶
Literal is a decoded scalar literal value, described without depending on the classad package so wire stays decoupled from it. Non-scalar nodes (lists, records, and computed expressions) are not literals.
func LiteralValue ¶
func NumberValue ¶ added in v0.32.0
NumberValue returns the number a node denotes without evaluating anything: an int or real literal under any parentheses and unary minus or plus.
The encoder folds `-<numeric literal>` into a signed literal, so a node written today spells a negative number as a literal and LiteralValue alone reads it. This stays because a record is read as it was written: a segment sealed before that fold still carries `-5` as unary minus over 5, as does any spelling the fold leaves alone (`-(5)`, `+5`), and a reader summarizing numeric values -- a zone map -- would otherwise have to treat those as expressions.
The result is what the evaluator computes for the node: minus negates (an int wraps, as int64 negation does), plus is the identity. Any other operand -- a boolean included, which the evaluator's unary minus rejects -- is not a number here.
type MergeScratch ¶ added in v0.30.0
type MergeScratch struct {
// contains filtered or unexported fields
}
MergeScratch holds AppendAdMergedInline's per-call scratch: the overlay attributes' names and entry byte ranges. Reused across merges so a merge allocates only its output.
func (*MergeScratch) Release ¶ added in v0.30.0
func (s *MergeScratch) Release()
Release is Reset plus dropping the references the backing arrays still hold. The names and entries are slices INTO the caller's ads, so a pooled scratch that keeps them keeps those ads alive; a caller returning a scratch to a pool must Release, not Reset.
func (*MergeScratch) Reset ¶ added in v0.30.0
func (s *MergeScratch) Reset()
Reset clears the scratch, keeping its backing arrays.
type NameInterner ¶ added in v0.46.0
NameInterner assigns the ids a transcode writes in place of names. A false ok refuses the name, and the transcode then refuses the whole record -- which is how a caller holding a bounded table declines a record that would grow it past its bound.
type NodeClass ¶ added in v0.34.1
type NodeClass uint8
NodeClass classifies a node by the kind of thing it holds, which is coarser than the tag table and finer than LiteralValue's ok flag.
LiteralValue already answers "is this a scalar literal, and what is it"; everything it rejects comes back as one undifferentiated false. That is the right answer for a reader deciding whether it can take a fast path, and the wrong one for a caller PROFILING what an attribute holds across many records, which needs to tell apart the reasons a value is not a scalar: an expression can be evaluated to a scalar, a list or a nested ad cannot, and an encrypted node must not be looked at at all.
Deliberately NOT unwrapped: nParen. `(5)` is a parenthesized expression, not an int literal, and classifying it as one here would disagree with the storage layer -- LiteralValue rejects it, so nodeKind calls it akNone and the columnar encoder escapes it to the cold tail. A profile is measured against what storage does, so it has to classify the way storage classifies.
const ( // ClassInvalid is an empty node or a tag this package does not write. ClassInvalid NodeClass = iota ClassUndefined ClassError ClassBool ClassInt ClassReal ClassString // ClassList and ClassRecord are composite VALUES: already evaluated, and with no // scalar form to coerce to. ClassList ClassRecord // ClassEncrypted is an at-rest-encrypted value (nEncrypted). The class is as far as // a caller without a Sealer may go: the plaintext's own class is deliberately not // reported, because reaching through to it is how a redacted path leaks a value it // was supposed to withhold. ClassEncrypted // ClassExpr is an unevaluated expression -- a reference, operator, call, // conditional, select, subscript or parenthesized form. It may evaluate to any // class above, including a scalar, which is why it is worth distinguishing from // ClassList and ClassRecord rather than lumping all non-literals together. ClassExpr )
func ClassifyNode ¶ added in v0.34.1
ClassifyNode returns the node's class. It reads only the tag byte, so it is O(1) and does not validate the payload: a node whose tag is known but whose body is truncated is classified by its tag, and it is the decoders (which do validate) that reject it.
type NodeEmitter ¶ added in v0.3.0
type NodeEmitter struct {
// contains filtered or unexported fields
}
NodeEmitter builds one wire expression node into a reusable buffer, for a parser that emits wire directly from text rather than via an ast.Expr. The wire form is prefix (a node's tag precedes its children), but expression parsing is infix, so a caller records Mark() before parsing an operand and, once the enclosing operator is known, calls a Wrap* method to insert the operator's tag/header before that already-emitted operand. Names are interned as they are emitted.
Byte-for-byte identical to encoder.node for the same expression, so a node it builds decodes with DecodeNode.
func NewInlineNodeEmitter ¶ added in v0.3.0
func NewInlineNodeEmitter() *NodeEmitter
NewInlineNodeEmitter returns an emitter writing inline-name node variants (no interning), matching the persistent-store encoding.
func NewNodeEmitter ¶ added in v0.3.0
func NewNodeEmitter(t *InternTable) *NodeEmitter
NewNodeEmitter returns an emitter interning names into t.
func (*NodeEmitter) AttrRef ¶ added in v0.3.0
func (e *NodeEmitter) AttrRef(scope byte, name string)
AttrRef emits an attribute reference with the given scope (ast.AttributeScope).
func (*NodeEmitter) Bool ¶ added in v0.3.0
func (e *NodeEmitter) Bool(v bool)
func (*NodeEmitter) Bytes ¶ added in v0.3.0
func (e *NodeEmitter) Bytes() []byte
Bytes returns the emitted node bytes (valid until the next Reset).
func (*NodeEmitter) Err ¶ added in v0.3.0
func (e *NodeEmitter) Err()
func (*NodeEmitter) FoldNegate ¶ added in v0.33.0
func (e *NodeEmitter) FoldNegate(mark int)
FoldNegate collapses a just-emitted `-<numeric literal>` at [mark:end] into the single signed literal node it denotes, by the same rule and the same function the reference encoder applies to the equivalent ast.UnaryOp (see foldNegatedLiteral). Anything else at mark is left alone.
It runs after the operand is emitted rather than deciding on the next token, because whether the minus applies to a bare literal is not known until the operand is parsed: in `- 5[0]` the operand is the subscript, not the 5, exactly as the reference grammar binds it.
The two encoders are required to be byte-identical (TestParseExprToWireMatchesReference), so this is not an optimization -- a fold on one side only is a divergence.
func (*NodeEmitter) FuncNameID ¶ added in v0.3.0
func (e *NodeEmitter) FuncNameID(name string) uint32
FuncNameID interns a function name and returns its id. A caller emits a call by interning the name with FuncNameID *before* parsing/emitting the argument nodes (so the name's id is assigned ahead of the args, matching the reference encoder's pre-order), then calls WrapFuncID after the args. Returns 0 in inline mode, where the name is written verbatim and no interning happens.
func (*NodeEmitter) Int ¶ added in v0.3.0
func (e *NodeEmitter) Int(v int64)
func (*NodeEmitter) Mark ¶ added in v0.3.0
func (e *NodeEmitter) Mark() int
Mark returns the current buffer position, to pass to a later Wrap* call.
func (*NodeEmitter) Real ¶ added in v0.3.0
func (e *NodeEmitter) Real(v float64)
func (*NodeEmitter) RecordKey ¶ added in v0.3.0
func (e *NodeEmitter) RecordKey(name string)
RecordKey emits a record attribute key -- an interned id, or the inline name -- matching the reference encoder's putKey. Call before emitting the attribute's value node.
func (*NodeEmitter) Reset ¶ added in v0.3.0
func (e *NodeEmitter) Reset()
Reset clears the emitter for another node, keeping the buffer.
func (*NodeEmitter) Str ¶ added in v0.3.0
func (e *NodeEmitter) Str(v string)
func (*NodeEmitter) UnOp ¶ added in v0.3.0
func (e *NodeEmitter) UnOp(op string)
UnOp emits a unary-operator tag; the operand is emitted after (source-prefix, so no insertion needed).
func (*NodeEmitter) Undef ¶ added in v0.3.0
func (e *NodeEmitter) Undef()
func (*NodeEmitter) WrapBinOp ¶ added in v0.3.0
func (e *NodeEmitter) WrapBinOp(mark int, op string)
WrapBinOp turns the operand at [mark:end] plus the operand appended after it into a binary-op node by inserting the op tag at mark.
func (*NodeEmitter) WrapCond ¶ added in v0.3.0
func (e *NodeEmitter) WrapCond(mark int)
WrapCond wraps cond+true+false (cond at mark, true/false appended after) into a conditional node.
func (*NodeEmitter) WrapElvis ¶ added in v0.3.0
func (e *NodeEmitter) WrapElvis(mark int)
WrapElvis wraps left+right (left at mark, right appended after) into an elvis node.
func (*NodeEmitter) WrapFuncID ¶ added in v0.3.0
func (e *NodeEmitter) WrapFuncID(mark int, name string, id uint32, argc int)
WrapFuncID wraps the argc argument nodes at [mark:end] into a function call, using the name id pre-interned by FuncNameID (interned mode) or name verbatim (inline mode).
func (*NodeEmitter) WrapList ¶ added in v0.3.0
func (e *NodeEmitter) WrapList(mark, count int)
WrapList wraps the count elements at [mark:end] into a list node.
func (*NodeEmitter) WrapParen ¶ added in v0.3.0
func (e *NodeEmitter) WrapParen(mark int)
WrapParen wraps the operand at [mark:end] in an explicit-parenthesis node.
func (*NodeEmitter) WrapRecord ¶ added in v0.3.0
func (e *NodeEmitter) WrapRecord(mark, attrCount int)
WrapRecord wraps the attrCount (key, node) pairs at [mark:end] into a record node by inserting the record tag and ad-body header (hotCount 0, attrCount) at mark. A record carries no hot header.
func (*NodeEmitter) WrapSelect ¶ added in v0.3.0
func (e *NodeEmitter) WrapSelect(mark int, attr string)
WrapSelect wraps the record at [mark:end] into a select of attr: the select tag is inserted at mark and the attribute id/name appended after the record (matching the nSelect <record> <attr> layout).
func (*NodeEmitter) WrapSubscript ¶ added in v0.3.0
func (e *NodeEmitter) WrapSubscript(mark int)
WrapSubscript wraps container+index (container at mark, index appended after).
type NodeRefs ¶ added in v0.33.3
type NodeRefs struct {
IDs []uint32 // interned-id references (nAttrRef), unscoped or MY.
Names [][]byte // inline-name references (nAttrRefStr), unscoped or MY.; sub-slices of the node
// Sealed reports that the node holds a sealed value. The walk cannot see its plaintext and
// contributes nothing for it: by the encryption-at-rest contract a sealed value refers to no
// other attribute, and no reader follows a reference inside one. It is reported for a caller
// that wants to know a sealed value was there, not because the set is incomplete.
Sealed bool
}
NodeRefs is the reference set of one node, for a caller that must know it is COMPLETE: one deciding whether a narrowed ad evaluates exactly as the whole ad would. AppendNodeRefIDs and AppendNodeRefNames are deliberately lenient -- they serve a projection that ships what it finds -- and stay silent about what they cannot see. This reports it instead.
type Sealer ¶ added in v0.7.0
type Sealer interface {
Seal(plaintext []byte) (nonce, ciphertext []byte, err error)
Open(nonce, ciphertext []byte) (plaintext []byte, err error)
}
Sealer encrypts and decrypts an attribute value's encoded bytes for at-rest encryption (the nEncrypted node). A collection supplies one backed by a segment's data-encryption key; the wire layer stays crypto-agnostic. Seal returns a fresh nonce and ciphertext; Open reverses it and authenticates (errors on tampering or a wrong key). It is used from a single goroutine per encode/decode pass. Implementations must be safe for concurrent use: both the parallel query scan and the parallel wire scan open sealed values from several goroutines at once, and nothing serializes them. The built-in dataKeySealer satisfies this through crypt.AEAD, which never hands one cipher to two goroutines at once.
type StreamEncoder ¶
type StreamEncoder struct {
// contains filtered or unexported fields
}
StreamEncoder builds a wire ad one attribute at a time, so a caller decoding an external serialization (e.g. old-ClassAd lines from a socket) can emit wire form directly without first materializing an ast.ClassAd. Scalar literals are written with no AST at all (Int/Real/String/Bool/Undefined/Error); only genuinely computed values need Expr (an ast.Expr subtree).
A StreamEncoder is reusable: Reset() clears it for the next ad, retaining the backing buffers.
func NewInlineStreamEncoder ¶
func NewInlineStreamEncoder(hotNames map[string]struct{}) *StreamEncoder
NewInlineStreamEncoder returns a StreamEncoder that writes inline names (no interning), for the persistent store. hotNames (may be nil) are the case-folded names to front-load in the hot header.
func NewStreamEncoder ¶
func NewStreamEncoder(t *InternTable, hot map[uint32]struct{}) *StreamEncoder
NewStreamEncoder returns an encoder interning names into t. hot (may be nil) is the set of interned ids to front-load in the hot header.
func (*StreamEncoder) Bool ¶
func (s *StreamEncoder) Bool(name string, v bool)
Bool writes a boolean attribute.
func (*StreamEncoder) Bytes ¶
func (s *StreamEncoder) Bytes(dst []byte) []byte
Bytes assembles the encoded ad (appending to dst) from the attributes written since the last Reset. The result is byte-identical to EncodeWithHot of the same attributes and decodes with Decode.
func (*StreamEncoder) Count ¶
func (s *StreamEncoder) Count() int
Count returns the number of attributes written so far.
func (*StreamEncoder) Err ¶ added in v0.34.3
func (s *StreamEncoder) Err() error
Err reports the first attribute written since Reset that cannot be stored: a value nesting deeper than MaxDepth, as a *DepthError (errors.Is ErrTooDeep). The refused attribute is not written, but the ad as a whole must not be stored either -- it would silently lack the attribute -- so a caller checks Err before Bytes.
func (*StreamEncoder) Error ¶
func (s *StreamEncoder) Error(name string)
Error writes an error attribute.
func (*StreamEncoder) Expr ¶
func (s *StreamEncoder) Expr(name string, e ast.Expr)
Expr writes a computed (non-literal) attribute from an ast.Expr subtree. A value deeper than MaxDepth is refused instead (see Err).
func (*StreamEncoder) ExprWire ¶ added in v0.3.0
func (s *StreamEncoder) ExprWire(name, val string) error
ExprWire writes a computed (non-literal) attribute by parsing its expression text straight to wire via the native parser -- no ast.Expr. It leaves no partial entry if the native parser cannot handle the expression (a record, an int64-min magnitude, ...): it rolls the buffer back and returns the error, so the caller can fall back to Expr(name, parser.ParseExpr(val)). Interned names added before a rollback are harmless (unused ids in a shared table).
A value deeper than MaxDepth is rolled back the same way, returning ErrTooDeep: the fallback's Expr then refuses it with the attribute and its depth (see Err).
func (*StreamEncoder) Int ¶
func (s *StreamEncoder) Int(name string, v int64)
Int writes an integer attribute.
func (*StreamEncoder) Real ¶
func (s *StreamEncoder) Real(name string, v float64)
Real writes a real attribute.
func (*StreamEncoder) Reset ¶
func (s *StreamEncoder) Reset()
Reset clears the encoder for another ad, keeping its buffers.
func (*StreamEncoder) SetHot ¶
func (s *StreamEncoder) SetHot(hot map[uint32]struct{})
SetHot replaces the hot-id set (e.g. after the store refreshes popularity).
func (*StreamEncoder) String ¶
func (s *StreamEncoder) String(name, v string)
String writes a string attribute (v is the unescaped value).
func (*StreamEncoder) StringBytes ¶
func (s *StreamEncoder) StringBytes(name string, v []byte)
StringBytes writes a string attribute whose (already unescaped) value is in v. It is String for a caller holding the value in a reused byte buffer, so no intermediate string is allocated.
func (*StreamEncoder) Undefined ¶
func (s *StreamEncoder) Undefined(name string)
Undefined writes an undefined attribute.
type SubsetScratch ¶ added in v0.16.4
type SubsetScratch struct {
// contains filtered or unexported fields
}
SubsetScratch holds AppendAdSubsetInlineHotFirst's per-scan scratch (hot pairs, copied-entry offsets), reused across ads so assembly allocates nothing per ad.