Documentation
¶
Overview ¶
Package controlplane is the document format of the files that the Semaphore relay proxy reads from a store (for example S3): the flag files, the segments files and the documents that the relay builds of them (the flag-set documents and the manifest of a generation, which no program writes for the relay any more).
A program that writes a flag file or a segments file fills the exported structs, calls a Marshal function and writes the bytes. The relay decodes the same bytes with an Unmarshal function and runs the same Validate functions, so "valid for the writer" and "accepted by the relay" are one definition.
Format ¶
The manifest and the flag-set documents are YAML (JSON is accepted and can be written with the JSON variants) and start with a header: apiVersion "semaphore/v1" and kind "Manifest" or "FlagSet". Flag objects are headerless: a flag file is a top-level map keyed by flag names, which is the flag file format that the engine loads today (flag format v1). Their version and text format are listed in the manifest entry.
Output is deterministic: fields keep the order of the structs, map keys are sorted, no anchors or aliases are written and every string that a YAML 1.1 or 1.2 reader could read as another type (yes, no, on, off, y, n, 007, 1e3, 2026-01-01, null, ...) is double quoted.
Reading and validating ¶
The Unmarshal functions read YAML and JSON through one reader. Field names are case sensitive; duplicate keys, non-string keys, NaN, infinity, a second YAML document and an integer field with a fraction or an overflow are a *DecodeError, which never contains the text of a value. A float keeps its type (written 2.0) and an integer stays an integer, in both formats. Anchors, aliases and merge keys are accepted on read and never written.
The Validate functions return a *ValidationError whose FieldErrors carry a stable Code, the Kind of the entry (object, flag set, flag, document), its Name and Index, so a reader can keep the good entries and drop the bad ones without parsing text. Of two objects or flag sets with one name, and of an API key held by two flag sets, the first in document order keeps it and the later one has the problem. An object with a newer content version is an entry problem (CodeUnsupportedVersion), not a failure of the manifest. A wrong kind or apiVersion rejects the document whole (*KindError, *UnsupportedVersionError; they match ErrInvalid too).
Compatibility ¶
Within a version only additive optional fields are allowed. Readers ignore unknown fields of documents (the Unmarshal functions report them in DecodeInfo) so an older relay reads the documents of a newer writer. A document with an unsupported apiVersion or the wrong kind is rejected whole. A breaking change is a new apiVersion with new types side by side.
The Go API of this package follows semantic versioning from its first release. It is the only public, stability-guaranteed Go package of the module; the production files import only the standard library and gopkg.in/yaml.v3.
Example ¶
A flag file written by a Go program: validate the flags as the relay does, marshal them, and read them back.
package main
import (
"fmt"
"github.com/blackbirdworks/semaphore/controlplane"
)
func main() {
flags := controlplane.Flags{"new-cart": {
Variations: map[string]any{"enabled": true, "disabled": false},
DefaultRule: &controlplane.Rule{Variation: new("disabled")},
Targeting: []controlplane.Rule{
{Name: new("pilot"), Query: new(`plan eq "pilot"`), Variation: new("enabled")},
},
}}
err := controlplane.ValidateFlags(flags)
if err != nil {
fmt.Println(err)
return
}
body, err := controlplane.MarshalFlags(flags)
if err != nil {
fmt.Println(err)
return
}
// Write body to the flag file that a flag set file names, for example flags/cart.yaml.
back, _, err := controlplane.UnmarshalFlags(body, controlplane.FormatYAML)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(len(back), "flag:", back["new-cart"].Variations["enabled"])
}
Output: 1 flag: true
Index ¶
- Constants
- Variables
- func MarshalFlagSet(d *FlagSetDocument) ([]byte, error)
- func MarshalFlagSetJSON(d *FlagSetDocument) ([]byte, error)
- func MarshalFlags(f Flags) ([]byte, error)
- func MarshalFlagsJSON(f Flags) ([]byte, error)
- func MarshalManifest(m *Manifest) ([]byte, error)
- func MarshalManifestJSON(m *Manifest) ([]byte, error)
- func MarshalSegments(d *SegmentsDocument) ([]byte, error)
- func MarshalSegmentsJSON(d *SegmentsDocument) ([]byte, error)
- func ObjectKey(sum Checksum, ext string) (string, error)
- func StepsExceeded(steps int) bool
- func UnmarshalFlagSet(data []byte) (*FlagSetDocument, DecodeInfo, error)
- func UnmarshalFlags(data []byte, format string) (Flags, DecodeInfo, error)
- func UnmarshalManifest(data []byte) (*Manifest, DecodeInfo, error)
- func UnmarshalSegments(data []byte) (*SegmentsDocument, DecodeInfo, error)
- func ValidateFlagSet(doc *FlagSetDocument, manifest *Manifest) error
- func ValidateFlagSetDocuments(docs []*FlagSetDocument, manifest *Manifest) error
- func ValidateFlags(flags Flags) error
- func ValidateManifest(manifest *Manifest, opts ...ValidateOption) error
- func ValidateObject(entry *ManifestObject, body []byte) (DecodeInfo, *FlagSetDocument, error)
- func ValidateSegments(doc *SegmentsDocument) error
- func VerifyChecksum(data []byte, want Checksum) error
- type Checksum
- type ChecksumMismatchError
- type Code
- type DecodeError
- type DecodeInfo
- type EntryKind
- type Experimentation
- type FieldError
- type Flag
- type FlagCheck
- type FlagEntry
- type FlagSet
- type FlagSetDocument
- type Flags
- type FlagsTree
- func (t *FlagsTree) CheckEntry(entry *FlagEntry) (FlagCheck, error)
- func (t *FlagsTree) Decode(out any) error
- func (*FlagsTree) DecodeEntries(entries []FlagEntry, out any) error
- func (t *FlagsTree) Entries() ([]FlagEntry, bool)
- func (t *FlagsTree) ReadEntries(entries []FlagEntry) (Flags, []int, error)
- func (t *FlagsTree) Single() bool
- func (t *FlagsTree) UnknownFields() (DecodeInfo, error)
- type KindError
- type Manifest
- type ManifestObject
- type MemberList
- type ProgressiveRollout
- type ProgressiveRolloutStep
- type Rule
- type ScheduledStep
- type SegmentCache
- type SegmentDefinition
- type SegmentVersion
- type SegmentsDocument
- type UnsupportedVersionError
- type ValidateOption
- type ValidationError
Examples ¶
Constants ¶
const ( // MaxSegmentMembers is the most members of a static segment. MaxSegmentMembers = 100_000 // MaxSegmentMemberBytes is the most bytes of the members of one static segment (the sum of their lengths). MaxSegmentMemberBytes = 4 << 20 // MaxSegmentMemberLen is the longest member of a static segment. MaxSegmentMemberLen = 4096 // MaxSegmentNameLen is the longest name of a segment. MaxSegmentNameLen = 64 // MaxSegmentKeyLen is the longest key or version of a dynamic segment. MaxSegmentKeyLen = 512 // MinVersionInterval is the shortest poll interval of a version key. MinVersionInterval = 100 * time.Millisecond // MaxSegmentDuration is the longest interval or time-to-live of a segment. MaxSegmentDuration = 24 * time.Hour // MaxCacheEntries is the most cache entries that a lookup segment may ask for. MaxCacheEntries = 10_000_000 )
The limits of a segments document and of the segments in it.
const ( // SegmentModeSnapshot pulls the whole member set and keeps it in memory. It is the default. SegmentModeSnapshot = "snapshot" // SegmentModeLookup asks the store for each evaluation. SegmentModeLookup = "lookup" // SegmentLayoutSet stores the members in one set. SegmentLayoutSet = "set" // SegmentLayoutKeys stores one key per member (lookup only). SegmentLayoutKeys = "keys" // SegmentMissingNotMember: a segment that does not exist has no member. It is the default. SegmentMissingNotMember = "notMember" // SegmentMissingUnknown: a segment that does not exist is unknown. SegmentMissingUnknown = "unknown" )
The values of the fields of a segment.
const ( // APIVersion is the document version this package writes. APIVersion = "semaphore/v1" // DocumentKindManifest is the kind of a manifest document. DocumentKindManifest = "Manifest" // DocumentKindFlagSet is the kind of a flag-set document. DocumentKindFlagSet = "FlagSet" // DocumentKindSegments is the kind of a segments document. DocumentKindSegments = "Segments" // KindFlags is the manifest object kind of a flag file. KindFlags = "flags" // KindFlagSets is the manifest object kind of a flag-set document. KindFlagSets = "flagSets" // KindSegments is the manifest object kind of a segments document. KindSegments = "segments" // FormatYAML is the YAML text format of an object. FormatYAML = "yaml" // FormatJSON is the JSON text format of an object. FormatJSON = "json" // FormatTOML is the TOML text format of an object (flag files only; this package does not read it). FormatTOML = "toml" // AlgorithmSHA256 is the only checksum algorithm of schema v1. AlgorithmSHA256 = "sha256" // ObjectVersion1 is the version of the content schema of an object: the headerless flag format. ObjectVersion1 = 1 )
const ( // DefaultMaxObjectBytes is the largest size of one object (16 MiB). DefaultMaxObjectBytes int64 = 16 << 20 // DefaultMaxTotalBytes is the largest sum of the sizes of the distinct objects of a manifest (1 GiB). DefaultMaxTotalBytes int64 = 1 << 30 // DefaultMaxManifestBytes is the largest size of the marshalled manifest (16 MiB). DefaultMaxManifestBytes int64 = 16 << 20 )
The limits the relay reader applies to what it downloads. A publisher must stay inside them, or the reader rejects what was published.
const DefaultMaxObjects = 20000
DefaultMaxObjects is the default bound on the number of objects of a manifest (validation and memory). The relay makes it a setting with the same default; pass WithMaxObjects to change it.
const NoIndex = -1
NoIndex is the Index of a FieldError whose entry has no position in a list.
Variables ¶
var ( // ErrUnsupportedAPIVersion is matched by an UnsupportedVersionError: a document whose apiVersion this // package does not read. ErrUnsupportedAPIVersion = errors.New("controlplane: unsupported apiVersion") // ErrWrongKind is matched by a KindError: a document of another kind than the one asked for. ErrWrongKind = errors.New("controlplane: wrong document kind") // ErrInvalid is matched by every ValidationError, UnsupportedVersionError and KindError. ErrInvalid = errors.New("controlplane: invalid document") // ErrChecksumMismatch is returned by VerifyChecksum when the bytes do not match. ErrChecksumMismatch = errors.New("controlplane: checksum mismatch") // ErrUnsupportedChecksum is returned for a checksum algorithm other than sha256. ErrUnsupportedChecksum = errors.New("controlplane: unsupported checksum algorithm") // ErrInvalidChecksum is returned for a checksum value that is not 64 lower-case hex characters. ErrInvalidChecksum = errors.New("controlplane: invalid checksum value") // ErrInvalidExtension is returned by ObjectKey for an extension that is not [a-z0-9]+. ErrInvalidExtension = errors.New("controlplane: invalid object extension") // ErrNilDocument is returned when a nil document is marshalled or validated. ErrNilDocument = errors.New("controlplane: nil document") // ErrUnsupportedFormat is returned for a text format this package does not read (for example toml). ErrUnsupportedFormat = errors.New("controlplane: unsupported format") // ErrUnsupportedValue is returned by a Marshal function for a value that cannot be written: NaN, infinity, // a map with non-string keys, a string that is not valid UTF-8, or a type outside the format. ErrUnsupportedValue = errors.New("controlplane: unsupported value") // ErrDecode is matched by every DecodeError: a document that is not readable. ErrDecode = errors.New("controlplane: decode") )
Functions ¶
func MarshalFlagSet ¶
func MarshalFlagSet(d *FlagSetDocument) ([]byte, error)
MarshalFlagSet writes d as deterministic YAML. See MarshalManifest for the header rules.
func MarshalFlagSetJSON ¶
func MarshalFlagSetJSON(d *FlagSetDocument) ([]byte, error)
MarshalFlagSetJSON writes d as deterministic indented JSON.
func MarshalFlags ¶
MarshalFlags writes a flag file as deterministic YAML. The file has no header.
func MarshalFlagsJSON ¶
MarshalFlagsJSON writes a flag file as deterministic indented JSON.
func MarshalManifest ¶
MarshalManifest writes m as deterministic YAML. An empty APIVersion or Kind is filled in; any other value than the current one is an error. m is not changed and not validated.
func MarshalManifestJSON ¶
MarshalManifestJSON writes m as deterministic indented JSON: the same document, field order and number types as MarshalManifest.
func MarshalSegments ¶
func MarshalSegments(d *SegmentsDocument) ([]byte, error)
MarshalSegments writes d as deterministic YAML. See MarshalManifest for the header rules.
func MarshalSegmentsJSON ¶
func MarshalSegmentsJSON(d *SegmentsDocument) ([]byte, error)
MarshalSegmentsJSON writes d as deterministic indented JSON.
func ObjectKey ¶
ObjectKey returns the immutable content-addressed key of an object: objects/sha256/<2 hex>/<hex>.<ext>. The checksum must be a valid sha256 (ErrUnsupportedChecksum, ErrInvalidChecksum) and ext must match [a-z0-9]+ without a dot (ErrInvalidExtension), so a key can never contain a path separator or a ".." element.
func StepsExceeded ¶ added in v1.3.0
StepsExceeded tells whether the checks of a file whose entries took steps in all are more than the check of a whole file allows (one step is taken by the top level itself): such a file reports no unknown fields.
func UnmarshalFlagSet ¶
func UnmarshalFlagSet(data []byte) (*FlagSetDocument, DecodeInfo, error)
UnmarshalFlagSet reads a flag-set document from YAML or JSON. See UnmarshalManifest.
func UnmarshalFlags ¶
func UnmarshalFlags(data []byte, format string) (Flags, DecodeInfo, error)
UnmarshalFlags reads a flag file. format is "yaml" (or empty) or "json"; toml is not read by this package (ErrUnsupportedFormat). Input that is valid JSON is read as JSON whatever the format says, as JSON is YAML; format "json" requires valid JSON. A flag file has no header: any top-level map is flag format v1.
func UnmarshalManifest ¶
func UnmarshalManifest(data []byte) (*Manifest, DecodeInfo, error)
UnmarshalManifest reads a manifest from YAML or JSON. It rejects another kind or an unsupported apiVersion whole (*KindError, *UnsupportedVersionError) and reports unknown fields in DecodeInfo. It does not validate; call ValidateManifest. The rules of every Unmarshal function:
- YAML and JSON go through one reader: field names are case sensitive, duplicate keys, non-string keys, NaN, infinity, a second YAML document and trailing JSON data are a *DecodeError;
- an integer field rejects a fraction and an overflow; an integer value keeps its type (int, or uint64 above the int64 range) and a float keeps float64, in both formats;
- anchors, aliases and merge keys are accepted on read (and never written);
- an error never contains the text of a value.
Example ¶
package main
import (
"fmt"
"github.com/blackbirdworks/semaphore/controlplane"
)
func main() {
doc := []byte("apiVersion: semaphore/v1\nkind: Manifest\nchannel: prod\ngeneration: 3\nfuture: true\nobjects: []\n")
manifest, info, err := controlplane.UnmarshalManifest(doc)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(manifest.Channel, manifest.Generation, info.UnknownFields)
}
Output: prod 3 [future]
Example (UnsupportedVersion) ¶
package main
import (
"fmt"
"github.com/blackbirdworks/semaphore/controlplane"
)
func main() {
_, _, err := controlplane.UnmarshalManifest([]byte("apiVersion: semaphore/v2\nkind: Manifest\n"))
fmt.Println(err)
}
Output: controlplane: unsupported apiVersion: got "semaphore/v2", supported "semaphore/v1"
func UnmarshalSegments ¶
func UnmarshalSegments(data []byte) (*SegmentsDocument, DecodeInfo, error)
UnmarshalSegments reads a segments document from YAML or JSON. See UnmarshalManifest.
func ValidateFlagSet ¶
func ValidateFlagSet(doc *FlagSetDocument, manifest *Manifest) error
ValidateFlagSet checks a flag-set document. When manifest is not nil every source must name an object of kind flags of the manifest. Header failures are returned as for ValidateManifest.
Problems name the flag set (Kind EntryFlagSet, Name, Index) so a caller can keep the good flag sets. Of two flag sets with one name, and of an API key held by two flag sets, the first in document order keeps it and the later flag set has the problem (CodeDuplicateName, CodeDuplicateKey). The text of an API key is never printed.
func ValidateFlagSetDocuments ¶
func ValidateFlagSetDocuments(docs []*FlagSetDocument, manifest *Manifest) error
ValidateFlagSetDocuments checks a set of flag-set documents together, as the relay sees them: the flag sets of every document share one namespace. On top of what ValidateFlagSet checks per document, a flag-set name used in two documents is CodeDuplicateName and an API key held by flag sets of two documents is CodeDuplicateKey. The first in document order keeps the name or key and the later flag set has the problem. Paths are prefixed with the position of the document (documents[1].flagSets[0].apiKeys[0]) and a duplicate key names the path of the first use, never the text of the key. When manifest is not nil every source must resolve in it.
func ValidateFlags ¶
ValidateFlags checks a flag file with the structural rules of the engine's own validation, so that a flag accepted here is not dropped when the relay loads it: variations present, not null and all of one type, a default rule, enabled targeting rules with a query and an outcome, declared variations, valid percentages (finite, not negative, a non-zero sum), complete progressive rollouts (both steps, variations, dates in order), and the same checks on scheduled steps (whose rules may be partial updates of a named rule). A disabled targeting rule is not checked. It does not compile queries; the engine does.
Problems have Kind EntryFlag and the flag name in Name, so a caller can keep the good flags.
func ValidateManifest ¶
func ValidateManifest(manifest *Manifest, opts ...ValidateOption) error
ValidateManifest runs the checks the relay runs on a manifest (an empty header means the current one).
A wrong kind or an unsupported apiVersion rejects the document whole (*KindError, *UnsupportedVersionError, both match ErrInvalid too). Every other problem is a *ValidationError whose FieldErrors name the entry, so a caller can keep the good entries: an object with a problem is one that has a FieldError of Kind EntryObject with its Index. Of two objects with one name the first keeps it and the later one has the problem. An object with a newer content version is an entry problem (CodeUnsupportedVersion), not a failure of the manifest.
Example (WithMaxObjects) ¶
package main
import (
"fmt"
"github.com/blackbirdworks/semaphore/controlplane"
)
func main() {
manifest := &controlplane.Manifest{Channel: "prod", Generation: 1}
fmt.Println(controlplane.ValidateManifest(manifest, controlplane.WithMaxObjects(10)))
}
Output: <nil>
func ValidateObject ¶ added in v1.2.0
func ValidateObject(entry *ManifestObject, body []byte) (DecodeInfo, *FlagSetDocument, error)
ValidateObject decodes and validates the bytes of one object by its kind. For a flag-set document it returns the decoded document; the documents are validated together by the caller. The errors are the ones of the controlplane package.
func ValidateSegments ¶
func ValidateSegments(doc *SegmentsDocument) error
ValidateSegments checks a segments document (an empty header means the current one). Header failures are returned as for ValidateManifest; the other problems are a *ValidationError whose problems have Kind EntrySegment, so a caller can keep the good segments. Of two segments with one name the first keeps it. It mirrors the validation of the engine's segment definition; the parity test of the flagcheck package keeps the two together.
func VerifyChecksum ¶
VerifyChecksum checks that data has the checksum want. It returns ErrUnsupportedChecksum for an algorithm other than sha256, ErrInvalidChecksum for a value that is not 64 lower-case hex characters (upper-case hex is invalid, not a mismatch) and a *ChecksumMismatchError (matches ErrChecksumMismatch) when the digest differs.
Example ¶
package main
import (
"fmt"
"github.com/blackbirdworks/semaphore/controlplane"
)
func main() {
sum := controlplane.ChecksumOf([]byte("hello"))
fmt.Println(controlplane.VerifyChecksum([]byte("hello"), sum))
fmt.Println(controlplane.VerifyChecksum([]byte("hellO"), sum) != nil)
}
Output: <nil> true
Types ¶
type Checksum ¶
type Checksum struct {
// Algorithm is AlgorithmSHA256.
Algorithm string `json:"algorithm" yaml:"algorithm"`
// Value is the lower-case hex digest.
Value string `json:"value" yaml:"value"`
}
Checksum is a content checksum: an algorithm and a lower-case hex value.
func ChecksumOf ¶
ChecksumOf returns the sha256 of the exact bytes, as lower-case hex. (The function is not named Checksum because that name is the wire type.)
type ChecksumMismatchError ¶
type ChecksumMismatchError struct {
// Want is the listed value.
Want string
// Got is the computed value.
Got string
}
ChecksumMismatchError carries the two digests of a failed VerifyChecksum.
func (*ChecksumMismatchError) Error ¶
func (e *ChecksumMismatchError) Error() string
Error implements error.
func (*ChecksumMismatchError) Is ¶
func (*ChecksumMismatchError) Is(target error) bool
Is reports a match with ErrChecksumMismatch.
type Code ¶
type Code string
Code is a stable, machine-readable reason of a FieldError.
const ( // CodeUnresolvedSource: a flag set source names no flags object of the manifest. CodeUnresolvedSource Code = "unresolved-source" // CodeDuplicateKey: an API key that an earlier flag set already holds. CodeDuplicateKey Code = "duplicate-key" // CodeDuplicateName: a name that an earlier entry already holds. CodeDuplicateName Code = "duplicate-name" // CodeInvalidName: a name that does not match ^[a-z][a-z0-9-]{0,62}$. CodeInvalidName Code = "invalid-name" // CodeUnsupportedVersion: an object whose content version is not supported. CodeUnsupportedVersion Code = "unsupported-version" // CodeInvalidChecksum: a checksum with another algorithm than sha256 or a malformed value. CodeInvalidChecksum Code = "invalid-checksum" // CodeInvalidValue: a value that is not allowed. CodeInvalidValue Code = "invalid-value" // CodeMissingValue: a required value is absent. CodeMissingValue Code = "missing-value" // CodeTooManyObjects: the manifest lists more objects than the limit. CodeTooManyObjects Code = "too-many-objects" // CodeUndeclaredVariation: a rule names a variation that the flag does not declare. CodeUndeclaredVariation Code = "undeclared-variation" )
The codes of a FieldError.
type DecodeError ¶
type DecodeError struct {
// Path addresses the field, such as "flagSets[0].apiKeys". Empty for the document.
Path string
// Reason says what is wrong, for example "expected a list".
Reason string
// Line is the line of the problem (1-based), or 0 when unknown.
Line int
}
DecodeError says where and why a document cannot be read. It never contains the text of a value (a value may be a secret such as an API key); Path holds field names and indexes only.
func (*DecodeError) Is ¶
func (*DecodeError) Is(target error) bool
Is reports a match with ErrDecode.
type DecodeInfo ¶
type DecodeInfo struct {
// UnknownFields lists the paths of fields that the structs of this package do not know, for example
// "objects[2].extra", sorted by key within each mapping. Published documents are forward compatible:
// unknown fields are reported, not fatal.
UnknownFields []string
}
DecodeInfo reports what a decoder noticed besides the document.
type EntryKind ¶
type EntryKind string
EntryKind says which entry of a document a FieldError belongs to.
const ( // EntryDocument: the document as a whole (header, channel, generation, object count). EntryDocument EntryKind = "document" // EntryObject: an entry of manifest.objects. EntryObject EntryKind = "object" // EntryFlagSet: an entry of flagSets. EntryFlagSet EntryKind = "flagSet" // EntrySegment: a segment of a segments document. EntrySegment EntryKind = "segment" // EntryFlag: a flag of a flag file. EntryFlag EntryKind = "flag" )
The entry kinds of a FieldError.
type Experimentation ¶
type Experimentation struct {
Start *time.Time `json:"start,omitempty" yaml:"start,omitempty"`
End *time.Time `json:"end,omitempty" yaml:"end,omitempty"`
}
Experimentation limits a flag to a time window.
type FieldError ¶
type FieldError struct {
// Path addresses the field, such as "objects[1].checksum.value".
Path string
// Reason says what is wrong, in words.
Reason string
// Code is the stable reason.
Code Code
// Kind is the kind of entry that has the problem.
Kind EntryKind
// Name is the name of the entry (object name, flag set name, flag name); empty for a document.
Name string
// Index is the position of the entry in its list, or NoIndex.
Index int
}
FieldError is one problem of a document. A caller can keep the entries without a problem and drop the others with Kind, Name and Index, without parsing text. The Reason never contains a secret such as an API key.
type Flag ¶
type Flag struct {
TrackEvents *bool `json:"trackEvents,omitempty" yaml:"trackEvents,omitempty"`
Disable *bool `json:"disable,omitempty" yaml:"disable,omitempty"`
Version *string `json:"version,omitempty" yaml:"version,omitempty"`
Converter *string `json:"converter,omitempty" yaml:"converter,omitempty"`
Variations map[string]any `json:"variations,omitempty" yaml:"variations,omitempty"`
Targeting []Rule `json:"targeting,omitempty" yaml:"targeting,omitempty"`
BucketingKey *string `json:"bucketingKey,omitempty" yaml:"bucketingKey,omitempty"`
DefaultRule *Rule `json:"defaultRule,omitempty" yaml:"defaultRule,omitempty"`
ScheduledRollout []ScheduledStep `json:"scheduledRollout,omitempty" yaml:"scheduledRollout,omitempty"`
Experimentation *Experimentation `json:"experimentation,omitempty" yaml:"experimentation,omitempty"`
Metadata map[string]any `json:"metadata,omitempty" yaml:"metadata,omitempty"`
}
Flag is one flag of a flag file.
type FlagCheck ¶ added in v1.3.0
type FlagCheck struct {
// Unknown lists the unknown fields of the flag, as "flag.field" paths.
Unknown []string
// Steps is the work of the check, counted as the whole file check counts it.
Steps int
}
FlagCheck is what the format check of one flag found.
type FlagEntry ¶ added in v1.3.0
type FlagEntry struct {
// Name is the key of the flag.
Name string
// Digest is the SHA-256 of the value node tree: kind, style, tag, anchor and text of every node, in order. Two
// flags with the same digest decode and check the same, whatever line they sit on and whatever the text around
// them is. The anchor is in it because the check of a time reads it (an anchored time is refused).
Digest [sha256.Size]byte
// contains filtered or unexported fields
}
FlagEntry is one flag of a flag file whose top level is a plain mapping.
type FlagSet ¶
type FlagSet struct {
// Name is the unique name of the flag set.
Name string `json:"name" yaml:"name"`
// Sources are names of manifest objects of kind flags; a later source wins on a duplicate flag key.
Sources []string `json:"sources" yaml:"sources"`
// SegmentSources are names of manifest objects of kind segments; the segments that the rules of this flag set
// name with segment("name") are defined there. A name must be defined once in all the sources of a flag set.
SegmentSources []string `json:"segmentSources,omitempty" yaml:"segmentSources,omitempty"`
// APIKeys are plain inline keys (UUIDs). They are secrets: never log them.
APIKeys []string `json:"apiKeys,omitempty" yaml:"apiKeys,omitempty"`
}
FlagSet binds flag objects and API keys.
type FlagSetDocument ¶
type FlagSetDocument struct {
// APIVersion is the document version, "semaphore/v1". Empty means the current version when marshalling.
APIVersion string `json:"apiVersion" yaml:"apiVersion"`
// Kind is "FlagSet". Empty means "FlagSet" when marshalling.
Kind string `json:"kind" yaml:"kind"`
// FlagSets are the flag-set definitions.
FlagSets []FlagSet `json:"flagSets" yaml:"flagSets"`
}
FlagSetDocument is the document of kind FlagSet.
type FlagsTree ¶ added in v1.3.0
type FlagsTree struct {
// contains filtered or unexported fields
}
FlagsTree is a YAML flag file that was read once into a node tree. The relay reads a flag file for two jobs, the flags themselves and the report of the unknown fields; the tree lets both use one parse, and lets a reader that holds the previous generation decode only the flags whose text changed (see FlagsTree.Entries).
A tree is not safe for concurrent use: the check of an entry rewrites time nodes of that entry.
func ParseFlagsTree ¶ added in v1.3.0
ParseFlagsTree reads the first YAML document of a flag file, as the engine parser does, and notes whether a second document follows. The caller has checked that the text is not JSON (that is read by another path). The error is the one of the YAML library, unchanged. An empty file gives an empty tree.
func (*FlagsTree) CheckEntry ¶ added in v1.3.0
CheckEntry checks one flag of the file against the flag format, as FlagsTree.UnknownFields checks it as a part of the file. A flag that fails the check makes the check of the whole file fail. Call it after the decode of the entry: the check rewrites time nodes.
func (*FlagsTree) Decode ¶ added in v1.3.0
Decode decodes the whole file into out, as the engine parser does. An empty file leaves out as it is.
func (*FlagsTree) DecodeEntries ¶ added in v1.3.0
DecodeEntries decodes the given entries, and only them, into out, a pointer to a map from flag name to the value type. It reports what FlagsTree.Decode reports for the same flags, except that the position of an error is not meant to be shown: a caller that needs the message of the whole file decodes the whole file.
func (*FlagsTree) Entries ¶ added in v1.3.0
Entries lists the flags of a file whose top level is a plain mapping of string keys that are all different, with no merge key and no alias anywhere, sorted by name. ok is false for any other file: it is read as a whole.
func (*FlagsTree) ReadEntries ¶ added in v1.3.0
ReadEntries reads the given entries of the file as UnmarshalFlags reads them as a part of the whole file, and validates them as ValidateFlags does: the strict check of the format, the decode and the validation of every flag. The flags are independent of each other in all three, so a reader that holds the answer for some flags of an earlier read passes the others only. It returns the flags and the steps of the check of each entry, counted as the whole file check counts them (see StepsExceeded). The entries are the ones that FlagsTree.Entries listed, so the keys are different and no merge key or alias is anywhere. The error is not meant to be shown: a reader that needs the text of the refusal reads the file by UnmarshalFlags. A file with a second document is refused. The check rewrites time nodes: call it after every other decode of the same entries.
func (*FlagsTree) Single ¶ added in v1.3.0
Single tells whether the file holds one document. A file with a second one reports no unknown fields.
func (*FlagsTree) UnknownFields ¶ added in v1.3.0
func (t *FlagsTree) UnknownFields() (DecodeInfo, error)
UnknownFields checks the whole file against the flag format and lists the unknown fields, as UnmarshalFlags does. Call it after every FlagsTree.Decode: the check rewrites time nodes.
type KindError ¶
type KindError struct {
// Got is the kind of the document.
Got string
// Want is the kind that was asked for.
Want string
}
KindError is returned for a document of another kind than the one asked for.
type Manifest ¶
type Manifest struct {
// APIVersion is the document version, "semaphore/v1". Empty means the current version when marshalling.
APIVersion string `json:"apiVersion" yaml:"apiVersion"`
// Kind is "Manifest". Empty means "Manifest" when marshalling.
Kind string `json:"kind" yaml:"kind"`
// Channel names the channel (environment) of the manifest.
Channel string `json:"channel" yaml:"channel"`
// Generation increases strictly with every publication of a channel, starting at 1.
Generation uint64 `json:"generation" yaml:"generation"`
// CreatedAt is informational.
CreatedAt *time.Time `json:"createdAt,omitempty" yaml:"createdAt,omitempty"`
// Objects are the source objects.
Objects []ManifestObject `json:"objects" yaml:"objects"`
}
Manifest lists the objects of one channel at one generation. It is the pointer to the current state and is written last by a publisher.
type ManifestObject ¶
type ManifestObject struct {
// Name is the logical name, unique in the manifest; flag sets reference objects by it.
Name string `json:"name" yaml:"name"`
// Kind is KindFlags, KindFlagSets or KindSegments.
Kind string `json:"kind" yaml:"kind"`
// Connection names a connection of the relay bootstrap file; it fixes endpoint, bucket and credentials.
Connection string `json:"connection" yaml:"connection"`
// Key is the key of the object in the bucket of the connection.
Key string `json:"key" yaml:"key"`
// Format is FormatYAML, FormatJSON or (flags only) FormatTOML.
Format string `json:"format" yaml:"format"`
// Version is the version of the content schema; 0 means ObjectVersion1.
Version int `json:"version,omitempty" yaml:"version,omitempty"`
// Checksum is the checksum of the exact stored bytes.
Checksum Checksum `json:"checksum" yaml:"checksum"`
// Size is the size of the stored bytes.
Size int64 `json:"size" yaml:"size"`
// VersionID is an optional object version id of the store.
VersionID string `json:"versionId,omitempty" yaml:"versionId,omitempty"`
// Modified is the modification time that the store reported for the object; zero when it did not say. The relay
// keeps it so that the date of a flag set is the same on every replica, and survives a restart.
Modified *time.Time `json:"modified,omitempty" yaml:"modified,omitempty"`
}
ManifestObject is one source object of a manifest.
type MemberList ¶
type MemberList []string
MemberList is the member list of a static segment. It is a list of strings like any other, except that the decoder rejects an item that is null or is not a string (it would otherwise drop the first and turn the other into text).
type ProgressiveRollout ¶
type ProgressiveRollout struct {
Initial *ProgressiveRolloutStep `json:"initial,omitempty" yaml:"initial,omitempty"`
End *ProgressiveRolloutStep `json:"end,omitempty" yaml:"end,omitempty"`
}
ProgressiveRollout ramps a rule from an initial to an end step.
type ProgressiveRolloutStep ¶
type ProgressiveRolloutStep struct {
Variation *string `json:"variation,omitempty" yaml:"variation,omitempty"`
Percentage *float64 `json:"percentage,omitempty" yaml:"percentage,omitempty"`
Date *time.Time `json:"date,omitempty" yaml:"date,omitempty"`
}
ProgressiveRolloutStep is one end of a progressive rollout.
type Rule ¶
type Rule struct {
Name *string `json:"name,omitempty" yaml:"name,omitempty"`
Query *string `json:"query,omitempty" yaml:"query,omitempty"`
Variation *string `json:"variation,omitempty" yaml:"variation,omitempty"`
Percentage map[string]float64 `json:"percentage,omitempty" yaml:"percentage,omitempty"`
ProgressiveRollout *ProgressiveRollout `json:"progressiveRollout,omitempty" yaml:"progressiveRollout,omitempty"`
Disable *bool `json:"disable,omitempty" yaml:"disable,omitempty"`
OnError *string `json:"onError,omitempty" yaml:"onError,omitempty"`
}
Rule is a targeting rule or the default rule.
type ScheduledStep ¶
type ScheduledStep struct {
Date *time.Time `json:"date,omitempty" yaml:"date,omitempty"`
TrackEvents *bool `json:"trackEvents,omitempty" yaml:"trackEvents,omitempty"`
Disable *bool `json:"disable,omitempty" yaml:"disable,omitempty"`
Version *string `json:"version,omitempty" yaml:"version,omitempty"`
Variations map[string]any `json:"variations,omitempty" yaml:"variations,omitempty"`
Targeting []Rule `json:"targeting,omitempty" yaml:"targeting,omitempty"`
BucketingKey *string `json:"bucketingKey,omitempty" yaml:"bucketingKey,omitempty"`
DefaultRule *Rule `json:"defaultRule,omitempty" yaml:"defaultRule,omitempty"`
Experimentation *Experimentation `json:"experimentation,omitempty" yaml:"experimentation,omitempty"`
Metadata map[string]any `json:"metadata,omitempty" yaml:"metadata,omitempty"`
}
ScheduledStep updates fields of a flag at a date. The flag fields are the optional fields of Flag that the engine allows in a step (a nested scheduledRollout is not part of the format).
type SegmentCache ¶
type SegmentCache struct {
// MaxEntries is the most cached answers.
MaxEntries int `json:"maxEntries,omitempty" yaml:"maxEntries,omitempty"`
// TTL is how long an answer is cached, a duration such as "30s".
TTL string `json:"ttl,omitempty" yaml:"ttl,omitempty"`
}
SegmentCache sizes the cache of a lookup segment.
type SegmentDefinition ¶
type SegmentDefinition struct {
// Name is the name that rules use: segment("name").
Name string `json:"name" yaml:"name"`
// Connection names a connection of the relay bootstrap file: a dynamic segment.
Connection string `json:"connection,omitempty" yaml:"connection,omitempty"`
// Members are the members of a static segment. An empty list is a static segment with no member.
Members MemberList `json:"members,omitempty" yaml:"members,omitempty"`
// Mode is "snapshot" (default) or "lookup" (dynamic only).
Mode string `json:"mode,omitempty" yaml:"mode,omitempty"`
// Key is the key of the set (layout set) or the prefix of the member keys (layout keys) in the store.
Key string `json:"key,omitempty" yaml:"key,omitempty"`
// Layout is "set" (default) or "keys". The keys layout is lookup only.
Layout string `json:"layout,omitempty" yaml:"layout,omitempty"`
// MissingKey is "notMember" (default) or "unknown": what a segment that does not exist in the store means.
MissingKey string `json:"missingKey,omitempty" yaml:"missingKey,omitempty"`
// OnError is what a lookup that could not be answered becomes: "notMember" (default), "unknown" or "member".
OnError string `json:"onError,omitempty" yaml:"onError,omitempty"`
// Version says how the version of the segment is learned (dynamic only).
Version *SegmentVersion `json:"version,omitempty" yaml:"version,omitempty"`
// Cache sizes the cache of a lookup segment.
Cache *SegmentCache `json:"cache,omitempty" yaml:"cache,omitempty"`
}
SegmentDefinition is one segment. It has no type: with a Connection it is a dynamic segment (its members are in a store, and the store kind is the one of the connection of the relay bootstrap file), without one it is a static segment with its Members inline. Exactly one of the two must be given.
type SegmentVersion ¶
type SegmentVersion struct {
// Value is a version that the document carries.
Value string `json:"value,omitempty" yaml:"value,omitempty"`
// Key is the version key in the store.
Key string `json:"key,omitempty" yaml:"key,omitempty"`
// Interval is the poll period of Key, a duration such as "5s" (needs Key).
Interval string `json:"interval,omitempty" yaml:"interval,omitempty"`
}
SegmentVersion is the version of a dynamic segment: the publisher bumps Value, or the writer of the members bumps the version key Key in the store, which the relay polls every Interval. Value and Key are exclusive.
type SegmentsDocument ¶
type SegmentsDocument struct {
// APIVersion is the document version, "semaphore/v1". Empty means the current version when marshalling.
APIVersion string `json:"apiVersion" yaml:"apiVersion"`
// Kind is "Segments". Empty means "Segments" when marshalling.
Kind string `json:"kind" yaml:"kind"`
// Segments are the definitions.
Segments []SegmentDefinition `json:"segments" yaml:"segments"`
}
SegmentsDocument is the document of kind Segments: named segment definitions.
type UnsupportedVersionError ¶
type UnsupportedVersionError struct {
// Got is the apiVersion of the document.
Got string
// Supported is the apiVersion this package reads.
Supported string
}
UnsupportedVersionError is returned for a document whose apiVersion is not supported.
func (*UnsupportedVersionError) Error ¶
func (e *UnsupportedVersionError) Error() string
Error implements error.
func (*UnsupportedVersionError) Is ¶
func (*UnsupportedVersionError) Is(target error) bool
Is reports a match with ErrUnsupportedAPIVersion and ErrInvalid.
type ValidateOption ¶
type ValidateOption func(*validateConfig)
ValidateOption changes how a Validate function checks.
func WithMaxObjects ¶
func WithMaxObjects(limit int) ValidateOption
WithMaxObjects sets the largest number of objects a manifest may list (default DefaultMaxObjects). A value of zero or less keeps the default.
type ValidationError ¶
type ValidationError struct {
// Problems are the problems in document order.
Problems []FieldError
}
ValidationError lists every problem found by a Validate function.
func (*ValidationError) Is ¶
func (*ValidationError) Is(target error) bool
Is reports a match with ErrInvalid.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package flagcheck validates the bytes of a flag object with the engine of the relay: the same decoder and the same validity checks the relay applies when it loads a flag file, and that "semaphore-cli lint" applies.
|
Package flagcheck validates the bytes of a flag object with the engine of the relay: the same decoder and the same validity checks the relay applies when it loads a flag file, and that "semaphore-cli lint" applies. |