mirror of
https://github.com/tiennm99/miti99bot.git
synced 2026-09-13 20:20:52 +00:00
Concurrency - lolschedule: serialize subscriber Get→mutate→Put via state.subscribersMu; the single-slot list was previously losing writes under concurrent /lolschedule_subscribe. - trading: PriceClient memoises its default *http.Client so /trade_stats reuses TLS connections across held tickers. Observability - server/log_middleware: defer the req log line and recover panics so a panicking cron handler still emits the structured req entry CloudWatch filters on for 5xx alerting. - server/router (cron): inner recover with cron-name context captures the panicking job before the middleware's safety net does. - telegram/webhook: rune-safe truncation in dispatch logs — Vietnamese, Korean, and emoji previews no longer ship as garbled bytes. - lolschedule/api_client: same rune-safe fix for error-body log truncation. - telegram/webhook: gate the post-recover WriteHeader(200) so a panicking handler that already touched w doesn't trigger superfluous-WriteHeader. Correctness - twentyq: clearGame error during solved-relaunch is logged instead of silently swallowed (was a permanent deadlock vector on KV failure). - misc /mstats: KV read failure replies "Could not load stats. Try again later." to the user instead of returning into the dispatcher; matches the pattern other modules use. - migrate_cf_data trading-audit-dump: surface f.Close error so a truncated JSONL never passes silently as a complete audit dump. Operator ergonomics - migrate_cf_data (all 4 subcommands): signal.NotifyContext for SIGINT / SIGTERM. Ctrl-C mid-Scan now propagates cleanly instead of leaving a half-converted DynamoDB table. - ai/ratelimit: doc the Lambda-recycle memory bound to match keylock.Map so a future reviewer doesn't re-flag the unbounded map. I/O-changing (user-approved) - lolschedule daily push auto-prunes subscribers whose Telegram error matches a terminal marker (blocked / deactivated / chat gone). Transient errors keep the chat on the list. Subscribe message updated to mention the auto-cleanup. - twentyq seed pool grown 50 → 178; repeat-collision threshold moves from ~9 plays to ~17 (birthday paradox). - util /info flipped Public → Protected — chat/thread/sender IDs are no longer enumerable by every group member. - cmd/server WriteTimeout 6min → 75s (cron 60s + 15s slack). No-op on Lambda; matters only for local non-Lambda runs. - webhook + cron rejection paths drop response bodies (no fingerprintable text for internet scanners hitting the public Function URL). Status codes preserved for CloudWatch metrics; structured log lines carry the rejection reason for operator triage. Tests added: TestTruncateRunes, TestRunDailyPush_PrunesDeadSubscribers, TestIsTerminalSendError, TestInfo_DeniedToNonOwner, TestInfo_DeniedToChannelMessageNoFrom, plus owner-allowed counterparts.
103 lines
3.3 KiB
Go
103 lines
3.3 KiB
Go
// Package misc is a small stub module that proves the framework end-to-end:
|
|
// /ping (public, exercises KV write), /mstats (protected, exercises KV read),
|
|
// /fortytwo (private easter egg).
|
|
package misc
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/go-telegram/bot"
|
|
"github.com/go-telegram/bot/models"
|
|
|
|
"github.com/tiennm99/miti99bot/internal/log"
|
|
"github.com/tiennm99/miti99bot/internal/modules"
|
|
"github.com/tiennm99/miti99bot/internal/modules/util/chathelper"
|
|
"github.com/tiennm99/miti99bot/internal/storage"
|
|
)
|
|
|
|
// lastPingKey is the per-module KV key /ping writes and /mstats reads.
|
|
const lastPingKey = "last_ping"
|
|
|
|
// lastPing mirrors the JS bot's wire format: { at: <ms-since-epoch number> }.
|
|
// Stored as int64 ms-epoch (not time.Time → RFC3339) so a future cross-runtime
|
|
// KV export/import migration round-trips byte-for-byte.
|
|
type lastPing struct {
|
|
At int64 `json:"at"`
|
|
}
|
|
|
|
// New is the module Factory. Captures the per-module Deps via closure so each
|
|
// command handler has direct access to its KV store.
|
|
func New(deps modules.Deps) modules.Module {
|
|
return modules.Module{
|
|
Commands: []modules.Command{
|
|
pingCommand(deps),
|
|
mstatsCommand(deps),
|
|
fortytwoCommand(),
|
|
},
|
|
}
|
|
}
|
|
|
|
func pingCommand(deps modules.Deps) modules.Command {
|
|
return modules.Command{
|
|
Name: "ping",
|
|
Visibility: modules.VisibilityPublic,
|
|
Description: "Health check — replies pong and records last ping",
|
|
Handler: func(ctx context.Context, b *bot.Bot, update *models.Update) error {
|
|
if update.Message == nil {
|
|
return nil
|
|
}
|
|
// Best-effort write — if KV is unavailable, still reply.
|
|
payload := lastPing{At: chathelper.NowMillis()}
|
|
if err := deps.KV.PutJSON(ctx, lastPingKey, payload); err != nil {
|
|
log.Error("kv put failed", "module", "misc", "command", "ping", "key", lastPingKey, "err", err)
|
|
}
|
|
return chathelper.Reply(ctx, b, update.Message, "pong")
|
|
},
|
|
}
|
|
}
|
|
|
|
func mstatsCommand(deps modules.Deps) modules.Command {
|
|
return modules.Command{
|
|
Name: "mstats",
|
|
Visibility: modules.VisibilityProtected,
|
|
Description: "Show the timestamp of the last /ping",
|
|
Handler: func(ctx context.Context, b *bot.Bot, update *models.Update) error {
|
|
if update.Message == nil {
|
|
return nil
|
|
}
|
|
var last lastPing
|
|
text := "last ping: never"
|
|
err := deps.KV.GetJSON(ctx, lastPingKey, &last)
|
|
switch {
|
|
case err == nil && last.At > 0:
|
|
text = fmt.Sprintf("last ping: %s",
|
|
time.UnixMilli(last.At).UTC().Format(time.RFC3339))
|
|
case err != nil && !errors.Is(err, storage.ErrNotFound):
|
|
// User-visible reply mirrors how trading/wordle/loldle handle
|
|
// transient KV failures — returning the error here would leave
|
|
// the user with no reply at all.
|
|
log.Error("kv get failed", "module", "misc", "command", "mstats", "key", lastPingKey, "err", err)
|
|
text = "Could not load stats. Try again later."
|
|
}
|
|
return chathelper.Reply(ctx, b, update.Message, text)
|
|
},
|
|
}
|
|
}
|
|
|
|
func fortytwoCommand() modules.Command {
|
|
return modules.Command{
|
|
Name: "fortytwo",
|
|
Visibility: modules.VisibilityPrivate,
|
|
Description: "Easter egg — the answer",
|
|
Handler: func(ctx context.Context, b *bot.Bot, update *models.Update) error {
|
|
if update.Message == nil {
|
|
return nil
|
|
}
|
|
return chathelper.Reply(ctx, b, update.Message, "The answer.")
|
|
},
|
|
}
|
|
}
|