mirror of
https://github.com/tiennm99/miti99bot.git
synced 2026-09-18 16:20:25 +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.
82 lines
2.3 KiB
Go
82 lines
2.3 KiB
Go
package lolschedule
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"github.com/tiennm99/miti99bot/internal/storage"
|
|
)
|
|
|
|
// subscribersKey is the KV slot holding the per-module subscriber list.
|
|
// Stored as a JSON array of int64 chat ids — same shape as JS so a
|
|
// cross-runtime KV migration round-trips byte-for-byte.
|
|
const subscribersKey = "subscribers"
|
|
|
|
// listSubscribers returns the current subscriber list, or an empty slice
|
|
// if none have ever subscribed.
|
|
func listSubscribers(ctx context.Context, kv storage.KVStore) ([]int64, error) {
|
|
var ids []int64
|
|
err := kv.GetJSON(ctx, subscribersKey, &ids)
|
|
switch {
|
|
case err == nil:
|
|
return ids, nil
|
|
case errors.Is(err, storage.ErrNotFound):
|
|
return nil, nil
|
|
default:
|
|
return nil, fmt.Errorf("lolschedule listSubscribers: %w", err)
|
|
}
|
|
}
|
|
|
|
// addSubscriber appends chatID if absent. Returns true on first-add, false
|
|
// when already subscribed (idempotent).
|
|
//
|
|
// Concurrency: the list lives in a single KV slot, so a concurrent
|
|
// Get→mutate→Put from two chats subscribing in the same millisecond would
|
|
// drop one write. Callers MUST serialize through state.subscribersMu (or an
|
|
// equivalent module-scoped lock) before calling this.
|
|
func addSubscriber(ctx context.Context, kv storage.KVStore, chatID int64) (bool, error) {
|
|
ids, err := listSubscribers(ctx, kv)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
for _, id := range ids {
|
|
if id == chatID {
|
|
return false, nil
|
|
}
|
|
}
|
|
ids = append(ids, chatID)
|
|
if err := kv.PutJSON(ctx, subscribersKey, ids); err != nil {
|
|
return false, fmt.Errorf("lolschedule addSubscriber: %w", err)
|
|
}
|
|
return true, nil
|
|
}
|
|
|
|
// removeSubscriber drops chatID from the list. Returns true when removed,
|
|
// false when chatID wasn't present (idempotent).
|
|
//
|
|
// Concurrency: same single-slot Get→mutate→Put as addSubscriber; callers
|
|
// must hold state.subscribersMu.
|
|
func removeSubscriber(ctx context.Context, kv storage.KVStore, chatID int64) (bool, error) {
|
|
ids, err := listSubscribers(ctx, kv)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
out := make([]int64, 0, len(ids))
|
|
removed := false
|
|
for _, id := range ids {
|
|
if id == chatID {
|
|
removed = true
|
|
continue
|
|
}
|
|
out = append(out, id)
|
|
}
|
|
if !removed {
|
|
return false, nil
|
|
}
|
|
if err := kv.PutJSON(ctx, subscribersKey, out); err != nil {
|
|
return false, fmt.Errorf("lolschedule removeSubscriber: %w", err)
|
|
}
|
|
return true, nil
|
|
}
|