| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556 |
- package device
- import (
- "context"
- "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/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
- startedAt time.Time
- deadline time.Time
- timeout time.Duration
- frame protocol.SetAll
- }
- type serialResult struct {
- id uint64
- portGen uint64
- epoch uint64
- kind jobKind
- origin string
- started time.Time
- wr backend.WriteResult
- err error
- temp *backend.TempReport
- motor *backend.MotorReport
- frame protocol.SetAll
- }
- 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
- enqueued time.Time
- deadline time.Time
- epoch uint64
- }
- 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.currentInflight = inflightIdent{
- id: j.id, portGen: j.portGen, epoch: j.epoch, kind: j.kind,
- origin: j.origin, startedAt: j.startedAt,
- }
- }
- func (d *Device) endInflight() {
- atomic.StoreInt64(&d.inflightSinceNano, 0)
- d.inflightTimeout = 0
- d.inflightKind = 0
- d.currentInflight = inflightIdent{}
- }
- func (d *Device) resultMatchesInflight(res serialResult) bool {
- inf := d.currentInflight
- 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) remainingInflight() time.Duration {
- if !d.serialInflight() {
- return 0
- }
- to := d.inflightTimeout
- if to <= 0 {
- to = 2 * time.Second
- }
- elapsed := d.SerialBusy()
- rem := to - elapsed
- if rem < 50*time.Millisecond {
- rem = 50 * time.Millisecond
- }
- if d.inflightKind == jobGetTemp {
- return rem
- }
- // Motor/open/SET_ALL I/O timeouts are much larger than the typical
- // completion time. Do not treat the full timeout as queue wait for
- // ordinary 2s action TTLs.
- if rem > 100*time.Millisecond {
- return 100 * time.Millisecond
- }
- return rem
- }
- 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()
- j.portGen = d.portGen
- j.epoch = d.store.Epoch()
- j.startedAt = 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, started: j.startedAt, frame: j.frame,
- }
- 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) {
- d.log.Warn("discarding stale serial result",
- "job_id", res.id, "job_epoch", res.epoch, "job_port_gen", res.portGen,
- "inflight_id", d.currentInflight.id, "inflight_epoch", d.currentInflight.epoch,
- "inflight_port_gen", d.currentInflight.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)
- 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.portGen++
- 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()
- if !d.enqueueSerial(serialJob{kind: jobSetAllSafe, timeout: d.cfg.SetAllTimeout(), frame: frame, origin: originEpochBaseline}) {
- 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
- 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()
- out.DeviceEpoch = d.store.Epoch()
- out.Dispatched = actionRecord(job.batch, now, conf, job.target)
- if out.Dispatched != nil {
- out.Dispatched.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED
- }
- out.AcceptedAction = actionRecord(job.batch, now, conf, job.target)
- 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"
- }
- if res.wr.Outcome == backend.WriteFullyWritten && res.err == nil {
- d.lastHWHeartbeat = now
- 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: d.portGen,
- })
- 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: d.nextInternalCommandID("heartbeat"), 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: d.store.Epoch(), PortGeneration: d.portGen, ActionOrigin: origin,
- })
- 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: d.nextInternalCommandID("heartbeat"), 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: d.store.Epoch(), PortGeneration: d.portGen, ActionOrigin: origin,
- })
- 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) kickPendingSerial(ctx context.Context) {
- if !d.connected || d.serialInflight() {
- return
- }
- if d.draining {
- return
- }
- d.expirePendingResume(ctx)
- if d.pendingSafeJob != nil || d.pendingSafe {
- job := d.pendingSafeJob
- d.pendingSafeJob = nil
- d.pendingSafe = false
- origin := "queued_safe"
- if job != nil && job.origin != "" {
- origin = job.origin
- }
- frame := d.safeFrame()
- if !d.enqueueSerial(serialJob{kind: jobSetAllSafe, timeout: d.cfg.SetAllTimeout(), frame: frame, origin: origin}) {
- d.pendingSafe = true
- if job == nil {
- job = &pendingSafeState{origin: origin, enqueued: d.clk.Now(), epoch: d.store.Epoch()}
- }
- d.pendingSafeJob = job
- }
- 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.pendingHB {
- d.pendingHB = false
- d.heartbeat(ctx)
- return
- }
- if d.pendingTemp && d.startupDone {
- if d.pendingSafe || d.pendingSafeJob != nil || d.pendingResume != nil || len(d.pendingApply) > 0 || d.controlWindowOpen(d.clk.Now()) {
- return
- }
- d.pendingTemp = false
- d.enqueueSerial(serialJob{kind: jobGetTemp, timeout: d.cfg.GetTempTimeout(d.prof)})
- }
- }
- func replyNonblock(ch chan res, r res) {
- if ch == nil {
- return
- }
- select {
- case ch <- r:
- default:
- }
- }
|