From a2bf8be33ea81b5ee96a8f62a5cd75dad7546023 Mon Sep 17 00:00:00 2001 From: Daniyar Ennanov <21172041+limeflash@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:55:17 +0300 Subject: [PATCH 1/3] User notifications, step 3: the sender of the notices to people The outbox user_notice now drains through the people's bot. A pass leases the due rows that have the Telegram channel (a row for the app alone is never leased: the app pulls it), gathers one person's rows into one message per chat in the chat's language (panel language when it has none), loud when any line is loud and disable_notification otherwise, and skips announcements for a chat that said /mute. Kinds come from a registry (text and "still true" check) that the later steps fill; an unknown kind is dropped with a code, a stale one is skipped_stale. Pace is 20 messages a second per bot and one a second per chat. 429 stops the pass and puts the rows back at retry_after; a refused token (401) writes "unauthorized" on the bot's card and the queue waits, neither spends an attempt. 5xx or no answer retries after 1, 2, 4 ... 64 minutes and drops on the eighth failure. 403 or "chat not found" forgets the chat, and a person left with none gets "unlinked". The message ids are kept per chat row id (never the Telegram chat id), so a retry after a partial send does not repeat to the chats that have it. A pass cut short puts its rows back at once. The VPS runs the pass in a loop of Run; the edge tick runs one bounded pass after a one-row read (HasDueUserNotices). "Test" button of a chat: UserNotifyService.TestUserTelegramChat (owner and helper, like Unlink) sends a fixed text in the chat's language at once, outside the outbox; a blocked bot unlinks the chat. Texts in ru/en/zh/tr/fa. Edge: jobs Worker +87 KiB (253 KiB left under its limit), admin +36 KiB, public +16 KiB; no limit raised. The cron test counts one more D1 read per tick. Co-Authored-By: Claude Sonnet 5.5 --- edge/bridge/cron_js_test.go | 14 +- gen/mistgate/usernotify/v1/usernotify.pb.go | 31 +- .../usernotifyv1connect/usernotify.connect.go | 35 + internal/panel/app/edge_tick.go | 6 +- internal/panel/auth/policy.go | 1 + internal/panel/auth/policy_usernotify.go | 1 + internal/panel/auth/policy_usernotify_test.go | 2 + internal/panel/store/user_notice.go | 24 +- internal/panel/store/user_notify_test.go | 94 ++ internal/panel/store/user_telegram.go | 19 + internal/panel/telegram/client.go | 13 + internal/panel/telegram/service.go | 8 +- internal/panel/telegram/testenv_test.go | 14 +- internal/panel/telegram/user_admin.go | 76 ++ internal/panel/telegram/user_send.go | 465 ++++++++++ internal/panel/telegram/user_send_test.go | 817 ++++++++++++++++++ internal/panel/telegram/user_texts.go | 34 + .../panel/telegram/usernotifyrpc/service.go | 7 + proto/mistgate/usernotify/v1/usernotify.proto | 4 + .../mistgate/usernotify/v1/usernotify_pb.ts | 14 +- 20 files changed, 1647 insertions(+), 32 deletions(-) create mode 100644 internal/panel/telegram/user_send.go create mode 100644 internal/panel/telegram/user_send_test.go diff --git a/edge/bridge/cron_js_test.go b/edge/bridge/cron_js_test.go index 708eea06e..53df8ef9e 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 and updates each add one read, 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. + // Telegram adds two reads (a link code waiting, 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 != 21 { - t.Fatalf("cron used %d sequential D1 calls, want 21 (6 tick + updates read + Telegram code 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 != 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 := 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. 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 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. // 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 != 39 { - t.Fatalf("minute 17 cron used %d sequential D1 calls, want 39 (5 tick + 2 updates + Telegram code 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 != 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) } // 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/gen/mistgate/usernotify/v1/usernotify.pb.go b/gen/mistgate/usernotify/v1/usernotify.pb.go index fd0d9137b..a9019747a 100644 --- a/gen/mistgate/usernotify/v1/usernotify.pb.go +++ b/gen/mistgate/usernotify/v1/usernotify.pb.go @@ -733,7 +733,7 @@ const file_mistgate_usernotify_v1_usernotify_proto_rawDesc = "" + "\x05muted\x18\x03 \x01(\bR\x05muted\"D\n" + "\x13SetChatLimitRequest\x12\x17\n" + "\auser_id\x18\x01 \x01(\tR\x06userId\x12\x14\n" + - "\x05limit\x18\x02 \x01(\x05R\x05limit2\xfa\x06\n" + + "\x05limit\x18\x02 \x01(\x05R\x05limit2\xd2\a\n" + "\x11UserNotifyService\x12L\n" + "\n" + "GetUserBot\x12\x1d.mistgate.usernotify.v1.Empty\x1a\x1f.mistgate.usernotify.v1.UserBot\x12c\n" + @@ -744,7 +744,8 @@ const file_mistgate_usernotify_v1_usernotify_proto_rawDesc = "" + "\x16CancelUserTelegramLink\x12\x1f.mistgate.usernotify.v1.UserRef\x1a\x1d.mistgate.usernotify.v1.Empty\x12o\n" + "\x15ListUserTelegramChats\x12\x1f.mistgate.usernotify.v1.UserRef\x1a5.mistgate.usernotify.v1.ListUserTelegramChatsResponse\x12X\n" + "\x16UnlinkUserTelegramChat\x12\x1f.mistgate.usernotify.v1.ChatRef\x1a\x1d.mistgate.usernotify.v1.Empty\x12f\n" + - "\x18SetUserTelegramChatMuted\x12+.mistgate.usernotify.v1.SetChatMutedRequest\x1a\x1d.mistgate.usernotify.v1.Empty\x12f\n" + + "\x18SetUserTelegramChatMuted\x12+.mistgate.usernotify.v1.SetChatMutedRequest\x1a\x1d.mistgate.usernotify.v1.Empty\x12V\n" + + "\x14TestUserTelegramChat\x12\x1f.mistgate.usernotify.v1.ChatRef\x1a\x1d.mistgate.usernotify.v1.Empty\x12f\n" + "\x18SetUserTelegramChatLimit\x12+.mistgate.usernotify.v1.SetChatLimitRequest\x1a\x1d.mistgate.usernotify.v1.EmptyB\xed\x01\n" + "\x1acom.mistgate.usernotify.v1B\x0fUsernotifyProtoP\x01ZDgithub.com/mistgate/mistgate/gen/mistgate/usernotify/v1;usernotifyv1\xa2\x02\x03MUX\xaa\x02\x16Mistgate.Usernotify.V1\xca\x02\x16Mistgate\\Usernotify\\V1\xe2\x02\"Mistgate\\Usernotify\\V1\\GPBMetadata\xea\x02\x18Mistgate::Usernotify::V1b\x06proto3" @@ -785,18 +786,20 @@ var file_mistgate_usernotify_v1_usernotify_proto_depIdxs = []int32{ 4, // 7: mistgate.usernotify.v1.UserNotifyService.ListUserTelegramChats:input_type -> mistgate.usernotify.v1.UserRef 8, // 8: mistgate.usernotify.v1.UserNotifyService.UnlinkUserTelegramChat:input_type -> mistgate.usernotify.v1.ChatRef 9, // 9: mistgate.usernotify.v1.UserNotifyService.SetUserTelegramChatMuted:input_type -> mistgate.usernotify.v1.SetChatMutedRequest - 10, // 10: mistgate.usernotify.v1.UserNotifyService.SetUserTelegramChatLimit:input_type -> mistgate.usernotify.v1.SetChatLimitRequest - 1, // 11: mistgate.usernotify.v1.UserNotifyService.GetUserBot:output_type -> mistgate.usernotify.v1.UserBot - 3, // 12: mistgate.usernotify.v1.UserNotifyService.SetUserBot:output_type -> mistgate.usernotify.v1.SetUserBotResponse - 3, // 13: mistgate.usernotify.v1.UserNotifyService.ClearUserBot:output_type -> mistgate.usernotify.v1.SetUserBotResponse - 5, // 14: mistgate.usernotify.v1.UserNotifyService.BeginUserTelegramLink:output_type -> mistgate.usernotify.v1.UserTelegramLink - 0, // 15: mistgate.usernotify.v1.UserNotifyService.CancelUserTelegramLink:output_type -> mistgate.usernotify.v1.Empty - 7, // 16: mistgate.usernotify.v1.UserNotifyService.ListUserTelegramChats:output_type -> mistgate.usernotify.v1.ListUserTelegramChatsResponse - 0, // 17: mistgate.usernotify.v1.UserNotifyService.UnlinkUserTelegramChat:output_type -> mistgate.usernotify.v1.Empty - 0, // 18: mistgate.usernotify.v1.UserNotifyService.SetUserTelegramChatMuted:output_type -> mistgate.usernotify.v1.Empty - 0, // 19: mistgate.usernotify.v1.UserNotifyService.SetUserTelegramChatLimit:output_type -> mistgate.usernotify.v1.Empty - 11, // [11:20] is the sub-list for method output_type - 2, // [2:11] is the sub-list for method input_type + 8, // 10: mistgate.usernotify.v1.UserNotifyService.TestUserTelegramChat:input_type -> mistgate.usernotify.v1.ChatRef + 10, // 11: mistgate.usernotify.v1.UserNotifyService.SetUserTelegramChatLimit:input_type -> mistgate.usernotify.v1.SetChatLimitRequest + 1, // 12: mistgate.usernotify.v1.UserNotifyService.GetUserBot:output_type -> mistgate.usernotify.v1.UserBot + 3, // 13: mistgate.usernotify.v1.UserNotifyService.SetUserBot:output_type -> mistgate.usernotify.v1.SetUserBotResponse + 3, // 14: mistgate.usernotify.v1.UserNotifyService.ClearUserBot:output_type -> mistgate.usernotify.v1.SetUserBotResponse + 5, // 15: mistgate.usernotify.v1.UserNotifyService.BeginUserTelegramLink:output_type -> mistgate.usernotify.v1.UserTelegramLink + 0, // 16: mistgate.usernotify.v1.UserNotifyService.CancelUserTelegramLink:output_type -> mistgate.usernotify.v1.Empty + 7, // 17: mistgate.usernotify.v1.UserNotifyService.ListUserTelegramChats:output_type -> mistgate.usernotify.v1.ListUserTelegramChatsResponse + 0, // 18: mistgate.usernotify.v1.UserNotifyService.UnlinkUserTelegramChat:output_type -> mistgate.usernotify.v1.Empty + 0, // 19: mistgate.usernotify.v1.UserNotifyService.SetUserTelegramChatMuted:output_type -> mistgate.usernotify.v1.Empty + 0, // 20: mistgate.usernotify.v1.UserNotifyService.TestUserTelegramChat:output_type -> mistgate.usernotify.v1.Empty + 0, // 21: mistgate.usernotify.v1.UserNotifyService.SetUserTelegramChatLimit:output_type -> mistgate.usernotify.v1.Empty + 12, // [12:22] is the sub-list for method output_type + 2, // [2:12] is the sub-list for method input_type 2, // [2:2] is the sub-list for extension type_name 2, // [2:2] is the sub-list for extension extendee 0, // [0:2] is the sub-list for field type_name diff --git a/gen/mistgate/usernotify/v1/usernotifyv1connect/usernotify.connect.go b/gen/mistgate/usernotify/v1/usernotifyv1connect/usernotify.connect.go index 374afdf68..363559ee8 100644 --- a/gen/mistgate/usernotify/v1/usernotifyv1connect/usernotify.connect.go +++ b/gen/mistgate/usernotify/v1/usernotifyv1connect/usernotify.connect.go @@ -57,6 +57,9 @@ const ( // UserNotifyServiceSetUserTelegramChatMutedProcedure is the fully-qualified name of the // UserNotifyService's SetUserTelegramChatMuted RPC. UserNotifyServiceSetUserTelegramChatMutedProcedure = "/mistgate.usernotify.v1.UserNotifyService/SetUserTelegramChatMuted" + // UserNotifyServiceTestUserTelegramChatProcedure is the fully-qualified name of the + // UserNotifyService's TestUserTelegramChat RPC. + UserNotifyServiceTestUserTelegramChatProcedure = "/mistgate.usernotify.v1.UserNotifyService/TestUserTelegramChat" // UserNotifyServiceSetUserTelegramChatLimitProcedure is the fully-qualified name of the // UserNotifyService's SetUserTelegramChatLimit RPC. UserNotifyServiceSetUserTelegramChatLimitProcedure = "/mistgate.usernotify.v1.UserNotifyService/SetUserTelegramChatLimit" @@ -80,6 +83,10 @@ type UserNotifyServiceClient interface { UnlinkUserTelegramChat(context.Context, *connect.Request[v1.ChatRef]) (*connect.Response[v1.Empty], error) // Switches the announcements of one chat off or on. SetUserTelegramChatMuted(context.Context, *connect.Request[v1.SetChatMutedRequest]) (*connect.Response[v1.Empty], error) + // Sends the fixed test message to one chat at once (not through the outbox), in the language of the chat, and answers when + // Telegram took it. A chat that blocked the bot is forgotten. FAILED_PRECONDITION: "telegram_blocked", "telegram_unauthorized", + // "user_bot_not_configured". UNAVAILABLE: "telegram_unreachable". RESOURCE_EXHAUSTED: "telegram_test_too_soon" (one in 10 s). + TestUserTelegramChat(context.Context, *connect.Request[v1.ChatRef]) (*connect.Response[v1.Empty], error) // The chat limit: of everybody (user_id empty) or of one person, 1 to 10; 0 returns to the default. Owner only. SetUserTelegramChatLimit(context.Context, *connect.Request[v1.SetChatLimitRequest]) (*connect.Response[v1.Empty], error) } @@ -143,6 +150,12 @@ func NewUserNotifyServiceClient(httpClient connect.HTTPClient, baseURL string, o connect.WithSchema(userNotifyServiceMethods.ByName("SetUserTelegramChatMuted")), connect.WithClientOptions(opts...), ), + testUserTelegramChat: connect.NewClient[v1.ChatRef, v1.Empty]( + httpClient, + baseURL+UserNotifyServiceTestUserTelegramChatProcedure, + connect.WithSchema(userNotifyServiceMethods.ByName("TestUserTelegramChat")), + connect.WithClientOptions(opts...), + ), setUserTelegramChatLimit: connect.NewClient[v1.SetChatLimitRequest, v1.Empty]( httpClient, baseURL+UserNotifyServiceSetUserTelegramChatLimitProcedure, @@ -162,6 +175,7 @@ type userNotifyServiceClient struct { listUserTelegramChats *connect.Client[v1.UserRef, v1.ListUserTelegramChatsResponse] unlinkUserTelegramChat *connect.Client[v1.ChatRef, v1.Empty] setUserTelegramChatMuted *connect.Client[v1.SetChatMutedRequest, v1.Empty] + testUserTelegramChat *connect.Client[v1.ChatRef, v1.Empty] setUserTelegramChatLimit *connect.Client[v1.SetChatLimitRequest, v1.Empty] } @@ -205,6 +219,11 @@ func (c *userNotifyServiceClient) SetUserTelegramChatMuted(ctx context.Context, return c.setUserTelegramChatMuted.CallUnary(ctx, req) } +// TestUserTelegramChat calls mistgate.usernotify.v1.UserNotifyService.TestUserTelegramChat. +func (c *userNotifyServiceClient) TestUserTelegramChat(ctx context.Context, req *connect.Request[v1.ChatRef]) (*connect.Response[v1.Empty], error) { + return c.testUserTelegramChat.CallUnary(ctx, req) +} + // SetUserTelegramChatLimit calls mistgate.usernotify.v1.UserNotifyService.SetUserTelegramChatLimit. func (c *userNotifyServiceClient) SetUserTelegramChatLimit(ctx context.Context, req *connect.Request[v1.SetChatLimitRequest]) (*connect.Response[v1.Empty], error) { return c.setUserTelegramChatLimit.CallUnary(ctx, req) @@ -229,6 +248,10 @@ type UserNotifyServiceHandler interface { UnlinkUserTelegramChat(context.Context, *connect.Request[v1.ChatRef]) (*connect.Response[v1.Empty], error) // Switches the announcements of one chat off or on. SetUserTelegramChatMuted(context.Context, *connect.Request[v1.SetChatMutedRequest]) (*connect.Response[v1.Empty], error) + // Sends the fixed test message to one chat at once (not through the outbox), in the language of the chat, and answers when + // Telegram took it. A chat that blocked the bot is forgotten. FAILED_PRECONDITION: "telegram_blocked", "telegram_unauthorized", + // "user_bot_not_configured". UNAVAILABLE: "telegram_unreachable". RESOURCE_EXHAUSTED: "telegram_test_too_soon" (one in 10 s). + TestUserTelegramChat(context.Context, *connect.Request[v1.ChatRef]) (*connect.Response[v1.Empty], error) // The chat limit: of everybody (user_id empty) or of one person, 1 to 10; 0 returns to the default. Owner only. SetUserTelegramChatLimit(context.Context, *connect.Request[v1.SetChatLimitRequest]) (*connect.Response[v1.Empty], error) } @@ -288,6 +311,12 @@ func NewUserNotifyServiceHandler(svc UserNotifyServiceHandler, opts ...connect.H connect.WithSchema(userNotifyServiceMethods.ByName("SetUserTelegramChatMuted")), connect.WithHandlerOptions(opts...), ) + userNotifyServiceTestUserTelegramChatHandler := connect.NewUnaryHandler( + UserNotifyServiceTestUserTelegramChatProcedure, + svc.TestUserTelegramChat, + connect.WithSchema(userNotifyServiceMethods.ByName("TestUserTelegramChat")), + connect.WithHandlerOptions(opts...), + ) userNotifyServiceSetUserTelegramChatLimitHandler := connect.NewUnaryHandler( UserNotifyServiceSetUserTelegramChatLimitProcedure, svc.SetUserTelegramChatLimit, @@ -312,6 +341,8 @@ func NewUserNotifyServiceHandler(svc UserNotifyServiceHandler, opts ...connect.H userNotifyServiceUnlinkUserTelegramChatHandler.ServeHTTP(w, r) case UserNotifyServiceSetUserTelegramChatMutedProcedure: userNotifyServiceSetUserTelegramChatMutedHandler.ServeHTTP(w, r) + case UserNotifyServiceTestUserTelegramChatProcedure: + userNotifyServiceTestUserTelegramChatHandler.ServeHTTP(w, r) case UserNotifyServiceSetUserTelegramChatLimitProcedure: userNotifyServiceSetUserTelegramChatLimitHandler.ServeHTTP(w, r) default: @@ -355,6 +386,10 @@ func (UnimplementedUserNotifyServiceHandler) SetUserTelegramChatMuted(context.Co return nil, connect.NewError(connect.CodeUnimplemented, errors.New("mistgate.usernotify.v1.UserNotifyService.SetUserTelegramChatMuted is not implemented")) } +func (UnimplementedUserNotifyServiceHandler) TestUserTelegramChat(context.Context, *connect.Request[v1.ChatRef]) (*connect.Response[v1.Empty], error) { + return nil, connect.NewError(connect.CodeUnimplemented, errors.New("mistgate.usernotify.v1.UserNotifyService.TestUserTelegramChat is not implemented")) +} + func (UnimplementedUserNotifyServiceHandler) SetUserTelegramChatLimit(context.Context, *connect.Request[v1.SetChatLimitRequest]) (*connect.Response[v1.Empty], error) { return nil, connect.NewError(connect.CodeUnimplemented, errors.New("mistgate.usernotify.v1.UserNotifyService.SetUserTelegramChatLimit is not implemented")) } diff --git a/internal/panel/app/edge_tick.go b/internal/panel/app/edge_tick.go index 56350f1f7..eff73562d 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, and delivers queued messages", + "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)", "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,6 +143,10 @@ 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. + run("telegram user notices", func(ctx context.Context) error { + return p.Telegram.SendUserNotices(ctx) + }) } if p.Cheburcheck != nil { runFor("cheburcheck", 40*time.Second, func(ctx context.Context) error { diff --git a/internal/panel/auth/policy.go b/internal/panel/auth/policy.go index 62b5428ba..4e4c73525 100644 --- a/internal/panel/auth/policy.go +++ b/internal/panel/auth/policy.go @@ -358,6 +358,7 @@ var procedureLevels = map[string]level{ UserNotifyListChatsProcedure: levelRead, UserNotifyUnlinkChatProcedure: levelWrite, UserNotifySetChatMutedProcedure: levelWrite, + UserNotifyTestChatProcedure: levelWrite, UserNotifySetChatLimitProcedure: levelOwner, adminv1connect.UserServiceListUsersProcedure: levelRead, diff --git a/internal/panel/auth/policy_usernotify.go b/internal/panel/auth/policy_usernotify.go index ddb014506..626e9fb3b 100644 --- a/internal/panel/auth/policy_usernotify.go +++ b/internal/panel/auth/policy_usernotify.go @@ -17,5 +17,6 @@ const ( UserNotifyListChatsProcedure = "/mistgate.usernotify.v1.UserNotifyService/ListUserTelegramChats" UserNotifyUnlinkChatProcedure = "/mistgate.usernotify.v1.UserNotifyService/UnlinkUserTelegramChat" UserNotifySetChatMutedProcedure = "/mistgate.usernotify.v1.UserNotifyService/SetUserTelegramChatMuted" + UserNotifyTestChatProcedure = "/mistgate.usernotify.v1.UserNotifyService/TestUserTelegramChat" UserNotifySetChatLimitProcedure = "/mistgate.usernotify.v1.UserNotifyService/SetUserTelegramChatLimit" ) diff --git a/internal/panel/auth/policy_usernotify_test.go b/internal/panel/auth/policy_usernotify_test.go index b82fd32d5..98e7b589e 100644 --- a/internal/panel/auth/policy_usernotify_test.go +++ b/internal/panel/auth/policy_usernotify_test.go @@ -19,6 +19,7 @@ func TestUserNotifyPolicyLiteralsAreTheGeneratedNames(t *testing.T) { UserNotifyListChatsProcedure: usernotifyv1connect.UserNotifyServiceListUserTelegramChatsProcedure, UserNotifyUnlinkChatProcedure: usernotifyv1connect.UserNotifyServiceUnlinkUserTelegramChatProcedure, UserNotifySetChatMutedProcedure: usernotifyv1connect.UserNotifyServiceSetUserTelegramChatMutedProcedure, + UserNotifyTestChatProcedure: usernotifyv1connect.UserNotifyServiceTestUserTelegramChatProcedure, UserNotifySetChatLimitProcedure: usernotifyv1connect.UserNotifyServiceSetUserTelegramChatLimitProcedure, } { if literal != generated { @@ -44,6 +45,7 @@ func TestUserNotifyServicePolicy(t *testing.T) { {"ListUserTelegramChats", UserNotifyListChatsProcedure, true, true, true, false}, {"UnlinkUserTelegramChat", UserNotifyUnlinkChatProcedure, true, true, false, false}, {"SetUserTelegramChatMuted", UserNotifySetChatMutedProcedure, true, true, false, false}, + {"TestUserTelegramChat", UserNotifyTestChatProcedure, true, true, false, false}, {"SetUserTelegramChatLimit", UserNotifySetChatLimitProcedure, true, false, false, false}, } { if _, listed := procedureLevels[tc.path]; !listed { diff --git a/internal/panel/store/user_notice.go b/internal/panel/store/user_notice.go index 9277a257b..d92d460d0 100644 --- a/internal/panel/store/user_notice.go +++ b/internal/panel/store/user_notice.go @@ -119,16 +119,32 @@ func (s *Store) EnqueueUserNotice(ctx context.Context, n UserNotice) (bool, erro return rows > 0, err } -// LeaseDueUserNotices claims up to limit notices that are due (not finished, approved or needing no approval, due_at passed) for -// leaseFor, the most overdue first. One statement picks and claims them, so two callers never get the same row; a row whose -// lease ran out (a worker that stopped) is taken again. The rows come back as they were claimed. +// dueUserNoticeWhere selects the notices the Telegram sender takes: not finished, approved or needing no approval, due, not held, +// and sent to Telegram at all. A notice for the app only is never leased: the app pulls it (UserAppNotices) and nothing here +// finishes it. +const dueUserNoticeWhere = `done_at = 0 AND approval IN ('', 'approved') AND due_at <= ? AND lease_until <= ? AND (channels & 1) <> 0` + +// HasDueUserNotices is the one-row read that says whether LeaseDueUserNotices would take anything: the edge tick asks it before it +// does any work. +func (s *Store) HasDueUserNotices(ctx context.Context, now time.Time) (bool, error) { + var one int + err := s.R.QueryRowContext(ctx, `SELECT 1 FROM user_notice WHERE `+dueUserNoticeWhere+` LIMIT 1`, unix(now), unix(now)).Scan(&one) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + return err == nil, err +} + +// LeaseDueUserNotices claims up to limit notices for Telegram that are due (see dueUserNoticeWhere) for leaseFor, the most +// overdue first. One statement picks and claims them, so two callers never get the same row; a row whose lease ran out (a worker +// that stopped) is taken again. The rows come back as they were claimed. func (s *Store) LeaseDueUserNotices(ctx context.Context, now time.Time, leaseFor time.Duration, limit int) ([]UserNotice, error) { if limit <= 0 || leaseFor <= 0 { return nil, nil } // the batch form (not a plain query) is how the repo reads the rows of an UPDATE ... RETURNING on both editions results, err := s.batch(ctx, Stmt{Query: `UPDATE user_notice SET lease_id = ?, lease_until = ? - WHERE id IN (SELECT id FROM user_notice WHERE done_at = 0 AND approval IN ('', 'approved') AND due_at <= ? AND lease_until <= ? + WHERE id IN (SELECT id FROM user_notice WHERE ` + dueUserNoticeWhere + ` ORDER BY due_at, id LIMIT ?) RETURNING ` + userNoticeColumns, Args: []any{NewID("unl_"), unix(now.Add(leaseFor)), unix(now), unix(now), limit}, Returning: true}) diff --git a/internal/panel/store/user_notify_test.go b/internal/panel/store/user_notify_test.go index 8be232db8..bc269f2ea 100644 --- a/internal/panel/store/user_notify_test.go +++ b/internal/panel/store/user_notify_test.go @@ -891,3 +891,97 @@ func TestUserNotifyMigrationUpDown(t *testing.T) { } present(1) } + +// The sender takes Telegram's notices only: one for the app alone is never leased (the app pulls it), and HasDueUserNotices agrees +// with the lease on what is there to take. +func TestLeaseTakesTelegramNoticesOnly(t *testing.T) { + ctx := context.Background() + s := openUserNotify(t, "usr_u") + now := userNotifyNow + has := func(at time.Time) bool { + t.Helper() + ok, err := s.HasDueUserNotices(ctx, at) + if err != nil { + t.Fatal(err) + } + return ok + } + if has(now) { + t.Fatal("an empty outbox has something due") + } + app := testNotice("app", "usr_u") + app.Channels = UserNoticeApp + enqueue(t, s, app) + if has(now) || len(leaseIDs(t, s, now, 10)) != 0 { + t.Fatal("a notice for the app alone is due for the sender") + } + tg := testNotice("tg", "usr_u") + tg.Channels = UserNoticeTelegram + tg.DueAt = now.Add(time.Minute) + both := testNotice("both", "usr_u") + enqueue(t, s, tg) + enqueue(t, s, both) + if !has(now) || has(now.Add(-time.Second)) { + t.Error("due is about the due time") + } + if ids := leaseIDs(t, s, now, 10); !sameIDs(ids, "both") { + t.Fatalf("lease = %v", ids) + } + if has(now) { // held + t.Error("a held notice is due") + } + if !has(now.Add(time.Minute)) { // the lease ran out, and "tg" is due + t.Error("nothing due after the lease ran out") + } + if ids := leaseIDs(t, s, now.Add(time.Minute), 10); !sameIDs(ids, "both", "tg") { + t.Fatalf("lease = %v", ids) + } + if st := noticeRow(t, s, "app"); st.LeaseID != "" || !st.DoneAt.IsZero() { + t.Errorf("the app's notice was touched: %+v", st) + } +} + +// The sender's state on the card: a refused token, and a success that clears it (but not the poller's conflict) and moves last_ok +// forward only. +func TestUserTelegramBotSendState(t *testing.T) { + ctx := context.Background() + s := openUserNotify(t, "usr_u") + if ok, err := s.SetUserTelegramBotSendState(ctx, "unauthorized", time.Time{}); err != nil || ok { + t.Fatalf("without a bot: %v %v", ok, err) + } + if _, err := s.SetUserTelegramBot(ctx, UserTelegramBot{Token: []byte("sealed"), BotID: 7, Username: "bot"}, userNotifyNow); err != nil { + t.Fatal(err) + } + if ok, err := s.SaveUserTelegramBotPoll(ctx, 42, "", userNotifyNow.Add(time.Hour)); err != nil || !ok { + t.Fatal(ok, err) + } + bot := func() UserTelegramBot { + t.Helper() + b, err := s.UserTelegramBot(ctx) + if err != nil { + t.Fatal(err) + } + return b + } + if ok, err := s.SetUserTelegramBotSendState(ctx, "unauthorized", time.Time{}); err != nil || !ok { + t.Fatal(ok, err) + } + if b := bot(); b.LastError != "unauthorized" || b.Offset != 42 || !b.LastOK.Equal(userNotifyNow.Add(time.Hour)) { + t.Fatalf("after a refusal: %+v", b) + } + if _, err := s.SetUserTelegramBotSendState(ctx, "", userNotifyNow); err != nil { // an older success: last_ok stays + t.Fatal(err) + } + if b := bot(); b.LastError != "" || !b.LastOK.Equal(userNotifyNow.Add(time.Hour)) || b.Offset != 42 { + t.Fatalf("after a success: %+v", b) + } + if _, err := s.SaveUserTelegramBotPoll(ctx, 43, "conflict", time.Time{}); err != nil { + t.Fatal(err) + } + if _, err := s.SetUserTelegramBotSendState(ctx, "", userNotifyNow.Add(2*time.Hour)); err != nil { + t.Fatal(err) + } + if b := bot(); b.LastError != "conflict" || !b.LastOK.Equal(userNotifyNow.Add(2*time.Hour)) { + t.Fatalf("a send cleared the poller's conflict: %+v", b) + } +} diff --git a/internal/panel/store/user_telegram.go b/internal/panel/store/user_telegram.go index ed02ef145..0e1e2c3bc 100644 --- a/internal/panel/store/user_telegram.go +++ b/internal/panel/store/user_telegram.go @@ -104,6 +104,25 @@ func (s *Store) SaveUserTelegramBotPoll(ctx context.Context, offset int64, lastE return n > 0, err } +// SetUserTelegramBotSendState records how sending went, for the card of the bot, without touching the poller's offset: a failure +// code (the token was refused), or "" after a success, which clears a refused-token or unreachable error that a send has just +// disproved (a conflict is the poller's own and stays) and moves the time of the last success to ok. False when no bot is set. +func (s *Store) SetUserTelegramBotSendState(ctx context.Context, failure string, ok time.Time) (bool, error) { + var r sql.Result + var err error + if failure != "" { + r, err = s.W.ExecContext(ctx, `UPDATE user_telegram_bot SET last_error = ? WHERE id = 1`, failure) + } else { + r, err = s.W.ExecContext(ctx, `UPDATE user_telegram_bot SET last_ok = max(last_ok, ?), + last_error = CASE WHEN last_error IN ('unauthorized', 'unreachable') THEN '' ELSE last_error END WHERE id = 1`, unixOrZero(ok)) + } + if err != nil { + return false, err + } + n, err := r.RowsAffected() + return n > 0, err +} + // UserTelegramChat is one chat of a person. ChatEnc is vault ciphertext of the chat id, ChatMAC its keyed MAC. type UserTelegramChat struct { ID, UserID string diff --git a/internal/panel/telegram/client.go b/internal/panel/telegram/client.go index a27b9c9fd..893f4bd90 100644 --- a/internal/panel/telegram/client.go +++ b/internal/panel/telegram/client.go @@ -195,3 +195,16 @@ func (c *apiClient) sendMessage(ctx context.Context, token vault.Redacted, chatI "link_preview_options": map[string]any{"is_disabled": true}, }, nil) } + +// sendNotice sends HTML text without a link preview and says the id of the message that was made (what an edit of it will need). +// silent sends it without a sound (disable_notification). +func (c *apiClient) sendNotice(ctx context.Context, token vault.Redacted, chatID int64, text string, silent bool) (int64, error) { + var m struct { + MessageID int64 `json:"message_id"` + } + err := c.call(ctx, token, "sendMessage", map[string]any{ + "chat_id": chatID, "text": text, "parse_mode": "HTML", "disable_notification": silent, + "link_preview_options": map[string]any{"is_disabled": true}, + }, &m) + return m.MessageID, err +} diff --git a/internal/panel/telegram/service.go b/internal/panel/telegram/service.go index f920dc118..d8ad95a06 100644 --- a/internal/panel/telegram/service.go +++ b/internal/panel/telegram/service.go @@ -116,6 +116,11 @@ type Service struct { userPollStop context.CancelFunc // ends the poll of the people's bot in flight when that bot changes userWake chan struct{} chatKey []byte // the key of the chat MACs + + kinds map[string]userKind // the notices to people the sender knows (user_texts.go) + userPaceMu sync.Mutex + userBotNext time.Time // when the people's bot may send again + userChatNext map[string]time.Time // chat row id -> when it may be sent to again } // item is a line of news waiting for the next message: who gets it and how it reads in a language. @@ -183,6 +188,7 @@ func New(cfg Config) (*Service, error) { uapi: &apiClient{base: strings.TrimRight(cfg.UserAPIBase, "/"), hc: cfg.HTTPClient}, announcing: map[string]struct{}{}, open: map[string]time.Time{}, seenIP: map[string]time.Time{}, lastTest: map[string]time.Time{}, notify: make(chan struct{}, 1), wake: make(chan struct{}, 1), userWake: make(chan struct{}, 1), chatKey: cfg.Vault.Derive("user_telegram_chat_mac"), + kinds: defaultUserKinds(), userChatNext: map[string]time.Time{}, }, nil } @@ -202,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} { + for _, f := range []func(context.Context){s.pollLoop, s.sendLoop, s.watchLoop, s.userPollLoop, s.userSendLoop} { wg.Add(1) go func() { defer wg.Done(); f(ctx) }() } diff --git a/internal/panel/telegram/testenv_test.go b/internal/panel/telegram/testenv_test.go index f0c7eeb88..178bcdf6e 100644 --- a/internal/panel/telegram/testenv_test.go +++ b/internal/panel/telegram/testenv_test.go @@ -22,8 +22,10 @@ import ( const testToken = "123456789:AAFakeFakeFakeFakeFakeFakeFakeFake_x" type sentMsg struct { - Chat int64 - Text string + Chat int64 + Text string + Silent bool // disable_notification + ID int64 // the message_id the fake answered with } // fakeTG is a stand-in for api.telegram.org: it records what the panel sends and serves the updates a test queues. @@ -44,6 +46,7 @@ type fakeTG struct { botID int64 webhooks int badToken bool // every call answers 401 + msgSeq int64 } type planned struct { @@ -103,6 +106,7 @@ func (f *fakeTG) serve(w http.ResponseWriter, r *http.Request) { ChatID int64 `json:"chat_id"` Text string `json:"text"` ParseMode string `json:"parse_mode"` + Silent bool `json:"disable_notification"` } _ = json.Unmarshal(raw, &m) f.mu.Lock() @@ -129,9 +133,11 @@ func (f *fakeTG) serve(w http.ResponseWriter, r *http.Request) { return } f.mu.Lock() - f.sent = append(f.sent, sentMsg{m.ChatID, m.Text}) + f.msgSeq++ + id := 1000 + f.msgSeq + f.sent = append(f.sent, sentMsg{Chat: m.ChatID, Text: m.Text, Silent: m.Silent, ID: id}) f.mu.Unlock() - f.reply(w, 200, map[string]any{"ok": true, "result": map[string]any{"message_id": 1}}) + f.reply(w, 200, map[string]any{"ok": true, "result": map[string]any{"message_id": id}}) case "getUpdates": var p struct { Offset int64 `json:"offset"` diff --git a/internal/panel/telegram/user_admin.go b/internal/panel/telegram/user_admin.go index a4c2c2b28..97a5255ef 100644 --- a/internal/panel/telegram/user_admin.go +++ b/internal/panel/telegram/user_admin.go @@ -326,3 +326,79 @@ func (s *Service) SetUserChatLimit(ctx context.Context, user string, n int) erro s.auditCtx(ctx, a, "user_telegram_chat_limit", map[string]any{"user_id": user, "limit": n}) return nil } + +// TestUserChat sends the fixed test message to one chat of a person at once, outside the outbox, in the language of the chat. It +// answers nil when Telegram took it. A chat that blocked the bot is forgotten, and the answer says so ("telegram_blocked"); a +// refused token is "telegram_unauthorized" and shows on the card of the bot; any other failure is "telegram_unreachable". +func (s *Service) TestUserChat(ctx context.Context, user, chat string) error { + a, err := auth.SignedInSession(ctx) + if err != nil { + return err + } + chats, err := s.st.UserTelegramChats(ctx, user) + if err != nil { + s.log.Error("telegram: list people's chats", "code", "user_telegram_chat_list_failed", "err", err) + return errInternal + } + var c store.UserTelegramChat + for _, ch := range chats { + if ch.ID == chat { + c = ch + } + } + if c.ID == "" { + return fail(connect.CodeNotFound, "chat_not_found") + } + b, err := s.st.UserTelegramBot(ctx) + if errors.Is(err, store.ErrNotFound) { + return fail(connect.CodeFailedPrecondition, "user_bot_not_configured") + } + if err != nil { + s.log.Error("telegram: read people's bot", "code", "user_telegram_bot_read_failed", "err", err) + return errInternal + } + tok, ok := s.userToken(b) + if !ok { + return errInternal + } + id, err := s.openChatID(c) + if err != nil { + s.log.Error("telegram: open people's chat", "code", "user_telegram_chat_open_failed", "err", err) + return errInternal + } + s.mu.Lock() + tooSoon := s.now().Sub(s.lastTest[c.ID]) < testEvery + if !tooSoon { + s.lastTest[c.ID] = s.now() + } + s.mu.Unlock() + if tooSoon { + return fail(connect.CodeResourceExhausted, "telegram_test_too_soon") + } + panelLang, _ := s.panel(ctx) + sctx, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + if err := s.uapi.sendMessage(sctx, tok, id, userTest.in(userLang(c.Lang, string(panelLang)))); err != nil { + var ae *apiError + switch { + case errors.As(err, &ae) && ae.chatGone(): + if _, err := s.st.UnlinkUserTelegramChatByMAC(ctx, c.ChatMAC); err != nil { + s.log.Warn("telegram: unlink people's chat", "code", "user_telegram_unlink_failed", "err", err) + } + s.auditCtx(ctx, a, "user_telegram_test", map[string]any{"user_id": user, "result": "blocked"}) + return fail(connect.CodeFailedPrecondition, "telegram_blocked") + case errCode(err) == "unauthorized": + if _, err := s.st.SetUserTelegramBotSendState(ctx, "unauthorized", time.Time{}); err != nil { + s.log.Warn("telegram: save people's bot send state", "code", "user_telegram_state_store_failed", "err", err) + } + return fail(connect.CodeFailedPrecondition, "telegram_unauthorized") + } + s.log.Warn("telegram: people's chat test", "code", errCode(err)) + return fail(connect.CodeUnavailable, "telegram_unreachable") + } + if _, err := s.st.SetUserTelegramBotSendState(ctx, "", s.now()); err != nil { + s.log.Warn("telegram: save people's bot send state", "code", "user_telegram_state_store_failed", "err", err) + } + s.auditCtx(ctx, a, "user_telegram_test", map[string]any{"user_id": user, "result": "ok"}) + return nil +} diff --git a/internal/panel/telegram/user_send.go b/internal/panel/telegram/user_send.go new file mode 100644 index 000000000..f61a18d2c --- /dev/null +++ b/internal/panel/telegram/user_send.go @@ -0,0 +1,465 @@ +package telegram + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "strings" + "time" + + "github.com/mistgate/mistgate/internal/panel/store" + "github.com/mistgate/mistgate/internal/panel/vault" +) + +// The sender of the notices to people: the other half of the people's bot (user_bot.go listens, this speaks). It drains the outbox +// user_notice for the Telegram channel. A pass takes the notices that are due (LeaseDueUserNotices), gathers the ones of one person +// into one message per chat of theirs, sends them at the pace Telegram allows and writes down how each notice ended. At-least-once: +// a crash between Telegram's answer and the write sends that message again, never loses it. +// +// The VPS runs passes in a loop (userSendLoop); the edge runs one bounded pass per tick (SendUserNotices), after one read that says +// whether anything is due. How a send ends, per notice: +// - sent: the chats it was meant for got it (the message ids are kept in tg_message_refs, by row id of the chat, never by chat id); +// - 429: the whole pass stops and the notices come back at retry_after, no attempt spent (the limit is the bot's, not the notice's); +// - 401 or 404 (the token is refused): the same, and the card of the bot says "unauthorized" until a send works again; +// - 5xx or no answer: a later attempt after 1, 2, 4 ... 64 minutes, "dropped" when the eighth fails; +// - 403 or "chat not found": the chat is forgotten; a person left with no chat gets "unlinked"; +// - any other 4xx: Telegram will not take it, "dropped". + +const ( + userSendBatch = 50 // notices leased by one pass + userSendEdgeBatch = 20 + userSendLease = 2 * time.Minute // how long a pass may hold its notices: a crash frees them after this + userSendIdle = 5 * time.Second // the VPS loop looks at the outbox this often when it is empty + userSendTimeout = 20 * time.Second + userStoreTimeout = 10 * time.Second + userMaxAttempts = 8 + userBotGap = time.Second / 20 // at most 20 messages a second from the bot ... + userChatGap = time.Second // ... and one a second to a chat + userHoldPause = time.Minute // a refused token or a failed read: the queue waits this long, no attempt spent +) + +// userSendLoop is the VPS sender: a pass, then another at once while the outbox is full, else after a short rest. +func (s *Service) userSendLoop(ctx context.Context) { + for ctx.Err() == nil { + n, err := s.sendUserNotices(ctx) + switch { + case ctx.Err() != nil: + return + case err != nil: + s.log.Warn("telegram: people's notices pass failed", "code", "user_telegram_send_pass_failed", "err", err) + s.wait(ctx, userSendIdle, nil) + case n < userSendBatch: + s.wait(ctx, userSendIdle, nil) + } + } +} + +// SendUserNotices is the edge tick's pass: one read says whether anything is due (nothing due, no call to Telegram and no write), +// then a bounded batch is sent. What is left waits for the next tick. +func (s *Service) SendUserNotices(ctx context.Context) error { + _, err := s.sendUserNotices(ctx) + return err +} + +// userRow is a leased notice on its way through a pass. +type userRow struct { + n store.UserNotice + kind userKind + refs map[string]int64 // row id of a chat -> id of the message it got + done bool // finished in the store + // retry: a send failed in a way that may pass. dead: Telegram refuses it for good. muted: a chat that holds announcements + // skipped it. holdUntil: it was fine but cannot be sent now (a read failed); it goes back to the queue then, no attempt spent. + retry, dead, muted bool + holdUntil time.Time +} + +// sendable: the row still has a send in front of it in this pass. +func (r *userRow) sendable() bool { return !r.done && !r.dead && r.holdUntil.IsZero() } + +// userHold is why a pass stopped before it was done. +type userHold struct{ until time.Time } + +// userPass is the state of one pass. +type userPass struct { + s *Service + ctx context.Context + tok vault.Redacted + gotTok bool + lang string + hold *userHold + sentAny bool +} + +// sendUserNotices is one pass; n is how many notices it took (userSendBatch: there may be more). +func (s *Service) sendUserNotices(ctx context.Context) (n int, err error) { + now := s.now() + due, err := s.st.HasDueUserNotices(ctx, now) + if err != nil || !due { + return 0, err + } + limit := userSendBatch + if s.cfg.Edge { + limit = userSendEdgeBatch + } + notices, err := s.st.LeaseDueUserNotices(ctx, now, userSendLease, limit) + if err != nil || len(notices) == 0 { + return 0, err + } + var order []string + byUser := map[string][]store.UserNotice{} + for _, n := range notices { + if _, seen := byUser[n.UserID]; !seen { + order = append(order, n.UserID) + } + byUser[n.UserID] = append(byUser[n.UserID], n) + } + p := &userPass{s: s, ctx: ctx} + for _, user := range order { + p.sendUser(user, byUser[user]) + } + if p.sentAny { // one write for the pass: the card shows that sending works + wctx, cancel := s.writeCtx(ctx) + if _, err := s.st.SetUserTelegramBotSendState(wctx, "", s.now()); err != nil { + s.log.Warn("telegram: save people's bot send state", "code", "user_telegram_state_store_failed", "err", err) + } + cancel() + } + return len(notices), nil +} + +// writeCtx is a context for a write that must happen even when the pass was cut short: what a send did is recorded either way. +func (s *Service) writeCtx(ctx context.Context) (context.Context, context.CancelFunc) { + return context.WithTimeout(context.WithoutCancel(ctx), userStoreTimeout) +} + +// halted says whether the pass has stopped; a pass whose context ended stops with its notices due at once. +func (p *userPass) halted() bool { + if p.hold == nil && p.ctx.Err() != nil { + p.hold = &userHold{until: p.s.now()} + } + return p.hold != nil +} + +// stop ends the pass: what is not sent yet goes back to the queue at until, no attempt spent. The first reason stays. +func (p *userPass) stop(until time.Time) { + if p.hold == nil { + p.hold = &userHold{until: until} + } +} + +func (p *userPass) panelLang() string { + if p.lang == "" { + l, _ := p.s.panel(p.ctx) + p.lang = string(l) + } + return p.lang +} + +// token opens the token of the people's bot once per pass; false (and the pass stops) when there is none to use. +func (p *userPass) token() bool { + if p.gotTok { + return true + } + s := p.s + b, err := s.st.UserTelegramBot(p.ctx) + switch { + case errors.Is(err, store.ErrNotFound): + s.log.Warn("telegram: people's notices wait: no bot is set", "code", "user_telegram_no_bot") + case err != nil: + s.log.Warn("telegram: read people's bot", "code", "user_telegram_bot_read_failed", "err", err) + case s.userBotIsOwners(p.ctx, b.BotID): + s.log.Warn("telegram: people's notices wait: the bot is the owner's own", "code", "user_telegram_same_as_owner") + default: + if tok, ok := s.userToken(b); ok { + p.tok, p.gotTok = tok, true + return true + } + } + p.stop(s.now().Add(userHoldPause)) + return false +} + +// sendUser sends the notices of one person: each chat of theirs gets one message that gathers what it is to receive. +func (p *userPass) sendUser(user string, notices []store.UserNotice) { + s := p.s + rows := make([]*userRow, 0, len(notices)) + for _, n := range notices { + rows = append(rows, &userRow{n: n, refs: s.parseRefs(n)}) + } + defer func() { p.settle(rows) }() + if p.halted() { + return + } + + var live []*userRow + for _, r := range rows { + k, known := s.kinds[r.n.Kind] + if !known { + s.log.Warn("telegram: a notice of a kind the sender does not know is dropped", "code", "user_telegram_kind_unknown", "kind", clip(r.n.Kind, 40)) + p.end(r, store.UserNoticeDropped) + continue + } + r.kind = k + if k.fresh != nil { + fresh, err := k.fresh(p.ctx, s, r.n) + switch { + case err != nil: + s.log.Warn("telegram: check whether a notice is still true", "code", "user_telegram_fresh_check_failed", "kind", r.n.Kind, "err", err) + r.holdUntil = s.now().Add(userHoldPause) + case !fresh: + p.end(r, store.UserNoticeSkippedStale) + continue + } + } + live = append(live, r) + } + if len(live) == 0 { + return + } + chats, err := s.st.UserTelegramChats(p.ctx, user) + if err != nil { + s.log.Warn("telegram: read people's chats", "code", "user_telegram_chat_read_failed", "err", err) + for _, r := range live { + r.holdUntil = s.now().Add(userHoldPause) + } + return + } + if len(chats) > 0 && !p.token() { + return + } + for _, c := range chats { + if p.halted() { + return + } + p.sendChat(c, live) + } +} + +// sendChat sends one chat what is due to it from rows: one message (more when it is too long for one). +func (p *userPass) sendChat(c store.UserTelegramChat, rows []*userRow) { + s := p.s + var lines []string + var lineRows []*userRow + for _, r := range rows { + if !r.sendable() { + continue + } + if _, got := r.refs[c.ID]; got { + continue // a retry: this chat has it already + } + if c.Muted && r.n.Kind == userKindBroadcast { + r.muted = true + continue + } + text := r.n.ApprovalText + if text == "" { + var params userParams + _ = json.Unmarshal([]byte(r.n.ParamsJSON), ¶ms) + text = r.kind.text(userLang(c.Lang, p.panelLang()), params) + } + if text == "" { + r.dead = true + continue + } + lines = append(lines, escapeUserText(text)) + lineRows = append(lineRows, r) + } + if len(lines) == 0 { + return + } + chat, err := s.openChatID(c) + if err != nil { + s.log.Warn("telegram: open people's chat", "code", "user_telegram_chat_open_failed", "err", err) + for _, r := range lineRows { + r.dead = true + } + return + } + for _, msg := range chunk(lines) { + var in []*userRow + loud := false + for _, i := range msg.lineIndexes { + in = append(in, lineRows[i]) + loud = loud || lineRows[i].n.Loud + } + if !s.userPace(p.ctx, c.ID) { + p.halted() + return + } + sctx, cancel := context.WithTimeout(p.ctx, userSendTimeout) + id, err := s.uapi.sendNotice(sctx, p.tok, chat, msg.text, !loud) + cancel() + if err == nil { + p.sentAny = true + for _, r := range in { + r.refs[c.ID] = id + } + wctx, cancel := s.writeCtx(p.ctx) + if err := s.st.SetUserTelegramChatLastSent(wctx, c.UserID, c.ID, s.now()); err != nil && !errors.Is(err, store.ErrNotFound) { + s.log.Warn("telegram: save people's chat delivery", "code", "user_telegram_last_sent_failed", "err", err) + } + cancel() + continue + } + if !p.sendFailed(err, c, in, lineRows) { + return + } + } +} + +// sendFailed handles a failed send of one message (the rows in) to a chat and says whether the chat's next message may still be +// tried; all are the rows the chat was to get. +func (p *userPass) sendFailed(err error, c store.UserTelegramChat, in, all []*userRow) (goOn bool) { + s := p.s + var ae *apiError + errors.As(err, &ae) + switch { + case p.ctx.Err() != nil: + p.halted() + return false + case ae != nil && !ae.Transport && ae.Status == http.StatusTooManyRequests: + wait := retryAfterWait(ae.RetryAfter) + s.log.Warn("telegram: people's bot is rate limited", "code", "user_telegram_rate_limited", "retry_in", wait.String()) + p.stop(s.now().Add(wait)) + return false + case ae != nil && !ae.Transport && ae.code() == "unauthorized": + s.log.Warn("telegram: the people's bot token is refused", "code", "user_telegram_unauthorized") + wctx, cancel := s.writeCtx(p.ctx) + if _, err := s.st.SetUserTelegramBotSendState(wctx, "unauthorized", time.Time{}); err != nil { + s.log.Warn("telegram: save people's bot send state", "code", "user_telegram_state_store_failed", "err", err) + } + cancel() + p.stop(s.now().Add(userHoldPause)) + return false + case ae != nil && ae.chatGone(): + s.log.Info("telegram: a people's chat cannot be written to, it is forgotten", "code", "user_telegram_chat_gone") + wctx, cancel := s.writeCtx(p.ctx) + if _, err := s.st.UnlinkUserTelegramChatByMAC(wctx, c.ChatMAC); err != nil { + s.log.Warn("telegram: unlink people's chat", "code", "user_telegram_unlink_failed", "err", err) + } + cancel() + return false + case ae != nil && !ae.Transport && ae.Status >= 400 && ae.Status < 500: + s.log.Warn("telegram: a people's message is refused", "code", "user_telegram_message_refused", "status", ae.Status) + for _, r := range in { + r.dead = true + } + return true + } + s.log.Warn("telegram: a people's message did not go, it will be tried again", "code", "user_telegram_send_failed", "reason", errCode(err)) + for _, r := range all { // the rest of this chat's messages are not tried now: it would fail the same way + if _, got := r.refs[c.ID]; !got { + r.retry = true + } + } + return false +} + +// settle writes down how each notice of a person ended, or puts it back in the queue. +func (p *userPass) settle(rows []*userRow) { + s := p.s + for _, r := range rows { + if r.done { + continue + } + hold := r.holdUntil + if p.hold != nil && p.hold.until.After(hold) { + hold = p.hold.until + } + switch { + case !hold.IsZero(): // not its fault: it keeps its attempts + p.requeue(r, r.n.Attempts, hold) + case r.retry: + attempts := r.n.Attempts + 1 + if attempts >= userMaxAttempts { + s.log.Warn("telegram: a people's notice is dropped after its last attempt", "code", "user_telegram_notice_dropped", "kind", r.n.Kind) + p.end(r, store.UserNoticeDropped) + continue + } + p.requeue(r, attempts, s.now().Add(time.Duration(1<<(attempts-1))*time.Minute)) // 1, 2, 4 ... 64 minutes + case len(r.refs) > 0, r.muted: + p.end(r, store.UserNoticeSent) + case r.dead: + p.end(r, store.UserNoticeDropped) + default: // no chat is left to tell + p.end(r, store.UserNoticeUnlinked) + } + } +} + +// end finishes a notice with a result. +func (p *userPass) end(r *userRow, result string) { + s := p.s + r.done = true + wctx, cancel := s.writeCtx(p.ctx) + defer cancel() + ok, err := s.st.FinishUserNotice(wctx, r.n.ID, r.n.LeaseID, s.now(), result, len(r.refs), refsJSON(r.refs)) + s.logWrite(ok, err) +} + +// requeue gives a notice back to the queue to be tried at due. +func (p *userPass) requeue(r *userRow, attempts int, due time.Time) { + s := p.s + r.done = true + wctx, cancel := s.writeCtx(p.ctx) + defer cancel() + ok, err := s.st.RetryUserNotice(wctx, r.n.ID, r.n.LeaseID, due, attempts, refsJSON(r.refs)) + s.logWrite(ok, err) +} + +func (s *Service) logWrite(ok bool, err error) { + switch { + case err != nil: + s.log.Warn("telegram: save a people's notice", "code", "user_telegram_notice_store_failed", "err", err) + case !ok: + s.log.Warn("telegram: a people's notice was taken by another worker while it was sent", "code", "user_telegram_lease_lost") + } +} + +// parseRefs reads the message ids a notice has so far. +func (s *Service) parseRefs(n store.UserNotice) map[string]int64 { + refs := map[string]int64{} + if err := json.Unmarshal([]byte(n.TGMessageRefs), &refs); err != nil || refs == nil { + return map[string]int64{} + } + return refs +} + +func refsJSON(refs map[string]int64) string { + b, err := json.Marshal(refs) + if err != nil { + return "{}" + } + return string(b) +} + +// userPace waits until the bot and the chat may send again: 20 messages a second from the bot, one a second to a chat. false when +// ctx ended while it waited. +func (s *Service) userPace(ctx context.Context, chat string) bool { + s.userPaceMu.Lock() + now := s.now() + at := now + if s.userBotNext.After(at) { + at = s.userBotNext + } + if next := s.userChatNext[chat]; next.After(at) { + at = next + } + s.userBotNext, s.userChatNext[chat] = at.Add(userBotGap), at.Add(userChatGap) + if len(s.userChatNext) > 256 { // the map holds only the chats that were sent to lately + for id, next := range s.userChatNext { + if !next.After(now) { + delete(s.userChatNext, id) + } + } + } + s.userPaceMu.Unlock() + if d := at.Sub(now); d > 0 { + return s.wait(ctx, d, nil) + } + return ctx.Err() == nil +} + +// escapeUserText makes text safe for parse_mode HTML: the notices are plain text, whoever wrote them. +var escapeUserText = strings.NewReplacer("&", "&", "<", "<", ">", ">").Replace diff --git a/internal/panel/telegram/user_send_test.go b/internal/panel/telegram/user_send_test.go new file mode 100644 index 000000000..d67d59304 --- /dev/null +++ b/internal/panel/telegram/user_send_test.go @@ -0,0 +1,817 @@ +package telegram + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "strings" + "sync" + "testing" + "time" + + "connectrpc.com/connect" + + "github.com/mistgate/mistgate/internal/panel/store" +) + +// sendEnv is a userEnv whose waits are recorded and cost nothing, with a few kinds of notice registered. +type sendEnv struct { + *userEnv + mu sync.Mutex + waits []time.Duration + logs *lockedBuf +} + +type lockedBuf struct { + mu sync.Mutex + b strings.Builder +} + +func (l *lockedBuf) Write(p []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + return l.b.Write(p) +} + +func (l *lockedBuf) String() string { + l.mu.Lock() + defer l.mu.Unlock() + return l.b.String() +} + +func newSendEnv(t *testing.T, opts ...option) *sendEnv { + t.Helper() + logs := &lockedBuf{} + se := &sendEnv{logs: logs} + all := append([]option{func(c *Config) { + c.Log = slog.New(slog.NewTextHandler(logs, nil)) + c.Wait = func(ctx context.Context, d time.Duration, _ <-chan struct{}) bool { + se.mu.Lock() + se.waits = append(se.waits, d) + se.mu.Unlock() + select { + case <-ctx.Done(): + return false + case <-time.After(2 * time.Millisecond): + return true + } + } + }}, opts...) + se.userEnv = newUserEnv(t, all...) + se.setUserBot() + se.svc.kinds = map[string]userKind{ + "expired": {text: func(lang string, _ userParams) string { + return map[string]string{"ru": "Срок вышел", "en": "Expired"}[lang] + "." + lang + }}, + "quota_warn": {text: func(lang string, p userParams) string { return fmt.Sprintf("Traffic %v%% (%s)", p["pct"], lang) }}, + "broadcast": {text: func(_ string, p userParams) string { s, _ := p["text"].(string); return s }}, + "renewed": {text: func(string, userParams) string { return "never" }, + fresh: func(context.Context, *Service, store.UserNotice) (bool, error) { return false, nil }}, + "broken_check": {text: func(string, userParams) string { return "never" }, + fresh: func(context.Context, *Service, store.UserNotice) (bool, error) { return false, errors.New("boom") }}, + } + return se +} + +func (e *sendEnv) maxWait() time.Duration { + e.mu.Lock() + defer e.mu.Unlock() + var m time.Duration + for _, d := range e.waits { + m = max(m, d) + } + return m +} + +// notice enqueues a notice for Telegram and the app that is due now. +func (e *sendEnv) notice(id, user, kind string, loud bool, params string) { + e.t.Helper() + e.noticeFor(id, user, kind, loud, params, store.UserNoticeTelegram|store.UserNoticeApp) +} + +func (e *sendEnv) noticeFor(id, user, kind string, loud bool, params string, channels int) { + e.t.Helper() + if params == "" { + params = "{}" + } + ok, err := e.st.EnqueueUserNotice(context.Background(), store.UserNotice{ID: id, UserID: user, Kind: kind, Dedupe: "d-" + id, ParamsJSON: params, + Loud: loud, Channels: channels, CreatedAt: e.clk.now(), DueAt: e.clk.now()}) + if err != nil || !ok { + e.t.Fatalf("enqueue %s: %v %v", id, ok, err) + } +} + +// pass runs one pass of the sender and fails the test on an error. +func (e *sendEnv) pass() int { + e.t.Helper() + n, err := e.svc.sendUserNotices(context.Background()) + if err != nil { + e.t.Fatalf("pass: %v", err) + } + return n +} + +// reset forgets what the fake Telegram has received so far (the welcomes of the joins). +func (e *sendEnv) reset() { + e.utg.mu.Lock() + e.utg.sent = nil + e.utg.calls["sendMessage"] = 0 + e.utg.mu.Unlock() +} + +// joinAll links a chat with a language for a person and says its row id. +func (e *sendEnv) joinChat(user string, chat int64, lang string) string { + e.t.Helper() + e.join(user, chat, lang) + e.clk.advance(time.Second) // chats are listed by the time they were linked: a second apart, in the order of the calls + for _, c := range e.chats(user) { + if id, _ := e.svc.openChatID(c); id == chat { + return c.ID + } + } + e.t.Fatalf("chat %d did not link", chat) + return "" +} + +type noticeState struct { + Done, Due time.Time + Result, Refs, Lease string + TGSent, Attempts int +} + +func (e *sendEnv) state(id string) noticeState { + e.t.Helper() + var s noticeState + var done, due int64 + err := e.st.R.QueryRow(`SELECT done_at, due_at, result, tg_message_refs, lease_id, tg_sent, attempts FROM user_notice WHERE id = ?`, id). + Scan(&done, &due, &s.Result, &s.Refs, &s.Lease, &s.TGSent, &s.Attempts) + if err != nil { + e.t.Fatalf("notice %s: %v", id, err) + } + if done > 0 { + s.Done = time.Unix(done, 0).UTC() + } + s.Due = time.Unix(due, 0).UTC() + return s +} + +func (e *sendEnv) refs(id string) map[string]int64 { + e.t.Helper() + m := map[string]int64{} + if err := json.Unmarshal([]byte(e.state(id).Refs), &m); err != nil { + e.t.Fatal(err) + } + return m +} + +func (e *sendEnv) sentMsgs() []sentMsg { + e.utg.mu.Lock() + defer e.utg.mu.Unlock() + return append([]sentMsg(nil), e.utg.sent...) +} + +func (e *sendEnv) plan(p ...planned) { + e.utg.mu.Lock() + e.utg.sendPlan = p + e.utg.mu.Unlock() +} + +// Notices of one person become one message per chat, in the language of the chat, loud when any line is loud; a chat that is not +// known to Telegram's languages gets the panel's. The result keeps the message ids by chat row id, never the chat id. +func TestUserSendGluesPerChatInItsLanguageAndSound(t *testing.T) { + e := newSendEnv(t) + e.addUser("usr_a") + e.addUser("usr_b") + ruChat := e.joinChat("usr_a", 500, "ru") + enChat := e.joinChat("usr_a", 501, "en") + e.joinChat("usr_b", 600, "en") + oddChat := e.joinChat("usr_b", 601, "en") + if err := e.st.SetUserTelegramChatLang(context.Background(), "usr_b", oddChat, "xx"); err != nil { + t.Fatal(err) + } + e.reset() + + e.notice("n1", "usr_a", "expired", true, "") + e.notice("n2", "usr_a", "quota_warn", false, `{"pct": 80}`) + e.notice("n3", "usr_b", "quota_warn", false, `{"pct": 90}`) + if n := e.pass(); n != 3 { + t.Fatalf("the pass took %d notices", n) + } + + got := e.sentMsgs() + if len(got) != 4 { + t.Fatalf("%d messages, want one per chat: %+v", len(got), got) + } + ru, en := e.utg.sentTo(500), e.utg.sentTo(501) + if len(ru) != 1 || ru[0] != "Срок вышел.ru\n\nTraffic 80% (ru)" || len(en) != 1 || en[0] != "Expired.en\n\nTraffic 80% (en)" { + t.Errorf("a: ru = %q, en = %q", ru, en) + } + panelLang, _ := e.svc.panel(context.Background()) + if msg := only(t, e.utg.sentTo(601)); msg != fmt.Sprintf("Traffic 90%% (%s)", userLang("xx", string(panelLang))) { + t.Errorf("a chat of an unknown language got %q", msg) + } + for _, m := range got { + loud := m.Chat == 500 || m.Chat == 501 + if m.Silent == loud { + t.Errorf("chat %d: silent = %v, but loud = %v (one loud line makes the message loud, none makes it silent)", m.Chat, m.Silent, loud) + } + } + + for _, id := range []string{"n1", "n2"} { + st := e.state(id) + refs := e.refs(id) + if st.Result != store.UserNoticeSent || st.TGSent != 2 || st.Lease != "" || len(refs) != 2 || refs[ruChat] == 0 || refs[enChat] == 0 || refs[ruChat] == refs[enChat] { + t.Errorf("%s: %+v refs %v", id, st, refs) + } + if strings.Contains(st.Refs, "500") || strings.Contains(st.Refs, "501") { + t.Errorf("%s: the refs hold a Telegram chat id: %s", id, st.Refs) + } + } + if st := e.state("n3"); st.Result != store.UserNoticeSent || st.TGSent != 2 { + t.Errorf("n3: %+v", st) + } + for _, c := range e.chats("usr_a") { + if !c.LastSentAt.Equal(e.clk.now()) { + t.Errorf("a chat that got a message has last_sent_at %v", c.LastSentAt) + } + } + // nothing is left: another pass costs no call + calls := e.utg.count("sendMessage") + if n := e.pass(); n != 0 || e.utg.count("sendMessage") != calls { + t.Errorf("an empty outbox: %d notices, %d new calls", n, e.utg.count("sendMessage")-calls) + } +} + +// /mute holds announcements only: the other notices still come. +func TestUserSendMutedChatSkipsOnlyBroadcast(t *testing.T) { + e := newSendEnv(t) + e.addUser("usr_a") + e.addUser("usr_b") + e.joinChat("usr_a", 500, "en") + talk := e.joinChat("usr_a", 501, "en") + quiet := e.joinChat("usr_b", 600, "en") + if err := e.svc.st.SetUserTelegramChatMuted(context.Background(), "usr_a", talk, true); err != nil { + t.Fatal(err) + } + if err := e.svc.st.SetUserTelegramChatMuted(context.Background(), "usr_b", quiet, true); err != nil { + t.Fatal(err) + } + e.reset() + e.notice("b1", "usr_a", "broadcast", false, `{"text":"Maintenance tonight"}`) + e.notice("b2", "usr_a", "expired", true, "") + e.notice("b3", "usr_b", "broadcast", false, `{"text":"Maintenance tonight"}`) + e.pass() + + if got := e.utg.sentTo(500); len(got) != 1 || got[0] != "Maintenance tonight\n\nExpired.en" { + t.Errorf("the chat that listens: %q", got) + } + if got := e.utg.sentTo(501); len(got) != 1 || got[0] != "Expired.en" { + t.Errorf("the muted chat: %q, want the notice that is not an announcement", got) + } + if got := e.utg.sentTo(600); len(got) != 0 { + t.Errorf("a person whose only chat is muted got an announcement: %q", got) + } + if st := e.state("b3"); st.Result != store.UserNoticeSent || st.TGSent != 0 { + t.Errorf("an announcement nobody was to get: %+v", st) + } + if st := e.state("b1"); st.TGSent != 1 { + t.Errorf("b1: %+v", st) + } +} + +// A notice for the app alone is not the sender's: it stays unleased and unfinished for the app to pull; one for both channels +// finishes with Telegram and is still the app's. +func TestUserSendLeavesAppOnlyNoticesAlone(t *testing.T) { + e := newSendEnv(t) + e.addUser("usr_a") + e.joinChat("usr_a", 500, "en") + e.reset() + e.noticeFor("app", "usr_a", "expired", true, "", store.UserNoticeApp) + if n := e.pass(); n != 0 || e.utg.count("sendMessage") != 0 { + t.Fatalf("an app-only notice: %d taken, %d sent", n, e.utg.count("sendMessage")) + } + e.notice("both", "usr_a", "expired", true, "") + if n := e.pass(); n != 1 { + t.Fatalf("pass took %d, want the notice with Telegram only", n) + } + if st := e.state("app"); !st.Done.IsZero() || st.Lease != "" || st.Result != "" { + t.Errorf("the app-only notice was touched: %+v", st) + } + if st := e.state("both"); st.Result != store.UserNoticeSent { + t.Errorf("both: %+v", st) + } + pulled, err := e.st.UserAppNotices(context.Background(), "usr_a", e.clk.now()) + if err != nil || len(pulled) != 2 { + t.Errorf("the app pulls %d notices, %v; want both", len(pulled), err) + } +} + +// A kind the sender does not know is dropped with a code, never sent raw; a notice that is no longer true is skipped as stale. +func TestUserSendUnknownAndStaleKinds(t *testing.T) { + e := newSendEnv(t) + e.addUser("usr_a") + e.joinChat("usr_a", 500, "en") + e.reset() + e.notice("mystery", "usr_a", "mystery_kind", true, `{"secret":"do not print"}`) + e.notice("old", "usr_a", "renewed", true, "") + e.notice("sick", "usr_a", "broken_check", true, "") + e.notice("fine", "usr_a", "expired", true, "") + e.pass() + if st := e.state("mystery"); st.Result != store.UserNoticeDropped { + t.Errorf("unknown kind: %+v", st) + } + if st := e.state("old"); st.Result != store.UserNoticeSkippedStale { + t.Errorf("stale: %+v", st) + } + // a check that failed is not an answer: the notice waits and keeps its attempts + if st := e.state("sick"); st.Result != "" || st.Attempts != 0 || !st.Due.Equal(e.clk.now().Add(time.Minute)) { + t.Errorf("a failed freshness check: %+v", st) + } + if got := only(t, e.utg.sentTo(500)); got != "Expired.en" { + t.Errorf("message = %q", got) + } + logs := e.logs.String() + if !strings.Contains(logs, "user_telegram_kind_unknown") || strings.Contains(logs, "do not print") || strings.Contains(logs, "Expired") { + t.Errorf("logs: %s", logs) + } +} + +// 429 stops the pass, nothing is spent, and the notices come back when Telegram said. +func TestUserSendRateLimitWaitsRetryAfter(t *testing.T) { + e := newSendEnv(t) + e.addUser("usr_a") + e.addUser("usr_b") + e.joinChat("usr_a", 500, "en") + e.joinChat("usr_b", 600, "en") + e.reset() + e.notice("a", "usr_a", "expired", true, "") + e.notice("b", "usr_b", "expired", true, "") + e.plan(planned{status: 429, retryAfter: 7, desc: "Too Many Requests: retry after 7"}) + e.pass() + for _, id := range []string{"a", "b"} { + st := e.state(id) + if st.Result != "" || st.Attempts != 0 || st.Lease != "" || !st.Due.Equal(e.clk.now().Add(7*time.Second)) { + t.Errorf("%s after 429: %+v", id, st) + } + } + if e.utg.count("sendMessage") != 1 { + t.Errorf("%d sends after a 429, the pass should have stopped", e.utg.count("sendMessage")) + } + if n := e.pass(); n != 0 { + t.Errorf("a notice is taken before retry_after: %d", n) + } + e.clk.advance(7 * time.Second) + if n := e.pass(); n != 2 { + t.Fatalf("after retry_after: %d notices", n) + } + if e.state("a").Result != store.UserNoticeSent || e.state("b").Result != store.UserNoticeSent || len(e.sentMsgs()) != 2 { + t.Errorf("after the wait: %+v %+v", e.state("a"), e.state("b")) + } + if !strings.Contains(e.logs.String(), "user_telegram_rate_limited") { + t.Errorf("no code in the logs: %s", e.logs.String()) + } +} + +// A server error is tried again after 1, 2, 4 ... 64 minutes; the eighth failure drops the notice. +func TestUserSendRetriesThenDrops(t *testing.T) { + e := newSendEnv(t) + e.addUser("usr_a") + e.joinChat("usr_a", 500, "en") + e.reset() + e.notice("n", "usr_a", "expired", true, "") + for attempt := 1; attempt <= 8; attempt++ { + e.plan(planned{status: 502, desc: "Bad Gateway"}) + if n := e.pass(); n != 1 { + t.Fatalf("attempt %d: the pass took %d notices", attempt, n) + } + st := e.state("n") + if attempt < 8 { + pause := time.Duration(1<<(attempt-1)) * time.Minute + if st.Result != "" || st.Attempts != attempt || !st.Due.Equal(e.clk.now().Add(pause)) || st.Lease != "" { + t.Fatalf("attempt %d: %+v, want a retry in %v", attempt, st, pause) + } + e.clk.advance(pause - time.Second) + if n := e.pass(); n != 0 { + t.Fatalf("attempt %d: taken a second early", attempt) + } + e.clk.advance(time.Second) + } else if st.Result != store.UserNoticeDropped || st.TGSent != 0 { + t.Fatalf("the eighth failure: %+v", st) + } + } + if e.utg.count("sendMessage") != 8 { + t.Errorf("%d attempts, want 8", e.utg.count("sendMessage")) + } + if !strings.Contains(e.logs.String(), "user_telegram_notice_dropped") { + t.Errorf("logs: %s", e.logs.String()) + } +} + +// The person blocked the bot: that chat is forgotten and the others still get it; with none left the notice is "unlinked". +func TestUserSendForgetsChatsThatAreGone(t *testing.T) { + e := newSendEnv(t) + e.addUser("usr_a") + e.addUser("usr_b") + e.addUser("usr_c") + e.joinChat("usr_a", 500, "en") + e.joinChat("usr_a", 501, "en") + e.joinChat("usr_b", 600, "en") + e.reset() + e.notice("a", "usr_a", "expired", true, "") + e.notice("b", "usr_b", "expired", true, "") + e.notice("c", "usr_c", "expired", true, "") // no chat at all + e.plan(planned{status: 403, desc: "Forbidden: bot was blocked by the user"}, planned{}, planned{status: 400, desc: "Bad Request: chat not found"}) + e.pass() + + if chats := e.chats("usr_a"); len(chats) != 1 { + t.Fatalf("usr_a has %d chats, the blocked one should be gone", len(chats)) + } else if id, _ := e.svc.openChatID(chats[0]); id != 501 { + t.Errorf("the chat left is %d", id) + } + if len(e.chats("usr_b")) != 0 { + t.Error("a chat that is not found stays linked") + } + if st := e.state("a"); st.Result != store.UserNoticeSent || st.TGSent != 1 { + t.Errorf("a: %+v", st) + } + for _, id := range []string{"b", "c"} { + if st := e.state(id); st.Result != store.UserNoticeUnlinked || st.TGSent != 0 || st.Attempts != 0 { + t.Errorf("%s: %+v", id, st) + } + } + if got := e.utg.sentTo(501); len(got) != 1 { + t.Errorf("the chat that is fine got %q", got) + } +} + +// A refused token costs no attempt: the card says so, the queue waits, and a later success clears it. +func TestUserSendUnauthorizedWaitsWithoutSpendingAttempts(t *testing.T) { + e := newSendEnv(t) + e.addUser("usr_a") + e.joinChat("usr_a", 500, "en") + e.reset() + e.notice("n", "usr_a", "expired", true, "") + e.utg.mu.Lock() + e.utg.badToken = true + e.utg.mu.Unlock() + for range 3 { + e.pass() + e.clk.advance(time.Minute) + } + if st := e.state("n"); st.Result != "" || st.Attempts != 0 || st.Lease != "" { + t.Errorf("after three refusals: %+v", st) + } + b, _ := e.st.UserTelegramBot(context.Background()) + if b.LastError != "unauthorized" { + t.Errorf("the card says %q", b.LastError) + } + if c, err := e.svc.userBotStatus(context.Background()); err != nil || c.State != "unauthorized" { + t.Errorf("state = %q, %v", c.State, err) + } + if !strings.Contains(e.logs.String(), "user_telegram_unauthorized") || strings.Contains(e.logs.String(), testToken) { + t.Errorf("logs: %s", e.logs.String()) + } + + e.utg.mu.Lock() + e.utg.badToken = false + e.utg.mu.Unlock() + if n := e.pass(); n != 1 { + t.Fatalf("the token works again, the pass took %d", n) + } + b, _ = e.st.UserTelegramBot(context.Background()) + if st := e.state("n"); st.Result != store.UserNoticeSent || b.LastError != "" || b.LastOK.IsZero() { + t.Errorf("after recovery: %+v, card error %q, last ok %v", st, b.LastError, b.LastOK) + } + // a conflict of the poller is the poller's: a send does not clear it + if _, err := e.st.SaveUserTelegramBotPoll(context.Background(), 5, "conflict", time.Time{}); err != nil { + t.Fatal(err) + } + e.notice("m", "usr_a", "expired", true, "") + e.pass() + if b, _ = e.st.UserTelegramBot(context.Background()); b.LastError != "conflict" { + t.Errorf("a send cleared the poller's error: %q", b.LastError) + } +} + +// A retry after a partial send goes only to the chats that do not have the message yet. +func TestUserSendRetryDoesNotRepeatToChatsThatGotIt(t *testing.T) { + e := newSendEnv(t) + e.addUser("usr_a") + first := e.joinChat("usr_a", 500, "en") + second := e.joinChat("usr_a", 501, "en") + e.reset() + e.notice("n", "usr_a", "expired", true, "") + e.plan(planned{}, planned{status: 500, desc: "oops"}) + e.pass() + st := e.state("n") + refs := e.refs("n") + if st.Result != "" || st.Attempts != 1 || len(refs) != 1 || refs[first] == 0 { + t.Fatalf("after the partial send: %+v refs %v", st, refs) + } + if len(e.utg.sentTo(500)) != 1 || len(e.utg.sentTo(501)) != 0 { + t.Fatalf("sent to 500: %q, to 501: %q", e.utg.sentTo(500), e.utg.sentTo(501)) + } + e.clk.advance(time.Minute) + e.pass() + st = e.state("n") + refs = e.refs("n") + if st.Result != store.UserNoticeSent || st.TGSent != 2 || refs[first] == 0 || refs[second] == 0 { + t.Errorf("after the retry: %+v refs %v", st, refs) + } + if len(e.utg.sentTo(500)) != 1 || len(e.utg.sentTo(501)) != 1 { + t.Errorf("the retry repeated a message: 500 %q, 501 %q", e.utg.sentTo(500), e.utg.sentTo(501)) + } +} + +// The pace: a chat is written to once a second at most, the bot 20 times a second. +func TestUserSendPace(t *testing.T) { + e := newSendEnv(t) + e.addUser("usr_a") + e.addUser("usr_b") + e.joinChat("usr_a", 500, "en") + e.joinChat("usr_b", 600, "en") + e.reset() + e.notice("a1", "usr_a", "expired", true, "") + e.pass() + if e.maxWait() != 0 { + t.Fatalf("the first message waited %v", e.maxWait()) + } + e.notice("a2", "usr_a", "quota_warn", true, `{"pct":1}`) + e.notice("b1", "usr_b", "expired", true, "") + e.pass() + e.mu.Lock() + waits := append([]time.Duration(nil), e.waits...) + e.mu.Unlock() + // the second message to chat 500 waits out the second; the one after it, to another chat, only the bot's gap behind that (the + // fake clock stands still while the waits are not waited) + if len(waits) != 2 || waits[0] != time.Second || waits[1] != time.Second+time.Second/20 { + t.Errorf("waits = %v", waits) + } + if len(e.sentMsgs()) != 3 { + t.Errorf("sent %d", len(e.sentMsgs())) + } +} + +// One chat's notices that do not fit one message go out as several, each as loud as its own lines, each row pointing to its message. +func TestUserSendLongNoticesSplitIntoMessages(t *testing.T) { + e := newSendEnv(t) + e.addUser("usr_a") + chat := e.joinChat("usr_a", 500, "en") + e.reset() + long := strings.Repeat("x", 2000) + e.notice("l1", "usr_a", "broadcast", false, `{"text":"`+long+`"}`) + e.notice("l2", "usr_a", "broadcast", true, `{"text":"`+long+`"}`) + e.notice("l3", "usr_a", "broadcast", false, `{"text":"`+long+`"}`) + e.pass() + got := e.sentMsgs() + if len(got) != 3 || !got[0].Silent || got[1].Silent || !got[2].Silent { + t.Fatalf("messages: %+v", got) + } + for i, id := range []string{"l1", "l2", "l3"} { + if refs := e.refs(id); refs[chat] != got[i].ID || e.state(id).Result != store.UserNoticeSent { + t.Errorf("%s: refs %v, message %d", id, refs, got[i].ID) + } + } + if e.maxWait() < time.Second { + t.Errorf("messages to one chat came without a second between them: max wait %v", e.maxWait()) + } +} + +// Text a person or the owner wrote is plain text: it cannot inject markup. +func TestUserSendEscapesText(t *testing.T) { + e := newSendEnv(t) + e.addUser("usr_a") + e.joinChat("usr_a", 500, "en") + e.reset() + e.notice("n", "usr_a", "broadcast", false, `{"text":"a bold & c"}`) + e.pass() + if got := only(t, e.utg.sentTo(500)); got != "a <b>bold</b> & c" { + t.Errorf("message = %q", got) + } +} + +// The owner's own text of a draft replaces the rendered one. +func TestUserSendApprovedTextReplacesTheRenderedOne(t *testing.T) { + e := newSendEnv(t) + e.addUser("usr_a") + e.joinChat("usr_a", 500, "en") + e.reset() + ok, err := e.st.EnqueueUserNotice(context.Background(), store.UserNotice{ID: "d", UserID: "usr_a", Kind: "expired", Dedupe: "d-d", ParamsJSON: "{}", Loud: true, + Channels: store.UserNoticeTelegram, CreatedAt: e.clk.now(), DueAt: e.clk.now(), Approval: store.UserNoticeApprovalPending}) + if err != nil || !ok { + t.Fatal(err) + } + if e.pass() != 0 { + t.Fatal("a draft was sent before the owner approved it") + } + if ok, err := e.st.SetUserNoticeApproval(context.Background(), "d", store.UserNoticeApprovalApproved, "In the owner's words", e.clk.now()); err != nil || !ok { + t.Fatal(err) + } + e.pass() + if got := only(t, e.utg.sentTo(500)); got != "In the owner's words" { + t.Errorf("message = %q", got) + } +} + +// The people's bot that is the owner's own is not used to send either. +func TestUserSendWaitsWhenTheBotIsTheOwners(t *testing.T) { + e := newSendEnv(t) + e.addUser("usr_a") + e.joinChat("usr_a", 500, "en") + e.reset() + if _, err := e.st.SetTelegramBot(context.Background(), store.TelegramBotRow{Token: e.svc.vault.Seal([]byte(testToken), tokenRecordID), BotID: e.utg.botID, Username: "x_bot"}, e.clk.now()); err != nil { + t.Fatal(err) + } + e.notice("n", "usr_a", "expired", true, "") + e.pass() + if st := e.state("n"); st.Result != "" || st.Attempts != 0 || e.utg.count("sendMessage") != 0 { + t.Errorf("sent through the owner's bot: %+v", st) + } +} + +// On the edge a tick with nothing due costs one read and no call to Telegram; with something due it sends a bounded batch. +func TestUserSendOnTheEdge(t *testing.T) { + e := newSendEnv(t, func(c *Config) { c.Edge = true }) + e.addUser("usr_a") + e.joinChat("usr_a", 500, "en") + e.reset() + ctx := context.Background() + if err := e.svc.SendUserNotices(ctx); err != nil || e.utg.count("sendMessage") != 0 { + t.Fatalf("nothing due: %v, %d sends", err, e.utg.count("sendMessage")) + } + for i := range 25 { + e.notice(fmt.Sprintf("n%02d", i), "usr_a", "expired", true, "") + } + if err := e.svc.SendUserNotices(ctx); err != nil { + t.Fatal(err) + } + sent := 0 + for i := range 25 { + if e.state(fmt.Sprintf("n%02d", i)).Result == store.UserNoticeSent { + sent++ + } + } + if sent != userSendEdgeBatch { + t.Errorf("one tick finished %d notices, want the batch of %d", sent, userSendEdgeBatch) + } + if err := e.svc.SendUserNotices(ctx); err != nil { + t.Fatal(err) + } + if e.state("n24").Result != store.UserNoticeSent { + t.Error("the next tick did not take the rest") + } +} + +// A pass cut short (the tick's time is up, the panel stops) puts what it did not send back at once, and remembers what it did. +func TestUserSendCutShortKeepsWhatWasSent(t *testing.T) { + e := newSendEnv(t) + e.addUser("usr_a") + first := e.joinChat("usr_a", 500, "en") + e.joinChat("usr_a", 501, "en") + e.reset() + e.notice("n", "usr_a", "expired", true, "") + + started := make(chan struct{}) + e.utg.mu.Lock() + e.utg.blockSendCall = e.utg.calls["sendMessage"] + 2 // the second send hangs + e.utg.blockSendStarted = started + e.utg.mu.Unlock() + ctx, cancel := context.WithCancel(context.Background()) + go func() { <-started; cancel() }() + if _, err := e.svc.sendUserNotices(ctx); err != nil { + t.Fatal(err) + } + st := e.state("n") + refs := e.refs("n") + if st.Result != "" || st.Attempts != 0 || st.Lease != "" || !st.Due.Equal(e.clk.now()) || len(refs) != 1 || refs[first] == 0 { + t.Fatalf("after a cut-short pass: %+v refs %v", st, refs) + } + if n := e.pass(); n != 1 { + t.Fatalf("the notice is not due at once: %d", n) + } + if st := e.state("n"); st.Result != store.UserNoticeSent || st.TGSent != 2 || len(e.utg.sentTo(500)) != 1 || len(e.utg.sentTo(501)) != 1 { + t.Errorf("after the next pass: %+v", st) + } +} + +// The VPS loop sends what arrives and ends with its context. +func TestUserSendLoopOnTheVPS(t *testing.T) { + e := newSendEnv(t) + e.addUser("usr_a") + e.joinChat("usr_a", 500, "en") + e.reset() + e.run() + e.notice("n", "usr_a", "expired", true, "") + waitFor(t, "the notice to be sent", func() bool { return e.state("n").Result == store.UserNoticeSent }) + if got := only(t, e.utg.sentTo(500)); got != "Expired.en" { + t.Errorf("message = %q", got) + } +} + +// ---- the "Test" button of a chat + +func TestTestUserChat(t *testing.T) { + e := newSendEnv(t) + owner := e.addAdmin("adm_o", "Owner", store.RoleOwner) + e.addUser("usr_a") + e.addUser("usr_b") + ctx := e.ctxAs(owner) + ru := e.joinChat("usr_a", 500, "ru") + other := e.joinChat("usr_b", 600, "en") + e.reset() + + if err := e.svc.TestUserChat(ctx, "usr_a", ru); err != nil { + t.Fatal(err) + } + if got := only(t, e.utg.sentTo(500)); got != userTest.ru { + t.Errorf("test message = %q", got) + } + if m := e.sentMsgs()[0]; m.Silent { + t.Error("the test is silent") + } + if n := countRows(t, e, `SELECT count(*) FROM user_notice`); n != 0 { + t.Errorf("the test went through the outbox: %d rows", n) + } + if a := e.userAudit(); len(a) == 0 || !strings.HasPrefix(a[0], "user_telegram_test ") || strings.Contains(a[0], "500") { + t.Errorf("audit = %v", a) + } + // one test in ten seconds per chat + if err := e.svc.TestUserChat(ctx, "usr_a", ru); connectCode(err) != connect.CodeResourceExhausted { + t.Errorf("a second test at once: %v", err) + } + e.clk.advance(11 * time.Second) + + // not this person's chat, not a chat at all, a token, nobody + if err := e.svc.TestUserChat(ctx, "usr_a", other); connectCode(err) != connect.CodeNotFound { + t.Errorf("another person's chat: %v", err) + } + if err := e.svc.TestUserChat(ctx, "usr_a", "utc_none"); connectCode(err) != connect.CodeNotFound { + t.Errorf("a missing chat: %v", err) + } + if err := e.svc.TestUserChat(e.ctxAs(store.Admin{ID: "token:t", Role: store.RoleOwner}), "usr_a", ru); connectCode(err) != connect.CodePermissionDenied { + t.Errorf("a token: %v", err) + } + if err := e.svc.TestUserChat(context.Background(), "usr_a", ru); err == nil { + t.Error("no session") + } + + // a refused token shows on the card + e.utg.mu.Lock() + e.utg.badToken = true + e.utg.mu.Unlock() + if err := e.svc.TestUserChat(ctx, "usr_a", ru); connectCode(err) != connect.CodeFailedPrecondition || !strings.Contains(err.Error(), "telegram_unauthorized") { + t.Errorf("a refused token: %v", err) + } + if b, _ := e.st.UserTelegramBot(ctx); b.LastError != "unauthorized" { + t.Errorf("the card says %q", b.LastError) + } + e.utg.mu.Lock() + e.utg.badToken = false + e.utg.mu.Unlock() + e.clk.advance(11 * time.Second) + + // no answer is "unreachable", the chat stays; a blocked bot unlinks the chat + e.plan(planned{status: 502, desc: "Bad Gateway"}) + if err := e.svc.TestUserChat(ctx, "usr_a", ru); connectCode(err) != connect.CodeUnavailable || !strings.Contains(err.Error(), "telegram_unreachable") || len(e.chats("usr_a")) != 1 { + t.Errorf("a failed test: %v", err) + } + e.clk.advance(11 * time.Second) + e.plan(planned{status: 403, desc: "Forbidden: bot was blocked by the user"}) + if err := e.svc.TestUserChat(ctx, "usr_a", ru); connectCode(err) != connect.CodeFailedPrecondition || !strings.Contains(err.Error(), "telegram_blocked") { + t.Errorf("a blocked bot: %v", err) + } + if len(e.chats("usr_a")) != 0 { + t.Error("the chat that blocked the bot is still linked") + } + + // no bot + if _, err := e.st.ClearUserTelegramBot(ctx); err != nil { + t.Fatal(err) + } + if err := e.svc.TestUserChat(ctx, "usr_b", other); connectCode(err) != connect.CodeNotFound { // its chat went with the bot + t.Errorf("without a bot: %v", err) + } +} + +func TestUserTestTextExistsInEveryLanguage(t *testing.T) { + for lang, s := range map[string]string{"ru": userTest.ru, "en": userTest.en, "zh": userTest.zh, "tr": userTest.tr, "fa": userTest.fa} { + low := strings.ToLower(s) + if s == "" || strings.Contains(low, "vpn") || strings.Contains(low, "http") || strings.ContainsAny(s, "<>&") { + t.Errorf("%s: %q", lang, s) + } + } + if userTest.in("xx") != userTest.en { + t.Error("a language the panel does not speak gets English") + } +} + +func countRows(t *testing.T, e *sendEnv, query string) int { + t.Helper() + var n int + if err := e.st.R.QueryRow(query).Scan(&n); err != nil { + t.Fatal(err) + } + return n +} diff --git a/internal/panel/telegram/user_texts.go b/internal/panel/telegram/user_texts.go index 1e1eeddcf..96e215397 100644 --- a/internal/panel/telegram/user_texts.go +++ b/internal/panel/telegram/user_texts.go @@ -1,8 +1,11 @@ package telegram import ( + "context" "strconv" "strings" + + "github.com/mistgate/mistgate/internal/panel/store" ) // What the bot of the people says. Neutral words (access, device, service), no link and no question: the bot never sends a link @@ -89,6 +92,14 @@ var ( tr: "Duyurular kapatıldı, diğer bildirimler eskisi gibi gelir. Duyuruları yeniden açmak için /mute komutunu tekrar gönderin", fa: "اطلاعیه‌ها خاموش شد و اعلان‌های دیگر مثل قبل می‌آیند. برای روشن کردن دوباره اطلاعیه‌ها، /mute را دوباره بفرستید", } + // userTest is what the "Test" button of a chat sends: fixed words, in the language of the chat. + userTest = userText{ + ru: "Проверка связи: если вы видите это сообщение, уведомления сюда доходят. Ничего делать не нужно", + en: "Connection check: if you can see this message, notifications reach this chat. You don’t need to do anything", + zh: "连接测试:如果您看到这条消息,说明通知可以送达此聊天。您无需进行任何操作", + tr: "Bağlantı denemesi: bu mesajı görüyorsanız bildirimler bu sohbete ulaşıyor demektir. Hiçbir şey yapmanız gerekmiyor", + fa: "آزمایش اتصال: اگر این پیام را می‌بینید، اعلان‌ها به این گفتگو می‌رسند. نیازی به انجام کاری نیست", + } userUnmuted = userText{ ru: "Объявления снова включены. /mute — выключить", en: "Announcements are on again. /mute turns them off", @@ -109,3 +120,26 @@ func userLimitText(lang string, limit int) string { fa: "تعداد گفتگوهای متصل به این دسترسی به حداکثر رسیده است: " + n + ". یکی را در صفحهٔ خودتان قطع کنید و پیوند تازه‌ای بخواهید", }.in(lang) } + +// ---- the kinds of notice the sender knows + +// userKindBroadcast is the owner's announcement: the only kind a chat can switch off with /mute (everything else it still gets). +const userKindBroadcast = "broadcast" + +// userParams is what a producer stored in user_notice.params_json, the JSON object a text is rendered from. +type userParams map[string]any + +// userKind is what the sender knows about one kind of notice: how it reads, and whether it still matters when its turn comes. +type userKind struct { + // text is the notice in a language (ru, en, zh, tr or fa) from its params. Plain text: the sender escapes it, a link is never + // part of it. "" means there is nothing to say, and the notice is dropped. + text func(lang string, params userParams) string + // fresh says whether the notice is still true at the moment of sending ("expires soon" does not go after a renewal). nil: it is. + fresh func(ctx context.Context, s *Service, n store.UserNotice) (bool, error) +} + +// 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. +func defaultUserKinds() map[string]userKind { + return map[string]userKind{} +} diff --git a/internal/panel/telegram/usernotifyrpc/service.go b/internal/panel/telegram/usernotifyrpc/service.go index e5e907575..0480c1f1a 100644 --- a/internal/panel/telegram/usernotifyrpc/service.go +++ b/internal/panel/telegram/usernotifyrpc/service.go @@ -106,6 +106,13 @@ func (r rpc) SetUserTelegramChatMuted(ctx context.Context, req *connect.Request[ return connect.NewResponse(&usernotifyv1.Empty{}), nil } +func (r rpc) TestUserTelegramChat(ctx context.Context, req *connect.Request[usernotifyv1.ChatRef]) (*connect.Response[usernotifyv1.Empty], error) { + if err := r.tg.TestUserChat(ctx, req.Msg.UserId, req.Msg.ChatId); err != nil { + return nil, err + } + return connect.NewResponse(&usernotifyv1.Empty{}), nil +} + func (r rpc) SetUserTelegramChatLimit(ctx context.Context, req *connect.Request[usernotifyv1.SetChatLimitRequest]) (*connect.Response[usernotifyv1.Empty], error) { if err := r.tg.SetUserChatLimit(ctx, req.Msg.UserId, int(req.Msg.Limit)); err != nil { return nil, err diff --git a/proto/mistgate/usernotify/v1/usernotify.proto b/proto/mistgate/usernotify/v1/usernotify.proto index 5ba198993..62a32c34a 100644 --- a/proto/mistgate/usernotify/v1/usernotify.proto +++ b/proto/mistgate/usernotify/v1/usernotify.proto @@ -40,6 +40,10 @@ service UserNotifyService { rpc UnlinkUserTelegramChat(ChatRef) returns (Empty); // Switches the announcements of one chat off or on. rpc SetUserTelegramChatMuted(SetChatMutedRequest) returns (Empty); + // Sends the fixed test message to one chat at once (not through the outbox), in the language of the chat, and answers when + // Telegram took it. A chat that blocked the bot is forgotten. FAILED_PRECONDITION: "telegram_blocked", "telegram_unauthorized", + // "user_bot_not_configured". UNAVAILABLE: "telegram_unreachable". RESOURCE_EXHAUSTED: "telegram_test_too_soon" (one in 10 s). + rpc TestUserTelegramChat(ChatRef) returns (Empty); // The chat limit: of everybody (user_id empty) or of one person, 1 to 10; 0 returns to the default. Owner only. rpc SetUserTelegramChatLimit(SetChatLimitRequest) returns (Empty); } diff --git a/web/src/gen/mistgate/usernotify/v1/usernotify_pb.ts b/web/src/gen/mistgate/usernotify/v1/usernotify_pb.ts index 4f0e5134b..626eb5cf1 100644 --- a/web/src/gen/mistgate/usernotify/v1/usernotify_pb.ts +++ b/web/src/gen/mistgate/usernotify/v1/usernotify_pb.ts @@ -10,7 +10,7 @@ import type { Message } from "@bufbuild/protobuf"; * Describes the file mistgate/usernotify/v1/usernotify.proto. */ export const file_mistgate_usernotify_v1_usernotify: GenFile = /*@__PURE__*/ - fileDesc("CidtaXN0Z2F0ZS91c2Vybm90a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0Gh0ubWlzdGdhdGUudXNlcm5vdGlmeS52MS5FbXB0eULtAQoaY29tLm1pc3RnYXRlLnVzZXJub3RpZnkudjFCD1VzZXJub3RpZnlQcm90b1ABWkRnaXRodWIuY29tL21pc3RnYXRlL21pc3RnYXRlL2dlbi9taXN0Z2F0ZS91c2Vybm90aWZ5L3YxO3VzZXJub3RpZnl2MaICA01VWKoCFk1pc3RnYXRlLlVzZXJub3RpZnkuVjHKAhZNaXN0Z2F0ZVxVc2Vybm90aWZ5XFYx4gIiTWlzdGdhdGVcVXNlcm5vdGlmeVxWMVxHUEJNZXRhZGF0YeoCGE1pc3RnYXRlOjpVc2Vybm90aWZ5OjpWMWIGcHJvdG8z"); /** * @generated from message mistgate.usernotify.v1.Empty @@ -439,6 +439,18 @@ export const UserNotifyService: GenService<{ input: typeof SetChatMutedRequestSchema; output: typeof EmptySchema; }, + /** + * Sends the fixed test message to one chat at once (not through the outbox), in the language of the chat, and answers when + * Telegram took it. A chat that blocked the bot is forgotten. FAILED_PRECONDITION: "telegram_blocked", "telegram_unauthorized", + * "user_bot_not_configured". UNAVAILABLE: "telegram_unreachable". RESOURCE_EXHAUSTED: "telegram_test_too_soon" (one in 10 s). + * + * @generated from rpc mistgate.usernotify.v1.UserNotifyService.TestUserTelegramChat + */ + testUserTelegramChat: { + methodKind: "unary"; + input: typeof ChatRefSchema; + output: typeof EmptySchema; + }, /** * The chat limit: of everybody (user_id empty) or of one person, 1 to 10; 0 returns to the default. Owner only. * From 26374643264598bfef180a872fc04b76da0f3c70 Mon Sep 17 00:00:00 2001 From: Daniyar Ennanov <21172041+limeflash@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:57:29 +0300 Subject: [PATCH 2/3] Sender: a pass ends within half its lease, so a slow Telegram cannot let the next pass send the same notices again Co-Authored-By: Claude Opus 5.5 --- internal/panel/telegram/user_send.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/internal/panel/telegram/user_send.go b/internal/panel/telegram/user_send.go index f61a18d2c..6e996c03b 100644 --- a/internal/panel/telegram/user_send.go +++ b/internal/panel/telegram/user_send.go @@ -106,6 +106,10 @@ func (s *Service) sendUserNotices(ctx context.Context) (n int, err error) { if err != nil || len(notices) == 0 { return 0, err } + // The pass ends well inside the lease: a slow Telegram must not let the next pass take the same notices and send them twice. + // What is not sent by then goes back to the queue with its attempts kept. + ctx, cancel := context.WithTimeout(ctx, userSendLease/2) + defer cancel() var order []string byUser := map[string][]store.UserNotice{} for _, n := range notices { From e2d3c05f7f19566e34f246b2bb56cc5d5caadb93 Mon Sep 17 00:00:00 2001 From: Daniyar Ennanov <21172041+limeflash@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:13:32 +0300 Subject: [PATCH 3/3] edge entry test: a cron tick has one more D1 read, the check for notices due to people Co-Authored-By: Claude Opus 5.5 --- cmd/mistgate-edge/testdata/bridge.cjs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/cmd/mistgate-edge/testdata/bridge.cjs b/cmd/mistgate-edge/testdata/bridge.cjs index 487fcb3dd..332164e4d 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 + // 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 // 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, 23); + assert.equal((await tick(3)).queries.sequentialQueries, 24); 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, 23, "waking costs no query beyond the look"); + assert.equal((await tick(3)).queries.sequentialQueries, 24, "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, - 28, - "a normal cron tick costs 28 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 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)", + 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)", ); liveProjectionQueries = 0; @@ -1225,8 +1225,8 @@ async function run() { console.log(`D1 query count ${JSON.stringify(cronQueries)}`); assert.equal( cronQueries.sequentialQueries, - 25, - "one minute 10 cron tick costs 25 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 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)", + 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)", ); 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, - 45, - "a minute 17 cron tick costs 45 D1 calls: 6 for the sweeps and settings, one Telegram pending-code check, 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)", + 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)", ); // The Overview is polled every 10 seconds. The health summary of every node is one settings row, read once: more connected