Skip to content
File

Blob: config/record.go

go169 lines
1// Package config stores complete, versioned configuration documents on each
2// physical server, independently of Chord key ownership. Consumers own document
3// schema validation and activation.
4package config
5 
6import (
7 "bytes"
8 "cmp"
9 "crypto/sha256"
10 "encoding/base64"
11 "encoding/binary"
12 "errors"
13 "fmt"
14 "strings"
15 "unicode"
16 "unicode/utf8"
17)
18 
19const (
20 MaxNameBytes = 512
21 MaxValueBytes = 256 << 10
22 MaxDocuments = 4096
23 MaxSnapshotBytes = 8 << 20
24 versionBytes = 48
25)
26 
27var (
28 ErrInvalidRecord = errors.New("invalid configuration record")
29 ErrInvalidVersion = errors.New("invalid configuration version")
30 ErrTooLarge = errors.New("configuration exceeds size limit")
31 ErrConflict = errors.New("configuration version changed")
32 ErrSchemaRegression = errors.New("configuration schema cannot decrease")
33 ErrDurabilityUncertain = errors.New("configuration save outcome is uncertain")
34)
35 
36// Version orders copies of a document without interpreting its value. Schema
37// takes precedence so an older writer cannot defeat a newer document format.
38// The digest breaks equal-revision ties and detects changed document bytes.
39type Version struct {
40 Schema uint64
41 Revision uint64
42 Digest [sha256.Size]byte
43}
44 
45func (v Version) bytes() []byte {
46 data := make([]byte, versionBytes)
47 binary.BigEndian.PutUint64(data, v.Schema)
48 binary.BigEndian.PutUint64(data[8:], v.Revision)
49 copy(data[16:], v.Digest[:])
50 return data
51}
52 
53func decodeVersion(data []byte) (Version, error) {
54 if len(data) != versionBytes {
55 return Version{}, ErrInvalidVersion
56 }
57 v := Version{Schema: binary.BigEndian.Uint64(data), Revision: binary.BigEndian.Uint64(data[8:])}
58 copy(v.Digest[:], data[16:])
59 if v.Schema == 0 || v.Revision == 0 {
60 return Version{}, ErrInvalidVersion
61 }
62 return v, nil
63}
64 
65// MarshalText gives JSON the same bounded, opaque version used by storage.
66func (v Version) MarshalText() ([]byte, error) {
67 return []byte(base64.RawURLEncoding.EncodeToString(v.bytes())), nil
68}
69 
70func (v *Version) UnmarshalText(data []byte) error {
71 if len(data) != base64.RawURLEncoding.EncodedLen(versionBytes) {
72 return ErrInvalidVersion
73 }
74 decoded, err := base64.RawURLEncoding.Strict().DecodeString(string(data))
75 if err != nil {
76 return ErrInvalidVersion
77 }
78 *v, err = decodeVersion(decoded)
79 return err
80}
81 
82// Record is one complete document. JSON encodes Value as base64 so relays
83// preserve exact bytes, including schemas they do not understand.
84type Record struct {
85 Name string `json:"name"`
86 Version Version `json:"version"`
87 Value []byte `json:"value,omitempty"`
88}
89 
90func NewRecord(name string, schema, revision uint64, value []byte) (Record, error) {
91 if len(value) > MaxValueBytes {
92 return Record{}, ErrTooLarge
93 }
94 r := Record{Name: name, Version: Version{Schema: schema, Revision: revision, Digest: sha256.Sum256(value)}, Value: bytes.Clone(value)}
95 return r, r.Validate()
96}
97 
98func (r Record) Validate() error {
99 if !validName(r.Name) {
100 return fmt.Errorf("%w: invalid document name", ErrInvalidRecord)
101 }
102 if r.Version.Schema == 0 || r.Version.Revision == 0 {
103 return fmt.Errorf("%w: schema and revision must be positive", ErrInvalidRecord)
104 }
105 if len(r.Value) > MaxValueBytes {
106 return fmt.Errorf("%w: document %q", ErrTooLarge, r.Name)
107 }
108 if r.Version.Digest != sha256.Sum256(r.Value) {
109 return fmt.Errorf("%w: document %q digest mismatch", ErrInvalidRecord, r.Name)
110 }
111 return nil
112}
113 
114// Token is a name-scoped local editing guard, not a globally serialized revision
115// or a replication acknowledgement.
116func (r Record) Token() string {
117 if r.Name == "" {
118 return ""
119 }
120 version, _ := r.Version.MarshalText()
121 return "v1." + base64.RawURLEncoding.EncodeToString([]byte(r.Name)) + "." + string(version)
122}
123 
124// CompareVersion compares against a token for the same document. The order is
125// deterministic; it does not imply that concurrent edits were combined.
126func (r Record) CompareVersion(token string) (int, error) {
127 if len(token) > 1024 {
128 return 0, ErrInvalidVersion
129 }
130 parts := strings.Split(token, ".")
131 if len(parts) != 3 || parts[0] != "v1" {
132 return 0, ErrInvalidVersion
133 }
134 name, err := base64.RawURLEncoding.DecodeString(parts[1])
135 if err != nil || !validName(string(name)) || string(name) != r.Name {
136 return 0, ErrInvalidVersion
137 }
138 other := Record{Name: string(name)}
139 if err := other.Version.UnmarshalText([]byte(parts[2])); err != nil {
140 return 0, ErrInvalidVersion
141 }
142 if other.Token() != token {
143 return 0, ErrInvalidVersion
144 }
145 return compare(r, other), nil
146}
147 
148func validName(name string) bool {
149 if len(name) == 0 || len(name) > MaxNameBytes || !utf8.ValidString(name) {
150 return false
151 }
152 for _, c := range name {
153 if unicode.IsControl(c) || unicode.IsSpace(c) {
154 return false
155 }
156 }
157 return true
158}
159 
160func compare(a, b Record) int {
161 if c := cmp.Compare(a.Version.Schema, b.Version.Schema); c != 0 {
162 return c
163 }
164 if c := cmp.Compare(a.Version.Revision, b.Version.Revision); c != 0 {
165 return c
166 }
167 return bytes.Compare(a.Version.Digest[:], b.Version.Digest[:])
168}