Skip to content
File

Blob: config/codec.go

go103 lines
1package config
2 
3import (
4 "bytes"
5 "encoding/json"
6 "errors"
7 "fmt"
8 
9 "go.miragespace.co/specter/util"
10)
11 
12const snapshotFormat = 1
13 
14type snapshot struct {
15 Format uint64 `json:"format"`
16 Records snapshotRecords `json:"records"`
17}
18 
19type snapshotRecords []Record
20 
21func (records *snapshotRecords) UnmarshalJSON(data []byte) error {
22 if *records != nil {
23 return errors.New("configuration snapshot repeats records")
24 }
25 decoder := json.NewDecoder(bytes.NewReader(data))
26 decoder.DisallowUnknownFields()
27 token, err := decoder.Token()
28 if err != nil {
29 return err
30 }
31 if token != json.Delim('[') {
32 return errors.New("configuration records must be an array")
33 }
34 *records = make([]Record, 0)
35 for decoder.More() {
36 if len(*records) == MaxDocuments {
37 return ErrTooLarge
38 }
39 var record Record
40 if err := decoder.Decode(&record); err != nil {
41 return err
42 }
43 *records = append(*records, record)
44 }
45 _, err = decoder.Token()
46 return err
47}
48 
49// EncodeSnapshot validates and bounds the complete wire envelope. Documents are
50// opaque; no consumer-specific decoding occurs here.
51func EncodeSnapshot(records []Record) ([]byte, error) {
52 if err := checkRecords(records); err != nil {
53 return nil, err
54 }
55 if records == nil {
56 records = []Record{}
57 }
58 return json.Marshal(snapshot{Format: snapshotFormat, Records: records})
59}
60 
61// DecodeSnapshot bounds bytes before parsing and document count before
62// allocation, then validates every record, including losing duplicate versions.
63func DecodeSnapshot(data []byte) ([]Record, error) {
64 if len(data) > MaxSnapshotBytes {
65 return nil, ErrTooLarge
66 }
67 var state snapshot
68 if err := util.DecodeJSON(bytes.NewReader(data), &state); err != nil {
69 return nil, fmt.Errorf("decode configuration snapshot: %w", err)
70 }
71 if state.Format != snapshotFormat || state.Records == nil {
72 return nil, errors.New("unsupported configuration snapshot format")
73 }
74 if err := checkRecords(state.Records); err != nil {
75 return nil, err
76 }
77 return state.Records, nil
78}
79 
80func checkRecords(records []Record) error {
81 if len(records) > MaxDocuments {
82 return ErrTooLarge
83 }
84 size := len(`{"format":1,"records":[]}`)
85 for i, record := range records {
86 if err := record.Validate(); err != nil {
87 return err
88 }
89 encoded, err := json.Marshal(record)
90 if err != nil {
91 return err
92 }
93 size += len(encoded)
94 if i != 0 {
95 size++
96 }
97 if size > MaxSnapshotBytes {
98 return fmt.Errorf("%w: snapshot exceeds %d bytes", ErrTooLarge, MaxSnapshotBytes)
99 }
100 }
101 return nil
102}