diff --git a/cmd/mistgate-edge/testdata/bridge.cjs b/cmd/mistgate-edge/testdata/bridge.cjs index 332164e4..04f8abd3 100644 --- a/cmd/mistgate-edge/testdata/bridge.cjs +++ b/cmd/mistgate-edge/testdata/bridge.cjs @@ -563,14 +563,14 @@ async function assertProvisioner(bytes, forwardPanel, adminCookie, initOptions, return countedJob("cron tick with installs", () => Promise.race([forwardPanel.cron({ at: at.getTime() }), wasmFailure])); }; await insertJob("prv_done", "failed"); - // 6 for the sweeps and settings, one read of the active rollout for the updates job, one Telegram pending-code check, one check for due notices to people, one + // 6 for the sweeps and settings, one read of the active rollout for the updates job, one Telegram pending-code check, one check for a chat of a person (the status notices), one check for due notices to people, one // cheburcheck and one bsbord settings read while off, one read of the proposals that apply and 12 for a warm evaluator pass (see "cron tick" below); nothing in an install wakes more. - assert.equal((await tick(3)).queries.sequentialQueries, 24); + assert.equal((await tick(3)).queries.sequentialQueries, 25); assert.equal(provisionKicks, 0, "a finished install wakes nothing"); for (const [i, state] of ["queued", "running", "cancel_requested"].entries()) { await globalThis.__d1.prepare("DELETE FROM node_provision_job WHERE id = 'prv_open'").run(); await insertJob("prv_open", state); - assert.equal((await tick(3)).queries.sequentialQueries, 24, "waking costs no query beyond the look"); + assert.equal((await tick(3)).queries.sequentialQueries, 25, "waking costs no query beyond the look"); assert.equal(provisionKicks, i + 1, `a ${state} install wakes the Provisioner`); } await globalThis.__d1.prepare("DELETE FROM node_provision_job").run(); @@ -1209,8 +1209,8 @@ async function run() { console.log(`D1 query count ${JSON.stringify(normalCronQueries)}`); assert.equal( normalCronQueries.sequentialQueries, - 29, - "a normal cron tick costs 29 D1 calls: 6 for the sweeps and the country settings, one read of the active rollout for the updates job, one Telegram pending-code check, one check for due notices to people, one cheburcheck and one bsbord settings read while off, one read of the proposals that apply (none: no lease), and 17 for the isolate's first evaluator pass: its lease, nodes, inbounds, live nodes, doctor results and acceptances, the signal batch, port checks, UDP path losses, active alerts, the interval setting (read with the silent-port result in one call), the update rollout, the country settings, the node-summary write and one batched external-source settings read, and the silent-port count of the hour (one batch of statistics and one write of the result: the fleet has servers to judge)", + 30, + "a normal cron tick costs 30 D1 calls: 6 for the sweeps and the country settings, one read of the active rollout for the updates job, one Telegram pending-code check, one check for a chat of a person (the status notices), one check for due notices to people, one cheburcheck and one bsbord settings read while off, one read of the proposals that apply (none: no lease), and 17 for the isolate's first evaluator pass: its lease, nodes, inbounds, live nodes, doctor results and acceptances, the signal batch, port checks, UDP path losses, active alerts, the interval setting (read with the silent-port result in one call), the update rollout, the country settings, the node-summary write and one batched external-source settings read, and the silent-port count of the hour (one batch of statistics and one write of the result: the fleet has servers to judge)", ); liveProjectionQueries = 0; @@ -1225,8 +1225,8 @@ async function run() { console.log(`D1 query count ${JSON.stringify(cronQueries)}`); assert.equal( cronQueries.sequentialQueries, - 26, - "one minute 10 cron tick costs 26 D1 calls: the 7 of the sweeps, the country settings and the fan-out live read, one read of the active rollout for the updates job, one Telegram pending-code check, one check for due notices to people, one Telegram bot check for the watcher, one cheburcheck and one bsbord settings read while off, one read of the proposals that apply (none: no lease), plus 12 for a warm evaluator pass (no nodes or inbounds read again, no summary write, the UDP path losses, and one batched external-source settings read)", + 27, + "one minute 10 cron tick costs 27 D1 calls: the 7 of the sweeps, the country settings and the fan-out live read, one read of the active rollout for the updates job, one Telegram pending-code check, one check for a chat of a person (the status notices), one check for due notices to people, one Telegram bot check for the watcher, one cheburcheck and one bsbord settings read while off, one read of the proposals that apply (none: no lease), plus 12 for a warm evaluator pass (no nodes or inbounds read again, no summary write, the UDP path losses, and one batched external-source settings read)", ); assert.equal(liveProjectionQueries, 3, "the node-down sweep, the evaluator and the ten-minute safety net each read live nodes once"); assert.equal(nodePokeCalls, 1, "the ten-minute safety net performs one remote fan-out"); @@ -1241,8 +1241,8 @@ async function run() { console.log(`D1 query count ${JSON.stringify(retentionQueries)}`); assert.equal( retentionQueries.sequentialQueries, - 46, - "a minute 17 cron tick costs 46 D1 calls: 6 for the sweeps and settings, one Telegram pending-code check, one check for due notices to people, one cheburcheck and one bsbord settings read while off, one read of the proposals that apply (none: no lease), 21 for retention (the batched retention settings read and thirteen prune statements, the prune of the proposals that ended 90 days ago among them, the one count read of orphan AWG path keys, the audit log, the hourly host load and the two hourly traffic tables among them), 12 for a warm evaluator pass (including the UDP path losses and one batched external-source settings read), and 2 for the updates job (the active rollout read and its history prune)", + 47, + "a minute 17 cron tick costs 47 D1 calls: 6 for the sweeps and settings, one Telegram pending-code check, one check for a chat of a person (the status notices), one check for due notices to people, one cheburcheck and one bsbord settings read while off, one read of the proposals that apply (none: no lease), 21 for retention (the batched retention settings read and thirteen prune statements, the prune of the proposals that ended 90 days ago among them, the one count read of orphan AWG path keys, the audit log, the hourly host load and the two hourly traffic tables among them), 12 for a warm evaluator pass (including the UDP path losses and one batched external-source settings read), and 2 for the updates job (the active rollout read and its history prune)", ); // The Overview is polled every 10 seconds. The health summary of every node is one settings row, read once: more connected diff --git a/edge/bridge/cron_js_test.go b/edge/bridge/cron_js_test.go index 53df8ef9..1e21a11e 100644 --- a/edge/bridge/cron_js_test.go +++ b/edge/bridge/cron_js_test.go @@ -135,12 +135,12 @@ func TestCronOpRunsEdgeTickAndReleasesFanout(t *testing.T) { awaitCronPromise(t, waitUntil) counts := binding.Call("__endQueryCount") ended = true - // Telegram adds two reads (a link code waiting, a notice to a person due) and updates one, the empty-owner watcher adds one, and + // Telegram adds three reads (a link code waiting, a chat of a person for the status notices, a notice to a person due) and updates one, the empty-owner watcher adds one, and // cheburcheck and bsbord each read their settings once while off. The proposals work adds one read (the proposals that apply: none) and, with none, no lease. // The rest is the four sweeps, two country settings and eight evaluator calls on an empty fleet. The evaluator pass reads // both external-source settings in one batched call, even while those sources are off. - if got := counts.Get("sequentialQueries").Int(); got != 22 { - t.Fatalf("cron used %d sequential D1 calls, want 22 (6 tick + updates read + Telegram code check + Telegram people's notices check + empty-owner watcher + one cheburcheck and one bsbord settings read + 8 evaluator on an empty fleet + one batched external settings read per evaluator pass + the proposals read)", got) + if got := counts.Get("sequentialQueries").Int(); got != 23 { + t.Fatalf("cron used %d sequential D1 calls, want 23 (6 tick + updates read + Telegram code check + Telegram people's chat check + Telegram people's notices check + empty-owner watcher + one cheburcheck and one bsbord settings read + 8 evaluator on an empty fleet + one batched external settings read per evaluator pass + the proposals read)", got) } if got := remote.pokeCount(); got != 1 { t.Fatalf("minute 10 remote fan-outs = %d, want 1", got) @@ -167,11 +167,11 @@ func TestCronOpRunsEdgeTickAndReleasesFanout(t *testing.T) { retentionEnded = true // The nodes are still warm in the isolate and the empty summary is unchanged, so the evaluator pass is six calls: its lease, // the signal batch, the active alerts, the interval setting, the update rollout and the country settings. Telegram's pending - // code check adds one read on every tick, and so does the check for a notice to a person that is due. The updates job adds the active rollout read, and its history prune at minute 17. + // code check adds one read on every tick, and so do the check for a chat of a person and the check for a notice to a person that is due. The updates job adds the active rollout read, and its history prune at minute 17. // The evaluator pass reads both external-source settings in one batched call, even while those sources are off. The proposals // work adds its read of the proposals that apply, and the retention one prune of the proposals that ended 90 days ago. - if got := retentionCounts.Get("sequentialQueries").Int(); got != 40 { - t.Fatalf("minute 17 cron used %d sequential D1 calls, want 40 (5 tick + 2 updates + Telegram code check + people's notices check + one cheburcheck and one bsbord settings read + 21 retention (the batched retention settings read, the two hourly traffic prunes, the orphan AWG path count and the proposals prune included) + 6 evaluator + one batched external settings read + the proposals read)", got) + if got := retentionCounts.Get("sequentialQueries").Int(); got != 41 { + t.Fatalf("minute 17 cron used %d sequential D1 calls, want 41 (5 tick + 2 updates + Telegram code check + people's chat check + people's notices check + one cheburcheck and one bsbord settings read + 21 retention (the batched retention settings read, the two hourly traffic prunes, the orphan AWG path count and the proposals prune included) + 6 evaluator + one batched external settings read + the proposals read)", got) } // Three batches: the node-down sweep's live read (every tick), the evaluator's signal batch and the daily rollup; the // prunes are single statements. diff --git a/internal/panel/app/edge_tick.go b/internal/panel/app/edge_tick.go index eff73562..fad8a643 100644 --- a/internal/panel/app/edge_tick.go +++ b/internal/panel/app/edge_tick.go @@ -28,7 +28,7 @@ var edgeTickJobs = map[string]string{ "cheburcheck": "one due cheburcheck source and node per tick; off means no site request", "bsbord": "one previewed, capped mobile reachability request when a round is due; off means no site request", "provision": "wakes the Provisioner every tick while an install is queued, running or being cancelled", - "telegram": "polls pending chat codes (the admins' bot, and the bot of the people while a link code of a person is waiting), checks the release and agent watcher every fifth tick, delivers queued messages, and sends the notices to people (one read while none is due)", + "telegram": "polls pending chat codes (the admins' bot, and the bot of the people while a link code of a person is waiting), checks the release and agent watcher every fifth tick, delivers queued messages, makes the status notices to people (one read while no person has a chat) and sends them (one read while none is due)", "updates": "advances the edge node rollout and scheduled update state machines", "proposals": "carries out the panel's accepted proposals (one read while none applies; the round lease is taken only when one does)", } @@ -143,7 +143,11 @@ func (p *Panel) EdgeTick(ctx context.Context, now time.Time) error { p.Telegram.FlushNow(ctx) return nil }) - // The people's bot: a bounded pass over the notices that are due, after the owner's messages. With none due it is one read. + // The people's bot: the status notices (term, quota) are made first, then a bounded pass sends what is due, after the owner's + // messages. With no chat of a person the first is one read; with none due the second is one read. + run("telegram user status", func(ctx context.Context) error { + return p.Telegram.ProduceUserStatus(ctx) + }) run("telegram user notices", func(ctx context.Context) error { return p.Telegram.SendUserNotices(ctx) }) diff --git a/internal/panel/store/d1_user_status_test.go b/internal/panel/store/d1_user_status_test.go new file mode 100644 index 00000000..42eec204 --- /dev/null +++ b/internal/panel/store/d1_user_status_test.go @@ -0,0 +1,7 @@ +//go:build js && wasm + +package store + +import "testing" + +func TestD1UserStatus(t *testing.T) { userStatusProof(t, openD1Store(t)) } diff --git a/internal/panel/store/transaction_shapes_test.go b/internal/panel/store/transaction_shapes_test.go index 16eaf3dc..813a3b5b 100644 --- a/internal/panel/store/transaction_shapes_test.go +++ b/internal/panel/store/transaction_shapes_test.go @@ -67,6 +67,7 @@ var transactionShape1 = map[string]string{ "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.", + "user_status.go:ProduceUserStatusNotices": "One fixed batch of INSERT ... SELECT statements, one per kind; the dedupe key makes each row once, so a repeat or a second worker writes nothing twice.", "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.", diff --git a/internal/panel/store/user_notice_kinds.go b/internal/panel/store/user_notice_kinds.go new file mode 100644 index 00000000..4337e4d4 --- /dev/null +++ b/internal/panel/store/user_notice_kinds.go @@ -0,0 +1,97 @@ +package store + +import ( + "encoding/json" + "sort" + "strings" +) + +// What a kind of notice does, from the code's defaults, the owner's global settings and one person's own. Two keys hold it: +// +// - user_notify_setting "notice.": a JSON object whose every field is optional, a field that is missing or not valid +// means its default: {"mode":"off|ask|auto","loud":true,"channels":3,"days":[3,1],"percent":80}. "days" (the days before the +// end of the term, for expiry_soon) and "percent" (of the quota, for quota_warn) belong to those two kinds only. +// - user_notify_override "notice_off": a JSON array of the kinds switched off for that person. + +const ( + UserNoticeSettingPrefix = "notice." + UserNoticeOffKey = "notice_off" +) + +// UserNoticeKindSettings is the resolved policy of one kind of notice for one person (or, with no person, for everybody). +type UserNoticeKindSettings struct { + Mode string // "off", "ask" or "auto" + Loud bool + Channels int // UserNoticeTelegram | UserNoticeApp + Days []int // expiry_soon: how many days before the end of the term, largest first + Percent int // quota_warn: the share of the quota that has been used +} + +type userNoticeKindSetting struct { + Mode *string `json:"mode"` + Loud *bool `json:"loud"` + Channels *int `json:"channels"` + Days []int `json:"days"` + Percent *int `json:"percent"` +} + +// ResolveUserNoticeKind is the policy of a kind: its default (DefaultUserNoticeKinds), changed by the global settings, then +// switched off when the person's own settings say so. own may be nil. ok is false for a kind that does not exist. A value that does +// not make sense (a mode that is none of the three, channels outside 1 to 3, days or a percent out of range) is ignored: the +// default stays, so a bad row can never silence or flood a kind. +func ResolveUserNoticeKind(kind string, global, own map[string]string) (UserNoticeKindSettings, bool) { + def, ok := DefaultUserNoticeKinds()[kind] + if !ok { + return UserNoticeKindSettings{}, false + } + out := UserNoticeKindSettings{Mode: def.Mode, Loud: def.Loud, Channels: def.Channels} + switch kind { + case "expiry_soon": + out.Days = []int{int(DefaultUserExpiryFirstThreshold.Hours() / 24), int(DefaultUserExpirySecondThreshold.Hours() / 24)} + case "quota_warn": + out.Percent = DefaultUserQuotaWarningPercent + } + var set userNoticeKindSetting + if err := json.Unmarshal([]byte(global[UserNoticeSettingPrefix+kind]), &set); err == nil { + if set.Mode != nil && (*set.Mode == "off" || *set.Mode == "ask" || *set.Mode == "auto") { + out.Mode = *set.Mode + } + if set.Loud != nil { + out.Loud = *set.Loud + } + if set.Channels != nil && *set.Channels >= 1 && *set.Channels <= (UserNoticeTelegram|UserNoticeApp) { + out.Channels = *set.Channels + } + if days, ok := cleanNoticeDays(set.Days); ok && kind == "expiry_soon" { + out.Days = days + } + if set.Percent != nil && *set.Percent >= 1 && *set.Percent <= 99 && kind == "quota_warn" { + out.Percent = *set.Percent + } + } + var off []string + if json.Unmarshal([]byte(own[UserNoticeOffKey]), &off) == nil { + for _, k := range off { + if strings.TrimSpace(k) == kind { + out.Mode = "off" + } + } + } + return out, true +} + +// cleanNoticeDays is days sorted largest first without repeats; ok is false when there are none, more than five, or one outside +// 1 to 365. +func cleanNoticeDays(days []int) ([]int, bool) { + if len(days) == 0 || len(days) > 5 { + return nil, false + } + out := append([]int(nil), days...) + sort.Sort(sort.Reverse(sort.IntSlice(out))) + for i, d := range out { + if d < 1 || d > 365 || (i > 0 && d == out[i-1]) { + return nil, false + } + } + return out, true +} diff --git a/internal/panel/store/user_status.go b/internal/panel/store/user_status.go new file mode 100644 index 00000000..f1532d51 --- /dev/null +++ b/internal/panel/store/user_status.go @@ -0,0 +1,200 @@ +package store + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "strings" + "time" +) + +// The producer of the status notices to people: expiry_soon, expired, quota_warn, quota_over and restored. It looks at the state +// of the people (the term, the quota, the status the access sweep keeps) and inserts the rows that are missing, in SQL, so that +// a minute on the edge costs one read and one batch whatever the number of people. Rules, all in the statements below: +// +// - only a person with a Telegram chat gets a row, and only for an event that happened after the first of their chats was +// linked and not more than 24 hours ago: turning the feature on, or linking a chat, never sends the past (spec 5); +// - the dedupe key names the event, so the same event is inserted once, and a renewal (a new end of the term) or a new quota +// period is a new event; +// - the row is for the Telegram channel only; the app sees the term and the traffic itself (spec 6a); +// - what goes in is a page at most: what does not fit is inserted by the next call, as the rows already there leave the +// candidates. +// +// When a quota threshold was crossed is not stored, so it is read off the hourly traffic: the use before the hour of the cut +// (the later of the first link and 24 hours ago, rounded down to the hour) must still be under the threshold. The hour is the +// grain: a crossing in the hour of the cut counts as after it, and one after that hour is never missed. + +// UserStatusKinds are the kinds ProduceUserStatusNotices makes, in the order it makes them. +var UserStatusKinds = []string{"expiry_soon", "expired", "quota_warn", "quota_over", "restored"} + +// userStatusRestoredLookback is how far back the sent "expired" and "quota_over" notices are looked at for "restored": the default +// retention of the journal, which removes them anyway. +const userStatusRestoredLookback = DefaultUserNoticeRetentionDays * 24 * time.Hour + +// HasUserTelegramChats says whether any person has a Telegram chat: the early exit of the producer, one row read. +func (s *Store) HasUserTelegramChats(ctx context.Context) (bool, error) { + var one int + err := s.R.QueryRowContext(ctx, `SELECT 1 FROM user_telegram_chat LIMIT 1`).Scan(&one) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + return err == nil, err +} + +// userStatusAudience is the people with a chat and the time of their first chat; it joins as c. +const userStatusAudience = `JOIN (SELECT user_id, min(linked_at) AS first FROM user_telegram_chat GROUP BY user_id) c ON c.user_id = ` + +// userStatusNotOff keeps out the people who switched the kind (?2) off for themselves (user_notify_override). +func userStatusNotOff(person string) string { + return `NOT EXISTS (SELECT 1 FROM user_notify_override o WHERE o.user_id = ` + person + ` AND o.key = '` + UserNoticeOffKey + `' + AND EXISTS (SELECT 1 FROM json_each(CASE WHEN json_valid(o.value_json) THEN o.value_json ELSE '[]' END) j WHERE j.value = ?2))` +} + +// userStatusInsert is the head of every statement: ?1 now, ?2 the kind, ?3 loud, ?4 approval (none or pending), ?5 the page size, +// ?6 (only the kinds that have one) the days (a JSON array), the percent or the earliest finish time. The SELECT that follows +// gives the user id, the dedupe key and the params. +const userStatusInsert = `INSERT INTO user_notice (id, user_id, kind, dedupe, params_json, loud, channels, created_at, due_at, approval) + SELECT 'unn_' || lower(hex(randomblob(16))), t.user_id, ?2, t.dedupe, t.params, ?3, 1, ?1, ?1, ?4 FROM (` + +// userStatusTail closes a statement: the page, and the dedupe that makes a repeat a no-op (a candidate is never one that has its row). +const userStatusTail = `) t WHERE 1 ON CONFLICT (dedupe) DO NOTHING` + +// A candidate: the audience joins as c and the user as u. recent is the use since the hour of the cut. +const userStatusRecent = `COALESCE((SELECT sum(b.bytes_up + b.bytes_down) FROM traffic_bucket b + WHERE b.user_id = u.id AND b.hour_start >= max(c.first, ?1 - 86400) / 3600 * 3600), 0)` + +// intArgs makes the numeric parameters of a statement integers where they are used: D1 may hand a number over as a real, and a +// real would make the integer division of the days a fraction and a key like "quota_warn:u:1:80.0". +func intArgs(query string, params ...string) string { + pairs := make([]string, 0, 2*len(params)) + for _, p := range params { + pairs = append(pairs, p, "CAST("+p+" AS INTEGER)") + } + return strings.NewReplacer(pairs...).Replace(query) +} + +var userStatusSQL = map[string]string{ + // ?6 is the days before the end of the term. The event is the moment the term had that many days left. + "expiry_soon": userStatusInsert + ` + SELECT u.id AS user_id, 'expiry_soon:' || u.id || ':' || u.expires_at || ':' || d.value AS dedupe, + json_object('days', (u.expires_at - ?1 + 86399) / 86400, 'expires', u.expires_at) AS params + FROM json_each(?6) d + JOIN user u ON u.expires_at IS NOT NULL AND u.disabled = 0 AND u.expires_at > ?1 AND u.expires_at - d.value * 86400 <= ?1 + ` + userStatusAudience + `u.id + WHERE u.expires_at - d.value * 86400 >= max(c.first, ?1 - 86400) + AND ` + userStatusNotOff("u.id") + ` + AND NOT EXISTS (SELECT 1 FROM user_notice x WHERE x.dedupe = 'expiry_soon:' || u.id || ':' || u.expires_at || ':' || d.value) + LIMIT ?5` + userStatusTail, + + "expired": userStatusInsert + ` + SELECT u.id AS user_id, 'expired:' || u.id || ':' || u.expires_at AS dedupe, json_object('expires', u.expires_at) AS params + FROM user u ` + userStatusAudience + `u.id + WHERE u.expires_at IS NOT NULL AND u.disabled = 0 AND u.expires_at <= ?1 AND u.expires_at >= max(c.first, ?1 - 86400) + AND ` + userStatusNotOff("u.id") + ` + AND NOT EXISTS (SELECT 1 FROM user_notice x WHERE x.dedupe = 'expired:' || u.id || ':' || u.expires_at) + LIMIT ?5` + userStatusTail, + + // ?6 is the percent. A person at or over the quota is quota_over's (the sweep makes them "limited" within the minute). + "quota_warn": userStatusInsert + ` + SELECT u.id AS user_id, 'quota_warn:' || u.id || ':' || u.period_start || ':' || ?6 AS dedupe, + json_object('pct', ?6, 'used', u.used_bytes, 'quota', u.quota_bytes, 'period', u.period_start, 'reset', u.quota_reset) AS params + FROM user u ` + userStatusAudience + `u.id + WHERE u.status = 'active' AND u.disabled = 0 AND u.quota_bytes > 0 AND u.used_bytes < u.quota_bytes AND u.used_bytes * 100 >= u.quota_bytes * ?6 + AND (u.used_bytes - ` + userStatusRecent + `) * 100 < u.quota_bytes * ?6 + AND ` + userStatusNotOff("u.id") + ` + AND NOT EXISTS (SELECT 1 FROM user_notice x WHERE x.dedupe = 'quota_warn:' || u.id || ':' || u.period_start || ':' || ?6) + LIMIT ?5` + userStatusTail, + + "quota_over": userStatusInsert + ` + SELECT u.id AS user_id, 'quota_over:' || u.id || ':' || u.period_start AS dedupe, + json_object('used', u.used_bytes, 'quota', u.quota_bytes, 'period', u.period_start, 'reset', u.quota_reset) AS params + FROM user u ` + userStatusAudience + `u.id + WHERE u.status = 'limited' AND u.disabled = 0 AND u.quota_bytes > 0 AND u.used_bytes >= u.quota_bytes + AND u.used_bytes - ` + userStatusRecent + ` < u.quota_bytes + AND ` + userStatusNotOff("u.id") + ` + AND NOT EXISTS (SELECT 1 FROM user_notice x WHERE x.dedupe = 'quota_over:' || u.id || ':' || u.period_start) + LIMIT ?5` + userStatusTail, + + // ?6 is the earliest finish time looked at. Active is the stored status and also what the clock says (the sweep may lag a + // minute behind an expiry, and a "restored" sent then would use up the event for the real return). A person is told once for the newest "expired" or "quota_over" that was sent to + // them, and only when it is newer than their last "restored" (older ones do not come back after it). + "restored": userStatusInsert + ` + SELECT n.user_id AS user_id, 'restored:' || n.id AS dedupe, json_object('after', n.kind, 'notice', n.id) AS params + FROM user_notice n JOIN user u ON u.id = n.user_id + WHERE n.done_at >= ?6 AND n.kind IN ('expired', 'quota_over') AND n.result = 'sent' + AND u.status = 'active' AND u.disabled = 0 AND (u.expires_at IS NULL OR u.expires_at > ?1) AND (u.quota_bytes = 0 OR u.used_bytes < u.quota_bytes) + AND EXISTS (SELECT 1 FROM user_telegram_chat c WHERE c.user_id = n.user_id) + AND ` + userStatusNotOff("n.user_id") + ` + AND NOT EXISTS (SELECT 1 FROM user_notice x WHERE x.dedupe = 'restored:' || n.id) + AND n.done_at > COALESCE((SELECT max(r.created_at) FROM user_notice r WHERE r.user_id = n.user_id AND r.kind = 'restored'), 0) + AND NOT EXISTS (SELECT 1 FROM user_notice m WHERE m.user_id = n.user_id AND m.kind IN ('expired', 'quota_over') AND m.result = 'sent' + AND (m.done_at > n.done_at OR (m.done_at = n.done_at AND m.id > n.id))) + LIMIT ?5` + userStatusTail, +} + +func init() { + for kind, query := range userStatusSQL { + params := []string{"?1", "?3", "?5"} + if kind == "quota_warn" || kind == "restored" { // the other kinds have a JSON array or nothing in ?6 + params = append(params, "?6") + } + userStatusSQL[kind] = intArgs(query, params...) + } +} + +// ProduceUserStatusNotices inserts the status notices that are missing for the kinds in plan (the kinds that are off, or have no +// Telegram channel, are skipped) and returns how many rows each kind got. A kind that got limit rows may have more waiting: call +// again. Every statement runs in one batch, so a minute on the edge is one round trip. Ask mode inserts a draft for the owner +// (approval pending, no draft group: each row is its own); auto inserts a row the sender takes at once. +func (s *Store) ProduceUserStatusNotices(ctx context.Context, now time.Time, limit int, plan map[string]UserNoticeKindSettings) (map[string]int64, error) { + if limit <= 0 { + return nil, nil + } + var kinds []string + var stmts []Stmt + for _, kind := range UserStatusKinds { + set, ok := plan[kind] + if !ok || set.Mode == "off" || set.Channels&UserNoticeTelegram == 0 { + continue + } + loud := 0 + if set.Loud { + loud = 1 + } + approval := UserNoticeApprovalNone + if set.Mode == "ask" { + approval = UserNoticeApprovalPending + } + args := []any{unix(now), kind, loud, approval, limit} + switch kind { + case "expiry_soon": + if len(set.Days) == 0 { + continue + } + b, _ := json.Marshal(set.Days) + args = append(args, string(b)) + case "quota_warn": + if set.Percent < 1 || set.Percent > 99 { + continue + } + args = append(args, set.Percent) + case "restored": + args = append(args, unix(now.Add(-userStatusRestoredLookback))) + } + kinds = append(kinds, kind) + stmts = append(stmts, Stmt{Query: userStatusSQL[kind], Args: args}) + } + if len(stmts) == 0 { + return nil, nil + } + results, err := s.batch(ctx, stmts...) + if err != nil { + return nil, err + } + out := make(map[string]int64, len(kinds)) + for i, kind := range kinds { + out[kind] = results[i].RowsAffected + } + return out, nil +} diff --git a/internal/panel/store/user_status_proof_test.go b/internal/panel/store/user_status_proof_test.go new file mode 100644 index 00000000..dc96d0d1 --- /dev/null +++ b/internal/panel/store/user_status_proof_test.go @@ -0,0 +1,122 @@ +package store + +import ( + "context" + "fmt" + "reflect" + "sort" + "testing" + "time" +) + +// userStatusProof runs on SQLite and on D1: the one batch of INSERT ... SELECT statements of ProduceUserStatusNotices makes each +// event once, for the people with a chat, and nothing for the past, for the kinds that are off, or for a person who switched a kind off. +func userStatusProof(t *testing.T, st *Store) { + ctx := context.Background() + now := time.Unix(1_800_000_000, 0).UTC() // on an hour + n := now.Unix() + exec := func(q string, args ...any) { + t.Helper() + if _, err := st.W.ExecContext(ctx, q, args...); err != nil { + t.Fatalf("%s: %v", q, err) + } + } + exec(`INSERT INTO user_group (id, name, created_at) VALUES ('grp_us', 'us', 1)`) + exec(`INSERT INTO node (id, name, address, state, created_at) VALUES ('nod_us', 'us1', 'us1.example.com', 'active', 1)`) + user := func(id, set string, args ...any) { + t.Helper() + exec(`INSERT INTO user (id, name, group_id, period_start, sub_token_hash, sub_token_enc, created_at) VALUES (?, ?, 'grp_us', ?, ?, x'02', 1)`, + id, "name-"+id, n-20*86400, []byte(id)) + if set != "" { + exec(`UPDATE user SET `+set+` WHERE id = ?`, append(args, id)...) + } + if id != "usr_nochat" { + exec(`INSERT INTO user_telegram_chat (id, user_id, chat_mac, chat_enc, lang, linked_at) VALUES (?, ?, ?, x'01', 'en', ?)`, + "utc_"+id, id, []byte("mac-"+id), n-10*86400) + } + } + soon := n + 3*86400 - 60 + user("usr_soon", `expires_at = ?`, soon) + user("usr_expired", `expires_at = ?, status = 'expired'`, n-60) + user("usr_nochat", `expires_at = ?, status = 'expired'`, n-60) + user("usr_off", `expires_at = ?, status = 'expired'`, n-60) + user("usr_warn", `quota_bytes = 1000, used_bytes = 850`) + user("usr_over", `quota_bytes = 1000, used_bytes = 1000, status = 'limited'`) + user("usr_back", `status = 'active'`) + exec(`INSERT INTO user_notify_override (user_id, key, value_json) VALUES ('usr_off', 'notice_off', '["expired"]')`) + for _, b := range []struct { + user string + bytes int64 + }{{"usr_warn", 200}, {"usr_over", 300}} { + exec(`INSERT INTO traffic_bucket (user_id, node_id, protocol, hour_start, bytes_up, bytes_down) VALUES (?, 'nod_us', 'hysteria2', ?, ?, 0)`, b.user, n-3600, b.bytes) + } + exec(`INSERT INTO user_notice (id, user_id, kind, dedupe, params_json, loud, channels, created_at, due_at, done_at, result) + VALUES ('n_back', 'usr_back', 'expired', 'd-back', '{}', 1, 1, ?, ?, ?, 'sent')`, n-86400, n-86400, n-86000) + + plan := map[string]UserNoticeKindSettings{} + for _, kind := range UserStatusKinds { + plan[kind], _ = ResolveUserNoticeKind(kind, nil, nil) + } + got, err := st.ProduceUserStatusNotices(ctx, now, 100, plan) + if err != nil { + t.Fatal(err) + } + if want := map[string]int64{"expiry_soon": 1, "expired": 1, "quota_warn": 1, "quota_over": 1, "restored": 1}; !reflect.DeepEqual(got, want) { + t.Fatalf("made %v, want %v", got, want) + } + period := n - 20*86400 + want := []string{ + fmt.Sprintf("expired:usr_expired:%d", n-60), + fmt.Sprintf("expiry_soon:usr_soon:%d:3", soon), + fmt.Sprintf("quota_over:usr_over:%d", period), + fmt.Sprintf("quota_warn:usr_warn:%d:80", period), + "restored:n_back", + } + list := func() []string { + rows, err := st.R.QueryContext(ctx, `SELECT dedupe FROM user_notice WHERE dedupe NOT LIKE 'd-%' ORDER BY dedupe`) + if err != nil { + t.Fatal(err) + } + defer rows.Close() + var out []string + for rows.Next() { + var d string + if err := rows.Scan(&d); err != nil { + t.Fatal(err) + } + out = append(out, d) + } + return out + } + sort.Strings(want) + if gotKeys := list(); !reflect.DeepEqual(gotKeys, want) { + t.Fatalf("notices = %q, want %q", gotKeys, want) + } + // every row is for Telegram, due now, with params that say what happened + var loud, channels, due int64 + var params string + if err := st.R.QueryRowContext(ctx, `SELECT loud, channels, due_at, params_json FROM user_notice WHERE kind = 'quota_over'`).Scan(&loud, &channels, &due, ¶ms); err != nil || + loud != 1 || channels != UserNoticeTelegram || due != n || params != fmt.Sprintf(`{"used":1000,"quota":1000,"period":%d,"reset":"month"}`, period) { + t.Errorf("quota_over row: %d %d %d %s %v", loud, channels, due, params, err) + } + // again: nothing; the changed settings: off and ask + if again, err := st.ProduceUserStatusNotices(ctx, now.Add(time.Minute), 100, plan); err != nil || again["expired"]+again["expiry_soon"]+again["quota_warn"]+again["quota_over"]+again["restored"] != 0 { + t.Errorf("repeat: %v %v", again, err) + } + exec(`UPDATE user SET expires_at = ?, status = 'expired' WHERE id = 'usr_nochat'`, n-30) + exec(`UPDATE user SET expires_at = ? WHERE id = 'usr_soon'`, n-30) + ask := plan["expired"] + ask.Mode = "ask" + plan["expired"] = ask + if got, err := st.ProduceUserStatusNotices(ctx, now.Add(time.Minute), 100, plan); err != nil || got["expired"] != 1 { // usr_soon: the term it was renewed to ended; usr_nochat has no chat + t.Fatalf("ask: %v %v", got, err) + } + var approval string + if err := st.R.QueryRowContext(ctx, `SELECT approval FROM user_notice WHERE dedupe = ?`, fmt.Sprintf("expired:usr_soon:%d", n-30)).Scan(&approval); err != nil || approval != UserNoticeApprovalPending { + t.Errorf("draft: %q %v", approval, err) + } + plan["expired"] = UserNoticeKindSettings{Mode: "off", Channels: 3} + if got, err := st.ProduceUserStatusNotices(ctx, now.Add(time.Minute), 100, plan); err != nil || len(got) != 4 { + t.Errorf("off: %v %v", got, err) + } +} diff --git a/internal/panel/store/user_status_test.go b/internal/panel/store/user_status_test.go new file mode 100644 index 00000000..2b7239c9 --- /dev/null +++ b/internal/panel/store/user_status_test.go @@ -0,0 +1,486 @@ +//go:build !js + +package store + +import ( + "context" + "fmt" + "reflect" + "sort" + "strings" + "testing" + "time" +) + +const ( + hour = int64(3600) + day = 24 * hour +) + +// statusNow is hour aligned, so the hourly traffic of the tests lines up with the hour of the cut. +var statusNow = userNotifyNow + +func nowU() int64 { return statusNow.Unix() } + +// statusPlan is every kind at its default, with the changes of mutate. +func statusPlan(mutate func(map[string]UserNoticeKindSettings)) map[string]UserNoticeKindSettings { + plan := map[string]UserNoticeKindSettings{} + for _, kind := range UserStatusKinds { + plan[kind], _ = ResolveUserNoticeKind(kind, nil, nil) + } + if mutate != nil { + mutate(plan) + } + return plan +} + +func openStatus(t *testing.T, users ...string) *Store { + t.Helper() + s := openUserNotify(t, users...) + execT(t, s, `INSERT INTO node (id, name, address, state, created_at) VALUES ('nod_1', 'de1', 'de1.example.com', 'active', 1)`) + return s +} + +func setUser(t *testing.T, s *Store, id, set string, args ...any) { + t.Helper() + execT(t, s, `UPDATE user SET `+set+` WHERE id = ?`, append(args, id)...) +} + +func linkChatAt(t *testing.T, s *Store, user string, at int64) { + t.Helper() + execT(t, s, `INSERT INTO user_telegram_chat (id, user_id, chat_mac, chat_enc, lang, linked_at) VALUES (?, ?, ?, x'01', 'en', ?)`, + fmt.Sprintf("utc_%s_%d", user, at), user, []byte(fmt.Sprintf("%s-%d", user, at)), at) +} + +func produce(t *testing.T, s *Store, now int64, limit int, plan map[string]UserNoticeKindSettings) map[string]int64 { + t.Helper() + got, err := s.ProduceUserStatusNotices(context.Background(), time.Unix(now, 0).UTC(), limit, plan) + if err != nil { + t.Fatalf("produce: %v", err) + } + return got +} + +// keys are the dedupe keys of the notices of a kind ("" = every kind), sorted. +func keys(t *testing.T, s *Store, kind string) []string { + t.Helper() + rows, err := s.R.QueryContext(context.Background(), `SELECT dedupe FROM user_notice WHERE kind = ? OR ? = '' ORDER BY dedupe`, kind, kind) + if err != nil { + t.Fatal(err) + } + defer rows.Close() + var out []string + for rows.Next() { + var d string + if err := rows.Scan(&d); err != nil { + t.Fatal(err) + } + out = append(out, d) + } + return out +} + +func wantKeys(t *testing.T, s *Store, kind string, want ...string) { + t.Helper() + got := keys(t, s, kind) + if want == nil { + want = []string{} + } + sort.Strings(want) + if got == nil { + got = []string{} + } + if !reflect.DeepEqual(got, want) { + t.Errorf("%s notices = %q, want %q", kind, got, want) + } +} + +func TestResolveUserNoticeKind(t *testing.T) { + r := func(kind string, global, own map[string]string) UserNoticeKindSettings { + got, ok := ResolveUserNoticeKind(kind, global, own) + if !ok { + t.Fatalf("%s: not a kind", kind) + } + return got + } + // the defaults: the policy of the kind, the thresholds of the spec + if got := r("expiry_soon", nil, nil); got.Mode != "auto" || got.Loud || got.Channels != 3 || !reflect.DeepEqual(got.Days, []int{3, 1}) || got.Percent != 0 { + t.Errorf("expiry_soon default = %+v", got) + } + if got := r("quota_warn", nil, nil); got.Percent != 80 || got.Days != nil || got.Loud { + t.Errorf("quota_warn default = %+v", got) + } + if got := r("expired", nil, nil); !got.Loud || got.Mode != "auto" { + t.Errorf("expired default = %+v", got) + } + if got := r("incident_all_down", nil, nil); got.Mode != "ask" { + t.Errorf("incident_all_down default = %+v", got) + } + if _, ok := ResolveUserNoticeKind("nonsense", nil, nil); ok { + t.Error("an unknown kind resolved") + } + + // the owner's settings change a field at a time; days come back largest first + global := map[string]string{ + "notice.expiry_soon": `{"mode":"ask","loud":true,"channels":1,"days":[1,7,3]}`, + "notice.quota_warn": `{"percent":90}`, + "notice.expired": `{"mode":"off"}`, + } + if got := r("expiry_soon", global, nil); got.Mode != "ask" || !got.Loud || got.Channels != 1 || !reflect.DeepEqual(got.Days, []int{7, 3, 1}) { + t.Errorf("expiry_soon set = %+v", got) + } + if got := r("quota_warn", global, nil); got.Percent != 90 || got.Mode != "auto" { + t.Errorf("quota_warn set = %+v", got) + } + if got := r("expired", global, nil); got.Mode != "off" || !got.Loud { + t.Errorf("expired set = %+v", got) + } + + // what does not make sense is ignored, field by field: a bad row never silences or floods a kind + bad := map[string]string{ + "notice.expiry_soon": `{"mode":"loud","channels":9,"days":[3,3]}`, + "notice.quota_warn": `{"percent":100,"mode":"ask"}`, + "notice.quota_over": `not json`, + "notice.restored": `{"days":[2],"percent":50}`, // thresholds belong to two kinds only + } + if got := r("expiry_soon", bad, nil); got.Mode != "auto" || got.Channels != 3 || !reflect.DeepEqual(got.Days, []int{3, 1}) { + t.Errorf("expiry_soon bad = %+v", got) + } + if got := r("quota_warn", bad, nil); got.Percent != 80 || got.Mode != "ask" { + t.Errorf("quota_warn bad = %+v", got) + } + if got := r("quota_over", bad, nil); got.Mode != "auto" { + t.Errorf("quota_over bad = %+v", got) + } + if got := r("restored", bad, nil); got.Days != nil || got.Percent != 0 { + t.Errorf("restored bad = %+v", got) + } + + // a person's own off wins over the owner's mode; nothing else of theirs changes + own := map[string]string{UserNoticeOffKey: `["quota_warn", "torrent"]`} + if got := r("quota_warn", global, own); got.Mode != "off" || got.Percent != 90 { + t.Errorf("quota_warn own off = %+v", got) + } + if got := r("expiry_soon", global, own); got.Mode != "ask" { + t.Errorf("expiry_soon with another kind off = %+v", got) + } + if got := r("expiry_soon", global, map[string]string{UserNoticeOffKey: `{"x":1}`}); got.Mode != "ask" { + t.Errorf("a bad own value switched a kind off: %+v", got) + } +} + +func TestHasUserTelegramChats(t *testing.T) { + s := openStatus(t, "usr_a") + ctx := context.Background() + if has, err := s.HasUserTelegramChats(ctx); err != nil || has { + t.Fatalf("no chat: %v %v", has, err) + } + linkChatAt(t, s, "usr_a", 5) + if has, err := s.HasUserTelegramChats(ctx); err != nil || !has { + t.Fatalf("a chat: %v %v", has, err) + } +} + +// expiry_soon: one row per threshold crossed, once; a renewal is a new event; nothing for the past or for people with no chat. +func TestProduceExpirySoon(t *testing.T) { + s := openStatus(t, "usr_a", "usr_late", "usr_old", "usr_nochat", "usr_off", "usr_forever") + now := nowU() + exp := now + 3*day - 60 // the 3-day mark passed a minute ago + for _, u := range []string{"usr_a", "usr_late", "usr_old", "usr_nochat", "usr_off"} { + setUser(t, s, u, `expires_at = ?`, exp) + } + setUser(t, s, "usr_old", `expires_at = ?`, now+3*day-25*hour) // the mark passed 25 hours ago: before the cut + setUser(t, s, "usr_off", `disabled = 1, status = 'disabled'`) + linkChatAt(t, s, "usr_a", now-10*day) + linkChatAt(t, s, "usr_a", now-5*day) // the first chat counts + linkChatAt(t, s, "usr_late", now-30) // linked after the mark + linkChatAt(t, s, "usr_old", now-10*day) + linkChatAt(t, s, "usr_off", now-10*day) + linkChatAt(t, s, "usr_forever", now-10*day) + + got := produce(t, s, now, 100, statusPlan(nil)) + if got["expiry_soon"] != 1 { + t.Fatalf("made %v", got) + } + wantKeys(t, s, "expiry_soon", fmt.Sprintf("expiry_soon:usr_a:%d:3", exp)) + n := noticeByDedupe(t, s, fmt.Sprintf("expiry_soon:usr_a:%d:3", exp)) + if n.Loud || n.Channels != UserNoticeTelegram || n.Approval != "" || !n.DueAt.Equal(statusNow) || n.ParamsJSON != fmt.Sprintf(`{"days":3,"expires":%d}`, exp) { + t.Errorf("row = %+v", n) + } + + // the same minute again, and a later one: no repeat + if got := produce(t, s, now+60, 100, statusPlan(nil)); got["expiry_soon"] != 0 { + t.Errorf("repeat made %v", got) + } + // the 1-day mark: usr_a and usr_late both have a chat by then and are inside the day; usr_old's term is further off + got = produce(t, s, exp-day+10, 100, statusPlan(nil)) + wantKeys(t, s, "expiry_soon", fmt.Sprintf("expiry_soon:usr_a:%d:3", exp), fmt.Sprintf("expiry_soon:usr_a:%d:1", exp), + fmt.Sprintf("expiry_soon:usr_late:%d:1", exp)) + if n := noticeByDedupe(t, s, fmt.Sprintf("expiry_soon:usr_a:%d:1", exp)); n.ParamsJSON != fmt.Sprintf(`{"days":1,"expires":%d}`, exp) { + t.Errorf("1-day params = %s", n.ParamsJSON) + } + // a renewal is a new event with new keys, and the old ones stay: producing again changes nothing until the new marks + setUser(t, s, "usr_a", `expires_at = ?`, exp+30*day) + if got := produce(t, s, exp-day+20, 100, statusPlan(nil)); got["expiry_soon"] != 0 { + t.Errorf("after the renewal made %v", got) + } + exp2 := exp + 30*day + produce(t, s, exp2-3*day+5, 100, statusPlan(nil)) + if k := keys(t, s, "expiry_soon"); !contains(k, fmt.Sprintf("expiry_soon:usr_a:%d:3", exp2)) { + t.Errorf("the renewed term got no row: %q", k) + } +} + +func contains(list []string, s string) bool { + for _, x := range list { + if x == s { + return true + } + } + return false +} + +func noticeByDedupe(t *testing.T, s *Store, dedupe string) UserNotice { + t.Helper() + n, err := scanUserNotice(s.R.QueryRowContext(context.Background(), `SELECT `+userNoticeColumns+` FROM user_notice WHERE dedupe = ?`, dedupe)) + if err != nil { + t.Fatalf("notice %s: %v", dedupe, err) + } + return n +} + +func TestProduceExpired(t *testing.T) { + s := openStatus(t, "usr_a", "usr_late", "usr_old", "usr_nochat", "usr_live", "usr_off") + now := nowU() + setUser(t, s, "usr_a", `expires_at = ?, status = 'expired'`, now-60) + setUser(t, s, "usr_late", `expires_at = ?, status = 'expired'`, now-600) + setUser(t, s, "usr_old", `expires_at = ?, status = 'expired'`, now-25*hour) + setUser(t, s, "usr_nochat", `expires_at = ?, status = 'expired'`, now-60) + setUser(t, s, "usr_live", `expires_at = ?`, now+day) + setUser(t, s, "usr_off", `expires_at = ?, disabled = 1, status = 'disabled'`, now-60) + linkChatAt(t, s, "usr_a", now-10*day) + linkChatAt(t, s, "usr_late", now-60) // linked after the term ended + linkChatAt(t, s, "usr_old", now-10*day) + linkChatAt(t, s, "usr_live", now-10*day) + linkChatAt(t, s, "usr_off", now-10*day) + + if got := produce(t, s, now, 100, statusPlan(nil)); got["expired"] != 1 { + t.Fatalf("made %v", got) + } + wantKeys(t, s, "expired", fmt.Sprintf("expired:usr_a:%d", now-60)) + n := noticeByDedupe(t, s, fmt.Sprintf("expired:usr_a:%d", now-60)) + if !n.Loud || n.ParamsJSON != fmt.Sprintf(`{"expires":%d}`, now-60) { + t.Errorf("row = %+v", n) + } + if got := produce(t, s, now+60, 100, statusPlan(nil)); got["expired"] != 0 { + t.Errorf("repeat made %v", got) + } + // renewed and ended again: a new term is a new event + setUser(t, s, "usr_a", `expires_at = ?`, now+60) + produce(t, s, now+120, 100, statusPlan(nil)) + if k := keys(t, s, "expired"); len(k) != 2 { + t.Errorf("the second end of the term: %q", k) + } +} + +// quota_warn and quota_over: the crossing is read off the hourly traffic; use that was there before the chat is not news. +func TestProduceQuota(t *testing.T) { + s := openStatus(t, "usr_recent", "usr_old", "usr_late", "usr_fresh", "usr_over", "usr_overold", "usr_stale", "usr_free") + now := nowU() + for _, u := range []string{"usr_recent", "usr_old", "usr_late", "usr_fresh"} { + setUser(t, s, u, `quota_bytes = 1000, used_bytes = 850, period_start = ?`, now-20*day) + } + setUser(t, s, "usr_over", `quota_bytes = 1000, used_bytes = 1000, status = 'limited', period_start = ?`, now-20*day) + setUser(t, s, "usr_overold", `quota_bytes = 1000, used_bytes = 1200, status = 'limited', period_start = ?`, now-20*day) + setUser(t, s, "usr_stale", `quota_bytes = 1000, used_bytes = 1000, period_start = ?`, now-20*day) // status not yet recomputed: still active + setUser(t, s, "usr_free", `quota_bytes = 0, used_bytes = 5000, period_start = ?`, now-20*day) + for _, u := range []string{"usr_recent", "usr_old", "usr_over", "usr_overold", "usr_stale", "usr_free"} { + linkChatAt(t, s, u, now-10*day) + } + linkChatAt(t, s, "usr_late", now-2*hour) // linked two hours ago + linkChatAt(t, s, "usr_fresh", now-2*hour) + bucket := func(user string, at, bytes int64) { + execT(t, s, `INSERT INTO traffic_bucket (user_id, node_id, protocol, hour_start, bytes_up, bytes_down) VALUES (?, 'nod_1', 'hysteria2', ?, ?, 0)`, user, at, bytes) + } + bucket("usr_recent", now-3*hour, 200) // 650 before it, 850 after: crossed after the cut + bucket("usr_old", now-30*hour, 900) // the use is all older than a day: crossed long ago + bucket("usr_late", now-10*hour, 900) // crossed before the chat was linked + bucket("usr_fresh", now-hour, 200) // crossed after the chat was linked + bucket("usr_over", now-hour, 300) + bucket("usr_overold", now-40*hour, 1200) + bucket("usr_stale", now-hour, 300) + + got := produce(t, s, now, 100, statusPlan(nil)) + if got["quota_warn"] != 2 || got["quota_over"] != 1 { + t.Fatalf("made %v", got) + } + p := fmt.Sprintf("%d", now-20*day) + wantKeys(t, s, "quota_warn", "quota_warn:usr_recent:"+p+":80", "quota_warn:usr_fresh:"+p+":80") + wantKeys(t, s, "quota_over", "quota_over:usr_over:"+p) + if n := noticeByDedupe(t, s, "quota_warn:usr_recent:"+p+":80"); n.Loud || n.ParamsJSON != fmt.Sprintf(`{"pct":80,"used":850,"quota":1000,"period":%s,"reset":"month"}`, p) { + t.Errorf("warn row = %+v", n) + } + if n := noticeByDedupe(t, s, "quota_over:usr_over:"+p); !n.Loud || n.ParamsJSON != fmt.Sprintf(`{"used":1000,"quota":1000,"period":%s,"reset":"month"}`, p) { + t.Errorf("over row = %+v", n) + } + if got := produce(t, s, now+60, 100, statusPlan(nil)); got["quota_warn"]+got["quota_over"] != 0 { + t.Errorf("repeat made %v", got) + } + + // a new period starts over: new keys, and the percent is part of the key + setUser(t, s, "usr_recent", `period_start = ?, used_bytes = 100`, now+1) + if got := produce(t, s, now+120, 100, statusPlan(nil)); got["quota_warn"] != 0 { + t.Errorf("under the threshold in the new period made %v", got) + } + setUser(t, s, "usr_recent", `used_bytes = 900`) + bucket("usr_recent", now+hour, 800) + if got := produce(t, s, now+2*hour, 100, statusPlan(nil)); got["quota_warn"] != 1 { + t.Errorf("the new period made %v", got) + } + plan := statusPlan(func(p map[string]UserNoticeKindSettings) { + w := p["quota_warn"] + w.Percent = 85 + p["quota_warn"] = w + }) + // the percent is part of the key: a second threshold is a second event, for usr_fresh (850 of 1000) and for usr_recent's new period + if got := produce(t, s, now+2*hour, 100, plan); got["quota_warn"] != 2 { + t.Errorf("a second threshold made %v", got) + } + if k := keys(t, s, "quota_warn"); !contains(k, "quota_warn:usr_fresh:"+p+":85") { + t.Errorf("keys = %q", k) + } +} + +// restored: only for a person who was sent "expired" or "quota_over", once, when their access is active again. +func TestProduceRestored(t *testing.T) { + s := openStatus(t, "usr_a", "usr_b", "usr_c", "usr_d") + now := nowU() + for _, u := range []string{"usr_a", "usr_b", "usr_c", "usr_d"} { + linkChatAt(t, s, u, now-10*day) + } + sent := func(id, user, kind, result string, doneAt int64) { + execT(t, s, `INSERT INTO user_notice (id, user_id, kind, dedupe, params_json, loud, channels, created_at, due_at, done_at, result) + VALUES (?, ?, ?, ?, '{}', 1, 1, ?, ?, ?, ?)`, id, user, kind, "d-"+id, doneAt-5, doneAt-5, doneAt, result) + } + // usr_a was sent "expired", then "quota_over" later; usr_b's was dropped; usr_c's is still queued; usr_d was never told + sent("n_a1", "usr_a", "expired", "sent", now-3*day) + sent("n_a2", "usr_a", "quota_over", "sent", now-2*day) + sent("n_b", "usr_b", "expired", "dropped", now-2*day) + execT(t, s, `INSERT INTO user_notice (id, user_id, kind, dedupe, params_json, loud, channels, created_at, due_at) VALUES ('n_c', 'usr_c', 'expired', 'd-n_c', '{}', 1, 1, 1, 1)`) + for _, u := range []string{"usr_a", "usr_b", "usr_c", "usr_d"} { + setUser(t, s, u, `status = 'expired'`) + } + + // the access is not back: nothing + if got := produce(t, s, now, 100, statusPlan(nil)); got["restored"] != 0 { + t.Fatalf("while expired made %v", got) + } + for _, u := range []string{"usr_a", "usr_b", "usr_c", "usr_d"} { + setUser(t, s, u, `status = 'active'`) + } + if got := produce(t, s, now, 100, statusPlan(nil)); got["restored"] != 1 { + t.Fatalf("made %v", got) + } + wantKeys(t, s, "restored", "restored:n_a2") // the newest one only + n := noticeByDedupe(t, s, "restored:n_a2") + if n.UserID != "usr_a" || n.Loud || n.Channels != UserNoticeTelegram || n.ParamsJSON != `{"after":"quota_over","notice":"n_a2"}` { + t.Errorf("row = %+v", n) + } + // again and again: once, and the older notice of the same person does not come back after it + for i := 1; i <= 2; i++ { + if got := produce(t, s, now+int64(i)*60, 100, statusPlan(nil)); got["restored"] != 0 { + t.Errorf("repeat %d made %v", i, got) + } + } + // a new end of the access that was sent, and a new return, is a new event + sent("n_a3", "usr_a", "expired", "sent", now+3600) + setUser(t, s, "usr_a", `status = 'expired'`) + if got := produce(t, s, now+3700, 100, statusPlan(nil)); got["restored"] != 0 { + t.Errorf("while expired again made %v", got) + } + setUser(t, s, "usr_a", `status = 'active'`) + if got := produce(t, s, now+3800, 100, statusPlan(nil)); got["restored"] != 1 { + t.Errorf("the second return made %v", got) + } + wantKeys(t, s, "restored", "restored:n_a2", "restored:n_a3") + // the sweep lags behind the clock: stored "active" while the term ended is not a return + sent("n_e", "usr_c", "expired", "sent", now+3000) + setUser(t, s, "usr_c", `status = 'active', expires_at = ?`, now+3500) + if got := produce(t, s, now+3600, 100, statusPlan(nil)); got["restored"] != 0 { + t.Errorf("an ended term still stored as active made %v", got) + } + setUser(t, s, "usr_c", `expires_at = ?`, now+30*day) + if got := produce(t, s, now+3700, 100, statusPlan(nil)); got["restored"] != 1 { + t.Errorf("the return after the renewal made %v", got) + } + // a notice older than the journal keeps nothing alive + sent("n_d", "usr_d", "expired", "sent", now-40*day) + if got := produce(t, s, now+3900, 100, statusPlan(nil)); got["restored"] != 0 { + t.Errorf("an old notice made %v", got) + } +} + +// off makes nothing, ask makes drafts, a person's own off is honoured, a kind with no Telegram channel is left alone, and a page +// is a page. +func TestProduceModesAndPages(t *testing.T) { + s := openStatus(t, "usr_a", "usr_b", "usr_c") + now := nowU() + for _, u := range []string{"usr_a", "usr_b", "usr_c"} { + setUser(t, s, u, `expires_at = ?, status = 'expired'`, now-60) + linkChatAt(t, s, u, now-10*day) + } + execT(t, s, `INSERT INTO user_notify_override (user_id, key, value_json) VALUES ('usr_b', 'notice_off', '["expired","torrent"]')`) + execT(t, s, `INSERT INTO user_notify_override (user_id, key, value_json) VALUES ('usr_c', 'notice_off', 'garbage')`) // not JSON: ignored + + if got := produce(t, s, now, 100, statusPlan(func(p map[string]UserNoticeKindSettings) { + e := p["expired"] + e.Mode = "off" + p["expired"] = e + })); got["expired"] != 0 || len(got) != len(UserStatusKinds)-1 { + t.Fatalf("off made %v", got) + } + if got := produce(t, s, now, 100, statusPlan(func(p map[string]UserNoticeKindSettings) { + e := p["expired"] + e.Channels = UserNoticeApp + p["expired"] = e + })); got["expired"] != 0 { + t.Fatalf("an app-only kind made %v", got) + } + + ask := statusPlan(func(p map[string]UserNoticeKindSettings) { + e := p["expired"] + e.Mode, e.Loud = "ask", false + p["expired"] = e + }) + if got := produce(t, s, now, 1, ask); got["expired"] != 1 { // a page of one + t.Fatalf("page 1 made %v", got) + } + if got := produce(t, s, now, 1, ask); got["expired"] != 1 { + t.Fatalf("page 2 made %v", got) + } + if got := produce(t, s, now, 1, ask); got["expired"] != 0 { // usr_b switched it off + t.Fatalf("page 3 made %v", got) + } + wantKeys(t, s, "expired", fmt.Sprintf("expired:usr_a:%d", now-60), fmt.Sprintf("expired:usr_c:%d", now-60)) + n := noticeByDedupe(t, s, fmt.Sprintf("expired:usr_a:%d", now-60)) + if n.Approval != UserNoticeApprovalPending || n.Loud || n.DraftID != "" { + t.Errorf("draft = %+v", n) + } + // a draft is not sent until the owner approves it + if ids := leaseIDs(t, s, statusNow.Add(time.Minute), 10); len(ids) != 0 { + t.Errorf("a draft was leased: %v", ids) + } + if got := produce(t, s, now, 100, nil); got != nil { + t.Errorf("an empty plan made %v", got) + } + if got, err := s.ProduceUserStatusNotices(context.Background(), statusNow, 0, ask); err != nil || got != nil { + t.Errorf("no page: %v %v", got, err) + } + for _, d := range keys(t, s, "") { + if strings.Contains(d, "usr_b") { + t.Errorf("a person who switched it off got %s", d) + } + } +} + +func TestUserStatusProofOnSQLite(t *testing.T) { userStatusProof(t, openTemp(t)) } diff --git a/internal/panel/telegram/service.go b/internal/panel/telegram/service.go index d8ad95a0..80e0e817 100644 --- a/internal/panel/telegram/service.go +++ b/internal/panel/telegram/service.go @@ -208,7 +208,7 @@ func (s *Service) SetSources(src Sources) { // outlives it; the edge runs bounded methods from EdgeTick instead. func (s *Service) Run(ctx context.Context) { var wg sync.WaitGroup - for _, f := range []func(context.Context){s.pollLoop, s.sendLoop, s.watchLoop, s.userPollLoop, s.userSendLoop} { + for _, f := range []func(context.Context){s.pollLoop, s.sendLoop, s.watchLoop, s.userPollLoop, s.userSendLoop, s.userStatusLoop} { wg.Add(1) go func() { defer wg.Done(); f(ctx) }() } diff --git a/internal/panel/telegram/user_status.go b/internal/panel/telegram/user_status.go new file mode 100644 index 00000000..6bba0002 --- /dev/null +++ b/internal/panel/telegram/user_status.go @@ -0,0 +1,353 @@ +package telegram + +import ( + "context" + "encoding/json" + "fmt" + "math" + "strconv" + "strings" + "time" + + "github.com/mistgate/mistgate/internal/panel/access" + "github.com/mistgate/mistgate/internal/panel/store" +) + +// The status notices to people (spec 6): expiry_soon, expired, quota_warn, quota_over and restored. The producer here only decides +// what to ask of the store (one read of the settings, then ProduceUserStatusNotices does the work in SQL: who, which event, once); +// the kinds below say how a row reads and whether it is still true when its turn to be sent comes. + +const ( + userStatusEvery = time.Minute // the producers look at the state this often + userStatusPage = 100 // rows of one kind made by one call: the rest waits for the next + userStatusRounds = 10 // calls in a row of the VPS loop while pages come back full +) + +// userStatusLoop is the VPS producer: a pass a minute, and more at once while a pass finds a full page. +func (s *Service) userStatusLoop(ctx context.Context) { + for ctx.Err() == nil { + for range userStatusRounds { + more, err := s.produceUserStatus(ctx) + if err != nil && ctx.Err() == nil { + s.log.Warn("telegram: people's status notices pass failed", "code", "user_telegram_status_pass_failed", "err", err) + } + if err != nil || !more { + break + } + } + s.wait(ctx, userStatusEvery, nil) + } +} + +// ProduceUserStatus is the edge tick's pass: with no chat of a person it is one read; else the settings are read and one batch +// inserts what is missing. What does not fit in the page is made by the next tick. +func (s *Service) ProduceUserStatus(ctx context.Context) error { + _, err := s.produceUserStatus(ctx) + return err +} + +// produceUserStatus is one pass; more says a page came back full. +func (s *Service) produceUserStatus(ctx context.Context) (more bool, err error) { + has, err := s.st.HasUserTelegramChats(ctx) + if err != nil || !has { + return false, err + } + global, err := s.st.UserNotifySettings(ctx) + if err != nil { + return false, err + } + plan := map[string]store.UserNoticeKindSettings{} + for _, kind := range store.UserStatusKinds { + if set, ok := store.ResolveUserNoticeKind(kind, global, nil); ok { + plan[kind] = set + } + } + made, err := s.st.ProduceUserStatusNotices(ctx, s.now(), userStatusPage, plan) + if err != nil { + return false, err + } + for kind, n := range made { + if n > 0 { + s.log.Info("telegram: people's status notices queued", "code", "user_telegram_status_queued", "kind", kind, "count", n) + } + more = more || n >= userStatusPage + } + return more, nil +} + +// userStatusKinds are the kinds of notice that tell a person about the term and the traffic of their access. +func userStatusKinds() map[string]userKind { + return map[string]userKind{ + "expiry_soon": {text: expirySoonText, fresh: freshExpirySoon}, + "expired": {text: expiredText, fresh: freshExpired}, + "quota_warn": {text: quotaWarnText, fresh: freshQuotaWarn}, + "quota_over": {text: quotaOverText, fresh: freshQuotaOver}, + "restored": {text: restoredText, fresh: freshRestored}, + } +} + +// ---- is it still true + +// userView is what a person's access is at now: the status the panel computes (the sweep may not have run yet), the start of +// the quota period and what was used in it. +type userView struct { + status string + periodStart int64 + used uint64 + st store.AccessUserState +} + +func viewUser(st store.AccessUserState, now time.Time) userView { + ps, reset := access.AdvancePeriod(st.QuotaReset, st.PeriodStart, now) + used := st.UsedBytes + if reset { + used = 0 + } + return userView{status: access.ComputeStatus(st.Disabled, st.ExpiresAt, st.QuotaBytes, used, now), periodStart: ps.Unix(), used: used, st: st} +} + +// userViewOf reads the person of a notice; ok is false when there is none any more (the notice is stale). +func (s *Service) userViewOf(ctx context.Context, n store.UserNotice) (v userView, ok bool, err error) { + states, err := s.st.Access().UserStates(ctx, []string{n.UserID}) + if err != nil || len(states) == 0 { + return userView{}, false, err + } + return viewUser(states[0], s.now()), true, nil +} + +// freshWith runs check on the person's view of the notice. +func freshWith(check func(v userView, p userParams) bool) func(context.Context, *Service, store.UserNotice) (bool, error) { + return func(ctx context.Context, s *Service, n store.UserNotice) (bool, error) { + v, ok, err := s.userViewOf(ctx, n) + if err != nil || !ok { + return false, err + } + return check(v, parseUserParams(n.ParamsJSON)), nil + } +} + +// the term is still the one the notice was made for +func sameTerm(v userView, p userParams) bool { + return !v.st.ExpiresAt.IsZero() && v.st.ExpiresAt.Unix() == p.num("expires") +} + +var ( + // "ends soon" does not go after a renewal, nor once the term has ended + freshExpirySoon = freshWith(func(v userView, p userParams) bool { + return sameTerm(v, p) && (v.status == access.StatusActive || v.status == access.StatusLimited) + }) + freshExpired = freshWith(func(v userView, p userParams) bool { return sameTerm(v, p) && v.status == access.StatusExpired }) + // a new period (the usage is reset) or a raised quota takes the warning back, and so does running out: that is quota_over's + freshQuotaWarn = freshWith(func(v userView, p userParams) bool { + return v.status == access.StatusActive && v.periodStart == p.num("period") && v.st.QuotaBytes > 0 && + v.used*100 >= v.st.QuotaBytes*uint64(p.num("pct")) + }) + freshQuotaOver = freshWith(func(v userView, p userParams) bool { + return v.status == access.StatusLimited && v.periodStart == p.num("period") + }) + freshRestored = freshWith(func(v userView, _ userParams) bool { return v.status == access.StatusActive }) +) + +func parseUserParams(raw string) userParams { + var p userParams + _ = json.Unmarshal([]byte(raw), &p) + return p +} + +// num is a whole number of the params (JSON numbers arrive as float64, exact up to 2^53); 0 when it is missing. +func (p userParams) num(key string) int64 { + f, _ := p[key].(float64) + return int64(f) +} + +func (p userParams) str(key string) string { + s, _ := p[key].(string) + return s +} + +// ---- how it reads + +func expirySoonText(lang string, p userParams) string { + exp := p.num("expires") + if exp == 0 { + return "" + } + days, date := userDays(lang, int(max(p.num("days"), 1))), userDate(lang, exp) + return userText{ + ru: "Доступ закончится через " + days + ", " + date + ". Чтобы продлить, напишите тому, кто вас подключил", + en: "Your access ends in " + days + ", on " + date + ". To extend it, contact the person who set it up for you", + zh: "您的访问将在 " + days + "后(" + date + ")到期。如需续期,请联系为您开通的人", + tr: "Erişiminiz " + days + " sonra, " + date + " tarihinde sona erecek. Uzatmak için sizi bağlayan kişiyle iletişime geçin", + fa: "دسترسی شما " + days + " دیگر، " + date + "، به پایان می‌رسد. برای تمدید با کسی که شما را متصل کرده است تماس بگیرید", + }.in(lang) +} + +func expiredText(lang string, p userParams) string { + exp := p.num("expires") + if exp == 0 { + return "" + } + date := userDate(lang, exp) + return userText{ + ru: "Доступ закончился " + date + ". Устройства не подключатся, пока его не продлят", + en: "Your access ended on " + date + ". Devices won’t connect until it’s extended", + zh: "您的访问已于 " + date + "到期。续期之前设备将无法连接", + tr: "Erişiminiz " + date + " tarihinde sona erdi. Uzatılana kadar cihazlar bağlanamaz", + fa: "دسترسی شما در " + date + " به پایان رسید. تا زمانی که تمدید نشود، دستگاه‌ها متصل نمی‌شوند", + }.in(lang) +} + +func quotaWarnText(lang string, p userParams) string { + quota := p.num("quota") + if quota <= 0 { + return "" + } + pct := strconv.FormatInt(max(p.num("used")*100/quota, p.num("pct")), 10) + used, total := userGB(lang, p.num("used")), userGB(lang, quota) + base := userText{ + ru: "Потрачено " + pct + "% трафика: " + used + " из " + total, + en: "You’ve used " + pct + "% of your data: " + used + " of " + total, + zh: "流量已使用 " + pct + "%:" + total + " 中的 " + used, + tr: "Trafiğinizin %" + pct + " kadarı kullanıldı: " + total + " içinden " + used, + fa: faDigits(pct) + "٪ از ترافیک شما مصرف شده است: " + used + " از " + total, + }.in(lang) + next := userNextPeriod(p) + if next == 0 { // a quota that never starts over has no new period to name + return base + } + date := userDate(lang, next) + tail := userText{ + ru: "Новый период начнётся " + date, + en: "A new period starts on " + date, + zh: "新周期将于 " + date + "开始", + tr: "Yeni dönem " + date + " tarihinde başlayacak", + fa: "دوره جدید در " + date + " آغاز می‌شود", + }.in(lang) + if lang == "zh" { + return base + "。" + tail + } + return base + ". " + tail +} + +func quotaOverText(lang string, p userParams) string { + if next := userNextPeriod(p); next != 0 { + date := userDate(lang, next) + return userText{ + ru: "Трафик на этот период закончился. Доступ вернётся " + date + " или раньше, если лимит увеличат", + en: "Your data for this period has run out. Access returns on " + date + ", or sooner if the limit is raised", + zh: "本周期流量已用完。访问将于 " + date + "恢复,若提高限额则会更早恢复", + tr: "Bu dönemlik trafiğiniz bitti. Erişim " + date + " tarihinde geri gelir, limit artırılırsa daha erken", + fa: "ترافیک این دوره تمام شد. دسترسی در " + date + " برمی‌گردد، یا زودتر اگر محدودیت افزایش یابد", + }.in(lang) + } + return userText{ // a quota that never starts over: only a higher limit brings access back + ru: "Трафик закончился. Доступ вернётся, если лимит увеличат", + en: "Your data has run out. Access returns if the limit is raised", + zh: "流量已用完。若提高限额,访问将恢复", + tr: "Trafiğiniz bitti. Limit artırılırsa erişim geri gelir", + fa: "ترافیک شما تمام شد. اگر محدودیت افزایش یابد، دسترسی برمی‌گردد", + }.in(lang) +} + +func restoredText(lang string, _ userParams) string { + return userText{ + ru: "Доступ снова работает. Если устройство не подключается, откройте приложение и обновите его", + en: "Your access works again. If a device doesn’t connect, open the app and refresh it", + zh: "您的访问已恢复。如果设备无法连接,请打开应用并刷新", + tr: "Erişiminiz yeniden çalışıyor. Bir cihaz bağlanmazsa uygulamayı açıp yenileyin", + fa: "دسترسی شما دوباره کار می‌کند. اگر دستگاهی متصل نشد، برنامه را باز کنید و آن را به‌روزرسانی کنید", + }.in(lang) +} + +// userNextPeriod is when the quota period of the notice ends and a new one starts (a unix time); 0 when the quota never starts over. +func userNextPeriod(p userParams) int64 { + next := access.NextReset(p.str("reset"), time.Unix(p.num("period"), 0)) + if next.IsZero() { + return 0 + } + return next.Unix() +} + +// ---- numbers and dates in the language of the chat + +var ( + ruMonths = [12]string{"января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря"} + enMonths = [12]string{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"} + trMonths = [12]string{"Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"} + faMonths = [12]string{"ژانویه", "فوریه", "مارس", "آوریل", "مه", "ژوئن", "ژوئیه", "اوت", "سپتامبر", "اکتبر", "نوامبر", "دسامبر"} +) + +// userDate is a day ("14 декабря", "December 14", "12 月 14 日") of the unix time, in UTC like the periods of the quota. +func userDate(lang string, unixTime int64) string { + t := time.Unix(unixTime, 0).UTC() + d, m := t.Day(), int(t.Month())-1 + switch lang { + case "ru": + return fmt.Sprintf("%d %s", d, ruMonths[m]) + case "zh": + return fmt.Sprintf("%d 月 %d 日", m+1, d) + case "tr": + return fmt.Sprintf("%d %s", d, trMonths[m]) + case "fa": + return faDigits(strconv.Itoa(d)) + " " + faMonths[m] + } + return fmt.Sprintf("%s %d", enMonths[m], d) +} + +// userDays is a number of days with its noun ("1 день", "3 дня", "5 дней"). +func userDays(lang string, n int) string { + switch lang { + case "ru": + noun := "дней" + if n%100 < 11 || n%100 > 14 { + switch n % 10 { + case 1: + noun = "день" + case 2, 3, 4: + noun = "дня" + } + } + return fmt.Sprintf("%d %s", n, noun) + case "zh": + return fmt.Sprintf("%d 天", n) + case "tr": + return fmt.Sprintf("%d gün", n) + case "fa": + return faDigits(strconv.Itoa(n)) + " روز" + } + if n == 1 { + return "1 day" + } + return fmt.Sprintf("%d days", n) +} + +// userGB is an amount of traffic in gigabytes (2^30 bytes, as the quota is entered): one decimal below 10, none above, the +// decimal mark and the unit of the language. +func userGB(lang string, bytes int64) string { + v := float64(bytes) / (1 << 30) + if v >= 10 { + v = math.Round(v) + } else { + v = math.Round(v*10) / 10 + } + s := strconv.FormatFloat(v, 'f', -1, 64) + switch lang { + case "ru": + return strings.Replace(s, ".", ",", 1) + " ГБ" + case "tr": + return strings.Replace(s, ".", ",", 1) + " GB" + case "fa": + return faDigits(strings.Replace(s, ".", "٫", 1)) + " گیگابایت" + } + return s + " GB" +} + +// faDigits writes the digits of s the way Persian does. +func faDigits(s string) string { + return strings.Map(func(r rune) rune { + if r >= '0' && r <= '9' { + return '۰' + (r - '0') + } + return r + }, s) +} diff --git a/internal/panel/telegram/user_status_test.go b/internal/panel/telegram/user_status_test.go new file mode 100644 index 00000000..0b8b4d22 --- /dev/null +++ b/internal/panel/telegram/user_status_test.go @@ -0,0 +1,398 @@ +package telegram + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "testing" + "time" + + "github.com/mistgate/mistgate/internal/panel/store" +) + +// statusEnv is a sendEnv that speaks with the real status kinds, not the test ones. +func newStatusEnv(t *testing.T, opts ...option) *sendEnv { + t.Helper() + e := newSendEnv(t, opts...) + e.svc.kinds = defaultUserKinds() + return e +} + +func (e *sendEnv) setUser(user, set string, args ...any) { + e.t.Helper() + if _, err := e.st.W.Exec(`UPDATE user SET `+set+` WHERE id = ?`, append(args, user)...); err != nil { + e.t.Fatal(err) + } +} + +func (e *sendEnv) produce() { + e.t.Helper() + if err := e.svc.ProduceUserStatus(context.Background()); err != nil { + e.t.Fatalf("produce: %v", err) + } +} + +func (e *sendEnv) dedupes(kind string) []string { + e.t.Helper() + rows, err := e.st.R.Query(`SELECT dedupe FROM user_notice WHERE kind = ? ORDER BY dedupe`, kind) + if err != nil { + e.t.Fatal(err) + } + defer rows.Close() + var out []string + for rows.Next() { + var d string + if err := rows.Scan(&d); err != nil { + e.t.Fatal(err) + } + out = append(out, d) + } + return out +} + +func (e *sendEnv) resultOf(dedupe string) string { + e.t.Helper() + var r string + if err := e.st.R.QueryRow(`SELECT result FROM user_notice WHERE dedupe = ?`, dedupe).Scan(&r); err != nil { + e.t.Fatalf("notice %s: %v", dedupe, err) + } + return r +} + +// The words are the owner's, as the mock shows them: the same numbers, the same dates, filled from the params. +func TestUserStatusTextsAreTheMocks(t *testing.T) { + dec14 := time.Date(2026, 12, 14, 9, 0, 0, 0, time.UTC).Unix() + dec1 := time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC).Unix() + kinds := defaultUserKinds() + render := func(kind, lang string, p userParams) string { return kinds[kind].text(lang, p) } + soon := userParams{"days": 3.0, "expires": float64(dec14)} + for lang, want := range map[string]string{ + "ru": "Доступ закончится через 3 дня, 14 декабря. Чтобы продлить, напишите тому, кто вас подключил", + "en": "Your access ends in 3 days, on December 14. To extend it, contact the person who set it up for you", + "zh": "您的访问将在 3 天后(12 月 14 日)到期。如需续期,请联系为您开通的人", + } { + if got := render("expiry_soon", lang, soon); got != want { + t.Errorf("expiry_soon %s = %q", lang, got) + } + } + for lang, want := range map[string]string{ + "ru": "Доступ закончился 14 декабря. Устройства не подключатся, пока его не продлят", + "en": "Your access ended on December 14. Devices won’t connect until it’s extended", + "zh": "您的访问已于 12 月 14 日到期。续期之前设备将无法连接", + } { + if got := render("expired", lang, userParams{"expires": float64(dec14)}); got != want { + t.Errorf("expired %s = %q", lang, got) + } + } + quota := userParams{"pct": 80.0, "used": float64(80 << 30), "quota": float64(100 << 30), "period": float64(dec1), "reset": "month"} + for lang, want := range map[string]string{ + "ru": "Потрачено 80% трафика: 80 ГБ из 100 ГБ. Новый период начнётся 1 января", + "en": "You’ve used 80% of your data: 80 GB of 100 GB. A new period starts on January 1", + "zh": "流量已使用 80%:100 GB 中的 80 GB。新周期将于 1 月 1 日开始", + } { + if got := render("quota_warn", lang, quota); got != want { + t.Errorf("quota_warn %s = %q", lang, got) + } + } + for lang, want := range map[string]string{ + "ru": "Трафик на этот период закончился. Доступ вернётся 1 января или раньше, если лимит увеличат", + "en": "Your data for this period has run out. Access returns on January 1, or sooner if the limit is raised", + "zh": "本周期流量已用完。访问将于 1 月 1 日恢复,若提高限额则会更早恢复", + } { + if got := render("quota_over", lang, quota); got != want { + t.Errorf("quota_over %s = %q", lang, got) + } + } + for lang, want := range map[string]string{ + "ru": "Доступ снова работает. Если устройство не подключается, откройте приложение и обновите его", + "en": "Your access works again. If a device doesn’t connect, open the app and refresh it", + "zh": "您的访问已恢复。如果设备无法连接,请打开应用并刷新", + } { + if got := render("restored", lang, userParams{}); got != want { + t.Errorf("restored %s = %q", lang, got) + } + } + + // a quota that never starts over names no date; the numbers follow the quota and the language + none := userParams{"days": 1.0, "expires": float64(dec14), "pct": 80.0, "used": float64(8 << 30), "quota": float64(10 << 30), "period": float64(dec1), "reset": "none"} + if got := render("quota_warn", "en", none); got != "You’ve used 80% of your data: 8 GB of 10 GB" { + t.Errorf("no new period: %q", got) + } + if got := render("quota_over", "ru", none); got != "Трафик закончился. Доступ вернётся, если лимит увеличат" { + t.Errorf("over with no new period: %q", got) + } + if got := render("quota_warn", "ru", userParams{"pct": 80.0, "used": float64(1<<30 + 1<<29), "quota": float64(1 << 31), "reset": "none"}); !strings.Contains(got, "1,5 ГБ из 2 ГБ") || !strings.Contains(got, "75%") && !strings.Contains(got, "80%") { + t.Errorf("a fraction of a gigabyte: %q", got) + } + + // ru plural, the date and the days in the other languages + for n, want := range map[int]string{1: "1 день", 2: "2 дня", 5: "5 дней", 11: "11 дней", 21: "21 день", 24: "24 дня", 112: "112 дней"} { + if got := userDays("ru", n); got != want { + t.Errorf("userDays(ru, %d) = %q", n, got) + } + } + if userDays("en", 1) != "1 day" || userDays("en", 2) != "2 days" || userDate("tr", dec14) != "14 Aralık" || userDate("fa", dec14) != "۱۴ دسامبر" { + t.Error("days and dates in en, tr, fa") + } + + all := userParams{"days": 3.0, "expires": float64(dec14), "pct": 80.0, "used": float64(80 << 30), "quota": float64(100 << 30), "period": float64(dec1), "reset": "month"} + // every text exists in all five languages and says what the bot may say: no link, none of the words the panel avoids + for _, kind := range store.UserStatusKinds { + for _, lang := range []string{"ru", "en", "zh", "tr", "fa"} { + for name, p := range map[string]userParams{"dated": all, "none": none} { + s := render(kind, lang, p) + low := strings.ToLower(s) + if s == "" || strings.Contains(low, "vpn") || strings.Contains(low, "прокси") || strings.Contains(low, "обход") || strings.Contains(low, "http") || + strings.Contains(low, "t.me") || strings.ContainsAny(s, "<>&") { + t.Errorf("%s/%s/%s: %q", kind, lang, name, s) + } + } + } + } + // a row with no usable numbers says nothing (the sender drops it) rather than a sentence with a hole in it + if render("expired", "en", userParams{}) != "" || render("expiry_soon", "en", userParams{}) != "" || render("quota_warn", "en", userParams{}) != "" { + t.Error("a notice with no params was rendered") + } +} + +// From the state of a person to the message in their chat: made once, sent in their language, quiet or loud by kind. +func TestUserStatusEndToEnd(t *testing.T) { + e := newStatusEnv(t) + e.addUser("usr_a") + e.joinChat("usr_a", 500, "en") + e.reset() + start := e.clk.now() + + // the 3-day mark passes after the chat was linked + end := start.Add(3*24*time.Hour + time.Hour) + e.setUser("usr_a", `expires_at = ?`, end.Unix()) + e.produce() + if got := e.dedupes("expiry_soon"); len(got) != 0 { + t.Fatalf("before the mark: %q", got) + } + e.clk.advance(2 * time.Hour) + e.produce() + e.produce() + key := fmt.Sprintf("expiry_soon:usr_a:%d:3", end.Unix()) + if got := e.dedupes("expiry_soon"); len(got) != 1 || got[0] != key { + t.Fatalf("after the mark: %q", got) + } + e.pass() + msgs := e.utg.sentTo(500) + want := "Your access ends in 3 days, on " + userDate("en", end.Unix()) + ". To extend it, contact the person who set it up for you" + if len(msgs) != 1 || msgs[0] != want { + t.Fatalf("messages = %q, want %q", msgs, want) + } + if m := e.sentMsgs(); !m[0].Silent { + t.Error("expiry_soon is quiet by default") + } + + // the term ends: loud, once; the sweep (here by hand) marks the person expired + e.clk.advance(3*24*time.Hour + time.Hour) + e.produce() + if got := e.dedupes("expired"); len(got) != 1 { + t.Fatalf("expired: %q", got) + } + e.pass() + if got := e.utg.sentTo(500); len(got) != 2 || !strings.HasPrefix(got[1], "Your access ended on "+userDate("en", end.Unix())) { + t.Fatalf("messages = %q", got) + } + if m := e.sentMsgs(); m[1].Silent { + t.Error("expired is loud by default") + } + e.setUser("usr_a", `status = 'expired'`) + e.produce() + if e.dedupes("restored") != nil { + t.Fatalf("restored while expired: %q", e.dedupes("restored")) + } + + // the term is renewed: restored, quiet, once + e.setUser("usr_a", `expires_at = ?, status = 'active'`, e.clk.now().Add(30*24*time.Hour).Unix()) + e.produce() + e.produce() + if got := e.dedupes("restored"); len(got) != 1 { + t.Fatalf("restored: %q", got) + } + e.pass() + got := e.utg.sentTo(500) + if len(got) != 3 || got[2] != "Your access works again. If a device doesn’t connect, open the app and refresh it" { + t.Fatalf("messages = %q", got) + } + if m := e.sentMsgs(); !m[2].Silent { + t.Error("restored is quiet by default") + } + e.produce() + if n := e.pass(); n != 0 { + t.Errorf("a finished history made %d more notices", n) + } +} + +// A notice that is no longer true when its turn comes is not sent: renewed, a new period, a raised quota. +func TestUserStatusFreshChecks(t *testing.T) { + e := newStatusEnv(t) + e.addUser("usr_a") + e.joinChat("usr_a", 500, "en") + e.reset() + now := e.clk.now() + period := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC).Unix() // the monthly quota period that is running + // a person at 85% of the quota whose 1-day mark passes now: a warning and that mark are made + e.setUser("usr_a", `expires_at = ?, quota_bytes = 1000, used_bytes = 850, period_start = ?, quota_reset = 'month'`, now.Add(24*time.Hour).Unix(), period) + e.clk.advance(time.Second) + if _, err := e.st.W.Exec(`INSERT INTO node (id, name, address, state, created_at) VALUES ('nod_1', 'n', 'n.example.com', 'active', 1)`); err != nil { + t.Fatal(err) + } + if _, err := e.st.W.Exec(`INSERT INTO traffic_bucket (user_id, node_id, protocol, hour_start, bytes_up, bytes_down) VALUES ('usr_a', 'nod_1', 'hysteria2', ?, 300, 0)`, + e.clk.now().Unix()/3600*3600); err != nil { + t.Fatal(err) + } + e.produce() + if len(e.dedupes("expiry_soon")) != 1 || len(e.dedupes("quota_warn")) != 1 { + t.Fatalf("made %q and %q", e.dedupes("expiry_soon"), e.dedupes("quota_warn")) + } + + // before they are sent: the term is renewed (the mark is no longer true) and the quota is raised + e.setUser("usr_a", `expires_at = ?, quota_bytes = 100000`, e.clk.now().Add(60*24*time.Hour).Unix()) + e.pass() + if got := e.utg.sentTo(500); len(got) != 0 { + t.Errorf("stale notices were sent: %q", got) + } + for _, d := range append(e.dedupes("expiry_soon"), e.dedupes("quota_warn")...) { + if r := e.resultOf(d); r != store.UserNoticeSkippedStale { + t.Errorf("%s: %s", d, r) + } + } + // and with the term and quota as they were, the same kinds are true + for _, tc := range []struct { + kind, params string + set string + args []any + fresh bool + }{ + {"expired", `{"expires":%d}`, `expires_at = ?`, []any{now.Add(-time.Hour).Unix()}, true}, + {"expired", `{"expires":%d}`, `expires_at = ?`, []any{now.Add(time.Hour).Unix()}, false}, + {"expired", `{"expires":%d}`, `expires_at = ?, disabled = 1`, []any{now.Add(-time.Hour).Unix()}, false}, + {"expiry_soon", `{"days":3,"expires":%d}`, `expires_at = ?`, []any{now.Add(48 * time.Hour).Unix()}, true}, + {"quota_over", `{"period":` + fmt.Sprint(period) + `,"used":1000,"quota":1000,"reset":"month"}`, `quota_bytes = 1000, used_bytes = 1000, expires_at = NULL`, nil, true}, + {"quota_over", `{"period":` + fmt.Sprint(period) + `}`, `quota_bytes = 1000, used_bytes = 1000, expires_at = NULL, period_start = 1`, nil, false}, // the sweep has not run: the period is over + {"quota_over", `{"period":1,"used":1000,"quota":1000,"reset":"month"}`, `quota_bytes = 1000, used_bytes = 1000, expires_at = NULL`, nil, false}, + {"quota_over", `{"period":` + fmt.Sprint(period) + `}`, `quota_bytes = 1000, used_bytes = 100, expires_at = NULL`, nil, false}, + {"quota_warn", `{"pct":80,"period":` + fmt.Sprint(period) + `}`, `quota_bytes = 1000, used_bytes = 900, expires_at = NULL`, nil, true}, + {"quota_warn", `{"pct":80,"period":` + fmt.Sprint(period) + `}`, `quota_bytes = 1000, used_bytes = 1000, expires_at = NULL`, nil, false}, // over: quota_over's + {"restored", `{}`, `quota_bytes = 1000, used_bytes = 100, expires_at = NULL`, nil, true}, + {"restored", `{}`, `quota_bytes = 1000, used_bytes = 1000, expires_at = NULL`, nil, false}, + } { + e.setUser("usr_a", `disabled = 0, quota_bytes = 0, used_bytes = 0, expires_at = NULL, period_start = ?`, period) + params := tc.params + if strings.Contains(params, "%d") { + params = fmt.Sprintf(params, tc.args[0]) + } + e.setUser("usr_a", tc.set, tc.args...) + n := store.UserNotice{UserID: "usr_a", ParamsJSON: params} + ok, err := defaultUserKinds()[tc.kind].fresh(context.Background(), e.svc, n) + if err != nil || ok != tc.fresh { + t.Errorf("%s %s with %s: fresh = %v, %v; want %v", tc.kind, params, tc.set, ok, err, tc.fresh) + } + } + // a person who is gone: nothing to tell + if ok, err := defaultUserKinds()["restored"].fresh(context.Background(), e.svc, store.UserNotice{UserID: "usr_gone"}); err != nil || ok { + t.Errorf("a missing person: %v %v", ok, err) + } +} + +// A person with no chat gets nothing; the owner's settings decide: off makes nothing, ask makes a draft that does not go out, the +// per-person off is honoured; with no chat anywhere a pass reads one row. +func TestUserStatusModes(t *testing.T) { + e := newStatusEnv(t) + e.addUser("usr_a") + e.addUser("usr_b") + e.addUser("usr_none") + ctx := context.Background() + past := e.clk.now().Add(-time.Minute).Unix() + for _, u := range []string{"usr_a", "usr_b", "usr_none"} { + e.setUser(u, `expires_at = ?`, past) + } + e.produce() // no chat anywhere: nothing to do + if len(e.dedupes("expired")) != 0 { + t.Fatal("a person with no chat got a notice") + } + e.clk.advance(-time.Hour) // the chats are linked before the event + e.joinChat("usr_a", 500, "en") + e.joinChat("usr_b", 600, "en") + e.clk.advance(time.Hour) + e.reset() + + set := func(kind, value string) { + t.Helper() + if err := e.st.SetUserNotifySetting(ctx, store.UserNoticeSettingPrefix+kind, value); err != nil { + t.Fatal(err) + } + } + set("expired", `{"mode":"off"}`) + e.produce() + if len(e.dedupes("expired")) != 0 { + t.Fatal("an off kind made a notice") + } + set("expired", `{"mode":"ask","loud":false}`) + if err := e.st.SetUserNotifyOverride(ctx, "usr_b", store.UserNoticeOffKey, `["expired"]`); err != nil { + t.Fatal(err) + } + e.produce() + got := e.dedupes("expired") + if len(got) != 1 || got[0] != fmt.Sprintf("expired:usr_a:%d", past) { + t.Fatalf("ask: %q (usr_b switched it off, usr_none has no chat)", got) + } + var approval string + var loud bool + if err := e.st.R.QueryRow(`SELECT approval, loud FROM user_notice WHERE kind = 'expired'`).Scan(&approval, &loud); err != nil || approval != store.UserNoticeApprovalPending || loud { + t.Fatalf("draft: %q %v %v", approval, loud, err) + } + if n := e.pass(); n != 0 || len(e.utg.sentTo(500)) != 0 { + t.Errorf("a draft went out: %d, %q", n, e.utg.sentTo(500)) + } + set("expired", `{"mode":"auto"}`) // the draft stays what it is: one event, one row + e.produce() + if len(e.dedupes("expired")) != 1 { + t.Errorf("a second row for the event: %q", e.dedupes("expired")) + } +} + +func TestUserStatusOnTheEdgeIsOneReadWithNoChat(t *testing.T) { + e := newStatusEnv(t, func(c *Config) { c.Edge = true }) + e.addUser("usr_a") + e.setUser("usr_a", `expires_at = ?`, e.clk.now().Add(-time.Minute).Unix()) + if err := e.svc.ProduceUserStatus(context.Background()); err != nil || len(e.dedupes("expired")) != 0 { + t.Fatalf("no chat: %v %q", err, e.dedupes("expired")) + } + if _, err := e.st.W.Exec(`DELETE FROM user_notice`); err != nil { + t.Fatal(err) + } + // the VPS loop makes a pass of its own and stops with its context + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { e.svc.userStatusLoop(ctx); close(done) }() + cancel() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("the status loop did not stop") + } +} + +// The params are what the text is rendered from and a person's own data: no name, no chat id. +func TestUserStatusRowsHoldNoPersonalData(t *testing.T) { + e := newStatusEnv(t) + e.addUser("usr_a") + e.setUser("usr_a", `name = 'Alice Example'`) + e.joinChat("usr_a", 987654, "en") + e.setUser("usr_a", `expires_at = ?`, e.clk.now().Add(-time.Second).Unix()) + e.produce() + var params string + if err := e.st.R.QueryRow(`SELECT params_json FROM user_notice WHERE kind = 'expired'`).Scan(¶ms); err != nil { + t.Fatal(err) + } + var back map[string]any + if err := json.Unmarshal([]byte(params), &back); err != nil || len(back) != 1 || strings.Contains(params, "Alice") || strings.Contains(params, "987654") { + t.Errorf("params = %s, %v", params, err) + } +} diff --git a/internal/panel/telegram/user_texts.go b/internal/panel/telegram/user_texts.go index 96e21539..a66721fa 100644 --- a/internal/panel/telegram/user_texts.go +++ b/internal/panel/telegram/user_texts.go @@ -139,7 +139,8 @@ type userKind struct { } // defaultUserKinds is the registry of a new Service: kind -> how it is rendered and checked. The kinds arrive with the steps that -// produce them (status, owner's actions, incidents, broadcast); a notice of a kind that is not here is dropped, never sent raw. +// produce them (the status kinds are in user_status.go; the owner's actions, incidents and broadcast follow); a notice of a kind +// that is not here is dropped, never sent raw. func defaultUserKinds() map[string]userKind { - return map[string]userKind{} + return userStatusKinds() }