serial_worker.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  1. package device
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "sync/atomic"
  7. "time"
  8. "google.golang.org/protobuf/types/known/timestamppb"
  9. "hth/internal/backend"
  10. "hth/internal/config"
  11. hthv1 "hth/internal/gen/hth/api/v1"
  12. "hth/internal/grpcserver"
  13. "hth/internal/protocol"
  14. )
  15. type jobKind int
  16. const (
  17. jobOpen jobKind = iota
  18. jobGetTemp
  19. jobGetMotor
  20. jobSetAllApply
  21. jobSetAllHB
  22. jobSetAllSafe
  23. )
  24. const originEpochBaseline = "epoch_safe_baseline"
  25. const originShutdown = "shutdown"
  26. type serialJob struct {
  27. id uint64
  28. portGen uint64
  29. epoch uint64
  30. kind jobKind
  31. origin string
  32. commandID string
  33. peerUID int32
  34. peerGID int32
  35. peerPID int32
  36. startedAt time.Time
  37. deadline time.Time
  38. timeout time.Duration
  39. frame protocol.SetAll
  40. ax ActionExecutionContext
  41. }
  42. // ActionExecutionContext is the Actor-owned identity of one physical SET_ALL.
  43. // Call sites must not invent command IDs, epochs, or peer credentials ad hoc.
  44. type ActionExecutionContext struct {
  45. CommandID string
  46. Origin string
  47. Mode hthv1.ActionMode
  48. DeviceEpoch uint64
  49. PortGeneration uint64
  50. JobID uint64
  51. LeaseID string
  52. LeaseEpoch uint64
  53. PeerUID int32
  54. PeerGID int32
  55. PeerPID int32
  56. RequestedAt time.Time
  57. QueuedAt time.Time
  58. DispatchStartedAt time.Time
  59. ValidUntil time.Time
  60. Frame protocol.SetAll
  61. Requested *hthv1.ActionBatch
  62. Normalized protocol.SetAll
  63. Accepted protocol.SetAll
  64. EffectiveTarget protocol.SetAll
  65. }
  66. func (d *Device) newActionContext(commandID, origin string, mode hthv1.ActionMode, frame protocol.SetAll, rpcCtx context.Context) ActionExecutionContext {
  67. now := d.clk.Now()
  68. if commandID == "" {
  69. commandID = d.nextInternalCommandID(origin)
  70. }
  71. ax := ActionExecutionContext{
  72. CommandID: commandID,
  73. Origin: origin,
  74. Mode: mode,
  75. DeviceEpoch: d.store.Epoch(),
  76. PortGeneration: d.portGen,
  77. Frame: frame,
  78. RequestedAt: now,
  79. QueuedAt: now,
  80. EffectiveTarget: frame,
  81. }
  82. if rpcCtx != nil {
  83. if cred, ok := grpcserver.PeerFromContext(rpcCtx); ok {
  84. ax.PeerUID, ax.PeerGID, ax.PeerPID = cred.UID, cred.GID, cred.PID
  85. }
  86. }
  87. return ax
  88. }
  89. func (d *Device) serialJobFromAction(kind jobKind, timeout time.Duration, ax ActionExecutionContext) serialJob {
  90. return serialJob{
  91. kind: kind,
  92. timeout: timeout,
  93. frame: ax.Frame,
  94. origin: ax.Origin,
  95. commandID: ax.CommandID,
  96. peerUID: ax.PeerUID,
  97. peerGID: ax.PeerGID,
  98. peerPID: ax.PeerPID,
  99. portGen: ax.PortGeneration,
  100. epoch: ax.DeviceEpoch,
  101. ax: ax,
  102. }
  103. }
  104. func bindActionRecord(rec *hthv1.ActionRecord, ax ActionExecutionContext, dispatch hthv1.ActionDispatchState) *hthv1.ActionRecord {
  105. if rec == nil {
  106. return nil
  107. }
  108. if rec.CommandId == "" {
  109. rec.CommandId = ax.CommandID
  110. }
  111. rec.Origin = ax.Origin
  112. rec.ActionMode = ax.Mode
  113. rec.ActionEpoch = ax.DeviceEpoch
  114. rec.PortGeneration = ax.PortGeneration
  115. rec.PeerUid = ax.PeerUID
  116. rec.PeerGid = ax.PeerGID
  117. rec.PeerPid = ax.PeerPID
  118. rec.DispatchState = dispatch
  119. return rec
  120. }
  121. type serialResult struct {
  122. id uint64
  123. portGen uint64
  124. epoch uint64
  125. kind jobKind
  126. origin string
  127. commandID string
  128. peerUID int32
  129. peerGID int32
  130. peerPID int32
  131. started time.Time
  132. wr backend.WriteResult
  133. err error
  134. temp *backend.TempReport
  135. motor *backend.MotorReport
  136. frame protocol.SetAll
  137. ax ActionExecutionContext
  138. }
  139. type inflightIdent struct {
  140. id uint64
  141. portGen uint64
  142. epoch uint64
  143. kind jobKind
  144. origin string
  145. startedAt time.Time
  146. }
  147. type pendingResumeState struct {
  148. req req
  149. prepared *hthv1.ActionResult
  150. target protocol.SetAll
  151. credit map[string]float64
  152. commandID string
  153. leaseID string
  154. leaseEp uint64
  155. devEpoch uint64
  156. validUntil time.Time
  157. acceptedAt time.Time
  158. }
  159. type pendingSafeState struct {
  160. commandID string
  161. reason string
  162. origin string
  163. peerUID int32
  164. peerGID int32
  165. peerPID int32
  166. enqueued time.Time
  167. deadline time.Time
  168. epoch uint64
  169. requestedAt time.Time
  170. attempts int
  171. maxAttempts int
  172. nextRetry time.Time
  173. }
  174. const safeNotStartedRetry = 50 * time.Millisecond
  175. const safeNotStartedMaxAttempts = 8
  176. func (d *Device) newPendingSafe(cmd, reason, origin string, rpcCtx context.Context) *pendingSafeState {
  177. now := d.clk.Now()
  178. wait := d.cfg.SetAllTimeout() + d.remainingInflight()
  179. st := &pendingSafeState{
  180. commandID: cmd,
  181. reason: reason,
  182. origin: origin,
  183. enqueued: now,
  184. deadline: now.Add(wait),
  185. epoch: d.store.Epoch(),
  186. requestedAt: now,
  187. maxAttempts: safeNotStartedMaxAttempts,
  188. }
  189. if rpcCtx != nil {
  190. if cred, ok := grpcserver.PeerFromContext(rpcCtx); ok {
  191. st.peerUID, st.peerGID, st.peerPID = cred.UID, cred.GID, cred.PID
  192. }
  193. }
  194. return st
  195. }
  196. func (d *Device) markProgress() {
  197. atomic.StoreInt64(&d.progressUnix, time.Now().UnixNano())
  198. }
  199. func (d *Device) ActorProgress() time.Time {
  200. n := atomic.LoadInt64(&d.progressUnix)
  201. if n == 0 {
  202. return time.Time{}
  203. }
  204. return time.Unix(0, n)
  205. }
  206. func (d *Device) serialInflight() bool {
  207. return atomic.LoadInt64(&d.inflightSinceNano) != 0
  208. }
  209. func (d *Device) beginInflight(j serialJob) {
  210. atomic.StoreInt64(&d.inflightSinceNano, time.Now().UnixNano())
  211. d.inflightMu.Lock()
  212. d.currentInflight = inflightIdent{
  213. id: j.id, portGen: j.portGen, epoch: j.epoch, kind: j.kind,
  214. origin: j.origin, startedAt: j.startedAt,
  215. }
  216. d.inflightMu.Unlock()
  217. }
  218. func (d *Device) endInflight() {
  219. atomic.StoreInt64(&d.inflightSinceNano, 0)
  220. d.inflightTimeout = 0
  221. d.inflightKind = 0
  222. d.inflightMu.Lock()
  223. d.currentInflight = inflightIdent{}
  224. d.inflightMu.Unlock()
  225. }
  226. func (d *Device) inflightSnapshot() inflightIdent {
  227. d.inflightMu.Lock()
  228. defer d.inflightMu.Unlock()
  229. return d.currentInflight
  230. }
  231. func (d *Device) resultMatchesInflight(res serialResult) bool {
  232. inf := d.inflightSnapshot()
  233. if inf.id == 0 {
  234. return false
  235. }
  236. return res.id == inf.id && res.portGen == inf.portGen && res.epoch == inf.epoch && res.kind == inf.kind
  237. }
  238. func (d *Device) SerialBusy() time.Duration {
  239. n := atomic.LoadInt64(&d.inflightSinceNano)
  240. if n == 0 {
  241. return 0
  242. }
  243. return time.Since(time.Unix(0, n))
  244. }
  245. func (d *Device) schedulerMargin() time.Duration {
  246. if d.caps != nil && d.caps.Timing != nil && d.caps.Timing.SchedulerMarginMs > 0 {
  247. return time.Duration(d.caps.Timing.SchedulerMarginMs) * time.Millisecond
  248. }
  249. return 50 * time.Millisecond
  250. }
  251. func (d *Device) remainingInflight() time.Duration {
  252. if !d.serialInflight() {
  253. return 0
  254. }
  255. to := d.inflightTimeout
  256. if to <= 0 {
  257. to = d.worstCaseJob(d.inflightKind)
  258. }
  259. elapsed := d.SerialBusy()
  260. rem := to - elapsed
  261. if rem < 0 {
  262. rem = 0
  263. }
  264. return rem + d.schedulerMargin()
  265. }
  266. func (d *Device) worstCaseJob(k jobKind) time.Duration {
  267. switch k {
  268. case jobGetTemp:
  269. return d.cfg.GetTempTimeout(d.prof)
  270. case jobGetMotor:
  271. return d.cfg.GetMotorTimeout()
  272. case jobOpen:
  273. return d.cfg.OpenTimeout()
  274. default:
  275. return d.cfg.SetAllTimeout()
  276. }
  277. }
  278. func (d *Device) minControlPeriod() time.Duration {
  279. if d.caps != nil && d.caps.Timing != nil && d.caps.Timing.MinimumControlPeriodMs > 0 {
  280. return time.Duration(d.caps.Timing.MinimumControlPeriodMs) * time.Millisecond
  281. }
  282. return 50 * time.Millisecond
  283. }
  284. func (d *Device) leaseActive(now time.Time) bool {
  285. if d.lease == nil {
  286. return false
  287. }
  288. l := d.lease.Current()
  289. return l != nil && l.Active(now)
  290. }
  291. func (d *Device) controlWindowOpen(now time.Time) bool {
  292. return d.leaseActive(now) && !d.controlWindowUntil.IsZero() && now.Before(d.controlWindowUntil)
  293. }
  294. func (d *Device) deadlineUnmeetable(batch *hthv1.ActionBatch) string {
  295. if batch == nil || batch.ValidUntil == nil {
  296. return ""
  297. }
  298. now := d.clk.Now()
  299. until := batch.ValidUntil.AsTime()
  300. if !until.After(now) {
  301. return "valid_until expired before first hardware write"
  302. }
  303. need := d.remainingInflight()
  304. if need <= 0 {
  305. return ""
  306. }
  307. if !until.After(now.Add(need)) {
  308. return fmt.Sprintf("valid_until cannot wait for in-flight serial (%s remaining); rejected before enqueue", need.Round(time.Millisecond))
  309. }
  310. return ""
  311. }
  312. func (d *Device) nextJobID() uint64 {
  313. d.jobSeq++
  314. return d.jobSeq
  315. }
  316. func (d *Device) nextInternalCommandID(origin string) string {
  317. d.cmdSeq++
  318. return fmt.Sprintf("%s:%d:%d:%s", d.daemon, d.store.Epoch(), d.cmdSeq, origin)
  319. }
  320. func (d *Device) enqueueSerial(j serialJob) bool {
  321. if d.serialInflight() {
  322. return false
  323. }
  324. if j.kind != jobOpen && !d.connected {
  325. return false
  326. }
  327. now := d.clk.Now()
  328. j.id = d.nextJobID()
  329. if j.portGen == 0 {
  330. j.portGen = d.portGen
  331. }
  332. if j.epoch == 0 {
  333. j.epoch = d.store.Epoch()
  334. }
  335. j.startedAt = now
  336. j.ax.JobID = j.id
  337. if j.ax.PortGeneration == 0 {
  338. j.ax.PortGeneration = j.portGen
  339. }
  340. if j.ax.DeviceEpoch == 0 {
  341. j.ax.DeviceEpoch = j.epoch
  342. }
  343. j.ax.DispatchStartedAt = now
  344. if j.ax.QueuedAt.IsZero() {
  345. j.ax.QueuedAt = now
  346. }
  347. if j.timeout > 0 {
  348. j.deadline = now.Add(j.timeout)
  349. }
  350. d.inflightTimeout = j.timeout
  351. d.inflightKind = j.kind
  352. d.beginInflight(j)
  353. select {
  354. case d.jobs <- j:
  355. return true
  356. default:
  357. d.endInflight()
  358. return false
  359. }
  360. }
  361. func (d *Device) serialWorker(ctx context.Context) {
  362. for {
  363. select {
  364. case <-ctx.Done():
  365. return
  366. case j := <-d.jobs:
  367. res := d.execSerial(ctx, j)
  368. select {
  369. case d.results <- res:
  370. case <-ctx.Done():
  371. return
  372. }
  373. }
  374. }
  375. }
  376. func (d *Device) execSerial(parent context.Context, j serialJob) serialResult {
  377. to := j.timeout
  378. if to <= 0 {
  379. to = 2 * time.Second
  380. }
  381. ctx, cancel := context.WithTimeout(parent, to)
  382. defer cancel()
  383. out := serialResult{
  384. id: j.id, portGen: j.portGen, epoch: j.epoch, kind: j.kind,
  385. origin: j.origin, commandID: j.commandID,
  386. peerUID: j.peerUID, peerGID: j.peerGID, peerPID: j.peerPID,
  387. started: j.startedAt, frame: j.frame, ax: j.ax,
  388. }
  389. switch j.kind {
  390. case jobOpen:
  391. out.err = d.backend.Open(ctx)
  392. if out.err != nil {
  393. _ = d.backend.Close()
  394. }
  395. case jobGetTemp:
  396. out.temp, out.err = d.backend.GetTemperature(ctx)
  397. case jobGetMotor:
  398. out.motor, out.err = d.backend.GetMotorStatus(ctx)
  399. case jobSetAllApply, jobSetAllHB, jobSetAllSafe:
  400. out.wr, out.err = d.backend.WriteSetAll(ctx, j.frame)
  401. }
  402. return out
  403. }
  404. func (d *Device) applySerialResult(ctx context.Context, res serialResult, backoff *time.Duration, next *time.Time) {
  405. if !d.resultMatchesInflight(res) {
  406. inf := d.inflightSnapshot()
  407. d.log.Warn("discarding stale serial result",
  408. "job_id", res.id, "job_epoch", res.epoch, "job_port_gen", res.portGen,
  409. "inflight_id", inf.id, "inflight_epoch", inf.epoch,
  410. "inflight_port_gen", inf.portGen, "kind", int(res.kind))
  411. return
  412. }
  413. d.endInflight()
  414. d.markProgress()
  415. if res.kind == jobOpen {
  416. d.onOpenResult(ctx, res, backoff, next)
  417. return
  418. }
  419. if res.err != nil && res.kind != jobSetAllApply && res.kind != jobSetAllHB && res.kind != jobSetAllSafe {
  420. d.log.Warn("serial transaction failed", "kind", int(res.kind), "origin", res.origin, "err", res.err)
  421. if errors.Is(res.err, backend.ErrResponseTimeout) {
  422. d.book.Raise(d.clk.Now(), hthv1.FaultType_FAULT_TYPE_RESPONSE_TIMEOUT, d.id, "", res.err.Error(), "", nil)
  423. if res.kind == jobGetTemp {
  424. d.pendingTemp = true
  425. }
  426. d.kickPendingSerial(ctx)
  427. return
  428. }
  429. d.handleIOErr(ctx, res.err, backoff, next)
  430. d.kickPendingSerial(ctx)
  431. return
  432. }
  433. switch res.kind {
  434. case jobGetTemp:
  435. if res.temp != nil {
  436. d.lastTemp = d.clk.Now()
  437. d.applyTempMeas(res.temp)
  438. d.publishNow()
  439. }
  440. if d.leaseActive(d.clk.Now()) {
  441. d.controlWindowUntil = d.clk.Now().Add(d.minControlPeriod())
  442. }
  443. case jobGetMotor:
  444. if res.motor != nil {
  445. d.applyMotorReport(res.motor)
  446. }
  447. case jobSetAllApply:
  448. d.finishApplyWrite(ctx, res)
  449. case jobSetAllHB:
  450. d.finishHeartbeat(ctx, res)
  451. case jobSetAllSafe:
  452. d.finishSafeWrite(ctx, res)
  453. }
  454. d.kickPendingSerial(ctx)
  455. }
  456. func (d *Device) onOpenResult(ctx context.Context, res serialResult, backoff *time.Duration, next *time.Time) {
  457. if res.err != nil {
  458. kind := backend.ClassifyOpen(res.err)
  459. t := hthv1.FaultType_FAULT_TYPE_SERIAL_DEVICE_NOT_FOUND
  460. if kind == "permission" {
  461. t = hthv1.FaultType_FAULT_TYPE_SERIAL_PERMISSION_DENIED
  462. }
  463. if d.cfg.Backend == config.BackendSerial {
  464. d.book.Raise(d.clk.Now(), t, d.id, "", res.err.Error(), "", map[string]string{"class": kind})
  465. d.book.Raise(d.clk.Now(), hthv1.FaultType_FAULT_TYPE_SERIAL_RECONNECTING, d.id, "", "reconnect backoff", "", nil)
  466. }
  467. *backoff = serialBackoff(*backoff)
  468. *next = d.clk.Now().Add(*backoff)
  469. d.connected = false
  470. d.log.Warn("serial open failed", "class", kind, "err", res.err)
  471. d.publishNow()
  472. return
  473. }
  474. *backoff = 0
  475. d.connected = true
  476. d.inflightMu.Lock()
  477. d.portGen++
  478. d.inflightMu.Unlock()
  479. d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_PROBING)
  480. d.book.Clear(hthv1.FaultType_FAULT_TYPE_SERIAL_DISCONNECTED, d.id, "", d.clk.Now())
  481. d.book.Clear(hthv1.FaultType_FAULT_TYPE_SERIAL_RECONNECTING, d.id, "", d.clk.Now())
  482. d.publishNow()
  483. frame := d.safeFrame()
  484. ax := d.newActionContext("", originEpochBaseline, hthv1.ActionMode_ACTION_MODE_SAFE, frame, nil)
  485. if !d.enqueueSerial(d.serialJobFromAction(jobSetAllSafe, d.cfg.SetAllTimeout(), ax)) {
  486. d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_DEGRADED)
  487. }
  488. }
  489. func (d *Device) finishApplyWrite(ctx context.Context, sr serialResult) {
  490. job := d.applyJob
  491. d.applyJob = nil
  492. if job == nil || job.result == nil {
  493. if backend.WriteNeedsReconnect(sr.wr, sr.err) {
  494. d.onDrop(ctx, fmt.Errorf("orphaned apply write %s: %v", sr.wr.Outcome, sr.err))
  495. }
  496. return
  497. }
  498. now := d.clk.Now()
  499. out := job.result
  500. if sr.wr.Outcome == backend.WriteNotStarted {
  501. out.Accepted = false
  502. out.RejectReason = hthv1.RejectReason_REJECT_REASON_EXPIRED_DEADLINE
  503. out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED
  504. out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED
  505. out.Message = "serial write not started"
  506. if job.resume {
  507. d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, "resume_not_started")
  508. }
  509. d.recordAction(out)
  510. d.publishActionResult(out)
  511. replyNonblock(job.reply, res{action: out})
  512. return
  513. }
  514. conf := hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED
  515. if backend.WriteNeedsReconnect(sr.wr, sr.err) {
  516. conf = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN
  517. 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)
  518. out.Confirmation = conf
  519. out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_OUTCOME_UNKNOWN
  520. out.Message = "OUTCOME_UNKNOWN; transport closed, epoch bumped, lease invalidated; action not auto-replayed"
  521. out.DeviceEpoch = d.store.Epoch()
  522. if job.resume {
  523. d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, "resume_unknown")
  524. }
  525. d.lease.Cache().Store(job.batch.CommandId, job.payload, out)
  526. d.recordAction(out)
  527. d.publishActionResult(out)
  528. replyNonblock(job.reply, res{action: out})
  529. d.onDrop(ctx, fmt.Errorf("ambiguous serial write outcome=%v err=%v", sr.wr.Outcome, sr.err))
  530. return
  531. }
  532. d.lastCont = job.target
  533. d.haveCont = true
  534. d.haveDispatch = true
  535. d.lastDispatchAt = now
  536. d.lastHWHeartbeat = now
  537. d.hbPendingSince = time.Time{}
  538. d.pendingHB = false
  539. if job.credit != nil {
  540. d.slewCredit = job.credit
  541. }
  542. if job.resume {
  543. d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_NORMAL, "resume_dispatched")
  544. d.safeMode = false
  545. if d.startupDone {
  546. d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_READY)
  547. }
  548. d.publishEvent(hthv1.EventKind_EVENT_KIND_RESUME_FROM_SAFE, job.batch.GetCommandId())
  549. }
  550. d.store.BumpControlRevision()
  551. out.Confirmation = conf
  552. out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED
  553. out.ControlRevision = d.store.ControlRevision()
  554. ax := job.ax
  555. if ax.CommandID == "" {
  556. ax = d.newActionContext(job.batch.GetCommandId(), "apply", hthv1.ActionMode_ACTION_MODE_NORMAL, job.target, nil)
  557. }
  558. ax.EffectiveTarget = job.target
  559. stampResultContext(out, ax)
  560. out.DeviceEpoch = ax.DeviceEpoch
  561. out.PortGeneration = ax.PortGeneration
  562. out.Dispatched = recordFromAction(ax, now, conf, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED)
  563. out.AcceptedAction = recordFromAction(ax, now, conf, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED)
  564. d.lease.Cache().Store(job.batch.CommandId, job.payload, out)
  565. d.recordAction(out)
  566. d.publishActionResult(out)
  567. d.publishNow()
  568. replyNonblock(job.reply, res{action: out})
  569. }
  570. func (d *Device) finishHeartbeat(ctx context.Context, res serialResult) {
  571. now := d.clk.Now()
  572. origin := res.origin
  573. if origin == "" {
  574. origin = "watchdog_heartbeat_repeat_continuous"
  575. }
  576. cmd := res.commandID
  577. if cmd == "" {
  578. cmd = fmt.Sprintf("%s:heartbeat-job:%d", d.daemon, res.id)
  579. }
  580. if res.wr.Outcome == backend.WriteFullyWritten && res.err == nil {
  581. d.lastHWHeartbeat = now
  582. d.hbPendingSince = time.Time{}
  583. d.pendingHB = false
  584. d.hbDeliveryState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED
  585. d.hub.PublishEvent(&hthv1.Event{
  586. EventId: d.store.NextEventID(), Kind: hthv1.EventKind_EVENT_KIND_WATCHDOG_HEARTBEAT,
  587. WallTime: timestamppb.New(now), DeviceId: d.id, Message: origin,
  588. PortGeneration: res.portGen,
  589. })
  590. ax := res.ax
  591. var rec *hthv1.ActionRecord
  592. if ax.CommandID == "" {
  593. rec = d.makeInternalRecord(cmd, origin, hthv1.ActionMode_ACTION_MODE_HEARTBEAT, now,
  594. hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED, res.frame)
  595. ax.CommandID, ax.Origin, ax.DeviceEpoch, ax.PortGeneration = cmd, origin, res.epoch, res.portGen
  596. } else {
  597. rec = recordFromAction(ax, now, hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED,
  598. hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED)
  599. }
  600. d.publishActionResult(&hthv1.ActionResult{
  601. CommandId: cmd, Accepted: true, DeviceEpoch: ax.DeviceEpoch, PortGeneration: ax.PortGeneration,
  602. ActionOrigin: origin, Dispatched: rec,
  603. Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED,
  604. DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED,
  605. Message: "hardware heartbeat dispatched UNCONFIRMED; control_revision unchanged",
  606. ControlRevision: d.store.ControlRevision(),
  607. })
  608. d.publishNow()
  609. return
  610. }
  611. if res.wr.Outcome == backend.WriteNotStarted {
  612. d.hbDeliveryState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED
  613. d.book.Raise(now, hthv1.FaultType_FAULT_TYPE_SAFE_ACTION_NOT_DELIVERED, d.id, origin,
  614. fmt.Sprintf("heartbeat NOT_STARTED n=%d err=%v", res.wr.N, res.err), "", nil)
  615. d.publishActionResult(&hthv1.ActionResult{
  616. CommandId: cmd, Accepted: false,
  617. Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED,
  618. DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED,
  619. Message: "hardware heartbeat not started; not counted as success",
  620. DeviceEpoch: res.epoch, PortGeneration: res.portGen, ActionOrigin: origin,
  621. ControlRevision: d.store.ControlRevision(),
  622. })
  623. d.publishNow()
  624. if d.watchdogMargin() < d.cfg.Heartbeat()*2 {
  625. d.pendingHB = true
  626. }
  627. return
  628. }
  629. d.hbDeliveryState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_OUTCOME_UNKNOWN
  630. d.book.Raise(now, hthv1.FaultType_FAULT_TYPE_CONTROL_OUTCOME_UNKNOWN, d.id, origin,
  631. fmt.Sprintf("heartbeat %s: %v", res.wr.Outcome, res.err), "", nil)
  632. d.publishActionResult(&hthv1.ActionResult{
  633. CommandId: cmd, Accepted: false,
  634. Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN,
  635. DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_OUTCOME_UNKNOWN,
  636. Message: "hardware heartbeat outcome unknown; transport dropped",
  637. DeviceEpoch: res.epoch, PortGeneration: res.portGen, ActionOrigin: origin,
  638. ControlRevision: d.store.ControlRevision(),
  639. })
  640. d.onDrop(ctx, fmt.Errorf("heartbeat write %s: %v", res.wr.Outcome, res.err))
  641. }
  642. func (d *Device) watchdogTimeout() time.Duration {
  643. if d.prof != nil && d.prof.Watchdog.TimeoutSeconds > 0 {
  644. return time.Duration(d.prof.Watchdog.TimeoutSeconds) * time.Second
  645. }
  646. return 30 * time.Second
  647. }
  648. func (d *Device) watchdogMargin() time.Duration {
  649. to := d.watchdogTimeout()
  650. if d.lastHWHeartbeat.IsZero() {
  651. return 0
  652. }
  653. elapsed := d.clk.Now().Sub(d.lastHWHeartbeat)
  654. if elapsed >= to {
  655. return 0
  656. }
  657. return to - elapsed
  658. }
  659. func (d *Device) markHeartbeatPending() {
  660. if d.draining || !d.connected || !d.startupDone || !d.baselineReady || !d.haveCont {
  661. return
  662. }
  663. d.pendingHB = true
  664. if d.hbPendingSince.IsZero() {
  665. d.hbPendingSince = d.clk.Now()
  666. }
  667. }
  668. func (d *Device) heartbeatDue() bool {
  669. if d.draining || !d.connected || !d.startupDone || !d.baselineReady || !d.haveCont {
  670. return false
  671. }
  672. if d.backend.PollMode() != backend.PollUART {
  673. return false
  674. }
  675. if d.pendingHB {
  676. return true
  677. }
  678. if d.lastHWHeartbeat.IsZero() {
  679. return true
  680. }
  681. now := d.clk.Now()
  682. if !now.Before(d.lastHWHeartbeat.Add(d.cfg.Heartbeat())) {
  683. return true
  684. }
  685. return now.Sub(d.lastHWHeartbeat) >= d.maxAllowedHeartbeatGap()
  686. }
  687. func (d *Device) maxAllowedHeartbeatGap() time.Duration {
  688. fw := d.watchdogTimeout()
  689. gap := d.cfg.Heartbeat() * 3
  690. if gap >= fw {
  691. gap = fw - time.Second
  692. if gap < d.cfg.Heartbeat() {
  693. gap = d.cfg.Heartbeat()
  694. }
  695. }
  696. return gap
  697. }
  698. func (d *Device) temperatureScanReserve() time.Duration {
  699. est := d.cfg.GetTempTimeout(d.prof)
  700. if d.prof != nil && d.prof.Timeouts.TemperatureScanBusyMS > 0 {
  701. busy := time.Duration(d.prof.Timeouts.TemperatureScanBusyMS)*time.Millisecond + time.Second
  702. if busy < est {
  703. est = busy
  704. }
  705. }
  706. // A UART timeout budget can meet or exceed the firmware watchdog
  707. // (production yaml: GET_TEMP 20s + SET_ALL 8s + slack >= 30s). Using
  708. // that budget as the reservation would permanently suppress
  709. // GET_TEMPERATURE. Cap the scan reserve at half the watchdog.
  710. half := d.watchdogTimeout() / 2
  711. if est > half {
  712. est = half
  713. }
  714. if est < time.Second {
  715. est = time.Second
  716. }
  717. return est
  718. }
  719. func (d *Device) temperatureWouldStarveWatchdog() bool {
  720. if d.lastHWHeartbeat.IsZero() {
  721. return true
  722. }
  723. need := d.temperatureScanReserve() + d.cfg.SetAllTimeout() + time.Second
  724. return d.watchdogMargin() < need
  725. }
  726. func (d *Device) kickPendingSerial(ctx context.Context) {
  727. if !d.connected || d.serialInflight() {
  728. return
  729. }
  730. if d.draining {
  731. return
  732. }
  733. d.expirePendingResume(ctx)
  734. if d.pendingSafeJob != nil {
  735. job := d.pendingSafeJob
  736. now := d.clk.Now()
  737. origin := "queued_safe"
  738. if job.origin != "" {
  739. origin = job.origin
  740. }
  741. if !job.deadline.IsZero() && now.After(job.deadline) {
  742. if d.serialInflight() {
  743. job.deadline = now.Add(d.remainingInflight() + d.cfg.SetAllTimeout())
  744. return
  745. }
  746. d.pendingSafeJob = nil
  747. ax := ActionExecutionContext{
  748. CommandID: job.commandID, Origin: origin, Mode: hthv1.ActionMode_ACTION_MODE_SAFE,
  749. DeviceEpoch: job.epoch, PortGeneration: d.portGen,
  750. PeerUID: job.peerUID, PeerGID: job.peerGID, PeerPID: job.peerPID,
  751. }
  752. if ax.DeviceEpoch == 0 {
  753. ax.DeviceEpoch = d.store.Epoch()
  754. }
  755. out := &hthv1.ActionResult{
  756. CommandId: job.commandID, Accepted: false, DeviceEpoch: ax.DeviceEpoch, PortGeneration: ax.PortGeneration,
  757. ActionOrigin: origin, ControlRevision: d.store.ControlRevision(),
  758. Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED,
  759. DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED,
  760. Message: "SAFE_DELIVERY_FAILED: WriteNotStarted retry budget/deadline exhausted; explicit EnterSafeMode may retry",
  761. }
  762. stampResultContext(out, ax)
  763. d.publishActionResult(out)
  764. if d.controlMode != hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE {
  765. d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING, "safe_retry_deadline")
  766. }
  767. d.publishNow()
  768. return
  769. }
  770. if !job.nextRetry.IsZero() && now.Before(job.nextRetry) {
  771. return
  772. }
  773. frame := d.safeFrame()
  774. ax := ActionExecutionContext{
  775. CommandID: job.commandID, Origin: origin, Mode: hthv1.ActionMode_ACTION_MODE_SAFE,
  776. DeviceEpoch: job.epoch, PortGeneration: d.portGen, Frame: frame, EffectiveTarget: frame,
  777. PeerUID: job.peerUID, PeerGID: job.peerGID, PeerPID: job.peerPID,
  778. }
  779. if ax.DeviceEpoch == 0 {
  780. ax.DeviceEpoch = d.store.Epoch()
  781. }
  782. if !d.enqueueSerial(d.serialJobFromAction(jobSetAllSafe, d.cfg.SetAllTimeout(), ax)) {
  783. return
  784. }
  785. return
  786. }
  787. if d.pendingResume != nil {
  788. d.dispatchPendingResume(ctx)
  789. return
  790. }
  791. if len(d.pendingApply) > 0 {
  792. r := d.pendingApply[0]
  793. d.pendingApply = d.pendingApply[1:]
  794. if r.rpcCtx != nil && r.rpcCtx.Err() != nil {
  795. replyNonblock(r.reply, res{action: cancelledResult(r.batch, r.rpcCtx.Err()), err: r.rpcCtx.Err()})
  796. d.kickPendingSerial(ctx)
  797. return
  798. }
  799. d.beginApply(ctx, r)
  800. return
  801. }
  802. if d.heartbeatDue() {
  803. d.pendingHB = false
  804. d.heartbeat(ctx)
  805. return
  806. }
  807. if d.pendingMotor && d.backend.PollMode() == backend.PollUART {
  808. d.pendingMotor = false
  809. d.enqueueSerial(serialJob{kind: jobGetMotor, timeout: d.cfg.GetMotorTimeout(), origin: "readiness_probe"})
  810. return
  811. }
  812. if d.pendingTemp && d.startupDone {
  813. if d.pendingSafeJob != nil || d.pendingResume != nil || len(d.pendingApply) > 0 || d.controlWindowOpen(d.clk.Now()) {
  814. return
  815. }
  816. if d.heartbeatDue() || d.temperatureWouldStarveWatchdog() {
  817. d.markHeartbeatPending()
  818. d.heartbeat(ctx)
  819. return
  820. }
  821. d.pendingTemp = false
  822. d.enqueueSerial(serialJob{kind: jobGetTemp, timeout: d.cfg.GetTempTimeout(d.prof)})
  823. return
  824. }
  825. }
  826. func replyNonblock(ch chan res, r res) {
  827. if ch == nil {
  828. return
  829. }
  830. select {
  831. case ch <- r:
  832. default:
  833. }
  834. }