325 lines
13 KiB
Go
325 lines
13 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
const TaskFocusEventType = "task.focus.complete"
|
|
|
|
type TaskFocus struct {
|
|
UUID string `json:"uuid"`
|
|
TaskUUID string `json:"task_uuid"`
|
|
Phase string `json:"phase"`
|
|
State string `json:"state"`
|
|
DurationMS int64 `json:"duration_ms"`
|
|
RemainingMS int64 `json:"remaining_ms"`
|
|
DeadlineMS int64 `json:"deadline_ms"`
|
|
CreatedMS int64 `json:"created_at_ms"`
|
|
UpdatedMS int64 `json:"updated_at_ms"`
|
|
Version int64 `json:"version"`
|
|
}
|
|
|
|
func (s *Store) ensureTaskFocusSchema() error {
|
|
if s.sqlBackend == storePostgreSQL {
|
|
return s.ensurePostgreSQLTaskProductivity(context.Background())
|
|
}
|
|
_, err := s.DB.Exec(`CREATE TABLE IF NOT EXISTS organizer_focus(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,uuid TEXT PRIMARY KEY,task_uuid TEXT NOT NULL,phase TEXT NOT NULL,state TEXT NOT NULL,duration_ms INTEGER NOT NULL,remaining_ms INTEGER NOT NULL,deadline_ms INTEGER NOT NULL,created_at_ms INTEGER NOT NULL,updated_at_ms INTEGER NOT NULL,version INTEGER NOT NULL);
|
|
CREATE UNIQUE INDEX IF NOT EXISTS organizer_focus_active ON organizer_focus(owner_uuid) WHERE state IN ('running','paused');
|
|
CREATE INDEX IF NOT EXISTS organizer_focus_due ON organizer_focus(state,deadline_ms,uuid);
|
|
CREATE INDEX IF NOT EXISTS organizer_focus_owner ON organizer_focus(domain_uuid,owner_uuid,created_at_ms DESC,uuid DESC);
|
|
CREATE TABLE IF NOT EXISTS organizer_focus_changes(session_uuid TEXT NOT NULL,version INTEGER NOT NULL,action TEXT NOT NULL,created_at_ms INTEGER NOT NULL,data TEXT NOT NULL,PRIMARY KEY(session_uuid,version))`)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return s.ensureTaskFocusSpans()
|
|
}
|
|
|
|
const focusColumns = `uuid,task_uuid,phase,state,duration_ms,remaining_ms,deadline_ms,created_at_ms,updated_at_ms,version`
|
|
|
|
func scanFocus(row interface{ Scan(...any) error }) (TaskFocus, error) {
|
|
var f TaskFocus
|
|
err := row.Scan(&f.UUID, &f.TaskUUID, &f.Phase, &f.State, &f.DurationMS, &f.RemainingMS, &f.DeadlineMS, &f.CreatedMS, &f.UpdatedMS, &f.Version)
|
|
return f, err
|
|
}
|
|
|
|
func (s *Store) LatestTaskFocus(ctx context.Context, domain, actor string) (result0 *TaskFocus, resultErr error) {
|
|
defer func() { resultErr = s.sqlError("organizer repository", resultErr) }()
|
|
if err := s.taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
|
return nil, err
|
|
}
|
|
f, err := scanFocus(s.DB.QueryRowContext(ctx, `SELECT `+focusColumns+` FROM organizer_focus WHERE domain_uuid=`+s.sqlParam(1)+` AND owner_uuid=`+s.sqlParam(2)+` AND state IN ('running','paused')`, domain, actor))
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
f, err = scanFocus(s.DB.QueryRowContext(ctx, `SELECT `+focusColumns+` FROM organizer_focus WHERE domain_uuid=`+s.sqlParam(1)+` AND owner_uuid=`+s.sqlParam(2)+` ORDER BY created_at_ms DESC,uuid DESC LIMIT 1`, domain, actor))
|
|
}
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &f, nil
|
|
}
|
|
|
|
func (s *Store) recordFocusTx(ctx context.Context, tx *sql.Tx, f TaskFocus, action string) error {
|
|
if err := s.recordFocusSpanTx(ctx, tx, f); err != nil {
|
|
return err
|
|
}
|
|
data, err := json.Marshal(f)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_focus_changes(session_uuid,version,action,created_at_ms,data) VALUES(`+s.sqlParam(1)+`,`+s.sqlParam(2)+`,`+s.sqlParam(3)+`,`+s.sqlParam(4)+`,`+s.sqlParam(5)+`)`, f.UUID, f.Version, action, f.UpdatedMS, string(data))
|
|
return err
|
|
}
|
|
|
|
// ChangeTaskFocus serializes transitions, including cross-Domain starts, under
|
|
// the backend's writer lock. The partial unique index is a second line of defense.
|
|
// The supplied time is server-controlled (also allows deterministic tests).
|
|
func (s *Store) ChangeTaskFocus(ctx context.Context, domain, actor, action string, f TaskFocus, expected int64, now time.Time) (result0 TaskFocus, resultErr error) {
|
|
defer func() { resultErr = s.sqlError("organizer repository", resultErr) }()
|
|
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
defer cancel()
|
|
if _, err := uuid.Parse(f.UUID); err != nil {
|
|
return f, ErrTaskInvalid
|
|
}
|
|
tx, err := s.DB.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return f, err
|
|
}
|
|
defer tx.Rollback()
|
|
if err = s.lockTaskWriter(ctx, tx); err != nil {
|
|
return f, err
|
|
}
|
|
if _, err = tx.ExecContext(ctx, `UPDATE domain_memberships SET state=state WHERE domain_uuid=`+s.sqlParam(1)+` AND principal_uuid=`+s.sqlParam(2)+``, domain, actor); err != nil {
|
|
return f, err
|
|
}
|
|
if err = s.taskActor(ctx, tx, domain, actor, true); err != nil {
|
|
return f, err
|
|
}
|
|
enabled, err := s.taskReminderExtensionEnabled(ctx, tx, domain)
|
|
if err != nil {
|
|
return f, err
|
|
}
|
|
if !enabled {
|
|
return f, ErrAccessDenied
|
|
}
|
|
old, err := scanFocus(tx.QueryRowContext(ctx, `SELECT `+focusColumns+` FROM organizer_focus WHERE domain_uuid=`+s.sqlParam(1)+` AND owner_uuid=`+s.sqlParam(2)+` AND uuid=`+s.sqlParam(3)+``, domain, actor, f.UUID))
|
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
|
return f, err
|
|
}
|
|
ms := now.UnixMilli()
|
|
if action == "start" {
|
|
if f.Phase != "focus" && f.Phase != "break" || f.DurationMS < 60000 || f.DurationMS > 180*60000 || f.DurationMS%60000 != 0 || expected != 0 {
|
|
return f, ErrTaskInvalid
|
|
}
|
|
if err == nil {
|
|
if old.TaskUUID != f.TaskUUID || old.Phase != f.Phase || old.DurationMS != f.DurationMS {
|
|
return f, ErrTaskConflict
|
|
}
|
|
return old, tx.Commit()
|
|
}
|
|
if f.TaskUUID != "" {
|
|
var exists bool
|
|
if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM organizer_items WHERE domain_uuid=`+s.sqlParam(1)+` AND owner_uuid=`+s.sqlParam(2)+` AND uuid=`+s.sqlParam(3)+` AND kind='task' AND archived=0 AND status NOT IN ('done','cancelled'))`, domain, actor, f.TaskUUID).Scan(&exists); err != nil {
|
|
return f, err
|
|
}
|
|
if !exists {
|
|
return f, sql.ErrNoRows
|
|
}
|
|
}
|
|
var otherDomain, otherID string
|
|
err = tx.QueryRowContext(ctx, `SELECT domain_uuid,uuid FROM organizer_focus WHERE owner_uuid=`+s.sqlParam(1)+` AND state IN ('running','paused')`, actor).Scan(&otherDomain, &otherID)
|
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
|
return f, err
|
|
}
|
|
if err == nil {
|
|
allowed := s.taskActor(ctx, tx, otherDomain, actor, false)
|
|
if allowed != nil && !errors.Is(allowed, ErrAccessDenied) {
|
|
return f, allowed
|
|
}
|
|
on, e := s.taskReminderExtensionEnabled(ctx, tx, otherDomain)
|
|
if e != nil {
|
|
return f, e
|
|
}
|
|
if allowed == nil && on {
|
|
return f, ErrTaskConflict
|
|
}
|
|
// A timer stranded in a revoked/disabled Domain must not lock the
|
|
// user out forever. Release only their timer, never another task.
|
|
stale, e := scanFocus(tx.QueryRowContext(ctx, `SELECT `+focusColumns+` FROM organizer_focus WHERE uuid=`+s.sqlParam(1)+``, otherID))
|
|
if e != nil {
|
|
return f, e
|
|
}
|
|
if stale.State == "running" {
|
|
stale.RemainingMS = max(0, min(stale.RemainingMS, stale.DeadlineMS-ms))
|
|
}
|
|
stale.State = "cancelled"
|
|
stale.DeadlineMS = 0
|
|
stale.UpdatedMS = ms
|
|
stale.Version++
|
|
if _, e = tx.ExecContext(ctx, `UPDATE organizer_focus SET state='cancelled',deadline_ms=0,remaining_ms=`+s.sqlParam(1)+`,updated_at_ms=`+s.sqlParam(2)+`,version=`+s.sqlParam(3)+` WHERE uuid=`+s.sqlParam(4)+``, stale.RemainingMS, ms, stale.Version, stale.UUID); e != nil {
|
|
return f, e
|
|
}
|
|
if e = s.recordFocusTx(ctx, tx, stale, "revoked"); e != nil {
|
|
return f, e
|
|
}
|
|
}
|
|
f.State = "running"
|
|
f.RemainingMS = f.DurationMS
|
|
f.DeadlineMS = ms + f.DurationMS
|
|
f.CreatedMS = ms
|
|
f.UpdatedMS = ms
|
|
f.Version = 1
|
|
res, e := tx.ExecContext(ctx, `INSERT INTO organizer_focus(domain_uuid,owner_uuid,uuid,task_uuid,phase,state,duration_ms,remaining_ms,deadline_ms,created_at_ms,updated_at_ms,version) VALUES(`+s.sqlParam(1)+`,`+s.sqlParam(2)+`,`+s.sqlParam(3)+`,`+s.sqlParam(4)+`,`+s.sqlParam(5)+`,`+s.sqlParam(6)+`,`+s.sqlParam(7)+`,`+s.sqlParam(8)+`,`+s.sqlParam(9)+`,`+s.sqlParam(10)+`,`+s.sqlParam(11)+`,`+s.sqlParam(12)+`) ON CONFLICT DO NOTHING`, domain, actor, f.UUID, f.TaskUUID, f.Phase, f.State, f.DurationMS, f.RemainingMS, f.DeadlineMS, f.CreatedMS, f.UpdatedMS, f.Version)
|
|
if e != nil {
|
|
return f, e
|
|
}
|
|
if n, _ := res.RowsAffected(); n != 1 {
|
|
return f, ErrTaskConflict
|
|
}
|
|
} else {
|
|
if err != nil {
|
|
return f, err
|
|
}
|
|
f = old
|
|
if f.Version != expected {
|
|
return f, ErrTaskConflict
|
|
}
|
|
if f.State != "running" && f.State != "paused" {
|
|
return f, ErrTaskConflict
|
|
}
|
|
if f.State == "running" {
|
|
f.RemainingMS = max(0, min(f.RemainingMS, f.DeadlineMS-ms))
|
|
}
|
|
switch action {
|
|
case "pause":
|
|
if f.State != "running" || f.RemainingMS == 0 {
|
|
return f, ErrTaskConflict
|
|
}
|
|
f.State = "paused"
|
|
f.DeadlineMS = 0
|
|
case "resume":
|
|
if f.State != "paused" {
|
|
return f, ErrTaskConflict
|
|
}
|
|
f.State = "running"
|
|
f.DeadlineMS = ms + f.RemainingMS
|
|
case "complete":
|
|
f.State = "completed"
|
|
f.DeadlineMS = 0
|
|
case "cancel":
|
|
f.State = "cancelled"
|
|
f.DeadlineMS = 0
|
|
default:
|
|
return f, ErrTaskInvalid
|
|
}
|
|
f.Version++
|
|
f.UpdatedMS = ms
|
|
if _, err = tx.ExecContext(ctx, `UPDATE organizer_focus SET state=`+s.sqlParam(1)+`,remaining_ms=`+s.sqlParam(2)+`,deadline_ms=`+s.sqlParam(3)+`,updated_at_ms=`+s.sqlParam(4)+`,version=`+s.sqlParam(5)+` WHERE uuid=`+s.sqlParam(6)+``, f.State, f.RemainingMS, f.DeadlineMS, f.UpdatedMS, f.Version, f.UUID); err != nil {
|
|
return f, err
|
|
}
|
|
}
|
|
if err = s.recordFocusTx(ctx, tx, f, action); err != nil {
|
|
return f, err
|
|
}
|
|
return f, tx.Commit()
|
|
}
|
|
|
|
// A bounded, indexed sweep completes timers even while all browsers are closed.
|
|
// Completing a timer never changes a task's status, due date or planned date.
|
|
func (s *Store) CompleteTaskFocus(ctx context.Context, now time.Time, limit int) (result0 int, resultErr error) {
|
|
defer func() { resultErr = s.sqlError("organizer repository", resultErr) }()
|
|
if limit < 1 || limit > 100 {
|
|
limit = 100
|
|
}
|
|
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
|
defer cancel()
|
|
tx, err := s.DB.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
defer tx.Rollback()
|
|
if err = s.lockTaskWriter(ctx, tx); err != nil {
|
|
return 0, err
|
|
}
|
|
if _, err = tx.ExecContext(ctx, `UPDATE organizer_focus SET state=state WHERE uuid=''`); err != nil {
|
|
return 0, err
|
|
}
|
|
rows, err := tx.QueryContext(ctx, `SELECT domain_uuid,owner_uuid,uuid FROM organizer_focus WHERE state='running' AND deadline_ms<=`+s.sqlParam(1)+` ORDER BY deadline_ms,uuid LIMIT `+s.sqlParam(2)+``, now.UnixMilli(), limit)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
type entry struct{ domain, owner, id string }
|
|
items := []entry{}
|
|
for rows.Next() {
|
|
var e entry
|
|
if err = rows.Scan(&e.domain, &e.owner, &e.id); err != nil {
|
|
rows.Close()
|
|
return 0, err
|
|
}
|
|
items = append(items, e)
|
|
}
|
|
err = rows.Err()
|
|
rows.Close()
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
for _, e := range items {
|
|
f, err := scanFocus(tx.QueryRowContext(ctx, `SELECT `+focusColumns+` FROM organizer_focus WHERE uuid=`+s.sqlParam(1)+``, e.id))
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
enabled, err := s.taskReminderExtensionEnabled(ctx, tx, e.domain)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
auth := s.taskActor(ctx, tx, e.domain, e.owner, false)
|
|
if auth != nil && !errors.Is(auth, ErrAccessDenied) {
|
|
return 0, auth
|
|
}
|
|
// Stop unauthorized/disabled sessions without notification. Do not queue
|
|
// them indefinitely ahead of valid timers belonging to other users.
|
|
f.State = "completed"
|
|
action := "elapsed"
|
|
if !enabled || auth != nil {
|
|
f.State = "cancelled"
|
|
action = "revoked"
|
|
}
|
|
if enabled && auth == nil && now.UnixMilli()-f.DeadlineMS < 24*time.Hour.Milliseconds() {
|
|
_, _, err = s.CreateNotificationTx(tx, Notification{DomainUUID: e.domain, RecipientUUID: e.owner, EventUUID: f.UUID, Kind: TaskFocusEventType, RequestUUID: f.TaskUUID, Href: "/v/plan/today", Message: "Timer completed", CreatedAtMS: now.UnixMilli()})
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
}
|
|
f.RemainingMS = 0
|
|
f.DeadlineMS = 0
|
|
f.UpdatedMS = now.UnixMilli()
|
|
f.Version++
|
|
if _, err = tx.ExecContext(ctx, `UPDATE organizer_focus SET state=`+s.sqlParam(1)+`,remaining_ms=0,deadline_ms=0,updated_at_ms=`+s.sqlParam(2)+`,version=`+s.sqlParam(3)+` WHERE uuid=`+s.sqlParam(4)+``, f.State, f.UpdatedMS, f.Version, f.UUID); err != nil {
|
|
return 0, err
|
|
}
|
|
if err = s.recordFocusTx(ctx, tx, f, action); err != nil {
|
|
return 0, err
|
|
}
|
|
}
|
|
if err = tx.Commit(); err != nil {
|
|
return 0, err
|
|
}
|
|
return len(items), nil
|
|
}
|
|
|
|
func (s *Store) EnsureTaskFocusEvent() error {
|
|
if s.sqlBackend == storePostgreSQL {
|
|
return s.ensureNativeBuiltinEvent("builtin.task.focus", "Focus timer completion", TaskFocusEventType, 60, -2, 3)
|
|
}
|
|
now := time.Now().UnixMilli()
|
|
_, err := s.DB.Exec(`INSERT OR IGNORE INTO event_definitions(uuid,name,event_type,event_key,payload,schedule_kind,interval_seconds,next_run_at_ms,enabled,priority,max_attempts,created_at_ms,updated_at_ms) VALUES('builtin.task.focus','Focus timer completion',`+s.sqlParam(1)+`,'local','{}','interval',60,`+s.sqlParam(2)+`,1,-2,3,`+s.sqlParam(3)+`,`+s.sqlParam(4)+`)`, TaskFocusEventType, now, now, now)
|
|
return err
|
|
}
|