| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207 |
- package backend
- import (
- "context"
- "fmt"
- "os"
- "path/filepath"
- "strings"
- "sync"
- "time"
- "hth/internal/capture"
- "hth/internal/protocol"
- )
- var ErrReplayEOF = fmt.Errorf("replay: end of capture")
- const maxReplayRecords = 1_000_000
- type Replay struct {
- path string
- speed float64
- step bool
- fromEventID uint64
- requireComplete bool
- apiVersion string
- capHash string
- mu sync.Mutex
- items []ReplayItem
- idx int
- lastWall time.Time
- haveLast bool
- stepCh chan struct{}
- }
- func NewReplay(path string, speed float64, step bool, fromEventID uint64) *Replay {
- if speed <= 0 {
- speed = 1
- }
- return &Replay{
- path: path, speed: speed, step: step, fromEventID: fromEventID,
- requireComplete: true,
- stepCh: make(chan struct{}, 1),
- }
- }
- func (r *Replay) SetContract(apiVersion, capHash string) {
- r.apiVersion = apiVersion
- r.capHash = capHash
- }
- func (r *Replay) Kind() string { return "replay" }
- func (r *Replay) PollMode() PollMode { return PollReplay }
- func (r *Replay) Stepping() bool { return r.step }
- func looksLikeSerial(path string) bool {
- p := strings.ToLower(path)
- return strings.HasPrefix(p, "/dev/tty") ||
- strings.HasPrefix(p, "/dev/hth") ||
- strings.HasPrefix(p, "/dev/serial") ||
- strings.Contains(p, "ttyusb") ||
- strings.Contains(p, "ttyacm")
- }
- func (r *Replay) Open(context.Context) error {
- if looksLikeSerial(r.path) {
- return fmt.Errorf("%w: %s", ErrReplaySerial, r.path)
- }
- fi, err := os.Stat(r.path)
- if err != nil {
- return err
- }
- if fi.Mode()&os.ModeDevice != 0 || fi.Mode()&os.ModeCharDevice != 0 {
- return fmt.Errorf("%w: %s is a device node", ErrReplaySerial, r.path)
- }
- dir := r.path
- recPath := r.path
- if fi.IsDir() {
- recPath = capture.RecordsPath(r.path)
- } else {
- dir = filepath.Dir(r.path)
- }
- man, err := capture.ReadManifest(dir)
- if err != nil {
- return fmt.Errorf("capture: manifest required: %w", err)
- }
- if err := capture.ValidateManifest(man, r.apiVersion, r.capHash, r.requireComplete); err != nil {
- return err
- }
- rfi, err := os.Stat(recPath)
- if err != nil {
- return err
- }
- if rfi.Size() > capture.MaxRecordsBytes {
- return fmt.Errorf("capture: records size %d exceeds %d", rfi.Size(), capture.MaxRecordsBytes)
- }
- if rfi.Size() == 0 {
- return fmt.Errorf("capture: empty records")
- }
- raw, err := os.ReadFile(recPath)
- if err != nil {
- return err
- }
- if raw[len(raw)-1] != '\n' {
- return fmt.Errorf("capture: truncated records.jsonl (missing trailing newline)")
- }
- recSHA, err := capture.HashFile(recPath)
- if err != nil {
- return err
- }
- recs, err := capture.ReadRecords(recPath)
- if err != nil {
- return fmt.Errorf("capture: records: %w", err)
- }
- if err := capture.ValidateRecordsAgainstManifest(man, recs, recSHA); err != nil {
- return err
- }
- if len(recs) > maxReplayRecords {
- return fmt.Errorf("capture: %d records exceeds limit %d", len(recs), maxReplayRecords)
- }
- r.mu.Lock()
- defer r.mu.Unlock()
- r.items = r.items[:0]
- for _, rec := range recs {
- if rec.V != 0 && rec.V != capture.Version {
- return fmt.Errorf("capture: unsupported record version %d", rec.V)
- }
- if rec.Kind != "snapshot" && rec.Kind != "event" {
- return fmt.Errorf("capture: unknown record kind %q", rec.Kind)
- }
- src := rec.SourceID()
- if src < r.fromEventID {
- continue
- }
- r.items = append(r.items, ReplayItem{
- Kind: rec.Kind,
- EventID: src,
- WallTime: rec.WallTime,
- Snapshot: rec.Snapshot,
- Event: rec.Event,
- })
- }
- r.idx = 0
- r.haveLast = false
- return nil
- }
- func (r *Replay) Close() error { return nil }
- func (r *Replay) WriteSetAll(context.Context, protocol.SetAll) (WriteResult, error) {
- return WriteResult{}, ErrReadOnly
- }
- func (r *Replay) GetTemperature(context.Context) (*TempReport, error) {
- return nil, ErrReadOnly
- }
- func (r *Replay) GetMotorStatus(context.Context) (*MotorReport, error) {
- return nil, ErrReadOnly
- }
- func (r *Replay) RequestStep() {
- select {
- case r.stepCh <- struct{}{}:
- default:
- }
- }
- func (r *Replay) Next(ctx context.Context) (ReplayItem, error) {
- r.mu.Lock()
- if r.idx >= len(r.items) {
- r.mu.Unlock()
- return ReplayItem{}, ErrReplayEOF
- }
- item := r.items[r.idx]
- last := r.lastWall
- have := r.haveLast
- step := r.step
- speed := r.speed
- r.mu.Unlock()
- if !step && have && !item.WallTime.IsZero() && !last.IsZero() && speed < 1000 {
- dt := item.WallTime.Sub(last)
- if dt > 0 {
- wait := time.Duration(float64(dt) / speed)
- select {
- case <-ctx.Done():
- return ReplayItem{}, ctx.Err()
- case <-time.After(wait):
- }
- }
- }
- r.mu.Lock()
- defer r.mu.Unlock()
- if r.idx >= len(r.items) {
- return ReplayItem{}, ErrReplayEOF
- }
- item = r.items[r.idx]
- r.idx++
- if !item.WallTime.IsZero() {
- r.lastWall = item.WallTime
- r.haveLast = true
- }
- return item, nil
- }
- func CaptureFile(dir string) string { return filepath.Join(dir, "records.jsonl") }
|