| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883 |
- package device
- import (
- "context"
- "errors"
- "fmt"
- "sync/atomic"
- "time"
- "google.golang.org/protobuf/types/known/timestamppb"
- "hth/internal/backend"
- "hth/internal/config"
- hthv1 "hth/internal/gen/hth/api/v1"
- "hth/internal/grpcserver"
- "hth/internal/protocol"
- )
- type jobKind int
- const (
- jobOpen jobKind = iota
- jobGetTemp
- jobGetMotor
- jobSetAllApply
- jobSetAllHB
- jobSetAllSafe
- )
- const originEpochBaseline = "epoch_safe_baseline"
- const originShutdown = "shutdown"
- type serialJob struct {
- id uint64
- portGen uint64
- epoch uint64
- kind jobKind
- origin string
- commandID string
- peerUID int32
- peerGID int32
- peerPID int32
- startedAt time.Time
- deadline time.Time
- timeout time.Duration
- frame protocol.SetAll
- ax ActionExecutionContext
- }
- // ActionExecutionContext is the Actor-owned identity of one physical SET_ALL.
- // Call sites must not invent command IDs, epochs, or peer credentials ad hoc.
- type ActionExecutionContext struct {
- CommandID string
- Origin string
- Mode hthv1.ActionMode
- DeviceEpoch uint64
- PortGeneration uint64
- JobID uint64
- LeaseID string
- LeaseEpoch uint64
- PeerUID int32
- PeerGID int32
- PeerPID int32
- RequestedAt time.Time
- QueuedAt time.Time
- DispatchStartedAt time.Time
- ValidUntil time.Time
- Frame protocol.SetAll
- Requested *hthv1.ActionBatch
- Normalized protocol.SetAll
- Accepted protocol.SetAll
- EffectiveTarget protocol.SetAll
- }
- func (d *Device) newActionContext(commandID, origin string, mode hthv1.ActionMode, frame protocol.SetAll, rpcCtx context.Context) ActionExecutionContext {
- now := d.clk.Now()
- if commandID == "" {
- commandID = d.nextInternalCommandID(origin)
- }
- ax := ActionExecutionContext{
- CommandID: commandID,
- Origin: origin,
- Mode: mode,
- DeviceEpoch: d.store.Epoch(),
- PortGeneration: d.portGen,
- Frame: frame,
- RequestedAt: now,
- QueuedAt: now,
- EffectiveTarget: frame,
- }
- if rpcCtx != nil {
- if cred, ok := grpcserver.PeerFromContext(rpcCtx); ok {
- ax.PeerUID, ax.PeerGID, ax.PeerPID = cred.UID, cred.GID, cred.PID
- }
- }
- return ax
- }
- func (d *Device) serialJobFromAction(kind jobKind, timeout time.Duration, ax ActionExecutionContext) serialJob {
- return serialJob{
- kind: kind,
- timeout: timeout,
- frame: ax.Frame,
- origin: ax.Origin,
- commandID: ax.CommandID,
- peerUID: ax.PeerUID,
- peerGID: ax.PeerGID,
- peerPID: ax.PeerPID,
- portGen: ax.PortGeneration,
- epoch: ax.DeviceEpoch,
- ax: ax,
- }
- }
- func bindActionRecord(rec *hthv1.ActionRecord, ax ActionExecutionContext, dispatch hthv1.ActionDispatchState) *hthv1.ActionRecord {
- if rec == nil {
- return nil
- }
- if rec.CommandId == "" {
- rec.CommandId = ax.CommandID
- }
- rec.Origin = ax.Origin
- rec.ActionMode = ax.Mode
- rec.ActionEpoch = ax.DeviceEpoch
- rec.PortGeneration = ax.PortGeneration
- rec.PeerUid = ax.PeerUID
- rec.PeerGid = ax.PeerGID
- rec.PeerPid = ax.PeerPID
- rec.DispatchState = dispatch
- return rec
- }
- type serialResult struct {
- id uint64
- portGen uint64
- epoch uint64
- kind jobKind
- origin string
- commandID string
- peerUID int32
- peerGID int32
- peerPID int32
- started time.Time
- wr backend.WriteResult
- err error
- temp *backend.TempReport
- motor *backend.MotorReport
- frame protocol.SetAll
- ax ActionExecutionContext
- }
- type inflightIdent struct {
- id uint64
- portGen uint64
- epoch uint64
- kind jobKind
- origin string
- startedAt time.Time
- }
- type pendingResumeState struct {
- req req
- prepared *hthv1.ActionResult
- target protocol.SetAll
- credit map[string]float64
- commandID string
- leaseID string
- leaseEp uint64
- devEpoch uint64
- validUntil time.Time
- acceptedAt time.Time
- }
- type pendingSafeState struct {
- commandID string
- reason string
- origin string
- peerUID int32
- peerGID int32
- peerPID int32
- enqueued time.Time
- deadline time.Time
- epoch uint64
- requestedAt time.Time
- attempts int
- maxAttempts int
- nextRetry time.Time
- }
- const safeNotStartedRetry = 50 * time.Millisecond
- const safeNotStartedMaxAttempts = 8
- func (d *Device) newPendingSafe(cmd, reason, origin string, rpcCtx context.Context) *pendingSafeState {
- now := d.clk.Now()
- wait := d.cfg.SetAllTimeout() + d.remainingInflight()
- st := &pendingSafeState{
- commandID: cmd,
- reason: reason,
- origin: origin,
- enqueued: now,
- deadline: now.Add(wait),
- epoch: d.store.Epoch(),
- requestedAt: now,
- maxAttempts: safeNotStartedMaxAttempts,
- }
- if rpcCtx != nil {
- if cred, ok := grpcserver.PeerFromContext(rpcCtx); ok {
- st.peerUID, st.peerGID, st.peerPID = cred.UID, cred.GID, cred.PID
- }
- }
- return st
- }
- func (d *Device) markProgress() {
- atomic.StoreInt64(&d.progressUnix, time.Now().UnixNano())
- }
- func (d *Device) ActorProgress() time.Time {
- n := atomic.LoadInt64(&d.progressUnix)
- if n == 0 {
- return time.Time{}
- }
- return time.Unix(0, n)
- }
- func (d *Device) serialInflight() bool {
- return atomic.LoadInt64(&d.inflightSinceNano) != 0
- }
- func (d *Device) beginInflight(j serialJob) {
- atomic.StoreInt64(&d.inflightSinceNano, time.Now().UnixNano())
- d.inflightMu.Lock()
- d.currentInflight = inflightIdent{
- id: j.id, portGen: j.portGen, epoch: j.epoch, kind: j.kind,
- origin: j.origin, startedAt: j.startedAt,
- }
- d.inflightMu.Unlock()
- }
- func (d *Device) endInflight() {
- atomic.StoreInt64(&d.inflightSinceNano, 0)
- d.inflightTimeout = 0
- d.inflightKind = 0
- d.inflightMu.Lock()
- d.currentInflight = inflightIdent{}
- d.inflightMu.Unlock()
- }
- func (d *Device) inflightSnapshot() inflightIdent {
- d.inflightMu.Lock()
- defer d.inflightMu.Unlock()
- return d.currentInflight
- }
- func (d *Device) resultMatchesInflight(res serialResult) bool {
- inf := d.inflightSnapshot()
- if inf.id == 0 {
- return false
- }
- return res.id == inf.id && res.portGen == inf.portGen && res.epoch == inf.epoch && res.kind == inf.kind
- }
- func (d *Device) SerialBusy() time.Duration {
- n := atomic.LoadInt64(&d.inflightSinceNano)
- if n == 0 {
- return 0
- }
- return time.Since(time.Unix(0, n))
- }
- func (d *Device) schedulerMargin() time.Duration {
- if d.caps != nil && d.caps.Timing != nil && d.caps.Timing.SchedulerMarginMs > 0 {
- return time.Duration(d.caps.Timing.SchedulerMarginMs) * time.Millisecond
- }
- return 50 * time.Millisecond
- }
- func (d *Device) remainingInflight() time.Duration {
- if !d.serialInflight() {
- return 0
- }
- to := d.inflightTimeout
- if to <= 0 {
- to = d.worstCaseJob(d.inflightKind)
- }
- elapsed := d.SerialBusy()
- rem := to - elapsed
- if rem < 0 {
- rem = 0
- }
- return rem + d.schedulerMargin()
- }
- func (d *Device) worstCaseJob(k jobKind) time.Duration {
- switch k {
- case jobGetTemp:
- return d.cfg.GetTempTimeout(d.prof)
- case jobGetMotor:
- return d.cfg.GetMotorTimeout()
- case jobOpen:
- return d.cfg.OpenTimeout()
- default:
- return d.cfg.SetAllTimeout()
- }
- }
- func (d *Device) minControlPeriod() time.Duration {
- if d.caps != nil && d.caps.Timing != nil && d.caps.Timing.MinimumControlPeriodMs > 0 {
- return time.Duration(d.caps.Timing.MinimumControlPeriodMs) * time.Millisecond
- }
- return 50 * time.Millisecond
- }
- func (d *Device) leaseActive(now time.Time) bool {
- if d.lease == nil {
- return false
- }
- l := d.lease.Current()
- return l != nil && l.Active(now)
- }
- func (d *Device) controlWindowOpen(now time.Time) bool {
- return d.leaseActive(now) && !d.controlWindowUntil.IsZero() && now.Before(d.controlWindowUntil)
- }
- func (d *Device) deadlineUnmeetable(batch *hthv1.ActionBatch) string {
- if batch == nil || batch.ValidUntil == nil {
- return ""
- }
- now := d.clk.Now()
- until := batch.ValidUntil.AsTime()
- if !until.After(now) {
- return "valid_until expired before first hardware write"
- }
- need := d.remainingInflight()
- if need <= 0 {
- return ""
- }
- if !until.After(now.Add(need)) {
- return fmt.Sprintf("valid_until cannot wait for in-flight serial (%s remaining); rejected before enqueue", need.Round(time.Millisecond))
- }
- return ""
- }
- func (d *Device) nextJobID() uint64 {
- d.jobSeq++
- return d.jobSeq
- }
- func (d *Device) nextInternalCommandID(origin string) string {
- d.cmdSeq++
- return fmt.Sprintf("%s:%d:%d:%s", d.daemon, d.store.Epoch(), d.cmdSeq, origin)
- }
- func (d *Device) enqueueSerial(j serialJob) bool {
- if d.serialInflight() {
- return false
- }
- if j.kind != jobOpen && !d.connected {
- return false
- }
- now := d.clk.Now()
- j.id = d.nextJobID()
- if j.portGen == 0 {
- j.portGen = d.portGen
- }
- if j.epoch == 0 {
- j.epoch = d.store.Epoch()
- }
- j.startedAt = now
- j.ax.JobID = j.id
- if j.ax.PortGeneration == 0 {
- j.ax.PortGeneration = j.portGen
- }
- if j.ax.DeviceEpoch == 0 {
- j.ax.DeviceEpoch = j.epoch
- }
- j.ax.DispatchStartedAt = now
- if j.ax.QueuedAt.IsZero() {
- j.ax.QueuedAt = now
- }
- if j.timeout > 0 {
- j.deadline = now.Add(j.timeout)
- }
- d.inflightTimeout = j.timeout
- d.inflightKind = j.kind
- d.beginInflight(j)
- select {
- case d.jobs <- j:
- return true
- default:
- d.endInflight()
- return false
- }
- }
- func (d *Device) serialWorker(ctx context.Context) {
- for {
- select {
- case <-ctx.Done():
- return
- case j := <-d.jobs:
- res := d.execSerial(ctx, j)
- select {
- case d.results <- res:
- case <-ctx.Done():
- return
- }
- }
- }
- }
- func (d *Device) execSerial(parent context.Context, j serialJob) serialResult {
- to := j.timeout
- if to <= 0 {
- to = 2 * time.Second
- }
- ctx, cancel := context.WithTimeout(parent, to)
- defer cancel()
- out := serialResult{
- id: j.id, portGen: j.portGen, epoch: j.epoch, kind: j.kind,
- origin: j.origin, commandID: j.commandID,
- peerUID: j.peerUID, peerGID: j.peerGID, peerPID: j.peerPID,
- started: j.startedAt, frame: j.frame, ax: j.ax,
- }
- switch j.kind {
- case jobOpen:
- out.err = d.backend.Open(ctx)
- if out.err != nil {
- _ = d.backend.Close()
- }
- case jobGetTemp:
- out.temp, out.err = d.backend.GetTemperature(ctx)
- case jobGetMotor:
- out.motor, out.err = d.backend.GetMotorStatus(ctx)
- case jobSetAllApply, jobSetAllHB, jobSetAllSafe:
- out.wr, out.err = d.backend.WriteSetAll(ctx, j.frame)
- }
- return out
- }
- func (d *Device) applySerialResult(ctx context.Context, res serialResult, backoff *time.Duration, next *time.Time) {
- if !d.resultMatchesInflight(res) {
- inf := d.inflightSnapshot()
- d.log.Warn("discarding stale serial result",
- "job_id", res.id, "job_epoch", res.epoch, "job_port_gen", res.portGen,
- "inflight_id", inf.id, "inflight_epoch", inf.epoch,
- "inflight_port_gen", inf.portGen, "kind", int(res.kind))
- return
- }
- d.endInflight()
- d.markProgress()
- if res.kind == jobOpen {
- d.onOpenResult(ctx, res, backoff, next)
- return
- }
- if res.err != nil && res.kind != jobSetAllApply && res.kind != jobSetAllHB && res.kind != jobSetAllSafe {
- d.log.Warn("serial transaction failed", "kind", int(res.kind), "origin", res.origin, "err", res.err)
- if errors.Is(res.err, backend.ErrResponseTimeout) {
- d.book.Raise(d.clk.Now(), hthv1.FaultType_FAULT_TYPE_RESPONSE_TIMEOUT, d.id, "", res.err.Error(), "", nil)
- if res.kind == jobGetTemp {
- d.pendingTemp = true
- }
- d.kickPendingSerial(ctx)
- return
- }
- d.handleIOErr(ctx, res.err, backoff, next)
- d.kickPendingSerial(ctx)
- return
- }
- switch res.kind {
- case jobGetTemp:
- if res.temp != nil {
- d.lastTemp = d.clk.Now()
- d.applyTempMeas(res.temp)
- d.publishNow()
- }
- if d.leaseActive(d.clk.Now()) {
- d.controlWindowUntil = d.clk.Now().Add(d.minControlPeriod())
- }
- case jobGetMotor:
- if res.motor != nil {
- d.applyMotorReport(res.motor)
- }
- case jobSetAllApply:
- d.finishApplyWrite(ctx, res)
- case jobSetAllHB:
- d.finishHeartbeat(ctx, res)
- case jobSetAllSafe:
- d.finishSafeWrite(ctx, res)
- }
- d.kickPendingSerial(ctx)
- }
- func (d *Device) onOpenResult(ctx context.Context, res serialResult, backoff *time.Duration, next *time.Time) {
- if res.err != nil {
- kind := backend.ClassifyOpen(res.err)
- t := hthv1.FaultType_FAULT_TYPE_SERIAL_DEVICE_NOT_FOUND
- if kind == "permission" {
- t = hthv1.FaultType_FAULT_TYPE_SERIAL_PERMISSION_DENIED
- }
- if d.cfg.Backend == config.BackendSerial {
- d.book.Raise(d.clk.Now(), t, d.id, "", res.err.Error(), "", map[string]string{"class": kind})
- d.book.Raise(d.clk.Now(), hthv1.FaultType_FAULT_TYPE_SERIAL_RECONNECTING, d.id, "", "reconnect backoff", "", nil)
- }
- *backoff = serialBackoff(*backoff)
- *next = d.clk.Now().Add(*backoff)
- d.connected = false
- d.log.Warn("serial open failed", "class", kind, "err", res.err)
- d.publishNow()
- return
- }
- *backoff = 0
- d.connected = true
- d.inflightMu.Lock()
- d.portGen++
- d.inflightMu.Unlock()
- d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_PROBING)
- d.book.Clear(hthv1.FaultType_FAULT_TYPE_SERIAL_DISCONNECTED, d.id, "", d.clk.Now())
- d.book.Clear(hthv1.FaultType_FAULT_TYPE_SERIAL_RECONNECTING, d.id, "", d.clk.Now())
- d.publishNow()
- frame := d.safeFrame()
- ax := d.newActionContext("", originEpochBaseline, hthv1.ActionMode_ACTION_MODE_SAFE, frame, nil)
- if !d.enqueueSerial(d.serialJobFromAction(jobSetAllSafe, d.cfg.SetAllTimeout(), ax)) {
- d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_DEGRADED)
- }
- }
- func (d *Device) finishApplyWrite(ctx context.Context, sr serialResult) {
- job := d.applyJob
- d.applyJob = nil
- if job == nil || job.result == nil {
- if backend.WriteNeedsReconnect(sr.wr, sr.err) {
- d.onDrop(ctx, fmt.Errorf("orphaned apply write %s: %v", sr.wr.Outcome, sr.err))
- }
- return
- }
- now := d.clk.Now()
- out := job.result
- if sr.wr.Outcome == backend.WriteNotStarted {
- out.Accepted = false
- out.RejectReason = hthv1.RejectReason_REJECT_REASON_EXPIRED_DEADLINE
- out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED
- out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED
- out.Message = "serial write not started"
- if job.resume {
- d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, "resume_not_started")
- }
- d.recordAction(out)
- d.publishActionResult(out)
- replyNonblock(job.reply, res{action: out})
- return
- }
- conf := hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED
- if backend.WriteNeedsReconnect(sr.wr, sr.err) {
- conf = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN
- d.book.Raise(now, hthv1.FaultType_FAULT_TYPE_CONTROL_OUTCOME_UNKNOWN, d.id, job.batch.GetCommandId(), fmt.Sprintf("write outcome unknown: %v", sr.err), "", nil)
- out.Confirmation = conf
- out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_OUTCOME_UNKNOWN
- out.Message = "OUTCOME_UNKNOWN; transport closed, epoch bumped, lease invalidated; action not auto-replayed"
- out.DeviceEpoch = d.store.Epoch()
- if job.resume {
- d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, "resume_unknown")
- }
- d.lease.Cache().Store(job.batch.CommandId, job.payload, out)
- d.recordAction(out)
- d.publishActionResult(out)
- replyNonblock(job.reply, res{action: out})
- d.onDrop(ctx, fmt.Errorf("ambiguous serial write outcome=%v err=%v", sr.wr.Outcome, sr.err))
- return
- }
- d.lastCont = job.target
- d.haveCont = true
- d.haveDispatch = true
- d.lastDispatchAt = now
- d.lastHWHeartbeat = now
- d.hbPendingSince = time.Time{}
- d.pendingHB = false
- if job.credit != nil {
- d.slewCredit = job.credit
- }
- if job.resume {
- d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_NORMAL, "resume_dispatched")
- d.safeMode = false
- if d.startupDone {
- d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_READY)
- }
- d.publishEvent(hthv1.EventKind_EVENT_KIND_RESUME_FROM_SAFE, job.batch.GetCommandId())
- }
- d.store.BumpControlRevision()
- out.Confirmation = conf
- out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED
- out.ControlRevision = d.store.ControlRevision()
- ax := job.ax
- if ax.CommandID == "" {
- ax = d.newActionContext(job.batch.GetCommandId(), "apply", hthv1.ActionMode_ACTION_MODE_NORMAL, job.target, nil)
- }
- ax.EffectiveTarget = job.target
- stampResultContext(out, ax)
- out.DeviceEpoch = ax.DeviceEpoch
- out.PortGeneration = ax.PortGeneration
- out.Dispatched = recordFromAction(ax, now, conf, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED)
- out.AcceptedAction = recordFromAction(ax, now, conf, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED)
- d.lease.Cache().Store(job.batch.CommandId, job.payload, out)
- d.recordAction(out)
- d.publishActionResult(out)
- d.publishNow()
- replyNonblock(job.reply, res{action: out})
- }
- func (d *Device) finishHeartbeat(ctx context.Context, res serialResult) {
- now := d.clk.Now()
- origin := res.origin
- if origin == "" {
- origin = "watchdog_heartbeat_repeat_continuous"
- }
- cmd := res.commandID
- if cmd == "" {
- cmd = fmt.Sprintf("%s:heartbeat-job:%d", d.daemon, res.id)
- }
- if res.wr.Outcome == backend.WriteFullyWritten && res.err == nil {
- d.lastHWHeartbeat = now
- d.hbPendingSince = time.Time{}
- d.pendingHB = false
- d.hbDeliveryState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED
- d.hub.PublishEvent(&hthv1.Event{
- EventId: d.store.NextEventID(), Kind: hthv1.EventKind_EVENT_KIND_WATCHDOG_HEARTBEAT,
- WallTime: timestamppb.New(now), DeviceId: d.id, Message: origin,
- PortGeneration: res.portGen,
- })
- ax := res.ax
- var rec *hthv1.ActionRecord
- if ax.CommandID == "" {
- rec = d.makeInternalRecord(cmd, origin, hthv1.ActionMode_ACTION_MODE_HEARTBEAT, now,
- hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED, res.frame)
- ax.CommandID, ax.Origin, ax.DeviceEpoch, ax.PortGeneration = cmd, origin, res.epoch, res.portGen
- } else {
- rec = recordFromAction(ax, now, hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED,
- hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED)
- }
- d.publishActionResult(&hthv1.ActionResult{
- CommandId: cmd, Accepted: true, DeviceEpoch: ax.DeviceEpoch, PortGeneration: ax.PortGeneration,
- ActionOrigin: origin, Dispatched: rec,
- Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED,
- DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED,
- Message: "hardware heartbeat dispatched UNCONFIRMED; control_revision unchanged",
- ControlRevision: d.store.ControlRevision(),
- })
- d.publishNow()
- return
- }
- if res.wr.Outcome == backend.WriteNotStarted {
- d.hbDeliveryState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED
- d.book.Raise(now, hthv1.FaultType_FAULT_TYPE_SAFE_ACTION_NOT_DELIVERED, d.id, origin,
- fmt.Sprintf("heartbeat NOT_STARTED n=%d err=%v", res.wr.N, res.err), "", nil)
- d.publishActionResult(&hthv1.ActionResult{
- CommandId: cmd, Accepted: false,
- Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED,
- DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED,
- Message: "hardware heartbeat not started; not counted as success",
- DeviceEpoch: res.epoch, PortGeneration: res.portGen, ActionOrigin: origin,
- ControlRevision: d.store.ControlRevision(),
- })
- d.publishNow()
- if d.watchdogMargin() < d.cfg.Heartbeat()*2 {
- d.pendingHB = true
- }
- return
- }
- d.hbDeliveryState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_OUTCOME_UNKNOWN
- d.book.Raise(now, hthv1.FaultType_FAULT_TYPE_CONTROL_OUTCOME_UNKNOWN, d.id, origin,
- fmt.Sprintf("heartbeat %s: %v", res.wr.Outcome, res.err), "", nil)
- d.publishActionResult(&hthv1.ActionResult{
- CommandId: cmd, Accepted: false,
- Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN,
- DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_OUTCOME_UNKNOWN,
- Message: "hardware heartbeat outcome unknown; transport dropped",
- DeviceEpoch: res.epoch, PortGeneration: res.portGen, ActionOrigin: origin,
- ControlRevision: d.store.ControlRevision(),
- })
- d.onDrop(ctx, fmt.Errorf("heartbeat write %s: %v", res.wr.Outcome, res.err))
- }
- func (d *Device) watchdogTimeout() time.Duration {
- if d.prof != nil && d.prof.Watchdog.TimeoutSeconds > 0 {
- return time.Duration(d.prof.Watchdog.TimeoutSeconds) * time.Second
- }
- return 30 * time.Second
- }
- func (d *Device) watchdogMargin() time.Duration {
- to := d.watchdogTimeout()
- if d.lastHWHeartbeat.IsZero() {
- return 0
- }
- elapsed := d.clk.Now().Sub(d.lastHWHeartbeat)
- if elapsed >= to {
- return 0
- }
- return to - elapsed
- }
- func (d *Device) markHeartbeatPending() {
- if d.draining || !d.connected || !d.startupDone || !d.baselineReady || !d.haveCont {
- return
- }
- d.pendingHB = true
- if d.hbPendingSince.IsZero() {
- d.hbPendingSince = d.clk.Now()
- }
- }
- func (d *Device) heartbeatDue() bool {
- if d.draining || !d.connected || !d.startupDone || !d.baselineReady || !d.haveCont {
- return false
- }
- if d.backend.PollMode() != backend.PollUART {
- return false
- }
- if d.pendingHB {
- return true
- }
- if d.lastHWHeartbeat.IsZero() {
- return true
- }
- now := d.clk.Now()
- if !now.Before(d.lastHWHeartbeat.Add(d.cfg.Heartbeat())) {
- return true
- }
- return now.Sub(d.lastHWHeartbeat) >= d.maxAllowedHeartbeatGap()
- }
- func (d *Device) maxAllowedHeartbeatGap() time.Duration {
- fw := d.watchdogTimeout()
- gap := d.cfg.Heartbeat() * 3
- if gap >= fw {
- gap = fw - time.Second
- if gap < d.cfg.Heartbeat() {
- gap = d.cfg.Heartbeat()
- }
- }
- return gap
- }
- func (d *Device) temperatureScanReserve() time.Duration {
- est := d.cfg.GetTempTimeout(d.prof)
- if d.prof != nil && d.prof.Timeouts.TemperatureScanBusyMS > 0 {
- busy := time.Duration(d.prof.Timeouts.TemperatureScanBusyMS)*time.Millisecond + time.Second
- if busy < est {
- est = busy
- }
- }
- // A UART timeout budget can meet or exceed the firmware watchdog
- // (production yaml: GET_TEMP 20s + SET_ALL 8s + slack >= 30s). Using
- // that budget as the reservation would permanently suppress
- // GET_TEMPERATURE. Cap the scan reserve at half the watchdog.
- half := d.watchdogTimeout() / 2
- if est > half {
- est = half
- }
- if est < time.Second {
- est = time.Second
- }
- return est
- }
- func (d *Device) temperatureWouldStarveWatchdog() bool {
- if d.lastHWHeartbeat.IsZero() {
- return true
- }
- need := d.temperatureScanReserve() + d.cfg.SetAllTimeout() + time.Second
- return d.watchdogMargin() < need
- }
- func (d *Device) kickPendingSerial(ctx context.Context) {
- if !d.connected || d.serialInflight() {
- return
- }
- if d.draining {
- return
- }
- d.expirePendingResume(ctx)
- if d.pendingSafeJob != nil {
- job := d.pendingSafeJob
- now := d.clk.Now()
- origin := "queued_safe"
- if job.origin != "" {
- origin = job.origin
- }
- if !job.deadline.IsZero() && now.After(job.deadline) {
- if d.serialInflight() {
- job.deadline = now.Add(d.remainingInflight() + d.cfg.SetAllTimeout())
- return
- }
- d.pendingSafeJob = nil
- ax := ActionExecutionContext{
- CommandID: job.commandID, Origin: origin, Mode: hthv1.ActionMode_ACTION_MODE_SAFE,
- DeviceEpoch: job.epoch, PortGeneration: d.portGen,
- PeerUID: job.peerUID, PeerGID: job.peerGID, PeerPID: job.peerPID,
- }
- if ax.DeviceEpoch == 0 {
- ax.DeviceEpoch = d.store.Epoch()
- }
- out := &hthv1.ActionResult{
- CommandId: job.commandID, Accepted: false, DeviceEpoch: ax.DeviceEpoch, PortGeneration: ax.PortGeneration,
- ActionOrigin: origin, ControlRevision: d.store.ControlRevision(),
- Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED,
- DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED,
- Message: "SAFE_DELIVERY_FAILED: WriteNotStarted retry budget/deadline exhausted; explicit EnterSafeMode may retry",
- }
- stampResultContext(out, ax)
- d.publishActionResult(out)
- if d.controlMode != hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE {
- d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING, "safe_retry_deadline")
- }
- d.publishNow()
- return
- }
- if !job.nextRetry.IsZero() && now.Before(job.nextRetry) {
- return
- }
- frame := d.safeFrame()
- ax := ActionExecutionContext{
- CommandID: job.commandID, Origin: origin, Mode: hthv1.ActionMode_ACTION_MODE_SAFE,
- DeviceEpoch: job.epoch, PortGeneration: d.portGen, Frame: frame, EffectiveTarget: frame,
- PeerUID: job.peerUID, PeerGID: job.peerGID, PeerPID: job.peerPID,
- }
- if ax.DeviceEpoch == 0 {
- ax.DeviceEpoch = d.store.Epoch()
- }
- if !d.enqueueSerial(d.serialJobFromAction(jobSetAllSafe, d.cfg.SetAllTimeout(), ax)) {
- return
- }
- return
- }
- if d.pendingResume != nil {
- d.dispatchPendingResume(ctx)
- return
- }
- if len(d.pendingApply) > 0 {
- r := d.pendingApply[0]
- d.pendingApply = d.pendingApply[1:]
- if r.rpcCtx != nil && r.rpcCtx.Err() != nil {
- replyNonblock(r.reply, res{action: cancelledResult(r.batch, r.rpcCtx.Err()), err: r.rpcCtx.Err()})
- d.kickPendingSerial(ctx)
- return
- }
- d.beginApply(ctx, r)
- return
- }
- if d.heartbeatDue() {
- d.pendingHB = false
- d.heartbeat(ctx)
- return
- }
- if d.pendingMotor && d.backend.PollMode() == backend.PollUART {
- d.pendingMotor = false
- d.enqueueSerial(serialJob{kind: jobGetMotor, timeout: d.cfg.GetMotorTimeout(), origin: "readiness_probe"})
- return
- }
- if d.pendingTemp && d.startupDone {
- if d.pendingSafeJob != nil || d.pendingResume != nil || len(d.pendingApply) > 0 || d.controlWindowOpen(d.clk.Now()) {
- return
- }
- if d.heartbeatDue() || d.temperatureWouldStarveWatchdog() {
- d.markHeartbeatPending()
- d.heartbeat(ctx)
- return
- }
- d.pendingTemp = false
- d.enqueueSerial(serialJob{kind: jobGetTemp, timeout: d.cfg.GetTempTimeout(d.prof)})
- return
- }
- }
- func replyNonblock(ch chan res, r res) {
- if ch == nil {
- return
- }
- select {
- case ch <- r:
- default:
- }
- }
|