| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "slices" |
| 8 | "strings" |
| 9 | "time" |
| 10 | |
| 11 | "gorm.io/gorm" |
| 12 | |
| 13 | "amadan.net/oficina/equipo/internal/equipo/housekeeping" |
| 14 | "amadan.net/oficina/equipo/internal/wire" |
| 15 | ) |
| 16 | |
| 17 | // Control (spec §4): Pause, detectors switched off after two failures, |
| 18 | // quiet hours, the daily digest, the daily sweep and claim recovery. |
| 19 | |
| 20 | // ErrActionConflict: an Undo that can no longer apply (undone already, |
| 21 | // past its window, or the subject moved on). |
| 22 | var ErrActionConflict = errors.New("chat: action conflict") |
| 23 | |
| 24 | // ErrRevision: a settings change against a revision that is not current. |
| 25 | var ErrRevision = errors.New("chat: stale revision") |
| 26 | |
| 27 | // hkSettingsRecord is one person's housekeeping settings. Disabled is a |
| 28 | // JSON map of detector id to hkDisabled. |
| 29 | type hkSettingsRecord struct { |
| 30 | Person string `gorm:"primaryKey"` |
| 31 | Paused bool |
| 32 | Disabled string |
| 33 | LastDigestAt *time.Time |
| 34 | LastSweepAt *time.Time |
| 35 | Revision int64 |
| 36 | // QuietFrom and QuietUntil are the person's quiet hours; null is the |
| 37 | // default, 22:00 to 08:00; equal is none. |
| 38 | QuietFrom *int |
| 39 | QuietUntil *int |
| 40 | } |
| 41 | |
| 42 | func (hkSettingsRecord) TableName() string { return "chat_housekeeping_settings" } |
| 43 | |
| 44 | // hkDisabled is a detector switched off for a person: Since counts |
| 45 | // failures from a re-enable (re-enabling clears the count); Told once |
| 46 | // the digest said so. |
| 47 | type hkDisabled struct { |
| 48 | Off bool `json:"off"` |
| 49 | Reason string `json:"reason"` |
| 50 | At time.Time `json:"at"` |
| 51 | Since time.Time `json:"since"` |
| 52 | Told bool `json:"told"` |
| 53 | } |
| 54 | |
| 55 | type hkSettings struct { |
| 56 | hkSettingsRecord |
| 57 | found bool |
| 58 | disabled map[string]hkDisabled |
| 59 | } |
| 60 | |
| 61 | func (s hkSettings) disabledFor(id string) bool { return s.disabled[id].Off } |
| 62 | |
| 63 | // quiet is the person's quiet hours. |
| 64 | func (s hkSettings) quiet() housekeeping.QuietHours { |
| 65 | if s.QuietFrom == nil || s.QuietUntil == nil { |
| 66 | return housekeeping.DefaultQuiet |
| 67 | } |
| 68 | return housekeeping.QuietHours{From: *s.QuietFrom, Until: *s.QuietUntil} |
| 69 | } |
| 70 | |
| 71 | // SetHousekeepingClock moves the loop's clock (quiet hours, the day's |
| 72 | // budget, the digest and the sweep); nil restores the store's own. |
| 73 | func (s *Store) SetHousekeepingClock(now func() time.Time) { |
| 74 | s.hkMu.Lock() |
| 75 | defer s.hkMu.Unlock() |
| 76 | s.clock = now |
| 77 | } |
| 78 | |
| 79 | func (s *Store) registry() *housekeeping.Registry { return s.detectors } |
| 80 | |
| 81 | func (t *txn) hkNow() time.Time { return t.s.hkClock() } |
| 82 | |
| 83 | // hkClock is the loop's clock: the store's unless a test moved it. |
| 84 | func (s *Store) hkClock() time.Time { |
| 85 | s.hkMu.Lock() |
| 86 | clock := s.clock |
| 87 | s.hkMu.Unlock() |
| 88 | if clock != nil { |
| 89 | return clock().UTC() |
| 90 | } |
| 91 | return s.now() |
| 92 | } |
| 93 | |
| 94 | func (t *txn) hkSettings(person string) (hkSettings, error) { |
| 95 | var r hkSettingsRecord |
| 96 | err := t.db.Where("person = ?", person).First(&r).Error |
| 97 | out := hkSettings{hkSettingsRecord: r, disabled: map[string]hkDisabled{}} |
| 98 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 99 | out.Person = person |
| 100 | return out, nil |
| 101 | } |
| 102 | if err != nil { |
| 103 | return out, err |
| 104 | } |
| 105 | out.found = true |
| 106 | if r.Disabled != "" { |
| 107 | if err := json.Unmarshal([]byte(r.Disabled), &out.disabled); err != nil { |
| 108 | return out, err |
| 109 | } |
| 110 | } |
| 111 | return out, nil |
| 112 | } |
| 113 | |
| 114 | func (t *txn) saveSettings(s *hkSettings) error { |
| 115 | raw, _ := json.Marshal(s.disabled) |
| 116 | s.Disabled = string(raw) |
| 117 | s.Revision++ |
| 118 | if !s.found { |
| 119 | s.found = true |
| 120 | if err := t.db.Create(&s.hkSettingsRecord).Error; err != nil { |
| 121 | return err |
| 122 | } |
| 123 | } else if err := t.db.Model(&hkSettingsRecord{}).Where("person = ?", s.Person).Select("paused", "disabled", "last_digest_at", "last_sweep_at", "revision", "quiet_from", "quiet_until").Updates(&s.hkSettingsRecord).Error; err != nil { |
| 124 | return err |
| 125 | } |
| 126 | sum, err := t.hkSummary(s.Person) |
| 127 | if err != nil { |
| 128 | return err |
| 129 | } |
| 130 | return t.event("", s.Person, wire.EventHousekeeping, "housekeeping", s.Person, s.Revision, "", "", 0, sum) |
| 131 | } |
| 132 | |
| 133 | func (t *txn) hkSummary(person string) (wire.HousekeepingSummary, error) { |
| 134 | s, err := t.hkSettings(person) |
| 135 | if err != nil { |
| 136 | return wire.HousekeepingSummary{}, err |
| 137 | } |
| 138 | out := wire.HousekeepingSummary{Paused: s.Paused, Disabled: []string{}, Revision: s.Revision} |
| 139 | for id, d := range s.disabled { |
| 140 | if d.Off { |
| 141 | out.Disabled = append(out.Disabled, id) |
| 142 | } |
| 143 | } |
| 144 | slices.Sort(out.Disabled) |
| 145 | return out, nil |
| 146 | } |
| 147 | |
| 148 | // --- The selected connection's headroom. |
| 149 | |
| 150 | // selectedHeadroom is the headroom of the connection the choice would |
| 151 | // select for the person: the one that answered their last turn, else |
| 152 | // their only connection. Nil means unknown, which stands down; no other |
| 153 | // connection is tried in its place. |
| 154 | func (t *txn) selectedHeadroom(person string) (*housekeeping.Headroom, error) { |
| 155 | conns, err := t.connections(person) |
| 156 | if err != nil { |
| 157 | return nil, err |
| 158 | } |
| 159 | var last []string |
| 160 | if err := t.db.Model(&turnRecord{}).Where("person = ? AND connection <> '' AND connection IS NOT NULL", person).Order("updated_at DESC, id DESC").Limit(1).Pluck("connection", &last).Error; err != nil { |
| 161 | return nil, err |
| 162 | } |
| 163 | var pick *connectionRecord |
| 164 | for i := range conns { |
| 165 | if len(last) > 0 && conns[i].LocalID == last[0] { |
| 166 | pick = &conns[i] |
| 167 | } |
| 168 | } |
| 169 | if pick == nil && len(conns) == 1 { |
| 170 | pick = &conns[0] |
| 171 | } |
| 172 | if pick == nil { |
| 173 | return nil, nil |
| 174 | } |
| 175 | h := &housekeeping.Headroom{Healthy: pick.State == wire.ConnHealthy, CheckedAt: pick.UpdatedAt} |
| 176 | if pick.Headroom != "" { |
| 177 | var w wire.Headroom |
| 178 | if json.Unmarshal([]byte(pick.Headroom), &w) == nil && w.Utilization != nil { |
| 179 | h.Reported, h.Utilization = true, *w.Utilization |
| 180 | } |
| 181 | } |
| 182 | return h, nil |
| 183 | } |
| 184 | |
| 185 | // --- Failures and auto-disable. |
| 186 | |
| 187 | // recordFailures counts failures in their own transaction, after the one |
| 188 | // that failed ended. |
| 189 | func (s *Store) recordFailures(ctx context.Context, fs []hkFailureRecord) error { |
| 190 | return s.tx(ctx, func(t *txn) error { |
| 191 | for _, f := range fs { |
| 192 | if err := t.hkFailure(f); err != nil { |
| 193 | return err |
| 194 | } |
| 195 | } |
| 196 | return nil |
| 197 | }) |
| 198 | } |
| 199 | |
| 200 | // hkFailure records one failure and switches the detector off for the |
| 201 | // person at the second within the window. Nothing switches it back on |
| 202 | // but the person. |
| 203 | func (t *txn) hkFailure(f hkFailureRecord) error { |
| 204 | if f.Person == "" { |
| 205 | return nil |
| 206 | } |
| 207 | if err := t.db.Create(&f).Error; err != nil { |
| 208 | return err |
| 209 | } |
| 210 | s, err := t.hkSettings(f.Person) |
| 211 | if err != nil { |
| 212 | return err |
| 213 | } |
| 214 | d := s.disabled[f.Detector] |
| 215 | if d.Off { |
| 216 | return nil |
| 217 | } |
| 218 | from := f.At.Add(-housekeeping.FailureWindow) |
| 219 | if d.Since.After(from) { |
| 220 | from = d.Since |
| 221 | } |
| 222 | var n int64 |
| 223 | if err := t.db.Model(&hkFailureRecord{}).Where("person = ? AND detector = ? AND at >= ?", f.Person, f.Detector, from).Count(&n).Error; err != nil { |
| 224 | return err |
| 225 | } |
| 226 | if n < housekeeping.FailuresToDisable { |
| 227 | return nil |
| 228 | } |
| 229 | s.disabled[f.Detector] = hkDisabled{Off: true, Reason: wire.ReasonDetectorFailures, At: f.At, Since: d.Since} |
| 230 | return t.saveSettings(&s) |
| 231 | } |
| 232 | |
| 233 | // hkUndone is a person's Undo of an action: the row becomes a retained |
| 234 | // veto and the Undo counts as a failure of its detector. |
| 235 | func (t *txn) hkUndone(r *hkRecord) error { |
| 236 | now := t.hkNow() |
| 237 | r.State, r.UndoneAt = wire.ActionUndone, &now |
| 238 | if err := t.hkSave(r, false); err != nil { |
| 239 | return err |
| 240 | } |
| 241 | return t.hkFailure(hkFailureRecord{Person: r.Person, Detector: r.Detector, Kind: failureUndone, ActionID: r.ID, At: now}) |
| 242 | } |
| 243 | |
| 244 | // --- Quiet hours. |
| 245 | |
| 246 | // hkRelease shows held receipts: a person's now (their first message |
| 247 | // ends quiet hours for them), or everyone's whose time has come. Nothing |
| 248 | // is published for a person who is paused; Resume lets it show. |
| 249 | func (t *txn) hkRelease(person string, now time.Time) error { |
| 250 | var cards []cardRecord |
| 251 | q := t.db.Where("held = ?", true) |
| 252 | if person != "" { |
| 253 | q = q.Where("person = ?", person) |
| 254 | } else { |
| 255 | q = q.Where("visible_at <= ?", now) |
| 256 | } |
| 257 | if err := q.Order("created_at, id").Find(&cards).Error; err != nil { |
| 258 | return err |
| 259 | } |
| 260 | paused := map[string]bool{} |
| 261 | for i := range cards { |
| 262 | c := &cards[i] |
| 263 | p, seen := paused[c.Person] |
| 264 | if !seen { |
| 265 | set, err := t.hkSettings(c.Person) |
| 266 | if err != nil { |
| 267 | return err |
| 268 | } |
| 269 | p, paused[c.Person] = set.Paused, set.Paused |
| 270 | } |
| 271 | if p { |
| 272 | continue |
| 273 | } |
| 274 | if c.VisibleAt == nil || c.VisibleAt.After(now) { |
| 275 | c.VisibleAt = &now |
| 276 | } |
| 277 | c.Held = false |
| 278 | if err := t.db.Model(&cardRecord{}).Where("id = ?", c.ID).Select("held", "visible_at").Updates(c).Error; err != nil { |
| 279 | return err |
| 280 | } |
| 281 | if err := t.cardEvent(*c); err != nil { |
| 282 | return err |
| 283 | } |
| 284 | } |
| 285 | return nil |
| 286 | } |
| 287 | |
| 288 | // --- Pause and the switches. |
| 289 | |
| 290 | // SetHousekeeping is Pause and the person's quiet hours. Paused, no |
| 291 | // detector runs, no sweep, nothing is posted; claims not yet dispatched |
| 292 | // go back to held and dispatched ones keep releasing until their charge |
| 293 | // is in; existing Undo stays. Quiet hours, when given, replace the |
| 294 | // window (From equal to Until is none). |
| 295 | func (s *Store) SetHousekeeping(ctx context.Context, person string, in wire.SetHousekeeping) (out wire.Housekeeping, err error) { |
| 296 | if in.Quiet != nil && !(housekeeping.QuietHours{From: in.Quiet.From, Until: in.Quiet.Until}).Valid() { |
| 297 | return out, ErrInvalid |
| 298 | } |
| 299 | err = s.tx(ctx, func(t *txn) error { |
| 300 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 301 | return err |
| 302 | } |
| 303 | set, err := t.hkSettings(person) |
| 304 | if err != nil { |
| 305 | return err |
| 306 | } |
| 307 | if in.Revision != set.Revision { |
| 308 | return ErrRevision |
| 309 | } |
| 310 | quiet := set.quiet() |
| 311 | if in.Quiet != nil && (quiet.From != in.Quiet.From || quiet.Until != in.Quiet.Until) { |
| 312 | from, until := in.Quiet.From, in.Quiet.Until |
| 313 | set.QuietFrom, set.QuietUntil = &from, &until |
| 314 | if set.Paused == in.Paused { |
| 315 | if err := t.saveSettings(&set); err != nil { |
| 316 | return err |
| 317 | } |
| 318 | } |
| 319 | } |
| 320 | if set.Paused != in.Paused { |
| 321 | set.Paused = in.Paused |
| 322 | if err := t.saveSettings(&set); err != nil { |
| 323 | return err |
| 324 | } |
| 325 | if in.Paused { |
| 326 | if err := t.hkStandDownClaims(person); err != nil { |
| 327 | return err |
| 328 | } |
| 329 | } |
| 330 | } |
| 331 | out, err = t.housekeepingView(person) |
| 332 | return err |
| 333 | }) |
| 334 | return out, err |
| 335 | } |
| 336 | |
| 337 | // hkStandDownClaims releases what a paused person's loop held: a claim |
| 338 | // that never left goes back to held; one dispatched keeps its |
| 339 | // reservation releasing until termination and its charge. |
| 340 | func (t *txn) hkStandDownClaims(person string) error { |
| 341 | var rows []hkRecord |
| 342 | if err := t.db.Where("person = ? AND state = ?", person, wire.ActionClaimed).Find(&rows).Error; err != nil { |
| 343 | return err |
| 344 | } |
| 345 | for i := range rows { |
| 346 | if rows[i].Attempt == "" { |
| 347 | rows[i].State, rows[i].Reason, rows[i].ClaimedAt = wire.ActionHeld, "", nil |
| 348 | rows[i].ReservedTurns, rows[i].ReservedTokens, rows[i].ReservedRetries = 0, 0, 0 |
| 349 | } else { |
| 350 | rows[i].Releasing = true |
| 351 | } |
| 352 | if err := t.hkSave(&rows[i], false); err != nil { |
| 353 | return err |
| 354 | } |
| 355 | } |
| 356 | return nil |
| 357 | } |
| 358 | |
| 359 | // SetDetector switches a detector on or off for the person; switching it |
| 360 | // back on clears its failure count. |
| 361 | func (s *Store) SetDetector(ctx context.Context, person, id string, in wire.SetDetector) (out wire.Housekeeping, err error) { |
| 362 | if _, ok := s.registry().Get(id); !ok { |
| 363 | return out, ErrNotFound |
| 364 | } |
| 365 | err = s.tx(ctx, func(t *txn) error { |
| 366 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 367 | return err |
| 368 | } |
| 369 | set, err := t.hkSettings(person) |
| 370 | if err != nil { |
| 371 | return err |
| 372 | } |
| 373 | if in.Revision != set.Revision { |
| 374 | return ErrRevision |
| 375 | } |
| 376 | d := set.disabled[id] |
| 377 | if d.Off == in.Enabled { |
| 378 | now := t.hkNow() |
| 379 | if in.Enabled { |
| 380 | d = hkDisabled{Since: now} |
| 381 | } else { |
| 382 | d = hkDisabled{Off: true, Reason: "person", At: now, Since: d.Since, Told: true} |
| 383 | } |
| 384 | set.disabled[id] = d |
| 385 | if err := t.saveSettings(&set); err != nil { |
| 386 | return err |
| 387 | } |
| 388 | } |
| 389 | out, err = t.housekeepingView(person) |
| 390 | return err |
| 391 | }) |
| 392 | return out, err |
| 393 | } |
| 394 | |
| 395 | // --- Recovery, the sweep and the digest. |
| 396 | |
| 397 | // RecoverHousekeeping revalidates claims at start-up (stale says only |
| 398 | // those older than ClaimStale, for the periodic tick): a claim whose |
| 399 | // subject is unchanged and that dispatched nothing is released to held |
| 400 | // and found afresh; one dispatched waits for the runner's sync; one whose |
| 401 | // subject moved expires and its reservation is released. A row never |
| 402 | // silently stays claimed. |
| 403 | func (s *Store) RecoverHousekeeping(ctx context.Context, stale bool) (released, expired int, err error) { |
| 404 | err = s.tx(ctx, func(t *txn) error { |
| 405 | q := t.db.Where("state = ?", wire.ActionClaimed) |
| 406 | if stale { |
| 407 | q = q.Where("claimed_at < ?", t.hkNow().Add(-housekeeping.ClaimStale)) |
| 408 | } |
| 409 | var rows []hkRecord |
| 410 | if err := q.Find(&rows).Error; err != nil { |
| 411 | return err |
| 412 | } |
| 413 | for i := range rows { |
| 414 | r := &rows[i] |
| 415 | if r.Attempt != "" { |
| 416 | // The runner's sync settles a dispatched attempt. |
| 417 | continue |
| 418 | } |
| 419 | rev, err := t.subjectRevision(r.SubjectKind, r.SubjectID) |
| 420 | if err != nil { |
| 421 | return err |
| 422 | } |
| 423 | if rev == r.SubjectRevision { |
| 424 | r.State, r.Reason, r.ClaimedAt = wire.ActionHeld, "", nil |
| 425 | r.ReservedTurns, r.ReservedTokens, r.ReservedRetries = 0, 0, 0 |
| 426 | released++ |
| 427 | } else { |
| 428 | r.State, r.Reason = wire.ActionExpired, wire.ReasonSubjectMoved |
| 429 | // Nothing was dispatched: nothing to charge. |
| 430 | if err := t.hkSettle(r, &housekeeping.Cost{}, true, true); err != nil { |
| 431 | return err |
| 432 | } |
| 433 | expired++ |
| 434 | continue |
| 435 | } |
| 436 | if err := t.hkSave(r, false); err != nil { |
| 437 | return err |
| 438 | } |
| 439 | } |
| 440 | return nil |
| 441 | }) |
| 442 | return released, expired, err |
| 443 | } |
| 444 | |
| 445 | // subjectRevision reads a subject's revision now; -1 when it is gone. |
| 446 | func (t *txn) subjectRevision(kind, id string) (int64, error) { |
| 447 | if kind != housekeeping.SubjectTask { |
| 448 | return -1, nil |
| 449 | } |
| 450 | var revs []int64 |
| 451 | if err := t.db.Model(&taskRecord{}).Where("id = ?", id).Pluck("revision", &revs).Error; err != nil { |
| 452 | return 0, err |
| 453 | } |
| 454 | if len(revs) == 0 { |
| 455 | return -1, nil |
| 456 | } |
| 457 | return revs[0], nil |
| 458 | } |
| 459 | |
| 460 | // HousekeepingTick is the loop's minute: receipts whose quiet hours ended |
| 461 | // show; a job's preview that expired is offered no more; a legacy |
| 462 | // hand-off's mirrored question that needs no answer now is resolved; |
| 463 | // stale claims |
| 464 | // are revalidated; the daily sweep runs once per day at 03:00 and held |
| 465 | // findings are looked at again; each person gets their digest once a |
| 466 | // day from 08:00 when something happened. |
| 467 | func (s *Store) HousekeepingTick(ctx context.Context) error { |
| 468 | if err := s.tx(ctx, func(t *txn) error { return t.hkRelease("", t.hkNow()) }); err != nil { |
| 469 | return err |
| 470 | } |
| 471 | if err := s.tx(ctx, func(t *txn) error { return t.expirePreviews() }); err != nil { |
| 472 | return err |
| 473 | } |
| 474 | // A paused job's words follow the clock, the zone and a runner that |
| 475 | // went offline. |
| 476 | s.refreshJobs(ctx) |
| 477 | // A legacy hand-off's mirrored question nobody will answer now. |
| 478 | if err := s.tx(ctx, func(t *txn) error { return t.settleStaleLegacyQuestions() }); err != nil { |
| 479 | return err |
| 480 | } |
| 481 | // A go-ahead whose work landed, still worded as a question. |
| 482 | if err := s.tx(ctx, func(t *txn) error { return t.closeLandedOutcomes() }); err != nil { |
| 483 | return err |
| 484 | } |
| 485 | if _, _, err := s.RecoverHousekeeping(ctx, true); err != nil { |
| 486 | return err |
| 487 | } |
| 488 | // Needs-you triage held for today's budget: claimed again once there |
| 489 | // is room, if the task is still exactly where it was. |
| 490 | if _, err := s.Retriage(ctx, true); err != nil { |
| 491 | return err |
| 492 | } |
| 493 | // And tasks with no progress for a while: carried through to the end. |
| 494 | if _, err := s.SweepStalled(ctx); err != nil { |
| 495 | return err |
| 496 | } |
| 497 | sweep, err := s.sweepDue(ctx) |
| 498 | if err != nil { |
| 499 | return err |
| 500 | } |
| 501 | if sweep { |
| 502 | if _, err := s.TidyDuplicates(ctx); err != nil { |
| 503 | return err |
| 504 | } |
| 505 | } |
| 506 | var people []string |
| 507 | err = s.tx(ctx, func(t *txn) error { |
| 508 | var err error |
| 509 | if people, err = t.members(); err != nil { |
| 510 | return err |
| 511 | } |
| 512 | for _, p := range people { |
| 513 | if err := t.digest(p); err != nil { |
| 514 | return err |
| 515 | } |
| 516 | } |
| 517 | return nil |
| 518 | }) |
| 519 | if err != nil { |
| 520 | return err |
| 521 | } |
| 522 | // Advice looks again each minute (connectors spec §9: on fact changes |
| 523 | // and at 08:00), each person in their own transaction. |
| 524 | var first error |
| 525 | for _, p := range people { |
| 526 | if err := s.RefreshAdvice(ctx, p); err != nil && first == nil { |
| 527 | first = err |
| 528 | } |
| 529 | } |
| 530 | return first |
| 531 | } |
| 532 | |
| 533 | // sweepDue marks today's sweep as run when it is due (03:00 or later and |
| 534 | // not yet run today), or when held findings wait for a person who is not |
| 535 | // paused. |
| 536 | func (s *Store) sweepDue(ctx context.Context) (due bool, err error) { |
| 537 | err = s.tx(ctx, func(t *txn) error { |
| 538 | people, err := t.members() |
| 539 | if err != nil { |
| 540 | return err |
| 541 | } |
| 542 | now := t.hkNow() |
| 543 | for _, p := range people { |
| 544 | set, err := t.hkSettings(p) |
| 545 | if err != nil { |
| 546 | return err |
| 547 | } |
| 548 | if set.Paused { |
| 549 | continue |
| 550 | } |
| 551 | loc := t.zone(p) |
| 552 | at := housekeeping.AtHour(now, loc, housekeeping.SweepHour) |
| 553 | if !now.Before(at) && (set.LastSweepAt == nil || set.LastSweepAt.Before(at)) { |
| 554 | set.LastSweepAt = &now |
| 555 | if err := t.saveSettings(&set); err != nil { |
| 556 | return err |
| 557 | } |
| 558 | due = true |
| 559 | } |
| 560 | var held int64 |
| 561 | if err := t.db.Model(&hkRecord{}).Where("person = ? AND state = ?", p, wire.ActionHeld).Count(&held).Error; err != nil { |
| 562 | return err |
| 563 | } |
| 564 | due = due || held > 0 |
| 565 | } |
| 566 | return nil |
| 567 | }) |
| 568 | return due, err |
| 569 | } |
| 570 | |
| 571 | // digest writes the person's one line a day, from the end of their quiet |
| 572 | // hours, when something happened since the last: what was tidied, a |
| 573 | // detector switched off, a stand-down. Never while paused; one due inside |
| 574 | // quiet hours waits for their end, as receipts do. |
| 575 | func (t *txn) digest(person string) error { |
| 576 | set, err := t.hkSettings(person) |
| 577 | if err != nil || set.Paused { |
| 578 | return err |
| 579 | } |
| 580 | now := t.hkNow() |
| 581 | loc := t.zone(person) |
| 582 | from := housekeeping.AtHour(now, loc, set.quiet().Morning()) |
| 583 | if now.Before(from) || set.LastDigestAt != nil && !set.LastDigestAt.Before(from) { |
| 584 | return nil |
| 585 | } |
| 586 | // The first digest covers everything so far. |
| 587 | since := time.Time{} |
| 588 | if set.LastDigestAt != nil { |
| 589 | since = *set.LastDigestAt |
| 590 | } |
| 591 | var tidied int64 |
| 592 | if err := t.db.Model(&hkRecord{}).Where("person = ? AND class = ? AND state IN ? AND claimed_at >= ?", person, housekeeping.ClassAct, []string{wire.ActionDone, wire.ActionUndone}, since).Count(&tidied).Error; err != nil { |
| 593 | return err |
| 594 | } |
| 595 | var parts []string |
| 596 | switch { |
| 597 | case tidied == 1: |
| 598 | parts = append(parts, t.words("chat.housekeeping.digest_one")) |
| 599 | case tidied > 1: |
| 600 | parts = append(parts, t.words("chat.housekeeping.digest", tidied)) |
| 601 | } |
| 602 | for _, id := range sortedKeys(set.disabled) { |
| 603 | d := set.disabled[id] |
| 604 | if d.Off && !d.Told { |
| 605 | parts = append(parts, t.words("chat.housekeeping.digest_disabled", t.words("chat.housekeeping.detector."+id))) |
| 606 | d.Told = true |
| 607 | set.disabled[id] = d |
| 608 | } |
| 609 | } |
| 610 | var stood []string |
| 611 | if err := t.db.Model(&hkRecord{}).Where("person = ? AND state = ? AND reason IN ? AND at >= ?", person, wire.ActionHeld, []string{wire.ReasonHeldBudget, wire.ReasonHeldStandDown}, since).Distinct().Pluck("reason", &stood).Error; err != nil { |
| 612 | return err |
| 613 | } |
| 614 | if slices.Contains(stood, wire.ReasonHeldBudget) { |
| 615 | parts = append(parts, t.words("chat.housekeeping.stood_down_budget")) |
| 616 | } else if slices.Contains(stood, wire.ReasonHeldStandDown) { |
| 617 | parts = append(parts, t.words("chat.housekeeping.stood_down_limit")) |
| 618 | } |
| 619 | // Nothing to say keeps the day's digest for later. |
| 620 | if len(parts) == 0 { |
| 621 | return nil |
| 622 | } |
| 623 | set.LastDigestAt = &now |
| 624 | if err := t.saveSettings(&set); err != nil { |
| 625 | return err |
| 626 | } |
| 627 | // Scheduled as receipts are: in quiet hours it waits for their end. |
| 628 | visible, held := &now, false |
| 629 | if at := set.quiet().VisibleAt(now, loc); at != nil { |
| 630 | visible, held = at, true |
| 631 | } |
| 632 | c := cardRecord{ID: newID("c_"), Person: person, Kind: wire.CardHousekeeping, State: wire.CardDigest, Question: strings.Join(parts, " "), Options: "[]", Revision: 1, CreatedAt: now, UpdatedAt: now, VisibleAt: visible, Held: held} |
| 633 | if err := t.db.Create(&c).Error; err != nil { |
| 634 | return err |
| 635 | } |
| 636 | return t.cardEvent(c) |
| 637 | } |
| 638 | |
| 639 | func sortedKeys[V any](m map[string]V) []string { |
| 640 | out := make([]string, 0, len(m)) |
| 641 | for k := range m { |
| 642 | out = append(out, k) |
| 643 | } |
| 644 | slices.Sort(out) |
| 645 | return out |
| 646 | } |
| 647 | |
| 648 | // --- Undo from the view. |
| 649 | |
| 650 | // UndoAction is Undo on a housekeeping action, its person's only: the |
| 651 | // combine's Undo (uncombine), the same path as the receipt's and the task |
| 652 | // page's. When it can no longer apply, ErrActionConflict with the action |
| 653 | // as it is now. |
| 654 | func (s *Store) UndoAction(ctx context.Context, person, id string) (out wire.HousekeepingAction, err error) { |
| 655 | err = s.tx(ctx, func(t *txn) error { |
| 656 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 657 | return err |
| 658 | } |
| 659 | var r hkRecord |
| 660 | if err := t.db.Where("id = ? AND person = ?", id, person).First(&r).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 661 | return ErrNotFound |
| 662 | } else if err != nil { |
| 663 | return err |
| 664 | } |
| 665 | var res hkResult |
| 666 | _ = json.Unmarshal([]byte(r.Result), &res) |
| 667 | if !t.undoable(r) || res.Action != housekeeping.ActionCombine { |
| 668 | out, err = t.actionView(r) |
| 669 | if err != nil { |
| 670 | return err |
| 671 | } |
| 672 | return ErrActionConflict |
| 673 | } |
| 674 | k, err := t.loadTask(res.Task) |
| 675 | if err != nil { |
| 676 | return err |
| 677 | } |
| 678 | if k.FoldedInto != res.Into { |
| 679 | out, _ = t.actionView(r) |
| 680 | return ErrActionConflict |
| 681 | } |
| 682 | if _, err := t.unfold(person, k); err != nil { |
| 683 | if errors.Is(err, ErrConflict) || errors.Is(err, ErrActionConflict) { |
| 684 | out, _ = t.actionView(r) |
| 685 | return ErrActionConflict |
| 686 | } |
| 687 | return err |
| 688 | } |
| 689 | if err := t.db.Where("id = ?", r.ID).First(&r).Error; err != nil { |
| 690 | return err |
| 691 | } |
| 692 | out, err = t.actionView(r) |
| 693 | return err |
| 694 | }) |
| 695 | return out, err |
| 696 | } |
| 697 | |
| 698 | func (t *txn) undoable(r hkRecord) bool { |
| 699 | return r.State == wire.ActionDone && r.Class == housekeeping.ClassAct && r.UndoUntil != nil && t.hkNow().Before(*r.UndoUntil) |
| 700 | } |
| 701 | |
| 702 | // --- Views. |
| 703 | |
| 704 | func (t *txn) actionView(r hkRecord) (wire.HousekeepingAction, error) { |
| 705 | v := wire.HousekeepingAction{ID: r.ID, Revision: r.Revision, Detector: r.Detector, Class: r.Class, State: r.State, Reason: r.Reason, Subject: wire.HousekeepingSubject{Kind: r.SubjectKind, ID: r.SubjectID}, Evidence: wire.HousekeepingEvidence{Tasks: []wire.TaskRef{}}, UndoUntil: r.UndoUntil, VisibleAt: r.VisibleAt, At: r.At, UndoneAt: r.UndoneAt} |
| 706 | var ev housekeeping.Evidence |
| 707 | if r.Evidence != "" { |
| 708 | if err := json.Unmarshal([]byte(r.Evidence), &ev); err != nil { |
| 709 | return v, err |
| 710 | } |
| 711 | } |
| 712 | v.Evidence.Similarity, v.Evidence.Shared = ev.Similarity, ev.Shared |
| 713 | for _, k := range ev.Tasks { |
| 714 | ref := wire.TaskRef{ID: k.ID, Title: k.Title, Creator: k.Creator} |
| 715 | var stages []string |
| 716 | if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Pluck("stage", &stages).Error; err != nil { |
| 717 | return v, err |
| 718 | } |
| 719 | if len(stages) > 0 { |
| 720 | ref.Stage = stages[0] |
| 721 | } |
| 722 | v.Evidence.Tasks = append(v.Evidence.Tasks, ref) |
| 723 | } |
| 724 | if t.undoable(r) { |
| 725 | var res hkResult |
| 726 | if json.Unmarshal([]byte(r.Result), &res) == nil && res.Action == housekeeping.ActionCombine { |
| 727 | var folded []string |
| 728 | if err := t.db.Model(&taskRecord{}).Where("id = ?", res.Task).Pluck("folded_into", &folded).Error; err != nil { |
| 729 | return v, err |
| 730 | } |
| 731 | v.Undoable = len(folded) == 1 && folded[0] == res.Into |
| 732 | } |
| 733 | } |
| 734 | return v, nil |
| 735 | } |
| 736 | |
| 737 | // housekeepingView is GET /api/v1/housekeeping for the person. |
| 738 | func (t *txn) housekeepingView(person string) (wire.Housekeeping, error) { |
| 739 | set, err := t.hkSettings(person) |
| 740 | if err != nil { |
| 741 | return wire.Housekeeping{}, err |
| 742 | } |
| 743 | q := set.quiet() |
| 744 | out := wire.Housekeeping{Paused: set.Paused, Quiet: wire.QuietHours{From: q.From, Until: q.Until}, Revision: set.Revision, Detectors: []wire.HousekeepingDetector{}, Actions: []wire.HousekeepingAction{}, Refusals: []wire.HousekeepingAction{}} |
| 745 | day := housekeeping.DayStart(t.hkNow(), t.zone(person)) |
| 746 | used, charged, err := t.hkUsed(person, day) |
| 747 | if err != nil { |
| 748 | return out, err |
| 749 | } |
| 750 | l := housekeeping.Limits |
| 751 | // Reserved is what is held and not yet charged. |
| 752 | out.Budget = wire.HousekeepingBudget{ |
| 753 | Turns: wire.BudgetMeter{Reserved: used.Turns - charged.Turns, Charged: charged.Turns, Limit: l.Turns}, |
| 754 | Tokens: wire.BudgetMeter{Reserved: used.Tokens - charged.Tokens, Charged: charged.Tokens, Limit: l.Tokens}, |
| 755 | Retries: wire.BudgetMeter{Reserved: used.Retries - charged.Retries, Charged: charged.Retries, Limit: l.Retries}, |
| 756 | } |
| 757 | for _, d := range t.s.registry().Detectors() { |
| 758 | off := set.disabled[d.ID] |
| 759 | v := wire.HousekeepingDetector{ID: d.ID, Class: d.Class, Enabled: !off.Off} |
| 760 | if off.Off { |
| 761 | at := off.At |
| 762 | v.DisabledReason, v.DisabledAt = off.Reason, &at |
| 763 | } |
| 764 | out.Detectors = append(out.Detectors, v) |
| 765 | } |
| 766 | var acts []hkRecord |
| 767 | if err := t.db.Where("person = ? AND class IN ? AND state IN ?", person, []string{housekeeping.ClassAct, classTriage}, []string{wire.ActionDone, wire.ActionUndone, wire.ActionHeld, wire.ActionClaimed}).Order("at DESC, id DESC").Limit(50).Find(&acts).Error; err != nil { |
| 768 | return out, err |
| 769 | } |
| 770 | for _, r := range acts { |
| 771 | v, err := t.actionView(r) |
| 772 | if err != nil { |
| 773 | return out, err |
| 774 | } |
| 775 | out.Actions = append(out.Actions, v) |
| 776 | } |
| 777 | var refused []hkRecord |
| 778 | if err := t.db.Where("person = ? AND state IN ?", person, []string{wire.ActionRefused, wire.ActionFailed}).Order("at DESC, id DESC").Limit(20).Find(&refused).Error; err != nil { |
| 779 | return out, err |
| 780 | } |
| 781 | for _, r := range refused { |
| 782 | v, err := t.actionView(r) |
| 783 | if err != nil { |
| 784 | return out, err |
| 785 | } |
| 786 | out.Refusals = append(out.Refusals, v) |
| 787 | } |
| 788 | return out, nil |
| 789 | } |
| 790 | |
| 791 | // Housekeeping is GET /api/v1/housekeeping. |
| 792 | func (s *Store) Housekeeping(ctx context.Context, person string) (out wire.Housekeeping, err error) { |
| 793 | err = s.read(ctx, func(tx *gorm.DB) error { |
| 794 | if err := s.authority.CurrentPerson(ctx, tx); err != nil { |
| 795 | return err |
| 796 | } |
| 797 | out, err = (&txn{s: s, db: tx}).housekeepingView(person) |
| 798 | return err |
| 799 | }) |
| 800 | return out, err |
| 801 | } |
| 802 | |
| 803 | // HousekeepingActions pages the person's actions newest first, before |
| 804 | // the action id given. |
| 805 | func (s *Store) HousekeepingActions(ctx context.Context, person, before string, limit int) (out wire.HousekeepingActions, err error) { |
| 806 | if limit <= 0 || limit > 100 { |
| 807 | limit = 50 |
| 808 | } |
| 809 | err = s.read(ctx, func(tx *gorm.DB) error { |
| 810 | if err := s.authority.CurrentPerson(ctx, tx); err != nil { |
| 811 | return err |
| 812 | } |
| 813 | t := &txn{s: s, db: tx} |
| 814 | q := tx.Where("person = ?", person) |
| 815 | if before != "" { |
| 816 | var b hkRecord |
| 817 | if err := tx.Where("id = ? AND person = ?", before, person).First(&b).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 818 | return ErrInvalid |
| 819 | } else if err != nil { |
| 820 | return err |
| 821 | } |
| 822 | q = q.Where("at < ? OR (at = ? AND id < ?)", b.At, b.At, b.ID) |
| 823 | } |
| 824 | var rows []hkRecord |
| 825 | if err := q.Order("at DESC, id DESC").Limit(limit + 1).Find(&rows).Error; err != nil { |
| 826 | return err |
| 827 | } |
| 828 | more := len(rows) > limit |
| 829 | if more { |
| 830 | rows = rows[:limit] |
| 831 | } |
| 832 | out.Items = []wire.HousekeepingAction{} |
| 833 | for _, r := range rows { |
| 834 | v, err := t.actionView(r) |
| 835 | if err != nil { |
| 836 | return err |
| 837 | } |
| 838 | out.Items = append(out.Items, v) |
| 839 | } |
| 840 | if more { |
| 841 | out.Before = rows[len(rows)-1].ID |
| 842 | } |
| 843 | return nil |
| 844 | }) |
| 845 | return out, err |
| 846 | } |
| 847 | |