| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443 |
- package capture
- import (
- "bufio"
- "crypto/sha256"
- "encoding/hex"
- "encoding/json"
- "fmt"
- "io"
- "os"
- "path/filepath"
- "time"
- "google.golang.org/protobuf/encoding/protojson"
- hthv1 "hth/internal/gen/hth/api/v1"
- )
- const Version = 1
- const (
- StatusIncomplete = "incomplete"
- StatusComplete = "complete"
- )
- const (
- MaxRecordsBytes = 64 << 20
- MaxRecordLine = 4 << 20
- MaxRecordCount = 1_000_000
- )
- type Manifest struct {
- V int `json:"v"`
- Kind string `json:"kind"`
- APIVersion string `json:"api_version"`
- APISchemaVersion string `json:"api_schema_version"`
- ProfileHash string `json:"profile_hash"`
- ProfileID string `json:"profile_id,omitempty"`
- ProfileRevision string `json:"profile_revision,omitempty"`
- ProfileContractHash string `json:"profile_contract_hash"`
- CapabilityHash string `json:"capability_hash"`
- DeviceID string `json:"device_id"`
- StartedAt time.Time `json:"started_at"`
- StartTime time.Time `json:"start_time"`
- EndedAt time.Time `json:"ended_at,omitempty"`
- EndTime time.Time `json:"end_time,omitempty"`
- RecordCount int `json:"record_count"`
- RecordsSHA256 string `json:"records_sha256"`
- FirstSourceEventID uint64 `json:"first_source_event_id"`
- LastSourceEventID uint64 `json:"last_source_event_id"`
- Status string `json:"status"`
- CompletionStatus string `json:"completion_status"`
- IncompleteReason string `json:"incomplete_reason,omitempty"`
- CompletionReason string `json:"completion_reason,omitempty"`
- CaptureID string `json:"capture_id,omitempty"`
- }
- type Record struct {
- V int `json:"v"`
- Kind string `json:"kind"`
- EventID uint64 `json:"event_id,omitempty"`
- SourceEventID uint64 `json:"source_event_id,omitempty"`
- WallTime time.Time `json:"wall_time,omitempty"`
- Snapshot json.RawMessage `json:"snapshot,omitempty"`
- Event json.RawMessage `json:"event,omitempty"`
- }
- var marshal = protojson.MarshalOptions{UseProtoNames: true, EmitUnpopulated: false}
- func (m *Manifest) Normalize() {
- if m == nil {
- return
- }
- if m.APISchemaVersion == "" {
- m.APISchemaVersion = m.APIVersion
- }
- if m.APIVersion == "" {
- m.APIVersion = m.APISchemaVersion
- }
- if m.ProfileContractHash == "" {
- m.ProfileContractHash = m.ProfileHash
- }
- if m.ProfileHash == "" {
- m.ProfileHash = m.ProfileContractHash
- }
- if m.StartTime.IsZero() {
- m.StartTime = m.StartedAt
- }
- if m.StartedAt.IsZero() {
- m.StartedAt = m.StartTime
- }
- if m.EndTime.IsZero() {
- m.EndTime = m.EndedAt
- }
- if m.EndedAt.IsZero() {
- m.EndedAt = m.EndTime
- }
- if m.CompletionStatus == "" {
- m.CompletionStatus = m.Status
- }
- if m.Status == "" {
- m.Status = m.CompletionStatus
- }
- if m.CompletionReason == "" {
- m.CompletionReason = m.IncompleteReason
- }
- if m.IncompleteReason == "" {
- m.IncompleteReason = m.CompletionReason
- }
- if m.Kind == "" {
- m.Kind = "manifest"
- }
- if m.V == 0 {
- m.V = Version
- }
- if m.CaptureID == "" {
- h := sha256.Sum256([]byte(m.DeviceID + "|" + m.StartedAt.UTC().Format(time.RFC3339Nano) + "|" + m.RecordsSHA256 + "|" + m.ProfileHash))
- m.CaptureID = hex.EncodeToString(h[:16])
- }
- }
- func WriteManifest(dir string, m Manifest) error {
- return writeManifestAtomic(dir, m)
- }
- func writeManifestAtomic(dir string, m Manifest) error {
- m.Normalize()
- m.V = Version
- m.Kind = "manifest"
- if m.Status == "" {
- m.Status = StatusIncomplete
- m.CompletionStatus = StatusIncomplete
- }
- b, err := json.MarshalIndent(m, "", " ")
- if err != nil {
- return err
- }
- b = append(b, '\n')
- final := filepath.Join(dir, "manifest.json")
- tmp := final + ".tmp"
- f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
- if err != nil {
- return err
- }
- if _, err := f.Write(b); err != nil {
- f.Close()
- _ = os.Remove(tmp)
- return err
- }
- if err := f.Sync(); err != nil {
- f.Close()
- _ = os.Remove(tmp)
- return fmt.Errorf("capture: manifest fsync: %w", err)
- }
- if err := f.Close(); err != nil {
- _ = os.Remove(tmp)
- return err
- }
- if err := os.Rename(tmp, final); err != nil {
- _ = os.Remove(tmp)
- return err
- }
- return syncDir(dir)
- }
- func syncDir(dir string) error {
- d, err := os.Open(dir)
- if err != nil {
- return fmt.Errorf("capture: dir fsync open: %w", err)
- }
- defer d.Close()
- if err := d.Sync(); err != nil {
- return fmt.Errorf("capture: dir fsync: %w", err)
- }
- return nil
- }
- func AppendRecord(f *os.File, rec Record) error {
- rec.V = Version
- if rec.SourceEventID == 0 {
- rec.SourceEventID = rec.EventID
- }
- b, err := json.Marshal(rec)
- if err != nil {
- return err
- }
- n, err := f.Write(append(b, '\n'))
- if err != nil {
- return err
- }
- if n < len(b)+1 {
- return fmt.Errorf("capture: short write %d/%d", n, len(b)+1)
- }
- return nil
- }
- func SyncFile(f *os.File) error {
- if f == nil {
- return fmt.Errorf("capture: nil file")
- }
- if err := f.Sync(); err != nil {
- return fmt.Errorf("capture: fsync: %w", err)
- }
- return nil
- }
- func HashFile(path string) (string, error) {
- f, err := os.Open(path)
- if err != nil {
- return "", err
- }
- defer f.Close()
- h := sha256.New()
- if _, err := io.Copy(h, f); err != nil {
- return "", err
- }
- return hex.EncodeToString(h.Sum(nil)), nil
- }
- func Seal(dir string, m Manifest) error {
- recPath := RecordsPath(dir)
- fi, err := os.Stat(recPath)
- if err != nil {
- return err
- }
- if fi.Size() > MaxRecordsBytes {
- return fmt.Errorf("capture: records size %d exceeds %d", fi.Size(), MaxRecordsBytes)
- }
- recs, err := ReadRecords(recPath)
- if err != nil {
- return err
- }
- sum, err := HashFile(recPath)
- if err != nil {
- return err
- }
- m.RecordCount = len(recs)
- m.RecordsSHA256 = sum
- if len(recs) > 0 {
- m.FirstSourceEventID = recs[0].SourceID()
- m.LastSourceEventID = recs[len(recs)-1].SourceID()
- } else if m.Status == StatusComplete || m.CompletionStatus == StatusComplete {
- return fmt.Errorf("capture: refusing to seal complete capture with zero records")
- }
- m.EndedAt = time.Now().UTC()
- m.EndTime = m.EndedAt
- return WriteManifest(dir, m)
- }
- func (r Record) SourceID() uint64 {
- if r.SourceEventID != 0 {
- return r.SourceEventID
- }
- return r.EventID
- }
- func ValidateManifest(m Manifest, apiVersion, capHash string, requireComplete bool) error {
- m.Normalize()
- if m.V != 0 && m.V != Version {
- return fmt.Errorf("capture: unsupported manifest version %d", m.V)
- }
- if m.Kind != "" && m.Kind != "manifest" {
- return fmt.Errorf("capture: unexpected kind %q", m.Kind)
- }
- if requireComplete {
- if m.Status != StatusComplete {
- return fmt.Errorf("capture: manifest status %q is not complete", m.Status)
- }
- if m.RecordCount == 0 {
- return fmt.Errorf("capture: complete capture requires at least one record")
- }
- if m.CapabilityHash == "" {
- return fmt.Errorf("capture: empty capability_hash is not valid")
- }
- if m.RecordsSHA256 == "" {
- return fmt.Errorf("capture: empty records_sha256 is not valid")
- }
- if m.APIVersion == "" {
- return fmt.Errorf("capture: api_schema_version required")
- }
- if m.ProfileHash == "" {
- return fmt.Errorf("capture: empty profile_hash is not valid")
- }
- }
- if apiVersion != "" && m.APIVersion != "" && m.APIVersion != apiVersion {
- return fmt.Errorf("capture: api_version %q != %q", m.APIVersion, apiVersion)
- }
- if capHash != "" {
- if m.CapabilityHash == "" {
- return fmt.Errorf("capture: empty capability_hash is not valid")
- }
- if m.CapabilityHash != capHash {
- return fmt.Errorf("capture: capability_hash mismatch")
- }
- }
- return nil
- }
- func ValidateRecordsAgainstManifest(m Manifest, recs []Record, recSHA string) error {
- m.Normalize()
- if m.RecordCount != len(recs) {
- return fmt.Errorf("capture: record_count %d != %d records", m.RecordCount, len(recs))
- }
- if m.RecordsSHA256 != "" && recSHA != "" && m.RecordsSHA256 != recSHA {
- return fmt.Errorf("capture: records_sha256 mismatch")
- }
- if len(recs) == 0 {
- if m.Status == StatusComplete || m.CompletionStatus == StatusComplete {
- return fmt.Errorf("capture: complete capture with zero records is not valid")
- }
- if m.FirstSourceEventID != 0 || m.LastSourceEventID != 0 {
- return fmt.Errorf("capture: empty records but event ids set")
- }
- return nil
- }
- var prev uint64
- for i, rec := range recs {
- if rec.V != 0 && rec.V != Version {
- return fmt.Errorf("capture: record %d unsupported version %d", i, rec.V)
- }
- id := rec.SourceID()
- if i > 0 && id != 0 && prev != 0 && id < prev {
- return fmt.Errorf("capture: source event id not monotonic at %d: %d < %d", i, id, prev)
- }
- if id != 0 {
- prev = id
- }
- }
- first := recs[0].SourceID()
- last := recs[len(recs)-1].SourceID()
- if m.FirstSourceEventID != 0 && m.FirstSourceEventID != first {
- return fmt.Errorf("capture: first_source_event_id %d != %d", m.FirstSourceEventID, first)
- }
- if m.LastSourceEventID != 0 && m.LastSourceEventID != last {
- return fmt.Errorf("capture: last_source_event_id %d != %d", m.LastSourceEventID, last)
- }
- return nil
- }
- func SnapshotRecord(s *hthv1.Snapshot) (Record, error) {
- b, err := marshal.Marshal(s)
- if err != nil {
- return Record{}, err
- }
- wt := time.Time{}
- if s.WallTime != nil {
- wt = s.WallTime.AsTime()
- }
- return Record{Kind: "snapshot", EventID: s.EventId, SourceEventID: s.EventId, WallTime: wt, Snapshot: b}, nil
- }
- func EventRecord(e *hthv1.Event) (Record, error) {
- b, err := marshal.Marshal(e)
- if err != nil {
- return Record{}, err
- }
- wt := time.Time{}
- if e.WallTime != nil {
- wt = e.WallTime.AsTime()
- }
- return Record{Kind: "event", EventID: e.EventId, SourceEventID: e.EventId, WallTime: wt, Event: b}, nil
- }
- func ReadManifest(dir string) (Manifest, error) {
- var m Manifest
- f, err := os.Open(filepath.Join(dir, "manifest.json"))
- if err != nil {
- return m, err
- }
- defer f.Close()
- dec := json.NewDecoder(f)
- dec.DisallowUnknownFields()
- if err := dec.Decode(&m); err != nil {
- return m, fmt.Errorf("capture: manifest: %w", err)
- }
- var extra json.RawMessage
- if err := dec.Decode(&extra); err != io.EOF {
- if err == nil {
- return m, fmt.Errorf("capture: trailing data after manifest")
- }
- return m, fmt.Errorf("capture: manifest trailing: %w", err)
- }
- m.Normalize()
- return m, nil
- }
- func ReadRecords(path string) ([]Record, error) {
- fi, err := os.Stat(path)
- if err != nil {
- return nil, err
- }
- if fi.Size() > MaxRecordsBytes {
- return nil, fmt.Errorf("capture: records size %d exceeds %d", fi.Size(), MaxRecordsBytes)
- }
- f, err := os.Open(path)
- if err != nil {
- return nil, err
- }
- defer f.Close()
- var out []Record
- sc := bufio.NewScanner(f)
- sc.Buffer(make([]byte, 0, 64*1024), MaxRecordLine)
- for sc.Scan() {
- line := sc.Bytes()
- if len(line) == 0 {
- continue
- }
- var rec Record
- if err := json.Unmarshal(line, &rec); err != nil {
- return nil, fmt.Errorf("capture: bad record: %w", err)
- }
- if rec.Kind != "snapshot" && rec.Kind != "event" {
- return nil, fmt.Errorf("capture: unknown record kind %q", rec.Kind)
- }
- out = append(out, rec)
- if len(out) > MaxRecordCount {
- return nil, fmt.Errorf("capture: %d records exceeds limit %d", len(out), MaxRecordCount)
- }
- }
- if err := sc.Err(); err != nil {
- return nil, err
- }
- return out, nil
- }
- func DecodeSnapshot(rec Record) (*hthv1.Snapshot, error) {
- if len(rec.Snapshot) == 0 {
- return nil, fmt.Errorf("no snapshot")
- }
- s := &hthv1.Snapshot{}
- return s, protojson.Unmarshal(rec.Snapshot, s)
- }
- func DecodeEvent(rec Record) (*hthv1.Event, error) {
- if len(rec.Event) == 0 {
- return nil, fmt.Errorf("no event")
- }
- e := &hthv1.Event{}
- return e, protojson.Unmarshal(rec.Event, e)
- }
- func RecordsPath(dir string) string {
- return filepath.Join(dir, "records.jsonl")
- }
|