capture.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. package capture
  2. import (
  3. "bufio"
  4. "crypto/sha256"
  5. "encoding/hex"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "os"
  10. "path/filepath"
  11. "time"
  12. "google.golang.org/protobuf/encoding/protojson"
  13. hthv1 "hth/internal/gen/hth/api/v1"
  14. )
  15. const Version = 1
  16. const (
  17. StatusIncomplete = "incomplete"
  18. StatusComplete = "complete"
  19. )
  20. const (
  21. MaxRecordsBytes = 64 << 20
  22. MaxRecordLine = 4 << 20
  23. MaxRecordCount = 1_000_000
  24. )
  25. type Manifest struct {
  26. V int `json:"v"`
  27. Kind string `json:"kind"`
  28. APIVersion string `json:"api_version"`
  29. APISchemaVersion string `json:"api_schema_version"`
  30. ProfileHash string `json:"profile_hash"`
  31. ProfileID string `json:"profile_id,omitempty"`
  32. ProfileRevision string `json:"profile_revision,omitempty"`
  33. ProfileContractHash string `json:"profile_contract_hash"`
  34. CapabilityHash string `json:"capability_hash"`
  35. DeviceID string `json:"device_id"`
  36. StartedAt time.Time `json:"started_at"`
  37. StartTime time.Time `json:"start_time"`
  38. EndedAt time.Time `json:"ended_at,omitempty"`
  39. EndTime time.Time `json:"end_time,omitempty"`
  40. RecordCount int `json:"record_count"`
  41. RecordsSHA256 string `json:"records_sha256"`
  42. FirstSourceEventID uint64 `json:"first_source_event_id"`
  43. LastSourceEventID uint64 `json:"last_source_event_id"`
  44. Status string `json:"status"`
  45. CompletionStatus string `json:"completion_status"`
  46. IncompleteReason string `json:"incomplete_reason,omitempty"`
  47. CompletionReason string `json:"completion_reason,omitempty"`
  48. }
  49. type Record struct {
  50. V int `json:"v"`
  51. Kind string `json:"kind"`
  52. EventID uint64 `json:"event_id,omitempty"`
  53. SourceEventID uint64 `json:"source_event_id,omitempty"`
  54. WallTime time.Time `json:"wall_time,omitempty"`
  55. Snapshot json.RawMessage `json:"snapshot,omitempty"`
  56. Event json.RawMessage `json:"event,omitempty"`
  57. }
  58. var marshal = protojson.MarshalOptions{UseProtoNames: true, EmitUnpopulated: false}
  59. func (m *Manifest) Normalize() {
  60. if m == nil {
  61. return
  62. }
  63. if m.APISchemaVersion == "" {
  64. m.APISchemaVersion = m.APIVersion
  65. }
  66. if m.APIVersion == "" {
  67. m.APIVersion = m.APISchemaVersion
  68. }
  69. if m.ProfileContractHash == "" {
  70. m.ProfileContractHash = m.ProfileHash
  71. }
  72. if m.ProfileHash == "" {
  73. m.ProfileHash = m.ProfileContractHash
  74. }
  75. if m.StartTime.IsZero() {
  76. m.StartTime = m.StartedAt
  77. }
  78. if m.StartedAt.IsZero() {
  79. m.StartedAt = m.StartTime
  80. }
  81. if m.EndTime.IsZero() {
  82. m.EndTime = m.EndedAt
  83. }
  84. if m.EndedAt.IsZero() {
  85. m.EndedAt = m.EndTime
  86. }
  87. if m.CompletionStatus == "" {
  88. m.CompletionStatus = m.Status
  89. }
  90. if m.Status == "" {
  91. m.Status = m.CompletionStatus
  92. }
  93. if m.CompletionReason == "" {
  94. m.CompletionReason = m.IncompleteReason
  95. }
  96. if m.IncompleteReason == "" {
  97. m.IncompleteReason = m.CompletionReason
  98. }
  99. if m.Kind == "" {
  100. m.Kind = "manifest"
  101. }
  102. if m.V == 0 {
  103. m.V = Version
  104. }
  105. }
  106. func WriteManifest(dir string, m Manifest) error {
  107. return writeManifestAtomic(dir, m)
  108. }
  109. func writeManifestAtomic(dir string, m Manifest) error {
  110. m.Normalize()
  111. m.V = Version
  112. m.Kind = "manifest"
  113. if m.Status == "" {
  114. m.Status = StatusIncomplete
  115. m.CompletionStatus = StatusIncomplete
  116. }
  117. b, err := json.MarshalIndent(m, "", " ")
  118. if err != nil {
  119. return err
  120. }
  121. b = append(b, '\n')
  122. final := filepath.Join(dir, "manifest.json")
  123. tmp := final + ".tmp"
  124. f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
  125. if err != nil {
  126. return err
  127. }
  128. if _, err := f.Write(b); err != nil {
  129. f.Close()
  130. _ = os.Remove(tmp)
  131. return err
  132. }
  133. if err := f.Sync(); err != nil {
  134. f.Close()
  135. _ = os.Remove(tmp)
  136. return fmt.Errorf("capture: manifest fsync: %w", err)
  137. }
  138. if err := f.Close(); err != nil {
  139. _ = os.Remove(tmp)
  140. return err
  141. }
  142. if err := os.Rename(tmp, final); err != nil {
  143. _ = os.Remove(tmp)
  144. return err
  145. }
  146. return syncDir(dir)
  147. }
  148. func syncDir(dir string) error {
  149. d, err := os.Open(dir)
  150. if err != nil {
  151. return fmt.Errorf("capture: dir fsync open: %w", err)
  152. }
  153. defer d.Close()
  154. if err := d.Sync(); err != nil {
  155. return fmt.Errorf("capture: dir fsync: %w", err)
  156. }
  157. return nil
  158. }
  159. func AppendRecord(f *os.File, rec Record) error {
  160. rec.V = Version
  161. if rec.SourceEventID == 0 {
  162. rec.SourceEventID = rec.EventID
  163. }
  164. b, err := json.Marshal(rec)
  165. if err != nil {
  166. return err
  167. }
  168. n, err := f.Write(append(b, '\n'))
  169. if err != nil {
  170. return err
  171. }
  172. if n < len(b)+1 {
  173. return fmt.Errorf("capture: short write %d/%d", n, len(b)+1)
  174. }
  175. return nil
  176. }
  177. func SyncFile(f *os.File) error {
  178. if f == nil {
  179. return fmt.Errorf("capture: nil file")
  180. }
  181. if err := f.Sync(); err != nil {
  182. return fmt.Errorf("capture: fsync: %w", err)
  183. }
  184. return nil
  185. }
  186. func HashFile(path string) (string, error) {
  187. f, err := os.Open(path)
  188. if err != nil {
  189. return "", err
  190. }
  191. defer f.Close()
  192. h := sha256.New()
  193. if _, err := io.Copy(h, f); err != nil {
  194. return "", err
  195. }
  196. return hex.EncodeToString(h.Sum(nil)), nil
  197. }
  198. func Seal(dir string, m Manifest) error {
  199. recPath := RecordsPath(dir)
  200. fi, err := os.Stat(recPath)
  201. if err != nil {
  202. return err
  203. }
  204. if fi.Size() > MaxRecordsBytes {
  205. return fmt.Errorf("capture: records size %d exceeds %d", fi.Size(), MaxRecordsBytes)
  206. }
  207. recs, err := ReadRecords(recPath)
  208. if err != nil {
  209. return err
  210. }
  211. sum, err := HashFile(recPath)
  212. if err != nil {
  213. return err
  214. }
  215. m.RecordCount = len(recs)
  216. m.RecordsSHA256 = sum
  217. if len(recs) > 0 {
  218. m.FirstSourceEventID = recs[0].SourceID()
  219. m.LastSourceEventID = recs[len(recs)-1].SourceID()
  220. } else if m.Status == StatusComplete || m.CompletionStatus == StatusComplete {
  221. return fmt.Errorf("capture: refusing to seal complete capture with zero records")
  222. }
  223. m.EndedAt = time.Now().UTC()
  224. m.EndTime = m.EndedAt
  225. return WriteManifest(dir, m)
  226. }
  227. func (r Record) SourceID() uint64 {
  228. if r.SourceEventID != 0 {
  229. return r.SourceEventID
  230. }
  231. return r.EventID
  232. }
  233. func ValidateManifest(m Manifest, apiVersion, capHash string, requireComplete bool) error {
  234. m.Normalize()
  235. if m.V != 0 && m.V != Version {
  236. return fmt.Errorf("capture: unsupported manifest version %d", m.V)
  237. }
  238. if m.Kind != "" && m.Kind != "manifest" {
  239. return fmt.Errorf("capture: unexpected kind %q", m.Kind)
  240. }
  241. if requireComplete {
  242. if m.Status != StatusComplete {
  243. return fmt.Errorf("capture: manifest status %q is not complete", m.Status)
  244. }
  245. if m.RecordCount == 0 {
  246. return fmt.Errorf("capture: complete capture requires at least one record")
  247. }
  248. if m.CapabilityHash == "" {
  249. return fmt.Errorf("capture: empty capability_hash is not valid")
  250. }
  251. if m.RecordsSHA256 == "" {
  252. return fmt.Errorf("capture: empty records_sha256 is not valid")
  253. }
  254. if m.APIVersion == "" {
  255. return fmt.Errorf("capture: api_schema_version required")
  256. }
  257. if m.ProfileHash == "" {
  258. return fmt.Errorf("capture: empty profile_hash is not valid")
  259. }
  260. }
  261. if apiVersion != "" && m.APIVersion != "" && m.APIVersion != apiVersion {
  262. return fmt.Errorf("capture: api_version %q != %q", m.APIVersion, apiVersion)
  263. }
  264. if capHash != "" {
  265. if m.CapabilityHash == "" {
  266. return fmt.Errorf("capture: empty capability_hash is not valid")
  267. }
  268. if m.CapabilityHash != capHash {
  269. return fmt.Errorf("capture: capability_hash mismatch")
  270. }
  271. }
  272. return nil
  273. }
  274. func ValidateRecordsAgainstManifest(m Manifest, recs []Record, recSHA string) error {
  275. m.Normalize()
  276. if m.RecordCount != len(recs) {
  277. return fmt.Errorf("capture: record_count %d != %d records", m.RecordCount, len(recs))
  278. }
  279. if m.RecordsSHA256 != "" && recSHA != "" && m.RecordsSHA256 != recSHA {
  280. return fmt.Errorf("capture: records_sha256 mismatch")
  281. }
  282. if len(recs) == 0 {
  283. if m.Status == StatusComplete || m.CompletionStatus == StatusComplete {
  284. return fmt.Errorf("capture: complete capture with zero records is not valid")
  285. }
  286. if m.FirstSourceEventID != 0 || m.LastSourceEventID != 0 {
  287. return fmt.Errorf("capture: empty records but event ids set")
  288. }
  289. return nil
  290. }
  291. var prev uint64
  292. for i, rec := range recs {
  293. if rec.V != 0 && rec.V != Version {
  294. return fmt.Errorf("capture: record %d unsupported version %d", i, rec.V)
  295. }
  296. id := rec.SourceID()
  297. if i > 0 && id != 0 && prev != 0 && id < prev {
  298. return fmt.Errorf("capture: source event id not monotonic at %d: %d < %d", i, id, prev)
  299. }
  300. if id != 0 {
  301. prev = id
  302. }
  303. }
  304. first := recs[0].SourceID()
  305. last := recs[len(recs)-1].SourceID()
  306. if m.FirstSourceEventID != 0 && m.FirstSourceEventID != first {
  307. return fmt.Errorf("capture: first_source_event_id %d != %d", m.FirstSourceEventID, first)
  308. }
  309. if m.LastSourceEventID != 0 && m.LastSourceEventID != last {
  310. return fmt.Errorf("capture: last_source_event_id %d != %d", m.LastSourceEventID, last)
  311. }
  312. return nil
  313. }
  314. func SnapshotRecord(s *hthv1.Snapshot) (Record, error) {
  315. b, err := marshal.Marshal(s)
  316. if err != nil {
  317. return Record{}, err
  318. }
  319. wt := time.Time{}
  320. if s.WallTime != nil {
  321. wt = s.WallTime.AsTime()
  322. }
  323. return Record{Kind: "snapshot", EventID: s.EventId, SourceEventID: s.EventId, WallTime: wt, Snapshot: b}, nil
  324. }
  325. func EventRecord(e *hthv1.Event) (Record, error) {
  326. b, err := marshal.Marshal(e)
  327. if err != nil {
  328. return Record{}, err
  329. }
  330. wt := time.Time{}
  331. if e.WallTime != nil {
  332. wt = e.WallTime.AsTime()
  333. }
  334. return Record{Kind: "event", EventID: e.EventId, SourceEventID: e.EventId, WallTime: wt, Event: b}, nil
  335. }
  336. func ReadManifest(dir string) (Manifest, error) {
  337. var m Manifest
  338. f, err := os.Open(filepath.Join(dir, "manifest.json"))
  339. if err != nil {
  340. return m, err
  341. }
  342. defer f.Close()
  343. dec := json.NewDecoder(f)
  344. dec.DisallowUnknownFields()
  345. if err := dec.Decode(&m); err != nil {
  346. return m, fmt.Errorf("capture: manifest: %w", err)
  347. }
  348. var extra json.RawMessage
  349. if err := dec.Decode(&extra); err != io.EOF {
  350. if err == nil {
  351. return m, fmt.Errorf("capture: trailing data after manifest")
  352. }
  353. return m, fmt.Errorf("capture: manifest trailing: %w", err)
  354. }
  355. m.Normalize()
  356. return m, nil
  357. }
  358. func ReadRecords(path string) ([]Record, error) {
  359. fi, err := os.Stat(path)
  360. if err != nil {
  361. return nil, err
  362. }
  363. if fi.Size() > MaxRecordsBytes {
  364. return nil, fmt.Errorf("capture: records size %d exceeds %d", fi.Size(), MaxRecordsBytes)
  365. }
  366. f, err := os.Open(path)
  367. if err != nil {
  368. return nil, err
  369. }
  370. defer f.Close()
  371. var out []Record
  372. sc := bufio.NewScanner(f)
  373. sc.Buffer(make([]byte, 0, 64*1024), MaxRecordLine)
  374. for sc.Scan() {
  375. line := sc.Bytes()
  376. if len(line) == 0 {
  377. continue
  378. }
  379. var rec Record
  380. if err := json.Unmarshal(line, &rec); err != nil {
  381. return nil, fmt.Errorf("capture: bad record: %w", err)
  382. }
  383. if rec.Kind != "snapshot" && rec.Kind != "event" {
  384. return nil, fmt.Errorf("capture: unknown record kind %q", rec.Kind)
  385. }
  386. out = append(out, rec)
  387. if len(out) > MaxRecordCount {
  388. return nil, fmt.Errorf("capture: %d records exceeds limit %d", len(out), MaxRecordCount)
  389. }
  390. }
  391. if err := sc.Err(); err != nil {
  392. return nil, err
  393. }
  394. return out, nil
  395. }
  396. func DecodeSnapshot(rec Record) (*hthv1.Snapshot, error) {
  397. if len(rec.Snapshot) == 0 {
  398. return nil, fmt.Errorf("no snapshot")
  399. }
  400. s := &hthv1.Snapshot{}
  401. return s, protojson.Unmarshal(rec.Snapshot, s)
  402. }
  403. func DecodeEvent(rec Record) (*hthv1.Event, error) {
  404. if len(rec.Event) == 0 {
  405. return nil, fmt.Errorf("no event")
  406. }
  407. e := &hthv1.Event{}
  408. return e, protojson.Unmarshal(rec.Event, e)
  409. }
  410. func RecordsPath(dir string) string {
  411. return filepath.Join(dir, "records.jsonl")
  412. }