mirror of
https://github.com/warmbly/warmbly.git
synced 2026-11-27 00:07:00 +00:00
Merge pull request #1146 from warmbly/perf/postgres-load
feat: cut Postgres load: single-replica loops, claimed task and queue polling, fewer statements per arrival and sync report, retention and prune indexes
This commit is contained in:
@@ -292,6 +292,13 @@ jobs:
|
||||
run: |
|
||||
go test -race -p 1 ./internal/repository ./internal/scheduler ./internal/tasks -run '^TestLive(MailboxSendClaim(AdmitsOnePerGap|WaitsOutAReservedSend)|BookedSendsLeaveOutCampaignWakeups|ParkedCampaignDoesNotThrottleItsPoolMate|BookedSendsStillSpaceTheCampaign|ClaimedMailboxIsPassedOver|CampaignsSharingAMailboxSendOncePerGap|LostMailboxClaimReschedulesWithoutSending)$' -count=1
|
||||
|
||||
- name: Postgres queue claim regressions (PostgreSQL)
|
||||
if: matrix.suite == 'live-3'
|
||||
env:
|
||||
WARMBLY_TEST_DB: postgres://warmbly:warmbly@127.0.0.1:5432/warmbly_test?sslmode=disable
|
||||
run: |
|
||||
go test -race -p 1 ./internal/repository -run '^TestLive(ConcurrentDispatchersNeverClaimTheSameTask|SendResultEffectsBatchClaimsDeliverEachEffectOnce|CRMClaimTakesDueAndLapsedJobsOnce)$' -count=1
|
||||
|
||||
- name: Invited signup atomic provisioning regressions (PostgreSQL)
|
||||
if: matrix.suite == 'live-1'
|
||||
env:
|
||||
|
||||
@@ -109,7 +109,28 @@ const RETENTION_FIELDS = [
|
||||
setting: "warmup_event_days",
|
||||
label: "Warmup records (days)",
|
||||
min: 30,
|
||||
help: "Per-message warmup records: tokens, receipts, tampering events and spam reports. The pool health bands read the last 30 days, which is the floor. The daily sent and received counts behind the analytics are separate and never pruned.",
|
||||
help: "Per-message warmup records: tokens, receipts, tampering events, spam reports and the record of which messages belong to a warmup thread. The pool health bands read the last 30 days, which is the floor. The daily sent and received counts behind the analytics are separate and never pruned.",
|
||||
},
|
||||
{
|
||||
key: "campaignLogDays",
|
||||
setting: "campaign_log_days",
|
||||
label: "Campaign activity feed (days)",
|
||||
min: 0,
|
||||
help: "Entries in each campaign's activity feed: sends that failed or were deferred, pauses and the reasons for them. Campaign stats, progress and sent mail are separate and unaffected. 0 keeps every entry, which is the default.",
|
||||
},
|
||||
{
|
||||
key: "notificationDays",
|
||||
setting: "notification_days",
|
||||
label: "Notifications (days)",
|
||||
min: 0,
|
||||
help: "In-app notifications, read or unread. One still waiting to be emailed is kept until it is sent or skipped. 0 keeps every entry, which is the default.",
|
||||
},
|
||||
{
|
||||
key: "webhookDeliveryDays",
|
||||
setting: "webhook_delivery_days",
|
||||
label: "Webhook delivery log (days)",
|
||||
min: 0,
|
||||
help: "Delivered and abandoned webhook deliveries, with the payload and the endpoint's response excerpt. A delivery still being retried is kept until it settles. A delivery past this window can no longer be redelivered from the log. 0 keeps every entry, which is the default.",
|
||||
},
|
||||
] as const;
|
||||
|
||||
@@ -120,25 +141,31 @@ const RETENTION_PRESETS = [
|
||||
{
|
||||
id: "default",
|
||||
label: "Defaults",
|
||||
description: "365 / 180 / 90 days, warmup 30 / 365",
|
||||
description: "365 / 180 / 90 days, warmup 30 / 365, feeds kept",
|
||||
values: {
|
||||
engagementDays: "365",
|
||||
formDays: "180",
|
||||
auditDays: "90",
|
||||
warmupMailDays: "30",
|
||||
warmupEventDays: "365",
|
||||
campaignLogDays: "0",
|
||||
notificationDays: "0",
|
||||
webhookDeliveryDays: "0",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "minimal",
|
||||
label: "Minimal retention",
|
||||
description: "30 / 30 / 30 days, warmup 7 / 30",
|
||||
description: "30 / 30 / 30 days, warmup 7 / 30, feeds 30 / 30 / 30",
|
||||
values: {
|
||||
engagementDays: "30",
|
||||
formDays: "30",
|
||||
auditDays: "30",
|
||||
warmupMailDays: "7",
|
||||
warmupEventDays: "30",
|
||||
campaignLogDays: "30",
|
||||
notificationDays: "30",
|
||||
webhookDeliveryDays: "30",
|
||||
},
|
||||
},
|
||||
] as const;
|
||||
@@ -304,6 +331,9 @@ function toForm(s: InstanceSettings): FormState {
|
||||
auditDays: String(s.retention.audit_log_days),
|
||||
warmupMailDays: String(s.retention.warmup_mail_days),
|
||||
warmupEventDays: String(s.retention.warmup_event_days),
|
||||
campaignLogDays: String(s.retention.campaign_log_days ?? 0),
|
||||
notificationDays: String(s.retention.notification_days ?? 0),
|
||||
webhookDeliveryDays: String(s.retention.webhook_delivery_days ?? 0),
|
||||
},
|
||||
tracking: {
|
||||
machineWindowOpen: String(s.tracking.machine_window_open_seconds),
|
||||
@@ -373,7 +403,7 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) {
|
||||
!!server &&
|
||||
!!form &&
|
||||
RETENTION_FIELDS.some(
|
||||
(f) => form.retention[f.key] !== String(server.retention[f.setting]),
|
||||
(f) => form.retention[f.key] !== String(server.retention[f.setting] ?? 0),
|
||||
);
|
||||
const trackingDirty =
|
||||
!!server &&
|
||||
@@ -482,6 +512,9 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) {
|
||||
audit_log_days: Number(form.retention.auditDays),
|
||||
warmup_mail_days: Number(form.retention.warmupMailDays),
|
||||
warmup_event_days: Number(form.retention.warmupEventDays),
|
||||
campaign_log_days: Number(form.retention.campaignLogDays),
|
||||
notification_days: Number(form.retention.notificationDays),
|
||||
webhook_delivery_days: Number(form.retention.webhookDeliveryDays),
|
||||
},
|
||||
tracking: {
|
||||
machine_window_open_seconds: Number(form.tracking.machineWindowOpen),
|
||||
|
||||
@@ -135,6 +135,11 @@ export interface InstanceSettings {
|
||||
// second. The daily warmup statistics are never pruned.
|
||||
warmup_mail_days: number;
|
||||
warmup_event_days: number;
|
||||
// History shown in the product: a campaign's activity feed, in-app
|
||||
// notifications, and each webhook endpoint's delivery log.
|
||||
campaign_log_days: number;
|
||||
notification_days: number;
|
||||
webhook_delivery_days: number;
|
||||
};
|
||||
// How soon after a send an open or click is recorded as automated. The
|
||||
// clock starts at dispatch to the worker, so the window also covers the
|
||||
|
||||
+15
-3
@@ -150,6 +150,7 @@ import (
|
||||
"github.com/warmbly/warmbly/internal/infrastructure/storage"
|
||||
"github.com/warmbly/warmbly/internal/jobrun"
|
||||
"github.com/warmbly/warmbly/internal/jobs"
|
||||
"github.com/warmbly/warmbly/internal/leader"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/notify"
|
||||
"github.com/warmbly/warmbly/internal/observability"
|
||||
@@ -866,6 +867,8 @@ func main() {
|
||||
Cache: cache,
|
||||
AppDomains: oauthService.AllowedWebhookDomains,
|
||||
})
|
||||
// An enqueue in any process wakes the worker, so an idle queue's slower poll never delays a delivery.
|
||||
go webhookWorker.Listen(ctx, primaryDB.ConnectSession)
|
||||
go webhookWorker.Run(ctx)
|
||||
campaignProgressRepository := repository.NewCampaignProgressRepository(primaryDB.Pool)
|
||||
warmupService = warmupapp.NewService(warmupRepository)
|
||||
@@ -2140,20 +2143,26 @@ func main() {
|
||||
go segmentService.StartCampaignSegmentSync(ctx, 2*time.Minute)
|
||||
}
|
||||
|
||||
// Loops that keep their place in memory run on one backend at a time, the
|
||||
// same one for as long as it holds the lock, so a fleet of replicas does
|
||||
// the work once instead of once per replica.
|
||||
elector := leader.New(primaryDB, "backend")
|
||||
|
||||
// Worker reconciler: assign + (re)load every active mailbox onto its
|
||||
// worker. Workers hold accounts in memory only, so this is what makes a
|
||||
// freshly onboarded account send/sync and re-seeds a restarted worker.
|
||||
go emailService.StartWorkerReconciler(ctx, 60*time.Second)
|
||||
elector.Go("worker_reconciler", func(ctx context.Context) { emailService.StartWorkerReconciler(ctx, 60*time.Second) })
|
||||
|
||||
// Unibox search backfill: record the searchable text of messages synced
|
||||
// before bodies were indexed, so search covers the whole archive and not
|
||||
// just new mail. Walks the table once, then returns.
|
||||
go uniboxService.StartBodyTextBackfill(ctx)
|
||||
elector.Go("unibox_body_backfill", uniboxService.StartBodyTextBackfill)
|
||||
|
||||
// Automation signing secrets live in each connection's sealed config.
|
||||
if m, ok := integrationServiceForHandler.(interface{ StartSigningSecretMigration(context.Context) }); ok {
|
||||
go m.StartSigningSecretMigration(ctx)
|
||||
elector.Go("signing_secret_migration", m.StartSigningSecretMigration)
|
||||
}
|
||||
go elector.Run(ctx)
|
||||
|
||||
// Danger zone: schedule + execute delayed deletions (orgs, accounts).
|
||||
dangerZoneRepository := repository.NewDangerZoneRepository(primaryDB.Pool)
|
||||
@@ -2207,6 +2216,9 @@ func main() {
|
||||
auditRetentionScheduler := jobs.NewAuditRetentionScheduler(auditRetentionJob, 6*time.Hour)
|
||||
go auditRetentionScheduler.Start(ctx)
|
||||
|
||||
// Feeds, logs and finished bookkeeping rows past their windows, in batches.
|
||||
go jobs.NewTableRetentionJob(repository.NewTableRetentionRepository(primaryDB.Pool), instanceSettings).Start(ctx, 6*time.Hour)
|
||||
|
||||
// Website tracking: the snippet's settings, the ingest path the tracking
|
||||
// service forwards page views to, and the per-workspace retention sweep
|
||||
// that keeps the window promised on the settings page.
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func runDB(ctx context.Context, args []string) error {
|
||||
if len(args) == 0 {
|
||||
dbUsage(os.Stderr)
|
||||
return errors.New("`db` needs a subcommand. Pick one from the list above.")
|
||||
}
|
||||
switch args[0] {
|
||||
case "help", "-h", "--help":
|
||||
dbUsage(os.Stdout)
|
||||
return nil
|
||||
case "load":
|
||||
return runDBLoad(ctx, args[1:])
|
||||
}
|
||||
dbUsage(os.Stderr)
|
||||
return fmt.Errorf("unknown db subcommand %q", args[0])
|
||||
}
|
||||
|
||||
func dbUsage(w io.Writer) {
|
||||
fmt.Fprintln(w, "Usage:\n warmblyctl db load [--limit 15] [--json]")
|
||||
}
|
||||
|
||||
// dbLoad is what the database is busy with. Read-only: it reads the statistics views and changes nothing.
|
||||
type dbLoad struct {
|
||||
MaxConnections int `json:"max_connections"`
|
||||
Connections []dbConnections `json:"connections"`
|
||||
Busy []dbBusy `json:"busy"`
|
||||
Statements []dbStatement `json:"statements"`
|
||||
StatementsNote string `json:"statements_note,omitempty"`
|
||||
Tables []dbTable `json:"tables"`
|
||||
Since *time.Time `json:"statements_since,omitempty"`
|
||||
Settings map[string]string `json:"settings"`
|
||||
}
|
||||
|
||||
type dbConnections struct {
|
||||
Application string `json:"application"`
|
||||
State string `json:"state"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
// dbBusy carries no query text: pg_stat_activity holds literal values, pg_stat_statements does not.
|
||||
type dbBusy struct {
|
||||
PID int `json:"pid"`
|
||||
Application string `json:"application"`
|
||||
State string `json:"state"`
|
||||
Seconds float64 `json:"seconds"`
|
||||
Wait string `json:"wait"`
|
||||
}
|
||||
|
||||
type dbStatement struct {
|
||||
QueryID int64 `json:"queryid"`
|
||||
Calls int64 `json:"calls"`
|
||||
TotalMS float64 `json:"total_ms"`
|
||||
MeanMS float64 `json:"mean_ms"`
|
||||
Rows int64 `json:"rows"`
|
||||
Query string `json:"query"`
|
||||
}
|
||||
|
||||
type dbTable struct {
|
||||
Name string `json:"name"`
|
||||
Bytes int64 `json:"bytes"`
|
||||
Live int64 `json:"live_rows"`
|
||||
Dead int64 `json:"dead_rows"`
|
||||
SeqScans int64 `json:"seq_scans"`
|
||||
LastVacuum *time.Time `json:"last_autovacuum,omitempty"`
|
||||
}
|
||||
|
||||
func runDBLoad(ctx context.Context, args []string) error {
|
||||
fs := newFlagSet("db load")
|
||||
limit := fs.Int("limit", 15, "rows to show per section")
|
||||
asJSON := fs.Bool("json", false, "print the report as JSON")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := noExtraArgs(fs); err != nil {
|
||||
return err
|
||||
}
|
||||
if *limit < 1 || *limit > 200 {
|
||||
return errors.New("--limit must be between 1 and 200")
|
||||
}
|
||||
c, err := connect(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer c.close()
|
||||
load, err := readDBLoad(ctx, c.db.Pool, *limit)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if *asJSON {
|
||||
enc := json.NewEncoder(os.Stdout)
|
||||
enc.SetIndent("", " ")
|
||||
return enc.Encode(load)
|
||||
}
|
||||
printDBLoad(os.Stdout, load)
|
||||
return nil
|
||||
}
|
||||
|
||||
func readDBLoad(ctx context.Context, pool *pgxpool.Pool, limit int) (*dbLoad, error) {
|
||||
load := &dbLoad{Settings: map[string]string{}, Connections: []dbConnections{}, Busy: []dbBusy{}, Statements: []dbStatement{}, Tables: []dbTable{}}
|
||||
if err := pool.QueryRow(ctx, `SELECT current_setting('max_connections')::int`).Scan(&load.MaxConnections); err != nil {
|
||||
return nil, fmt.Errorf("read max_connections: %w", err)
|
||||
}
|
||||
for _, name := range []string{"shared_buffers", "work_mem", "statement_timeout", "idle_in_transaction_session_timeout", "autovacuum_vacuum_scale_factor"} {
|
||||
var v string
|
||||
if err := pool.QueryRow(ctx, `SELECT current_setting($1, true)`, name).Scan(&v); err == nil {
|
||||
load.Settings[name] = v
|
||||
}
|
||||
}
|
||||
|
||||
// A client session another role owns shows no state to a role without pg_read_all_stats.
|
||||
rows, err := pool.Query(ctx, `SELECT COALESCE(NULLIF(application_name, ''), '(unnamed)'),
|
||||
CASE WHEN backend_type IS DISTINCT FROM 'client backend' THEN '(background)' ELSE COALESCE(state, '(hidden)') END, count(*)::int
|
||||
FROM pg_stat_activity WHERE pid <> pg_backend_pid()
|
||||
GROUP BY 1, 2 ORDER BY 3 DESC, 1, 2`)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read connections: %w", err)
|
||||
}
|
||||
for rows.Next() {
|
||||
var r dbConnections
|
||||
if err := rows.Scan(&r.Application, &r.State, &r.Count); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
load.Connections = append(load.Connections, r)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err = pool.Query(ctx, `SELECT pid, COALESCE(NULLIF(application_name, ''), '(unnamed)'), state,
|
||||
EXTRACT(EPOCH FROM now() - COALESCE(xact_start, query_start))::float8,
|
||||
COALESCE(wait_event_type || ':' || wait_event, '')
|
||||
FROM pg_stat_activity
|
||||
WHERE datname = current_database() AND pid <> pg_backend_pid() AND state IS NOT NULL AND state <> 'idle'
|
||||
ORDER BY COALESCE(xact_start, query_start) LIMIT $1`, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read active sessions: %w", err)
|
||||
}
|
||||
for rows.Next() {
|
||||
var r dbBusy
|
||||
if err := rows.Scan(&r.PID, &r.Application, &r.State, &r.Seconds, &r.Wait); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
load.Busy = append(load.Busy, r)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := readStatements(ctx, pool, limit, load); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err = pool.Query(ctx, `SELECT relname, pg_total_relation_size(relid), n_live_tup, n_dead_tup, seq_scan, last_autovacuum
|
||||
FROM pg_stat_user_tables ORDER BY pg_total_relation_size(relid) DESC LIMIT $1`, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read tables: %w", err)
|
||||
}
|
||||
for rows.Next() {
|
||||
var r dbTable
|
||||
if err := rows.Scan(&r.Name, &r.Bytes, &r.Live, &r.Dead, &r.SeqScans, &r.LastVacuum); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
load.Tables = append(load.Tables, r)
|
||||
}
|
||||
return load, rows.Err()
|
||||
}
|
||||
|
||||
// readStatements reads pg_stat_statements when the server has it. Only a query's text has its constants replaced, so other statements show their queryid alone.
|
||||
func readStatements(ctx context.Context, pool *pgxpool.Pool, limit int, load *dbLoad) error {
|
||||
var schema string
|
||||
err := pool.QueryRow(ctx, `SELECT n.nspname FROM pg_extension e JOIN pg_namespace n ON n.oid = e.extnamespace WHERE e.extname = 'pg_stat_statements'`).Scan(&schema)
|
||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
||||
return fmt.Errorf("check pg_stat_statements: %w", err)
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
load.StatementsNote = "pg_stat_statements is not installed; run CREATE EXTENSION pg_stat_statements as a superuser to see the costliest queries"
|
||||
return nil
|
||||
}
|
||||
rows, err := pool.Query(ctx, `SELECT COALESCE(queryid, 0), calls, total_exec_time, mean_exec_time, rows,
|
||||
CASE WHEN query ~* '^\s*(select|insert|update|delete|with|merge|values|table)\M'
|
||||
THEN left(regexp_replace(query, '\s+', ' ', 'g'), 200) ELSE '(not a query; text withheld)' END
|
||||
FROM `+pgx.Identifier{schema, "pg_stat_statements"}.Sanitize()+` WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database())
|
||||
ORDER BY total_exec_time DESC LIMIT $1`, limit)
|
||||
if err != nil {
|
||||
load.StatementsNote = "pg_stat_statements could not be read by this role: " + err.Error()
|
||||
return nil
|
||||
}
|
||||
for rows.Next() {
|
||||
var r dbStatement
|
||||
if err := rows.Scan(&r.QueryID, &r.Calls, &r.TotalMS, &r.MeanMS, &r.Rows, &r.Query); err != nil {
|
||||
return err
|
||||
}
|
||||
load.Statements = append(load.Statements, r)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
var since time.Time
|
||||
if err := pool.QueryRow(ctx, `SELECT stats_reset FROM `+pgx.Identifier{schema, "pg_stat_statements_info"}.Sanitize()).Scan(&since); err == nil {
|
||||
load.Since = &since
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func printDBLoad(w io.Writer, load *dbLoad) {
|
||||
used := 0
|
||||
for _, c := range load.Connections {
|
||||
// Background processes have their own slots, outside max_connections.
|
||||
if c.State != "(background)" {
|
||||
used += c.Count
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(w, "Client connections to the server, not counting this one: %d of max_connections %d\n", used, load.MaxConnections)
|
||||
tw := tabwriter.NewWriter(w, 2, 4, 2, ' ', 0)
|
||||
fmt.Fprintln(tw, " APPLICATION\tSTATE\tCOUNT")
|
||||
for _, c := range load.Connections {
|
||||
fmt.Fprintf(tw, " %s\t%s\t%d\n", c.Application, c.State, c.Count)
|
||||
}
|
||||
tw.Flush()
|
||||
|
||||
fmt.Fprintln(w, "\nLongest-running sessions:")
|
||||
if len(load.Busy) == 0 {
|
||||
fmt.Fprintln(w, " none")
|
||||
} else {
|
||||
tw = tabwriter.NewWriter(w, 2, 4, 2, ' ', 0)
|
||||
fmt.Fprintln(tw, " PID\tAPPLICATION\tSTATE\tSECONDS\tWAITING ON")
|
||||
for _, b := range load.Busy {
|
||||
fmt.Fprintf(tw, " %d\t%s\t%s\t%.1f\t%s\n", b.PID, b.Application, b.State, b.Seconds, b.Wait)
|
||||
}
|
||||
tw.Flush()
|
||||
}
|
||||
|
||||
fmt.Fprint(w, "\nCostliest statements")
|
||||
if load.Since != nil {
|
||||
fmt.Fprintf(w, " since %s", load.Since.Format(time.RFC3339))
|
||||
}
|
||||
fmt.Fprintln(w, ":")
|
||||
if load.StatementsNote != "" {
|
||||
fmt.Fprintf(w, " %s\n", load.StatementsNote)
|
||||
}
|
||||
tw = tabwriter.NewWriter(w, 2, 4, 2, ' ', 0)
|
||||
if len(load.Statements) > 0 {
|
||||
fmt.Fprintln(tw, " TOTAL MS\tCALLS\tMEAN MS\tROWS\tQUERYID\tQUERY")
|
||||
}
|
||||
for _, s := range load.Statements {
|
||||
fmt.Fprintf(tw, " %.0f\t%d\t%.2f\t%d\t%d\t%s\n", s.TotalMS, s.Calls, s.MeanMS, s.Rows, s.QueryID, strings.TrimSpace(s.Query))
|
||||
}
|
||||
tw.Flush()
|
||||
|
||||
fmt.Fprintln(w, "\nLargest tables:")
|
||||
tw = tabwriter.NewWriter(w, 2, 4, 2, ' ', 0)
|
||||
fmt.Fprintln(tw, " TABLE\tSIZE\tLIVE ROWS\tDEAD ROWS\tSEQ SCANS\tLAST AUTOVACUUM")
|
||||
for _, t := range load.Tables {
|
||||
vacuum := "never"
|
||||
if t.LastVacuum != nil {
|
||||
vacuum = t.LastVacuum.Format(time.RFC3339)
|
||||
}
|
||||
fmt.Fprintf(tw, " %s\t%s\t%d\t%d\t%d\t%s\n", t.Name, humanBytes(t.Bytes), t.Live, t.Dead, t.SeqScans, vacuum)
|
||||
}
|
||||
tw.Flush()
|
||||
}
|
||||
@@ -90,6 +90,8 @@ func dispatch(ctx context.Context, args []string) error {
|
||||
return runInboxTag(ctx, args[1:])
|
||||
case "keys":
|
||||
return runKeys(ctx, args[1:])
|
||||
case "db":
|
||||
return runDB(ctx, args[1:])
|
||||
}
|
||||
if _, ok := apiFamilies[args[0]]; ok {
|
||||
return runAPIResource(ctx, args[0], args[1:])
|
||||
@@ -138,6 +140,7 @@ var commands = []command{
|
||||
{"fleet rollout start", "Move the fleet to a tag in stages: one canary, then waves", composeExec + "fleet rollout start v1.4.2 --bake 30m"},
|
||||
{"fleet rollout status", "Show a staged rollout's stage, admitted nodes and halt reason", composeExec + "fleet rollout status"},
|
||||
{"fleet env-status", "Whether every live node has applied the current rendered env", composeExec + "fleet env-status"},
|
||||
{"db load", "Show what the database is busy with: connections by service, costliest queries, largest tables", composeExec + "db load"},
|
||||
}
|
||||
|
||||
func usage(w *os.File) {
|
||||
|
||||
@@ -52,6 +52,16 @@ Realtime fanout is a separate channel: backend and consumer publish JSON events
|
||||
|
||||
Object storage: encrypted email bodies (EMSG format) live in the blob store (filesystem by default, S3-compatible opt-in).
|
||||
|
||||
### Background loops across replicas
|
||||
|
||||
The backend and the consumer can each run as several replicas, and their background loops do their work once rather than once per replica:
|
||||
|
||||
- **Scheduled jobs** claim each run in `scheduled_job_runs`, so one replica runs each slot. They are listed under **Jobs** in the [admin panel](/development/admin-panel/). Each process asks for pending **Run now** requests for all its jobs in one query every 15 seconds.
|
||||
- **Loops that keep their place in memory** (the worker reconciler, the unibox search backfill and the signing-secret migration) run on whichever backend holds a Postgres session advisory lock. That backend keeps them until it stops or its lock connection breaks; another replica then takes over within about 30 seconds and starts them from the beginning, as a restart would. The lock costs each backend one direct connection while it leads and a short one every 30 seconds while it waits.
|
||||
- **Queues** that claim rows with `FOR UPDATE SKIP LOCKED` or a lease (webhook deliveries, CRM sync jobs, the arrival outbox) run on every replica and share the work.
|
||||
|
||||
A single backend wins the lock at boot and runs everything, as before. During a rolling deploy, replicas still on the previous release run their loops unconditionally until they are replaced, which is safe because every loop is idempotent.
|
||||
|
||||
## Data stores
|
||||
|
||||
| Store | Purpose |
|
||||
|
||||
@@ -416,7 +416,7 @@ one-command installer defaults.
|
||||
| Variable | What it does | Default | Restart needed |
|
||||
|---|---|---|---|
|
||||
| `PRIMARY_DB` | PostgreSQL connection string. Carries inline credentials, so it is never returned by any API | the compose postgres | yes |
|
||||
| `PRIMARY_DB_DIRECT` | Direct PostgreSQL connection for migrations, backups and session advisory locks. Required when `DB_POOL_MODE=transaction`. It must address the same database as `PRIMARY_DB`; its credentials can be different. With AWS configuration loading, the secret path is `postgres/primary_direct` | falls back to `PRIMARY_DB` in direct mode | yes |
|
||||
| `PRIMARY_DB_DIRECT` | Direct PostgreSQL connection for migrations, backups, session advisory locks and the webhook delivery listener. Required when `DB_POOL_MODE=transaction`. It must address the same database as `PRIMARY_DB`; its credentials can be different. With AWS configuration loading, the secret path is `postgres/primary_direct` | falls back to `PRIMARY_DB` in direct mode | yes |
|
||||
| `DB_POOL_MODE` | `direct` or `transaction` for the Go services. Transaction mode uses `PRIMARY_DB` for ordinary queries and `PRIMARY_DB_DIRECT` for session operations. It verifies server-side role defaults of nonzero `statement_timeout` at most 60 seconds and `idle_in_transaction_session_timeout` at most 5 minutes on every new pooled client connection. Configure those role defaults before connecting | `direct` | yes |
|
||||
| `DB_MIGRATIONS_ON_START` | Whether the backend applies embedded migrations at startup. Set `false` when a deployment job runs `/app/migrate` first. The backend still waits for a clean schema at the version its image requires. AWS configuration path: `postgres/migrations_on_start` | `true` for self-host compatibility; `false` in the AWS runtime root | yes |
|
||||
| `PGSSLROOTCERT` | Certificate bundle used to verify the database's TLS certificate, read by the Postgres driver. Amazon RDS chains to a root in no public trust store, so `sslmode=verify-full` against it needs AWS's bundle; the backend and consumer images ship it at `/etc/ssl/rds/global-bundle.pem`. Prefer `sslrootcert=` in the DSN so the setting travels with the connection it applies to | unset (system trust store) | yes |
|
||||
@@ -862,7 +862,7 @@ Per-mailbox `test_mode`, `test_send_enabled` and `test_receive_enabled` separate
|
||||
|
||||
| Variable | What it does | Default |
|
||||
|---|---|---|
|
||||
| `TASKS_PROVIDER` | `local` (an in-process Postgres poller) or `gcloud` (Cloud Tasks) | `local` |
|
||||
| `TASKS_PROVIDER` | `local` (an in-process Postgres poller; each backend replica claims the due tasks it runs) or `gcloud` (Cloud Tasks) | `local` |
|
||||
| `TASKS_LOCAL_POLL_INTERVAL` | How often the local poller looks for due work | `1s` |
|
||||
| `SEND_PLAN_SNAPSHOT_INTERVAL` | How often the backend re-walks the send plan of every active campaign whose stored plan is out of date. Each walk reads all of that campaign's leads, so a longer interval lowers database load on large campaigns | `1m` |
|
||||
| `SEND_PLAN_SNAPSHOT_MAX_AGE` | How old a stored send plan may be before it counts as out of date. An out-of-date plan is still served, with `stale: true`, while a fresh one is computed in the background | three times `SEND_PLAN_SNAPSHOT_INTERVAL` (`3m`) |
|
||||
@@ -1120,7 +1120,10 @@ These are the only settings a browser can change, and no environment variable ow
|
||||
| `retention.form_event_days` | integer, 1 to 3650 | `180` | How long form funnel events (views, starts, field-level drop-off) are kept. Funnel reports range up to 90 days, so anything shorter shortens the report too |
|
||||
| `retention.audit_log_days` | integer, 1 to 3650 | `90` | How long the audit trail is kept. It carries IP addresses, user agents and change payloads, so this is also how long that data is held |
|
||||
| `retention.warmup_mail_days` | integer, 3 to 3650 | `30` | How long warmup mail stays in each mailbox before Warmbly deletes it, wherever the mailbox's filing setting keeps it (Trash on Gmail), with the stored copy of its body. A mailbox can set its own window on the Warmup tab of its drawer or through `warmup_retention_days` on the API; this is what every other mailbox follows. The floor leaves room for the engagement and for a reply in the thread to finish |
|
||||
| `retention.warmup_event_days` | integer, 30 to 3650 | `365` | How long the per-message warmup records (tokens, receipts, tampering events, spam reports, and a linked instance's closed commands and reported arrivals) are kept. The pool health bands read the last 30 days, which is the floor. The daily sent and received counts behind the warmup analytics are separate and never pruned |
|
||||
| `retention.warmup_event_days` | integer, 30 to 3650 | `365` | How long the per-message warmup records (tokens, receipts, tampering events, spam reports, warmup thread turns, and a linked instance's closed commands and reported arrivals) are kept. The pool health bands read the last 30 days, which is the floor. The daily sent and received counts behind the warmup analytics are separate and never pruned |
|
||||
| `retention.campaign_log_days` | integer, 0 to 3650 | `0` | How long each campaign's activity feed keeps an entry. `0` keeps every entry. Campaign stats, progress and sent mail are separate and unaffected |
|
||||
| `retention.notification_days` | integer, 0 to 3650 | `0` | How long in-app notifications are kept, read or unread. `0` keeps them all. One still waiting to be emailed is kept until it is sent or skipped |
|
||||
| `retention.webhook_delivery_days` | integer, 0 to 3650 | `0` | How long a settled webhook delivery (delivered or abandoned) stays in its endpoint's delivery log. `0` keeps them all. A delivery still being retried is kept until it settles, and one past this window can no longer be redelivered |
|
||||
| `tracking.machine_window_open_seconds` | integer, 1 to 900 | `60` | How soon after a send was dispatched an open is recorded as automated rather than a person's. The clock starts when the send is handed to a worker, so this window also covers the sending provider's queue and the transit to the recipient, not just reading time. Raise it when delivery-time scanners are being counted as opens; lower it when recipients who read immediately are being missed. A change applies within a minute and only to events recorded after it |
|
||||
| `tracking.machine_window_click_seconds` | integer, 1 to 900 | `30` | The same window for click tickets. Kept separate because the two mistakes cost different things: a misjudged open loses a metric, a misjudged click loses the automation behind an interested lead |
|
||||
| `tracking.machine_window_probable_seconds` | integer, 1 to 86400 | `600` | The window used instead of the two above when the tracking service recognised the source as a mail-security network that also renders clicked pages for people, which Proofpoint, Mimecast and Cisco do through browser isolation. Such a match cannot settle whether a person is behind the request, so it widens the window rather than deciding: inside it the event is the delivery-time scan, past it the recipient who got to the mail later. Never applied shorter than the window for the kind of event in hand, so naming a network can only ever catch more scans. Its ceiling reaches a day because how long a vendor takes to detonate a link is the vendor's property, not the instance's |
|
||||
@@ -1139,7 +1142,7 @@ These are the only settings a browser can change, and no environment variable ow
|
||||
|
||||
The four `sync.*` values are read by the backend when a mailbox is loaded onto a worker (on connect, on reassignment, and by the reconciler's periodic republish), so a change reaches every mailbox within 30 minutes without a restart (the republish gives each mailbox one turn per 30 minutes, spread out so no worker gets them all at once). The fixed pacing numbers around them (burst per five minutes, hourly, backfill pace, the flood threshold and the chronic-overage rule) are compiled constants listed under **Instance > Configuration > Effective limits**; see [Mailboxes](/guides/mailboxes/#what-gets-synced) for how the budgets behave. The four `sync.*` values also have a companion read view on **Operations > Sync**, which shows each mailbox's backfill progress and fair-use throttle against them and can clear a throttle or restart a backfill.
|
||||
|
||||
The five `retention.*` values are read by the pruning sweeps on every pass, so shortening one takes effect on the next sweep rather than at the next restart. Deletion is permanent and there is no grace period: what already sits outside a shortened window goes on that sweep. The warmup mail window is the one that reaches into customers' mailboxes: the consumer retires each message and the worker holding the mailbox deletes it there, so shortening it empties the warmup folders of the whole instance down to the new window within a few hours. See [data control](/development/data-control/#what-is-kept-and-for-how-long) for what each log holds and what a shorter window costs.
|
||||
The eight `retention.*` values are read by the pruning sweeps on every pass, so shortening one takes effect on the next sweep rather than at the next restart. Deletion is permanent and there is no grace period: what already sits outside a shortened window goes on that sweep. The warmup mail window is the one that reaches into customers' mailboxes: the consumer retires each message and the worker holding the mailbox deletes it there, so shortening it empties the warmup folders of the whole instance down to the new window within a few hours. See [data control](/development/data-control/#what-is-kept-and-for-how-long) for what each log holds and what a shorter window costs.
|
||||
|
||||
An unattended install can seed the whole document before anyone signs in, with `WARMBLY_SETTINGS_BOOTSTRAP` holding the same partial JSON the admin API takes:
|
||||
|
||||
|
||||
@@ -100,17 +100,24 @@ See [Automatic inbox tagging](/guides/inbox-tagging/), [Advisor](/guides/advisor
|
||||
| `retention.form_event_days` | 180 | Form funnel events: views, starts, field-level drop-off |
|
||||
| `retention.audit_log_days` | 90 | The audit trail: actor, IP address, user agent, change payload |
|
||||
| `retention.warmup_mail_days` | 30 | Warmup mail in the mailboxes themselves, and the stored copy of each message's body. Deleted by the platform once older than this, wherever the mailbox files it; a mailbox can set its own window |
|
||||
| `retention.warmup_event_days` | 365 | Per-message warmup records: tokens, receipts, tampering events, spam moves and their attribution, spam reports, and for a linked instance that runs its own mailboxes, the commands Cloud queued for it once they are closed and the warmup mail it reported once retired. The daily sent and received counts behind the analytics are kept. When each mailbox's owner last acted in it (five-minute marks, no message content) is kept 30 days whatever this is set to |
|
||||
| `retention.warmup_event_days` | 365 | Per-message warmup records: tokens, receipts, tampering events, spam moves and their attribution, spam reports, and which messages belong to a warmup thread, and for a linked instance that runs its own mailboxes, the commands Cloud queued for it once they are closed and the warmup mail it reported once retired. The daily sent and received counts behind the analytics are kept. When each mailbox's owner last acted in it (five-minute marks, no message content) is kept 30 days whatever this is set to |
|
||||
| `retention.campaign_log_days` | 0 (kept) | Each campaign's activity feed: failed and deferred sends, pauses and their reasons |
|
||||
| `retention.notification_days` | 0 (kept) | In-app notifications, read or unread. One still waiting to be emailed is kept until it is sent or skipped |
|
||||
| `retention.webhook_delivery_days` | 0 (kept) | Each webhook endpoint's delivery log of settled deliveries, with the payload and the response excerpt. A delivery still being retried is kept until it settles |
|
||||
|
||||
The first three are between 1 and 3,650 days, and they are the settings a retention or privacy policy applies to, because each window is also how long the personal data in that log is held. The warmup mail window starts at 3 days and the warmup records window at 30, the least the engagement legs and the pool health bands need.
|
||||
The event logs take 1 to 3,650 days. Each history feed takes 0, which keeps everything, or 1 to 3,650 days. These are the settings a retention or privacy policy applies to, because each window is also how long the personal data in that log or feed is held; a feed left at 0 holds it until its campaign or workspace is deleted. The warmup mail window starts at 3 days and the warmup records window at 30, the least the engagement legs and the pool health bands need.
|
||||
|
||||
None of them change a number anyone reads. Campaign progress keeps its own summary of opens and clicks that outlives the per-event log, so counts, filters and branching are unaffected by shortening any of these. What gets shorter is what a contact's timeline can show, how far a funnel report reaches, and how far back an admin can audit.
|
||||
|
||||
The history feeds are the same: a campaign's stats and sent mail are not in its activity feed, and an old notification that was never read stops counting toward the unread badge when it goes. A webhook delivery past its window can no longer be redelivered from the log.
|
||||
|
||||
A few bookkeeping tables are trimmed on fixed windows with no setting: worker health samples are kept 7 days, and a send's queued follow-up effects 7 days after they ran, unless that send could still be applied again. The marks the consumer uses to count each open or click once are not pruned by any window. The send record itself (each task and its message, which tracking, threading and campaign stats read), the message map and synced mail have no window and stay until their mailbox, campaign or workspace is deleted.
|
||||
|
||||
<Callout type="warn" title="Shortening a window deletes on the next sweep">
|
||||
There is no grace period and no copy. Take a backup first if you are not sure.
|
||||
</Callout>
|
||||
|
||||
The **minimal retention** preset in the admin panel and in the installer sets the three event logs to 30 days, warmup mail to 7 and warmup records to 30.
|
||||
The **minimal retention** preset in the admin panel and in the installer sets the three event logs to 30 days, warmup mail to 7 and warmup records to 30. The admin panel's preset also sets the three history feeds to 30; an install leaves them at their defaults.
|
||||
|
||||
### Warmup mail in mailboxes
|
||||
|
||||
|
||||
@@ -89,6 +89,10 @@ The local task dispatcher also waits five minutes before revisiting a task whose
|
||||
|
||||
Failed attempts keep their existing retry policy. During a mixed-version rollout, older local dispatchers can still clear successful no-op waits. Verify dispatch fairness only after every service running the local dispatcher has been upgraded.
|
||||
|
||||
Each local dispatcher claims the due tasks it fires, so with several backend replicas every due task runs on one of them. A claim lasts two minutes. A replica that stops mid-task leaves its tasks to the others once that lapses, and a replica that shuts down cleanly hands its claims back at once. A dispatcher only claims as many tasks as it has free slots. During a rollout, replicas still on the previous release do not claim and can run a task a claiming replica already holds, as every replica did before; the task handlers stay idempotent for this. Pending tasks that are claimed still count as effectively due in the dispatch backlog.
|
||||
|
||||
The webhook and HubSpot and Pipedrive outboxes poll again at once while work is waiting, and slow down to every 10 seconds while they are empty. An enqueued webhook still starts delivery at once, from a backend or a consumer: the enqueue sends a Postgres notification, and each backend keeps one direct connection listening for it. Send-result effects are claimed in batches of 25.
|
||||
|
||||
Worker heartbeat totals and up to 20 worker details share one PostgreSQL snapshot and one database observation clock, captured after reading the registered workers. That source's observation can be later than the overall snapshot start; its collection-attempt clock still marks the refresh request start, not measurement time. Null timestamps, timestamps at least five minutes old, and timestamps ahead of that observation remain visible. Future worker details are unknown clock evidence, not proof of a stopped worker: HTTP heartbeat registration uses the database clock, while Redis-mirrored heartbeats retain the worker's timestamp. A future-only aggregate is also unknown; any stale or null heartbeat keeps the aggregate's stale-telemetry condition. Counts and positive warning severity do not change. No clock-skew tolerance is assumed. Expected scopes count all matching workers, measured scopes count the bounded details, and truncation is partial coverage even when the aggregate is complete.
|
||||
|
||||
### Reading a snapshot
|
||||
|
||||
@@ -247,6 +247,7 @@ The [shared authentication reference](/api/authentication/) remains the backend
|
||||
| [`org list`](#org-list) | Lists the workspaces on this instance with their id, owner, and size |
|
||||
| [`org export`](#org-export) | Writes a whole workspace to a portable archive file |
|
||||
| [`org import`](#org-import) | Applies an archive to a workspace on this instance |
|
||||
| [`db load`](#db-load) | Shows what the database is busy with: connections by service, costliest queries, largest tables |
|
||||
|
||||
`warmblyctl --help` lists them, and `warmblyctl <command> --help` prints one command's flags with an example. The [API commands](#the-api-commands) are further down, because they authenticate differently.
|
||||
|
||||
@@ -695,6 +696,22 @@ Every one of these runs `warmblyctl` inside the backend container of a compose i
|
||||
| `make grant-admin EMAIL=... ROLE=...` | `user grant-admin` |
|
||||
| `make revoke-admin EMAIL=...` | `user revoke-admin` |
|
||||
|
||||
## db load
|
||||
|
||||
Shows what the database is busy with. It only reads the statistics views and changes nothing.
|
||||
|
||||
```bash
|
||||
warmblyctl db load
|
||||
warmblyctl db load --limit 30 --json
|
||||
```
|
||||
|
||||
It prints four sections:
|
||||
|
||||
- **Connections** to the whole server, grouped by the service that opened them and their state, against `max_connections`. Postgres's own background processes are listed but not counted, because they have their own slots. Every Go service names its connections `warmbly-<binary>` (`warmbly-backend`, `warmbly-consumer`, `warmbly-warmblyctl`), unless the connection string sets its own `application_name`.
|
||||
- **Longest-running sessions**, with how long each has been in its transaction and what it is waiting on. Query text is left out, because it can hold literal values.
|
||||
- **Costliest statements** by total execution time, read from `pg_stat_statements`, with each statement's `queryid`. Text is shown only for queries, whose constants Postgres replaces with placeholders; other statements such as `ALTER ROLE` can keep literal values, so they show their `queryid` alone. When the extension is not installed, the section says how to enable it.
|
||||
- **Largest tables** with live and dead rows, sequential scans and the last autovacuum.
|
||||
|
||||
## See also
|
||||
|
||||
- [First run](/development/first-run/) for claiming a fresh instance and provisioning the owner unattended
|
||||
|
||||
@@ -71,7 +71,7 @@ You need at least one active mailbox and a contact list. Warm new mailboxes befo
|
||||
|
||||
## Shared workspace access
|
||||
|
||||
Campaigns belong to the workspace. Members with **View campaigns** can read campaign details, steps and activity logs regardless of who created them. **Manage campaigns** allows members to edit settings, create or edit steps and delete steps. Campaign overview metrics require **View analytics**. See [Team and roles](/guides/team-roles/) for permission details.
|
||||
Campaigns belong to the workspace. Members with **View campaigns** can read campaign details, steps and activity logs regardless of who created them. **Manage campaigns** allows members to edit settings, create or edit steps and delete steps. Campaign overview metrics require **View analytics**. See [Team and roles](/guides/team-roles/) for permission details. A campaign's activity log keeps its entries unless the instance sets a window (`retention.campaign_log_days` on a self-hosted instance); its stats and sent mail are kept separately and are unaffected.
|
||||
|
||||
Select the workspace that owns the campaign before opening it. Creating a campaign does not grant access to it from a different workspace.
|
||||
|
||||
|
||||
@@ -45,6 +45,8 @@ The bell in the dashboard chrome shows your unread count. Every time you open it
|
||||
|
||||
**Feeds are per user**, not shared across the workspace, so two teammates see different things depending on what they own and what they enabled.
|
||||
|
||||
Notifications are kept, read or not, unless the instance sets a window, after which an older one leaves the feed and the bell count. One still waiting to be emailed is kept until it is sent. A self-hosted instance sets this window with `retention.notification_days` (see [data control](/development/data-control/#event-history)).
|
||||
|
||||
The feed floats above the dashboard instead of being clipped by the header or page. It stays within the screen on narrow displays, with the list scrolling while its filters and settings link remain accessible. Press outside it, press Escape, or open another dashboard menu to close it.
|
||||
|
||||
<Callout type="info" title="Realtime by default">
|
||||
|
||||
@@ -130,6 +130,8 @@ Every delivery attempt is logged. Open an endpoint in Settings -> Webhooks and g
|
||||
|
||||
You can also query deliveries across all endpoints with `GET /webhooks/deliveries`, or scope it to one endpoint with `GET /webhooks/{id}/deliveries`. Both support filtering by status and event type, and return opaque cursor pagination.
|
||||
|
||||
A settled delivery stays in the log unless the instance sets a window, measured from its last attempt; one past that window can no longer be redelivered. A delivery still being retried stays until it settles. A self-hosted instance sets this window with `retention.webhook_delivery_days` (see [data control](/development/data-control/#event-history)).
|
||||
|
||||
If an event was throttled rather than delivered, it appears in `GET /webhooks/throttle-drops` instead of the delivery log.
|
||||
|
||||
</Fold>
|
||||
|
||||
@@ -161,6 +161,9 @@ func instanceSettingsAuditDetails(doc instancesettings.Document) map[string]any
|
||||
"retention_engagement_event_days": doc.Retention.EngagementEventDays,
|
||||
"retention_form_event_days": doc.Retention.FormEventDays,
|
||||
"retention_audit_log_days": doc.Retention.AuditLogDays,
|
||||
"retention_campaign_log_days": doc.Retention.CampaignLogDays,
|
||||
"retention_notification_days": doc.Retention.NotificationDays,
|
||||
"retention_webhook_delivery_days": doc.Retention.WebhookDeliveryDays,
|
||||
"tracking_machine_window_open": doc.Tracking.MachineWindowOpenSeconds,
|
||||
"tracking_machine_window_click": doc.Tracking.MachineWindowClickSeconds,
|
||||
"tracking_machine_window_probable": doc.Tracking.MachineWindowProbableSeconds,
|
||||
|
||||
@@ -64,7 +64,8 @@ func TestArrivalDiagnosticsShutdownBetweenPassesFlushesReturnedWork(t *testing.T
|
||||
attempts += record["pass_attempts"].(float64)
|
||||
cancelled += record["cancelled_pass_attempts"].(float64)
|
||||
}
|
||||
if summaries != 2 || attempts != 2 || cancelled != 0 || stub.backlogCalls != 2 {
|
||||
// Two passes five seconds apart share one backlog reading (arrivalBacklogInterval).
|
||||
if summaries != 2 || attempts != 2 || cancelled != 0 || stub.backlogCalls != 1 {
|
||||
t.Fatalf("shutdown lost returned work or invented a cancelled pass: summaries=%v attempts=%v cancelled=%v backlog=%d", summaries, attempts, cancelled, stub.backlogCalls)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,10 +55,21 @@ func (s *JobsService) runArrivalOutboxPass(ctx context.Context, diagnostics *arr
|
||||
cancel()
|
||||
}
|
||||
|
||||
// arrivalBacklogInterval spaces the queue count; the alert it feeds waits minutes anyway.
|
||||
const arrivalBacklogInterval = 30 * time.Second
|
||||
|
||||
func (s *JobsService) observeArrivalBacklog(ctx context.Context, deliveryErr error, now time.Time, failedSince, lastAlert *time.Time) {
|
||||
backlog := repository.ArrivalBacklog{}
|
||||
known := false
|
||||
if stats, ok := s.ArrivalOutbox.(repository.ArrivalBacklogRepository); ok {
|
||||
if !s.arrivalBacklogAt.IsZero() && now.Sub(s.arrivalBacklogAt) < arrivalBacklogInterval {
|
||||
// Between readings a failure can start the clock but only a reading can stop it.
|
||||
if deliveryErr != nil && failedSince.IsZero() {
|
||||
*failedSince = now
|
||||
}
|
||||
return
|
||||
}
|
||||
s.arrivalBacklogAt = now
|
||||
var err error
|
||||
backlog, err = stats.ArrivalBacklog(ctx)
|
||||
if err != nil {
|
||||
|
||||
@@ -164,3 +164,40 @@ func TestDurableArrivalBacklogAlertsAreAgedAndDeduplicated(t *testing.T) {
|
||||
t.Fatal("operator notice exposed an error or fabricated unavailable counts")
|
||||
}
|
||||
}
|
||||
|
||||
func TestArrivalBacklogIsCountedOncePerIntervalAndFailuresStillAge(t *testing.T) {
|
||||
now := time.Now()
|
||||
outbox := &countedBacklogStub{}
|
||||
ops := &arrivalOperatorStub{}
|
||||
s := &JobsService{ArrivalOutbox: outbox, OpsNotifier: ops}
|
||||
var failed, alerted time.Time
|
||||
for i := range 6 {
|
||||
s.observeArrivalBacklog(t.Context(), nil, now.Add(time.Duration(i)*5*time.Second), &failed, &alerted)
|
||||
}
|
||||
if outbox.reads != 1 {
|
||||
t.Fatalf("queue counted %d times in 25 seconds", outbox.reads)
|
||||
}
|
||||
s.observeArrivalBacklog(t.Context(), nil, now.Add(arrivalBacklogInterval), &failed, &alerted)
|
||||
if outbox.reads != 2 {
|
||||
t.Fatal("the next interval did not count the queue")
|
||||
}
|
||||
// A failure between readings starts the clock; the reading after a minute of it alerts.
|
||||
failing := errors.New("delivery down")
|
||||
start := now.Add(time.Minute)
|
||||
for at := start; !at.After(start.Add(90 * time.Second)); at = at.Add(5 * time.Second) {
|
||||
s.observeArrivalBacklog(t.Context(), failing, at, &failed, &alerted)
|
||||
}
|
||||
if !failed.Equal(start) || ops.calls != 1 {
|
||||
t.Fatalf("failure since %v (want %v), alerts %d", failed, start, ops.calls)
|
||||
}
|
||||
}
|
||||
|
||||
type countedBacklogStub struct {
|
||||
repository.ArrivalOutbox
|
||||
reads int
|
||||
}
|
||||
|
||||
func (s *countedBacklogStub) ArrivalBacklog(context.Context) (repository.ArrivalBacklog, error) {
|
||||
s.reads++
|
||||
return repository.ArrivalBacklog{}, nil
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -14,6 +15,7 @@ import (
|
||||
"github.com/warmbly/warmbly/internal/app/advanced"
|
||||
"github.com/warmbly/warmbly/internal/app/inboxtag"
|
||||
"github.com/warmbly/warmbly/internal/config"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/infrastructure/pubsub"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/observability/arrivaldiag"
|
||||
@@ -23,6 +25,7 @@ import (
|
||||
)
|
||||
|
||||
func (s *JobsService) HandleNewEmail(ctx context.Context, e *models.JobEventNewEmail) error {
|
||||
ctx = withMailboxMemo(ctx)
|
||||
err := s.ingestNewEmail(ctx, e)
|
||||
if errors.Is(err, errWarmupVerification) && s.UniboxRepository != nil {
|
||||
finish := arrivaldiag.Begin(ctx, arrivaldiag.WarmupDefer)
|
||||
@@ -183,7 +186,7 @@ func (s *JobsService) ingestNewEmail(ctx context.Context, e *models.JobEventNewE
|
||||
|
||||
if s.SlackInbox != nil && e.Message.MayBeInbound() {
|
||||
finish = arrivaldiag.Begin(ctx, arrivaldiag.Slack)
|
||||
if account, aerr := s.EmailRepository.GetByID(ctx, e.Message.EmailID); aerr == nil && account != nil && account.OrganizationID != nil {
|
||||
if account, aerr := s.mailbox(ctx, e.Message.EmailID); aerr == nil && account != nil && account.OrganizationID != nil {
|
||||
s.SlackInbox.InboundMessage(ctx, *account.OrganizationID, account, e.Message)
|
||||
}
|
||||
finish()
|
||||
@@ -209,7 +212,7 @@ func (s *JobsService) publishEmailUpdated(ctx context.Context, userID uuid.UUID,
|
||||
// so every teammate's unibox updates live, not just the mailbox owner's.
|
||||
func (s *JobsService) emailInboxEvent(ctx context.Context, userID uuid.UUID, message *models.EmailMessageStoreData) *pubsub.EmailInboxEvent {
|
||||
var orgID string
|
||||
if account, err := s.EmailRepository.GetByID(ctx, message.EmailID); err == nil && account != nil && account.OrganizationID != nil {
|
||||
if account, err := s.mailbox(ctx, message.EmailID); err == nil && account != nil && account.OrganizationID != nil {
|
||||
orgID = account.OrganizationID.String()
|
||||
}
|
||||
return &pubsub.EmailInboxEvent{
|
||||
@@ -754,13 +757,45 @@ func (s *JobsService) recipientAccount(ctx context.Context, accountID uuid.UUID)
|
||||
if s.EmailRepository == nil {
|
||||
return nil
|
||||
}
|
||||
acc, err := s.EmailRepository.GetByID(ctx, accountID)
|
||||
acc, err := s.mailbox(ctx, accountID)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return acc
|
||||
}
|
||||
|
||||
type mailboxMemoKey struct{}
|
||||
|
||||
type mailboxMemo struct {
|
||||
mu sync.Mutex
|
||||
accounts map[uuid.UUID]*models.Email
|
||||
}
|
||||
|
||||
// withMailboxMemo makes one event load each mailbox row once.
|
||||
func withMailboxMemo(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, mailboxMemoKey{}, &mailboxMemo{accounts: map[uuid.UUID]*models.Email{}})
|
||||
}
|
||||
|
||||
// mailbox reads through the event's memo when there is one.
|
||||
func (s *JobsService) mailbox(ctx context.Context, accountID uuid.UUID) (*models.Email, *errx.Error) {
|
||||
memo, _ := ctx.Value(mailboxMemoKey{}).(*mailboxMemo)
|
||||
if memo != nil {
|
||||
memo.mu.Lock()
|
||||
acc, ok := memo.accounts[accountID]
|
||||
memo.mu.Unlock()
|
||||
if ok {
|
||||
return acc, nil
|
||||
}
|
||||
}
|
||||
acc, err := s.EmailRepository.GetByID(ctx, accountID)
|
||||
if err == nil && acc != nil && memo != nil {
|
||||
memo.mu.Lock()
|
||||
memo.accounts[accountID] = acc
|
||||
memo.mu.Unlock()
|
||||
}
|
||||
return acc, err
|
||||
}
|
||||
|
||||
// recipientProviderDomain is a recipient mailbox's connect provider
|
||||
// ("gmail"/"outlook"/"smtp_imap") and email domain for the per-provider
|
||||
// placement dimension. Empty strings when the account is unknown.
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/infrastructure/pubsub"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/repository"
|
||||
)
|
||||
|
||||
// HandleSyncState persists the worker's SYNC_STATE relay and tells the
|
||||
@@ -21,12 +22,7 @@ func (s *JobsService) HandleSyncState(ctx context.Context, e *models.JobEventSyn
|
||||
return nil
|
||||
}
|
||||
|
||||
prev, err := s.EmailSyncStateRepository.Get(ctx, e.EmailID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
recover := func(ctx context.Context) error {
|
||||
recover := func(ctx context.Context, prev *repository.SyncStatePrior) error {
|
||||
if e.State.LastSyncedAt != nil && e.State.Deferred == 0 && e.State.BackfillCursor.GoogleRecovery == nil &&
|
||||
(prev == nil || prev.LastSyncedAt == nil || !models.ValidMailTransportTime(*prev.LastSyncedAt, time.Now()) || e.State.LastSyncedAt.After(*prev.LastSyncedAt)) {
|
||||
return s.resolveTransientMailErrors(ctx, e.EmailID, e.State.LastSyncedAt, e.State.TransportGeneration)
|
||||
@@ -35,11 +31,18 @@ func (s *JobsService) HandleSyncState(ctx context.Context, e *models.JobEventSyn
|
||||
}
|
||||
|
||||
accepted := true
|
||||
var prev *repository.SyncStatePrior
|
||||
var err error
|
||||
if e.WorkerID != nil {
|
||||
accepted, err = s.EmailSyncStateRepository.PutFromWorker(ctx, e.UserID, e.EmailID, *e.WorkerID, e.ReportGeneration, &e.State, recover)
|
||||
accepted, prev, err = s.EmailSyncStateRepository.PutFromWorker(ctx, e.UserID, e.EmailID, *e.WorkerID, e.ReportGeneration, &e.State, recover)
|
||||
} else {
|
||||
// Retained v0.6.72 reports remain supported through the rollback window.
|
||||
err = recover(ctx)
|
||||
stored, getErr := s.EmailSyncStateRepository.Get(ctx, e.EmailID)
|
||||
if getErr != nil {
|
||||
return getErr
|
||||
}
|
||||
prev = repository.PriorOf(stored)
|
||||
err = recover(ctx, prev)
|
||||
if err == nil {
|
||||
err = s.EmailSyncStateRepository.Put(ctx, e.UserID, e.EmailID, &e.State)
|
||||
}
|
||||
|
||||
@@ -36,18 +36,19 @@ func (s *stubSyncStateRepo) Put(_ context.Context, _, _ uuid.UUID, st *models.Sy
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *stubSyncStateRepo) PutFromWorker(ctx context.Context, _, _, workerID, generation uuid.UUID, st *models.SyncState, before func(context.Context) error) (bool, error) {
|
||||
func (s *stubSyncStateRepo) PutFromWorker(ctx context.Context, _, _, workerID, generation uuid.UUID, st *models.SyncState, before func(context.Context, *repository.SyncStatePrior) error) (bool, *repository.SyncStatePrior, error) {
|
||||
s.reportWorker = workerID
|
||||
s.reportGeneration = generation
|
||||
prior := repository.PriorOf(s.saved)
|
||||
if s.reportAccepted {
|
||||
if before != nil {
|
||||
if err := before(ctx); err != nil {
|
||||
return false, err
|
||||
if err := before(ctx, prior); err != nil {
|
||||
return false, nil, err
|
||||
}
|
||||
}
|
||||
s.put = st
|
||||
}
|
||||
return s.reportAccepted, nil
|
||||
return s.reportAccepted, prior, nil
|
||||
}
|
||||
|
||||
type syncStateBus struct {
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -18,6 +20,7 @@ import (
|
||||
"github.com/warmbly/warmbly/internal/infrastructure/codec"
|
||||
"github.com/warmbly/warmbly/internal/infrastructure/eventbus"
|
||||
"github.com/warmbly/warmbly/internal/infrastructure/pubsub"
|
||||
"github.com/warmbly/warmbly/internal/jobrun"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/pkg/geo"
|
||||
"github.com/warmbly/warmbly/internal/pkg/mailclient"
|
||||
@@ -203,35 +206,30 @@ func (tc *TrackingConsumer) sweepPendingClicks(ctx context.Context) {
|
||||
}
|
||||
|
||||
// pruneEngagementLogs deletes opens and clicks older than the retention
|
||||
// window, at start and then daily. The progress-row summary stays, so
|
||||
// nothing a count, filter or branch reads is affected.
|
||||
// window, at start and then daily, on one replica per pass. The progress-row
|
||||
// summary stays, so nothing a count, filter or branch reads is affected.
|
||||
func (tc *TrackingConsumer) pruneEngagementLogs(ctx context.Context) {
|
||||
ticker := time.NewTicker(24 * time.Hour)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
jobrun.Loop(ctx, "engagement_log_prune", 24*time.Hour, true, func(ctx context.Context) error {
|
||||
pctx, cancel := context.WithTimeout(ctx, 5*time.Minute)
|
||||
defer cancel()
|
||||
days := tc.engagementRetentionDays(pctx)
|
||||
var failures []error
|
||||
if tc.opens != nil {
|
||||
if n, err := tc.opens.Cleanup(pctx, days); err != nil {
|
||||
log.Warn().Err(err).Msg("open log prune failed")
|
||||
failures = append(failures, fmt.Errorf("open log prune: %w", err))
|
||||
} else if n > 0 {
|
||||
log.Info().Int64("deleted", n).Msg("open log pruned")
|
||||
}
|
||||
}
|
||||
if tc.linkClicks != nil {
|
||||
if n, err := tc.linkClicks.Cleanup(pctx, days); err != nil {
|
||||
log.Warn().Err(err).Msg("click log prune failed")
|
||||
failures = append(failures, fmt.Errorf("click log prune: %w", err))
|
||||
} else if n > 0 {
|
||||
log.Info().Int64("deleted", n).Msg("click log pruned")
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
return errors.Join(failures...)
|
||||
})
|
||||
}
|
||||
|
||||
// Close is a no-op: the event bus lifecycle is owned by the consumer main,
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package jobs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/repository"
|
||||
)
|
||||
|
||||
type countingEmailRepo struct {
|
||||
repository.EmailRepository
|
||||
reads int
|
||||
}
|
||||
|
||||
func (r *countingEmailRepo) GetByID(_ context.Context, id uuid.UUID) (*models.Email, *errx.Error) {
|
||||
r.reads++
|
||||
return &models.Email{ID: id}, nil
|
||||
}
|
||||
|
||||
func TestMailboxMemoLoadsEachMailboxOncePerEvent(t *testing.T) {
|
||||
repo := &countingEmailRepo{}
|
||||
s := &JobsService{EmailRepository: repo}
|
||||
a, b := uuid.New(), uuid.New()
|
||||
ctx := withMailboxMemo(t.Context())
|
||||
for range 3 {
|
||||
s.recipientAccount(ctx, a)
|
||||
s.emailInboxEvent(ctx, uuid.New(), &models.EmailMessageStoreData{EmailID: a})
|
||||
}
|
||||
s.recipientAccount(ctx, b)
|
||||
if repo.reads != 2 {
|
||||
t.Fatalf("read %d times within one event, want once per mailbox", repo.reads)
|
||||
}
|
||||
s.recipientAccount(t.Context(), a)
|
||||
s.recipientAccount(t.Context(), a)
|
||||
if repo.reads != 4 {
|
||||
t.Fatal("reads outside an event were memoized")
|
||||
}
|
||||
}
|
||||
@@ -133,6 +133,8 @@ type JobsService struct {
|
||||
Evidence advanced.EvidenceRecorder
|
||||
|
||||
eventHandlers map[models.JobEventType]func(ctx context.Context, body any) error
|
||||
// arrivalBacklogAt is when the arrival loop last counted its queue; only that loop touches it.
|
||||
arrivalBacklogAt time.Time
|
||||
}
|
||||
|
||||
func (s *JobsService) Start(ctx context.Context) {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/config"
|
||||
@@ -34,7 +35,9 @@ import (
|
||||
// retention.warmup_event_days once a full pass has completed.
|
||||
|
||||
const (
|
||||
warmupRetentionBatch = 100
|
||||
warmupRetentionBatch = 500
|
||||
// warmupRetentionRunBudget is how long one run keeps taking batches, so a backlog clears in hours, not weeks.
|
||||
warmupRetentionRunBudget = 40 * time.Second
|
||||
// warmupRetentionPassEvery is how often a completed pass is repeated. The
|
||||
// windows are whole days, so nothing is gained by walking the tables
|
||||
// more often than this.
|
||||
@@ -52,13 +55,29 @@ func (s *JobsService) StartWarmupMailRetention(ctx context.Context) {
|
||||
if time.Now().Before(nextPass) {
|
||||
return nil
|
||||
}
|
||||
batchCtx, cancel := context.WithTimeout(ctx, 45*time.Second)
|
||||
batchCtx, cancel := context.WithTimeout(ctx, 55*time.Second)
|
||||
defer cancel()
|
||||
done, err := s.retireWarmupMailBatch(batchCtx)
|
||||
if err != nil || !done {
|
||||
return err
|
||||
started, run := time.Now(), newRetireRun()
|
||||
for {
|
||||
done, err := s.retireWarmupMailBatch(batchCtx, run)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if done {
|
||||
break
|
||||
}
|
||||
if time.Since(started) > warmupRetentionRunBudget {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if err := s.pruneWarmupEvents(batchCtx); err != nil {
|
||||
if run.full {
|
||||
// A mailbox took its whole share this run and may hold more; the next run continues it.
|
||||
return nil
|
||||
}
|
||||
// The record prune gets its own budget, so a long retirement run cannot starve it.
|
||||
pruneCtx, cancelPrune := context.WithTimeout(ctx, 5*time.Minute)
|
||||
defer cancelPrune()
|
||||
if err := s.pruneWarmupEvents(pruneCtx); err != nil {
|
||||
return err
|
||||
}
|
||||
nextPass = time.Now().Add(warmupRetentionPassEvery)
|
||||
@@ -82,13 +101,43 @@ func (s *JobsService) warmupRetentionDays(ctx context.Context) (mail, events int
|
||||
return mail, events
|
||||
}
|
||||
|
||||
// retireRun is what one run has handed each mailbox, so no mailbox gets more than its share a run.
|
||||
type retireRun struct {
|
||||
received, sent map[uuid.UUID]bool
|
||||
// full is set when a mailbox took its whole share, so the pass is not complete.
|
||||
full bool
|
||||
}
|
||||
|
||||
func newRetireRun() *retireRun {
|
||||
return &retireRun{received: map[uuid.UUID]bool{}, sent: map[uuid.UUID]bool{}}
|
||||
}
|
||||
|
||||
// take records a batch against the run and reports whether the listing ran out; a mailbox it skips next is marked by full.
|
||||
func (r *retireRun) take(served map[uuid.UUID]bool, batch []repository.WarmupMailToRetire) bool {
|
||||
for _, m := range batch {
|
||||
served[m.EmailAccountID] = true
|
||||
}
|
||||
if atShare(batch) {
|
||||
r.full = true
|
||||
}
|
||||
return len(batch) < warmupRetentionBatch
|
||||
}
|
||||
|
||||
func keys(m map[uuid.UUID]bool) []uuid.UUID {
|
||||
out := make([]uuid.UUID, 0, len(m))
|
||||
for id := range m {
|
||||
out = append(out, id)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// retireWarmupMailBatch offers one batch of received copies and one of sent
|
||||
// copies to the workers. It reports done when both listings came back short,
|
||||
// which means nothing older is waiting.
|
||||
func (s *JobsService) retireWarmupMailBatch(ctx context.Context) (bool, error) {
|
||||
// copies to the workers, skipping mailboxes this run already served. It
|
||||
// reports done when both listings came back drained.
|
||||
func (s *JobsService) retireWarmupMailBatch(ctx context.Context, run *retireRun) (bool, error) {
|
||||
days, _ := s.warmupRetentionDays(ctx)
|
||||
|
||||
received, err := s.WarmupRepo.ListWarmupMailToRetire(ctx, days, warmupRetentionBatch)
|
||||
received, err := s.WarmupRepo.ListWarmupMailToRetire(ctx, days, warmupRetentionBatch, keys(run.received))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
@@ -104,7 +153,7 @@ func (s *JobsService) retireWarmupMailBatch(ctx context.Context) (bool, error) {
|
||||
}
|
||||
}
|
||||
|
||||
sent, err := s.WarmupRepo.ListWarmupSentCopiesToRetire(ctx, days, warmupRetentionBatch)
|
||||
sent, err := s.WarmupRepo.ListWarmupSentCopiesToRetire(ctx, days, warmupRetentionBatch, keys(run.sent))
|
||||
if err != nil {
|
||||
return false, errors.Join(append(failures, err)...)
|
||||
}
|
||||
@@ -124,7 +173,24 @@ func (s *JobsService) retireWarmupMailBatch(ctx context.Context) (bool, error) {
|
||||
// the pass is not complete until every row of the batch went.
|
||||
return false, errors.Join(failures...)
|
||||
}
|
||||
return len(received) < warmupRetentionBatch && len(sent) < warmupRetentionBatch, nil
|
||||
doneReceived, doneSent := run.take(run.received, received), run.take(run.sent, sent)
|
||||
return doneReceived && doneSent, nil
|
||||
}
|
||||
|
||||
// drained is a listing that came back short with no mailbox at its per-mailbox share, so nothing older is waiting.
|
||||
func drained(batch []repository.WarmupMailToRetire) bool {
|
||||
return len(batch) < warmupRetentionBatch && !atShare(batch)
|
||||
}
|
||||
|
||||
// atShare reports a mailbox that took its whole per-mailbox share and may hold more.
|
||||
func atShare(batch []repository.WarmupMailToRetire) bool {
|
||||
per := map[uuid.UUID]int{}
|
||||
for _, m := range batch {
|
||||
if per[m.EmailAccountID]++; per[m.EmailAccountID] >= repository.WarmupRetirePerMailbox {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// publishWarmupDelete sends the delete for one message to the worker holding
|
||||
@@ -153,9 +219,9 @@ func (s *JobsService) publishWarmupDelete(ctx context.Context, m *repository.War
|
||||
// window. Runs after a complete retention pass, so a record is only ever
|
||||
// pruned once the mail it describes has been retired.
|
||||
func (s *JobsService) pruneWarmupEvents(ctx context.Context) error {
|
||||
_, days := s.warmupRetentionDays(ctx)
|
||||
mailDays, days := s.warmupRetentionDays(ctx)
|
||||
before := time.Now().AddDate(0, 0, -days)
|
||||
pruned, err := s.WarmupRepo.PruneWarmupEventsBefore(ctx, before)
|
||||
pruned, err := s.WarmupRepo.PruneWarmupEventsBefore(ctx, before, mailDays)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -334,11 +334,11 @@ type retentionRepo struct {
|
||||
pruned *time.Time
|
||||
}
|
||||
|
||||
func (r *retentionRepo) ListWarmupMailToRetire(context.Context, int, int) ([]repository.WarmupMailToRetire, error) {
|
||||
func (r *retentionRepo) ListWarmupMailToRetire(context.Context, int, int, []uuid.UUID) ([]repository.WarmupMailToRetire, error) {
|
||||
return r.received, nil
|
||||
}
|
||||
|
||||
func (r *retentionRepo) ListWarmupSentCopiesToRetire(context.Context, int, int) ([]repository.WarmupMailToRetire, error) {
|
||||
func (r *retentionRepo) ListWarmupSentCopiesToRetire(context.Context, int, int, []uuid.UUID) ([]repository.WarmupMailToRetire, error) {
|
||||
return r.sent, nil
|
||||
}
|
||||
|
||||
@@ -352,7 +352,7 @@ func (r *retentionRepo) RetireWarmupSentCopy(_ context.Context, token uuid.UUID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *retentionRepo) PruneWarmupEventsBefore(_ context.Context, before time.Time) (int64, error) {
|
||||
func (r *retentionRepo) PruneWarmupEventsBefore(_ context.Context, before time.Time, _ int) (int64, error) {
|
||||
r.pruned = &before
|
||||
return 0, nil
|
||||
}
|
||||
@@ -374,7 +374,7 @@ func TestRetireWarmupMailBatchPublishesAndRetires(t *testing.T) {
|
||||
pub := &retentionPublisher{}
|
||||
s := &JobsService{WarmupRepo: repo, Publisher: pub}
|
||||
|
||||
done, err := s.retireWarmupMailBatch(context.Background())
|
||||
done, err := s.retireWarmupMailBatch(context.Background(), newRetireRun())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -412,3 +412,34 @@ func TestPruneWarmupEventsUsesTheInstanceWindow(t *testing.T) {
|
||||
t.Fatalf("pruned before %v, want about %v", repo.pruned, want)
|
||||
}
|
||||
}
|
||||
|
||||
// A mailbox at its per-mailbox share may hold more, so the pass is not done even when the batch is short.
|
||||
func TestRetirementPassWaitsForAMailboxAtItsShare(t *testing.T) {
|
||||
busy := uuid.New()
|
||||
var batch []repository.WarmupMailToRetire
|
||||
for range repository.WarmupRetirePerMailbox {
|
||||
batch = append(batch, repository.WarmupMailToRetire{EmailAccountID: busy})
|
||||
}
|
||||
if drained(batch) {
|
||||
t.Fatal("a mailbox that filled its share was treated as caught up")
|
||||
}
|
||||
if !drained(batch[:repository.WarmupRetirePerMailbox-1]) {
|
||||
t.Fatal("a short batch below every share must complete the pass")
|
||||
}
|
||||
}
|
||||
|
||||
// A mailbox that took its whole share leaves the pass open, so the event prune waits for its backlog.
|
||||
func TestRetireRunKeepsThePassOpenForAMailboxAtItsShare(t *testing.T) {
|
||||
busy := uuid.New()
|
||||
var batch []repository.WarmupMailToRetire
|
||||
for range repository.WarmupRetirePerMailbox {
|
||||
batch = append(batch, repository.WarmupMailToRetire{EmailAccountID: busy})
|
||||
}
|
||||
run := newRetireRun()
|
||||
if !run.take(run.received, batch) {
|
||||
t.Fatal("a short listing should end the run's batches")
|
||||
}
|
||||
if !run.full || !run.received[busy] {
|
||||
t.Fatalf("the busy mailbox was not held for the next run: %+v", run)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -226,7 +226,9 @@ func TestLiveTrackingDomainSweep(t *testing.T) {
|
||||
t.Fatalf("seed: %v", err)
|
||||
}
|
||||
|
||||
svc.runTrackingDomainSweep(ctx, time.Hour)
|
||||
if err := svc.runTrackingDomainSweep(ctx, time.Hour); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if domain, verified := f.stored(t); domain != "www.wikipedia.org" || !verified {
|
||||
t.Fatalf("the sweep should have verified it without anybody asking: %q verified=%v", domain, verified)
|
||||
@@ -241,7 +243,9 @@ func TestLiveTrackingDomainSweep(t *testing.T) {
|
||||
t.Fatalf("seed: %v", err)
|
||||
}
|
||||
|
||||
svc.runTrackingDomainSweep(ctx, time.Hour)
|
||||
if err := svc.runTrackingDomainSweep(ctx, time.Hour); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, verified := f.stored(t); verified {
|
||||
t.Fatalf("a domain pointing somewhere else must not stay verified")
|
||||
@@ -264,7 +268,9 @@ func TestLiveTrackingDomainSweepDoesNothingWithoutATarget(t *testing.T) {
|
||||
t.Fatalf("seed: %v", err)
|
||||
}
|
||||
|
||||
svc.runTrackingDomainSweep(ctx, time.Hour)
|
||||
if err := svc.runTrackingDomainSweep(ctx, time.Hour); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, verified := f.stored(t); !verified {
|
||||
t.Fatalf("the sweep must leave everything alone when it has no target")
|
||||
|
||||
@@ -2,12 +2,14 @@ package email
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/config"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/jobrun"
|
||||
"github.com/warmbly/warmbly/internal/pkg/trackdns"
|
||||
)
|
||||
|
||||
@@ -29,39 +31,30 @@ func (s *emailService) StartTrackingDomainSweep(ctx context.Context, interval, s
|
||||
return
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
sweepCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
|
||||
s.runTrackingDomainSweep(sweepCtx, staleAfter)
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
jobrun.Loop(ctx, "tracking_domain_sweep", interval, false, func(ctx context.Context) error {
|
||||
sweepCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
|
||||
defer cancel()
|
||||
return s.runTrackingDomainSweep(sweepCtx, staleAfter)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *emailService) runTrackingDomainSweep(ctx context.Context, staleAfter time.Duration) {
|
||||
func (s *emailService) runTrackingDomainSweep(ctx context.Context, staleAfter time.Duration) error {
|
||||
target := config.TrackingHostname()
|
||||
if target == "" {
|
||||
// Nothing to compare against. Unverifying every mailbox because this
|
||||
// install has no tracking host would be the worst of both worlds.
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
due, xerr := s.emailRepository.ListTrackingDomainCheckDue(ctx, time.Now().Add(-staleAfter), trackingDomainSweepBatch)
|
||||
if xerr != nil {
|
||||
log.Warn().Str("error", xerr.Error()).Msg("tracking-domain sweep: failed to list due mailboxes")
|
||||
return
|
||||
return fmt.Errorf("tracking-domain sweep: list due mailboxes: %s", xerr.Error())
|
||||
}
|
||||
|
||||
var verified, revoked int
|
||||
var verified, revoked, failed int
|
||||
for _, t := range due {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
break
|
||||
}
|
||||
|
||||
lookupCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
@@ -85,6 +78,7 @@ func (s *emailService) runTrackingDomainSweep(ctx context.Context, staleAfter ti
|
||||
continue
|
||||
}
|
||||
log.Warn().Str("domain", t.Domain).Str("error", err.Error()).Msg("tracking-domain sweep: failed to persist")
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
if !t.Verified {
|
||||
@@ -93,6 +87,7 @@ func (s *emailService) runTrackingDomainSweep(ctx context.Context, staleAfter ti
|
||||
case t.Verified:
|
||||
if err := s.emailRepository.SetTrackingDomainVerified(ctx, t.ID, false, nil); err != nil {
|
||||
log.Warn().Str("domain", t.Domain).Str("error", err.Error()).Msg("tracking-domain sweep: failed to persist")
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
revoked++
|
||||
@@ -103,4 +98,8 @@ func (s *emailService) runTrackingDomainSweep(ctx context.Context, staleAfter ti
|
||||
if verified > 0 || revoked > 0 {
|
||||
log.Info().Int("checked", len(due)).Int("newly_verified", verified).Int("revoked", revoked).Msg("tracking-domain sweep completed")
|
||||
}
|
||||
if failed > 0 {
|
||||
return fmt.Errorf("tracking-domain sweep: %d of %d verdicts could not be saved", failed, len(due))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -12,12 +12,15 @@ import (
|
||||
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/pkg/idlepoll"
|
||||
)
|
||||
|
||||
// Jobs are claimed one at a time under a lease longer than a job may run, so
|
||||
// a lease never lapses while its job is still working.
|
||||
// a lease never lapses while its job is still working. An empty outbox is
|
||||
// polled less often, up to drainIdleMax.
|
||||
const (
|
||||
drainEvery = 2 * time.Second
|
||||
drainIdleMax = 10 * time.Second
|
||||
drainPerTick = 50
|
||||
jobTimeout = 2 * time.Minute
|
||||
drainLease = jobTimeout + time.Minute
|
||||
@@ -29,7 +32,8 @@ var retryDelays = []time.Duration{time.Minute, 5 * time.Minute, 30 * time.Minute
|
||||
|
||||
// RunDrainer works the outbox until ctx ends. Safe to run in several processes.
|
||||
func (s *Service) RunDrainer(ctx context.Context) {
|
||||
t := time.NewTicker(drainEvery)
|
||||
pace := idlepoll.Pace{Min: drainEvery, Max: drainIdleMax}
|
||||
t := time.NewTimer(drainEvery)
|
||||
defer t.Stop()
|
||||
purge := time.NewTicker(time.Hour)
|
||||
defer purge.Stop()
|
||||
@@ -40,7 +44,8 @@ func (s *Service) RunDrainer(ctx context.Context) {
|
||||
case <-purge.C:
|
||||
_ = s.d.Repo.PurgeJobs(ctx)
|
||||
case <-t.C:
|
||||
for n := 0; n < drainPerTick && ctx.Err() == nil; n++ {
|
||||
ran := 0
|
||||
for ran < drainPerTick && ctx.Err() == nil {
|
||||
jobs, err := s.d.Repo.ClaimJobs(ctx, provider, 1, drainLease)
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Msg("hubspot: claim jobs")
|
||||
@@ -50,7 +55,9 @@ func (s *Service) RunDrainer(ctx context.Context) {
|
||||
break
|
||||
}
|
||||
s.runJob(ctx, &jobs[0])
|
||||
ran++
|
||||
}
|
||||
t.Reset(pace.Next(ran, ran >= drainPerTick))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,6 +75,12 @@ type Retention struct {
|
||||
// receipts, tampering and spam reports) are kept. The daily warmup
|
||||
// statistics behind the analytics are separate and never pruned.
|
||||
WarmupEventDays int `json:"warmup_event_days"`
|
||||
// CampaignLogDays is how long a campaign's activity feed keeps an entry; 0 keeps every entry.
|
||||
CampaignLogDays int `json:"campaign_log_days"`
|
||||
// NotificationDays is how long in-app notifications are kept, read or not; 0 keeps them all.
|
||||
NotificationDays int `json:"notification_days"`
|
||||
// WebhookDeliveryDays is how long a settled webhook delivery stays in its endpoint's log; 0 keeps them all.
|
||||
WebhookDeliveryDays int `json:"webhook_delivery_days"`
|
||||
}
|
||||
|
||||
// Tracking holds the engagement-classification windows. Zero means "compiled
|
||||
@@ -346,6 +352,9 @@ func DefaultRetention() Retention {
|
||||
AuditLogDays: config.AuditLogRetentionDaysDefault,
|
||||
WarmupMailDays: config.WarmupMailRetentionDaysDefault,
|
||||
WarmupEventDays: config.WarmupEventRetentionDaysDefault,
|
||||
CampaignLogDays: config.CampaignLogRetentionDaysDefault,
|
||||
NotificationDays: config.NotificationRetentionDaysDefault,
|
||||
WebhookDeliveryDays: config.WebhookDeliveryRetentionDaysDefault,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -374,6 +383,16 @@ func (r *Retention) Normalize() {
|
||||
// the thirty-day health bands that read them.
|
||||
r.WarmupMailDays = clamp(r.WarmupMailDays, config.WarmupMailRetentionDaysDefault, config.WarmupMailRetentionDaysMin)
|
||||
r.WarmupEventDays = clamp(r.WarmupEventDays, config.WarmupEventRetentionDaysDefault, config.WarmupEventRetentionDaysMin)
|
||||
// The feed windows treat 0 as keep everything, which is also their default.
|
||||
optional := func(v int) int {
|
||||
if v <= 0 {
|
||||
return 0
|
||||
}
|
||||
return clamp(v, 0, config.RetentionDaysMin)
|
||||
}
|
||||
r.CampaignLogDays = optional(r.CampaignLogDays)
|
||||
r.NotificationDays = optional(r.NotificationDays)
|
||||
r.WebhookDeliveryDays = optional(r.WebhookDeliveryDays)
|
||||
}
|
||||
|
||||
// Normalize clamps a document into its accepted range. It is applied on read
|
||||
@@ -463,6 +482,9 @@ type Patch struct {
|
||||
AuditLogDays *int `json:"audit_log_days"`
|
||||
WarmupMailDays *int `json:"warmup_mail_days"`
|
||||
WarmupEventDays *int `json:"warmup_event_days"`
|
||||
CampaignLogDays *int `json:"campaign_log_days"`
|
||||
NotificationDays *int `json:"notification_days"`
|
||||
WebhookDeliveryDays *int `json:"webhook_delivery_days"`
|
||||
} `json:"retention"`
|
||||
Tracking *struct {
|
||||
MachineWindowOpenSeconds *int `json:"machine_window_open_seconds"`
|
||||
@@ -541,6 +563,15 @@ func (p Patch) Apply(doc Document) Document {
|
||||
if p.Retention.WarmupEventDays != nil {
|
||||
doc.Retention.WarmupEventDays = *p.Retention.WarmupEventDays
|
||||
}
|
||||
if p.Retention.CampaignLogDays != nil {
|
||||
doc.Retention.CampaignLogDays = *p.Retention.CampaignLogDays
|
||||
}
|
||||
if p.Retention.NotificationDays != nil {
|
||||
doc.Retention.NotificationDays = *p.Retention.NotificationDays
|
||||
}
|
||||
if p.Retention.WebhookDeliveryDays != nil {
|
||||
doc.Retention.WebhookDeliveryDays = *p.Retention.WebhookDeliveryDays
|
||||
}
|
||||
}
|
||||
if p.Tracking != nil {
|
||||
if p.Tracking.MachineWindowOpenSeconds != nil {
|
||||
|
||||
@@ -831,7 +831,7 @@ var Tables = []Table{
|
||||
Scope: `email_account_id IN ` + orgMailboxes + ` AND task_type <> 'placement'`,
|
||||
Owner: `email_account_id IN ` + orgMailboxes,
|
||||
// The handle belongs to the source instance's queue.
|
||||
ResetOnImport: []string{"cloud_task_name", "send_executor_nonce", "send_executor_worker", "send_executor_started_at", "send_executor_result", "dispatch_retry_at", "dispatch_failure_since", "dispatch_failure_at"},
|
||||
ResetOnImport: []string{"cloud_task_name", "send_executor_nonce", "send_executor_worker", "send_executor_started_at", "send_executor_result", "dispatch_retry_at", "dispatch_failure_since", "dispatch_failure_at", "dispatch_claimed_until"},
|
||||
},
|
||||
{
|
||||
Name: "outbound_attempts", Group: models.OrgDataGroupSending,
|
||||
|
||||
@@ -12,12 +12,15 @@ import (
|
||||
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/pkg/idlepoll"
|
||||
)
|
||||
|
||||
// Jobs are claimed one at a time under a lease longer than a job may run, so
|
||||
// a lease never lapses while its job is still working.
|
||||
// a lease never lapses while its job is still working. An empty outbox is
|
||||
// polled less often, up to drainIdleMax.
|
||||
const (
|
||||
drainEvery = 2 * time.Second
|
||||
drainIdleMax = 10 * time.Second
|
||||
drainPerTick = 50
|
||||
jobTimeout = 2 * time.Minute
|
||||
drainLease = jobTimeout + time.Minute
|
||||
@@ -30,14 +33,16 @@ var retryDelays = []time.Duration{time.Minute, 5 * time.Minute, 30 * time.Minute
|
||||
// RunDrainer works the Pipedrive outbox until ctx ends. Safe to run in
|
||||
// several processes.
|
||||
func (s *Service) RunDrainer(ctx context.Context) {
|
||||
t := time.NewTicker(drainEvery)
|
||||
pace := idlepoll.Pace{Min: drainEvery, Max: drainIdleMax}
|
||||
t := time.NewTimer(drainEvery)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
for n := 0; n < drainPerTick && ctx.Err() == nil; n++ {
|
||||
ran := 0
|
||||
for ran < drainPerTick && ctx.Err() == nil {
|
||||
jobs, err := s.d.Repo.ClaimJobs(ctx, provider, 1, drainLease)
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Msg("pipedrive: claim jobs")
|
||||
@@ -47,7 +52,9 @@ func (s *Service) RunDrainer(ctx context.Context) {
|
||||
break
|
||||
}
|
||||
s.runJob(ctx, &jobs[0])
|
||||
ran++
|
||||
}
|
||||
t.Reset(pace.Next(ran, ran >= drainPerTick))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/jobrun"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/repository"
|
||||
)
|
||||
@@ -490,21 +491,12 @@ func (s *service) runOrgSyncPass(ctx context.Context, orgID uuid.UUID) {
|
||||
}
|
||||
}
|
||||
|
||||
// StartCampaignSegmentSync sweeps linked campaigns every interval on one replica per pass, and once on boot so links catch up promptly.
|
||||
func (s *service) StartCampaignSegmentSync(ctx context.Context, interval time.Duration) {
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
// Sweep once on boot so links catch up promptly after a restart.
|
||||
s.sweepLinkedCampaigns(ctx)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
s.sweepLinkedCampaigns(ctx)
|
||||
}
|
||||
}
|
||||
jobrun.Loop(ctx, "campaign_segment_sync", interval, true, func(ctx context.Context) error {
|
||||
s.sweepLinkedCampaigns(ctx)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *service) sweepLinkedCampaigns(ctx context.Context) {
|
||||
|
||||
@@ -2,12 +2,15 @@ package unibox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/warmbly/warmbly/internal/config"
|
||||
"github.com/warmbly/warmbly/internal/infrastructure/storage"
|
||||
"github.com/warmbly/warmbly/internal/pkg/mailhtml"
|
||||
"github.com/warmbly/warmbly/internal/repository"
|
||||
)
|
||||
|
||||
// Backfill pacing. A pass is one query plus one object-storage read per row, so
|
||||
@@ -16,22 +19,43 @@ import (
|
||||
const (
|
||||
bodyBackfillBatch = 100
|
||||
bodyBackfillInterval = 30 * time.Second
|
||||
// bodyBackfillRetries is how many ticks one message is retried before the sweep moves past it.
|
||||
bodyBackfillRetries = 3
|
||||
)
|
||||
|
||||
// StartBodyTextBackfill fills in the searchable text of messages synced before
|
||||
// bodies were indexed, so unibox search covers the whole archive rather than
|
||||
// only mail that arrives from now on.
|
||||
//
|
||||
// The sweep walks the table once per process: it pages by id, and stops for
|
||||
// good when a pass turns up no rows left to visit. Rows whose stored body
|
||||
// really is empty stay at body_text = ” and are simply re-visited after the
|
||||
// next restart, which is cheaper than inventing a "tried and failed" marker.
|
||||
// The sweep walks the table once per instance: it pages by id, stores its
|
||||
// place after every page, and records itself done when a page comes back
|
||||
// empty, so a restart resumes rather than re-reading rows whose stored body
|
||||
// really is empty. New mail is written with its text, so finishing leaves
|
||||
// nothing behind.
|
||||
func (s *uniboxService) StartBodyTextBackfill(ctx context.Context) {
|
||||
progress, err := s.uniboxRepository.BodyBackfillProgress(ctx)
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Msg("unibox body backfill: progress unreadable, starting over")
|
||||
}
|
||||
if progress.Done {
|
||||
return
|
||||
}
|
||||
ticker := time.NewTicker(bodyBackfillInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
var cursor uuid.UUID
|
||||
cursor := progress.After
|
||||
var filled int
|
||||
var stuck uuid.UUID
|
||||
var tries int
|
||||
// retry reports whether a failed message is tried again next tick, so the saved place never passes it.
|
||||
retry := func(id uuid.UUID, err error) bool {
|
||||
if id != stuck {
|
||||
stuck, tries = id, 0
|
||||
}
|
||||
tries++
|
||||
log.Warn().Err(err).Str("message_id", id.String()).Int("attempt", tries).Msg("unibox body backfill: message failed")
|
||||
return tries < bodyBackfillRetries
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
@@ -45,6 +69,9 @@ func (s *uniboxService) StartBodyTextBackfill(ctx context.Context) {
|
||||
continue
|
||||
}
|
||||
if len(targets) == 0 {
|
||||
if serr := s.uniboxRepository.SaveBodyBackfillProgress(ctx, repository.UniboxBodyBackfill{After: cursor, Done: true}); serr != nil {
|
||||
log.Warn().Err(serr).Msg("unibox body backfill: could not record completion")
|
||||
}
|
||||
if filled > 0 {
|
||||
log.Info().Int("messages", filled).Msg("unibox body backfill: complete")
|
||||
}
|
||||
@@ -52,22 +79,27 @@ func (s *uniboxService) StartBodyTextBackfill(ctx context.Context) {
|
||||
}
|
||||
|
||||
for _, t := range targets {
|
||||
cursor = t.ID
|
||||
body, gerr := s.GetBody(ctx, t.UserID, t.EmailID, t.ID)
|
||||
if gerr != nil {
|
||||
// A missing blob is expected here: fixtures and mail synced
|
||||
// before body storage existed have no object to read.
|
||||
continue
|
||||
// A missing blob is expected here: fixtures and mail synced before body storage existed have no object to read.
|
||||
if gerr != nil && !errors.Is(gerr, storage.ErrNotFound) && retry(t.ID, gerr) {
|
||||
break
|
||||
}
|
||||
text := mailhtml.SearchText(string(body.PlainText), string(body.HTMLBody), config.MaxSearchBodyText)
|
||||
if text == "" {
|
||||
continue
|
||||
if gerr == nil {
|
||||
text := mailhtml.SearchText(string(body.PlainText), string(body.HTMLBody), config.MaxSearchBodyText)
|
||||
if text != "" {
|
||||
if serr := s.uniboxRepository.SetBodyText(ctx, t.ID, text); serr != nil {
|
||||
if retry(t.ID, serr) {
|
||||
break
|
||||
}
|
||||
} else {
|
||||
filled++
|
||||
}
|
||||
}
|
||||
}
|
||||
if serr := s.uniboxRepository.SetBodyText(ctx, t.ID, text); serr != nil {
|
||||
log.Warn().Err(serr).Str("message_id", t.ID.String()).Msg("unibox body backfill: write failed")
|
||||
continue
|
||||
}
|
||||
filled++
|
||||
cursor = t.ID
|
||||
}
|
||||
if serr := s.uniboxRepository.SaveBodyBackfillProgress(ctx, repository.UniboxBodyBackfill{After: cursor}); serr != nil {
|
||||
log.Warn().Err(serr).Msg("unibox body backfill: could not record progress")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/repository"
|
||||
)
|
||||
|
||||
func TestLiveDeliveryWorkerWakesOnANotificationFromAnotherProcess(t *testing.T) {
|
||||
dsn := os.Getenv("WARMBLY_TEST_DB")
|
||||
if dsn == "" {
|
||||
t.Skip("WARMBLY_TEST_DB not set")
|
||||
}
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
w := NewDeliveryWorker(nil, DeliveryWorkerOptions{})
|
||||
connect := func(ctx context.Context) (*pgx.Conn, error) { return pgx.Connect(ctx, dsn) }
|
||||
go w.Listen(ctx, connect)
|
||||
|
||||
wait := func(what string) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-w.wake:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("no wake for %s", what)
|
||||
}
|
||||
}
|
||||
// The listener wakes once on connecting, for anything enqueued before LISTEN took effect.
|
||||
wait("the connected listener")
|
||||
|
||||
other, err := pgx.Connect(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer other.Close(context.Background())
|
||||
if _, err := other.Exec(ctx, `SELECT pg_notify($1, '')`, repository.WebhookDeliveryChannel); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wait("a notification sent on another connection")
|
||||
}
|
||||
@@ -21,11 +21,13 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/config"
|
||||
"github.com/warmbly/warmbly/internal/infrastructure/cache"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/pkg/idlepoll"
|
||||
"github.com/warmbly/warmbly/internal/pkg/safehttp"
|
||||
"github.com/warmbly/warmbly/internal/pkg/whdomain"
|
||||
"github.com/warmbly/warmbly/internal/repository"
|
||||
@@ -650,6 +652,7 @@ type DeliveryWorker struct {
|
||||
reapEvery time.Duration
|
||||
autoDisableAfter time.Duration
|
||||
lastReap time.Time
|
||||
wake chan struct{}
|
||||
}
|
||||
|
||||
// DeliveryWorkerOptions configures the worker. Sensible defaults are
|
||||
@@ -710,27 +713,84 @@ func NewDeliveryWorker(repo repository.WebhookRepository, opts DeliveryWorkerOpt
|
||||
leaseTimeout: opts.LeaseTimeout,
|
||||
reapEvery: time.Minute,
|
||||
autoDisableAfter: opts.AutoDisableAfter,
|
||||
wake: make(chan struct{}, 1),
|
||||
}
|
||||
}
|
||||
|
||||
// Run blocks until ctx is cancelled, draining the delivery queue on a
|
||||
// fixed interval. Errors are logged but do not stop the loop — the queue
|
||||
// stays in Postgres, so a crashed dispatcher resumes on restart.
|
||||
// Wake makes Run poll now instead of waiting out an idle interval.
|
||||
func (w *DeliveryWorker) Wake() {
|
||||
select {
|
||||
case w.wake <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// listenRetry is how long Listen waits before reopening a lost connection; the poll covers the gap.
|
||||
const listenRetry = 30 * time.Second
|
||||
|
||||
// Listen wakes the worker on every enqueue from any process, through
|
||||
// LISTEN on a direct connection, until ctx ends.
|
||||
func (w *DeliveryWorker) Listen(ctx context.Context, connect func(context.Context) (*pgx.Conn, error)) {
|
||||
for ctx.Err() == nil {
|
||||
if err := w.listenOnce(ctx, connect); err != nil && ctx.Err() == nil {
|
||||
log.Warn().Err(err).Msg("webhook: delivery listener stopped; polling until it reconnects")
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(listenRetry):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *DeliveryWorker) listenOnce(ctx context.Context, connect func(context.Context) (*pgx.Conn, error)) error {
|
||||
dialCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
conn, err := connect(dialCtx)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
closeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = conn.Close(closeCtx)
|
||||
}()
|
||||
if _, err := conn.Exec(ctx, "LISTEN "+repository.WebhookDeliveryChannel); err != nil {
|
||||
return err
|
||||
}
|
||||
// Anything enqueued before LISTEN took effect is picked up by this poll.
|
||||
w.Wake()
|
||||
for {
|
||||
if _, err := conn.WaitForNotification(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
w.Wake()
|
||||
}
|
||||
}
|
||||
|
||||
// Run blocks until ctx is cancelled, draining the delivery queue: at once
|
||||
// while batches come back full, slowing to 5x the poll interval while empty.
|
||||
// Errors are logged but do not stop the loop — the queue stays in Postgres,
|
||||
// so a crashed dispatcher resumes on restart.
|
||||
func (w *DeliveryWorker) Run(ctx context.Context) {
|
||||
t := time.NewTicker(w.pollEvery)
|
||||
pace := idlepoll.Pace{Min: w.pollEvery, Max: 5 * w.pollEvery}
|
||||
t := time.NewTimer(w.pollEvery)
|
||||
defer t.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-w.wake:
|
||||
n := w.tick(ctx)
|
||||
t.Reset(pace.Next(n, n >= w.batchSize))
|
||||
case <-t.C:
|
||||
w.tick(ctx)
|
||||
n := w.tick(ctx)
|
||||
t.Reset(pace.Next(n, n >= w.batchSize))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *DeliveryWorker) tick(ctx context.Context) {
|
||||
func (w *DeliveryWorker) tick(ctx context.Context) int {
|
||||
// Periodically re-queue deliveries stranded in_flight by a crashed worker.
|
||||
if now := time.Now(); now.Sub(w.lastReap) >= w.reapEvery {
|
||||
w.lastReap = now
|
||||
@@ -744,11 +804,12 @@ func (w *DeliveryWorker) tick(ctx context.Context) {
|
||||
deliveries, err := w.repo.ClaimDueDeliveries(ctx, w.batchSize)
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Msg("Failed to claim webhook deliveries")
|
||||
return
|
||||
return 0
|
||||
}
|
||||
for i := range deliveries {
|
||||
w.deliver(ctx, &deliveries[i])
|
||||
}
|
||||
return len(deliveries)
|
||||
}
|
||||
|
||||
// rateLimited reports whether the endpoint is over its per-second delivery
|
||||
|
||||
@@ -342,6 +342,11 @@ const (
|
||||
// shortens it under Instance settings.
|
||||
AuditLogRetentionDaysDefault = 90
|
||||
|
||||
// The feed windows default to 0, keep everything, so an upgrade deletes no history an operator did not ask to prune.
|
||||
CampaignLogRetentionDaysDefault = 0
|
||||
NotificationRetentionDaysDefault = 0
|
||||
WebhookDeliveryRetentionDaysDefault = 0
|
||||
|
||||
// Ten years is the ceiling every retention window shares. It is not a
|
||||
// recommendation: it is the point past which "keep it" and "keep it
|
||||
// forever" stop differing, and it bounds a typo. One day is the floor, so
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
@@ -68,6 +69,7 @@ func connectionConfigs(endpoint, directEndpoint string) (*pgxpool.Config, *pgx.C
|
||||
return nil, nil, false, errors.New("invalid PRIMARY_DB_DIRECT connection configuration")
|
||||
}
|
||||
direct := directPool.ConnConfig
|
||||
nameConnections(pool.ConnConfig, direct)
|
||||
direct.ConnectTimeout = defaultConnectTimeout
|
||||
direct.RuntimeParams["idle_in_transaction_session_timeout"] = idleInTxnTimeoutMs
|
||||
direct.RuntimeParams["statement_timeout"] = statementTimeoutMs
|
||||
@@ -82,6 +84,16 @@ func connectionConfigs(endpoint, directEndpoint string) (*pgxpool.Config, *pgx.C
|
||||
return pool, direct, pooled, nil
|
||||
}
|
||||
|
||||
// nameConnections labels each connection with the binary that opened it, so pg_stat_activity shows who holds the slots; a DSN's own application_name wins.
|
||||
func nameConnections(configs ...*pgx.ConnConfig) {
|
||||
name := "warmbly-" + filepath.Base(os.Args[0])
|
||||
for _, c := range configs {
|
||||
if c.RuntimeParams["application_name"] == "" {
|
||||
c.RuntimeParams["application_name"] = name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Transaction pooling relies on role defaults, which must apply to every server connection.
|
||||
func verifyPooledTimeouts(ctx context.Context, conn *pgx.Conn) error {
|
||||
var statement, idle int64
|
||||
|
||||
@@ -25,6 +25,19 @@ func TestTransactionConnectionConfiguration(t *testing.T) {
|
||||
if pool.ConnConfig.TLSConfig == nil || session.TLSConfig == nil || pool.ConnConfig.TLSConfig.InsecureSkipVerify || session.TLSConfig.InsecureSkipVerify {
|
||||
t.Fatal("both connection paths must preserve TLS verification")
|
||||
}
|
||||
if name := pool.ConnConfig.RuntimeParams["application_name"]; !strings.HasPrefix(name, "warmbly-") || session.RuntimeParams["application_name"] != name {
|
||||
t.Fatalf("connections are not labelled with the process that opened them: %q", name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplicationNameFromTheDSNWins(t *testing.T) {
|
||||
pool, session, _, err := connectionConfigs("postgres://app:fixture@db.example:5432/app?application_name=ops", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if pool.ConnConfig.RuntimeParams["application_name"] != "ops" || session.RuntimeParams["application_name"] != "ops" {
|
||||
t.Fatal("an operator's application_name was replaced")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirectConnectionDefaults(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
DROP INDEX CONCURRENTLY IF EXISTS public.idx_email_opens_opened_at;
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Alone in its file for CONCURRENTLY. Serves the engagement-log prune, which deletes by age in batches.
|
||||
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_email_opens_opened_at
|
||||
ON public.email_opens (opened_at);
|
||||
+1
@@ -0,0 +1 @@
|
||||
DROP INDEX CONCURRENTLY IF EXISTS public.idx_email_link_clicks_clicked_at;
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Alone in its file for CONCURRENTLY. Serves the engagement-log prune, which deletes by age in batches.
|
||||
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_email_link_clicks_clicked_at
|
||||
ON public.email_link_clicks (clicked_at);
|
||||
+1
@@ -0,0 +1 @@
|
||||
DROP INDEX CONCURRENTLY IF EXISTS public.idx_worker_health_samples_observed;
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
-- Alone in its file for CONCURRENTLY. Serves the capacity view's last-hour window and the sample prune.
|
||||
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_worker_health_samples_observed
|
||||
ON public.worker_health_samples (observed_at);
|
||||
@@ -0,0 +1 @@
|
||||
DROP INDEX CONCURRENTLY IF EXISTS public.idx_campaign_logs_created;
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Alone in its file for CONCURRENTLY. Serves the campaign activity-feed prune.
|
||||
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_campaign_logs_created
|
||||
ON public.campaign_logs (created_at);
|
||||
@@ -0,0 +1 @@
|
||||
DROP INDEX CONCURRENTLY IF EXISTS public.idx_notifications_created;
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Alone in its file for CONCURRENTLY. Serves the notification prune.
|
||||
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notifications_created
|
||||
ON public.notifications (created_at);
|
||||
@@ -0,0 +1 @@
|
||||
DROP INDEX CONCURRENTLY IF EXISTS public.idx_webhook_deliveries_settled;
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Alone in its file for CONCURRENTLY. Serves the delivery-log prune, which only removes settled deliveries.
|
||||
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_webhook_deliveries_settled
|
||||
ON public.webhook_deliveries (updated_at)
|
||||
WHERE status IN ('delivered', 'failed', 'abandoned');
|
||||
+1
@@ -0,0 +1 @@
|
||||
DROP INDEX CONCURRENTLY IF EXISTS public.idx_warmup_received_account_live;
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Alone in its file for CONCURRENTLY. Serves the warmup mail retention listing, which walks each mailbox's unretired receipts.
|
||||
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_warmup_received_account_live
|
||||
ON public.warmup_received (email_account_id, created_at)
|
||||
WHERE retired_at IS NULL;
|
||||
@@ -0,0 +1 @@
|
||||
DROP INDEX CONCURRENTLY IF EXISTS public.idx_warmup_tokens_sender_live;
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Alone in its file for CONCURRENTLY. Serves the warmup mail retention listing for each sender's own copies.
|
||||
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_warmup_tokens_sender_live
|
||||
ON public.warmup_tokens (sender_account_id, created_at)
|
||||
WHERE sent_retired_at IS NULL AND sent_message_id <> '';
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE tasks DROP COLUMN IF EXISTS dispatch_claimed_until;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- A local dispatcher's claim on a due task; other replicas skip it until it lapses.
|
||||
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS dispatch_claimed_until timestamptz;
|
||||
+1
@@ -0,0 +1 @@
|
||||
DROP INDEX CONCURRENTLY IF EXISTS public.idx_crm_sync_jobs_running_lease;
|
||||
@@ -0,0 +1,2 @@
|
||||
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_crm_sync_jobs_running_lease
|
||||
ON public.crm_sync_jobs (provider, locked_until) WHERE status = 'running';
|
||||
+107
-16
@@ -34,12 +34,12 @@ type Store interface {
|
||||
// RequestRun asks the owning loop to run at its next poll. False when no
|
||||
// job by that name has ever registered.
|
||||
RequestRun(ctx context.Context, name string) (bool, error)
|
||||
// TakeRunRequest clears a pending request and reports whether there was one.
|
||||
TakeRunRequest(ctx context.Context, name string) (bool, error)
|
||||
// TakeRunRequests clears the pending requests among names and returns the jobs that had one.
|
||||
TakeRunRequests(ctx context.Context, names []string) ([]string, error)
|
||||
List(ctx context.Context) ([]models.ScheduledJobRun, error)
|
||||
}
|
||||
|
||||
// requestPoll is how often a loop checks for a "run now" request.
|
||||
// requestPoll is how often a process checks for "run now" requests, in one query for all its loops.
|
||||
const requestPoll = 15 * time.Second
|
||||
|
||||
// phaseWindow is how far apart loops that share an interval are pulled. Every
|
||||
@@ -119,8 +119,8 @@ func Loop(ctx context.Context, name string, interval time.Duration, runOnBoot bo
|
||||
|
||||
timer := time.NewTimer(time.Until(due))
|
||||
defer timer.Stop()
|
||||
poll := time.NewTicker(requestPoll)
|
||||
defer poll.Stop()
|
||||
requests := watchRequests(name)
|
||||
defer unwatchRequests(name, requests)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
@@ -144,20 +144,111 @@ func Loop(ctx context.Context, name string, interval time.Duration, runOnBoot bo
|
||||
Run(ctx, name, fn)
|
||||
}
|
||||
timer.Reset(time.Until(due))
|
||||
case <-poll.C:
|
||||
if st == nil {
|
||||
continue
|
||||
}
|
||||
requested, err := st.TakeRunRequest(ctx, name)
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Str("job", name).Msg("jobrun: poll failed")
|
||||
continue
|
||||
}
|
||||
if requested {
|
||||
Run(ctx, name, fn)
|
||||
case <-requests:
|
||||
Run(ctx, name, fn)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
watchMu sync.Mutex
|
||||
watchers = map[string][]chan struct{}{}
|
||||
pollerStop chan struct{}
|
||||
)
|
||||
|
||||
// watchRequests registers a loop for run requests, starting the process's poller with the first one.
|
||||
func watchRequests(name string) chan struct{} {
|
||||
ch := make(chan struct{}, 1)
|
||||
watchMu.Lock()
|
||||
defer watchMu.Unlock()
|
||||
watchers[name] = append(watchers[name], ch)
|
||||
if pollerStop == nil {
|
||||
pollerStop = make(chan struct{})
|
||||
go pollRequests(pollerStop)
|
||||
}
|
||||
return ch
|
||||
}
|
||||
|
||||
// unwatchRequests removes a loop; the poller stops with the last one.
|
||||
func unwatchRequests(name string, ch chan struct{}) {
|
||||
watchMu.Lock()
|
||||
defer watchMu.Unlock()
|
||||
list := watchers[name]
|
||||
for i, c := range list {
|
||||
if c == ch {
|
||||
list = append(list[:i], list[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(list) == 0 {
|
||||
delete(watchers, name)
|
||||
} else {
|
||||
watchers[name] = list
|
||||
}
|
||||
if len(watchers) == 0 && pollerStop != nil {
|
||||
close(pollerStop)
|
||||
pollerStop = nil
|
||||
}
|
||||
}
|
||||
|
||||
// pollRequests takes every pending request for this process's loops in one query per poll.
|
||||
func pollRequests(stop chan struct{}) {
|
||||
ticker := time.NewTicker(requestPoll)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
case <-ticker.C:
|
||||
takeRequests(context.Background())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func takeRequests(ctx context.Context) {
|
||||
st, _ := current()
|
||||
if st == nil {
|
||||
return
|
||||
}
|
||||
watchMu.Lock()
|
||||
names := make([]string, 0, len(watchers))
|
||||
for name := range watchers {
|
||||
names = append(names, name)
|
||||
}
|
||||
watchMu.Unlock()
|
||||
if len(names) == 0 {
|
||||
return
|
||||
}
|
||||
pollCtx, cancel := context.WithTimeout(ctx, requestPoll)
|
||||
defer cancel()
|
||||
taken, err := st.TakeRunRequests(pollCtx, names)
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Msg("jobrun: run request poll failed")
|
||||
return
|
||||
}
|
||||
var orphaned []string
|
||||
watchMu.Lock()
|
||||
for _, name := range taken {
|
||||
if len(watchers[name]) == 0 {
|
||||
orphaned = append(orphaned, name)
|
||||
}
|
||||
for _, ch := range watchers[name] {
|
||||
select {
|
||||
case ch <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
watchMu.Unlock()
|
||||
// The loop stopped here after the poll began; the request goes back for whichever process runs it now.
|
||||
for _, name := range orphaned {
|
||||
handCtx, cancelHand := context.WithTimeout(ctx, requestPoll)
|
||||
_, err := st.RequestRun(handCtx, name)
|
||||
cancelHand()
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Str("job", name).Msg("jobrun: could not hand a run request back")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// nextDue is the first slot after at on due's cadence; slots missed while a
|
||||
|
||||
@@ -20,9 +20,15 @@ type memStore struct {
|
||||
// write behind each one landed anyway.
|
||||
failClaims int
|
||||
applyFailed bool
|
||||
requested map[string]bool
|
||||
polls int
|
||||
// onTake runs as a poll takes its requests, before they are delivered.
|
||||
onTake func()
|
||||
}
|
||||
|
||||
func newMemStore() *memStore { return &memStore{due: map[string]time.Time{}} }
|
||||
func newMemStore() *memStore {
|
||||
return &memStore{due: map[string]time.Time{}, requested: map[string]bool{}}
|
||||
}
|
||||
|
||||
func (m *memStore) Register(_ context.Context, name, _ string, _ time.Duration, next, earliest time.Time) (time.Time, error) {
|
||||
m.mu.Lock()
|
||||
@@ -76,8 +82,29 @@ func (m *memStore) MarkStarted(context.Context, string, time.Time) error { retur
|
||||
func (m *memStore) MarkFinished(context.Context, string, time.Time, time.Time, error) error {
|
||||
return nil
|
||||
}
|
||||
func (m *memStore) RequestRun(context.Context, string) (bool, error) { return false, nil }
|
||||
func (m *memStore) TakeRunRequest(context.Context, string) (bool, error) { return false, nil }
|
||||
func (m *memStore) RequestRun(_ context.Context, name string) (bool, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.requested[name] = true
|
||||
return true, nil
|
||||
}
|
||||
func (m *memStore) TakeRunRequests(_ context.Context, names []string) ([]string, error) {
|
||||
m.mu.Lock()
|
||||
m.polls++
|
||||
var taken []string
|
||||
for _, n := range names {
|
||||
if m.requested[n] {
|
||||
delete(m.requested, n)
|
||||
taken = append(taken, n)
|
||||
}
|
||||
}
|
||||
onTake := m.onTake
|
||||
m.mu.Unlock()
|
||||
if onTake != nil {
|
||||
onTake()
|
||||
}
|
||||
return taken, nil
|
||||
}
|
||||
func (m *memStore) List(context.Context) ([]models.ScheduledJobRun, error) {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -278,3 +305,50 @@ func TestNextDueKeepsTheCadenceAndDropsMissedSlots(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A process asks for every loop's run requests in one query per poll, and only the requested loop runs.
|
||||
func TestRunRequestsArePolledOncePerProcess(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
store := newMemStore()
|
||||
useStore(t, store)
|
||||
|
||||
var wanted, other atomic.Int32
|
||||
stopWanted := startLoop("wanted", 24*time.Hour, false, &wanted)
|
||||
defer stopWanted()
|
||||
stopOther := startLoop("other", 24*time.Hour, false, &other)
|
||||
defer stopOther()
|
||||
|
||||
if _, err := store.RequestRun(context.Background(), "wanted"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(requestPoll + time.Millisecond)
|
||||
synctest.Wait()
|
||||
|
||||
if wanted.Load() != 1 || other.Load() != 0 {
|
||||
t.Fatalf("requested job ran %d times and the other %d, want 1 and 0", wanted.Load(), other.Load())
|
||||
}
|
||||
store.mu.Lock()
|
||||
polls := store.polls
|
||||
store.mu.Unlock()
|
||||
if polls != 1 {
|
||||
t.Fatalf("two loops polled for requests %d times in one interval, want 1", polls)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A request taken just as its loop stopped here goes back to the store for the process that runs the loop now.
|
||||
func TestRunRequestForAStoppedLoopIsHandedBack(t *testing.T) {
|
||||
store := newMemStore()
|
||||
useStore(t, store)
|
||||
ch := watchRequests("moved")
|
||||
store.requested["moved"] = true
|
||||
store.onTake = func() { unwatchRequests("moved", ch) }
|
||||
|
||||
takeRequests(context.Background())
|
||||
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
if !store.requested["moved"] {
|
||||
t.Fatal("a run request taken for a loop that had stopped was lost")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
package jobs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/app/instancesettings"
|
||||
"github.com/warmbly/warmbly/internal/jobrun"
|
||||
)
|
||||
|
||||
const (
|
||||
// workerHealthSampleKeepDays covers every reader of the samples, the longest of which is one hour.
|
||||
workerHealthSampleKeepDays = 7
|
||||
// sendResultEffectKeepDays keeps a delivered effect long enough to explain a late duplicate.
|
||||
sendResultEffectKeepDays = 7
|
||||
)
|
||||
|
||||
// TableRetentionStore is the prune half of repository.TableRetentionRepository.
|
||||
type TableRetentionStore interface {
|
||||
PruneCampaignLogs(ctx context.Context, before time.Time) (int64, error)
|
||||
PruneNotifications(ctx context.Context, before time.Time) (int64, error)
|
||||
PruneWebhookDeliveries(ctx context.Context, before time.Time) (int64, error)
|
||||
PruneWorkerHealthSamples(ctx context.Context, before time.Time) (int64, error)
|
||||
PruneDeliveredSendResultEffects(ctx context.Context, before time.Time) (int64, error)
|
||||
}
|
||||
|
||||
// TableRetentionJob prunes feeds, logs and finished bookkeeping past their
|
||||
// windows. The windows that bound product history are instance settings.
|
||||
type TableRetentionJob struct {
|
||||
store TableRetentionStore
|
||||
retention RetentionSource
|
||||
}
|
||||
|
||||
// NewTableRetentionJob builds the job; without a settings source the compiled defaults apply.
|
||||
func NewTableRetentionJob(store TableRetentionStore, retention RetentionSource) *TableRetentionJob {
|
||||
return &TableRetentionJob{store: store, retention: retention}
|
||||
}
|
||||
|
||||
// Start runs the prune on every replica's loop; jobrun gives each slot to one of them.
|
||||
func (j *TableRetentionJob) Start(ctx context.Context, interval time.Duration) {
|
||||
if j.store == nil {
|
||||
return
|
||||
}
|
||||
jobrun.Loop(ctx, "table_retention", interval, true, j.Run)
|
||||
}
|
||||
|
||||
// Run executes one pass and keeps going past a failing table.
|
||||
func (j *TableRetentionJob) Run(ctx context.Context) error {
|
||||
windows := instancesettings.DefaultRetention()
|
||||
if j.retention != nil {
|
||||
windows = j.retention.RetentionWindows(ctx)
|
||||
}
|
||||
now := time.Now()
|
||||
steps := []struct {
|
||||
table string
|
||||
prune func(context.Context, time.Time) (int64, error)
|
||||
days int
|
||||
}{
|
||||
{"campaign_logs", j.store.PruneCampaignLogs, windows.CampaignLogDays},
|
||||
{"notifications", j.store.PruneNotifications, windows.NotificationDays},
|
||||
{"webhook_deliveries", j.store.PruneWebhookDeliveries, windows.WebhookDeliveryDays},
|
||||
{"worker_health_samples", j.store.PruneWorkerHealthSamples, workerHealthSampleKeepDays},
|
||||
{"send_result_effects", j.store.PruneDeliveredSendResultEffects, sendResultEffectKeepDays},
|
||||
}
|
||||
var failures []error
|
||||
for _, s := range steps {
|
||||
if s.days <= 0 {
|
||||
continue
|
||||
}
|
||||
n, err := s.prune(ctx, now.AddDate(0, 0, -s.days))
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
failures = append(failures, err)
|
||||
log.Warn().Err(err).Str("table", s.table).Msg("table retention: prune failed")
|
||||
continue
|
||||
}
|
||||
if n > 0 {
|
||||
log.Info().Int64("deleted", n).Str("table", s.table).Msg("table retention: pruned")
|
||||
}
|
||||
}
|
||||
return errors.Join(failures...)
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package jobs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/app/instancesettings"
|
||||
)
|
||||
|
||||
type fakeTableRetention struct {
|
||||
before map[string]time.Time
|
||||
fail string
|
||||
}
|
||||
|
||||
func (f *fakeTableRetention) record(table string, before time.Time) (int64, error) {
|
||||
f.before[table] = before
|
||||
if table == f.fail {
|
||||
return 0, errors.New("boom")
|
||||
}
|
||||
return 1, nil
|
||||
}
|
||||
|
||||
func (f *fakeTableRetention) PruneCampaignLogs(_ context.Context, b time.Time) (int64, error) {
|
||||
return f.record("campaign_logs", b)
|
||||
}
|
||||
func (f *fakeTableRetention) PruneNotifications(_ context.Context, b time.Time) (int64, error) {
|
||||
return f.record("notifications", b)
|
||||
}
|
||||
func (f *fakeTableRetention) PruneWebhookDeliveries(_ context.Context, b time.Time) (int64, error) {
|
||||
return f.record("webhook_deliveries", b)
|
||||
}
|
||||
func (f *fakeTableRetention) PruneWorkerHealthSamples(_ context.Context, b time.Time) (int64, error) {
|
||||
return f.record("worker_health_samples", b)
|
||||
}
|
||||
func (f *fakeTableRetention) PruneDeliveredSendResultEffects(_ context.Context, b time.Time) (int64, error) {
|
||||
return f.record("send_result_effects", b)
|
||||
}
|
||||
|
||||
type fixedRetention instancesettings.Retention
|
||||
|
||||
func (r fixedRetention) RetentionWindows(context.Context) instancesettings.Retention {
|
||||
return instancesettings.Retention(r)
|
||||
}
|
||||
|
||||
func TestTableRetentionReadsWindowsAndSurvivesAFailingTable(t *testing.T) {
|
||||
store := &fakeTableRetention{before: map[string]time.Time{}, fail: "notifications"}
|
||||
windows := instancesettings.DefaultRetention()
|
||||
windows.CampaignLogDays, windows.NotificationDays, windows.WebhookDeliveryDays = 10, 15, 20
|
||||
err := NewTableRetentionJob(store, fixedRetention(windows)).Run(context.Background())
|
||||
if err == nil {
|
||||
t.Fatal("a failing table was not reported")
|
||||
}
|
||||
if len(store.before) != 5 {
|
||||
t.Fatalf("pruned %d tables, want all five despite the failure: %v", len(store.before), store.before)
|
||||
}
|
||||
for table, days := range map[string]int{
|
||||
"campaign_logs": 10, "webhook_deliveries": 20,
|
||||
"worker_health_samples": workerHealthSampleKeepDays, "send_result_effects": sendResultEffectKeepDays,
|
||||
} {
|
||||
age := time.Since(store.before[table])
|
||||
if want := time.Duration(days) * 24 * time.Hour; age < want-2*time.Hour || age > want+2*time.Hour {
|
||||
t.Errorf("%s pruned before %v ago, want %d days", table, age, days)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// An instance that never chose a feed window keeps its feeds; only bookkeeping is pruned.
|
||||
func TestTableRetentionKeepsFeedsByDefault(t *testing.T) {
|
||||
store := &fakeTableRetention{before: map[string]time.Time{}}
|
||||
if err := NewTableRetentionJob(store, fixedRetention(instancesettings.DefaultRetention())).Run(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, feed := range []string{"campaign_logs", "notifications", "webhook_deliveries"} {
|
||||
if _, pruned := store.before[feed]; pruned {
|
||||
t.Errorf("%s was pruned with no window set", feed)
|
||||
}
|
||||
}
|
||||
if len(store.before) != 2 {
|
||||
t.Fatalf("pruned %v, want only the worker health samples and delivered effects", store.before)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
// Package leader runs loops on one process of a role at a time. The leader
|
||||
// holds a session advisory lock on a direct connection and keeps it until the
|
||||
// process stops or the connection breaks, so loops that keep state in memory
|
||||
// stay on the same replica instead of moving every tick.
|
||||
package leader
|
||||
|
||||
import (
|
||||
"context"
|
||||
"hash/fnv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// lockClass is the advisory-lock namespace; 266 is the cloud-link reconciliation lock.
|
||||
const lockClass = 267
|
||||
|
||||
const (
|
||||
defaultRetry = 30 * time.Second
|
||||
defaultPing = 10 * time.Second
|
||||
dialTimeout = 10 * time.Second
|
||||
)
|
||||
|
||||
// Sessioner opens a connection whose close releases its session locks; *db.DB implements it.
|
||||
type Sessioner interface {
|
||||
ConnectSession(ctx context.Context) (*pgx.Conn, error)
|
||||
}
|
||||
|
||||
type loop struct {
|
||||
name string
|
||||
fn func(ctx context.Context)
|
||||
}
|
||||
|
||||
// Elector runs the loops registered with Go while this process holds the role's lock.
|
||||
type Elector struct {
|
||||
db Sessioner
|
||||
role string
|
||||
key int32
|
||||
retry time.Duration
|
||||
ping time.Duration
|
||||
mu sync.Mutex
|
||||
loops []loop
|
||||
running bool
|
||||
leading atomic.Bool
|
||||
}
|
||||
|
||||
// New returns an elector for role, one lock per role (backend, consumer).
|
||||
func New(db Sessioner, role string) *Elector {
|
||||
h := fnv.New32a()
|
||||
_, _ = h.Write([]byte(role))
|
||||
return &Elector{db: db, role: role, key: int32(h.Sum32() & 0x7fffffff), retry: defaultRetry, ping: defaultPing}
|
||||
}
|
||||
|
||||
// Go registers a loop to run while leading. fn must return when its ctx ends;
|
||||
// it is started again whenever this process wins the lock again.
|
||||
func (e *Elector) Go(name string, fn func(ctx context.Context)) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
if e.running {
|
||||
panic("leader: Go after Run")
|
||||
}
|
||||
e.loops = append(e.loops, loop{name: name, fn: fn})
|
||||
}
|
||||
|
||||
// Leading reports whether this process holds the lock now.
|
||||
func (e *Elector) Leading() bool { return e.leading.Load() }
|
||||
|
||||
// Run competes for the lock until ctx ends, running the registered loops while it holds it.
|
||||
func (e *Elector) Run(ctx context.Context) {
|
||||
e.mu.Lock()
|
||||
e.running = true
|
||||
loops := append([]loop(nil), e.loops...)
|
||||
e.mu.Unlock()
|
||||
if len(loops) == 0 {
|
||||
return
|
||||
}
|
||||
for {
|
||||
if conn := e.acquire(ctx); conn != nil {
|
||||
e.lead(ctx, conn, loops)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(e.retry):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// acquire returns the lock-holding connection, or nil when another process leads.
|
||||
func (e *Elector) acquire(ctx context.Context) *pgx.Conn {
|
||||
dialCtx, cancel := context.WithTimeout(ctx, dialTimeout)
|
||||
defer cancel()
|
||||
conn, err := e.db.ConnectSession(dialCtx)
|
||||
if err != nil {
|
||||
if ctx.Err() == nil {
|
||||
log.Warn().Err(err).Str("role", e.role).Msg("leader: could not open the lock connection")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
var won bool
|
||||
if err := conn.QueryRow(dialCtx, `SELECT pg_try_advisory_lock($1, $2)`, lockClass, e.key).Scan(&won); err != nil || !won {
|
||||
if err != nil && ctx.Err() == nil {
|
||||
log.Warn().Err(err).Str("role", e.role).Msg("leader: lock attempt failed")
|
||||
}
|
||||
closeConn(ctx, conn)
|
||||
return nil
|
||||
}
|
||||
return conn
|
||||
}
|
||||
|
||||
// lead runs the loops until ctx ends or the lock connection stops answering.
|
||||
func (e *Elector) lead(ctx context.Context, conn *pgx.Conn, loops []loop) {
|
||||
leadCtx, cancel := context.WithCancel(ctx)
|
||||
var wg sync.WaitGroup
|
||||
e.leading.Store(true)
|
||||
log.Info().Str("role", e.role).Int("loops", len(loops)).Msg("leader: this process now runs the single-replica loops")
|
||||
for _, l := range loops {
|
||||
wg.Add(1)
|
||||
go func(l loop) {
|
||||
defer wg.Done()
|
||||
l.fn(leadCtx)
|
||||
}(l)
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(e.ping)
|
||||
defer ticker.Stop()
|
||||
for leadCtx.Err() == nil {
|
||||
select {
|
||||
case <-leadCtx.Done():
|
||||
case <-ticker.C:
|
||||
pingCtx, done := context.WithTimeout(leadCtx, e.ping)
|
||||
_, err := conn.Exec(pingCtx, `SELECT 1`)
|
||||
done()
|
||||
if err != nil && ctx.Err() == nil {
|
||||
log.Warn().Err(err).Str("role", e.role).Msg("leader: lock connection lost; stopping the single-replica loops")
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
wg.Wait()
|
||||
e.leading.Store(false)
|
||||
closeConn(ctx, conn)
|
||||
}
|
||||
|
||||
func closeConn(ctx context.Context, conn *pgx.Conn) {
|
||||
closeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = conn.Close(closeCtx)
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package leader
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/infrastructure/db"
|
||||
)
|
||||
|
||||
func liveDB(t *testing.T) *db.DB {
|
||||
t.Helper()
|
||||
dsn := os.Getenv("WARMBLY_TEST_DB")
|
||||
if dsn == "" {
|
||||
t.Skip("WARMBLY_TEST_DB not set")
|
||||
}
|
||||
handle, err := db.New(context.Background(), dsn)
|
||||
if err != nil {
|
||||
t.Fatalf("connect: %v", err)
|
||||
}
|
||||
t.Cleanup(handle.Pool.Close)
|
||||
return handle
|
||||
}
|
||||
|
||||
func waitFor(t *testing.T, what string, ok func() bool) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for !ok() {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("timed out waiting for %s", what)
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveOneProcessLeadsAndTheOtherTakesOverWhenItStops(t *testing.T) {
|
||||
handle := liveDB(t)
|
||||
role := "leader-test-" + time.Now().Format("150405.000000000")
|
||||
var runningA, runningB atomic.Int32
|
||||
elector := func(running *atomic.Int32) *Elector {
|
||||
e := New(handle, role)
|
||||
e.retry, e.ping = 50*time.Millisecond, 50*time.Millisecond
|
||||
e.Go("probe", func(ctx context.Context) {
|
||||
running.Add(1)
|
||||
<-ctx.Done()
|
||||
running.Add(-1)
|
||||
})
|
||||
return e
|
||||
}
|
||||
|
||||
ctxA, stopA := context.WithCancel(context.Background())
|
||||
a := elector(&runningA)
|
||||
doneA := make(chan struct{})
|
||||
go func() { a.Run(ctxA); close(doneA) }()
|
||||
waitFor(t, "the first process to lead", a.Leading)
|
||||
|
||||
ctxB, stopB := context.WithCancel(context.Background())
|
||||
defer stopB()
|
||||
b := elector(&runningB)
|
||||
go b.Run(ctxB)
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
if b.Leading() || runningB.Load() != 0 {
|
||||
t.Fatal("a second process led while the first held the lock")
|
||||
}
|
||||
if runningA.Load() != 1 {
|
||||
t.Fatalf("the leader runs %d copies of its loop, want 1", runningA.Load())
|
||||
}
|
||||
|
||||
stopA()
|
||||
<-doneA
|
||||
if runningA.Load() != 0 {
|
||||
t.Fatal("the old leader's loop outlived its leadership")
|
||||
}
|
||||
waitFor(t, "the second process to take over", b.Leading)
|
||||
waitFor(t, "the new leader's loop to start", func() bool { return runningB.Load() == 1 })
|
||||
}
|
||||
|
||||
func TestLiveALostLockConnectionStopsTheLoops(t *testing.T) {
|
||||
handle := liveDB(t)
|
||||
e := New(handle, "leader-test-lost-"+time.Now().Format("150405.000000000"))
|
||||
e.retry, e.ping = 50*time.Millisecond, 50*time.Millisecond
|
||||
var started, stopped atomic.Int32
|
||||
e.Go("probe", func(ctx context.Context) {
|
||||
started.Add(1)
|
||||
<-ctx.Done()
|
||||
stopped.Add(1)
|
||||
})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go e.Run(ctx)
|
||||
waitFor(t, "leadership", e.Leading)
|
||||
|
||||
if _, err := handle.Pool.Exec(ctx, `SELECT pg_terminate_backend(pid) FROM pg_locks
|
||||
WHERE locktype = 'advisory' AND classid::bigint = $1 AND objid::bigint = $2`, int64(lockClass), int64(e.key)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitFor(t, "the loop to stop with its lock", func() bool { return stopped.Load() >= 1 })
|
||||
// A second start is a new term; Leading alone can still read true from the old one.
|
||||
waitFor(t, "leadership to be won back", func() bool { return started.Load() >= 2 && e.Leading() })
|
||||
}
|
||||
|
||||
func TestRunWithNoLoopsReturnsWithoutConnecting(t *testing.T) {
|
||||
e := New(nil, "empty")
|
||||
done := make(chan struct{})
|
||||
go func() { e.Run(context.Background()); close(done) }()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("an elector with nothing to run held on")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// Package idlepoll paces a loop that polls a Postgres queue: it asks again at
|
||||
// once while work keeps coming and slows down while the queue stays empty.
|
||||
package idlepoll
|
||||
|
||||
import "time"
|
||||
|
||||
// Pace is a poll interval that doubles from Min to Max while polls find nothing.
|
||||
type Pace struct {
|
||||
Min, Max time.Duration
|
||||
cur time.Duration
|
||||
}
|
||||
|
||||
// Next is the wait before the next poll. A full poll means more may be
|
||||
// waiting, so it is asked for at once; any work resets the pace to Min.
|
||||
func (p *Pace) Next(found int, full bool) time.Duration {
|
||||
switch {
|
||||
case full:
|
||||
p.cur = p.Min
|
||||
return 0
|
||||
case found > 0 || p.cur == 0:
|
||||
p.cur = p.Min
|
||||
default:
|
||||
p.cur = min(p.cur*2, p.Max)
|
||||
}
|
||||
return p.cur
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package idlepoll
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestPaceDrainsBusyQueuesAndSlowsOnEmptyOnes(t *testing.T) {
|
||||
p := Pace{Min: 2 * time.Second, Max: 15 * time.Second}
|
||||
steps := []struct {
|
||||
found int
|
||||
full bool
|
||||
want time.Duration
|
||||
}{
|
||||
{0, false, 2 * time.Second},
|
||||
{0, false, 4 * time.Second},
|
||||
{0, false, 8 * time.Second},
|
||||
{0, false, 15 * time.Second},
|
||||
{0, false, 15 * time.Second},
|
||||
{25, true, 0},
|
||||
{3, false, 2 * time.Second},
|
||||
{0, false, 4 * time.Second},
|
||||
}
|
||||
for i, s := range steps {
|
||||
if got := p.Next(s.found, s.full); got != s.want {
|
||||
t.Fatalf("step %d: found %d full %v waited %v, want %v", i, s.found, s.full, got, s.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -100,7 +100,8 @@ func TestLiveArrivalDiagnosticsPreserveStageRetryAndKeyCalls(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stages := record["stages"].(map[string]any)
|
||||
for name, want := range map[string]float64{"claim": 4, "key_lookup": 2, "decrypt": 2, "decode": 2, "new_email": 1, "bounce": 2, "complaint": 1, "checkpoint": 3, "retry": 1, "retire": 1} {
|
||||
// One batched claim per pass; a checkpoint only where a later stage still has to run.
|
||||
for name, want := range map[string]float64{"claim": 2, "key_lookup": 2, "decrypt": 2, "decode": 2, "new_email": 1, "bounce": 2, "complaint": 1, "checkpoint": 2, "retry": 1, "retire": 1} {
|
||||
if stages[name].(map[string]any)["attempts"] != want {
|
||||
t.Fatalf("%s count was not an attempt count: %v", name, stages[name])
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLiveEventAudienceRemembersResourceOrganizationsOnly(t *testing.T) {
|
||||
_, pool := liveContactDB(t)
|
||||
f := newSharedOrgFixture(t, pool)
|
||||
ctx := context.Background()
|
||||
audience := NewEventAudienceRepository(pool)
|
||||
if org, err := audience.ResourceOrganization(ctx, "campaign", f.campaign); err != nil || org != f.org {
|
||||
t.Fatalf("resource org=%v err=%v", org, err)
|
||||
}
|
||||
// The second lookup is served from memory: it answers through a reader whose pool is closed.
|
||||
_, other := liveContactDB(t)
|
||||
closed := NewEventAudienceRepository(other)
|
||||
closed.orgs = audience.orgs
|
||||
other.Close()
|
||||
if org, err := closed.ResourceOrganization(ctx, "campaign", f.campaign); err != nil || org != f.org {
|
||||
t.Fatalf("cached resource org=%v err=%v", org, err)
|
||||
}
|
||||
if _, err := closed.CanAddressUser(ctx, f.org, f.mate); err == nil {
|
||||
t.Fatal("membership was answered without asking the database")
|
||||
}
|
||||
}
|
||||
@@ -104,8 +104,8 @@ func TestLiveJobRunRetirementPreservesHistoryAndReactivatesOnlyOnRegistration(t
|
||||
if found, err := repo.RequestRun(ctx, name); err != nil || found {
|
||||
t.Fatalf("retired RequestRun found=%v err=%v", found, err)
|
||||
}
|
||||
if taken, err := repo.TakeRunRequest(ctx, name); err != nil || taken {
|
||||
t.Fatalf("retired TakeRunRequest taken=%v err=%v", taken, err)
|
||||
if taken, err := repo.TakeRunRequests(ctx, []string{name}); err != nil || len(taken) != 0 {
|
||||
t.Fatalf("retired TakeRunRequests taken=%v err=%v", taken, err)
|
||||
}
|
||||
if won, got, err := repo.Claim(ctx, name, due, next); err != nil || won || !got.Equal(next) {
|
||||
t.Fatalf("retired Claim won=%v due=%s err=%v", won, got, err)
|
||||
@@ -208,3 +208,36 @@ func TestLiveJobRunMonitoringExcludesOnlyExplicitRetirements(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// One poll takes the requests of every named job and leaves the rest pending.
|
||||
func TestLiveTakeRunRequestsTakesOnlyNamedRequestsOnce(t *testing.T) {
|
||||
handle, pool := liveContactDB(t)
|
||||
ctx := context.Background()
|
||||
repo := NewJobRunRepository(handle)
|
||||
asked, idle, elsewhere := "live_take_"+uuid.NewString(), "live_take_"+uuid.NewString(), "live_take_"+uuid.NewString()
|
||||
t.Cleanup(func() {
|
||||
_, _ = pool.Exec(ctx, `DELETE FROM scheduled_job_runs WHERE name = ANY($1)`, []string{asked, idle, elsewhere})
|
||||
})
|
||||
now := time.Now().Truncate(time.Microsecond)
|
||||
for _, name := range []string{asked, idle, elsewhere} {
|
||||
if _, err := repo.Register(ctx, name, "test", time.Hour, now.Add(time.Hour), now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, name := range []string{asked, elsewhere} {
|
||||
if found, err := repo.RequestRun(ctx, name); err != nil || !found {
|
||||
t.Fatalf("RequestRun %s found=%v err=%v", name, found, err)
|
||||
}
|
||||
}
|
||||
|
||||
taken, err := repo.TakeRunRequests(ctx, []string{asked, idle})
|
||||
if err != nil || len(taken) != 1 || taken[0] != asked {
|
||||
t.Fatalf("taken %v err %v, want only %s", taken, err, asked)
|
||||
}
|
||||
if again, err := repo.TakeRunRequests(ctx, []string{asked, idle}); err != nil || len(again) != 0 {
|
||||
t.Fatalf("a request was taken twice: %v err %v", again, err)
|
||||
}
|
||||
if other, err := repo.TakeRunRequests(ctx, []string{elsewhere}); err != nil || len(other) != 1 {
|
||||
t.Fatalf("another process's request was not left pending: %v err %v", other, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -856,7 +856,7 @@ func TestLiveMailTransportSyncFolderCoverageRequiresCurrentWorker(t *testing.T)
|
||||
oldReport := models.SyncState{LastSyncedAt: &completed, FolderCoverageObservedAt: &first, FoldersSkippedCap: 4}
|
||||
put := func(worker uuid.UUID, state *models.SyncState, want bool) {
|
||||
t.Helper()
|
||||
accepted, err := repo.PutFromWorker(t.Context(), f.user, f.account, worker, uuid.Nil, state, nil)
|
||||
accepted, _, err := repo.PutFromWorker(t.Context(), f.user, f.account, worker, uuid.Nil, state, nil)
|
||||
if err != nil || accepted != want {
|
||||
t.Fatalf("accepted=%t want=%t err=%v", accepted, want, err)
|
||||
}
|
||||
@@ -910,7 +910,7 @@ func TestLiveMailTransportSyncReportRequiresCurrentGeneration(t *testing.T) {
|
||||
}
|
||||
put := func(report uuid.UUID, state models.SyncState, want bool) {
|
||||
t.Helper()
|
||||
accepted, err := repo.PutFromWorker(t.Context(), f.user, f.account, worker, report, &state, nil)
|
||||
accepted, _, err := repo.PutFromWorker(t.Context(), f.user, f.account, worker, report, &state, nil)
|
||||
if err != nil || accepted != want {
|
||||
t.Fatalf("report=%s pass=%s accepted=%t want=%t err=%v", report, state.TransportGeneration, accepted, want, err)
|
||||
}
|
||||
@@ -959,17 +959,17 @@ func TestLiveMailTransportSyncReportCommitsRecoveryAndBothClocks(t *testing.T) {
|
||||
synced := old.Add(time.Minute)
|
||||
state := &models.SyncState{LastSyncedAt: &synced, FolderCoverageObservedAt: &synced, FoldersSkippedCap: -1}
|
||||
calls := 0
|
||||
recover := func(ctx context.Context) error {
|
||||
recover := func(ctx context.Context, _ *SyncStatePrior) error {
|
||||
calls++
|
||||
if xerr := f.repo.RecordTransportSuccess(ctx, f.account, models.MailTransportSync, synced, nil, f.generation); xerr != nil {
|
||||
return xerr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if accepted, err := repo.PutFromWorker(t.Context(), f.user, f.account, uuid.New(), uuid.Nil, state, recover); err != nil || accepted || calls != 0 {
|
||||
if accepted, _, err := repo.PutFromWorker(t.Context(), f.user, f.account, uuid.New(), uuid.Nil, state, recover); err != nil || accepted || calls != 0 {
|
||||
t.Fatalf("declined report recovered: accepted=%t calls=%d err=%v", accepted, calls, err)
|
||||
}
|
||||
if accepted, err := repo.PutFromWorker(t.Context(), f.user, f.account, worker, uuid.Nil, state, recover); err == nil || accepted {
|
||||
if accepted, _, err := repo.PutFromWorker(t.Context(), f.user, f.account, worker, uuid.Nil, state, recover); err == nil || accepted {
|
||||
t.Fatalf("invalid state committed: accepted=%t err=%v", accepted, err)
|
||||
}
|
||||
var accountAt *time.Time
|
||||
@@ -985,7 +985,7 @@ func TestLiveMailTransportSyncReportCommitsRecoveryAndBothClocks(t *testing.T) {
|
||||
t.Fatalf("failed state escaped rollback: state=%+v account=%v recoveries=%d calls=%d err=%v", got, accountAt, recoveries, calls, err)
|
||||
}
|
||||
state.FoldersSkippedCap = 4
|
||||
if accepted, err := repo.PutFromWorker(t.Context(), f.user, f.account, worker, uuid.Nil, state, recover); err != nil || !accepted {
|
||||
if accepted, _, err := repo.PutFromWorker(t.Context(), f.user, f.account, worker, uuid.Nil, state, recover); err != nil || !accepted {
|
||||
t.Fatalf("accepted=%t err=%v", accepted, err)
|
||||
}
|
||||
got, err = repo.Get(t.Context(), f.account)
|
||||
|
||||
@@ -866,21 +866,34 @@ func scanJob(row pgx.Row) (*models.CRMSyncJob, error) {
|
||||
}
|
||||
|
||||
// ClaimJobs leases due jobs. A lease that lapses (a crashed drainer) makes the
|
||||
// job claimable again, so nothing is stranded in running.
|
||||
// job claimable again, so nothing is stranded in running. Each arm is its own
|
||||
// select so the due and the running-lease partial indexes serve it.
|
||||
func (r *crmProviderRepository) ClaimJobs(ctx context.Context, provider models.CRMProvider, limit int, lease time.Duration) ([]models.CRMSyncJob, error) {
|
||||
rows, err := r.db.Query(ctx, `
|
||||
UPDATE crm_sync_jobs j
|
||||
SET status = 'running', attempts = j.attempts + 1, locked_until = NOW() + make_interval(secs => $2),
|
||||
lease_token = gen_random_uuid(), updated_at = NOW()
|
||||
WHERE j.id IN (
|
||||
SELECT id FROM crm_sync_jobs
|
||||
WHERE provider = $3
|
||||
AND ((status = 'pending' AND next_attempt_at <= NOW())
|
||||
OR (status = 'running' AND locked_until < NOW()))
|
||||
WITH lapsed AS (
|
||||
SELECT id, next_attempt_at FROM crm_sync_jobs
|
||||
WHERE provider = $3 AND status = 'running' AND locked_until < NOW()
|
||||
ORDER BY locked_until
|
||||
LIMIT $1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
), due AS (
|
||||
SELECT id, next_attempt_at FROM crm_sync_jobs
|
||||
WHERE provider = $3 AND status = 'pending' AND next_attempt_at <= NOW()
|
||||
ORDER BY next_attempt_at
|
||||
LIMIT $1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
), picked AS (
|
||||
SELECT id AS pick_id, next_attempt_at AS pick_at FROM lapsed
|
||||
UNION ALL
|
||||
SELECT id, next_attempt_at FROM due
|
||||
ORDER BY pick_at
|
||||
LIMIT $1
|
||||
)
|
||||
UPDATE crm_sync_jobs j
|
||||
SET status = 'running', attempts = j.attempts + 1, locked_until = NOW() + make_interval(secs => $2),
|
||||
lease_token = gen_random_uuid(), updated_at = NOW()
|
||||
FROM picked
|
||||
WHERE j.id = picked.pick_id
|
||||
RETURNING `+jobCols, limit, lease.Seconds(), provider)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -98,13 +98,8 @@ func (r *emailOpenRepository) HasHumanOpen(ctx context.Context, campaignID, cont
|
||||
}
|
||||
|
||||
func (r *emailOpenRepository) Cleanup(ctx context.Context, olderThanDays int) (int64, error) {
|
||||
tag, err := r.db.Exec(ctx,
|
||||
`DELETE FROM email_opens WHERE opened_at < NOW() - $1 * INTERVAL '1 day'`,
|
||||
olderThanDays)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return tag.RowsAffected(), nil
|
||||
return DeleteInBatches(ctx, r.db, "email_opens",
|
||||
`SELECT ctid FROM email_opens WHERE opened_at < NOW() - $2 * INTERVAL '1 day' LIMIT $1`, olderThanDays)
|
||||
}
|
||||
|
||||
// OriginDeriver re-reads one logged event's origin from its stored user agent
|
||||
|
||||
@@ -21,8 +21,9 @@ type EmailSyncStateRepository interface {
|
||||
// Put stores the full state and stamps email_accounts.last_synced_at, the
|
||||
// column the admin and dashboard "Last synced" surfaces read.
|
||||
Put(ctx context.Context, userID, emailID uuid.UUID, state *models.SyncState) error
|
||||
// PutFromWorker stores a report only while the reporting worker owns the mailbox at the reported generation.
|
||||
PutFromWorker(ctx context.Context, userID, emailID, workerID, generation uuid.UUID, state *models.SyncState, before func(context.Context) error) (bool, error)
|
||||
// PutFromWorker stores a report only while the reporting worker owns the mailbox at the reported generation,
|
||||
// and returns what the report replaced (nil when the mailbox never reported).
|
||||
PutFromWorker(ctx context.Context, userID, emailID, workerID, generation uuid.UUID, state *models.SyncState, before func(context.Context, *SyncStatePrior) error) (bool, *SyncStatePrior, error)
|
||||
// Get returns nil, nil when the mailbox has never reported.
|
||||
Get(ctx context.Context, emailID uuid.UUID) (*models.SyncState, error)
|
||||
// IsOwnConversation reports whether any of the RFC message ids or the
|
||||
@@ -59,6 +60,22 @@ func (r *pgEmailSyncStateRepository) ListProviderMessages(ctx context.Context, u
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// SyncStatePrior is the stored state a report replaces, read under the report's lock.
|
||||
type SyncStatePrior struct {
|
||||
BackfillStatus models.SyncBackfillStatus
|
||||
// ThrottledUntil is nil once the hold has expired.
|
||||
ThrottledUntil *time.Time
|
||||
LastSyncedAt *time.Time
|
||||
}
|
||||
|
||||
// PriorOf summarizes a stored state; nil stays nil.
|
||||
func PriorOf(st *models.SyncState) *SyncStatePrior {
|
||||
if st == nil {
|
||||
return nil
|
||||
}
|
||||
return &SyncStatePrior{BackfillStatus: st.BackfillStatus, ThrottledUntil: st.ThrottledUntil, LastSyncedAt: st.LastSyncedAt}
|
||||
}
|
||||
|
||||
type pgEmailSyncStateRepository struct {
|
||||
db *db.DB
|
||||
}
|
||||
@@ -70,24 +87,24 @@ func NewEmailSyncStateRepository(d *db.DB) EmailSyncStateRepository {
|
||||
}
|
||||
|
||||
func (r *pgEmailSyncStateRepository) Put(ctx context.Context, userID, emailID uuid.UUID, state *models.SyncState) error {
|
||||
_, err := r.put(ctx, userID, emailID, nil, uuid.Nil, state, nil)
|
||||
_, _, err := r.put(ctx, userID, emailID, nil, uuid.Nil, state, nil)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *pgEmailSyncStateRepository) PutFromWorker(ctx context.Context, userID, emailID, workerID, generation uuid.UUID, state *models.SyncState, before func(context.Context) error) (bool, error) {
|
||||
func (r *pgEmailSyncStateRepository) PutFromWorker(ctx context.Context, userID, emailID, workerID, generation uuid.UUID, state *models.SyncState, before func(context.Context, *SyncStatePrior) error) (bool, *SyncStatePrior, error) {
|
||||
if workerID == uuid.Nil {
|
||||
return false, nil
|
||||
return false, nil, nil
|
||||
}
|
||||
return r.put(ctx, userID, emailID, &workerID, generation, state, before)
|
||||
}
|
||||
|
||||
func (r *pgEmailSyncStateRepository) put(ctx context.Context, userID, emailID uuid.UUID, workerID *uuid.UUID, generation uuid.UUID, state *models.SyncState, before func(context.Context) error) (bool, error) {
|
||||
func (r *pgEmailSyncStateRepository) put(ctx context.Context, userID, emailID uuid.UUID, workerID *uuid.UUID, generation uuid.UUID, state *models.SyncState, before func(context.Context, *SyncStatePrior) error) (bool, *SyncStatePrior, error) {
|
||||
if state == nil {
|
||||
return false, nil
|
||||
return false, nil, nil
|
||||
}
|
||||
cursor, err := json.Marshal(state.BackfillCursor)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("email_sync_state: cursor: %w", err)
|
||||
return false, nil, fmt.Errorf("email_sync_state: cursor: %w", err)
|
||||
}
|
||||
status := state.BackfillStatus
|
||||
if status == "" {
|
||||
@@ -95,38 +112,50 @@ func (r *pgEmailSyncStateRepository) put(ctx context.Context, userID, emailID uu
|
||||
}
|
||||
tx, err := r.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("email_sync_state: begin: %w", err)
|
||||
return false, nil, fmt.Errorf("email_sync_state: begin: %w", err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
if err := lockTransportMailbox(ctx, tx, emailID); err != nil {
|
||||
return false, fmt.Errorf("email_sync_state: lock: %w", err)
|
||||
return false, nil, fmt.Errorf("email_sync_state: lock: %w", err)
|
||||
}
|
||||
var assigned *uuid.UUID
|
||||
var current uuid.UUID
|
||||
err = tx.QueryRow(ctx, `SELECT worker_id, transport_generation FROM email_accounts WHERE id=$1 FOR UPDATE`, emailID).Scan(&assigned, ¤t)
|
||||
var priorStatus *string
|
||||
var priorThrottle, priorSynced *time.Time
|
||||
// NO KEY UPDATE holds off reassignment without blocking the mailbox's foreign-key inserts.
|
||||
err = tx.QueryRow(ctx, `SELECT a.worker_id, a.transport_generation, s.backfill_status::text, s.throttled_until, s.last_synced_at
|
||||
FROM email_accounts a LEFT JOIN email_sync_state s ON s.email_id = a.id
|
||||
WHERE a.id=$1 FOR NO KEY UPDATE OF a`, emailID).Scan(&assigned, ¤t, &priorStatus, &priorThrottle, &priorSynced)
|
||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, fmt.Errorf("email_sync_state: owner: %w", err)
|
||||
return false, nil, fmt.Errorf("email_sync_state: owner: %w", err)
|
||||
}
|
||||
if workerID != nil && (assigned == nil || *assigned != *workerID) {
|
||||
return false, nil
|
||||
return false, nil, nil
|
||||
}
|
||||
// Reports from releases that predate the incarnation generation carry only the completed-pass one, or none.
|
||||
if generation == uuid.Nil {
|
||||
generation = state.TransportGeneration
|
||||
}
|
||||
if generation != uuid.Nil && err == nil && generation != current {
|
||||
return false, nil
|
||||
return false, nil, nil
|
||||
}
|
||||
var prior *SyncStatePrior
|
||||
if priorStatus != nil {
|
||||
prior = &SyncStatePrior{BackfillStatus: models.SyncBackfillStatus(*priorStatus), LastSyncedAt: priorSynced}
|
||||
if priorThrottle != nil && priorThrottle.After(time.Now()) {
|
||||
prior.ThrottledUntil = priorThrottle
|
||||
}
|
||||
}
|
||||
if before != nil {
|
||||
if err := before(context.WithValue(ctx, syncReportKey{}, tx)); err != nil {
|
||||
return false, err
|
||||
if err := before(context.WithValue(ctx, syncReportKey{}, tx), prior); err != nil {
|
||||
return false, nil, err
|
||||
}
|
||||
}
|
||||
const q = `
|
||||
-- Retain original coverage clocks for replay ordering, allowing at most five seconds of lead.
|
||||
WITH coverage AS (
|
||||
SELECT $15::timestamptz IS NULL OR ($15 > to_timestamp(0) AND $15 <= now() + interval '5 seconds') AS valid
|
||||
)
|
||||
), saved AS (
|
||||
INSERT INTO email_sync_state (
|
||||
email_id, user_id, backfill_status, backfill_cursor, backfill_synced,
|
||||
backfill_since, backfill_started_at, backfill_completed_at,
|
||||
@@ -167,27 +196,34 @@ func (r *pgEmailSyncStateRepository) put(ctx context.Context, userID, emailID uu
|
||||
),
|
||||
last_synced_at = GREATEST(EXCLUDED.last_synced_at, email_sync_state.last_synced_at),
|
||||
updated_at = now()
|
||||
-- A redelivered report leaves the row, and its dead tuple, alone.
|
||||
WHERE (email_sync_state.user_id, email_sync_state.backfill_status, email_sync_state.backfill_cursor, email_sync_state.backfill_synced,
|
||||
email_sync_state.backfill_since, email_sync_state.backfill_started_at, email_sync_state.backfill_completed_at,
|
||||
email_sync_state.throttled_until, email_sync_state.throttle_reason, email_sync_state.deferred, email_sync_state.last_synced_at,
|
||||
email_sync_state.folders_skipped_cap, email_sync_state.folders_skipped_conflict, email_sync_state.folder_coverage_observed_at)
|
||||
IS DISTINCT FROM (EXCLUDED.user_id, EXCLUDED.backfill_status, EXCLUDED.backfill_cursor, EXCLUDED.backfill_synced,
|
||||
EXCLUDED.backfill_since, EXCLUDED.backfill_started_at, EXCLUDED.backfill_completed_at,
|
||||
EXCLUDED.throttled_until, EXCLUDED.throttle_reason, EXCLUDED.deferred, GREATEST(EXCLUDED.last_synced_at, email_sync_state.last_synced_at),
|
||||
EXCLUDED.folders_skipped_cap, EXCLUDED.folders_skipped_conflict, EXCLUDED.folder_coverage_observed_at)
|
||||
RETURNING 1)
|
||||
-- "Last synced" reads at minute precision, so a busy mailbox does not rewrite its account row every pass.
|
||||
UPDATE email_accounts SET last_synced_at = $12 WHERE id = $1 AND $12::timestamptz IS NOT NULL
|
||||
AND (last_synced_at IS NULL OR last_synced_at < $12::timestamptz - interval '1 minute')
|
||||
AND $12::timestamptz > to_timestamp(0) AND $12::timestamptz <= now() AND ($16::uuid IS NULL OR worker_id = $16)
|
||||
`
|
||||
_, err = tx.Exec(ctx, q,
|
||||
emailID, userID, string(status), cursor, state.BackfillSynced,
|
||||
state.BackfillSince, state.BackfillStartedAt, state.BackfillCompletedAt,
|
||||
state.ThrottledUntil, state.ThrottleReason, state.Deferred, state.LastSyncedAt,
|
||||
state.FoldersSkippedCap, state.FoldersSkippedConflict, state.FolderCoverageObservedAt,
|
||||
state.FoldersSkippedCap, state.FoldersSkippedConflict, state.FolderCoverageObservedAt, workerID,
|
||||
)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("email_sync_state: put: %w", err)
|
||||
}
|
||||
if state.LastSyncedAt != nil {
|
||||
const touch = `UPDATE email_accounts SET last_synced_at = $2 WHERE id = $1 AND (last_synced_at IS NULL OR last_synced_at < $2)
|
||||
AND $2::timestamptz > to_timestamp(0) AND $2 <= now() AND ($3::uuid IS NULL OR worker_id = $3)`
|
||||
if _, err := tx.Exec(ctx, touch, emailID, *state.LastSyncedAt, workerID); err != nil {
|
||||
return false, fmt.Errorf("email_sync_state: touch last_synced_at: %w", err)
|
||||
}
|
||||
return false, nil, fmt.Errorf("email_sync_state: put: %w", err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return false, fmt.Errorf("email_sync_state: commit: %w", err)
|
||||
return false, nil, fmt.Errorf("email_sync_state: commit: %w", err)
|
||||
}
|
||||
return true, nil
|
||||
return true, prior, nil
|
||||
}
|
||||
|
||||
func (r *pgEmailSyncStateRepository) Get(ctx context.Context, emailID uuid.UUID) (*models.SyncState, error) {
|
||||
|
||||
@@ -3,17 +3,38 @@ package repository
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// resourceOrgTTL bounds how long a resource's organization is remembered; nothing moves a resource between organizations.
|
||||
const (
|
||||
resourceOrgTTL = time.Minute
|
||||
resourceOrgEntries = 50_000
|
||||
)
|
||||
|
||||
type EventAudienceRepository struct {
|
||||
db *pgxpool.Pool
|
||||
|
||||
mu sync.Mutex
|
||||
orgs map[resourceKey]cachedOrg
|
||||
}
|
||||
|
||||
type resourceKey struct {
|
||||
kind string
|
||||
id uuid.UUID
|
||||
}
|
||||
|
||||
type cachedOrg struct {
|
||||
org uuid.UUID
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
func NewEventAudienceRepository(db *pgxpool.Pool) *EventAudienceRepository {
|
||||
return &EventAudienceRepository{db: db}
|
||||
return &EventAudienceRepository{db: db, orgs: map[resourceKey]cachedOrg{}}
|
||||
}
|
||||
|
||||
func (r *EventAudienceRepository) ResourceOrganization(ctx context.Context, kind string, id uuid.UUID) (uuid.UUID, error) {
|
||||
@@ -32,11 +53,28 @@ func (r *EventAudienceRepository) ResourceOrganization(ctx context.Context, kind
|
||||
default:
|
||||
return uuid.Nil, fmt.Errorf("unsupported event resource kind %q", kind)
|
||||
}
|
||||
key := resourceKey{kind: kind, id: id}
|
||||
now := time.Now()
|
||||
r.mu.Lock()
|
||||
cached, ok := r.orgs[key]
|
||||
r.mu.Unlock()
|
||||
if ok && now.Before(cached.expires) {
|
||||
return cached.org, nil
|
||||
}
|
||||
var orgID uuid.UUID
|
||||
err := r.db.QueryRow(ctx, query, id).Scan(&orgID)
|
||||
if err == nil && orgID != uuid.Nil {
|
||||
r.mu.Lock()
|
||||
if len(r.orgs) >= resourceOrgEntries {
|
||||
clear(r.orgs)
|
||||
}
|
||||
r.orgs[key] = cachedOrg{org: orgID, expires: now.Add(resourceOrgTTL)}
|
||||
r.mu.Unlock()
|
||||
}
|
||||
return orgID, err
|
||||
}
|
||||
|
||||
// CanAddressUser is never cached: removing a member stops their events at once.
|
||||
func (r *EventAudienceRepository) CanAddressUser(ctx context.Context, orgID, userID uuid.UUID) (bool, error) {
|
||||
var allowed bool
|
||||
err := r.db.QueryRow(ctx, `SELECT EXISTS (
|
||||
|
||||
@@ -19,7 +19,7 @@ type JobRunRepository interface {
|
||||
MarkStarted(ctx context.Context, name string, at time.Time) error
|
||||
MarkFinished(ctx context.Context, name string, startedAt, finishedAt time.Time, runErr error) error
|
||||
RequestRun(ctx context.Context, name string) (bool, error)
|
||||
TakeRunRequest(ctx context.Context, name string) (bool, error)
|
||||
TakeRunRequests(ctx context.Context, names []string) ([]string, error)
|
||||
List(ctx context.Context) ([]models.ScheduledJobRun, error)
|
||||
}
|
||||
|
||||
@@ -126,15 +126,16 @@ func (r *jobRunRepository) RequestRun(ctx context.Context, name string) (bool, e
|
||||
return tag.RowsAffected() > 0, nil
|
||||
}
|
||||
|
||||
func (r *jobRunRepository) TakeRunRequest(ctx context.Context, name string) (bool, error) {
|
||||
tag, err := r.db.Exec(ctx, `
|
||||
func (r *jobRunRepository) TakeRunRequests(ctx context.Context, names []string) ([]string, error) {
|
||||
rows, err := r.db.Query(ctx, `
|
||||
UPDATE scheduled_job_runs SET run_requested_at = NULL, updated_at = now()
|
||||
WHERE name = $1 AND run_requested_at IS NOT NULL AND retired_at IS NULL
|
||||
`, name)
|
||||
WHERE name = ANY($1) AND run_requested_at IS NOT NULL AND retired_at IS NULL
|
||||
RETURNING name
|
||||
`, names)
|
||||
if err != nil {
|
||||
return false, err
|
||||
return nil, err
|
||||
}
|
||||
return tag.RowsAffected() > 0, nil
|
||||
return pgx.CollectRows(rows, pgx.RowTo[string])
|
||||
}
|
||||
|
||||
func (r *jobRunRepository) List(ctx context.Context) ([]models.ScheduledJobRun, error) {
|
||||
|
||||
@@ -179,13 +179,8 @@ func (r *linkClickRepository) ListPendingAnnouncements(ctx context.Context, befo
|
||||
}
|
||||
|
||||
func (r *linkClickRepository) Cleanup(ctx context.Context, olderThanDays int) (int64, error) {
|
||||
tag, err := r.db.Exec(ctx,
|
||||
`DELETE FROM email_link_clicks WHERE clicked_at < NOW() - $1 * INTERVAL '1 day'`,
|
||||
olderThanDays)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return tag.RowsAffected(), nil
|
||||
return DeleteInBatches(ctx, r.db, "email_link_clicks",
|
||||
`SELECT ctid FROM email_link_clicks WHERE clicked_at < NOW() - $2 * INTERVAL '1 day' LIMIT $1`, olderThanDays)
|
||||
}
|
||||
|
||||
func (r *linkClickRepository) CountRecentOtherLinks(ctx context.Context, taskID uuid.UUID, ipHash string, linkID *uuid.UUID, destination string, since time.Time) (int, error) {
|
||||
|
||||
@@ -28,6 +28,10 @@ func (r *emailAccountErrorRepository) RecordTransportSuccess(ctx context.Context
|
||||
if operation == models.MailTransportSend && taskID == nil || operation == models.MailTransportSync && taskID != nil {
|
||||
return nil
|
||||
}
|
||||
// A sync report already holds this mailbox's transport lock and account row.
|
||||
if tx, ok := ctx.Value(syncReportKey{}).(pgx.Tx); ok {
|
||||
return recordTransportSuccess(ctx, tx, accountID, operation, at, taskID, generation)
|
||||
}
|
||||
tx, err := beginResultTx(ctx, r.DB)
|
||||
if err != nil {
|
||||
return errx.InternalError()
|
||||
@@ -37,21 +41,42 @@ func (r *emailAccountErrorRepository) RecordTransportSuccess(ctx context.Context
|
||||
return errx.InternalError()
|
||||
}
|
||||
var current uuid.UUID
|
||||
if err := tx.QueryRow(ctx, `SELECT transport_generation FROM email_accounts WHERE id=$1 AND transport_generation=$2 FOR UPDATE`, accountID, generation).Scan(¤t); err != nil {
|
||||
if err := tx.QueryRow(ctx, `SELECT transport_generation FROM email_accounts WHERE id=$1 AND transport_generation=$2 FOR NO KEY UPDATE`, accountID, generation).Scan(¤t); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
return errx.InternalError()
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO email_account_transport_recovery AS existing(email_account_id,operation,recovered_at,source_task_id)
|
||||
SELECT id,$2,$3,$4 FROM email_accounts WHERE id=$1 AND transport_generation=$5 AND $3::timestamptz <= NOW()
|
||||
if xerr := recordTransportSuccess(ctx, tx, accountID, operation, at, taskID, generation); xerr != nil {
|
||||
return xerr
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return errx.InternalError()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// recordTransportSuccess runs under the mailbox's transport lock and account row lock.
|
||||
func recordTransportSuccess(ctx context.Context, tx pgx.Tx, accountID uuid.UUID, operation models.MailTransportOperation, at time.Time, taskID *uuid.UUID, generation uuid.UUID) *errx.Error {
|
||||
// The sync clock is exact, because a late error is judged against it; a report that is not newer writes nothing.
|
||||
var resolve bool
|
||||
err := tx.QueryRow(ctx, `WITH account AS (SELECT id FROM email_accounts WHERE id=$1 AND transport_generation=$5),
|
||||
pending AS (SELECT EXISTS(SELECT 1 FROM email_account_errors WHERE email_account_id=$1 AND resolved_at IS NULL
|
||||
AND error_code IN ('SERVER_UNREACHABLE','CONNECTION_LOST','RESOURCE_NOT_FOUND','IMAP_UNKNOWN','SENDING_TOO_FAST','QUOTA_EXCEEDED')) AS open),
|
||||
recovered AS (INSERT INTO email_account_transport_recovery AS existing(email_account_id,operation,recovered_at,source_task_id)
|
||||
SELECT id,$2,$3,$4 FROM account WHERE $3::timestamptz <= NOW()
|
||||
AND ($2='sync' OR EXISTS(SELECT 1 FROM tasks WHERE id=$4 AND email_account_id=$1 AND send_result_state='sent'))
|
||||
ON CONFLICT(email_account_id,operation) DO UPDATE
|
||||
SET recovered_at=GREATEST(existing.recovered_at,EXCLUDED.recovered_at),
|
||||
source_task_id=CASE WHEN EXCLUDED.recovered_at >= existing.recovered_at THEN EXCLUDED.source_task_id ELSE existing.source_task_id END`, accountID, operation, at.UTC(), taskID, generation)
|
||||
source_task_id=CASE WHEN EXCLUDED.recovered_at >= existing.recovered_at THEN EXCLUDED.source_task_id ELSE existing.source_task_id END
|
||||
WHERE existing.recovered_at < EXCLUDED.recovered_at OR EXCLUDED.operation<>'sync')
|
||||
SELECT EXISTS(SELECT 1 FROM account) AND (SELECT open FROM pending)`, accountID, operation, at.UTC(), taskID, generation).Scan(&resolve)
|
||||
if err != nil {
|
||||
return errx.InternalError()
|
||||
}
|
||||
if !resolve {
|
||||
return nil
|
||||
}
|
||||
_, err = tx.Exec(ctx, `UPDATE email_account_errors report SET resolved_at=recovery.recovered_at,resolved_by=$2 || ' recovered'
|
||||
FROM email_account_transport_recovery recovery, email_accounts account
|
||||
WHERE report.email_account_id=$1 AND report.operation=$2 AND report.resolved_at IS NULL
|
||||
@@ -76,9 +101,6 @@ func (r *emailAccountErrorRepository) RecordTransportSuccess(ctx context.Context
|
||||
if err != nil {
|
||||
return errx.InternalError()
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return errx.InternalError()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -62,43 +63,39 @@ func (r *pgEmailMessageMapRepository) AdmitArrival(ctx context.Context, data Ema
|
||||
if err != nil {
|
||||
return arrivalFailure("payload_encryption", err)
|
||||
}
|
||||
tx, err := r.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return arrivalFailure("database_begin", err)
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
// Recheck and lock ownership after crypto, without nesting key-store I/O in the transaction.
|
||||
var owned uuid.UUID
|
||||
if err = tx.QueryRow(ctx, `SELECT id FROM email_accounts WHERE id=$1 AND user_id=$2 AND organization_id=$3 FOR SHARE`, email, user, org).Scan(&owned); err != nil {
|
||||
return arrivalOwnershipFailure("mailbox_ownership_recheck", err)
|
||||
}
|
||||
// Recheck and lock ownership after crypto, and write the map and the outbox row as one statement.
|
||||
// A retry after an ambiguous response adopts the first canonical identity.
|
||||
inserted, err := tx.Exec(ctx, `INSERT INTO email_message_map(user_id,email_id,message_id,id,thread_id)
|
||||
VALUES($1,$2,$3,$4,$5) ON CONFLICT DO NOTHING`, user, email, data.MessageID, id, data.ThreadID)
|
||||
var owned, queued bool
|
||||
err = r.db.QueryRow(ctx, `WITH owner AS (
|
||||
SELECT id FROM email_accounts WHERE id=$2 AND user_id=$1 AND organization_id=$3 FOR SHARE
|
||||
), mapped AS (
|
||||
INSERT INTO email_message_map(user_id,email_id,message_id,id,thread_id)
|
||||
SELECT $1::uuid,$2::uuid,$4::text,$5::uuid,$6::text FROM owner ON CONFLICT DO NOTHING RETURNING 1
|
||||
), queued AS (
|
||||
INSERT INTO sync_arrival_outbox(user_id,email_id,organization_id,message_id,id,payload)
|
||||
SELECT $1::uuid,$2::uuid,$3::uuid,$4::text,$5::uuid,$7::text FROM mapped RETURNING 1
|
||||
)
|
||||
SELECT EXISTS(SELECT 1 FROM owner), EXISTS(SELECT 1 FROM queued)`,
|
||||
user, email, org, data.MessageID, id, data.ThreadID, payload).Scan(&owned, &queued)
|
||||
if err != nil {
|
||||
return arrivalFailure("mapping_write", err)
|
||||
}
|
||||
if inserted.RowsAffected() != 0 {
|
||||
_, err = tx.Exec(ctx, `INSERT INTO sync_arrival_outbox(user_id,email_id,organization_id,message_id,id,payload)
|
||||
VALUES($1,$2,$3,$4,$5,$6)`, user, email, org, data.MessageID, id, payload)
|
||||
if err != nil {
|
||||
return arrivalFailure("outbox_write", err)
|
||||
}
|
||||
} else {
|
||||
var pending bool
|
||||
err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM email_message_map m
|
||||
JOIN sync_arrival_outbox o USING(user_id,email_id,message_id,id)
|
||||
WHERE m.user_id=$1 AND m.email_id=$2 AND m.message_id=$3 AND o.organization_id=$4)`, user, email, data.MessageID, org).Scan(&pending)
|
||||
if err != nil {
|
||||
return arrivalFailure("durability_check", err)
|
||||
}
|
||||
// Legacy, deleted and already-delivered maps have no durable admission proof.
|
||||
if !pending {
|
||||
return ErrArrivalAdmissionUnconfirmed
|
||||
}
|
||||
if !owned {
|
||||
return arrivalOwnershipFailure("mailbox_ownership_recheck", pgx.ErrNoRows)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return arrivalFailure("database_commit", err)
|
||||
if queued {
|
||||
return nil
|
||||
}
|
||||
var durable bool
|
||||
err = r.db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM email_message_map m
|
||||
JOIN sync_arrival_outbox o USING(user_id,email_id,message_id,id)
|
||||
WHERE m.user_id=$1 AND m.email_id=$2 AND m.message_id=$3 AND o.organization_id=$4)`, user, email, data.MessageID, org).Scan(&durable)
|
||||
if err != nil {
|
||||
return arrivalFailure("durability_check", err)
|
||||
}
|
||||
// Legacy, deleted and already-delivered maps have no durable admission proof.
|
||||
if !durable {
|
||||
return ErrArrivalAdmissionUnconfirmed
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -124,14 +121,30 @@ func (r *pgEmailMessageMapRepository) HasPendingArrival(ctx context.Context, use
|
||||
return pending, err
|
||||
}
|
||||
|
||||
// arrivalBatch is how many stored arrivals one claim leases; the lease outlives the 30 second pass.
|
||||
const arrivalBatch = 32
|
||||
|
||||
// DeliverArrivals invokes the existing consumer handlers, retaining every failed stage.
|
||||
func (r *pgEmailMessageMapRepository) DeliverArrivals(ctx context.Context, deliver func(context.Context, models.JobEventType, any) error) error {
|
||||
return deliverArrivalBatch(ctx, func() (bool, error) { return r.deliverArrival(ctx, nil, deliver) })
|
||||
claimed, err := r.claimArrivals(ctx, nil, arrivalBatch)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
next := 0
|
||||
err = deliverArrivalBatch(ctx, func() (bool, error) {
|
||||
if next == len(claimed) {
|
||||
return false, nil
|
||||
}
|
||||
next++
|
||||
return true, r.deliverClaimed(ctx, claimed[next-1], deliver)
|
||||
})
|
||||
r.releaseArrivals(claimed[next:])
|
||||
return err
|
||||
}
|
||||
|
||||
func deliverArrivalBatch(ctx context.Context, deliverOne func() (bool, error)) error {
|
||||
var first error
|
||||
for i := 0; i < 32; i++ {
|
||||
for i := 0; i < arrivalBatch; i++ {
|
||||
found, err := deliverOne()
|
||||
if err != nil && first == nil {
|
||||
first = err
|
||||
@@ -151,38 +164,90 @@ func (r *pgEmailMessageMapRepository) DeliverPendingArrival(ctx context.Context,
|
||||
if user == uuid.Nil || email == uuid.Nil || id == uuid.Nil {
|
||||
return false, errors.New("invalid pending arrival identity")
|
||||
}
|
||||
return r.deliverArrival(ctx, &arrivalIdentity{user: user, email: email, id: id}, deliver)
|
||||
}
|
||||
|
||||
func (r *pgEmailMessageMapRepository) deliverArrival(ctx context.Context, target *arrivalIdentity, deliver func(context.Context, models.JobEventType, any) error) (bool, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
var user, email, org, lease uuid.UUID
|
||||
var key, payload string
|
||||
var stage int
|
||||
scope := ""
|
||||
var args []any
|
||||
if target != nil {
|
||||
scope = " AND o.user_id=$1 AND o.email_id=$2 AND o.id=$3"
|
||||
args = []any{target.user, target.email, target.id}
|
||||
}
|
||||
// Claim without retaining a connection while handlers use their repositories.
|
||||
finish := arrivaldiag.Begin(ctx, arrivaldiag.Claim)
|
||||
err := r.db.QueryRow(ctx, `WITH candidate AS (SELECT o.user_id,o.email_id,o.message_id
|
||||
FROM sync_arrival_outbox o JOIN email_accounts a ON a.id=o.email_id AND a.user_id=o.user_id AND a.organization_id=o.organization_id
|
||||
WHERE o.retry_at<=now() AND (o.locked_until IS NULL OR o.locked_until<now())`+scope+`
|
||||
ORDER BY o.retry_at,o.created_at LIMIT 1 FOR UPDATE OF o SKIP LOCKED)
|
||||
UPDATE sync_arrival_outbox o SET lease=gen_random_uuid(),locked_until=now()+interval '1 minute'
|
||||
FROM candidate c WHERE o.user_id=c.user_id AND o.email_id=c.email_id AND o.message_id=c.message_id
|
||||
RETURNING o.user_id,o.email_id,o.organization_id,o.message_id,o.payload,o.stage,o.lease`, args...).Scan(&user, &email, &org, &key, &payload, &stage, &lease)
|
||||
finish()
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
claimed, err := r.claimArrivals(ctx, &arrivalIdentity{user: user, email: email, id: id}, 1)
|
||||
if err != nil || len(claimed) == 0 {
|
||||
return false, err
|
||||
}
|
||||
finish = arrivaldiag.Begin(ctx, arrivaldiag.KeyLookup)
|
||||
return true, r.deliverClaimed(ctx, claimed[0], deliver)
|
||||
}
|
||||
|
||||
type claimedArrival struct {
|
||||
user, email, org, lease uuid.UUID
|
||||
key, payload string
|
||||
stage int
|
||||
}
|
||||
|
||||
// claimArrivals leases up to limit due arrivals without holding a connection while handlers run.
|
||||
func (r *pgEmailMessageMapRepository) claimArrivals(ctx context.Context, target *arrivalIdentity, limit int) ([]claimedArrival, error) {
|
||||
scope := ""
|
||||
args := []any{limit}
|
||||
if target != nil {
|
||||
scope = " AND o.user_id=$2 AND o.email_id=$3 AND o.id=$4"
|
||||
args = append(args, target.user, target.email, target.id)
|
||||
}
|
||||
finish := arrivaldiag.Begin(ctx, arrivaldiag.Claim)
|
||||
defer finish()
|
||||
rows, err := r.db.Query(ctx, `WITH candidate AS (SELECT o.user_id,o.email_id,o.message_id
|
||||
FROM sync_arrival_outbox o JOIN email_accounts a ON a.id=o.email_id AND a.user_id=o.user_id AND a.organization_id=o.organization_id
|
||||
WHERE o.retry_at<=now() AND (o.locked_until IS NULL OR o.locked_until<now())`+scope+`
|
||||
ORDER BY o.retry_at,o.created_at LIMIT $1 FOR UPDATE OF o SKIP LOCKED)
|
||||
UPDATE sync_arrival_outbox o SET lease=gen_random_uuid(),locked_until=now()+interval '1 minute'
|
||||
FROM candidate c WHERE o.user_id=c.user_id AND o.email_id=c.email_id AND o.message_id=c.message_id
|
||||
RETURNING o.user_id,o.email_id,o.organization_id,o.message_id,o.payload,o.stage,o.lease,o.retry_at,o.created_at`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
type ordered struct {
|
||||
claimedArrival
|
||||
retryAt, createdAt time.Time
|
||||
}
|
||||
var out []ordered
|
||||
for rows.Next() {
|
||||
var c ordered
|
||||
if err := rows.Scan(&c.user, &c.email, &c.org, &c.key, &c.payload, &c.stage, &c.lease, &c.retryAt, &c.createdAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, c)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// RETURNING carries no order; deliver oldest first as the claim chose them.
|
||||
slices.SortFunc(out, func(a, b ordered) int {
|
||||
if c := a.retryAt.Compare(b.retryAt); c != 0 {
|
||||
return c
|
||||
}
|
||||
return a.createdAt.Compare(b.createdAt)
|
||||
})
|
||||
claimed := make([]claimedArrival, len(out))
|
||||
for i := range out {
|
||||
claimed[i] = out[i].claimedArrival
|
||||
}
|
||||
return claimed, nil
|
||||
}
|
||||
|
||||
// releaseArrivals hands back leases a pass ran out of time to use.
|
||||
func (r *pgEmailMessageMapRepository) releaseArrivals(claimed []claimedArrival) {
|
||||
if len(claimed) == 0 {
|
||||
return
|
||||
}
|
||||
users, emails, keys, leases := make([]uuid.UUID, len(claimed)), make([]uuid.UUID, len(claimed)), make([]string, len(claimed)), make([]uuid.UUID, len(claimed))
|
||||
for i, c := range claimed {
|
||||
users[i], emails[i], keys[i], leases[i] = c.user, c.email, c.key, c.lease
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_, _ = r.db.Exec(ctx, `UPDATE sync_arrival_outbox o SET locked_until=NULL
|
||||
FROM unnest($1::uuid[],$2::uuid[],$3::text[],$4::uuid[]) AS c(user_id,email_id,message_id,lease)
|
||||
WHERE o.user_id=c.user_id AND o.email_id=c.email_id AND o.message_id=c.message_id AND o.lease=c.lease`, users, emails, keys, leases)
|
||||
}
|
||||
|
||||
func (r *pgEmailMessageMapRepository) deliverClaimed(ctx context.Context, c claimedArrival, deliver func(context.Context, models.JobEventType, any) error) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
user, email, org, lease, key, payload, stage := c.user, c.email, c.org, c.lease, c.key, c.payload, c.stage
|
||||
finish := arrivaldiag.Begin(ctx, arrivaldiag.KeyLookup)
|
||||
sealed, err := r.cipher.Cipher(ctx, org)
|
||||
finish()
|
||||
var raw string
|
||||
@@ -208,6 +273,12 @@ func (r *pgEmailMessageMapRepository) deliverArrival(ctx context.Context, target
|
||||
{models.JobEventTypeInboundBounce, pending.Bounce, pending.Bounce != nil, arrivaldiag.Bounce},
|
||||
{models.JobEventTypeInboundComplaint, pending.Complaint, pending.Complaint != nil, arrivaldiag.Complaint},
|
||||
}
|
||||
last := 0
|
||||
for i, e := range events {
|
||||
if e.present {
|
||||
last = i
|
||||
}
|
||||
}
|
||||
for stage < len(events) {
|
||||
e := events[stage]
|
||||
if e.present {
|
||||
@@ -219,12 +290,16 @@ func (r *pgEmailMessageMapRepository) deliverArrival(ctx context.Context, target
|
||||
}
|
||||
}
|
||||
stage++
|
||||
// Only a delivered stage with a later one still to run needs a checkpoint; the delete retires the rest.
|
||||
if !e.present || stage > last {
|
||||
continue
|
||||
}
|
||||
finish = arrivaldiag.Begin(ctx, arrivaldiag.Checkpoint)
|
||||
_, updateErr := r.db.Exec(ctx, `UPDATE sync_arrival_outbox SET stage=$5
|
||||
WHERE user_id=$1 AND email_id=$2 AND message_id=$3 AND lease=$4`, user, email, key, lease, stage)
|
||||
finish()
|
||||
if updateErr != nil {
|
||||
return true, updateErr
|
||||
return updateErr
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -238,8 +313,8 @@ func (r *pgEmailMessageMapRepository) deliverArrival(ctx context.Context, target
|
||||
WHERE user_id=$1 AND email_id=$2 AND message_id=$3 AND lease=$4`, user, email, key, lease)
|
||||
finish()
|
||||
if updateErr != nil {
|
||||
return true, updateErr
|
||||
return updateErr
|
||||
}
|
||||
}
|
||||
return true, err
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
const (
|
||||
// PruneBatch is how many rows one delete statement removes.
|
||||
PruneBatch = 5000
|
||||
// prunePause lets autovacuum, replication and live writes in between batches.
|
||||
prunePause = 50 * time.Millisecond
|
||||
)
|
||||
|
||||
// DeleteInBatches runs a ctid-selecting delete until it removes fewer than a
|
||||
// full batch. selectCtids is `SELECT ctid FROM t WHERE ... LIMIT $1` with the
|
||||
// batch size as $1 and its own arguments after it.
|
||||
func DeleteInBatches(ctx context.Context, db *pgxpool.Pool, table, selectCtids string, args ...any) (int64, error) {
|
||||
query := `DELETE FROM ` + table + ` WHERE ctid = ANY(ARRAY(` + selectCtids + `))`
|
||||
var total int64
|
||||
for {
|
||||
tag, err := db.Exec(ctx, query, append([]any{PruneBatch}, args...)...)
|
||||
if err != nil {
|
||||
return total, err
|
||||
}
|
||||
total += tag.RowsAffected()
|
||||
if tag.RowsAffected() < PruneBatch {
|
||||
return total, nil
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return total, ctx.Err()
|
||||
case <-time.After(prunePause):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TableRetentionRepository prunes history that has a retention window and no
|
||||
// owner of its own: feeds, logs and finished bookkeeping rows.
|
||||
type TableRetentionRepository struct {
|
||||
db *pgxpool.Pool
|
||||
}
|
||||
|
||||
// NewTableRetentionRepository builds the repository.
|
||||
func NewTableRetentionRepository(db *pgxpool.Pool) *TableRetentionRepository {
|
||||
return &TableRetentionRepository{db: db}
|
||||
}
|
||||
|
||||
// PruneCampaignLogs drops campaign activity-feed entries older than before.
|
||||
func (r *TableRetentionRepository) PruneCampaignLogs(ctx context.Context, before time.Time) (int64, error) {
|
||||
return DeleteInBatches(ctx, r.db, "campaign_logs",
|
||||
`SELECT ctid FROM campaign_logs WHERE created_at < $2 LIMIT $1`, before)
|
||||
}
|
||||
|
||||
// PruneNotifications drops notifications older than before, except one still owed an email.
|
||||
func (r *TableRetentionRepository) PruneNotifications(ctx context.Context, before time.Time) (int64, error) {
|
||||
return DeleteInBatches(ctx, r.db, "notifications",
|
||||
`SELECT ctid FROM notifications WHERE created_at < $2
|
||||
AND email_state NOT IN ('pending', 'sending') LIMIT $1`, before)
|
||||
}
|
||||
|
||||
// PruneWebhookDeliveries drops settled deliveries last touched before before; one still retrying stays.
|
||||
func (r *TableRetentionRepository) PruneWebhookDeliveries(ctx context.Context, before time.Time) (int64, error) {
|
||||
return DeleteInBatches(ctx, r.db, "webhook_deliveries",
|
||||
`SELECT ctid FROM webhook_deliveries WHERE status IN ('delivered', 'failed', 'abandoned')
|
||||
AND updated_at < $2 LIMIT $1`, before)
|
||||
}
|
||||
|
||||
// PruneWorkerHealthSamples drops worker health samples older than before.
|
||||
func (r *TableRetentionRepository) PruneWorkerHealthSamples(ctx context.Context, before time.Time) (int64, error) {
|
||||
return DeleteInBatches(ctx, r.db, "worker_health_samples",
|
||||
`SELECT ctid FROM worker_health_samples WHERE observed_at < $2 LIMIT $1`, before)
|
||||
}
|
||||
|
||||
// PruneDeliveredSendResultEffects drops send-result effects delivered before before. An effect whose
|
||||
// task could still apply a result again (not applied, or dead-lettered and repairable) stays, so it is never re-sent.
|
||||
func (r *TableRetentionRepository) PruneDeliveredSendResultEffects(ctx context.Context, before time.Time) (int64, error) {
|
||||
return DeleteInBatches(ctx, r.db, "send_result_effects",
|
||||
`SELECT e.ctid FROM send_result_effects e WHERE e.delivered_at IS NOT NULL AND e.delivered_at < $2
|
||||
AND NOT EXISTS (SELECT 1 FROM tasks t WHERE t.id = e.task_id
|
||||
AND (t.send_result_applied_at IS NULL OR t.status = 'dead_lettered'))
|
||||
LIMIT $1`, before)
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ancient is older than any fixture another live test writes, so a prune in
|
||||
// a shared test database only reaches this test's rows.
|
||||
const ancientDays = 4000
|
||||
|
||||
func TestLiveTableRetentionPrunesOnlyPastWindow(t *testing.T) {
|
||||
_, pool := liveContactDB(t)
|
||||
ctx := context.Background()
|
||||
user, org, campaign, worker, endpoint, account, task, repairable := uuid.New(), uuid.New(), uuid.New(), uuid.New(), uuid.New(), uuid.New(), uuid.New(), uuid.New()
|
||||
exec := func(query string, args ...any) {
|
||||
t.Helper()
|
||||
if _, err := pool.Exec(ctx, query, args...); err != nil {
|
||||
t.Fatalf("fixture %q: %v", query[:min(60, len(query))], err)
|
||||
}
|
||||
}
|
||||
exec(`INSERT INTO users (id, first_name, last_name, email) VALUES ($1, 'Table', 'Retention', $2)`, user, "table-retention-"+uuid.NewString()+"@example.test")
|
||||
exec(`INSERT INTO organizations (id, name, owner_user_id) VALUES ($1, 'Table retention', $2)`, org, user)
|
||||
exec(`INSERT INTO campaigns (id, user_id, organization_id, name, description, days, status, updated_at, created_at)
|
||||
VALUES ($1, $2, $3, 'Retention', '', 62, 'active', NOW(), NOW())`, campaign, user, org)
|
||||
exec(`INSERT INTO fleet_nodes (id, role, name) VALUES ($1, 'worker', 'table-retention')`, worker)
|
||||
exec(`INSERT INTO workers (id) VALUES ($1)`, worker)
|
||||
exec(`INSERT INTO webhook_endpoints (id, organization_id, url, secret) VALUES ($1, $2, 'https://example.test/hook', 's')`, endpoint, org)
|
||||
exec(`INSERT INTO email_accounts (id, user_id, organization_id, email, name, signature_plain, signature_html, provider)
|
||||
VALUES ($1, $2, $3, $4, 'Retention', '', '', 'smtp_imap')`, account, user, org, "table-retention-"+uuid.NewString()+"@example.test")
|
||||
exec(`INSERT INTO tasks (id, task_type, email_account_id, status, message_id, send_result_state, send_result_applied_at)
|
||||
VALUES ($1, 'campaign', $3, 'completed', '<retention@x>', 'sent', NOW()), ($2, 'campaign', $3, 'dead_lettered', '<repairable@x>', 'sent', NOW())`, task, repairable, account)
|
||||
t.Cleanup(func() {
|
||||
c := context.Background()
|
||||
_, _ = pool.Exec(c, `DELETE FROM tasks WHERE id = ANY($1)`, []uuid.UUID{task, repairable})
|
||||
_, _ = pool.Exec(c, `DELETE FROM email_accounts WHERE id = $1`, account)
|
||||
_, _ = pool.Exec(c, `DELETE FROM workers WHERE id = $1`, worker)
|
||||
_, _ = pool.Exec(c, `DELETE FROM fleet_nodes WHERE id = $1`, worker)
|
||||
_, _ = pool.Exec(c, `DELETE FROM organizations WHERE id = $1`, org)
|
||||
_, _ = pool.Exec(c, `DELETE FROM users WHERE id = $1`, user)
|
||||
})
|
||||
|
||||
old := time.Now().AddDate(0, 0, -ancientDays-1)
|
||||
fresh := time.Now()
|
||||
exec(`INSERT INTO campaign_logs (campaign_id, event_type, created_at) VALUES ($1, 'old', $2), ($1, 'fresh', $3)`, campaign, old, fresh)
|
||||
exec(`INSERT INTO notifications (user_id, organization_id, category, title, created_at, email_state)
|
||||
VALUES ($1, $2, 'c', 'old', $3, 'none'), ($1, $2, 'c', 'owed', $3, 'pending'), ($1, $2, 'c', 'fresh', $4, 'none')`, user, org, old, fresh)
|
||||
exec(`INSERT INTO webhook_deliveries (endpoint_id, organization_id, event_type, event_id, payload, status, updated_at)
|
||||
VALUES ($1, $2, 'old', gen_random_uuid(), '{}', 'delivered', $3),
|
||||
($1, $2, 'retrying', gen_random_uuid(), '{}', 'pending', $3),
|
||||
($1, $2, 'fresh', gen_random_uuid(), '{}', 'abandoned', $4)`, endpoint, org, old, fresh)
|
||||
exec(`INSERT INTO worker_health_samples (worker_id, observed_at) VALUES ($1, $2), ($1, $3)`, worker, old, fresh)
|
||||
exec(`INSERT INTO send_result_effects (task_id, effect_key, organization_id, kind, payload, delivered_at)
|
||||
VALUES ($1, 'old', $2, 'webhook', '{}', $3), ($1, 'undelivered', $2, 'webhook', '{}', NULL), ($1, 'fresh', $2, 'webhook', '{}', $4),
|
||||
($5, 'old', $2, 'webhook', '{}', $3)`, task, org, old, fresh, repairable)
|
||||
// More than one batch, so the loop has to come back for the rest.
|
||||
exec(`INSERT INTO worker_health_samples (worker_id, observed_at) SELECT $1, $2::timestamptz - g * interval '1 second' FROM generate_series(1, $3::int) g`, worker, old, PruneBatch+7)
|
||||
|
||||
repo := NewTableRetentionRepository(pool)
|
||||
before := time.Now().AddDate(0, 0, -ancientDays)
|
||||
for name, prune := range map[string]func(context.Context, time.Time) (int64, error){
|
||||
"campaign_logs": repo.PruneCampaignLogs, "notifications": repo.PruneNotifications, "webhook_deliveries": repo.PruneWebhookDeliveries,
|
||||
"worker_health_samples": repo.PruneWorkerHealthSamples,
|
||||
"send_result_effects": repo.PruneDeliveredSendResultEffects,
|
||||
} {
|
||||
if _, err := prune(ctx, before); err != nil {
|
||||
t.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
count := func(query string, args ...any) int {
|
||||
t.Helper()
|
||||
var n int
|
||||
if err := pool.QueryRow(ctx, query, args...).Scan(&n); err != nil {
|
||||
t.Fatalf("count: %v", err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
for _, c := range []struct {
|
||||
what string
|
||||
query string
|
||||
arg uuid.UUID
|
||||
want int
|
||||
}{
|
||||
{"campaign feed keeps only the fresh entry", `SELECT count(*) FROM campaign_logs WHERE campaign_id = $1 AND event_type = 'fresh'`, campaign, 1},
|
||||
{"campaign feed drops the old entry", `SELECT count(*) FROM campaign_logs WHERE campaign_id = $1`, campaign, 1},
|
||||
{"notifications keep the fresh one and the one owed an email", `SELECT count(*) FROM notifications WHERE user_id = $1 AND title IN ('fresh', 'owed')`, user, 2},
|
||||
{"notifications drop the old one", `SELECT count(*) FROM notifications WHERE user_id = $1`, user, 2},
|
||||
{"webhook log keeps the retrying and fresh deliveries", `SELECT count(*) FROM webhook_deliveries WHERE endpoint_id = $1 AND event_type IN ('retrying', 'fresh')`, endpoint, 2},
|
||||
{"webhook log drops the old settled delivery", `SELECT count(*) FROM webhook_deliveries WHERE endpoint_id = $1`, endpoint, 2},
|
||||
{"health samples keep only the fresh one, across batches", `SELECT count(*) FROM worker_health_samples WHERE worker_id = $1`, worker, 1},
|
||||
{"effects keep the undelivered and fresh ones", `SELECT count(*) FROM send_result_effects WHERE task_id = $1`, task, 2},
|
||||
{"effects keep an old one whose dead-lettered task can apply its result again", `SELECT count(*) FROM send_result_effects WHERE task_id = $1`, repairable, 1},
|
||||
} {
|
||||
if got := count(c.query, c.arg); got != c.want {
|
||||
t.Errorf("%s: got %d rows, want %d", c.what, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Each prune's row selection is served by an index, so a prune never scans
|
||||
// the whole table it trims.
|
||||
func TestLiveRetentionPrunesUseTheirIndexes(t *testing.T) {
|
||||
_, pool := liveContactDB(t)
|
||||
ctx := context.Background()
|
||||
conn, err := pool.Acquire(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Release()
|
||||
if _, err := conn.Exec(ctx, `SET enable_seqscan = off`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _, _ = conn.Exec(context.Background(), `RESET enable_seqscan`) }()
|
||||
|
||||
for _, c := range []struct{ query, index string }{
|
||||
{`SELECT ctid FROM email_opens WHERE opened_at < NOW() - 30 * INTERVAL '1 day' LIMIT 5000`, "idx_email_opens_opened_at"},
|
||||
{`SELECT ctid FROM email_link_clicks WHERE clicked_at < NOW() - 30 * INTERVAL '1 day' LIMIT 5000`, "idx_email_link_clicks_clicked_at"},
|
||||
{`SELECT ctid FROM campaign_logs WHERE created_at < NOW() LIMIT 5000`, "idx_campaign_logs_created"},
|
||||
{`SELECT ctid FROM notifications WHERE created_at < NOW() AND email_state NOT IN ('pending', 'sending') LIMIT 5000`, "idx_notifications_created"},
|
||||
{`SELECT ctid FROM webhook_deliveries WHERE status IN ('delivered', 'failed', 'abandoned') AND updated_at < NOW() LIMIT 5000`, "idx_webhook_deliveries_settled"},
|
||||
{`SELECT ctid FROM worker_health_samples WHERE observed_at < NOW() LIMIT 5000`, "idx_worker_health_samples_observed"},
|
||||
// Either index answers the one-hour window; which one depends on the table's statistics.
|
||||
{`SELECT worker_id, sum(sends_attempted) FROM worker_health_samples WHERE observed_at > now() - interval '1 hour' GROUP BY worker_id`, "idx_worker_health_samples_"},
|
||||
{`SELECT e.ctid FROM send_result_effects e WHERE e.delivered_at IS NOT NULL AND e.delivered_at < NOW()
|
||||
AND NOT EXISTS (SELECT 1 FROM tasks t WHERE t.id = e.task_id AND (t.send_result_applied_at IS NULL OR t.status = 'dead_lettered')) LIMIT 5000`, "idx_send_result_effects_delivered"},
|
||||
{`SELECT internal_id FROM warmup_received WHERE email_account_id = '00000000-0000-0000-0000-000000000001' AND retired_at IS NULL AND created_at < NOW() ORDER BY created_at LIMIT 100`, "idx_warmup_received_account_live"},
|
||||
{`SELECT token FROM warmup_tokens WHERE sender_account_id = '00000000-0000-0000-0000-000000000001' AND sent_message_id <> '' AND sent_retired_at IS NULL AND created_at < NOW() ORDER BY created_at LIMIT 100`, "idx_warmup_tokens_sender_live"},
|
||||
} {
|
||||
rows, err := conn.Query(ctx, `EXPLAIN `+c.query)
|
||||
if err != nil {
|
||||
t.Fatalf("explain %q: %v", c.query, err)
|
||||
}
|
||||
var plan strings.Builder
|
||||
for rows.Next() {
|
||||
var line string
|
||||
if err := rows.Scan(&line); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
plan.WriteString(line + "\n")
|
||||
}
|
||||
rows.Close()
|
||||
if !strings.Contains(plan.String(), c.index) || strings.Contains(plan.String(), "Seq Scan") {
|
||||
t.Errorf("%s is not used by %q:\n%s", c.index, c.query, plan.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -145,11 +145,13 @@ type TaskRepository interface {
|
||||
// whole sender pool. Accounts that have never sent are absent from the map.
|
||||
GetLastSendTimes(ctx context.Context, accountIDs []uuid.UUID, taskType string) (map[uuid.UUID]time.Time, error)
|
||||
GetBookedSendsForAccount(ctx context.Context, accountID uuid.UUID, around time.Time) ([]Task, error)
|
||||
// ListDuePendingTaskIDs returns pending tasks whose scheduled_at has passed,
|
||||
// oldest first, capped at limit. Drives the in-process (TASKS_PROVIDER=local)
|
||||
// dispatcher, which fires each due task by id.
|
||||
ListDuePendingTaskIDs(ctx context.Context, limit int) ([]uuid.UUID, error)
|
||||
RecordDispatchAttempt(ctx context.Context, taskID uuid.UUID, failed bool, retryAt time.Time) error
|
||||
// ClaimDueTaskIDs leases pending tasks whose slot has arrived, oldest first,
|
||||
// capped at limit. Drives the in-process (TASKS_PROVIDER=local) dispatcher,
|
||||
// which fires each claimed task by id. The returned claim is the lease's end,
|
||||
// and identifies the claim when it is recorded or released.
|
||||
ClaimDueTaskIDs(ctx context.Context, limit int, lease time.Duration) ([]uuid.UUID, time.Time, error)
|
||||
RecordDispatchAttempt(ctx context.Context, taskID uuid.UUID, claim time.Time, failed bool, retryAt time.Time) error
|
||||
ReleaseDispatchClaims(ctx context.Context, taskIDs []uuid.UUID, claim time.Time) error
|
||||
ListOverdueWarmupDispatches(ctx context.Context, now time.Time) ([]MailboxLoadingIncident, error)
|
||||
|
||||
// Update operations
|
||||
@@ -896,47 +898,68 @@ func (r *taskRepository) CancelOverduePendingTasks(ctx context.Context, taskType
|
||||
return tag.RowsAffected(), nil
|
||||
}
|
||||
|
||||
// ListDuePendingTaskIDs returns pending tasks whose slot has arrived, oldest
|
||||
// first. The in-process dispatcher fires each; rows stay pending until their
|
||||
// handler flips the status, so this is safe to call on a short interval.
|
||||
func (r *taskRepository) ListDuePendingTaskIDs(ctx context.Context, limit int) ([]uuid.UUID, error) {
|
||||
// ClaimDueTaskIDs claims up to limit pending tasks whose slot has arrived, oldest
|
||||
// first, for lease. Another replica skips a claimed task until RecordDispatchAttempt
|
||||
// releases it or the lease lapses, so each due task is fired by one dispatcher.
|
||||
func (r *taskRepository) ClaimDueTaskIDs(ctx context.Context, limit int, lease time.Duration) ([]uuid.UUID, time.Time, error) {
|
||||
query := `
|
||||
SELECT id
|
||||
FROM tasks
|
||||
WHERE status = 'pending'
|
||||
AND GREATEST(scheduled_at, COALESCE(dispatch_retry_at, scheduled_at)) <= NOW()
|
||||
ORDER BY GREATEST(scheduled_at, COALESCE(dispatch_retry_at, scheduled_at)), id
|
||||
LIMIT $1
|
||||
UPDATE tasks t
|
||||
SET dispatch_claimed_until = NOW() + make_interval(secs => $2)
|
||||
FROM (
|
||||
SELECT id
|
||||
FROM tasks
|
||||
WHERE status = 'pending'
|
||||
AND GREATEST(scheduled_at, COALESCE(dispatch_retry_at, scheduled_at)) <= NOW()
|
||||
AND (dispatch_claimed_until IS NULL OR dispatch_claimed_until <= NOW())
|
||||
ORDER BY GREATEST(scheduled_at, COALESCE(dispatch_retry_at, scheduled_at)), id
|
||||
LIMIT $1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
) due
|
||||
WHERE t.id = due.id
|
||||
RETURNING t.id, t.dispatch_claimed_until
|
||||
`
|
||||
rows, err := r.db.Query(ctx, query, limit)
|
||||
rows, err := r.db.Query(ctx, query, limit, lease.Seconds())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, time.Time{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var ids []uuid.UUID
|
||||
var claim time.Time
|
||||
for rows.Next() {
|
||||
var id uuid.UUID
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
if err := rows.Scan(&id, &claim); err != nil {
|
||||
return nil, time.Time{}, err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids, rows.Err()
|
||||
return ids, claim, rows.Err()
|
||||
}
|
||||
|
||||
// Retry metadata never changes the send's reservation, outcome, or intended schedule.
|
||||
func (r *taskRepository) RecordDispatchAttempt(ctx context.Context, taskID uuid.UUID, failed bool, retryAt time.Time) error {
|
||||
func (r *taskRepository) RecordDispatchAttempt(ctx context.Context, taskID uuid.UUID, claim time.Time, failed bool, retryAt time.Time) error {
|
||||
// A lease that lapsed and was taken again belongs to the other replica now; only our own claim is cleared.
|
||||
const release = `dispatch_claimed_until=CASE WHEN dispatch_claimed_until=$3 THEN NULL ELSE dispatch_claimed_until END`
|
||||
if failed {
|
||||
_, err := r.db.Exec(ctx, `UPDATE tasks SET dispatch_retry_at=$2,
|
||||
dispatch_failure_since=COALESCE(dispatch_failure_since,NOW()),dispatch_failure_at=NOW()
|
||||
WHERE id=$1 AND status='pending'`, taskID, retryAt)
|
||||
dispatch_failure_since=COALESCE(dispatch_failure_since,NOW()),dispatch_failure_at=NOW(),
|
||||
`+release+`
|
||||
WHERE id=$1 AND status='pending'`, taskID, retryAt, claim)
|
||||
return err
|
||||
}
|
||||
_, err := r.db.Exec(ctx, `UPDATE tasks SET dispatch_retry_at=CASE
|
||||
WHEN status='pending' AND scheduled_at<=NOW() THEN GREATEST(dispatch_retry_at,$2)
|
||||
ELSE NULL END,
|
||||
dispatch_failure_since=NULL,dispatch_failure_at=NULL WHERE id=$1`, taskID, retryAt)
|
||||
dispatch_failure_since=NULL,dispatch_failure_at=NULL,`+release+` WHERE id=$1`, taskID, retryAt, claim)
|
||||
return err
|
||||
}
|
||||
|
||||
// ReleaseDispatchClaims hands claimed tasks that never ran back to the next poll, unless another replica has claimed them since.
|
||||
func (r *taskRepository) ReleaseDispatchClaims(ctx context.Context, taskIDs []uuid.UUID, claim time.Time) error {
|
||||
if len(taskIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
_, err := r.db.Exec(ctx, `UPDATE tasks SET dispatch_claimed_until=NULL WHERE id = ANY($1) AND dispatch_claimed_until = $2`, taskIDs, claim)
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestLiveConcurrentDispatchersNeverClaimTheSameTask(t *testing.T) {
|
||||
_, pool := liveContactDB(t)
|
||||
ctx := t.Context()
|
||||
f := newWarmupUsageFixture(t, pool)
|
||||
base := time.Date(1971, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
ids := make([]uuid.UUID, 40)
|
||||
mine := map[uuid.UUID]bool{}
|
||||
for i := range ids {
|
||||
ids[i] = uuid.New()
|
||||
mine[ids[i]] = true
|
||||
f.exec(`INSERT INTO tasks(id,task_type,email_account_id,status,message_id,scheduled_at) VALUES($1,'warmup',$2,'pending','',$3)`, ids[i], f.account, base.Add(time.Duration(i)*time.Second))
|
||||
}
|
||||
t.Cleanup(func() { _, _ = pool.Exec(t.Context(), `DELETE FROM tasks WHERE id = ANY($1)`, ids) })
|
||||
|
||||
repo := &taskRepository{db: pool}
|
||||
var mu sync.Mutex
|
||||
owner := map[uuid.UUID]int{}
|
||||
var foreign []uuid.UUID
|
||||
claims := map[uuid.UUID]time.Time{}
|
||||
var wg sync.WaitGroup
|
||||
for d := range 2 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for range 40 {
|
||||
got, claim, err := repo.ClaimDueTaskIDs(ctx, 5, time.Minute)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
for _, id := range got {
|
||||
claims[id] = claim
|
||||
if !mine[id] {
|
||||
foreign = append(foreign, id)
|
||||
continue
|
||||
}
|
||||
if prev, seen := owner[id]; seen {
|
||||
t.Errorf("task %s claimed by dispatcher %d and %d", id, prev, d)
|
||||
}
|
||||
owner[id] = d
|
||||
}
|
||||
done := len(owner) == len(ids)
|
||||
mu.Unlock()
|
||||
if done || len(got) == 0 {
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
// Other tests' due tasks share the table; hand theirs back untouched.
|
||||
for _, id := range foreign {
|
||||
if err := repo.ReleaseDispatchClaims(ctx, []uuid.UUID{id}, claims[id]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if len(owner) != len(ids) {
|
||||
t.Fatalf("two dispatchers claimed %d of %d due tasks", len(owner), len(ids))
|
||||
}
|
||||
|
||||
claimable := func() map[uuid.UUID]bool {
|
||||
t.Helper()
|
||||
got, claim, err := repo.ClaimDueTaskIDs(ctx, 100000, time.Minute)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := map[uuid.UUID]bool{}
|
||||
var theirs []uuid.UUID
|
||||
for _, id := range got {
|
||||
if mine[id] {
|
||||
out[id] = true
|
||||
} else {
|
||||
theirs = append(theirs, id)
|
||||
}
|
||||
}
|
||||
if err := repo.ReleaseDispatchClaims(ctx, theirs, claim); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for id := range out {
|
||||
claims[id] = claim
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Every task is leased: a third dispatcher finds none of them.
|
||||
if got := claimable(); len(got) != 0 {
|
||||
t.Fatalf("leased tasks claimed again: %v", got)
|
||||
}
|
||||
|
||||
// A lapsed lease, as left by a replica that died mid-task, is claimed again; a live one is not.
|
||||
lapsed := ids[0]
|
||||
stale := claims[lapsed]
|
||||
f.exec(`UPDATE tasks SET dispatch_claimed_until = NOW() - INTERVAL '1 second' WHERE id = $1`, lapsed)
|
||||
if got := claimable(); len(got) != 1 || !got[lapsed] {
|
||||
t.Fatalf("claimed %v, want only the task whose lease lapsed", got)
|
||||
}
|
||||
|
||||
// The replica whose lease lapsed cannot clear the claim another replica took since.
|
||||
if err := repo.ReleaseDispatchClaims(ctx, []uuid.UUID{lapsed}, stale); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := repo.RecordDispatchAttempt(ctx, lapsed, stale, false, time.Now().Add(-time.Hour)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var held *time.Time
|
||||
if err := pool.QueryRow(ctx, `SELECT dispatch_claimed_until FROM tasks WHERE id = $1`, lapsed).Scan(&held); err != nil || held == nil {
|
||||
t.Fatalf("a stale claim released the current one: %v, %v", held, err)
|
||||
}
|
||||
|
||||
// Recording an attempt releases the claim, and so does handing a claim back.
|
||||
if err := repo.RecordDispatchAttempt(ctx, ids[1], claims[ids[1]], false, time.Now().Add(-time.Hour)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var claimed *time.Time
|
||||
if err := pool.QueryRow(ctx, `SELECT dispatch_claimed_until FROM tasks WHERE id = $1`, ids[1]).Scan(&claimed); err != nil || claimed != nil {
|
||||
t.Fatalf("recorded attempt kept its claim: %v, %v", claimed, err)
|
||||
}
|
||||
for _, id := range ids[2:] {
|
||||
if err := repo.ReleaseDispatchClaims(ctx, []uuid.UUID{id}, claims[id]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if got := claimable(); len(got) != len(ids)-1 || got[lapsed] {
|
||||
t.Fatalf("after release %d of %d tasks claimable, want all but the one still leased", len(got), len(ids)-1)
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
type TrackingDedupeRepository interface {
|
||||
IsProcessed(ctx context.Context, taskID uuid.UUID, eventType, urlHash string) (bool, error)
|
||||
MarkProcessed(ctx context.Context, taskID uuid.UUID, eventType, urlHash string) error
|
||||
Cleanup(ctx context.Context, olderThanDays int) (int64, error)
|
||||
}
|
||||
|
||||
type trackingDedupeRepository struct {
|
||||
@@ -63,18 +62,3 @@ func (r *trackingDedupeRepository) MarkProcessed(ctx context.Context, taskID uui
|
||||
_, err := r.db.Exec(ctx, query, taskID, eventType, urlHash)
|
||||
return err
|
||||
}
|
||||
|
||||
// Cleanup removes old processed tracking events (for scheduled job)
|
||||
func (r *trackingDedupeRepository) Cleanup(ctx context.Context, olderThanDays int) (int64, error) {
|
||||
query := `
|
||||
DELETE FROM tracking_events_processed
|
||||
WHERE processed_at < NOW() - $1 * INTERVAL '1 day'
|
||||
`
|
||||
|
||||
result, err := r.db.Exec(ctx, query, olderThanDays)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
@@ -155,6 +155,9 @@ type UniboxRepository interface {
|
||||
// over message text would only ever work for mail synced from now on.
|
||||
ListMissingBodyText(ctx context.Context, afterID uuid.UUID, limit int) ([]UniboxBodyTarget, error)
|
||||
SetBodyText(ctx context.Context, id uuid.UUID, bodyText string) error
|
||||
// BodyBackfillProgress and SaveBodyBackfillProgress keep the walk's place across restarts.
|
||||
BodyBackfillProgress(ctx context.Context) (UniboxBodyBackfill, error)
|
||||
SaveBodyBackfillProgress(ctx context.Context, p UniboxBodyBackfill) error
|
||||
|
||||
// GroundingByThread and GroundingByAddress return message text for AI
|
||||
// prompts. They are separate from the preview queries because they select
|
||||
@@ -2153,6 +2156,41 @@ func (r *uniboxRepository) ListMissingBodyText(ctx context.Context, afterID uuid
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// uniboxBodyBackfillKey is the admin_settings row holding the backfill's place.
|
||||
const uniboxBodyBackfillKey = "unibox.body_text_backfill"
|
||||
|
||||
// UniboxBodyBackfill is how far the body text backfill has walked, and whether it finished.
|
||||
type UniboxBodyBackfill struct {
|
||||
After uuid.UUID `json:"after"`
|
||||
Done bool `json:"done"`
|
||||
}
|
||||
|
||||
// BodyBackfillProgress returns the stored place, or the start when none is stored.
|
||||
func (r *uniboxRepository) BodyBackfillProgress(ctx context.Context) (UniboxBodyBackfill, error) {
|
||||
var p UniboxBodyBackfill
|
||||
var raw []byte
|
||||
err := r.db.QueryRow(ctx, `SELECT value FROM admin_settings WHERE key = $1`, uniboxBodyBackfillKey).Scan(&raw)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return p, nil
|
||||
}
|
||||
if err != nil {
|
||||
return p, err
|
||||
}
|
||||
return p, json.Unmarshal(raw, &p)
|
||||
}
|
||||
|
||||
// SaveBodyBackfillProgress stores the place reached.
|
||||
func (r *uniboxRepository) SaveBodyBackfillProgress(ctx context.Context, p UniboxBodyBackfill) error {
|
||||
raw, err := json.Marshal(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = r.db.Exec(ctx, `
|
||||
INSERT INTO admin_settings (key, value, updated_at) VALUES ($1, $2, now())
|
||||
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`, uniboxBodyBackfillKey, raw)
|
||||
return err
|
||||
}
|
||||
|
||||
// SetBodyText records the searchable rendering of a message body.
|
||||
func (r *uniboxRepository) SetBodyText(ctx context.Context, id uuid.UUID, bodyText string) error {
|
||||
_, err := r.db.Exec(ctx, `UPDATE unibox_emails SET body_text = $2 WHERE id = $1`, id, bodyText)
|
||||
|
||||
@@ -187,7 +187,7 @@ type WarmupRepository interface {
|
||||
SumWarmupSentSince(ctx context.Context, accountID uuid.UUID, since time.Time) (int, error)
|
||||
|
||||
// Health sweep
|
||||
GetAllParticipantAccountIDs(ctx context.Context) ([]uuid.UUID, error)
|
||||
ListParticipantMemberships(ctx context.Context) ([]WarmupParticipantMembership, error)
|
||||
GetPoolHealthCounts(ctx context.Context) (map[string]int, float64, error)
|
||||
|
||||
// Spam tracking
|
||||
@@ -305,15 +305,16 @@ type WarmupRepository interface {
|
||||
// mailboxes that have a worker to act. ListWarmupSentCopiesToRetire is
|
||||
// the same for the sender's own copy of each send. RetireWarmupReceived
|
||||
// and RetireWarmupSentCopy stamp the row once the deletion is on the bus.
|
||||
ListWarmupMailToRetire(ctx context.Context, defaultDays, limit int) ([]WarmupMailToRetire, error)
|
||||
ListWarmupMailToRetire(ctx context.Context, defaultDays, limit int, skip []uuid.UUID) ([]WarmupMailToRetire, error)
|
||||
RetireWarmupReceived(ctx context.Context, accountID, internalID uuid.UUID) error
|
||||
ListWarmupSentCopiesToRetire(ctx context.Context, defaultDays, limit int) ([]WarmupMailToRetire, error)
|
||||
ListWarmupSentCopiesToRetire(ctx context.Context, defaultDays, limit int, skip []uuid.UUID) ([]WarmupMailToRetire, error)
|
||||
RetireWarmupSentCopy(ctx context.Context, token uuid.UUID) error
|
||||
// PruneWarmupEventsBefore drops per-message records older than before:
|
||||
// tampering events, spam reports, retired receipts, and tokens whose sent
|
||||
// copy is gone. A receipt or token whose mail is still in the mailbox is
|
||||
// kept, so a removal seen later can still be told apart from tampering.
|
||||
PruneWarmupEventsBefore(ctx context.Context, before time.Time) (int64, error)
|
||||
// mailDays is the instance mail window, which a thread turn also outlives.
|
||||
PruneWarmupEventsBefore(ctx context.Context, before time.Time, mailDays int) (int64, error)
|
||||
|
||||
// Appeals (user-facing submission; admin review lives in the admin repo).
|
||||
CreateWarmupAppeal(ctx context.Context, accountID, userID uuid.UUID, reason string) (uuid.UUID, error)
|
||||
@@ -1986,29 +1987,37 @@ func (r *warmupRepository) GetWarmupReceived(ctx context.Context, accountID, int
|
||||
return &w, nil
|
||||
}
|
||||
|
||||
// WarmupRetirePerMailbox bounds one mailbox's share of a retirement run; the sweep skips a mailbox it already served that run.
|
||||
const WarmupRetirePerMailbox = 50
|
||||
|
||||
// ListWarmupMailToRetire lists received warmup copies past their window:
|
||||
// the mailbox's own when it set one, else the instance default handed in as
|
||||
// $1, on active mailboxes that have a worker to act. The provider key comes
|
||||
// from the message map by the internal id, which is what the worker's remove
|
||||
// and flag events are keyed on.
|
||||
func (r *warmupRepository) ListWarmupMailToRetire(ctx context.Context, defaultDays, limit int) ([]WarmupMailToRetire, error) {
|
||||
// and flag events are keyed on. It starts from the mailboxes, so receipts
|
||||
// held by a mailbox that cannot act are never walked.
|
||||
func (r *warmupRepository) ListWarmupMailToRetire(ctx context.Context, defaultDays, limit int, skip []uuid.UUID) ([]WarmupMailToRetire, error) {
|
||||
query := `
|
||||
SELECT ea.user_id, ea.id, ` + actionWorkerSQL("ea") + `, wr.internal_id, wr.message_id,
|
||||
COALESCE(m.message_id, ''), ea.warmup_placement, ea.warmup_folder
|
||||
FROM warmup_received wr
|
||||
JOIN email_accounts ea ON ea.id = wr.email_account_id
|
||||
FROM email_accounts ea
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT r.internal_id, r.message_id, r.created_at FROM warmup_received r
|
||||
WHERE r.email_account_id = ea.id AND r.retired_at IS NULL
|
||||
AND r.created_at < NOW() - make_interval(days => COALESCE(ea.warmup_retention_days, $1))
|
||||
ORDER BY r.created_at
|
||||
LIMIT LEAST($2, ` + strconv.Itoa(WarmupRetirePerMailbox) + `)
|
||||
) wr
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT em.message_id FROM email_message_map em
|
||||
WHERE em.email_id = ea.id AND em.id = wr.internal_id
|
||||
LIMIT 1
|
||||
) m ON true
|
||||
WHERE ea.status = 'active'
|
||||
WHERE ea.status = 'active' AND NOT (ea.id = ANY($3::uuid[]))
|
||||
AND ` + actionRoutableSQL("ea") + `
|
||||
AND wr.retired_at IS NULL
|
||||
AND wr.created_at < NOW() - make_interval(days => COALESCE(ea.warmup_retention_days, $1))
|
||||
ORDER BY wr.created_at
|
||||
LIMIT $2`
|
||||
return r.scanMailToRetire(ctx, query, defaultDays, limit, false)
|
||||
return r.scanMailToRetire(ctx, query, defaultDays, limit, skip, false)
|
||||
}
|
||||
|
||||
// ListWarmupSentCopiesToRetire lists the sender's own copies past their
|
||||
@@ -2017,30 +2026,37 @@ func (r *warmupRepository) ListWarmupMailToRetire(ctx context.Context, defaultDa
|
||||
// senders are left out rather than searched for a message that does not
|
||||
// exist. The map is keyed by the provider's id on Gmail and Graph, so the key
|
||||
// is usually empty there and the worker searches by Message-ID instead.
|
||||
func (r *warmupRepository) ListWarmupSentCopiesToRetire(ctx context.Context, defaultDays, limit int) ([]WarmupMailToRetire, error) {
|
||||
// Like the received side it starts from the mailboxes that can act.
|
||||
func (r *warmupRepository) ListWarmupSentCopiesToRetire(ctx context.Context, defaultDays, limit int, skip []uuid.UUID) ([]WarmupMailToRetire, error) {
|
||||
query := `
|
||||
SELECT ea.user_id, ea.id, ` + actionWorkerSQL("ea") + `, wt.token, wt.sent_message_id,
|
||||
COALESCE(m.message_id, ''), ea.warmup_placement, ea.warmup_folder
|
||||
FROM warmup_tokens wt
|
||||
JOIN email_accounts ea ON ea.id = wt.sender_account_id
|
||||
FROM email_accounts ea
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT t.token, t.sent_message_id, t.created_at FROM warmup_tokens t
|
||||
WHERE t.sender_account_id = ea.id AND t.sent_message_id <> '' AND t.sent_retired_at IS NULL
|
||||
AND t.created_at < NOW() - make_interval(days => COALESCE(ea.warmup_retention_days, $1))
|
||||
ORDER BY t.created_at
|
||||
LIMIT LEAST($2, ` + strconv.Itoa(WarmupRetirePerMailbox) + `)
|
||||
) wt
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT em.message_id FROM email_message_map em
|
||||
WHERE em.email_id = ea.id AND em.message_id = wt.sent_message_id
|
||||
LIMIT 1
|
||||
) m ON true
|
||||
WHERE ea.status = 'active'
|
||||
WHERE ea.status = 'active' AND NOT (ea.id = ANY($3::uuid[]))
|
||||
AND ` + actionRoutableSQL("ea") + `
|
||||
AND ea.provider <> 'smtp_imap'
|
||||
AND wt.sent_message_id <> ''
|
||||
AND wt.sent_retired_at IS NULL
|
||||
AND wt.created_at < NOW() - make_interval(days => COALESCE(ea.warmup_retention_days, $1))
|
||||
ORDER BY wt.created_at
|
||||
LIMIT $2`
|
||||
return r.scanMailToRetire(ctx, query, defaultDays, limit, true)
|
||||
return r.scanMailToRetire(ctx, query, defaultDays, limit, skip, true)
|
||||
}
|
||||
|
||||
func (r *warmupRepository) scanMailToRetire(ctx context.Context, query string, defaultDays, limit int, sent bool) ([]WarmupMailToRetire, error) {
|
||||
rows, err := resultDB(ctx, r.db).Query(ctx, query, defaultDays, limit)
|
||||
func (r *warmupRepository) scanMailToRetire(ctx context.Context, query string, defaultDays, limit int, skip []uuid.UUID, sent bool) ([]WarmupMailToRetire, error) {
|
||||
if skip == nil {
|
||||
skip = []uuid.UUID{}
|
||||
}
|
||||
rows, err := resultDB(ctx, r.db).Query(ctx, query, defaultDays, limit, skip)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -2079,11 +2095,14 @@ func (r *warmupRepository) RetireWarmupSentCopy(ctx context.Context, token uuid.
|
||||
return err
|
||||
}
|
||||
|
||||
// warmupRecoveryIdentifierDays matches the expiry remember_warmup_identifier gives (migration 000265).
|
||||
const warmupRecoveryIdentifierDays = 90
|
||||
|
||||
// PruneWarmupEventsBefore drops the per-message warmup records older than
|
||||
// before. Receipts and tokens are kept while their mail may still be in the
|
||||
// mailbox (not yet retired), so the retention sweep can still reach it and a
|
||||
// removal seen later is still recognised as warmup rather than tampering.
|
||||
func (r *warmupRepository) PruneWarmupEventsBefore(ctx context.Context, before time.Time) (int64, error) {
|
||||
func (r *warmupRepository) PruneWarmupEventsBefore(ctx context.Context, before time.Time, mailDays int) (int64, error) {
|
||||
var total int64
|
||||
// Each statement gets only the arguments it references; pgx refuses an extra one.
|
||||
for _, st := range []struct {
|
||||
@@ -2115,6 +2134,15 @@ func (r *warmupRepository) PruneWarmupEventsBefore(ctx context.Context, before t
|
||||
}
|
||||
total += cmd.RowsAffected()
|
||||
}
|
||||
// Replies are matched against a thread turn, so it outlives the event window, its mailbox's mail window and the recovery identifiers.
|
||||
n, err := DeleteInBatches(ctx, r.db, "warmup_thread_messages",
|
||||
`SELECT m.ctid FROM warmup_thread_messages m JOIN email_accounts ea ON ea.id = m.email_account_id
|
||||
WHERE m.created_at < LEAST($2, NOW() - make_interval(days => GREATEST(`+strconv.Itoa(warmupRecoveryIdentifierDays)+`, COALESCE(ea.warmup_retention_days, $3))))
|
||||
LIMIT $1`, before, mailDays)
|
||||
total += n
|
||||
if err != nil {
|
||||
return total, err
|
||||
}
|
||||
return total, nil
|
||||
}
|
||||
|
||||
@@ -2471,23 +2499,38 @@ func (r *warmupRepository) GetLatestReplyCandidate(ctx context.Context, senderAc
|
||||
return candidate, nil
|
||||
}
|
||||
|
||||
// GetAllParticipantAccountIDs returns all unique account IDs across all warmup pools
|
||||
func (r *warmupRepository) GetAllParticipantAccountIDs(ctx context.Context) ([]uuid.UUID, error) {
|
||||
rows, err := resultDB(ctx, r.db).Query(ctx, `SELECT DISTINCT email_account_id FROM warmup_pool_participants`)
|
||||
// WarmupParticipantMembership is one participating mailbox, what decides its pool, and the pools it sits in.
|
||||
type WarmupParticipantMembership struct {
|
||||
EmailAccountID uuid.UUID
|
||||
Status string
|
||||
OrganizationID *uuid.UUID
|
||||
WarmupPoolType string
|
||||
PoolTypes []string
|
||||
}
|
||||
|
||||
// ListParticipantMemberships reads every participant with its mailbox in one query.
|
||||
func (r *warmupRepository) ListParticipantMemberships(ctx context.Context) ([]WarmupParticipantMembership, error) {
|
||||
rows, err := resultDB(ctx, r.db).Query(ctx, `
|
||||
SELECT p.email_account_id, ea.status::text, ea.organization_id, COALESCE(ea.warmup_pool_type, ''),
|
||||
array_agg(DISTINCT wp.pool_type::text)
|
||||
FROM warmup_pool_participants p
|
||||
JOIN warmup_pools wp ON wp.id = p.pool_id
|
||||
JOIN email_accounts ea ON ea.id = p.email_account_id
|
||||
GROUP BY p.email_account_id, ea.id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var ids []uuid.UUID
|
||||
var out []WarmupParticipantMembership
|
||||
for rows.Next() {
|
||||
var id uuid.UUID
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
var m WarmupParticipantMembership
|
||||
if err := rows.Scan(&m.EmailAccountID, &m.Status, &m.OrganizationID, &m.WarmupPoolType, &m.PoolTypes); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
out = append(out, m)
|
||||
}
|
||||
return ids, rows.Err()
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// GetPoolHealthCounts returns counts per health state and the average band score
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -490,6 +491,19 @@ func (r *webhookRepository) MatchingEndpoints(ctx context.Context, orgID uuid.UU
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// WebhookDeliveryChannel is the NOTIFY channel an enqueued delivery signals.
|
||||
const WebhookDeliveryChannel = "warmbly_webhook_delivery"
|
||||
|
||||
// webhookNotifyEvery spaces this process's notifications, since commits that NOTIFY serialize on one lock; the woken poll then drains what follows.
|
||||
const webhookNotifyEvery = 200 * time.Millisecond
|
||||
|
||||
var lastDeliveryNotify atomic.Int64
|
||||
|
||||
func deliveryNotifyDue() bool {
|
||||
now, last := time.Now().UnixNano(), lastDeliveryNotify.Load()
|
||||
return now-last >= int64(webhookNotifyEvery) && lastDeliveryNotify.CompareAndSwap(last, now)
|
||||
}
|
||||
|
||||
func (r *webhookRepository) EnqueueDelivery(ctx context.Context, delivery *models.WebhookDelivery) error {
|
||||
if id := SendResultEffectEventID(ctx); id != uuid.Nil {
|
||||
delivery.ID = uuid.NewSHA1(id, []byte(delivery.EndpointID.String()))
|
||||
@@ -506,12 +520,16 @@ func (r *webhookRepository) EnqueueDelivery(ctx context.Context, delivery *model
|
||||
if delivery.Status == "" {
|
||||
delivery.Status = models.WebhookDeliveryPending
|
||||
}
|
||||
_, err := r.db.Exec(ctx, `
|
||||
insert := `
|
||||
INSERT INTO webhook_deliveries (
|
||||
id, endpoint_id, organization_id, event_type, event_id, payload,
|
||||
status, attempt_count, max_attempts, next_attempt_at, created_at, updated_at
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, NOW(), NOW()) ON CONFLICT(id) DO NOTHING
|
||||
`,
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, NOW(), NOW()) ON CONFLICT(id) DO NOTHING`
|
||||
if deliveryNotifyDue() {
|
||||
// Delivered on commit, so a listening delivery worker wakes once the row is visible.
|
||||
insert = `WITH queued AS (` + insert + `) SELECT pg_notify('` + WebhookDeliveryChannel + `', '')`
|
||||
}
|
||||
_, err := r.db.Exec(ctx, insert,
|
||||
delivery.ID, delivery.EndpointID, delivery.OrganizationID,
|
||||
delivery.EventType, delivery.EventID, json.RawMessage(delivery.Payload),
|
||||
string(delivery.Status), delivery.AttemptCount, delivery.MaxAttempts,
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
)
|
||||
|
||||
// Older than anything else in the database, so each claim below takes these first.
|
||||
var queueFixtureEpoch = time.Date(1971, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
|
||||
func TestLiveSendResultEffectsBatchClaimsDeliverEachEffectOnce(t *testing.T) {
|
||||
_, pool := liveContactDB(t)
|
||||
ctx := t.Context()
|
||||
f := newWarmupUsageFixture(t, pool)
|
||||
task := uuid.New()
|
||||
f.exec(`INSERT INTO tasks(id,task_type,email_account_id,status,message_id,scheduled_at) VALUES($1,'campaign',$2,'completed','',NOW())`, task, f.account)
|
||||
t.Cleanup(func() { _, _ = pool.Exec(context.Background(), `DELETE FROM tasks WHERE id=$1`, task) })
|
||||
insert := func(n, from int) {
|
||||
for i := range n {
|
||||
f.exec(`INSERT INTO send_result_effects(task_id,effect_key,organization_id,kind,payload,created_at) VALUES($1,$2,$3,'notification','{}',$4)`,
|
||||
task, fmt.Sprintf("k%d", from+i), f.org, queueFixtureEpoch.Add(time.Duration(from+i)*time.Second))
|
||||
}
|
||||
}
|
||||
mine := func() map[uuid.UUID]bool {
|
||||
rows, err := pool.Query(ctx, `SELECT id FROM send_result_effects WHERE task_id=$1`, task)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
out := map[uuid.UUID]bool{}
|
||||
for rows.Next() {
|
||||
var id uuid.UUID
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out[id] = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// More than one batch, drained by two replicas at once.
|
||||
insert(2*sendResultEffectBatch+5, 0)
|
||||
ours := mine()
|
||||
repo := &advancedOutreachRepository{db: pool}
|
||||
var mu sync.Mutex
|
||||
delivered := map[uuid.UUID]int{}
|
||||
var wg sync.WaitGroup
|
||||
for range 2 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
err := repo.DeliverSendResultEffects(ctx, func(_ context.Context, e SendResultEffect) error {
|
||||
if ours[e.ID] {
|
||||
mu.Lock()
|
||||
delivered[e.ID]++
|
||||
mu.Unlock()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if len(delivered) != len(ours) {
|
||||
t.Fatalf("delivered %d of %d effects", len(delivered), len(ours))
|
||||
}
|
||||
for id, n := range delivered {
|
||||
if n != 1 {
|
||||
t.Fatalf("effect %s delivered %d times", id, n)
|
||||
}
|
||||
}
|
||||
var undelivered int
|
||||
if err := pool.QueryRow(ctx, `SELECT count(*) FROM send_result_effects WHERE task_id=$1 AND delivered_at IS NULL`, task).Scan(&undelivered); err != nil || undelivered != 0 {
|
||||
t.Fatalf("%d effects left undelivered: %v", undelivered, err)
|
||||
}
|
||||
|
||||
// A failure stops the pass and hands back what it never attempted, uncounted.
|
||||
f.exec(`DELETE FROM send_result_effects WHERE task_id=$1`, task)
|
||||
insert(4, 100)
|
||||
calls := 0
|
||||
err := repo.DeliverSendResultEffects(ctx, func(_ context.Context, e SendResultEffect) error {
|
||||
calls++
|
||||
if calls == 2 {
|
||||
return errors.New("notifier unavailable")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("a failed delivery was not reported")
|
||||
}
|
||||
rows, err := pool.Query(ctx, `SELECT delivered_at IS NOT NULL, attempts, locked_until IS NOT NULL FROM send_result_effects WHERE task_id=$1 ORDER BY created_at`, task)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
type state struct {
|
||||
delivered bool
|
||||
attempts int
|
||||
locked bool
|
||||
}
|
||||
var got []state
|
||||
for rows.Next() {
|
||||
var s state
|
||||
if err := rows.Scan(&s.delivered, &s.attempts, &s.locked); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got = append(got, s)
|
||||
}
|
||||
want := []state{{true, 1, false}, {false, 1, true}, {false, 0, false}, {false, 0, false}}
|
||||
if fmt.Sprint(got) != fmt.Sprint(want) {
|
||||
t.Fatalf("after a failed pass: %+v, want %+v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveCRMClaimTakesDueAndLapsedJobsOnce(t *testing.T) {
|
||||
_, pool := liveContactDB(t)
|
||||
ctx := t.Context()
|
||||
f := newWarmupUsageFixture(t, pool)
|
||||
t.Cleanup(func() {
|
||||
_, _ = pool.Exec(context.Background(), `DELETE FROM crm_sync_jobs WHERE organization_id=$1`, f.org)
|
||||
})
|
||||
add := func(status string, at time.Time, lockedUntil *time.Time) uuid.UUID {
|
||||
id := uuid.New()
|
||||
f.exec(`INSERT INTO crm_sync_jobs(id,organization_id,provider,kind,status,next_attempt_at,locked_until) VALUES($1,$2,'pipedrive','log_event',$3,$4,$5)`,
|
||||
id, f.org, status, at, lockedUntil)
|
||||
return id
|
||||
}
|
||||
lapsed, live := queueFixtureEpoch, time.Now().Add(time.Hour)
|
||||
want := map[uuid.UUID]bool{}
|
||||
for i := range 6 {
|
||||
want[add("pending", queueFixtureEpoch.Add(time.Duration(i)*time.Second), nil)] = true
|
||||
}
|
||||
want[add("running", queueFixtureEpoch, &lapsed)] = true
|
||||
held := add("running", queueFixtureEpoch, &live)
|
||||
future := add("pending", time.Now().Add(time.Hour), nil)
|
||||
|
||||
repo := &crmProviderRepository{db: pool}
|
||||
var mu sync.Mutex
|
||||
owner := map[uuid.UUID]int{}
|
||||
var wg sync.WaitGroup
|
||||
for d := range 2 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for range 4 {
|
||||
jobs, err := repo.ClaimJobs(ctx, models.CRMProvider("pipedrive"), 1, time.Minute)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
for _, j := range jobs {
|
||||
if prev, seen := owner[j.ID]; seen {
|
||||
t.Errorf("job %s claimed by drainer %d and %d", j.ID, prev, d)
|
||||
}
|
||||
owner[j.ID] = d
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
for id := range want {
|
||||
if _, ok := owner[id]; !ok {
|
||||
t.Fatalf("due or lapsed job %s never claimed", id)
|
||||
}
|
||||
}
|
||||
if _, ok := owner[held]; ok {
|
||||
t.Fatal("a job under a live lease was claimed")
|
||||
}
|
||||
if _, ok := owner[future]; ok {
|
||||
t.Fatal("a job not yet due was claimed")
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,11 @@ package repository
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
)
|
||||
|
||||
@@ -49,30 +50,84 @@ func SendResultEffectEventID(ctx context.Context) uuid.UUID {
|
||||
return id
|
||||
}
|
||||
|
||||
// One claim statement leases a batch; a pass drains batches until one comes back short.
|
||||
const (
|
||||
sendResultEffectBatch = 25
|
||||
sendResultEffectBatches = 20
|
||||
)
|
||||
|
||||
type claimedSendResultEffect struct {
|
||||
id, lease uuid.UUID
|
||||
raw []byte
|
||||
created time.Time
|
||||
}
|
||||
|
||||
func (r *advancedOutreachRepository) DeliverSendResultEffects(ctx context.Context, deliver func(context.Context, SendResultEffect) error) error {
|
||||
for range 10 {
|
||||
var id, lease uuid.UUID
|
||||
var raw []byte
|
||||
err := r.db.QueryRow(ctx, `WITH candidate AS(SELECT id FROM send_result_effects WHERE delivered_at IS NULL AND (locked_until IS NULL OR locked_until<NOW()) ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED)
|
||||
UPDATE send_result_effects e SET lease=gen_random_uuid(),locked_until=NOW()+INTERVAL '1 minute',attempts=attempts+1 FROM candidate c WHERE e.id=c.id RETURNING e.id,e.lease,e.payload`).Scan(&id, &lease, &raw)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
break
|
||||
}
|
||||
for range sendResultEffectBatches {
|
||||
batch, err := r.claimSendResultEffects(ctx, sendResultEffectBatch)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var effect SendResultEffect
|
||||
if err = json.Unmarshal(raw, &effect); err != nil {
|
||||
return err
|
||||
for i, c := range batch {
|
||||
if err := r.deliverSendResultEffect(ctx, c, deliver); err != nil {
|
||||
r.releaseSendResultEffects(batch[i+1:])
|
||||
return err
|
||||
}
|
||||
}
|
||||
effect.ID = id
|
||||
if err = deliver(context.WithValue(ctx, sendResultEffectIDKey{}, id), effect); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = r.db.Exec(ctx, `UPDATE send_result_effects SET delivered_at=NOW(),locked_until=NULL WHERE id=$1 AND lease=$2`, id, lease); err != nil {
|
||||
return err
|
||||
if len(batch) < sendResultEffectBatch {
|
||||
break
|
||||
}
|
||||
}
|
||||
_, err := r.db.Exec(ctx, `DELETE FROM send_result_effects WHERE delivered_at<NOW()-INTERVAL '7 days'`)
|
||||
return nil
|
||||
}
|
||||
|
||||
// claimSendResultEffects leases up to limit pending effects, oldest first.
|
||||
func (r *advancedOutreachRepository) claimSendResultEffects(ctx context.Context, limit int) ([]claimedSendResultEffect, error) {
|
||||
rows, err := r.db.Query(ctx, `WITH candidate AS(SELECT id FROM send_result_effects WHERE delivered_at IS NULL AND (locked_until IS NULL OR locked_until<NOW()) ORDER BY created_at LIMIT $1 FOR UPDATE SKIP LOCKED)
|
||||
UPDATE send_result_effects e SET lease=gen_random_uuid(),locked_until=NOW()+INTERVAL '1 minute',attempts=attempts+1 FROM candidate c WHERE e.id=c.id RETURNING e.id,e.lease,e.payload,e.created_at`, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var claimed []claimedSendResultEffect
|
||||
for rows.Next() {
|
||||
var c claimedSendResultEffect
|
||||
if err := rows.Scan(&c.id, &c.lease, &c.raw, &c.created); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
claimed = append(claimed, c)
|
||||
}
|
||||
// RETURNING has no order; deliver oldest first, as the claim chose them.
|
||||
slices.SortFunc(claimed, func(a, b claimedSendResultEffect) int { return a.created.Compare(b.created) })
|
||||
return claimed, rows.Err()
|
||||
}
|
||||
|
||||
func (r *advancedOutreachRepository) deliverSendResultEffect(ctx context.Context, c claimedSendResultEffect, deliver func(context.Context, SendResultEffect) error) error {
|
||||
var effect SendResultEffect
|
||||
if err := json.Unmarshal(c.raw, &effect); err != nil {
|
||||
return err
|
||||
}
|
||||
effect.ID = c.id
|
||||
if err := deliver(context.WithValue(ctx, sendResultEffectIDKey{}, c.id), effect); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := r.db.Exec(ctx, `UPDATE send_result_effects SET delivered_at=NOW(),locked_until=NULL WHERE id=$1 AND lease=$2`, c.id, c.lease)
|
||||
return err
|
||||
}
|
||||
|
||||
// releaseSendResultEffects hands claims a failed pass never attempted back to the next pass, uncounted.
|
||||
func (r *advancedOutreachRepository) releaseSendResultEffects(batch []claimedSendResultEffect) {
|
||||
if len(batch) == 0 {
|
||||
return
|
||||
}
|
||||
ids, leases := make([]uuid.UUID, len(batch)), make([]uuid.UUID, len(batch))
|
||||
for i, c := range batch {
|
||||
ids[i], leases[i] = c.id, c.lease
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if _, err := r.db.Exec(ctx, `UPDATE send_result_effects e SET locked_until=NULL,attempts=GREATEST(e.attempts-1,0)
|
||||
FROM unnest($1::uuid[],$2::uuid[]) AS c(id,lease) WHERE e.id=c.id AND e.lease=c.lease AND e.delivered_at IS NULL`, ids, leases); err != nil {
|
||||
log.Warn().Err(err).Msg("send result effects: release unattempted claims")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
)
|
||||
|
||||
func TestLiveSyncArrivalBatchDeliversInOrderAndHandsBackUnusedLeases(t *testing.T) {
|
||||
d := liveUniboxFolderDB(t)
|
||||
f := newUniboxFolderFixture(t, d.Pool)
|
||||
r := NewDurableEmailMessageMapRepository(d, arrivalLiveCipher(t, d))
|
||||
ctx := t.Context()
|
||||
var admitted []string
|
||||
for i := range 5 {
|
||||
data, pending := arrivalLivePayload(f, "batch-"+string(rune('a'+i)))
|
||||
if err := r.AdmitArrival(ctx, data, pending); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
admitted = append(admitted, data.MessageID)
|
||||
}
|
||||
// A pass cancelled during its second arrival hands back the three it never reached;
|
||||
// the interrupted one keeps its lease, as it did before batching.
|
||||
pass, cancel := context.WithCancel(ctx)
|
||||
var seen []string
|
||||
err := r.DeliverArrivals(pass, func(_ context.Context, _ models.JobEventType, body any) error {
|
||||
seen = append(seen, body.(*models.JobEventNewEmail).Message.MessageID)
|
||||
if len(seen) == 2 {
|
||||
cancel()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if len(seen) != 2 || seen[0] != admitted[0] || seen[1] != admitted[1] {
|
||||
t.Fatalf("delivered %v, want the two oldest of %v", seen, admitted)
|
||||
}
|
||||
var leased, left int
|
||||
if err := d.QueryRow(ctx, `SELECT count(*) FILTER (WHERE locked_until > now()), count(*) FROM sync_arrival_outbox WHERE email_id=$1`, f.mailbox).Scan(&leased, &left); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if leased != 1 || left != 4 {
|
||||
t.Fatalf("leased=%d left=%d after the pass ended", leased, left)
|
||||
}
|
||||
if err := r.DeliverArrivals(ctx, func(_ context.Context, _ models.JobEventType, body any) error {
|
||||
seen = append(seen, body.(*models.JobEventNewEmail).Message.MessageID)
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(seen) != 5 || seen[2] != admitted[2] || seen[4] != admitted[4] {
|
||||
t.Fatalf("delivered %v", seen)
|
||||
}
|
||||
if err := d.QueryRow(ctx, `SELECT count(*) FROM sync_arrival_outbox WHERE email_id=$1`, f.mailbox).Scan(&left); err != nil || left != 1 {
|
||||
t.Fatalf("left=%d err=%v", left, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
)
|
||||
|
||||
// rowVersion is a row's xmin, which moves only when the row is rewritten.
|
||||
func rowVersion(t *testing.T, f transportFixture, query string) string {
|
||||
t.Helper()
|
||||
var xmin string
|
||||
if err := f.pool.QueryRow(t.Context(), query, f.account).Scan(&xmin); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return xmin
|
||||
}
|
||||
|
||||
func ownedTransportFixture(t *testing.T) (transportFixture, uuid.UUID) {
|
||||
t.Helper()
|
||||
f := newTransportFixture(t)
|
||||
worker := uuid.New()
|
||||
if _, err := f.pool.Exec(t.Context(), `INSERT INTO fleet_nodes(id,role) VALUES($1,'worker')`, worker); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if _, err := f.pool.Exec(context.Background(), `DELETE FROM fleet_nodes WHERE id=$1`, worker); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
if _, err := f.pool.Exec(t.Context(), `INSERT INTO workers(id) VALUES($1)`, worker); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.pool.Exec(t.Context(), `UPDATE email_accounts SET worker_id=$2 WHERE id=$1`, f.account, worker); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return f, worker
|
||||
}
|
||||
|
||||
func TestLiveSyncReportWritesOnlyWhatChanged(t *testing.T) {
|
||||
f, worker := ownedTransportFixture(t)
|
||||
repo := NewEmailSyncStateRepository(f.db)
|
||||
const stateRow = `SELECT xmin::text FROM email_sync_state WHERE email_id=$1`
|
||||
const accountRow = `SELECT xmin::text FROM email_accounts WHERE id=$1`
|
||||
synced := time.Now().UTC().Add(-10 * time.Minute).Truncate(time.Millisecond)
|
||||
state := models.SyncState{TransportGeneration: f.generation, BackfillStatus: models.SyncBackfillRunning, BackfillSynced: 3, LastSyncedAt: &synced,
|
||||
BackfillCursor: models.SyncCursor{Folders: map[string]models.SyncFolderCursor{"INBOX": {}}}}
|
||||
put := func(st models.SyncState) *SyncStatePrior {
|
||||
t.Helper()
|
||||
accepted, prior, err := repo.PutFromWorker(t.Context(), f.user, f.account, worker, f.generation, &st, nil)
|
||||
if err != nil || !accepted {
|
||||
t.Fatalf("accepted=%t err=%v", accepted, err)
|
||||
}
|
||||
return prior
|
||||
}
|
||||
if prior := put(state); prior != nil {
|
||||
t.Fatalf("first report replaced %+v", prior)
|
||||
}
|
||||
stored, account := rowVersion(t, f, stateRow), rowVersion(t, f, accountRow)
|
||||
|
||||
// A redelivery of the same report rewrites nothing.
|
||||
prior := put(state)
|
||||
if prior == nil || prior.BackfillStatus != models.SyncBackfillRunning || prior.LastSyncedAt == nil || !prior.LastSyncedAt.Equal(synced) {
|
||||
t.Fatalf("prior=%+v", prior)
|
||||
}
|
||||
if rowVersion(t, f, stateRow) != stored || rowVersion(t, f, accountRow) != account {
|
||||
t.Fatal("an identical report rewrote a row")
|
||||
}
|
||||
|
||||
// Half a minute later the state persists but the account's "Last synced" waits for the minute.
|
||||
soon := synced.Add(30 * time.Second)
|
||||
state.LastSyncedAt, state.BackfillSynced = &soon, 4
|
||||
put(state)
|
||||
got, err := repo.Get(t.Context(), f.account)
|
||||
if err != nil || got.BackfillSynced != 4 || !got.LastSyncedAt.Equal(soon) {
|
||||
t.Fatalf("changed report not stored: %+v %v", got, err)
|
||||
}
|
||||
if rowVersion(t, f, accountRow) != account {
|
||||
t.Fatal("account row rewritten inside the minute")
|
||||
}
|
||||
later := synced.Add(2 * time.Minute)
|
||||
state.LastSyncedAt = &later
|
||||
put(state)
|
||||
var accountAt time.Time
|
||||
if err := f.pool.QueryRow(t.Context(), `SELECT last_synced_at FROM email_accounts WHERE id=$1`, f.account).Scan(&accountAt); err != nil || !accountAt.Equal(later) {
|
||||
t.Fatalf("account last_synced_at=%v err=%v, want %v", accountAt, err, later)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveSyncRecoveryClockStaysExactAndSkipsOnlyStaleReports(t *testing.T) {
|
||||
f, worker := ownedTransportFixture(t)
|
||||
repo := NewEmailSyncStateRepository(f.db)
|
||||
const recoveryRow = `SELECT xmin::text FROM email_account_transport_recovery WHERE email_account_id=$1 AND operation='sync'`
|
||||
recover := func(at time.Time) func(context.Context, *SyncStatePrior) error {
|
||||
return func(ctx context.Context, _ *SyncStatePrior) error {
|
||||
if xerr := f.repo.RecordTransportSuccess(ctx, f.account, models.MailTransportSync, at, nil, f.generation); xerr != nil {
|
||||
return xerr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
put := func(at time.Time) {
|
||||
t.Helper()
|
||||
state := models.SyncState{TransportGeneration: f.generation, LastSyncedAt: &at}
|
||||
if accepted, _, err := repo.PutFromWorker(t.Context(), f.user, f.account, worker, f.generation, &state, recover(at)); err != nil || !accepted {
|
||||
t.Fatalf("accepted=%t err=%v", accepted, err)
|
||||
}
|
||||
}
|
||||
base := time.Now().UTC().Add(-time.Hour).Truncate(time.Millisecond)
|
||||
put(base)
|
||||
quiet := rowVersion(t, f, recoveryRow)
|
||||
put(base.Add(-time.Second))
|
||||
if rowVersion(t, f, recoveryRow) != quiet {
|
||||
t.Fatal("a report older than the recovery clock rewrote it")
|
||||
}
|
||||
put(base.Add(20 * time.Second))
|
||||
if rowVersion(t, f, recoveryRow) == quiet {
|
||||
t.Fatal("a newer pass did not move the recovery clock, so a late error would be judged against a stale one")
|
||||
}
|
||||
// An error raised now is cleared by the very next pass.
|
||||
errAt := base.Add(30 * time.Second)
|
||||
if _, err := f.repo.CreateOnce(t.Context(), f.report(models.MailTransportSync, &errAt)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
put(base.Add(40 * time.Second))
|
||||
if open := f.errors(t, true); len(open) != 0 {
|
||||
t.Fatalf("pending error survived a later pass: %+v", open)
|
||||
}
|
||||
var recovered time.Time
|
||||
if err := f.pool.QueryRow(t.Context(), `SELECT recovered_at FROM email_account_transport_recovery WHERE email_account_id=$1 AND operation='sync'`, f.account).Scan(&recovered); err != nil || !recovered.Equal(base.Add(40*time.Second)) {
|
||||
t.Fatalf("recovered_at=%v err=%v", recovered, err)
|
||||
}
|
||||
}
|
||||
@@ -97,7 +97,7 @@ func TestLiveWarmupMailRetention(t *testing.T) {
|
||||
|
||||
repo := &warmupRepository{db: pool}
|
||||
|
||||
rows, err := repo.ListWarmupMailToRetire(ctx, 30, 100)
|
||||
rows, err := repo.ListWarmupMailToRetire(ctx, 30, 100, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("ListWarmupMailToRetire: %v", err)
|
||||
}
|
||||
@@ -135,7 +135,7 @@ func TestLiveWarmupMailRetention(t *testing.T) {
|
||||
if err != nil || rec == nil || rec.RetiredAt == nil {
|
||||
t.Fatalf("GetWarmupReceived after retiring = %+v, %v; want retired_at set", rec, err)
|
||||
}
|
||||
rows, err = repo.ListWarmupMailToRetire(ctx, 30, 100)
|
||||
rows, err = repo.ListWarmupMailToRetire(ctx, 30, 100, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("ListWarmupMailToRetire again: %v", err)
|
||||
}
|
||||
@@ -147,7 +147,7 @@ func TestLiveWarmupMailRetention(t *testing.T) {
|
||||
|
||||
// The sender's own copies follow the same window, and the map resolves
|
||||
// the provider key where it is keyed by Message-ID.
|
||||
sent, err := repo.ListWarmupSentCopiesToRetire(ctx, 30, 100)
|
||||
sent, err := repo.ListWarmupSentCopiesToRetire(ctx, 30, 100, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("ListWarmupSentCopiesToRetire: %v", err)
|
||||
}
|
||||
@@ -180,7 +180,12 @@ func TestLiveWarmupMailRetention(t *testing.T) {
|
||||
exec(`INSERT INTO mailbox_owner_activity (email_account_id, bucket) VALUES
|
||||
($1, NOW() - make_interval(days => $2::int + 1)), ($1, NOW() - interval '1 day')`,
|
||||
following, config.WarmupOwnerActivityKeepDays)
|
||||
if _, err := repo.PruneWarmupEventsBefore(ctx, time.Now().AddDate(0, 0, -365)); err != nil {
|
||||
// A thread turn goes with the event window unless its mailbox still keeps that mail.
|
||||
exec(`UPDATE email_accounts SET warmup_retention_days = 500 WHERE id = $1`, idle)
|
||||
exec(`INSERT INTO warmup_thread_messages (email_account_id, message_id, created_at) VALUES
|
||||
($1, 'turn-past-every-window@example.test', NOW() - interval '400 days'),
|
||||
($2, 'turn-in-its-mail-window@example.test', NOW() - interval '400 days')`, following, idle)
|
||||
if _, err := repo.PruneWarmupEventsBefore(ctx, time.Now().AddDate(0, 0, -365), 30); err != nil {
|
||||
t.Fatalf("PruneWarmupEventsBefore: %v", err)
|
||||
}
|
||||
if rec, _ := repo.GetWarmupReceived(ctx, following, oldFollowing); rec != nil {
|
||||
@@ -193,6 +198,13 @@ func TestLiveWarmupMailRetention(t *testing.T) {
|
||||
if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM warmup_tokens WHERE token IN ($1, $2)`, oldSent, smtpSent).Scan(&tokens); err != nil || tokens != 0 {
|
||||
t.Fatalf("retired and SMTP tokens past the window: count=%d err=%v, want both pruned", tokens, err)
|
||||
}
|
||||
var turns []string
|
||||
if err := pool.QueryRow(ctx, `SELECT COALESCE(array_agg(message_id), '{}') FROM warmup_thread_messages WHERE email_account_id IN ($1, $2)`, following, idle).Scan(&turns); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(turns) != 1 || turns[0] != "turn-in-its-mail-window@example.test" {
|
||||
t.Fatalf("thread turns after the prune: %v, want only the one its mailbox still keeps", turns)
|
||||
}
|
||||
var buckets int
|
||||
if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM mailbox_owner_activity WHERE email_account_id = $1`, following).Scan(&buckets); err != nil || buckets != 1 {
|
||||
t.Fatalf("owner activity after the prune: count=%d err=%v, want only the recent bucket", buckets, err)
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
)
|
||||
|
||||
// One query returns each participant with what decides its pool and every pool it sits in.
|
||||
//
|
||||
// WARMBLY_TEST_DB=postgres://warmbly:warmbly@localhost:15432/<db>?sslmode=disable \
|
||||
// go test ./internal/repository/ -run LiveParticipantMemberships -v
|
||||
func TestLiveParticipantMembershipsReadEveryParticipantAtOnce(t *testing.T) {
|
||||
handle, pool := liveContactDB(t)
|
||||
ctx := context.Background()
|
||||
user, org, active, paused := uuid.New(), uuid.New(), uuid.New(), uuid.New()
|
||||
tag := "membership-" + org.String()[:8]
|
||||
exec := func(sql string, args ...any) {
|
||||
t.Helper()
|
||||
if _, err := pool.Exec(ctx, sql, args...); err != nil {
|
||||
t.Fatalf("fixture: %v", err)
|
||||
}
|
||||
}
|
||||
exec(`INSERT INTO users (id, first_name, last_name, email, password_hash) VALUES ($1, 'Pool', 'Live', $2, 'x')`, user, tag+"@test.local")
|
||||
exec(`INSERT INTO organizations (id, name, slug, owner_user_id) VALUES ($1, 'Pool', $2, $3)`, org, tag, user)
|
||||
t.Cleanup(func() {
|
||||
_, _ = pool.Exec(ctx, `DELETE FROM email_accounts WHERE id = ANY($1)`, []uuid.UUID{active, paused})
|
||||
_, _ = pool.Exec(ctx, `DELETE FROM organizations WHERE id = $1`, org)
|
||||
_, _ = pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, user)
|
||||
})
|
||||
exec(`INSERT INTO email_accounts (id, user_id, organization_id, email, name, signature_plain, signature_html, provider, warmup_pool_type)
|
||||
VALUES ($1, $2, $3, $4, 'A', '', '', 'gmail', 'premium')`, active, user, org, tag+"[EMAIL]")
|
||||
exec(`INSERT INTO email_accounts (id, user_id, organization_id, email, name, signature_plain, signature_html, provider, status, warmup_pool_type)
|
||||
VALUES ($1, $2, $3, $4, 'B', '', '', 'gmail', 'inactive', NULL)`, paused, user, org, tag+"[EMAIL]")
|
||||
exec(`INSERT INTO warmup_pool_participants (pool_id, email_account_id) VALUES ($1, $2), ($3, $4)`,
|
||||
models.WarmupPoolFreeID, active, models.WarmupPoolPremiumID, paused)
|
||||
|
||||
members, err := NewWarmupRepository(handle.Pool).ListParticipantMemberships(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := map[uuid.UUID]WarmupParticipantMembership{}
|
||||
for _, m := range members {
|
||||
got[m.EmailAccountID] = m
|
||||
}
|
||||
a, b := got[active], got[paused]
|
||||
if a.Status != "active" || a.OrganizationID == nil || *a.OrganizationID != org || a.WarmupPoolType != "premium" || len(a.PoolTypes) != 1 || a.PoolTypes[0] != "free" {
|
||||
t.Fatalf("active mailbox read as %+v", a)
|
||||
}
|
||||
if b.Status != "inactive" || b.WarmupPoolType != "" || len(b.PoolTypes) != 1 || b.PoolTypes[0] != "premium" {
|
||||
t.Fatalf("paused mailbox read as %+v", b)
|
||||
}
|
||||
}
|
||||
@@ -266,6 +266,15 @@ func TestLiveLoadingIncidentNonLoadingBoundary(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// claimDueForTest claims every due task and hands the claims straight back, so tests sharing the database keep theirs.
|
||||
func claimDueForTest(ctx context.Context, repo *taskRepository) ([]uuid.UUID, error) {
|
||||
ids, claim, err := repo.ClaimDueTaskIDs(ctx, 10000, time.Minute)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, repo.ReleaseDispatchClaims(ctx, ids, claim)
|
||||
}
|
||||
|
||||
func TestLiveDispatchRetrySuccessfulPendingNoopDoesNotStarveNewerTask(t *testing.T) {
|
||||
_, pool := liveContactDB(t)
|
||||
ctx, now := t.Context(), time.Now().UTC().Truncate(time.Microsecond)
|
||||
@@ -274,10 +283,10 @@ func TestLiveDispatchRetrySuccessfulPendingNoopDoesNotStarveNewerTask(t *testing
|
||||
old, newer := uuid.New(), uuid.New()
|
||||
f.exec(`INSERT INTO tasks(id,task_type,email_account_id,status,message_id,scheduled_at) VALUES($1,'warmup',$3,'pending','',$4),($2,'warmup',$3,'pending','',$5)`, old, newer, f.account, now.Add(-24*time.Hour), now.Add(-2*time.Hour))
|
||||
repo := &taskRepository{db: pool}
|
||||
if err := repo.RecordDispatchAttempt(ctx, old, false, now.Add(5*time.Minute)); err != nil {
|
||||
if err := repo.RecordDispatchAttempt(ctx, old, time.Time{}, false, now.Add(5*time.Minute)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ids, err := repo.ListDuePendingTaskIDs(ctx, 10000)
|
||||
ids, err := claimDueForTest(ctx, repo)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -298,7 +307,7 @@ func TestLiveDispatchRetrySuccessfulPendingNoopDoesNotStarveNewerTask(t *testing
|
||||
t.Fatalf("no-op changed schedule/state or manufactured failure: %v %v %s %v %v %v", scheduled, retry, status, failureSince, failureAt, err)
|
||||
}
|
||||
f.exec(`UPDATE tasks SET dispatch_retry_at=NOW()-INTERVAL '1 second' WHERE id=$1`, old)
|
||||
ids, err = repo.ListDuePendingTaskIDs(ctx, 10000)
|
||||
ids, err = claimDueForTest(ctx, repo)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -336,7 +345,7 @@ func TestLiveDispatchRetrySuccessfulAttemptPreservesSchedulingAndSafety(t *testi
|
||||
f.exec(`UPDATE email_accounts SET send_recovery_hold=true,send_recovery_reason='unknown',send_recovery_task_id=$2 WHERE id=$1`, f.account, id)
|
||||
}
|
||||
repo := &taskRepository{db: pool}
|
||||
if err := repo.RecordDispatchAttempt(ctx, id, false, now.Add(5*time.Minute)); err != nil {
|
||||
if err := repo.RecordDispatchAttempt(ctx, id, time.Time{}, false, now.Add(5*time.Minute)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var scheduled time.Time
|
||||
@@ -369,10 +378,10 @@ func TestLiveDispatchRetryDoesNotStarveNewerTask(t *testing.T) {
|
||||
old, newer := uuid.New(), uuid.New()
|
||||
f.exec(`INSERT INTO tasks(id,task_type,email_account_id,status,message_id,scheduled_at) VALUES($1,'warmup',$3,'pending','',$4),($2,'warmup',$3,'pending','',$5)`, old, newer, f.account, now.Add(-24*time.Hour), now.Add(-2*time.Hour))
|
||||
repo := &taskRepository{db: pool}
|
||||
if err := repo.RecordDispatchAttempt(ctx, old, true, now.Add(5*time.Minute)); err != nil {
|
||||
if err := repo.RecordDispatchAttempt(ctx, old, time.Time{}, true, now.Add(5*time.Minute)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ids, err := repo.ListDuePendingTaskIDs(ctx, 10000)
|
||||
ids, err := claimDueForTest(ctx, repo)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -407,7 +416,7 @@ func TestLiveDispatchRetryDoesNotStarveNewerTask(t *testing.T) {
|
||||
t.Fatalf("retry changed intended schedule or send state: %v %s %v", scheduled, status, err)
|
||||
}
|
||||
f.exec(`UPDATE tasks SET dispatch_retry_at=NOW()-INTERVAL '1 second' WHERE id=$1`, old)
|
||||
ids, err = repo.ListDuePendingTaskIDs(ctx, 10000)
|
||||
ids, err = claimDueForTest(ctx, repo)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -421,7 +430,7 @@ func TestLiveDispatchRetryDoesNotStarveNewerTask(t *testing.T) {
|
||||
t.Fatal("old task never becomes retryable")
|
||||
}
|
||||
f.exec(`UPDATE tasks SET status='completed',send_result_state='unknown',send_executor_started_at=NOW() WHERE id=$1`, old)
|
||||
if err := repo.RecordDispatchAttempt(ctx, old, true, now.Add(time.Hour)); err != nil {
|
||||
if err := repo.RecordDispatchAttempt(ctx, old, time.Time{}, true, now.Add(time.Hour)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var retry time.Time
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/pkg/encrypt"
|
||||
)
|
||||
|
||||
func TestLiveWebhookEnqueueNotifiesAndStoresTheDelivery(t *testing.T) {
|
||||
_, pool := liveContactDB(t)
|
||||
f := newSharedOrgFixture(t, pool)
|
||||
ctx := t.Context()
|
||||
enc, err := encrypt.NewEncrypter(make([]byte, 32))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := NewWebhookRepositorySealed(pool, enc)
|
||||
endpoint := &models.WebhookEndpoint{OrganizationID: f.org, URL: "https://example.com/hooks/notify", Enabled: true}
|
||||
if err := repo.CreateEndpoint(ctx, endpoint, "secret", "token"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_, _ = pool.Exec(context.Background(), `DELETE FROM webhook_endpoints WHERE id = $1`, endpoint.ID)
|
||||
})
|
||||
|
||||
listener, err := pool.Acquire(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
_, _ = listener.Exec(context.Background(), "UNLISTEN *")
|
||||
listener.Release()
|
||||
}()
|
||||
if _, err := listener.Exec(ctx, "LISTEN "+WebhookDeliveryChannel); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
lastDeliveryNotify.Store(0)
|
||||
delivery := &models.WebhookDelivery{EndpointID: endpoint.ID, OrganizationID: f.org, EventType: "test.notify", EventID: uuid.New(), Payload: []byte(`{}`)}
|
||||
if err := repo.EnqueueDelivery(ctx, delivery); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
n, err := listener.Conn().WaitForNotification(waitCtx)
|
||||
if err != nil {
|
||||
t.Fatalf("an enqueued delivery woke no listener: %v", err)
|
||||
}
|
||||
if n.Channel != WebhookDeliveryChannel {
|
||||
t.Fatalf("notified on %q", n.Channel)
|
||||
}
|
||||
var queued int
|
||||
if err := pool.QueryRow(ctx, `SELECT count(*) FROM webhook_deliveries WHERE id = $1`, delivery.ID).Scan(&queued); err != nil || queued != 1 {
|
||||
t.Fatalf("the notifying enqueue stored %d rows: %v", queued, err)
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/config"
|
||||
"github.com/warmbly/warmbly/internal/jobrun"
|
||||
"github.com/warmbly/warmbly/internal/scheduler"
|
||||
)
|
||||
|
||||
@@ -181,24 +182,13 @@ func (s *tasksService) repark(ctx context.Context, limit int) {
|
||||
}
|
||||
|
||||
// StartCampaignReconciler runs ReconcileCampaignSchedules on an interval until
|
||||
// the context is cancelled. Mirrors StartWarmupReconciler and is started from
|
||||
// the backend, which owns Cloud Tasks.
|
||||
// the context is cancelled, one replica per pass. Started from the backend,
|
||||
// which owns Cloud Tasks; seeded on boot so chains recover promptly.
|
||||
func (s *tasksService) StartCampaignReconciler(ctx context.Context, interval time.Duration) {
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
// Seed once on boot so chains recover promptly after a restart instead of
|
||||
// waiting a full interval.
|
||||
s.reconcileCampaignsOnce(ctx)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
s.reconcileCampaignsOnce(ctx)
|
||||
}
|
||||
}
|
||||
jobrun.Loop(ctx, "campaign_reconcile", interval, true, func(ctx context.Context) error {
|
||||
s.reconcileCampaignsOnce(ctx)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *tasksService) reconcileCampaignsOnce(ctx context.Context) {
|
||||
|
||||
@@ -935,28 +935,41 @@ func (s *tasksService) resolveWarmupPoolType(ctx context.Context, account *Email
|
||||
if account == nil {
|
||||
return "premium"
|
||||
}
|
||||
return warmupPoolTypeFor(account.OrganizationID, account.WarmupPoolType,
|
||||
func(org uuid.UUID) bool { return s.orgSuspendedOrRestricted(ctx, org) },
|
||||
func(org uuid.UUID) (bool, bool) { return s.hasPremiumWarmup(ctx, org) })
|
||||
}
|
||||
|
||||
// warmupPoolTypeFor is the pool a mailbox belongs in, given lookups for its organization.
|
||||
func warmupPoolTypeFor(orgID *uuid.UUID, stored string, restricted func(uuid.UUID) bool, premium func(uuid.UUID) (paid, known bool)) string {
|
||||
// No organization means no entitlement to check, so the mailbox gets the
|
||||
// lower-trust pool rather than defaulting into the paid one.
|
||||
if account.OrganizationID == nil {
|
||||
if orgID == nil {
|
||||
return "free"
|
||||
}
|
||||
// A restricted organization leaves the paid pool whatever it pays. Checked
|
||||
// before the stored tier, which is never empty and would short-circuit it.
|
||||
if s.orgSuspendedOrRestricted(ctx, *account.OrganizationID) {
|
||||
if restricted(*orgID) {
|
||||
return "free"
|
||||
}
|
||||
if account.WarmupPoolType != "" {
|
||||
return account.WarmupPoolType
|
||||
if stored != "" {
|
||||
return stored
|
||||
}
|
||||
if s.featureGate != nil {
|
||||
isPaid, xerr := s.featureGate.HasPremiumWarmup(ctx, *account.OrganizationID)
|
||||
if xerr == nil && !isPaid {
|
||||
return "free"
|
||||
}
|
||||
if paid, known := premium(*orgID); known && !paid {
|
||||
return "free"
|
||||
}
|
||||
return "premium"
|
||||
}
|
||||
|
||||
// hasPremiumWarmup reports the organization's paid warmup, and whether it could be read.
|
||||
func (s *tasksService) hasPremiumWarmup(ctx context.Context, orgID uuid.UUID) (bool, bool) {
|
||||
if s.featureGate == nil {
|
||||
return false, false
|
||||
}
|
||||
isPaid, xerr := s.featureGate.HasPremiumWarmup(ctx, orgID)
|
||||
return isPaid, xerr == nil
|
||||
}
|
||||
|
||||
func (s *tasksService) scheduleWarmupRecovery(ctx context.Context, accountID uuid.UUID, poolType string) {
|
||||
if s.warmupRepo == nil {
|
||||
return
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
package tasks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/jobrun"
|
||||
"github.com/warmbly/warmbly/internal/repository"
|
||||
)
|
||||
|
||||
// warmupPoolReconcileInterval spaces the membership pass; the warmup task corrects the mailboxes it runs for in between.
|
||||
const warmupPoolReconcileInterval = 10 * time.Minute
|
||||
|
||||
// StartWarmupReconciler seeds warmup chains every interval and checks pool
|
||||
// membership every warmupPoolReconcileInterval, each on one replica per pass.
|
||||
func (s *tasksService) StartWarmupReconciler(ctx context.Context, interval time.Duration) {
|
||||
if interval <= 0 {
|
||||
interval = time.Minute
|
||||
}
|
||||
go jobrun.Loop(ctx, "warmup_pool_membership", warmupPoolReconcileInterval, true, func(ctx context.Context) error {
|
||||
rctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
|
||||
defer cancel()
|
||||
moved, removed, err := s.ReconcileWarmupPoolMembership(rctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if moved > 0 || removed > 0 {
|
||||
log.Info().Int("moved", moved).Int("removed", removed).Msg("warmup pool membership reconciled")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
// Seeded on boot so chains recover promptly after a restart.
|
||||
jobrun.Loop(ctx, "warmup_schedule_reconcile", interval, true, func(ctx context.Context) error {
|
||||
rctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
|
||||
defer cancel()
|
||||
seeded, err := s.ReconcileWarmupSchedules(rctx, warmupReconcileBatch)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if seeded > 0 {
|
||||
log.Info().Int("seeded", seeded).Msg("warmup reconcile seeded chains")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// ReconcileWarmupPoolMembership makes every participant's membership agree with its
|
||||
// entitlement: no longer entitled leaves warmup, changed tier moves pool. The warmup task does
|
||||
// this too, but only for mailboxes it still runs for, and one that stopped warming has no chain
|
||||
// and is not a schedule candidate, so nothing else would ever revisit it (issue #211).
|
||||
// Roles are left alone so a domain-auth demotion is not quietly promoted back.
|
||||
//
|
||||
// One query reads every participant; entitlement, risk and tier are looked up once per
|
||||
// organization, and only a mailbox in the wrong place is written.
|
||||
func (s *tasksService) ReconcileWarmupPoolMembership(ctx context.Context) (moved int, removed int, err error) {
|
||||
if s.warmupRepo == nil || s.warmupHealth == nil {
|
||||
return 0, 0, nil
|
||||
}
|
||||
|
||||
members, err := s.warmupRepo.ListParticipantMemberships(ctx)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
|
||||
var orgs []uuid.UUID
|
||||
seen := map[uuid.UUID]bool{}
|
||||
for _, m := range members {
|
||||
if m.OrganizationID != nil && !seen[*m.OrganizationID] {
|
||||
seen[*m.OrganizationID] = true
|
||||
orgs = append(orgs, *m.OrganizationID)
|
||||
}
|
||||
}
|
||||
restricted := s.orgsForcedToFreeWarmup(ctx, orgs)
|
||||
entitled := map[uuid.UUID]bool{}
|
||||
premium := map[uuid.UUID][2]bool{}
|
||||
hasPremium := func(org uuid.UUID) (bool, bool) {
|
||||
v, ok := premium[org]
|
||||
if !ok {
|
||||
paid, known := s.hasPremiumWarmup(ctx, org)
|
||||
v = [2]bool{paid, known}
|
||||
premium[org] = v
|
||||
}
|
||||
return v[0], v[1]
|
||||
}
|
||||
// A failed write is logged and the pass moves on; the run still reports it.
|
||||
var failed int
|
||||
var lastErr error
|
||||
fail := func(m repository.WarmupParticipantMembership, action string, xerr error) {
|
||||
failed++
|
||||
lastErr = xerr
|
||||
log.Warn().Str("email_account_id", m.EmailAccountID.String()).Str("action", action).Str("error", xerr.Error()).Msg("warmup reconcile: could not update a mailbox's membership")
|
||||
}
|
||||
|
||||
for _, m := range members {
|
||||
if m.Status != "active" || m.OrganizationID == nil {
|
||||
// Nothing left to check an entitlement against, so it does not belong in a shared pool.
|
||||
if xerr := s.warmupHealth.RemoveFromAllPools(ctx, m.EmailAccountID); xerr != nil {
|
||||
fail(m, "leave", xerr)
|
||||
} else {
|
||||
removed++
|
||||
}
|
||||
continue
|
||||
}
|
||||
org := *m.OrganizationID
|
||||
|
||||
if s.featureGate != nil {
|
||||
ok, cached := entitled[org]
|
||||
if !cached {
|
||||
canWarmup, xerr := s.featureGate.CanUseWarmup(ctx, org)
|
||||
if xerr != nil {
|
||||
// Entitlement unknown: leave this mailbox exactly as it is.
|
||||
continue
|
||||
}
|
||||
ok = canWarmup
|
||||
entitled[org] = ok
|
||||
}
|
||||
if !ok {
|
||||
if xerr := s.warmupHealth.RemoveFromAllPools(ctx, m.EmailAccountID); xerr != nil {
|
||||
fail(m, "leave", xerr)
|
||||
} else {
|
||||
removed++
|
||||
log.Info().
|
||||
Str("email_account_id", m.EmailAccountID.String()).
|
||||
Msg("warmup reconcile: mailbox left warmup, organization is no longer entitled")
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
poolType := warmupPoolTypeFor(m.OrganizationID, m.WarmupPoolType,
|
||||
func(uuid.UUID) bool { return restricted[org] }, hasPremium)
|
||||
if !slices.ContainsFunc(m.PoolTypes, func(p string) bool { return p != poolType }) {
|
||||
continue
|
||||
}
|
||||
didMove, xerr := s.warmupHealth.MovePoolMembership(ctx, m.EmailAccountID, poolType)
|
||||
if xerr != nil {
|
||||
fail(m, "move to "+poolType, xerr)
|
||||
continue
|
||||
}
|
||||
if didMove {
|
||||
moved++
|
||||
log.Info().
|
||||
Str("email_account_id", m.EmailAccountID.String()).
|
||||
Str("pool_type", poolType).
|
||||
Msg("warmup reconcile: mailbox moved to the pool its tier belongs to")
|
||||
}
|
||||
}
|
||||
|
||||
if failed > 0 {
|
||||
return moved, removed, fmt.Errorf("%d warmup pool membership updates failed, last: %w", failed, lastErr)
|
||||
}
|
||||
return moved, removed, nil
|
||||
}
|
||||
|
||||
// orgsForcedToFreeWarmup reads the risk state of every organization at once. Fails open, as orgSuspendedOrRestricted does.
|
||||
func (s *tasksService) orgsForcedToFreeWarmup(ctx context.Context, orgs []uuid.UUID) map[uuid.UUID]bool {
|
||||
out := map[uuid.UUID]bool{}
|
||||
if s.orgRiskRepo == nil || len(orgs) == 0 {
|
||||
return out
|
||||
}
|
||||
states, err := s.orgRiskRepo.GetOrgRiskStates(ctx, orgs)
|
||||
if err != nil {
|
||||
return out
|
||||
}
|
||||
for id, state := range states {
|
||||
out[id] = state.ForcesFreeWarmupPool()
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -19,21 +19,29 @@ import (
|
||||
|
||||
type poolReconcileWarmupRepo struct {
|
||||
repository.WarmupRepository
|
||||
participants []uuid.UUID
|
||||
listErr error
|
||||
members []repository.WarmupParticipantMembership
|
||||
listErr error
|
||||
}
|
||||
|
||||
func (r *poolReconcileWarmupRepo) GetAllParticipantAccountIDs(_ context.Context) ([]uuid.UUID, error) {
|
||||
return r.participants, r.listErr
|
||||
func (r *poolReconcileWarmupRepo) ListParticipantMemberships(_ context.Context) ([]repository.WarmupParticipantMembership, error) {
|
||||
return r.members, r.listErr
|
||||
}
|
||||
|
||||
type poolReconcileEmailRepo struct {
|
||||
repository.EmailRepository
|
||||
accounts map[uuid.UUID]*models.Email
|
||||
type poolReconcileRisk struct {
|
||||
repository.OrgRiskRepository
|
||||
states map[uuid.UUID]models.OrgRiskState
|
||||
calls int
|
||||
}
|
||||
|
||||
func (r *poolReconcileEmailRepo) GetByID(_ context.Context, id uuid.UUID) (*models.Email, *errx.Error) {
|
||||
return r.accounts[id], nil
|
||||
func (r *poolReconcileRisk) GetOrgRiskStates(_ context.Context, ids []uuid.UUID) (map[uuid.UUID]models.OrgRiskState, error) {
|
||||
r.calls++
|
||||
out := map[uuid.UUID]models.OrgRiskState{}
|
||||
for _, id := range ids {
|
||||
if st, ok := r.states[id]; ok {
|
||||
out[id] = st
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
type poolReconcileGate struct {
|
||||
@@ -76,18 +84,21 @@ func (w *poolReconcileWarmup) RemoveFromAllPools(_ context.Context, accountID uu
|
||||
}
|
||||
|
||||
type poolReconcileFixture struct {
|
||||
svc *tasksService
|
||||
gate *poolReconcileGate
|
||||
warmup *poolReconcileWarmup
|
||||
emails *poolReconcileEmailRepo
|
||||
orgPaid uuid.UUID
|
||||
orgFree uuid.UUID
|
||||
svc *tasksService
|
||||
gate *poolReconcileGate
|
||||
warmup *poolReconcileWarmup
|
||||
risk *poolReconcileRisk
|
||||
accounts map[uuid.UUID]*repository.WarmupParticipantMembership
|
||||
orgPaid uuid.UUID
|
||||
orgFree uuid.UUID
|
||||
}
|
||||
|
||||
func newPoolReconcileFixture() *poolReconcileFixture {
|
||||
f := &poolReconcileFixture{
|
||||
orgPaid: uuid.New(),
|
||||
orgFree: uuid.New(),
|
||||
orgPaid: uuid.New(),
|
||||
orgFree: uuid.New(),
|
||||
accounts: map[uuid.UUID]*repository.WarmupParticipantMembership{},
|
||||
risk: &poolReconcileRisk{states: map[uuid.UUID]models.OrgRiskState{}},
|
||||
}
|
||||
f.gate = &poolReconcileGate{entitled: map[uuid.UUID]bool{}}
|
||||
f.warmup = &poolReconcileWarmup{
|
||||
@@ -95,7 +106,6 @@ func newPoolReconcileFixture() *poolReconcileFixture {
|
||||
removed: map[uuid.UUID]bool{},
|
||||
inPool: map[uuid.UUID]string{},
|
||||
}
|
||||
f.emails = &poolReconcileEmailRepo{accounts: map[uuid.UUID]*models.Email{}}
|
||||
f.gate.entitled[f.orgPaid] = true
|
||||
f.gate.entitled[f.orgFree] = false
|
||||
return f
|
||||
@@ -105,8 +115,8 @@ func newPoolReconcileFixture() *poolReconcileFixture {
|
||||
func (f *poolReconcileFixture) mailbox(orgID uuid.UUID, poolType, sittingIn string) uuid.UUID {
|
||||
id := uuid.New()
|
||||
org := orgID
|
||||
f.emails.accounts[id] = &models.Email{
|
||||
ID: id,
|
||||
f.accounts[id] = &repository.WarmupParticipantMembership{
|
||||
EmailAccountID: id,
|
||||
OrganizationID: &org,
|
||||
Status: "active",
|
||||
WarmupPoolType: poolType,
|
||||
@@ -117,15 +127,17 @@ func (f *poolReconcileFixture) mailbox(orgID uuid.UUID, poolType, sittingIn stri
|
||||
|
||||
func (f *poolReconcileFixture) run(t *testing.T) (int, int) {
|
||||
t.Helper()
|
||||
participants := make([]uuid.UUID, 0, len(f.warmup.inPool))
|
||||
for id := range f.warmup.inPool {
|
||||
participants = append(participants, id)
|
||||
members := make([]repository.WarmupParticipantMembership, 0, len(f.warmup.inPool))
|
||||
for id, pool := range f.warmup.inPool {
|
||||
m := *f.accounts[id]
|
||||
m.PoolTypes = []string{pool}
|
||||
members = append(members, m)
|
||||
}
|
||||
f.svc = &tasksService{
|
||||
warmupRepo: &poolReconcileWarmupRepo{participants: participants},
|
||||
emailRepo: f.emails,
|
||||
warmupRepo: &poolReconcileWarmupRepo{members: members},
|
||||
featureGate: f.gate,
|
||||
warmupHealth: f.warmup,
|
||||
orgRiskRepo: f.risk,
|
||||
}
|
||||
moved, removed, err := f.svc.ReconcileWarmupPoolMembership(context.Background())
|
||||
if err != nil {
|
||||
@@ -199,26 +211,21 @@ func TestPoolReconcileLeavesMembershipAloneWhenEntitlementCannotBeRead(t *testin
|
||||
}
|
||||
}
|
||||
|
||||
// A participant row whose mailbox is gone, suspended, or has no workspace has
|
||||
// nothing left to check an entitlement against, so it leaves the shared pool.
|
||||
// A participant whose mailbox is suspended or has no workspace has nothing left
|
||||
// to check an entitlement against, so it leaves the shared pool. A deleted
|
||||
// mailbox takes its participant rows with it (ON DELETE CASCADE).
|
||||
func TestPoolReconcileEvictsMailboxesItCannotVouchFor(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
account func(id uuid.UUID) *models.Email
|
||||
name string
|
||||
adjust func(m *repository.WarmupParticipantMembership)
|
||||
}{
|
||||
{"deleted", func(uuid.UUID) *models.Email { return nil }},
|
||||
{"inactive", func(id uuid.UUID) *models.Email {
|
||||
org := uuid.New()
|
||||
return &models.Email{ID: id, OrganizationID: &org, Status: "inactive", WarmupPoolType: "premium"}
|
||||
}},
|
||||
{"no workspace", func(id uuid.UUID) *models.Email {
|
||||
return &models.Email{ID: id, Status: "active", WarmupPoolType: "premium"}
|
||||
}},
|
||||
{"inactive", func(m *repository.WarmupParticipantMembership) { m.Status = "inactive" }},
|
||||
{"no workspace", func(m *repository.WarmupParticipantMembership) { m.OrganizationID = nil }},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
f := newPoolReconcileFixture()
|
||||
id := f.mailbox(f.orgPaid, "premium", "premium")
|
||||
f.emails.accounts[id] = c.account(id)
|
||||
c.adjust(f.accounts[id])
|
||||
|
||||
_, removed := f.run(t)
|
||||
|
||||
@@ -247,7 +254,6 @@ func TestPoolReconcileAsksAboutEachOrganizationOnce(t *testing.T) {
|
||||
func TestPoolReconcileReportsAListingFailure(t *testing.T) {
|
||||
svc := &tasksService{
|
||||
warmupRepo: &poolReconcileWarmupRepo{listErr: errors.New("connection reset by peer")},
|
||||
emailRepo: &poolReconcileEmailRepo{},
|
||||
warmupHealth: &poolReconcileWarmup{},
|
||||
}
|
||||
|
||||
|
||||
@@ -90,27 +90,25 @@ func TestResolveWarmupPoolTypeFallsBackToEntitlementWithoutAStoredTier(t *testin
|
||||
}
|
||||
|
||||
// The reconciler is what moves a mailbox that is not actively warming (a
|
||||
// recipient-only member, say), so restriction has to reach it there too.
|
||||
// recipient-only member, say), so restriction has to reach it there too. Every
|
||||
// workspace's risk is read in one query per pass.
|
||||
func TestPoolReconcileMovesARestrictedOrganizationToTheFreePool(t *testing.T) {
|
||||
f := newPoolReconcileFixture()
|
||||
restricted := f.mailbox(f.orgPaid, "premium", "premium")
|
||||
participants := []uuid.UUID{restricted}
|
||||
f.svc = &tasksService{
|
||||
warmupRepo: &poolReconcileWarmupRepo{participants: participants},
|
||||
emailRepo: f.emails,
|
||||
featureGate: f.gate,
|
||||
warmupHealth: f.warmup,
|
||||
orgRiskRepo: &poolTypeRiskRepo{states: map[uuid.UUID]models.OrgRiskState{f.orgPaid: models.OrgRiskRestricted}},
|
||||
}
|
||||
other := uuid.New()
|
||||
f.gate.entitled[other] = true
|
||||
f.mailbox(other, "premium", "premium")
|
||||
f.risk.states[f.orgPaid] = models.OrgRiskRestricted
|
||||
|
||||
moved, removed := f.run(t)
|
||||
|
||||
moved, removed, err := f.svc.ReconcileWarmupPoolMembership(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("reconcile: %v", err)
|
||||
}
|
||||
if moved != 1 || removed != 0 {
|
||||
t.Fatalf("moved %d removed %d, want 1 and 0", moved, removed)
|
||||
}
|
||||
if f.warmup.moved[restricted] != "free" {
|
||||
t.Fatalf("moved to %q, want free", f.warmup.moved[restricted])
|
||||
}
|
||||
if f.risk.calls != 1 {
|
||||
t.Fatalf("read risk %d times, want once per pass", f.risk.calls)
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user