package device import ( "context" "errors" "fmt" "log/slog" "os" "sort" "strings" "sync" "sync/atomic" "time" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/durationpb" "google.golang.org/protobuf/types/known/timestamppb" "hth/internal/backend" "hth/internal/caphash" "hth/internal/capture" "hth/internal/clock" "hth/internal/config" "hth/internal/control" "hth/internal/faults" hthv1 "hth/internal/gen/hth/api/v1" "hth/internal/grpcserver" "hth/internal/ids" "hth/internal/profile" "hth/internal/protocol" "hth/internal/safety" "hth/internal/state" "hth/internal/telemetry" ) type opKind int const ( opAcquire opKind = iota opRenew opRelease opValidate opApply opSafe opStep opResume ) const applyBurstLimit = 4 type req struct { kind opKind batch *hthv1.ActionBatch holder string ttl time.Duration leaseID string leaseEpoch uint64 reason string rpcCtx context.Context reply chan res } type res struct { lease *hthv1.ControlLease action *hthv1.ActionResult err error } type Device struct { cfg *config.Config prof *profile.Profile backend backend.Backend log *slog.Logger clk clock.Clock id string daemon string store *state.Store hub *telemetry.Hub book *faults.Book lease *control.Manager safeCh chan req applyCh chan req applyMu sync.Mutex ctrlCh chan req lastCont protocol.SetAll haveCont bool startupDone bool connected bool safeMode bool controlMode hthv1.SafetyControlMode draining bool pendingTemp bool lastTemp time.Time caps *hthv1.Capabilities cancel context.CancelFunc wg sync.WaitGroup stopOnce sync.Once lifeMu sync.Mutex stopped atomic.Bool inflightApply []chan res lastDispatchAt time.Time haveDispatch bool baselineReady bool jobs chan serialJob results chan serialResult pendingHB bool pendingApply []req applyJob *applyJobState runCtx context.Context progressUnix int64 inflightSinceNano int64 lastMotor time.Time replayEOF atomic.Bool lastStepEvent *hthv1.Event lastStepSnap *hthv1.Snapshot workerCancel context.CancelFunc slewCredit map[string]float64 shutdownSafeResult *hthv1.ActionResult maxTxnOverrideNano int64 inflightTimeout time.Duration inflightKind jobKind controlWindowUntil time.Time jobSeq uint64 portGen uint64 inflightMu sync.Mutex currentInflight inflightIdent pendingResume *pendingResumeState pendingSafeJob *pendingSafeState cmdSeq uint64 lastHWHeartbeat time.Time hbDeliveryState hthv1.ActionDispatchState safetyContract safety.EffectiveContract safetyErr error workerCtx context.Context actorHold atomic.Bool } type applyJobState struct { reply chan res batch *hthv1.ActionBatch payload []byte target protocol.SetAll result *hthv1.ActionResult resume bool credit map[string]float64 } type Params struct { Config *config.Config Profile *profile.Profile Backend backend.Backend Logger *slog.Logger Clock clock.Clock InstanceID string } func New(p Params) *Device { clk := p.Clock if clk == nil { clk = clock.Real{} } log := p.Logger if log == nil { log = slog.Default() } d := &Device{ cfg: p.Config, prof: p.Profile, backend: p.Backend, log: log, clk: clk, id: p.Config.DeviceID, daemon: p.InstanceID, store: state.NewStore(p.Config.DeviceID, p.InstanceID, clk), hub: telemetry.NewHub(p.Config.RingBufferSize, p.Config.SubscriberBufferSize, p.Config.MaxSubscribers, p.Config.MaxStreamsPerPeer), book: faults.NewBook(256), lease: control.NewManager(p.Config.DeviceID, p.Config.MinTTL(), p.Config.MaxTTL(), p.Config.CommandCacheSize), safeCh: make(chan req, 4), applyCh: make(chan req, 1), ctrlCh: make(chan req, 16), jobs: make(chan serialJob, 1), results: make(chan serialResult, 1), caps: buildCaps(p.Config, p.Profile), lastCont: protocol.SetAll{}, slewCredit: map[string]float64{}, controlMode: hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_NORMAL, } if p.Config != nil { c, err := safety.BuildEffectiveSafetyContract(p.Profile, p.Config.Safety) d.safetyContract = c d.safetyErr = err if err == nil { d.caps = overlaySafetyDefaults(d.caps, c) d.caps.CapabilityHash = caphash.HashCanonicalCapabilities(d.caps) } } d.hub.SetIDAlloc(d.store.NextEventID) d.book.SetHook(d.publishFaultEvent) return d } func (d *Device) ID() string { return d.id } func (d *Device) Start(parent context.Context) { if parent == nil { parent = context.Background() } d.lifeMu.Lock() defer d.lifeMu.Unlock() if d.stopped.Load() { return } actorCtx, actorCancel := context.WithCancel(parent) workerCtx, workerCancel := context.WithCancel(context.Background()) d.cancel = actorCancel d.workerCancel = workerCancel d.runCtx = actorCtx d.workerCtx = workerCtx if d.safetyErr != nil { d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_UNAVAILABLE) d.book.Raise(d.clk.Now(), hthv1.FaultType_FAULT_TYPE_CONFIG_INVALID, d.id, "", "effective safety contract invalid: "+d.safetyErr.Error(), "", nil) d.publishNow() // Actor still runs so Stop/Doctor work, but UART is never opened. } d.wg.Add(2) go func() { defer d.wg.Done() d.serialWorker(workerCtx) }() go func() { defer d.wg.Done() d.loop(actorCtx) }() } func (d *Device) Stop() { d.stopOnce.Do(func() { d.stopped.Store(true) d.lifeMu.Lock() cancel := d.cancel workerCancel := d.workerCancel d.lifeMu.Unlock() if cancel != nil { cancel() } deadline := d.cfg.ShutdownSafeTimeout() if deadline < 2*time.Second { deadline = 2 * time.Second } done := make(chan struct{}) go func() { d.wg.Wait() close(done) }() select { case <-done: _ = d.backend.Close() case <-time.After(deadline): _ = d.backend.Close() if workerCancel != nil { workerCancel() } join := deadline if join > 3*time.Second { join = 3 * time.Second } select { case <-done: case <-time.After(join): d.book.Raise(d.clk.Now(), hthv1.FaultType_FAULT_TYPE_SERIAL_DISCONNECTED, d.id, "", "worker join exceeded deadline after Close; process should exit for systemd restart", "", nil) } } }) } func (d *Device) loop(ctx context.Context) { d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_CONNECTING) d.publishInfo(ctx, hthv1.EventKind_EVENT_KIND_BACKEND_STATE, "connecting") hb := time.NewTicker(d.cfg.Heartbeat()) motor := time.NewTicker(d.cfg.MotorPoll()) temp := time.NewTicker(d.cfg.TemperaturePoll()) leaseTick := time.NewTicker(100 * time.Millisecond) reconnect := time.NewTicker(100 * time.Millisecond) defer hb.Stop() defer motor.Stop() defer temp.Stop() defer leaseTick.Stop() defer reconnect.Stop() backoff := time.Duration(0) nextTry := time.Time{} d.tryOpen(ctx, &backoff, &nextTry) applyBurst := 0 for { d.markProgress() for d.actorHold.Load() { d.markProgress() if ctx.Err() != nil { d.runShutdown() return } time.Sleep(2 * time.Millisecond) } for { select { case r := <-d.safeCh: d.handle(ctx, r) default: goto afterSafe } } afterSafe: select { case r := <-d.ctrlCh: d.handle(ctx, r) case res := <-d.results: d.applySerialResult(ctx, res, &backoff, &nextTry) default: } if applyBurst < applyBurstLimit { select { case r := <-d.applyCh: d.handle(ctx, r) applyBurst++ continue default: applyBurst = 0 } } else { applyBurst = 0 } select { case <-ctx.Done(): d.runShutdown() return case r := <-d.safeCh: d.handle(ctx, r) case r := <-d.ctrlCh: d.handle(ctx, r) case r := <-d.applyCh: d.handle(ctx, r) applyBurst = 1 case res := <-d.results: d.applySerialResult(ctx, res, &backoff, &nextTry) case <-hb.C: d.heartbeat(ctx) case <-motor.C: if d.backend.PollMode() == backend.PollUART && d.connected && !d.serialInflight() { d.enqueueSerial(serialJob{kind: jobGetMotor, timeout: d.cfg.GetMotorTimeout()}) } case <-temp.C: if d.backend.PollMode() == backend.PollUART && d.connected && d.startupDone { if d.serialInflight() || d.pendingSafeJob != nil || d.pendingResume != nil || len(d.pendingApply) > 0 || d.controlWindowOpen(d.clk.Now()) { d.pendingTemp = true break } d.enqueueSerial(serialJob{kind: jobGetTemp, timeout: d.cfg.GetTempTimeout(d.prof)}) } case <-leaseTick.C: d.checkLease(ctx) case <-reconnect.C: if d.backend.PollMode() == backend.PollReplay { d.replayTick(ctx) continue } d.recoverStuckSerial(ctx, &backoff, &nextTry) if d.connected { d.kickPendingSerial(ctx) } if !d.connected && (nextTry.IsZero() || !d.clk.Now().Before(nextTry)) { d.tryOpen(ctx, &backoff, &nextTry) } } } } func (d *Device) tryOpen(ctx context.Context, backoff *time.Duration, next *time.Time) { _ = ctx if d.safetyErr != nil { return } if d.connected || d.serialInflight() { return } if !next.IsZero() && d.clk.Now().Before(*next) { return } d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_CONNECTING) if !d.enqueueSerial(serialJob{kind: jobOpen, timeout: d.cfg.OpenTimeout()}) { d.log.Warn("serial open enqueue failed") } } func (d *Device) MaxSerialTxn() time.Duration { return d.maxSerialTxn() } func (d *Device) maxSerialTxn() time.Duration { if n := atomic.LoadInt64(&d.maxTxnOverrideNano); n > 0 { return time.Duration(n) } m := d.cfg.GetTempTimeout(d.prof) for _, x := range []time.Duration{d.cfg.GetMotorTimeout(), d.cfg.SetAllTimeout(), d.cfg.ProbeTimeout(), d.cfg.OpenTimeout(), d.cfg.ShutdownSafeTimeout()} { if x > m { m = x } } if m < 2*time.Second { m = 2 * time.Second } // Worker context timeout is `m`; allow the actor to observe a clean // timeout/error before treating the worker as wedged. return m + 2*time.Second } func (d *Device) recoverStuckSerial(ctx context.Context, backoff *time.Duration, next *time.Time) { if !d.serialInflight() { return } busy := d.SerialBusy() if busy <= d.maxSerialTxn() { return } d.log.Error("serial worker exceeded max transaction time", "busy", busy, "limit", d.maxSerialTxn()) if ir, ok := d.backend.(backend.Interrupter); ok { ir.Interrupt() } d.onDrop(ctx, fmt.Errorf("serial worker watchdog: inflight %s", busy)) *backoff = serialBackoff(*backoff) *next = d.clk.Now().Add(*backoff) } func serialBackoff(cur time.Duration) time.Duration { if cur <= 0 { return 100 * time.Millisecond } n := cur * 2 if n > 5*time.Second { return 5 * time.Second } return n } func (d *Device) onDrop(ctx context.Context, cause error) { _ = ctx d.connected = false d.startupDone = false d.lastTemp = time.Time{} d.lastCont = protocol.SetAll{} d.haveCont = false d.haveDispatch = false d.baselineReady = false d.inflightMu.Lock() d.portGen++ d.inflightMu.Unlock() d.slewCredit = map[string]float64{} if d.controlMode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE || d.controlMode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_RESUME_PENDING { d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING, "transport_drop") } d.endInflight() d.pendingSafeJob = nil select { case <-d.jobs: default: } epoch := d.store.BumpEpoch() d.lease.InvalidateAndBump() d.failInflight() d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_UNAVAILABLE) d.book.Raise(d.clk.Now(), hthv1.FaultType_FAULT_TYPE_SERIAL_DISCONNECTED, d.id, "", cause.Error(), "", nil) now := d.clk.Now() snap := d.store.Commit(func(s *hthv1.Snapshot) { s.Measurements = missingTemps(d.prof, now, "SERIAL_DROP_NOT_REUSING_OLD_SNAPSHOT") s.ContinuousTargets = nil s.LastRequested = nil s.LastAccepted = nil s.LastDispatched = nil s.Lease = d.lease.Current().Summary(now) s.ActiveFaults = d.book.Active() s.DeviceConfirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN d.annotateSnapshot(s) }) d.hub.PublishSnapshot(snap, now) d.hub.PublishEvent(&hthv1.Event{ EventId: d.store.NextEventID(), Kind: hthv1.EventKind_EVENT_KIND_DEVICE_EPOCH_CHANGED, WallTime: timestamppb.New(now), DeviceId: d.id, Message: fmt.Sprintf("epoch=%d", epoch), }) _ = d.backend.Close() } func (d *Device) failInflight() { unknown := func(msg string) res { return res{action: &hthv1.ActionResult{ Accepted: false, RejectReason: hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY, Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN, Message: msg, DeviceEpoch: d.store.Epoch(), }} } if d.applyJob != nil { replyNonblock(d.applyJob.reply, unknown("serial drop while inflight")) d.applyJob = nil } for _, r := range d.pendingApply { replyNonblock(r.reply, unknown("serial drop while queued")) } d.pendingApply = nil d.pendingHB = false d.pendingSafeJob = nil if d.pendingResume != nil { d.abortPendingResume("serial drop while queued", hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_OUTCOME_UNKNOWN) } for _, ch := range d.inflightApply { replyNonblock(ch, unknown("serial drop while inflight")) } d.inflightApply = nil } func (d *Device) handle(ctx context.Context, r req) { for d.actorHold.Load() && ctx.Err() == nil { if r.rpcCtx != nil && r.rpcCtx.Err() != nil { replyNonblock(r.reply, res{err: r.rpcCtx.Err(), action: cancelledResult(r.batch, r.rpcCtx.Err())}) return } time.Sleep(2 * time.Millisecond) } if (d.draining || ctx.Err() != nil) && (r.kind == opAcquire || r.kind == opApply || r.kind == opResume) { reason := hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY st := hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED conf := hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED if r.kind == opApply { reason = hthv1.RejectReason_REJECT_REASON_SUPERSEDED_BY_SHUTDOWN st = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_SUPERSEDED conf = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED } r.reply <- res{action: &hthv1.ActionResult{ CommandId: r.batch.GetCommandId(), Accepted: false, RejectReason: reason, Confirmation: conf, DispatchState: st, Message: "daemon draining", DeviceEpoch: d.store.Epoch(), }} return } switch r.kind { case opAcquire: if r.rpcCtx != nil && r.rpcCtx.Err() != nil { replyNonblock(r.reply, res{err: r.rpcCtx.Err(), action: cancelledResult(r.batch, r.rpcCtx.Err())}) return } l, err := d.lease.Acquire(d.clk.Now(), r.holder, r.ttl) if err != nil { replyNonblock(r.reply, res{err: err}) return } d.publishEvent(hthv1.EventKind_EVENT_KIND_LEASE_ACQUIRED, "acquired") d.publishNow() replyNonblock(r.reply, res{lease: l.Proto()}) case opRenew: if r.rpcCtx != nil && r.rpcCtx.Err() != nil { replyNonblock(r.reply, res{err: r.rpcCtx.Err(), action: cancelledResult(r.batch, r.rpcCtx.Err())}) return } l, err := d.lease.Renew(d.clk.Now(), r.leaseID, r.leaseEpoch, r.ttl) if err != nil { replyNonblock(r.reply, res{err: err}) return } d.publishEvent(hthv1.EventKind_EVENT_KIND_LEASE_RENEWED, "renewed") d.publishNow() replyNonblock(r.reply, res{lease: l.Proto()}) case opRelease: if r.rpcCtx != nil && r.rpcCtx.Err() != nil { replyNonblock(r.reply, res{err: r.rpcCtx.Err(), action: cancelledResult(r.batch, r.rpcCtx.Err())}) return } err := d.lease.Release(d.clk.Now(), r.leaseID, r.leaseEpoch) if err != nil { replyNonblock(r.reply, res{err: err}) return } d.publishEvent(hthv1.EventKind_EVENT_KIND_LEASE_RELEASED, "released") d.enterSafe(ctx, "lease_released") replyNonblock(r.reply, res{}) case opValidate: r.reply <- res{action: d.validate(r.batch)} case opApply: d.beginApply(ctx, r) case opResume: d.beginResume(ctx, r) case opSafe: now := d.clk.Now() rr := d.lease.CheckAction(now, &hthv1.ActionBatch{ CommandId: "safe", LeaseId: r.leaseID, LeaseEpoch: r.leaseEpoch, }, d.store.Seq(), d.store.ControlRevision()) if rr != 0 && rr != hthv1.RejectReason_REJECT_REASON_STALE_SNAPSHOT && rr != hthv1.RejectReason_REJECT_REASON_STALE_CONTROL_REVISION { r.reply <- res{action: &hthv1.ActionResult{ Accepted: false, RejectReason: rr, Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED, Message: rr.String(), DeviceEpoch: d.store.Epoch(), }} return } r.reply <- res{action: func() *hthv1.ActionResult { out := d.enterSafe(ctx, r.reason) d.attachPeer(r, out) return out }()} case opStep: r.reply <- res{action: d.stepReplay(ctx)} } } func (d *Device) validate(batch *hthv1.ActionBatch) *hthv1.ActionResult { out := d.assembleResult(batch, true, false) return out } func (d *Device) assembleResult(batch *hthv1.ActionBatch, validateOnly, resume bool) *hthv1.ActionResult { now := d.clk.Now() res := &hthv1.ActionResult{CommandId: "", DeviceEpoch: d.store.Epoch()} if batch == nil { res.RejectReason = hthv1.RejectReason_REJECT_REASON_INVALID_ARGUMENT res.Message = "nil batch" res.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED return res } res.CommandId = batch.CommandId res.Requested = rawRequestedRecord(batch, now) res.RawRequested = res.Requested if batch.DeviceId != "" && batch.DeviceId != d.id { res.RejectReason = hthv1.RejectReason_REJECT_REASON_UNKNOWN_ID res.Message = "device_id mismatch" res.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED return res } if !validateOnly && !d.connected { res.RejectReason = hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY res.Message = "transport not connected" res.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED res.Accepted = false return res } if !validateOnly && !d.baselineReady { res.RejectReason = hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY res.Message = "epoch safety baseline not established; partial actions rejected" res.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED res.Accepted = false return res } if !validateOnly && batch.ValidUntil == nil { res.RejectReason = hthv1.RejectReason_REJECT_REASON_INVALID_ARGUMENT res.Message = "valid_until required for ApplyAction" res.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED return res } payload := control.PayloadHash(batch) if !validateOnly { if hit, conflict := d.lease.Cache().Lookup(batch.CommandId, payload); conflict { res.RejectReason = hthv1.RejectReason_REJECT_REASON_IDEMPOTENCY_CONFLICT res.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED res.Message = "command_id reused with different payload" return res } else if hit != nil { hit.ReplayedFromCache = true return hit } if rr := d.lease.CheckAction(now, batch, d.store.Seq(), d.store.ControlRevision()); rr != 0 { res.RejectReason = rr res.Accepted = false res.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED res.Message = rr.String() d.book.Raise(now, hthv1.FaultType_FAULT_TYPE_CONTROL_COMMAND_REJECTED, d.id, batch.CommandId, rr.String(), "", nil) return res } if !d.cfg.AllowUnboundActions && !resume { if batch.BasedOnSnapshotSeq == 0 || batch.ExpectedControlRevision == 0 { res.RejectReason = hthv1.RejectReason_REJECT_REASON_STALE_SNAPSHOT res.Accepted = false res.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED res.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED res.Message = "ordinary ApplyAction requires based_on_snapshot_seq and expected_control_revision" return res } } } if !validateOnly && d.latchedSafe() && !resume { res.RejectReason = hthv1.RejectReason_REJECT_REASON_SAFE_MODE_ACTIVE res.Message = "SAFE latched; use ResumeFromSafe with a complete action batch" res.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED res.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED res.Accepted = false return res } assembled := safety.Assemble(d.lastCont, batch, d.prof) audits := safety.AnnotateAudits(safety.RawFieldAudits(batch), assembled.Clamps, assembled.SetAll) if res.Requested != nil { res.Requested.FieldAudits = audits } res.NormalizedRequested = actionRecord(batch, now, hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNSPECIFIED, assembled.SetAll) if assembled.Reject != 0 { res.RejectReason = assembled.Reject res.Message = assembled.Message res.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED if assembled.Reject == hthv1.RejectReason_REJECT_REASON_CLAMP_REQUIRED || assembled.Reject == hthv1.RejectReason_REJECT_REASON_OUT_OF_RANGE { res.RejectReason = assembled.Reject if !batch.AllowClamp && assembled.Reject == hthv1.RejectReason_REJECT_REASON_OUT_OF_RANGE { res.RejectReason = hthv1.RejectReason_REJECT_REASON_ATOMIC_BATCH_FAILED res.Message = "batch rejected atomically (clamp not allowed): " + assembled.Message } } return res } if !d.startupDone && safety.DoorChanged(d.lastCont, assembled.SetAll) { res.RejectReason = hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY res.Message = "startup incomplete: batches that change door percent are rejected atomically (plan A)" res.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED res.Accepted = false return res } elapsed := time.Duration(0) if d.haveDispatch { elapsed = now.Sub(d.lastDispatchAt) } slew := safety.LimitSlew(d.lastCont, assembled.SetAll, d.prof, safety.SlewOpts{ Elapsed: elapsed, First: false, Bypass: false, AllowClamp: batch.AllowClamp, Credit: copyCredit(d.slewCredit), }) if slew.Reject != 0 { res.RejectReason = slew.Reject res.Message = slew.Message res.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED res.Accepted = false return res } if len(slew.Clamps) > 0 { assembled.Clamps = append(assembled.Clamps, slew.Clamps...) assembled.SetAll = slew.SetAll res.NormalizedRequested = actionRecord(batch, now, hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNSPECIFIED, assembled.SetAll) } if !d.startupDone && safety.DoorChanged(d.lastCont, assembled.SetAll) { res.RejectReason = hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY res.Message = "startup incomplete: batches that change door percent are rejected atomically (plan A)" res.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED res.Accepted = false return res } res.Clamps = safety.ProtoClamps(assembled.Clamps) res.Accepted = true res.AcceptedAction = actionRecord(batch, now, hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNSPECIFIED, assembled.SetAll) if validateOnly { res.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNSPECIFIED res.Message = "validated; not dispatched" return res } return res } func (d *Device) beginApply(ctx context.Context, r req) { out := d.prepareApply(ctx, r) if out == nil { return } if !out.Accepted || out.ReplayedFromCache { replyNonblock(r.reply, res{action: out}) return } if msg := d.deadlineUnmeetable(r.batch); msg != "" { out.Accepted = false out.RejectReason = hthv1.RejectReason_REJECT_REASON_EXPIRED_DEADLINE out.Message = msg out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED d.recordAction(out) replyNonblock(r.reply, res{action: out}) return } if d.serialInflight() { d.enqueueLatestApply(r) return } assembled := safety.Assemble(d.lastCont, r.batch, d.prof) now := d.clk.Now() elapsed := time.Duration(0) if d.haveDispatch { elapsed = now.Sub(d.lastDispatchAt) } credit := copyCredit(d.slewCredit) slew := safety.LimitSlew(d.lastCont, assembled.SetAll, d.prof, safety.SlewOpts{ Elapsed: elapsed, First: false, Bypass: false, AllowClamp: r.batch.AllowClamp, Credit: credit, }) target := slew.SetAll d.applyJob = &applyJobState{ reply: r.reply, batch: r.batch, payload: control.PayloadHash(r.batch), target: target, result: out, credit: credit, } ax := d.newActionContext(r.batch.GetCommandId(), "apply", hthv1.ActionMode_ACTION_MODE_NORMAL, target, r.rpcCtx) if !d.enqueueSerial(d.serialJobFromAction(jobSetAllApply, d.cfg.SetAllTimeout(), ax)) { d.applyJob = nil out.Accepted = false out.RejectReason = hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY out.Message = "serial worker busy or disconnected" out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED replyNonblock(r.reply, res{action: out}) } } func (d *Device) prepareApply(ctx context.Context, r req) *hthv1.ActionResult { batch := r.batch if d.backend.PollMode() == backend.PollReplay { return &hthv1.ActionResult{ CommandId: batch.GetCommandId(), Accepted: false, RejectReason: hthv1.RejectReason_REJECT_REASON_NOT_SUPPORTED, Message: "replay backend is read-only and never opens serial", Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_SUPPORTED, DeviceEpoch: d.store.Epoch(), Requested: rawRequestedRecord(batch, d.clk.Now()), } } now := d.clk.Now() if batch == nil { res := d.assembleResult(nil, false, r.kind == opResume) d.recordAction(res) return res } if r.rpcCtx != nil && r.rpcCtx.Err() != nil { res := &hthv1.ActionResult{ CommandId: batch.CommandId, Accepted: false, RejectReason: hthv1.RejectReason_REJECT_REASON_EXPIRED_DEADLINE, Message: "rpc cancelled before first hardware write", Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED, DeviceEpoch: d.store.Epoch(), Requested: rawRequestedRecord(batch, now), } res.RawRequested = res.Requested d.recordAction(res) return res } if batch.ValidUntil != nil && !batch.ValidUntil.AsTime().After(now) { res := &hthv1.ActionResult{ CommandId: batch.CommandId, Accepted: false, RejectReason: hthv1.RejectReason_REJECT_REASON_EXPIRED_DEADLINE, Message: "valid_until expired before first hardware write", Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED, DeviceEpoch: d.store.Epoch(), Requested: rawRequestedRecord(batch, now), } res.RawRequested = res.Requested d.recordAction(res) return res } payload := control.PayloadHash(batch) res := d.assembleResult(batch, false, r.kind == opResume) if cred, ok := grpcserver.PeerFromContext(r.rpcCtx); ok && res.Requested != nil { res.Requested.PeerUid = cred.UID res.Requested.PeerGid = cred.GID res.Requested.PeerPid = cred.PID if res.RawRequested != nil { res.RawRequested.PeerUid = cred.UID res.RawRequested.PeerGid = cred.GID res.RawRequested.PeerPid = cred.PID } } if res.ReplayedFromCache { return res } if !res.Accepted { d.lease.Cache().Store(batch.CommandId, payload, res) d.recordAction(res) return res } assembled := safety.Assemble(d.lastCont, batch, d.prof) elapsed := time.Duration(0) if d.haveDispatch { elapsed = now.Sub(d.lastDispatchAt) } slew := safety.LimitSlew(d.lastCont, assembled.SetAll, d.prof, safety.SlewOpts{ Elapsed: elapsed, First: false, Bypass: false, AllowClamp: batch.AllowClamp, Credit: copyCredit(d.slewCredit), }) if slew.Reject != 0 { res.Accepted = false res.RejectReason = slew.Reject res.Message = slew.Message res.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED d.lease.Cache().Store(batch.CommandId, payload, res) d.recordAction(res) return res } target := slew.SetAll if !d.startupDone && safety.DoorChanged(d.lastCont, target) { res.Accepted = false res.RejectReason = hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY res.Message = "startup incomplete: door change rejected atomically" res.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED d.lease.Cache().Store(batch.CommandId, payload, res) d.recordAction(res) return res } if r.rpcCtx != nil && r.rpcCtx.Err() != nil { res.Accepted = false res.RejectReason = hthv1.RejectReason_REJECT_REASON_EXPIRED_DEADLINE res.Message = "rpc cancelled before first hardware write" res.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED d.recordAction(res) return res } res.AcceptedAction = actionRecord(batch, now, hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNSPECIFIED, target) return res } func (d *Device) recordAction(res *hthv1.ActionResult) { now := d.clk.Now() d.store.Commit(func(s *hthv1.Snapshot) { if res.Requested != nil { s.LastRequested = res.Requested } if res.AcceptedAction != nil { s.LastAccepted = res.AcceptedAction } if res.Dispatched != nil { s.LastDispatched = res.Dispatched } s.ContinuousTargets = d.commandedTargetsAt(s.DeviceEpoch) s.Lease = d.lease.Current().Summary(now) s.ActiveFaults = d.book.Active() s.DeviceConfirmation = res.Confirmation d.annotateSnapshot(s) }) } func (d *Device) heartbeat(ctx context.Context) { if d.safetyErr != nil || d.draining || !d.connected || d.backend.PollMode() != backend.PollUART { return } if !d.startupDone || !d.baselineReady || !d.haveCont { return } if d.serialInflight() { d.pendingHB = true return } now := d.clk.Now() frame := d.lastCont origin := "watchdog_heartbeat_repeat_continuous" if !d.lease.Current().Active(now) || d.safeMode { frame = d.safeFrame() origin = "watchdog_heartbeat_safe_policy_full_open_doors" } ax := d.newActionContext("", origin, hthv1.ActionMode_ACTION_MODE_HEARTBEAT, frame, nil) d.enqueueSerial(d.serialJobFromAction(jobSetAllHB, d.cfg.SetAllTimeout(), ax)) } func (d *Device) safeFrame() protocol.SetAll { if d.safetyErr != nil { return protocol.SetAll{} } return d.safetyContract.Frame } func (d *Device) checkLease(ctx context.Context) { d.expirePendingResume(ctx) if expired := d.lease.ExpireIfNeeded(d.clk.Now()); expired != nil { d.book.Raise(d.clk.Now(), hthv1.FaultType_FAULT_TYPE_CONTROL_LEASE_EXPIRED, d.id, "", "lease expired", "", nil) d.publishEvent(hthv1.EventKind_EVENT_KIND_LEASE_EXPIRED, "expired") d.enterSafe(ctx, "lease_expired") } } func (d *Device) applyMotorReport(rep *backend.MotorReport) { if rep == nil { return } if rep.Status.WatchdogTripped { d.book.Raise(d.clk.Now(), hthv1.FaultType_FAULT_TYPE_WATCHDOG_TRIPPED, d.id, "", "device watchdog_tripped", "", map[string]string{"source": "MOTOR_STATUS"}) } else { d.book.Clear(hthv1.FaultType_FAULT_TYPE_WATCHDOG_TRIPPED, d.id, "", d.clk.Now()) } for name, ax := range map[string]protocol.AxisStatus{"x": rep.Status.X, "y": rep.Status.Y, "z": rep.Status.Z} { if ax.Fault != protocol.FaultNone { d.book.Raise(d.clk.Now(), hthv1.FaultType_FAULT_TYPE_DEVICE_AXIS_FAULT, d.id, "", faultCodeName(ax.Fault), name, map[string]string{"axis": name, "code": fmt.Sprintf("%d", ax.Fault), "state": ax.State.String()}) } else { d.book.Clear(hthv1.FaultType_FAULT_TYPE_DEVICE_AXIS_FAULT, d.id, name, d.clk.Now()) } } if rep.Status.StartupComplete && !d.startupDone { d.startupDone = true d.pendingTemp = true d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_READY) } if d.startupDone && d.store.Lifecycle() == hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_PROBING { d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_READY) } d.applyMotorMeas(rep) d.publishNow() } func (d *Device) handleIOErr(ctx context.Context, err error, backoff *time.Duration, next *time.Time) { if err == nil { return } if d.draining { return } if errors.Is(err, backend.ErrStreamUntrusted) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) && !d.connected { d.onDrop(ctx, err) *backoff = serialBackoff(*backoff) *next = d.clk.Now().Add(*backoff) return } if errors.Is(err, context.Canceled) { return } if errors.Is(err, backend.ErrNotConnected) || errors.Is(err, os.ErrClosed) { d.onDrop(ctx, err) *backoff = serialBackoff(*backoff) *next = d.clk.Now().Add(*backoff) return } msg := err.Error() if strings.Contains(msg, "disconnected") || strings.Contains(msg, "input/output error") || strings.Contains(msg, "untrusted") || strings.Contains(msg, "timeout") { d.onDrop(ctx, err) *backoff = serialBackoff(*backoff) *next = d.clk.Now().Add(*backoff) return } d.book.Raise(d.clk.Now(), hthv1.FaultType_FAULT_TYPE_RESPONSE_TIMEOUT, d.id, "", err.Error(), "", nil) d.onDrop(ctx, err) *backoff = serialBackoff(*backoff) *next = d.clk.Now().Add(*backoff) } func (d *Device) applyTempMeas(rep *backend.TempReport) { now := d.clk.Now() meas := make([]*hthv1.Measurement, 0, len(rep.Samples)+9) invalid := false for i, s := range rep.Samples { m := &hthv1.Measurement{ Id: ids.TempChannel(i), Unit: "degC", HostTime: timestamppb.New(now), SourceTimestampAvailable: false, RawCode: protoInt32(int32(s.Raw)), } switch s.Quality { case protocol.TempDeviceInvalid: m.Quality = hthv1.DataQuality_DATA_QUALITY_INVALID m.QualityReason = "DEVICE_REPORTED_INVALID" invalid = true case protocol.TempOutOfRange: m.Quality = hthv1.DataQuality_DATA_QUALITY_INVALID m.QualityReason = "OUT_OF_DECLARED_RANGE" invalid = true default: m.Quality = hthv1.DataQuality_DATA_QUALITY_VALID m.Value = s.Celsius } meas = append(meas, m) } if invalid { d.book.Raise(now, hthv1.FaultType_FAULT_TYPE_TEMPERATURE_DATA_INVALID, d.id, "", "one or more channels invalid", "", nil) } else { d.book.Clear(hthv1.FaultType_FAULT_TYPE_TEMPERATURE_DATA_INVALID, d.id, "", now) } d.store.Commit(func(s *hthv1.Snapshot) { s.Measurements = mergeMeas(s.Measurements, meas) s.CaptureWindow = window(rep.Window) s.ContinuousTargets = d.commandedTargetsAt(s.DeviceEpoch) s.Lease = d.lease.Current().Summary(now) s.ActiveFaults = d.book.Active() }) } func (d *Device) applyMotorMeas(rep *backend.MotorReport) { now := d.clk.Now() d.lastMotor = now meas := motorMeasurements(rep.Status, now) d.store.Commit(func(s *hthv1.Snapshot) { s.Measurements = mergeMeas(s.Measurements, meas) s.ContinuousTargets = d.commandedTargetsAt(s.DeviceEpoch) s.Lease = d.lease.Current().Summary(now) s.ActiveFaults = d.book.Active() if !d.startupDone { s.Lifecycle = hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_PROBING } }) } func (d *Device) replayTick(ctx context.Context) { rp, ok := d.backend.(backend.Replayer) if !ok { return } if stepper, ok := d.backend.(interface{ Stepping() bool }); ok && stepper.Stepping() { return } _ = d.replayAdvance(ctx, rp) } func (d *Device) stepReplay(ctx context.Context) *hthv1.ActionResult { rp, ok := d.backend.(backend.Replayer) if !ok { return &hthv1.ActionResult{ Accepted: false, RejectReason: hthv1.RejectReason_REJECT_REASON_NOT_SUPPORTED, Message: "backend is not replay", Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_SUPPORTED, DeviceEpoch: d.store.Epoch(), } } if stepper, ok := d.backend.(interface{ RequestStep() }); ok { stepper.RequestStep() } err := d.replayAdvance(ctx, rp) if err != nil { if errors.Is(err, backend.ErrReplayEOF) { d.replayEOF.Store(true) d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_READY) return &hthv1.ActionResult{Accepted: false, Message: "EOF", DeviceEpoch: d.store.Epoch()} } return &hthv1.ActionResult{Accepted: false, Message: err.Error(), DeviceEpoch: d.store.Epoch()} } return &hthv1.ActionResult{Accepted: true, Message: "replay stepped", DeviceEpoch: d.store.Epoch()} } func (d *Device) replayAdvance(ctx context.Context, rp backend.Replayer) error { item, err := rp.Next(ctx) if err != nil { if errors.Is(err, backend.ErrReplayEOF) { d.replayEOF.Store(true) } return err } now := d.clk.Now() d.lastStepEvent = nil d.lastStepSnap = nil if item.Kind == "snapshot" || (len(item.Snapshot) > 0 && len(item.Event) == 0) { rec := capture.Record{Snapshot: item.Snapshot, Kind: "snapshot", EventID: item.EventID, SourceEventID: item.EventID} if snap, err := capture.DecodeSnapshot(rec); err == nil { src := item.EventID srcDev := snap.GetDeviceId() srcDaemon := snap.GetDaemonInstanceId() out := d.store.ReplaceFromReplay(snap) d.lastStepSnap = out d.hub.PublishEvent(&hthv1.Event{ EventId: out.EventId, SourceEventId: src, SourceDeviceId: srcDev, SourceDaemonInstanceId: srcDaemon, SourceCaptureId: d.replayCaptureID(), Kind: hthv1.EventKind_EVENT_KIND_SNAPSHOT, WallTime: timestamppb.New(now), DeviceId: d.id, Snapshot: out, }) } else { return fmt.Errorf("capture: snapshot record: %w", err) } return nil } if len(item.Event) > 0 { rec := capture.Record{Event: item.Event, Kind: "event", EventID: item.EventID, SourceEventID: item.EventID} ev, err := capture.DecodeEvent(rec) if err != nil { return fmt.Errorf("capture: event record: %w", err) } if ev.Kind == hthv1.EventKind_EVENT_KIND_SNAPSHOT && ev.Snapshot != nil { out := d.store.ReplaceFromReplay(ev.Snapshot) d.lastStepSnap = out d.hub.PublishSnapshot(out, now) } else { src := ev.EventId if ev.SourceEventId != 0 { src = ev.SourceEventId } srcDev := ev.SourceDeviceId if srcDev == "" { srcDev = ev.DeviceId } srcDaemon := ev.SourceDaemonInstanceId srcCap := ev.SourceCaptureId if srcCap == "" { srcCap = d.replayCaptureID() } ev.SourceEventId = src ev.SourceDeviceId = srcDev ev.SourceDaemonInstanceId = srcDaemon ev.SourceCaptureId = srcCap ev.EventId = d.store.NextEventID() if ev.EventId == 0 { ev.EventId = 1 } d.lastStepEvent = ev d.hub.PublishEvent(ev) } return nil } return fmt.Errorf("capture: record missing snapshot and event") } func (d *Device) replayCaptureID() string { if d.cfg == nil || d.cfg.Replay.Path == "" { return "" } man, err := capture.ReadManifest(d.cfg.Replay.Path) if err != nil { return "" } man.Normalize() return man.CaptureID } func (d *Device) publishNow() { now := d.clk.Now() stale := false if !d.lastTemp.IsZero() && now.Sub(d.lastTemp) > 2*d.cfg.TemperaturePoll() { stale = true d.book.Raise(now, hthv1.FaultType_FAULT_TYPE_TELEMETRY_STALE, d.id, "", "temperature older than 2 poll periods", "", nil) } else if !d.lastTemp.IsZero() { d.book.Clear(hthv1.FaultType_FAULT_TYPE_TELEMETRY_STALE, d.id, "", now) } snap := d.store.Commit(func(s *hthv1.Snapshot) { s.ContinuousTargets = d.commandedTargetsAt(s.DeviceEpoch) s.Lease = d.lease.Current().Summary(now) s.ActiveFaults = d.book.Active() d.refreshMeasurementAge(s, now, stale) d.annotateSnapshot(s) }) d.hub.PublishSnapshot(snap, now) } func (d *Device) refreshMeasurementAge(s *hthv1.Snapshot, now time.Time, tempStale bool) { tempLimit := 2 * d.cfg.TemperaturePoll() motorLimit := 2 * d.cfg.MotorPoll() for _, m := range s.Measurements { if m == nil { continue } hostT := now if m.HostTime != nil { hostT = m.HostTime.AsTime() } age := now.Sub(hostT) if age < 0 { age = 0 } m.Age = durationpb.New(age) q := m.Quality fresh := q == hthv1.DataQuality_DATA_QUALITY_VALID || q == hthv1.DataQuality_DATA_QUALITY_ESTIMATED stale := false switch { case strings.HasPrefix(m.Id, "temperature."): stale = tempStale || age > tempLimit case strings.HasPrefix(m.Id, "door."): stale = !d.lastMotor.IsZero() && age > motorLimit default: stale = age > tempLimit } if fresh && stale { m.Quality = hthv1.DataQuality_DATA_QUALITY_STALE m.QualityReason = "TELEMETRY_STALE" } } } func (d *Device) publishEvent(kind hthv1.EventKind, msg string) { d.hub.PublishEvent(&hthv1.Event{ EventId: d.store.NextEventID(), Kind: kind, WallTime: timestamppb.New(d.clk.Now()), DeviceId: d.id, Message: msg, }) } func (d *Device) publishFaultEvent(kind string, f *hthv1.Fault) { if f == nil { return } evKind := hthv1.EventKind_EVENT_KIND_FAULT_RAISED switch kind { case "FAULT_CLEARED": evKind = hthv1.EventKind_EVENT_KIND_FAULT_CLEARED case "FAULT_UPDATED": evKind = hthv1.EventKind_EVENT_KIND_FAULT_UPDATED case "FAULT_ACKNOWLEDGED": evKind = hthv1.EventKind_EVENT_KIND_FAULT_ACKNOWLEDGED } d.hub.PublishEvent(&hthv1.Event{ EventId: d.store.NextEventID(), Kind: evKind, WallTime: timestamppb.New(d.clk.Now()), DeviceId: d.id, Fault: f, Message: kind, }) } func (d *Device) publishInfo(ctx context.Context, kind hthv1.EventKind, msg string) { _ = ctx d.publishEvent(kind, msg) } func (d *Device) drainPending(err error) { rej := func(r req) { select { case r.reply <- res{action: cancelledResult(r.batch, err), err: err}: default: } } if d.applyJob != nil { rej(req{reply: d.applyJob.reply, batch: d.applyJob.batch}) d.applyJob = nil } for _, r := range d.pendingApply { rej(r) } d.pendingApply = nil for { select { case r := <-d.safeCh: rej(r) case r := <-d.ctrlCh: rej(r) case r := <-d.applyCh: rej(r) default: return } } } func (d *Device) submit(ctx context.Context, ch chan req, r req) res { r.reply = make(chan res, 1) r.rpcCtx = ctx if r.kind == opApply { return d.submitApply(ctx, r) } select { case ch <- r: default: select { case ch <- r: case <-ctx.Done(): return res{action: cancelledResult(r.batch, ctx.Err()), err: ctx.Err()} } } var shutting <-chan struct{} if d.runCtx != nil { shutting = d.runCtx.Done() } select { case out := <-r.reply: return out case <-ctx.Done(): return res{action: cancelledResult(r.batch, ctx.Err()), err: ctx.Err()} case <-shutting: return res{action: cancelledResult(r.batch, context.Canceled), err: context.Canceled} } } func (d *Device) submitApply(ctx context.Context, r req) res { d.applyMu.Lock() select { case old := <-d.applyCh: d.applyMu.Unlock() d.replySuperseded(old, hthv1.RejectReason_REJECT_REASON_SUPERSEDED, "SUPERSEDED by later apply at ingress") d.applyMu.Lock() default: } select { case d.applyCh <- r: d.applyMu.Unlock() default: d.applyMu.Unlock() select { case d.applyCh <- r: case <-ctx.Done(): return res{action: cancelledResult(r.batch, ctx.Err()), err: ctx.Err()} } } var shutting <-chan struct{} if d.runCtx != nil { shutting = d.runCtx.Done() } select { case out := <-r.reply: return out case <-ctx.Done(): return res{action: cancelledResult(r.batch, ctx.Err()), err: ctx.Err()} case <-shutting: return res{action: cancelledResult(r.batch, context.Canceled), err: context.Canceled} } } func cancelledResult(batch *hthv1.ActionBatch, err error) *hthv1.ActionResult { id := "" if batch != nil { id = batch.CommandId } msg := "rpc cancelled" if err != nil { msg = err.Error() } return &hthv1.ActionResult{ CommandId: id, Accepted: false, RejectReason: hthv1.RejectReason_REJECT_REASON_EXPIRED_DEADLINE, Message: msg, Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED, Requested: rawRequestedRecord(batch, time.Now()), } } func (d *Device) Capabilities() *hthv1.Capabilities { return proto.Clone(d.caps).(*hthv1.Capabilities) } func (d *Device) Snapshot() *hthv1.Snapshot { // Read only the committed snapshot. Actor-owned fields such as // connected/startupDone are copied onto the snapshot in annotateSnapshot // under the actor goroutine; do not read them here. return d.store.Get() } func (d *Device) ReplayComplete() bool { return d.replayEOF.Load() } func (d *Device) LastStepEvent() *hthv1.Event { return d.lastStepEvent } func (d *Device) LastStepSnapshot() *hthv1.Snapshot { return d.lastStepSnap } func (d *Device) TestingSetProgress(t time.Time) { if t.IsZero() { atomic.StoreInt64(&d.progressUnix, 0) return } atomic.StoreInt64(&d.progressUnix, t.UnixNano()) } func (d *Device) TestingSetInflightSince(d0 time.Duration) { atomic.StoreInt64(&d.inflightSinceNano, time.Now().Add(-d0).UnixNano()) } func (d *Device) TestingSetMaxSerialTxn(d0 time.Duration) { atomic.StoreInt64(&d.maxTxnOverrideNano, int64(d0)) } func (d *Device) TestingShutdownSafeResult() *hthv1.ActionResult { return d.shutdownSafeResult } func (d *Device) Info() *hthv1.DeviceInfo { return &hthv1.DeviceInfo{ Identity: &hthv1.DeviceIdentity{ DeviceId: d.id, DisplayName: d.cfg.DisplayName, ProfileId: d.prof.ProfileID, ProfileRevision: d.prof.ProfileRevision, ProtocolContractHash: d.prof.SourceContractSHA256, BackendKind: string(d.cfg.Backend), }, Lifecycle: d.store.Lifecycle(), DeviceEpoch: d.store.Epoch(), } } func (d *Device) Faults(include bool) []*hthv1.Fault { return d.book.All(include) } func (d *Device) SubscribeTelemetry(resume uint64, peer string) (*telemetry.SnapshotSub, []*hthv1.Snapshot, *hthv1.Event, error) { return d.hub.SubscribeSnapshotsPeer(resume, peer) } func (d *Device) SubscribeEvents(resume uint64, peer string) (*telemetry.EventSub, []*hthv1.Event, *hthv1.Event, error) { // Gap descriptors must not consume a global event_id. SubscribeEventsPeer // attaches delivery_gap onto the next real event (or first replay event). return d.hub.SubscribeEventsPeer(resume, peer) } func (d *Device) AcquireLease(ctx context.Context, holder string, ttl time.Duration) (*hthv1.ControlLease, error) { out := d.submit(ctx, d.ctrlCh, req{kind: opAcquire, holder: holder, ttl: ttl}) return out.lease, out.err } func (d *Device) RenewLease(ctx context.Context, id string, epoch uint64, ttl time.Duration) (*hthv1.ControlLease, error) { out := d.submit(ctx, d.ctrlCh, req{kind: opRenew, leaseID: id, leaseEpoch: epoch, ttl: ttl}) return out.lease, out.err } func (d *Device) ReleaseLease(ctx context.Context, id string, epoch uint64) error { return d.submit(ctx, d.ctrlCh, req{kind: opRelease, leaseID: id, leaseEpoch: epoch}).err } func (d *Device) ValidateAction(ctx context.Context, batch *hthv1.ActionBatch) *hthv1.ActionResult { out := d.submit(ctx, d.ctrlCh, req{kind: opValidate, batch: batch, rpcCtx: ctx}) if out.action != nil { return out.action } return cancelledResult(batch, out.err) } func (d *Device) ApplyAction(ctx context.Context, batch *hthv1.ActionBatch) *hthv1.ActionResult { out := d.submit(ctx, d.applyCh, req{kind: opApply, batch: batch, rpcCtx: ctx}) if out.action != nil { return out.action } return cancelledResult(batch, out.err) } func (d *Device) EnterSafeMode(ctx context.Context, leaseID string, epoch uint64, reason string) *hthv1.ActionResult { out := d.submit(ctx, d.safeCh, req{kind: opSafe, reason: reason, leaseID: leaseID, leaseEpoch: epoch, rpcCtx: ctx}) if out.action != nil { return out.action } return cancelledResult(nil, out.err) } func (d *Device) ResumeFromSafe(ctx context.Context, leaseID string, epoch uint64, batch *hthv1.ActionBatch) *hthv1.ActionResult { if batch != nil { if batch.LeaseId == "" { batch.LeaseId = leaseID batch.LeaseEpoch = epoch } } out := d.submit(ctx, d.safeCh, req{kind: opResume, batch: batch, leaseID: leaseID, leaseEpoch: epoch, rpcCtx: ctx}) if out.action != nil { return out.action } return cancelledResult(batch, out.err) } func (d *Device) StepReplay(ctx context.Context) *hthv1.ActionResult { out := d.submit(ctx, d.ctrlCh, req{kind: opStep, rpcCtx: ctx}) if out.action != nil { return out.action } return cancelledResult(nil, out.err) } func rawRequestedRecord(batch *hthv1.ActionBatch, now time.Time) *hthv1.ActionRecord { if batch == nil { return &hthv1.ActionRecord{Time: timestamppb.New(now), Origin: "client", ActionMode: hthv1.ActionMode_ACTION_MODE_NORMAL} } acts := make([]*hthv1.CommandedActuator, 0, len(batch.ContinuousTargets)) for _, t := range batch.ContinuousTargets { if t == nil { continue } acts = append(acts, &hthv1.CommandedActuator{ Id: t.Id, CommandedTarget: t.Value, ActualQuality: hthv1.DataQuality_DATA_QUALITY_UNSPECIFIED, ActualReason: "raw_requested", }) } return &hthv1.ActionRecord{ CommandId: batch.CommandId, ClientId: batch.ClientId, Time: timestamppb.New(now), Origin: "client", Actuators: acts, FieldAudits: safety.RawFieldAudits(batch), ActionMode: hthv1.ActionMode_ACTION_MODE_NORMAL, } } func copyCredit(in map[string]float64) map[string]float64 { out := make(map[string]float64, len(in)) for k, v := range in { out[k] = v } return out } func actionRecord(batch *hthv1.ActionBatch, now time.Time, conf hthv1.ConfirmationStatus, s protocol.SetAll) *hthv1.ActionRecord { if batch == nil { batch = &hthv1.ActionBatch{} } return &hthv1.ActionRecord{ CommandId: batch.CommandId, ClientId: batch.ClientId, Time: timestamppb.New(now), Confirmation: conf, Origin: "hthd", Actuators: commanded(s), ActionMode: hthv1.ActionMode_ACTION_MODE_NORMAL, } } func overlaySafetyDefaults(c *hthv1.Capabilities, contract safety.EffectiveContract) *hthv1.Capabilities { if c == nil { return c } for _, a := range c.Actuators { if a == nil { continue } if v, ok := contract.ByID[a.Id]; ok { a.SafetyDefault = v } } return c } func (d *Device) commandedTargetsAt(epoch uint64) []*hthv1.CommandedActuator { if !d.haveCont || !d.baselineReady { return nil } return commandedWithEpoch(d.lastCont, epoch) } // TestingHoldActor blocks the actor loop so tests can enqueue then cancel RPCs // before handle() runs. Production code must not call this. func (d *Device) TestingHoldActor(hold bool) { d.actorHold.Store(hold) } func commandedWithEpoch(s protocol.SetAll, epoch uint64) []*hthv1.CommandedActuator { out := commanded(s) for _, a := range out { if a == nil { continue } a.TargetEpoch = epoch a.TargetSource = "HOST_DISPATCHED_COMMAND" a.TargetQuality = hthv1.DataQuality_DATA_QUALITY_VALID a.ActualQuality = hthv1.DataQuality_DATA_QUALITY_NOT_SUPPORTED a.ActualReason = "COMMANDED_NOT_ACTUAL" } return out } func (d *Device) makeInternalRecord(cmd, origin string, mode hthv1.ActionMode, now time.Time, conf hthv1.ConfirmationStatus, frame protocol.SetAll) *hthv1.ActionRecord { rec := actionRecord(&hthv1.ActionBatch{CommandId: cmd, ClientId: "hthd"}, now, conf, frame) ax := ActionExecutionContext{ CommandID: cmd, Origin: "daemon/internal", Mode: mode, DeviceEpoch: d.store.Epoch(), PortGeneration: d.portGen, } if origin != "" { ax.Origin = "daemon/internal:" + origin } return bindActionRecord(rec, ax, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED) } func (d *Device) publishActionResult(res *hthv1.ActionResult) { if res == nil { return } now := d.clk.Now() if res.DeviceEpoch == 0 { res.DeviceEpoch = d.store.Epoch() } if res.PortGeneration == 0 { res.PortGeneration = d.portGen } d.hub.PublishEvent(&hthv1.Event{ EventId: d.store.NextEventID(), Kind: hthv1.EventKind_EVENT_KIND_ACTION_RESULT, WallTime: timestamppb.New(now), MonotonicNs: uint64(now.UnixNano()), DeviceId: d.id, Message: res.Message, ActionResult: proto.Clone(res).(*hthv1.ActionResult), PortGeneration: d.portGen, }) } func (d *Device) enqueueLatestApply(r req) { if d.draining { d.replySuperseded(r, hthv1.RejectReason_REJECT_REASON_SUPERSEDED_BY_SHUTDOWN, "SUPERSEDED_BY_SHUTDOWN") return } leaseID := r.batch.GetLeaseId() for _, old := range d.pendingApply { if old.batch != nil && old.batch.GetLeaseId() != leaseID { replyNonblock(r.reply, res{action: &hthv1.ActionResult{ CommandId: r.batch.GetCommandId(), Accepted: false, RejectReason: hthv1.RejectReason_REJECT_REASON_LEASE_MISMATCH, Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED, DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED, Message: "pending action belongs to a different lease", DeviceEpoch: d.store.Epoch(), }}) return } d.replySuperseded(old, hthv1.RejectReason_REJECT_REASON_SUPERSEDED, "SUPERSEDED by later apply") } d.pendingApply = []req{r} } func (d *Device) replySuperseded(r req, reason hthv1.RejectReason, msg string) { out := &hthv1.ActionResult{ CommandId: r.batch.GetCommandId(), Accepted: false, RejectReason: reason, Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED, DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_SUPERSEDED, Message: msg, DeviceEpoch: d.store.Epoch(), PortGeneration: d.portGen, ActionOrigin: "apply", } d.publishActionResult(out) replyNonblock(r.reply, res{action: out}) } func (d *Device) supersedePendingApplies(msg string) { reason := hthv1.RejectReason_REJECT_REASON_SUPERSEDED if msg == "SUPERSEDED_BY_SHUTDOWN" { reason = hthv1.RejectReason_REJECT_REASON_SUPERSEDED_BY_SHUTDOWN } for _, r := range d.pendingApply { d.replySuperseded(r, reason, msg) } d.pendingApply = nil } // TestingInjectStaleSerialResult injects a result that must not clear CurrentInflight. func (d *Device) TestingInjectStaleSerialResult(jobID, portGen, epoch uint64, kind int) { select { case d.results <- serialResult{id: jobID, portGen: portGen, epoch: epoch, kind: jobKind(kind)}: default: } } func (d *Device) TestingCurrentInflight() (jobID, portGen, epoch uint64, kind int, ok bool) { inf := d.inflightSnapshot() if inf.id == 0 { return 0, 0, 0, 0, false } return inf.id, inf.portGen, inf.epoch, int(inf.kind), true } func (d *Device) TestingPortGeneration() uint64 { d.inflightMu.Lock() defer d.inflightMu.Unlock() return d.portGen } func commanded(s protocol.SetAll) []*hthv1.CommandedActuator { mk := func(id string, v uint8) *hthv1.CommandedActuator { return &hthv1.CommandedActuator{ Id: id, CommandedTarget: float64(v), ActualQuality: hthv1.DataQuality_DATA_QUALITY_NOT_SUPPORTED, ActualReason: "NOT_SUPPORTED", } } return []*hthv1.CommandedActuator{ mk(ids.Fan1, s.Fan[0]), mk(ids.Fan2, s.Fan[1]), mk(ids.Fan3, s.Fan[2]), mk(ids.Fan4, s.Fan[3]), mk(ids.PTC1, s.PTC[0]), mk(ids.PTC2, s.PTC[1]), mk(ids.PTC3, s.PTC[2]), mk(ids.PTC4, s.PTC[3]), mk(ids.DoorZ, s.DoorZ), mk(ids.DoorX, s.DoorX), mk(ids.DoorY, s.DoorY), } } func protoInt32(v int32) *int32 { return &v } func window(w backend.TimeWindow) *hthv1.TimeWindow { reqDone := w.RequestComplete if reqDone.IsZero() { reqDone = w.RequestSent } return &hthv1.TimeWindow{ RequestSent: timestamppb.New(w.RequestSent), ResponseStart: timestamppb.New(w.ResponseStart), ResponseComplete: timestamppb.New(w.ResponseComplete), HostReceive: timestamppb.New(w.HostReceive), ApproxAcquireStart: timestamppb.New(w.RequestSent), ApproxAcquireEnd: timestamppb.New(reqDone), SourceTimestampAvailable: false, } } func mergeMeas(old, neu []*hthv1.Measurement) []*hthv1.Measurement { m := map[string]*hthv1.Measurement{} for _, x := range old { m[x.Id] = x } for _, x := range neu { m[x.Id] = x } ids := make([]string, 0, len(m)) for id := range m { ids = append(ids, id) } sort.Strings(ids) out := make([]*hthv1.Measurement, 0, len(ids)) for _, id := range ids { out = append(out, m[id]) } return out } func missingTemps(p *profile.Profile, now time.Time, reason string) []*hthv1.Measurement { return state.MissingTemps(p.Temperature.ValueCount, now, reason) } func motorMeasurements(ms protocol.MotorStatus, now time.Time) []*hthv1.Measurement { out := []*hthv1.Measurement{} add := func(axis string, ax protocol.AxisStatus) { val, q, reason := ax.EstimatedClosePercent() dq := hthv1.DataQuality_DATA_QUALITY_ESTIMATED switch reason { case "OPEN_LIMIT_CONFIRMED", "CLOSE_LIMIT_CONFIRMED": dq = hthv1.DataQuality_DATA_QUALITY_VALID case "TRAVEL_STEPS_ZERO": dq = hthv1.DataQuality_DATA_QUALITY_INVALID } _ = q id := "door." + axis + ".estimated_close_percent" out = append(out, &hthv1.Measurement{ Id: id, Value: val, Unit: "percent", Quality: dq, QualityReason: reason, HostTime: timestamppb.New(now), SourceTimestampAvailable: false, }) ol, cl := 0.0, 0.0 if ax.Flags&protocol.FlagOpenLimit != 0 { ol = 1 } if ax.Flags&protocol.FlagCloseLimit != 0 { cl = 1 } out = append(out, &hthv1.Measurement{Id: "door." + axis + ".open_limit", Value: ol, Unit: "bool", Quality: hthv1.DataQuality_DATA_QUALITY_VALID, HostTime: timestamppb.New(now)}, &hthv1.Measurement{Id: "door." + axis + ".close_limit", Value: cl, Unit: "bool", Quality: hthv1.DataQuality_DATA_QUALITY_VALID, HostTime: timestamppb.New(now)}, ) } add("x", ms.X) add("y", ms.Y) add("z", ms.Z) return out } func buildCaps(cfg *config.Config, p *profile.Profile) *hthv1.Capabilities { c := &hthv1.Capabilities{ DeviceId: cfg.DeviceID, ProfileId: p.ProfileID, ProfileRevision: p.ProfileRevision, ProtocolContractHash: p.SourceContractSHA256, ApiVersion: p.APIVersion, FirmwareVersion: "", FirmwareVersionQuality: hthv1.DataQuality_DATA_QUALITY_NOT_SUPPORTED, HoodCount: int32(p.Topology.HoodCount), ChamberCount: int32(p.Topology.ChamberCount), RecommendedSamplePeriod: durationpb.New(cfg.GetTempTimeout(p)), AckSupported: false, StatusQuerySupported: p.Protocol.StatusQuery, PositionFeedbackSupported: false, RpmFeedbackSupported: false, DeviceFaultQuerySupported: false, HostFaultReportingSupported: true, DeviceNativeFaultQuerySupported: false, DeviceFaultSource: "host_inferred_from_motor_status_and_transport; no device fault queue", LimitReadbackSupported: true, ReadinessProbe: p.Startup.ReadinessProbe, Notes: "No encoder: door current_position is ESTIMATED open-loop STEP count; endpoints may be limit-confirmed. Fan RPM, PTC actual power, firmware version, DIMM map: NOT_SUPPORTED / UNKNOWN. Door 0 = full open. SET_ALL has no ACK. Axis faults come from MOTOR_STATUS_DATA, not a device fault queue. One hthd instance owns one serial controller.", } for _, s := range p.Sensors { sc := &hthv1.SensorCapability{ Id: s.ID, Aliases: s.Aliases, DisplayName: s.DisplayName, Kind: sensorKind(s.Kind), Unit: s.Unit, ValidRange: &hthv1.Range{Min: s.ValidRange.Min, Max: s.ValidRange.Max}, Resolution: s.Resolution, SourceTimestamp: s.SourceTimestamp, MappingConfidence: s.MappingConfidence, HoodId: s.HoodID, ChamberId: s.ChamberID, DimmId: s.DIMMID, Connector: s.Connector, SourceIndex: int32(s.SourceIndex), CalibrationVersion: s.CalibrationVersion, FeedbackMode: feedback(s.FeedbackMode), } if s.Kind == "TEMPERATURE" { sc.UpdatePeriod = durationpb.New(p.RecommendedSamplePeriod()) } c.Sensors = append(c.Sensors, sc) } sort.Slice(c.Sensors, func(i, j int) bool { return c.Sensors[i].Id < c.Sensors[j].Id }) for _, a := range p.Actuators { c.Actuators = append(c.Actuators, &hthv1.ActuatorCapability{ Id: a.ID, Aliases: a.Aliases, DisplayName: a.DisplayName, Kind: actuatorKind(a.Kind), Unit: a.Unit, CommandRange: &hthv1.Range{Min: a.CommandRange.Min, Max: a.CommandRange.Max}, Resolution: a.Resolution, ControlMode: controlMode(a.ControlMode), FeedbackMode: feedback(a.FeedbackMode), Idempotent: a.Idempotent, OneShot: a.OneShot, SafetyDefault: a.SafetyDefault, MaxSlewPerSecond: a.MaxSlewPerSecond, ActualFeedback: a.ActualFeedback, HoodId: a.HoodID, ChamberId: a.ChamberID, Connector: a.Connector, Notes: a.Notes, }) } sort.Slice(c.Actuators, func(i, j int) bool { return c.Actuators[i].Id < c.Actuators[j].Id }) tempMS := uint32(cfg.GetTempTimeout(p) / time.Millisecond) motorMS := uint32(cfg.GetMotorTimeout() / time.Millisecond) setMS := uint32(cfg.SetAllTimeout() / time.Millisecond) if tempMS < 1 { tempMS = 6500 } unpreempt := tempMS if motorMS > unpreempt { unpreempt = motorMS } if setMS > unpreempt { unpreempt = setMS } ctrlWindow := setMS + 50 schedMargin := uint32(50) ctrlWorst := unpreempt + ctrlWindow + schedMargin recRPC := tempMS + ctrlWorst + motorMS + 2000 if recRPC < tempMS+3000 { recRPC = tempMS + 3000 } physTemp := uint32(p.RecommendedSamplePeriod() / time.Millisecond) if physTemp < 1000 { physTemp = tempMS } snapSub := uint32(cfg.TemperaturePoll() / time.Millisecond) if snapSub < 1 { snapSub = 50 } c.Notes += fmt.Sprintf(" physical_temperature_update_period_ms=%d is the 27-channel GET_TEMPERATURE scan, not the %dms host poll tick (recommended_snapshot_subscription_period_ms). 50ms is a scheduler floor, not an ADC period.", physTemp, snapSub) c.Timing = &hthv1.TimingCapabilities{ TemperatureTransactionWorstCaseMs: tempMS, MotorStatusWorstCaseMs: motorMS, ControlDispatchWorstCaseMs: ctrlWorst, RecommendedRpcDeadlineMs: recRPC, RecommendedActionTtlMs: recRPC, MinimumControlPeriodMs: ctrlWindow, RecommendedSamplePeriodMs: physTemp, MaxUnpreemptableTransactionMs: unpreempt, ControlWindowMs: ctrlWindow, SchedulerMarginMs: schedMargin, MaxPendingContinuousActions: 1, PhysicalTemperatureUpdatePeriodMs: physTemp, RecommendedSnapshotSubscriptionPeriodMs: snapSub, } contract, err := safety.BuildEffectiveSafetyContract(p, cfg.Safety) if err != nil { c.Notes += " CONFIG_INVALID: effective safety contract unavailable; no SafeSetAll fallback" c.CapabilityHash = "CONFIG_INVALID" return c } c = overlaySafetyDefaults(c, contract) c.CapabilityHash = caphash.HashCanonicalCapabilities(c) return c } func BuildCanonicalCapabilities(cfg *config.Config, p *profile.Profile) *hthv1.Capabilities { return buildCaps(cfg, p) } func CapabilityHashOf(cfg *config.Config, p *profile.Profile) string { return caphash.HashCanonicalCapabilities(buildCaps(cfg, p)) } func sensorKind(s string) hthv1.SensorKind { switch s { case "TEMPERATURE": return hthv1.SensorKind_SENSOR_KIND_TEMPERATURE case "LIMIT_SWITCH": return hthv1.SensorKind_SENSOR_KIND_LIMIT_SWITCH case "ESTIMATED_POSITION": return hthv1.SensorKind_SENSOR_KIND_ESTIMATED_POSITION default: return hthv1.SensorKind_SENSOR_KIND_UNSPECIFIED } } func actuatorKind(s string) hthv1.ActuatorKind { switch s { case "FAN": return hthv1.ActuatorKind_ACTUATOR_KIND_FAN case "HEATER": return hthv1.ActuatorKind_ACTUATOR_KIND_HEATER case "DOOR": return hthv1.ActuatorKind_ACTUATOR_KIND_DOOR default: return hthv1.ActuatorKind_ACTUATOR_KIND_UNSPECIFIED } } func controlMode(s string) hthv1.ControlMode { switch s { case "PERCENT_CLOSE": return hthv1.ControlMode_CONTROL_MODE_PERCENT_CLOSE case "CONTINUOUS_DUTY": return hthv1.ControlMode_CONTROL_MODE_CONTINUOUS_DUTY case "JOG_ONLY": return hthv1.ControlMode_CONTROL_MODE_JOG_ONLY default: return hthv1.ControlMode_CONTROL_MODE_UNSPECIFIED } } func faultCodeName(c protocol.FaultCode) string { switch c { case protocol.FaultNone: return "NONE" case protocol.FaultBothLimitsActive: return "BOTH_LIMITS_ACTIVE" case protocol.FaultCalCloseTimeout: return "CAL_CLOSE_TIMEOUT" case protocol.FaultCalOpenTimeout: return "CAL_OPEN_TIMEOUT" case protocol.FaultInvalidTravel: return "INVALID_ZERO_OR_TINY_TRAVEL" case protocol.FaultEndpointTimeout: return "ENDPOINT_TIMEOUT" default: return fmt.Sprintf("UNKNOWN_%d", c) } } func feedback(s string) hthv1.FeedbackMode { switch s { case "NONE": return hthv1.FeedbackMode_FEEDBACK_MODE_NONE case "ESTIMATED_OPEN_LOOP": return hthv1.FeedbackMode_FEEDBACK_MODE_ESTIMATED_OPEN_LOOP case "LIMIT_SWITCH": return hthv1.FeedbackMode_FEEDBACK_MODE_LIMIT_SWITCH case "ENCODER": return hthv1.FeedbackMode_FEEDBACK_MODE_ENCODER default: return hthv1.FeedbackMode_FEEDBACK_MODE_UNSPECIFIED } }