Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions cmd/mistgate-edge/testdata/bridge.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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;
Expand All @@ -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");
Expand All @@ -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
Expand Down
12 changes: 6 additions & 6 deletions edge/bridge/cron_js_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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.
Expand Down
8 changes: 6 additions & 2 deletions internal/panel/app/edge_tick.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)",
}
Expand Down Expand Up @@ -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)
})
Expand Down
7 changes: 7 additions & 0 deletions internal/panel/store/d1_user_status_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
//go:build js && wasm

package store

import "testing"

func TestD1UserStatus(t *testing.T) { userStatusProof(t, openD1Store(t)) }
1 change: 1 addition & 0 deletions internal/panel/store/transaction_shapes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
97 changes: 97 additions & 0 deletions internal/panel/store/user_notice_kinds.go
Original file line number Diff line number Diff line change
@@ -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.<kind>": 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
}
Loading
Loading