mirror of
https://github.com/tiennm99/tiennm99bot.git
synced 2026-10-18 02:15:04 +00:00
fix(alias): answer inline queries from one store read under a deadline
Telegram expires an inline query and then rejects the answer with "query is too old and response timeout expired or query ID is invalid". The picker invited that: it listed the names and then read the store once per name — up to 50 round trips per keystroke — and it was the only handler in the module with no deadline of its own. Updates are dispatched one at a time, so a single slow answer also held up the queries queued behind it, each ageing while it waited, and one slow read expired a whole burst of typing. Add DocStore.Scan, which reads a key prefix with its values in one round trip, ordered by key. The picker and /aliases both use it, so neither grows a round trip per saved alias. Bound the inline handler at 3s: an answer later than that is rejected anyway, and giving up frees the worker for the fresher query behind it. When Telegram does reject an answer, the error now carries how long it took, which separates a slow handler from a query that was already stale on arrival. The 50-result cap now counts results the picker can show, so a video-note alias — which has no cached inline type — no longer consumes a slot.
This commit is contained in:
1 parent
cb86ec4cf3
commit
8260d2860b
9 files changed
+278
-63
No files matched your search
@@ -2,8 +2,9 @@ package alias
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
@@ -19,6 +20,17 @@ const (
|
||||
// query. Kept short because the namespace is shared and writable: a name
|
||||
// saved now should show up in the picker within seconds, not minutes.
|
||||
inlineCacheSeconds = 5
|
||||
|
||||
// inlineTimeout bounds one answer, far tighter than the 10s handlerTimeout
|
||||
// the command handlers use.
|
||||
//
|
||||
// An inline query has a shelf life: Telegram invalidates the id and rejects
|
||||
// the answer as "query is too old". Every keystroke opens a new query, and
|
||||
// updates are dispatched one at a time, so a single slow answer also holds
|
||||
// up the queries queued behind it — which are themselves ageing while they
|
||||
// wait. Giving up early loses one result set; running long loses the whole
|
||||
// burst.
|
||||
inlineTimeout = 3 * time.Second
|
||||
)
|
||||
|
||||
// handleInline answers "@botname <prefix>" with the matching aliases.
|
||||
@@ -32,51 +44,52 @@ func (s *state) handleInline(ctx context.Context, b *bot.Bot, update *models.Upd
|
||||
return nil
|
||||
}
|
||||
|
||||
names, err := s.store.List(ctx, "")
|
||||
ctx, cancel := context.WithTimeout(ctx, inlineTimeout)
|
||||
defer cancel()
|
||||
started := time.Now()
|
||||
|
||||
// One round trip for names *and* values. Reading the names and then each
|
||||
// alias would cost a round trip per saved name on every keystroke, which is
|
||||
// exactly the latency an expiring query cannot absorb.
|
||||
docs, err := s.store.Scan(ctx, "")
|
||||
if err != nil {
|
||||
log.Error("alias_inline_list", "err", err)
|
||||
log.Error("alias_inline_scan", "err", err)
|
||||
// Answer with nothing rather than leaving the client spinning. An empty
|
||||
// answer is also what Telegram expects when a query has no matches.
|
||||
return s.answer(ctx, b, query.ID, nil)
|
||||
return s.answer(ctx, b, query.ID, nil, started)
|
||||
}
|
||||
|
||||
// Scan returns key order, so the picker is sorted with no sort here.
|
||||
prefix := strings.ToLower(strings.TrimSpace(query.Query))
|
||||
matches := make([]string, 0, len(names))
|
||||
for _, name := range names {
|
||||
if prefix == "" || strings.HasPrefix(name, prefix) {
|
||||
matches = append(matches, name)
|
||||
}
|
||||
}
|
||||
sort.Strings(matches)
|
||||
if len(matches) > maxInlineResults {
|
||||
matches = matches[:maxInlineResults]
|
||||
}
|
||||
|
||||
results := make([]models.InlineQueryResult, 0, len(matches))
|
||||
for _, name := range matches {
|
||||
entry, found, err := s.get(ctx, name)
|
||||
if err != nil {
|
||||
// One unreadable record must not blank the whole picker.
|
||||
log.Error("alias_inline_get", "name", name, "err", err)
|
||||
results := make([]models.InlineQueryResult, 0, min(len(docs), maxInlineResults))
|
||||
for _, doc := range docs {
|
||||
if prefix != "" && !strings.HasPrefix(doc.ID, prefix) {
|
||||
continue
|
||||
}
|
||||
if !found {
|
||||
continue // deleted between the List and this read
|
||||
}
|
||||
if r := inlineResult(name, entry); r != nil {
|
||||
if r := inlineResult(doc.ID, doc.Val); r != nil {
|
||||
results = append(results, r)
|
||||
}
|
||||
if len(results) == maxInlineResults {
|
||||
break // Telegram's cap; the rest stay reachable by name
|
||||
}
|
||||
}
|
||||
return s.answer(ctx, b, query.ID, results)
|
||||
return s.answer(ctx, b, query.ID, results, started)
|
||||
}
|
||||
|
||||
func (s *state) answer(ctx context.Context, b *bot.Bot, queryID string, results []models.InlineQueryResult) error {
|
||||
func (s *state) answer(ctx context.Context, b *bot.Bot, queryID string, results []models.InlineQueryResult, started time.Time) error {
|
||||
_, err := b.AnswerInlineQuery(ctx, &bot.AnswerInlineQueryParams{
|
||||
InlineQueryID: queryID,
|
||||
Results: results,
|
||||
CacheTime: inlineCacheSeconds,
|
||||
})
|
||||
return err
|
||||
if err != nil {
|
||||
// The elapsed time is the whole diagnosis when Telegram rejects the
|
||||
// answer as stale: it separates "this handler was slow" from "the query
|
||||
// was already old when it reached us".
|
||||
return fmt.Errorf("answer %d results after %s: %w",
|
||||
len(results), time.Since(started).Round(time.Millisecond), err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// inlineResult maps one alias to the inline result type that carries it, or nil
|
||||
|
||||
@@ -181,3 +181,25 @@ func TestInline_CapsAtFiftyResults(t *testing.T) {
|
||||
func uniqueName(i int) string {
|
||||
return "n" + strings.Repeat("x", i/10) + string(rune('a'+i%10))
|
||||
}
|
||||
|
||||
// The cap counts results the picker can actually show. A kind with no cached
|
||||
// inline type must not consume a slot, or a handful of video notes would
|
||||
// shrink an otherwise full answer.
|
||||
func TestInline_VideoNotesDoNotConsumeCapSlots(t *testing.T) {
|
||||
rb := installAlias(t)
|
||||
for i := 0; i < 10; i++ {
|
||||
rb.Bot.ProcessUpdate(context.Background(),
|
||||
aliasCmd(uniqueName(i), &models.Message{VideoNote: &models.VideoNote{FileID: "note-id"}}))
|
||||
}
|
||||
for i := 10; i < 70; i++ {
|
||||
rb.Bot.ProcessUpdate(context.Background(),
|
||||
aliasCmd(uniqueName(i), &models.Message{Text: "x"}))
|
||||
}
|
||||
|
||||
rb.Reset()
|
||||
rb.Bot.ProcessUpdate(context.Background(), inlineQuery(7, ""))
|
||||
|
||||
if got := len(inlineResults(t, rb)); got != 50 {
|
||||
t.Errorf("returned %d results, want the full 50 despite the skipped video notes", got)
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"fmt"
|
||||
"html"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -263,52 +262,39 @@ func (s *state) handleAliases(ctx context.Context, b *bot.Bot, update *models.Up
|
||||
return nil
|
||||
}
|
||||
|
||||
names, err := s.store.List(ctx, "")
|
||||
// Scan, not List plus a read per name: the kind lives in the document, so a
|
||||
// name-only listing would cost a round trip per alias to label each line.
|
||||
// Scan also returns key order, which is what makes the same command twice
|
||||
// produce the same list.
|
||||
docs, err := s.store.Scan(ctx, "")
|
||||
if err != nil {
|
||||
log.Error("alias_list", "err", err)
|
||||
return chathelper.Reply(ctx, b, msg, genericFailure)
|
||||
}
|
||||
if len(names) == 0 {
|
||||
if len(docs) == 0 {
|
||||
return chathelper.Reply(ctx, b, msg,
|
||||
"No aliases saved yet. Reply to a message with /alias <name> to save one.")
|
||||
}
|
||||
|
||||
// List gives no ordering guarantee, and an unstable list is unreadable when
|
||||
// it is the same command run twice.
|
||||
sort.Strings(names)
|
||||
return chathelper.ReplyHTML(ctx, b, msg, s.renderNames(ctx, names))
|
||||
return chathelper.ReplyHTML(ctx, b, msg, renderNames(docs))
|
||||
}
|
||||
|
||||
// renderNames formats the list as Telegram HTML, trimmed to fit one message.
|
||||
//
|
||||
// One line per alias, each showing what the name holds, with the invocation
|
||||
// wrapped in <code> so tapping it copies a command ready to send.
|
||||
//
|
||||
// This costs one store read per *listed* alias: DocStore has no bulk get and
|
||||
// the kind lives in the document. The reads stop as soon as the message is
|
||||
// full, so the cost is bounded by what fits in one reply rather than by how
|
||||
// many aliases exist.
|
||||
func (s *state) renderNames(ctx context.Context, names []string) string {
|
||||
func renderNames(docs []storage.Doc[Alias]) string {
|
||||
var sb strings.Builder
|
||||
fmt.Fprintf(&sb, "%d aliases:", len(names))
|
||||
|
||||
for i, name := range names {
|
||||
entry, found, err := s.get(ctx, name)
|
||||
if err != nil {
|
||||
// One unreadable record must not blank the whole list.
|
||||
log.Error("alias_list_get", "name", name, "err", err)
|
||||
} else if !found {
|
||||
continue // deleted between the List above and this read
|
||||
}
|
||||
fmt.Fprintf(&sb, "%d aliases:", len(docs))
|
||||
|
||||
for i, doc := range docs {
|
||||
// Escaped despite parseName restricting names to [a-zA-Z0-9_]: the
|
||||
// validation and the rendering are far apart, and a later relaxation of
|
||||
// the name rules must not silently become an HTML injection.
|
||||
line := "\n<code>/" + html.EscapeString(name) + "</code> — " + kindLabel(entry.Kind)
|
||||
line := "\n<code>/" + html.EscapeString(doc.ID) + "</code> — " + kindLabel(doc.Val.Kind)
|
||||
// Reserve room for the "…and N more" tail before committing to a line,
|
||||
// so the trim can never be what pushes the message over the limit.
|
||||
if sb.Len()+len(line) > maxListBytes {
|
||||
fmt.Fprintf(&sb, "\n…and %d more.", len(names)-i)
|
||||
fmt.Fprintf(&sb, "\n…and %d more.", len(docs)-i)
|
||||
return sb.String()
|
||||
}
|
||||
sb.WriteString(line)
|
||||
@@ -320,7 +306,7 @@ func (s *state) renderNames(ctx context.Context, names []string) string {
|
||||
//
|
||||
// Differs from describe in exactly one case: text reads as "message" in a
|
||||
// sentence ("send that message") but as "text" in a column of kinds, next to
|
||||
// sticker and video. An empty kind means the read above failed.
|
||||
// sticker and video. An empty kind means a stored document without one.
|
||||
func kindLabel(kind string) string {
|
||||
switch kind {
|
||||
case kindText:
|
||||
|
||||
Reference in new issue
Block a user