184 lines
8.6 KiB
Go
184 lines
8.6 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
const TaskReminderEventType = "task.reminders.deliver"
|
|
|
|
func (s *Store) ensureTaskReminderSchema() error {
|
|
for _, q := range []string{
|
|
`CREATE TABLE IF NOT EXISTS organizer_reminders(domain_uuid TEXT NOT NULL,item_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,kind TEXT NOT NULL,source_version INTEGER NOT NULL,fire_at_ms INTEGER NOT NULL,civil_date TEXT NOT NULL,timezone TEXT NOT NULL,notification_key TEXT NOT NULL,state TEXT NOT NULL,PRIMARY KEY(domain_uuid,item_uuid,kind))`,
|
|
`CREATE INDEX IF NOT EXISTS organizer_reminders_due ON organizer_reminders(state,fire_at_ms,domain_uuid,item_uuid,kind)`,
|
|
`CREATE INDEX IF NOT EXISTS organizer_reminders_notification ON organizer_reminders(domain_uuid,owner_uuid,notification_key)`,
|
|
} {
|
|
if _, err := s.DB.Exec(q); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Derived reservations are replaced in the source mutation transaction, not
|
|
// asynchronously from an old event: completion/date changes cannot race a
|
|
// delayed outbox consumer into resurrecting obsolete reminders.
|
|
func (s *Store) syncTaskRemindersTx(ctx context.Context, tx *sql.Tx, domain, actor string, item TaskRecord) error {
|
|
for _, kind := range []string{"due", "planned"} {
|
|
date, enabled := item.DueOn, item.NotifyDue
|
|
if kind == "planned" {
|
|
date, enabled = item.PlannedOn, item.NotifyPlanned
|
|
}
|
|
if item.Kind != "task" || !enabled || item.Archived || item.Status == "done" || item.Status == "cancelled" {
|
|
if _, err := tx.ExecContext(ctx, `DELETE FROM organizer_reminders WHERE domain_uuid=`+s.sqlParam(1)+` AND item_uuid=`+s.sqlParam(2)+` AND kind=`+s.sqlParam(3)+``, domain, item.UUID, kind); err != nil {
|
|
return err
|
|
}
|
|
continue
|
|
}
|
|
loc, err := time.LoadLocation(item.ReminderTimezone)
|
|
if err != nil {
|
|
return ErrTaskInvalid
|
|
}
|
|
stamp := date + " " + item.ReminderTime
|
|
fire, err := time.ParseInLocation("2006-01-02 15:04", stamp, loc)
|
|
if err != nil || fire.Format("2006-01-02 15:04") != stamp {
|
|
return ErrTaskInvalid
|
|
}
|
|
key := uuid.NewSHA1(uuid.NameSpaceOID, []byte(domain+":"+item.UUID+":"+kind+":"+stamp+":"+item.ReminderTimezone)).String()
|
|
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_reminders(domain_uuid,item_uuid,owner_uuid,kind,source_version,fire_at_ms,civil_date,timezone,notification_key,state) 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)+`,'pending') ON CONFLICT(domain_uuid,item_uuid,kind) DO UPDATE SET owner_uuid=excluded.owner_uuid,source_version=excluded.source_version,fire_at_ms=excluded.fire_at_ms,civil_date=excluded.civil_date,timezone=excluded.timezone,state=CASE WHEN organizer_reminders.notification_key=excluded.notification_key AND organizer_reminders.state='sent' THEN 'sent' ELSE 'pending' END,notification_key=excluded.notification_key`, domain, item.UUID, actor, kind, item.Version, fire.UnixMilli(), date, item.ReminderTimezone, key)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func taskReminderExtensionEnabled(ctx context.Context, tx *sql.Tx, domain string) (bool, error) {
|
|
var raw string
|
|
err := tx.QueryRowContext(ctx, `SELECT value FROM config WHERE domain_uuid=? AND key='system_extension_states'`, domain).Scan(&raw)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return true, nil
|
|
}
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
if raw == "" {
|
|
return true, nil
|
|
}
|
|
states := map[string]bool{}
|
|
if json.Unmarshal([]byte(raw), &states) != nil {
|
|
return false, nil
|
|
}
|
|
v, ok := states["organizer.tasks"]
|
|
return !ok || v, nil
|
|
}
|
|
|
|
// Notification insertion and reservation acknowledgment share one writer
|
|
// transaction. Current membership, source version and extension state are
|
|
// rechecked under that lock. No task title/body is copied into the Inbox.
|
|
func (s *Store) DeliverTaskReminders(ctx context.Context, now time.Time, limit int) (scanned int, sentCount int, resultErr error) {
|
|
defer func() { resultErr = s.sqlError("task reminder delivery", 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, 0, err
|
|
}
|
|
defer tx.Rollback()
|
|
if err = s.lockTaskWriter(ctx, tx); err != nil {
|
|
return 0, 0, err
|
|
}
|
|
// Acquire the shared writer before selecting candidates. Mutations
|
|
// and parallel delivery workers cannot change the checked source meanwhile.
|
|
if _, err = tx.ExecContext(ctx, `UPDATE organizer_reminders SET state=state WHERE item_uuid=''`); err != nil {
|
|
return 0, 0, err
|
|
}
|
|
rows, err := tx.QueryContext(ctx, `SELECT domain_uuid,item_uuid,owner_uuid,kind,source_version,fire_at_ms,civil_date,timezone,notification_key FROM organizer_reminders WHERE state='pending' AND fire_at_ms<=`+s.sqlParam(1)+` ORDER BY fire_at_ms,domain_uuid,item_uuid,kind LIMIT `+s.sqlParam(2)+``, now.UnixMilli(), limit)
|
|
if err != nil {
|
|
return 0, 0, err
|
|
}
|
|
type reminder struct {
|
|
domain, id, owner, kind, date, timezone, key string
|
|
version, fire int64
|
|
}
|
|
items := []reminder{}
|
|
for rows.Next() {
|
|
var v reminder
|
|
if err = rows.Scan(&v.domain, &v.id, &v.owner, &v.kind, &v.version, &v.fire, &v.date, &v.timezone, &v.key); err != nil {
|
|
rows.Close()
|
|
return 0, 0, err
|
|
}
|
|
items = append(items, v)
|
|
}
|
|
err = rows.Err()
|
|
rows.Close()
|
|
if err != nil {
|
|
return 0, 0, err
|
|
}
|
|
sent := 0
|
|
for _, v := range items {
|
|
state := "skipped"
|
|
loc, e := time.LoadLocation(v.timezone)
|
|
if e != nil {
|
|
return 0, 0, e
|
|
}
|
|
auth := s.taskActor(ctx, tx, v.domain, v.owner, false)
|
|
if auth != nil && !errors.Is(auth, ErrAccessDenied) {
|
|
return 0, 0, auth
|
|
}
|
|
enabled, e := s.taskReminderExtensionEnabled(ctx, tx, v.domain)
|
|
if e != nil {
|
|
return 0, 0, e
|
|
}
|
|
var current bool
|
|
if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM organizer_items WHERE domain_uuid=`+s.sqlParam(1)+` AND uuid=`+s.sqlParam(2)+` AND owner_uuid=`+s.sqlParam(3)+` AND version=`+s.sqlParam(4)+` AND archived=0 AND status NOT IN ('done','cancelled') AND kind='task')`, v.domain, v.id, v.owner, v.version).Scan(¤t); err != nil {
|
|
return 0, 0, err
|
|
}
|
|
if auth == nil && enabled && current && now.In(loc).Format("2006-01-02") == v.date {
|
|
_, created, e := s.CreateNotificationTx(tx, Notification{DomainUUID: v.domain, RecipientUUID: v.owner, EventUUID: v.key, Kind: "task." + v.kind, RequestUUID: v.id, Href: "/v/plan/task/" + v.id, Message: "Task reminder", CreatedAtMS: now.UnixMilli()})
|
|
if e != nil {
|
|
return 0, 0, e
|
|
}
|
|
if created {
|
|
sent++
|
|
}
|
|
state = "sent"
|
|
}
|
|
if _, err = tx.ExecContext(ctx, `UPDATE organizer_reminders SET state=`+s.sqlParam(1)+` WHERE domain_uuid=`+s.sqlParam(2)+` AND item_uuid=`+s.sqlParam(3)+` AND kind=`+s.sqlParam(4)+``, state, v.domain, v.id, v.kind); err != nil {
|
|
return 0, 0, err
|
|
}
|
|
}
|
|
if err = tx.Commit(); err != nil {
|
|
return 0, 0, err
|
|
}
|
|
return len(items), sent, nil
|
|
}
|
|
|
|
// Resolve a notification using current owner-only metadata; no CAS body fetch
|
|
// is necessary. Stale notices remain generic receipts, with no title or link.
|
|
func (s *Store) TaskReminderTitle(ctx context.Context, domain, actor, key string) (string, error) {
|
|
if err := s.taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
|
return "", err
|
|
}
|
|
var title string
|
|
err := s.DB.QueryRowContext(ctx, `SELECT i.title FROM organizer_reminders r JOIN organizer_items i ON i.domain_uuid=r.domain_uuid AND i.uuid=r.item_uuid AND i.owner_uuid=r.owner_uuid AND i.version=r.source_version JOIN principals p ON p.uuid=r.owner_uuid AND p.state IN ('active','readonly') JOIN domain_memberships m ON m.principal_uuid=r.owner_uuid AND m.domain_uuid=r.domain_uuid AND m.state='active' JOIN domains d ON d.uuid=r.domain_uuid AND d.enabled=1 AND COALESCE(d.placement,'local')='local' WHERE r.domain_uuid=`+s.sqlParam(1)+` AND r.owner_uuid=`+s.sqlParam(2)+` AND r.notification_key=`+s.sqlParam(3)+` AND r.state='sent' AND i.archived=0 AND i.status NOT IN ('done','cancelled')`, domain, actor, key).Scan(&title)
|
|
return title, err
|
|
}
|
|
|
|
func (s *Store) EnsureTaskReminderEvent() error {
|
|
if s.sqlBackend == storePostgreSQL {
|
|
return s.ensureNativeBuiltinEvent("builtin.task.reminders", "Task Inbox reminders", TaskReminderEventType, 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.reminders','Task Inbox reminders',`+s.sqlParam(1)+`,'local','{}','interval',60,`+s.sqlParam(2)+`,1,-2,3,`+s.sqlParam(3)+`,`+s.sqlParam(4)+`)`, TaskReminderEventType, now, now, now)
|
|
return err
|
|
}
|