diff --git a/internal/panel/backup/validate_vault.go b/internal/panel/backup/validate_vault.go index f0482875..774d301e 100644 --- a/internal/panel/backup/validate_vault.go +++ b/internal/panel/backup/validate_vault.go @@ -80,6 +80,14 @@ var restoredSealedValueQueries = []sealedValueQuery{ // telegram_bot.token is sealed with tokenRecordID; see telegram.rpc.SetTelegramBot in telegram/rpc.go. {description: "Telegram bot token", table: "telegram_bot", columns: []string{"token"}, query: "SELECT token, 'telegram_bot.token' FROM telegram_bot WHERE length(token) > 0"}, + // user_telegram_bot.token is sealed with userTokenRecordID; see telegram.rpc.SetUserBot in telegram/user_rpc.go. + {description: "Telegram bot token of the people", table: "user_telegram_bot", columns: []string{"token"}, + query: "SELECT token, 'user_telegram_bot.token' FROM user_telegram_bot WHERE length(token) > 0"}, + // user_telegram_chat.chat_enc is sealed to the chat's own MAC (the row id is born inside the store insert); see + // telegram.Service.linkUserChat and chatRecordID in telegram/user_bot.go. The hex is lower case, as Go prints it. + {description: "Telegram chat of a person", table: "user_telegram_chat", columns: []string{"chat_enc", "chat_mac"}, aadParts: 1, + aadFrom: func(parts ...string) string { return "user_telegram_chat:" + parts[0] }, + query: "SELECT chat_enc, lower(hex(chat_mac)) FROM user_telegram_chat WHERE length(chat_enc) > 0"}, // auth_ceremony.totp_enc uses auth.AuthCeremonyTOTPRecordID; see auth.Service.ceremonyRow in auth/service.go. {description: "auth ceremony TOTP", table: "auth_ceremony", columns: []string{"totp_enc", "id"}, aadParts: 1, aadFrom: func(parts ...string) string { return auth.AuthCeremonyTOTPRecordID(parts[0]) }, diff --git a/internal/panel/store/migrations/00165_user_notify.sql b/internal/panel/store/migrations/00165_user_notify.sql new file mode 100644 index 00000000..d1a1ed46 --- /dev/null +++ b/internal/panel/store/migrations/00165_user_notify.sql @@ -0,0 +1,126 @@ +-- Notifications to people (store/user_telegram.go, store/user_notice.go). A person's subscription gets news through two channels: +-- Telegram (a bot of its own, not the admins' one) and the Mistgate app (pulled with its sync). The outbox user_notice feeds both. +-- +-- Secrets: the bot token is vault ciphertext; a chat id is never stored in the clear. chat_enc is the sealed id (to send), chat_mac +-- is its keyed MAC (to find a chat from an update, and to keep one chat from belonging to two people). A chat belongs to a bot: +-- replacing or clearing the bot deletes every chat, every pending link code and the Telegram channel of unfinished notices. +-- +-- user_notice is an outbox with at-least-once delivery. A row is unfinished while done_at = 0 and finished when it has a result +-- (the CHECK keeps the two in step). Rules that are not obvious from the columns: +-- * dedupe is unique for the life of the row: a producer inserts its event again and again, the second insert is a no-op, and a +-- row that finished keeps the event from coming back until retention purges it. +-- * approval is '' (no approval needed), pending (a draft waits for the owner), approved, dismissed or expired. A pending row is +-- never leased. dismissed and expired rows are finished at once (done_at and the same result), so retention removes them. +-- * draft_id groups the rows of one owner's draft: a failure draft is one per incident, the rows are one per person, and +-- approving, dismissing or expiring the draft touches them all. NULL = the row is its own draft. +-- * incident_id and draft_id are NULL when absent (a partial index covers only the rows that have one), never ''. +-- * a worker leases a row (lease_id, lease_until) and may finish or retry it only while it still holds that lease id; a lease +-- that ran out is taken again, so a crash costs a repeat, not a loss. +-- * channels is a bit mask, Telegram = 1, app = 2; the app pulls its events, so it has no retries. tg_sent counts the chats that +-- got the message, app_taken_count counts the devices that pulled it (written by the sync, never by the sender). +-- * tg_message_refs is a JSON object user_telegram_chat.id -> message id (the row id, never a Telegram chat id), kept to edit +-- an incident message and to not send twice on a retry. +-- +-- user_incident is a service failure of one person (every server of the subscription down). A person has at most one open +-- incident, which the partial unique index enforces. No foreign key on notice_id: the notice is purged earlier than the incident. +-- +-- Default values of the settings live in the code: a key with no row means its default, so this migration writes none. + +-- +goose Up +CREATE TABLE user_telegram_bot ( + id INTEGER PRIMARY KEY CHECK (id = 1), + token BLOB NOT NULL, -- vault ciphertext, record "user_telegram_bot.token"; never returned by an RPC + bot_id INTEGER NOT NULL, -- from getMe: tells a new bot from the same one pasted again + username TEXT NOT NULL, + updated_at INTEGER NOT NULL, + poll_offset INTEGER NOT NULL DEFAULT 0, -- next getUpdates offset + last_error TEXT NOT NULL DEFAULT '', -- code of the last failure, for the bot card; never a message text + last_ok INTEGER NOT NULL DEFAULT 0 -- last successful call to the Bot API +) STRICT; + +CREATE TABLE user_telegram_chat ( + id TEXT PRIMARY KEY, -- utc_... + user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, + chat_mac BLOB NOT NULL UNIQUE, -- keyed MAC of the chat id: one chat belongs to one person + chat_enc BLOB NOT NULL, -- vault ciphertext of the chat id, AAD user_telegram_chat: + lang TEXT NOT NULL, -- language of the messages to this chat + muted INTEGER NOT NULL DEFAULT 0 CHECK (muted IN (0, 1)), -- announcements off + linked_at INTEGER NOT NULL, + last_sent_at INTEGER NOT NULL DEFAULT 0 +) STRICT; +-- The chats of a person, oldest first, and how many there are. +CREATE INDEX user_telegram_chat_user ON user_telegram_chat (user_id, linked_at); + +CREATE TABLE user_telegram_code ( + hash TEXT PRIMARY KEY CHECK (length(hash) = 64), -- sha256 of the code, hex + user_id TEXT NOT NULL UNIQUE REFERENCES user (id) ON DELETE CASCADE, -- one pending code per person + expires_at INTEGER NOT NULL +) STRICT; +CREATE INDEX user_telegram_code_expiry ON user_telegram_code (expires_at); + +CREATE TABLE user_notice ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, + kind TEXT NOT NULL, + dedupe TEXT NOT NULL UNIQUE, + params_json TEXT NOT NULL, + loud INTEGER NOT NULL CHECK (loud IN (0, 1)), + channels INTEGER NOT NULL CHECK (channels BETWEEN 1 AND 3), + created_at INTEGER NOT NULL, + due_at INTEGER NOT NULL, + draft_id TEXT, + approval TEXT NOT NULL DEFAULT '' CHECK (approval IN ('', 'pending', 'approved', 'dismissed', 'expired')), + approval_text TEXT NOT NULL DEFAULT '', -- the owner's own text ("edit"), '' = the rendered one + lease_id TEXT NOT NULL DEFAULT '', + lease_until INTEGER NOT NULL DEFAULT 0, + attempts INTEGER NOT NULL DEFAULT 0, + done_at INTEGER NOT NULL DEFAULT 0, + result TEXT NOT NULL DEFAULT '' CHECK (result IN ('', 'sent', 'dropped', 'unlinked', 'skipped_stale', 'dismissed', 'expired')), + tg_sent INTEGER NOT NULL DEFAULT 0, + app_taken_count INTEGER NOT NULL DEFAULT 0, + incident_id TEXT, + tg_message_refs TEXT NOT NULL DEFAULT '{}', + CHECK ((done_at = 0) = (result = '')) +) STRICT; +-- The sender's queue: unfinished rows by due time (the lease and the approval are filtered per row, they are few). +CREATE INDEX user_notice_due ON user_notice (due_at, id) WHERE done_at = 0; +-- The retention purge reads finished rows only. +CREATE INDEX user_notice_done ON user_notice (done_at) WHERE done_at > 0; +-- Drafts that wait: the expiry scan, and an approval of the whole draft. +CREATE INDEX user_notice_pending ON user_notice (created_at) WHERE approval = 'pending'; +CREATE INDEX user_notice_draft ON user_notice (draft_id) WHERE draft_id IS NOT NULL; +-- The events a person's app pulls and the history of the person's page. +CREATE INDEX user_notice_user ON user_notice (user_id, created_at); + +CREATE TABLE user_incident ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, + opened_at INTEGER NOT NULL, + resolved_at INTEGER NOT NULL DEFAULT 0, -- 0 = still open + nodes_json TEXT NOT NULL, -- ids of the nodes that went down + notice_id TEXT -- the notice that carries the incident message; NULL until it exists +) STRICT; +CREATE UNIQUE INDEX user_incident_open ON user_incident (user_id) WHERE resolved_at = 0; +-- The anti-storm rule asks when a person's last incident began. +CREATE INDEX user_incident_user ON user_incident (user_id, opened_at); + +CREATE TABLE user_notify_setting ( + key TEXT PRIMARY KEY, + value_json TEXT NOT NULL +) STRICT; + +CREATE TABLE user_notify_override ( + user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, + key TEXT NOT NULL, + value_json TEXT NOT NULL, + PRIMARY KEY (user_id, key) +) STRICT, WITHOUT ROWID; + +-- +goose Down +DROP TABLE user_notify_override; +DROP TABLE user_notify_setting; +DROP TABLE user_incident; +DROP TABLE user_notice; +DROP TABLE user_telegram_code; +DROP TABLE user_telegram_chat; +DROP TABLE user_telegram_bot; diff --git a/internal/panel/store/schema_snapshot.sql b/internal/panel/store/schema_snapshot.sql index d9d034fc..39b83c0d 100644 --- a/internal/panel/store/schema_snapshot.sql +++ b/internal/panel/store/schema_snapshot.sql @@ -1,5 +1,5 @@ -- Schema and data of a new, fully migrated panel database. --- goose version 164 +-- goose version 165 -- Generated by `go test ./internal/panel/store -run '^TestSchemaSnapshot$' -update`; do not edit by hand. PRAGMA defer_foreign_keys = ON; CREATE TABLE admin ( @@ -1162,6 +1162,14 @@ CREATE TABLE user_group_profile ( profile_id TEXT NOT NULL REFERENCES profile (id) ON DELETE CASCADE, PRIMARY KEY (group_id, profile_id) ) STRICT, WITHOUT ROWID; +CREATE TABLE user_incident ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, + opened_at INTEGER NOT NULL, + resolved_at INTEGER NOT NULL DEFAULT 0, -- 0 = still open + nodes_json TEXT NOT NULL, -- ids of the nodes that went down + notice_id TEXT -- the notice that carries the incident message; NULL until it exists +) STRICT; CREATE TABLE user_link_dns ( user_id TEXT NOT NULL PRIMARY KEY REFERENCES user (id) ON DELETE CASCADE, preset_id TEXT NOT NULL REFERENCES dns_preset (id) ON DELETE CASCADE, @@ -1186,6 +1194,65 @@ CREATE TABLE user_node_dns ( updated_at INTEGER NOT NULL, PRIMARY KEY (user_id, node_id) ) STRICT; +CREATE TABLE user_notice ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, + kind TEXT NOT NULL, + dedupe TEXT NOT NULL UNIQUE, + params_json TEXT NOT NULL, + loud INTEGER NOT NULL CHECK (loud IN (0, 1)), + channels INTEGER NOT NULL CHECK (channels BETWEEN 1 AND 3), + created_at INTEGER NOT NULL, + due_at INTEGER NOT NULL, + draft_id TEXT, + approval TEXT NOT NULL DEFAULT '' CHECK (approval IN ('', 'pending', 'approved', 'dismissed', 'expired')), + approval_text TEXT NOT NULL DEFAULT '', -- the owner's own text ("edit"), '' = the rendered one + lease_id TEXT NOT NULL DEFAULT '', + lease_until INTEGER NOT NULL DEFAULT 0, + attempts INTEGER NOT NULL DEFAULT 0, + done_at INTEGER NOT NULL DEFAULT 0, + result TEXT NOT NULL DEFAULT '' CHECK (result IN ('', 'sent', 'dropped', 'unlinked', 'skipped_stale', 'dismissed', 'expired')), + tg_sent INTEGER NOT NULL DEFAULT 0, + app_taken_count INTEGER NOT NULL DEFAULT 0, + incident_id TEXT, + tg_message_refs TEXT NOT NULL DEFAULT '{}', + CHECK ((done_at = 0) = (result = '')) +) STRICT; +CREATE TABLE user_notify_override ( + user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, + key TEXT NOT NULL, + value_json TEXT NOT NULL, + PRIMARY KEY (user_id, key) +) STRICT, WITHOUT ROWID; +CREATE TABLE user_notify_setting ( + key TEXT PRIMARY KEY, + value_json TEXT NOT NULL +) STRICT; +CREATE TABLE user_telegram_bot ( + id INTEGER PRIMARY KEY CHECK (id = 1), + token BLOB NOT NULL, -- vault ciphertext, record "user_telegram_bot.token"; never returned by an RPC + bot_id INTEGER NOT NULL, -- from getMe: tells a new bot from the same one pasted again + username TEXT NOT NULL, + updated_at INTEGER NOT NULL, + poll_offset INTEGER NOT NULL DEFAULT 0, -- next getUpdates offset + last_error TEXT NOT NULL DEFAULT '', -- code of the last failure, for the bot card; never a message text + last_ok INTEGER NOT NULL DEFAULT 0 -- last successful call to the Bot API +) STRICT; +CREATE TABLE user_telegram_chat ( + id TEXT PRIMARY KEY, -- utc_... + user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, + chat_mac BLOB NOT NULL UNIQUE, -- keyed MAC of the chat id: one chat belongs to one person + chat_enc BLOB NOT NULL, -- vault ciphertext of the chat id, AAD user_telegram_chat: + lang TEXT NOT NULL, -- language of the messages to this chat + muted INTEGER NOT NULL DEFAULT 0 CHECK (muted IN (0, 1)), -- announcements off + linked_at INTEGER NOT NULL, + last_sent_at INTEGER NOT NULL DEFAULT 0 +) STRICT; +CREATE TABLE user_telegram_code ( + hash TEXT PRIMARY KEY CHECK (length(hash) = 64), -- sha256 of the code, hex + user_id TEXT NOT NULL UNIQUE REFERENCES user (id) ON DELETE CASCADE, -- one pending code per person + expires_at INTEGER NOT NULL +) STRICT; CREATE TABLE warp_account ( -- at most one per node node_id TEXT PRIMARY KEY REFERENCES node (id) ON DELETE CASCADE, source TEXT NOT NULL CHECK (source IN ('registered', 'imported')), @@ -1320,11 +1387,20 @@ CREATE INDEX user_by_group ON user (group_id, name COLLATE NOCASE); CREATE INDEX user_expires ON user (expires_at) WHERE expires_at IS NOT NULL; CREATE INDEX user_extra_group_by_group ON user_extra_group (group_id); CREATE INDEX user_group_profile_profile ON user_group_profile (profile_id); +CREATE UNIQUE INDEX user_incident_open ON user_incident (user_id) WHERE resolved_at = 0; +CREATE INDEX user_incident_user ON user_incident (user_id, opened_at); CREATE INDEX user_network_last_hour ON user_network (last_hour); CREATE INDEX user_node_dns_node ON user_node_dns (node_id); CREATE INDEX user_node_node ON user_node (node_id); +CREATE INDEX user_notice_done ON user_notice (done_at) WHERE done_at > 0; +CREATE INDEX user_notice_draft ON user_notice (draft_id) WHERE draft_id IS NOT NULL; +CREATE INDEX user_notice_due ON user_notice (due_at, id) WHERE done_at = 0; +CREATE INDEX user_notice_pending ON user_notice (created_at) WHERE approval = 'pending'; +CREATE INDEX user_notice_user ON user_notice (user_id, created_at); CREATE INDEX user_quota ON user (used_bytes) WHERE quota_bytes > 0; CREATE INDEX user_status ON user (status); +CREATE INDEX user_telegram_chat_user ON user_telegram_chat (user_id, linked_at); +CREATE INDEX user_telegram_code_expiry ON user_telegram_code (expires_at); CREATE TRIGGER job_name_node_insert BEFORE INSERT ON node_provision_job WHEN NEW.state IN ('queued', 'running', 'cancel_requested') @@ -1557,8 +1633,9 @@ INSERT INTO "goose_db_version" ("id", "version_id", "is_applied", "tstamp") VALU INSERT INTO "goose_db_version" ("id", "version_id", "is_applied", "tstamp") VALUES (154, 162, 1, datetime('now')); INSERT INTO "goose_db_version" ("id", "version_id", "is_applied", "tstamp") VALUES (155, 163, 1, datetime('now')); INSERT INTO "goose_db_version" ("id", "version_id", "is_applied", "tstamp") VALUES (156, 164, 1, datetime('now')); +INSERT INTO "goose_db_version" ("id", "version_id", "is_applied", "tstamp") VALUES (157, 165, 1, datetime('now')); INSERT INTO "setting" ("k", "v") VALUES ('device_idle_after_days', '30'); DELETE FROM sqlite_sequence; INSERT INTO "sqlite_sequence" ("name", "seq") VALUES ('audit', 0); -INSERT INTO "sqlite_sequence" ("name", "seq") VALUES ('goose_db_version', 156); +INSERT INTO "sqlite_sequence" ("name", "seq") VALUES ('goose_db_version', 157); INSERT INTO "sqlite_sequence" ("name", "seq") VALUES ('node_provision_event', 0); diff --git a/internal/panel/store/testdata/schema.golden b/internal/panel/store/testdata/schema.golden index 3a48af18..82803d28 100644 --- a/internal/panel/store/testdata/schema.golden +++ b/internal/panel/store/testdata/schema.golden @@ -623,6 +623,18 @@ "tbl_name": "user_group_profile", "sql": "CREATE INDEX user_group_profile_profile ON user_group_profile (profile_id)" }, + { + "type": "index", + "name": "user_incident_open", + "tbl_name": "user_incident", + "sql": "CREATE UNIQUE INDEX user_incident_open ON user_incident (user_id) WHERE resolved_at = 0" + }, + { + "type": "index", + "name": "user_incident_user", + "tbl_name": "user_incident", + "sql": "CREATE INDEX user_incident_user ON user_incident (user_id, opened_at)" + }, { "type": "index", "name": "user_network_last_hour", @@ -641,6 +653,36 @@ "tbl_name": "user_node", "sql": "CREATE INDEX user_node_node ON user_node (node_id)" }, + { + "type": "index", + "name": "user_notice_done", + "tbl_name": "user_notice", + "sql": "CREATE INDEX user_notice_done ON user_notice (done_at) WHERE done_at \u003e 0" + }, + { + "type": "index", + "name": "user_notice_draft", + "tbl_name": "user_notice", + "sql": "CREATE INDEX user_notice_draft ON user_notice (draft_id) WHERE draft_id IS NOT NULL" + }, + { + "type": "index", + "name": "user_notice_due", + "tbl_name": "user_notice", + "sql": "CREATE INDEX user_notice_due ON user_notice (due_at, id) WHERE done_at = 0" + }, + { + "type": "index", + "name": "user_notice_pending", + "tbl_name": "user_notice", + "sql": "CREATE INDEX user_notice_pending ON user_notice (created_at) WHERE approval = 'pending'" + }, + { + "type": "index", + "name": "user_notice_user", + "tbl_name": "user_notice", + "sql": "CREATE INDEX user_notice_user ON user_notice (user_id, created_at)" + }, { "type": "index", "name": "user_quota", @@ -653,6 +695,18 @@ "tbl_name": "user", "sql": "CREATE INDEX user_status ON user (status)" }, + { + "type": "index", + "name": "user_telegram_chat_user", + "tbl_name": "user_telegram_chat", + "sql": "CREATE INDEX user_telegram_chat_user ON user_telegram_chat (user_id, linked_at)" + }, + { + "type": "index", + "name": "user_telegram_code_expiry", + "tbl_name": "user_telegram_code", + "sql": "CREATE INDEX user_telegram_code_expiry ON user_telegram_code (expires_at)" + }, { "type": "table", "name": "admin", @@ -1289,6 +1343,12 @@ "tbl_name": "user_group_profile", "sql": "CREATE TABLE user_group_profile ( group_id TEXT NOT NULL REFERENCES user_group (id) ON DELETE CASCADE, profile_id TEXT NOT NULL REFERENCES profile (id) ON DELETE CASCADE, PRIMARY KEY (group_id, profile_id) ) STRICT, WITHOUT ROWID" }, + { + "type": "table", + "name": "user_incident", + "tbl_name": "user_incident", + "sql": "CREATE TABLE user_incident ( id TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, opened_at INTEGER NOT NULL, resolved_at INTEGER NOT NULL DEFAULT 0, -- 0 = still open nodes_json TEXT NOT NULL, -- ids of the nodes that went down notice_id TEXT -- the notice that carries the incident message; NULL until it exists ) STRICT" + }, { "type": "table", "name": "user_link_dns", @@ -1313,6 +1373,42 @@ "tbl_name": "user_node_dns", "sql": "CREATE TABLE user_node_dns ( user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, node_id TEXT NOT NULL REFERENCES node (id) ON DELETE CASCADE, preset_id TEXT NOT NULL REFERENCES dns_preset (id) ON DELETE CASCADE, updated_at INTEGER NOT NULL, PRIMARY KEY (user_id, node_id) ) STRICT" }, + { + "type": "table", + "name": "user_notice", + "tbl_name": "user_notice", + "sql": "CREATE TABLE user_notice ( id TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, kind TEXT NOT NULL, dedupe TEXT NOT NULL UNIQUE, params_json TEXT NOT NULL, loud INTEGER NOT NULL CHECK (loud IN (0, 1)), channels INTEGER NOT NULL CHECK (channels BETWEEN 1 AND 3), created_at INTEGER NOT NULL, due_at INTEGER NOT NULL, draft_id TEXT, approval TEXT NOT NULL DEFAULT '' CHECK (approval IN ('', 'pending', 'approved', 'dismissed', 'expired')), approval_text TEXT NOT NULL DEFAULT '', -- the owner's own text (\"edit\"), '' = the rendered one lease_id TEXT NOT NULL DEFAULT '', lease_until INTEGER NOT NULL DEFAULT 0, attempts INTEGER NOT NULL DEFAULT 0, done_at INTEGER NOT NULL DEFAULT 0, result TEXT NOT NULL DEFAULT '' CHECK (result IN ('', 'sent', 'dropped', 'unlinked', 'skipped_stale', 'dismissed', 'expired')), tg_sent INTEGER NOT NULL DEFAULT 0, app_taken_count INTEGER NOT NULL DEFAULT 0, incident_id TEXT, tg_message_refs TEXT NOT NULL DEFAULT '{}', CHECK ((done_at = 0) = (result = '')) ) STRICT" + }, + { + "type": "table", + "name": "user_notify_override", + "tbl_name": "user_notify_override", + "sql": "CREATE TABLE user_notify_override ( user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, key TEXT NOT NULL, value_json TEXT NOT NULL, PRIMARY KEY (user_id, key) ) STRICT, WITHOUT ROWID" + }, + { + "type": "table", + "name": "user_notify_setting", + "tbl_name": "user_notify_setting", + "sql": "CREATE TABLE user_notify_setting ( key TEXT PRIMARY KEY, value_json TEXT NOT NULL ) STRICT" + }, + { + "type": "table", + "name": "user_telegram_bot", + "tbl_name": "user_telegram_bot", + "sql": "CREATE TABLE user_telegram_bot ( id INTEGER PRIMARY KEY CHECK (id = 1), token BLOB NOT NULL, -- vault ciphertext, record \"user_telegram_bot.token\"; never returned by an RPC bot_id INTEGER NOT NULL, -- from getMe: tells a new bot from the same one pasted again username TEXT NOT NULL, updated_at INTEGER NOT NULL, poll_offset INTEGER NOT NULL DEFAULT 0, -- next getUpdates offset last_error TEXT NOT NULL DEFAULT '', -- code of the last failure, for the bot card; never a message text last_ok INTEGER NOT NULL DEFAULT 0 -- last successful call to the Bot API ) STRICT" + }, + { + "type": "table", + "name": "user_telegram_chat", + "tbl_name": "user_telegram_chat", + "sql": "CREATE TABLE user_telegram_chat ( id TEXT PRIMARY KEY, -- utc_... user_id TEXT NOT NULL REFERENCES user (id) ON DELETE CASCADE, chat_mac BLOB NOT NULL UNIQUE, -- keyed MAC of the chat id: one chat belongs to one person chat_enc BLOB NOT NULL, -- vault ciphertext of the chat id, AAD user_telegram_chat:\u003chex of chat_mac\u003e lang TEXT NOT NULL, -- language of the messages to this chat muted INTEGER NOT NULL DEFAULT 0 CHECK (muted IN (0, 1)), -- announcements off linked_at INTEGER NOT NULL, last_sent_at INTEGER NOT NULL DEFAULT 0 ) STRICT" + }, + { + "type": "table", + "name": "user_telegram_code", + "tbl_name": "user_telegram_code", + "sql": "CREATE TABLE user_telegram_code ( hash TEXT PRIMARY KEY CHECK (length(hash) = 64), -- sha256 of the code, hex user_id TEXT NOT NULL UNIQUE REFERENCES user (id) ON DELETE CASCADE, -- one pending code per person expires_at INTEGER NOT NULL ) STRICT" + }, { "type": "table", "name": "warp_account", diff --git a/internal/panel/store/transaction_shapes_test.go b/internal/panel/store/transaction_shapes_test.go index 795ec01d..16eaf3dc 100644 --- a/internal/panel/store/transaction_shapes_test.go +++ b/internal/panel/store/transaction_shapes_test.go @@ -65,6 +65,8 @@ var transactionShape1 = map[string]string{ "store.go:writeSettingChanges": "Retention upserts and resets run in the same fixed atomic batch.", "network_hour.go:SaveNetworkMode": "The mode change and any network-row deletion required by it run in one fixed batch.", "access_linkmode.go:SaveSubscriptionSettings": "The settings upserts, the mode and, for STRICT, the revoke of every shared device run in one fixed batch.", + "user_telegram.go:ClearUserTelegramBot": "Deletes the chats, the pending link codes, the Telegram channel of the unfinished notices and the bot as one fixed batch.", + "user_notice.go:LeaseDueUserNotices": "One UPDATE ... RETURNING picks the due rows and claims them, so two callers never get one row.", "telegram.go:ClearTelegramBot": "Deletes links, pending link codes, and the bot as one fixed batch.", "telegram.go:UnlinkTelegram": "Deletes the chat link and pending link code as one fixed batch.", "token.go:RevokeAPIToken": "Revokes the token and cancels its open plans in one fixed batch.", @@ -136,6 +138,8 @@ var transactionShape2 = map[string]string{ "proposal.go:RejectProposal": "A still-awaiting guard precedes the rejection and the server's mode off (never) in one atomic batch; without never it is one compare-and-swap.", "relay.go:CreateRelay": "A guard on a server and an entry that are two enrolled nodes precedes the insert (which also stores the owner's mode); the unique keys refuse a duplicate or a taken port.", "telegram.go:BindTelegramChat": "SQL checks the admin while replacing both unique link owners.", + "user_telegram.go:SetUserTelegramBot": "SQL drops chats, pending link codes and the Telegram channel of the unfinished notices only when the stored bot differs, with the bot upsert in one batch.", + "user_notice.go:OpenUserIncident": "The insert is guarded by the one-open-incident unique index (a conflict writes nothing) and the open row is read back in the same batch.", "telegram.go:SetTelegramBot": "SQL drops links and pending link codes only when the stored bot differs, with the bot upsert in one batch.", "token.go:CreateAPIToken": "The insert guard enforces the live-token cap and unique active name in SQL.", "update.go:AddNodeToRunningRollout": "A current-rollout guard precedes stage shifting, insertion, and schedule consumption.", diff --git a/internal/panel/store/user_notice.go b/internal/panel/store/user_notice.go new file mode 100644 index 00000000..9277a257 --- /dev/null +++ b/internal/panel/store/user_notice.go @@ -0,0 +1,448 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "sort" + "time" +) + +// The outbox of the notifications to people, their incidents and their settings. Tables: migration 00165, whose header holds the +// rules a reader needs (dedupe, approval, drafts, leases, channels). A write that changes a row compares what it expects (the +// approval, the lease id) in its WHERE clause, so two workers or two owner windows cannot both win; the loser gets false. + +// The channels of a notice, bits of UserNotice.Channels. +const ( + UserNoticeTelegram = 1 + UserNoticeApp = 2 +) + +// The approval of a notice, the values of user_notice.approval. +const ( + UserNoticeApprovalNone = "" + UserNoticeApprovalPending = "pending" + UserNoticeApprovalApproved = "approved" + UserNoticeApprovalDismissed = "dismissed" + UserNoticeApprovalExpired = "expired" +) + +// The outcome of a finished notice, the values of user_notice.result. A dismissed or expired draft is finished with the result of +// the same name. +const ( + UserNoticeSent = "sent" + UserNoticeDropped = "dropped" + UserNoticeUnlinked = "unlinked" + UserNoticeSkippedStale = "skipped_stale" + UserNoticeDismissed = "dismissed" + UserNoticeExpired = "expired" +) + +// ErrUserNoticeResult: a notice cannot finish without a result. +var ErrUserNoticeResult = errors.New("store: a finished notice needs a result") + +// ErrUserNoticeApproval: an approval can be set to approved or dismissed only. +var ErrUserNoticeApproval = errors.New("store: a notice is approved or dismissed") + +// UserNotice is one row of user_notice. IncidentID and DraftID are "" when the notice has none (NULL in the table). +type UserNotice struct { + ID, UserID string + Kind string // the kind of notice, "expiry_soon" ... + Dedupe string // unique: the same event enqueued twice makes one row + ParamsJSON string // what the text is rendered from + Loud bool + Channels int // UserNoticeTelegram | UserNoticeApp + CreatedAt time.Time + DueAt time.Time // not sent before + DraftID string // the owner's draft this row belongs to (ask mode): one draft covers the rows of every person it reaches + Approval string // UserNoticeApproval* + // ApprovalText is the owner's own text of a draft ("edit the text"); "" sends the rendered one. + ApprovalText string + LeaseID string + LeaseUntil time.Time + Attempts int + DoneAt time.Time // zero while unfinished + Result string // UserNotice*, "" while unfinished + TGSent int // chats that got it + AppTakenCount int // devices that pulled it + IncidentID string + TGMessageRefs string // JSON object, user_telegram_chat.id -> message id (never the Telegram chat id) +} + +// userNoticeColumns is the column list scanUserNotice reads. +const userNoticeColumns = `id, user_id, kind, dedupe, params_json, loud, channels, created_at, due_at, draft_id, approval, approval_text, + lease_id, lease_until, attempts, done_at, result, tg_sent, app_taken_count, incident_id, tg_message_refs` + +func scanUserNotice(row rowScanner) (UserNotice, error) { + var n UserNotice + var created, due, leaseUntil, done int64 + var draft, incident sql.NullString + err := row.Scan(&n.ID, &n.UserID, &n.Kind, &n.Dedupe, &n.ParamsJSON, &n.Loud, &n.Channels, &created, &due, &draft, &n.Approval, + &n.ApprovalText, &n.LeaseID, &leaseUntil, &n.Attempts, &done, &n.Result, &n.TGSent, &n.AppTakenCount, &incident, &n.TGMessageRefs) + if err != nil { + return UserNotice{}, err + } + n.CreatedAt, n.DueAt, n.LeaseUntil, n.DoneAt = fromUnix(created), fromUnix(due), unixTime(leaseUntil), unixTime(done) + n.DraftID, n.IncidentID = draft.String, incident.String + return n, nil +} + +// nullableRef is s as a column value: "" is NULL, so a partial index covers only the rows that have a reference. +func nullableRef(s string) any { + if s == "" { + return nil + } + return s +} + +// messageRefs is refs, or the empty JSON object. +func messageRefs(refs string) string { + if refs == "" { + return "{}" + } + return refs +} + +// EnqueueUserNotice inserts the notice unless one with its dedupe key exists; it reports whether it was inserted. Lease, attempts +// and result are the notice's own to keep: only the fields of a new notice are read. +func (s *Store) EnqueueUserNotice(ctx context.Context, n UserNotice) (bool, error) { + r, err := s.W.ExecContext(ctx, `INSERT INTO user_notice (id, user_id, kind, dedupe, params_json, loud, channels, created_at, due_at, + draft_id, approval, approval_text, incident_id, tg_message_refs) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(dedupe) DO NOTHING`, + n.ID, n.UserID, n.Kind, n.Dedupe, n.ParamsJSON, n.Loud, n.Channels, unix(n.CreatedAt), unix(n.DueAt), + nullableRef(n.DraftID), n.Approval, n.ApprovalText, nullableRef(n.IncidentID), messageRefs(n.TGMessageRefs)) + if err != nil { + return false, err + } + rows, err := r.RowsAffected() + return rows > 0, err +} + +// LeaseDueUserNotices claims up to limit notices that are due (not finished, approved or needing no approval, due_at passed) for +// leaseFor, the most overdue first. One statement picks and claims them, so two callers never get the same row; a row whose +// lease ran out (a worker that stopped) is taken again. The rows come back as they were claimed. +func (s *Store) LeaseDueUserNotices(ctx context.Context, now time.Time, leaseFor time.Duration, limit int) ([]UserNotice, error) { + if limit <= 0 || leaseFor <= 0 { + return nil, nil + } + // the batch form (not a plain query) is how the repo reads the rows of an UPDATE ... RETURNING on both editions + results, err := s.batch(ctx, Stmt{Query: `UPDATE user_notice SET lease_id = ?, lease_until = ? + WHERE id IN (SELECT id FROM user_notice WHERE done_at = 0 AND approval IN ('', 'approved') AND due_at <= ? AND lease_until <= ? + ORDER BY due_at, id LIMIT ?) + RETURNING ` + userNoticeColumns, + Args: []any{NewID("unl_"), unix(now.Add(leaseFor)), unix(now), unix(now), limit}, Returning: true}) + if err != nil { + return nil, err + } + var out []UserNotice + for _, row := range results[0].Rows { + n, err := scanUserNotice(batchRow(row)) + if err != nil { + return nil, err + } + out = append(out, n) + } + // RETURNING has no order of its own + sort.Slice(out, func(i, j int) bool { + if !out[i].DueAt.Equal(out[j].DueAt) { + return out[i].DueAt.Before(out[j].DueAt) + } + return out[i].ID < out[j].ID + }) + return out, nil +} + +// FinishUserNotice ends a notice the caller holds the lease of: result, the chats that got it and the message ids (JSON, chat id +// -> message id). It reports false when the caller's lease is not the current one (it ran out and another worker took the row), +// so a stale worker cannot overwrite its successor. The devices that pulled it (AppTakenCount) are not its to write: they pull +// at any time. +func (s *Store) FinishUserNotice(ctx context.Context, id, leaseID string, now time.Time, result string, tgSent int, refs string) (bool, error) { + if result == "" { + return false, ErrUserNoticeResult + } + r, err := s.W.ExecContext(ctx, `UPDATE user_notice SET done_at = ?, result = ?, tg_sent = ?, tg_message_refs = ?, lease_id = '', lease_until = 0 + WHERE id = ? AND lease_id = ? AND lease_id <> '' AND done_at = 0`, + unix(now), result, tgSent, messageRefs(refs), id, leaseID) + if err != nil { + return false, err + } + n, err := r.RowsAffected() + return n > 0, err +} + +// RetryUserNotice gives the lease back to try again at due, with the attempts so far and the message ids of the chats that did get +// the message (so the retry sends to the others only). It reports false when the caller's lease is not the current one. +func (s *Store) RetryUserNotice(ctx context.Context, id, leaseID string, due time.Time, attempts int, refs string) (bool, error) { + r, err := s.W.ExecContext(ctx, `UPDATE user_notice SET due_at = ?, attempts = ?, tg_message_refs = ?, lease_id = '', lease_until = 0 + WHERE id = ? AND lease_id = ? AND lease_id <> '' AND done_at = 0`, + unix(due), attempts, messageRefs(refs), id, leaseID) + if err != nil { + return false, err + } + n, err := r.RowsAffected() + return n > 0, err +} + +// decideUserNotices is the update behind SetUserNoticeApproval and SetUserNoticeApprovalByDraft: the pending rows that match +// where (one argument) are approved with the owner's text, or dismissed, which also finishes them so that retention removes them. +func (s *Store) decideUserNotices(ctx context.Context, where, arg, approval, text string, now time.Time) (int64, error) { + var r sql.Result + var err error + switch approval { + case UserNoticeApprovalApproved: + r, err = s.W.ExecContext(ctx, `UPDATE user_notice SET approval = 'approved', approval_text = ? WHERE approval = 'pending' AND `+where, text, arg) + case UserNoticeApprovalDismissed: + r, err = s.W.ExecContext(ctx, `UPDATE user_notice SET approval = 'dismissed', approval_text = ?, done_at = ?, result = 'dismissed' + WHERE approval = 'pending' AND `+where, text, unix(now), arg) + default: + return 0, ErrUserNoticeApproval + } + if err != nil { + return 0, err + } + return r.RowsAffected() +} + +// SetUserNoticeApproval approves (with the owner's own text, or "" for the rendered one) or dismisses a notice that waits for the +// owner; false when it does not (it was decided, or expired). +func (s *Store) SetUserNoticeApproval(ctx context.Context, id, approval, text string, now time.Time) (bool, error) { + n, err := s.decideUserNotices(ctx, `id = ?`, id, approval, text, now) + return n > 0, err +} + +// SetUserNoticeApprovalByDraft decides every row of a draft that still waits, in one statement: the owner answers one draft of an +// incident, the rows are one per person. It returns how many rows it decided. +func (s *Store) SetUserNoticeApprovalByDraft(ctx context.Context, draftID, approval, text string, now time.Time) (int64, error) { + return s.decideUserNotices(ctx, `draft_id = ?`, draftID, approval, text, now) +} + +// ExpireUserNoticeApprovals burns the drafts the owner did not answer within ttl of their creation, finishing their rows with the +// result "expired". A draft burns whole: when one of its rows is older than ttl, so are the others. It returns how many rows went. +func (s *Store) ExpireUserNoticeApprovals(ctx context.Context, now time.Time, ttl time.Duration) (int64, error) { + before := unix(now.Add(-ttl)) + r, err := s.W.ExecContext(ctx, `UPDATE user_notice SET approval = 'expired', done_at = ?, result = 'expired' + WHERE approval = 'pending' AND (created_at <= ? + OR draft_id IN (SELECT draft_id FROM user_notice WHERE approval = 'pending' AND created_at <= ?))`, + unix(now), before, before) + if err != nil { + return 0, err + } + return r.RowsAffected() +} + +// UserAppNotices is what the app of a person pulls: its events (the notices that have the app channel, need no approval or have +// it, are due and were not found stale) of the last seven days, newest first, at most 20. +func (s *Store) UserAppNotices(ctx context.Context, user string, now time.Time) ([]UserNotice, error) { + rows, err := s.R.QueryContext(ctx, `SELECT `+userNoticeColumns+` FROM user_notice + WHERE user_id = ? AND (channels & 2) <> 0 AND approval IN ('', 'approved') AND due_at <= ? AND created_at >= ? AND result <> 'skipped_stale' + ORDER BY created_at DESC, id DESC LIMIT 20`, user, unix(now), unix(now.Add(-7*24*time.Hour))) + if err != nil { + return nil, err + } + defer rows.Close() + var out []UserNotice + for rows.Next() { + n, err := scanUserNotice(rows) + if err != nil { + return nil, err + } + out = append(out, n) + } + return out, rows.Err() +} + +// PurgeUserNotices deletes the notices that finished before olderThan (the retention of the journal); it returns how many went. +func (s *Store) PurgeUserNotices(ctx context.Context, olderThan time.Time) (int64, error) { + r, err := s.W.ExecContext(ctx, `DELETE FROM user_notice WHERE done_at > 0 AND done_at < ?`, unix(olderThan)) + if err != nil { + return 0, err + } + return r.RowsAffected() +} + +// ErrUserIncidentOpen: the person already has an open incident. OpenUserIncident returns it with the open one. +var ErrUserIncidentOpen = errors.New("store: the person has an open incident") + +// UserIncident is one row of user_incident: every server of a person's subscription was down. NoticeID is "" until the notice +// that carries the incident message exists. +type UserIncident struct { + ID, UserID string + OpenedAt, ResolvedAt time.Time // ResolvedAt is zero while it is open + NodesJSON string // ids of the nodes that went down + NoticeID string +} + +const userIncidentColumns = `id, user_id, opened_at, resolved_at, nodes_json, notice_id` + +func scanUserIncident(row rowScanner) (UserIncident, error) { + var i UserIncident + var opened, resolved int64 + var notice sql.NullString + if err := row.Scan(&i.ID, &i.UserID, &opened, &resolved, &i.NodesJSON, ¬ice); err != nil { + return UserIncident{}, err + } + i.OpenedAt, i.ResolvedAt, i.NoticeID = fromUnix(opened), unixTime(resolved), notice.String + return i, nil +} + +// OpenUserIncident opens an incident (ResolvedAt is ignored: a new one is open). A person has one open incident at most: when +// there is one already, nothing is written and the call returns it with ErrUserIncidentOpen. The insert and the read of the open +// row are one batch, so what comes back is the row that holds the person's slot. +func (s *Store) OpenUserIncident(ctx context.Context, i UserIncident) (UserIncident, error) { + results, err := s.batch(ctx, + Stmt{Query: `INSERT INTO user_incident (id, user_id, opened_at, resolved_at, nodes_json, notice_id) VALUES (?, ?, ?, 0, ?, ?) + ON CONFLICT(user_id) WHERE resolved_at = 0 DO NOTHING`, + Args: []any{i.ID, i.UserID, unix(i.OpenedAt), i.NodesJSON, nullableRef(i.NoticeID)}}, + Stmt{Query: `SELECT ` + userIncidentColumns + ` FROM user_incident WHERE user_id = ? AND resolved_at = 0`, Args: []any{i.UserID}, Returning: true}, + ) + if err != nil { + return UserIncident{}, err + } + if len(results[1].Rows) != 1 { + return UserIncident{}, errors.New("store: opened incident not found") + } + open, err := scanUserIncident(batchRow(results[1].Rows[0])) + if err != nil { + return UserIncident{}, err + } + if results[0].RowsAffected == 0 { + return open, ErrUserIncidentOpen + } + return open, nil +} + +// ResolveUserIncident closes an open incident; it reports false when there is none with this id. +func (s *Store) ResolveUserIncident(ctx context.Context, id string, now time.Time) (bool, error) { + r, err := s.W.ExecContext(ctx, `UPDATE user_incident SET resolved_at = ? WHERE id = ? AND resolved_at = 0`, unix(now), id) + if err != nil { + return false, err + } + n, err := r.RowsAffected() + return n > 0, err +} + +// UserOpenIncident is the open incident of a person; ErrNotFound when there is none. +func (s *Store) UserOpenIncident(ctx context.Context, user string) (UserIncident, error) { + i, err := scanUserIncident(s.R.QueryRowContext(ctx, `SELECT `+userIncidentColumns+` FROM user_incident WHERE user_id = ? AND resolved_at = 0`, user)) + if errors.Is(err, sql.ErrNoRows) { + return UserIncident{}, ErrNotFound + } + return i, err +} + +// PurgeUserIncidents deletes the incidents that were resolved before olderThan; it returns how many went. +func (s *Store) PurgeUserIncidents(ctx context.Context, olderThan time.Time) (int64, error) { + r, err := s.W.ExecContext(ctx, `DELETE FROM user_incident WHERE resolved_at > 0 AND resolved_at < ?`, unix(olderThan)) + if err != nil { + return 0, err + } + return r.RowsAffected() +} + +// UserNotifySettings is every global setting of the notifications, key -> JSON value. A key that is not there has its default +// (below). +func (s *Store) UserNotifySettings(ctx context.Context) (map[string]string, error) { + return s.userNotifyValues(ctx, `SELECT key, value_json FROM user_notify_setting`) +} + +// UserNotifyOverrides is the settings that apply to one person only (the chat limit, the kinds switched off), key -> JSON value. +func (s *Store) UserNotifyOverrides(ctx context.Context, user string) (map[string]string, error) { + return s.userNotifyValues(ctx, `SELECT key, value_json FROM user_notify_override WHERE user_id = ?`, user) +} + +func (s *Store) userNotifyValues(ctx context.Context, query string, args ...any) (map[string]string, error) { + rows, err := s.R.QueryContext(ctx, query, args...) + if err != nil { + return nil, err + } + defer rows.Close() + out := map[string]string{} + for rows.Next() { + var key, value string + if err := rows.Scan(&key, &value); err != nil { + return nil, err + } + out[key] = value + } + return out, rows.Err() +} + +// SetUserNotifySetting stores the JSON value of a global setting. +func (s *Store) SetUserNotifySetting(ctx context.Context, key, value string) error { + _, err := s.W.ExecContext(ctx, `INSERT INTO user_notify_setting (key, value_json) VALUES (?, ?) + ON CONFLICT(key) DO UPDATE SET value_json = excluded.value_json`, key, value) + return err +} + +// DeleteUserNotifySetting returns a global setting to its default. +func (s *Store) DeleteUserNotifySetting(ctx context.Context, key string) error { + _, err := s.W.ExecContext(ctx, `DELETE FROM user_notify_setting WHERE key = ?`, key) + return err +} + +// SetUserNotifyOverride stores the JSON value of a setting for one person; ErrNotFound when there is no such person. +func (s *Store) SetUserNotifyOverride(ctx context.Context, user, key, value string) error { + r, err := s.W.ExecContext(ctx, `INSERT INTO user_notify_override (user_id, key, value_json) + SELECT id, ?, ? FROM user WHERE id = ? + ON CONFLICT(user_id, key) DO UPDATE SET value_json = excluded.value_json`, key, value, user) + if err != nil { + return err + } + if n, err := r.RowsAffected(); err != nil { + return err + } else if n == 0 { + return ErrNotFound + } + return nil +} + +// DeleteUserNotifyOverride returns a setting of one person to the global one. +func (s *Store) DeleteUserNotifyOverride(ctx context.Context, user, key string) error { + _, err := s.W.ExecContext(ctx, `DELETE FROM user_notify_override WHERE user_id = ? AND key = ?`, user, key) + return err +} + +// The defaults of the settings. A key with no row in user_notify_setting means its default, so a default changes with the code. +const ( + DefaultUserTelegramChatLimit = 3 // chats per person, 1 to 10 globally + DefaultUserNoticeRetentionDays = 30 // how long the journal keeps finished notices + DefaultUserNoticeApprovalTTL = 30 * time.Minute // how long a draft waits for the owner + DefaultUserIncidentThreshold = 10 * time.Minute // every server down for this long opens an incident + DefaultUserIncidentCooldown = time.Hour // one incident per person per this time + DefaultUserIncidentMinimumDuration = 5 * time.Minute // a shorter outage is not an incident + DefaultUserQuotaWarningPercent = 80 + DefaultUserExpiryFirstThreshold = 72 * time.Hour + DefaultUserExpirySecondThreshold = 24 * time.Hour +) + +// UserNoticeKindDefault is the policy of a kind of notice when no setting changes it. +type UserNoticeKindDefault struct { + Mode string // "off", "ask" (a draft the owner approves) or "auto" + Loud bool // false sends it without a sound + Channels int // UserNoticeTelegram | UserNoticeApp +} + +// DefaultUserNoticeKinds is the default policy of every kind of notice but the owner's broadcast, which is sent by hand. The map +// is new on every call, so a caller may change it. +func DefaultUserNoticeKinds() map[string]UserNoticeKindDefault { + both := UserNoticeTelegram | UserNoticeApp + auto := func(loud bool) UserNoticeKindDefault { + return UserNoticeKindDefault{Mode: "auto", Loud: loud, Channels: both} + } + return map[string]UserNoticeKindDefault{ + "expiry_soon": auto(false), + "expired": auto(true), + "quota_warn": auto(false), + "quota_over": auto(true), + "restored": auto(false), + "link_rotated": auto(true), + "device_removed": auto(true), + "awg_reconfig": auto(true), + "tg_key_changed": auto(false), + "device_limit": auto(false), + "incident_all_down": {Mode: "ask", Loud: true, Channels: both}, + "incident_primary_down": {Mode: "off", Loud: false, Channels: both}, + "torrent": {Mode: "off", Loud: true, Channels: both}, + } +} diff --git a/internal/panel/store/user_notify_test.go b/internal/panel/store/user_notify_test.go new file mode 100644 index 00000000..8be232db --- /dev/null +++ b/internal/panel/store/user_notify_test.go @@ -0,0 +1,893 @@ +//go:build !js + +package store + +import ( + "context" + "errors" + "fmt" + "sync" + "testing" + "time" +) + +// userNotifyNow is the clock of these tests. +var userNotifyNow = time.Unix(1_800_000_000, 0).UTC() + +// openUserNotify opens a store with a group and the given people. +func openUserNotify(t *testing.T, users ...string) *Store { + t.Helper() + s := openTemp(t) + execT(t, s, `INSERT INTO user_group (id, name, created_at) VALUES ('grp_a', 'a', 1)`) + for i, id := range users { + execT(t, s, `INSERT INTO user (id, name, group_id, period_start, sub_token_hash, sub_token_enc, created_at) VALUES (?, ?, 'grp_a', 1, ?, x'02', 1)`, + id, "name-"+id, []byte{byte(i + 1)}) + } + return s +} + +// testNotice is a notice for both channels that is due now and needs no approval. +func testNotice(id, user string) UserNotice { + return UserNotice{ID: id, UserID: user, Kind: "expired", Dedupe: "dedupe-" + id, ParamsJSON: "{}", Channels: UserNoticeTelegram | UserNoticeApp, + CreatedAt: userNotifyNow, DueAt: userNotifyNow} +} + +func enqueue(t *testing.T, s *Store, n UserNotice) { + t.Helper() + if ok, err := s.EnqueueUserNotice(context.Background(), n); err != nil || !ok { + t.Fatalf("enqueue %s: %v %v", n.ID, ok, err) + } +} + +// noticeRow reads one notice back. +func noticeRow(t *testing.T, s *Store, id string) UserNotice { + t.Helper() + n, err := scanUserNotice(s.R.QueryRowContext(context.Background(), `SELECT `+userNoticeColumns+` FROM user_notice WHERE id = ?`, id)) + if err != nil { + t.Fatalf("notice %s: %v", id, err) + } + return n +} + +func leaseIDs(t *testing.T, s *Store, now time.Time, limit int) []string { + t.Helper() + got, err := s.LeaseDueUserNotices(context.Background(), now, time.Minute, limit) + if err != nil { + t.Fatal(err) + } + var ids []string + for _, n := range got { + ids = append(ids, n.ID) + } + return ids +} + +func sameIDs(got []string, want ...string) bool { + if len(got) != len(want) { + return false + } + for i := range got { + if got[i] != want[i] { + return false + } + } + return true +} + +func TestLinkUserTelegramChat(t *testing.T) { + ctx := context.Background() + s := openUserNotify(t, "usr_u", "usr_v") + calls := 0 + link := func(user, mac string, limit int) error { + calls++ // every link is a second later, so "oldest first" has an order + return s.LinkUserTelegramChat(ctx, user, []byte(mac), []byte("sealed"), "en", limit, userNotifyNow.Add(time.Duration(calls)*time.Second)) + } + steps := []struct { + name string + user string + mac string + limit int + want error + }{ + {"first", "usr_u", "a", 2, nil}, + {"same chat again is no change", "usr_u", "a", 2, nil}, + {"second", "usr_u", "b", 2, nil}, + {"over the limit", "usr_u", "c", 2, ErrUserTelegramChatLimit}, + {"a linked chat passes at the limit", "usr_u", "b", 2, nil}, + {"another person's chat", "usr_v", "a", 2, ErrUserTelegramChatTaken}, + {"taken wins over the limit", "usr_v", "a", 0, ErrUserTelegramChatTaken}, + {"limit zero", "usr_v", "z", 0, ErrUserTelegramChatLimit}, + {"unknown person", "usr_nobody", "n", 2, ErrNotFound}, + {"the other person has room", "usr_v", "d", 2, nil}, + } + for _, step := range steps { + if err := link(step.user, step.mac, step.limit); !errors.Is(err, step.want) { + t.Fatalf("%s: got %v, want %v", step.name, err, step.want) + } + } + if n, err := s.CountUserTelegramChats(ctx, "usr_u"); err != nil || n != 2 { + t.Fatalf("count: %d %v", n, err) + } + chats, err := s.UserTelegramChats(ctx, "usr_u") + if err != nil || len(chats) != 2 || string(chats[0].ChatMAC) != "a" || chats[0].Lang != "en" || chats[0].Muted || !chats[0].LastSentAt.IsZero() || !chats[0].LinkedAt.After(userNotifyNow) { + t.Fatalf("chats: %+v %v", chats, err) + } + if c, err := s.UserTelegramChatByMAC(ctx, []byte("b")); err != nil || c.UserID != "usr_u" || c.ID != chats[1].ID { + t.Fatalf("by mac: %+v %v", c, err) + } + if _, err := s.UserTelegramChatByMAC(ctx, []byte("none")); !errors.Is(err, ErrNotFound) { + t.Fatalf("by mac, none: %v", err) + } + + // muted, language and the last send change the person's own chat only + id := chats[0].ID + edits := []struct { + name string + do func() error + want error + }{ + {"mute", func() error { return s.SetUserTelegramChatMuted(ctx, "usr_u", id, true) }, nil}, + {"lang", func() error { return s.SetUserTelegramChatLang(ctx, "usr_u", id, "ru") }, nil}, + {"last sent", func() error { return s.SetUserTelegramChatLastSent(ctx, "usr_u", id, userNotifyNow.Add(time.Hour)) }, nil}, + {"mute of another person's chat", func() error { return s.SetUserTelegramChatMuted(ctx, "usr_v", id, true) }, ErrNotFound}, + {"lang of no chat", func() error { return s.SetUserTelegramChatLang(ctx, "usr_u", "utc_none", "ru") }, ErrNotFound}, + } + for _, e := range edits { + if err := e.do(); !errors.Is(err, e.want) { + t.Fatalf("%s: got %v, want %v", e.name, err, e.want) + } + } + if c, _ := s.UserTelegramChatByMAC(ctx, []byte("a")); !c.Muted || c.Lang != "ru" || !c.LastSentAt.Equal(userNotifyNow.Add(time.Hour)) { + t.Fatalf("edited chat: %+v", c) + } + + // unlink by id (the person's own) and by MAC + if ok, err := s.UnlinkUserTelegramChat(ctx, "usr_v", id); err != nil || ok { + t.Fatalf("unlink of another person's chat: %v %v", ok, err) + } + if ok, err := s.UnlinkUserTelegramChat(ctx, "usr_u", id); err != nil || !ok { + t.Fatalf("unlink: %v %v", ok, err) + } + if ok, err := s.UnlinkUserTelegramChatByMAC(ctx, []byte("b")); err != nil || !ok { + t.Fatalf("unlink by mac: %v %v", ok, err) + } + if ok, err := s.UnlinkUserTelegramChatByMAC(ctx, []byte("b")); err != nil || ok { + t.Fatalf("unlink by mac again: %v %v", ok, err) + } + if n, _ := s.CountUserTelegramChats(ctx, "usr_u"); n != 0 { + t.Fatalf("chats left: %d", n) + } + // a freed slot and a freed chat are usable again + if err := link("usr_v", "a", 2); err != nil { + t.Fatalf("relink after unlink: %v", err) + } +} + +// Two links at once for the last slot: one wins, the other gets the limit. The same chat linked by two people at once belongs to +// one of them. +func TestLinkUserTelegramChatRace(t *testing.T) { + ctx := context.Background() + var users []string + for i := range 20 { + users = append(users, fmt.Sprintf("usr_%d", i)) + } + s := openUserNotify(t, users...) + race := func(calls ...func() error) (nils int, errs []error) { + var wg sync.WaitGroup + results := make([]error, len(calls)) + start := make(chan struct{}) + for i, call := range calls { + wg.Add(1) + go func() { + defer wg.Done() + <-start + results[i] = call() + }() + } + close(start) + wg.Wait() + for _, err := range results { + if err == nil { + nils++ + } else { + errs = append(errs, err) + } + } + return nils, errs + } + for i, user := range users[:10] { + link := func(mac string) func() error { + return func() error { + return s.LinkUserTelegramChat(ctx, user, []byte(fmt.Sprintf("%d-%s", i, mac)), []byte("sealed"), "en", 1, userNotifyNow) + } + } + nils, errs := race(link("a"), link("b")) + if nils != 1 || len(errs) != 1 || !errors.Is(errs[0], ErrUserTelegramChatLimit) { + t.Fatalf("last slot of %s: %d winners, errors %v", user, nils, errs) + } + if n, _ := s.CountUserTelegramChats(ctx, user); n != 1 { + t.Fatalf("%s has %d chats", user, n) + } + } + for i := range 5 { + mac := []byte(fmt.Sprintf("shared-%d", i)) + link := func(user string) func() error { + return func() error { + return s.LinkUserTelegramChat(ctx, user, mac, []byte("sealed"), "en", 3, userNotifyNow) + } + } + nils, errs := race(link(users[10+2*i]), link(users[11+2*i])) + if nils != 1 || len(errs) != 1 || !errors.Is(errs[0], ErrUserTelegramChatTaken) { + t.Fatalf("shared chat %d: %d winners, errors %v", i, nils, errs) + } + } +} + +func TestUserTelegramCode(t *testing.T) { + ctx := context.Background() + s := openUserNotify(t, "usr_u", "usr_v") + code := func(c string) string { return fmt.Sprintf("%064s", c) } // a sha256 hex is 64 characters + if _, err := s.W.ExecContext(ctx, `INSERT INTO user_telegram_code (hash, user_id, expires_at) VALUES ('short', 'usr_u', 1)`); err == nil { + t.Fatal("a hash of the wrong length was stored") + } + if pending, err := s.HasPendingUserTelegramCode(ctx, userNotifyNow); err != nil || pending { + t.Fatalf("pending with no code: %v %v", pending, err) + } + for user, c := range map[string]string{"usr_u": "a", "usr_v": "b"} { + if err := s.SetUserTelegramCode(ctx, code(c), user, userNotifyNow.Add(15*time.Minute)); err != nil { + t.Fatal(err) + } + } + if err := s.SetUserTelegramCode(ctx, code("a2"), "usr_u", userNotifyNow.Add(15*time.Minute)); err != nil { // replaces a + t.Fatal(err) + } + if err := s.SetUserTelegramCode(ctx, code("gone"), "usr_nobody", userNotifyNow.Add(15*time.Minute)); err == nil { + t.Fatal("a code for no person was stored") + } + if n := countT(t, s, `SELECT count(*) FROM user_telegram_code`); n != 2 { + t.Fatalf("one code per person: %d rows", n) + } + steps := []struct { + name string + hash string + at time.Time + user string + want error + }{ + {"the replaced code is dead", code("a"), userNotifyNow, "", ErrNotFound}, + {"unknown", code("x"), userNotifyNow, "", ErrNotFound}, + {"expired", code("b"), userNotifyNow.Add(15 * time.Minute), "", ErrNotFound}, + {"take", code("a2"), userNotifyNow.Add(time.Minute), "usr_u", nil}, + {"single use", code("a2"), userNotifyNow.Add(time.Minute), "", ErrNotFound}, + {"take of the other person's", code("b"), userNotifyNow.Add(14 * time.Minute), "usr_v", nil}, + } + for _, step := range steps { + if got, err := s.TakeUserTelegramCode(ctx, step.hash, step.at); !errors.Is(err, step.want) || got != step.user { + t.Fatalf("%s: %q %v, want %q %v", step.name, got, err, step.user, step.want) + } + } + if err := s.SetUserTelegramCode(ctx, code("c"), "usr_u", userNotifyNow.Add(time.Minute)); err != nil { + t.Fatal(err) + } + for _, step := range []struct { + at time.Time + want bool + }{{userNotifyNow, true}, {userNotifyNow.Add(time.Minute), false}} { + if pending, err := s.HasPendingUserTelegramCode(ctx, step.at); err != nil || pending != step.want { + t.Fatalf("pending at +%v: %v %v", step.at.Sub(userNotifyNow), pending, err) + } + } + // only one of two takes at once gets the person + if err := s.SetUserTelegramCode(ctx, code("d"), "usr_v", userNotifyNow.Add(time.Hour)); err != nil { + t.Fatal(err) + } + var wg sync.WaitGroup + var won sync.Map + for i := range 4 { + wg.Add(1) + go func() { + defer wg.Done() + if user, err := s.TakeUserTelegramCode(ctx, code("d"), userNotifyNow); err == nil { + won.Store(i, user) + } + }() + } + wg.Wait() + n := 0 + won.Range(func(_, _ any) bool { n++; return true }) + if n != 1 { + t.Fatalf("%d takes of one code won", n) + } +} + +// A different bot takes the chats, the pending codes and the Telegram channel of the unfinished notices with it; the same bot +// pasted again changes nothing but its token. The app channel survives both. +func TestUserTelegramBotChange(t *testing.T) { + ctx := context.Background() + if _, err := openUserNotify(t).UserTelegramBot(ctx); !errors.Is(err, ErrNotFound) { + t.Fatalf("no bot: %v", err) + } + type outcome struct { + chats, codes int + notices map[string]int // id -> channels, the notices that remain + } + // the state before the change: a chat, a code, and unfinished notices for Telegram, for both, for the app, and a finished one + prepare := func(t *testing.T) *Store { + s := openUserNotify(t, "usr_u") + if _, err := s.SetUserTelegramBot(ctx, UserTelegramBot{Token: []byte("sealed"), BotID: 7, Username: "bot"}, userNotifyNow); err != nil { + t.Fatal(err) + } + if ok, err := s.SaveUserTelegramBotPoll(ctx, 42, "boom", userNotifyNow.Add(time.Minute)); err != nil || !ok { + t.Fatalf("poll state: %v %v", ok, err) + } + if err := s.LinkUserTelegramChat(ctx, "usr_u", []byte("mac"), []byte("sealed"), "en", 3, userNotifyNow); err != nil { + t.Fatal(err) + } + if err := s.SetUserTelegramCode(ctx, fmt.Sprintf("%064s", "c"), "usr_u", userNotifyNow.Add(time.Hour)); err != nil { + t.Fatal(err) + } + for id, channels := range map[string]int{"tg": 1, "both": 3, "app": 2} { + n := testNotice(id, "usr_u") + n.Channels = channels + enqueue(t, s, n) + } + done := testNotice("done", "usr_u") + enqueue(t, s, done) + execT(t, s, `UPDATE user_notice SET done_at = 5, result = 'sent' WHERE id = 'done'`) + return s + } + tests := []struct { + name string + do func(s *Store) (int, error) + want outcome + bot bool // a bot remains + poll bool // and keeps its poller state + }{ + {"same bot, new token", func(s *Store) (int, error) { + return s.SetUserTelegramBot(ctx, UserTelegramBot{Token: []byte("sealed 2"), BotID: 7, Username: "bot2"}, userNotifyNow.Add(time.Hour)) + }, outcome{1, 1, map[string]int{"tg": 1, "both": 3, "app": 2, "done": 3}}, true, true}, + {"another bot", func(s *Store) (int, error) { + return s.SetUserTelegramBot(ctx, UserTelegramBot{Token: []byte("sealed 2"), BotID: 8, Username: "bot2"}, userNotifyNow.Add(time.Hour)) + }, outcome{0, 0, map[string]int{"both": 2, "app": 2, "done": 3}}, true, false}, + {"clear", func(s *Store) (int, error) { return s.ClearUserTelegramBot(ctx) }, + outcome{0, 0, map[string]int{"both": 2, "app": 2, "done": 3}}, false, false}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + s := prepare(t) + dropped, err := tc.do(s) + if err != nil { + t.Fatal(err) + } + if wantDropped := 1 - tc.want.chats; dropped != wantDropped { + t.Fatalf("dropped %d chats, want %d", dropped, wantDropped) + } + if n := countT(t, s, `SELECT count(*) FROM user_telegram_chat`); n != tc.want.chats { + t.Fatalf("%d chats", n) + } + if n := countT(t, s, `SELECT count(*) FROM user_telegram_code`); n != tc.want.codes { + t.Fatalf("%d codes", n) + } + got := map[string]int{} + rows, err := s.R.QueryContext(ctx, `SELECT id, channels FROM user_notice`) + if err != nil { + t.Fatal(err) + } + defer rows.Close() + for rows.Next() { + var id string + var channels int + if err := rows.Scan(&id, &channels); err != nil { + t.Fatal(err) + } + got[id] = channels + } + if fmt.Sprint(got) != fmt.Sprint(tc.want.notices) { + t.Fatalf("notices %v, want %v", got, tc.want.notices) + } + bot, err := s.UserTelegramBot(ctx) + if !tc.bot { + if !errors.Is(err, ErrNotFound) { + t.Fatalf("bot after clear: %+v %v", bot, err) + } + return + } + if err != nil || bot.BotID == 0 || string(bot.Token) != "sealed 2" || bot.Username != "bot2" || !bot.UpdatedAt.Equal(userNotifyNow.Add(time.Hour)) { + t.Fatalf("bot: %+v %v", bot, err) + } + if kept := bot.Offset == 42 && bot.LastError == "boom" && bot.LastOK.Equal(userNotifyNow.Add(time.Minute)); kept != tc.poll { + t.Fatalf("poller state kept = %v, want %v: %+v", kept, tc.poll, bot) + } + }) + } +} + +func TestEnqueueAndLeaseUserNotices(t *testing.T) { + ctx := context.Background() + s := openUserNotify(t, "usr_u") + now := userNotifyNow + + n := testNotice("n1", "usr_u") + n.DraftID, n.IncidentID = "dr", "inc" + enqueue(t, s, n) + dup := testNotice("n1-again", "usr_u") + dup.Dedupe = n.Dedupe + if ok, err := s.EnqueueUserNotice(ctx, dup); err != nil || ok { + t.Fatalf("dedupe: %v %v", ok, err) + } + if c := countT(t, s, `SELECT count(*) FROM user_notice`); c != 1 { + t.Fatalf("%d rows after a duplicate", c) + } + if got := noticeRow(t, s, "n1"); got.DraftID != "dr" || got.IncidentID != "inc" || got.TGMessageRefs != "{}" { + t.Fatalf("stored: %+v", got) + } + plain := testNotice("plain", "usr_u") + enqueue(t, s, plain) + if c := countT(t, s, `SELECT count(*) FROM user_notice WHERE draft_id IS NULL AND incident_id IS NULL`); c != 1 { + t.Fatalf("a notice with no references stores NULL, not '': %d", c) + } + execT(t, s, `DELETE FROM user_notice`) + + // which rows a lease takes: due, unfinished, approved or needing no approval, not held, most overdue first + later := testNotice("later", "usr_u") + later.DueAt = now.Add(time.Hour) + pending := testNotice("pending", "usr_u") + pending.Approval = UserNoticeApprovalPending + approved := testNotice("approved", "usr_u") + approved.Approval = UserNoticeApprovalApproved + old := testNotice("old", "usr_u") + old.DueAt = now.Add(-time.Hour) + for _, n := range []UserNotice{later, pending, approved, old, testNotice("plain", "usr_u"), testNotice("finished", "usr_u")} { + enqueue(t, s, n) + } + execT(t, s, `UPDATE user_notice SET done_at = 5, result = 'sent' WHERE id = 'finished'`) + first, err := s.LeaseDueUserNotices(ctx, now, time.Minute, 10) + if err != nil || len(first) != 3 || first[0].ID != "old" || first[1].ID != "approved" || first[2].ID != "plain" { + t.Fatalf("first lease: %+v %v", first, err) + } + for _, n := range first { + if n.LeaseID == "" || n.LeaseID != first[0].LeaseID || !n.LeaseUntil.Equal(now.Add(time.Minute)) { + t.Fatalf("lease of %s: %q until %v", n.ID, n.LeaseID, n.LeaseUntil) + } + } + if ids := leaseIDs(t, s, now, 10); len(ids) != 0 { + t.Fatalf("rows leased twice: %v", ids) + } + if ids := leaseIDs(t, s, now, 0); ids != nil { + t.Fatalf("limit 0: %v", ids) + } + // the lease ran out: the rows come back with a new lease id, and the old holder is stale + again, err := s.LeaseDueUserNotices(ctx, now.Add(time.Minute), time.Minute, 10) + if err != nil || len(again) != 3 || again[0].LeaseID == first[0].LeaseID { + t.Fatalf("expired lease: %+v %v", again, err) + } + if ok, err := s.FinishUserNotice(ctx, "old", first[0].LeaseID, now, UserNoticeSent, 1, "{}"); err != nil || ok { + t.Fatalf("finish with a stale lease: %v %v", ok, err) + } + if ok, err := s.RetryUserNotice(ctx, "old", first[0].LeaseID, now, 1, "{}"); err != nil || ok { + t.Fatalf("retry with a stale lease: %v %v", ok, err) + } + if ok, err := s.FinishUserNotice(ctx, "old", "", now, UserNoticeSent, 1, "{}"); err != nil || ok { + t.Fatalf("finish with no lease id: %v %v", ok, err) + } + if _, err := s.FinishUserNotice(ctx, "old", again[0].LeaseID, now, "", 0, ""); !errors.Is(err, ErrUserNoticeResult) { + t.Fatalf("finish with no result: %v", err) + } + + // finish keeps the result and the message ids; a finished row is not leased again + if ok, err := s.FinishUserNotice(ctx, "old", again[0].LeaseID, now.Add(time.Minute), UserNoticeSent, 2, `{"utc_1":5}`); err != nil || !ok { + t.Fatalf("finish: %v %v", ok, err) + } + if ok, _ := s.FinishUserNotice(ctx, "old", again[0].LeaseID, now, UserNoticeSent, 2, "{}"); ok { + t.Fatal("a finished notice finished twice") + } + if got := noticeRow(t, s, "old"); got.Result != UserNoticeSent || got.TGSent != 2 || got.TGMessageRefs != `{"utc_1":5}` || got.LeaseID != "" || + !got.DoneAt.Equal(now.Add(time.Minute)) { + t.Fatalf("finished: %+v", got) + } + // retry gives the lease back, later, with the attempts and the message ids so far + retryAt := now.Add(10 * time.Minute) + if ok, err := s.RetryUserNotice(ctx, "approved", again[1].LeaseID, retryAt, 1, `{"utc_1":6}`); err != nil || !ok { + t.Fatalf("retry: %v %v", ok, err) + } + if got := noticeRow(t, s, "approved"); got.Attempts != 1 || !got.DueAt.Equal(retryAt) || got.LeaseID != "" || got.TGMessageRefs != `{"utc_1":6}` || !got.DoneAt.IsZero() { + t.Fatalf("retried: %+v", got) + } + if ids := leaseIDs(t, s, now.Add(90*time.Second), 10); len(ids) != 0 { // the others are held or finished + t.Fatalf("a retry is due early: %v", ids) + } + if ids := leaseIDs(t, s, retryAt, 10); !sameIDs(ids, "plain", "approved") { // plain: its lease ran out + t.Fatalf("lease of the retry: %v", ids) + } +} + +// Four workers lease one queue: every row goes to exactly one of them. +func TestLeaseDueUserNoticesConcurrent(t *testing.T) { + ctx := context.Background() + s := openUserNotify(t, "usr_u") + const total = 60 + for i := range total { + enqueue(t, s, testNotice(fmt.Sprintf("n%02d", i), "usr_u")) + } + var mu sync.Mutex + taken := map[string]int{} + var wg sync.WaitGroup + for range 4 { + wg.Add(1) + go func() { + defer wg.Done() + for { + got, err := s.LeaseDueUserNotices(ctx, userNotifyNow, time.Hour, 7) + if err != nil { + t.Error(err) + return + } + if len(got) == 0 { + return + } + mu.Lock() + for _, n := range got { + taken[n.ID]++ + } + mu.Unlock() + } + }() + } + wg.Wait() + if len(taken) != total { + t.Fatalf("%d of %d rows leased", len(taken), total) + } + for id, n := range taken { + if n != 1 { + t.Fatalf("%s leased %d times", id, n) + } + } +} + +// The owner's answer to a draft: one row, or every row of the draft; a dismissed or an expired draft is finished, so retention +// takes it, and what is decided cannot be decided again. +func TestUserNoticeApproval(t *testing.T) { + ctx := context.Background() + s := openUserNotify(t, "usr_u", "usr_v", "usr_w") + now := userNotifyNow + draftRow := func(id, user, draft string, created time.Time) { + n := testNotice(id, user) + n.DraftID, n.Approval, n.CreatedAt = draft, UserNoticeApprovalPending, created + enqueue(t, s, n) + } + // one draft of an incident reaches three people; another draft reaches one; one more row has no draft + draftRow("a1", "usr_u", "dr_a", now) + draftRow("a2", "usr_v", "dr_a", now.Add(time.Minute)) + draftRow("a3", "usr_w", "dr_a", now.Add(2*time.Minute)) + draftRow("b1", "usr_u", "dr_b", now) + draftRow("solo", "usr_u", "", now) + approval := func(id string) string { return noticeRow(t, s, id).Approval } + + if n, err := s.SetUserNoticeApprovalByDraft(ctx, "dr_a", UserNoticeApprovalPending, "", now); !errors.Is(err, ErrUserNoticeApproval) || n != 0 { + t.Fatalf("a decision that is neither approve nor dismiss: %d %v", n, err) + } + if ids := leaseIDs(t, s, now, 10); len(ids) != 0 { + t.Fatalf("a draft that waits was leased: %v", ids) + } + + // approve the whole draft with the owner's text; the other draft and the row with no draft wait on + if n, err := s.SetUserNoticeApprovalByDraft(ctx, "dr_a", UserNoticeApprovalApproved, "own words", now); err != nil || n != 3 { + t.Fatalf("approve draft: %d %v", n, err) + } + for _, id := range []string{"a1", "a2", "a3"} { + if got := noticeRow(t, s, id); got.Approval != UserNoticeApprovalApproved || got.ApprovalText != "own words" || !got.DoneAt.IsZero() { + t.Fatalf("%s: %+v", id, got) + } + } + if approval("b1") != UserNoticeApprovalPending || approval("solo") != UserNoticeApprovalPending { + t.Fatal("the approval of one draft reached another") + } + if ids := leaseIDs(t, s, now.Add(time.Minute), 10); !sameIDs(ids, "a1", "a2", "a3") { + t.Fatalf("leased after approval: %v", ids) + } + if n, err := s.SetUserNoticeApprovalByDraft(ctx, "dr_a", UserNoticeApprovalDismissed, "", now); err != nil || n != 0 { + t.Fatalf("dismiss of a decided draft: %d %v", n, err) + } + + // dismiss one row, then the other draft + if ok, err := s.SetUserNoticeApproval(ctx, "solo", UserNoticeApprovalDismissed, "", now.Add(time.Minute)); err != nil || !ok { + t.Fatalf("dismiss: %v %v", ok, err) + } + if ok, _ := s.SetUserNoticeApproval(ctx, "solo", UserNoticeApprovalApproved, "", now); ok { + t.Fatal("a dismissed notice was approved") + } + if _, err := s.SetUserNoticeApproval(ctx, "b1", "maybe", "", now); !errors.Is(err, ErrUserNoticeApproval) { + t.Fatalf("unknown decision: %v", err) + } + if got := noticeRow(t, s, "solo"); got.Approval != UserNoticeApprovalDismissed || got.Result != UserNoticeDismissed || !got.DoneAt.Equal(now.Add(time.Minute)) { + t.Fatalf("dismissed: %+v", got) + } + if n, err := s.SetUserNoticeApprovalByDraft(ctx, "dr_b", UserNoticeApprovalDismissed, "", now); err != nil || n != 1 { + t.Fatalf("dismiss draft: %d %v", n, err) + } + if ids := leaseIDs(t, s, now.Add(90*time.Second), 10); len(ids) != 0 { // a1 to a3 are still held + t.Fatalf("dismissed rows leased: %v", ids) + } + // a dismissed row is finished, so retention removes it + if n, err := s.PurgeUserNotices(ctx, now.Add(time.Hour)); err != nil || n != 2 { + t.Fatalf("purge dismissed: %d %v", n, err) + } + if left := countT(t, s, `SELECT count(*) FROM user_notice WHERE approval IN ('dismissed', 'expired')`); left != 0 { + t.Fatalf("%d dismissed rows survived the purge", left) + } +} + +// A draft the owner left unanswered burns whole, from the creation of its rows. +func TestExpireUserNoticeApprovals(t *testing.T) { + ctx := context.Background() + s := openUserNotify(t, "usr_u", "usr_v") + now := userNotifyNow + const ttl = 30 * time.Minute + pending := func(id, user, draft string, created time.Time) { + n := testNotice(id, user) + n.DraftID, n.Approval, n.CreatedAt = draft, UserNoticeApprovalPending, created + enqueue(t, s, n) + } + pending("old-1", "usr_u", "dr_old", now.Add(-time.Hour)) + pending("old-2", "usr_v", "dr_old", now.Add(-10*time.Minute)) // enqueued later, but its draft is past the time + pending("fresh", "usr_u", "dr_fresh", now.Add(-10*time.Minute)) + pending("solo-old", "usr_v", "", now.Add(-time.Hour)) + pending("solo-fresh", "usr_v", "", now) + if n, err := s.ExpireUserNoticeApprovals(ctx, now, ttl); err != nil || n != 3 { + t.Fatalf("expire: %d %v", n, err) + } + for id, want := range map[string]string{"old-1": UserNoticeApprovalExpired, "old-2": UserNoticeApprovalExpired, "solo-old": UserNoticeApprovalExpired, + "fresh": UserNoticeApprovalPending, "solo-fresh": UserNoticeApprovalPending} { + got := noticeRow(t, s, id) + if got.Approval != want || (want == UserNoticeApprovalExpired) != (got.Result == UserNoticeExpired && got.DoneAt.Equal(now)) { + t.Fatalf("%s: %+v", id, got) + } + } + if n, err := s.ExpireUserNoticeApprovals(ctx, now, ttl); err != nil || n != 0 { + t.Fatalf("expire twice: %d %v", n, err) + } + if ok, _ := s.SetUserNoticeApproval(ctx, "old-1", UserNoticeApprovalApproved, "", now); ok { + t.Fatal("an expired draft was approved") + } + if n, err := s.SetUserNoticeApprovalByDraft(ctx, "dr_old", UserNoticeApprovalApproved, "", now); err != nil || n != 0 { + t.Fatalf("approve of an expired draft: %d %v", n, err) + } + // finished rows leave with the retention purge; the waiting ones stay + if n, err := s.PurgeUserNotices(ctx, now.Add(time.Second)); err != nil || n != 3 { + t.Fatalf("purge expired: %d %v", n, err) + } + if left := countT(t, s, `SELECT count(*) FROM user_notice`); left != 2 { + t.Fatalf("%d rows left, want the two that wait", left) + } +} + +func TestPurgeUserNotices(t *testing.T) { + ctx := context.Background() + s := openUserNotify(t, "usr_u") + for id, done := range map[string]int64{"unfinished": 0, "old": 100, "edge": 200, "new": 300} { + enqueue(t, s, testNotice(id, "usr_u")) + if done > 0 { + execT(t, s, `UPDATE user_notice SET done_at = ?, result = 'sent' WHERE id = ?`, done, id) + } + } + if n, err := s.PurgeUserNotices(ctx, time.Unix(200, 0)); err != nil || n != 1 { + t.Fatalf("purge: %d %v", n, err) + } + if n, err := s.PurgeUserNotices(ctx, time.Unix(1000, 0)); err != nil || n != 2 { + t.Fatalf("purge the rest: %d %v", n, err) + } + if left := countT(t, s, `SELECT count(*) FROM user_notice WHERE id = 'unfinished'`); left != 1 { + t.Fatal("an unfinished notice was purged") + } +} + +func TestUserAppNotices(t *testing.T) { + ctx := context.Background() + s := openUserNotify(t, "usr_u", "usr_v") + now := userNotifyNow + add := func(id, user string, edit func(*UserNotice)) { + n := testNotice(id, user) + edit(&n) + enqueue(t, s, n) + } + app := func(n *UserNotice) { n.Channels = UserNoticeApp } + add("visible", "usr_u", func(n *UserNotice) { app(n); n.CreatedAt = now.Add(-time.Hour) }) + add("both channels", "usr_u", func(n *UserNotice) { n.CreatedAt = now.Add(-2 * time.Hour) }) + add("approved", "usr_u", func(n *UserNotice) { + app(n) + n.Approval = UserNoticeApprovalApproved + n.CreatedAt = now.Add(-3 * time.Hour) + }) + add("telegram only", "usr_u", func(n *UserNotice) { n.Channels = UserNoticeTelegram }) + add("pending", "usr_u", func(n *UserNotice) { app(n); n.Approval = UserNoticeApprovalPending }) + add("dismissed", "usr_u", func(n *UserNotice) { app(n); n.Approval = UserNoticeApprovalPending }) + add("not due", "usr_u", func(n *UserNotice) { app(n); n.DueAt = now.Add(time.Minute) }) + add("too old", "usr_u", func(n *UserNotice) { app(n); n.CreatedAt = now.Add(-7*24*time.Hour - time.Second) }) + add("stale", "usr_u", func(n *UserNotice) { app(n) }) + add("someone else's", "usr_v", func(n *UserNotice) { app(n) }) + if ok, err := s.SetUserNoticeApproval(ctx, "dismissed", UserNoticeApprovalDismissed, "", now); err != nil || !ok { + t.Fatalf("dismiss: %v %v", ok, err) + } + execT(t, s, `UPDATE user_notice SET done_at = 5, result = 'skipped_stale' WHERE id = 'stale'`) + got, err := s.UserAppNotices(ctx, "usr_u", now) + var ids []string + for _, n := range got { + ids = append(ids, n.ID) + } + if err != nil || !sameIDs(ids, "visible", "both channels", "approved") { + t.Fatalf("app notices: %v %v", ids, err) + } + // at most 20, the newest first + for i := range 25 { + add(fmt.Sprintf("bulk-%02d", i), "usr_v", func(n *UserNotice) { app(n); n.CreatedAt = now.Add(-time.Duration(i) * time.Minute) }) + } + got, err = s.UserAppNotices(ctx, "usr_v", now) + if err != nil || len(got) != 20 || got[0].ID != "someone else's" { + t.Fatalf("bulk: %d %v", len(got), err) + } + for i := 1; i < len(got); i++ { + if got[i].CreatedAt.After(got[i-1].CreatedAt) { + t.Fatalf("not newest first at %d", i) + } + } +} + +func TestUserIncidents(t *testing.T) { + ctx := context.Background() + s := openUserNotify(t, "usr_u", "usr_v") + now := userNotifyNow + incident := func(id, user string) UserIncident { + return UserIncident{ID: id, UserID: user, OpenedAt: now, NodesJSON: `["nod_a"]`} + } + if _, err := s.UserOpenIncident(ctx, "usr_u"); !errors.Is(err, ErrNotFound) { + t.Fatalf("no incident: %v", err) + } + opened, err := s.OpenUserIncident(ctx, incident("inc_1", "usr_u")) + if err != nil || opened.ID != "inc_1" || !opened.OpenedAt.Equal(now) || !opened.ResolvedAt.IsZero() || opened.NoticeID != "" || opened.NodesJSON != `["nod_a"]` { + t.Fatalf("open: %+v %v", opened, err) + } + // a second one for the person is refused and the open one comes back, in the same call + again, err := s.OpenUserIncident(ctx, UserIncident{ID: "inc_2", UserID: "usr_u", OpenedAt: now.Add(time.Hour), NodesJSON: "[]", NoticeID: "not_x"}) + if !errors.Is(err, ErrUserIncidentOpen) || again.ID != "inc_1" { + t.Fatalf("second open: %+v %v", again, err) + } + if c := countT(t, s, `SELECT count(*) FROM user_incident`); c != 1 { + t.Fatalf("%d incidents", c) + } + if other, err := s.OpenUserIncident(ctx, UserIncident{ID: "inc_v", UserID: "usr_v", OpenedAt: now, NodesJSON: "[]", NoticeID: "not_v"}); err != nil || other.NoticeID != "not_v" { + t.Fatalf("another person: %+v %v", other, err) + } + if got, err := s.UserOpenIncident(ctx, "usr_u"); err != nil || got.ID != "inc_1" { + t.Fatalf("open incident: %+v %v", got, err) + } + // resolved: the slot is free again, and a resolved incident resolves once + if ok, err := s.ResolveUserIncident(ctx, "inc_1", now.Add(20*time.Minute)); err != nil || !ok { + t.Fatalf("resolve: %v %v", ok, err) + } + if ok, _ := s.ResolveUserIncident(ctx, "inc_1", now.Add(time.Hour)); ok { + t.Fatal("resolved twice") + } + if ok, _ := s.ResolveUserIncident(ctx, "inc_none", now); ok { + t.Fatal("resolved an unknown incident") + } + if _, err := s.UserOpenIncident(ctx, "usr_u"); !errors.Is(err, ErrNotFound) { + t.Fatalf("open after resolve: %v", err) + } + if next, err := s.OpenUserIncident(ctx, incident("inc_3", "usr_u")); err != nil || next.ID != "inc_3" { + t.Fatalf("open after resolve: %+v %v", next, err) + } + // retention takes the resolved ones only + if n, err := s.PurgeUserIncidents(ctx, now.Add(time.Hour)); err != nil || n != 1 { + t.Fatalf("purge: %d %v", n, err) + } + if c := countT(t, s, `SELECT count(*) FROM user_incident`); c != 2 { + t.Fatalf("%d incidents left, want the two open ones", c) + } +} + +func TestUserNotifySettings(t *testing.T) { + ctx := context.Background() + s := openUserNotify(t, "usr_u", "usr_v") + for _, key := range []string{"chat_limit", "retention_days"} { + if err := s.SetUserNotifySetting(ctx, key, "3"); err != nil { + t.Fatal(err) + } + } + if err := s.SetUserNotifySetting(ctx, "chat_limit", "5"); err != nil { + t.Fatal(err) + } + if err := s.DeleteUserNotifySetting(ctx, "retention_days"); err != nil { + t.Fatal(err) + } + if got, err := s.UserNotifySettings(ctx); err != nil || fmt.Sprint(got) != "map[chat_limit:5]" { + t.Fatalf("settings: %v %v", got, err) + } + for _, o := range []struct{ user, key, value string }{{"usr_u", "chat_limit", "1"}, {"usr_u", "off", `["torrent"]`}, {"usr_v", "chat_limit", "9"}, {"usr_u", "chat_limit", "2"}} { + if err := s.SetUserNotifyOverride(ctx, o.user, o.key, o.value); err != nil { + t.Fatal(err) + } + } + if err := s.SetUserNotifyOverride(ctx, "usr_nobody", "chat_limit", "1"); !errors.Is(err, ErrNotFound) { + t.Fatalf("override of no person: %v", err) + } + if err := s.DeleteUserNotifyOverride(ctx, "usr_u", "off"); err != nil { + t.Fatal(err) + } + if got, err := s.UserNotifyOverrides(ctx, "usr_u"); err != nil || fmt.Sprint(got) != "map[chat_limit:2]" { + t.Fatalf("overrides: %v %v", got, err) + } + if got, err := s.UserNotifyOverrides(ctx, "usr_v"); err != nil || fmt.Sprint(got) != "map[chat_limit:9]" { + t.Fatalf("overrides of the other person: %v %v", got, err) + } + // the defaults live in the code + if kinds := DefaultUserNoticeKinds(); len(kinds) != 13 || kinds["incident_all_down"].Mode != "ask" || kinds["expired"].Mode != "auto" || !kinds["expired"].Loud { + t.Fatalf("default kinds: %+v", kinds) + } +} + +// Deleting a person deletes everything about the person. +func TestUserNotifyCascade(t *testing.T) { + ctx := context.Background() + s := openUserNotify(t, "usr_u", "usr_v") + if _, err := s.SetUserTelegramBot(ctx, UserTelegramBot{Token: []byte("sealed"), BotID: 1, Username: "bot"}, userNotifyNow); err != nil { + t.Fatal(err) + } + for _, user := range []string{"usr_u", "usr_v"} { + if err := s.LinkUserTelegramChat(ctx, user, []byte(user), []byte("sealed"), "en", 3, userNotifyNow); err != nil { + t.Fatal(err) + } + if err := s.SetUserTelegramCode(ctx, fmt.Sprintf("%064s", user), user, userNotifyNow.Add(time.Hour)); err != nil { + t.Fatal(err) + } + enqueue(t, s, testNotice("n-"+user, user)) + if _, err := s.OpenUserIncident(ctx, UserIncident{ID: "inc-" + user, UserID: user, OpenedAt: userNotifyNow, NodesJSON: "[]"}); err != nil { + t.Fatal(err) + } + if err := s.SetUserNotifyOverride(ctx, user, "chat_limit", "1"); err != nil { + t.Fatal(err) + } + } + execT(t, s, `DELETE FROM user WHERE id = 'usr_u'`) + for _, table := range []string{"user_telegram_chat", "user_telegram_code", "user_notice", "user_incident", "user_notify_override"} { + if n := countT(t, s, `SELECT count(*) FROM `+table+` WHERE user_id = 'usr_u'`); n != 0 { + t.Errorf("%s: %d rows of the deleted person", table, n) + } + if n := countT(t, s, `SELECT count(*) FROM `+table+` WHERE user_id = 'usr_v'`); n != 1 { + t.Errorf("%s: %d rows of the other person", table, n) + } + } + if _, err := s.UserTelegramBot(ctx); err != nil { + t.Fatalf("the bot went with a person: %v", err) + } +} + +// Migration 00165 goes up and down, and down removes every table it made. +func TestUserNotifyMigrationUpDown(t *testing.T) { + ctx := context.Background() + s, p := openProvider(t) + if _, err := p.UpTo(ctx, 164); err != nil { + t.Fatal(err) + } + tables := []string{"user_telegram_bot", "user_telegram_chat", "user_telegram_code", "user_notice", "user_incident", "user_notify_setting", "user_notify_override"} + present := func(want int) { + t.Helper() + for _, name := range tables { + if n := countT(t, s, `SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = ?`, name); n != want { + t.Fatalf("table %s: %d, want %d", name, n, want) + } + } + } + present(0) + if _, err := p.Up(ctx); err != nil { + t.Fatal(err) + } + present(1) + if _, err := p.DownTo(ctx, 164); err != nil { + t.Fatal(err) + } + present(0) + if _, err := p.Up(ctx); err != nil { + t.Fatal(err) + } + present(1) +} diff --git a/internal/panel/store/user_telegram.go b/internal/panel/store/user_telegram.go new file mode 100644 index 00000000..e6c12b72 --- /dev/null +++ b/internal/panel/store/user_telegram.go @@ -0,0 +1,271 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "time" +) + +// The Telegram side of the notifications to people: the bot of its own, the chats of the people who linked one and their +// one-time link codes. Tables: migration 00165. A chat belongs to a bot, so a different bot (or none) drops every link, every +// pending code and the Telegram channel of the notices still waiting, all in the same transaction. + +var ( + // ErrUserTelegramChatLimit: the person already has as many chats as the limit allows. + ErrUserTelegramChatLimit = errors.New("store: user telegram chat limit reached") + // ErrUserTelegramChatTaken: the chat is linked to another person. + ErrUserTelegramChatTaken = errors.New("store: user telegram chat already linked") +) + +// UserTelegramBot is the stored bot of the notifications to people. Token is vault ciphertext and must never be returned by an +// RPC. Offset, LastError and LastOK are the state of the poller, for the card of the bot. +type UserTelegramBot struct { + Token []byte + BotID int64 + Username string + UpdatedAt time.Time + Offset int64 + LastError string + LastOK time.Time +} + +// UserTelegramBot is the stored bot; ErrNotFound when none is set. +func (s *Store) UserTelegramBot(ctx context.Context) (UserTelegramBot, error) { + var b UserTelegramBot + var updated, lastOK int64 + err := s.R.QueryRowContext(ctx, `SELECT token, bot_id, username, updated_at, poll_offset, last_error, last_ok + FROM user_telegram_bot WHERE id = 1`).Scan(&b.Token, &b.BotID, &b.Username, &updated, &b.Offset, &b.LastError, &lastOK) + if errors.Is(err, sql.ErrNoRows) { + return UserTelegramBot{}, ErrNotFound + } + if err != nil { + return UserTelegramBot{}, err + } + b.UpdatedAt, b.LastOK = fromUnix(updated), unixTime(lastOK) + return b, nil +} + +// resetUserTelegramStmts drop what belongs to the bot stored now, unless it is the bot with id botID: its chats, its pending +// link codes, and the Telegram channel of the notices that have not finished (a notice for Telegram only goes, one for both +// channels keeps the app). The first statement's RowsAffected is the number of chats dropped. They must run before the bot row +// changes, because they read it. +func resetUserTelegramStmts(botID int64) []Stmt { + other := `NOT EXISTS (SELECT 1 FROM user_telegram_bot WHERE id = 1 AND bot_id = ?)` + return []Stmt{ + {Query: `DELETE FROM user_telegram_chat WHERE ` + other, Args: []any{botID}}, + {Query: `DELETE FROM user_telegram_code WHERE ` + other, Args: []any{botID}}, + {Query: `DELETE FROM user_notice WHERE done_at = 0 AND channels = ? AND ` + other, Args: []any{UserNoticeTelegram, botID}}, + {Query: `UPDATE user_notice SET channels = channels & ~? WHERE done_at = 0 AND (channels & ?) <> 0 AND ` + other, + Args: []any{UserNoticeTelegram, UserNoticeTelegram, botID}}, + } +} + +// SetUserTelegramBot stores the bot (token, id and username; the poller's state is kept for the same bot and zeroed for another). +// When it is another bot than the one stored, every chat, pending code and Telegram delivery goes with the old one; dropped says +// how many chats went. +func (s *Store) SetUserTelegramBot(ctx context.Context, b UserTelegramBot, now time.Time) (dropped int, err error) { + stmts := append(resetUserTelegramStmts(b.BotID), Stmt{Query: `INSERT INTO user_telegram_bot (id, token, bot_id, username, updated_at) + VALUES (1, ?, ?, ?, ?) + ON CONFLICT(id) DO UPDATE SET token = excluded.token, username = excluded.username, updated_at = excluded.updated_at, + poll_offset = CASE WHEN bot_id = excluded.bot_id THEN poll_offset ELSE 0 END, + last_error = CASE WHEN bot_id = excluded.bot_id THEN last_error ELSE '' END, + last_ok = CASE WHEN bot_id = excluded.bot_id THEN last_ok ELSE 0 END, + bot_id = excluded.bot_id`, + Args: []any{b.Token, b.BotID, b.Username, unix(now)}}) + results, err := s.batch(ctx, stmts...) + if err != nil { + return 0, err + } + return int(results[0].RowsAffected), nil +} + +// ClearUserTelegramBot forgets the bot, every chat, every pending code and the Telegram channel of the unfinished notices (the +// app keeps its events); dropped says how many chats went. +func (s *Store) ClearUserTelegramBot(ctx context.Context) (dropped int, err error) { + results, err := s.batch(ctx, + // bot id 0 is no bot's id, so every row counts as another bot's + append(resetUserTelegramStmts(0), Stmt{Query: `DELETE FROM user_telegram_bot`})...) + if err != nil { + return 0, err + } + return int(results[0].RowsAffected), nil +} + +// SaveUserTelegramBotPoll stores the state of the poller: the next offset, the code of the last failure ("" after a success) +// and the time of the last success (zero: keep the stored one). False when no bot is set. +func (s *Store) SaveUserTelegramBotPoll(ctx context.Context, offset int64, lastError string, lastOK time.Time) (bool, error) { + r, err := s.W.ExecContext(ctx, `UPDATE user_telegram_bot SET poll_offset = ?, last_error = ?, last_ok = max(last_ok, ?) WHERE id = 1`, + offset, lastError, unixOrZero(lastOK)) + if err != nil { + return false, err + } + n, err := r.RowsAffected() + return n > 0, err +} + +// UserTelegramChat is one chat of a person. ChatEnc is vault ciphertext of the chat id, ChatMAC its keyed MAC. +type UserTelegramChat struct { + ID, UserID string + ChatMAC, ChatEnc []byte + Lang string + Muted bool // announcements are off + LinkedAt, LastSentAt time.Time +} + +const userTelegramChatColumns = `id, user_id, chat_mac, chat_enc, lang, muted, linked_at, last_sent_at` + +func scanUserTelegramChat(row rowScanner) (UserTelegramChat, error) { + var c UserTelegramChat + var linked, lastSent int64 + if err := row.Scan(&c.ID, &c.UserID, &c.ChatMAC, &c.ChatEnc, &c.Lang, &c.Muted, &linked, &lastSent); err != nil { + return UserTelegramChat{}, err + } + c.LinkedAt, c.LastSentAt = fromUnix(linked), unixTime(lastSent) + return c, nil +} + +// LinkUserTelegramChat links a chat to a person unless the person already has limit chats (ErrUserTelegramChatLimit) or the +// chat belongs to another person (ErrUserTelegramChatTaken); ErrNotFound: no such person. The limit is part of the insert +// itself, so two calls at once cannot both take the last slot. A chat the person has linked already passes without a change. +func (s *Store) LinkUserTelegramChat(ctx context.Context, user string, mac, enc []byte, lang string, limit int, now time.Time) error { + r, err := s.W.ExecContext(ctx, `INSERT INTO user_telegram_chat (id, user_id, chat_mac, chat_enc, lang, linked_at) + SELECT ?, ?, ?, ?, ?, ? WHERE EXISTS (SELECT 1 FROM user WHERE id = ?) + AND (SELECT count(*) FROM user_telegram_chat WHERE user_id = ?) < ? + ON CONFLICT(chat_mac) DO NOTHING`, + NewID("utc_"), user, mac, enc, lang, unix(now), user, user, limit) + if err != nil { + return err + } + if n, err := r.RowsAffected(); err != nil { + return err + } else if n > 0 { + return nil + } + var owner string + var userExists bool + if err := s.W.QueryRowContext(ctx, `SELECT COALESCE((SELECT user_id FROM user_telegram_chat WHERE chat_mac = ?), ''), + EXISTS (SELECT 1 FROM user WHERE id = ?)`, mac, user).Scan(&owner, &userExists); err != nil { + return err + } + switch { + case owner == user: + return nil + case owner != "": + return ErrUserTelegramChatTaken + case !userExists: + return ErrNotFound + default: + return ErrUserTelegramChatLimit + } +} + +// UserTelegramChats lists a person's chats, the oldest first. +func (s *Store) UserTelegramChats(ctx context.Context, user string) ([]UserTelegramChat, error) { + rows, err := s.R.QueryContext(ctx, `SELECT `+userTelegramChatColumns+` FROM user_telegram_chat WHERE user_id = ? ORDER BY linked_at, id`, user) + if err != nil { + return nil, err + } + defer rows.Close() + var out []UserTelegramChat + for rows.Next() { + c, err := scanUserTelegramChat(rows) + if err != nil { + return nil, err + } + out = append(out, c) + } + return out, rows.Err() +} + +// UserTelegramChatByMAC is the chat with this MAC (what a message from the chat is looked up by); ErrNotFound when it is not linked. +func (s *Store) UserTelegramChatByMAC(ctx context.Context, mac []byte) (UserTelegramChat, error) { + c, err := scanUserTelegramChat(s.R.QueryRowContext(ctx, `SELECT `+userTelegramChatColumns+` FROM user_telegram_chat WHERE chat_mac = ?`, mac)) + if errors.Is(err, sql.ErrNoRows) { + return UserTelegramChat{}, ErrNotFound + } + return c, err +} + +// CountUserTelegramChats is how many chats a person has linked. +func (s *Store) CountUserTelegramChats(ctx context.Context, user string) (int, error) { + var n int + err := s.R.QueryRowContext(ctx, `SELECT count(*) FROM user_telegram_chat WHERE user_id = ?`, user).Scan(&n) + return n, err +} + +// UnlinkUserTelegramChat forgets a person's chat; it reports whether there was one. +func (s *Store) UnlinkUserTelegramChat(ctx context.Context, user, id string) (bool, error) { + return s.deleteUserTelegramChat(ctx, `DELETE FROM user_telegram_chat WHERE user_id = ? AND id = ?`, user, id) +} + +// UnlinkUserTelegramChatByMAC forgets the chat with this MAC (the person sent /stop, or blocked the bot); it reports whether +// there was one. +func (s *Store) UnlinkUserTelegramChatByMAC(ctx context.Context, mac []byte) (bool, error) { + return s.deleteUserTelegramChat(ctx, `DELETE FROM user_telegram_chat WHERE chat_mac = ?`, mac) +} + +func (s *Store) deleteUserTelegramChat(ctx context.Context, query string, args ...any) (bool, error) { + r, err := s.W.ExecContext(ctx, query, args...) + if err != nil { + return false, err + } + n, err := r.RowsAffected() + return n > 0, err +} + +// SetUserTelegramChatMuted switches the announcements of a person's chat off (true) or on; ErrNotFound when there is no such chat. +func (s *Store) SetUserTelegramChatMuted(ctx context.Context, user, id string, muted bool) error { + return s.updateUserTelegramChat(ctx, `UPDATE user_telegram_chat SET muted = ? WHERE user_id = ? AND id = ?`, muted, user, id) +} + +// SetUserTelegramChatLang sets the language of the messages to a person's chat; ErrNotFound when there is no such chat. +func (s *Store) SetUserTelegramChatLang(ctx context.Context, user, id, lang string) error { + return s.updateUserTelegramChat(ctx, `UPDATE user_telegram_chat SET lang = ? WHERE user_id = ? AND id = ?`, lang, user, id) +} + +// SetUserTelegramChatLastSent records when the last message reached a person's chat; ErrNotFound when there is no such chat. +func (s *Store) SetUserTelegramChatLastSent(ctx context.Context, user, id string, now time.Time) error { + return s.updateUserTelegramChat(ctx, `UPDATE user_telegram_chat SET last_sent_at = ? WHERE user_id = ? AND id = ?`, unix(now), user, id) +} + +func (s *Store) updateUserTelegramChat(ctx context.Context, query string, args ...any) error { + r, err := s.W.ExecContext(ctx, query, args...) + if err != nil { + return err + } + if n, err := r.RowsAffected(); err != nil { + return err + } else if n == 0 { + return ErrNotFound + } + return nil +} + +// SetUserTelegramCode stores a one-time link code by its hash. A person has at most one pending code: a new one replaces it. +func (s *Store) SetUserTelegramCode(ctx context.Context, hash, user string, expires time.Time) error { + _, err := s.W.ExecContext(ctx, `INSERT INTO user_telegram_code (hash, user_id, expires_at) VALUES (?, ?, ?) + ON CONFLICT(user_id) DO UPDATE SET hash = excluded.hash, expires_at = excluded.expires_at`, hash, user, unix(expires)) + return err +} + +// HasPendingUserTelegramCode is the one-row check the edge tick uses before it starts a long poll. +func (s *Store) HasPendingUserTelegramCode(ctx context.Context, now time.Time) (bool, error) { + var one int + err := s.R.QueryRowContext(ctx, `SELECT 1 FROM user_telegram_code WHERE expires_at > ? LIMIT 1`, unix(now)).Scan(&one) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + return err == nil, err +} + +// TakeUserTelegramCode atomically consumes a code before it expires and returns its person; ErrNotFound when the code is +// unknown, spent or expired. DELETE ... RETURNING makes concurrent polls single use. +func (s *Store) TakeUserTelegramCode(ctx context.Context, hash string, now time.Time) (string, error) { + var user string + err := s.W.QueryRowContext(ctx, `DELETE FROM user_telegram_code WHERE hash = ? AND expires_at > ? RETURNING user_id`, hash, unix(now)).Scan(&user) + if errors.Is(err, sql.ErrNoRows) { + return "", ErrNotFound + } + return user, err +}