replay.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. package backend
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "sync"
  9. "time"
  10. "hth/internal/capture"
  11. "hth/internal/protocol"
  12. )
  13. var ErrReplayEOF = fmt.Errorf("replay: end of capture")
  14. const maxReplayRecords = 1_000_000
  15. type Replay struct {
  16. path string
  17. speed float64
  18. step bool
  19. fromEventID uint64
  20. requireComplete bool
  21. apiVersion string
  22. capHash string
  23. mu sync.Mutex
  24. items []ReplayItem
  25. idx int
  26. lastWall time.Time
  27. haveLast bool
  28. stepCh chan struct{}
  29. }
  30. func NewReplay(path string, speed float64, step bool, fromEventID uint64) *Replay {
  31. if speed <= 0 {
  32. speed = 1
  33. }
  34. return &Replay{
  35. path: path, speed: speed, step: step, fromEventID: fromEventID,
  36. requireComplete: true,
  37. stepCh: make(chan struct{}, 1),
  38. }
  39. }
  40. func (r *Replay) SetContract(apiVersion, capHash string) {
  41. r.apiVersion = apiVersion
  42. r.capHash = capHash
  43. }
  44. func (r *Replay) Kind() string { return "replay" }
  45. func (r *Replay) PollMode() PollMode { return PollReplay }
  46. func (r *Replay) Stepping() bool { return r.step }
  47. func looksLikeSerial(path string) bool {
  48. p := strings.ToLower(path)
  49. return strings.HasPrefix(p, "/dev/tty") ||
  50. strings.HasPrefix(p, "/dev/hth") ||
  51. strings.HasPrefix(p, "/dev/serial") ||
  52. strings.Contains(p, "ttyusb") ||
  53. strings.Contains(p, "ttyacm")
  54. }
  55. func (r *Replay) Open(context.Context) error {
  56. if looksLikeSerial(r.path) {
  57. return fmt.Errorf("%w: %s", ErrReplaySerial, r.path)
  58. }
  59. fi, err := os.Stat(r.path)
  60. if err != nil {
  61. return err
  62. }
  63. if fi.Mode()&os.ModeDevice != 0 || fi.Mode()&os.ModeCharDevice != 0 {
  64. return fmt.Errorf("%w: %s is a device node", ErrReplaySerial, r.path)
  65. }
  66. dir := r.path
  67. recPath := r.path
  68. if fi.IsDir() {
  69. recPath = capture.RecordsPath(r.path)
  70. } else {
  71. dir = filepath.Dir(r.path)
  72. }
  73. man, err := capture.ReadManifest(dir)
  74. if err != nil {
  75. return fmt.Errorf("capture: manifest required: %w", err)
  76. }
  77. if err := capture.ValidateManifest(man, r.apiVersion, r.capHash, r.requireComplete); err != nil {
  78. return err
  79. }
  80. rfi, err := os.Stat(recPath)
  81. if err != nil {
  82. return err
  83. }
  84. if rfi.Size() > capture.MaxRecordsBytes {
  85. return fmt.Errorf("capture: records size %d exceeds %d", rfi.Size(), capture.MaxRecordsBytes)
  86. }
  87. if rfi.Size() == 0 {
  88. return fmt.Errorf("capture: empty records")
  89. }
  90. raw, err := os.ReadFile(recPath)
  91. if err != nil {
  92. return err
  93. }
  94. if raw[len(raw)-1] != '\n' {
  95. return fmt.Errorf("capture: truncated records.jsonl (missing trailing newline)")
  96. }
  97. recSHA, err := capture.HashFile(recPath)
  98. if err != nil {
  99. return err
  100. }
  101. recs, err := capture.ReadRecords(recPath)
  102. if err != nil {
  103. return fmt.Errorf("capture: records: %w", err)
  104. }
  105. if err := capture.ValidateRecordsAgainstManifest(man, recs, recSHA); err != nil {
  106. return err
  107. }
  108. if len(recs) > maxReplayRecords {
  109. return fmt.Errorf("capture: %d records exceeds limit %d", len(recs), maxReplayRecords)
  110. }
  111. r.mu.Lock()
  112. defer r.mu.Unlock()
  113. r.items = r.items[:0]
  114. for _, rec := range recs {
  115. if rec.V != 0 && rec.V != capture.Version {
  116. return fmt.Errorf("capture: unsupported record version %d", rec.V)
  117. }
  118. if rec.Kind != "snapshot" && rec.Kind != "event" {
  119. return fmt.Errorf("capture: unknown record kind %q", rec.Kind)
  120. }
  121. src := rec.SourceID()
  122. if src < r.fromEventID {
  123. continue
  124. }
  125. r.items = append(r.items, ReplayItem{
  126. Kind: rec.Kind,
  127. EventID: src,
  128. WallTime: rec.WallTime,
  129. Snapshot: rec.Snapshot,
  130. Event: rec.Event,
  131. })
  132. }
  133. r.idx = 0
  134. r.haveLast = false
  135. return nil
  136. }
  137. func (r *Replay) Close() error { return nil }
  138. func (r *Replay) WriteSetAll(context.Context, protocol.SetAll) (WriteResult, error) {
  139. return WriteResult{}, ErrReadOnly
  140. }
  141. func (r *Replay) GetTemperature(context.Context) (*TempReport, error) {
  142. return nil, ErrReadOnly
  143. }
  144. func (r *Replay) GetMotorStatus(context.Context) (*MotorReport, error) {
  145. return nil, ErrReadOnly
  146. }
  147. func (r *Replay) RequestStep() {
  148. select {
  149. case r.stepCh <- struct{}{}:
  150. default:
  151. }
  152. }
  153. func (r *Replay) Next(ctx context.Context) (ReplayItem, error) {
  154. r.mu.Lock()
  155. if r.idx >= len(r.items) {
  156. r.mu.Unlock()
  157. return ReplayItem{}, ErrReplayEOF
  158. }
  159. item := r.items[r.idx]
  160. last := r.lastWall
  161. have := r.haveLast
  162. step := r.step
  163. speed := r.speed
  164. r.mu.Unlock()
  165. if !step && have && !item.WallTime.IsZero() && !last.IsZero() && speed < 1000 {
  166. dt := item.WallTime.Sub(last)
  167. if dt > 0 {
  168. wait := time.Duration(float64(dt) / speed)
  169. select {
  170. case <-ctx.Done():
  171. return ReplayItem{}, ctx.Err()
  172. case <-time.After(wait):
  173. }
  174. }
  175. }
  176. r.mu.Lock()
  177. defer r.mu.Unlock()
  178. if r.idx >= len(r.items) {
  179. return ReplayItem{}, ErrReplayEOF
  180. }
  181. item = r.items[r.idx]
  182. r.idx++
  183. if !item.WallTime.IsZero() {
  184. r.lastWall = item.WallTime
  185. r.haveLast = true
  186. }
  187. return item, nil
  188. }
  189. func CaptureFile(dir string) string { return filepath.Join(dir, "records.jsonl") }