| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "time" |
| 8 | |
| 9 | "amadan.net/oficina/equipo/internal/equipo/pause" |
| 10 | "amadan.net/oficina/equipo/internal/wire" |
| 11 | "gorm.io/gorm" |
| 12 | ) |
| 13 | |
| 14 | // A paused job (paused work, decision 5). A job is paused when every |
| 15 | // task it follows that is still open waits and carries on by itself: its |
| 16 | // step held for a plan's limit (headroom) or a spending limit (budget) |
| 17 | // with nothing asked of the person, or waiting for its runner while that |
| 18 | // runner is offline. A brief wait for a busy slot is still working. A |
| 19 | // hold that needs the person (spend unknown, nothing that can run it, the |
| 20 | // deadline check) is not paused either, and not asking: its held card is |
| 21 | // in the person's conversation, not a question card, so the job reads as |
| 22 | // working until the person answers (a known gap, in the spec). |
| 23 | |
| 24 | // Why a job is paused: the words Base shows. |
| 25 | const ( |
| 26 | pausedAllowance = "allowance" |
| 27 | pausedLimit = "limit" |
| 28 | pausedOffline = "offline" |
| 29 | ) |
| 30 | |
| 31 | // carryOnFor is how long a Carry on now written for a step keeps its job |
| 32 | // working while the runner has yet to start the step: past it, a hold the |
| 33 | // runner still reports shows again. |
| 34 | const carryOnFor = 2 * time.Minute |
| 35 | |
| 36 | // jobPause is a paused job's words and its Carry on now, if any: the |
| 37 | // held step another plan would take at no extra cost. |
| 38 | type jobPause struct { |
| 39 | reason string |
| 40 | at *time.Time |
| 41 | task string |
| 42 | step string |
| 43 | rev int64 |
| 44 | // conn is the connection Carry on now would run on (RunNowOffer's id): |
| 45 | // the card keeps it, and the release is pinned to it (review R1). |
| 46 | conn string |
| 47 | } |
| 48 | |
| 49 | // jobPaused is the hand-off's pause, nil while any task it follows that |
| 50 | // is open is not paused (or it follows none). |
| 51 | func (t *txn) jobPaused(h handoffRecord) (*jobPause, error) { |
| 52 | tasks, err := t.handoffTasks(h) |
| 53 | if err != nil { |
| 54 | return nil, err |
| 55 | } |
| 56 | var out *jobPause |
| 57 | for _, k := range tasks { |
| 58 | if wire.FinalStage(k.Stage) || k.CancelRequested { |
| 59 | continue |
| 60 | } |
| 61 | s, ok, err := t.latestStep(k.ID) |
| 62 | if err != nil || !ok { |
| 63 | return nil, err |
| 64 | } |
| 65 | p, err := t.taskPause(k, s) |
| 66 | if err != nil || p == nil { |
| 67 | return nil, err |
| 68 | } |
| 69 | if out == nil { |
| 70 | out = p |
| 71 | continue |
| 72 | } |
| 73 | // The job carries on when its first task does. |
| 74 | if p.at != nil && (out.at == nil || p.at.Before(*out.at)) { |
| 75 | out.reason, out.at = p.reason, p.at |
| 76 | } |
| 77 | if out.step == "" { |
| 78 | out.task, out.step, out.rev, out.conn = p.task, p.step, p.rev, p.conn |
| 79 | } |
| 80 | } |
| 81 | return out, nil |
| 82 | } |
| 83 | |
| 84 | // taskPause is task k's pause while its latest step s waits, nil when it |
| 85 | // does not (or a Carry on now for it is on its way). |
| 86 | func (t *txn) taskPause(k taskRecord, s stepRecord) (*jobPause, error) { |
| 87 | p := t.stepPaused(k, s) |
| 88 | if p == nil { |
| 89 | return nil, nil |
| 90 | } |
| 91 | if p.Offline { |
| 92 | return &jobPause{reason: pausedOffline}, nil |
| 93 | } |
| 94 | h := stepHold(s) |
| 95 | if h == nil || h.NeedsPerson != "" { |
| 96 | return nil, nil |
| 97 | } |
| 98 | out := &jobPause{} |
| 99 | switch h.Reason { |
| 100 | case wire.HoldHeadroom: |
| 101 | out.reason, out.at = pausedAllowance, h.ResetsAt |
| 102 | if out.at == nil { |
| 103 | out.at = h.WakeAt |
| 104 | } |
| 105 | case wire.HoldBudget: |
| 106 | out.reason, out.at = pausedLimit, h.WakeAt |
| 107 | default: |
| 108 | return nil, nil |
| 109 | } |
| 110 | var r releaseRecord |
| 111 | err := t.db.Where("step_id = ? AND step_revision = ?", s.ID, h.StepRevision).Limit(1).Find(&r).Error |
| 112 | if err != nil { |
| 113 | return nil, err |
| 114 | } |
| 115 | if r.ID != "" && t.now().Sub(r.CreatedAt) < carryOnFor { |
| 116 | // Carry on now (or Run now) was tapped: the job is working. |
| 117 | return nil, nil |
| 118 | } |
| 119 | if o := p.RunNow; r.ID == "" && o != nil && o.Billing == wire.BillingSubscription && !o.Same { |
| 120 | out.task, out.step, out.rev, out.conn = k.ID, s.ID, h.StepRevision, o.Connection |
| 121 | } |
| 122 | return out, nil |
| 123 | } |
| 124 | |
| 125 | // pausedWords are a paused job's status and sentence, in the person's |
| 126 | // zone: "Paused until 21:00", and why and when it carries on, never |
| 127 | // naming a computer, a model, a runner, Equipo or an allowance. |
| 128 | func (t *txn) pausedWords(person string, p *jobPause) (result, detail string) { |
| 129 | now, loc := t.now(), t.zone(person) |
| 130 | result = t.copy("work.stage.paused") |
| 131 | var at, in string |
| 132 | if p.at != nil && p.at.After(now) { |
| 133 | result = fmt.Sprintf(t.copy("assistant.job.paused"), pause.Short(t.copy, now, *p.at, loc)) |
| 134 | at, in = pause.At(t.copy, now, *p.at, loc), pause.In(t.copy, p.at.Sub(now)) |
| 135 | } |
| 136 | switch { |
| 137 | case p.reason == pausedOffline: |
| 138 | detail = t.copy("assistant.job.detail.paused_offline") |
| 139 | case at == "": |
| 140 | case p.reason == pausedLimit: |
| 141 | detail = fmt.Sprintf(t.copy("assistant.job.detail.paused_limit"), at, in) |
| 142 | default: |
| 143 | detail = fmt.Sprintf(t.copy("assistant.job.detail.paused_allowance"), at, in) |
| 144 | } |
| 145 | return result, detail |
| 146 | } |
| 147 | |
| 148 | // refreshJobs brings each working or paused job card up to date (the |
| 149 | // housekeeping minute): a runner that went offline, a pause's relative |
| 150 | // words and the person's zone change without a report. A card moves |
| 151 | // only when its words do. Each card is its own transaction, and one that |
| 152 | // cannot be projected is logged and skipped (review S1): it never stops |
| 153 | // the rest of the minute, or the cards after it. |
| 154 | func (s *Store) refreshJobs(ctx context.Context) { |
| 155 | var cards []cardRecord |
| 156 | err := s.read(ctx, func(tx *gorm.DB) error { |
| 157 | return tx.Select("id", "handoff_id", "person").Where("lane = ? AND kind = ? AND state IN ?", wire.LaneAssistant, wire.CardJob, []string{wire.JobWorking, wire.JobPaused}).Order("created_at, id").Find(&cards).Error |
| 158 | }) |
| 159 | if err != nil { |
| 160 | s.logJobRefresh("", err) |
| 161 | return |
| 162 | } |
| 163 | for _, c := range cards { |
| 164 | err := s.tx(ctx, func(t *txn) error { |
| 165 | var h handoffRecord |
| 166 | if err := t.db.Where("id = ? AND person = ?", c.HandoffID, c.Person).Limit(1).Find(&h).Error; err != nil || h.ID == "" { |
| 167 | return err |
| 168 | } |
| 169 | if s.projectJobHook != nil { |
| 170 | return s.projectJobHook(t, h) |
| 171 | } |
| 172 | return t.projectJob(h) |
| 173 | }) |
| 174 | if err != nil { |
| 175 | s.logJobRefresh(c.ID, err) |
| 176 | } |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | // logJobRefresh reports a job card the sweep could not bring up to date. |
| 181 | func (s *Store) logJobRefresh(card string, err error) { |
| 182 | if l := s.logger.Load(); l != nil { |
| 183 | l.Warn("job card refresh", "card", card, "err", err) |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | // ErrNotPaused: Carry on now for a job card that is not paused. |
| 188 | var ErrNotPaused = errors.New("chat: the job is not paused") |
| 189 | |
| 190 | // ErrCarryOnUnavailable: Carry on now for a paused job card that does |
| 191 | // not offer it. |
| 192 | var ErrCarryOnUnavailable = errors.New("chat: carry on is not available") |
| 193 | |
| 194 | // actionCarryOn is Carry on now's handoffActionRecord kind. |
| 195 | const actionCarryOn = "carry_on" |
| 196 | |
| 197 | // CarryOn is Carry on now on one of the person's paused job cards (POST |
| 198 | // /api/v1/assistant/cards/{id}/carry_on): Run now's release for the held |
| 199 | // step another plan would take, against the card's revision, once per |
| 200 | // idempotency key (the same key again answers with the card as it is |
| 201 | // now). It answers the card, or the card as it is now with |
| 202 | // ErrCardConflict (stale), ErrNotPaused or ErrCarryOnUnavailable. |
| 203 | func (s *Store) CarryOn(ctx context.Context, person, id string, in wire.CarryOn) (out wire.AssistantCard, err error) { |
| 204 | if in.IdempotencyKey == "" || len(in.IdempotencyKey) > 128 { |
| 205 | return out, ErrInvalid |
| 206 | } |
| 207 | s.refreshBeforeAct(ctx, person) |
| 208 | var refused error |
| 209 | err = s.tx(ctx, func(t *txn) error { |
| 210 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 211 | return err |
| 212 | } |
| 213 | var c cardRecord |
| 214 | if err := t.db.Where("id = ? AND person = ? AND lane = ? AND kind = ?", id, person, wire.LaneAssistant, wire.CardJob).Limit(1).Find(&c).Error; err != nil { |
| 215 | return err |
| 216 | } |
| 217 | if c.ID == "" { |
| 218 | return ErrNotFound |
| 219 | } |
| 220 | key := actionCarryOn + ":" + c.ID + ":" + in.IdempotencyKey |
| 221 | var done handoffActionRecord |
| 222 | if err := t.db.Where("ledger_key = ?", key).Limit(1).Find(&done).Error; err != nil { |
| 223 | return err |
| 224 | } |
| 225 | if done.LedgerKey != "" { |
| 226 | out, err = t.assistantCardOf(c.ID) |
| 227 | return err |
| 228 | } |
| 229 | var h handoffRecord |
| 230 | if err := t.db.Where("id = ? AND person = ?", c.HandoffID, person).Limit(1).Find(&h).Error; err != nil { |
| 231 | return err |
| 232 | } |
| 233 | // The card as it is now: projected afresh, so the answer and the |
| 234 | // refusal are about what the person would see on reading it. |
| 235 | if h.ID != "" { |
| 236 | if err := t.projectJob(h); err != nil { |
| 237 | return err |
| 238 | } |
| 239 | } |
| 240 | now, err := t.assistantCardOf(c.ID) |
| 241 | if err != nil { |
| 242 | return err |
| 243 | } |
| 244 | out = now |
| 245 | if now.Revision != in.Revision { |
| 246 | refused = ErrCardConflict |
| 247 | return nil |
| 248 | } |
| 249 | if h.ID != "" && h.AbilityHeldAt != nil && h.State == handoffOpen { |
| 250 | // A job held while building was off: Carry on now resumes it, |
| 251 | // once building is on again (abilities §6.3). |
| 252 | if err := t.resumeAbilityHold(h); errors.Is(err, ErrAbilityOff) { |
| 253 | refused = ErrAbilityOff |
| 254 | return nil |
| 255 | } else if err != nil { |
| 256 | return err |
| 257 | } |
| 258 | if err := t.db.Create(&handoffActionRecord{LedgerKey: key, HandoffID: h.ID, Person: person, Kind: actionCarryOn, Result: "resumed", CreatedAt: t.now()}).Error; err != nil { |
| 259 | return err |
| 260 | } |
| 261 | out, err = t.assistantCardOf(c.ID) |
| 262 | return err |
| 263 | } |
| 264 | switch { |
| 265 | case now.State != wire.JobPaused: |
| 266 | refused = ErrNotPaused |
| 267 | return nil |
| 268 | case !now.CarryOn || h.ID == "": |
| 269 | refused = ErrCarryOnUnavailable |
| 270 | return nil |
| 271 | } |
| 272 | p, err := t.jobPaused(h) |
| 273 | if err != nil { |
| 274 | return err |
| 275 | } |
| 276 | if p == nil || p.step == "" { |
| 277 | refused = ErrCarryOnUnavailable |
| 278 | return nil |
| 279 | } |
| 280 | if err := t.hkForbid("carry on"); err != nil { |
| 281 | return err |
| 282 | } |
| 283 | k, err := t.loadTask(p.task) |
| 284 | if errors.Is(err, ErrNotFound) { |
| 285 | refused = ErrCarryOnUnavailable |
| 286 | return nil |
| 287 | } |
| 288 | if err != nil { |
| 289 | return err |
| 290 | } |
| 291 | if k.Creator != person { |
| 292 | refused = ErrCarryOnUnavailable |
| 293 | return nil |
| 294 | } |
| 295 | // Pinned to the plan behind the card's carry_on: a different one now |
| 296 | // moved the card's revision when it was projected above. |
| 297 | if p.conn != c.CarryOnConnection { |
| 298 | refused = ErrCarryOnUnavailable |
| 299 | return nil |
| 300 | } |
| 301 | release, err := t.release(k, person, p.step, p.rev, &p.conn) |
| 302 | if errors.Is(err, ErrConflict) || errors.Is(err, ErrHoldBar) || errors.Is(err, ErrRunnerTooOld) || errors.Is(err, ErrNotFound) || errors.Is(err, ErrOfferChanged) { |
| 303 | // Run now's own refusals are one answer here: Carry on now is |
| 304 | // not available (the contract's three 409s, and no other). |
| 305 | refused = ErrCarryOnUnavailable |
| 306 | return nil |
| 307 | } |
| 308 | if err != nil { |
| 309 | return err |
| 310 | } |
| 311 | if err := t.db.Create(&handoffActionRecord{LedgerKey: key, HandoffID: h.ID, Person: person, Kind: actionCarryOn, Result: release, CreatedAt: t.now()}).Error; err != nil { |
| 312 | return err |
| 313 | } |
| 314 | if err := t.projectJob(h); err != nil { |
| 315 | return err |
| 316 | } |
| 317 | out, err = t.assistantCardOf(c.ID) |
| 318 | return err |
| 319 | }) |
| 320 | if err == nil && refused != nil { |
| 321 | return out, refused |
| 322 | } |
| 323 | return out, err |
| 324 | } |
| 325 | |
| 326 | // assistantCardOf is one card as the Assistant lane shows it, read now. |
| 327 | func (t *txn) assistantCardOf(id string) (wire.AssistantCard, error) { |
| 328 | var c cardRecord |
| 329 | if err := t.db.Where("id = ?", id).First(&c).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 330 | return wire.AssistantCard{}, ErrNotFound |
| 331 | } else if err != nil { |
| 332 | return wire.AssistantCard{}, err |
| 333 | } |
| 334 | return t.assistantCardView(c) |
| 335 | } |
| 336 | |