serial_worker.go 21 KB

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