serial_worker.go 21 KB

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