From d3422047cdbf5d4ec5a8f0679ecf065473367cd0 Mon Sep 17 00:00:00 2001 From: Tugser OKUR Date: Mon, 26 Oct 2026 14:17:25 +0300 Subject: [PATCH 001/318] feat: preserve Remie final answers and completed tool history within the run budget with provider and cancellation regression coverage --- docs/content/docs/guides/ai-assistant.mdx | 6 +- internal/app/aiagent/credits_test.go | 116 ++++++ internal/app/aiagent/run_test.go | 350 ++++++++++++++++++ internal/app/aiagent/service.go | 33 +- internal/app/aiagent/service_test.go | 31 ++ .../generation/agent_final_response_test.go | 267 +++++++++++++ internal/pkg/generation/anthropic_provider.go | 24 +- internal/pkg/generation/openai_provider.go | 26 +- internal/pkg/generation/openai_tools_test.go | 50 +++ internal/pkg/generation/provider.go | 15 +- internal/pkg/generation/tool_catalog.go | 9 +- 11 files changed, 889 insertions(+), 38 deletions(-) create mode 100644 internal/app/aiagent/credits_test.go create mode 100644 internal/app/aiagent/run_test.go create mode 100644 internal/pkg/generation/agent_final_response_test.go diff --git a/docs/content/docs/guides/ai-assistant.mdx b/docs/content/docs/guides/ai-assistant.mdx index d7a559616..c053c7726 100644 --- a/docs/content/docs/guides/ai-assistant.mdx +++ b/docs/content/docs/guides/ai-assistant.mdx @@ -116,7 +116,7 @@ These preferences are yours alone, kept in your browser for each workspace. It knows what page you are on, so "summarize this campaign" and "draft a reply here" resolve correctly. -When the available tools exceed the OpenAI-compatible provider's 128-tool limit, Remie discovers the tools it needs on demand, including tools from connected MCP servers. No permitted capability is removed. Discovery is a read-only step; the action itself keeps its normal permissions and approval requirements. Like other model steps, discovery counts toward the run's step budget and AI credits. +When the available tools exceed the OpenAI-compatible provider's 128-tool limit, Remie discovers the tools it needs on demand, including tools from connected MCP servers. Discovery results include each tool's argument schema, so its usage remains available in the conversation after another search. No permitted capability is removed. Discovery is a read-only step; the action itself keeps its normal permissions and approval requirements. Like other model steps, discovery counts toward the run's step budget and AI credits. @@ -149,8 +149,8 @@ Settings > Workspace > Remie lists every action that is always allowed, who allo ## Credits and privacy -Each step costs one AI credit, and a request is capped at a set number of steps (shown as the run progresses) so nothing runs away. Remaining credits show at the panel's bottom, and the stop button ends a run anytime. On a self-hosted install with a free or local model, runs are not charged and a "free model" notice appears. +Each model turn costs one AI credit, and a run is capped at 20 model turns between approval pauses. A turn can call several tools, so the activity list can show more than 20 tool steps. Remie reserves the last turn for an answer from the evidence already gathered, without calling more tools. If it cannot verify the answer, it is instructed to explain what remains unknown and what to check next. An empty provider answer is reported as an error. Remaining credits show at the panel's bottom, and the stop button ends a run anytime. On a self-hosted install with a free or local model, runs are not charged and a "free model" notice appears. -Changes Remie makes (a created task, an updated contact) appear in the shared activity feed like any other edit, so teammates' views stay current. +Completed tool steps stay in the conversation history if a later provider call fails or you stop the run. Remie gives recording those steps and refunding a failed model turn up to five seconds to finish after cancellation. Changes Remie makes (a created task, an updated contact) appear in the shared activity feed like any other edit, so teammates' views stay current. diff --git a/internal/app/aiagent/credits_test.go b/internal/app/aiagent/credits_test.go new file mode 100644 index 000000000..89cf440f9 --- /dev/null +++ b/internal/app/aiagent/credits_test.go @@ -0,0 +1,116 @@ +package aiagent + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/google/uuid" + + "github.com/warmbly/warmbly/internal/app/aitools" + "github.com/warmbly/warmbly/internal/app/credits" + "github.com/warmbly/warmbly/internal/errx" + "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/pkg/generation" +) + +type runCreditLedger struct { + credits.CreditService + balance, attempts, refunded, settlements, settledCredits, settledTokens int + keys []string +} + +func (l *runCreditLedger) Consume(ctx context.Context, _ uuid.UUID, amount int, _, _ string, _ int, key string) (int, error) { + if err := ctx.Err(); err != nil { + return l.balance, err + } + l.attempts++ + if l.balance < amount { + return l.balance, credits.ErrInsufficientCredits + } + l.balance -= amount + l.keys = append(l.keys, key) + return l.balance, nil +} + +func (l *runCreditLedger) Grant(ctx context.Context, _ uuid.UUID, amount int, _ string) (int, *errx.Error) { + if ctx.Err() != nil { + return l.balance, errx.New(errx.Internal, "credit context is canceled") + } + l.refunded += amount + l.balance += amount + return l.balance, nil +} + +func (l *runCreditLedger) SettleUsage(ctx context.Context, _ uuid.UUID, charged int, _ string, tokens int, _, _ string) (int, error) { + if err := ctx.Err(); err != nil { + return 0, err + } + l.settlements++ + l.settledCredits, l.settledTokens = charged, tokens + return 0, nil +} + +func TestRunMessageChargesReservedAnswerWithinBudget(t *testing.T) { + for _, tc := range []struct { + name string + balance, wantRequests, wantCharged, wantRefund, wantBalance, wantRows, wantSettlements int + wantCode string + }{ + {name: "answer", balance: 50, wantRequests: 20, wantCharged: 20, wantBalance: 30, wantRows: 40, wantSettlements: 1}, + {name: "empty_answer", balance: 50, wantRequests: 20, wantCharged: 20, wantRefund: 1, wantBalance: 31, wantRows: 39, wantCode: "provider_error"}, + {name: "no_credit_for_answer", balance: 19, wantRequests: 19, wantCharged: 19, wantBalance: 0, wantRows: 39, wantSettlements: 1, wantCode: "insufficient_credits"}, + } { + t.Run(tc.name, func(t *testing.T) { + requests := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests++ + message := map[string]any{"role": "assistant", "content": "The mailbox is paused."} + if requests < 20 { + message["content"], message["tool_calls"] = "", []any{map[string]any{ + "id": fmt.Sprint(requests), "type": "function", "function": map[string]string{"name": "read", "arguments": `{}`}, + }} + } else if tc.name == "empty_answer" { + message["content"] = "" + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "choices": []any{map[string]any{"message": message}}, "usage": map[string]int{"total_tokens": 10}, + }) + })) + defer srv.Close() + provider, err := generation.NewProvider(generation.ProviderConfig{ + OpenAIAPIKey: "fixture", OpenAIBaseURL: srv.URL, OpenAIModelPaid: "fixture-model", + }) + if err != nil { + t.Fatal(err) + } + registry := aitools.NewRegistry() + registry.Register(aitools.Tool{Name: "read", Risk: generation.RiskRead, Handler: func(context.Context, aitools.Invocation, json.RawMessage) (string, error) { + return `{"status":"paused"}`, nil + }}) + repo := &runRepository{session: models.AgentSession{ID: uuid.New(), OrgID: uuid.New(), UserID: uuid.New()}} + ledger := &runCreditLedger{balance: tc.balance} + svc := NewService(repo, registry, provider, ledger, runFeatureGate{}, nil, nil, nil, nil) + var last StreamEvent + if xerr := svc.RunMessage(context.Background(), aitools.Invocation{OrgID: repo.session.OrgID, UserID: repo.session.UserID}, repo.session.ID, "paid-message", "Inspect sending", "", "", func(ev StreamEvent) { last = ev }); xerr != nil { + t.Fatal(xerr) + } + if requests != tc.wantRequests || ledger.attempts != 20 || len(ledger.keys) != tc.wantCharged || ledger.refunded != tc.wantRefund || ledger.balance != tc.wantBalance { + t.Fatalf("requests=%d attempts=%d charged=%d refunded=%d balance=%d", requests, ledger.attempts, len(ledger.keys), ledger.refunded, ledger.balance) + } + if ledger.keys[0] != "paid-message:1" || ledger.keys[len(ledger.keys)-1] != fmt.Sprintf("paid-message:%d", tc.wantCharged) { + t.Fatalf("credit idempotency keys changed: %v", ledger.keys) + } + if ledger.settlements != tc.wantSettlements || tc.wantSettlements > 0 && (ledger.settledCredits != tc.wantCharged || ledger.settledTokens != tc.wantRequests*10) { + t.Fatalf("settlements=%d credits=%d tokens=%d", ledger.settlements, ledger.settledCredits, ledger.settledTokens) + } + if last.Code != tc.wantCode || last.CreditsRemaining != tc.wantBalance || len(repo.rows) != tc.wantRows { + t.Fatalf("event=%+v persisted rows=%d", last, len(repo.rows)) + } + }) + } +} diff --git a/internal/app/aiagent/run_test.go b/internal/app/aiagent/run_test.go new file mode 100644 index 000000000..9c1f5f3ac --- /dev/null +++ b/internal/app/aiagent/run_test.go @@ -0,0 +1,350 @@ +package aiagent + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/google/uuid" + + "github.com/warmbly/warmbly/internal/app/aitools" + "github.com/warmbly/warmbly/internal/errx" + "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/pkg/generation" + "github.com/warmbly/warmbly/internal/repository" +) + +type runRepository struct { + repository.AgentRepository + session models.AgentSession + rows []models.AgentMessageRow + policies map[string]string + afterAppend func(context.Context) +} + +func (r *runRepository) GetSession(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) (*models.AgentSession, error) { + session := r.session + return &session, nil +} + +func (r *runRepository) LoadTranscript(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) ([]models.AgentMessageRow, error) { + return r.rows, nil +} + +func (r *runRepository) AppendMessages(ctx context.Context, _, _, _ uuid.UUID, rows []models.AgentMessageRow) error { + if err := ctx.Err(); err != nil { + return err + } + r.rows = append(r.rows, rows...) + if r.afterAppend != nil { + r.afterAppend(ctx) + } + return nil +} + +func (r *runRepository) UpdateSessionContext(_ context.Context, _, _, _ uuid.UUID, sctx models.AgentSessionContext) error { + r.session.Context = sctx + return nil +} + +func (r *runRepository) UpdateSessionTitle(context.Context, uuid.UUID, uuid.UUID, uuid.UUID, string) error { + return nil +} + +func (r *runRepository) GetToolPolicies(context.Context, uuid.UUID) (map[string]string, error) { + return r.policies, nil +} + +func (r *runRepository) ClearPendingTool(ctx context.Context, _ uuid.UUID, _ uuid.UUID) error { + if err := ctx.Err(); err != nil { + return err + } + r.session.Context.Pending = nil + return nil +} + +func (r *runRepository) ClaimPendingTool(_ context.Context, _, _ uuid.UUID, callID string) (*models.PendingAgentTool, error) { + pending := r.session.Context.Pending + if pending == nil || pending.ToolCallID != callID { + return nil, nil + } + r.session.Context.Pending = nil + return pending, nil +} + +type runFeatureGate struct{} + +func (runFeatureGate) IsPaidOrganization(context.Context, uuid.UUID) (bool, *errx.Error) { + return true, nil +} + +func TestRunMessageAnswersBeforeBudgetIsExhausted(t *testing.T) { + const answer = "No sending mailbox matched that address, so I could not verify why it did not send." + requests, executions := 0, 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var req struct { + Tools []json.RawMessage `json:"tools"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + t.Error(err) + } + requests++ + message := map[string]any{"role": "assistant", "content": answer} + if len(req.Tools) > 0 { + calls := make([]map[string]any, 3) + for i := range calls { + calls[i] = map[string]any{ + "id": fmt.Sprintf("call-%d-%d", requests, i), "type": "function", + "function": map[string]string{"name": "list_mailboxes", "arguments": `{}`}, + } + } + message["content"], message["tool_calls"] = "", calls + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "choices": []any{map[string]any{"message": message}}, + "usage": map[string]int{"total_tokens": 10}, + }) + })) + defer srv.Close() + provider, err := generation.NewProvider(generation.ProviderConfig{ + OpenAIAPIKey: "fixture", OpenAIBaseURL: srv.URL, Local: true, + }) + if err != nil { + t.Fatal(err) + } + registry := aitools.NewRegistry() + registry.Register(aitools.Tool{ + Name: "list_mailboxes", Risk: generation.RiskRead, + InputSchema: map[string]any{"type": "object", "properties": map[string]any{}}, + Handler: func(context.Context, aitools.Invocation, json.RawMessage) (string, error) { + executions++ + return `{"mailboxes":[],"count":0}`, nil + }, + }) + repo := &runRepository{session: models.AgentSession{ID: uuid.New(), OrgID: uuid.New(), UserID: uuid.New()}} + inv := aitools.Invocation{OrgID: repo.session.OrgID, UserID: repo.session.UserID} + svc := NewService(repo, registry, provider, nil, runFeatureGate{}, nil, nil, nil, nil) + var events []StreamEvent + if xerr := svc.RunMessage(context.Background(), inv, repo.session.ID, "message-1", "Why did this mailbox not send?", "", "", func(ev StreamEvent) { + events = append(events, ev) + }); xerr != nil { + t.Fatal(xerr) + } + if requests != 20 || executions != 57 { + t.Errorf("requests=%d tool executions=%d, want 20 and 57 (one round reserved for the answer)", requests, executions) + } + if len(events) < 2 || events[len(events)-2].Type != evText || events[len(events)-2].Text != answer || events[len(events)-1].Type != evDone { + t.Errorf("run did not emit its answer before done: last event=%+v", events[len(events)-1]) + } + turns, _, xerr := svc.Transcript(context.Background(), inv, repo.session.ID) + if xerr != nil { + t.Fatal(xerr) + } + blocks := turns[len(turns)-1].Blocks + if blocks[len(blocks)-1].Kind != "text" || blocks[len(blocks)-1].Text != answer { + t.Errorf("reopened conversation has no final answer: last block=%+v", blocks[len(blocks)-1]) + } +} + +func TestRunMessageReportsEmptyProviderAnswer(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"choices":[{"message":{"role":"assistant","content":""}}]}`)) + })) + defer srv.Close() + provider, err := generation.NewProvider(generation.ProviderConfig{ + OpenAIAPIKey: "fixture", OpenAIBaseURL: srv.URL, Local: true, + }) + if err != nil { + t.Fatal(err) + } + repo := &runRepository{session: models.AgentSession{ID: uuid.New(), OrgID: uuid.New(), UserID: uuid.New()}} + svc := NewService(repo, aitools.NewRegistry(), provider, nil, runFeatureGate{}, nil, nil, nil, nil) + var events []StreamEvent + if xerr := svc.RunMessage(context.Background(), aitools.Invocation{OrgID: repo.session.OrgID, UserID: repo.session.UserID}, repo.session.ID, "message-1", "Inspect sending", "", "", func(ev StreamEvent) { + events = append(events, ev) + }); xerr != nil { + t.Fatal(xerr) + } + if last := events[len(events)-1]; last.Type != evError || last.Code != "provider_error" || last.Message == "" { + t.Fatalf("empty answer did not produce a visible error: %+v", last) + } +} + +func TestRunMessagePreservesCompletedActionsWhenFinalResponseFails(t *testing.T) { + for _, failure := range []string{"empty", "unexpected_tool", "provider_error"} { + t.Run(failure, func(t *testing.T) { + requests, writes := 0, 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests++ + w.Header().Set("Content-Type", "application/json") + message := map[string]any{"role": "assistant", "content": ""} + tool := "list_mailboxes" + if requests == 1 || failure == "unexpected_tool" && requests == 20 { + tool = "update_contact_fields" + } + if requests < 20 || failure == "unexpected_tool" { + message["tool_calls"] = []any{map[string]any{ + "id": fmt.Sprintf("call-%d", requests), "type": "function", + "function": map[string]string{"name": tool, "arguments": `{}`}, + }} + } else if failure == "provider_error" { + w.WriteHeader(http.StatusBadGateway) + _, _ = w.Write([]byte(`{"error":{"message":"fixture upstream unavailable"}}`)) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{"choices": []any{map[string]any{"message": message}}}) + })) + defer srv.Close() + provider, err := generation.NewProvider(generation.ProviderConfig{OpenAIAPIKey: "fixture", OpenAIBaseURL: srv.URL, Local: true}) + if err != nil { + t.Fatal(err) + } + registry := aitools.NewRegistry() + registry.Register(aitools.Tool{Name: "update_contact_fields", Risk: generation.RiskWrite, Handler: func(context.Context, aitools.Invocation, json.RawMessage) (string, error) { + writes++ + return `{"updated":true}`, nil + }}) + registry.Register(aitools.Tool{Name: "list_mailboxes", Risk: generation.RiskRead, Handler: func(context.Context, aitools.Invocation, json.RawMessage) (string, error) { + return `{"mailboxes":[],"count":0}`, nil + }}) + repo := &runRepository{ + session: models.AgentSession{ID: uuid.New(), OrgID: uuid.New(), UserID: uuid.New()}, + policies: map[string]string{"update_contact_fields": "always_allow"}, + } + svc := NewService(repo, registry, provider, nil, runFeatureGate{}, nil, nil, nil, nil) + inv := aitools.Invocation{OrgID: repo.session.OrgID, UserID: repo.session.UserID} + var last StreamEvent + if xerr := svc.RunMessage(context.Background(), inv, repo.session.ID, "message-1", "Update the contact and inspect sending", "", "", func(ev StreamEvent) { last = ev }); xerr != nil { + t.Fatal(xerr) + } + if requests != 20 || writes != 1 || last.Type != evError { + t.Fatalf("requests=%d writes=%d last=%+v", requests, writes, last) + } + turns, _, xerr := svc.Transcript(context.Background(), inv, repo.session.ID) + if xerr != nil { + t.Fatal(xerr) + } + if len(turns) != 2 || len(turns[1].Blocks) != 19 || turns[1].Blocks[0].Tool != "update_contact_fields" || turns[1].Blocks[0].Result != `{"updated":true}` { + t.Fatalf("completed actions were lost after a failed final response: %+v", turns) + } + }) + } +} + +func TestResumePreservesApprovedActionWhenProviderFails(t *testing.T) { + requests, writes := 0, 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests++ + w.Header().Set("Content-Type", "application/json") + if requests == 1 { + _, _ = w.Write([]byte(`{"choices":[{"message":{"role":"assistant","tool_calls":[{"id":"approved-call","type":"function","function":{"name":"update_contact_fields","arguments":"{}"}}]}}]}`)) + return + } + _, _ = w.Write([]byte(`{"choices":[{"message":{"role":"assistant","content":""}}]}`)) + })) + defer srv.Close() + provider, err := generation.NewProvider(generation.ProviderConfig{OpenAIAPIKey: "fixture", OpenAIBaseURL: srv.URL, Local: true}) + if err != nil { + t.Fatal(err) + } + registry := aitools.NewRegistry() + registry.Register(aitools.Tool{Name: "update_contact_fields", Risk: generation.RiskWrite, Handler: func(context.Context, aitools.Invocation, json.RawMessage) (string, error) { + writes++ + return `{"updated":true}`, nil + }}) + repo := &runRepository{session: models.AgentSession{ID: uuid.New(), OrgID: uuid.New(), UserID: uuid.New()}} + svc := NewService(repo, registry, provider, nil, runFeatureGate{}, nil, nil, nil, nil) + inv := aitools.Invocation{OrgID: repo.session.OrgID, UserID: repo.session.UserID} + var last StreamEvent + emit := func(ev StreamEvent) { last = ev } + if xerr := svc.RunMessage(context.Background(), inv, repo.session.ID, "approval-message", "Update the contact", "", "", emit); xerr != nil { + t.Fatal(xerr) + } + if writes != 0 || requests != 1 || last.Message != "awaiting_approval" { + t.Fatalf("action did not pause for approval: writes=%d requests=%d event=%+v", writes, requests, last) + } + if xerr := svc.Resume(context.Background(), inv, repo.session.ID, "another-call", "approve", emit); xerr != errApprovalNotPending { + t.Fatalf("an unrelated approval was accepted: %v", xerr) + } + if xerr := svc.Resume(context.Background(), inv, repo.session.ID, "approved-call", "approve", emit); xerr != nil { + t.Fatal(xerr) + } + if requests != 2 || writes != 1 || last.Type != evError || last.Code != "provider_error" { + t.Fatalf("approved action was not executed once before the provider failure: writes=%d requests=%d event=%+v", writes, requests, last) + } + turns, pending, xerr := svc.Transcript(context.Background(), inv, repo.session.ID) + if xerr != nil { + t.Fatal(xerr) + } + if pending != nil || len(turns) != 2 || len(turns[1].Blocks) != 1 || turns[1].Blocks[0].Result != `{"updated":true}` { + t.Fatalf("approved action was not retained: turns=%+v pending=%+v", turns, pending) + } + if xerr := svc.Resume(context.Background(), inv, repo.session.ID, "approved-call", "approve", emit); xerr != errApprovalNotPending || requests != 2 || writes != 1 { + t.Fatalf("approval replay changed state: err=%v writes=%d requests=%d", xerr, writes, requests) + } +} + +func TestRunMessagePreservesCompletedActionsAfterCancellation(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + requests, writes := 0, 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests++ + w.Header().Set("Content-Type", "application/json") + if requests == 1 { + _, _ = w.Write([]byte(`{"choices":[{"message":{"role":"assistant","tool_calls":[{"id":"completed-write","type":"function","function":{"name":"update_contact_fields","arguments":"{}"}}]}}]}`)) + return + } + cancel() + _, _ = w.Write([]byte(`{"choices":[{"message":{"role":"assistant","content":""}}]}`)) + })) + defer srv.Close() + provider, err := generation.NewProvider(generation.ProviderConfig{OpenAIAPIKey: "fixture", OpenAIBaseURL: srv.URL, OpenAIModelPaid: "fixture-model"}) + if err != nil { + t.Fatal(err) + } + registry := aitools.NewRegistry() + registry.Register(aitools.Tool{Name: "update_contact_fields", Risk: generation.RiskWrite, Handler: func(context.Context, aitools.Invocation, json.RawMessage) (string, error) { + writes++ + return `{"updated":true}`, nil + }}) + repo := &runRepository{ + session: models.AgentSession{ID: uuid.New(), OrgID: uuid.New(), UserID: uuid.New()}, + policies: map[string]string{"update_contact_fields": "always_allow"}, + } + ledger := &runCreditLedger{balance: 50} + repo.afterAppend = func(receiptCtx context.Context) { + if ctx.Err() != nil { + if _, bounded := receiptCtx.Deadline(); !bounded { + t.Error("canceled-run receipt persistence must have a deadline") + } + repo.session.Context.Pending = &models.PendingAgentTool{ToolCallID: "newer-run-call", ToolName: "update_contact_fields", Risk: "write"} + } + } + svc := NewService(repo, registry, provider, ledger, runFeatureGate{}, nil, nil, nil, nil) + inv := aitools.Invocation{OrgID: repo.session.OrgID, UserID: repo.session.UserID} + if xerr := svc.RunMessage(ctx, inv, repo.session.ID, "canceled-message", "Update the contact", "", "", func(StreamEvent) {}); xerr != nil { + t.Fatal(xerr) + } + if ctx.Err() == nil || requests != 2 || writes != 1 { + t.Fatalf("fixture did not cancel after one completed action: canceled=%v requests=%d writes=%d", ctx.Err(), requests, writes) + } + if ledger.refunded != 1 || ledger.balance != 49 { + t.Errorf("cancellation lost the failed iteration refund: refunded=%d balance=%d", ledger.refunded, ledger.balance) + } + turns, pending, xerr := svc.Transcript(context.Background(), inv, repo.session.ID) + if xerr != nil { + t.Fatal(xerr) + } + if len(turns) != 2 || len(turns[1].Blocks) != 1 || turns[1].Blocks[0].Result != `{"updated":true}` { + t.Fatalf("request cancellation discarded a completed action: %+v", turns) + } + if pending == nil || pending.ToolCallID != "newer-run-call" { + t.Fatalf("canceled run cleared a newer run's approval: %+v", pending) + } +} diff --git a/internal/app/aiagent/service.go b/internal/app/aiagent/service.go index 31de21afc..e97257029 100644 --- a/internal/app/aiagent/service.go +++ b/internal/app/aiagent/service.go @@ -527,11 +527,12 @@ func (s *service) runLoop(ctx context.Context, inv aitools.Invocation, sess *mod voiceBlock = s.voice.VoiceInstructions(ctx, inv.OrgID) } req := generation.AgentRequest{ - System: s.systemPrompt(sess, voiceBlock, skillsBlock), - Messages: genMsgs, - Tools: s.boundTools(ctx, inv, emit), - Model: model, - MaxIterations: DefaultRunBudget, + System: s.systemPrompt(sess, voiceBlock, skillsBlock), + Messages: genMsgs, + Tools: s.boundTools(ctx, inv, emit), + Model: model, + MaxIterations: DefaultRunBudget, + ReserveFinalResponse: true, OnEvent: func(ev generation.AgentEvent) { switch ev.Type { case generation.EventText: @@ -603,6 +604,15 @@ func (s *service) runLoop(ctx context.Context, inv aitools.Invocation, sess *mod } result, rerr := s.provider.RunAgent(ctx, req) + // Receipts and refunds get a bounded window after request cancellation. + finalizeCtx, cancelFinalize := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + defer cancelFinalize() + // Preserve completed tool actions even when a later provider call fails. + if result != nil && len(result.Messages) > baseline { + if perr := s.persist(finalizeCtx, sess.OrgID, sess.UserID, sess.ID, result.Messages[baseline:], result.TokensUsed); perr != nil { + log.Printf("aiagent: transcript persist failed (org=%s session=%s): %v", inv.OrgID, sess.ID, perr) + } + } if rerr != nil { // The client only ever sees the generic message; the real cause goes to // the server log so a failing provider is debuggable. @@ -611,7 +621,7 @@ func (s *service) runLoop(ctx context.Context, inv aitools.Invocation, sess *mod // (PreIteration); refund it so the user is not billed for output they // never received. Nothing to refund on the free/local path. if chargeCredits { - if bal, gerr := s.credits.Grant(ctx, inv.OrgID, credits.CostAgentIteration, "agent_iteration_refund"); gerr == nil { + if bal, gerr := s.credits.Grant(finalizeCtx, inv.OrgID, credits.CostAgentIteration, "agent_iteration_refund"); gerr == nil { lastRemaining = bal } } @@ -630,13 +640,6 @@ func (s *service) runLoop(ctx context.Context, inv aitools.Invocation, sess *mod } } - // Persist the new transcript tail. - if len(result.Messages) > baseline { - if perr := s.persist(ctx, sess.OrgID, sess.UserID, sess.ID, result.Messages[baseline:], result.TokensUsed); perr != nil { - log.Printf("aiagent: transcript persist failed (org=%s session=%s): %v", inv.OrgID, sess.ID, perr) - } - } - switch result.StopReason { case "approval_required": _ = s.repo.UpdateSessionContext(ctx, sess.OrgID, sess.UserID, sess.ID, sess.Context) @@ -954,10 +957,10 @@ func summarize(tool, result string) string { if _, ok := m["withheld"]; ok { return "result withheld" } - if id, ok := m["campaign_id"]; ok { + if id, ok := m["campaign_id"]; ok && tool == "create_campaign_draft" { return fmt.Sprintf("created campaign %v", id) } - if id, ok := m["automation_id"]; ok { + if id, ok := m["automation_id"]; ok && tool == "create_automation_draft" { return fmt.Sprintf("created automation %v", id) } } diff --git a/internal/app/aiagent/service_test.go b/internal/app/aiagent/service_test.go index 97e525c6e..c5a26187e 100644 --- a/internal/app/aiagent/service_test.go +++ b/internal/app/aiagent/service_test.go @@ -100,3 +100,34 @@ func TestForReaderWithholdsResultsOfToolsTheReaderCannotRun(t *testing.T) { t.Error("the stored messages were modified") } } + +func TestTranscriptOnlyDescribesDraftToolsAsCreation(t *testing.T) { + for _, tc := range []struct{ tool, result, want string }{ + {"get_campaign_stats", `{"campaign_id":"c1","emails_sent":4}`, `{"campaign_id":"c1","emails_sent":4}`}, + {"get_automation", `{"automation_id":"a1"}`, `{"automation_id":"a1"}`}, + {"create_campaign_draft", `{"campaign_id":"c1"}`, "created campaign c1"}, + {"create_automation_draft", `{"automation_id":"a1"}`, "created automation a1"}, + } { + t.Run(tc.tool, func(t *testing.T) { + repo := &runRepository{session: models.AgentSession{ID: uuid.New(), OrgID: uuid.New(), UserID: uuid.New()}} + for _, message := range []generation.AgentMessage{ + {Role: "assistant", ToolCalls: []generation.ToolCall{{ID: "call", Name: tc.tool}}}, + {Role: "tool", ToolCallID: "call", Content: tc.result}, + } { + content, err := json.Marshal(message) + if err != nil { + t.Fatal(err) + } + repo.rows = append(repo.rows, models.AgentMessageRow{Role: message.Role, Content: content}) + } + svc := NewService(repo, nil, nil, nil, nil, nil, nil, nil, nil) + turns, _, xerr := svc.Transcript(context.Background(), aitools.Invocation{OrgID: repo.session.OrgID, UserID: repo.session.UserID}, repo.session.ID) + if xerr != nil { + t.Fatal(xerr) + } + if got := turns[0].Blocks[0].Result; got != tc.want { + t.Errorf("tool summary = %q, want %q", got, tc.want) + } + }) + } +} diff --git a/internal/pkg/generation/agent_final_response_test.go b/internal/pkg/generation/agent_final_response_test.go new file mode 100644 index 000000000..87bf4e6cc --- /dev/null +++ b/internal/pkg/generation/agent_final_response_test.go @@ -0,0 +1,267 @@ +package generation + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" +) + +type agentFixtureTransport struct{ handler http.Handler } + +func (tr agentFixtureTransport) RoundTrip(req *http.Request) (*http.Response, error) { + w := httptest.NewRecorder() + tr.handler.ServeHTTP(w, req) + return w.Result(), nil +} + +func agentFixtureProvider(kind string, handler http.Handler) Provider { + client := &http.Client{Transport: agentFixtureTransport{handler: handler}} + if kind == "anthropic" { + return &anthropicProvider{http: client} + } + return &openAIProvider{baseURL: "http://provider.test", http: client} +} + +func writeAgentFixture(w http.ResponseWriter, kind, text string, calls ...ToolCall) { + if kind != "anthropic" { + writeAgentResponse(w, kind == "openai-stream", text, calls...) + return + } + blocks := []antContentBlock{{Type: "text", Text: text}} + for _, call := range calls { + blocks = append(blocks, antContentBlock{Type: "tool_use", ID: call.ID, Name: call.Name, Input: call.Args}) + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "content": blocks, "usage": map[string]int{"input_tokens": 6, "output_tokens": 4}, + }) +} + +func TestAgentReservesFinalResponseOnlyWhenRequested(t *testing.T) { + for _, kind := range []string{"openai", "openai-stream", "anthropic"} { + for _, reserve := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/reserve=%t", kind, reserve), func(t *testing.T) { + requests, executions := 0, 0 + var iterations []int + var finalText string + provider := agentFixtureProvider(kind, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var req struct { + Tools []json.RawMessage `json:"tools"` + Messages json.RawMessage `json:"messages"` + System string `json:"system"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + t.Error(err) + } + requests++ + if reserve && requests == 2 { + if len(req.Tools) != 0 || !strings.Contains(string(req.Messages), "verified evidence") { + t.Error("final request must keep tool evidence and omit tools") + } + if !strings.Contains(req.System+string(req.Messages), "Do not invent findings") { + t.Error("final request lacks instructions to ground the answer") + } + writeAgentFixture(w, kind, "I could not verify the sending cause.") + return + } + writeAgentFixture(w, kind, "", ToolCall{ID: fmt.Sprint(requests), Name: "read", Args: json.RawMessage(`{}`)}) + })) + req := AgentRequest{ + Messages: []AgentMessage{{Role: "user", Content: "Why did sending stop?"}}, + Tools: []ToolDef{{Name: "read", Risk: RiskRead, Handler: func(context.Context, json.RawMessage) (string, error) { + executions++ + return "verified evidence", nil + }}}, + MaxIterations: 2, ReserveFinalResponse: reserve, + PreIteration: func(_ context.Context, iter int) error { iterations = append(iterations, iter); return nil }, + OnEvent: func(ev AgentEvent) { + if ev.Type == EventText { + finalText = ev.Text + } + }, + } + if kind == "openai" { + req.OnEvent = nil + } + result, err := provider.RunAgent(context.Background(), req) + if err != nil { + t.Fatal(err) + } + if requests != 2 || result.Iterations != 2 || result.TokensUsed != 20 || !reflect.DeepEqual(iterations, []int{1, 2}) || result.StopReason != "max_iterations" { + t.Fatalf("result=%+v requests=%d charged iterations=%v", result, requests, iterations) + } + if reserve { + last := result.Messages[len(result.Messages)-1] + if executions != 1 || result.Text != "I could not verify the sending cause." || kind != "openai" && finalText != result.Text || last.Role != "assistant" || last.Content != result.Text || len(last.ToolCalls) != 0 { + t.Fatalf("missing final answer: result=%+v executions=%d event=%q", result, executions, finalText) + } + } else if executions != 2 || result.Text != "" { + t.Fatalf("tool-only caller behavior changed: result=%+v executions=%d", result, executions) + } + }) + } + } +} + +func TestAgentReturnsEarlyAnswerWithoutSpendingReservedTurn(t *testing.T) { + for _, kind := range []string{"openai", "openai-stream", "anthropic"} { + t.Run(kind, func(t *testing.T) { + requests, charges := 0, 0 + provider := agentFixtureProvider(kind, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests++ + writeAgentFixture(w, kind, "The mailbox is paused.") + })) + result, err := provider.RunAgent(context.Background(), AgentRequest{ + Messages: []AgentMessage{{Role: "user", Content: "Why did sending stop?"}}, + ReserveFinalResponse: true, + PreIteration: func(context.Context, int) error { charges++; return nil }, + OnEvent: func(AgentEvent) {}, + }) + if err != nil { + t.Fatal(err) + } + if requests != 1 || charges != 1 || result.Iterations != 1 || result.StopReason != "stop" || result.Text != "The mailbox is paused." { + t.Fatalf("early answer spent extra turns: requests=%d charges=%d result=%+v", requests, charges, result) + } + }) + } +} + +func TestAgentRejectsEmptyAnswer(t *testing.T) { + for _, kind := range []string{"openai", "openai-stream", "anthropic"} { + t.Run(kind, func(t *testing.T) { + provider := agentFixtureProvider(kind, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + writeAgentFixture(w, kind, " ") + })) + req := AgentRequest{ + Messages: []AgentMessage{{Role: "user", Content: "Explain the sending status"}}, ReserveFinalResponse: true, + } + if kind == "openai-stream" { + req.OnEvent = func(AgentEvent) {} + } + result, err := provider.RunAgent(context.Background(), req) + if err == nil { + t.Fatalf("empty answer returned as success: %+v", result) + } + }) + } +} + +func TestAgentAllowsEmptyStopForToolOnlyCallers(t *testing.T) { + for _, kind := range []string{"openai", "openai-stream", "anthropic"} { + t.Run(kind, func(t *testing.T) { + provider := agentFixtureProvider(kind, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + writeAgentFixture(w, kind, "") + })) + result, err := provider.RunAgent(context.Background(), AgentRequest{ + Messages: []AgentMessage{ + {Role: "user", Content: "Save the findings and stop"}, + {Role: "assistant", ToolCalls: []ToolCall{{ID: "save-1", Name: "save_research", Args: json.RawMessage(`{}`)}}}, + {Role: "tool", ToolCallID: "save-1", Content: `{"saved":true}`}, + }, + OnEvent: func(AgentEvent) {}, + }) + if err != nil || result.StopReason != "stop" || result.Text != "" || len(result.Messages) != 4 { + t.Fatalf("tool-only completion changed: result=%+v err=%v", result, err) + } + }) + } +} + +func TestAgentHonorsStopBeforeReservedFinalResponse(t *testing.T) { + for _, kind := range []string{"openai", "openai-stream", "anthropic"} { + t.Run(kind, func(t *testing.T) { + requests := 0 + provider := agentFixtureProvider(kind, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests++ + writeAgentFixture(w, kind, "", ToolCall{ID: "read-1", Name: "read", Args: json.RawMessage(`{}`)}) + })) + result, err := provider.RunAgent(context.Background(), AgentRequest{ + Messages: []AgentMessage{{Role: "user", Content: "Inspect sending"}}, + Tools: []ToolDef{{Name: "read", Risk: RiskRead, Handler: func(context.Context, json.RawMessage) (string, error) { + return `{}`, nil + }}}, + MaxIterations: 2, ReserveFinalResponse: true, + OnEvent: func(AgentEvent) {}, + PreIteration: func(_ context.Context, iter int) error { + if iter == 2 { + return errors.New("no remaining credits") + } + return nil + }, + }) + if err != nil { + t.Fatal(err) + } + if requests != 1 || result.Iterations != 1 || result.StopReason != "stopped" || result.Messages[len(result.Messages)-1].Role != "tool" { + t.Fatalf("stop hook was bypassed: result=%+v requests=%d", result, requests) + } + }) + } +} + +func TestAgentNeverExecutesToolsInReservedResponse(t *testing.T) { + for _, kind := range []string{"openai", "openai-stream", "anthropic"} { + t.Run(kind, func(t *testing.T) { + provider := agentFixtureProvider(kind, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + writeAgentFixture(w, kind, "", ToolCall{ID: "write-1", Name: "write", Args: json.RawMessage(`{}`)}) + })) + executions, approvals := 0, 0 + _, err := provider.RunAgent(context.Background(), AgentRequest{ + Messages: []AgentMessage{{Role: "user", Content: "Inspect sending"}}, + Tools: []ToolDef{{Name: "write", Risk: RiskWrite, Handler: func(context.Context, json.RawMessage) (string, error) { + executions++ + return `{}`, nil + }}}, + MaxIterations: 1, ReserveFinalResponse: true, + OnEvent: func(AgentEvent) {}, + Approve: func(context.Context, ToolDef, ToolCall) error { approvals++; return nil }, + }) + if err == nil || executions != 0 || approvals != 0 { + t.Fatalf("unexpected final tool call: err=%v executions=%d approvals=%d", err, executions, approvals) + } + }) + } +} + +func TestAgentPreservesCompletedToolsWhenFinalResponseFails(t *testing.T) { + for _, kind := range []string{"openai", "openai-stream", "anthropic"} { + for _, failure := range []string{"empty", "unexpected_tool", "provider_error"} { + t.Run(kind+"/"+failure, func(t *testing.T) { + requests, executions := 0, 0 + provider := agentFixtureProvider(kind, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests++ + if requests == 1 || failure == "unexpected_tool" { + writeAgentFixture(w, kind, "", ToolCall{ID: fmt.Sprint(requests), Name: "read", Args: json.RawMessage(`{}`)}) + } else if failure == "provider_error" { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadGateway) + _, _ = w.Write([]byte(`{"error":{"message":"fixture upstream unavailable"}}`)) + } else { + writeAgentFixture(w, kind, "") + } + })) + result, err := provider.RunAgent(context.Background(), AgentRequest{ + Messages: []AgentMessage{{Role: "user", Content: "Inspect sending"}}, + Tools: []ToolDef{{Name: "read", Risk: RiskRead, Handler: func(context.Context, json.RawMessage) (string, error) { + executions++ + return "verified evidence", nil + }}}, + MaxIterations: 2, ReserveFinalResponse: true, OnEvent: func(AgentEvent) {}, + }) + if err == nil || result == nil { + t.Fatalf("expected partial result with error: result=%+v err=%v", result, err) + } + if requests != 2 || executions != 1 || len(result.Messages) != 3 || result.Messages[2].Content != "verified evidence" || result.StopReason != "error" { + t.Fatalf("completed turns were lost: result=%+v requests=%d executions=%d", result, requests, executions) + } + }) + } + } +} diff --git a/internal/pkg/generation/anthropic_provider.go b/internal/pkg/generation/anthropic_provider.go index 5070a7ea5..80cc9c80a 100644 --- a/internal/pkg/generation/anthropic_provider.go +++ b/internal/pkg/generation/anthropic_provider.go @@ -236,9 +236,10 @@ func (p *anthropicProvider) RunAgent(ctx context.Context, req AgentRequest) (*Ag tools := antToolsFromDefs(req.Tools, false) messages := append([]AgentMessage(nil), req.Messages...) - result := &AgentResult{Model: model} + result := &AgentResult{Model: model, StopReason: "error"} for iter := 0; iter < maxIter; iter++ { + result.Messages = messages if req.PreIteration != nil { if err := req.PreIteration(ctx, iter+1); err != nil { result.Messages = messages @@ -251,9 +252,15 @@ func (p *anthropicProvider) RunAgent(ctx context.Context, req AgentRequest) (*Ag req.OnEvent(AgentEvent{Type: EventIteration, Iteration: result.Iterations}) } - resp, err := p.complete(ctx, model, maxTokens, req.System, transcriptToAnthropic(messages), tools, nil) + iterationTools, system := tools, req.System + finalTurn := req.ReserveFinalResponse && iter == maxIter-1 + if finalTurn { + iterationTools = nil + system += agentFinalResponseInstructions + } + resp, err := p.complete(ctx, model, maxTokens, system, transcriptToAnthropic(messages), iterationTools, nil) if err != nil { - return nil, err + return result, err } result.TokensUsed += resp.Usage.InputTokens + resp.Usage.OutputTokens @@ -271,6 +278,9 @@ func (p *anthropicProvider) RunAgent(ctx context.Context, req AgentRequest) (*Ag if len(calls) == 0 { final := strings.TrimSpace(text.String()) + if final == "" && req.ReserveFinalResponse { + return result, errors.New("anthropic: empty agent response") + } messages = append(messages, AgentMessage{Role: "assistant", Content: final}) if req.OnEvent != nil && final != "" { req.OnEvent(AgentEvent{Type: EventText, Text: final}) @@ -278,8 +288,14 @@ func (p *anthropicProvider) RunAgent(ctx context.Context, req AgentRequest) (*Ag result.Text = final result.Messages = messages result.StopReason = "stop" + if finalTurn { + result.StopReason = "max_iterations" + } return result, nil } + if finalTurn { + return result, errors.New("anthropic: unexpected tool call in final response") + } // Approval gate before executing any tool (see OpenAI provider). if req.Approve != nil { @@ -295,7 +311,7 @@ func (p *anthropicProvider) RunAgent(ctx context.Context, req AgentRequest) (*Ag result.Pending = &PendingToolCall{Call: call, Risk: tool.Risk} return result, nil } - return nil, err + return result, err } } } diff --git a/internal/pkg/generation/openai_provider.go b/internal/pkg/generation/openai_provider.go index 3db1f1fef..0527a05b4 100644 --- a/internal/pkg/generation/openai_provider.go +++ b/internal/pkg/generation/openai_provider.go @@ -532,9 +532,10 @@ func (p *openAIProvider) RunAgent(ctx context.Context, req AgentRequest) (*Agent // messages is the durable transcript; we mutate a copy so the caller's // slice is not aliased. messages := append([]AgentMessage(nil), req.Messages...) - result := &AgentResult{Model: model} + result := &AgentResult{Model: model, StopReason: "error"} for iter := 0; iter < maxIter; iter++ { + result.Messages = messages if req.PreIteration != nil { if err := req.PreIteration(ctx, iter+1); err != nil { result.Messages = messages @@ -554,18 +555,24 @@ func (p *openAIProvider) RunAgent(ctx context.Context, req AgentRequest) (*Agent if catalog != nil { available = catalog.definitions() } + iterationSystem := system + finalTurn := req.ReserveFinalResponse && iter == maxIter-1 + if finalTurn { + available = nil + iterationSystem += agentFinalResponseInstructions + } wireTools := toolDefsToWire(available) var resp *oaiResponse var err error if req.OnEvent != nil { - resp, err = p.completeStream(ctx, model, maxTokens, transcriptToWire(system, messages), wireTools, nil, func(delta string) { + resp, err = p.completeStream(ctx, model, maxTokens, transcriptToWire(iterationSystem, messages), wireTools, nil, func(delta string) { req.OnEvent(AgentEvent{Type: EventTextDelta, Text: delta}) }) } else { - resp, err = p.complete(ctx, model, maxTokens, transcriptToWire(system, messages), wireTools, nil) + resp, err = p.complete(ctx, model, maxTokens, transcriptToWire(iterationSystem, messages), wireTools, nil) } if err != nil { - return nil, err + return result, err } result.TokensUsed += resp.Usage.TotalTokens choice := resp.Choices[0] @@ -573,6 +580,9 @@ func (p *openAIProvider) RunAgent(ctx context.Context, req AgentRequest) (*Agent // No tool calls: final answer. if len(choice.Message.ToolCalls) == 0 { text := strings.TrimSpace(choice.Message.Content) + if text == "" && req.ReserveFinalResponse { + return result, errors.New("openai: empty agent response") + } messages = append(messages, AgentMessage{Role: "assistant", Content: text}) if req.OnEvent != nil && text != "" { req.OnEvent(AgentEvent{Type: EventText, Text: text}) @@ -580,8 +590,14 @@ func (p *openAIProvider) RunAgent(ctx context.Context, req AgentRequest) (*Agent result.Text = text result.Messages = messages result.StopReason = "stop" + if finalTurn { + result.StopReason = "max_iterations" + } return result, nil } + if finalTurn { + return result, errors.New("openai: unexpected tool call in final response") + } // Commentary alongside tool calls streams too; close its block so the // client can finalize it before the tool chips appear. @@ -612,7 +628,7 @@ func (p *openAIProvider) RunAgent(ctx context.Context, req AgentRequest) (*Agent result.Pending = &PendingToolCall{Call: call, Risk: tool.Risk} return result, nil } - return nil, err + return result, err } } } diff --git a/internal/pkg/generation/openai_tools_test.go b/internal/pkg/generation/openai_tools_test.go index c0cac99d2..ebd732813 100644 --- a/internal/pkg/generation/openai_tools_test.go +++ b/internal/pkg/generation/openai_tools_test.go @@ -209,3 +209,53 @@ func TestOpenAIAgentDiscoveredToolPausesAndResumes(t *testing.T) { t.Fatalf("resumed = %+v, executions=%d requests=%d", resumed, executions, requests) } } + +func TestOpenAIAgentDiscoveryKeepsArgumentSchemasAcrossSearches(t *testing.T) { + tools := catalogTestTools(138) + tools[136].InputSchema = map[string]any{ + "type": "object", "properties": map[string]any{"contact_id": map[string]any{"type": "string"}}, "required": []string{"contact_id"}, + } + tools[137].InputSchema = map[string]any{ + "type": "object", "properties": map[string]any{"campaign_id": map[string]any{"type": "string"}}, "required": []string{"campaign_id"}, + } + requests := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + req := readAgentRequest(t, w, r) + requests++ + if requests == 1 { + writeAgentResponse(w, false, "", + ToolCall{ID: "search-contact", Name: req.Tools[0].Function.Name, Args: json.RawMessage(`{"query":"tool_0136"}`)}, + ToolCall{ID: "search-campaign", Name: req.Tools[0].Function.Name, Args: json.RawMessage(`{"query":"tool_0137"}`)}, + ) + return + } + for i, want := range []string{"contact_id", "campaign_id"} { + var result struct { + Tools []struct { + InputSchema struct { + Required []string `json:"required"` + } `json:"input_schema"` + } `json:"tools"` + } + message := req.Messages[len(req.Messages)-2+i] + if err := json.Unmarshal([]byte(message.Content), &result); err != nil { + t.Error(err) + } + if len(result.Tools) != 1 || !reflect.DeepEqual(result.Tools[0].InputSchema.Required, []string{want}) { + t.Errorf("discovery result lost required %s argument: %s", want, message.Content) + } + } + writeAgentResponse(w, false, "Done") + })) + defer srv.Close() + p := &openAIProvider{baseURL: srv.URL, http: srv.Client()} + result, err := p.RunAgent(context.Background(), AgentRequest{ + Tools: tools, Messages: []AgentMessage{{Role: "user", Content: "Inspect the contact and campaign"}}, + }) + if err != nil { + t.Fatal(err) + } + if result.Text != "Done" || requests != 2 { + t.Fatalf("result=%+v requests=%d", result, requests) + } +} diff --git a/internal/pkg/generation/provider.go b/internal/pkg/generation/provider.go index 1dfaa9a06..f7e37e0c8 100644 --- a/internal/pkg/generation/provider.go +++ b/internal/pkg/generation/provider.go @@ -100,6 +100,8 @@ type AgentRequest struct { // MaxIterations bounds tool-use rounds (each model call is one iteration). // Zero uses the provider default. MaxIterations int + // ReserveFinalResponse makes the last iteration answer from existing evidence without tools. + ReserveFinalResponse bool // MaxTokens caps a single completion. Zero uses the provider default. MaxTokens int // OnEvent, if set, receives streamed step events. Optional. @@ -124,10 +126,9 @@ type PendingToolCall struct { Risk RiskClass } -// AgentResult is the final output of a RunAgent run. +// AgentResult includes completed turns even when RunAgent returns a later error. type AgentResult struct { - // Text is the model's final assistant text (empty when the run stopped for - // approval before producing final text). + // Text is the final assistant text, including a budget-limited summary when requested. Text string // Messages is the full transcript including this run's new turns, so a // caller can persist it and resume. @@ -136,8 +137,7 @@ type AgentResult struct { // TokensUsed is the summed input+output tokens across all iterations. TokensUsed int Iterations int - // StopReason is "stop" (final text), "max_iterations", or - // "approval_required". + // StopReason is "stop", "max_iterations", "approval_required", "stopped", or "error". StopReason string // Pending is set only when StopReason == "approval_required". Pending *PendingToolCall @@ -205,8 +205,9 @@ var ErrProviderNotConfigured = errors.New("no LLM provider configured: set AI_PR // Default agent-loop bounds, applied when a request leaves them zero. const ( - defaultMaxIterations = 12 - defaultAgentTokens = 2048 + defaultMaxIterations = 12 + defaultAgentTokens = 2048 + agentFinalResponseInstructions = "\n\nThis is the final turn within this run's budget. No more tools are available. Answer the user's question in their language using only the evidence already gathered. Clearly distinguish confirmed findings from uncertainty. If the cause or answer could not be verified, say so and name the missing evidence or next step. Do not invent findings or claim unperformed actions." ) // ProviderConfig configures provider construction. Only the keys and optional diff --git a/internal/pkg/generation/tool_catalog.go b/internal/pkg/generation/tool_catalog.go index f26b4656a..374092e1d 100644 --- a/internal/pkg/generation/tool_catalog.go +++ b/internal/pkg/generation/tool_catalog.go @@ -81,9 +81,10 @@ func (c *toolCatalog) instructions() string { } type toolSearchMatch struct { - Name string `json:"name"` - Description string `json:"description"` - Risk RiskClass `json:"risk"` + Name string `json:"name"` + Description string `json:"description"` + Risk RiskClass `json:"risk"` + InputSchema map[string]any `json:"input_schema"` } type toolSearchResult struct { @@ -136,7 +137,7 @@ func (c *toolCatalog) find(_ context.Context, args json.RawMessage) (string, err for _, match := range matches[start:end] { tool := match.tool c.active = append(c.active, tool) - result.Tools = append(result.Tools, toolSearchMatch{Name: tool.Name, Description: tool.Description, Risk: tool.Risk}) + result.Tools = append(result.Tools, toolSearchMatch{Name: tool.Name, Description: tool.Description, Risk: tool.Risk, InputSchema: tool.InputSchema}) } out, err := json.Marshal(result) return string(out), err From 21dd0ce063950450c8779278e54568e8c6efceb6 Mon Sep 17 00:00:00 2001 From: Tugser OKUR Date: Mon, 26 Oct 2026 14:38:25 +0300 Subject: [PATCH 002/318] feat: document Remie regression contracts and tool discovery behavior with concise Go function comments --- internal/app/aiagent/credits_test.go | 4 ++++ internal/app/aiagent/run_test.go | 14 ++++++++++++++ internal/app/aiagent/service_test.go | 1 + .../pkg/generation/agent_final_response_test.go | 10 ++++++++++ internal/pkg/generation/openai_tools_test.go | 1 + internal/pkg/generation/tool_catalog.go | 1 + 6 files changed, 31 insertions(+) diff --git a/internal/app/aiagent/credits_test.go b/internal/app/aiagent/credits_test.go index 89cf440f9..66d520f94 100644 --- a/internal/app/aiagent/credits_test.go +++ b/internal/app/aiagent/credits_test.go @@ -23,6 +23,7 @@ type runCreditLedger struct { keys []string } +// Consume enforces the fixture balance and records the idempotency key of each charged turn. func (l *runCreditLedger) Consume(ctx context.Context, _ uuid.UUID, amount int, _, _ string, _ int, key string) (int, error) { if err := ctx.Err(); err != nil { return l.balance, err @@ -36,6 +37,7 @@ func (l *runCreditLedger) Consume(ctx context.Context, _ uuid.UUID, amount int, return l.balance, nil } +// Grant records failed-turn refunds and rejects canceled storage contexts. func (l *runCreditLedger) Grant(ctx context.Context, _ uuid.UUID, amount int, _ string) (int, *errx.Error) { if ctx.Err() != nil { return l.balance, errx.New(errx.Internal, "credit context is canceled") @@ -45,6 +47,7 @@ func (l *runCreditLedger) Grant(ctx context.Context, _ uuid.UUID, amount int, _ return l.balance, nil } +// SettleUsage records the charged turns and token usage without introducing external pricing into the fixture. func (l *runCreditLedger) SettleUsage(ctx context.Context, _ uuid.UUID, charged int, _ string, tokens int, _, _ string) (int, error) { if err := ctx.Err(); err != nil { return 0, err @@ -54,6 +57,7 @@ func (l *runCreditLedger) SettleUsage(ctx context.Context, _ uuid.UUID, charged return 0, nil } +// TestRunMessageChargesReservedAnswerWithinBudget covers successful answers, failed-turn refunds, and depleted credits. func TestRunMessageChargesReservedAnswerWithinBudget(t *testing.T) { for _, tc := range []struct { name string diff --git a/internal/app/aiagent/run_test.go b/internal/app/aiagent/run_test.go index b173ee86d..c59e7e410 100644 --- a/internal/app/aiagent/run_test.go +++ b/internal/app/aiagent/run_test.go @@ -26,15 +26,18 @@ type runRepository struct { afterAppend func(context.Context) } +// GetSession returns a snapshot so an older run cannot mutate newer persisted approval state. func (r *runRepository) GetSession(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) (*models.AgentSession, error) { session := r.session return &session, nil } +// LoadTranscript exposes persisted fixture rows in their per-session timestamp order. func (r *runRepository) LoadTranscript(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) ([]models.AgentMessageRow, error) { return r.rows, nil } +// AppendMessages models cancellation and monotonic timestamps at the transcript storage boundary. func (r *runRepository) AppendMessages(ctx context.Context, _, _, _ uuid.UUID, rows []models.AgentMessageRow) error { if err := ctx.Err(); err != nil { return err @@ -50,19 +53,23 @@ func (r *runRepository) AppendMessages(ctx context.Context, _, _, _ uuid.UUID, r return nil } +// UpdateSessionContext persists approval state for subsequent run and resume calls. func (r *runRepository) UpdateSessionContext(_ context.Context, _, _, _ uuid.UUID, sctx models.AgentSessionContext) error { r.session.Context = sctx return nil } +// UpdateSessionTitle ignores title writes because these fixtures exercise run completion. func (r *runRepository) UpdateSessionTitle(context.Context, uuid.UUID, uuid.UUID, uuid.UUID, string) error { return nil } +// GetToolPolicies supplies the explicit always-allow policies needed to exercise completed writes. func (r *runRepository) GetToolPolicies(context.Context, uuid.UUID) (map[string]string, error) { return r.policies, nil } +// ClearPendingTool rejects canceled requests so stale cleanup cannot remove a newer approval. func (r *runRepository) ClearPendingTool(ctx context.Context, _ uuid.UUID, _ uuid.UUID) error { if err := ctx.Err(); err != nil { return err @@ -71,6 +78,7 @@ func (r *runRepository) ClearPendingTool(ctx context.Context, _ uuid.UUID, _ uui return nil } +// ClaimPendingTool consumes only the matching approval, leaving replay attempts without an action. func (r *runRepository) ClaimPendingTool(_ context.Context, _, _ uuid.UUID, callID string) (*models.PendingAgentTool, error) { pending := r.session.Context.Pending if pending == nil || pending.ToolCallID != callID { @@ -82,10 +90,12 @@ func (r *runRepository) ClaimPendingTool(_ context.Context, _, _ uuid.UUID, call type runFeatureGate struct{} +// IsPaidOrganization selects the paid model while each test chooses whether credits are metered. func (runFeatureGate) IsPaidOrganization(context.Context, uuid.UUID) (bool, *errx.Error) { return true, nil } +// TestRunMessageAnswersBeforeBudgetIsExhausted requires a streamed and persisted answer after repeated tool rounds. func TestRunMessageAnswersBeforeBudgetIsExhausted(t *testing.T) { const answer = "No sending mailbox matched that address, so I could not verify why it did not send." requests, executions := 0, 0 @@ -155,6 +165,7 @@ func TestRunMessageAnswersBeforeBudgetIsExhausted(t *testing.T) { } } +// TestRunMessageReportsEmptyProviderAnswer surfaces an explicit error instead of silently completing the chat. func TestRunMessageReportsEmptyProviderAnswer(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") @@ -180,6 +191,7 @@ func TestRunMessageReportsEmptyProviderAnswer(t *testing.T) { } } +// TestRunMessagePreservesCompletedActionsWhenFinalResponseFails keeps completed writes visible after provider failure. func TestRunMessagePreservesCompletedActionsWhenFinalResponseFails(t *testing.T) { for _, failure := range []string{"empty", "unexpected_tool", "provider_error"} { t.Run(failure, func(t *testing.T) { @@ -241,6 +253,7 @@ func TestRunMessagePreservesCompletedActionsWhenFinalResponseFails(t *testing.T) } } +// TestResumePreservesApprovedActionWhenProviderFails records the approved action once and refuses approval replay. func TestResumePreservesApprovedActionWhenProviderFails(t *testing.T) { requests, writes := 0, 0 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -294,6 +307,7 @@ func TestResumePreservesApprovedActionWhenProviderFails(t *testing.T) { } } +// TestRunMessagePreservesCompletedActionsAfterCancellation protects receipts, refunds, and newer approvals during cleanup. func TestRunMessagePreservesCompletedActionsAfterCancellation(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() diff --git a/internal/app/aiagent/service_test.go b/internal/app/aiagent/service_test.go index 1dfb47a3c..4ead34137 100644 --- a/internal/app/aiagent/service_test.go +++ b/internal/app/aiagent/service_test.go @@ -103,6 +103,7 @@ func TestForReaderWithholdsResultsOfToolsTheReaderCannotRun(t *testing.T) { } } +// TestTranscriptOnlyDescribesDraftToolsAsCreation keeps read results from being presented as newly created resources. func TestTranscriptOnlyDescribesDraftToolsAsCreation(t *testing.T) { for _, tc := range []struct{ tool, result, want string }{ {"get_campaign_stats", `{"campaign_id":"c1","emails_sent":4}`, `{"campaign_id":"c1","emails_sent":4}`}, diff --git a/internal/pkg/generation/agent_final_response_test.go b/internal/pkg/generation/agent_final_response_test.go index 87bf4e6cc..19f2c0b9a 100644 --- a/internal/pkg/generation/agent_final_response_test.go +++ b/internal/pkg/generation/agent_final_response_test.go @@ -14,12 +14,14 @@ import ( type agentFixtureTransport struct{ handler http.Handler } +// RoundTrip routes provider requests to deterministic fixtures without external network access. func (tr agentFixtureTransport) RoundTrip(req *http.Request) (*http.Response, error) { w := httptest.NewRecorder() tr.handler.ServeHTTP(w, req) return w.Result(), nil } +// agentFixtureProvider exercises each provider adapter against the same local HTTP contract. func agentFixtureProvider(kind string, handler http.Handler) Provider { client := &http.Client{Transport: agentFixtureTransport{handler: handler}} if kind == "anthropic" { @@ -28,6 +30,7 @@ func agentFixtureProvider(kind string, handler http.Handler) Provider { return &openAIProvider{baseURL: "http://provider.test", http: client} } +// writeAgentFixture emits equivalent tool and text responses in each provider's wire format. func writeAgentFixture(w http.ResponseWriter, kind, text string, calls ...ToolCall) { if kind != "anthropic" { writeAgentResponse(w, kind == "openai-stream", text, calls...) @@ -43,6 +46,7 @@ func writeAgentFixture(w http.ResponseWriter, kind, text string, calls ...ToolCa }) } +// TestAgentReservesFinalResponseOnlyWhenRequested keeps chat answers inside the caller's turn and credit budget. func TestAgentReservesFinalResponseOnlyWhenRequested(t *testing.T) { for _, kind := range []string{"openai", "openai-stream", "anthropic"} { for _, reserve := range []bool{false, true} { @@ -109,6 +113,7 @@ func TestAgentReservesFinalResponseOnlyWhenRequested(t *testing.T) { } } +// TestAgentReturnsEarlyAnswerWithoutSpendingReservedTurn avoids charging another turn after an answer arrives. func TestAgentReturnsEarlyAnswerWithoutSpendingReservedTurn(t *testing.T) { for _, kind := range []string{"openai", "openai-stream", "anthropic"} { t.Run(kind, func(t *testing.T) { @@ -133,6 +138,7 @@ func TestAgentReturnsEarlyAnswerWithoutSpendingReservedTurn(t *testing.T) { } } +// TestAgentRejectsEmptyAnswer requires visible text for a successful chat completion. func TestAgentRejectsEmptyAnswer(t *testing.T) { for _, kind := range []string{"openai", "openai-stream", "anthropic"} { t.Run(kind, func(t *testing.T) { @@ -153,6 +159,7 @@ func TestAgentRejectsEmptyAnswer(t *testing.T) { } } +// TestAgentAllowsEmptyStopForToolOnlyCallers preserves research flows that report findings through tools. func TestAgentAllowsEmptyStopForToolOnlyCallers(t *testing.T) { for _, kind := range []string{"openai", "openai-stream", "anthropic"} { t.Run(kind, func(t *testing.T) { @@ -174,6 +181,7 @@ func TestAgentAllowsEmptyStopForToolOnlyCallers(t *testing.T) { } } +// TestAgentHonorsStopBeforeReservedFinalResponse keeps the final answer behind the caller's credit gate. func TestAgentHonorsStopBeforeReservedFinalResponse(t *testing.T) { for _, kind := range []string{"openai", "openai-stream", "anthropic"} { t.Run(kind, func(t *testing.T) { @@ -206,6 +214,7 @@ func TestAgentHonorsStopBeforeReservedFinalResponse(t *testing.T) { } } +// TestAgentNeverExecutesToolsInReservedResponse refuses tool execution after the tool budget closes. func TestAgentNeverExecutesToolsInReservedResponse(t *testing.T) { for _, kind := range []string{"openai", "openai-stream", "anthropic"} { t.Run(kind, func(t *testing.T) { @@ -230,6 +239,7 @@ func TestAgentNeverExecutesToolsInReservedResponse(t *testing.T) { } } +// TestAgentPreservesCompletedToolsWhenFinalResponseFails retains tool evidence alongside later provider errors. func TestAgentPreservesCompletedToolsWhenFinalResponseFails(t *testing.T) { for _, kind := range []string{"openai", "openai-stream", "anthropic"} { for _, failure := range []string{"empty", "unexpected_tool", "provider_error"} { diff --git a/internal/pkg/generation/openai_tools_test.go b/internal/pkg/generation/openai_tools_test.go index ebd732813..a2d6fd1bf 100644 --- a/internal/pkg/generation/openai_tools_test.go +++ b/internal/pkg/generation/openai_tools_test.go @@ -210,6 +210,7 @@ func TestOpenAIAgentDiscoveredToolPausesAndResumes(t *testing.T) { } } +// TestOpenAIAgentDiscoveryKeepsArgumentSchemasAcrossSearches retains required arguments after the active tool page changes. func TestOpenAIAgentDiscoveryKeepsArgumentSchemasAcrossSearches(t *testing.T) { tools := catalogTestTools(138) tools[136].InputSchema = map[string]any{ diff --git a/internal/pkg/generation/tool_catalog.go b/internal/pkg/generation/tool_catalog.go index 374092e1d..f16214b5c 100644 --- a/internal/pkg/generation/tool_catalog.go +++ b/internal/pkg/generation/tool_catalog.go @@ -93,6 +93,7 @@ type toolSearchResult struct { NextOffset *int `json:"next_offset,omitempty"` } +// find preserves matching argument schemas in the transcript while replacing the active tool page. func (c *toolCatalog) find(_ context.Context, args json.RawMessage) (string, error) { var input struct { Query string `json:"query"` From 3d638880a8317a9fb5b0813d670c77db2c3b509a Mon Sep 17 00:00:00 2001 From: 555aaditya <107977627+555aaditya@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:59:37 +0530 Subject: [PATCH 003/318] =?UTF-8?q?feat:=20read=20interest=20in=20German,?= =?UTF-8?q?=20French=20and=20Spanish=20replies=20for=20workspaces=20that?= =?UTF-8?q?=20choose=20those=20tagging=20languages,=20after=20the=20langua?= =?UTF-8?q?ge's=20no=20phrases=20and=20never=20straight=20after=20a=20nega?= =?UTF-8?q?ting=20word,=20and=20read=20colloquial=20French=20=C3=A7a=20m'i?= =?UTF-8?q?nt=C3=A9resse=20pas=20as=20declined?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/content/docs/guides/inbox-tagging.mdx | 3 +- internal/app/replyclassify/languages.go | 53 ++++++++++- internal/app/replyclassify/lexicon.go | 15 +++- .../replyclassify/sentiment_languages_test.go | 87 +++++++++++++++++++ 4 files changed, 151 insertions(+), 7 deletions(-) diff --git a/docs/content/docs/guides/inbox-tagging.mdx b/docs/content/docs/guides/inbox-tagging.mdx index dbb4cd61f..cfcffe4c3 100644 --- a/docs/content/docs/guides/inbox-tagging.mdx +++ b/docs/content/docs/guides/inbox-tagging.mdx @@ -233,7 +233,8 @@ The reading before any call covers: - **Quoted history**, cut from a reply so the classifier reads what the person wrote and not your own message quoted under it: the reply line each mail client writes ("Den ... skrev", "W dniu ... pisze:", "ไบŽ ... ๅ†™้“๏ผš" and the like), Outlook's quoted `From: / Sent:` block in that language (`Von: / Gesendet:`, `De : / Envoyรฉ :`, `ๅทฎๅ‡บไบบ: / ้€ไฟกๆ—ฅๆ™‚:`), and the dashed "Original message" and "Forwarded message" lines. - **Out-of-office replies**, recognized by the subject their mail provider writes (`ะะฒั‚ะพะผะฐั‚ะธั‡ะตัะบะธะน ะพั‚ะฒะตั‚`, `่‡ชๅ‹•ๅฟœ็ญ”`, `์ž๋™ ํšŒ์‹ `, `ุฑุฏ ุชู„ู‚ุงุฆูŠ` and so on) and decided with no call at all. - **Non-delivery notices**, by the subject Exchange writes in Spanish, Italian, Dutch and Portuguese. A notice carrying a delivery-status report is recognized in any language without this. -- **Replies that say no**, in German, French, Spanish, Dutch, Italian and Portuguese: a declined interest ("kein Interesse", "pas intรฉressรฉ", "no me interesa", "geen interesse", "non sono interessato", "nรฃo tenho interesse") or another clear no ("nein danke", "non merci", "no gracias", "nee bedankt", "no grazie", "nรฃo, obrigado", "falscher Ansprechpartner", "persona sbagliata"). Each phrase is matched as whole words, so "no grazie" never matches inside "buono, grazie". The reply classifier reads these as negative with no call, the same verdict "not interested" and "no thanks" get in English, so they take the `reply_negative` branch. Inbox labels still come from the classifier. Phrases of interest are read in English only for now. +- **Replies that say no**, in German, French, Spanish, Dutch, Italian and Portuguese: a declined interest ("kein Interesse", "pas intรฉressรฉ", "no me interesa", "geen interesse", "non sono interessato", "nรฃo tenho interesse") or another clear no ("nein danke", "non merci", "no gracias", "nee bedankt", "no grazie", "nรฃo, obrigado", "falscher Ansprechpartner", "persona sbagliata"). Each phrase is matched as whole words, so "no grazie" never matches inside "buono, grazie". The reply classifier reads these as negative with no call, the same verdict "not interested" and "no thanks" get in English, so they take the `reply_negative` branch. Inbox labels still come from the classifier. +- **Replies that show interest**, in German, French and Spanish ("klingt gut", "lassen Sie uns telefonieren", "รงa m'intรฉresse", "je suis intรฉressรฉ", "me interesa mucho", "agendemos una llamada"), read as positive with no call, the same verdict "interested" and "let's talk" get in English, so they take the `reply_positive` branch and count as interested leads. A reply that also says no in one of these languages ("klingt gut, aber kein Bedarf") stays negative, and a phrase straight after "no", "nicht", "pas" and the like ("no me interesa mucho") does not count. Tagging languages are part of the workspace settings, so they travel with a [workspace export](/guides/workspace-export-import/). diff --git a/internal/app/replyclassify/languages.go b/internal/app/replyclassify/languages.go index 74a70c586..e7ac659f5 100644 --- a/internal/app/replyclassify/languages.go +++ b/internal/app/replyclassify/languages.go @@ -35,11 +35,15 @@ type langRules struct { // declined turns down interest and is read before any interest phrase; // negative is any other clear no. Both are phrases, never single words. declined, negative []string + // positive is clear interest. A chosen language's is read after its no + // phrases, and never straight after a negating word. + positive []string } var baseRules = langRules{ declined: declinedInterestKeywords, negative: negativeKeywords, + positive: positiveKeywords, quote: []quoteMarker{ {re: attribution(`on`, `wrote:`)}, {re: regexp.MustCompile(`(?i)_{10,}`)}, @@ -139,6 +143,11 @@ var languageRules = map[string]langRules{ "nein danke", "nein, danke", "kein bedarf", "keinen bedarf", "falscher ansprechpartner", "falschen ansprechpartner", "nicht der richtige ansprechpartner", "nicht die richtige ansprechpartnerin", "nicht zustรคndig", }, + positive: []string{ + "klingt gut", "klingt interessant", "klingt spannend", "ich bin interessiert", "wir sind interessiert", + "lassen sie uns telefonieren", "lass uns telefonieren", "kรถnnen wir telefonieren", "termin vereinbaren", + "gerne mehr erfahren", "schicken sie mir mehr informationen", "was kostet das", + }, }, "fr": { quote: []quoteMarker{{re: headerBlock(`de ?`, `envoyรฉ ?|date ?`)}}, @@ -146,13 +155,21 @@ var languageRules = map[string]langRules{ ooo: []string{"absent du bureau", "absente du bureau"}, declined: []string{ "pas intรฉressรฉ", "pas intรฉressรฉe", "pas intรฉressรฉs", "pas intรฉressรฉes", "aucun intรฉrรชt", - "ne nous intรฉresse pas", "ne m'intรฉresse pas", "ne suis plus intรฉressรฉ", "ne suis plus intรฉressรฉe", + "nous intรฉresse pas", "m'intรฉresse pas", "ne m'intรฉresse plus", "ne nous intรฉresse plus", + "ne suis plus intรฉressรฉ", "ne suis plus intรฉressรฉe", "ne sommes plus intรฉressรฉs", "ne sommes plus intรฉressรฉes", }, negative: []string{ "non merci", "non, merci", "pas le bon interlocuteur", "pas la bonne personne", "nous avons dรฉjร  une solution", "nous avons dรฉjร  un prestataire", }, + positive: []string{ + "je suis intรฉressรฉ", "je suis intรฉressรฉe", "nous sommes intรฉressรฉs", "nous sommes intรฉressรฉes", + "รงa m'intรฉresse", "cela m'intรฉresse", "รงa nous intรฉresse", "cela nous intรฉresse", + "รงa a l'air intรฉressant", "cela semble intรฉressant", "prenons rendez-vous", "fixer un rendez-vous", + "envoyez-moi plus d'informations", "envoyez-moi une offre", "envoyez-moi un devis", + "quel est le tarif", "quels sont vos tarifs", + }, }, "es": { quote: []quoteMarker{{re: headerBlock(`de`, `enviado|fecha`)}}, @@ -167,6 +184,12 @@ var languageRules = map[string]langRules{ "no gracias", "no, gracias", "no soy la persona", "persona equivocada", "ya tenemos una soluciรณn", "ya tenemos proveedor", }, + positive: []string{ + "me interesa mucho", "nos interesa mucho", "sรญ me interesa", "sรญ, me interesa", "estoy muy interesado", + "estoy muy interesada", "estamos muy interesados", "agendemos una llamada", "agendar una llamada", + "programar una llamada", "envรญeme mรกs informaciรณn", "envรญame mรกs informaciรณn", "cuรกnto cuesta", + "cuรกl es el precio", + }, }, "pt": { quote: []quoteMarker{ @@ -429,6 +452,7 @@ type ruleSet struct { bounce []string declined []phrase negative []phrase + positive []phrase } // phrase is a sentiment phrase as compiled. The English base set keeps the @@ -437,6 +461,28 @@ type ruleSet struct { type phrase struct { text string bounded bool + // negatable phrases do not count straight after a negating word ("no me interesa mucho"). + negatable bool +} + +// negators are the words that, directly before an interest phrase, turn it around. +var negators = map[string]bool{ + "no": true, "not": true, "nicht": true, "kein": true, "keine": true, "keinen": true, "nie": true, + "pas": true, "ne": true, "non": true, "niet": true, "geen": true, "nao": true, "nunca": true, "jamas": true, "mai": true, +} + +// negatedAt reports a negating word directly before start, with nothing but spaces between. +func negatedAt(text string, start int) bool { + head := strings.TrimRight(text[:start], " ") + end := len(head) + for end > 0 { + r, size := utf8.DecodeLastRuneInString(head[:end]) + if !unicode.IsLetter(r) { + break + } + end -= size + } + return negators[head[end:]] } // in matches an English base phrase against the text as written and a chosen @@ -454,7 +500,7 @@ func (p phrase) in(text, folded string) bool { start, end := i+j, i+j+len(p.text) before, _ := utf8.DecodeLastRuneInString(text[:start]) after, _ := utf8.DecodeRuneInString(text[end:]) - if !wordRune(before) && !wordRune(after) { + if !wordRune(before) && !wordRune(after) && !(p.negatable && negatedAt(text, start)) { return true } _, size := utf8.DecodeRuneInString(text[start:]) @@ -519,6 +565,9 @@ func compileRules(parts []langRules) *ruleSet { for _, n := range p.negative { rs.negative = append(rs.negative, phrase{text: accentFolder.Replace(strings.ToLower(n)), bounded: i > 0}) } + for _, pos := range p.positive { + rs.positive = append(rs.positive, phrase{text: accentFolder.Replace(strings.ToLower(pos)), bounded: i > 0, negatable: i > 0}) + } } rs.quote = append(rs.quote, quoteMarker{re: regexp.MustCompile(`(?i)-{2,}\s*(` + strings.Join(separators, `|`) + `)\s*-{2,}`)}) rs.cue = regexp.MustCompile(`(?i)\b(` + strings.Join(longestFirst(cues), `|`) + `)\b`) diff --git a/internal/app/replyclassify/lexicon.go b/internal/app/replyclassify/lexicon.go index 2b9827ffd..22bbee133 100644 --- a/internal/app/replyclassify/lexicon.go +++ b/internal/app/replyclassify/lexicon.go @@ -39,16 +39,23 @@ func classifyLexicon(in Input) (Result, bool) { } } + // A chosen language's clear no is read before any interest, so "klingt gut, aber kein bedarf" stays negative. + for _, kw := range rules.negative { + if kw.bounded && kw.in(text, folded) { + return Result{Class: ClassNegative, Confidence: 0.8, Source: SourceLexicon}, true + } + } + // 3. Clear interest => positive. - for _, kw := range positiveKeywords { - if strings.Contains(text, kw) { + for _, kw := range rules.positive { + if kw.in(text, folded) { return Result{Class: ClassPositive, Confidence: 0.8, Source: SourceLexicon}, true } } - // 4. Clear rejection => negative. + // 4. Clear rejection => negative. English keeps its place after interest. for _, kw := range rules.negative { - if kw.in(text, folded) { + if !kw.bounded && kw.in(text, folded) { return Result{Class: ClassNegative, Confidence: 0.8, Source: SourceLexicon}, true } } diff --git a/internal/app/replyclassify/sentiment_languages_test.go b/internal/app/replyclassify/sentiment_languages_test.go index 686e8d999..be2a1c911 100644 --- a/internal/app/replyclassify/sentiment_languages_test.go +++ b/internal/app/replyclassify/sentiment_languages_test.go @@ -183,3 +183,90 @@ func TestEnglishPhrasesReadTheTextAsWritten(t *testing.T) { t.Errorf("English reply with an accent = %q, want it read as before", got.Class) } } + +// Replies that show interest, in each language as people write them. Each is +// positive once its language is chosen and not positive without it. +func TestInterestedRepliesByLanguage(t *testing.T) { + positive := map[string][]string{ + "de": { + "Klingt gut, lassen Sie uns telefonieren.", + "Ich bin interessiert, was kostet das?", + "Klingt interessant!", + "Wir sind interessiert.", + "Gerne mehr erfahren.", + "Kรถnnen wir telefonieren?", + }, + "fr": { + "ร‡a m'intรฉresse, quel est le tarif ?", + "Je suis intรฉressรฉe.", + "Nous sommes intรฉressรฉs, prenons rendez-vous.", + "Cela semble intรฉressant.", + "Envoyez-moi un devis s'il vous plaรฎt.", + "Ca nous interesse.", + }, + "es": { + "Me interesa mucho.", + "Sรญ, me interesa.", + "Estoy muy interesado, ยฟcuรกnto cuesta?", + "Agendemos una llamada.", + "Envรญeme mรกs informaciรณn, por favor.", + "Estamos muy interesados.", + }, + } + for lang, replies := range positive { + for _, body := range replies { + in := Input{Subject: "Re: Hallo", BodyText: body, Languages: []string{lang}} + if got := ClassifyOffline(in); got.Class != ClassPositive { + t.Errorf("%s %q = %q, want positive", lang, body, got.Class) + } + in.Languages = nil + if got := ClassifyOffline(in); got.Class == ClassPositive { + t.Errorf("%s %q read as positive without %s chosen", lang, body, lang) + } + } + } +} + +// An interest phrase that is negated, outweighed by a no, or only conditional +// never reads as interest. +func TestNegatedAndHedgedInterestIsNotPositive(t *testing.T) { + all := []string{"de", "fr", "es", "nl", "it", "pt"} + for _, body := range []string{ + "Ich bin nicht interessiert.", + "Klingt gut, aber wir haben keinen Bedarf.", + "Wir mรถchten keinen Termin vereinbaren.", + "Wir wรคren interessiert, wenn der Preis stimmt.", + "Falls Interesse besteht, melden wir uns.", + "ร‡a m'intรฉresse pas.", + "Cela ne nous intรฉresse plus.", + "Je ne suis pas intรฉressรฉ.", + "Nous ne sommes pas intรฉressรฉs.", + "No me interesa mucho.", + "No estoy muy interesado.", + "Gracias, pero no estamos muy interesados.", + } { + if got := ClassifyOffline(Input{Subject: "Re: Hallo", BodyText: body, Languages: all}); got.Class == ClassPositive { + t.Errorf("%q read as positive", body) + } + } +} + +// A negating word straight before the phrase turns it around; anything else between does not. +func TestNegatedAtReadsTheWordBefore(t *testing.T) { + for text, want := range map[string]bool{ + "no me interesa mucho": true, + "nicht klingt gut": true, + "no, me interesa mucho": false, + "bueno me interesa mucho": false, + "me interesa mucho": false, + "pero no me interesa mucho": true, + } { + start := len(text) - len("me interesa mucho") + if text == "nicht klingt gut" { + start = len("nicht ") + } + if got := negatedAt(text, start); got != want { + t.Errorf("negatedAt(%q) = %v, want %v", text, got, want) + } + } +} From 52cc6c1e661aa81ab647d7b5ef744e4c25089745 Mon Sep 17 00:00:00 2001 From: 555aaditya <107977627+555aaditya@users.noreply.github.com> Date: Wed, 28 Oct 2026 14:09:34 +0530 Subject: [PATCH 004/318] feat: read out-of-office return dates in Swedish, Danish, Norwegian, Finnish, Polish and Czech for workspaces that choose those tagging languages, by passing the tagging languages to the return-date reader from the out-of-office hold and inbox tagging --- docs/content/docs/guides/campaigns.mdx | 2 +- .../app/advanced/out_of_office_hold_test.go | 22 ++++++++++ internal/app/advanced/service.go | 6 +-- internal/app/inboxtag/returndate.go | 2 +- internal/app/replyclassify/languages.go | 32 +++++++++++++- internal/app/replyclassify/returndate.go | 11 ++--- internal/app/replyclassify/returndate_test.go | 44 +++++++++++++++++++ 7 files changed, 107 insertions(+), 12 deletions(-) diff --git a/docs/content/docs/guides/campaigns.mdx b/docs/content/docs/guides/campaigns.mdx index 992748653..e0e7ff1e2 100644 --- a/docs/content/docs/guides/campaigns.mdx +++ b/docs/content/docs/guides/campaigns.mdx @@ -285,7 +285,7 @@ A lead is **Processing** only while steps remain, so a finished campaign reads a When a recipient's mailbox answers a step with an away message, that is not a reply: Warmbly never counts an auto-reply as a human one, so stop on reply does not fire and, left alone, the next step would go out on schedule to an empty desk. Warmbly holds the lead instead, in every campaign that contact is still a lead of rather than only the one that was answered. An empty desk is an empty desk, so a contact you are running two sequences to is held in both. Completed campaigns are left alone, since nothing in them will send again. -The hold reads the return date out of the away message when it can. English, German, French, Spanish, Portuguese, Italian and Dutch phrasings are recognised (`back on 8 September`, `zurรผck am 09.09.2026`, `ab dem 10.9.`, `jusqu'au 12 septembre`), in ISO and day-dot-month form as well as written months. German calendar weeks count too: `ab KW 42` resumes from that week's Monday, `bis KW 41` from the Monday after it. Two kinds of date are deliberately not read, because a wrong one parks a live lead for weeks: slash dates, since `9/8/2026` means two different days on two sides of the Atlantic, and a month with no day (`until October`), since there is no way to tell which day in it was meant. The lead resumes one working day after the date it found, so the follow-up does not land in the backlog of their first morning back. When no date can be read, the hold is the workspace's fallback, `7` days by default, set under **Settings > Sending > Out of office**. The same section turns the whole behaviour off. +The hold reads the return date out of the away message when it can. English, German, French, Spanish, Portuguese, Italian and Dutch phrasings are recognised (`back on 8 September`, `zurรผck am 09.09.2026`, `ab dem 10.9.`, `jusqu'au 12 septembre`), in ISO and day-dot-month form as well as written months. Swedish, Danish, Norwegian, Finnish, Polish and Czech phrasings are read too when the workspace adds those [tagging languages](/guides/inbox-tagging/#tagging-languages) (`tillbaka den 14 september`, `til og med 18. september`, `palaan 14.9.`, `wracam 14 wrzeล›nia`, `budu zpฤ›t 14. zรกล™รญ`). German calendar weeks count too: `ab KW 42` resumes from that week's Monday, `bis KW 41` from the Monday after it. Two kinds of date are deliberately not read, because a wrong one parks a live lead for weeks: slash dates, since `9/8/2026` means two different days on two sides of the Atlantic, and a month with no day (`until October`), since there is no way to tell which day in it was meant. The lead resumes one working day after the date it found, so the follow-up does not land in the backlog of their first morning back. When no date can be read, the hold is the workspace's fallback, `7` days by default, set under **Settings > Sending > Out of office**. The same section turns the whole behaviour off. With [automatic inbox tagging](/guides/inbox-tagging/#confirming-an-away-messages-return-date) on, the date gets a second reading. The phrase it came from is shown to the classifier, which is asked whether it says when the sender is back. When the answer is a clear no (the date is the first day of the absence, or a stand-in's hours), the hold uses the fallback instead, and the lead's reason reads `auto-reply, return date unclear`. An unsure answer, or a failed call, leaves the date as read. diff --git a/internal/app/advanced/out_of_office_hold_test.go b/internal/app/advanced/out_of_office_hold_test.go index 0237725ac..20153a712 100644 --- a/internal/app/advanced/out_of_office_hold_test.go +++ b/internal/app/advanced/out_of_office_hold_test.go @@ -189,3 +189,25 @@ func TestHoldForOutOfOfficeReadsTheReturnDateCheck(t *testing.T) { }) } } + +// A workspace's tagging languages reach the return-date reader, so a Polish +// away message holds until its date instead of the fallback. +func TestHoldForOutOfOfficeReadsTheWorkspaceLanguages(t *testing.T) { + cfg := models.ReplyIntentSettings{HoldOnOutOfOffice: true, OutOfOfficeHoldDays: 7} + back := time.Now().UTC().Truncate(24*time.Hour).AddDate(0, 0, 10) + msg := &models.EmailMessageStoreData{Subject: "Odpowiedลบ automatyczna", BodyText: "Wracam " + back.Format("02.01.2006") + "."} + for name, langs := range map[string][]string{"with Polish chosen": {"pl"}, "without it": nil} { + t.Run(name, func(t *testing.T) { + rec := &holdRecorder{} + s := &service{campaignProgressRepo: rec} + s.holdForOutOfOffice(context.Background(), uuid.New(), uuid.New(), cfg, msg, langs...) + want := "auto-reply, no return date" + if langs != nil { + want = "back " + back.Format("2 Jan 2006") + } + if rec.reason != want { + t.Errorf("hold reason = %q, want %q", rec.reason, want) + } + }) + } +} diff --git a/internal/app/advanced/service.go b/internal/app/advanced/service.go index 01b049a7a..72ef94d7a 100644 --- a/internal/app/advanced/service.go +++ b/internal/app/advanced/service.go @@ -1614,7 +1614,7 @@ func (s *service) ProcessIncomingReply(ctx context.Context, emailAccountID uuid. var held *time.Time if campaignID != nil && contactID != nil && !senderIsCopy && verdict.Class == replyclassify.ClassOutOfOffice && settings.ReplyIntent.HoldOnOutOfOffice { - held = s.holdForOutOfOffice(ctx, *account.OrganizationID, *contactID, settings.ReplyIntent, msg) + held = s.holdForOutOfOffice(ctx, *account.OrganizationID, *contactID, settings.ReplyIntent, msg, settings.InboxTagging.Languages...) } actionTaken := "" @@ -1806,7 +1806,7 @@ func (s *service) ProcessIncomingReply(ctx context.Context, emailAccountID uuid. // one this reply was attributed to. An empty desk is an empty desk: holding // one sequence while a second kept mailing them was issue #470 again, narrowed // to the second campaign (issue #518). -func (s *service) holdForOutOfOffice(ctx context.Context, orgID, contactID uuid.UUID, cfg models.ReplyIntentSettings, msg *models.EmailMessageStoreData) *time.Time { +func (s *service) holdForOutOfOffice(ctx context.Context, orgID, contactID uuid.UUID, cfg models.ReplyIntentSettings, msg *models.EmailMessageStoreData, langs ...string) *time.Time { if s.campaignProgressRepo == nil { return nil } @@ -1820,7 +1820,7 @@ func (s *service) holdForOutOfOffice(ctx context.Context, orgID, contactID uuid. return now.AddDate(0, 0, days), "auto-reply, no return date" } until, reason := fallback() - if back, ok := replyclassify.ParseReturnDate(msg.Subject, body, now); ok { + if back, ok := replyclassify.ParseReturnDate(msg.Subject, body, now, langs...); ok { if s.returnDateDoubted(ctx, orgID, msg.MessageID, back) { until, reason = now.AddDate(0, 0, days), "auto-reply, return date unclear" } else { diff --git a/internal/app/inboxtag/returndate.go b/internal/app/inboxtag/returndate.go index 43edb1c41..2bf51c4a7 100644 --- a/internal/app/inboxtag/returndate.go +++ b/internal/app/inboxtag/returndate.go @@ -24,7 +24,7 @@ func returnDateToConfirm(m Message, ws workspaceSettings, deterministicKind stri if deterministicKind != "" && deterministicKind != KindAutoReplyOOO { return replyclassify.ReturnDate{}, false } - return replyclassify.FindReturnDate(m.Subject, m.holdBody(), now) + return replyclassify.FindReturnDate(m.Subject, m.holdBody(), now, ws.languages...) } // holdBody is the text the out-of-office hold reads its date from: the body, diff --git a/internal/app/replyclassify/languages.go b/internal/app/replyclassify/languages.go index 74a70c586..f12cd9951 100644 --- a/internal/app/replyclassify/languages.go +++ b/internal/app/replyclassify/languages.go @@ -26,8 +26,7 @@ type langRules struct { // ooo are away-message subject prefixes, in their own spelling. ooo []string // cues introduce a return date; inclusive ones name the last day away. - // Only the base set carries them: nothing passes languages to the - // return-date reader. + // Written accent-folded, as the return-date reader sees the text. cues, inclusive []string months map[int][]string // bounce are non-delivery subject prefixes, lower case. @@ -218,14 +217,23 @@ var languageRules = map[string]langRules{ quote: []quoteMarker{nordicAttribution, {re: headerBlock(`frรฅn`, `skickat|datum`)}}, separators: []string{`ursprungligt meddelande`, `vidarebefordrat meddelande`}, ooo: []string{"frรฅnvaro"}, + cues: []string{`tillbaka den`, `tillbaka igen den`, `tillbaka pa kontoret den`, `ater pa kontoret den`, `ater den`, `nas igen den`, `till och med`}, + inclusive: []string{"till och med"}, + months: map[int][]string{5: {"maj"}, 8: {"augusti"}}, }, "da": { quote: []quoteMarker{nordicAttribution, {re: headerBlock(`fra`, `sendt|dato`)}}, separators: []string{`oprindelig meddelelse`, `videresendt meddelelse`}, + cues: []string{`tilbage den`, `tilbage igen den`, `tilbage pa kontoret den`, `traeffes igen den`, `til og med`}, + inclusive: []string{"til og med"}, + months: map[int][]string{3: {"marts"}, 5: {"maj"}}, }, "nb": { quote: []quoteMarker{nordicAttribution, {re: headerBlock(`fra`, `sendt|dato`)}}, separators: []string{`opprinnelig melding`, `videresendt melding`}, + cues: []string{`tilbake den`, `tilbake igjen den`, `tilbake pa kontoret den`, `tilgjengelig igjen den`, `til og med`}, + inclusive: []string{"til og med"}, + months: map[int][]string{12: {"desember"}}, }, "fi": { quote: []quoteMarker{ @@ -234,6 +242,13 @@ var languageRules = map[string]langRules{ }, separators: []string{`alkuperรคinen viesti`, `vรคlitetty viesti`}, ooo: []string{"automaattinen vastaus", "poissa toimistolta"}, + cues: []string{`palaan`, `olen takaisin`, `takaisin toimistolla`, `tavoitettavissa jaelleen`}, + months: map[int][]string{ + 1: {"tammikuuta", "tammikuu"}, 2: {"helmikuuta", "helmikuu"}, 3: {"maaliskuuta", "maaliskuu"}, + 4: {"huhtikuuta", "huhtikuu"}, 5: {"toukokuuta", "toukokuu"}, 6: {"kesaekuuta", "kesaekuu"}, + 7: {"heinaekuuta", "heinaekuu"}, 8: {"elokuuta", "elokuu"}, 9: {"syyskuuta", "syyskuu"}, + 10: {"lokakuuta", "lokakuu"}, 11: {"marraskuuta", "marraskuu"}, 12: {"joulukuuta", "joulukuu"}, + }, }, "pl": { quote: []quoteMarker{ @@ -243,6 +258,13 @@ var languageRules = map[string]langRules{ }, separators: []string{`oryginalna wiadomoล›ฤ‡`, `wiadomoล›ฤ‡ oryginalna`, `wiadomoล›ฤ‡ przekazana`}, ooo: []string{"odpowiedลบ automatyczna", "poza biurem"}, + cues: []string{`wracam`, `wroce`, `bede z powrotem`, `z powrotem w biurze`, `do dnia`}, + months: map[int][]string{ + 1: {"stycznia", "styczen"}, 2: {"lutego", "luty"}, 3: {"marca", "marzec"}, 4: {"kwietnia", "kwiecien"}, + 5: {"maja", "maj"}, 6: {"czerwca", "czerwiec"}, 7: {"lipca", "lipiec"}, 8: {"sierpnia", "sierpien"}, + 9: {"wrzesnia", "wrzesien"}, 10: {"pazdziernika", "pazdziernik"}, 11: {"listopada", "listopad"}, + 12: {"grudnia", "grudzien"}, + }, }, "cs": { quote: []quoteMarker{ @@ -251,6 +273,12 @@ var languageRules = map[string]langRules{ }, separators: []string{`pลฏvodnรญ zprรกva`, `pล™eposlanรก zprรกva`}, ooo: []string{"automatickรก odpovฤ›ฤ", "mimo kancelรกล™"}, + cues: []string{`budu zpet`, `zpet v kancelari`, `vracim se`, `opet k zastizeni`}, + months: map[int][]string{ + 1: {"ledna", "leden"}, 2: {"unora", "unor"}, 3: {"brezna", "brezen"}, 4: {"dubna", "duben"}, + 5: {"kvetna", "kveten"}, 6: {"cervna", "cerven"}, 7: {"cervence", "cervenec"}, 8: {"srpna", "srpen"}, + 9: {"zari"}, 10: {"rijna", "rijen"}, 11: {"listopadu", "listopad"}, 12: {"prosince", "prosinec"}, + }, }, "ro": { quote: []quoteMarker{{re: attribution(`pe`, `a scris\s*:`)}, {re: headerBlock(`de la`, `trimis|data`)}}, diff --git a/internal/app/replyclassify/returndate.go b/internal/app/replyclassify/returndate.go index afe165fbe..a7dfa7d87 100644 --- a/internal/app/replyclassify/returndate.go +++ b/internal/app/replyclassify/returndate.go @@ -23,8 +23,9 @@ const ReturnWindowDays = 92 // back, as midnight UTC on that day. now anchors the year for dates written // without one ("back on the 8th of September") and rejects dates in the past. // Returns false when nothing parses with enough confidence. -func ParseReturnDate(subject, body string, now time.Time) (time.Time, bool) { - r, ok := FindReturnDate(subject, body, now) +// langs are the workspace's tagging languages, which add their cues and months. +func ParseReturnDate(subject, body string, now time.Time, langs ...string) (time.Time, bool) { + r, ok := FindReturnDate(subject, body, now, langs...) return r.Back, ok } @@ -39,12 +40,12 @@ type ReturnDate struct { } // FindReturnDate is ParseReturnDate with the phrase the date came from. -func FindReturnDate(subject, body string, now time.Time) (ReturnDate, bool) { - text := normalizeForDates(subject + "\n" + StripQuoted(body)) +func FindReturnDate(subject, body string, now time.Time, langs ...string) (ReturnDate, bool) { + text := normalizeForDates(subject + "\n" + StripQuoted(body, langs...)) if text == "" { return ReturnDate{}, false } - rs := rulesFor(nil) + rs := rulesFor(langs) at := func(m []int) (ReturnDate, bool) { // Only the span right after the cue is considered: an auto-reply is // mostly prose, and the first date anywhere in it is usually not the diff --git a/internal/app/replyclassify/returndate_test.go b/internal/app/replyclassify/returndate_test.go index e49c63d7e..ea307ffa9 100644 --- a/internal/app/replyclassify/returndate_test.go +++ b/internal/app/replyclassify/returndate_test.go @@ -151,3 +151,47 @@ func TestFindReturnDatePhrase(t *testing.T) { }) } } + +// Return dates as away messages write them in each language. The date is found +// once the language is chosen, and not the same way without it. +func TestReturnDateCuesByLanguage(t *testing.T) { + now := time.Date(2026, 9, 4, 10, 0, 0, 0, time.UTC) + cases := []struct { + lang, body, want string + }{ + {"sv", "Jag รคr tillbaka den 14 september.", "2026-09-14"}, + {"sv", "Jag รคr ledig till och med 18 september.", "2026-09-19"}, + {"sv", "ร…ter pรฅ kontoret den 7 oktober.", "2026-10-07"}, + {"sv", "Jag nรฅs igen den 21.9.", "2026-09-21"}, + {"da", "Jeg er tilbage den 14. september.", "2026-09-14"}, + {"da", "Jeg holder ferie til og med 18. september.", "2026-09-19"}, + {"da", "Jeg trรฆffes igen den 7. oktober.", "2026-10-07"}, + {"nb", "Jeg er tilbake den 14. september.", "2026-09-14"}, + {"nb", "Jeg er pรฅ ferie til og med 18. september.", "2026-09-19"}, + {"nb", "Tilgjengelig igjen den 2. desember.", "2026-12-02"}, + {"fi", "Palaan toimistolle 14.9.", "2026-09-14"}, + {"fi", "Olen takaisin 21. syyskuuta.", "2026-09-21"}, + {"fi", "Tavoitettavissa jรคlleen 7. lokakuuta.", "2026-10-07"}, + {"pl", "Wracam 14 wrzeล›nia.", "2026-09-14"}, + {"pl", "Bฤ™dฤ™ z powrotem 7 paลบdziernika.", "2026-10-07"}, + {"pl", "Jestem nieobecny do dnia 21.09.2026.", "2026-09-21"}, + {"cs", "Budu zpฤ›t 14. zรกล™รญ.", "2026-09-14"}, + {"cs", "Vracรญm se 7. ล™รญjna.", "2026-10-07"}, + {"cs", "Zpฤ›t v kancelรกล™i 21.9.2026.", "2026-09-21"}, + } + for _, tc := range cases { + day := func(langs ...string) string { + back, ok := ParseReturnDate("Re: Hello", tc.body, now, langs...) + if !ok { + return "" + } + return back.Format("2006-01-02") + } + if got := day(tc.lang); got != tc.want { + t.Errorf("%s %q = %q, want %q", tc.lang, tc.body, got, tc.want) + } + if got := day(); got == tc.want { + t.Errorf("%s %q read as %q without %s chosen", tc.lang, tc.body, got, tc.lang) + } + } +} From 23ed853a5ca21b51634949e52b421a5ccdc6c3dd Mon Sep 17 00:00:00 2001 From: 555aaditya <107977627+555aaditya@users.noreply.github.com> Date: Wed, 28 Oct 2026 14:13:26 +0530 Subject: [PATCH 005/318] =?UTF-8?q?feat:=20keep=20Spanish=20s=C3=AD=20me?= =?UTF-8?q?=20interesa=20accented=20so=20conditional=20si=20me=20interesa?= =?UTF-8?q?=20is=20not=20read=20as=20interest,=20and=20let=20a=20negator?= =?UTF-8?q?=20up=20to=20three=20words=20back=20in=20the=20same=20clause,?= =?UTF-8?q?=20across=20line=20breaks,=20turn=20a=20language's=20interest?= =?UTF-8?q?=20phrase=20around?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/app/replyclassify/languages.go | 57 +++++++++++++------ .../replyclassify/sentiment_languages_test.go | 19 +++++-- 2 files changed, 54 insertions(+), 22 deletions(-) diff --git a/internal/app/replyclassify/languages.go b/internal/app/replyclassify/languages.go index e7ac659f5..02932ad6c 100644 --- a/internal/app/replyclassify/languages.go +++ b/internal/app/replyclassify/languages.go @@ -36,8 +36,9 @@ type langRules struct { // negative is any other clear no. Both are phrases, never single words. declined, negative []string // positive is clear interest. A chosen language's is read after its no - // phrases, and never straight after a negating word. - positive []string + // phrases, and never shortly after a negating word. positiveAsWritten + // keeps its accents, where folding would change the meaning. + positive, positiveAsWritten []string } var baseRules = langRules{ @@ -185,11 +186,13 @@ var languageRules = map[string]langRules{ "ya tenemos una soluciรณn", "ya tenemos proveedor", }, positive: []string{ - "me interesa mucho", "nos interesa mucho", "sรญ me interesa", "sรญ, me interesa", "estoy muy interesado", + "me interesa mucho", "nos interesa mucho", "estoy muy interesado", "estoy muy interesada", "estamos muy interesados", "agendemos una llamada", "agendar una llamada", "programar una llamada", "envรญeme mรกs informaciรณn", "envรญame mรกs informaciรณn", "cuรกnto cuesta", "cuรกl es el precio", }, + // "Si me interesa, les aviso" is conditional; only the accented "sรญ" says yes. + positiveAsWritten: []string{"sรญ me interesa", "sรญ, me interesa"}, }, "pt": { quote: []quoteMarker{ @@ -461,28 +464,45 @@ type ruleSet struct { type phrase struct { text string bounded bool - // negatable phrases do not count straight after a negating word ("no me interesa mucho"). + // negatable phrases do not count after a negating word in the same clause ("no me interesa mucho"). negatable bool + // asWritten phrases keep their accents, because folding them changes the meaning ("sรญ" is not "si"). + asWritten bool } -// negators are the words that, directly before an interest phrase, turn it around. +// negators are the words that, shortly before an interest phrase, turn it around. var negators = map[string]bool{ "no": true, "not": true, "nicht": true, "kein": true, "keine": true, "keinen": true, "nie": true, - "pas": true, "ne": true, "non": true, "niet": true, "geen": true, "nao": true, "nunca": true, "jamas": true, "mai": true, + "pas": true, "ne": true, "non": true, "niet": true, "geen": true, "nao": true, "nunca": true, "jamas": true, } -// negatedAt reports a negating word directly before start, with nothing but spaces between. +// negationWindow is how many words back a negator still reaches ("no quiero agendar una llamada"). +const negationWindow = 3 + +// negatedAt reports a negator within negationWindow words before start. Words are +// separated by any whitespace; punctuation ends the clause, and the search with it. func negatedAt(text string, start int) bool { - head := strings.TrimRight(text[:start], " ") - end := len(head) - for end > 0 { - r, size := utf8.DecodeLastRuneInString(head[:end]) - if !unicode.IsLetter(r) { - break + head := text[:start] + for range negationWindow { + head = strings.TrimRightFunc(head, unicode.IsSpace) + end := len(head) + for end > 0 { + r, size := utf8.DecodeLastRuneInString(head[:end]) + if !unicode.IsLetter(r) { + break + } + end -= size } - end -= size + word := head[end:] + if word == "" { + return false + } + if negators[word] { + return true + } + head = head[:end] } - return negators[head[end:]] + return false } // in matches an English base phrase against the text as written and a chosen @@ -491,7 +511,9 @@ func (p phrase) in(text, folded string) bool { if !p.bounded { return strings.Contains(text, p.text) } - text = folded + if !p.asWritten { + text = folded + } for i := 0; i < len(text); { j := strings.Index(text[i:], p.text) if j < 0 { @@ -568,6 +590,9 @@ func compileRules(parts []langRules) *ruleSet { for _, pos := range p.positive { rs.positive = append(rs.positive, phrase{text: accentFolder.Replace(strings.ToLower(pos)), bounded: i > 0, negatable: i > 0}) } + for _, pos := range p.positiveAsWritten { + rs.positive = append(rs.positive, phrase{text: strings.ToLower(pos), bounded: true, negatable: true, asWritten: true}) + } } rs.quote = append(rs.quote, quoteMarker{re: regexp.MustCompile(`(?i)-{2,}\s*(` + strings.Join(separators, `|`) + `)\s*-{2,}`)}) rs.cue = regexp.MustCompile(`(?i)\b(` + strings.Join(longestFirst(cues), `|`) + `)\b`) diff --git a/internal/app/replyclassify/sentiment_languages_test.go b/internal/app/replyclassify/sentiment_languages_test.go index be2a1c911..0eebe1d98 100644 --- a/internal/app/replyclassify/sentiment_languages_test.go +++ b/internal/app/replyclassify/sentiment_languages_test.go @@ -244,6 +244,10 @@ func TestNegatedAndHedgedInterestIsNotPositive(t *testing.T) { "No me interesa mucho.", "No estoy muy interesado.", "Gracias, pero no estamos muy interesados.", + "Si me interesa, les aviso.", + "No\nme interesa mucho.", + "No quiero agendar una llamada.", + "Wir wollen nicht gleich einen Termin vereinbaren.", } { if got := ClassifyOffline(Input{Subject: "Re: Hallo", BodyText: body, Languages: all}); got.Class == ClassPositive { t.Errorf("%q read as positive", body) @@ -254,12 +258,15 @@ func TestNegatedAndHedgedInterestIsNotPositive(t *testing.T) { // A negating word straight before the phrase turns it around; anything else between does not. func TestNegatedAtReadsTheWordBefore(t *testing.T) { for text, want := range map[string]bool{ - "no me interesa mucho": true, - "nicht klingt gut": true, - "no, me interesa mucho": false, - "bueno me interesa mucho": false, - "me interesa mucho": false, - "pero no me interesa mucho": true, + "no me interesa mucho": true, + "nicht klingt gut": true, + "no, me interesa mucho": false, + "bueno me interesa mucho": false, + "me interesa mucho": false, + "pero no me interesa mucho": true, + "no\nme interesa mucho": true, + "no quiero me interesa mucho": true, + "no a b c me interesa mucho": false, } { start := len(text) - len("me interesa mucho") if text == "nicht klingt gut" { From f7302bb7b14973da0465190d9bafaccf169e897d Mon Sep 17 00:00:00 2001 From: 555aaditya <107977627+555aaditya@users.noreply.github.com> Date: Wed, 28 Oct 2026 14:22:57 +0530 Subject: [PATCH 006/318] feat: add the first tests for the Apollo and Clay integrations, covering Clay's body shapes and column spellings and Apollo's enrichment cells, person accessors and retry backoff --- internal/app/apollo/enrich_test.go | 117 +++++++++++++++++++++++++ internal/app/clay/row_test.go | 136 +++++++++++++++++++++++++++++ 2 files changed, 253 insertions(+) create mode 100644 internal/app/apollo/enrich_test.go create mode 100644 internal/app/clay/row_test.go diff --git a/internal/app/apollo/enrich_test.go b/internal/app/apollo/enrich_test.go new file mode 100644 index 000000000..001e22ab6 --- /dev/null +++ b/internal/app/apollo/enrich_test.go @@ -0,0 +1,117 @@ +package apollo + +import ( + "strings" + "testing" + "time" + + "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/repository" +) + +// cell is the value enrichCells wrote for one target, or "" when it left it alone. +func cell(cells []string, target models.ContactImportColumnTarget, custom string) string { + for i, col := range importColumns { + if col.target == target && col.custom == custom { + return cells[i] + } + } + return "" +} + +func TestEnrichCellsFillsBlanksAndKeepsWhatIsThere(t *testing.T) { + ref := repository.ApolloContactRef{ + Email: "ana@acme.test", FirstName: "Ana", Company: "", + CustomFields: map[string]string{"title": "Founder"}, + } + p := Person{ + Email: "someone-else@acme.test", FirstName: "Anna", LastName: "Lรณpez", OrganizationName: " Acme ", + Title: "CEO", City: "Madrid", PhoneNumbers: []PhoneNumber{{RawNumber: "+34 600 000 000"}}, + } + cells, changed := enrichCells(ref, p, false) + if !changed { + t.Fatal("blank fields were not filled") + } + if got := cell(cells, models.ContactImportTargetEmail, ""); got != "ana@acme.test" { + t.Errorf("email = %q, want the contact's own address", got) + } + for name, got := range map[string]string{ + "first name": cell(cells, models.ContactImportTargetFirstName, ""), + "title": cell(cells, models.ContactImportTargetCustom, "title"), + } { + if got != "" { + t.Errorf("%s overwritten with %q without overwrite", name, got) + } + } + for name, tc := range map[string]struct{ got, want string }{ + "last name": {cell(cells, models.ContactImportTargetLastName, ""), "Lรณpez"}, + "company": {cell(cells, models.ContactImportTargetCompany, ""), "Acme"}, + "phone": {cell(cells, models.ContactImportTargetPhone, ""), "+34 600 000 000"}, + "city": {cell(cells, models.ContactImportTargetCustom, "city"), "Madrid"}, + } { + if tc.got != tc.want { + t.Errorf("%s = %q, want %q", name, tc.got, tc.want) + } + } +} + +func TestEnrichCellsOverwriteAndNoChange(t *testing.T) { + ref := repository.ApolloContactRef{Email: "ana@acme.test", FirstName: "Ana", CustomFields: map[string]string{"title": "Founder"}} + cells, changed := enrichCells(ref, Person{FirstName: "Anna", Title: "CEO"}, true) + if !changed || cell(cells, models.ContactImportTargetFirstName, "") != "Anna" || cell(cells, models.ContactImportTargetCustom, "title") != "CEO" { + t.Errorf("overwrite did not replace: changed=%v cells=%q", changed, cells) + } + // The same values, or nothing new, change nothing. + if _, changed := enrichCells(ref, Person{FirstName: "Ana", Title: "Founder"}, true); changed { + t.Error("identical values reported a change") + } + if _, changed := enrichCells(ref, Person{}, true); changed { + t.Error("an empty match reported a change") + } + long := strings.Repeat("x", 600) + cells, _ = enrichCells(repository.ApolloContactRef{Email: "a@acme.test"}, Person{Title: long}, false) + if got := cell(cells, models.ContactImportTargetCustom, "title"); len(got) != 500 { + t.Errorf("title length = %d, want 500", len(got)) + } +} + +func TestPersonAccessorsReadWhereApolloPutsTheValue(t *testing.T) { + org := &Org{Name: "Org Co", WebsiteURL: " https://org.test ", PrimaryDomain: "", Domain: "org.test", Industry: " Software "} + p := Person{Organization: org, Account: &Org{Name: "Account Co"}} + if p.Company() != "Org Co" || p.Website() != "https://org.test" || p.CompanyDomain() != "org.test" || p.Industry() != "Software" { + t.Errorf("organization fields = %q %q %q %q", p.Company(), p.Website(), p.CompanyDomain(), p.Industry()) + } + if got := (Person{OrganizationName: " Named ", Organization: org}).Company(); got != "Named" { + t.Errorf("organization_name did not win: %q", got) + } + if got := (Person{Account: &Org{Name: "Account Co", PrimaryDomain: "acct.test"}}).CompanyDomain(); got != "acct.test" { + t.Errorf("account domain = %q", got) + } + contactPhone := Person{Contact: &struct { + PhoneNumbers []PhoneNumber `json:"phone_numbers"` + }{PhoneNumbers: []PhoneNumber{{RawNumber: " "}, {SanitizedNumber: "+15550100", RawNumber: "(555) 0100"}}}} + if got := contactPhone.Phone(); got != "+15550100" { + t.Errorf("phone = %q, want the first usable sanitized number", got) + } + if got := (Person{FirstName: "Ana", LastName: "Lรณpez"}).DisplayName(); got != "Ana Lรณpez" { + t.Errorf("display name = %q", got) + } +} + +func TestBackoffHonoursABoundedRetryAfter(t *testing.T) { + for _, tc := range []struct { + attempt int + retryAfter string + want time.Duration + }{ + {0, "", time.Second}, + {3, "", 8 * time.Second}, + {0, "5", 5 * time.Second}, + {0, "120", time.Second}, + {2, "soon", 4 * time.Second}, + } { + if got := backoff(tc.attempt, tc.retryAfter); got != tc.want { + t.Errorf("backoff(%d, %q) = %s, want %s", tc.attempt, tc.retryAfter, got, tc.want) + } + } +} diff --git a/internal/app/clay/row_test.go b/internal/app/clay/row_test.go new file mode 100644 index 000000000..7aef9c6e6 --- /dev/null +++ b/internal/app/clay/row_test.go @@ -0,0 +1,136 @@ +package clay + +import ( + "fmt" + "reflect" + "strings" + "testing" +) + +func TestParseBodyAcceptsEveryShapeClaySends(t *testing.T) { + for name, tc := range map[string]struct { + body string + rows int + }{ + "one object": {`{"email":"a@x.test"}`, 1}, + "an array": {`[{"email":"a@x.test"},{"email":"b@x.test"}]`, 2}, + "under rows": {`{"rows":[{"email":"a@x.test"},{"email":"b@x.test"}]}`, 2}, + "under contacts": {`{"contacts":[{"email":"a@x.test"}]}`, 1}, + "under records": {`{"records":[{"email":"a@x.test"},{"email":"b@x.test"},{"email":"c@x.test"}]}`, 3}, + "a rows field that is no array": {`{"email":"a@x.test","rows":"3"}`, 1}, + "surrounding whitespace": {" \n[{\"email\":\"a@x.test\"}]\n", 1}, + } { + t.Run(name, func(t *testing.T) { + rows, err := parseBody([]byte(tc.body)) + if err != nil { + t.Fatal(err) + } + if len(rows) != tc.rows { + t.Errorf("rows = %d, want %d", len(rows), tc.rows) + } + }) + } +} + +func TestParseBodyRefusesWhatIsNotRows(t *testing.T) { + tooMany := "[" + strings.TrimSuffix(strings.Repeat(`{"email":"a@x.test"},`, MaxRows+1), ",") + "]" + for name, body := range map[string]string{ + "empty": "", + "not JSON": "email=a@x.test", + "a bare string": `"a@x.test"`, + "broken object": `{"email":`, + "an empty array": `[]`, + "rows holding a non-object": `{"rows":["a@x.test"]}`, + "more than MaxRows": tooMany, + } { + t.Run(name, func(t *testing.T) { + if rows, err := parseBody([]byte(body)); err == nil { + t.Errorf("parseBody accepted %d rows", len(rows)) + } + }) + } +} + +func TestNormalizeRowReadsClayColumnSpellings(t *testing.T) { + r := normalizeRow(map[string]any{ + "Work Email": " ana@acme.test ", + "Full Name": "Ana Marรญa Lรณpez", + "Company Name": "Acme", + "Mobile Phone": "+44 20 7946 0000", + "Job Title": "Head of Sales", + "LinkedIn URL": "https://linkedin.com/in/ana", + "Funding Stage": "Series B", + "Employee Count": float64(120), + "_clay_row_id": "r_1", + "Notes": "", + "Tags": "vip, warm; q4", + "custom_fields": map[string]any{"Lead Score": float64(87)}, + "Email Status": "valid", + "Unrelated Empty": nil, + }) + if r.email != "ana@acme.test" || r.company != "Acme" || r.phone != "+44 20 7946 0000" || r.verification != "valid" { + t.Errorf("fields = %+v", r) + } + // A full name fills first and last only when neither came on its own. + if r.first != "Ana" || r.last != "Marรญa Lรณpez" { + t.Errorf("name = %q %q", r.first, r.last) + } + if !reflect.DeepEqual(r.categories, []string{"vip", "warm", "q4"}) { + t.Errorf("categories = %q", r.categories) + } + want := map[string]string{ + "title": "Head of Sales", + "linkedin_url": "https://linkedin.com/in/ana", + "employee_count": "120", + "Funding Stage": "Series B", + "Lead Score": "87", + } + if !reflect.DeepEqual(r.custom, want) { + t.Errorf("custom = %v, want %v", r.custom, want) + } +} + +func TestNormalizeRowKeepsExplicitNamesAndReadsTheCampaign(t *testing.T) { + r := normalizeRow(map[string]any{ + "email": "b@acme.test", "first_name": "Bo", "name": "Robert Smith", + "campaign_id": "3f6b3c1e-6d0b-4d9e-9a8e-2f3c4b5a6d7e", + }) + if r.first != "Bo" || r.last != "" { + t.Errorf("an explicit first name lost to the full name: %q %q", r.first, r.last) + } + if r.campaign == nil || r.campaign.String() != "3f6b3c1e-6d0b-4d9e-9a8e-2f3c4b5a6d7e" || r.campaignErr { + t.Errorf("campaign = %v, err %v", r.campaign, r.campaignErr) + } + if bad := normalizeRow(map[string]any{"email": "c@acme.test", "campaign_id": "not-a-uuid"}); bad.campaign != nil || !bad.campaignErr { + t.Errorf("a malformed campaign id was not flagged: %+v", bad) + } +} + +func TestNormalizeRowCapsTags(t *testing.T) { + tags := make([]any, 30) + for i := range tags { + tags[i] = fmt.Sprintf("t%d", i) + } + if r := normalizeRow(map[string]any{"email": "d@acme.test", "tags": tags}); len(r.categories) != 20 || r.categories[0] != "t0" { + t.Errorf("categories = %d, first %q", len(r.categories), r.categories[0]) + } +} + +func TestSplitNameAndScalar(t *testing.T) { + for in, want := range map[string][2]string{"": {"", ""}, "Ana": {"Ana", ""}, " Ana Marรญa Lรณpez ": {"Ana", "Marรญa Lรณpez"}} { + if f, l := splitName(in); f != want[0] || l != want[1] { + t.Errorf("splitName(%q) = %q %q", in, f, l) + } + } + for v, want := range map[any]string{" x ": "x", float64(1.5): "1.5", true: "true"} { + if got := scalar(v); got != want { + t.Errorf("scalar(%v) = %q, want %q", v, got, want) + } + } + if got := scalar([]any{"a", "", float64(2)}); got != "a, 2" { + t.Errorf("scalar(list) = %q", got) + } + if got := scalar(map[string]any{"a": "b"}); got != "" { + t.Errorf("an object read as a cell: %q", got) + } +} From 92a754e4e8ddfff68bfdb53a6016388defa979f8 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 28 Oct 2026 19:28:41 +0100 Subject: [PATCH 007/318] feat: keep each mailbox health and warmup reading independent of other pending Cloud reports --- docs/content/docs/guides/mailboxes.mdx | 2 + web/src/app/app/emails/page.tsx | 54 ++++++++++++++------------ 2 files changed, 31 insertions(+), 25 deletions(-) diff --git a/docs/content/docs/guides/mailboxes.mdx b/docs/content/docs/guides/mailboxes.mdx index 6cb44a7b6..2cef59817 100644 --- a/docs/content/docs/guides/mailboxes.mdx +++ b/docs/content/docs/guides/mailboxes.mdx @@ -638,6 +638,8 @@ This is not the same as the risk band that decides which sending worker and IP h ## Health +Each Cloud mailbox uses its own current health report. A missing report shows **Unavailable** for that mailbox while other mailboxes keep their reported readings. Summary counts remain unavailable until every listed mailbox has a current status. + The Accounts list groups mailboxes as **Healthy** (sending normally), **Warming** (ramping through warmup), or **Needs attention** (paused, failing, or not sending). Each row shows the mailbox with how it connects and its tags, a **Status** that says what it is doing (**Sending**, **Warming**, **Active** when it does both, **Resting**, or **Idle**, and **Error**, **Off** or **Reconnect** when something stops it), campaign emails sent today against its cap, warmup sent today against the ramp target, the inbox rate, and the health score. Hover a status for the reason, and click any column header to sort. A drop in health between refreshes notifies you rather than waiting to be noticed. Repeated reports of the same error code count once toward the health score, at their highest unresolved severity, rather than making one problem look like several. The drawer groups identical reports while keeping different error details and sending versus sync failures separate. Connection titles name Gmail, Microsoft Outlook or the mail server. **Reported** shows the stored report time: connection and temporary provider-limit observations refresh it, while other error categories may retain their original report time. It is not proof of an ongoing outage. diff --git a/web/src/app/app/emails/page.tsx b/web/src/app/app/emails/page.tsx index 3315fde96..84ad6d0b3 100644 --- a/web/src/app/app/emails/page.tsx +++ b/web/src/app/app/emails/page.tsx @@ -622,31 +622,35 @@ export default function AddressesPage() { - {sortedEmails.map((box) => ( - openMigration(retiringDomain.get(box.id) ?? null)} - checked={selected.includes(box.id)} - onToggleSelect={() => - selected.includes(box.id) - ? setSelected((bef) => bef.filter((i) => i !== box.id)) - : setSelected((bef) => [...bef, box.id]) - } - onOpen={openDetail} - /> - ))} + {sortedEmails.map((box) => { + const cloudRow = cloud.connected ? cloud.rowFor(box.id) : undefined; + const rowCloudUnavailable = cloud.unavailable || !!(cloudRow?.enrolled && !cloudRow.cloud?.health); + return ( + openMigration(retiringDomain.get(box.id) ?? null)} + checked={selected.includes(box.id)} + onToggleSelect={() => + selected.includes(box.id) + ? setSelected((bef) => bef.filter((i) => i !== box.id)) + : setSelected((bef) => [...bef, box.id]) + } + onOpen={openDetail} + /> + ); + })} From 95fbce009bd41db3e756cb4db716db4c825496d2 Mon Sep 17 00:00:00 2001 From: Eliran Yihye Date: Thu, 29 Oct 2026 11:15:05 -0400 Subject: [PATCH 008/318] feat: file provider account notices (Google and Microsoft sign-in, security and service mail) into Archive as read automated system notices kept out of every unibox view, count and the reply pipeline, backfill them in migration 000331, and list pending inbox-agent drafts at the top of the Drafts folder with their count --- docs/content/docs/guides/inbox-agent.mdx | 1 + docs/content/docs/guides/unibox.mdx | 4 +- internal/app/consumer/event_new_email.go | 4 + internal/app/consumer/event_new_email_test.go | 37 +++ .../000331_unibox_system_notices.down.sql | 2 + .../000331_unibox_system_notices.up.sql | 40 +++ internal/pkg/systemmail/systemmail.go | 43 ++++ internal/pkg/systemmail/systemmail_test.go | 54 +++++ internal/repository/pg_inbox_tag.go | 2 + internal/repository/pg_unibox.go | 45 +++- .../repository/unibox_automated_live_test.go | 2 +- .../unibox_system_notice_live_test.go | 229 ++++++++++++++++++ .../components/app/unibox/AgentDraftCard.tsx | 1 + .../app/unibox/ConversationList.tsx | 30 ++- web/src/components/app/unibox/ScopeRail.tsx | 7 +- .../unibox/conversationListDrafts.test.tsx | 111 +++++++++ .../components/app/unibox/scopeRail.test.tsx | 16 ++ 17 files changed, 611 insertions(+), 17 deletions(-) create mode 100644 internal/infrastructure/db/migrations/000331_unibox_system_notices.down.sql create mode 100644 internal/infrastructure/db/migrations/000331_unibox_system_notices.up.sql create mode 100644 internal/pkg/systemmail/systemmail.go create mode 100644 internal/pkg/systemmail/systemmail_test.go create mode 100644 internal/repository/unibox_system_notice_live_test.go create mode 100644 web/src/components/app/unibox/conversationListDrafts.test.tsx diff --git a/docs/content/docs/guides/inbox-agent.mdx b/docs/content/docs/guides/inbox-agent.mdx index bdb48159e..04b28c96d 100644 --- a/docs/content/docs/guides/inbox-agent.mdx +++ b/docs/content/docs/guides/inbox-agent.mdx @@ -32,6 +32,7 @@ A new draft shows up two ways: - In the conversation itself: open the thread in the unibox and the draft appears below the messages, in an editable box, with **Approve and send**, and **Discard**. - In the scope rail: the **Agent drafts** filter lists every conversation with a draft waiting, with a live count next to it. The count and list update the moment a new draft lands, no refresh needed. +- In the **Drafts** folder: the same conversations are listed first, under **Agent drafts**, above the drafts saved in your mailboxes, and the Drafts count includes them. From the draft box you can: diff --git a/docs/content/docs/guides/unibox.mdx b/docs/content/docs/guides/unibox.mdx index 95d90e154..a55884129 100644 --- a/docs/content/docs/guides/unibox.mdx +++ b/docs/content/docs/guides/unibox.mdx @@ -113,7 +113,7 @@ The rail is two short groups and then your mailboxes. The first group is where y | Folder | Group | Shows | | --- | --- | --- | | Inbox | First | Inbound mail, plus anything filed in a custom folder at the provider, unless that folder is [excluded from sync](/guides/mailboxes/#folders-you-do-not-want-synced) | -| Drafts | Second | Messages sitting in a mailbox's drafts folder | +| Drafts | Second | Conversations with an [inbox agent](/guides/inbox-agent/) reply waiting for review, listed first under **Agent drafts**, then messages sitting in a mailbox's drafts folder. The count includes both | | Sent | Second | Outbound mail, campaign and manual | | Archive | Second | Archived (Gmail's All Mail, the Archive folder elsewhere) | | Spam | Second | Junked at the provider | @@ -127,6 +127,8 @@ Each message starts in the folder the provider has it in: IMAP special-use folde Spam and Trash stay out of every other view, and so does Archive: filing a conversation is how you take it out of the way, so it leaves Unread, Awaiting reply, every mailbox, label and tag view, and the unread badge. **All mail** and the **Archive** folder are the two places it stays, which is where you go to find it again. +Account notices a mailbox receives from its own provider never reach the inbox. Connecting a mailbox signs in to it, so Google and Microsoft send it security alerts, 2-Step Verification notices, welcome tips and service notices. Mail from `no-reply@accounts.google.com`, `mail-noreply@google.com`, `workspace-noreply@google.com`, `account-security-noreply@accountprotection.microsoft.com`, `msonlineservicesteam@microsoftonline.com` and `no-reply@microsoft.com` is filed straight into **Archive**, marked read, and left out of All mail, every other view and every count. It never counts as a reply, never starts a webhook, Slack post or agent draft, and it is never deleted: the **Archive** folder and a search in All mail still find it. The match is on the sender's exact address, so a display name or a lookalike domain is ordinary mail. + The initial import that runs when a mailbox is first connected covers Inbox, Sent, Archive, and Drafts. It deliberately skips the existing contents of Spam and Trash, whose history would consume the import budget that belongs to real conversations. Both folders fill normally from the moment the mailbox is connected, so they show what arrives from then on rather than what was already there. diff --git a/internal/app/consumer/event_new_email.go b/internal/app/consumer/event_new_email.go index 97731d648..feb5a7c2b 100644 --- a/internal/app/consumer/event_new_email.go +++ b/internal/app/consumer/event_new_email.go @@ -126,6 +126,10 @@ func (s *JobsService) ingestNewEmail(ctx context.Context, e *models.JobEventNewE CaptureError(e.UserID, e.Message.EmailID, err) return err } + // A provider's notice about the mailbox itself is stored archived and read; it is nobody's reply, so nothing below runs. + if repository.IsSystemNotice(e.Message) { + return nil + } if e.Message != nil { finish = arrivaldiag.Begin(ctx, arrivaldiag.Realtime) inbox := s.emailInboxEvent(ctx, e.UserID, e.Message) diff --git a/internal/app/consumer/event_new_email_test.go b/internal/app/consumer/event_new_email_test.go index e0c63fe9a..801c8ae78 100644 --- a/internal/app/consumer/event_new_email_test.go +++ b/internal/app/consumer/event_new_email_test.go @@ -74,3 +74,40 @@ func TestHandleNewEmailDoesNotProcessSentMailAsReply(t *testing.T) { }) } } + +func TestHandleNewEmailRunsNothingForProviderNotices(t *testing.T) { + for _, tc := range []struct { + name, from string + wantCalls int + }{ + {name: "google security alert", from: "Google "}, + {name: "microsoft sign-in alert", from: "Microsoft account team "}, + {name: "display name spoof", from: "Google ", wantCalls: 1}, + {name: "lookalike domain", from: "no-reply@accounts.google.com.evil.io", wantCalls: 1}, + } { + t.Run(tc.name, func(t *testing.T) { + advancedService := &replyRecordingAdvanced{} + service := &JobsService{ + UniboxRepository: newEmailInboxRepo{}, + EmailRepository: newEmailAccountRepo{}, + AdvancedService: advancedService, + } + err := service.HandleNewEmail(context.Background(), &models.JobEventNewEmail{ + UserID: uuid.New(), + Message: &models.EmailMessageStoreData{ + ID: uuid.New(), EmailID: uuid.New(), Folder: models.FolderInbox, + FromAddr: []string{tc.from}, + ToAddr: []string{"recipient@example.test"}, + MessageID: "", + Subject: "Security alert", + }, + }) + if err != nil { + t.Fatal(err) + } + if advancedService.calls != tc.wantCalls { + t.Fatalf("ProcessIncomingReply calls = %d, want %d", advancedService.calls, tc.wantCalls) + } + }) + } +} diff --git a/internal/infrastructure/db/migrations/000331_unibox_system_notices.down.sql b/internal/infrastructure/db/migrations/000331_unibox_system_notices.down.sql new file mode 100644 index 000000000..c0e72c875 --- /dev/null +++ b/internal/infrastructure/db/migrations/000331_unibox_system_notices.down.sql @@ -0,0 +1,2 @@ +-- Archived rows stay archived: which a person filed is not recorded; Archive and search still list them. +ALTER TABLE unibox_emails DROP COLUMN IF EXISTS system_notice; diff --git a/internal/infrastructure/db/migrations/000331_unibox_system_notices.up.sql b/internal/infrastructure/db/migrations/000331_unibox_system_notices.up.sql new file mode 100644 index 000000000..efb9962fd --- /dev/null +++ b/internal/infrastructure/db/migrations/000331_unibox_system_notices.up.sql @@ -0,0 +1,40 @@ +-- Provider notices to a mailbox about itself (sign-in alerts, 2-Step Verification, tips); old releases ignore the column. +ALTER TABLE unibox_emails ADD COLUMN IF NOT EXISTS system_notice boolean NOT NULL DEFAULT false; + +-- Backfill every workspace with ingest's treatment; senders mirror internal/pkg/systemmail, re-running changes nothing. +UPDATE unibox_emails ue +SET system_notice = true, + automated = true, + seen = true, + folder = CASE WHEN ue.folder = 'inbox' THEN 'archive' ELSE ue.folder END, + updated_at = NOW() +WHERE ( + public.unibox_participants(ue.from_addr, ue.to_addr, ue.cc) ILIKE '%no-reply@accounts.google.com%' + OR public.unibox_participants(ue.from_addr, ue.to_addr, ue.cc) ILIKE '%mail-noreply@google.com%' + OR public.unibox_participants(ue.from_addr, ue.to_addr, ue.cc) ILIKE '%workspace-noreply@google.com%' + OR public.unibox_participants(ue.from_addr, ue.to_addr, ue.cc) ILIKE '%account-security-noreply@accountprotection.microsoft.com%' + OR public.unibox_participants(ue.from_addr, ue.to_addr, ue.cc) ILIKE '%msonlineservicesteam@microsoftonline.com%' + OR public.unibox_participants(ue.from_addr, ue.to_addr, ue.cc) ILIKE '%no-reply@microsoft.com%' + ) + AND ue.folder NOT IN ('sent', 'drafts') + AND ue.provider_folder NOT IN ('sent', 'drafts') + AND ( + SELECT lower(coalesce( + substring(f.addr from '<([^<>]*)>[^<>]*$'), + substring(f.addr from '^[[:space:]]*([^[:space:]()<>"]+@[^[:space:]()<>"]+)[[:space:]]*\('), + substring(f.addr from '\(([^()]*)\)\s*$'), + btrim(f.addr) + )) + FROM unnest(ue.from_addr) WITH ORDINALITY AS f(addr, n) + WHERE f.addr LIKE '%@%' + ORDER BY f.n + LIMIT 1 + ) IN ( + 'no-reply@accounts.google.com', + 'mail-noreply@google.com', + 'workspace-noreply@google.com', + 'account-security-noreply@accountprotection.microsoft.com', + 'msonlineservicesteam@microsoftonline.com', + 'no-reply@microsoft.com' + ) + AND NOT (ue.system_notice AND ue.automated AND ue.seen AND ue.folder <> 'inbox'); diff --git a/internal/pkg/systemmail/systemmail.go b/internal/pkg/systemmail/systemmail.go new file mode 100644 index 000000000..a39baf1f9 --- /dev/null +++ b/internal/pkg/systemmail/systemmail.go @@ -0,0 +1,43 @@ +// Package systemmail recognises a provider's notices to a mailbox about itself (sign-in alerts, 2-Step Verification, tips). +package systemmail + +import ( + "slices" + "strings" + + "github.com/warmbly/warmbly/internal/pkg/mailhdr" +) + +// providerNoticeSenders is matched exactly on the parsed address, never a display name or suffix. +// Migration 000331 backfills from a copy of this list; TestMigrationCoversEverySender keeps them in step. +var providerNoticeSenders = map[string]struct{}{ + "no-reply@accounts.google.com": {}, // Google sign-in, security and 2-Step Verification alerts + "mail-noreply@google.com": {}, // Gmail welcome and tips + "workspace-noreply@google.com": {}, // Google Workspace service and legal notices + "account-security-noreply@accountprotection.microsoft.com": {}, // Microsoft account security and sign-in alerts + "msonlineservicesteam@microsoftonline.com": {}, // Microsoft 365 service notices + "no-reply@microsoft.com": {}, // Microsoft account notices +} + +// Senders returns the recognised addresses, sorted. +func Senders() []string { + out := make([]string, 0, len(providerNoticeSenders)) + for addr := range providerNoticeSenders { + out = append(out, addr) + } + slices.Sort(out) + return out +} + +// IsProviderNotice reports whether the first From entry that parses to an address is a provider notice sender. +func IsProviderNotice(from []string) bool { + for _, raw := range from { + addr := strings.ToLower(strings.TrimSpace(mailhdr.Bare(raw))) + if !strings.Contains(addr, "@") { + continue + } + _, ok := providerNoticeSenders[addr] + return ok + } + return false +} diff --git a/internal/pkg/systemmail/systemmail_test.go b/internal/pkg/systemmail/systemmail_test.go new file mode 100644 index 000000000..2c75b81d3 --- /dev/null +++ b/internal/pkg/systemmail/systemmail_test.go @@ -0,0 +1,54 @@ +package systemmail + +import ( + "os" + "strings" + "testing" +) + +func TestIsProviderNoticeMatchesTheParsedAddressOnly(t *testing.T) { + for _, tc := range []struct { + name string + from []string + want bool + }{ + {"google security alert", []string{"Google "}, true}, + {"gmail team", []string{"Gmail Team "}, true}, + {"workspace team", []string{`"The Google Workspace Team" `}, true}, + {"bare and uppercase", []string{"NO-REPLY@ACCOUNTS.GOOGLE.COM"}, true}, + {"legacy parenthesised form", []string{"Google (no-reply@accounts.google.com)"}, true}, + {"microsoft account security", []string{"Microsoft account team "}, true}, + {"microsoft 365", []string{"Microsoft Online Services Team "}, true}, + {"microsoft no-reply", []string{"Microsoft "}, true}, + {"empty first entry skipped", []string{"", "Google "}, true}, + {"lookalike domain", []string{"Google "}, false}, + {"lookalike prefix", []string{"Google "}, false}, + {"display name spoof", []string{"Google "}, false}, + {"address quoted in display name", []string{`"no-reply@accounts.google.com" `}, false}, + {"other google sender", []string{"Google Calendar "}, false}, + {"only first sender counts", []string{"them@example.com", "Google "}, false}, + {"no sender", nil, false}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := IsProviderNotice(tc.from); got != tc.want { + t.Fatalf("IsProviderNotice(%q) = %v, want %v", tc.from, got, tc.want) + } + }) + } +} + +func TestMigrationCoversEverySender(t *testing.T) { + raw, err := os.ReadFile("../../infrastructure/db/migrations/000331_unibox_system_notices.up.sql") + if err != nil { + t.Fatal(err) + } + sql := string(raw) + for _, addr := range Senders() { + if !strings.Contains(sql, "'%"+addr+"%'") || !strings.Contains(sql, "'"+addr+"'") { + t.Errorf("migration 000331 does not backfill %s", addr) + } + } + if got := strings.Count(sql, "ILIKE '%"); got != len(Senders()) { + t.Errorf("migration prefilters %d senders, the list has %d", got, len(Senders())) + } +} diff --git a/internal/repository/pg_inbox_tag.go b/internal/repository/pg_inbox_tag.go index 10631a007..ba24b1814 100644 --- a/internal/repository/pg_inbox_tag.go +++ b/internal/repository/pg_inbox_tag.go @@ -168,6 +168,7 @@ func (r *inboxTagRepository) Save(ctx context.Context, res *InboxTagResult) erro WHERE ue.email_id = saved.email_account_id AND ue.message_id = saved.message_id AND ue.automated IS DISTINCT FROM saved.automated + AND NOT ue.system_notice ` answers := res.Answers if len(answers) == 0 { @@ -419,6 +420,7 @@ func (r *inboxTagRepository) Reopen(ctx context.Context, orgID uuid.UUID, messag WHERE ue.email_id = dropped.email_account_id AND ue.message_id = dropped.message_id AND ue.automated + AND NOT ue.system_notice ) SELECT labels FROM dropped `, orgID, messageID, kind).Scan(&labels) diff --git a/internal/repository/pg_unibox.go b/internal/repository/pg_unibox.go index 96113964f..343d981a5 100644 --- a/internal/repository/pg_unibox.go +++ b/internal/repository/pg_unibox.go @@ -13,6 +13,7 @@ import ( "github.com/jackc/pgx/v5" "github.com/warmbly/warmbly/internal/infrastructure/db" "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/pkg/systemmail" ) type UpdateUniboxEntry struct { @@ -258,27 +259,39 @@ func (r *uniboxRepository) CreateEntry(ctx context.Context, userID uuid.UUID, e flags, bcc, cc, from_addr, in_reply_to, reply_to, to_addr, subject, size, internal_date, sent_date, snippet, seen, created_at, updated_at, body_text, folder, - provider_folder, automated, filed_forward + provider_folder, automated, filed_forward, system_notice ) VALUES ( $1, $2, $3, $4, $5, COALESCE((SELECT thread_id FROM fwd), $6), $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, - $28, + $29, -- A row re-created by a sync keeps the verdict its message already has. - EXISTS ( + $30 OR EXISTS ( SELECT 1 FROM inbox_tag_results r WHERE r.organization_id = (SELECT organization_id FROM email_accounts WHERE id = $3) AND r.message_id = $7 AND $7 <> '' AND r.automated ), - EXISTS (SELECT 1 FROM fwd) + EXISTS (SELECT 1 FROM fwd), + $30 ) ON CONFLICT (id) DO NOTHING RETURNING thread_id ` + // A message starts where the provider put it; a system notice is filed to Archive, read, while provider_folder keeps the provider's placement for sync. + providerFolder := models.NormalizeFolder(e.Folder, e.Flags) + folder, seen := providerFolder, e.Seen + notice := IsSystemNotice(e) + if notice { + seen = true + if folder == models.FolderInbox { + folder = models.FolderArchive + } + } + // The array columns are NOT NULL. A nil Go slice binds as SQL NULL, so a // message with no In-Reply-To (any thread root) would fail the insert. var threadID string @@ -288,10 +301,8 @@ func (r *uniboxRepository) CreateEntry(ctx context.Context, userID uuid.UUID, e textArray(e.Flags), textArray(e.BCC), textArray(e.CC), textArray(e.FromAddr), textArray(e.InReplyTo), textArray(e.ReplyTo), textArray(e.ToAddr), e.Subject, e.Size, e.InternalDate, e.SentDate, - e.Snippet, e.Seen, e.CreatedAt, e.UpdatedAt, e.BodyText, - // $28 is both columns: a message starts out where the provider put it, - // and only diverges once someone files it in Warmbly. - models.NormalizeFolder(e.Folder, e.Flags), + e.Snippet, seen, e.CreatedAt, e.UpdatedAt, e.BodyText, + folder, providerFolder, notice, ).Scan(&threadID) if errors.Is(err, pgx.ErrNoRows) { // Already stored: the conflict leaves the row as it was. @@ -304,6 +315,11 @@ func (r *uniboxRepository) CreateEntry(ctx context.Context, userID uuid.UUID, e return nil } +// IsSystemNotice reports whether an arriving message is inbound mail from a provider notice sender (systemmail). +func IsSystemNotice(e *models.EmailMessageStoreData) bool { + return e.MayBeInbound() && systemmail.IsProviderNotice(e.FromAddr) +} + // FiledSentForward is a stored copy FileSentForward moved, with its mailbox owner. type FiledSentForward struct { UserID uuid.UUID @@ -745,6 +761,14 @@ func uniboxSearchQuery(orgID uuid.UUID, params *models.MailSearchParams) (string inner += ` AND ue.folder NOT IN ` + foldersOutsideWorkingViews } + // System notices show only in their own folder (never Inbox) and in a search. + searching := (params.Subject != nil && *params.Subject != "") || + (params.Sender != nil && *params.Sender != "") || + (params.Address != nil && *params.Address != "") + if !searching && (params.Folder == nil || *params.Folder == models.FolderInbox) { + inner += ` AND NOT ue.system_notice` + } + // Snooze handling. nil = exclude snoozed (the inbox default), so // threads with an active snooze never appear unless asked for. switch { @@ -981,6 +1005,7 @@ func (r *uniboxRepository) GetUnseenCount(ctx context.Context, orgID uuid.UUID, WHERE ue.email_id IN (SELECT id FROM email_accounts WHERE organization_id = $1) AND ue.seen = FALSE AND ue.folder = '` + models.FolderInbox + `' + AND NOT ue.system_notice AND NOT EXISTS ( SELECT 1 FROM unibox_snoozes s WHERE s.organization_id = $1 AND s.user_id = ue.user_id @@ -1006,6 +1031,7 @@ func (r *uniboxRepository) UnseenCountForMailboxes(ctx context.Context, orgID uu AND ue.email_id = ANY($2::uuid[]) AND ue.seen = FALSE AND ue.folder = '` + models.FolderInbox + `' + AND NOT ue.system_notice AND NOT EXISTS ( SELECT 1 FROM unibox_snoozes s WHERE s.organization_id = $1 AND s.user_id = ue.user_id @@ -1754,6 +1780,7 @@ func (r *uniboxRepository) overview(ctx context.Context, orgID uuid.UUID, accoun FROM unibox_emails e WHERE e.email_id IN `+mailboxes+` AND e.folder NOT IN `+foldersOutsideAllMail+` + AND NOT e.system_notice ), threads AS ( SELECT @@ -1819,6 +1846,7 @@ func (r *uniboxRepository) overview(ctx context.Context, orgID uuid.UUID, accoun AND s.snoozed_until > NOW() ) AND NOT (e.folder = 'inbox' AND `+automatedThreadSQL("e.thread_id", "e.automated", "$1")+`) + AND NOT e.system_notice GROUP BY e.folder `, orgID) if err != nil { @@ -1861,6 +1889,7 @@ func (r *uniboxRepository) overview(ctx context.Context, orgID uuid.UUID, accoun FROM email_accounts ea LEFT JOIN unibox_emails ue ON ue.email_id = ea.id AND ue.user_id = ea.user_id AND ue.folder NOT IN `+foldersOutsideWorkingViews+` + AND NOT ue.system_notice AND NOT `+automatedThreadSQL("ue.thread_id", "ue.automated", "$1")+` WHERE ea.organization_id = $1`+onlyMailboxes("ea.id")+` GROUP BY ea.id, ea.email, ea.name diff --git a/internal/repository/unibox_automated_live_test.go b/internal/repository/unibox_automated_live_test.go index af643d3a6..75d0117b1 100644 --- a/internal/repository/unibox_automated_live_test.go +++ b/internal/repository/unibox_automated_live_test.go @@ -45,7 +45,7 @@ func TestLiveUniboxAutomatedLeavesTheInbox(t *testing.T) { ours := f.mailboxAddress(t, repo) now := time.Now().UTC() - alert := f.scopedMessage(t, repo, "thread-alert", "Google ", models.FolderInbox, now) + alert := f.scopedMessage(t, repo, "thread-alert", "Acme Billing ", models.FolderInbox, now) f.judge(t, handle.Pool, alert, "thread-alert", true) f.scopedMessage(t, repo, "thread-person", "them@example.com", models.FolderInbox, now) diff --git a/internal/repository/unibox_system_notice_live_test.go b/internal/repository/unibox_system_notice_live_test.go new file mode 100644 index 000000000..bee782a93 --- /dev/null +++ b/internal/repository/unibox_system_notice_live_test.go @@ -0,0 +1,229 @@ +package repository + +import ( + "context" + "net/url" + "os" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + "github.com/warmbly/warmbly/internal/infrastructure/db" + "github.com/warmbly/warmbly/internal/models" +) + +// Provider notices to a mailbox about itself land archived, read and out of every working view and counter: +// +// WARMBLY_TEST_DB=postgres://warmbly@127.0.0.1:15432/warmbly_dev?sslmode=disable \ +// go test ./internal/repository/ -run LiveUniboxSystemNotice -v + +// liveFreshUniboxDB is a freshly migrated database of its own, so the backfill can run against it. +func liveFreshUniboxDB(t *testing.T) *db.DB { + t.Helper() + dsn := os.Getenv("WARMBLY_TEST_DB") + if dsn == "" { + t.Skip("WARMBLY_TEST_DB not set") + } + u, err := url.Parse(dsn) + if err != nil || (u.Hostname() != "localhost" && u.Hostname() != "127.0.0.1") { + t.Fatal("system notice fixture requires local PostgreSQL") + } + admin, err := pgx.Connect(t.Context(), dsn) + if err != nil { + t.Fatal(err) + } + name := "system_notice_" + uuid.New().String()[:8] + quoted := pgx.Identifier{name}.Sanitize() + if _, err := admin.Exec(t.Context(), "CREATE DATABASE "+quoted); err != nil { + _ = admin.Close(context.Background()) + t.Fatal(err) + } + u.Path = "/" + name + if err := db.RunMigrations(u.String()); err != nil { + t.Fatal(err) + } + handle, err := db.New(t.Context(), u.String()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + handle.Pool.Close() + if _, err := admin.Exec(context.Background(), "DROP DATABASE "+quoted); err != nil { + t.Error(err) + } + _ = admin.Close(context.Background()) + }) + return handle +} + +type storedPlacement struct { + folder, provider string + seen, automated, systemNotice bool + updatedAt time.Time +} + +func readPlacement(t *testing.T, handle *db.DB, id uuid.UUID) storedPlacement { + t.Helper() + var p storedPlacement + err := handle.Pool.QueryRow(context.Background(), ` + SELECT folder, provider_folder, seen, automated, system_notice, updated_at + FROM unibox_emails WHERE id = $1`, id). + Scan(&p.folder, &p.provider, &p.seen, &p.automated, &p.systemNotice, &p.updatedAt) + if err != nil { + t.Fatalf("read %s: %v", id, err) + } + return p +} + +func TestLiveUniboxSystemNoticeLandsArchivedAndOutOfEveryView(t *testing.T) { + handle := liveFreshUniboxDB(t) + f := newUniboxFolderFixture(t, handle.Pool) + repo := NewUniboxRepository(handle) + ctx := context.Background() + now := time.Now().UTC() + + alert := f.scopedMessage(t, repo, "thread-alert", "Google ", models.FolderInbox, now) + ms := f.scopedMessage(t, repo, "thread-ms", "Microsoft account team ", models.FolderInbox, now) + spoof := f.scopedMessage(t, repo, "thread-spoof", "Google ", models.FolderInbox, now) + f.scopedMessage(t, repo, "thread-person", "them@example.com", models.FolderInbox, now) + + for _, id := range []uuid.UUID{alert, ms} { + p := readPlacement(t, handle, id) + if p.folder != models.FolderArchive || p.provider != models.FolderInbox || !p.seen || !p.automated || !p.systemNotice { + t.Fatalf("notice stored as %+v, want archived, provider inbox, seen, automated, system_notice", p) + } + } + if p := readPlacement(t, handle, spoof); p.folder != models.FolderInbox || p.seen || p.systemNotice { + t.Fatalf("display-name spoof stored as %+v, want an unread inbox message", p) + } + + // The provider still reports the notice in its inbox; sync must not read that as a move back. + if folder, _, moved := models.ResolveFolderSync(models.FolderArchive, models.FolderInbox, models.FolderInbox); moved || folder != models.FolderArchive { + t.Fatalf("sync moved the notice to %q", folder) + } + + search := func(p models.MailSearchParams) *models.MailSearchResult { + t.Helper() + p.PageSize = 50 + res, err := repo.Search(ctx, f.org, &p) + if err != nil { + t.Fatalf("Search: %v", err) + } + return res + } + no, yes := false, true + inbox, archive := models.FolderInbox, models.FolderArchive + hidden := func(label string, res *models.MailSearchResult) { + t.Helper() + if listsThread(res, "thread-alert") || listsThread(res, "thread-ms") { + t.Fatalf("%s = %v, want no system notice", label, threadIDs(res)) + } + } + hidden("inbox", search(models.MailSearchParams{Folder: &inbox, Automated: &no})) + hidden("all mail", search(models.MailSearchParams{IncludeArchived: &yes})) + hidden("unread", search(models.MailSearchParams{Unseen: &yes, Automated: &no})) + hidden("automated", search(models.MailSearchParams{Automated: &yes})) + hidden("awaiting reply", search(models.MailSearchParams{AwaitingReply: &yes})) + if got := search(models.MailSearchParams{IncludeArchived: &yes}); !listsThread(got, "thread-spoof") || !listsThread(got, "thread-person") { + t.Fatalf("all mail = %v, want the spoof and the person", threadIDs(got)) + } + if got := search(models.MailSearchParams{Folder: &archive}); !listsThread(got, "thread-alert") || !listsThread(got, "thread-ms") { + t.Fatalf("archive = %v, want both notices", threadIDs(got)) + } + query := "Scope" + if got := search(models.MailSearchParams{IncludeArchived: &yes, Subject: &query}); !listsThread(got, "thread-alert") { + t.Fatalf("all mail search = %v, want the notice findable", threadIDs(got)) + } + + ov, err := repo.Overview(ctx, f.org) + if err != nil { + t.Fatalf("Overview: %v", err) + } + if ov.Total != 2 || ov.Unread != 2 || ov.Automated != 0 { + t.Fatalf("overview total=%d unread=%d automated=%d, want 2, 2, 0", ov.Total, ov.Unread, ov.Automated) + } + for _, fo := range ov.Folders { + if fo.Folder == models.FolderArchive && fo.Total != 0 { + t.Fatalf("archive folder total = %d, want 0", fo.Total) + } + } + if n, err := repo.GetUnseenCount(ctx, f.org, nil); err != nil || n != 2 { + t.Fatalf("unread badge = %d (%v), want 2", n, err) + } + + // A later classifier verdict never turns a notice back into a person's mail. + err = NewInboxTagRepository(handle.Pool).Save(ctx, &InboxTagResult{ + OrganizationID: f.org, EmailAccountID: f.mailbox, + MessageID: "<" + alert.String() + "@test.local>", ThreadID: "thread-alert", + Kind: "human_reply", KindConfidence: 0.9, KindSource: "model", Priority: "whenever", + }) + if err != nil { + t.Fatalf("Save verdict: %v", err) + } + if p := readPlacement(t, handle, alert); !p.automated { + t.Fatal("a human verdict cleared automated on a system notice") + } +} + +func TestLiveUniboxSystemNoticeBackfillIsIdempotent(t *testing.T) { + handle := liveFreshUniboxDB(t) + f := newUniboxFolderFixture(t, handle.Pool) + repo := NewUniboxRepository(handle) + ctx := context.Background() + now := time.Now().UTC() + + // Rows stored before the rule: written as ordinary mail, then given the sender they arrived with. + legacy := func(thread, from, folder string) uuid.UUID { + t.Helper() + id := f.scopedMessage(t, repo, thread, "them@example.com", folder, now) + if _, err := handle.Pool.Exec(ctx, `UPDATE unibox_emails SET from_addr = $2 WHERE id = $1`, id, []string{from}); err != nil { + t.Fatal(err) + } + return id + } + google := legacy("t-google", "Google ", models.FolderInbox) + gmail := legacy("t-gmail", "Gmail Team ", models.FolderInbox) + spam := legacy("t-spam", "Microsoft ", models.FolderSpam) + lookalike := legacy("t-look", "Google ", models.FolderInbox) + spoof := legacy("t-spoof", "Google ", models.FolderInbox) + cc := legacy("t-cc", "them@example.com", models.FolderInbox) + if _, err := handle.Pool.Exec(ctx, `UPDATE unibox_emails SET cc = ARRAY['no-reply@accounts.google.com'] WHERE id = $1`, cc); err != nil { + t.Fatal(err) + } + + up, err := os.ReadFile("../infrastructure/db/migrations/000331_unibox_system_notices.up.sql") + if err != nil { + t.Fatal(err) + } + if _, err := handle.Pool.Exec(ctx, string(up)); err != nil { + t.Fatalf("backfill: %v", err) + } + + for _, id := range []uuid.UUID{google, gmail} { + if p := readPlacement(t, handle, id); p.folder != models.FolderArchive || p.provider != models.FolderInbox || !p.seen || !p.automated || !p.systemNotice { + t.Fatalf("backfilled notice = %+v, want archived, seen, automated, system_notice", p) + } + } + if p := readPlacement(t, handle, spam); p.folder != models.FolderSpam || !p.systemNotice || !p.seen { + t.Fatalf("notice in spam = %+v, want left in spam, marked", p) + } + for _, id := range []uuid.UUID{lookalike, spoof, cc} { + if p := readPlacement(t, handle, id); p.folder != models.FolderInbox || p.seen || p.systemNotice { + t.Fatalf("non-notice touched: %+v", p) + } + } + + before := readPlacement(t, handle, google) + tag, err := handle.Pool.Exec(ctx, string(up)) + if err != nil { + t.Fatalf("backfill rerun: %v", err) + } + if tag.RowsAffected() != 0 { + t.Fatalf("rerun updated %d rows, want 0", tag.RowsAffected()) + } + if after := readPlacement(t, handle, google); !after.updatedAt.Equal(before.updatedAt) { + t.Fatal("rerun touched an already treated row") + } +} diff --git a/web/src/components/app/unibox/AgentDraftCard.tsx b/web/src/components/app/unibox/AgentDraftCard.tsx index 7fe02f03e..05639659f 100644 --- a/web/src/components/app/unibox/AgentDraftCard.tsx +++ b/web/src/components/app/unibox/AgentDraftCard.tsx @@ -30,6 +30,7 @@ export default function AgentDraftCard({ threadId }: { threadId: string }) { const refresh = () => { void queryClient.invalidateQueries({ queryKey: ["unibox", "agent-drafts"] }); void queryClient.invalidateQueries({ queryKey: ["unibox", "overview"] }); + void queryClient.invalidateQueries({ queryKey: ["unibox", "search"] }); void queryClient.invalidateQueries({ queryKey: ["unibox", "thread", threadId] }); }; diff --git a/web/src/components/app/unibox/ConversationList.tsx b/web/src/components/app/unibox/ConversationList.tsx index ea99d0f2b..33418f5c7 100644 --- a/web/src/components/app/unibox/ConversationList.tsx +++ b/web/src/components/app/unibox/ConversationList.tsx @@ -32,15 +32,18 @@ import { cn } from "@/lib/utils"; import type { UniboxSearchParams } from "@/lib/api/models/app/unibox/UniboxSearch"; import { Checkbox } from "@/components/ui/checkbox"; -type Bucket = "today" | "yesterday" | "week" | "earlier"; +type Bucket = "agent" | "today" | "yesterday" | "week" | "earlier"; const BUCKET_LABELS: Record = { + agent: "Agent drafts", today: "Today", yesterday: "Yesterday", week: "This week", earlier: "Earlier", }; +const NO_ROWS: ReturnType["emails"] = []; + // Views where an empty list means the work is done rather than that nothing // ever landed there. const CAUGHT_UP_SCOPES = new Set(["folder:inbox", "unread", "awaiting", "all"]); @@ -121,7 +124,26 @@ export function ConversationList({ const emptyScope = params.accountIds?.length === 0 || params.categoryIds?.length === 0; const result = useUniboxSearch(merged, scopeKey, !emptyScope); const q = emptyScope ? { ...result, emails: [], isPending: false, isFetching: false, hasNextPage: false } : result; - const emails = q.emails; + + // Drafts lists threads with a pending inbox-agent draft above the mailbox's own drafts. + const draftsFolder = params.folder === "drafts" && !emptyScope; + const agentParams = React.useMemo( + () => ({ ...merged, folder: undefined, agentDrafts: true }), + [merged], + ); + const agent = useUniboxSearch(agentParams, `${scopeKey}:agent`, draftsFolder); + const agentRows = draftsFolder ? agent.emails : NO_ROWS; + const agentKeys = React.useMemo( + () => new Set(agentRows.map((r) => r.thread_id || r.id)), + [agentRows], + ); + const emails = React.useMemo( + () => + agentRows.length === 0 + ? q.emails + : [...agentRows, ...q.emails.filter((r) => !agentKeys.has(r.thread_id || r.id))], + [agentRows, agentKeys, q.emails], + ); const totalShown = emails.length; const activeFilters = countUserFilters(params, baseParams); @@ -265,13 +287,13 @@ export function ConversationList({ )[] = []; let last: Bucket | null = null; for (const e of emails) { - const b = bucketFor(new Date(e.internal_date)); + const b = agentKeys.has(rowKey(e)) ? "agent" : bucketFor(new Date(e.internal_date)); if (b !== last) out.push({ kind: "header", key: `bucket:${b}`, bucket: b }); last = b; out.push({ kind: "row", key: rowKey(e), row: e }); } return out; - }, [emails, rowKey]); + }, [emails, rowKey, agentKeys]); // Which items were on screen last time, and a generation per key that // left. A key that comes back gets a fresh presence key: AnimatePresence diff --git a/web/src/components/app/unibox/ScopeRail.tsx b/web/src/components/app/unibox/ScopeRail.tsx index 841629ff8..f70ed6a91 100644 --- a/web/src/components/app/unibox/ScopeRail.tsx +++ b/web/src/components/app/unibox/ScopeRail.tsx @@ -274,14 +274,15 @@ export function ScopeRail({ scope, onChange, browseKey = "desktop" }: ScopeRailP const folderRow = (folder: UniboxFolder, label: string, icon: React.ReactNode): RailRow => { const counts = folderCounts.get(folder); - // Drafts reads better as a total; everywhere else the number is unread. - const count = folder === "drafts" ? counts?.total : counts?.unread; + // Drafts reads better as a total, pending agent drafts included; everywhere else the number is unread. + const agentDrafts = folder === "drafts" ? (data?.awaiting_agent_draft ?? 0) : 0; + const count = folder === "drafts" ? (counts?.total ?? 0) + agentDrafts : counts?.unread; return { key: `folder:${folder}`, label, icon, count: count || undefined, - accent: folder !== "drafts" && !!count, + accent: folder === "drafts" ? agentDrafts > 0 : !!count, noun: "folder", onOpen: () => onChange({ kind: "folder", folder }), onMarkAllRead: readOnly ? undefined : () => markSeen.mutate({ folder, seen: true }), diff --git a/web/src/components/app/unibox/conversationListDrafts.test.tsx b/web/src/components/app/unibox/conversationListDrafts.test.tsx new file mode 100644 index 000000000..14628b91e --- /dev/null +++ b/web/src/components/app/unibox/conversationListDrafts.test.tsx @@ -0,0 +1,111 @@ +// The Drafts folder lists threads with a pending inbox-agent draft above the mailbox's own drafts. + +import React from "react"; +import { afterEach, expect, it, vi } from "vitest"; +import { cleanup, render, screen } from "@testing-library/react"; +import type { UniboxSearchParams } from "@/lib/api/models/app/unibox/UniboxSearch"; +import { ConversationList } from "./ConversationList"; + +const search = vi.hoisted(() => ({ calls: [] as { params: UniboxSearchParams; enabled: boolean }[] })); + +function row(id: string, thread: string, subject: string) { + return { + id, + thread_id: thread, + email_id: "m1", + from_addr: ["Lead "], + to_addr: ["me@example.com"], + subject, + snippet: subject, + internal_date: new Date().toISOString(), + has_unread: false, + message_count: 1, + labels: [], + }; +} + +vi.mock("@/lib/api/hooks/app/unibox/useUniboxSearch", () => ({ + default: (params: UniboxSearchParams, _scopeKey: string, enabled = true) => { + search.calls.push({ params, enabled }); + const emails = !enabled + ? [] + : params.agentDrafts + ? [row("a1", "t-agent", "Agent reply to a lead"), row("a2", "t-both", "Agent reply on a drafted thread")] + : [row("d1", "t-mine", "My own draft"), row("d2", "t-both", "Provider copy of a drafted thread")]; + return { + emails, + isPending: false, + isFetching: false, + isPlaceholderData: false, + isError: false, + hasNextPage: false, + isFetchingNextPage: false, + isFetchNextPageError: false, + fetchNextPage: () => Promise.resolve(), + refetch: () => Promise.resolve(), + }; + }, +})); +vi.mock("./ConversationItem", () => ({ + ConversationItem: ({ email }: { email: { subject: string } }) =>
{email.subject}
, +})); +vi.mock("./AnimatedRow", () => ({ + AnimatedRow: ({ children }: { children: React.ReactNode }) => <>{children}, +})); +vi.mock("./SelectionBar", () => ({ SelectionBar: () => null })); +vi.mock("./UniboxFilterPopover", () => ({ + countUserFilters: () => 0, + UniboxFilterButton: () => null, + UniboxFilterChips: () => null, +})); +vi.mock("@/components/app/unibox/compose/ComposeButton", () => ({ default: () => null })); +vi.mock("@/hooks/useConversationActions", () => ({ useConversationActions: () => ({}) })); +vi.mock("@/hooks/useShortcutActions", () => ({ useShortcutActions: () => {} })); +vi.mock("@/hooks/usePermission", () => ({ useAccessRestricted: () => false })); +vi.mock("@/hooks/useBrowseDebouncedValue", () => ({ default: (v: unknown) => v })); +vi.mock("@/hooks/useScrollMemory", () => ({ useScrollMemory: () => {} })); +vi.mock("framer-motion", async (importOriginal) => ({ + ...(await importOriginal>()), + AnimatePresence: ({ children }: { children: React.ReactNode }) => <>{children}, +})); + +afterEach(() => { + cleanup(); + search.calls = []; +}); + +function mount(params: UniboxSearchParams, scopeKey: string) { + return render( + {}} + search="" + setSearch={() => {}} + />, + ); +} + +it("lists pending agent drafts first under their own header, then the mailbox drafts", () => { + mount({ sortBy: "newest", folder: "drafts" }, "folder:drafts"); + + expect(screen.getByText("Agent drafts")).toBeTruthy(); + expect(screen.getAllByTestId("row").map((r) => r.textContent)).toEqual([ + "Agent reply to a lead", + "Agent reply on a drafted thread", + "My own draft", + ]); + const agent = search.calls.find((c) => c.params.agentDrafts); + expect(agent?.enabled).toBe(true); + expect(agent?.params.folder).toBeUndefined(); +}); + +it("leaves every other folder alone", () => { + mount({ sortBy: "newest", folder: "inbox", automated: false }, "folder:inbox"); + + expect(screen.queryByText("Agent drafts")).toBeNull(); + expect(search.calls.filter((c) => c.params.agentDrafts).every((c) => !c.enabled)).toBe(true); + expect(screen.getAllByTestId("row")).toHaveLength(2); +}); diff --git a/web/src/components/app/unibox/scopeRail.test.tsx b/web/src/components/app/unibox/scopeRail.test.tsx index d18a055cd..d2d029e21 100644 --- a/web/src/components/app/unibox/scopeRail.test.tsx +++ b/web/src/components/app/unibox/scopeRail.test.tsx @@ -1139,3 +1139,19 @@ describe("sanitizeUniboxRailFavorites", () => { } }); }); + +it("counts pending agent drafts on Drafts and highlights them", () => { + const saved = overview.data; + overview.data = { + ...saved, + awaiting_agent_draft: 3, + folders: [...saved.folders, { folder: "drafts", unread: 0, total: 1 }], + }; + try { + mountRail(); + const rows = Array.from(document.querySelectorAll("[data-rail-row]")).map((r) => r.textContent ?? ""); + expect(rows.find((r) => r.startsWith("Drafts"))).toBe("Drafts4"); + } finally { + overview.data = saved; + } +}); From 7d05620d7d4aa716c3cdeb44b846a946511c542c Mon Sep 17 00:00:00 2001 From: Eliran Yihye Date: Thu, 29 Oct 2026 11:23:55 -0400 Subject: [PATCH 009/318] fix: keep system notices out of reply repair and Inbox searches, count them in Archive, clear the flag when a user files one into Inbox, and load every page of pending agent drafts --- docs/content/docs/guides/unibox.mdx | 2 +- internal/repository/pg_unibox.go | 16 ++-- internal/repository/pg_unibox_warmup.go | 3 + .../unibox_system_notice_live_test.go | 80 ++++++++++++++++++- .../app/unibox/ConversationList.tsx | 10 +++ .../unibox/conversationListDrafts.test.tsx | 30 ++++++- 6 files changed, 130 insertions(+), 11 deletions(-) diff --git a/docs/content/docs/guides/unibox.mdx b/docs/content/docs/guides/unibox.mdx index a55884129..f98d0c99e 100644 --- a/docs/content/docs/guides/unibox.mdx +++ b/docs/content/docs/guides/unibox.mdx @@ -127,7 +127,7 @@ Each message starts in the folder the provider has it in: IMAP special-use folde Spam and Trash stay out of every other view, and so does Archive: filing a conversation is how you take it out of the way, so it leaves Unread, Awaiting reply, every mailbox, label and tag view, and the unread badge. **All mail** and the **Archive** folder are the two places it stays, which is where you go to find it again. -Account notices a mailbox receives from its own provider never reach the inbox. Connecting a mailbox signs in to it, so Google and Microsoft send it security alerts, 2-Step Verification notices, welcome tips and service notices. Mail from `no-reply@accounts.google.com`, `mail-noreply@google.com`, `workspace-noreply@google.com`, `account-security-noreply@accountprotection.microsoft.com`, `msonlineservicesteam@microsoftonline.com` and `no-reply@microsoft.com` is filed straight into **Archive**, marked read, and left out of All mail, every other view and every count. It never counts as a reply, never starts a webhook, Slack post or agent draft, and it is never deleted: the **Archive** folder and a search in All mail still find it. The match is on the sender's exact address, so a display name or a lookalike domain is ordinary mail. +Account notices a mailbox receives from its own provider never reach the inbox. Connecting a mailbox signs in to it, so Google and Microsoft send it security alerts, 2-Step Verification notices, welcome tips and service notices. Mail from `no-reply@accounts.google.com`, `mail-noreply@google.com`, `workspace-noreply@google.com`, `account-security-noreply@accountprotection.microsoft.com`, `msonlineservicesteam@microsoftonline.com` and `no-reply@microsoft.com` is filed straight into **Archive**, marked read, and left out of All mail, every other view and every count except the Archive folder's own. It never counts as a reply, never starts a webhook, Slack post or agent draft, and it is never deleted: the **Archive** folder and a search in All mail still find it. The match is on the sender's exact address, so a display name or a lookalike domain is ordinary mail. Moving a notice into **Inbox** yourself turns it back into ordinary mail. The initial import that runs when a mailbox is first connected covers Inbox, Sent, Archive, and Drafts. It deliberately skips the existing contents of Spam and Trash, whose history would consume the import budget that belongs to real conversations. Both folders fill normally from the moment the mailbox is connected, so they show what arrives from then on rather than what was already there. diff --git a/internal/repository/pg_unibox.go b/internal/repository/pg_unibox.go index 343d981a5..8f48a7f96 100644 --- a/internal/repository/pg_unibox.go +++ b/internal/repository/pg_unibox.go @@ -761,11 +761,11 @@ func uniboxSearchQuery(orgID uuid.UUID, params *models.MailSearchParams) (string inner += ` AND ue.folder NOT IN ` + foldersOutsideWorkingViews } - // System notices show only in their own folder (never Inbox) and in a search. + // System notices never show in Inbox, searched or not; outside a folder only a search finds them. searching := (params.Subject != nil && *params.Subject != "") || (params.Sender != nil && *params.Sender != "") || (params.Address != nil && *params.Address != "") - if !searching && (params.Folder == nil || *params.Folder == models.FolderInbox) { + if (params.Folder != nil && *params.Folder == models.FolderInbox) || (params.Folder == nil && !searching) { inner += ` AND NOT ue.system_notice` } @@ -1218,7 +1218,7 @@ func (r *uniboxRepository) MoveToFolderBulk(ctx context.Context, orgID uuid.UUID return nil, nil } return r.fileRows(ctx, - `UPDATE unibox_emails u SET folder = $1, updated_at = NOW() + `UPDATE unibox_emails u SET folder = $1, updated_at = NOW(),`+fileIntoInboxClearsNotice+` FROM unibox_emails prev WHERE prev.id = u.id AND u.id = ANY($3) AND u.email_id IN (SELECT id FROM email_accounts WHERE organization_id = $2) @@ -1235,7 +1235,7 @@ func (r *uniboxRepository) MoveThreadsToFolder(ctx context.Context, orgID uuid.U return nil, nil } return r.fileRows(ctx, - `UPDATE unibox_emails u SET folder = $1, updated_at = NOW() + `UPDATE unibox_emails u SET folder = $1, updated_at = NOW(),`+fileIntoInboxClearsNotice+` FROM unibox_emails prev WHERE prev.id = u.id AND COALESCE(NULLIF(u.thread_id, ''), u.id::text) = ANY($3) AND u.email_id IN (SELECT id FROM email_accounts WHERE organization_id = $2) @@ -1244,6 +1244,11 @@ func (r *uniboxRepository) MoveThreadsToFolder(ctx context.Context, orgID uuid.U ) } +// fileIntoInboxClearsNotice is the SET tail of a user's filing: a system notice someone files into Inbox becomes their mail again. +const fileIntoInboxClearsNotice = ` + automated = CASE WHEN u.system_notice AND $1 = 'inbox' THEN false ELSE u.automated END, + system_notice = u.system_notice AND $1 <> 'inbox'` + // fileRows runs a filing UPDATE. Rows already in the folder come back too, // unmoved: the provider may still disagree with them. prev is the row as the // statement found it, which is how the folder it left is read. @@ -1846,7 +1851,8 @@ func (r *uniboxRepository) overview(ctx context.Context, orgID uuid.UUID, accoun AND s.snoozed_until > NOW() ) AND NOT (e.folder = 'inbox' AND `+automatedThreadSQL("e.thread_id", "e.automated", "$1")+`) - AND NOT e.system_notice + -- Archive lists its notices, so only Inbox leaves them out of its count. + AND NOT (e.folder = 'inbox' AND e.system_notice) GROUP BY e.folder `, orgID) if err != nil { diff --git a/internal/repository/pg_unibox_warmup.go b/internal/repository/pg_unibox_warmup.go index b5b76afb3..8c20f77c6 100644 --- a/internal/repository/pg_unibox_warmup.go +++ b/internal/repository/pg_unibox_warmup.go @@ -164,6 +164,7 @@ func (r *uniboxRepository) ListUnprocessedCampaignReplies(ctx context.Context, s scan, err := r.db.Query(ctx, `SELECT u.id FROM unibox_emails u WHERE u.id > $1 AND u.created_at >= $2 AND u.campaign_reply_processed_at IS NULL AND u.folder NOT IN ('sent', 'drafts') AND u.provider_folder NOT IN ('sent', 'drafts') + AND NOT u.system_notice ORDER BY u.id LIMIT $3`, afterID, since, scanSize) if err != nil { return page, err @@ -197,6 +198,8 @@ func (r *uniboxRepository) ListUnprocessedCampaignReplies(ctx context.Context, s AND u.campaign_reply_processed_at IS NULL AND u.folder NOT IN ('sent', 'drafts') AND u.provider_folder NOT IN ('sent', 'drafts') + -- A provider notice is nobody's reply; ingest never stamps it, so repair must skip it too. + AND NOT u.system_notice AND ( -- Both forms of each header against the raw column, so idx_tasks_message_id serves it. EXISTS ( diff --git a/internal/repository/unibox_system_notice_live_test.go b/internal/repository/unibox_system_notice_live_test.go index bee782a93..c86fd886e 100644 --- a/internal/repository/unibox_system_notice_live_test.go +++ b/internal/repository/unibox_system_notice_live_test.go @@ -136,6 +136,7 @@ func TestLiveUniboxSystemNoticeLandsArchivedAndOutOfEveryView(t *testing.T) { if got := search(models.MailSearchParams{IncludeArchived: &yes, Subject: &query}); !listsThread(got, "thread-alert") { t.Fatalf("all mail search = %v, want the notice findable", threadIDs(got)) } + hidden("inbox search", search(models.MailSearchParams{Folder: &inbox, Subject: &query})) ov, err := repo.Overview(ctx, f.org) if err != nil { @@ -145,8 +146,11 @@ func TestLiveUniboxSystemNoticeLandsArchivedAndOutOfEveryView(t *testing.T) { t.Fatalf("overview total=%d unread=%d automated=%d, want 2, 2, 0", ov.Total, ov.Unread, ov.Automated) } for _, fo := range ov.Folders { - if fo.Folder == models.FolderArchive && fo.Total != 0 { - t.Fatalf("archive folder total = %d, want 0", fo.Total) + if fo.Folder == models.FolderArchive && (fo.Total != 2 || fo.Unread != 0) { + t.Fatalf("archive folder total=%d unread=%d, want the 2 read notices it lists", fo.Total, fo.Unread) + } + if fo.Folder == models.FolderInbox && fo.Total != 2 { + t.Fatalf("inbox folder total = %d, want 2", fo.Total) } } if n, err := repo.GetUnseenCount(ctx, f.org, nil); err != nil || n != 2 { @@ -227,3 +231,75 @@ func TestLiveUniboxSystemNoticeBackfillIsIdempotent(t *testing.T) { t.Fatal("rerun touched an already treated row") } } + +func TestLiveUniboxSystemNoticeFiledIntoInboxBecomesMail(t *testing.T) { + handle := liveFreshUniboxDB(t) + f := newUniboxFolderFixture(t, handle.Pool) + repo := NewUniboxRepository(handle) + ctx := context.Background() + now := time.Now().UTC() + + alert := f.scopedMessage(t, repo, "thread-alert", "Google ", models.FolderInbox, now) + other := f.scopedMessage(t, repo, "thread-other", "Gmail Team ", models.FolderInbox, now) + + // Filing elsewhere keeps the notice a notice. + if _, err := repo.MoveThreadsToFolder(ctx, f.org, []string{"thread-other"}, models.FolderTrash); err != nil { + t.Fatalf("MoveThreadsToFolder trash: %v", err) + } + if p := readPlacement(t, handle, other); p.folder != models.FolderTrash || !p.systemNotice || !p.automated { + t.Fatalf("notice filed to trash = %+v, want still a system notice", p) + } + + if _, err := repo.MoveThreadsToFolder(ctx, f.org, []string{"thread-alert"}, models.FolderInbox); err != nil { + t.Fatalf("MoveThreadsToFolder inbox: %v", err) + } + if p := readPlacement(t, handle, alert); p.folder != models.FolderInbox || p.systemNotice || p.automated { + t.Fatalf("notice filed into inbox = %+v, want ordinary inbox mail", p) + } + no, inbox := false, models.FolderInbox + res, err := repo.Search(ctx, f.org, &models.MailSearchParams{Folder: &inbox, Automated: &no, PageSize: 50}) + if err != nil { + t.Fatalf("Search: %v", err) + } + if !listsThread(res, "thread-alert") { + t.Fatalf("inbox = %v, want the notice the user filed there", threadIDs(res)) + } + + if _, err := repo.MoveToFolderBulk(ctx, f.org, []uuid.UUID{other}, models.FolderInbox); err != nil { + t.Fatalf("MoveToFolderBulk inbox: %v", err) + } + if p := readPlacement(t, handle, other); p.folder != models.FolderInbox || p.systemNotice { + t.Fatalf("notice moved into inbox by id = %+v, want ordinary inbox mail", p) + } +} + +// The daily reply repair never hands a provider notice to reply detection, even from a contact's address. +func TestLiveUniboxSystemNoticeSkippedByReplyRepair(t *testing.T) { + handle := liveFreshUniboxDB(t) + f := newUniboxFolderFixture(t, handle.Pool) + repo := NewUniboxRepository(handle) + ctx := context.Background() + now := time.Now().UTC() + + for _, addr := range []string{"no-reply@accounts.google.com", "lead@example.com"} { + // contacts.created_at has no time zone: NOW() keeps it in the session's, as the server writes it. + if _, err := handle.Pool.Exec(ctx, `INSERT INTO contacts (id, user_id, organization_id, first_name, last_name, email, company, phone, custom_fields, created_at) + VALUES ($1, $2, $3, '', '', $4, '', '', '{}'::jsonb, NOW() - interval '1 hour')`, uuid.New(), f.user, f.org, addr); err != nil { + t.Fatal(err) + } + } + notice := f.scopedMessage(t, repo, "thread-alert", "Google ", models.FolderInbox, now) + reply := f.scopedMessage(t, repo, "thread-lead", "Lead ", models.FolderInbox, now) + + page, err := repo.ListUnprocessedCampaignReplies(ctx, now.Add(-time.Hour), uuid.Nil, 100) + if err != nil { + t.Fatalf("ListUnprocessedCampaignReplies: %v", err) + } + var got []uuid.UUID + for _, ev := range page.Events { + got = append(got, ev.Message.ID) + } + if len(got) != 1 || got[0] != reply { + t.Fatalf("repair listed %v, want only the lead reply %s (notice %s skipped)", got, reply, notice) + } +} diff --git a/web/src/components/app/unibox/ConversationList.tsx b/web/src/components/app/unibox/ConversationList.tsx index 33418f5c7..167675f1c 100644 --- a/web/src/components/app/unibox/ConversationList.tsx +++ b/web/src/components/app/unibox/ConversationList.tsx @@ -132,6 +132,16 @@ export function ConversationList({ [merged], ); const agent = useUniboxSearch(agentParams, `${scopeKey}:agent`, draftsFolder); + // Pending agent drafts are few, so every page loads up front: one past the first must not drop off the list. + const { + hasNextPage: agentHasMore, + isFetchingNextPage: agentLoadingMore, + isFetchNextPageError: agentMoreFailed, + fetchNextPage: fetchMoreAgent, + } = agent; + React.useEffect(() => { + if (draftsFolder && agentHasMore && !agentLoadingMore && !agentMoreFailed) void fetchMoreAgent(); + }, [draftsFolder, agentHasMore, agentLoadingMore, agentMoreFailed, fetchMoreAgent]); const agentRows = draftsFolder ? agent.emails : NO_ROWS; const agentKeys = React.useMemo( () => new Set(agentRows.map((r) => r.thread_id || r.id)), diff --git a/web/src/components/app/unibox/conversationListDrafts.test.tsx b/web/src/components/app/unibox/conversationListDrafts.test.tsx index 14628b91e..912ab51dc 100644 --- a/web/src/components/app/unibox/conversationListDrafts.test.tsx +++ b/web/src/components/app/unibox/conversationListDrafts.test.tsx @@ -6,7 +6,11 @@ import { cleanup, render, screen } from "@testing-library/react"; import type { UniboxSearchParams } from "@/lib/api/models/app/unibox/UniboxSearch"; import { ConversationList } from "./ConversationList"; -const search = vi.hoisted(() => ({ calls: [] as { params: UniboxSearchParams; enabled: boolean }[] })); +const search = vi.hoisted(() => ({ + calls: [] as { params: UniboxSearchParams; enabled: boolean }[], + agentHasMore: false, + agentNextPage: [] as string[], +})); function row(id: string, thread: string, subject: string) { return { @@ -38,10 +42,13 @@ vi.mock("@/lib/api/hooks/app/unibox/useUniboxSearch", () => ({ isFetching: false, isPlaceholderData: false, isError: false, - hasNextPage: false, + hasNextPage: enabled && !!params.agentDrafts && search.agentHasMore, isFetchingNextPage: false, isFetchNextPageError: false, - fetchNextPage: () => Promise.resolve(), + fetchNextPage: () => { + search.agentNextPage.push(params.agentDrafts ? "agent" : "mailbox"); + return Promise.resolve(); + }, refetch: () => Promise.resolve(), }; }, @@ -72,6 +79,8 @@ vi.mock("framer-motion", async (importOriginal) => ({ afterEach(() => { cleanup(); search.calls = []; + search.agentHasMore = false; + search.agentNextPage = []; }); function mount(params: UniboxSearchParams, scopeKey: string) { @@ -109,3 +118,18 @@ it("leaves every other folder alone", () => { expect(search.calls.filter((c) => c.params.agentDrafts).every((c) => !c.enabled)).toBe(true); expect(screen.getAllByTestId("row")).toHaveLength(2); }); + +it("loads every page of pending agent drafts, not just the first", () => { + search.agentHasMore = true; + mount({ sortBy: "newest", folder: "drafts" }, "folder:drafts"); + + expect(search.agentNextPage).toContain("agent"); + expect(search.agentNextPage).not.toContain("mailbox"); +}); + +it("never pages agent drafts outside the Drafts folder", () => { + search.agentHasMore = true; + mount({ sortBy: "newest", folder: "inbox", automated: false }, "folder:inbox"); + + expect(search.agentNextPage).toEqual([]); +}); From 82714407cbb19d9e9ae90477de2e0dbce8e225d9 Mon Sep 17 00:00:00 2001 From: Bruce <47136857+vulcanhelix@users.noreply.github.com> Date: Thu, 29 Oct 2026 17:26:57 +0000 Subject: [PATCH 010/318] feat: share one transport across the worker's internal API clients in internal/repository that keeps up to 512 idle connections and drains unread bodies on close, so mailbox syncs reuse connections instead of exhausting ephemeral ports --- internal/repository/http_brokered_token.go | 2 +- internal/repository/http_control_plane.go | 47 +++++++++++ .../repository/http_control_plane_test.go | 78 +++++++++++++++++++ internal/repository/http_email_message_map.go | 2 +- internal/repository/http_sync_context.go | 2 +- 5 files changed, 128 insertions(+), 3 deletions(-) create mode 100644 internal/repository/http_control_plane.go create mode 100644 internal/repository/http_control_plane_test.go diff --git a/internal/repository/http_brokered_token.go b/internal/repository/http_brokered_token.go index 0e788c441..809fbf8cc 100644 --- a/internal/repository/http_brokered_token.go +++ b/internal/repository/http_brokered_token.go @@ -38,7 +38,7 @@ func NewHTTPBrokeredTokenClient(baseURL, token string) (BrokeredTokenClient, err return &httpBrokeredTokenClient{ baseURL: strings.TrimRight(baseURL, "/"), token: token, - client: &http.Client{Timeout: 25 * time.Second}, + client: newControlPlaneClient(25 * time.Second), }, nil } diff --git a/internal/repository/http_control_plane.go b/internal/repository/http_control_plane.go new file mode 100644 index 000000000..01facbaa1 --- /dev/null +++ b/internal/repository/http_control_plane.go @@ -0,0 +1,47 @@ +package repository + +import ( + "io" + "net/http" + "time" +) + +// controlPlaneTransport is shared by the worker's internal API clients: http.DefaultTransport keeps only 2 idle connections per host. +var controlPlaneTransport = newControlPlaneTransport() + +func newControlPlaneTransport() http.RoundTripper { + base, ok := http.DefaultTransport.(*http.Transport) + if !ok { + return drainingTransport{next: http.DefaultTransport} + } + t := base.Clone() + t.MaxIdleConns = 512 + t.MaxIdleConnsPerHost = 512 + return drainingTransport{next: t} +} + +func newControlPlaneClient(timeout time.Duration) *http.Client { + return &http.Client{Transport: controlPlaneTransport, Timeout: timeout} +} + +// drainingTransport makes Close read what is left of a body (up to 64 KiB) so the connection is reused even when the caller never read it. +type drainingTransport struct { + next http.RoundTripper +} + +func (t drainingTransport) RoundTrip(req *http.Request) (*http.Response, error) { + resp, err := t.next.RoundTrip(req) + if resp != nil && resp.Body != nil { + resp.Body = drainingBody{resp.Body} + } + return resp, err +} + +type drainingBody struct { + io.ReadCloser +} + +func (b drainingBody) Close() error { + _, _ = io.Copy(io.Discard, io.LimitReader(b.ReadCloser, 64<<10)) + return b.ReadCloser.Close() +} diff --git a/internal/repository/http_control_plane_test.go b/internal/repository/http_control_plane_test.go new file mode 100644 index 000000000..7bf91d0dc --- /dev/null +++ b/internal/repository/http_control_plane_test.go @@ -0,0 +1,78 @@ +package repository + +import ( + "context" + "net" + "net/http" + "net/http/httptest" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/google/uuid" +) + +// countingServer is an httptest server that counts the connections opened to it. +func countingServer(t *testing.T, h http.HandlerFunc) (*httptest.Server, *atomic.Int32) { + t.Helper() + var opened atomic.Int32 + srv := httptest.NewUnstartedServer(h) + srv.Config.ConnState = func(_ net.Conn, s http.ConnState) { + if s == http.StateNew { + opened.Add(1) + } + } + srv.Start() + t.Cleanup(srv.Close) + return srv, &opened +} + +func TestControlPlaneClientReusesConnectionsUnderConcurrency(t *testing.T) { + srv, opened := countingServer(t, func(w http.ResponseWriter, _ *http.Request) { + // Hold each call open so every round has all of its calls in flight at once. + time.Sleep(10 * time.Millisecond) + w.WriteHeader(http.StatusNotFound) + }) + repo, err := NewHTTPEmailMessageMapRepository(srv.URL, "fixture-token") + if err != nil { + t.Fatal(err) + } + const concurrent, rounds = 32, 3 + for range rounds { + var wg sync.WaitGroup + for range concurrent { + wg.Add(1) + go func() { + defer wg.Done() + if _, err := repo.Get(context.Background(), uuid.New(), uuid.New(), ""); err != nil { + t.Error(err) + } + }() + } + wg.Wait() + } + if got := opened.Load(); got > concurrent { + t.Fatalf("%d rounds of %d concurrent calls opened %d connections, want at most %d", rounds, concurrent, got, concurrent) + } +} + +func TestControlPlaneClientDrainsUnreadBodies(t *testing.T) { + srv, opened := countingServer(t, func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte(`{"error":"temporarily unavailable"}`)) + }) + repo, err := NewHTTPEmailMessageMapRepository(srv.URL, "fixture-token") + if err != nil { + t.Fatal(err) + } + for range 10 { + if _, err := repo.Get(context.Background(), uuid.New(), uuid.New(), ""); err == nil { + t.Fatal("want an error for a 500") + } + } + if got := opened.Load(); got != 1 { + t.Fatalf("10 sequential calls with unread error bodies opened %d connections, want 1", got) + } +} diff --git a/internal/repository/http_email_message_map.go b/internal/repository/http_email_message_map.go index 63a6b9e37..b57d59df5 100644 --- a/internal/repository/http_email_message_map.go +++ b/internal/repository/http_email_message_map.go @@ -45,7 +45,7 @@ func NewHTTPEmailMessageMapRepository(baseURL, token string) (EmailMessageMapRep return &httpEmailMessageMapRepository{ baseURL: strings.TrimRight(baseURL, "/"), token: token, - client: &http.Client{Timeout: 10 * time.Second}, + client: newControlPlaneClient(10 * time.Second), }, nil } diff --git a/internal/repository/http_sync_context.go b/internal/repository/http_sync_context.go index 5e7d6a735..fb401ee2d 100644 --- a/internal/repository/http_sync_context.go +++ b/internal/repository/http_sync_context.go @@ -109,7 +109,7 @@ func NewHTTPSyncContextRepository(baseURL, token string) (SyncContextRepository, return &httpSyncContextRepository{ baseURL: strings.TrimRight(baseURL, "/"), token: token, - client: &http.Client{Timeout: 10 * time.Second}, + client: newControlPlaneClient(10 * time.Second), }, nil } From 8b0778535079bfe1d52a8cb59af6666239e7fd01 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Fri, 30 Oct 2026 12:44:48 +0100 Subject: [PATCH 011/318] feat: bound worker control-plane response cleanup to 100ms while retaining pooled connection reuse --- internal/repository/http_control_plane.go | 13 ++++++++++-- .../repository/http_control_plane_test.go | 20 +++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/internal/repository/http_control_plane.go b/internal/repository/http_control_plane.go index 01facbaa1..d17011d71 100644 --- a/internal/repository/http_control_plane.go +++ b/internal/repository/http_control_plane.go @@ -1,6 +1,7 @@ package repository import ( + "context" "io" "net/http" "time" @@ -30,18 +31,26 @@ type drainingTransport struct { } func (t drainingTransport) RoundTrip(req *http.Request) (*http.Response, error) { - resp, err := t.next.RoundTrip(req) + ctx, cancel := context.WithCancel(req.Context()) + resp, err := t.next.RoundTrip(req.Clone(ctx)) if resp != nil && resp.Body != nil { - resp.Body = drainingBody{resp.Body} + resp.Body = drainingBody{ReadCloser: resp.Body, cancel: cancel} + } else { + cancel() } return resp, err } type drainingBody struct { io.ReadCloser + cancel context.CancelFunc } func (b drainingBody) Close() error { + // Cancel a stalled read without spending the request's remaining timeout. + timer := time.AfterFunc(100*time.Millisecond, b.cancel) + defer timer.Stop() + defer b.cancel() _, _ = io.Copy(io.Discard, io.LimitReader(b.ReadCloser, 64<<10)) return b.ReadCloser.Close() } diff --git a/internal/repository/http_control_plane_test.go b/internal/repository/http_control_plane_test.go index 7bf91d0dc..4c704f16c 100644 --- a/internal/repository/http_control_plane_test.go +++ b/internal/repository/http_control_plane_test.go @@ -76,3 +76,23 @@ func TestControlPlaneClientDrainsUnreadBodies(t *testing.T) { t.Fatalf("10 sequential calls with unread error bodies opened %d connections, want 1", got) } } + +func TestControlPlaneClientBoundsStalledBodyDrain(t *testing.T) { + srv, _ := countingServer(t, func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + w.(http.Flusher).Flush() + <-r.Context().Done() + }) + repo, err := NewHTTPEmailMessageMapRepository(srv.URL, "fixture-token") + if err != nil { + t.Fatal(err) + } + repo.(*httpEmailMessageMapRepository).client.Timeout = time.Second + started := time.Now() + if _, err := repo.Get(context.Background(), uuid.New(), uuid.New(), ""); err == nil { + t.Fatal("want an error for a 500") + } + if elapsed := time.Since(started); elapsed > 500*time.Millisecond { + t.Fatalf("stalled error body delayed return for %s, want less than 500ms", elapsed) + } +} From 835282fb16b1f377304d3c3fffaaa29440dfd17f Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Fri, 30 Oct 2026 13:35:32 +0100 Subject: [PATCH 012/318] feat: keep provider notices unchanged and narrow Unibox changes to pending agent drafts --- docs/content/docs/guides/inbox-agent.mdx | 2 +- docs/content/docs/guides/unibox.mdx | 2 - internal/app/consumer/event_new_email.go | 4 - internal/app/consumer/event_new_email_test.go | 37 --- .../000331_unibox_system_notices.down.sql | 2 - .../000331_unibox_system_notices.up.sql | 40 --- internal/pkg/systemmail/systemmail.go | 43 --- internal/pkg/systemmail/systemmail_test.go | 54 ---- internal/repository/pg_inbox_tag.go | 2 - internal/repository/pg_unibox.go | 55 +--- internal/repository/pg_unibox_warmup.go | 3 - .../repository/unibox_automated_live_test.go | 2 +- .../unibox_system_notice_live_test.go | 305 ------------------ .../app/unibox/ConversationList.tsx | 41 +-- .../unibox/conversationListDrafts.test.tsx | 74 ++++- 15 files changed, 101 insertions(+), 565 deletions(-) delete mode 100644 internal/infrastructure/db/migrations/000331_unibox_system_notices.down.sql delete mode 100644 internal/infrastructure/db/migrations/000331_unibox_system_notices.up.sql delete mode 100644 internal/pkg/systemmail/systemmail.go delete mode 100644 internal/pkg/systemmail/systemmail_test.go delete mode 100644 internal/repository/unibox_system_notice_live_test.go diff --git a/docs/content/docs/guides/inbox-agent.mdx b/docs/content/docs/guides/inbox-agent.mdx index 04b28c96d..9a6ee55b8 100644 --- a/docs/content/docs/guides/inbox-agent.mdx +++ b/docs/content/docs/guides/inbox-agent.mdx @@ -28,7 +28,7 @@ The agent does not start new conversations and never messages a new recipient. I ## Reviewing a draft -A new draft shows up two ways: +A new draft appears in three places: - In the conversation itself: open the thread in the unibox and the draft appears below the messages, in an editable box, with **Approve and send**, and **Discard**. - In the scope rail: the **Agent drafts** filter lists every conversation with a draft waiting, with a live count next to it. The count and list update the moment a new draft lands, no refresh needed. diff --git a/docs/content/docs/guides/unibox.mdx b/docs/content/docs/guides/unibox.mdx index f98d0c99e..f8f7a6f86 100644 --- a/docs/content/docs/guides/unibox.mdx +++ b/docs/content/docs/guides/unibox.mdx @@ -127,8 +127,6 @@ Each message starts in the folder the provider has it in: IMAP special-use folde Spam and Trash stay out of every other view, and so does Archive: filing a conversation is how you take it out of the way, so it leaves Unread, Awaiting reply, every mailbox, label and tag view, and the unread badge. **All mail** and the **Archive** folder are the two places it stays, which is where you go to find it again. -Account notices a mailbox receives from its own provider never reach the inbox. Connecting a mailbox signs in to it, so Google and Microsoft send it security alerts, 2-Step Verification notices, welcome tips and service notices. Mail from `no-reply@accounts.google.com`, `mail-noreply@google.com`, `workspace-noreply@google.com`, `account-security-noreply@accountprotection.microsoft.com`, `msonlineservicesteam@microsoftonline.com` and `no-reply@microsoft.com` is filed straight into **Archive**, marked read, and left out of All mail, every other view and every count except the Archive folder's own. It never counts as a reply, never starts a webhook, Slack post or agent draft, and it is never deleted: the **Archive** folder and a search in All mail still find it. The match is on the sender's exact address, so a display name or a lookalike domain is ordinary mail. Moving a notice into **Inbox** yourself turns it back into ordinary mail. - The initial import that runs when a mailbox is first connected covers Inbox, Sent, Archive, and Drafts. It deliberately skips the existing contents of Spam and Trash, whose history would consume the import budget that belongs to real conversations. Both folders fill normally from the moment the mailbox is connected, so they show what arrives from then on rather than what was already there. diff --git a/internal/app/consumer/event_new_email.go b/internal/app/consumer/event_new_email.go index feb5a7c2b..97731d648 100644 --- a/internal/app/consumer/event_new_email.go +++ b/internal/app/consumer/event_new_email.go @@ -126,10 +126,6 @@ func (s *JobsService) ingestNewEmail(ctx context.Context, e *models.JobEventNewE CaptureError(e.UserID, e.Message.EmailID, err) return err } - // A provider's notice about the mailbox itself is stored archived and read; it is nobody's reply, so nothing below runs. - if repository.IsSystemNotice(e.Message) { - return nil - } if e.Message != nil { finish = arrivaldiag.Begin(ctx, arrivaldiag.Realtime) inbox := s.emailInboxEvent(ctx, e.UserID, e.Message) diff --git a/internal/app/consumer/event_new_email_test.go b/internal/app/consumer/event_new_email_test.go index 801c8ae78..e0c63fe9a 100644 --- a/internal/app/consumer/event_new_email_test.go +++ b/internal/app/consumer/event_new_email_test.go @@ -74,40 +74,3 @@ func TestHandleNewEmailDoesNotProcessSentMailAsReply(t *testing.T) { }) } } - -func TestHandleNewEmailRunsNothingForProviderNotices(t *testing.T) { - for _, tc := range []struct { - name, from string - wantCalls int - }{ - {name: "google security alert", from: "Google "}, - {name: "microsoft sign-in alert", from: "Microsoft account team "}, - {name: "display name spoof", from: "Google ", wantCalls: 1}, - {name: "lookalike domain", from: "no-reply@accounts.google.com.evil.io", wantCalls: 1}, - } { - t.Run(tc.name, func(t *testing.T) { - advancedService := &replyRecordingAdvanced{} - service := &JobsService{ - UniboxRepository: newEmailInboxRepo{}, - EmailRepository: newEmailAccountRepo{}, - AdvancedService: advancedService, - } - err := service.HandleNewEmail(context.Background(), &models.JobEventNewEmail{ - UserID: uuid.New(), - Message: &models.EmailMessageStoreData{ - ID: uuid.New(), EmailID: uuid.New(), Folder: models.FolderInbox, - FromAddr: []string{tc.from}, - ToAddr: []string{"recipient@example.test"}, - MessageID: "", - Subject: "Security alert", - }, - }) - if err != nil { - t.Fatal(err) - } - if advancedService.calls != tc.wantCalls { - t.Fatalf("ProcessIncomingReply calls = %d, want %d", advancedService.calls, tc.wantCalls) - } - }) - } -} diff --git a/internal/infrastructure/db/migrations/000331_unibox_system_notices.down.sql b/internal/infrastructure/db/migrations/000331_unibox_system_notices.down.sql deleted file mode 100644 index c0e72c875..000000000 --- a/internal/infrastructure/db/migrations/000331_unibox_system_notices.down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- Archived rows stay archived: which a person filed is not recorded; Archive and search still list them. -ALTER TABLE unibox_emails DROP COLUMN IF EXISTS system_notice; diff --git a/internal/infrastructure/db/migrations/000331_unibox_system_notices.up.sql b/internal/infrastructure/db/migrations/000331_unibox_system_notices.up.sql deleted file mode 100644 index efb9962fd..000000000 --- a/internal/infrastructure/db/migrations/000331_unibox_system_notices.up.sql +++ /dev/null @@ -1,40 +0,0 @@ --- Provider notices to a mailbox about itself (sign-in alerts, 2-Step Verification, tips); old releases ignore the column. -ALTER TABLE unibox_emails ADD COLUMN IF NOT EXISTS system_notice boolean NOT NULL DEFAULT false; - --- Backfill every workspace with ingest's treatment; senders mirror internal/pkg/systemmail, re-running changes nothing. -UPDATE unibox_emails ue -SET system_notice = true, - automated = true, - seen = true, - folder = CASE WHEN ue.folder = 'inbox' THEN 'archive' ELSE ue.folder END, - updated_at = NOW() -WHERE ( - public.unibox_participants(ue.from_addr, ue.to_addr, ue.cc) ILIKE '%no-reply@accounts.google.com%' - OR public.unibox_participants(ue.from_addr, ue.to_addr, ue.cc) ILIKE '%mail-noreply@google.com%' - OR public.unibox_participants(ue.from_addr, ue.to_addr, ue.cc) ILIKE '%workspace-noreply@google.com%' - OR public.unibox_participants(ue.from_addr, ue.to_addr, ue.cc) ILIKE '%account-security-noreply@accountprotection.microsoft.com%' - OR public.unibox_participants(ue.from_addr, ue.to_addr, ue.cc) ILIKE '%msonlineservicesteam@microsoftonline.com%' - OR public.unibox_participants(ue.from_addr, ue.to_addr, ue.cc) ILIKE '%no-reply@microsoft.com%' - ) - AND ue.folder NOT IN ('sent', 'drafts') - AND ue.provider_folder NOT IN ('sent', 'drafts') - AND ( - SELECT lower(coalesce( - substring(f.addr from '<([^<>]*)>[^<>]*$'), - substring(f.addr from '^[[:space:]]*([^[:space:]()<>"]+@[^[:space:]()<>"]+)[[:space:]]*\('), - substring(f.addr from '\(([^()]*)\)\s*$'), - btrim(f.addr) - )) - FROM unnest(ue.from_addr) WITH ORDINALITY AS f(addr, n) - WHERE f.addr LIKE '%@%' - ORDER BY f.n - LIMIT 1 - ) IN ( - 'no-reply@accounts.google.com', - 'mail-noreply@google.com', - 'workspace-noreply@google.com', - 'account-security-noreply@accountprotection.microsoft.com', - 'msonlineservicesteam@microsoftonline.com', - 'no-reply@microsoft.com' - ) - AND NOT (ue.system_notice AND ue.automated AND ue.seen AND ue.folder <> 'inbox'); diff --git a/internal/pkg/systemmail/systemmail.go b/internal/pkg/systemmail/systemmail.go deleted file mode 100644 index a39baf1f9..000000000 --- a/internal/pkg/systemmail/systemmail.go +++ /dev/null @@ -1,43 +0,0 @@ -// Package systemmail recognises a provider's notices to a mailbox about itself (sign-in alerts, 2-Step Verification, tips). -package systemmail - -import ( - "slices" - "strings" - - "github.com/warmbly/warmbly/internal/pkg/mailhdr" -) - -// providerNoticeSenders is matched exactly on the parsed address, never a display name or suffix. -// Migration 000331 backfills from a copy of this list; TestMigrationCoversEverySender keeps them in step. -var providerNoticeSenders = map[string]struct{}{ - "no-reply@accounts.google.com": {}, // Google sign-in, security and 2-Step Verification alerts - "mail-noreply@google.com": {}, // Gmail welcome and tips - "workspace-noreply@google.com": {}, // Google Workspace service and legal notices - "account-security-noreply@accountprotection.microsoft.com": {}, // Microsoft account security and sign-in alerts - "msonlineservicesteam@microsoftonline.com": {}, // Microsoft 365 service notices - "no-reply@microsoft.com": {}, // Microsoft account notices -} - -// Senders returns the recognised addresses, sorted. -func Senders() []string { - out := make([]string, 0, len(providerNoticeSenders)) - for addr := range providerNoticeSenders { - out = append(out, addr) - } - slices.Sort(out) - return out -} - -// IsProviderNotice reports whether the first From entry that parses to an address is a provider notice sender. -func IsProviderNotice(from []string) bool { - for _, raw := range from { - addr := strings.ToLower(strings.TrimSpace(mailhdr.Bare(raw))) - if !strings.Contains(addr, "@") { - continue - } - _, ok := providerNoticeSenders[addr] - return ok - } - return false -} diff --git a/internal/pkg/systemmail/systemmail_test.go b/internal/pkg/systemmail/systemmail_test.go deleted file mode 100644 index 2c75b81d3..000000000 --- a/internal/pkg/systemmail/systemmail_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package systemmail - -import ( - "os" - "strings" - "testing" -) - -func TestIsProviderNoticeMatchesTheParsedAddressOnly(t *testing.T) { - for _, tc := range []struct { - name string - from []string - want bool - }{ - {"google security alert", []string{"Google "}, true}, - {"gmail team", []string{"Gmail Team "}, true}, - {"workspace team", []string{`"The Google Workspace Team" `}, true}, - {"bare and uppercase", []string{"NO-REPLY@ACCOUNTS.GOOGLE.COM"}, true}, - {"legacy parenthesised form", []string{"Google (no-reply@accounts.google.com)"}, true}, - {"microsoft account security", []string{"Microsoft account team "}, true}, - {"microsoft 365", []string{"Microsoft Online Services Team "}, true}, - {"microsoft no-reply", []string{"Microsoft "}, true}, - {"empty first entry skipped", []string{"", "Google "}, true}, - {"lookalike domain", []string{"Google "}, false}, - {"lookalike prefix", []string{"Google "}, false}, - {"display name spoof", []string{"Google "}, false}, - {"address quoted in display name", []string{`"no-reply@accounts.google.com" `}, false}, - {"other google sender", []string{"Google Calendar "}, false}, - {"only first sender counts", []string{"them@example.com", "Google "}, false}, - {"no sender", nil, false}, - } { - t.Run(tc.name, func(t *testing.T) { - if got := IsProviderNotice(tc.from); got != tc.want { - t.Fatalf("IsProviderNotice(%q) = %v, want %v", tc.from, got, tc.want) - } - }) - } -} - -func TestMigrationCoversEverySender(t *testing.T) { - raw, err := os.ReadFile("../../infrastructure/db/migrations/000331_unibox_system_notices.up.sql") - if err != nil { - t.Fatal(err) - } - sql := string(raw) - for _, addr := range Senders() { - if !strings.Contains(sql, "'%"+addr+"%'") || !strings.Contains(sql, "'"+addr+"'") { - t.Errorf("migration 000331 does not backfill %s", addr) - } - } - if got := strings.Count(sql, "ILIKE '%"); got != len(Senders()) { - t.Errorf("migration prefilters %d senders, the list has %d", got, len(Senders())) - } -} diff --git a/internal/repository/pg_inbox_tag.go b/internal/repository/pg_inbox_tag.go index ba24b1814..10631a007 100644 --- a/internal/repository/pg_inbox_tag.go +++ b/internal/repository/pg_inbox_tag.go @@ -168,7 +168,6 @@ func (r *inboxTagRepository) Save(ctx context.Context, res *InboxTagResult) erro WHERE ue.email_id = saved.email_account_id AND ue.message_id = saved.message_id AND ue.automated IS DISTINCT FROM saved.automated - AND NOT ue.system_notice ` answers := res.Answers if len(answers) == 0 { @@ -420,7 +419,6 @@ func (r *inboxTagRepository) Reopen(ctx context.Context, orgID uuid.UUID, messag WHERE ue.email_id = dropped.email_account_id AND ue.message_id = dropped.message_id AND ue.automated - AND NOT ue.system_notice ) SELECT labels FROM dropped `, orgID, messageID, kind).Scan(&labels) diff --git a/internal/repository/pg_unibox.go b/internal/repository/pg_unibox.go index 8f48a7f96..96113964f 100644 --- a/internal/repository/pg_unibox.go +++ b/internal/repository/pg_unibox.go @@ -13,7 +13,6 @@ import ( "github.com/jackc/pgx/v5" "github.com/warmbly/warmbly/internal/infrastructure/db" "github.com/warmbly/warmbly/internal/models" - "github.com/warmbly/warmbly/internal/pkg/systemmail" ) type UpdateUniboxEntry struct { @@ -259,39 +258,27 @@ func (r *uniboxRepository) CreateEntry(ctx context.Context, userID uuid.UUID, e flags, bcc, cc, from_addr, in_reply_to, reply_to, to_addr, subject, size, internal_date, sent_date, snippet, seen, created_at, updated_at, body_text, folder, - provider_folder, automated, filed_forward, system_notice + provider_folder, automated, filed_forward ) VALUES ( $1, $2, $3, $4, $5, COALESCE((SELECT thread_id FROM fwd), $6), $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, - $29, + $28, -- A row re-created by a sync keeps the verdict its message already has. - $30 OR EXISTS ( + EXISTS ( SELECT 1 FROM inbox_tag_results r WHERE r.organization_id = (SELECT organization_id FROM email_accounts WHERE id = $3) AND r.message_id = $7 AND $7 <> '' AND r.automated ), - EXISTS (SELECT 1 FROM fwd), - $30 + EXISTS (SELECT 1 FROM fwd) ) ON CONFLICT (id) DO NOTHING RETURNING thread_id ` - // A message starts where the provider put it; a system notice is filed to Archive, read, while provider_folder keeps the provider's placement for sync. - providerFolder := models.NormalizeFolder(e.Folder, e.Flags) - folder, seen := providerFolder, e.Seen - notice := IsSystemNotice(e) - if notice { - seen = true - if folder == models.FolderInbox { - folder = models.FolderArchive - } - } - // The array columns are NOT NULL. A nil Go slice binds as SQL NULL, so a // message with no In-Reply-To (any thread root) would fail the insert. var threadID string @@ -301,8 +288,10 @@ func (r *uniboxRepository) CreateEntry(ctx context.Context, userID uuid.UUID, e textArray(e.Flags), textArray(e.BCC), textArray(e.CC), textArray(e.FromAddr), textArray(e.InReplyTo), textArray(e.ReplyTo), textArray(e.ToAddr), e.Subject, e.Size, e.InternalDate, e.SentDate, - e.Snippet, seen, e.CreatedAt, e.UpdatedAt, e.BodyText, - folder, providerFolder, notice, + e.Snippet, e.Seen, e.CreatedAt, e.UpdatedAt, e.BodyText, + // $28 is both columns: a message starts out where the provider put it, + // and only diverges once someone files it in Warmbly. + models.NormalizeFolder(e.Folder, e.Flags), ).Scan(&threadID) if errors.Is(err, pgx.ErrNoRows) { // Already stored: the conflict leaves the row as it was. @@ -315,11 +304,6 @@ func (r *uniboxRepository) CreateEntry(ctx context.Context, userID uuid.UUID, e return nil } -// IsSystemNotice reports whether an arriving message is inbound mail from a provider notice sender (systemmail). -func IsSystemNotice(e *models.EmailMessageStoreData) bool { - return e.MayBeInbound() && systemmail.IsProviderNotice(e.FromAddr) -} - // FiledSentForward is a stored copy FileSentForward moved, with its mailbox owner. type FiledSentForward struct { UserID uuid.UUID @@ -761,14 +745,6 @@ func uniboxSearchQuery(orgID uuid.UUID, params *models.MailSearchParams) (string inner += ` AND ue.folder NOT IN ` + foldersOutsideWorkingViews } - // System notices never show in Inbox, searched or not; outside a folder only a search finds them. - searching := (params.Subject != nil && *params.Subject != "") || - (params.Sender != nil && *params.Sender != "") || - (params.Address != nil && *params.Address != "") - if (params.Folder != nil && *params.Folder == models.FolderInbox) || (params.Folder == nil && !searching) { - inner += ` AND NOT ue.system_notice` - } - // Snooze handling. nil = exclude snoozed (the inbox default), so // threads with an active snooze never appear unless asked for. switch { @@ -1005,7 +981,6 @@ func (r *uniboxRepository) GetUnseenCount(ctx context.Context, orgID uuid.UUID, WHERE ue.email_id IN (SELECT id FROM email_accounts WHERE organization_id = $1) AND ue.seen = FALSE AND ue.folder = '` + models.FolderInbox + `' - AND NOT ue.system_notice AND NOT EXISTS ( SELECT 1 FROM unibox_snoozes s WHERE s.organization_id = $1 AND s.user_id = ue.user_id @@ -1031,7 +1006,6 @@ func (r *uniboxRepository) UnseenCountForMailboxes(ctx context.Context, orgID uu AND ue.email_id = ANY($2::uuid[]) AND ue.seen = FALSE AND ue.folder = '` + models.FolderInbox + `' - AND NOT ue.system_notice AND NOT EXISTS ( SELECT 1 FROM unibox_snoozes s WHERE s.organization_id = $1 AND s.user_id = ue.user_id @@ -1218,7 +1192,7 @@ func (r *uniboxRepository) MoveToFolderBulk(ctx context.Context, orgID uuid.UUID return nil, nil } return r.fileRows(ctx, - `UPDATE unibox_emails u SET folder = $1, updated_at = NOW(),`+fileIntoInboxClearsNotice+` + `UPDATE unibox_emails u SET folder = $1, updated_at = NOW() FROM unibox_emails prev WHERE prev.id = u.id AND u.id = ANY($3) AND u.email_id IN (SELECT id FROM email_accounts WHERE organization_id = $2) @@ -1235,7 +1209,7 @@ func (r *uniboxRepository) MoveThreadsToFolder(ctx context.Context, orgID uuid.U return nil, nil } return r.fileRows(ctx, - `UPDATE unibox_emails u SET folder = $1, updated_at = NOW(),`+fileIntoInboxClearsNotice+` + `UPDATE unibox_emails u SET folder = $1, updated_at = NOW() FROM unibox_emails prev WHERE prev.id = u.id AND COALESCE(NULLIF(u.thread_id, ''), u.id::text) = ANY($3) AND u.email_id IN (SELECT id FROM email_accounts WHERE organization_id = $2) @@ -1244,11 +1218,6 @@ func (r *uniboxRepository) MoveThreadsToFolder(ctx context.Context, orgID uuid.U ) } -// fileIntoInboxClearsNotice is the SET tail of a user's filing: a system notice someone files into Inbox becomes their mail again. -const fileIntoInboxClearsNotice = ` - automated = CASE WHEN u.system_notice AND $1 = 'inbox' THEN false ELSE u.automated END, - system_notice = u.system_notice AND $1 <> 'inbox'` - // fileRows runs a filing UPDATE. Rows already in the folder come back too, // unmoved: the provider may still disagree with them. prev is the row as the // statement found it, which is how the folder it left is read. @@ -1785,7 +1754,6 @@ func (r *uniboxRepository) overview(ctx context.Context, orgID uuid.UUID, accoun FROM unibox_emails e WHERE e.email_id IN `+mailboxes+` AND e.folder NOT IN `+foldersOutsideAllMail+` - AND NOT e.system_notice ), threads AS ( SELECT @@ -1851,8 +1819,6 @@ func (r *uniboxRepository) overview(ctx context.Context, orgID uuid.UUID, accoun AND s.snoozed_until > NOW() ) AND NOT (e.folder = 'inbox' AND `+automatedThreadSQL("e.thread_id", "e.automated", "$1")+`) - -- Archive lists its notices, so only Inbox leaves them out of its count. - AND NOT (e.folder = 'inbox' AND e.system_notice) GROUP BY e.folder `, orgID) if err != nil { @@ -1895,7 +1861,6 @@ func (r *uniboxRepository) overview(ctx context.Context, orgID uuid.UUID, accoun FROM email_accounts ea LEFT JOIN unibox_emails ue ON ue.email_id = ea.id AND ue.user_id = ea.user_id AND ue.folder NOT IN `+foldersOutsideWorkingViews+` - AND NOT ue.system_notice AND NOT `+automatedThreadSQL("ue.thread_id", "ue.automated", "$1")+` WHERE ea.organization_id = $1`+onlyMailboxes("ea.id")+` GROUP BY ea.id, ea.email, ea.name diff --git a/internal/repository/pg_unibox_warmup.go b/internal/repository/pg_unibox_warmup.go index 8c20f77c6..b5b76afb3 100644 --- a/internal/repository/pg_unibox_warmup.go +++ b/internal/repository/pg_unibox_warmup.go @@ -164,7 +164,6 @@ func (r *uniboxRepository) ListUnprocessedCampaignReplies(ctx context.Context, s scan, err := r.db.Query(ctx, `SELECT u.id FROM unibox_emails u WHERE u.id > $1 AND u.created_at >= $2 AND u.campaign_reply_processed_at IS NULL AND u.folder NOT IN ('sent', 'drafts') AND u.provider_folder NOT IN ('sent', 'drafts') - AND NOT u.system_notice ORDER BY u.id LIMIT $3`, afterID, since, scanSize) if err != nil { return page, err @@ -198,8 +197,6 @@ func (r *uniboxRepository) ListUnprocessedCampaignReplies(ctx context.Context, s AND u.campaign_reply_processed_at IS NULL AND u.folder NOT IN ('sent', 'drafts') AND u.provider_folder NOT IN ('sent', 'drafts') - -- A provider notice is nobody's reply; ingest never stamps it, so repair must skip it too. - AND NOT u.system_notice AND ( -- Both forms of each header against the raw column, so idx_tasks_message_id serves it. EXISTS ( diff --git a/internal/repository/unibox_automated_live_test.go b/internal/repository/unibox_automated_live_test.go index 75d0117b1..af643d3a6 100644 --- a/internal/repository/unibox_automated_live_test.go +++ b/internal/repository/unibox_automated_live_test.go @@ -45,7 +45,7 @@ func TestLiveUniboxAutomatedLeavesTheInbox(t *testing.T) { ours := f.mailboxAddress(t, repo) now := time.Now().UTC() - alert := f.scopedMessage(t, repo, "thread-alert", "Acme Billing ", models.FolderInbox, now) + alert := f.scopedMessage(t, repo, "thread-alert", "Google ", models.FolderInbox, now) f.judge(t, handle.Pool, alert, "thread-alert", true) f.scopedMessage(t, repo, "thread-person", "them@example.com", models.FolderInbox, now) diff --git a/internal/repository/unibox_system_notice_live_test.go b/internal/repository/unibox_system_notice_live_test.go deleted file mode 100644 index c86fd886e..000000000 --- a/internal/repository/unibox_system_notice_live_test.go +++ /dev/null @@ -1,305 +0,0 @@ -package repository - -import ( - "context" - "net/url" - "os" - "testing" - "time" - - "github.com/google/uuid" - "github.com/jackc/pgx/v5" - - "github.com/warmbly/warmbly/internal/infrastructure/db" - "github.com/warmbly/warmbly/internal/models" -) - -// Provider notices to a mailbox about itself land archived, read and out of every working view and counter: -// -// WARMBLY_TEST_DB=postgres://warmbly@127.0.0.1:15432/warmbly_dev?sslmode=disable \ -// go test ./internal/repository/ -run LiveUniboxSystemNotice -v - -// liveFreshUniboxDB is a freshly migrated database of its own, so the backfill can run against it. -func liveFreshUniboxDB(t *testing.T) *db.DB { - t.Helper() - dsn := os.Getenv("WARMBLY_TEST_DB") - if dsn == "" { - t.Skip("WARMBLY_TEST_DB not set") - } - u, err := url.Parse(dsn) - if err != nil || (u.Hostname() != "localhost" && u.Hostname() != "127.0.0.1") { - t.Fatal("system notice fixture requires local PostgreSQL") - } - admin, err := pgx.Connect(t.Context(), dsn) - if err != nil { - t.Fatal(err) - } - name := "system_notice_" + uuid.New().String()[:8] - quoted := pgx.Identifier{name}.Sanitize() - if _, err := admin.Exec(t.Context(), "CREATE DATABASE "+quoted); err != nil { - _ = admin.Close(context.Background()) - t.Fatal(err) - } - u.Path = "/" + name - if err := db.RunMigrations(u.String()); err != nil { - t.Fatal(err) - } - handle, err := db.New(t.Context(), u.String()) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { - handle.Pool.Close() - if _, err := admin.Exec(context.Background(), "DROP DATABASE "+quoted); err != nil { - t.Error(err) - } - _ = admin.Close(context.Background()) - }) - return handle -} - -type storedPlacement struct { - folder, provider string - seen, automated, systemNotice bool - updatedAt time.Time -} - -func readPlacement(t *testing.T, handle *db.DB, id uuid.UUID) storedPlacement { - t.Helper() - var p storedPlacement - err := handle.Pool.QueryRow(context.Background(), ` - SELECT folder, provider_folder, seen, automated, system_notice, updated_at - FROM unibox_emails WHERE id = $1`, id). - Scan(&p.folder, &p.provider, &p.seen, &p.automated, &p.systemNotice, &p.updatedAt) - if err != nil { - t.Fatalf("read %s: %v", id, err) - } - return p -} - -func TestLiveUniboxSystemNoticeLandsArchivedAndOutOfEveryView(t *testing.T) { - handle := liveFreshUniboxDB(t) - f := newUniboxFolderFixture(t, handle.Pool) - repo := NewUniboxRepository(handle) - ctx := context.Background() - now := time.Now().UTC() - - alert := f.scopedMessage(t, repo, "thread-alert", "Google ", models.FolderInbox, now) - ms := f.scopedMessage(t, repo, "thread-ms", "Microsoft account team ", models.FolderInbox, now) - spoof := f.scopedMessage(t, repo, "thread-spoof", "Google ", models.FolderInbox, now) - f.scopedMessage(t, repo, "thread-person", "them@example.com", models.FolderInbox, now) - - for _, id := range []uuid.UUID{alert, ms} { - p := readPlacement(t, handle, id) - if p.folder != models.FolderArchive || p.provider != models.FolderInbox || !p.seen || !p.automated || !p.systemNotice { - t.Fatalf("notice stored as %+v, want archived, provider inbox, seen, automated, system_notice", p) - } - } - if p := readPlacement(t, handle, spoof); p.folder != models.FolderInbox || p.seen || p.systemNotice { - t.Fatalf("display-name spoof stored as %+v, want an unread inbox message", p) - } - - // The provider still reports the notice in its inbox; sync must not read that as a move back. - if folder, _, moved := models.ResolveFolderSync(models.FolderArchive, models.FolderInbox, models.FolderInbox); moved || folder != models.FolderArchive { - t.Fatalf("sync moved the notice to %q", folder) - } - - search := func(p models.MailSearchParams) *models.MailSearchResult { - t.Helper() - p.PageSize = 50 - res, err := repo.Search(ctx, f.org, &p) - if err != nil { - t.Fatalf("Search: %v", err) - } - return res - } - no, yes := false, true - inbox, archive := models.FolderInbox, models.FolderArchive - hidden := func(label string, res *models.MailSearchResult) { - t.Helper() - if listsThread(res, "thread-alert") || listsThread(res, "thread-ms") { - t.Fatalf("%s = %v, want no system notice", label, threadIDs(res)) - } - } - hidden("inbox", search(models.MailSearchParams{Folder: &inbox, Automated: &no})) - hidden("all mail", search(models.MailSearchParams{IncludeArchived: &yes})) - hidden("unread", search(models.MailSearchParams{Unseen: &yes, Automated: &no})) - hidden("automated", search(models.MailSearchParams{Automated: &yes})) - hidden("awaiting reply", search(models.MailSearchParams{AwaitingReply: &yes})) - if got := search(models.MailSearchParams{IncludeArchived: &yes}); !listsThread(got, "thread-spoof") || !listsThread(got, "thread-person") { - t.Fatalf("all mail = %v, want the spoof and the person", threadIDs(got)) - } - if got := search(models.MailSearchParams{Folder: &archive}); !listsThread(got, "thread-alert") || !listsThread(got, "thread-ms") { - t.Fatalf("archive = %v, want both notices", threadIDs(got)) - } - query := "Scope" - if got := search(models.MailSearchParams{IncludeArchived: &yes, Subject: &query}); !listsThread(got, "thread-alert") { - t.Fatalf("all mail search = %v, want the notice findable", threadIDs(got)) - } - hidden("inbox search", search(models.MailSearchParams{Folder: &inbox, Subject: &query})) - - ov, err := repo.Overview(ctx, f.org) - if err != nil { - t.Fatalf("Overview: %v", err) - } - if ov.Total != 2 || ov.Unread != 2 || ov.Automated != 0 { - t.Fatalf("overview total=%d unread=%d automated=%d, want 2, 2, 0", ov.Total, ov.Unread, ov.Automated) - } - for _, fo := range ov.Folders { - if fo.Folder == models.FolderArchive && (fo.Total != 2 || fo.Unread != 0) { - t.Fatalf("archive folder total=%d unread=%d, want the 2 read notices it lists", fo.Total, fo.Unread) - } - if fo.Folder == models.FolderInbox && fo.Total != 2 { - t.Fatalf("inbox folder total = %d, want 2", fo.Total) - } - } - if n, err := repo.GetUnseenCount(ctx, f.org, nil); err != nil || n != 2 { - t.Fatalf("unread badge = %d (%v), want 2", n, err) - } - - // A later classifier verdict never turns a notice back into a person's mail. - err = NewInboxTagRepository(handle.Pool).Save(ctx, &InboxTagResult{ - OrganizationID: f.org, EmailAccountID: f.mailbox, - MessageID: "<" + alert.String() + "@test.local>", ThreadID: "thread-alert", - Kind: "human_reply", KindConfidence: 0.9, KindSource: "model", Priority: "whenever", - }) - if err != nil { - t.Fatalf("Save verdict: %v", err) - } - if p := readPlacement(t, handle, alert); !p.automated { - t.Fatal("a human verdict cleared automated on a system notice") - } -} - -func TestLiveUniboxSystemNoticeBackfillIsIdempotent(t *testing.T) { - handle := liveFreshUniboxDB(t) - f := newUniboxFolderFixture(t, handle.Pool) - repo := NewUniboxRepository(handle) - ctx := context.Background() - now := time.Now().UTC() - - // Rows stored before the rule: written as ordinary mail, then given the sender they arrived with. - legacy := func(thread, from, folder string) uuid.UUID { - t.Helper() - id := f.scopedMessage(t, repo, thread, "them@example.com", folder, now) - if _, err := handle.Pool.Exec(ctx, `UPDATE unibox_emails SET from_addr = $2 WHERE id = $1`, id, []string{from}); err != nil { - t.Fatal(err) - } - return id - } - google := legacy("t-google", "Google ", models.FolderInbox) - gmail := legacy("t-gmail", "Gmail Team ", models.FolderInbox) - spam := legacy("t-spam", "Microsoft ", models.FolderSpam) - lookalike := legacy("t-look", "Google ", models.FolderInbox) - spoof := legacy("t-spoof", "Google ", models.FolderInbox) - cc := legacy("t-cc", "them@example.com", models.FolderInbox) - if _, err := handle.Pool.Exec(ctx, `UPDATE unibox_emails SET cc = ARRAY['no-reply@accounts.google.com'] WHERE id = $1`, cc); err != nil { - t.Fatal(err) - } - - up, err := os.ReadFile("../infrastructure/db/migrations/000331_unibox_system_notices.up.sql") - if err != nil { - t.Fatal(err) - } - if _, err := handle.Pool.Exec(ctx, string(up)); err != nil { - t.Fatalf("backfill: %v", err) - } - - for _, id := range []uuid.UUID{google, gmail} { - if p := readPlacement(t, handle, id); p.folder != models.FolderArchive || p.provider != models.FolderInbox || !p.seen || !p.automated || !p.systemNotice { - t.Fatalf("backfilled notice = %+v, want archived, seen, automated, system_notice", p) - } - } - if p := readPlacement(t, handle, spam); p.folder != models.FolderSpam || !p.systemNotice || !p.seen { - t.Fatalf("notice in spam = %+v, want left in spam, marked", p) - } - for _, id := range []uuid.UUID{lookalike, spoof, cc} { - if p := readPlacement(t, handle, id); p.folder != models.FolderInbox || p.seen || p.systemNotice { - t.Fatalf("non-notice touched: %+v", p) - } - } - - before := readPlacement(t, handle, google) - tag, err := handle.Pool.Exec(ctx, string(up)) - if err != nil { - t.Fatalf("backfill rerun: %v", err) - } - if tag.RowsAffected() != 0 { - t.Fatalf("rerun updated %d rows, want 0", tag.RowsAffected()) - } - if after := readPlacement(t, handle, google); !after.updatedAt.Equal(before.updatedAt) { - t.Fatal("rerun touched an already treated row") - } -} - -func TestLiveUniboxSystemNoticeFiledIntoInboxBecomesMail(t *testing.T) { - handle := liveFreshUniboxDB(t) - f := newUniboxFolderFixture(t, handle.Pool) - repo := NewUniboxRepository(handle) - ctx := context.Background() - now := time.Now().UTC() - - alert := f.scopedMessage(t, repo, "thread-alert", "Google ", models.FolderInbox, now) - other := f.scopedMessage(t, repo, "thread-other", "Gmail Team ", models.FolderInbox, now) - - // Filing elsewhere keeps the notice a notice. - if _, err := repo.MoveThreadsToFolder(ctx, f.org, []string{"thread-other"}, models.FolderTrash); err != nil { - t.Fatalf("MoveThreadsToFolder trash: %v", err) - } - if p := readPlacement(t, handle, other); p.folder != models.FolderTrash || !p.systemNotice || !p.automated { - t.Fatalf("notice filed to trash = %+v, want still a system notice", p) - } - - if _, err := repo.MoveThreadsToFolder(ctx, f.org, []string{"thread-alert"}, models.FolderInbox); err != nil { - t.Fatalf("MoveThreadsToFolder inbox: %v", err) - } - if p := readPlacement(t, handle, alert); p.folder != models.FolderInbox || p.systemNotice || p.automated { - t.Fatalf("notice filed into inbox = %+v, want ordinary inbox mail", p) - } - no, inbox := false, models.FolderInbox - res, err := repo.Search(ctx, f.org, &models.MailSearchParams{Folder: &inbox, Automated: &no, PageSize: 50}) - if err != nil { - t.Fatalf("Search: %v", err) - } - if !listsThread(res, "thread-alert") { - t.Fatalf("inbox = %v, want the notice the user filed there", threadIDs(res)) - } - - if _, err := repo.MoveToFolderBulk(ctx, f.org, []uuid.UUID{other}, models.FolderInbox); err != nil { - t.Fatalf("MoveToFolderBulk inbox: %v", err) - } - if p := readPlacement(t, handle, other); p.folder != models.FolderInbox || p.systemNotice { - t.Fatalf("notice moved into inbox by id = %+v, want ordinary inbox mail", p) - } -} - -// The daily reply repair never hands a provider notice to reply detection, even from a contact's address. -func TestLiveUniboxSystemNoticeSkippedByReplyRepair(t *testing.T) { - handle := liveFreshUniboxDB(t) - f := newUniboxFolderFixture(t, handle.Pool) - repo := NewUniboxRepository(handle) - ctx := context.Background() - now := time.Now().UTC() - - for _, addr := range []string{"no-reply@accounts.google.com", "lead@example.com"} { - // contacts.created_at has no time zone: NOW() keeps it in the session's, as the server writes it. - if _, err := handle.Pool.Exec(ctx, `INSERT INTO contacts (id, user_id, organization_id, first_name, last_name, email, company, phone, custom_fields, created_at) - VALUES ($1, $2, $3, '', '', $4, '', '', '{}'::jsonb, NOW() - interval '1 hour')`, uuid.New(), f.user, f.org, addr); err != nil { - t.Fatal(err) - } - } - notice := f.scopedMessage(t, repo, "thread-alert", "Google ", models.FolderInbox, now) - reply := f.scopedMessage(t, repo, "thread-lead", "Lead ", models.FolderInbox, now) - - page, err := repo.ListUnprocessedCampaignReplies(ctx, now.Add(-time.Hour), uuid.Nil, 100) - if err != nil { - t.Fatalf("ListUnprocessedCampaignReplies: %v", err) - } - var got []uuid.UUID - for _, ev := range page.Events { - got = append(got, ev.Message.ID) - } - if len(got) != 1 || got[0] != reply { - t.Fatalf("repair listed %v, want only the lead reply %s (notice %s skipped)", got, reply, notice) - } -} diff --git a/web/src/components/app/unibox/ConversationList.tsx b/web/src/components/app/unibox/ConversationList.tsx index 167675f1c..4a9d32e00 100644 --- a/web/src/components/app/unibox/ConversationList.tsx +++ b/web/src/components/app/unibox/ConversationList.tsx @@ -132,16 +132,6 @@ export function ConversationList({ [merged], ); const agent = useUniboxSearch(agentParams, `${scopeKey}:agent`, draftsFolder); - // Pending agent drafts are few, so every page loads up front: one past the first must not drop off the list. - const { - hasNextPage: agentHasMore, - isFetchingNextPage: agentLoadingMore, - isFetchNextPageError: agentMoreFailed, - fetchNextPage: fetchMoreAgent, - } = agent; - React.useEffect(() => { - if (draftsFolder && agentHasMore && !agentLoadingMore && !agentMoreFailed) void fetchMoreAgent(); - }, [draftsFolder, agentHasMore, agentLoadingMore, agentMoreFailed, fetchMoreAgent]); const agentRows = draftsFolder ? agent.emails : NO_ROWS; const agentKeys = React.useMemo( () => new Set(agentRows.map((r) => r.thread_id || r.id)), @@ -240,9 +230,13 @@ export function ConversationList({ // a bar along the top and the stale rows dimmed. Background refetches from // realtime events do not qualify, so nothing flickers while reading. The // bar waits 150ms so a fast response never shows it at all. - const stale = q.isPlaceholderData && q.isFetching; + const stale = (q.isPlaceholderData && q.isFetching) || + (draftsFolder && agent.isPlaceholderData && agent.isFetching); const showProgress = useDelayed(stale, 150); - const firstLoad = (q.isPending || q.isPlaceholderData) && emails.length === 0; + const firstLoad = (q.isPending || q.isPlaceholderData || + (draftsFolder && (agent.isPending || agent.isPlaceholderData))) && emails.length === 0; + const failedQuery = q.isError && !q.isFetchNextPageError ? q : + draftsFolder && agent.isError && !agent.isFetchNextPageError ? agent : undefined; // Where this exact list was left. Opening a thread keeps the page mounted // (see the route's stableParams in main.tsx), so this covers what that @@ -257,13 +251,16 @@ export function ConversationList({ // data is on screen, which lags the request key for as long as the previous // rows are standing in, so the swap remounts rather than animates. const shownKey = React.useRef(listKey); - if (!q.isPlaceholderData) shownKey.current = listKey; + if (!q.isPlaceholderData && (!draftsFolder || !agent.isPlaceholderData)) shownKey.current = listKey; // Infinite scroll: reaching the end of the list loads the next page instead // of asking for a click. The button below stays as the manual fallback, and // isFetchingNextPage is a dependency so a page landing re-arms the observer: // a sentinel still on screen keeps pulling instead of stalling one page in. - const { hasNextPage, isFetchingNextPage, isFetchNextPageError, fetchNextPage } = q; + // Page agent drafts first, using the same bounded scroll and retry behavior as mailbox drafts. + const nextQuery = draftsFolder && agent.hasNextPage ? agent : q; + const { isFetchingNextPage, isFetchNextPageError, fetchNextPage } = nextQuery; + const hasNextPage = q.hasNextPage || (draftsFolder && agent.hasNextPage); React.useEffect(() => { const root = listRef.current; // A page that failed stays failed until the user asks again; re-arming on @@ -569,17 +566,17 @@ export function ConversationList({ > {firstLoad ? ( - ) : q.isError && emails.length === 0 ? ( + ) : failedQuery && emails.length === 0 ? (

Couldn't load inbox

- {q.error?.message ?? "Request failed"} + {failedQuery.error?.message ?? "Request failed"}

) : ( + {failedQuery && ( +
+ Some conversations couldn't load.{" "} + +
+ )} {items.map((item) => item.kind === "header" ? ( @@ -652,7 +657,7 @@ export function ConversationList({ ones can still animate out when an action empties the list. It waits for them before it appears. */} - {emails.length === 0 && !hasNextPage && ( + {emails.length === 0 && !hasNextPage && !failedQuery && ( ({ calls: [] as { params: UniboxSearchParams; enabled: boolean }[], agentHasMore: false, agentNextPage: [] as string[], + agentPending: false, + agentFailed: false, + agentRefetches: 0, + mailboxEmpty: false, })); function row(id: string, thread: string, subject: string) { @@ -34,14 +38,15 @@ vi.mock("@/lib/api/hooks/app/unibox/useUniboxSearch", () => ({ const emails = !enabled ? [] : params.agentDrafts - ? [row("a1", "t-agent", "Agent reply to a lead"), row("a2", "t-both", "Agent reply on a drafted thread")] - : [row("d1", "t-mine", "My own draft"), row("d2", "t-both", "Provider copy of a drafted thread")]; + ? search.agentPending || search.agentFailed ? [] : [row("a1", "t-agent", "Agent reply to a lead"), row("a2", "t-both", "Agent reply on a drafted thread")] + : search.mailboxEmpty ? [] : [row("d1", "t-mine", "My own draft"), row("d2", "t-both", "Provider copy of a drafted thread")]; return { emails, - isPending: false, + isPending: !!params.agentDrafts && search.agentPending, isFetching: false, isPlaceholderData: false, - isError: false, + isError: !!params.agentDrafts && search.agentFailed, + error: search.agentFailed ? new Error("Draft request failed") : null, hasNextPage: enabled && !!params.agentDrafts && search.agentHasMore, isFetchingNextPage: false, isFetchNextPageError: false, @@ -49,7 +54,10 @@ vi.mock("@/lib/api/hooks/app/unibox/useUniboxSearch", () => ({ search.agentNextPage.push(params.agentDrafts ? "agent" : "mailbox"); return Promise.resolve(); }, - refetch: () => Promise.resolve(), + refetch: () => { + if (params.agentDrafts) search.agentRefetches++; + return Promise.resolve(); + }, }; }, })); @@ -81,6 +89,10 @@ afterEach(() => { search.calls = []; search.agentHasMore = false; search.agentNextPage = []; + search.agentPending = false; + search.agentFailed = false; + search.agentRefetches = 0; + search.mailboxEmpty = false; }); function mount(params: UniboxSearchParams, scopeKey: string) { @@ -119,14 +131,60 @@ it("leaves every other folder alone", () => { expect(screen.getAllByTestId("row")).toHaveLength(2); }); -it("loads every page of pending agent drafts, not just the first", () => { +it("pages pending agent drafts through Load more without eagerly fetching every page", () => { search.agentHasMore = true; mount({ sortBy: "newest", folder: "drafts" }, "folder:drafts"); - expect(search.agentNextPage).toContain("agent"); + expect(search.agentNextPage).toEqual([]); + fireEvent.click(screen.getByRole("button", { name: "Load more" })); + expect(search.agentNextPage).toEqual(["agent"]); expect(search.agentNextPage).not.toContain("mailbox"); }); +it("does not claim Drafts is empty while agent drafts are still loading", () => { + search.agentPending = true; + search.mailboxEmpty = true; + const { container } = mount({ sortBy: "newest", folder: "drafts" }, "folder:drafts"); + + expect(container.querySelector(".animate-pulse")).toBeTruthy(); + expect(screen.queryByText(/No conversations/)).toBeNull(); +}); + +it("offers a retry when agent drafts fail while keeping mailbox drafts visible", () => { + search.agentFailed = true; + mount({ sortBy: "newest", folder: "drafts" }, "folder:drafts"); + + expect(screen.getByRole("alert").textContent).toContain("couldn't load"); + expect(screen.getByText("My own draft")).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "Try again" })); + expect(search.agentRefetches).toBe(1); +}); + +it("shows a retry instead of an empty folder when the agent request fails", () => { + search.agentFailed = true; + search.mailboxEmpty = true; + mount({ sortBy: "newest", folder: "drafts" }, "folder:drafts"); + + expect(screen.getByText("Couldn't load inbox")).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "Try again" })); + expect(search.agentRefetches).toBe(1); +}); + +it("preserves mailbox, category and search filters for agent drafts", () => { + mount({ sortBy: "newest", folder: "drafts", accountIds: ["mailbox"], categoryIds: ["category"], query: "proposal" }, "folder:drafts"); + + expect(search.calls.find((c) => c.params.agentDrafts)?.params).toMatchObject({ + accountIds: ["mailbox"], categoryIds: ["category"], query: "proposal", + }); +}); + +it("keeps an explicitly empty mailbox scope empty", () => { + mount({ sortBy: "newest", folder: "drafts", accountIds: [] }, "folder:drafts"); + + expect(search.calls.every((c) => !c.enabled)).toBe(true); + expect(screen.queryAllByTestId("row")).toHaveLength(0); +}); + it("never pages agent drafts outside the Drafts folder", () => { search.agentHasMore = true; mount({ sortBy: "newest", folder: "inbox", automated: false }, "folder:inbox"); From af9e58782e2fb27aa281072734b7501ec5c639bd Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Fri, 30 Oct 2026 13:45:16 +0100 Subject: [PATCH 013/318] feat: record pending agent replies alongside mailbox drafts in the Unibox proof harness --- qa/README.md | 7 +++++++ qa/fixtures/unibox-drafts.sql | 28 ++++++++++++++++++++++++++++ qa/flows/unibox-drafts.flow.ts | 23 +++++++++++++++++++++++ 3 files changed, 58 insertions(+) create mode 100644 qa/fixtures/unibox-drafts.sql create mode 100644 qa/flows/unibox-drafts.flow.ts diff --git a/qa/README.md b/qa/README.md index 6550f9550..89babbd57 100644 --- a/qa/README.md +++ b/qa/README.md @@ -142,6 +142,13 @@ Recording against a stack the harness did not start is possible but explicit: whatever happens to answer on the default ports, which is usually another session's stack. +## Unibox Drafts proof fixtures + +Apply `fixtures/unibox-drafts.sql` to this worktree's isolated rich-seed database, +then run `QA_UNIBOX_DRAFTS_FIXTURES=1 pnpm proof unibox-drafts`. The fixture adds +one inert pending agent reply and places one synthetic mailbox message in Drafts. +The walkthrough opens the agent reply for review without sending it. + ## Fleet admin proof fixtures `flows/fleet-telemetry.flow.ts` is opt-in: apply `fixtures/fleet-telemetry.sql` diff --git a/qa/fixtures/unibox-drafts.sql b/qa/fixtures/unibox-drafts.sql new file mode 100644 index 000000000..5b6de505e --- /dev/null +++ b/qa/fixtures/unibox-drafts.sql @@ -0,0 +1,28 @@ +-- Apply only to this worktree's isolated rich-seed database. +BEGIN; + +UPDATE users SET product_tour_completed_at = now() +WHERE id = '11111111-0000-0000-0000-000000000001' + AND product_tour_completed_at IS NULL; + +UPDATE unibox_emails +SET folder = 'drafts', subject = 'Partnership follow-up draft' +WHERE user_id = '11111111-0000-0000-0000-000000000001' + AND message_id = ''; + +INSERT INTO ai_thread_drafts ( + id, organization_id, email_account_id, owner_user_id, thread_id, + source_message_id, to_addr, subject, in_reply_to, body, status +) +SELECT '10870000-0000-0000-0000-000000000001', a.organization_id, + e.email_id, e.user_id, e.thread_id, e.id, + 'mira.kovacs@lumina-labs.test', e.subject, e.message_id, + 'Hi Mira, we can hold that price through the end of the month. Happy to walk through the report with your COO.', + 'pending' +FROM unibox_emails e +JOIN email_accounts a ON a.id = e.email_id +WHERE e.user_id = '11111111-0000-0000-0000-000000000001' + AND e.message_id = '' +ON CONFLICT (id) DO UPDATE SET status = 'pending', body = EXCLUDED.body; + +COMMIT; diff --git a/qa/flows/unibox-drafts.flow.ts b/qa/flows/unibox-drafts.flow.ts new file mode 100644 index 000000000..d8de22676 --- /dev/null +++ b/qa/flows/unibox-drafts.flow.ts @@ -0,0 +1,23 @@ +import { expect, test } from "../lib/proof.ts"; + +test.skip(process.env.QA_UNIBOX_DRAFTS_FIXTURES !== "1", "Apply qa/fixtures/unibox-drafts.sql to this stack's rich-seed database and set QA_UNIBOX_DRAFTS_FIXTURES=1."); + +test("review an agent reply alongside mailbox drafts", async ({ page, proof }) => { + await page.goto("/app/unibox"); + await page.getByRole("button", { name: /^Drafts(?: \d+)?$/ }).click(); + await expect(page.getByRole("heading", { name: "Drafts", exact: true })).toBeVisible(); + const agent = page.getByRole("button", { name: /Mira Kovacs.*Quick question about outbound at Lumina Labs/ }); + const mailbox = page.getByRole("button", { name: /Partnership follow-up draft/ }); + await expect(agent).toBeVisible(); + await expect(mailbox).toBeVisible(); + await expect(page.getByText("Agent drafts", { exact: true }).last()).toBeVisible(); + await proof.chapter("Drafts", "Pending agent replies appear first, above drafts saved in the mailbox"); + await proof.shot("drafts-list", { caption: "Agent replies and mailbox drafts in one folder" }); + + await agent.click(); + await expect(page.getByText("AI reply draft", { exact: true })).toBeVisible(); + await expect(page.getByRole("button", { name: "Approve & send" })).toBeVisible(); + await expect(page.getByRole("button", { name: "Discard", exact: true })).toBeVisible(); + await proof.dwell(); + await proof.shot("draft-review", { caption: "Opening an agent draft keeps the existing edit, approve and discard controls" }); +}); From ca73a1845997f5577e1bf10bb9acf1b0daad209a Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Fri, 30 Oct 2026 14:01:41 +0100 Subject: [PATCH 014/318] feat: run all PostgreSQL live tests in isolated advisory CI with failure and skip summaries --- .github/scripts/live-tests-summary.mjs | 62 ++++++++++++++++++ .github/scripts/live-tests-summary.test.mjs | 38 ++++++++++++ .github/workflows/ci.yml | 69 +++++++++++++++++++++ 3 files changed, 169 insertions(+) create mode 100644 .github/scripts/live-tests-summary.mjs create mode 100644 .github/scripts/live-tests-summary.test.mjs diff --git a/.github/scripts/live-tests-summary.mjs b/.github/scripts/live-tests-summary.mjs new file mode 100644 index 000000000..91b7cb4ce --- /dev/null +++ b/.github/scripts/live-tests-summary.mjs @@ -0,0 +1,62 @@ +import { appendFileSync, existsSync, readFileSync } from "node:fs"; +import { pathToFileURL } from "node:url"; + +export function summarizeLiveTests(input, outcome) { + const tests = new Map(); + const failedPackages = new Set(); + for (const line of input.split("\n")) { + let event; + try { + event = JSON.parse(line); + } catch { + continue; // Compiler diagnostics can be plain text alongside go test JSON. + } + if (!event || typeof event !== "object") continue; + if (event.Action === "fail" && typeof event.Package === "string" && !event.Test) { + failedPackages.add(event.Package); + } + if (typeof event.Test !== "string" || !event.Test.startsWith("TestLive") || event.Test.includes("/")) continue; + if (!["pass", "fail", "skip"].includes(event.Action)) continue; + tests.set(`${event.Package}/${event.Test}`, event.Action); + } + const names = (action) => [...tests].filter(([, result]) => result === action).map(([name]) => name).sort(); + const passed = names("pass"); + const failed = names("fail"); + const skipped = names("skip"); + const list = (heading, entries) => [ + `### ${heading}`, + "", + ...(entries.length ? entries.slice(0, 200).map((name) => `- \`${name.replaceAll("`", "\\`")}\``) : ["None recorded."]), + ...(entries.length > 200 ? ["", "Showing the first 200 entries; see the complete output artifact."] : []), + "", + ]; + return { + needsAttention: outcome !== "success" || tests.size === 0 || failed.length > 0 || skipped.length > 0 || failedPackages.size > 0, + markdown: [ + "## PostgreSQL catch-all (advisory)", + "", + `Test step outcome: **${outcome || "not started"}**. This job is outside the required CI Status aggregate while #1078 is triaged.`, + "", + "| Top-level TestLive results | Count |", + "| --- | ---: |", + `| Passed | ${passed.length} |`, + `| Failed | ${failed.length} |`, + `| Skipped | ${skipped.length} |`, + "", + ...(tests.size === 0 ? ["No completed TestLive results were recorded. Check setup, compilation and timeouts.", ""] : []), + ...list("Failed packages (including setup or build failures)", [...failedPackages].sort()), + ...list("Failed tests", failed), + ...list("Skipped tests", skipped), + "Full JSON events and compiler output are retained in the postgres-live-advisory artifact. Subtests are included there; counts above include each top-level test once.", + "", + ].join("\n"), + }; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const file = process.argv[2]; + const report = summarizeLiveTests(file && existsSync(file) ? readFileSync(file, "utf8") : "", process.env.LIVE_TEST_OUTCOME); + if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, report.markdown); + else process.stdout.write(report.markdown); + if (report.needsAttention) console.log("::warning::Advisory PostgreSQL coverage needs triage. See the job summary and complete output artifact."); +} diff --git a/.github/scripts/live-tests-summary.test.mjs b/.github/scripts/live-tests-summary.test.mjs new file mode 100644 index 000000000..e9cea53d9 --- /dev/null +++ b/.github/scripts/live-tests-summary.test.mjs @@ -0,0 +1,38 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { summarizeLiveTests } from "./live-tests-summary.mjs"; + +const events = (...rows) => rows.map((row) => JSON.stringify(row)).join("\n"); + +test("reports failures, skips and failed packages without counting subtests twice", () => { + const report = summarizeLiveTests(events( + { Action: "pass", Package: "app", Test: "TestLivePassed/child" }, + { Action: "pass", Package: "app", Test: "TestLivePassed" }, + { Action: "fail", Package: "repository", Test: "TestLiveFailed/child" }, + { Action: "fail", Package: "repository", Test: "TestLiveFailed" }, + { Action: "fail", Package: "repository" }, + { Action: "skip", Package: "app", Test: "TestLiveSkipped" }, + { Action: "pass", Package: "app", Test: "TestOther" }, + ), "failure"); + assert.equal(report.needsAttention, true); + assert.match(report.markdown, /\| Passed \| 1 \|/); + assert.match(report.markdown, /\| Failed \| 1 \|/); + assert.match(report.markdown, /\| Skipped \| 1 \|/); + assert.match(report.markdown, /`repository\/TestLiveFailed`/); + assert.match(report.markdown, /`app\/TestLiveSkipped`/); + assert.doesNotMatch(report.markdown, /\/child/); +}); + +test("empty, interrupted and compile-only output cannot look like passing coverage", () => { + for (const input of ["", "# app\ncompiler error", 'null\n{"Action":"fail","Package":"app"}']) { + const report = summarizeLiveTests(input, "failure"); + assert.equal(report.needsAttention, true); + assert.match(report.markdown, /No completed TestLive results/); + } + assert.equal(summarizeLiveTests(events({ Action: "pass", Package: "app", Test: "TestLiveOK" }), "cancelled").needsAttention, true); +}); + +test("successful coverage is clean only when completed tests contain no skips", () => { + assert.equal(summarizeLiveTests(events({ Action: "pass", Package: "app", Test: "TestLiveOK" }), "success").needsAttention, false); + assert.equal(summarizeLiveTests(events({ Action: "skip", Package: "app", Test: "TestLiveSkipped" }), "success").needsAttention, true); +}); diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d49ec3d31..2a6af9bdc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -49,6 +49,7 @@ jobs: filters: | go-services: - '.github/workflows/ci.yml' + - '.github/scripts/live-tests-summary*.mjs' - 'go.mod' - 'go.sum' - 'internal/**' @@ -212,6 +213,10 @@ jobs: if: matrix.suite == 'lint' run: make lint + - name: Check live-test reporting + if: matrix.suite == 'lint' + run: node --test .github/scripts/live-tests-summary.test.mjs + - name: Verify protobuf files are up to date if: matrix.suite == 'lint' run: make check-proto @@ -644,6 +649,70 @@ jobs: flags: go fail_ci_if_error: false + # Keep advisory coverage separate until #1078's failure inventory is resolved. + go-live-advisory: + name: PostgreSQL catch-all (advisory) + needs: changes + if: needs.changes.outputs.go-services == 'true' + runs-on: ubuntu-latest + timeout-minutes: 45 + continue-on-error: true + services: + postgres: + image: postgres:16 + env: + POSTGRES_USER: warmbly + POSTGRES_PASSWORD: warmbly + POSTGRES_DB: warmbly_test + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U warmbly -d warmbly_test" + --health-interval 10s + --health-timeout 5s + --health-retries 5 + redis: + image: redis:7-alpine + ports: + - 6379:6379 + options: >- + --health-cmd "redis-cli ping" + --health-interval 10s + --health-timeout 5s + --health-retries 5 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version-file: go.mod + cache: true + - name: Prepare isolated regression database + env: + PRIMARY_DB: postgres://warmbly:warmbly@127.0.0.1:5432/warmbly_test?sslmode=disable + run: go run ./cmd/migrate + - name: Run every TestLive test + id: live + timeout-minutes: 35 + env: + WARMBLY_TEST_DB: postgres://warmbly:warmbly@127.0.0.1:5432/warmbly_test?sslmode=disable + WARMBLY_TEST_REDIS: redis://127.0.0.1:6379/15 + run: | + set -o pipefail + go test -json -race -p 1 -timeout 10m -count=1 -run '^TestLive' ./... 2>&1 | tee live-tests.jsonl + - name: Summarize advisory results + if: always() + env: + LIVE_TEST_OUTCOME: ${{ steps.live.outcome }} + run: node .github/scripts/live-tests-summary.mjs live-tests.jsonl + - name: Retain complete live-test output + if: always() + uses: actions/upload-artifact@v4 + with: + name: postgres-live-advisory-${{ github.run_attempt }} + path: live-tests.jsonl + if-no-files-found: warn + retention-days: 14 + web-ci: name: Web CI needs: changes From 9beeeadc8ca011d8b398dce03a664bc796ba3d8f Mon Sep 17 00:00:00 2001 From: 555aaditya <107977627+555aaditya@users.noreply.github.com> Date: Fri, 30 Oct 2026 18:44:27 +0530 Subject: [PATCH 015/318] feat: keep German, French and Spanish interest phrases out of the positive path when a negating word appears anywhere earlier in the sentence, and drop the infinitive scheduling phrases termin vereinbaren, fixer un rendez-vous, agendar and programar una llamada that read the same inside a refusal --- docs/content/docs/guides/inbox-tagging.mdx | 2 +- internal/app/replyclassify/languages.go | 40 ++++++------------- .../replyclassify/sentiment_languages_test.go | 32 +++++++-------- 3 files changed, 30 insertions(+), 44 deletions(-) diff --git a/docs/content/docs/guides/inbox-tagging.mdx b/docs/content/docs/guides/inbox-tagging.mdx index cfcffe4c3..fb6c9133a 100644 --- a/docs/content/docs/guides/inbox-tagging.mdx +++ b/docs/content/docs/guides/inbox-tagging.mdx @@ -234,7 +234,7 @@ The reading before any call covers: - **Out-of-office replies**, recognized by the subject their mail provider writes (`ะะฒั‚ะพะผะฐั‚ะธั‡ะตัะบะธะน ะพั‚ะฒะตั‚`, `่‡ชๅ‹•ๅฟœ็ญ”`, `์ž๋™ ํšŒ์‹ `, `ุฑุฏ ุชู„ู‚ุงุฆูŠ` and so on) and decided with no call at all. - **Non-delivery notices**, by the subject Exchange writes in Spanish, Italian, Dutch and Portuguese. A notice carrying a delivery-status report is recognized in any language without this. - **Replies that say no**, in German, French, Spanish, Dutch, Italian and Portuguese: a declined interest ("kein Interesse", "pas intรฉressรฉ", "no me interesa", "geen interesse", "non sono interessato", "nรฃo tenho interesse") or another clear no ("nein danke", "non merci", "no gracias", "nee bedankt", "no grazie", "nรฃo, obrigado", "falscher Ansprechpartner", "persona sbagliata"). Each phrase is matched as whole words, so "no grazie" never matches inside "buono, grazie". The reply classifier reads these as negative with no call, the same verdict "not interested" and "no thanks" get in English, so they take the `reply_negative` branch. Inbox labels still come from the classifier. -- **Replies that show interest**, in German, French and Spanish ("klingt gut", "lassen Sie uns telefonieren", "รงa m'intรฉresse", "je suis intรฉressรฉ", "me interesa mucho", "agendemos una llamada"), read as positive with no call, the same verdict "interested" and "let's talk" get in English, so they take the `reply_positive` branch and count as interested leads. A reply that also says no in one of these languages ("klingt gut, aber kein Bedarf") stays negative, and a phrase straight after "no", "nicht", "pas" and the like ("no me interesa mucho") does not count. +- **Replies that show interest**, in German, French and Spanish ("klingt gut", "lassen Sie uns telefonieren", "รงa m'intรฉresse", "je suis intรฉressรฉ", "me interesa mucho", "agendemos una llamada"), read as positive with no call, the same verdict "interested" and "let's talk" get in English, so they take the `reply_positive` branch and count as interested leads. A reply that also says no in one of these languages ("klingt gut, aber kein Bedarf") stays negative, and a phrase in a sentence that already says "no", "nicht", "pas" and the like ("no me interesa mucho", "je ne crois pas, honnรชtement, que cela nous intรฉresse") does not count. Tagging languages are part of the workspace settings, so they travel with a [workspace export](/guides/workspace-export-import/). diff --git a/internal/app/replyclassify/languages.go b/internal/app/replyclassify/languages.go index 02932ad6c..16074755e 100644 --- a/internal/app/replyclassify/languages.go +++ b/internal/app/replyclassify/languages.go @@ -36,7 +36,7 @@ type langRules struct { // negative is any other clear no. Both are phrases, never single words. declined, negative []string // positive is clear interest. A chosen language's is read after its no - // phrases, and never shortly after a negating word. positiveAsWritten + // phrases, and never in a sentence with a negating word before it. positiveAsWritten // keeps its accents, where folding would change the meaning. positive, positiveAsWritten []string } @@ -146,7 +146,7 @@ var languageRules = map[string]langRules{ }, positive: []string{ "klingt gut", "klingt interessant", "klingt spannend", "ich bin interessiert", "wir sind interessiert", - "lassen sie uns telefonieren", "lass uns telefonieren", "kรถnnen wir telefonieren", "termin vereinbaren", + "lassen sie uns telefonieren", "lass uns telefonieren", "kรถnnen wir telefonieren", "gerne mehr erfahren", "schicken sie mir mehr informationen", "was kostet das", }, }, @@ -167,7 +167,7 @@ var languageRules = map[string]langRules{ positive: []string{ "je suis intรฉressรฉ", "je suis intรฉressรฉe", "nous sommes intรฉressรฉs", "nous sommes intรฉressรฉes", "รงa m'intรฉresse", "cela m'intรฉresse", "รงa nous intรฉresse", "cela nous intรฉresse", - "รงa a l'air intรฉressant", "cela semble intรฉressant", "prenons rendez-vous", "fixer un rendez-vous", + "รงa a l'air intรฉressant", "cela semble intรฉressant", "prenons rendez-vous", "envoyez-moi plus d'informations", "envoyez-moi une offre", "envoyez-moi un devis", "quel est le tarif", "quels sont vos tarifs", }, @@ -187,8 +187,8 @@ var languageRules = map[string]langRules{ }, positive: []string{ "me interesa mucho", "nos interesa mucho", "estoy muy interesado", - "estoy muy interesada", "estamos muy interesados", "agendemos una llamada", "agendar una llamada", - "programar una llamada", "envรญeme mรกs informaciรณn", "envรญame mรกs informaciรณn", "cuรกnto cuesta", + "estoy muy interesada", "estamos muy interesados", "agendemos una llamada", + "envรญeme mรกs informaciรณn", "envรญame mรกs informaciรณn", "cuรกnto cuesta", "cuรกl es el precio", }, // "Si me interesa, les aviso" is conditional; only the accented "sรญ" says yes. @@ -464,43 +464,29 @@ type ruleSet struct { type phrase struct { text string bounded bool - // negatable phrases do not count after a negating word in the same clause ("no me interesa mucho"). + // negatable phrases do not count after a negating word in the same sentence ("no me interesa mucho"). negatable bool // asWritten phrases keep their accents, because folding them changes the meaning ("sรญ" is not "si"). asWritten bool } -// negators are the words that, shortly before an interest phrase, turn it around. +// negators are the words that, earlier in the sentence, turn an interest phrase around. var negators = map[string]bool{ "no": true, "not": true, "nicht": true, "kein": true, "keine": true, "keinen": true, "nie": true, "pas": true, "ne": true, "non": true, "niet": true, "geen": true, "nao": true, "nunca": true, "jamas": true, } -// negationWindow is how many words back a negator still reaches ("no quiero agendar una llamada"). -const negationWindow = 3 - -// negatedAt reports a negator within negationWindow words before start. Words are -// separated by any whitespace; punctuation ends the clause, and the search with it. +// negatedAt reports a negator earlier in the sentence that holds start. Commas and +// line breaks do not end it ("je ne crois pas, honnรชtement, que cela nous intรฉresse"). func negatedAt(text string, start int) bool { head := text[:start] - for range negationWindow { - head = strings.TrimRightFunc(head, unicode.IsSpace) - end := len(head) - for end > 0 { - r, size := utf8.DecodeLastRuneInString(head[:end]) - if !unicode.IsLetter(r) { - break - } - end -= size - } - word := head[end:] - if word == "" { - return false - } + if i := strings.LastIndexAny(head, ".!?;"); i >= 0 { + head = head[i+1:] + } + for _, word := range strings.FieldsFunc(head, func(r rune) bool { return !unicode.IsLetter(r) }) { if negators[word] { return true } - head = head[:end] } return false } diff --git a/internal/app/replyclassify/sentiment_languages_test.go b/internal/app/replyclassify/sentiment_languages_test.go index 0eebe1d98..01eaddda2 100644 --- a/internal/app/replyclassify/sentiment_languages_test.go +++ b/internal/app/replyclassify/sentiment_languages_test.go @@ -248,6 +248,10 @@ func TestNegatedAndHedgedInterestIsNotPositive(t *testing.T) { "No\nme interesa mucho.", "No quiero agendar una llamada.", "Wir wollen nicht gleich einen Termin vereinbaren.", + "Ich glaube nicht, dass wir einen Termin vereinbaren sollten.", + "No me parece buena idea programar una llamada.", + "No sรฉ todavรญa si nos interesa mucho.", + "Je ne crois pas, honnรชtement, que cela nous intรฉresse.", } { if got := ClassifyOffline(Input{Subject: "Re: Hallo", BodyText: body, Languages: all}); got.Class == ClassPositive { t.Errorf("%q read as positive", body) @@ -255,24 +259,20 @@ func TestNegatedAndHedgedInterestIsNotPositive(t *testing.T) { } } -// A negating word straight before the phrase turns it around; anything else between does not. -func TestNegatedAtReadsTheWordBefore(t *testing.T) { +// A negating word anywhere earlier in the sentence turns the phrase around. +func TestNegatedAtReadsTheSentence(t *testing.T) { for text, want := range map[string]bool{ - "no me interesa mucho": true, - "nicht klingt gut": true, - "no, me interesa mucho": false, - "bueno me interesa mucho": false, - "me interesa mucho": false, - "pero no me interesa mucho": true, - "no\nme interesa mucho": true, - "no quiero me interesa mucho": true, - "no a b c me interesa mucho": false, + "no me interesa mucho": true, + "no, me interesa mucho": true, + "pero no me interesa mucho": true, + "no\nme interesa mucho": true, + "no a b c me interesa mucho": true, + "bueno me interesa mucho": false, + "me interesa mucho": false, + "no. me interesa mucho": false, + "por que no? me interesa mucho": false, } { - start := len(text) - len("me interesa mucho") - if text == "nicht klingt gut" { - start = len("nicht ") - } - if got := negatedAt(text, start); got != want { + if got := negatedAt(text, len(text)-len("me interesa mucho")); got != want { t.Errorf("negatedAt(%q) = %v, want %v", text, got, want) } } From c385eca2b34d764a1504cb3f27c7348a926643e5 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Fri, 30 Oct 2026 14:16:16 +0100 Subject: [PATCH 016/318] feat: count distinct Unibox draft conversations and preserve mailbox paging after agent failures --- .github/workflows/ci.yml | 2 +- docs/content/docs/api/endpoints.mdx | 1 + docs/content/docs/guides/unibox.mdx | 2 +- internal/models/unibox.go | 4 +- internal/repository/pg_unibox.go | 10 ++- internal/repository/unibox_scope_live_test.go | 68 +++++++++++++++++++ .../app/unibox/ConversationList.tsx | 11 ++- web/src/components/app/unibox/ScopeRail.tsx | 2 +- .../unibox/conversationListDrafts.test.tsx | 20 +++++- .../components/app/unibox/scopeRail.test.tsx | 16 ++++- .../api/models/app/unibox/UniboxOverview.ts | 2 + 11 files changed, 129 insertions(+), 9 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d49ec3d31..25f032415 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -621,7 +621,7 @@ jobs: if: matrix.suite == 'live-1' env: WARMBLY_TEST_DB: postgres://warmbly:warmbly@127.0.0.1:5432/warmbly_test?sslmode=disable - run: go test -race -v -p 1 ./internal/repository ./internal/infrastructure/db -run '^TestLiveUnibox(Search|ReadStream|SearchUpgrade|GetBySender)' -count=1 + run: go test -race -v -p 1 ./internal/repository ./internal/infrastructure/db -run '^TestLiveUnibox(Search|ReadStream|SearchUpgrade|GetBySender|ScopeDraftsCount)' -count=1 - name: Notification digest authorization retries (Redis) if: matrix.suite == 'live-3' diff --git a/docs/content/docs/api/endpoints.mdx b/docs/content/docs/api/endpoints.mdx index 1a72d7370..4b99cf369 100644 --- a/docs/content/docs/api/endpoints.mdx +++ b/docs/content/docs/api/endpoints.mdx @@ -21,6 +21,7 @@ All paths below are relative to the versioned base URL `https://api.warmbly.com/ - `GET /analytics/dashboard` intersects campaign and folder filters with grants before returning `scope.campaign_count`. - `GET /campaigns/:id/logs` keeps pagination and campaign activity, but restricted responses use safe messages and explicitly selected metadata. Mailbox addresses, caps, cross-campaign sending state, warmup health and account IDs outside mailbox grants are removed. Tracking domains, raw provider errors, unknown fields and nested metadata are not exposed. Granting a campaign alone does not grant its senders. - `GET /auth/me` and `/unibox/overview` include only categories applied to messages in accessible mailboxes for restricted members. Unrestricted members keep the workspace category registry. Inbox access is mailbox-based: granting a shared mailbox exposes its conversations from other campaigns too. +- `GET /unibox/overview` includes `drafts`, the distinct conversation count across mailbox drafts and visible pending inbox-agent replies, scoped to accessible mailboxes. Older servers omit this field; during rolling upgrades the dashboard uses their mailbox-only Drafts count until it is available. - `GET /unibox/thread/labels` checks for a message in the selected organization and effective mailbox allowlist before listing labels. Unknown, cross-workspace and inaccessible threads have the same `404`. An accessible thread with no labels returns an empty list. - `GET /emails` resolves a pagination cursor only inside the selected organization and effective mailbox allowlist. A cursor outside either boundary does not supply a timestamp for pagination. diff --git a/docs/content/docs/guides/unibox.mdx b/docs/content/docs/guides/unibox.mdx index f8f7a6f86..d0bcd70a0 100644 --- a/docs/content/docs/guides/unibox.mdx +++ b/docs/content/docs/guides/unibox.mdx @@ -113,7 +113,7 @@ The rail is two short groups and then your mailboxes. The first group is where y | Folder | Group | Shows | | --- | --- | --- | | Inbox | First | Inbound mail, plus anything filed in a custom folder at the provider, unless that folder is [excluded from sync](/guides/mailboxes/#folders-you-do-not-want-synced) | -| Drafts | Second | Conversations with an [inbox agent](/guides/inbox-agent/) reply waiting for review, listed first under **Agent drafts**, then messages sitting in a mailbox's drafts folder. The count includes both | +| Drafts | Second | Conversations with an [inbox agent](/guides/inbox-agent/) reply waiting for review, listed first under **Agent drafts**, then messages sitting in a mailbox's drafts folder. The count includes both, counting a conversation once if it has both kinds of draft | | Sent | Second | Outbound mail, campaign and manual | | Archive | Second | Archived (Gmail's All Mail, the Archive folder elsewhere) | | Spam | Second | Junked at the provider | diff --git a/internal/models/unibox.go b/internal/models/unibox.go index 8c0849a40..126ce069e 100644 --- a/internal/models/unibox.go +++ b/internal/models/unibox.go @@ -501,7 +501,9 @@ type UniboxOverview struct { // AwaitingAgentDraft is the count of threads with a pending inbox-agent draft // waiting for human review (M10). AwaitingAgentDraft int64 `json:"awaiting_agent_draft"` - ScheduledPending int64 `json:"scheduled_pending"` + // Drafts counts each visible thread once across mailbox and pending agent drafts. + Drafts int64 `json:"drafts"` + ScheduledPending int64 `json:"scheduled_pending"` // ScheduledPendingMax is the hard cap on pending scheduled email // tasks per workspace. The dashboard shows current/max so the user // sees how close they are to the limit before hitting it. diff --git a/internal/repository/pg_unibox.go b/internal/repository/pg_unibox.go index 96113964f..f67cb345a 100644 --- a/internal/repository/pg_unibox.go +++ b/internal/repository/pg_unibox.go @@ -1743,6 +1743,11 @@ func (r *uniboxRepository) overview(ctx context.Context, orgID uuid.UUID, accoun e.internal_date, e.seen, e.automated, + e.folder = 'drafts' AS is_draft, + EXISTS ( + SELECT 1 FROM ai_thread_drafts d + WHERE d.organization_id = $1 AND d.thread_id = e.thread_id AND d.status = 'pending' + ) AS has_agent_draft, e.folder IN ('sent', 'drafts') AS is_ours, e.folder = 'archive' AS is_archived, EXISTS ( @@ -1760,6 +1765,7 @@ func (r *uniboxRepository) overview(ctx context.Context, orgID uuid.UUID, accoun tkey, bool_or(is_snoozed) AS is_snoozed, bool_or(NOT is_archived) AS working, + bool_or(is_draft OR (NOT is_archived AND has_agent_draft)) AS has_draft, bool_or(NOT seen) FILTER (WHERE NOT is_archived) AS has_unread, max(internal_date) FILTER (WHERE NOT is_archived) AS last_date, -- The same rule as automatedThreadSQL, over rows already in hand. @@ -1783,7 +1789,8 @@ func (r *uniboxRepository) overview(ctx context.Context, orgID uuid.UUID, accoun COUNT(*) FILTER (WHERE NOT t.is_snoozed AND t.working AND t.is_automated AND t.has_unread) AS automated_unread, (SELECT COUNT(*) FROM latest_per_thread l WHERE `+ownAddressSQL("l.from_addr", "$1")+`) AS awaiting, (SELECT COUNT(*) FROM ai_thread_drafts d - WHERE d.organization_id = $1 AND d.status = 'pending'`+onlyMailboxes("d.email_account_id")+`) AS awaiting_agent_draft + WHERE d.organization_id = $1 AND d.status = 'pending'`+onlyMailboxes("d.email_account_id")+`) AS awaiting_agent_draft, + COUNT(*) FILTER (WHERE NOT t.is_snoozed AND t.has_draft) AS drafts FROM threads t `, orgID, todayStart, weekStart).Scan( &overview.Total, @@ -1795,6 +1802,7 @@ func (r *uniboxRepository) overview(ctx context.Context, orgID uuid.UUID, accoun &overview.AutomatedUnread, &overview.AwaitingReply, &overview.AwaitingAgentDraft, + &overview.Drafts, ) if err != nil { return nil, err diff --git a/internal/repository/unibox_scope_live_test.go b/internal/repository/unibox_scope_live_test.go index 3b47ec54e..afdd76e7b 100644 --- a/internal/repository/unibox_scope_live_test.go +++ b/internal/repository/unibox_scope_live_test.go @@ -54,6 +54,74 @@ func (f *uniboxFolderFixture) mailboxAddress(t *testing.T, repo UniboxRepository return ov.Mailboxes[0].Email } +func TestLiveUniboxScopeDraftsCountMatchesVisibleUnion(t *testing.T) { + handle := liveUniboxFolderDB(t) + f := newUniboxFolderFixture(t, handle.Pool) + other := newUniboxFolderFixture(t, handle.Pool) + repo := NewUniboxRepository(handle) + ctx := t.Context() + now := time.Now().UTC() + for _, tc := range []struct { + thread string + folder string + status string + }{ + {"mailbox-only", models.FolderDrafts, ""}, + {"overlap", models.FolderDrafts, "pending"}, + {"agent-only", models.FolderInbox, "pending"}, + {"archived", models.FolderArchive, "pending"}, + {"trashed", models.FolderTrash, "pending"}, + {"snoozed", models.FolderInbox, "pending"}, + {"resolved", models.FolderInbox, "discarded"}, + } { + f.scopedMessage(t, repo, tc.thread, "them@example.com", tc.folder, now) + if tc.status != "" { + if _, err := handle.Pool.Exec(ctx, `INSERT INTO ai_thread_drafts + (id, organization_id, email_account_id, owner_user_id, thread_id, to_addr, status) + VALUES ($1,$2,$3,$4,$5,'them@example.com',$6)`, uuid.New(), f.org, f.mailbox, f.user, tc.thread, tc.status); err != nil { + t.Fatal(err) + } + } + } + if _, err := repo.UpsertSnoozes(ctx, f.org, f.user, []string{"snoozed"}, now.Add(time.Hour)); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = repo.DeleteSnoozes(context.Background(), f.org, f.user, []string{"snoozed"}) }) + other.scopedMessage(t, repo, "another-workspace", "them@example.com", models.FolderDrafts, now) + + folder, agent := models.FolderDrafts, true + mailboxRows, err := repo.Search(ctx, f.org, &models.MailSearchParams{Folder: &folder, PageSize: 50}) + if err != nil { + t.Fatal(err) + } + agentRows, err := repo.Search(ctx, f.org, &models.MailSearchParams{AgentDraft: &agent, PageSize: 50}) + if err != nil { + t.Fatal(err) + } + visible := make(map[string]bool) + for _, result := range []*models.MailSearchResult{mailboxRows, agentRows} { + for _, thread := range threadIDs(result) { + visible[thread] = true + } + } + if len(visible) != 3 { + t.Fatalf("visible draft threads = %v, want mailbox-only, overlap and agent-only", visible) + } + overview, err := repo.Overview(ctx, f.org) + if err != nil || overview.Drafts != int64(len(visible)) { + t.Fatalf("overview = %+v, error = %v, want %d distinct drafts", overview, err, len(visible)) + } + for _, count := range overview.Folders { + if count.Folder == models.FolderDrafts && count.Total != 2 { + t.Fatalf("legacy mailbox Drafts total changed: %+v", count) + } + } + restricted, err := repo.OverviewForMailboxes(ctx, f.org, []uuid.UUID{other.mailbox}) + if err != nil || restricted.Drafts != 0 { + t.Fatalf("restricted overview = %+v, error = %v, want no drafts", restricted, err) + } +} + func threadIDs(res *models.MailSearchResult) []string { out := make([]string, 0, len(res.Data)) for _, row := range res.Data { diff --git a/web/src/components/app/unibox/ConversationList.tsx b/web/src/components/app/unibox/ConversationList.tsx index 4a9d32e00..b87a7fc29 100644 --- a/web/src/components/app/unibox/ConversationList.tsx +++ b/web/src/components/app/unibox/ConversationList.tsx @@ -258,7 +258,8 @@ export function ConversationList({ // isFetchingNextPage is a dependency so a page landing re-arms the observer: // a sentinel still on screen keeps pulling instead of stalling one page in. // Page agent drafts first, using the same bounded scroll and retry behavior as mailbox drafts. - const nextQuery = draftsFolder && agent.hasNextPage ? agent : q; + const nextQuery = draftsFolder && agent.hasNextPage && + (!agent.isFetchNextPageError || !q.hasNextPage) ? agent : q; const { isFetchingNextPage, isFetchNextPageError, fetchNextPage } = nextQuery; const hasNextPage = q.hasNextPage || (draftsFolder && agent.hasNextPage); React.useEffect(() => { @@ -584,6 +585,14 @@ export function ConversationList({ ) : ( + {draftsFolder && agent.isFetchNextPageError && nextQuery !== agent && ( +
+ Couldn't load more agent drafts.{" "} + +
+ )} {failedQuery && (
Some conversations couldn't load.{" "} diff --git a/web/src/components/app/unibox/ScopeRail.tsx b/web/src/components/app/unibox/ScopeRail.tsx index f70ed6a91..422cd1f1d 100644 --- a/web/src/components/app/unibox/ScopeRail.tsx +++ b/web/src/components/app/unibox/ScopeRail.tsx @@ -276,7 +276,7 @@ export function ScopeRail({ scope, onChange, browseKey = "desktop" }: ScopeRailP const counts = folderCounts.get(folder); // Drafts reads better as a total, pending agent drafts included; everywhere else the number is unread. const agentDrafts = folder === "drafts" ? (data?.awaiting_agent_draft ?? 0) : 0; - const count = folder === "drafts" ? (counts?.total ?? 0) + agentDrafts : counts?.unread; + const count = folder === "drafts" ? (data?.drafts ?? counts?.total) : counts?.unread; return { key: `folder:${folder}`, label, diff --git a/web/src/components/app/unibox/conversationListDrafts.test.tsx b/web/src/components/app/unibox/conversationListDrafts.test.tsx index c0b552305..d8ce2032d 100644 --- a/web/src/components/app/unibox/conversationListDrafts.test.tsx +++ b/web/src/components/app/unibox/conversationListDrafts.test.tsx @@ -9,6 +9,8 @@ import { ConversationList } from "./ConversationList"; const search = vi.hoisted(() => ({ calls: [] as { params: UniboxSearchParams; enabled: boolean }[], agentHasMore: false, + agentPageFailed: false, + mailboxHasMore: false, agentNextPage: [] as string[], agentPending: false, agentFailed: false, @@ -47,9 +49,9 @@ vi.mock("@/lib/api/hooks/app/unibox/useUniboxSearch", () => ({ isPlaceholderData: false, isError: !!params.agentDrafts && search.agentFailed, error: search.agentFailed ? new Error("Draft request failed") : null, - hasNextPage: enabled && !!params.agentDrafts && search.agentHasMore, + hasNextPage: enabled && (params.agentDrafts ? search.agentHasMore : search.mailboxHasMore), isFetchingNextPage: false, - isFetchNextPageError: false, + isFetchNextPageError: !!params.agentDrafts && search.agentPageFailed, fetchNextPage: () => { search.agentNextPage.push(params.agentDrafts ? "agent" : "mailbox"); return Promise.resolve(); @@ -88,6 +90,8 @@ afterEach(() => { cleanup(); search.calls = []; search.agentHasMore = false; + search.agentPageFailed = false; + search.mailboxHasMore = false; search.agentNextPage = []; search.agentPending = false; search.agentFailed = false; @@ -191,3 +195,15 @@ it("never pages agent drafts outside the Drafts folder", () => { expect(search.agentNextPage).toEqual([]); }); + +it("keeps mailbox pagination and a separate agent retry reachable after an agent-page failure", () => { + search.agentHasMore = true; + search.agentPageFailed = true; + search.mailboxHasMore = true; + mount({ sortBy: "newest", folder: "drafts" }, "folder:drafts"); + + fireEvent.click(screen.getByRole("button", { name: "Load more" })); + expect(search.agentNextPage).toEqual(["mailbox"]); + fireEvent.click(screen.getByRole("button", { name: "Retry agent drafts" })); + expect(search.agentNextPage).toEqual(["mailbox", "agent"]); +}); diff --git a/web/src/components/app/unibox/scopeRail.test.tsx b/web/src/components/app/unibox/scopeRail.test.tsx index d2d029e21..ddc0e1b6a 100644 --- a/web/src/components/app/unibox/scopeRail.test.tsx +++ b/web/src/components/app/unibox/scopeRail.test.tsx @@ -34,6 +34,7 @@ const overview = vi.hoisted(() => ({ automated: 0, automated_unread: 0, awaiting_agent_draft: 0, + drafts: undefined as number | undefined, scheduled_pending: 0, scheduled_pending_max: 100, folders: [ @@ -1145,12 +1146,25 @@ it("counts pending agent drafts on Drafts and highlights them", () => { overview.data = { ...saved, awaiting_agent_draft: 3, + drafts: 3, folders: [...saved.folders, { folder: "drafts", unread: 0, total: 1 }], }; try { mountRail(); const rows = Array.from(document.querySelectorAll("[data-rail-row]")).map((r) => r.textContent ?? ""); - expect(rows.find((r) => r.startsWith("Drafts"))).toBe("Drafts4"); + expect(rows.find((r) => r.startsWith("Drafts"))).toBe("Drafts3"); + } finally { + overview.data = saved; + } +}); + +it("keeps the mailbox Drafts count when connected to an older backend", () => { + const saved = overview.data; + overview.data = { ...saved, awaiting_agent_draft: 3, folders: [...saved.folders, { folder: "drafts", unread: 0, total: 1 }] }; + try { + mountRail(); + const rows = Array.from(document.querySelectorAll("[data-rail-row]")).map((r) => r.textContent ?? ""); + expect(rows.find((r) => r.startsWith("Drafts"))).toBe("Drafts1"); } finally { overview.data = saved; } diff --git a/web/src/lib/api/models/app/unibox/UniboxOverview.ts b/web/src/lib/api/models/app/unibox/UniboxOverview.ts index b4d47446a..05968c9f2 100644 --- a/web/src/lib/api/models/app/unibox/UniboxOverview.ts +++ b/web/src/lib/api/models/app/unibox/UniboxOverview.ts @@ -46,6 +46,8 @@ export default interface UniboxOverview { automated_unread: number; /** Threads with a pending inbox-agent draft awaiting human review. */ awaiting_agent_draft: number; + /** Distinct conversations across mailbox drafts and visible pending agent replies; absent on older servers. */ + drafts?: number; /** Pending outbound email tasks queued from the workspace's mailboxes. */ scheduled_pending: number; /** From a9ff0802bb338bd17bf075f09bc2cf2e865a409e Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Fri, 30 Oct 2026 14:18:47 +0100 Subject: [PATCH 017/318] feat: report skipped PostgreSQL subtests even when their parent test passes --- .github/scripts/live-tests-summary.mjs | 11 +++++++---- .github/scripts/live-tests-summary.test.mjs | 11 +++++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/.github/scripts/live-tests-summary.mjs b/.github/scripts/live-tests-summary.mjs index 91b7cb4ce..62d8ed5fb 100644 --- a/.github/scripts/live-tests-summary.mjs +++ b/.github/scripts/live-tests-summary.mjs @@ -3,6 +3,7 @@ import { pathToFileURL } from "node:url"; export function summarizeLiveTests(input, outcome) { const tests = new Map(); + const subtests = new Map(); const failedPackages = new Set(); for (const line of input.split("\n")) { let event; @@ -15,14 +16,16 @@ export function summarizeLiveTests(input, outcome) { if (event.Action === "fail" && typeof event.Package === "string" && !event.Test) { failedPackages.add(event.Package); } - if (typeof event.Test !== "string" || !event.Test.startsWith("TestLive") || event.Test.includes("/")) continue; + if (typeof event.Test !== "string" || !event.Test.startsWith("TestLive")) continue; if (!["pass", "fail", "skip"].includes(event.Action)) continue; - tests.set(`${event.Package}/${event.Test}`, event.Action); + const results = event.Test.includes("/") ? subtests : tests; + results.set(`${event.Package}/${event.Test}`, event.Action); } const names = (action) => [...tests].filter(([, result]) => result === action).map(([name]) => name).sort(); const passed = names("pass"); const failed = names("fail"); const skipped = names("skip"); + const skippedSubtests = [...subtests].filter(([, result]) => result === "skip").map(([name]) => name).sort(); const list = (heading, entries) => [ `### ${heading}`, "", @@ -31,7 +34,7 @@ export function summarizeLiveTests(input, outcome) { "", ]; return { - needsAttention: outcome !== "success" || tests.size === 0 || failed.length > 0 || skipped.length > 0 || failedPackages.size > 0, + needsAttention: outcome !== "success" || tests.size === 0 || failed.length > 0 || skipped.length > 0 || skippedSubtests.length > 0 || failedPackages.size > 0, markdown: [ "## PostgreSQL catch-all (advisory)", "", @@ -46,7 +49,7 @@ export function summarizeLiveTests(input, outcome) { ...(tests.size === 0 ? ["No completed TestLive results were recorded. Check setup, compilation and timeouts.", ""] : []), ...list("Failed packages (including setup or build failures)", [...failedPackages].sort()), ...list("Failed tests", failed), - ...list("Skipped tests", skipped), + ...list("Skipped tests and subtests", [...skipped, ...skippedSubtests]), "Full JSON events and compiler output are retained in the postgres-live-advisory artifact. Subtests are included there; counts above include each top-level test once.", "", ].join("\n"), diff --git a/.github/scripts/live-tests-summary.test.mjs b/.github/scripts/live-tests-summary.test.mjs index e9cea53d9..cd6d6a5a4 100644 --- a/.github/scripts/live-tests-summary.test.mjs +++ b/.github/scripts/live-tests-summary.test.mjs @@ -36,3 +36,14 @@ test("successful coverage is clean only when completed tests contain no skips", assert.equal(summarizeLiveTests(events({ Action: "pass", Package: "app", Test: "TestLiveOK" }), "success").needsAttention, false); assert.equal(summarizeLiveTests(events({ Action: "skip", Package: "app", Test: "TestLiveSkipped" }), "success").needsAttention, true); }); + +test("a skipped subtest is actionable even when its parent passes", () => { + const report = summarizeLiveTests(events( + { Action: "skip", Package: "app", Test: "TestLiveExample/needs-fixture" }, + { Action: "pass", Package: "app", Test: "TestLiveExample" }, + ), "success"); + assert.equal(report.needsAttention, true); + assert.match(report.markdown, /\| Passed \| 1 \|/); + assert.match(report.markdown, /\| Skipped \| 0 \|/); + assert.match(report.markdown, /`app\/TestLiveExample\/needs-fixture`/); +}); From 1626bd1b5efbe9632b6ecc16674f1f3db476f0c6 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Fri, 30 Oct 2026 14:37:31 +0100 Subject: [PATCH 018/318] feat: keep Unibox draft queries and counts aligned with mailbox scope and visible snooze state --- internal/repository/pg_unibox.go | 10 +- internal/repository/unibox_scope_live_test.go | 93 +++++++++++++++++++ 2 files changed, 100 insertions(+), 3 deletions(-) diff --git a/internal/repository/pg_unibox.go b/internal/repository/pg_unibox.go index f67cb345a..f3a4a0b0d 100644 --- a/internal/repository/pg_unibox.go +++ b/internal/repository/pg_unibox.go @@ -869,8 +869,10 @@ func uniboxSearchQuery(orgID uuid.UUID, params *models.MailSearchParams) (string inner += ` AND NOT ` + ownAddressSQL("ue.from_addr", "$1") } + agentMailboxScope := "" if len(params.EmailAccountIDs) > 0 { inner += fmt.Sprintf(` AND ue.email_id = ANY($%d)`, argPos) + agentMailboxScope = fmt.Sprintf(` AND d.email_account_id = ANY($%d)`, argPos) args = append(args, params.EmailAccountIDs) argPos++ } @@ -903,6 +905,7 @@ func uniboxSearchQuery(orgID uuid.UUID, params *models.MailSearchParams) (string WHERE d.organization_id = $1 AND d.thread_id = b.thread_id AND d.status = 'pending' + AND d.email_account_id IN (SELECT id FROM email_accounts WHERE organization_id = $1)` + agentMailboxScope + ` )` } @@ -1747,6 +1750,7 @@ func (r *uniboxRepository) overview(ctx context.Context, orgID uuid.UUID, accoun EXISTS ( SELECT 1 FROM ai_thread_drafts d WHERE d.organization_id = $1 AND d.thread_id = e.thread_id AND d.status = 'pending' + AND d.email_account_id IN `+mailboxes+` ) AS has_agent_draft, e.folder IN ('sent', 'drafts') AS is_ours, e.folder = 'archive' AS is_archived, @@ -1765,7 +1769,7 @@ func (r *uniboxRepository) overview(ctx context.Context, orgID uuid.UUID, accoun tkey, bool_or(is_snoozed) AS is_snoozed, bool_or(NOT is_archived) AS working, - bool_or(is_draft OR (NOT is_archived AND has_agent_draft)) AS has_draft, + bool_or((is_draft OR (NOT is_archived AND has_agent_draft)) AND NOT is_snoozed) AS has_draft, bool_or(NOT seen) FILTER (WHERE NOT is_archived) AS has_unread, max(internal_date) FILTER (WHERE NOT is_archived) AS last_date, -- The same rule as automatedThreadSQL, over rows already in hand. @@ -1789,8 +1793,8 @@ func (r *uniboxRepository) overview(ctx context.Context, orgID uuid.UUID, accoun COUNT(*) FILTER (WHERE NOT t.is_snoozed AND t.working AND t.is_automated AND t.has_unread) AS automated_unread, (SELECT COUNT(*) FROM latest_per_thread l WHERE `+ownAddressSQL("l.from_addr", "$1")+`) AS awaiting, (SELECT COUNT(*) FROM ai_thread_drafts d - WHERE d.organization_id = $1 AND d.status = 'pending'`+onlyMailboxes("d.email_account_id")+`) AS awaiting_agent_draft, - COUNT(*) FILTER (WHERE NOT t.is_snoozed AND t.has_draft) AS drafts + WHERE d.organization_id = $1 AND d.status = 'pending' AND d.email_account_id IN `+mailboxes+`) AS awaiting_agent_draft, + COUNT(*) FILTER (WHERE t.has_draft) AS drafts FROM threads t `, orgID, todayStart, weekStart).Scan( &overview.Total, diff --git a/internal/repository/unibox_scope_live_test.go b/internal/repository/unibox_scope_live_test.go index afdd76e7b..711027b2d 100644 --- a/internal/repository/unibox_scope_live_test.go +++ b/internal/repository/unibox_scope_live_test.go @@ -130,6 +130,99 @@ func threadIDs(res *models.MailSearchResult) []string { return out } +func TestLiveUniboxScopeDraftsCountHonorsMailboxScope(t *testing.T) { + handle := liveUniboxFolderDB(t) + f := newUniboxFolderFixture(t, handle.Pool) + foreign := newUniboxFolderFixture(t, handle.Pool) + repo := NewUniboxRepository(handle) + ctx := t.Context() + now := time.Now().UTC() + second := *f + second.mailbox = visibilityMailbox(t, handle.Pool, f, now) + for _, mailbox := range []*uniboxFolderFixture{f, &second, foreign} { + mailbox.scopedMessage(t, repo, "shared-thread", "them@example.com", models.FolderInbox, now) + } + if _, err := handle.Pool.Exec(ctx, `INSERT INTO ai_thread_drafts + (id, organization_id, email_account_id, owner_user_id, thread_id, to_addr) + VALUES ($1,$2,$3,$4,'shared-thread','them@example.com')`, uuid.New(), f.org, second.mailbox, f.user); err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + name string + allowed []uuid.UUID + want int64 + }{ + {"first mailbox", []uuid.UUID{f.mailbox}, 0}, + {"draft mailbox", []uuid.UUID{second.mailbox}, 1}, + {"both mailboxes", []uuid.UUID{f.mailbox, second.mailbox}, 1}, + {"cross-org grant", []uuid.UUID{f.mailbox, foreign.mailbox}, 0}, + {"foreign mailbox", []uuid.UUID{foreign.mailbox}, 0}, + {"none", models.NoneMatch(), 0}, + } { + t.Run(tc.name, func(t *testing.T) { + agent := true + rows, err := repo.Search(ctx, f.org, &models.MailSearchParams{AgentDraft: &agent, EmailAccountIDs: tc.allowed, PageSize: 50}) + if err != nil { + t.Fatal(err) + } + if int64(len(rows.Data)) != tc.want { + t.Errorf("agent draft rows = %d, want %d", len(rows.Data), tc.want) + } + overview, err := repo.OverviewForMailboxes(ctx, f.org, tc.allowed) + if err != nil { + t.Fatal(err) + } + if overview.Drafts != tc.want || overview.AwaitingAgentDraft != tc.want { + t.Errorf("draft counts = %d/%d, want %d", overview.Drafts, overview.AwaitingAgentDraft, tc.want) + } + }) + } +} + +func TestLiveUniboxScopeDraftsCountMatchesUnsnoozedOwner(t *testing.T) { + handle := liveUniboxFolderDB(t) + f := newUniboxFolderFixture(t, handle.Pool) + teammate := newUniboxFolderFixture(t, handle.Pool) + repo := NewUniboxRepository(handle) + ctx := t.Context() + now := time.Now().UTC() + if _, err := handle.Pool.Exec(ctx, `INSERT INTO organization_members + (organization_id, user_id, role, accepted_at) VALUES ($1,$2,'member',NOW())`, f.org, teammate.user); err != nil { + t.Fatal(err) + } + second := *f + second.user = teammate.user + second.mailbox = visibilityMailbox(t, handle.Pool, &second, now) + f.scopedMessage(t, repo, "shared-snooze", "them@example.com", models.FolderInbox, now) + second.scopedMessage(t, repo, "shared-snooze", "them@example.com", models.FolderDrafts, now) + f.scopedMessage(t, repo, "shared-agent", "them@example.com", models.FolderInbox, now) + second.scopedMessage(t, repo, "shared-agent", "them@example.com", models.FolderInbox, now) + if _, err := handle.Pool.Exec(ctx, `INSERT INTO ai_thread_drafts + (id, organization_id, email_account_id, owner_user_id, thread_id, to_addr) + VALUES ($1,$2,$3,$4,'shared-agent','them@example.com')`, uuid.New(), f.org, second.mailbox, second.user); err != nil { + t.Fatal(err) + } + threads := []string{"shared-snooze", "shared-agent"} + if _, err := repo.UpsertSnoozes(ctx, f.org, f.user, threads, now.Add(time.Hour)); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = repo.DeleteSnoozes(context.Background(), f.org, f.user, threads) }) + folder := models.FolderDrafts + rows, err := repo.Search(ctx, f.org, &models.MailSearchParams{Folder: &folder, PageSize: 50}) + if err != nil || len(rows.Data) != 1 { + t.Fatalf("mailbox draft rows = %+v, %v; want one", rows, err) + } + agent := true + agentRows, err := repo.Search(ctx, f.org, &models.MailSearchParams{AgentDraft: &agent, PageSize: 50}) + if err != nil || len(agentRows.Data) != 1 { + t.Fatalf("agent draft rows = %+v, %v; want one", agentRows, err) + } + overview, err := repo.Overview(ctx, f.org) + if err != nil || overview.Drafts != 2 { + t.Fatalf("overview = %+v, %v; want two drafts", overview, err) + } +} + func listsThread(res *models.MailSearchResult, want string) bool { for _, id := range threadIDs(res) { if id == want { From 0a4f70aedcb5ce48ac73a2e29d3ac247e00d43a2 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Fri, 30 Oct 2026 15:07:57 +0100 Subject: [PATCH 019/318] feat: let a workspace confirm its main website with its _warmbly TXT record so sending-domain and form redirects can point there (website_domains, migration 000333, POST /emails/domains/:domain/redirect/website, rechecked every 6 hours), skip the visitor check while a destination is unconfirmed, and redesign the sending domain Redirect tab as a step checklist with the website record inline --- cmd/backend/main.go | 2 + docs/content/docs/api/endpoints.mdx | 5 +- docs/content/docs/api/error-codes.mdx | 3 +- .../content/docs/development/data-control.mdx | 2 +- docs/content/docs/guides/forms.mdx | 2 +- docs/content/docs/guides/sending-domains.mdx | 18 +- .../docs/guides/workspace-export-import.mdx | 2 + internal/api/handler/sending_domains.go | 24 ++ internal/api/routes.go | 1 + internal/app/form/service.go | 7 +- internal/app/orgtransfer/spec.go | 1 + internal/app/owndomain/owndomain.go | 178 +++++++++++- internal/app/sendingdomain/service.go | 82 +++++- internal/app/sendingdomain/website_test.go | 174 +++++++++++ .../000333_website_domains.down.sql | 1 + .../migrations/000333_website_domains.up.sql | 10 + internal/models/mailbox_import.go | 10 + internal/repository/pg_website_domain.go | 96 +++++++ .../app/emails/domains/RedirectServing.tsx | 272 +++++++++++++----- .../emails/domains/SendingDomainDrawer.tsx | 164 +++++++---- .../components/app/emails/domains/rules.ts | 13 +- .../components/app/forms/SettingsPanel.tsx | 3 +- .../api/client/app/emails/sendingDomains.ts | 12 + .../api/hooks/app/emails/useSendingDomains.ts | 12 + .../api/models/app/emails/SendingDomain.ts | 12 +- 25 files changed, 946 insertions(+), 160 deletions(-) create mode 100644 internal/app/sendingdomain/website_test.go create mode 100644 internal/infrastructure/db/migrations/000333_website_domains.down.sql create mode 100644 internal/infrastructure/db/migrations/000333_website_domains.up.sql create mode 100644 internal/repository/pg_website_domain.go diff --git a/cmd/backend/main.go b/cmd/backend/main.go index 2fc154b21..a6c1f080e 100644 --- a/cmd/backend/main.go +++ b/cmd/backend/main.go @@ -1975,6 +1975,8 @@ func main() { // Sending domains: tracking host per domain and the bare-domain redirect. sendingDomainService = sendingdomain.NewService(repository.NewDomainRedirectRepository(primaryDB), emailRepostory, nil, domainProver) sendingDomainService.WireAuditor(auditService) + // A website the workspace proves with its TXT record becomes one of its own domains too. + ownDomains.WireWebsites(repository.NewWebsiteDomainRepository(primaryDB), domainProver, nil) sendingDomainService.WireOwnDomains(ownDomains) sendingDomainService.WireCustomHosts(customHosts) // A linked self-hosted instance can have Warmbly Cloud serve a redirect instead. diff --git a/docs/content/docs/api/endpoints.mdx b/docs/content/docs/api/endpoints.mdx index 1a72d7370..480933dd8 100644 --- a/docs/content/docs/api/endpoints.mdx +++ b/docs/content/docs/api/endpoints.mdx @@ -652,8 +652,9 @@ Alongside them, `api_url` is this API's own public base (for a copyable example - `POST /emails/domains/bulk`: `domains` (1 to 100), `tracking_label` (one DNS label, such as `link`; each domain gets `
+ )} +

@@ -313,6 +378,17 @@ export default function TestersPage() { {t.sample_data_seeded_at ? "Sample data added" : "Add sample data"} )} + {t.created_as_tester && ( + + )} +

+ ))} + + )} + + ); +} diff --git a/web/src/app/app/settings/security/page.tsx b/web/src/app/app/settings/security/page.tsx index af1c4062d..73a0b85a7 100644 --- a/web/src/app/app/settings/security/page.tsx +++ b/web/src/app/app/settings/security/page.tsx @@ -1,13 +1,12 @@ -import React from "react"; import { useNavigate } from "@tanstack/react-router"; import { RowLink, Section, SectionShell } from "../_components/SectionShell"; import PasskeyManager from "./PasskeyManager"; import SessionManager from "./SessionManager"; import TwoFactorManager from "./TwoFactorManager"; -import ChangePasswordDialog from "./ChangePasswordDialog"; +import PasswordSection from "./PasswordSection"; +import SignInMethods from "./SignInMethods"; export default function SecuritySettingsPage() { - const [pwOpen, setPwOpen] = React.useState(false); const navigate = useNavigate(); return ( @@ -15,14 +14,9 @@ export default function SecuritySettingsPage() { -
- setPwOpen(true)} - /> -
+ + + @@ -62,7 +56,6 @@ export default function SecuritySettingsPage() { onClick={() => (window.location.href = "/app/api-keys")} /> - setPwOpen(false)} />
); } diff --git a/web/src/app/auth/hooks/useResetPasswordConfirmForm.ts b/web/src/app/auth/hooks/useResetPasswordConfirmForm.ts index 74ff30201..af01f6ea9 100644 --- a/web/src/app/auth/hooks/useResetPasswordConfirmForm.ts +++ b/web/src/app/auth/hooks/useResetPasswordConfirmForm.ts @@ -1,6 +1,7 @@ import type React from "react"; import { useState, useEffect } from "react"; import { useNavigate } from "@tanstack/react-router"; +import { useQueryClient } from "@tanstack/react-query"; import { useSearchParams } from "@/hooks/useSearchParams"; import useResetPasswordConfirm from "@/lib/api/hooks/auth/useResetPasswordConfirm"; import { usePasswordStrength } from "@/hooks/usePasswordStrength"; @@ -9,11 +10,14 @@ import type { AppError } from "@/lib/api/client/normalizeError"; import buildError from "@/lib/helper/buildError"; import resetPasswordSession from "@/lib/api/client/auth/resetPasswordSession"; import { resetLinkToken } from "@/lib/resetLinkToken"; +import getToken from "@/lib/helper/getToken"; +import { clearClientSession } from "@/lib/session"; export function useResetPasswordConfirmForm() { // The link token is exchanged for a reset session held in memory, and cleared from the address bar. const [params, setParams] = useSearchParams(); const navigate = useNavigate(); + const queryClient = useQueryClient(); const resetConfirm = useResetPasswordConfirm(); const { evaluate } = usePasswordStrength(); @@ -67,6 +71,8 @@ export function useResetPasswordConfirmForm() { resetConfirm.mutateAsync({ session, password, turnstile: turnstileToken }), { loading: "Loading...", success: "Password successfully changed", error: (err: AppError) => buildError(err) } ); + // The reset ended every session, this browser's included. + if (getToken()) clearClientSession(queryClient); navigate({ to: "/auth/login", search: { action: "1" } }); } catch (err) { // The link died meanwhile (used, expired, or the password changed): show the request-a-new-one screen. diff --git a/web/src/app/auth/layout.tsx b/web/src/app/auth/layout.tsx index 645d8e2aa..e116b713b 100644 --- a/web/src/app/auth/layout.tsx +++ b/web/src/app/auth/layout.tsx @@ -34,7 +34,9 @@ export default function AuthLayout({ return () => window.removeEventListener("message", receiveMessage); }, [navigate]); - if (redirectIfAuthenticated && getToken()) { + // A reset link is opened from mail, often in the browser that is signed in. + const opensSignedIn = pathname.startsWith("/auth/reset-password"); + if (redirectIfAuthenticated && !opensSignedIn && getToken()) { return ; } diff --git a/web/src/lib/api/client/auth/identities/list.ts b/web/src/lib/api/client/auth/identities/list.ts new file mode 100644 index 000000000..e8f48b373 --- /dev/null +++ b/web/src/lib/api/client/auth/identities/list.ts @@ -0,0 +1,12 @@ +import Request from "../../Request"; +import type LinkedIdentity from "@/lib/api/models/auth/LinkedIdentity"; + +export default async function listLinkedIdentities(signal?: AbortSignal): Promise { + const res = await Request<{ data: LinkedIdentity[] }>({ + method: "GET", + url: "/auth/me/identities", + authorization: true, + signal, + }); + return res.data; +} diff --git a/web/src/lib/api/client/auth/identities/unlink.ts b/web/src/lib/api/client/auth/identities/unlink.ts new file mode 100644 index 000000000..c81555069 --- /dev/null +++ b/web/src/lib/api/client/auth/identities/unlink.ts @@ -0,0 +1,10 @@ +import Request from "../../Request"; + +// Needs a fresh confirmation; the client prompts for it on reauth_required. +export default async function unlinkIdentity(provider: string): Promise { + await Request({ + method: "DELETE", + url: `/auth/me/identities/${encodeURIComponent(provider)}`, + authorization: true, + }); +} diff --git a/web/src/lib/api/client/auth/sendPasswordLink.ts b/web/src/lib/api/client/auth/sendPasswordLink.ts new file mode 100644 index 000000000..d8adf9227 --- /dev/null +++ b/web/src/lib/api/client/auth/sendPasswordLink.ts @@ -0,0 +1,10 @@ +import Request from "../Request"; + +// Emails the signed-in user a single-use link to set a password. +export default async function sendPasswordLink(): Promise { + await Request({ + method: "POST", + url: "/auth/me/password/link", + authorization: true, + }); +} diff --git a/web/src/lib/api/hooks/auth/useLinkedIdentities.ts b/web/src/lib/api/hooks/auth/useLinkedIdentities.ts new file mode 100644 index 000000000..aff930bbc --- /dev/null +++ b/web/src/lib/api/hooks/auth/useLinkedIdentities.ts @@ -0,0 +1,9 @@ +import { useQuery } from "@tanstack/react-query"; +import listLinkedIdentities from "@/lib/api/client/auth/identities/list"; + +export default function useLinkedIdentities() { + return useQuery({ + queryKey: ["auth", "identities"], + queryFn: ({ signal }) => listLinkedIdentities(signal), + }); +} diff --git a/web/src/lib/api/hooks/auth/useReauthMethods.ts b/web/src/lib/api/hooks/auth/useReauthMethods.ts new file mode 100644 index 000000000..b53d9c4c7 --- /dev/null +++ b/web/src/lib/api/hooks/auth/useReauthMethods.ts @@ -0,0 +1,9 @@ +import { useQuery } from "@tanstack/react-query"; +import getReauthMethods from "@/lib/api/client/auth/reauth/methods"; + +export default function useReauthMethods() { + return useQuery({ + queryKey: ["auth", "reauth-methods"], + queryFn: ({ signal }) => getReauthMethods(signal), + }); +} diff --git a/web/src/lib/api/hooks/auth/useUnlinkIdentity.ts b/web/src/lib/api/hooks/auth/useUnlinkIdentity.ts new file mode 100644 index 000000000..9ab0b8636 --- /dev/null +++ b/web/src/lib/api/hooks/auth/useUnlinkIdentity.ts @@ -0,0 +1,15 @@ +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import unlinkIdentity from "@/lib/api/client/auth/identities/unlink"; + +// Not optimistic: the server refuses removing the last way to sign in. +export default function useUnlinkIdentity() { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (provider: string) => unlinkIdentity(provider), + onSettled: () => { + queryClient.invalidateQueries({ queryKey: ["auth", "identities"] }); + queryClient.invalidateQueries({ queryKey: ["auth", "reauth-methods"] }); + queryClient.invalidateQueries({ queryKey: ["sessions"] }); + }, + }); +} diff --git a/web/src/lib/api/models/auth/LinkedIdentity.ts b/web/src/lib/api/models/auth/LinkedIdentity.ts new file mode 100644 index 000000000..42954434d --- /dev/null +++ b/web/src/lib/api/models/auth/LinkedIdentity.ts @@ -0,0 +1,8 @@ +// GET /auth/me/identities: a provider the account can sign in with. +export default interface LinkedIdentity { + provider: "google" | "apple" | "oidc"; + label: string; + email?: string; + created_at: string; + last_login_at?: string; +} From 95986af748680feff56804331e6ab48bc7561838 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sat, 31 Oct 2026 14:33:54 +0100 Subject: [PATCH 035/318] feat: keep conditional German, French and Spanish interest phrases out of automatic positive reply classification --- docs/content/docs/guides/inbox-tagging.mdx | 2 +- internal/app/replyclassify/languages.go | 13 ++++++------- .../app/replyclassify/sentiment_languages_test.go | 13 +++++++++---- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/docs/content/docs/guides/inbox-tagging.mdx b/docs/content/docs/guides/inbox-tagging.mdx index 066de9f37..35f65a110 100644 --- a/docs/content/docs/guides/inbox-tagging.mdx +++ b/docs/content/docs/guides/inbox-tagging.mdx @@ -234,7 +234,7 @@ The reading before any call covers: - **Out-of-office replies**, recognized by the subject their mail provider writes (`ะะฒั‚ะพะผะฐั‚ะธั‡ะตัะบะธะน ะพั‚ะฒะตั‚`, `่‡ชๅ‹•ๅฟœ็ญ”`, `์ž๋™ ํšŒ์‹ `, `ุฑุฏ ุชู„ู‚ุงุฆูŠ` and so on) and decided with no call at all. - **Non-delivery notices**, by the subject Exchange writes in Spanish, Italian, Dutch and Portuguese. A notice carrying a delivery-status report is recognized in any language without this. - **Replies that say no**, in German, French, Spanish, Dutch, Italian and Portuguese: a declined interest ("kein Interesse", "pas intรฉressรฉ", "no me interesa", "geen interesse", "non sono interessato", "nรฃo tenho interesse") or another clear no ("nein danke", "non merci", "no gracias", "nee bedankt", "no grazie", "nรฃo, obrigado", "falscher Ansprechpartner", "persona sbagliata"). Each phrase is matched as whole words, so "no grazie" never matches inside "buono, grazie". The reply classifier reads these as negative with no call, the same verdict "not interested" and "no thanks" get in English, so they take the `reply_negative` branch. Inbox labels still come from the classifier. -- **Replies that show interest**, in German, French and Spanish ("klingt gut", "lassen Sie uns telefonieren", "รงa m'intรฉresse", "je suis intรฉressรฉ", "me interesa mucho", "agendemos una llamada"), read as positive with no call, the same verdict "interested" and "let's talk" get in English, so they take the `reply_positive` branch and count as interested leads. A reply that also says no in one of these languages ("klingt gut, aber kein Bedarf") stays negative, and a phrase in a sentence that already says "no", "nicht", "pas" and the like ("no me interesa mucho", "je ne crois pas, honnรชtement, que cela nous intรฉresse") does not count, nor does one taken back later by "pero no", "aber nicht", "mais pas" and the like ("me interesa mucho, pero no ahora"). +- **Replies that show interest**, in German, French and Spanish ("klingt gut", "lassen Sie uns telefonieren", "รงa m'intรฉresse", "je suis intรฉressรฉ", "me interesa mucho", "agendemos una llamada"), read as positive with no call, the same verdict "interested" and "let's talk" get in English, so they take the `reply_positive` branch and count as interested leads. A reply that also says no in one of these languages ("klingt gut, aber kein Bedarf") stays negative, and a phrase in a sentence that already says "no", "nicht", "pas" and the like ("no me interesa mucho", "je ne crois pas, honnรชtement, que cela nous intรฉresse") does not count, nor does one taken back later by "pero no", "aber nicht", "mais pas" and the like ("me interesa mucho, pero no ahora"). Conditional interest such as "Si cela m'intรฉresse, je vous contacterai" or "Si me interesa mucho, les aviso" stays inconclusive. Tagging languages are part of the workspace settings, so they travel with a [workspace export](/guides/workspace-export-import/). diff --git a/internal/app/replyclassify/languages.go b/internal/app/replyclassify/languages.go index 814a5336a..01b2acac2 100644 --- a/internal/app/replyclassify/languages.go +++ b/internal/app/replyclassify/languages.go @@ -36,7 +36,7 @@ type langRules struct { // negative is any other clear no. Both are phrases, never single words. declined, negative []string // positive is clear interest. A chosen language's is read after its no - // phrases, and never in a sentence with a negating word before it. positiveAsWritten + // phrases, and never after a negator or condition in its sentence. positiveAsWritten // keeps its accents, where folding would change the meaning. positive, positiveAsWritten []string } @@ -464,7 +464,7 @@ type ruleSet struct { type phrase struct { text string bounded bool - // negatable phrases do not count after a negating word in the same sentence ("no me interesa mucho"). + // negatable phrases do not count after a negator or condition in the same sentence. negatable bool // asWritten phrases keep their accents, because folding them changes the meaning ("sรญ" is not "si"). asWritten bool @@ -476,15 +476,14 @@ var negators = map[string]bool{ "pas": true, "ne": true, "non": true, "niet": true, "geen": true, "nao": true, "nunca": true, "jamas": true, } -// negatedAt reports a negator earlier in the sentence that holds start. Commas and -// line breaks do not end it ("je ne crois pas, honnรชtement, que cela nous intรฉresse"). -func negatedAt(text string, start int) bool { +// negatedOrConditionalAt keeps a qualified phrase from counting as definite interest. +func negatedOrConditionalAt(text string, start int) bool { head := text[:start] if i := strings.LastIndexAny(head, ".!?;"); i >= 0 { head = head[i+1:] } for _, word := range strings.FieldsFunc(head, func(r rune) bool { return !unicode.IsLetter(r) }) { - if negators[word] { + if negators[word] || word == "si" || word == "wenn" || word == "falls" || word == "sofern" { return true } } @@ -525,7 +524,7 @@ func (p phrase) in(text, folded string) bool { start, end := i+j, i+j+len(p.text) before, _ := utf8.DecodeLastRuneInString(text[:start]) after, _ := utf8.DecodeRuneInString(text[end:]) - if !wordRune(before) && !wordRune(after) && !(p.negatable && (negatedAt(text, start) || refusedAfter(text, end))) { + if !wordRune(before) && !wordRune(after) && !(p.negatable && (negatedOrConditionalAt(text, start) || refusedAfter(text, end))) { return true } _, size := utf8.DecodeRuneInString(text[start:]) diff --git a/internal/app/replyclassify/sentiment_languages_test.go b/internal/app/replyclassify/sentiment_languages_test.go index b84d0019a..7ef7ca463 100644 --- a/internal/app/replyclassify/sentiment_languages_test.go +++ b/internal/app/replyclassify/sentiment_languages_test.go @@ -246,6 +246,10 @@ func TestNegatedAndHedgedInterestIsNotPositive(t *testing.T) { "No estoy muy interesado.", "Gracias, pero no estamos muy interesados.", "Si me interesa, les aviso.", + "Si me interesa mucho, les aviso.", + "Si cela m'intรฉresse, je vous contacterai.", + "Si รงa m'intรฉresse, je vous recontacte.", + "Falls es passt, kรถnnen wir telefonieren.", "No\nme interesa mucho.", "No quiero agendar una llamada.", "Wir wollen nicht gleich einen Termin vereinbaren.", @@ -264,21 +268,22 @@ func TestNegatedAndHedgedInterestIsNotPositive(t *testing.T) { } } -// A negating word anywhere earlier in the sentence turns the phrase around. -func TestNegatedAtReadsTheSentence(t *testing.T) { +// A negator or condition earlier in the sentence qualifies the interest. +func TestNegatedOrConditionalAtReadsTheSentence(t *testing.T) { for text, want := range map[string]bool{ "no me interesa mucho": true, "no, me interesa mucho": true, "pero no me interesa mucho": true, "no\nme interesa mucho": true, "no a b c me interesa mucho": true, + "si me interesa mucho": true, "bueno me interesa mucho": false, "me interesa mucho": false, "no. me interesa mucho": false, "por que no? me interesa mucho": false, } { - if got := negatedAt(text, len(text)-len("me interesa mucho")); got != want { - t.Errorf("negatedAt(%q) = %v, want %v", text, got, want) + if got := negatedOrConditionalAt(text, len(text)-len("me interesa mucho")); got != want { + t.Errorf("negatedOrConditionalAt(%q) = %v, want %v", text, got, want) } } } From 7f0d4f2598deec5ed4cab1ff7318764c0247e597 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sat, 31 Oct 2026 14:43:33 +0100 Subject: [PATCH 036/318] feat: serialize passkey deletion and sign-in provider removal on the user row lock so neither removes an account's last way in (last_sign_in_method on DELETE /auth/passkey/credentials/:id), and clear legacy token keys after a password reset --- docs/content/docs/api/error-codes.mdx | 2 +- .../docs/api/reference/account-org.mdx | 2 +- docs/content/docs/guides/security.mdx | 2 + internal/app/auth/linked_identity.go | 6 +-- internal/app/auth/reauth_identity_test.go | 2 +- internal/errx/common.go | 7 +++- .../repository/identity_unlink_live_test.go | 19 +++++++++ internal/repository/pg_identity.go | 39 ++++++++++--------- internal/repository/pg_webauthn.go | 33 ++++++++++++---- .../app/settings/security/PasskeyManager.tsx | 7 +++- .../auth/hooks/useResetPasswordConfirmForm.ts | 3 +- 11 files changed, 83 insertions(+), 39 deletions(-) diff --git a/docs/content/docs/api/error-codes.mdx b/docs/content/docs/api/error-codes.mdx index cf213dd48..fdf076e66 100644 --- a/docs/content/docs/api/error-codes.mdx +++ b/docs/content/docs/api/error-codes.mdx @@ -202,7 +202,7 @@ Avatars, OAuth app logos, form logos, covers and backgrounds, and images placed | `api_credentials_revoke_unsupported` | 400 | `POST /auth/reset-password/confirm` or `POST /auth/me/password` asked to end connected apps and API keys (`revoke_api_credentials`) on a server that cannot. The password was not changed. Send it again without that option, then remove apps and keys from Settings | | `sessions_not_ended` | 503 | The same two routes could not sign out every device on the account, so the password was not changed. From `DELETE /auth/me/identities/:provider` it means the provider was removed but not every device that signed in with it was signed out; repeating the request finishes it. The response carries `Retry-After`; retry after it | | `identity_not_found` | 404 | `DELETE /auth/me/identities/:provider` named something other than `google`, `apple` or `oidc` | -| `last_sign_in_method` | 409 | `DELETE /auth/me/identities/:provider` would leave the account with no password, no passkey and no other provider. Nothing was removed. Set a password (`POST /auth/me/password/link`) or add a passkey first | +| `last_sign_in_method` | 409 | `DELETE /auth/me/identities/:provider` or `DELETE /auth/passkey/credentials/:id` would leave the account with no password, no passkey and no other provider. Nothing was removed. Set a password (`POST /auth/me/password/link`) or add a passkey first | | `password_login_disabled` | 403 | `POST /auth/me/password/link` was called on a server that turned password sign-in off (`DISABLE_PASSWORD_LOGIN`), so a password could never be used. No link was sent | A password must be 8 to 128 characters. There is no composition rule, but it is checked against the 100,000 most commonly breached passwords published by the UK National Cyber Security Centre, case-insensitively. diff --git a/docs/content/docs/api/reference/account-org.mdx b/docs/content/docs/api/reference/account-org.mdx index 21e5d24da..58c03df6e 100644 --- a/docs/content/docs/api/reference/account-org.mdx +++ b/docs/content/docs/api/reference/account-org.mdx @@ -1011,7 +1011,7 @@ Auth: Session only (not available to API keys). `DELETE /auth/passkey/credentials/:id` -Removes a stored passkey. Returns `204 No Content`. +Removes a stored passkey. Returns `204 No Content`. Refused with `409` `last_sign_in_method` when it is the account's only way to sign in (no password and no linked provider); set a password or link a provider first. Auth: Session only (not available to API keys). diff --git a/docs/content/docs/guides/security.mdx b/docs/content/docs/guides/security.mdx index 21187e31c..d5eef785a 100644 --- a/docs/content/docs/guides/security.mdx +++ b/docs/content/docs/guides/security.mdx @@ -77,6 +77,8 @@ To stop using a provider (for example when an Apple ID or a Google Workspace acc 4. Optionally add a passkey or turn on two-factor authentication on the same page. 5. Under **Sign-in methods**, choose **Remove** next to the provider. Warmbly asks you to confirm it is you first, refuses if the provider is still your only way in, and signs out every other device that signed in with it. +Warmbly never removes your last way in. A provider or passkey can only be removed while a password, another passkey or another provider remains. + The address on the account does not change, so it must keep receiving mail (a forward is fine): sign-in codes and password reset links are sent there. If you signed up with Apple's **Hide My Email**, the address is an `@privaterelay.appleid.com` relay that only forwards while Warmbly stays connected to your Apple ID, so do not disconnect Warmbly on Apple's side. With any other address, you can also disconnect Warmbly in your Apple ID or Google account settings after removing the provider here. Signing in to Warmbly is separate from any Gmail, Workspace or iCloud mailbox you connected for sending; removing a sign-in method does not affect it, and retiring that mailbox affects its sending and sync, not your sign-in. See [mailboxes](/guides/mailboxes/). diff --git a/internal/app/auth/linked_identity.go b/internal/app/auth/linked_identity.go index b03c45744..7115323a0 100644 --- a/internal/app/auth/linked_identity.go +++ b/internal/app/auth/linked_identity.go @@ -26,10 +26,6 @@ type LinkedIdentity struct { var ErrIdentityNotFound = errx.NewWithIdentifier(errx.NotFound, "identity_not_found", "That sign-in method is not linked to your account.") -// ErrLastSignInMethod refuses a removal that would leave no way to sign in. -var ErrLastSignInMethod = errx.NewWithIdentifier(errx.Conflict, "last_sign_in_method", - "This is the only way you sign in. Set a password or add a passkey first, then remove it.") - var identityLabels = map[string]string{ models.IdentityProviderGoogle: "Google", models.IdentityProviderApple: "Apple", @@ -79,7 +75,7 @@ func (s *authService) UnlinkIdentity(ctx context.Context, userID, currentSession switch { case err == nil, errors.Is(err, repository.ErrIdentityNotLinked): case errors.Is(err, repository.ErrLastSignInMethod): - return ErrLastSignInMethod + return errx.ErrLastSignInMethod default: errs.CaptureException(err) return errx.InternalError() diff --git a/internal/app/auth/reauth_identity_test.go b/internal/app/auth/reauth_identity_test.go index 56d4ef8a5..fb8981e20 100644 --- a/internal/app/auth/reauth_identity_test.go +++ b/internal/app/auth/reauth_identity_test.go @@ -290,7 +290,7 @@ func TestUnlinkIdentityMapsRefusals(t *testing.T) { cases := map[error]*errx.Error{ nil: nil, repository.ErrIdentityNotLinked: nil, - repository.ErrLastSignInMethod: ErrLastSignInMethod, + repository.ErrLastSignInMethod: errx.ErrLastSignInMethod, } for in, want := range cases { s := &authService{identities: &unlinkStub{err: in}} diff --git a/internal/errx/common.go b/internal/errx/common.go index 12f0722e6..cce94fed4 100644 --- a/internal/errx/common.go +++ b/internal/errx/common.go @@ -105,8 +105,11 @@ var ( ErrPasskeySession = New(BadRequest, "Your passkey request expired. Please start again.") ErrPasskeyName = New(BadRequest, "Passkey name must be between 1 and 60 characters.") ErrPasskeyNotFound = New(NotFound, "Passkey not found.") - ErrPasskeyExists = New(Conflict, "This passkey is already registered.") - ErrPasskeyNone = New(BadRequest, "No passkey was found for this account.") + // ErrLastSignInMethod refuses removing a passkey or provider that is the + // account's only way to sign in. + ErrLastSignInMethod = NewWithIdentifier(Conflict, "last_sign_in_method", "This is the only way you sign in. Set a password or add a passkey first, then remove it.") + ErrPasskeyExists = New(Conflict, "This passkey is already registered.") + ErrPasskeyNone = New(BadRequest, "No passkey was found for this account.") // A passkey sign-in counts as multi-factor, so the authenticator must verify the user. ErrPasskeyUserVerification = NewWithIdentifier(BadRequest, "passkey_user_verification_required", "This passkey didnโ€™t ask for a PIN or biometric. Set a PIN on the security key, or sign in another way.") diff --git a/internal/repository/identity_unlink_live_test.go b/internal/repository/identity_unlink_live_test.go index 73dc42cc1..96d90da39 100644 --- a/internal/repository/identity_unlink_live_test.go +++ b/internal/repository/identity_unlink_live_test.go @@ -7,6 +7,7 @@ import ( "github.com/google/uuid" + "github.com/warmbly/warmbly/internal/errx" "github.com/warmbly/warmbly/internal/models" ) @@ -27,6 +28,7 @@ func TestLiveIdentityUnlinkKeepsAWayIn(t *testing.T) { } t.Cleanup(func() { _, _ = pool.Exec(context.Background(), `DELETE FROM user_identities WHERE user_id = $1`, user) + _, _ = pool.Exec(context.Background(), `DELETE FROM webauthn_credentials WHERE user_id = $1`, user) _, _ = pool.Exec(context.Background(), `DELETE FROM users WHERE id = $1`, user) }) link := func(provider, issuer string) { @@ -48,6 +50,23 @@ func TestLiveIdentityUnlinkKeepsAWayIn(t *testing.T) { t.Fatalf("unlink of the only method: %v, want ErrLastSignInMethod", err) } + // A passkey is a way in too, and the last one cannot go either. + passkeys := NewWebAuthnRepository(handle) + passkey := uuid.New() + if _, err := pool.Exec(ctx, `INSERT INTO webauthn_credentials (id, user_id) VALUES ($1, $2)`, passkey, user); err != nil { + t.Fatal(err) + } + if err := repo.Unlink(ctx, user, models.IdentityProviderApple); err != nil { + t.Fatalf("unlink with a passkey remaining: %v", err) + } + if xerr := passkeys.Delete(ctx, user, passkey); xerr != errx.ErrLastSignInMethod { + t.Fatalf("delete of the only passkey: %v, want ErrLastSignInMethod", xerr) + } + link(models.IdentityProviderApple, "https://appleid.apple.com") + if xerr := passkeys.Delete(ctx, user, passkey); xerr != nil { + t.Fatalf("delete with Apple remaining: %v", xerr) + } + if _, err := pool.Exec(ctx, `UPDATE users SET password_hash = 'x' WHERE id = $1`, user); err != nil { t.Fatal(err) } diff --git a/internal/repository/pg_identity.go b/internal/repository/pg_identity.go index d05cb7754..196013cc1 100644 --- a/internal/repository/pg_identity.go +++ b/internal/repository/pg_identity.go @@ -137,36 +137,39 @@ func (r *identityRepository) Unlink(ctx context.Context, userID uuid.UUID, provi } defer func() { _ = tx.Rollback(ctx) }() - // The user row lock serialises two removals so they cannot each count the - // other as the remaining way in. - var hasPassword bool - err = tx.QueryRow(ctx, `SELECT COALESCE(`+livePasswordHash+`, '') <> '' FROM users WHERE id = $1 FOR UPDATE`, userID).Scan(&hasPassword) + remains, err := signInMethodRemains(ctx, tx, userID, provider, uuid.Nil) if errors.Is(err, pgx.ErrNoRows) { return ErrIdentityNotLinked } if err != nil { return err } - - var linked, others, passkeys bool - err = tx.QueryRow(ctx, ` - SELECT - EXISTS (SELECT 1 FROM user_identities WHERE user_id = $1 AND provider = $2), - EXISTS (SELECT 1 FROM user_identities WHERE user_id = $1 AND provider <> $2), - EXISTS (SELECT 1 FROM webauthn_credentials WHERE user_id = $1) - `, userID, provider).Scan(&linked, &others, &passkeys) + tag, err := tx.Exec(ctx, `DELETE FROM user_identities WHERE user_id = $1 AND provider = $2`, userID, provider) if err != nil { return err } - if !linked { + if tag.RowsAffected() == 0 { return ErrIdentityNotLinked } - if !hasPassword && !passkeys && !others { + if !remains { return ErrLastSignInMethod } - - if _, err := tx.Exec(ctx, `DELETE FROM user_identities WHERE user_id = $1 AND provider = $2`, userID, provider); err != nil { - return err - } return tx.Commit(ctx) } + +// signInMethodRemains locks the user row, which every removal of a way in +// takes first, and reports whether one remains besides the given provider or +// passkey. pgx.ErrNoRows means the user does not exist. +func signInMethodRemains(ctx context.Context, tx pgx.Tx, userID uuid.UUID, provider string, passkeyID uuid.UUID) (bool, error) { + var hasPassword bool + err := tx.QueryRow(ctx, `SELECT COALESCE(`+livePasswordHash+`, '') <> '' FROM users WHERE id = $1 FOR UPDATE`, userID).Scan(&hasPassword) + if err != nil || hasPassword { + return hasPassword, err + } + var remains bool + err = tx.QueryRow(ctx, ` + SELECT EXISTS (SELECT 1 FROM user_identities WHERE user_id = $1 AND provider <> $2) + OR EXISTS (SELECT 1 FROM webauthn_credentials WHERE user_id = $1 AND id <> $3) + `, userID, provider, passkeyID).Scan(&remains) + return remains, err +} diff --git a/internal/repository/pg_webauthn.go b/internal/repository/pg_webauthn.go index bbdb1423d..c6c8be3b7 100644 --- a/internal/repository/pg_webauthn.go +++ b/internal/repository/pg_webauthn.go @@ -197,24 +197,41 @@ func (r *webauthnRepository) Rename(ctx context.Context, userID, id uuid.UUID, n return nil } +// Delete removes a passkey unless it is the account's last way to sign in. func (r *webauthnRepository) Delete(ctx context.Context, userID, id uuid.UUID) *errx.Error { - query := ` - DELETE FROM webauthn_credentials - WHERE id = $1 AND user_id = $2 - ` + tx, err := r.DB.Begin(ctx) + if err != nil { + db.CaptureError(err, "begin passkey delete", []any{userID, id}, "begin") + return errx.InternalError() + } + defer func() { _ = tx.Rollback(ctx) }() + remains, err := signInMethodRemains(ctx, tx, userID, "", id) + if errors.Is(err, pgx.ErrNoRows) { + return errx.ErrPasskeyNotFound + } + if err != nil { + db.CaptureError(err, "lock sign-in methods", []any{userID, id}, "queryrow") + return errx.InternalError() + } + + query := `DELETE FROM webauthn_credentials WHERE id = $1 AND user_id = $2` params := []any{id, userID} - - cmd, err := r.DB.Exec(ctx, query, params...) + cmd, err := tx.Exec(ctx, query, params...) if err != nil { db.CaptureError(err, query, params, "exec") return errx.InternalError() } - if cmd.RowsAffected() == 0 { return errx.ErrPasskeyNotFound } - + if !remains { + return errx.ErrLastSignInMethod + } + if err := tx.Commit(ctx); err != nil { + db.CaptureError(err, query, params, "commit") + return errx.InternalError() + } return nil } diff --git a/web/src/app/app/settings/security/PasskeyManager.tsx b/web/src/app/app/settings/security/PasskeyManager.tsx index 652305dfa..606b1d806 100644 --- a/web/src/app/app/settings/security/PasskeyManager.tsx +++ b/web/src/app/app/settings/security/PasskeyManager.tsx @@ -9,6 +9,8 @@ import useDeletePasskey from "@/lib/api/hooks/auth/useDeletePasskey"; import useRenamePasskey from "@/lib/api/hooks/auth/useRenamePasskey"; import { registerPasskey, passkeySupported, PasskeyCancelled } from "@/lib/passkey"; import type Passkey from "@/lib/api/models/auth/Passkey"; +import type { AppError } from "@/lib/api/client/normalizeError"; +import buildError from "@/lib/helper/buildError"; const fmt = (d: Date | string) => new Date(d).toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" }); @@ -63,8 +65,9 @@ export default function PasskeyManager() { try { await del.mutateAsync(p.id); toast.success("Passkey removed"); - } catch { - toast.error("Couldn't remove passkey."); + } catch (err) { + // The server refuses removing the last way to sign in, and says so. + toast.error(buildError(err as AppError) || "Couldn't remove passkey."); } }); }; diff --git a/web/src/app/auth/hooks/useResetPasswordConfirmForm.ts b/web/src/app/auth/hooks/useResetPasswordConfirmForm.ts index af01f6ea9..fc08bee0a 100644 --- a/web/src/app/auth/hooks/useResetPasswordConfirmForm.ts +++ b/web/src/app/auth/hooks/useResetPasswordConfirmForm.ts @@ -11,6 +11,7 @@ import buildError from "@/lib/helper/buildError"; import resetPasswordSession from "@/lib/api/client/auth/resetPasswordSession"; import { resetLinkToken } from "@/lib/resetLinkToken"; import getToken from "@/lib/helper/getToken"; +import { TOKENS } from "@/lib/auth"; import { clearClientSession } from "@/lib/session"; export function useResetPasswordConfirmForm() { @@ -72,7 +73,7 @@ export function useResetPasswordConfirmForm() { { loading: "Loading...", success: "Password successfully changed", error: (err: AppError) => buildError(err) } ); // The reset ended every session, this browser's included. - if (getToken()) clearClientSession(queryClient); + if (getToken() || TOKENS.some((key) => localStorage.getItem(key))) clearClientSession(queryClient); navigate({ to: "/auth/login", search: { action: "1" } }); } catch (err) { // The link died meanwhile (used, expired, or the password changed): show the request-a-new-one screen. From 39e49f84f6d5947f95f7fa5f7505db2e38223385 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sat, 31 Oct 2026 14:51:41 +0100 Subject: [PATCH 037/318] feat: preserve affirmative Spanish accents and recognize elided French conditions in reply interest classification --- docs/content/docs/guides/inbox-tagging.mdx | 2 +- internal/app/replyclassify/languages.go | 32 ++++++++++++++++--- .../replyclassify/sentiment_languages_test.go | 12 +++++++ 3 files changed, 41 insertions(+), 5 deletions(-) diff --git a/docs/content/docs/guides/inbox-tagging.mdx b/docs/content/docs/guides/inbox-tagging.mdx index 35f65a110..25f6a3eac 100644 --- a/docs/content/docs/guides/inbox-tagging.mdx +++ b/docs/content/docs/guides/inbox-tagging.mdx @@ -234,7 +234,7 @@ The reading before any call covers: - **Out-of-office replies**, recognized by the subject their mail provider writes (`ะะฒั‚ะพะผะฐั‚ะธั‡ะตัะบะธะน ะพั‚ะฒะตั‚`, `่‡ชๅ‹•ๅฟœ็ญ”`, `์ž๋™ ํšŒ์‹ `, `ุฑุฏ ุชู„ู‚ุงุฆูŠ` and so on) and decided with no call at all. - **Non-delivery notices**, by the subject Exchange writes in Spanish, Italian, Dutch and Portuguese. A notice carrying a delivery-status report is recognized in any language without this. - **Replies that say no**, in German, French, Spanish, Dutch, Italian and Portuguese: a declined interest ("kein Interesse", "pas intรฉressรฉ", "no me interesa", "geen interesse", "non sono interessato", "nรฃo tenho interesse") or another clear no ("nein danke", "non merci", "no gracias", "nee bedankt", "no grazie", "nรฃo, obrigado", "falscher Ansprechpartner", "persona sbagliata"). Each phrase is matched as whole words, so "no grazie" never matches inside "buono, grazie". The reply classifier reads these as negative with no call, the same verdict "not interested" and "no thanks" get in English, so they take the `reply_negative` branch. Inbox labels still come from the classifier. -- **Replies that show interest**, in German, French and Spanish ("klingt gut", "lassen Sie uns telefonieren", "รงa m'intรฉresse", "je suis intรฉressรฉ", "me interesa mucho", "agendemos una llamada"), read as positive with no call, the same verdict "interested" and "let's talk" get in English, so they take the `reply_positive` branch and count as interested leads. A reply that also says no in one of these languages ("klingt gut, aber kein Bedarf") stays negative, and a phrase in a sentence that already says "no", "nicht", "pas" and the like ("no me interesa mucho", "je ne crois pas, honnรชtement, que cela nous intรฉresse") does not count, nor does one taken back later by "pero no", "aber nicht", "mais pas" and the like ("me interesa mucho, pero no ahora"). Conditional interest such as "Si cela m'intรฉresse, je vous contacterai" or "Si me interesa mucho, les aviso" stays inconclusive. +- **Replies that show interest**, in German, French and Spanish ("klingt gut", "lassen Sie uns telefonieren", "รงa m'intรฉresse", "je suis intรฉressรฉ", "me interesa mucho", "agendemos una llamada"), read as positive with no call, the same verdict "interested" and "let's talk" get in English, so they take the `reply_positive` branch and count as interested leads. A reply that also says no in one of these languages ("klingt gut, aber kein Bedarf") stays negative, and a phrase in a sentence that already says "no", "nicht", "pas" and the like ("no me interesa mucho", "je ne crois pas, honnรชtement, que cela nous intรฉresse") does not count, nor does one taken back later by "pero no", "aber nicht", "mais pas" and the like ("me interesa mucho, pero no ahora"). Conditional interest such as "Si cela m'intรฉresse, je vous contacterai", "Sโ€™il sโ€™avรจre que cela nous intรฉresse, nous vous recontacterons" or "Si me interesa mucho, les aviso" stays inconclusive. The accented Spanish affirmation "Sรญ, nos interesa mucho" reads as positive. Tagging languages are part of the workspace settings, so they travel with a [workspace export](/guides/workspace-export-import/). diff --git a/internal/app/replyclassify/languages.go b/internal/app/replyclassify/languages.go index 01b2acac2..ee7933f81 100644 --- a/internal/app/replyclassify/languages.go +++ b/internal/app/replyclassify/languages.go @@ -482,14 +482,31 @@ func negatedOrConditionalAt(text string, start int) bool { if i := strings.LastIndexAny(head, ".!?;"); i >= 0 { head = head[i+1:] } - for _, word := range strings.FieldsFunc(head, func(r rune) bool { return !unicode.IsLetter(r) }) { - if negators[word] || word == "si" || word == "wenn" || word == "falls" || word == "sofern" { + for _, word := range strings.FieldsFunc(head, func(r rune) bool { return !unicode.IsLetter(r) && r != '\'' }) { + word = strings.Trim(word, "'") + if word == "s'il" || word == "s'ils" { return true } + for _, part := range strings.Split(word, "'") { + if negators[accentFolder.Replace(part)] || part == "si" || part == "wenn" || part == "falls" || part == "sofern" { + return true + } + } } return false } +// unfoldedOffset maps a folded match back across replacements that change byte length. +func unfoldedOffset(text string, offset int) int { + for i, r := range text { + if offset <= 0 { + return i + } + offset -= len(accentFolder.Replace(string(r))) + } + return len(text) +} + // contrasts open a reservation; a negator after one takes the interest back. var contrasts = map[string]bool{ "aber": true, "jedoch": true, "allerdings": true, "mais": true, "cependant": true, "toutefois": true, "pero": true, "aunque": true, @@ -513,6 +530,7 @@ func (p phrase) in(text, folded string) bool { if !p.bounded { return strings.Contains(text, p.text) } + original := text if !p.asWritten { text = folded } @@ -524,8 +542,14 @@ func (p phrase) in(text, folded string) bool { start, end := i+j, i+j+len(p.text) before, _ := utf8.DecodeLastRuneInString(text[:start]) after, _ := utf8.DecodeRuneInString(text[end:]) - if !wordRune(before) && !wordRune(after) && !(p.negatable && (negatedOrConditionalAt(text, start) || refusedAfter(text, end))) { - return true + if !wordRune(before) && !wordRune(after) { + originalStart := start + if p.negatable && !p.asWritten { + originalStart = unfoldedOffset(original, start) + } + if !p.negatable || !(negatedOrConditionalAt(original, originalStart) || refusedAfter(text, end)) { + return true + } } _, size := utf8.DecodeRuneInString(text[start:]) i = start + size diff --git a/internal/app/replyclassify/sentiment_languages_test.go b/internal/app/replyclassify/sentiment_languages_test.go index 7ef7ca463..16782b7ef 100644 --- a/internal/app/replyclassify/sentiment_languages_test.go +++ b/internal/app/replyclassify/sentiment_languages_test.go @@ -207,6 +207,12 @@ func TestInterestedRepliesByLanguage(t *testing.T) { "es": { "Me interesa mucho.", "Sรญ, me interesa.", + "Sรญ, nos interesa mucho.", + "Sรญ nos interesa mucho.", + "Sรญ, Josรฉ, nos interesa mucho.", + "Sรญ, Mรผller, nos interesa mucho.", + "Sรญ, ร†gir, nos interesa mucho.", + "Sรญ, ฤฐpek, nos interesa mucho.", "Estoy muy interesado, ยฟcuรกnto cuesta?", "Agendemos una llamada.", "Envรญeme mรกs informaciรณn, por favor.", @@ -249,6 +255,12 @@ func TestNegatedAndHedgedInterestIsNotPositive(t *testing.T) { "Si me interesa mucho, les aviso.", "Si cela m'intรฉresse, je vous contacterai.", "Si รงa m'intรฉresse, je vous recontacte.", + "S'il s'avรจre que cela nous intรฉresse, nous vous recontacterons.", + "Sโ€™ils confirment que cela nous intรฉresse, nous vous recontacterons.", + "Sรญ, Josรฉ. Si nos interesa mucho, les aviso.", + "Sรญ, Mรผller. Si nos interesa mucho, les aviso.", + "Sรญ, ร†gir. Si nos interesa mucho, les aviso.", + "Sรญ, ฤฐpek. Si nos interesa mucho, les aviso.", "Falls es passt, kรถnnen wir telefonieren.", "No\nme interesa mucho.", "No quiero agendar una llamada.", From 62f325c4278152f1119055393a759778353c42bc Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sat, 31 Oct 2026 14:52:58 +0100 Subject: [PATCH 038/318] feat: give the sign-in method live test's passkey row the credential id and public key the webauthn_credentials table requires --- internal/repository/identity_unlink_live_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/internal/repository/identity_unlink_live_test.go b/internal/repository/identity_unlink_live_test.go index 96d90da39..34b2bf345 100644 --- a/internal/repository/identity_unlink_live_test.go +++ b/internal/repository/identity_unlink_live_test.go @@ -53,7 +53,8 @@ func TestLiveIdentityUnlinkKeepsAWayIn(t *testing.T) { // A passkey is a way in too, and the last one cannot go either. passkeys := NewWebAuthnRepository(handle) passkey := uuid.New() - if _, err := pool.Exec(ctx, `INSERT INTO webauthn_credentials (id, user_id) VALUES ($1, $2)`, passkey, user); err != nil { + if _, err := pool.Exec(ctx, `INSERT INTO webauthn_credentials (id, user_id, credential_id, public_key) + VALUES ($1, $2, $3, $4)`, passkey, user, passkey[:], []byte{1}); err != nil { t.Fatal(err) } if err := repo.Unlink(ctx, user, models.IdentityProviderApple); err != nil { From fe5228a0ebb87b0b2b716a95cb7de97ab4048166 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sat, 31 Oct 2026 15:06:46 +0100 Subject: [PATCH 039/318] feat: distinguish polite French requests and affirmative pas mal from postverbal reply negation --- docs/content/docs/guides/inbox-tagging.mdx | 2 +- internal/app/replyclassify/languages.go | 46 +++++++++++++++---- .../replyclassify/sentiment_languages_test.go | 14 ++++++ 3 files changed, 52 insertions(+), 10 deletions(-) diff --git a/docs/content/docs/guides/inbox-tagging.mdx b/docs/content/docs/guides/inbox-tagging.mdx index 25f6a3eac..ec48d388d 100644 --- a/docs/content/docs/guides/inbox-tagging.mdx +++ b/docs/content/docs/guides/inbox-tagging.mdx @@ -234,7 +234,7 @@ The reading before any call covers: - **Out-of-office replies**, recognized by the subject their mail provider writes (`ะะฒั‚ะพะผะฐั‚ะธั‡ะตัะบะธะน ะพั‚ะฒะตั‚`, `่‡ชๅ‹•ๅฟœ็ญ”`, `์ž๋™ ํšŒ์‹ `, `ุฑุฏ ุชู„ู‚ุงุฆูŠ` and so on) and decided with no call at all. - **Non-delivery notices**, by the subject Exchange writes in Spanish, Italian, Dutch and Portuguese. A notice carrying a delivery-status report is recognized in any language without this. - **Replies that say no**, in German, French, Spanish, Dutch, Italian and Portuguese: a declined interest ("kein Interesse", "pas intรฉressรฉ", "no me interesa", "geen interesse", "non sono interessato", "nรฃo tenho interesse") or another clear no ("nein danke", "non merci", "no gracias", "nee bedankt", "no grazie", "nรฃo, obrigado", "falscher Ansprechpartner", "persona sbagliata"). Each phrase is matched as whole words, so "no grazie" never matches inside "buono, grazie". The reply classifier reads these as negative with no call, the same verdict "not interested" and "no thanks" get in English, so they take the `reply_negative` branch. Inbox labels still come from the classifier. -- **Replies that show interest**, in German, French and Spanish ("klingt gut", "lassen Sie uns telefonieren", "รงa m'intรฉresse", "je suis intรฉressรฉ", "me interesa mucho", "agendemos una llamada"), read as positive with no call, the same verdict "interested" and "let's talk" get in English, so they take the `reply_positive` branch and count as interested leads. A reply that also says no in one of these languages ("klingt gut, aber kein Bedarf") stays negative, and a phrase in a sentence that already says "no", "nicht", "pas" and the like ("no me interesa mucho", "je ne crois pas, honnรชtement, que cela nous intรฉresse") does not count, nor does one taken back later by "pero no", "aber nicht", "mais pas" and the like ("me interesa mucho, pero no ahora"). Conditional interest such as "Si cela m'intรฉresse, je vous contacterai", "Sโ€™il sโ€™avรจre que cela nous intรฉresse, nous vous recontacterons" or "Si me interesa mucho, les aviso" stays inconclusive. The accented Spanish affirmation "Sรญ, nos interesa mucho" reads as positive. +- **Replies that show interest**, in German, French and Spanish ("klingt gut", "lassen Sie uns telefonieren", "รงa m'intรฉresse", "je suis intรฉressรฉ", "me interesa mucho", "agendemos una llamada"), read as positive with no call, the same verdict "interested" and "let's talk" get in English, so they take the `reply_positive` branch and count as interested leads. A reply that also says no in one of these languages ("klingt gut, aber kein Bedarf") stays negative, and a phrase in a sentence that already says "no", "nicht", "pas" and the like ("no me interesa mucho", "je ne crois pas, honnรชtement, que cela nous intรฉresse") does not count, nor does one taken back later by "pero no", "aber nicht", "mais pas" and the like ("me interesa mucho, pero no ahora"). Conditional interest such as "Si cela m'intรฉresse, je vous contacterai", "Sโ€™il sโ€™avรจre que cela nous intรฉresse, nous vous recontacterons" or "Si me interesa mucho, les aviso" stays inconclusive. The accented Spanish affirmation "Sรญ, nos interesa mucho" reads as positive. Polite French requests beginning with "sโ€™il vous plaรฎt" or "sโ€™il te plaรฎt" still count as requests. French interest followed by "vraiment pas" or "absolument pas" does not count as positive; "pas mal" keeps its affirmative meaning. Tagging languages are part of the workspace settings, so they travel with a [workspace export](/guides/workspace-export-import/). diff --git a/internal/app/replyclassify/languages.go b/internal/app/replyclassify/languages.go index ee7933f81..daf20a03f 100644 --- a/internal/app/replyclassify/languages.go +++ b/internal/app/replyclassify/languages.go @@ -39,6 +39,8 @@ type langRules struct { // phrases, and never after a negator or condition in its sentence. positiveAsWritten // keeps its accents, where folding would change the meaning. positive, positiveAsWritten []string + // postverbalNegation reads French pas after an interest phrase, including intervening adverbs. + postverbalNegation bool } var baseRules = langRules{ @@ -151,9 +153,10 @@ var languageRules = map[string]langRules{ }, }, "fr": { - quote: []quoteMarker{{re: headerBlock(`de ?`, `envoyรฉ ?|date ?`)}}, - separators: []string{`message d'origine`, `message transfรฉrรฉ`}, - ooo: []string{"absent du bureau", "absente du bureau"}, + postverbalNegation: true, + quote: []quoteMarker{{re: headerBlock(`de ?`, `envoyรฉ ?|date ?`)}}, + separators: []string{`message d'origine`, `message transfรฉrรฉ`}, + ooo: []string{"absent du bureau", "absente du bureau"}, declined: []string{ "pas intรฉressรฉ", "pas intรฉressรฉe", "pas intรฉressรฉs", "pas intรฉressรฉes", "aucun intรฉrรชt", "nous intรฉresse pas", "m'intรฉresse pas", "ne m'intรฉresse plus", "ne nous intรฉresse plus", @@ -467,7 +470,9 @@ type phrase struct { // negatable phrases do not count after a negator or condition in the same sentence. negatable bool // asWritten phrases keep their accents, because folding them changes the meaning ("sรญ" is not "si"). - asWritten bool + asWritten bool + postverbalNegation bool + unlessNextWord string } // negators are the words that, earlier in the sentence, turn an interest phrase around. @@ -482,8 +487,12 @@ func negatedOrConditionalAt(text string, start int) bool { if i := strings.LastIndexAny(head, ".!?;"); i >= 0 { head = head[i+1:] } - for _, word := range strings.FieldsFunc(head, func(r rune) bool { return !unicode.IsLetter(r) && r != '\'' }) { + words := strings.FieldsFunc(head, func(r rune) bool { return !unicode.IsLetter(r) && r != '\'' }) + for i, word := range words { word = strings.Trim(word, "'") + if word == "s'il" && i+2 < len(words) && (words[i+1] == "vous" || words[i+1] == "te") && accentFolder.Replace(strings.Trim(words[i+2], "'")) == "plait" { + continue + } if word == "s'il" || word == "s'ils" { return true } @@ -524,6 +533,21 @@ func refusedAfter(text string, end int) bool { return false } +var frenchPostverbalNegation = regexp.MustCompile(`^\s+(?:(?:vraiment|absolument|franchement|certainement|tellement|beaucoup)\s+)*pas\b(?:\s+(\p{L}+))?`) + +// frenchNegatedAfter keeps post-verbal pas distinct from the affirmative idiom pas mal. +func frenchNegatedAfter(text string, end int) bool { + match := frenchPostverbalNegation.FindStringSubmatch(text[end:]) + return match != nil && match[1] != "mal" +} + +func followedByWord(text string, end int, word string) bool { + tail := strings.TrimLeftFunc(text[end:], unicode.IsSpace) + rest, found := strings.CutPrefix(tail, word) + next, _ := utf8.DecodeRuneInString(rest) + return found && !wordRune(next) +} + // in matches an English base phrase against the text as written and a chosen // language's phrase, whole words only, against its accent-folded form. func (p phrase) in(text, folded string) bool { @@ -542,12 +566,12 @@ func (p phrase) in(text, folded string) bool { start, end := i+j, i+j+len(p.text) before, _ := utf8.DecodeLastRuneInString(text[:start]) after, _ := utf8.DecodeRuneInString(text[end:]) - if !wordRune(before) && !wordRune(after) { + if !wordRune(before) && !wordRune(after) && !(p.unlessNextWord != "" && followedByWord(text, end, p.unlessNextWord)) { originalStart := start if p.negatable && !p.asWritten { originalStart = unfoldedOffset(original, start) } - if !p.negatable || !(negatedOrConditionalAt(original, originalStart) || refusedAfter(text, end)) { + if !p.negatable || !(negatedOrConditionalAt(original, originalStart) || refusedAfter(text, end) || (p.postverbalNegation && frenchNegatedAfter(text, end))) { return true } } @@ -608,13 +632,17 @@ func compileRules(parts []langRules) *ruleSet { rs.bounce = append(rs.bounce, p.bounce...) // parts[0] is always baseRules. for _, d := range p.declined { - rs.declined = append(rs.declined, phrase{text: accentFolder.Replace(strings.ToLower(d)), bounded: i > 0}) + declined := phrase{text: accentFolder.Replace(strings.ToLower(d)), bounded: i > 0} + if p.postverbalNegation && strings.HasSuffix(declined.text, " pas") { + declined.unlessNextWord = "mal" + } + rs.declined = append(rs.declined, declined) } for _, n := range p.negative { rs.negative = append(rs.negative, phrase{text: accentFolder.Replace(strings.ToLower(n)), bounded: i > 0}) } for _, pos := range p.positive { - rs.positive = append(rs.positive, phrase{text: accentFolder.Replace(strings.ToLower(pos)), bounded: i > 0, negatable: i > 0}) + rs.positive = append(rs.positive, phrase{text: accentFolder.Replace(strings.ToLower(pos)), bounded: i > 0, negatable: i > 0, postverbalNegation: p.postverbalNegation}) } for _, pos := range p.positiveAsWritten { rs.positive = append(rs.positive, phrase{text: strings.ToLower(pos), bounded: true, negatable: true, asWritten: true}) diff --git a/internal/app/replyclassify/sentiment_languages_test.go b/internal/app/replyclassify/sentiment_languages_test.go index 16782b7ef..b37e1eb21 100644 --- a/internal/app/replyclassify/sentiment_languages_test.go +++ b/internal/app/replyclassify/sentiment_languages_test.go @@ -202,6 +202,15 @@ func TestInterestedRepliesByLanguage(t *testing.T) { "Nous sommes intรฉressรฉs, prenons rendez-vous.", "Cela semble intรฉressant.", "Envoyez-moi un devis s'il vous plaรฎt.", + "S'il vous plaรฎt, envoyez-moi un devis.", + "Sโ€™il vous plaรฎt, envoyez-moi un devis.", + "S'il vous plait, envoyez-moi un devis.", + "S'il te plaรฎt, envoyez-moi un devis.", + "S'il\nvous plaรฎt, envoyez-moi un devis.", + "Cela nous intรฉresse vraiment pas mal.", + "ร‡a nous intรฉresse pas mal.", + "ร‡a m'intรฉresse pas mal.", + "Je suis intรฉressรฉ, pas de problรจme.", "Ca nous interesse.", }, "es": { @@ -245,6 +254,9 @@ func TestNegatedAndHedgedInterestIsNotPositive(t *testing.T) { "Wir wรคren interessiert, wenn der Preis stimmt.", "Falls Interesse besteht, melden wir uns.", "ร‡a m'intรฉresse pas.", + "Cela nous intรฉresse vraiment pas.", + "ร‡a nous intรฉresse absolument pas.", + "Je suis intรฉressรฉ vraiment pas.", "Cela ne nous intรฉresse plus.", "Je ne suis pas intรฉressรฉ.", "Nous ne sommes pas intรฉressรฉs.", @@ -257,6 +269,8 @@ func TestNegatedAndHedgedInterestIsNotPositive(t *testing.T) { "Si รงa m'intรฉresse, je vous recontacte.", "S'il s'avรจre que cela nous intรฉresse, nous vous recontacterons.", "Sโ€™ils confirment que cela nous intรฉresse, nous vous recontacterons.", + "S'il vous plaรฎt, si cela nous intรฉresse, nous vous recontacterons.", + "S'il vous convient que cela nous intรฉresse, nous vous recontacterons.", "Sรญ, Josรฉ. Si nos interesa mucho, les aviso.", "Sรญ, Mรผller. Si nos interesa mucho, les aviso.", "Sรญ, ร†gir. Si nos interesa mucho, les aviso.", From ae39285262233e369d88775932d183cfd2ac1d66 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sat, 31 Oct 2026 15:22:09 +0100 Subject: [PATCH 040/318] feat: raise golang.org/x/net to v0.62.0, floor follow-redirects at 1.16.2 and seroval at 1.6.11 in the web, admin and forms pnpm overrides, and update tracking's libz-sys to 1.1.31 --- admin/pnpm-lock.yaml | 228 ++++++++++++++++++------------------ admin/pnpm-workspace.yaml | 4 +- forms/pnpm-lock.yaml | 161 ++++++++++++------------- forms/pnpm-workspace.yaml | 2 + go.mod | 12 +- go.sum | 24 ++-- tracking/Cargo.lock | 6 +- web/pnpm-lock.yaml | 240 +++++++++++++++++++------------------- web/pnpm-workspace.yaml | 4 +- 9 files changed, 347 insertions(+), 334 deletions(-) diff --git a/admin/pnpm-lock.yaml b/admin/pnpm-lock.yaml index b4d3e2af2..35e91512c 100644 --- a/admin/pnpm-lock.yaml +++ b/admin/pnpm-lock.yaml @@ -9,8 +9,8 @@ overrides: js-yaml: ^4.3.1 nanoid: ^3.3.17 dompurify: ^3.4.17 - follow-redirects: ^1.16.1 - seroval: ^1.6.3 + follow-redirects: ^1.16.2 + seroval: ^1.6.11 source-map-js: ^1.2.2 importers: @@ -67,7 +67,7 @@ importers: version: 5.103.1(@tanstack/react-query@5.103.1(react@19.3.0))(@types/react@19.3.0)(csstype@3.2.3)(react@19.3.0) axios: specifier: ^1.20.0 - version: 1.20.0 + version: 1.20.0(debug@4.4.3(supports-color@7.2.0))(supports-color@7.2.0) class-variance-authority: specifier: ^0.7.1 version: 0.7.1 @@ -119,7 +119,7 @@ importers: version: 9.39.5 '@sentry/vite-plugin': specifier: ^5.4.0 - version: 5.4.0(rollup@4.65.0) + version: 5.4.0(rollup@4.65.0)(supports-color@7.2.0) '@types/node': specifier: ^24.13.5 version: 24.13.5 @@ -131,22 +131,22 @@ importers: version: 19.3.0(@types/react@19.3.0) '@vitejs/plugin-react': specifier: ^5.2.0 - version: 5.2.0(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) + version: 5.2.0(supports-color@7.2.0)(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) eslint: specifier: ^9.39.5 - version: 9.39.5(jiti@2.7.0) + version: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) eslint-plugin-react-hooks: specifier: ^5.2.0 - version: 5.2.0(eslint@9.39.5(jiti@2.7.0)) + version: 5.2.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)) eslint-plugin-react-refresh: specifier: ^0.4.26 - version: 0.4.26(eslint@9.39.5(jiti@2.7.0)) + version: 0.4.26(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)) globals: specifier: ^16.5.0 version: 16.5.0 jsdom: specifier: ^27.4.0 - version: 27.4.0 + version: 27.4.0(supports-color@7.2.0) tw-animate-css: specifier: ^1.4.0 version: 1.4.0 @@ -155,13 +155,13 @@ importers: version: 5.9.3 typescript-eslint: specifier: ^8.70.0 - version: 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) + version: 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) vite: specifier: ^7.3.7 version: 7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0) vitest: specifier: ^4.1.11 - version: 4.1.11(@types/node@24.13.5)(jsdom@27.4.0)(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) + version: 4.1.11(@types/node@24.13.5)(jsdom@27.4.0(supports-color@7.2.0))(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) packages: @@ -1889,8 +1889,8 @@ packages: flatted@3.4.4: resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==} - follow-redirects@1.16.1: - resolution: {integrity: sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg==} + follow-redirects@1.16.2: + resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==} engines: {node: '>=4.0'} peerDependencies: debug: '*' @@ -2440,11 +2440,11 @@ packages: resolution: {integrity: sha512-HXuLAX2pu/UByPpaeo/TaMfvMIi+1QqIoPJYCcAtU8QkVNwgR6MPlGuCQTErV1JwraaMbYaWVIBX7mppzGLATQ==} engines: {node: '>=10'} peerDependencies: - seroval: ^1.6.3 + seroval: ^1.6.11 - seroval@1.6.8: - resolution: {integrity: sha512-HlSgSAkTk4EqHcje1ptJjfZi1YDv5KbhVJ/d3P7T/nAXua2VmDu+AKDX5VTdFfZf48nDkWB2TKYt0DrCSa+3wg==} - engines: {node: '>=10'} + seroval@1.7.5: + resolution: {integrity: sha512-UdNgpHdq0gVpme5JdQF+S3jNscnjFr4NTwUWOc1qcOa8OuWZmbV0+YX2hsqxkUZshBpHnpxDZfAKVZG2ugbrJA==} + engines: {node: '>=20'} set-cookie-parser@2.7.2: resolution: {integrity: sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==} @@ -2800,20 +2800,20 @@ snapshots: '@babel/compat-data@7.29.7': {} - '@babel/core@7.29.7': + '@babel/core@7.29.7(supports-color@7.2.0)': dependencies: '@babel/code-frame': 7.29.7 '@babel/generator': 7.29.8 '@babel/helper-compilation-targets': 7.29.7 - '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7) + '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7(supports-color@7.2.0))(supports-color@7.2.0) '@babel/helpers': 7.29.7 '@babel/parser': 7.29.8 '@babel/template': 7.29.7 - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@7.2.0) '@babel/types': 7.29.8 '@jridgewell/remapping': 2.3.5 convert-source-map: 2.0.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) gensync: 1.0.0-beta.2 json5: 2.2.3 semver: 6.3.1 @@ -2838,19 +2838,19 @@ snapshots: '@babel/helper-globals@7.29.7': {} - '@babel/helper-module-imports@7.29.7': + '@babel/helper-module-imports@7.29.7(supports-color@7.2.0)': dependencies: - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@7.2.0) '@babel/types': 7.29.8 transitivePeerDependencies: - supports-color - '@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7)': + '@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7(supports-color@7.2.0))(supports-color@7.2.0)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-module-imports': 7.29.7 + '@babel/core': 7.29.7(supports-color@7.2.0) + '@babel/helper-module-imports': 7.29.7(supports-color@7.2.0) '@babel/helper-validator-identifier': 7.29.7 - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@7.2.0) transitivePeerDependencies: - supports-color @@ -2871,14 +2871,14 @@ snapshots: dependencies: '@babel/types': 7.29.8 - '@babel/plugin-transform-react-jsx-self@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-react-jsx-self@7.29.7(@babel/core@7.29.7(supports-color@7.2.0))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@7.2.0) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-react-jsx-source@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-react-jsx-source@7.29.7(@babel/core@7.29.7(supports-color@7.2.0))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@7.2.0) '@babel/helper-plugin-utils': 7.29.7 '@babel/template@7.29.7': @@ -2887,7 +2887,7 @@ snapshots: '@babel/parser': 7.29.8 '@babel/types': 7.29.8 - '@babel/traverse@7.29.8': + '@babel/traverse@7.29.8(supports-color@7.2.0)': dependencies: '@babel/code-frame': 7.29.7 '@babel/generator': 7.29.8 @@ -2895,7 +2895,7 @@ snapshots: '@babel/parser': 7.29.8 '@babel/template': 7.29.7 '@babel/types': 7.29.8 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) transitivePeerDependencies: - supports-color @@ -3011,17 +3011,17 @@ snapshots: '@esbuild/win32-x64@0.28.2': optional: true - '@eslint-community/eslint-utils@4.10.1(eslint@9.39.5(jiti@2.7.0))': + '@eslint-community/eslint-utils@4.10.1(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))': dependencies: - eslint: 9.39.5(jiti@2.7.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) eslint-visitor-keys: 3.4.3 '@eslint-community/regexpp@4.12.2': {} - '@eslint/config-array@0.21.2': + '@eslint/config-array@0.21.2(supports-color@7.2.0)': dependencies: '@eslint/object-schema': 2.1.7 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) minimatch: 3.1.5 transitivePeerDependencies: - supports-color @@ -3034,10 +3034,10 @@ snapshots: dependencies: '@types/json-schema': 7.0.15 - '@eslint/eslintrc@3.3.7': + '@eslint/eslintrc@3.3.7(supports-color@7.2.0)': dependencies: ajv: 6.15.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) espree: 10.4.0 globals: 14.0.0 ignore: 5.3.2 @@ -3656,10 +3656,10 @@ snapshots: '@sentry/replay': 10.75.0 '@sentry/replay-canvas': 10.75.0 - '@sentry/bundler-plugins@10.75.0(rollup@4.65.0)': + '@sentry/bundler-plugins@10.75.0(rollup@4.65.0)(supports-color@7.2.0)': dependencies: - '@babel/core': 7.29.7 - '@sentry/cli': 2.58.6 + '@babel/core': 7.29.7(supports-color@7.2.0) + '@sentry/cli': 2.58.6(supports-color@7.2.0) '@sentry/core': 10.75.0 dotenv: 17.4.2 find-up: 5.0.0 @@ -3695,9 +3695,9 @@ snapshots: '@sentry/cli-win32-x64@2.58.6': optional: true - '@sentry/cli@2.58.6': + '@sentry/cli@2.58.6(supports-color@7.2.0)': dependencies: - https-proxy-agent: 5.0.1 + https-proxy-agent: 5.0.1(supports-color@7.2.0) node-fetch: 2.7.0 progress: 2.0.3 proxy-from-env: 1.1.0 @@ -3742,9 +3742,9 @@ snapshots: '@sentry/browser-utils': 10.75.0 '@sentry/core': 10.75.0 - '@sentry/vite-plugin@5.4.0(rollup@4.65.0)': + '@sentry/vite-plugin@5.4.0(rollup@4.65.0)(supports-color@7.2.0)': dependencies: - '@sentry/bundler-plugins': 10.75.0(rollup@4.65.0) + '@sentry/bundler-plugins': 10.75.0(rollup@4.65.0)(supports-color@7.2.0) transitivePeerDependencies: - encoding - rollup @@ -3976,15 +3976,15 @@ snapshots: '@types/trusted-types@2.0.7': optional: true - '@typescript-eslint/eslint-plugin@8.70.0(@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)': + '@typescript-eslint/eslint-plugin@8.70.0(@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@eslint-community/regexpp': 4.12.2 - '@typescript-eslint/parser': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) + '@typescript-eslint/parser': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/scope-manager': 8.70.0 - '@typescript-eslint/type-utils': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) - '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) + '@typescript-eslint/type-utils': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/visitor-keys': 8.70.0 - eslint: 9.39.5(jiti@2.7.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) ignore: 7.0.9 natural-compare: 1.4.0 ts-api-utils: 2.5.0(typescript@5.9.3) @@ -3992,23 +3992,23 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)': + '@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@typescript-eslint/scope-manager': 8.70.0 '@typescript-eslint/types': 8.70.0 - '@typescript-eslint/typescript-estree': 8.70.0(typescript@5.9.3) + '@typescript-eslint/typescript-estree': 8.70.0(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/visitor-keys': 8.70.0 - debug: 4.4.3 - eslint: 9.39.5(jiti@2.7.0) + debug: 4.4.3(supports-color@7.2.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color - '@typescript-eslint/project-service@8.70.0(typescript@5.9.3)': + '@typescript-eslint/project-service@8.70.0(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@typescript-eslint/tsconfig-utils': 8.70.0(typescript@5.9.3) '@typescript-eslint/types': 8.70.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color @@ -4022,13 +4022,13 @@ snapshots: dependencies: typescript: 5.9.3 - '@typescript-eslint/type-utils@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)': + '@typescript-eslint/type-utils@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@typescript-eslint/types': 8.70.0 - '@typescript-eslint/typescript-estree': 8.70.0(typescript@5.9.3) - '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) - debug: 4.4.3 - eslint: 9.39.5(jiti@2.7.0) + '@typescript-eslint/typescript-estree': 8.70.0(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + debug: 4.4.3(supports-color@7.2.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) ts-api-utils: 2.5.0(typescript@5.9.3) typescript: 5.9.3 transitivePeerDependencies: @@ -4036,13 +4036,13 @@ snapshots: '@typescript-eslint/types@8.70.0': {} - '@typescript-eslint/typescript-estree@8.70.0(typescript@5.9.3)': + '@typescript-eslint/typescript-estree@8.70.0(supports-color@7.2.0)(typescript@5.9.3)': dependencies: - '@typescript-eslint/project-service': 8.70.0(typescript@5.9.3) + '@typescript-eslint/project-service': 8.70.0(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/tsconfig-utils': 8.70.0(typescript@5.9.3) '@typescript-eslint/types': 8.70.0 '@typescript-eslint/visitor-keys': 8.70.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) minimatch: 10.2.6 semver: 7.8.5 tinyglobby: 0.2.17 @@ -4051,13 +4051,13 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/utils@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)': + '@typescript-eslint/utils@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: - '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(jiti@2.7.0)) + '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)) '@typescript-eslint/scope-manager': 8.70.0 '@typescript-eslint/types': 8.70.0 - '@typescript-eslint/typescript-estree': 8.70.0(typescript@5.9.3) - eslint: 9.39.5(jiti@2.7.0) + '@typescript-eslint/typescript-estree': 8.70.0(supports-color@7.2.0)(typescript@5.9.3) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color @@ -4067,11 +4067,11 @@ snapshots: '@typescript-eslint/types': 8.70.0 eslint-visitor-keys: 5.0.1 - '@vitejs/plugin-react@5.2.0(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0))': + '@vitejs/plugin-react@5.2.0(supports-color@7.2.0)(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0))': dependencies: - '@babel/core': 7.29.7 - '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@7.2.0) + '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.7(supports-color@7.2.0)) + '@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/core@7.29.7(supports-color@7.2.0)) '@rolldown/pluginutils': 1.0.0-rc.3 '@types/babel__core': 7.20.5 react-refresh: 0.18.0 @@ -4126,9 +4126,9 @@ snapshots: acorn@8.18.0: {} - agent-base@6.0.2: + agent-base@6.0.2(supports-color@7.2.0): dependencies: - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) transitivePeerDependencies: - supports-color @@ -4155,11 +4155,11 @@ snapshots: asynckit@0.4.0: {} - axios@1.20.0: + axios@1.20.0(debug@4.4.3(supports-color@7.2.0))(supports-color@7.2.0): dependencies: - follow-redirects: 1.16.1 + follow-redirects: 1.16.2(debug@4.4.3(supports-color@7.2.0)) form-data: 4.0.6 - https-proxy-agent: 5.0.1 + https-proxy-agent: 5.0.1(supports-color@7.2.0) proxy-from-env: 2.1.0 transitivePeerDependencies: - debug @@ -4273,9 +4273,11 @@ snapshots: date-fns@4.4.0: {} - debug@4.4.3: + debug@4.4.3(supports-color@7.2.0): dependencies: ms: 2.1.3 + optionalDependencies: + supports-color: 7.2.0 decimal.js@10.6.0: {} @@ -4358,13 +4360,13 @@ snapshots: escape-string-regexp@4.0.0: {} - eslint-plugin-react-hooks@5.2.0(eslint@9.39.5(jiti@2.7.0)): + eslint-plugin-react-hooks@5.2.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)): dependencies: - eslint: 9.39.5(jiti@2.7.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) - eslint-plugin-react-refresh@0.4.26(eslint@9.39.5(jiti@2.7.0)): + eslint-plugin-react-refresh@0.4.26(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)): dependencies: - eslint: 9.39.5(jiti@2.7.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) eslint-scope@8.4.0: dependencies: @@ -4377,14 +4379,14 @@ snapshots: eslint-visitor-keys@5.0.1: {} - eslint@9.39.5(jiti@2.7.0): + eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0): dependencies: - '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(jiti@2.7.0)) + '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)) '@eslint-community/regexpp': 4.12.2 - '@eslint/config-array': 0.21.2 + '@eslint/config-array': 0.21.2(supports-color@7.2.0) '@eslint/config-helpers': 0.4.2 '@eslint/core': 0.17.0 - '@eslint/eslintrc': 3.3.7 + '@eslint/eslintrc': 3.3.7(supports-color@7.2.0) '@eslint/js': 9.39.5 '@eslint/plugin-kit': 0.4.1 '@humanfs/node': 0.16.8 @@ -4394,7 +4396,7 @@ snapshots: ajv: 6.15.0 chalk: 4.1.2 cross-spawn: 7.0.6 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) escape-string-regexp: 4.0.0 eslint-scope: 8.4.0 eslint-visitor-keys: 4.2.1 @@ -4470,7 +4472,9 @@ snapshots: flatted@3.4.4: {} - follow-redirects@1.16.1: {} + follow-redirects@1.16.2(debug@4.4.3(supports-color@7.2.0)): + optionalDependencies: + debug: 4.4.3(supports-color@7.2.0) form-data@4.0.6: dependencies: @@ -4556,24 +4560,24 @@ snapshots: transitivePeerDependencies: - '@noble/hashes' - http-proxy-agent@7.0.2: + http-proxy-agent@7.0.2(supports-color@7.2.0): dependencies: agent-base: 7.1.4 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) transitivePeerDependencies: - supports-color - https-proxy-agent@5.0.1: + https-proxy-agent@5.0.1(supports-color@7.2.0): dependencies: - agent-base: 6.0.2 - debug: 4.4.3 + agent-base: 6.0.2(supports-color@7.2.0) + debug: 4.4.3(supports-color@7.2.0) transitivePeerDependencies: - supports-color - https-proxy-agent@7.0.6: + https-proxy-agent@7.0.6(supports-color@7.2.0): dependencies: agent-base: 7.1.4 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) transitivePeerDependencies: - supports-color @@ -4611,7 +4615,7 @@ snapshots: dependencies: argparse: 2.0.1 - jsdom@27.4.0: + jsdom@27.4.0(supports-color@7.2.0): dependencies: '@acemir/cssom': 0.9.31 '@asamuzakjp/dom-selector': 6.8.1 @@ -4620,8 +4624,8 @@ snapshots: data-urls: 6.0.1 decimal.js: 10.6.0 html-encoding-sniffer: 6.0.0 - http-proxy-agent: 7.0.2 - https-proxy-agent: 7.0.6 + http-proxy-agent: 7.0.2(supports-color@7.2.0) + https-proxy-agent: 7.0.6(supports-color@7.2.0) is-potential-custom-element-name: 1.0.1 parse5: 8.0.1 saxes: 6.0.0 @@ -4956,11 +4960,11 @@ snapshots: semver@7.8.5: {} - seroval-plugins@1.5.6(seroval@1.6.8): + seroval-plugins@1.5.6(seroval@1.7.5): dependencies: - seroval: 1.6.8 + seroval: 1.7.5 - seroval@1.6.8: {} + seroval@1.7.5: {} set-cookie-parser@2.7.2: {} @@ -4975,8 +4979,8 @@ snapshots: solid-js@1.9.15: dependencies: csstype: 3.2.3 - seroval: 1.6.8 - seroval-plugins: 1.5.6(seroval@1.6.8) + seroval: 1.7.5 + seroval-plugins: 1.5.6(seroval@1.7.5) solid-presence@0.2.0(solid-js@1.9.15): dependencies: @@ -5064,13 +5068,13 @@ snapshots: dependencies: prelude-ls: 1.2.1 - typescript-eslint@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3): + typescript-eslint@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3): dependencies: - '@typescript-eslint/eslint-plugin': 8.70.0(@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) - '@typescript-eslint/parser': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) - '@typescript-eslint/typescript-estree': 8.70.0(typescript@5.9.3) - '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) - eslint: 9.39.5(jiti@2.7.0) + '@typescript-eslint/eslint-plugin': 8.70.0(@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/parser': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/typescript-estree': 8.70.0(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color @@ -5118,7 +5122,7 @@ snapshots: jiti: 2.7.0 lightningcss: 1.32.0 - vitest@4.1.11(@types/node@24.13.5)(jsdom@27.4.0)(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)): + vitest@4.1.11(@types/node@24.13.5)(jsdom@27.4.0(supports-color@7.2.0))(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)): dependencies: '@vitest/expect': 4.1.11 '@vitest/mocker': 4.1.11(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) @@ -5142,7 +5146,7 @@ snapshots: why-is-node-running: 2.3.0 optionalDependencies: '@types/node': 24.13.5 - jsdom: 27.4.0 + jsdom: 27.4.0(supports-color@7.2.0) transitivePeerDependencies: - msw diff --git a/admin/pnpm-workspace.yaml b/admin/pnpm-workspace.yaml index 0f9721193..d8c27bd41 100644 --- a/admin/pnpm-workspace.yaml +++ b/admin/pnpm-workspace.yaml @@ -20,6 +20,6 @@ overrides: js-yaml: ^4.3.1 nanoid: ^3.3.17 dompurify: ^3.4.17 - follow-redirects: ^1.16.1 - seroval: ^1.6.3 + follow-redirects: ^1.16.2 + seroval: ^1.6.11 source-map-js: ^1.2.2 diff --git a/forms/pnpm-lock.yaml b/forms/pnpm-lock.yaml index 78840a35e..217c5e1d7 100644 --- a/forms/pnpm-lock.yaml +++ b/forms/pnpm-lock.yaml @@ -6,6 +6,7 @@ settings: overrides: dompurify: ^3.4.17 + seroval: ^1.6.11 importers: @@ -47,16 +48,16 @@ importers: version: 19.2.5(@types/react@19.2.18) '@vitejs/plugin-react': specifier: ^5.0.4 - version: 5.2.0(vite@7.3.7(@types/node@24.13.3)) + version: 5.2.0(supports-color@7.2.0)(vite@7.3.7(@types/node@24.13.3)) eslint: specifier: ^9.36.0 - version: 9.39.5 + version: 9.39.5(supports-color@7.2.0) eslint-plugin-react-hooks: specifier: ^5.2.0 - version: 5.2.0(eslint@9.39.5) + version: 5.2.0(eslint@9.39.5(supports-color@7.2.0)) eslint-plugin-react-refresh: specifier: ^0.4.22 - version: 0.4.26(eslint@9.39.5) + version: 0.4.26(eslint@9.39.5(supports-color@7.2.0)) globals: specifier: ^16.4.0 version: 16.5.0 @@ -65,7 +66,7 @@ importers: version: 5.9.3 typescript-eslint: specifier: ^8.45.0 - version: 8.68.0(eslint@9.39.5)(typescript@5.9.3) + version: 8.68.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) vite: specifier: ^7.3.7 version: 7.3.7(@types/node@24.13.3) @@ -1159,11 +1160,11 @@ packages: resolution: {integrity: sha512-R0f1U9hmn38+dFMz6b6ab8lwucmw4AtiY7St+JPWudy1dm+Bs3g884nyrsH9Cy6rKpZKLYayXuMda9GZ/fl8JQ==} engines: {node: '>=10'} peerDependencies: - seroval: ^1.0 + seroval: ^1.6.11 - seroval@1.6.4: - resolution: {integrity: sha512-LErWMNS2RRFdu2RMA5u/PA59/IWs0XsikyEXGQ2/36iEWFrdG0ABmg17E17cikrv76891kOAMq3TkTFXpwAHXw==} - engines: {node: '>=10'} + seroval@1.7.5: + resolution: {integrity: sha512-UdNgpHdq0gVpme5JdQF+S3jNscnjFr4NTwUWOc1qcOa8OuWZmbV0+YX2hsqxkUZshBpHnpxDZfAKVZG2ugbrJA==} + engines: {node: '>=20'} shebang-command@2.0.0: resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} @@ -1297,20 +1298,20 @@ snapshots: '@babel/compat-data@7.29.7': {} - '@babel/core@7.29.7': + '@babel/core@7.29.7(supports-color@7.2.0)': dependencies: '@babel/code-frame': 7.29.7 '@babel/generator': 7.29.8 '@babel/helper-compilation-targets': 7.29.7 - '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7) + '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7(supports-color@7.2.0))(supports-color@7.2.0) '@babel/helpers': 7.29.7 '@babel/parser': 7.29.8 '@babel/template': 7.29.7 - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@7.2.0) '@babel/types': 7.29.8 '@jridgewell/remapping': 2.3.5 convert-source-map: 2.0.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) gensync: 1.0.0-beta.2 json5: 2.2.3 semver: 6.3.1 @@ -1335,19 +1336,19 @@ snapshots: '@babel/helper-globals@7.29.7': {} - '@babel/helper-module-imports@7.29.7': + '@babel/helper-module-imports@7.29.7(supports-color@7.2.0)': dependencies: - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@7.2.0) '@babel/types': 7.29.8 transitivePeerDependencies: - supports-color - '@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7)': + '@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7(supports-color@7.2.0))(supports-color@7.2.0)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-module-imports': 7.29.7 + '@babel/core': 7.29.7(supports-color@7.2.0) + '@babel/helper-module-imports': 7.29.7(supports-color@7.2.0) '@babel/helper-validator-identifier': 7.29.7 - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@7.2.0) transitivePeerDependencies: - supports-color @@ -1368,14 +1369,14 @@ snapshots: dependencies: '@babel/types': 7.29.8 - '@babel/plugin-transform-react-jsx-self@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-react-jsx-self@7.29.7(@babel/core@7.29.7(supports-color@7.2.0))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@7.2.0) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-react-jsx-source@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-react-jsx-source@7.29.7(@babel/core@7.29.7(supports-color@7.2.0))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@7.2.0) '@babel/helper-plugin-utils': 7.29.7 '@babel/template@7.29.7': @@ -1384,7 +1385,7 @@ snapshots: '@babel/parser': 7.29.8 '@babel/types': 7.29.8 - '@babel/traverse@7.29.8': + '@babel/traverse@7.29.8(supports-color@7.2.0)': dependencies: '@babel/code-frame': 7.29.7 '@babel/generator': 7.29.8 @@ -1392,7 +1393,7 @@ snapshots: '@babel/parser': 7.29.8 '@babel/template': 7.29.7 '@babel/types': 7.29.8 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) transitivePeerDependencies: - supports-color @@ -1479,17 +1480,17 @@ snapshots: '@esbuild/win32-x64@0.28.2': optional: true - '@eslint-community/eslint-utils@4.10.1(eslint@9.39.5)': + '@eslint-community/eslint-utils@4.10.1(eslint@9.39.5(supports-color@7.2.0))': dependencies: - eslint: 9.39.5 + eslint: 9.39.5(supports-color@7.2.0) eslint-visitor-keys: 3.4.3 '@eslint-community/regexpp@4.12.2': {} - '@eslint/config-array@0.21.2': + '@eslint/config-array@0.21.2(supports-color@7.2.0)': dependencies: '@eslint/object-schema': 2.1.7 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) minimatch: 3.1.5 transitivePeerDependencies: - supports-color @@ -1502,10 +1503,10 @@ snapshots: dependencies: '@types/json-schema': 7.0.15 - '@eslint/eslintrc@3.3.6': + '@eslint/eslintrc@3.3.6(supports-color@7.2.0)': dependencies: ajv: 6.15.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) espree: 10.4.0 globals: 14.0.0 ignore: 5.3.2 @@ -1739,8 +1740,8 @@ snapshots: dependencies: '@tanstack/history': 1.162.1 cookie-es: 3.1.1 - seroval: 1.6.4 - seroval-plugins: 1.6.4(seroval@1.6.4) + seroval: 1.7.5 + seroval-plugins: 1.6.4(seroval@1.7.5) '@tanstack/store@0.11.1': {} @@ -1786,15 +1787,15 @@ snapshots: '@types/trusted-types@2.0.7': optional: true - '@typescript-eslint/eslint-plugin@8.68.0(@typescript-eslint/parser@8.68.0(eslint@9.39.5)(typescript@5.9.3))(eslint@9.39.5)(typescript@5.9.3)': + '@typescript-eslint/eslint-plugin@8.68.0(@typescript-eslint/parser@8.68.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3))(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@eslint-community/regexpp': 4.12.2 - '@typescript-eslint/parser': 8.68.0(eslint@9.39.5)(typescript@5.9.3) + '@typescript-eslint/parser': 8.68.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/scope-manager': 8.68.0 - '@typescript-eslint/type-utils': 8.68.0(eslint@9.39.5)(typescript@5.9.3) - '@typescript-eslint/utils': 8.68.0(eslint@9.39.5)(typescript@5.9.3) + '@typescript-eslint/type-utils': 8.68.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/utils': 8.68.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/visitor-keys': 8.68.0 - eslint: 9.39.5 + eslint: 9.39.5(supports-color@7.2.0) ignore: 7.0.7 natural-compare: 1.4.0 ts-api-utils: 2.5.0(typescript@5.9.3) @@ -1802,23 +1803,23 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/parser@8.68.0(eslint@9.39.5)(typescript@5.9.3)': + '@typescript-eslint/parser@8.68.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@typescript-eslint/scope-manager': 8.68.0 '@typescript-eslint/types': 8.68.0 - '@typescript-eslint/typescript-estree': 8.68.0(typescript@5.9.3) + '@typescript-eslint/typescript-estree': 8.68.0(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/visitor-keys': 8.68.0 - debug: 4.4.3 - eslint: 9.39.5 + debug: 4.4.3(supports-color@7.2.0) + eslint: 9.39.5(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color - '@typescript-eslint/project-service@8.68.0(typescript@5.9.3)': + '@typescript-eslint/project-service@8.68.0(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@typescript-eslint/tsconfig-utils': 8.68.0(typescript@5.9.3) '@typescript-eslint/types': 8.68.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color @@ -1832,13 +1833,13 @@ snapshots: dependencies: typescript: 5.9.3 - '@typescript-eslint/type-utils@8.68.0(eslint@9.39.5)(typescript@5.9.3)': + '@typescript-eslint/type-utils@8.68.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@typescript-eslint/types': 8.68.0 - '@typescript-eslint/typescript-estree': 8.68.0(typescript@5.9.3) - '@typescript-eslint/utils': 8.68.0(eslint@9.39.5)(typescript@5.9.3) - debug: 4.4.3 - eslint: 9.39.5 + '@typescript-eslint/typescript-estree': 8.68.0(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/utils': 8.68.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + debug: 4.4.3(supports-color@7.2.0) + eslint: 9.39.5(supports-color@7.2.0) ts-api-utils: 2.5.0(typescript@5.9.3) typescript: 5.9.3 transitivePeerDependencies: @@ -1846,13 +1847,13 @@ snapshots: '@typescript-eslint/types@8.68.0': {} - '@typescript-eslint/typescript-estree@8.68.0(typescript@5.9.3)': + '@typescript-eslint/typescript-estree@8.68.0(supports-color@7.2.0)(typescript@5.9.3)': dependencies: - '@typescript-eslint/project-service': 8.68.0(typescript@5.9.3) + '@typescript-eslint/project-service': 8.68.0(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/tsconfig-utils': 8.68.0(typescript@5.9.3) '@typescript-eslint/types': 8.68.0 '@typescript-eslint/visitor-keys': 8.68.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) minimatch: 10.2.6 semver: 7.8.5 tinyglobby: 0.2.17 @@ -1861,13 +1862,13 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/utils@8.68.0(eslint@9.39.5)(typescript@5.9.3)': + '@typescript-eslint/utils@8.68.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: - '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5) + '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(supports-color@7.2.0)) '@typescript-eslint/scope-manager': 8.68.0 '@typescript-eslint/types': 8.68.0 - '@typescript-eslint/typescript-estree': 8.68.0(typescript@5.9.3) - eslint: 9.39.5 + '@typescript-eslint/typescript-estree': 8.68.0(supports-color@7.2.0)(typescript@5.9.3) + eslint: 9.39.5(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color @@ -1877,11 +1878,11 @@ snapshots: '@typescript-eslint/types': 8.68.0 eslint-visitor-keys: 5.0.1 - '@vitejs/plugin-react@5.2.0(vite@7.3.7(@types/node@24.13.3))': + '@vitejs/plugin-react@5.2.0(supports-color@7.2.0)(vite@7.3.7(@types/node@24.13.3))': dependencies: - '@babel/core': 7.29.7 - '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@7.2.0) + '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.7(supports-color@7.2.0)) + '@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/core@7.29.7(supports-color@7.2.0)) '@rolldown/pluginutils': 1.0.0-rc.3 '@types/babel__core': 7.20.5 react-refresh: 0.18.0 @@ -1962,9 +1963,11 @@ snapshots: csstype@3.2.3: {} - debug@4.4.3: + debug@4.4.3(supports-color@7.2.0): dependencies: ms: 2.1.3 + optionalDependencies: + supports-color: 7.2.0 deep-is@0.1.4: {} @@ -2007,13 +2010,13 @@ snapshots: escape-string-regexp@4.0.0: {} - eslint-plugin-react-hooks@5.2.0(eslint@9.39.5): + eslint-plugin-react-hooks@5.2.0(eslint@9.39.5(supports-color@7.2.0)): dependencies: - eslint: 9.39.5 + eslint: 9.39.5(supports-color@7.2.0) - eslint-plugin-react-refresh@0.4.26(eslint@9.39.5): + eslint-plugin-react-refresh@0.4.26(eslint@9.39.5(supports-color@7.2.0)): dependencies: - eslint: 9.39.5 + eslint: 9.39.5(supports-color@7.2.0) eslint-scope@8.4.0: dependencies: @@ -2026,14 +2029,14 @@ snapshots: eslint-visitor-keys@5.0.1: {} - eslint@9.39.5: + eslint@9.39.5(supports-color@7.2.0): dependencies: - '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5) + '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(supports-color@7.2.0)) '@eslint-community/regexpp': 4.12.2 - '@eslint/config-array': 0.21.2 + '@eslint/config-array': 0.21.2(supports-color@7.2.0) '@eslint/config-helpers': 0.4.2 '@eslint/core': 0.17.0 - '@eslint/eslintrc': 3.3.6 + '@eslint/eslintrc': 3.3.6(supports-color@7.2.0) '@eslint/js': 9.39.5 '@eslint/plugin-kit': 0.4.1 '@humanfs/node': 0.16.8 @@ -2043,7 +2046,7 @@ snapshots: ajv: 6.15.0 chalk: 4.1.2 cross-spawn: 7.0.6 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) escape-string-regexp: 4.0.0 eslint-scope: 8.4.0 eslint-visitor-keys: 4.2.1 @@ -2308,11 +2311,11 @@ snapshots: semver@7.8.5: {} - seroval-plugins@1.6.4(seroval@1.6.4): + seroval-plugins@1.6.4(seroval@1.7.5): dependencies: - seroval: 1.6.4 + seroval: 1.7.5 - seroval@1.6.4: {} + seroval@1.7.5: {} shebang-command@2.0.0: dependencies: @@ -2341,13 +2344,13 @@ snapshots: dependencies: prelude-ls: 1.2.1 - typescript-eslint@8.68.0(eslint@9.39.5)(typescript@5.9.3): + typescript-eslint@8.68.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3): dependencies: - '@typescript-eslint/eslint-plugin': 8.68.0(@typescript-eslint/parser@8.68.0(eslint@9.39.5)(typescript@5.9.3))(eslint@9.39.5)(typescript@5.9.3) - '@typescript-eslint/parser': 8.68.0(eslint@9.39.5)(typescript@5.9.3) - '@typescript-eslint/typescript-estree': 8.68.0(typescript@5.9.3) - '@typescript-eslint/utils': 8.68.0(eslint@9.39.5)(typescript@5.9.3) - eslint: 9.39.5 + '@typescript-eslint/eslint-plugin': 8.68.0(@typescript-eslint/parser@8.68.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3))(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/parser': 8.68.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/typescript-estree': 8.68.0(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/utils': 8.68.0(eslint@9.39.5(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + eslint: 9.39.5(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color diff --git a/forms/pnpm-workspace.yaml b/forms/pnpm-workspace.yaml index e0208ac8e..c67adf334 100644 --- a/forms/pnpm-workspace.yaml +++ b/forms/pnpm-workspace.yaml @@ -9,3 +9,5 @@ allowBuilds: overrides: dompurify: ^3.4.17 + # Floor transitive dependencies at their patched releases. + seroval: ^1.6.11 diff --git a/go.mod b/go.mod index 2286e68e4..9ad8e5fb2 100644 --- a/go.mod +++ b/go.mod @@ -52,14 +52,14 @@ require ( github.com/stripe/stripe-go/v86 v86.4.2 github.com/xuri/excelize/v2 v2.11.1-0.20261003002531-6258dcebc4e2 go.uber.org/zap v1.27.0 - golang.org/x/crypto v0.57.0 + golang.org/x/crypto v0.58.0 golang.org/x/image v0.45.0 golang.org/x/mod v0.41.0 - golang.org/x/net v0.60.0 + golang.org/x/net v0.62.0 golang.org/x/oauth2 v0.36.0 - golang.org/x/sync v0.23.0 - golang.org/x/term v0.46.0 - golang.org/x/text v0.42.0 + golang.org/x/sync v0.24.0 + golang.org/x/term v0.47.0 + golang.org/x/text v0.43.0 google.golang.org/api v0.264.0 google.golang.org/grpc v1.83.2 google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.6.1 @@ -167,7 +167,7 @@ require ( go.uber.org/multierr v1.11.0 // indirect golang.org/x/arch v0.19.0 // indirect golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 // indirect - golang.org/x/sys v0.48.0 // indirect + golang.org/x/sys v0.49.0 // indirect golang.org/x/time v0.15.0 // indirect google.golang.org/genproto v0.0.0-20260128011058-8636f8732409 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect diff --git a/go.sum b/go.sum index 82752c318..949ebecb3 100644 --- a/go.sum +++ b/go.sum @@ -688,8 +688,8 @@ golang.org/x/arch v0.19.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= -golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= +golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 h1:e66Fs6Z+fZTbFBAxKfP3PALWBtpfqks2bwGcexMxgtk= golang.org/x/exp v0.0.0-20240909161429-701f63a606c0/go.mod h1:2TbTHSBQa924w8M6Xs1QcRcFwyucIwBGpK1p2f1YFFY= @@ -712,8 +712,8 @@ golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwY golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= -golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= @@ -722,8 +722,8 @@ golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= -golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -738,20 +738,20 @@ golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= -golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE= -golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= +golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM= +golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= -golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= diff --git a/tracking/Cargo.lock b/tracking/Cargo.lock index 54cf47a27..9cb431094 100644 --- a/tracking/Cargo.lock +++ b/tracking/Cargo.lock @@ -2028,9 +2028,9 @@ checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" [[package]] name = "libz-sys" -version = "1.1.29" +version = "1.1.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85bc9657773828b90eeb625adff10eeac83cc21bbfd8e23a03eaa8a33c9e28d9" +checksum = "ff20308ecabd635a2dc1dd5834a86c462cca20efba1d5d3ddab1f8aea3455cb2" dependencies = [ "cc", "libc", @@ -3698,7 +3698,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix", "windows-sys 0.61.2", diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yaml index 913b65214..a228b753a 100644 --- a/web/pnpm-lock.yaml +++ b/web/pnpm-lock.yaml @@ -10,8 +10,8 @@ overrides: js-yaml: ^4.3.1 nanoid: ^3.3.17 dompurify: ^3.4.17 - follow-redirects: ^1.16.1 - seroval: ^1.6.3 + follow-redirects: ^1.16.2 + seroval: ^1.6.11 source-map-js: ^1.2.2 importers: @@ -200,7 +200,7 @@ importers: version: 3.0.2 axios: specifier: ^1.20.0 - version: 1.20.0 + version: 1.20.0(debug@4.4.3(supports-color@7.2.0))(supports-color@7.2.0) class-variance-authority: specifier: ^0.7.1 version: 0.7.1 @@ -285,7 +285,7 @@ importers: version: 9.39.5 '@sentry/vite-plugin': specifier: ^5.4.0 - version: 5.4.0(rollup@4.65.0) + version: 5.4.0(rollup@4.65.0)(supports-color@7.2.0) '@testing-library/jest-dom': specifier: ^6.10.0 version: 6.10.0(@testing-library/dom@10.4.1) @@ -303,25 +303,25 @@ importers: version: 19.3.0(@types/react@19.3.0) '@vitejs/plugin-react': specifier: ^5.2.0 - version: 5.2.0(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) + version: 5.2.0(supports-color@7.2.0)(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) '@vitest/coverage-v8': specifier: ^4.1.11 version: 4.1.11(vitest@4.1.11) eslint: specifier: ^9.39.5 - version: 9.39.5(jiti@2.7.0) + version: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) eslint-plugin-react-hooks: specifier: ^5.2.0 - version: 5.2.0(eslint@9.39.5(jiti@2.7.0)) + version: 5.2.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)) eslint-plugin-react-refresh: specifier: ^0.4.26 - version: 0.4.26(eslint@9.39.5(jiti@2.7.0)) + version: 0.4.26(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)) globals: specifier: ^16.5.0 version: 16.5.0 jsdom: specifier: ^27.4.0 - version: 27.4.0 + version: 27.4.0(supports-color@7.2.0) tw-animate-css: specifier: ^1.4.0 version: 1.4.0 @@ -330,13 +330,13 @@ importers: version: 5.9.3 typescript-eslint: specifier: ^8.70.0 - version: 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) + version: 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) vite: specifier: ^7.3.7 version: 7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0) vitest: specifier: ^4.1.11 - version: 4.1.11(@types/node@24.13.5)(@vitest/coverage-v8@4.1.11)(jsdom@27.4.0)(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) + version: 4.1.11(@types/node@24.13.5)(@vitest/coverage-v8@4.1.11)(jsdom@27.4.0(supports-color@7.2.0))(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) packages: @@ -2559,8 +2559,8 @@ packages: flatted@3.4.4: resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==} - follow-redirects@1.16.1: - resolution: {integrity: sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg==} + follow-redirects@1.16.2: + resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==} engines: {node: '>=4.0'} peerDependencies: debug: '*' @@ -3233,17 +3233,17 @@ packages: resolution: {integrity: sha512-HXuLAX2pu/UByPpaeo/TaMfvMIi+1QqIoPJYCcAtU8QkVNwgR6MPlGuCQTErV1JwraaMbYaWVIBX7mppzGLATQ==} engines: {node: '>=10'} peerDependencies: - seroval: ^1.6.3 + seroval: ^1.6.11 seroval-plugins@1.6.8: resolution: {integrity: sha512-N7mWAMydj89EnYTHtRpS3LBrAz3J9O6oVrqpuXuvlAHfAUG8WEKqtbAd7SBiJNY5NfCAFhSdyAh7wI4Shjqy4g==} engines: {node: '>=10'} peerDependencies: - seroval: ^1.6.3 + seroval: ^1.6.11 - seroval@1.6.8: - resolution: {integrity: sha512-HlSgSAkTk4EqHcje1ptJjfZi1YDv5KbhVJ/d3P7T/nAXua2VmDu+AKDX5VTdFfZf48nDkWB2TKYt0DrCSa+3wg==} - engines: {node: '>=10'} + seroval@1.7.5: + resolution: {integrity: sha512-UdNgpHdq0gVpme5JdQF+S3jNscnjFr4NTwUWOc1qcOa8OuWZmbV0+YX2hsqxkUZshBpHnpxDZfAKVZG2ugbrJA==} + engines: {node: '>=20'} shebang-command@2.0.0: resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} @@ -3634,20 +3634,20 @@ snapshots: '@babel/compat-data@7.29.7': {} - '@babel/core@7.29.7': + '@babel/core@7.29.7(supports-color@7.2.0)': dependencies: '@babel/code-frame': 7.29.7 '@babel/generator': 7.29.8 '@babel/helper-compilation-targets': 7.29.7 - '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7) + '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7(supports-color@7.2.0))(supports-color@7.2.0) '@babel/helpers': 7.29.7 '@babel/parser': 7.29.8 '@babel/template': 7.29.7 - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@7.2.0) '@babel/types': 7.29.8 '@jridgewell/remapping': 2.3.5 convert-source-map: 2.0.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) gensync: 1.0.0-beta.2 json5: 2.2.3 semver: 6.3.1 @@ -3672,19 +3672,19 @@ snapshots: '@babel/helper-globals@7.29.7': {} - '@babel/helper-module-imports@7.29.7': + '@babel/helper-module-imports@7.29.7(supports-color@7.2.0)': dependencies: - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@7.2.0) '@babel/types': 7.29.8 transitivePeerDependencies: - supports-color - '@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7)': + '@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7(supports-color@7.2.0))(supports-color@7.2.0)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-module-imports': 7.29.7 + '@babel/core': 7.29.7(supports-color@7.2.0) + '@babel/helper-module-imports': 7.29.7(supports-color@7.2.0) '@babel/helper-validator-identifier': 7.29.7 - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@7.2.0) transitivePeerDependencies: - supports-color @@ -3705,14 +3705,14 @@ snapshots: dependencies: '@babel/types': 7.29.8 - '@babel/plugin-transform-react-jsx-self@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-react-jsx-self@7.29.7(@babel/core@7.29.7(supports-color@7.2.0))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@7.2.0) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-react-jsx-source@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-react-jsx-source@7.29.7(@babel/core@7.29.7(supports-color@7.2.0))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@7.2.0) '@babel/helper-plugin-utils': 7.29.7 '@babel/runtime@7.29.10': {} @@ -3725,7 +3725,7 @@ snapshots: '@babel/parser': 7.29.8 '@babel/types': 7.29.8 - '@babel/traverse@7.29.8': + '@babel/traverse@7.29.8(supports-color@7.2.0)': dependencies: '@babel/code-frame': 7.29.7 '@babel/generator': 7.29.8 @@ -3733,7 +3733,7 @@ snapshots: '@babel/parser': 7.29.8 '@babel/template': 7.29.7 '@babel/types': 7.29.8 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) transitivePeerDependencies: - supports-color @@ -3876,17 +3876,17 @@ snapshots: '@esbuild/win32-x64@0.28.2': optional: true - '@eslint-community/eslint-utils@4.10.1(eslint@9.39.5(jiti@2.7.0))': + '@eslint-community/eslint-utils@4.10.1(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))': dependencies: - eslint: 9.39.5(jiti@2.7.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) eslint-visitor-keys: 3.4.3 '@eslint-community/regexpp@4.12.2': {} - '@eslint/config-array@0.21.2': + '@eslint/config-array@0.21.2(supports-color@7.2.0)': dependencies: '@eslint/object-schema': 2.1.7 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) minimatch: 3.1.5 transitivePeerDependencies: - supports-color @@ -3899,10 +3899,10 @@ snapshots: dependencies: '@types/json-schema': 7.0.15 - '@eslint/eslintrc@3.3.7': + '@eslint/eslintrc@3.3.7(supports-color@7.2.0)': dependencies: ajv: 6.15.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) espree: 10.4.0 globals: 14.0.0 ignore: 5.3.2 @@ -4669,10 +4669,10 @@ snapshots: '@sentry/replay': 10.75.0 '@sentry/replay-canvas': 10.75.0 - '@sentry/bundler-plugins@10.75.0(rollup@4.65.0)': + '@sentry/bundler-plugins@10.75.0(rollup@4.65.0)(supports-color@7.2.0)': dependencies: - '@babel/core': 7.29.7 - '@sentry/cli': 2.58.6 + '@babel/core': 7.29.7(supports-color@7.2.0) + '@sentry/cli': 2.58.6(supports-color@7.2.0) '@sentry/core': 10.75.0 dotenv: 17.4.2 find-up: 5.0.0 @@ -4708,9 +4708,9 @@ snapshots: '@sentry/cli-win32-x64@2.58.6': optional: true - '@sentry/cli@2.58.6': + '@sentry/cli@2.58.6(supports-color@7.2.0)': dependencies: - https-proxy-agent: 5.0.1 + https-proxy-agent: 5.0.1(supports-color@7.2.0) node-fetch: 2.7.0 progress: 2.0.3 proxy-from-env: 1.1.0 @@ -4755,9 +4755,9 @@ snapshots: '@sentry/browser-utils': 10.75.0 '@sentry/core': 10.75.0 - '@sentry/vite-plugin@5.4.0(rollup@4.65.0)': + '@sentry/vite-plugin@5.4.0(rollup@4.65.0)(supports-color@7.2.0)': dependencies: - '@sentry/bundler-plugins': 10.75.0(rollup@4.65.0) + '@sentry/bundler-plugins': 10.75.0(rollup@4.65.0)(supports-color@7.2.0) transitivePeerDependencies: - encoding - rollup @@ -4968,8 +4968,8 @@ snapshots: dependencies: '@tanstack/history': 1.162.4 cookie-es: 3.1.1 - seroval: 1.6.8 - seroval-plugins: 1.6.8(seroval@1.6.8) + seroval: 1.7.5 + seroval-plugins: 1.6.8(seroval@1.7.5) '@tanstack/store@0.11.2': {} @@ -5197,15 +5197,15 @@ snapshots: '@types/use-sync-external-store@0.0.6': {} - '@typescript-eslint/eslint-plugin@8.70.0(@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)': + '@typescript-eslint/eslint-plugin@8.70.0(@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@eslint-community/regexpp': 4.12.2 - '@typescript-eslint/parser': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) + '@typescript-eslint/parser': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/scope-manager': 8.70.0 - '@typescript-eslint/type-utils': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) - '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) + '@typescript-eslint/type-utils': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/visitor-keys': 8.70.0 - eslint: 9.39.5(jiti@2.7.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) ignore: 7.0.9 natural-compare: 1.4.0 ts-api-utils: 2.5.0(typescript@5.9.3) @@ -5213,23 +5213,23 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)': + '@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@typescript-eslint/scope-manager': 8.70.0 '@typescript-eslint/types': 8.70.0 - '@typescript-eslint/typescript-estree': 8.70.0(typescript@5.9.3) + '@typescript-eslint/typescript-estree': 8.70.0(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/visitor-keys': 8.70.0 - debug: 4.4.3 - eslint: 9.39.5(jiti@2.7.0) + debug: 4.4.3(supports-color@7.2.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color - '@typescript-eslint/project-service@8.70.0(typescript@5.9.3)': + '@typescript-eslint/project-service@8.70.0(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@typescript-eslint/tsconfig-utils': 8.70.0(typescript@5.9.3) '@typescript-eslint/types': 8.70.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color @@ -5243,13 +5243,13 @@ snapshots: dependencies: typescript: 5.9.3 - '@typescript-eslint/type-utils@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)': + '@typescript-eslint/type-utils@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: '@typescript-eslint/types': 8.70.0 - '@typescript-eslint/typescript-estree': 8.70.0(typescript@5.9.3) - '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) - debug: 4.4.3 - eslint: 9.39.5(jiti@2.7.0) + '@typescript-eslint/typescript-estree': 8.70.0(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + debug: 4.4.3(supports-color@7.2.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) ts-api-utils: 2.5.0(typescript@5.9.3) typescript: 5.9.3 transitivePeerDependencies: @@ -5257,13 +5257,13 @@ snapshots: '@typescript-eslint/types@8.70.0': {} - '@typescript-eslint/typescript-estree@8.70.0(typescript@5.9.3)': + '@typescript-eslint/typescript-estree@8.70.0(supports-color@7.2.0)(typescript@5.9.3)': dependencies: - '@typescript-eslint/project-service': 8.70.0(typescript@5.9.3) + '@typescript-eslint/project-service': 8.70.0(supports-color@7.2.0)(typescript@5.9.3) '@typescript-eslint/tsconfig-utils': 8.70.0(typescript@5.9.3) '@typescript-eslint/types': 8.70.0 '@typescript-eslint/visitor-keys': 8.70.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) minimatch: 10.2.6 semver: 7.8.5 tinyglobby: 0.2.17 @@ -5272,13 +5272,13 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/utils@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)': + '@typescript-eslint/utils@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3)': dependencies: - '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(jiti@2.7.0)) + '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)) '@typescript-eslint/scope-manager': 8.70.0 '@typescript-eslint/types': 8.70.0 - '@typescript-eslint/typescript-estree': 8.70.0(typescript@5.9.3) - eslint: 9.39.5(jiti@2.7.0) + '@typescript-eslint/typescript-estree': 8.70.0(supports-color@7.2.0)(typescript@5.9.3) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color @@ -5288,11 +5288,11 @@ snapshots: '@typescript-eslint/types': 8.70.0 eslint-visitor-keys: 5.0.1 - '@vitejs/plugin-react@5.2.0(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0))': + '@vitejs/plugin-react@5.2.0(supports-color@7.2.0)(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0))': dependencies: - '@babel/core': 7.29.7 - '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@7.2.0) + '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.7(supports-color@7.2.0)) + '@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/core@7.29.7(supports-color@7.2.0)) '@rolldown/pluginutils': 1.0.0-rc.3 '@types/babel__core': 7.20.5 react-refresh: 0.18.0 @@ -5312,7 +5312,7 @@ snapshots: obug: 2.2.1 std-env: 4.2.0 tinyrainbow: 3.1.1 - vitest: 4.1.11(@types/node@24.13.5)(@vitest/coverage-v8@4.1.11)(jsdom@27.4.0)(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) + vitest: 4.1.11(@types/node@24.13.5)(@vitest/coverage-v8@4.1.11)(jsdom@27.4.0(supports-color@7.2.0))(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) '@vitest/expect@4.1.11': dependencies: @@ -5369,9 +5369,9 @@ snapshots: acorn@8.18.0: {} - agent-base@6.0.2: + agent-base@6.0.2(supports-color@7.2.0): dependencies: - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) transitivePeerDependencies: - supports-color @@ -5414,11 +5414,11 @@ snapshots: asynckit@0.4.0: {} - axios@1.20.0: + axios@1.20.0(debug@4.4.3(supports-color@7.2.0))(supports-color@7.2.0): dependencies: - follow-redirects: 1.16.1 + follow-redirects: 1.16.2(debug@4.4.3(supports-color@7.2.0)) form-data: 4.0.6 - https-proxy-agent: 5.0.1 + https-proxy-agent: 5.0.1(supports-color@7.2.0) proxy-from-env: 2.1.0 transitivePeerDependencies: - debug @@ -5534,9 +5534,11 @@ snapshots: date-fns@4.4.0: {} - debug@4.4.3: + debug@4.4.3(supports-color@7.2.0): dependencies: ms: 2.1.3 + optionalDependencies: + supports-color: 7.2.0 decimal.js@10.6.0: {} @@ -5625,13 +5627,13 @@ snapshots: escape-string-regexp@4.0.0: {} - eslint-plugin-react-hooks@5.2.0(eslint@9.39.5(jiti@2.7.0)): + eslint-plugin-react-hooks@5.2.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)): dependencies: - eslint: 9.39.5(jiti@2.7.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) - eslint-plugin-react-refresh@0.4.26(eslint@9.39.5(jiti@2.7.0)): + eslint-plugin-react-refresh@0.4.26(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)): dependencies: - eslint: 9.39.5(jiti@2.7.0) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) eslint-scope@8.4.0: dependencies: @@ -5644,14 +5646,14 @@ snapshots: eslint-visitor-keys@5.0.1: {} - eslint@9.39.5(jiti@2.7.0): + eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0): dependencies: - '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(jiti@2.7.0)) + '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0)) '@eslint-community/regexpp': 4.12.2 - '@eslint/config-array': 0.21.2 + '@eslint/config-array': 0.21.2(supports-color@7.2.0) '@eslint/config-helpers': 0.4.2 '@eslint/core': 0.17.0 - '@eslint/eslintrc': 3.3.7 + '@eslint/eslintrc': 3.3.7(supports-color@7.2.0) '@eslint/js': 9.39.5 '@eslint/plugin-kit': 0.4.1 '@humanfs/node': 0.16.8 @@ -5661,7 +5663,7 @@ snapshots: ajv: 6.15.0 chalk: 4.1.2 cross-spawn: 7.0.6 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) escape-string-regexp: 4.0.0 eslint-scope: 8.4.0 eslint-visitor-keys: 4.2.1 @@ -5741,7 +5743,9 @@ snapshots: flatted@3.4.4: {} - follow-redirects@1.16.1: {} + follow-redirects@1.16.2(debug@4.4.3(supports-color@7.2.0)): + optionalDependencies: + debug: 4.4.3(supports-color@7.2.0) form-data@4.0.6: dependencies: @@ -5831,24 +5835,24 @@ snapshots: html-to-image@1.11.13: {} - http-proxy-agent@7.0.2: + http-proxy-agent@7.0.2(supports-color@7.2.0): dependencies: agent-base: 7.1.4 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) transitivePeerDependencies: - supports-color - https-proxy-agent@5.0.1: + https-proxy-agent@5.0.1(supports-color@7.2.0): dependencies: - agent-base: 6.0.2 - debug: 4.4.3 + agent-base: 6.0.2(supports-color@7.2.0) + debug: 4.4.3(supports-color@7.2.0) transitivePeerDependencies: - supports-color - https-proxy-agent@7.0.6: + https-proxy-agent@7.0.6(supports-color@7.2.0): dependencies: agent-base: 7.1.4 - debug: 4.4.3 + debug: 4.4.3(supports-color@7.2.0) transitivePeerDependencies: - supports-color @@ -5907,7 +5911,7 @@ snapshots: dependencies: argparse: 2.0.1 - jsdom@27.4.0: + jsdom@27.4.0(supports-color@7.2.0): dependencies: '@acemir/cssom': 0.9.31 '@asamuzakjp/dom-selector': 6.8.1 @@ -5916,8 +5920,8 @@ snapshots: data-urls: 6.0.1 decimal.js: 10.6.0 html-encoding-sniffer: 6.0.0 - http-proxy-agent: 7.0.2 - https-proxy-agent: 7.0.6 + http-proxy-agent: 7.0.2(supports-color@7.2.0) + https-proxy-agent: 7.0.6(supports-color@7.2.0) is-potential-custom-element-name: 1.0.1 parse5: 8.0.1 saxes: 6.0.0 @@ -6370,15 +6374,15 @@ snapshots: semver@7.8.5: {} - seroval-plugins@1.5.6(seroval@1.6.8): + seroval-plugins@1.5.6(seroval@1.7.5): dependencies: - seroval: 1.6.8 + seroval: 1.7.5 - seroval-plugins@1.6.8(seroval@1.6.8): + seroval-plugins@1.6.8(seroval@1.7.5): dependencies: - seroval: 1.6.8 + seroval: 1.7.5 - seroval@1.6.8: {} + seroval@1.7.5: {} shebang-command@2.0.0: dependencies: @@ -6391,8 +6395,8 @@ snapshots: solid-js@1.9.15: dependencies: csstype: 3.2.3 - seroval: 1.6.8 - seroval-plugins: 1.5.6(seroval@1.6.8) + seroval: 1.7.5 + seroval-plugins: 1.5.6(seroval@1.7.5) solid-presence@0.2.0(solid-js@1.9.15): dependencies: @@ -6486,13 +6490,13 @@ snapshots: dependencies: prelude-ls: 1.2.1 - typescript-eslint@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3): + typescript-eslint@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3): dependencies: - '@typescript-eslint/eslint-plugin': 8.70.0(@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) - '@typescript-eslint/parser': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) - '@typescript-eslint/typescript-estree': 8.70.0(typescript@5.9.3) - '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3) - eslint: 9.39.5(jiti@2.7.0) + '@typescript-eslint/eslint-plugin': 8.70.0(@typescript-eslint/parser@8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/parser': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/typescript-estree': 8.70.0(supports-color@7.2.0)(typescript@5.9.3) + '@typescript-eslint/utils': 8.70.0(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.3) + eslint: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) typescript: 5.9.3 transitivePeerDependencies: - supports-color @@ -6544,7 +6548,7 @@ snapshots: jiti: 2.7.0 lightningcss: 1.32.0 - vitest@4.1.11(@types/node@24.13.5)(@vitest/coverage-v8@4.1.11)(jsdom@27.4.0)(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)): + vitest@4.1.11(@types/node@24.13.5)(@vitest/coverage-v8@4.1.11)(jsdom@27.4.0(supports-color@7.2.0))(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)): dependencies: '@vitest/expect': 4.1.11 '@vitest/mocker': 4.1.11(vite@7.3.7(@types/node@24.13.5)(jiti@2.7.0)(lightningcss@1.32.0)) @@ -6569,7 +6573,7 @@ snapshots: optionalDependencies: '@types/node': 24.13.5 '@vitest/coverage-v8': 4.1.11(vitest@4.1.11) - jsdom: 27.4.0 + jsdom: 27.4.0(supports-color@7.2.0) transitivePeerDependencies: - msw diff --git a/web/pnpm-workspace.yaml b/web/pnpm-workspace.yaml index 7693ac87e..29ebf3dec 100644 --- a/web/pnpm-workspace.yaml +++ b/web/pnpm-workspace.yaml @@ -23,6 +23,6 @@ overrides: js-yaml: ^4.3.1 nanoid: ^3.3.17 dompurify: ^3.4.17 - follow-redirects: ^1.16.1 - seroval: ^1.6.3 + follow-redirects: ^1.16.2 + seroval: ^1.6.11 source-map-js: ^1.2.2 From 75e77399be39ba8b1532b66f349c5bc0df975bbe Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sat, 31 Oct 2026 15:22:13 +0100 Subject: [PATCH 041/318] feat: scope French postverbal negation to interest phrases and accept Unicode whitespace in reply qualifiers --- docs/content/docs/guides/inbox-tagging.mdx | 2 +- internal/app/replyclassify/languages.go | 14 ++++++++++++-- .../replyclassify/sentiment_languages_test.go | 18 ++++++++++++++++++ 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/docs/content/docs/guides/inbox-tagging.mdx b/docs/content/docs/guides/inbox-tagging.mdx index ec48d388d..a708d07d8 100644 --- a/docs/content/docs/guides/inbox-tagging.mdx +++ b/docs/content/docs/guides/inbox-tagging.mdx @@ -234,7 +234,7 @@ The reading before any call covers: - **Out-of-office replies**, recognized by the subject their mail provider writes (`ะะฒั‚ะพะผะฐั‚ะธั‡ะตัะบะธะน ะพั‚ะฒะตั‚`, `่‡ชๅ‹•ๅฟœ็ญ”`, `์ž๋™ ํšŒ์‹ `, `ุฑุฏ ุชู„ู‚ุงุฆูŠ` and so on) and decided with no call at all. - **Non-delivery notices**, by the subject Exchange writes in Spanish, Italian, Dutch and Portuguese. A notice carrying a delivery-status report is recognized in any language without this. - **Replies that say no**, in German, French, Spanish, Dutch, Italian and Portuguese: a declined interest ("kein Interesse", "pas intรฉressรฉ", "no me interesa", "geen interesse", "non sono interessato", "nรฃo tenho interesse") or another clear no ("nein danke", "non merci", "no gracias", "nee bedankt", "no grazie", "nรฃo, obrigado", "falscher Ansprechpartner", "persona sbagliata"). Each phrase is matched as whole words, so "no grazie" never matches inside "buono, grazie". The reply classifier reads these as negative with no call, the same verdict "not interested" and "no thanks" get in English, so they take the `reply_negative` branch. Inbox labels still come from the classifier. -- **Replies that show interest**, in German, French and Spanish ("klingt gut", "lassen Sie uns telefonieren", "รงa m'intรฉresse", "je suis intรฉressรฉ", "me interesa mucho", "agendemos una llamada"), read as positive with no call, the same verdict "interested" and "let's talk" get in English, so they take the `reply_positive` branch and count as interested leads. A reply that also says no in one of these languages ("klingt gut, aber kein Bedarf") stays negative, and a phrase in a sentence that already says "no", "nicht", "pas" and the like ("no me interesa mucho", "je ne crois pas, honnรชtement, que cela nous intรฉresse") does not count, nor does one taken back later by "pero no", "aber nicht", "mais pas" and the like ("me interesa mucho, pero no ahora"). Conditional interest such as "Si cela m'intรฉresse, je vous contacterai", "Sโ€™il sโ€™avรจre que cela nous intรฉresse, nous vous recontacterons" or "Si me interesa mucho, les aviso" stays inconclusive. The accented Spanish affirmation "Sรญ, nos interesa mucho" reads as positive. Polite French requests beginning with "sโ€™il vous plaรฎt" or "sโ€™il te plaรฎt" still count as requests. French interest followed by "vraiment pas" or "absolument pas" does not count as positive; "pas mal" keeps its affirmative meaning. +- **Replies that show interest**, in German, French and Spanish ("klingt gut", "lassen Sie uns telefonieren", "รงa m'intรฉresse", "je suis intรฉressรฉ", "me interesa mucho", "agendemos una llamada"), read as positive with no call, the same verdict "interested" and "let's talk" get in English, so they take the `reply_positive` branch and count as interested leads. A reply that also says no in one of these languages ("klingt gut, aber kein Bedarf") stays negative, and a phrase in a sentence that already says "no", "nicht", "pas" and the like ("no me interesa mucho", "je ne crois pas, honnรชtement, que cela nous intรฉresse") does not count, nor does one taken back later by "pero no", "aber nicht", "mais pas" and the like ("me interesa mucho, pero no ahora"). Conditional interest such as "Si cela m'intรฉresse, je vous contacterai", "Sโ€™il sโ€™avรจre que cela nous intรฉresse, nous vous recontacterons" or "Si me interesa mucho, les aviso" stays inconclusive. The accented Spanish affirmation "Sรญ, nos interesa mucho" reads as positive. Polite French requests beginning with "sโ€™il vous plaรฎt" or "sโ€™il te plaรฎt" still count as requests. French interest followed by "vraiment pas" or "absolument pas" does not count as positive, including with Unicode whitespace; "pas mal" keeps its affirmative meaning. A request with a qualifier, such as "Envoyez-moi une offre pas trop chรจre", remains positive. Tagging languages are part of the workspace settings, so they travel with a [workspace export](/guides/workspace-export-import/). diff --git a/internal/app/replyclassify/languages.go b/internal/app/replyclassify/languages.go index daf20a03f..bd12a356f 100644 --- a/internal/app/replyclassify/languages.go +++ b/internal/app/replyclassify/languages.go @@ -39,6 +39,8 @@ type langRules struct { // phrases, and never after a negator or condition in its sentence. positiveAsWritten // keeps its accents, where folding would change the meaning. positive, positiveAsWritten []string + // positiveRequests express a request; a trailing qualifier need not negate it. + positiveRequests []string // postverbalNegation reads French pas after an interest phrase, including intervening adverbs. postverbalNegation bool } @@ -170,7 +172,10 @@ var languageRules = map[string]langRules{ positive: []string{ "je suis intรฉressรฉ", "je suis intรฉressรฉe", "nous sommes intรฉressรฉs", "nous sommes intรฉressรฉes", "รงa m'intรฉresse", "cela m'intรฉresse", "รงa nous intรฉresse", "cela nous intรฉresse", - "รงa a l'air intรฉressant", "cela semble intรฉressant", "prenons rendez-vous", + "รงa a l'air intรฉressant", "cela semble intรฉressant", + }, + positiveRequests: []string{ + "prenons rendez-vous", "envoyez-moi plus d'informations", "envoyez-moi une offre", "envoyez-moi un devis", "quel est le tarif", "quels sont vos tarifs", }, @@ -533,7 +538,9 @@ func refusedAfter(text string, end int) bool { return false } -var frenchPostverbalNegation = regexp.MustCompile(`^\s+(?:(?:vraiment|absolument|franchement|certainement|tellement|beaucoup)\s+)*pas\b(?:\s+(\p{L}+))?`) +const sentimentWhitespace = `[[:space:]\p{Z}\x{0085}]` + +var frenchPostverbalNegation = regexp.MustCompile(`^` + sentimentWhitespace + `+(?:(?:vraiment|absolument|franchement|certainement|tellement|beaucoup)` + sentimentWhitespace + `+)*pas\b(?:` + sentimentWhitespace + `+(\p{L}+))?`) // frenchNegatedAfter keeps post-verbal pas distinct from the affirmative idiom pas mal. func frenchNegatedAfter(text string, end int) bool { @@ -644,6 +651,9 @@ func compileRules(parts []langRules) *ruleSet { for _, pos := range p.positive { rs.positive = append(rs.positive, phrase{text: accentFolder.Replace(strings.ToLower(pos)), bounded: i > 0, negatable: i > 0, postverbalNegation: p.postverbalNegation}) } + for _, pos := range p.positiveRequests { + rs.positive = append(rs.positive, phrase{text: accentFolder.Replace(strings.ToLower(pos)), bounded: i > 0, negatable: i > 0}) + } for _, pos := range p.positiveAsWritten { rs.positive = append(rs.positive, phrase{text: strings.ToLower(pos), bounded: true, negatable: true, asWritten: true}) } diff --git a/internal/app/replyclassify/sentiment_languages_test.go b/internal/app/replyclassify/sentiment_languages_test.go index b37e1eb21..445331bcd 100644 --- a/internal/app/replyclassify/sentiment_languages_test.go +++ b/internal/app/replyclassify/sentiment_languages_test.go @@ -202,6 +202,9 @@ func TestInterestedRepliesByLanguage(t *testing.T) { "Nous sommes intรฉressรฉs, prenons rendez-vous.", "Cela semble intรฉressant.", "Envoyez-moi un devis s'il vous plaรฎt.", + "Envoyez-moi une offre pas trop chรจre.", + "Envoyez-moi un devis pas trop cher.", + "Envoyez-moi plus d'informations pas trop techniques.", "S'il vous plaรฎt, envoyez-moi un devis.", "Sโ€™il vous plaรฎt, envoyez-moi un devis.", "S'il vous plait, envoyez-moi un devis.", @@ -243,6 +246,21 @@ func TestInterestedRepliesByLanguage(t *testing.T) { } } +func TestFrenchInterestWithUnicodeWhitespace(t *testing.T) { + for _, space := range []string{"\t", "\n", "\v", "\f", "\r", " ", "\u0085", "\u00a0", "\u1680", "\u2000", "\u2001", "\u2002", "\u2003", "\u2004", "\u2005", "\u2006", "\u2007", "\u2008", "\u2009", "\u200a", "\u2028", "\u2029", "\u202f", "\u205f", "\u3000"} { + for body, wantPositive := range map[string]bool{ + "Cela nous intรฉresse" + space + "vraiment pas.": false, + "Cela nous intรฉresse vraiment" + space + "pas.": false, + "Cela nous intรฉresse vraiment pas" + space + "mal.": true, + } { + got := ClassifyOffline(Input{BodyText: body, Languages: []string{"fr"}}) + if (got.Class == ClassPositive) != wantPositive { + t.Errorf("%q = %q, want positive: %v", body, got.Class, wantPositive) + } + } + } +} + // An interest phrase that is negated, outweighed by a no, or only conditional // never reads as interest. func TestNegatedAndHedgedInterestIsNotPositive(t *testing.T) { From 6f55d9d848c59c573e338eafa2c0c9e3b1e13226 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sat, 31 Oct 2026 16:30:14 +0100 Subject: [PATCH 042/318] feat: raise the marketing site's astro to 7.4.4 --- site/package.json | 2 +- site/pnpm-lock.yaml | 450 +++++++++++++++++++++++++++++--------------- 2 files changed, 303 insertions(+), 149 deletions(-) diff --git a/site/package.json b/site/package.json index 0b8955161..533bdd006 100644 --- a/site/package.json +++ b/site/package.json @@ -16,7 +16,7 @@ "@astrojs/sitemap": "^3.7.4", "@fontsource/inter": "^5.2.6", "@tailwindcss/vite": "^4.1.10", - "astro": "^7.2.8", + "astro": "^7.4.4", "motion": "^12.34.0", "reading-time": "^1.5.0", "sharp": "0.35.5", diff --git a/site/pnpm-lock.yaml b/site/pnpm-lock.yaml index 241ec6169..edba6ca50 100644 --- a/site/pnpm-lock.yaml +++ b/site/pnpm-lock.yaml @@ -19,7 +19,7 @@ importers: dependencies: '@astrojs/mdx': specifier: ^7.0.8 - version: 7.0.8(@astrojs/markdown-satteri@0.3.8)(astro@7.2.8(@astrojs/markdown-remark@7.2.4)(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.3)(@types/node@24.13.5)(jiti@2.7.0)) + version: 7.0.8(@astrojs/markdown-satteri@0.3.8)(astro@7.4.4(@types/node@24.13.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)) '@astrojs/rss': specifier: ^4.0.19 version: 4.0.19 @@ -31,10 +31,10 @@ importers: version: 5.2.8 '@tailwindcss/vite': specifier: ^4.1.10 - version: 4.3.0(vite@8.3.5(@types/node@24.13.5)(esbuild@0.28.2)(jiti@2.7.0)) + version: 4.3.0(vite@8.3.5(@types/node@24.13.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)) astro: - specifier: ^7.2.8 - version: 7.2.8(@astrojs/markdown-remark@7.2.4)(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.3)(@types/node@24.13.5)(jiti@2.7.0) + specifier: ^7.4.4 + version: 7.4.4(@types/node@24.13.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1) motion: specifier: ^12.34.0 version: 12.40.0 @@ -50,86 +50,92 @@ importers: packages: - '@astrojs/compiler-binding-android-arm64@0.4.1': - resolution: {integrity: sha512-Wtx2DZORuNTLASLLZ8hlrjFaJe1LUloatcCn9EPq7knBhRpjMGXeJANIJMeBZG4igvz7x+3nyAJM2iwCSW9xog==} + '@astrojs/compiler-binding-android-arm64@0.5.2': + resolution: {integrity: sha512-kckIxon6Rm/Bxzh9mGPYpRRqUbToUQoHptCmpMmE+Yt0Xumq8CqrKUidyYhrBsrHVO7bxuRzzWUUqvpf+iYceQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [android] - '@astrojs/compiler-binding-darwin-arm64@0.4.1': - resolution: {integrity: sha512-7iwXcU+hB60Y1SvOfnWHNioT72gDsDQKaDipXh2Onwp/TvQMozhbvhy13wJR8Af940a0h6PbddCeJFpj791UDA==} + '@astrojs/compiler-binding-darwin-arm64@0.5.2': + resolution: {integrity: sha512-1ZG5Ar3dD8HtodX9XH1mRmE0qBXZlvjYXSFfpgFwocqfWnvhFuqtGUNseL8wgfImiRMztIjpQqlogQFQQtgiag==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [darwin] - '@astrojs/compiler-binding-darwin-x64@0.4.1': - resolution: {integrity: sha512-pifjICos49RXhSVKSDu5gDB0/8j0O7DmxSp1DaWW2PyLG5ekwSkcrfOZto5JqhdI7QYMZB3XOiXpsdOXpS4npA==} + '@astrojs/compiler-binding-darwin-x64@0.5.2': + resolution: {integrity: sha512-+kl35S7hiHJ2cb7eujwEsPFYYuSgE11uEE2Z20lAJ+undpgulMcW+weQqFPOSSZccEKHOiLIY+kQHkb4e4092w==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [darwin] - '@astrojs/compiler-binding-linux-arm64-gnu@0.4.1': - resolution: {integrity: sha512-hsZMlNWc6LqWHh9LlSwTq1/XCY7pxA5rkkKIdZRV8mgbOz9OwLvjEoe5Jry13eIZjMUQO8XnQyzk8o/Pjw2YFA==} + '@astrojs/compiler-binding-linux-arm64-gnu@0.5.2': + resolution: {integrity: sha512-BqlR0EHNQLPLwgL9+xogjsAc7zGf0cHho2CPdhv0P1yqbVMwGVaGAqrANP6VYAXCqSC43AF4Czcxc2n+oqdesg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] libc: [glibc] - '@astrojs/compiler-binding-linux-arm64-musl@0.4.1': - resolution: {integrity: sha512-a3EW27f+Z9uf57vYmpLgUriA1y9wDhKz57PT8D8XlFZt2HZEWhUxKuxI1jvKVI9p8okYee11WXEm/FHY1G9yoQ==} + '@astrojs/compiler-binding-linux-arm64-musl@0.5.2': + resolution: {integrity: sha512-GRGyby3AZWw5d6JQzidyxPyvGgHWsSusrpgKyFVpDTKctABF7L3Pd5V1cRJbV36/rcu+Eh292/wL7pF7MkmGkQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] libc: [musl] - '@astrojs/compiler-binding-linux-x64-gnu@0.4.1': - resolution: {integrity: sha512-XruPTKB/SS4DFzeAjQ1ZyM0ieHDjapHkOSnnzRApZ4FXY2YAI7UY3mETjfJiIS/acyZyrnPH5jObv1gATTdUJQ==} + '@astrojs/compiler-binding-linux-x64-gnu@0.5.2': + resolution: {integrity: sha512-9XAqGTMQAtIslMsjK3xdyY6OI9d59OZqcLBB6pvD/DcoR0daYswfrKx2azdDERDY4AqAnWPC7odVM1BmxYv3Vw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] libc: [glibc] - '@astrojs/compiler-binding-linux-x64-musl@0.4.1': - resolution: {integrity: sha512-E8j7lGanqNpudtkUbsFaOLJhmwFe4Ecqux7K9hkj4wULIPNZRM2bYZNcMSj8r1oWvaUiwZl8LaaNwv3+14jqhw==} + '@astrojs/compiler-binding-linux-x64-musl@0.5.2': + resolution: {integrity: sha512-jOViewGeTh9bSfS8vK72ECxoy2yvmA+Pd/ZcEvBI5c7+7IcfHwZ5qA4L9fRYuOhSrAifvQ2dV4vm1XAtloaWBw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] libc: [musl] - '@astrojs/compiler-binding-wasm32-wasi@0.4.1': - resolution: {integrity: sha512-vNLxIv41ZE+nmPFtw24cRW5ZXG+ZPcAGtgigtjCP8lvcxKI7u2GrXoMsCgEH5fMw8WCEJpwLvsVBg15rJKAkyA==} - engines: {node: '>=14.0.0'} + '@astrojs/compiler-binding-wasm32-wasi@0.5.2': + resolution: {integrity: sha512-Z7p64doar1uvR5C9Xs6j1CV9lGlPVQX7OQ2aAtZ/xKC5aGS6GB13nyc2UfQXTQLvZrvVwsyaflTQy6ziY5Bekw==} + engines: {node: ^20.19.0 || >=22.12.0} cpu: [wasm32] - '@astrojs/compiler-binding-win32-arm64-msvc@0.4.1': - resolution: {integrity: sha512-/xTDgRsFDoTh0/+KFXJ74DY4Jqn8CoSHwa8UP5RAblHfnRHkenwfSl4zYDET61O9vXKLk09UzHjjq09yP20/AQ==} + '@astrojs/compiler-binding-win32-arm64-msvc@0.5.2': + resolution: {integrity: sha512-Tr13bh+ahTWsjXjzctK7pFpWV+dUU4FtBfETlR7gO+ueex0F+RDch7eRr0YfKysaRhk9tWm14lsCJ5uWyFPNHQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [win32] - '@astrojs/compiler-binding-win32-x64-msvc@0.4.1': - resolution: {integrity: sha512-0x5J6iHZO0Fjo/CVzoIbXKzWnGESftDbEUQ/oXQ61HhUAFoR7+T1jfToZSNAS+gYyBXHSTpMWYC7lzarbhClcg==} + '@astrojs/compiler-binding-win32-x64-msvc@0.5.2': + resolution: {integrity: sha512-SfKkI+jOQYLh6wojPvVPV0lFfQnxisweN9B+qCzRvZp7DHAuGif8Y0WcC5PUgN4jb8VKy57LggQDtggR46Du1g==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [win32] - '@astrojs/compiler-binding@0.4.1': - resolution: {integrity: sha512-ZYVDW1P58OXyxqZbOMp+/2U9KA7y2esIx9r4pWdpZ/l6fCZhaw4ul+D7EgpRVxYLkyTWqzANbTTUFGPFP8zDHA==} + '@astrojs/compiler-binding@0.5.2': + resolution: {integrity: sha512-lEn76+0JcMQ5RDXU0wSMWJg2ZppiZvSULpghC29cfv4o9bhvWFDbQjsCtvjjXN9iVLFQ7fL3wTR2L2UU13mP8g==} engines: {node: ^20.19.0 || >=22.12.0} - '@astrojs/compiler-rs@0.4.1': - resolution: {integrity: sha512-//NmAuRhy7eU9iP0ceI5Pymy55M+nUZ//kS6XeOyhBWdDib2KbJOyFaVJ52k7sDkJwTKVox7oPu3SpYiVnGm5A==} + '@astrojs/compiler-rs@0.5.2': + resolution: {integrity: sha512-IvwYLB8t1M86rKO4oPdBi9GP4gzXcgrVlNgocjwos1jeeUuEIV8d9Crn1PvYD/5IKteWOxpIHomf7e8iYlkE+Q==} engines: {node: '>=22.12.0'} '@astrojs/internal-helpers@0.10.4': resolution: {integrity: sha512-nozZSy/mKYLqe4YrqbKtdOszedAfXYCtw3wZ0d+CAjz4GqQ4L9rl1ltIL5BlgwmYVinJg/RZ0MgGuWOdlyRZlA==} + '@astrojs/internal-helpers@0.13.0': + resolution: {integrity: sha512-20jxQqnSmpskcGyad7N5l6Xf1gz0UCa6lNde44bEBdaXGpncEYfAZJ142r2ZgzBaG4dUyzGmhqZWv1INU2eiHQ==} + '@astrojs/markdown-remark@7.2.4': resolution: {integrity: sha512-MvspGMynWKAjTe4/lTUdmBPHIFKNVLTCF6UlyWGogTGzNrTvjD+D4n48k7h8swxsEPKHK2TwxkZO7uoaCv1Pow==} '@astrojs/markdown-satteri@0.3.8': resolution: {integrity: sha512-n8ItpFTCmlDsVR5+rwDmehSf+jFCYLWmZiisZNGuF7xILqYhsVeBfcha4qgS2Seq3fAc9Tm58ZVrvqFQ6RQgRQ==} + '@astrojs/markdown-satteri@0.4.6': + resolution: {integrity: sha512-6biKp2lEAYycF3jhv91br+Otyf4EgDFkF1oRL9ks0u/m/YRGmI7XkGQ2MgaM35DslT03f7NtozKtlqfBNkp6bw==} + '@astrojs/mdx@7.0.8': resolution: {integrity: sha512-RNuwq2ccTSi7NX9YqlR0noaWoVdOrZuJvdfWXotAzdhMVB0b0zEMLnNU+xar7le0GwTMlTObD/QAu8jeHA/3nA==} engines: {node: '>=22.12.0'} @@ -144,15 +150,19 @@ packages: resolution: {integrity: sha512-KTivpmnz6lDsC6o9H4+DNm2SrE/GHzw8cNAvEJwAvUT+eoaEnn/4NtbDNfRRaxaJHdp15gf+tfHAWiXR4wB3BA==} engines: {node: '>=22.12.0'} + '@astrojs/prism@4.1.2': + resolution: {integrity: sha512-jMrUEpFDarDO1KWPvVc9eSa8DSfwBlwEOHwX+8zvZQpiqXRGDxFnOXHsYqV6DP7w+0qIgTr98gS1GdQlm8ypWg==} + engines: {node: '>=22.23.4'} + '@astrojs/rss@4.0.19': resolution: {integrity: sha512-e+z5wYeYtffQdHQO8c2tkSd2JEBdAuRXJV4ZEU5IxkYeE6e39woDd7nw1PH1Kk2tEYNCYuKdylnnbhGmt61awA==} '@astrojs/sitemap@3.7.4': resolution: {integrity: sha512-LbKNC24bdUWcQf/pThB6qLlSqHojxGjZDURIzFocY8rlWnAn2t74nnhnK6S5x0NHriHoAduLEpVjRykmeGiVvA==} - '@astrojs/telemetry@3.3.3': - resolution: {integrity: sha512-C1TLn5sPJr0x4vk56piHWKbnqlEB8BKyte5Y45V02U+D7BGO5eMqZDH5aPjnkXQWJggvmsTXxH03QMZ9NgWLzQ==} - engines: {node: 18.20.8 || ^20.3.0 || >=22.0.0} + '@astrojs/telemetry@3.4.2': + resolution: {integrity: sha512-2JOMRUxJrBSfiVDfeKLv1wBmvSIx1Y6u2YEO8awZ9qSq3u/rNAiUyFdOYi8dHv91kHrmYEQX7pRDw0J4xyj3UA==} + engines: {node: '>=22.23.4'} '@babel/helper-string-parser@7.29.7': resolution: {integrity: sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==} @@ -235,6 +245,9 @@ packages: '@emnapi/core@1.11.1': resolution: {integrity: sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==} + '@emnapi/core@1.11.3': + resolution: {integrity: sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg==} + '@emnapi/runtime@1.11.1': resolution: {integrity: sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==} @@ -244,6 +257,9 @@ packages: '@emnapi/wasi-threads@1.2.2': resolution: {integrity: sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==} + '@emnapi/wasi-threads@1.2.3': + resolution: {integrity: sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==} + '@esbuild/aix-ppc64@0.28.2': resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==} engines: {node: '>=18'} @@ -594,6 +610,13 @@ packages: '@emnapi/core': ^1.7.1 || ^2.0.0-alpha.4 '@emnapi/runtime': ^1.7.1 || ^2.0.0-alpha.4 + '@napi-rs/wasm-runtime@1.2.6': + resolution: {integrity: sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0} + peerDependencies: + '@emnapi/core': ^1.7.1 || 2.0.0-beta.2 + '@emnapi/runtime': ^1.7.1 || 2.0.0-beta.2 + '@nodable/entities@3.0.0': resolution: {integrity: sha512-8L9xFeTYKhm49xfIypoe2W5wV1m/3Z58kT+7kR9A8OyFxcPduI4VmxaUMQyKYrRjUoLLSXv6EKKID5Tvj9cUVw==} @@ -706,30 +729,58 @@ packages: resolution: {integrity: sha512-QCR4q2ZO/ILJEuwiBMel4wdcTDb1JGwfjKTxPDF6x8ixOaluPrVqIn06C99AcRPhmYlBR56d/Fb+GN58GzExpg==} engines: {node: '>=20'} + '@shikijs/core@4.5.0': + resolution: {integrity: sha512-6CIgwq+bt2JZ3OSjb/nBkkwEf/CfpHcbam+Mg5Pllco7HAGRQ2/EFhZrrJtbyNTgKwknfVS+llsXGygiDGwJWw==} + engines: {node: '>=20'} + '@shikijs/engine-javascript@4.4.3': resolution: {integrity: sha512-FbOjFJp9VLdo1Wevs10BBtVxiTWwNLqZh5Gkhjgda/ioL15YOgeSl9n+6XMa3qRlPQzfhFNe641SrynFHYG0nQ==} engines: {node: '>=20'} + '@shikijs/engine-javascript@4.5.0': + resolution: {integrity: sha512-Ed6UdEj84LyYkwnxM5CvSMWAD+id9ExTYri0/+x41U9zrgNifPSS9lZm0JqBP0VfYI8yr8tY5nbNq9+p9R0kFA==} + engines: {node: '>=20'} + '@shikijs/engine-oniguruma@4.4.3': resolution: {integrity: sha512-EcOQkxdxGQrc1Row/cC2c96/v1dbZqGnEVu1qTuT/MJmp6+cXCvQussowVmCv5Tqr3KuY3c7IbM6HTW3LJ1k9w==} engines: {node: '>=20'} + '@shikijs/engine-oniguruma@4.5.0': + resolution: {integrity: sha512-dKVmbJecVdB9recl8a/CU4jdpNXyjJQrIcesIkpS70s5HS02ohpnCSpMUbotPnEUzbAcLQ+S4hwZYbkBBiTcJw==} + engines: {node: '>=20'} + '@shikijs/langs@4.4.3': resolution: {integrity: sha512-ePic0yfAJGOF83D5wBHK/00EjK65oahBYxFk5epgq33WRv7X9UuxLEV8PtR0szC0z8dl7INIpIodB99JRFlR+A==} engines: {node: '>=20'} + '@shikijs/langs@4.5.0': + resolution: {integrity: sha512-wwBTqwduXSz0X4v9Qa2EWeFaYJEw1clCncWjoRNQRbVDu3SPRTRWucnouYapKj3b8Q+sk/41Vbc4B5c8nuYzLA==} + engines: {node: '>=20'} + '@shikijs/primitive@4.4.3': resolution: {integrity: sha512-m0wBeLDQDeIxRdUmrCPdQqfuUamDwRL5isCfYbguKD6NiaKpVbsv+3J81DyIKgNW5h4WAIIr8T4EkgQrBBxvaQ==} engines: {node: '>=20'} + '@shikijs/primitive@4.5.0': + resolution: {integrity: sha512-UM7ShlA8oz0OWxLLO8BmO9Ip6fVqdkt8yF0EH7nOCqHfrx1eEAzF0ZUVK7L+I8NEgeu1PEWSRlxaiPPeCb4iDg==} + engines: {node: '>=20'} + '@shikijs/themes@4.4.3': resolution: {integrity: sha512-w8UHjeUnIR965KMWJHUPXOc2mNJUnK3vpVLYLvw5IYU2mnTTJ89E24OrJDBNiJDQ0qzb0tc4l7mrIXx5cFeIyw==} engines: {node: '>=20'} + '@shikijs/themes@4.5.0': + resolution: {integrity: sha512-zGb87H3UBbpuI4yoh5UguB1XbU+2BDU3kflM7UfZ+Cy2hWo9lBtqjSVK20gmLY6ukYl040hAypGXMgud9vul8Q==} + engines: {node: '>=20'} + '@shikijs/types@4.4.3': resolution: {integrity: sha512-UEJxmRR++MAGR6hugn0vgVS2W/6lWAts84FFSrnlH9sP0LNol7E5+NQ792pH8liWUhyMyjhTgSUH3k7iD7tc5g==} engines: {node: '>=20'} + '@shikijs/types@4.5.0': + resolution: {integrity: sha512-drtPrtD8N0DENyD2cyt6Ajy+IWsiCLgMxODwLTpvH1UsN6a9jf90tNTPjqwHvA+0Lzu9e0txk8DjfqH1p9UJRw==} + engines: {node: '>=20'} + '@shikijs/vscode-textmate@10.0.2': resolution: {integrity: sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==} @@ -879,8 +930,8 @@ packages: engines: {node: '>=0.4.0'} hasBin: true - am-i-vibing@0.4.0: - resolution: {integrity: sha512-MxT4XZL7pzLHpuvhDKdMaQHMGGkJDLluKBLsbstn+8wv9sWcFT6h+0ve9qkml95amVTZtZV83gQe2hY+ojgHLg==} + am-i-vibing@0.5.0: + resolution: {integrity: sha512-KLcsDhqf1XRrJmJr+9I/C0EX2K+sGrAGZFgkmd84c8TJO9zJBu+/kFInjazu1KfJWFhWDKdRWkpBzEs7s35DVA==} hasBin: true anymatch@3.1.3: @@ -907,12 +958,12 @@ packages: resolution: {integrity: sha512-LElXdjswlqjWrPpJFg1Fx4wpkOCxj1TDHlSV4PlaRxHGWko024xICaa97ZkMfs6DRKlCguiAI+rbXv5GWwXIkg==} hasBin: true - astro@7.2.8: - resolution: {integrity: sha512-19nfgzl1IHNYzIfamUIr4dYSQcovWfMO5JGlN7Ahlg6Q6R+nzSPWAh+VO/mSg0hhcea35JHY0wL5ADZUi0WiYQ==} - engines: {node: '>=22.12.0', npm: '>=9.6.5', pnpm: '>=7.1.0'} + astro@7.4.4: + resolution: {integrity: sha512-e+BzhGCaIY/H1tV/BQPTbOPZVZ8wuu6+bbpc+3oSMH2UgoB1l9peSGASk6nswtYra9PO9OoMREhldKtQkZ5TVw==} + engines: {node: '>=22.23.4', npm: '>=9.6.5', pnpm: '>=7.1.0'} hasBin: true peerDependencies: - '@astrojs/markdown-remark': 7.2.4 + '@astrojs/markdown-remark': ^7.3.0 peerDependenciesMeta: '@astrojs/markdown-remark': optional: true @@ -1023,8 +1074,9 @@ packages: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} - devalue@5.9.4: - resolution: {integrity: sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg==} + devalue@6.0.3: + resolution: {integrity: sha512-3woMEITftG1wKeO/4d/QXH1DVKctTSZg3jNGPpjp9hNr5Hos8MCFF5McTML5ZtgKDObm2R591B0spRp2IVernA==} + engines: {node: '>=18'} devlop@1.1.0: resolution: {integrity: sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==} @@ -1065,6 +1117,9 @@ packages: es-module-lexer@2.3.2: resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} + es-module-lexer@3.0.4: + resolution: {integrity: sha512-BldNY5mwkVu+cQ5Ymn3e6hB9Sx8XHx4ZevWbiUyZbfKxJxYO27Hf0wfzkxIaD5CAJMaGl3YspKELj0ff/7nCMA==} + esast-util-from-estree@2.0.0: resolution: {integrity: sha512-4CyanoAudUSBAn5K13H4JhsMH6L9ZP7XbLVe/dKybkxMO7eDyLsT8UHl9TRNrU2Gr9nz+FovfSIjuXWJ81uVwQ==} @@ -1132,14 +1187,13 @@ packages: picomatch: optional: true - find-proc@0.1.0: - resolution: {integrity: sha512-OaOpEYv2PiQ7SQ5LIrl+deA1XaWcxEjnpM6VuWXTUvn+teIXxeFTLDmu18/zDQpFmHN4o3oDBX+BT0AGwEhemg==} - engines: {node: ^20.19.0 || >=22.12.0} - flattie@1.1.1: resolution: {integrity: sha512-9UbaD6XdAL97+k/n+N7JwX46K/M6Zc6KcFYskrYL8wbBV/Uyk0CTAMY0VT+qiK5PM7AIc9aTWYtq65U7T+aCNQ==} engines: {node: '>=8'} + fnv1a-64@0.1.2: + resolution: {integrity: sha512-mJbcILTPybAR1jdOwt/lVv8N2cffeJFFP+gVbSAwLEx1ujXH27RpPd8Rokec/KX9c76UYIB6Co+H4lQzxPnJfA==} + fontace@0.4.1: resolution: {integrity: sha512-lDMvbAzSnHmbYMTEld5qdtvNH2/pWpICOqpean9IgC7vUbUJc3k+k5Dokp85CegamqQpFbXf0rAVkbzpyTA8aw==} @@ -1166,8 +1220,8 @@ packages: engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} os: [darwin] - get-tsconfig@5.0.0-beta.4: - resolution: {integrity: sha512-7nF7C9fIPFEMHgEMEfgIlO9wDdZ8CyHw27rWciFZfHvHDReIiPhsYuzPRXsfvBCqFy1l8RRyyWV7QLM+ZhUJsQ==} + get-tsconfig@5.0.0-beta.6: + resolution: {integrity: sha512-X6fBC0pmImC70gvX2zm56go9hx0MyoGVdG0tUCkg/D+Xnh5TJsOZ7iDbOdI3PvmtrDxnu1YdDufpK2QJX1Meqw==} engines: {node: '>=20.20.0'} github-slugger@2.0.0: @@ -1423,8 +1477,8 @@ packages: magic-string@0.30.21: resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} - magic-string@1.4.1: - resolution: {integrity: sha512-8lyCu36ErXR0J9uaGKlKQoiLZKmtI63YGLE8G2o9jyRPdr4X47LusSOwgOJOzcVtp81fTAAjxR7BwKz682Jhow==} + magic-string@1.4.5: + resolution: {integrity: sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==} magicast@0.5.5: resolution: {integrity: sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==} @@ -1650,36 +1704,33 @@ packages: nth-check@2.1.1: resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==} - obug@2.2.1: - resolution: {integrity: sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==} + obug@3.0.0: + resolution: {integrity: sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==} engines: {node: '>=12.20.0'} ofetch@1.5.1: resolution: {integrity: sha512-2W4oUZlVaqAPAil6FUg/difl6YhqhUR7x2eZY4bQCko22UXg3hptq9KLQdqFClV+Wu85UX7hNtdGTngi/1BxcA==} - ohash@2.0.12: - resolution: {integrity: sha512-65S/5gk9YSsaRjcyf7Nfa6h/d3E8/1gslpXfI4W7Dxn/oap8IKRuNT5VXkLQ1YFKIEg4apRY4Pj6aiwFzrDdmw==} - oniguruma-parser@0.12.2: resolution: {integrity: sha512-6HVa5oIrgMC6aA6WF6XyyqbhRPJrKR02L20+2+zpDtO5QAzGHAUGw5TKQvwi5vctNnRHkJYmjAhRVQF2EKdTQw==} oniguruma-to-es@4.3.6: resolution: {integrity: sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA==} - p-limit@7.3.2: - resolution: {integrity: sha512-Ll0w3fU24vYpXoZmjjZIee6bJQDgG0oAyo1PdmFYI8UDwJJddaHAypxIH9avUu+t+lSsAwKVsb1jDCMIIChliw==} + p-limit@7.3.3: + resolution: {integrity: sha512-SKgVvDU5TNIxQ4r30U75BNLC6a+6GOEjngrk/ysM5+Zu3oJuk1SC5ApzIzY/7PjCEjoVPMWJ0zho/4QUiEB7TQ==} engines: {node: '>=20'} - p-queue@9.3.3: - resolution: {integrity: sha512-NXAOdnEe5FsZJfT4oK84lE1Y5cFFdWlRuOo5tww8DyNMxyRXwn39fIkUtNLKppcPC+UYU/bXujNCUGDv01y7CA==} + p-queue@9.3.5: + resolution: {integrity: sha512-Lki/zhXFVmDhesBUn/yHRLW9Bte7mE7xoFHzTR8sIomV7a2z+LxYAPkGvdfidNiu4fKSfjtawixxSHcZci5QcQ==} engines: {node: '>=20'} p-timeout@7.0.2: resolution: {integrity: sha512-prbX4Z3YszrFNgH+MW5Zoeq3baXrMtP/MQnFeET90UB/GtGcGDQ5Usg9OCy6ETjTTntOw1SL2z9fMPUppN3Guw==} engines: {node: '>=20'} - package-manager-detector@1.8.0: - resolution: {integrity: sha512-yQA4H19AmPEoMUeavPMDIe1higySl/gH/yaQrkT/s07Qp+7pp2hYz30N3z2l5BkjVkF9Ow6o0wjJamm2y7Sn0A==} + package-manager-detector@1.9.0: + resolution: {integrity: sha512-zAMfbta9nPA8AKkA4WdmNAT8R8s6Dk0/xwPsqNnRidMFcLo1YkLuPDTgs2f64XdzS8vbLNnoJ+uUIkgbz7oRHA==} parse-entities@4.0.2: resolution: {integrity: sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==} @@ -1829,6 +1880,10 @@ packages: resolution: {integrity: sha512-Mb/GvXPHBAXdgGIcnfU5L3ldpn1XcxrGkPHwqgRx17/I2XRfqlFKk2vGkHWINn1kdXvzJZeuO3is6I9KLPFm0g==} engines: {node: '>=20'} + shiki@4.5.0: + resolution: {integrity: sha512-OcRW72ngQvc+MSVWBRIovC/BTW589iUE/Vxav7VeM4RcY9MUjqB+IR6ILG1k9nuW6LiG/nct9uma4/MBtnZbmQ==} + engines: {node: '>=20'} + sisteransi@1.0.5: resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==} @@ -1852,6 +1907,9 @@ packages: space-separated-tokens@2.0.2: resolution: {integrity: sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==} + std-env@4.3.0: + resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==} + stringify-entities@4.0.4: resolution: {integrity: sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==} @@ -1879,8 +1937,8 @@ packages: tiny-inflate@1.0.3: resolution: {integrity: sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==} - tinyclip@0.1.15: - resolution: {integrity: sha512-uo33abH+Ays0xYaDysoBt494Hb3hsEczMpcC0MwFl773pazORx4fmvKhclhR1wonUbB6vvpRsvVMwnhfqeMc+A==} + tinyclip@1.0.3: + resolution: {integrity: sha512-nTv2raKFMzGG6JJp0lpNDsRPdfFE6UHlu2rVEjXo8vkx1ZS3LW2CVXqIaLu8xZlu+6tbFs9V58Qc/Jmk/Ii7wA==} engines: {node: ^16.14.0 || >= 17.3.0} tinyexec@1.3.1: @@ -1891,6 +1949,9 @@ packages: resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} engines: {node: '>=12.0.0'} + tinyps@0.5.1: + resolution: {integrity: sha512-B6Ykif5HflC3AdDkS4Zst/2muYVfeXoVMy+KorqH80s/1x4vunIORpNySH681X7fjj+dFM9MDKD6/Hsccjb87Q==} + trim-lines@3.0.1: resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==} @@ -1919,8 +1980,8 @@ packages: unified@11.0.5: resolution: {integrity: sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==} - unifont@0.7.5: - resolution: {integrity: sha512-ULe/Cs+ZIsq+dcFofNkhqielCrUJnb5mr+Yc4EBM2VlL+6OZR6+cjtI2mT1bJvRBrVncqHAbLURxmPLcCXzWMg==} + unifont@1.0.3: + resolution: {integrity: sha512-XGnEwj5sWdCbiBX01mWLSBncS0yMRjnLygau3IfdOlfjMacNIQvTGW4VH7pWBq+gGWArfSef/CensMLjMmIr/A==} unist-util-find-after@5.0.0: resolution: {integrity: sha512-amQa0Ep2m6hE2g72AugUItjbuM8X8cGQnFoHk0pGfrFeT9GZhzN5SW8nRsiGKK7Aif4CrACPENkA6P/Lw6fHGQ==} @@ -2014,6 +2075,10 @@ packages: uploadthing: optional: true + verkit@0.5.0: + resolution: {integrity: sha512-u4J1hr6Y+C/hit34GwL3eIcUf3wngT8TlYUjK7tk0jxydKLAq3sYvifjdTDA6U3KCKRcQCQDGf/srjxfZF3l7g==} + engines: {node: '>=18.12.0'} + vfile-location@5.0.3: resolution: {integrity: sha512-5yXvWDEgqeiYiBe1lbxYF7UMAIm/IcopxMHrMQDq3nvKcjPKIhZklUKL+AE7J7uApI4kwe2snsK+eI6UTj9EHg==} @@ -2084,6 +2149,11 @@ packages: xxhash-wasm@1.1.0: resolution: {integrity: sha512-147y/6YNh+tlp6nd/2pWq38i9h6mz/EuQ6njIrmW8D1BS5nCqs0P6DG+m6zTGnNz5I+uhZ0SHxBs9BsPrwcKDA==} + yaml@2.9.1: + resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==} + engines: {node: '>= 14.6'} + hasBin: true + yargs-parser@22.0.0: resolution: {integrity: sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==} engines: {node: ^20.19.0 || ^22.12.0 || >=23} @@ -2100,63 +2170,56 @@ packages: snapshots: - '@astrojs/compiler-binding-android-arm64@0.4.1': + '@astrojs/compiler-binding-android-arm64@0.5.2': optional: true - '@astrojs/compiler-binding-darwin-arm64@0.4.1': + '@astrojs/compiler-binding-darwin-arm64@0.5.2': optional: true - '@astrojs/compiler-binding-darwin-x64@0.4.1': + '@astrojs/compiler-binding-darwin-x64@0.5.2': optional: true - '@astrojs/compiler-binding-linux-arm64-gnu@0.4.1': + '@astrojs/compiler-binding-linux-arm64-gnu@0.5.2': optional: true - '@astrojs/compiler-binding-linux-arm64-musl@0.4.1': + '@astrojs/compiler-binding-linux-arm64-musl@0.5.2': optional: true - '@astrojs/compiler-binding-linux-x64-gnu@0.4.1': + '@astrojs/compiler-binding-linux-x64-gnu@0.5.2': optional: true - '@astrojs/compiler-binding-linux-x64-musl@0.4.1': + '@astrojs/compiler-binding-linux-x64-musl@0.5.2': optional: true - '@astrojs/compiler-binding-wasm32-wasi@0.4.1(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.3)': + '@astrojs/compiler-binding-wasm32-wasi@0.5.2': dependencies: - '@napi-rs/wasm-runtime': 1.2.4(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.3) - transitivePeerDependencies: - - '@emnapi/core' - - '@emnapi/runtime' + '@emnapi/core': 1.11.3 + '@emnapi/runtime': 1.11.3 + '@napi-rs/wasm-runtime': 1.2.6(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3) optional: true - '@astrojs/compiler-binding-win32-arm64-msvc@0.4.1': + '@astrojs/compiler-binding-win32-arm64-msvc@0.5.2': optional: true - '@astrojs/compiler-binding-win32-x64-msvc@0.4.1': + '@astrojs/compiler-binding-win32-x64-msvc@0.5.2': optional: true - '@astrojs/compiler-binding@0.4.1(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.3)': + '@astrojs/compiler-binding@0.5.2': optionalDependencies: - '@astrojs/compiler-binding-android-arm64': 0.4.1 - '@astrojs/compiler-binding-darwin-arm64': 0.4.1 - '@astrojs/compiler-binding-darwin-x64': 0.4.1 - '@astrojs/compiler-binding-linux-arm64-gnu': 0.4.1 - '@astrojs/compiler-binding-linux-arm64-musl': 0.4.1 - '@astrojs/compiler-binding-linux-x64-gnu': 0.4.1 - '@astrojs/compiler-binding-linux-x64-musl': 0.4.1 - '@astrojs/compiler-binding-wasm32-wasi': 0.4.1(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.3) - '@astrojs/compiler-binding-win32-arm64-msvc': 0.4.1 - '@astrojs/compiler-binding-win32-x64-msvc': 0.4.1 - transitivePeerDependencies: - - '@emnapi/core' - - '@emnapi/runtime' + '@astrojs/compiler-binding-android-arm64': 0.5.2 + '@astrojs/compiler-binding-darwin-arm64': 0.5.2 + '@astrojs/compiler-binding-darwin-x64': 0.5.2 + '@astrojs/compiler-binding-linux-arm64-gnu': 0.5.2 + '@astrojs/compiler-binding-linux-arm64-musl': 0.5.2 + '@astrojs/compiler-binding-linux-x64-gnu': 0.5.2 + '@astrojs/compiler-binding-linux-x64-musl': 0.5.2 + '@astrojs/compiler-binding-wasm32-wasi': 0.5.2 + '@astrojs/compiler-binding-win32-arm64-msvc': 0.5.2 + '@astrojs/compiler-binding-win32-x64-msvc': 0.5.2 - '@astrojs/compiler-rs@0.4.1(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.3)': + '@astrojs/compiler-rs@0.5.2': dependencies: - '@astrojs/compiler-binding': 0.4.1(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.3) - transitivePeerDependencies: - - '@emnapi/core' - - '@emnapi/runtime' + '@astrojs/compiler-binding': 0.5.2 '@astrojs/internal-helpers@0.10.4': dependencies: @@ -2169,6 +2232,17 @@ snapshots: smol-toml: 1.9.0 unified: 11.0.5 + '@astrojs/internal-helpers@0.13.0': + dependencies: + '@types/hast': 3.0.5 + '@types/mdast': 4.0.4 + picomatch: 4.0.7 + retext-smartypants: 6.2.0 + shiki: 4.5.0 + smol-toml: 1.9.0 + unified: 11.0.5 + yaml: 2.9.1 + '@astrojs/markdown-remark@7.2.4': dependencies: '@astrojs/internal-helpers': 0.10.4 @@ -2197,14 +2271,22 @@ snapshots: '@astrojs/prism': 4.0.2 github-slugger: 2.0.0 satteri: 0.10.5 + optional: true - '@astrojs/mdx@7.0.8(@astrojs/markdown-satteri@0.3.8)(astro@7.2.8(@astrojs/markdown-remark@7.2.4)(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.3)(@types/node@24.13.5)(jiti@2.7.0))': + '@astrojs/markdown-satteri@0.4.6': + dependencies: + '@astrojs/internal-helpers': 0.13.0 + '@astrojs/prism': 4.1.2 + github-slugger: 2.0.0 + satteri: 0.10.5 + + '@astrojs/mdx@7.0.8(@astrojs/markdown-satteri@0.3.8)(astro@7.4.4(@types/node@24.13.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))': dependencies: '@astrojs/internal-helpers': 0.10.4 '@astrojs/markdown-remark': 7.2.4 '@mdx-js/mdx': 3.1.1 acorn: 8.18.0 - astro: 7.2.8(@astrojs/markdown-remark@7.2.4)(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.3)(@types/node@24.13.5)(jiti@2.7.0) + astro: 7.4.4(@types/node@24.13.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1) es-module-lexer: 2.3.2 estree-util-visit: 2.0.0 hast-util-to-html: 9.0.5 @@ -2224,6 +2306,10 @@ snapshots: dependencies: prismjs: 1.30.0 + '@astrojs/prism@4.1.2': + dependencies: + prismjs: 1.30.0 + '@astrojs/rss@4.0.19': dependencies: fast-xml-parser: 5.11.1 @@ -2235,12 +2321,12 @@ snapshots: sitemap: 9.0.1 zod: 4.6.7 - '@astrojs/telemetry@3.3.3': + '@astrojs/telemetry@3.4.2': dependencies: ci-info: 4.4.0 dset: 3.1.4 is-docker: 4.0.0 - package-manager-detector: 1.8.0 + package-manager-detector: 1.9.0 '@babel/helper-string-parser@7.29.7': {} @@ -2308,6 +2394,12 @@ snapshots: tslib: 2.8.1 optional: true + '@emnapi/core@1.11.3': + dependencies: + '@emnapi/wasi-threads': 1.2.3 + tslib: 2.8.1 + optional: true + '@emnapi/runtime@1.11.1': dependencies: tslib: 2.8.1 @@ -2323,6 +2415,11 @@ snapshots: tslib: 2.8.1 optional: true + '@emnapi/wasi-threads@1.2.3': + dependencies: + tslib: 2.8.1 + optional: true + '@esbuild/aix-ppc64@0.28.2': optional: true @@ -2567,9 +2664,9 @@ snapshots: '@tybys/wasm-util': 0.10.4 optional: true - '@napi-rs/wasm-runtime@1.2.4(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.3)': + '@napi-rs/wasm-runtime@1.2.6(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)': dependencies: - '@emnapi/core': 1.11.1 + '@emnapi/core': 1.11.3 '@emnapi/runtime': 1.11.3 '@tybys/wasm-util': 0.10.4 optional: true @@ -2635,36 +2732,74 @@ snapshots: '@types/hast': 3.0.5 hast-util-to-html: 9.0.5 + '@shikijs/core@4.5.0': + dependencies: + '@shikijs/primitive': 4.5.0 + '@shikijs/types': 4.5.0 + '@shikijs/vscode-textmate': 10.0.2 + '@types/hast': 3.0.5 + hast-util-to-html: 9.0.5 + '@shikijs/engine-javascript@4.4.3': dependencies: '@shikijs/types': 4.4.3 '@shikijs/vscode-textmate': 10.0.2 oniguruma-to-es: 4.3.6 + '@shikijs/engine-javascript@4.5.0': + dependencies: + '@shikijs/types': 4.5.0 + '@shikijs/vscode-textmate': 10.0.2 + oniguruma-to-es: 4.3.6 + '@shikijs/engine-oniguruma@4.4.3': dependencies: '@shikijs/types': 4.4.3 '@shikijs/vscode-textmate': 10.0.2 + '@shikijs/engine-oniguruma@4.5.0': + dependencies: + '@shikijs/types': 4.5.0 + '@shikijs/vscode-textmate': 10.0.2 + '@shikijs/langs@4.4.3': dependencies: '@shikijs/types': 4.4.3 + '@shikijs/langs@4.5.0': + dependencies: + '@shikijs/types': 4.5.0 + '@shikijs/primitive@4.4.3': dependencies: '@shikijs/types': 4.4.3 '@shikijs/vscode-textmate': 10.0.2 '@types/hast': 3.0.5 + '@shikijs/primitive@4.5.0': + dependencies: + '@shikijs/types': 4.5.0 + '@shikijs/vscode-textmate': 10.0.2 + '@types/hast': 3.0.5 + '@shikijs/themes@4.4.3': dependencies: '@shikijs/types': 4.4.3 + '@shikijs/themes@4.5.0': + dependencies: + '@shikijs/types': 4.5.0 + '@shikijs/types@4.4.3': dependencies: '@shikijs/vscode-textmate': 10.0.2 '@types/hast': 3.0.5 + '@shikijs/types@4.5.0': + dependencies: + '@shikijs/vscode-textmate': 10.0.2 + '@types/hast': 3.0.5 + '@shikijs/vscode-textmate@10.0.2': {} '@tailwindcss/node@4.3.0': @@ -2728,12 +2863,12 @@ snapshots: '@tailwindcss/oxide-win32-arm64-msvc': 4.3.0 '@tailwindcss/oxide-win32-x64-msvc': 4.3.0 - '@tailwindcss/vite@4.3.0(vite@8.3.5(@types/node@24.13.5)(esbuild@0.28.2)(jiti@2.7.0))': + '@tailwindcss/vite@4.3.0(vite@8.3.5(@types/node@24.13.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1))': dependencies: '@tailwindcss/node': 4.3.0 '@tailwindcss/oxide': 4.3.0 tailwindcss: 4.3.0 - vite: 8.3.5(@types/node@24.13.5)(esbuild@0.28.2)(jiti@2.7.0) + vite: 8.3.5(@types/node@24.13.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1) '@tybys/wasm-util@0.10.4': dependencies: @@ -2786,7 +2921,7 @@ snapshots: acorn@8.18.0: {} - am-i-vibing@0.4.0: + am-i-vibing@0.5.0: dependencies: process-ancestry: 0.1.0 @@ -2807,63 +2942,61 @@ snapshots: astring@1.9.0: {} - astro@7.2.8(@astrojs/markdown-remark@7.2.4)(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.3)(@types/node@24.13.5)(jiti@2.7.0): + astro@7.4.4(@types/node@24.13.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1): dependencies: - '@astrojs/compiler-rs': 0.4.1(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.3) - '@astrojs/internal-helpers': 0.10.4 - '@astrojs/markdown-satteri': 0.3.8 - '@astrojs/telemetry': 3.3.3 + '@astrojs/compiler-rs': 0.5.2 + '@astrojs/internal-helpers': 0.13.0 + '@astrojs/markdown-satteri': 0.4.6 + '@astrojs/telemetry': 3.4.2 '@capsizecss/unpack': 4.0.1 '@clack/prompts': 1.8.1 '@oslojs/encoding': 1.1.0 - am-i-vibing: 0.4.0 + am-i-vibing: 0.5.0 aria-query: 5.3.2 axobject-query: 4.1.0 ci-info: 4.4.0 clsx: 2.1.1 common-ancestor-path: 2.0.0 cookie: 2.0.1 - devalue: 5.9.4 + devalue: 6.0.3 diff: 9.0.0 dset: 3.1.4 - es-module-lexer: 2.3.2 - esbuild: 0.28.2 - find-proc: 0.1.0 + es-module-lexer: 3.0.4 flattie: 1.1.1 fontace: 0.4.1 - get-tsconfig: 5.0.0-beta.4 + get-tsconfig: 5.0.0-beta.6 github-slugger: 2.0.0 html-escaper: 3.0.3 http-cache-semantics: 4.3.0 - js-yaml: 4.3.2 jsonc-parser: 3.3.1 - magic-string: 1.4.1 + magic-string: 1.4.5 magicast: 0.5.5 mrmime: 2.0.1 neotraverse: 1.0.1 - obug: 2.2.1 - p-limit: 7.3.2 - p-queue: 9.3.3 - package-manager-detector: 1.8.0 + obug: 3.0.0 + p-limit: 7.3.3 + p-queue: 9.3.5 + package-manager-detector: 1.9.0 piccolore: 0.1.3 picomatch: 4.0.7 - semver: 7.8.5 - shiki: 4.4.3 + rolldown: 1.2.15 + shiki: 4.5.0 smol-toml: 1.9.0 svgo: 4.1.0 - tinyclip: 0.1.15 + tinyclip: 1.0.3 tinyexec: 1.3.1 tinyglobby: 0.2.17 + tinyps: 0.5.1 ultrahtml: 1.7.0 - unifont: 0.7.5 + unifont: 1.0.3 unstorage: 1.17.5 - vite: 8.3.5(@types/node@24.13.5)(esbuild@0.28.2)(jiti@2.7.0) - vitefu: 1.1.3(vite@8.3.5(@types/node@24.13.5)(esbuild@0.28.2)(jiti@2.7.0)) + verkit: 0.5.0 + vite: 8.3.5(@types/node@24.13.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1) + vitefu: 1.1.3(vite@8.3.5(@types/node@24.13.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)) xxhash-wasm: 1.1.0 yargs-parser: 22.0.0 zod: 4.6.7 optionalDependencies: - '@astrojs/markdown-remark': 7.2.4 sharp: 0.35.5(@types/node@24.13.5) transitivePeerDependencies: - '@azure/app-configuration' @@ -2874,8 +3007,6 @@ snapshots: - '@azure/storage-blob' - '@capacitor/preferences' - '@deno/kv' - - '@emnapi/core' - - '@emnapi/runtime' - '@netlify/blobs' - '@planetscale/database' - '@types/node' @@ -2886,6 +3017,7 @@ snapshots: - '@vitejs/devtools' - aws4fetch - db0 + - esbuild - idb-keyval - ioredis - jiti @@ -2979,7 +3111,7 @@ snapshots: detect-libc@2.1.2: {} - devalue@5.9.4: {} + devalue@6.0.3: {} devlop@1.1.0: dependencies: @@ -3018,6 +3150,8 @@ snapshots: es-module-lexer@2.3.2: {} + es-module-lexer@3.0.4: {} + esast-util-from-estree@2.0.0: dependencies: '@types/estree-jsx': 1.0.5 @@ -3060,6 +3194,7 @@ snapshots: '@esbuild/win32-arm64': 0.28.2 '@esbuild/win32-ia32': 0.28.2 '@esbuild/win32-x64': 0.28.2 + optional: true escape-string-regexp@5.0.0: {} @@ -3128,10 +3263,10 @@ snapshots: optionalDependencies: picomatch: 4.0.7 - find-proc@0.1.0: {} - flattie@1.1.1: {} + fnv1a-64@0.1.2: {} + fontace@0.4.1: dependencies: fontkitten: 1.0.3 @@ -3149,7 +3284,7 @@ snapshots: fsevents@2.3.3: optional: true - get-tsconfig@5.0.0-beta.4: + get-tsconfig@5.0.0-beta.6: dependencies: resolve-pkg-maps: 1.0.0 @@ -3438,7 +3573,7 @@ snapshots: dependencies: '@jridgewell/sourcemap-codec': 1.5.5 - magic-string@1.4.1: + magic-string@1.4.5: dependencies: '@jridgewell/sourcemap-codec': 1.6.0 @@ -3922,7 +4057,7 @@ snapshots: dependencies: boolbase: 1.0.0 - obug@2.2.1: {} + obug@3.0.0: {} ofetch@1.5.1: dependencies: @@ -3930,8 +4065,6 @@ snapshots: node-fetch-native: 1.6.7 ufo: 1.6.4 - ohash@2.0.12: {} - oniguruma-parser@0.12.2: {} oniguruma-to-es@4.3.6: @@ -3940,18 +4073,18 @@ snapshots: regex: 6.1.0 regex-recursion: 6.0.2 - p-limit@7.3.2: + p-limit@7.3.3: dependencies: yocto-queue: 1.2.2 - p-queue@9.3.3: + p-queue@9.3.5: dependencies: eventemitter3: 5.0.4 p-timeout: 7.0.2 p-timeout@7.0.2: {} - package-manager-detector@1.8.0: {} + package-manager-detector@1.9.0: {} parse-entities@4.0.2: dependencies: @@ -4224,6 +4357,17 @@ snapshots: '@shikijs/vscode-textmate': 10.0.2 '@types/hast': 3.0.5 + shiki@4.5.0: + dependencies: + '@shikijs/core': 4.5.0 + '@shikijs/engine-javascript': 4.5.0 + '@shikijs/engine-oniguruma': 4.5.0 + '@shikijs/langs': 4.5.0 + '@shikijs/themes': 4.5.0 + '@shikijs/types': 4.5.0 + '@shikijs/vscode-textmate': 10.0.2 + '@types/hast': 3.0.5 + sisteransi@1.0.5: {} sitemap@9.0.1: @@ -4241,6 +4385,8 @@ snapshots: space-separated-tokens@2.0.2: {} + std-env@4.3.0: {} + stringify-entities@4.0.4: dependencies: character-entities-html4: 2.1.0 @@ -4274,7 +4420,7 @@ snapshots: tiny-inflate@1.0.3: {} - tinyclip@0.1.15: {} + tinyclip@1.0.3: {} tinyexec@1.3.1: {} @@ -4283,6 +4429,8 @@ snapshots: fdir: 6.5.0(picomatch@4.0.7) picomatch: 4.0.7 + tinyps@0.5.1: {} + trim-lines@3.0.1: {} trough@2.2.0: {} @@ -4309,10 +4457,11 @@ snapshots: trough: 2.2.0 vfile: 6.0.3 - unifont@0.7.5: + unifont@1.0.3: dependencies: css-tree: 3.2.1 - ohash: 2.0.12 + fnv1a-64: 0.1.2 + std-env: 4.3.0 undici: 8.12.3 unist-util-find-after@5.0.0: @@ -4372,6 +4521,8 @@ snapshots: ofetch: 1.5.1 ufo: 1.6.4 + verkit@0.5.0: {} + vfile-location@5.0.3: dependencies: '@types/unist': 3.0.3 @@ -4387,7 +4538,7 @@ snapshots: '@types/unist': 3.0.3 vfile-message: 4.0.3 - vite@8.3.5(@types/node@24.13.5)(esbuild@0.28.2)(jiti@2.7.0): + vite@8.3.5(@types/node@24.13.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1): dependencies: lightningcss: 1.33.0 picomatch: 4.0.7 @@ -4399,10 +4550,11 @@ snapshots: esbuild: 0.28.2 fsevents: 2.3.3 jiti: 2.7.0 + yaml: 2.9.1 - vitefu@1.1.3(vite@8.3.5(@types/node@24.13.5)(esbuild@0.28.2)(jiti@2.7.0)): + vitefu@1.1.3(vite@8.3.5(@types/node@24.13.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)): optionalDependencies: - vite: 8.3.5(@types/node@24.13.5)(esbuild@0.28.2)(jiti@2.7.0) + vite: 8.3.5(@types/node@24.13.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1) web-namespaces@2.0.1: {} @@ -4410,6 +4562,8 @@ snapshots: xxhash-wasm@1.1.0: {} + yaml@2.9.1: {} + yargs-parser@22.0.0: {} yocto-queue@1.2.2: {} From ae334a1c4a936d8b9ec275e7e5927b448b0fae2c Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sat, 31 Oct 2026 18:32:55 +0100 Subject: [PATCH 043/318] feat: finalize runtime TLS through a scoped versioned plan and protected infrastructure approval --- .github/scripts/runtime-tls.sh | 93 +++++++++++++++ .github/scripts/runtime-tls.test.sh | 39 +++++++ .github/workflows/runtime-tls.yml | 109 ++++++++++++++++++ docs/content/docs/development/aws-fargate.mdx | 20 ++++ 4 files changed, 261 insertions(+) create mode 100755 .github/scripts/runtime-tls.sh create mode 100755 .github/scripts/runtime-tls.test.sh create mode 100644 .github/workflows/runtime-tls.yml diff --git a/.github/scripts/runtime-tls.sh b/.github/scripts/runtime-tls.sh new file mode 100755 index 000000000..97383e4b6 --- /dev/null +++ b/.github/scripts/runtime-tls.sh @@ -0,0 +1,93 @@ +#!/usr/bin/env bash +# Finalize runtime TLS through the protected environment using a versioned private snapshot. +set -euo pipefail + +check_plan() { + jq -e ' + def service: "\\[\\\"(backend|forms|tracking|realtime)\\\"\\]"; + def normalize: + map(.mountPoints //= [] | .systemControls //= [] | .volumesFrom //= [] | + .portMappings = ((.portMappings // []) | map(.hostPort //= .containerPort))); + def same_except($keys): + (.change.before | delpaths($keys | map([.]))) == (.change.after | delpaths($keys | map([.]))); + def same_task_settings: + .change.before as $before | .change.after as $after | + all(["cpu", "memory", "execution_role_arn", "task_role_arn", "family", "network_mode", + "runtime_platform", "requires_compatibilities", "volume", "ephemeral_storage", "tags"][]; + . as $key | $before[$key] == $after[$key]); + def same_container_except_loopback: + (.change.before.container_definitions | fromjson | normalize) as $before | + (.change.after.container_definitions | fromjson | normalize) as $after | + ($after | map(.environment |= map(select(.name != "SERVE_HTTP_LOOPBACK_ONLY")))) == $before and + all($after[]; any(.environment[]; .name == "SERVE_HTTP_LOOPBACK_ONLY" and .value == "true")); + [.resource_changes[]? | select(.change.actions != ["no-op"] and .change.actions != ["read"])] as $changes | + all($changes[]; + if (.address | test("^aws_ecs_task_definition\\.service" + service + "$")) then + .change.actions == ["delete", "create"] and same_container_except_loopback and same_task_settings + elif (.address | test("^aws_ecs_service\\.service" + service + "$")) then + .change.actions == ["update"] and same_except(["load_balancer"]) + elif (.address | test("^aws_cloudwatch_metric_alarm\\.target_5xx" + service + "$")) then + .change.actions == ["update"] and same_except(["metric_query"]) + elif (.address | test("^aws_cloudwatch_metric_alarm\\.unhealthy_hosts" + service + "$")) then + .change.actions == ["update"] and same_except(["dimensions"]) + elif (.address | test("^aws_lb_listener_rule\\.(service" + service + "|tracking_alias\\[\\\"[0-9]+\\\"\\])$")) then + .change.actions == ["update"] and same_except(["action"]) + elif (.address | test("^aws_(lb_target_group|vpc_security_group_ingress_rule)\\.service" + service + "$")) then + .change.actions == ["delete"] + elif .address == "aws_vpc_security_group_ingress_rule.internal_backend[0]" then + .change.actions == ["delete"] + else false end) + ' "$1" >/dev/null || { echo 'Plan contains changes outside the runtime TLS switch' >&2; return 1; } +} + +main() { + local action=${1:?} + if [ "$action" = check-plan ]; then check_plan "${2:?}"; return; fi + case "$action" in plan|apply) ;; *) echo 'Unknown action' >&2; return 1 ;; esac + : "${STATE_BUCKET:?}" "${WORK:?}" "${VARS_VERSION:?}" "${RELEASE:?}" + [[ "$VARS_VERSION" != null && "$VARS_VERSION" != *$'\n'* && "$RELEASE" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] + mkdir -p "$WORK" + chmod 700 "$WORK" + umask 077 + local dir=deploy/terraform/aws/runtime vars="$WORK/runtime.tfvars.json" log="$WORK/runtime.log" + aws s3api get-object --bucket "$STATE_BUCKET" --key warmbly/production/vars/runtime-tls.tfvars.json \ + --version-id "$VARS_VERSION" "$vars" >/dev/null + jq -e '.target_tls == "both"' "$vars" >/dev/null + jq -r '.. | strings | select(length >= 6)' "$vars" | while IFS= read -r line; do + printf '::add-mask::%s\n' "$line" >&2 + done + local account cluster prefix definition live + account=$(aws sts get-caller-identity --query Account --output text) + [ "$account" = 925323749693 ] + cluster=$(jq -r '.name // "warmbly-production"' "$vars") + prefix=$cluster + definition=$(aws ecs describe-services --cluster "$cluster" --services "$prefix-backend" --query 'services[0].taskDefinition' --output text) + live=$(aws ecs describe-task-definition --task-definition "$definition" --include TAGS --query "tags[?key=='warmbly-release'].value | [0]" --output text) + [ "$live" = "$RELEASE" ] || { echo 'The live backend release changed' >&2; return 1; } + local service arn count + for service in backend forms tracking realtime; do + arn=$(aws elbv2 describe-target-groups --names "$prefix-$service-tls" --query 'TargetGroups[0].TargetGroupArn' --output text) + count=$(aws elbv2 describe-target-health --target-group-arn "$arn" --query 'TargetHealthDescriptions' --output json | + jq 'if length > 0 and all(.[]; .TargetHealth.State == "healthy") then length else 0 end') + [ "$count" -gt 0 ] || { echo "HTTPS targets are not healthy for $service" >&2; return 1; } + done + terraform -chdir="$dir" init -input=false -no-color -backend-config="bucket=$STATE_BUCKET" >"$log" 2>&1 + terraform -chdir="$dir" plan -input=false -no-color -lock-timeout=5m -var-file="$vars" \ + -var="state_bucket=$STATE_BUCKET" -var=target_tls=on \ + -target=aws_ecs_service.service -target=aws_lb_listener_rule.tracking_alias \ + -target=aws_vpc_security_group_ingress_rule.service -target=aws_vpc_security_group_ingress_rule.internal_backend \ + -out="$WORK/runtime.tfplan" >>"$log" 2>&1 || { echo 'Runtime TLS plan failed; inspect the private runner log' >&2; return 1; } + terraform -chdir="$dir" show -json "$WORK/runtime.tfplan" >"$WORK/runtime.json" + check_plan "$WORK/runtime.json" + local digest + digest=$(jq -cS '[.resource_changes[]? | select(.change.actions != ["no-op"] and .change.actions != ["read"])] | sort_by(.address)' "$WORK/runtime.json" | sha256sum | cut -d' ' -f1) + if [ "$action" = plan ]; then + printf 'digest=%s\n' "$digest" >>"${GITHUB_OUTPUT:?}" + jq -r '.resource_changes[]? | select(.change.actions != ["no-op"] and .change.actions != ["read"]) | "\(.change.actions | join("/")) \(.address)"' "$WORK/runtime.json" >>"${GITHUB_STEP_SUMMARY:?}" + else + [ "$digest" = "${APPROVED_DIGEST:?}" ] || { echo 'Runtime TLS plan changed; start a new approval run' >&2; return 1; } + terraform -chdir="$dir" apply -input=false -no-color -lock-timeout=5m "$WORK/runtime.tfplan" >>"$log" 2>&1 || { echo 'Runtime TLS apply failed; inspect state before retrying' >&2; return 1; } + echo 'Runtime TLS apply completed' + fi +} +main "$@" diff --git a/.github/scripts/runtime-tls.test.sh b/.github/scripts/runtime-tls.test.sh new file mode 100755 index 000000000..925cfcf28 --- /dev/null +++ b/.github/scripts/runtime-tls.test.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/../.." +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +expect() { + local want=$1 address=$2 actions=$3 + jq -n --arg address "$address" --argjson actions "$actions" '{resource_changes:[{address:$address,change:{actions:$actions}}]}' >"$work/plan.json" + if bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" 2>/dev/null; then + [ "$want" = pass ] + else + [ "$want" = fail ] + fi +} +expect pass 'aws_lb_target_group.service["backend"]' '["delete"]' +expect pass 'aws_ecs_service.service["forms"]' '["update"]' +expect pass 'aws_vpc_security_group_ingress_rule.internal_backend[0]' '["delete"]' +expect fail 'aws_ecs_task_definition.validation' '["delete","create"]' +expect fail 'aws_s3_bucket.data' '["delete"]' +expect fail 'aws_ecs_service.service["consumer"]' '["update"]' +expect fail 'aws_lb_target_group.service["backend"]' '["delete","create"]' +jq -n '{resource_changes:[{address:"aws_ecs_task_definition.service[\"backend\"]",change:{actions:["delete","create"],before:{container_definitions:([{image:"pinned",environment:[]}]|tojson)},after:{container_definitions:([{image:"pinned",environment:[{name:"SERVE_HTTP_LOOPBACK_ONLY",value:"true"}]}]|tojson)}}}]}' >"$work/plan.json" +bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" +jq '.resource_changes[0].change.after.container_definitions |= (fromjson | .[0].image = "changed" | tojson)' "$work/plan.json" >"$work/changed.json" +if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" 2>/dev/null; then + echo 'Changed image was accepted' >&2 + exit 1 +fi +jq '.resource_changes[0].change.before.cpu = "512" | .resource_changes[0].change.after.cpu = "1024"' "$work/plan.json" >"$work/changed.json" +if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" 2>/dev/null; then + echo 'Changed task settings were accepted' >&2 + exit 1 +fi +jq -n '{resource_changes:[{address:"aws_ecs_service.service[\"backend\"]",change:{actions:["update"],before:{network_configuration:[]},after:{network_configuration:[{subnets:["other"]}]}}}]}' >"$work/changed.json" +if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" 2>/dev/null; then + echo 'Changed service network was accepted' >&2 + exit 1 +fi +echo 'Runtime TLS plan guards passed' diff --git a/.github/workflows/runtime-tls.yml b/.github/workflows/runtime-tls.yml new file mode 100644 index 000000000..4aa061c85 --- /dev/null +++ b/.github/workflows/runtime-tls.yml @@ -0,0 +1,109 @@ +name: Finalize runtime TLS + +on: + workflow_dispatch: + inputs: + vars_version: + description: S3 version ID of the reviewed runtime-tls.tfvars.json snapshot at stage both + required: true + type: string + release: + description: Currently deployed release, retained for the service redeploy + required: true + type: string + pull_request: + paths: + - '.github/workflows/runtime-tls.yml' + - '.github/scripts/runtime-tls*' + +permissions: + contents: read + +env: + AWS_REGION: us-east-1 + TF_IN_AUTOMATION: "1" + TF_INPUT: "0" + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - run: shellcheck .github/scripts/runtime-tls.sh + - run: bash .github/scripts/runtime-tls.test.sh + + plan: + needs: check + if: github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + environment: aws-infrastructure-plan + permissions: + contents: read + id-token: write + outputs: + digest: ${{ steps.plan.outputs.digest }} + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: hashicorp/setup-terraform@v3 + with: + terraform_version: "1.16.5" + terraform_wrapper: false + - uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: ${{ vars.AWS_TERRAFORM_PLAN_ROLE_ARN }} + aws-region: us-east-1 + - id: plan + env: + STATE_BUCKET: ${{ vars.AWS_TERRAFORM_STATE_BUCKET }} + WORK: ${{ runner.temp }}/runtime-tls + VARS_VERSION: ${{ inputs.vars_version }} + RELEASE: ${{ inputs.release }} + run: .github/scripts/runtime-tls.sh plan + + apply: + needs: plan + runs-on: ubuntu-latest + environment: aws-infrastructure-approval + concurrency: + group: aws-production + cancel-in-progress: false + permissions: + contents: read + id-token: write + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: hashicorp/setup-terraform@v3 + with: + terraform_version: "1.16.5" + terraform_wrapper: false + - uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: ${{ vars.AWS_TERRAFORM_APPLY_ROLE_ARN }} + aws-region: us-east-1 + - env: + STATE_BUCKET: ${{ vars.AWS_TERRAFORM_STATE_BUCKET }} + WORK: ${{ runner.temp }}/runtime-tls + VARS_VERSION: ${{ inputs.vars_version }} + RELEASE: ${{ inputs.release }} + APPROVED_DIGEST: ${{ needs.plan.outputs.digest }} + run: .github/scripts/runtime-tls.sh apply + + redeploy: + needs: apply + permissions: + contents: read + id-token: write + attestations: read + uses: ./.github/workflows/deploy-aws.yml + with: + tag: ${{ inputs.release }} + mode: redeploy + services: backend,forms,tracking,realtime + fleet: false + secrets: inherit diff --git a/docs/content/docs/development/aws-fargate.mdx b/docs/content/docs/development/aws-fargate.mdx index 20a2676ec..2b24ea06b 100644 --- a/docs/content/docs/development/aws-fargate.mdx +++ b/docs/content/docs/development/aws-fargate.mdx @@ -411,6 +411,26 @@ one is `serve` or `both`. Stepping back from `on` is not supported, because it would forward to an HTTP target group that has no tasks yet; roll back images among releases that support `SERVE_TLS` instead. +### Finalize TLS independently + +The manual **Finalize runtime TLS** workflow advances `both` to `on` without +applying other infrastructure changes. After verifying the pinned backend hop +and every HTTPS target, upload the reviewed `both` runtime var file to +`warmbly/production/vars/runtime-tls.tfvars.json` in the private state bucket. +Keep its S3 version ID: the workflow reads that exact version in both jobs. + +Dispatch the workflow from `main` with that version ID and the currently +deployed release tag. It prints resource addresses and actions for review and +waits in `aws-infrastructure-approval`. After approval it rechecks HTTPS target +health, replans and requires the complete resource changes to match the approved +digest. Its scope guard permits only the TLS switch, including loopback listener +settings, and refuses changes to other task definitions or infrastructure. + +After applying, it redeploys the same release to backend, forms, tracking and +realtime through the normal attestation, secret comparison, alarm and bake gates. +It does not start a worker rollout. Persist `target_tls=on` in the authoritative +runtime var file after success, then verify HTTPS target health and routes. + ## One-time GitHub setup 1. On the `aws-production` environment, allow the `v*.*.*` tag pattern next to From 45e4ba23e69924f806b81861d20434d1fe15675b Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sat, 31 Oct 2026 19:25:44 +0100 Subject: [PATCH 044/318] feat: stage runtime TLS routing and draining with live compatibility and cleanup gates --- .github/scripts/runtime-tls.sh | 138 +++++++++++++++--- .github/scripts/runtime-tls.test.sh | 76 +++++++++- .github/workflows/runtime-tls.yml | 23 ++- deploy/terraform/aws/runtime/README.md | 6 +- deploy/terraform/aws/runtime/main.tf | 20 +-- .../aws/runtime/tests/target_tls.tftest.hcl | 73 +++++++++ .../terraform/aws/runtime/tracking-hosts.tf | 8 +- docs/content/docs/development/aws-fargate.mdx | 46 ++++-- 8 files changed, 328 insertions(+), 62 deletions(-) diff --git a/.github/scripts/runtime-tls.sh b/.github/scripts/runtime-tls.sh index 97383e4b6..99984b248 100755 --- a/.github/scripts/runtime-tls.sh +++ b/.github/scripts/runtime-tls.sh @@ -3,48 +3,101 @@ set -euo pipefail check_plan() { - jq -e ' + local stage=${2:-route} + [[ "$stage" = route || "$stage" = drain || "$stage" = on ]] + jq -e --arg stage "$stage" ' def service: "\\[\\\"(backend|forms|tracking|realtime)\\\"\\]"; def normalize: map(.mountPoints //= [] | .systemControls //= [] | .volumesFrom //= [] | .portMappings = ((.portMappings // []) | map(.hostPort //= .containerPort))); def same_except($keys): (.change.before | delpaths($keys | map([.]))) == (.change.after | delpaths($keys | map([.]))); + def normalize_empty_description: + .change.actions == ["update"] and same_except(["description"]) and + .change.before.description == "" and .change.after.description == null; + def task_settings: + del(.arn, .arn_without_revision, .id, .revision, .container_definitions) | + .enable_fault_injection //= false | .ipc_mode //= "" | .pid_mode //= ""; def same_task_settings: - .change.before as $before | .change.after as $after | - all(["cpu", "memory", "execution_role_arn", "task_role_arn", "family", "network_mode", - "runtime_platform", "requires_compatibilities", "volume", "ephemeral_storage", "tags"][]; - . as $key | $before[$key] == $after[$key]); + (.change.before | task_settings) == (.change.after | task_settings); def same_container_except_loopback: (.change.before.container_definitions | fromjson | normalize) as $before | (.change.after.container_definitions | fromjson | normalize) as $after | - ($after | map(.environment |= map(select(.name != "SERVE_HTTP_LOOPBACK_ONLY")))) == $before and - all($after[]; any(.environment[]; .name == "SERVE_HTTP_LOOPBACK_ONLY" and .value == "true")); + ($after | map(.environment |= map(select(.name != "SERVE_HTTP_LOOPBACK_ONLY")))) == + ($before | map(.environment |= map(select(.name != "SERVE_HTTP_LOOPBACK_ONLY")))) and + all($after[]; if $stage == "on" then + any(.environment[]; .name == "SERVE_HTTP_LOOPBACK_ONLY" and .value == "true") + else all(.environment[]; .name != "SERVE_HTTP_LOOPBACK_ONLY") end); [.resource_changes[]? | select(.change.actions != ["no-op"] and .change.actions != ["read"])] as $changes | all($changes[]; if (.address | test("^aws_ecs_task_definition\\.service" + service + "$")) then .change.actions == ["delete", "create"] and same_container_except_loopback and same_task_settings elif (.address | test("^aws_ecs_service\\.service" + service + "$")) then - .change.actions == ["update"] and same_except(["load_balancer"]) + .change.actions == ["update"] and same_except(["load_balancer"]) and + ($stage == "drain") and + (.change.before.load_balancer | length == 2) and + (.change.after.load_balancer | length == 1) and + (.change.after.load_balancer[0] as $tls | + ($tls.target_group_arn | contains("-tls/")) and + (.change.before.load_balancer | index($tls) != null)) elif (.address | test("^aws_cloudwatch_metric_alarm\\.target_5xx" + service + "$")) then .change.actions == ["update"] and same_except(["metric_query"]) elif (.address | test("^aws_cloudwatch_metric_alarm\\.unhealthy_hosts" + service + "$")) then .change.actions == ["update"] and same_except(["dimensions"]) elif (.address | test("^aws_lb_listener_rule\\.(service" + service + "|tracking_alias\\[\\\"[0-9]+\\\"\\])$")) then .change.actions == ["update"] and same_except(["action"]) - elif (.address | test("^aws_(lb_target_group|vpc_security_group_ingress_rule)\\.service" + service + "$")) then - .change.actions == ["delete"] - elif .address == "aws_vpc_security_group_ingress_rule.internal_backend[0]" then - .change.actions == ["delete"] + elif (.address | test("^aws_lb_target_group\\.service" + service + "$")) then + $stage == "on" and .change.actions == ["delete"] + elif (.address | test("^aws_vpc_security_group_ingress_rule\\.service" + service + "$")) or + .address == "aws_vpc_security_group_ingress_rule.internal_backend[0]" then + ($stage == "on" and .change.actions == ["delete"]) or normalize_empty_description else false end) ' "$1" >/dev/null || { echo 'Plan contains changes outside the runtime TLS switch' >&2; return 1; } } +check_live() { + jq -e --arg stage "$2" --arg release "$3" --arg port "$4" --arg prefix "$5" ' + . as $live | + (.services.failures | length == 0) and + ([.services.services[].serviceName] | sort) == + (["backend", "forms", "tracking", "realtime"] | map($prefix + "-" + .) | sort) and + all(.services.services[]; + . as $service | + .desiredCount > 0 and .runningCount == .desiredCount and .pendingCount == 0 and + (.deployments | length == 1) and .deployments[0].rolloutState == "COMPLETED" and + (.loadBalancers | length == (if $stage == "on" then 1 else 2 end)) and + any(.loadBalancers[]; .containerPort == ($port | tonumber) and + (.targetGroupArn | contains("-tls/"))) and + any($live.definitions[]; + .taskDefinition.taskDefinitionArn == $service.taskDefinition and + any(.tags[]; .key == "warmbly-release" and .value == $release) and + (.taskDefinition.containerDefinitions | length > 0) and + all(.taskDefinition.containerDefinitions[]; + (.environment | map({key:.name,value:.value}) | from_entries) as $env | + ($env.SERVE_TLS == "supplied" or $env.SERVE_TLS == "self-signed") and + $env.SERVE_TLS_PORT == $port and $env.SERVE_HTTP_LOOPBACK_ONLY != "true"))) + ' "$1" >/dev/null || { echo 'Live services must be stable on the expected release with compatible TLS listeners and registrations' >&2; return 1; } +} + +check_cleanup() { + jq -e ' + (.tlsPort // 8443) as $port | + (.services | length == 4) and (.httpGroups | length == 4) and + all(.services[]; (.loadBalancers | length > 0) and + all(.loadBalancers[]; .containerPort == $port and (.targetGroupArn | contains("-tls/")))) and + all(.httpGroups[]; (.LoadBalancerArns | length == 0) and (.targets | length == 0)) + ' "$1" >/dev/null || { echo 'HTTP listeners and registrations must be drained before cleanup' >&2; return 1; } +} + main() { local action=${1:?} - if [ "$action" = check-plan ]; then check_plan "${2:?}"; return; fi + if [ "$action" = check-plan ]; then check_plan "${2:?}" "${3:-route}"; return; fi + if [ "$action" = check-live ]; then check_live "${2:?}" "${3:?}" "${4:?}" "${5:?}" "${6:?}"; return; fi + if [ "$action" = check-cleanup ]; then check_cleanup "${2:?}"; return; fi case "$action" in plan|apply) ;; *) echo 'Unknown action' >&2; return 1 ;; esac : "${STATE_BUCKET:?}" "${WORK:?}" "${VARS_VERSION:?}" "${RELEASE:?}" + : "${STAGE:?}" + [[ "$STAGE" = route || "$STAGE" = drain || "$STAGE" = on ]] [[ "$VARS_VERSION" != null && "$VARS_VERSION" != *$'\n'* && "$RELEASE" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] mkdir -p "$WORK" chmod 700 "$WORK" @@ -52,33 +105,71 @@ main() { local dir=deploy/terraform/aws/runtime vars="$WORK/runtime.tfvars.json" log="$WORK/runtime.log" aws s3api get-object --bucket "$STATE_BUCKET" --key warmbly/production/vars/runtime-tls.tfvars.json \ --version-id "$VARS_VERSION" "$vars" >/dev/null - jq -e '.target_tls == "both"' "$vars" >/dev/null + local previous=both + case "$STAGE" in drain) previous=route ;; on) previous=drain ;; esac + jq -e --arg previous "$previous" '.target_tls == $previous' "$vars" >/dev/null jq -r '.. | strings | select(length >= 6)' "$vars" | while IFS= read -r line; do printf '::add-mask::%s\n' "$line" >&2 done - local account cluster prefix definition live + local account cluster prefix definition port account=$(aws sts get-caller-identity --query Account --output text) [ "$account" = 925323749693 ] cluster=$(jq -r '.name // "warmbly-production"' "$vars") prefix=$cluster - definition=$(aws ecs describe-services --cluster "$cluster" --services "$prefix-backend" --query 'services[0].taskDefinition' --output text) - live=$(aws ecs describe-task-definition --task-definition "$definition" --include TAGS --query "tags[?key=='warmbly-release'].value | [0]" --output text) - [ "$live" = "$RELEASE" ] || { echo 'The live backend release changed' >&2; return 1; } + port=$(jq -r '.target_tls_port // 8443' "$vars") + aws ecs describe-services --cluster "$cluster" --services \ + "$prefix-backend" "$prefix-forms" "$prefix-tracking" "$prefix-realtime" >"$WORK/services.json" + : >"$WORK/definitions.jsonl" + while IFS= read -r definition; do + aws ecs describe-task-definition --task-definition "$definition" --include TAGS >>"$WORK/definitions.jsonl" + done < <(jq -r '.services[].taskDefinition' "$WORK/services.json") + jq -n --slurpfile services "$WORK/services.json" --slurpfile definitions "$WORK/definitions.jsonl" \ + '{services:$services[0],definitions:$definitions}' >"$WORK/live.json" + check_live "$WORK/live.json" "$STAGE" "$RELEASE" "$port" "$prefix" local service arn count for service in backend forms tracking realtime; do arn=$(aws elbv2 describe-target-groups --names "$prefix-$service-tls" --query 'TargetGroups[0].TargetGroupArn' --output text) count=$(aws elbv2 describe-target-health --target-group-arn "$arn" --query 'TargetHealthDescriptions' --output json | jq 'if length > 0 and all(.[]; .TargetHealth.State == "healthy") then length else 0 end') [ "$count" -gt 0 ] || { echo "HTTPS targets are not healthy for $service" >&2; return 1; } + if [ "$STAGE" = route ]; then + arn=$(aws elbv2 describe-target-groups --names "$prefix-$service" --query 'TargetGroups[0].TargetGroupArn' --output text) + count=$(aws elbv2 describe-target-health --target-group-arn "$arn" --query 'TargetHealthDescriptions' --output json | + jq 'if length > 0 and all(.[]; .TargetHealth.State == "healthy") then length else 0 end') + [ "$count" -gt 0 ] || { echo "HTTP fallback is not healthy for $service" >&2; return 1; } + fi done + if [ "$STAGE" != route ]; then + : "${PREVIOUS_RUN:?}" "${GITHUB_REPOSITORY:?}" + [[ "$PREVIOUS_RUN" =~ ^[0-9]+$ ]] + gh api "repos/$GITHUB_REPOSITORY/actions/runs/$PREVIOUS_RUN" | + jq -e --arg title "Runtime TLS $previous $RELEASE" ' + .conclusion == "success" and .head_branch == "main" and + .path == ".github/workflows/runtime-tls.yml" and .display_title == $title + ' >/dev/null || { echo 'The preceding stage workflow and its release bakes must succeed first' >&2; return 1; } + fi + if [ "$STAGE" = on ]; then + aws elbv2 describe-target-groups --names "$prefix-backend" "$prefix-forms" \ + "$prefix-tracking" "$prefix-realtime" >"$WORK/http-groups.json" + : >"$WORK/http-health.jsonl" + while IFS= read -r arn; do + aws elbv2 describe-target-health --target-group-arn "$arn" | + jq --arg arn "$arn" '{arn:$arn,targets:.TargetHealthDescriptions}' >>"$WORK/http-health.jsonl" + done < <(jq -r '.TargetGroups[].TargetGroupArn' "$WORK/http-groups.json") + jq -n --slurpfile services "$WORK/services.json" --slurpfile groups "$WORK/http-groups.json" \ + --argjson port "$(jq '.target_tls_port // 8443' "$vars")" \ + --slurpfile health "$WORK/http-health.jsonl" '{tlsPort:$port,services:$services[0].services,httpGroups:[ + $groups[0].TargetGroups[] | . as $group | . + {targets:[$health[] | select(.arn == $group.TargetGroupArn) | .targets[]]}]}' >"$WORK/cleanup.json" + check_cleanup "$WORK/cleanup.json" + fi terraform -chdir="$dir" init -input=false -no-color -backend-config="bucket=$STATE_BUCKET" >"$log" 2>&1 terraform -chdir="$dir" plan -input=false -no-color -lock-timeout=5m -var-file="$vars" \ - -var="state_bucket=$STATE_BUCKET" -var=target_tls=on \ + -var="state_bucket=$STATE_BUCKET" -var="target_tls=$STAGE" \ -target=aws_ecs_service.service -target=aws_lb_listener_rule.tracking_alias \ -target=aws_vpc_security_group_ingress_rule.service -target=aws_vpc_security_group_ingress_rule.internal_backend \ -out="$WORK/runtime.tfplan" >>"$log" 2>&1 || { echo 'Runtime TLS plan failed; inspect the private runner log' >&2; return 1; } terraform -chdir="$dir" show -json "$WORK/runtime.tfplan" >"$WORK/runtime.json" - check_plan "$WORK/runtime.json" + check_plan "$WORK/runtime.json" "$STAGE" local digest digest=$(jq -cS '[.resource_changes[]? | select(.change.actions != ["no-op"] and .change.actions != ["read"])] | sort_by(.address)' "$WORK/runtime.json" | sha256sum | cut -d' ' -f1) if [ "$action" = plan ]; then @@ -86,7 +177,12 @@ main() { jq -r '.resource_changes[]? | select(.change.actions != ["no-op"] and .change.actions != ["read"]) | "\(.change.actions | join("/")) \(.address)"' "$WORK/runtime.json" >>"${GITHUB_STEP_SUMMARY:?}" else [ "$digest" = "${APPROVED_DIGEST:?}" ] || { echo 'Runtime TLS plan changed; start a new approval run' >&2; return 1; } - terraform -chdir="$dir" apply -input=false -no-color -lock-timeout=5m "$WORK/runtime.tfplan" >>"$log" 2>&1 || { echo 'Runtime TLS apply failed; inspect state before retrying' >&2; return 1; } + if ! terraform -chdir="$dir" apply -input=false -no-color -lock-timeout=5m "$WORK/runtime.tfplan" >>"$log" 2>&1; then + local diagnostic="warmbly/production/diagnostics/runtime-tls/${GITHUB_RUN_ID:?}/${GITHUB_RUN_ATTEMPT:?}/apply.log" + aws s3 cp "$log" "s3://$STATE_BUCKET/$diagnostic" --only-show-errors || echo 'Private diagnostic upload failed' >&2 + echo "Runtime TLS apply failed; inspect state and private diagnostic $diagnostic before retrying" >&2 + return 1 + fi echo 'Runtime TLS apply completed' fi } diff --git a/.github/scripts/runtime-tls.test.sh b/.github/scripts/runtime-tls.test.sh index 925cfcf28..e82a4c481 100755 --- a/.github/scripts/runtime-tls.test.sh +++ b/.github/scripts/runtime-tls.test.sh @@ -4,30 +4,60 @@ cd "$(dirname "$0")/../.." work=$(mktemp -d) trap 'rm -rf "$work"' EXIT expect() { - local want=$1 address=$2 actions=$3 + local want=$1 address=$2 actions=$3 stage=${4:-route} jq -n --arg address "$address" --argjson actions "$actions" '{resource_changes:[{address:$address,change:{actions:$actions}}]}' >"$work/plan.json" - if bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" 2>/dev/null; then + if bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" "$stage" 2>/dev/null; then [ "$want" = pass ] else [ "$want" = fail ] fi } -expect pass 'aws_lb_target_group.service["backend"]' '["delete"]' -expect pass 'aws_ecs_service.service["forms"]' '["update"]' -expect pass 'aws_vpc_security_group_ingress_rule.internal_backend[0]' '["delete"]' +expect fail 'aws_lb_target_group.service["backend"]' '["delete"]' +expect pass 'aws_lb_target_group.service["backend"]' '["delete"]' on +expect fail 'aws_ecs_service.service["forms"]' '["update"]' +expect fail 'aws_vpc_security_group_ingress_rule.internal_backend[0]' '["delete"]' +expect pass 'aws_vpc_security_group_ingress_rule.internal_backend[0]' '["delete"]' on +expect fail 'aws_vpc_security_group_ingress_rule.service["backend"]' '["delete"]' +expect pass 'aws_vpc_security_group_ingress_rule.service["backend"]' '["delete"]' on expect fail 'aws_ecs_task_definition.validation' '["delete","create"]' expect fail 'aws_s3_bucket.data' '["delete"]' expect fail 'aws_ecs_service.service["consumer"]' '["update"]' expect fail 'aws_lb_target_group.service["backend"]' '["delete","create"]' +expect fail 'aws_lb_target_group.service["backend"]' '["delete"]' drain +expect fail 'aws_vpc_security_group_ingress_rule.internal_backend[0]' '["delete"]' drain +jq -n '{resource_changes:[{address:"aws_ecs_service.service[\"forms\"]",change:{actions:["update"], + before:{load_balancer:[{target_group_arn:"forms/1",container_port:8090},{target_group_arn:"forms-tls/2",container_port:8443}]}, + after:{load_balancer:[{target_group_arn:"forms-tls/2",container_port:8443}]}}}]}' >"$work/plan.json" +bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" drain +for stage in route on; do + if bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" "$stage" 2>/dev/null; then + echo 'Registration detached outside the drain stage' >&2 + exit 1 + fi +done +jq -n '{resource_changes:[{address:"aws_vpc_security_group_ingress_rule.service[\"backend\"]",change:{actions:["update"], + before:{description:"",from_port:8080},after:{description:null,from_port:8080}}}]}' >"$work/plan.json" +bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" route +jq '.resource_changes[0].change.after.from_port=8443' "$work/plan.json" >"$work/changed.json" +if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" route 2>/dev/null; then + echo 'Network change accepted as metadata normalization' >&2 + exit 1 +fi jq -n '{resource_changes:[{address:"aws_ecs_task_definition.service[\"backend\"]",change:{actions:["delete","create"],before:{container_definitions:([{image:"pinned",environment:[]}]|tojson)},after:{container_definitions:([{image:"pinned",environment:[{name:"SERVE_HTTP_LOOPBACK_ONLY",value:"true"}]}]|tojson)}}}]}' >"$work/plan.json" -bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" +bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" on +if bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" route 2>/dev/null; then + echo 'Loopback-only listener accepted before HTTP registrations drained' >&2 + exit 1 +fi +jq '.resource_changes[0].change |= ({actions:.actions,before:.after,after:.before})' "$work/plan.json" >"$work/route.json" +bash .github/scripts/runtime-tls.sh check-plan "$work/route.json" route jq '.resource_changes[0].change.after.container_definitions |= (fromjson | .[0].image = "changed" | tojson)' "$work/plan.json" >"$work/changed.json" -if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" 2>/dev/null; then +if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" on 2>/dev/null; then echo 'Changed image was accepted' >&2 exit 1 fi jq '.resource_changes[0].change.before.cpu = "512" | .resource_changes[0].change.after.cpu = "1024"' "$work/plan.json" >"$work/changed.json" -if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" 2>/dev/null; then +if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" on 2>/dev/null; then echo 'Changed task settings were accepted' >&2 exit 1 fi @@ -36,4 +66,34 @@ if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" 2>/dev/nu echo 'Changed service network was accepted' >&2 exit 1 fi +jq -n '{services:[range(4) | {loadBalancers:[{containerPort:8443,targetGroupArn:"service-tls/123"}]}], + httpGroups:[range(4) | {LoadBalancerArns:[],targets:[]}]}' >"$work/cleanup.json" +bash .github/scripts/runtime-tls.sh check-cleanup "$work/cleanup.json" +for change in '.services[0].loadBalancers[0].containerPort=8080' \ + '.httpGroups[0].LoadBalancerArns=["listener"]' '.httpGroups[0].targets=[{Id:"still-draining"}]' \ + '.services=[]'; do + jq "$change" "$work/cleanup.json" >"$work/changed.json" + if bash .github/scripts/runtime-tls.sh check-cleanup "$work/changed.json" 2>/dev/null; then + echo 'HTTP cleanup accepted before all references drained' >&2 + exit 1 + fi +done +jq -n ' + ["backend","forms","tracking","realtime"] as $names | + {services:{failures:[],services:[$names[] | {serviceName:("test-"+.),taskDefinition:.,desiredCount:1,runningCount:1,pendingCount:0, + deployments:[{rolloutState:"COMPLETED"}],loadBalancers:[{containerPort:8080,targetGroupArn:(.+"/1")},{containerPort:8443,targetGroupArn:(.+"-tls/2")}]}]}, + definitions:[$names[] | {tags:[{key:"warmbly-release",value:"v0.6.70"}],taskDefinition:{taskDefinitionArn:.,containerDefinitions:[{ + environment:[{name:"SERVE_TLS",value:"supplied"},{name:"SERVE_TLS_PORT",value:"8443"}]}]}}]}' >"$work/live.json" +bash .github/scripts/runtime-tls.sh check-live "$work/live.json" route v0.6.70 8443 test +for change in '.services.services[0].pendingCount=1' '.services.services[0].deployments[0].rolloutState="IN_PROGRESS"' \ + '.services.services[0].loadBalancers|=.[0:1]' '.definitions[0].tags[0].value="v0.6.69"' \ + '.definitions[0].taskDefinition.containerDefinitions[0].environment=[]' \ + '.definitions[0].taskDefinition.containerDefinitions[0].environment += [{name:"SERVE_HTTP_LOOPBACK_ONLY",value:"true"}]' \ + '.services.services|=.[0:3]'; do + jq "$change" "$work/live.json" >"$work/changed.json" + if bash .github/scripts/runtime-tls.sh check-live "$work/changed.json" route v0.6.70 8443 test 2>/dev/null; then + echo 'Incompatible or unstable live services accepted' >&2 + exit 1 + fi +done echo 'Runtime TLS plan guards passed' diff --git a/.github/workflows/runtime-tls.yml b/.github/workflows/runtime-tls.yml index 4aa061c85..a97eb8b01 100644 --- a/.github/workflows/runtime-tls.yml +++ b/.github/workflows/runtime-tls.yml @@ -1,12 +1,23 @@ name: Finalize runtime TLS +run-name: Runtime TLS ${{ inputs.stage }} ${{ inputs.release }} on: workflow_dispatch: inputs: vars_version: - description: S3 version ID of the reviewed runtime-tls.tfvars.json snapshot at stage both + description: S3 version ID of the reviewed runtime-tls.tfvars.json snapshot at the previous stage required: true type: string + stage: + description: Advance one verified stage while preserving the previous traffic path + required: true + default: route + type: choice + options: [route, drain, on] + previous_run: + description: Successful preceding stage workflow run ID (required for drain and on) + required: false + type: string release: description: Currently deployed release, retained for the service redeploy required: true @@ -31,7 +42,7 @@ jobs: - uses: actions/checkout@v4 with: persist-credentials: false - - run: shellcheck .github/scripts/runtime-tls.sh + - run: shellcheck .github/scripts/runtime-tls.sh .github/scripts/runtime-tls.test.sh - run: bash .github/scripts/runtime-tls.test.sh plan: @@ -42,6 +53,7 @@ jobs: permissions: contents: read id-token: write + actions: read outputs: digest: ${{ steps.plan.outputs.digest }} steps: @@ -62,6 +74,9 @@ jobs: WORK: ${{ runner.temp }}/runtime-tls VARS_VERSION: ${{ inputs.vars_version }} RELEASE: ${{ inputs.release }} + STAGE: ${{ inputs.stage }} + PREVIOUS_RUN: ${{ inputs.previous_run }} + GH_TOKEN: ${{ github.token }} run: .github/scripts/runtime-tls.sh plan apply: @@ -74,6 +89,7 @@ jobs: permissions: contents: read id-token: write + actions: read steps: - uses: actions/checkout@v4 with: @@ -92,6 +108,9 @@ jobs: VARS_VERSION: ${{ inputs.vars_version }} RELEASE: ${{ inputs.release }} APPROVED_DIGEST: ${{ needs.plan.outputs.digest }} + STAGE: ${{ inputs.stage }} + PREVIOUS_RUN: ${{ inputs.previous_run }} + GH_TOKEN: ${{ github.token }} run: .github/scripts/runtime-tls.sh apply redeploy: diff --git a/deploy/terraform/aws/runtime/README.md b/deploy/terraform/aws/runtime/README.md index 04648ec24..966daa8a3 100644 --- a/deploy/terraform/aws/runtime/README.md +++ b/deploy/terraform/aws/runtime/README.md @@ -71,8 +71,10 @@ closes. ## TLS behind the load balancer `target_tls` moves the load balancer's target groups and the forms and tracking -services' internal calls to the backend onto TLS, in four stages (`off`, -`serve`, `both`, `on`) advanced one apply at a time. The backend serves the +services' internal calls to the backend onto TLS, in six stages (`off`, +`serve`, `both`, `route`, `drain`, `on`) advanced one apply at a time. Route keeps +the healthy HTTP path while HTTPS bakes; drain removes references and waits for +registrations to empty before a separately approved cleanup. The backend serves the certificate in `backend_internal_certificate` with `SERVE_TLS_KEY` from its secret, and its callers trust only that certificate. Prerequisites, the stages and what each one changes are in `aws-fargate.mdx` under "Encrypt traffic inside diff --git a/deploy/terraform/aws/runtime/main.tf b/deploy/terraform/aws/runtime/main.tf index fabe308de..10d999c5d 100644 --- a/deploy/terraform/aws/runtime/main.tf +++ b/deploy/terraform/aws/runtime/main.tf @@ -84,12 +84,12 @@ variable "services" { } variable "target_tls" { - description = "Stage of the move to TLS behind the load balancer: off, serve, both, on. Advance one stage per apply and let each redeploy finish" + description = "Stage of the move to TLS behind the load balancer: off, serve, both, route, drain, on. Advance one stage per apply and let each redeploy finish" type = string default = "off" validation { - condition = contains(["off", "serve", "both", "on"], var.target_tls) - error_message = "target_tls is off, serve, both or on." + condition = contains(["off", "serve", "both", "route", "drain", "on"], var.target_tls) + error_message = "target_tls is off, serve, both, route, drain or on." } } variable "target_tls_port" { @@ -129,7 +129,7 @@ locals { # Each stage keeps the previous one's listeners, so a rolling deploy never meets a task that cannot answer. tls_serving = var.target_tls != "off" http_targets = var.target_tls != "on" - tls_targets = contains(["both", "on"], var.target_tls) + tls_targets = contains(["both", "route", "drain", "on"], var.target_tls) tls_services = { for name, service in var.services : name => service if service.port != null && (contains(keys(local.public_services), name) || name == "backend") } @@ -342,7 +342,7 @@ resource "aws_lb_target_group" "service_tls" { } locals { # The group the listener sends traffic to; in both, the TLS group is attached at weight 0 while it fills. - serving_target_groups = var.target_tls == "on" ? aws_lb_target_group.service_tls : aws_lb_target_group.service + serving_target_groups = contains(["route", "drain", "on"], var.target_tls) ? aws_lb_target_group.service_tls : aws_lb_target_group.service } resource "aws_lb_listener" "https" { load_balancer_arn = aws_lb.main.arn @@ -373,17 +373,17 @@ resource "aws_lb_listener_rule" "service" { } action { type = "forward" - target_group_arn = var.target_tls == "both" ? null : local.serving_target_groups[each.key].arn + target_group_arn = contains(["both", "route"], var.target_tls) ? null : local.serving_target_groups[each.key].arn dynamic "forward" { - for_each = var.target_tls == "both" ? [each.key] : [] + for_each = contains(["both", "route"], var.target_tls) ? [each.key] : [] content { target_group { arn = aws_lb_target_group.service[forward.value].arn - weight = 1 + weight = var.target_tls == "both" ? 1 : 0 } target_group { arn = aws_lb_target_group.service_tls[forward.value].arn - weight = 0 + weight = var.target_tls == "route" ? 1 : 0 } } } @@ -510,7 +510,7 @@ resource "aws_ecs_service" "service" { assign_public_ip = true } dynamic "load_balancer" { - for_each = contains(keys(local.public_services), each.key) && local.http_targets ? [each.value.port] : [] + for_each = contains(keys(local.public_services), each.key) && local.http_targets && var.target_tls != "drain" ? [each.value.port] : [] content { target_group_arn = aws_lb_target_group.service[each.key].arn container_name = each.key diff --git a/deploy/terraform/aws/runtime/tests/target_tls.tftest.hcl b/deploy/terraform/aws/runtime/tests/target_tls.tftest.hcl index 902b2c459..fe67e0e5c 100644 --- a/deploy/terraform/aws/runtime/tests/target_tls.tftest.hcl +++ b/deploy/terraform/aws/runtime/tests/target_tls.tftest.hcl @@ -28,6 +28,14 @@ mock_provider "aws" { } } +override_resource { + target = aws_lb_target_group.service["tracking"] + values = { + arn = "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/http/1" + arn_suffix = "targetgroup/http/1" + } +} + override_data { target = data.terraform_remote_state.foundation values = { @@ -56,6 +64,7 @@ variables { state_bucket = "state" certificate_primary_domain = "warmbly.com" origin_ipv4_cidrs = ["173.245.48.0/20"] + tracking_additional_hosts = ["link.example.com"] backend_internal_certificate = "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n" services = { backend = { image = "r/backend@sha256:0000000000000000000000000000000000000000000000000000000000000000", cpu = 256, memory = 512, port = 8080, host = "api.warmbly.com", secret_version_id = "v", secret_keys = ["SERVE_TLS_KEY"] } @@ -127,6 +136,70 @@ run "both_attaches_the_tls_group_at_weight_zero" { } } +run "route_preserves_healthy_http_fallback" { + command = apply + variables { + target_tls = "route" + } + assert { + condition = length(aws_lb_target_group.service) == 4 && length(aws_vpc_security_group_ingress_rule.service) == 4 && length(aws_vpc_security_group_ingress_rule.internal_backend) == 1 + error_message = "route retains every HTTP target group and network rule" + } + assert { + condition = alltrue([for service in aws_ecs_service.service : length(service.load_balancer) == 0 || length(service.load_balancer) == 2]) + error_message = "route keeps both target registrations ready" + } + assert { + condition = alltrue([for group in aws_lb_listener_rule.service["tracking"].action[0].forward[0].target_group : group.arn == aws_lb_target_group.service_tls["tracking"].arn ? group.weight == 1 : group.weight == 0]) + error_message = "route sends traffic to HTTPS only" + } + assert { + condition = length(aws_lb_listener_rule.tracking_alias["0"].action[0].forward[0].target_group) == 2 && !strcontains(aws_ecs_task_definition.service["backend"].container_definitions, "SERVE_HTTP_LOOPBACK_ONLY") + error_message = "aliases retain fallback and HTTP remains available during route bake" + } +} + +run "route_can_return_to_healthy_http" { + command = apply + variables { + target_tls = "both" + } + assert { + condition = length(aws_ecs_service.service["tracking"].load_balancer) == 2 && alltrue([for group in aws_lb_listener_rule.service["tracking"].action[0].forward[0].target_group : group.arn == aws_lb_target_group.service["tracking"].arn ? group.weight == 1 : group.weight == 0]) + error_message = "returning to both routes to the retained HTTP registrations" + } +} + +run "restore_route_before_drain" { + command = apply + variables { + target_tls = "route" + } + assert { + condition = length(aws_ecs_service.service["tracking"].load_balancer) == 2 && length(aws_lb_target_group.service) == 4 + error_message = "restoring route retains the HTTP fallback" + } +} + +run "drain_removes_registrations_before_resources" { + command = apply + variables { + target_tls = "drain" + } + assert { + condition = length(aws_lb_target_group.service) == 4 && length(aws_vpc_security_group_ingress_rule.service) == 4 && length(aws_vpc_security_group_ingress_rule.internal_backend) == 1 + error_message = "drain retains HTTP resources until registrations have drained" + } + assert { + condition = alltrue([for service in aws_ecs_service.service : length(service.load_balancer) == 0 || alltrue([for lb in service.load_balancer : lb.container_port == 8443])]) + error_message = "drain registers only HTTPS targets" + } + assert { + condition = aws_lb_listener_rule.service["tracking"].action[0].target_group_arn == aws_lb_target_group.service_tls["tracking"].arn && aws_lb_listener_rule.tracking_alias["0"].action[0].target_group_arn == aws_lb_target_group.service_tls["tracking"].arn + error_message = "primary and alias listeners have only HTTPS references before cleanup" + } +} + run "on_forwards_tls_and_drops_plain" { command = apply variables { diff --git a/deploy/terraform/aws/runtime/tracking-hosts.tf b/deploy/terraform/aws/runtime/tracking-hosts.tf index 39f2e6a14..f648fc4ee 100644 --- a/deploy/terraform/aws/runtime/tracking-hosts.tf +++ b/deploy/terraform/aws/runtime/tracking-hosts.tf @@ -21,17 +21,17 @@ resource "aws_lb_listener_rule" "tracking_alias" { } action { type = "forward" - target_group_arn = var.target_tls == "both" ? null : local.serving_target_groups["tracking"].arn + target_group_arn = contains(["both", "route"], var.target_tls) ? null : local.serving_target_groups["tracking"].arn dynamic "forward" { - for_each = var.target_tls == "both" ? ["tracking"] : [] + for_each = contains(["both", "route"], var.target_tls) ? ["tracking"] : [] content { target_group { arn = aws_lb_target_group.service[forward.value].arn - weight = 1 + weight = var.target_tls == "both" ? 1 : 0 } target_group { arn = aws_lb_target_group.service_tls[forward.value].arn - weight = 0 + weight = var.target_tls == "route" ? 1 : 0 } } } diff --git a/docs/content/docs/development/aws-fargate.mdx b/docs/content/docs/development/aws-fargate.mdx index 2b24ea06b..fac16624e 100644 --- a/docs/content/docs/development/aws-fargate.mdx +++ b/docs/content/docs/development/aws-fargate.mdx @@ -386,7 +386,7 @@ stops click tracking and hosted forms. ### Move through the stages -`target_tls` takes four values. Change it one stage at a time, and let each +`target_tls` takes six values. Change it one stage at a time, and let each merge finish its apply and redeploy before the next: | Stage | What changes | @@ -394,42 +394,58 @@ merge finish its apply and redeploy before the next: | `off` | Nothing; tasks serve plain HTTP only | | `serve` | Every load-balanced task also serves TLS on `target_tls_port` (default `8443`), and the security groups open that port to the load balancer and between tasks. Traffic is unchanged | | `both` | An HTTPS target group per service is attached to its listener rule at weight 0 and the tasks register in both groups. The forms and tracking services move to the backend's TLS port | -| `on` | The listener rules forward to the HTTPS groups. The HTTP groups, the plain-port security group rules and the internal `8080` rule are removed, and every plain listener is bound to loopback for the container health check only | +| `route` | Listener rules forward to HTTPS and alarms watch the HTTPS groups. The HTTP groups, healthy registrations and network rules remain ready while the new path bakes | +| `drain` | After the route deployment and bakes pass, ECS stops registering HTTP targets and listeners drop their HTTP references. The groups and network rules remain while connections drain | +| `on` | After the drain deployment and bakes pass, the empty HTTP groups, the plain-port security group rules and the internal `8080` rule are removed. Every plain listener is bound to loopback for the container health check only | Each stage keeps the listeners the previous one used, so a rolling deploy never meets a task that cannot answer. `serve` and `both` only add task definition -revisions and resources, so they apply on their own. `on` destroys the HTTP -target groups and waits for approval in `aws-infrastructure-approval`. In -`both` and `on` the ECS services wait for a steady state before the apply moves -on, so traffic switches only to a target group whose tasks are healthy. +revisions and resources, so they apply on their own. `route` performs the traffic +switch without deleting network rules or target groups. It must finish its normal +release redeploy and bakes before a separately approved `drain` run. Cleanup checks +that the HTTP groups have no load balancer references or registered targets and +that every public service uses only its HTTPS target group. ECS waits for a steady +state during these stages. Before `serve`, the running release has to support `SERVE_TLS`. An older image ignores the setting and keeps working in `serve`, but not in `both` or `on`, so advance past `serve` only once rolling back to a release without it is no longer needed. A stage can be undone by setting the previous one while the current -one is `serve` or `both`. Stepping back from `on` is not supported, because it +one is `serve` or `both`. From `route`, returning to `both` sends traffic to the +still-registered HTTP targets. From `drain`, return to `route` first and wait for +healthy HTTP registrations before returning to `both`. Stepping back from `on` is not supported, because it would forward to an HTTP target group that has no tasks yet; roll back images among releases that support `SERVE_TLS` instead. ### Finalize TLS independently -The manual **Finalize runtime TLS** workflow advances `both` to `on` without -applying other infrastructure changes. After verifying the pinned backend hop +The manual **Finalize runtime TLS** workflow advances `both` to `route`, then +`drain` and `on` in separate approved runs without applying other infrastructure +changes. After verifying the pinned backend hop and every HTTPS target, upload the reviewed `both` runtime var file to `warmbly/production/vars/runtime-tls.tfvars.json` in the private state bucket. Keep its S3 version ID: the workflow reads that exact version in both jobs. -Dispatch the workflow from `main` with that version ID and the currently -deployed release tag. It prints resource addresses and actions for review and +Dispatch the workflow from `main` with stage `route`, that version ID and the +currently deployed release tag. It prints resource addresses and actions for review and waits in `aws-infrastructure-approval`. After approval it rechecks HTTPS target health, replans and requires the complete resource changes to match the approved -digest. Its scope guard permits only the TLS switch, including loopback listener -settings, and refuses changes to other task definitions or infrastructure. +digest. Each job first requires all four services to be stable on the selected +release with compatible TLS listeners and registrations. Route also requires +healthy HTTP fallback targets. Route and drain plans refuse target-group and security-rule deletions. The scope +guard refuses changes to other task definitions or infrastructure. After applying, it redeploys the same release to backend, forms, tracking and realtime through the normal attestation, secret comparison, alarm and bake gates. -It does not start a worker rollout. Persist `target_tls=on` in the authoritative -runtime var file after success, then verify HTTPS target health and routes. +It does not start a worker rollout. After that run succeeds, persist +`target_tls=route`, verify HTTPS health and routes, and upload a new versioned +snapshot. Dispatch stage `drain` with that snapshot and the successful route run ID +as `previous_run`. After the drain run succeeds, persist `target_tls=drain`, upload +a new snapshot, and dispatch `on` with the successful drain run ID. Each stage +verifies the preceding workflow completed all bakes. Cleanup is refused until +HTTP references and registrations have drained. Review and approve each +plan separately. Persist `target_tls=on` only after it succeeds, then verify the +effective loopback listeners and HTTPS routes. ## One-time GitHub setup From 65b9c754f8f981920c8652285f2e17ae55cd9366 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sat, 31 Oct 2026 19:53:03 +0100 Subject: [PATCH 045/318] feat: generate marketing script hash policies and verify isolated Pages previews before scoped production uploads --- .github/scripts/pages-marketing-preview.mjs | 50 ++++++++ .../scripts/pages-marketing-preview.test.mjs | 57 +++++++++ .github/workflows/marketing-pages.yml | 116 ++++++++++++++++++ .../docs/development/split-deployment.mdx | 21 ++++ site/astro.config.mjs | 2 + site/package.json | 6 +- site/pnpm-lock.yaml | 20 +++ site/public/_headers | 1 + site/scripts/content-security-policy.mjs | 83 +++++++++++++ site/scripts/content-security-policy.test.mjs | 63 ++++++++++ 10 files changed, 418 insertions(+), 1 deletion(-) create mode 100644 .github/scripts/pages-marketing-preview.mjs create mode 100644 .github/scripts/pages-marketing-preview.test.mjs create mode 100644 .github/workflows/marketing-pages.yml create mode 100644 site/scripts/content-security-policy.mjs create mode 100644 site/scripts/content-security-policy.test.mjs diff --git a/.github/scripts/pages-marketing-preview.mjs b/.github/scripts/pages-marketing-preview.mjs new file mode 100644 index 000000000..539b5ff39 --- /dev/null +++ b/.github/scripts/pages-marketing-preview.mjs @@ -0,0 +1,50 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { fileURLToPath } from 'node:url'; + +export function previewURL(deployments, project, branch, sha) { + const matches = deployments.filter(deployment => deployment.environment === 'preview' + && deployment.deployment_trigger?.metadata?.branch === branch + && deployment.deployment_trigger?.metadata?.commit_hash === sha + && deployment.latest_stage?.name === 'deploy' + && deployment.latest_stage?.status === 'success'); + assert.equal(matches.length, 1, 'Require one successful preview for this run and commit'); + const url = new URL(matches[0].url); + assert.equal(url.protocol, 'https:'); + assert.ok(url.hostname.endsWith(`.${project}.pages.dev`), 'Require the configured Pages project'); + assert.ok(!url.username && !url.password && url.pathname === '/' && !url.search && !url.hash); + return url; +} + +export async function verifyPreview(url, policy, request = fetch, directory = new URL('../../site/dist/', import.meta.url)) { + for (const [path, status, type] of [ + ['/', 200, 'text/html'], ['/terms/', 200, 'text/html'], ['/privacy/', 200, 'text/html'], + ['/marketing-csp-missing-page', 404, 'text/html'], + ['/install.sh', 200, null], ['/cli.sh', 200, null], + ]) { + const response = await request(new URL(path, url), { redirect: 'error', signal: AbortSignal.timeout(30000) }); + assert.equal(response.status, status, `Unexpected preview status for ${path}`); + assert.equal(response.headers.get('content-security-policy'), policy, `Unexpected preview CSP for ${path}`); + assert.equal(response.headers.get('x-content-type-options'), 'nosniff'); + if (type) assert.ok(response.headers.get('content-type')?.startsWith(type)); + else assert.equal(await response.text(), await readFile(new URL(path.slice(1), directory), 'utf8')); + } +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + const { CLOUDFLARE_ACCOUNT_ID: account, CLOUDFLARE_PAGES_PROJECT_NAME: project, + CLOUDFLARE_API_TOKEN: token, PREVIEW_BRANCH: branch, GITHUB_SHA: sha } = process.env; + assert.ok(account && project && token && branch && sha, 'Require preview deployment configuration'); + const response = await fetch(`https://api.cloudflare.com/client/v4/accounts/${account}/pages/projects/${project}/deployments?env=preview&per_page=100`, { + headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(30000), + }); + assert.ok(response.ok, `Pages deployment lookup returned ${response.status}`); + const data = await response.json(); + assert.equal(data.success, true, 'Pages deployment lookup must succeed'); + const url = previewURL(data.result, project, branch, sha); + const headers = await readFile(new URL('../../site/dist/_headers', import.meta.url), 'utf8'); + const policies = [...headers.matchAll(/^\s+Content-Security-Policy: (.+)$/gm)]; + assert.equal(policies.length, 1, 'Require one built policy'); + await verifyPreview(url, policies[0][1]); + console.log('Marketing preview headers, routes and published installers verified'); +} diff --git a/.github/scripts/pages-marketing-preview.test.mjs b/.github/scripts/pages-marketing-preview.test.mjs new file mode 100644 index 000000000..067dd9e10 --- /dev/null +++ b/.github/scripts/pages-marketing-preview.test.mjs @@ -0,0 +1,57 @@ +import assert from 'node:assert/strict'; +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { test } from 'node:test'; +import { previewURL, verifyPreview } from './pages-marketing-preview.mjs'; + +test('accepts only this run successful preview on the reviewed commit and project', () => { + const deployment = { environment: 'preview', url: 'https://abc.marketing.pages.dev', + deployment_trigger: { metadata: { branch: 'check-123', commit_hash: 'sha' } }, + latest_stage: { name: 'deploy', status: 'success' } }; + const select = value => previewURL([value], 'marketing', 'check-123', 'sha'); + assert.equal(select(deployment).origin, 'https://abc.marketing.pages.dev'); + for (const override of [ + { environment: 'production' }, { url: 'https://abc.other.pages.dev' }, + { latest_stage: { name: 'deploy', status: 'failure' } }, + { deployment_trigger: { metadata: { branch: 'other', commit_hash: 'sha' } } }, + { deployment_trigger: { metadata: { branch: 'check-123', commit_hash: 'old' } } }, + ]) assert.throws(() => select({ ...deployment, ...override })); + assert.throws(() => previewURL([deployment, deployment], 'marketing', 'check-123', 'sha')); +}); + +test('verifies page, error and byte-identical installer responses with the built policy', async () => { + const root = await mkdtemp(join(tmpdir(), 'marketing-preview-')); + try { + for (const file of ['install.sh', 'cli.sh']) await writeFile(join(root, file), `# ${file}\n`); + const paths = []; + const request = async url => { + paths.push(url.pathname); + const script = url.pathname.endsWith('.sh'); + return new Response(script ? `# ${url.pathname.slice(1)}\n` : 'Page', { + status: url.pathname.includes('missing-page') ? 404 : 200, + headers: { 'content-security-policy': 'policy', 'x-content-type-options': 'nosniff', + 'content-type': script ? 'text/plain' : 'text/html; charset=utf-8' }, + }); + }; + await verifyPreview('https://abc.marketing.pages.dev', 'policy', request, pathToFileURL(`${root}/`)); + assert.deepEqual(paths, ['/', '/terms/', '/privacy/', '/marketing-csp-missing-page', '/install.sh', '/cli.sh']); + await writeFile(join(root, 'cli.sh'), 'different bytes'); + await assert.rejects(verifyPreview('https://abc.marketing.pages.dev', 'policy', request, pathToFileURL(`${root}/`))); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test('blocks promotion for absent or different policy, redirects and unexpected responses', async () => { + for (const response of [ + new Response('', { status: 200 }), + new Response('', { status: 200, headers: { 'content-security-policy': 'other' } }), + new Response('', { status: 503 }), + ]) await assert.rejects(verifyPreview('https://abc.marketing.pages.dev', 'policy', async () => response)); + await assert.rejects(verifyPreview('https://abc.marketing.pages.dev', 'policy', async (url, options) => { + assert.equal(options.redirect, 'error'); + throw new Error('redirect refused'); + }), /redirect refused/); +}); diff --git a/.github/workflows/marketing-pages.yml b/.github/workflows/marketing-pages.yml new file mode 100644 index 000000000..3d3b66a92 --- /dev/null +++ b/.github/workflows/marketing-pages.yml @@ -0,0 +1,116 @@ +name: Deploy marketing Pages + +on: + pull_request: + paths: + - '.github/workflows/marketing-pages.yml' + - '.github/scripts/pages-*' + workflow_dispatch: + inputs: + expected_sha: + description: Reviewed main commit to deploy (full SHA) + required: true + type: string + +permissions: + contents: read + +concurrency: + group: ${{ github.event_name == 'workflow_dispatch' && 'release' || format('marketing-pages-check-{0}', github.ref) }} + cancel-in-progress: false + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "22" + - run: node --test .github/scripts/pages-*.test.mjs + + deploy: + needs: check + if: github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && vars.CLOUDFLARE_PAGES_DEPLOY_ENABLED == 'true' + runs-on: ubuntu-latest + timeout-minutes: 30 + environment: site-production + env: + CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} + PAGES_APP: site + WRANGLER_SEND_METRICS: "false" + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.sha }} + - name: Require the reviewed main commit + env: + EXPECTED_SHA: ${{ inputs.expected_sha }} + run: test "$EXPECTED_SHA" = "$GITHUB_SHA" + - uses: actions/setup-node@v4 + with: + node-version: "22" + - name: Select only the configured marketing project + env: + CLOUDFLARE_PAGES_PROJECTS: ${{ vars.CLOUDFLARE_PAGES_PROJECTS }} + run: | + node --input-type=module <<'JS' + import { appendFileSync } from 'node:fs'; + import { deploymentMatrix } from './.github/scripts/pages-projects.mjs'; + const sites = deploymentMatrix(process.env.CLOUDFLARE_PAGES_PROJECTS).include.filter(target => target.app === 'site'); + if (sites.length !== 1) throw new Error('Configure exactly one marketing Pages project'); + appendFileSync(process.env.GITHUB_ENV, `CLOUDFLARE_PAGES_PROJECT_NAME=${sites[0].project}\n`); + JS + - name: Load existing marketing production configuration + id: config + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + run: | + for name in CLOUDFLARE_API_TOKEN CLOUDFLARE_ACCOUNT_ID CLOUDFLARE_PAGES_PROJECT_NAME; do + test -n "${!name}" + done + curl --fail --silent --show-error \ + --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ + "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/pages/projects/$CLOUDFLARE_PAGES_PROJECT_NAME" \ + | node .github/scripts/pages-production-config.mjs + - uses: pnpm/action-setup@v4 + with: + version: "11.9.0" + - uses: actions/setup-node@v4 + with: + node-version: "22" + cache: pnpm + cache-dependency-path: site/pnpm-lock.yaml + - name: Install marketing dependencies + working-directory: site + run: pnpm install --frozen-lockfile + - name: Check marketing behavior and CSP + working-directory: site + run: pnpm test + - name: Build marketing with production configuration + working-directory: site + run: pnpm build + - name: Deploy an isolated preview + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + PREVIEW_BRANCH: marketing-check-${{ github.run_id }}-${{ github.run_attempt }} + PRODUCTION_BRANCH: ${{ steps.config.outputs.production_branch }} + run: | + test "$PREVIEW_BRANCH" != "$PRODUCTION_BRANCH" + pnpm dlx wrangler@4.45.0 pages deploy site/dist \ + --project-name "$CLOUDFLARE_PAGES_PROJECT_NAME" \ + --branch "$PREVIEW_BRANCH" --commit-hash "$GITHUB_SHA" + - name: Verify preview responses before production + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + PREVIEW_BRANCH: marketing-check-${{ github.run_id }}-${{ github.run_attempt }} + run: node .github/scripts/pages-marketing-preview.mjs + - name: Publish the verified marketing artifact + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + PRODUCTION_BRANCH: ${{ steps.config.outputs.production_branch }} + run: | + pnpm dlx wrangler@4.45.0 pages deploy site/dist \ + --project-name "$CLOUDFLARE_PAGES_PROJECT_NAME" \ + --branch "$PRODUCTION_BRANCH" --commit-hash "$GITHUB_SHA" \ + --commit-message "Marketing $GITHUB_SHA" diff --git a/docs/content/docs/development/split-deployment.mdx b/docs/content/docs/development/split-deployment.mdx index 83407e03f..86be11bd4 100644 --- a/docs/content/docs/development/split-deployment.mdx +++ b/docs/content/docs/development/split-deployment.mdx @@ -262,6 +262,27 @@ A Pages deploy hook would reuse Cloudflare's build configuration too, but it bui Projects deploy independently, not atomically: one failed build or upload leaves that project's previous deployment live and does not cancel the other projects. After fixing the configuration, use **Re-run failed jobs** on that release run to retry the same release commit without creating another tag or rebuilding successful jobs. Do not retry an older release after a newer one has deployed unless you intend a rollback. To pause release uploads, set `CLOUDFLARE_PAGES_DEPLOY_ENABLED` to `false`; this leaves current deployments live and does not re-enable Cloudflare's automatic deployments. This workflow deploys only the listed static frontends; it does not deploy backend services. +The marketing build generates a Content Security Policy in `site/dist/_headers` +from the inline scripts in every rendered page, including the error page. Serve +that header with the generated files when hosting outside Pages. Scripts require +a build-generated hash or an allowed origin; inline event handlers and dynamic +code evaluation are refused. Inline styles remain allowed for page presentation. +The configured PostHog HTTPS origin and its regional asset host are allowed when +analytics is enabled. Cloudflare's analytics beacon has its own explicit origin. +Changes to scripts or analytics configuration require a fresh build. A policy +that exceeds Pages' 2,000-character header limit fails the build. + +For a marketing-only update without a release tag, run **Deploy marketing Pages** +on `main`, passing its reviewed full commit SHA as `expected_sha`. The manual +workflow uses `site-production` and the existing Pages production variables. It +requires exactly one `site` project in `CLOUDFLARE_PAGES_PROJECTS`, runs the site +checks, and builds once. An isolated preview must serve the built CSP on the +home, legal and error pages and preserve the published installer bytes before +the same artifact is uploaded to the production branch. A failed preview leaves +production unchanged. The workflow shares the release concurrency lock and +deploys only the marketing site. The existing Pages deployment enable flag +applies to this workflow too. + ## Anything the control plane cannot know `warmbly join` writes `/etc/warmbly/node.env` from the control plane's answer and rewrites it on every join. Next to it, `/etc/warmbly/node.local.env` is created once and never written again, and the container reads it second, so a name repeated there wins. diff --git a/site/astro.config.mjs b/site/astro.config.mjs index 6d1c486eb..ef0168f08 100644 --- a/site/astro.config.mjs +++ b/site/astro.config.mjs @@ -3,11 +3,13 @@ import { defineConfig } from 'astro/config'; import tailwindcss from '@tailwindcss/vite'; import sitemap from '@astrojs/sitemap'; import mdx from '@astrojs/mdx'; +import contentSecurityPolicyHeaders from './scripts/content-security-policy.mjs'; // https://astro.build/config export default defineConfig({ site: 'https://warmbly.com', integrations: [ + contentSecurityPolicyHeaders(), mdx(), sitemap({ // The 404 page is noindex and should never appear in the sitemap. diff --git a/site/package.json b/site/package.json index 533bdd006..b042f6046 100644 --- a/site/package.json +++ b/site/package.json @@ -4,7 +4,7 @@ "version": "1.0.0", "private": true, "scripts": { - "test": "node scripts/check-observability.mjs && node scripts/check-acquisition.mjs", + "test": "node scripts/check-observability.mjs && node scripts/check-acquisition.mjs && node --test scripts/content-security-policy.test.mjs", "dev": "astro dev", "build": "astro build", "preview": "astro preview", @@ -21,5 +21,9 @@ "reading-time": "^1.5.0", "sharp": "0.35.5", "tailwindcss": "^4.1.10" + }, + "devDependencies": { + "parse5": "^8.0.1", + "vite": "^8.3.5" } } diff --git a/site/pnpm-lock.yaml b/site/pnpm-lock.yaml index edba6ca50..7cc864a7c 100644 --- a/site/pnpm-lock.yaml +++ b/site/pnpm-lock.yaml @@ -47,6 +47,13 @@ importers: tailwindcss: specifier: ^4.1.10 version: 4.3.0 + devDependencies: + parse5: + specifier: ^8.0.1 + version: 8.0.1 + vite: + specifier: ^8.3.5 + version: 8.3.5(@types/node@24.13.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1) packages: @@ -1114,6 +1121,10 @@ packages: resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==} engines: {node: '>=0.12'} + entities@8.1.0: + resolution: {integrity: sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==} + engines: {node: '>=20.19.0'} + es-module-lexer@2.3.2: resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} @@ -1741,6 +1752,9 @@ packages: parse5@7.3.0: resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==} + parse5@8.0.1: + resolution: {integrity: sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==} + path-expression-matcher@1.6.2: resolution: {integrity: sha512-enSlaiat05iasnzmgNxRj8reFdj3puY2QpNgP1aPIaVfT6nn9ICuPoFlKHk8EN22HcwewshO+mN2DGbkCEOtqQ==} engines: {node: '>=14.0.0'} @@ -3148,6 +3162,8 @@ snapshots: entities@6.0.1: {} + entities@8.1.0: {} + es-module-lexer@2.3.2: {} es-module-lexer@3.0.4: {} @@ -4109,6 +4125,10 @@ snapshots: dependencies: entities: 6.0.1 + parse5@8.0.1: + dependencies: + entities: 8.1.0 + path-expression-matcher@1.6.2: {} piccolore@0.1.3: {} diff --git a/site/public/_headers b/site/public/_headers index 42e3ffbfa..b43847c48 100644 --- a/site/public/_headers +++ b/site/public/_headers @@ -1,6 +1,7 @@ # Security response headers for the marketing site. Static pages, no # credentials, but the site serves install.sh and cli.sh, so framing and # content-type sniffing are both switched off. +# The build adds a CSP with hashes of the generated inline scripts. /* X-Content-Type-Options: nosniff X-Frame-Options: DENY diff --git a/site/scripts/content-security-policy.mjs b/site/scripts/content-security-policy.mjs new file mode 100644 index 000000000..a0deec5fc --- /dev/null +++ b/site/scripts/content-security-policy.mjs @@ -0,0 +1,83 @@ +import { createHash } from 'node:crypto'; +import { readFile, readdir, writeFile } from 'node:fs/promises'; +import { parse } from 'parse5'; +import { loadEnv } from 'vite'; +import { fileURLToPath } from 'node:url'; + +export function inlineHashes(html) { + const scripts = new Set(); + function visit(node) { + const attributes = Object.fromEntries((node.attrs ?? []).map(({ name, value }) => [name, value])); + if (Object.keys(attributes).some((name) => name.startsWith('on'))) { + throw new Error('Marketing CSP requires event listeners instead of inline handlers'); + } + if (node.tagName === 'script' && !attributes.src && !['application/ld+json', 'application/json'].includes(attributes.type)) { + const text = (node.childNodes ?? []).map((child) => child.value ?? '').join(''); + if (text) { + const hash = `'sha256-${createHash('sha256').update(text).digest('base64')}'`; + scripts.add(hash); + } + } + for (const child of node.childNodes ?? []) visit(child); + } + visit(parse(html)); + return scripts; +} + +export function contentSecurityPolicy(scripts, analyticsHost) { + const analytics = []; + if (analyticsHost) { + const url = new URL(analyticsHost); + if (url.protocol !== 'https:' || url.username || url.password) throw new Error('Analytics CSP requires an HTTPS host'); + analytics.push(url.origin); + if (/^(us|eu)\.i\.posthog\.com$/.test(url.hostname)) { + analytics.push(`https://${url.hostname.replace('.i.', '-assets.i.')}`); + } + } + return [ + "default-src 'none'", + "base-uri 'none'", + "object-src 'none'", + "frame-ancestors 'none'", + "form-action 'self'", + `script-src 'self' https://static.cloudflareinsights.com ${[...analytics, ...scripts].join(' ')}`, + "script-src-attr 'none'", + "style-src 'self' 'unsafe-inline'", + `img-src 'self' data: ${analytics.join(' ')}`, + "font-src 'self'", + `connect-src 'self' https://cloudflareinsights.com ${analytics.join(' ')}`, + "worker-src 'self' blob:", + ].join('; '); +} + +export default function contentSecurityPolicyHeaders() { + let analyticsHost; + return { + name: 'marketing-content-security-policy', + hooks: { + 'astro:config:setup': ({ config, mode }) => { + const env = loadEnv(mode, fileURLToPath(config.root), 'PUBLIC_POSTHOG_'); + analyticsHost = env.PUBLIC_POSTHOG_KEY ? env.PUBLIC_POSTHOG_HOST || 'https://us.i.posthog.com' : undefined; + }, + 'astro:build:done': async ({ dir, logger }) => { + const hashes = new Set(); + for (const entry of await readdir(dir, { recursive: true })) { + if (!entry.endsWith('.html')) continue; + const page = inlineHashes(await readFile(new URL(entry, dir), 'utf8')); + for (const hash of page) hashes.add(hash); + } + if (!hashes.size) throw new Error('No marketing page scripts found for CSP'); + const policy = contentSecurityPolicy(hashes, analyticsHost); + const header = ` Content-Security-Policy: ${policy}`; + // Pages rejects header lines longer than 2,000 characters. + if (header.length > 2000) throw new Error(`Marketing CSP exceeds the Pages header limit (${header.length})`); + const file = new URL('_headers', dir); + const headers = await readFile(file, 'utf8'); + if (/Content-Security-Policy:/i.test(headers)) throw new Error('Marketing CSP header already configured'); + if (!headers.includes('/*\n')) throw new Error('Marketing headers require a catch-all rule'); + await writeFile(file, headers.replace('/*\n', `/*\n${header}\n`)); + logger.info(`Generated CSP for all marketing routes (${hashes.size} script hashes)`); + }, + }, + }; +} diff --git a/site/scripts/content-security-policy.test.mjs b/site/scripts/content-security-policy.test.mjs new file mode 100644 index 000000000..e14f258d1 --- /dev/null +++ b/site/scripts/content-security-policy.test.mjs @@ -0,0 +1,63 @@ +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { test } from 'node:test'; +import integration, { contentSecurityPolicy, inlineHashes } from './content-security-policy.mjs'; + +test('hashes browser-normalized script text without treating JSON data or remote scripts as code', () => { + const hashes = inlineHashes(''); + const digest = createHash('sha256').update('window.ready = true;\n').digest('base64'); + assert.deepEqual([...hashes], [`'sha256-${digest}'`]); + assert.throws(() => inlineHashes(''), /inline handlers/); +}); + +test('restricts executable sources while preserving configured analytics and inline presentation', () => { + const directives = new Map(contentSecurityPolicy(new Set(["'sha256-known'"]), 'https://eu.i.posthog.com') + .split('; ').map((value) => { const [name, ...sources] = value.split(' '); return [name, sources]; })); + assert.deepEqual(directives.get('default-src'), ["'none'"]); + assert.deepEqual(directives.get('script-src-attr'), ["'none'"]); + assert.deepEqual(directives.get('frame-ancestors'), ["'none'"]); + const scripts = directives.get('script-src'); + assert.ok(scripts.includes("'sha256-known'")); + assert.ok(scripts.includes('https://eu-assets.i.posthog.com')); + assert.ok(!scripts.includes("'unsafe-inline'") && !scripts.includes("'unsafe-eval'")); + assert.ok(directives.get('style-src').includes("'unsafe-inline'")); + assert.ok(!contentSecurityPolicy(new Set()).includes('posthog')); + assert.throws(() => contentSecurityPolicy(new Set(), 'http://analytics.example.com'), /HTTPS/); + assert.throws(() => contentSecurityPolicy(new Set(), 'https://user:password@example.com'), /HTTPS/); +}); + +test('emits one catch-all header from every generated page and refuses oversized or duplicate policies', async () => { + const root = await mkdtemp(join(tmpdir(), 'marketing-csp-')); + const dir = pathToFileURL(`${root}/`); + try { + await writeFile(join(root, '.env.production'), 'PUBLIC_POSTHOG_KEY=test\nPUBLIC_POSTHOG_HOST=https://analytics.example.com/ingest\n'); + await mkdir(join(root, 'terms')); + await writeFile(join(root, 'index.html'), ''); + await writeFile(join(root, 'terms/index.html'), ''); + const baseline = '/*\n X-Frame-Options: DENY\n/_astro/*\n Cache-Control: public\n'; + await writeFile(join(root, '_headers'), baseline); + const { hooks } = integration(); + hooks['astro:config:setup']({ config: { root: dir }, mode: 'production' }); + const build = () => hooks['astro:build:done']({ dir, logger: { info() {} } }); + await build(); + const headers = await readFile(join(root, '_headers'), 'utf8'); + assert.ok(headers.startsWith('/*\n Content-Security-Policy:')); + for (const code of ['window.home=true', 'window.legal=true']) { + assert.ok(headers.includes(createHash('sha256').update(code).digest('base64'))); + } + assert.ok(headers.includes('https://analytics.example.com')); + assert.ok(headers.includes('X-Frame-Options: DENY')); + assert.ok(headers.includes('/_astro/*\n Cache-Control: public')); + await assert.rejects(build(), /already configured/); + await writeFile(join(root, '_headers'), baseline); + await writeFile(join(root, 'index.html'), Array.from({ length: 40 }, (_, i) => ``).join('')); + await assert.rejects(build(), /header limit/); + assert.equal(await readFile(join(root, '_headers'), 'utf8'), baseline); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); From f184f2475988aa8ee96501770b82ca94dcbe0220 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sat, 31 Oct 2026 20:06:22 +0100 Subject: [PATCH 046/318] feat: align marketing policies with resolved build environments and exact catch-all header rules --- .github/workflows/marketing-pages.yml | 3 ++ .../docs/development/split-deployment.mdx | 2 ++ site/scripts/content-security-policy.mjs | 17 ++++++---- site/scripts/content-security-policy.test.mjs | 32 ++++++++++++++++++- 4 files changed, 47 insertions(+), 7 deletions(-) diff --git a/.github/workflows/marketing-pages.yml b/.github/workflows/marketing-pages.yml index 3d3b66a92..7bc87b3ba 100644 --- a/.github/workflows/marketing-pages.yml +++ b/.github/workflows/marketing-pages.yml @@ -24,6 +24,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + persist-credentials: false - uses: actions/setup-node@v4 with: node-version: "22" @@ -43,6 +45,7 @@ jobs: - uses: actions/checkout@v4 with: ref: ${{ github.sha }} + persist-credentials: false - name: Require the reviewed main commit env: EXPECTED_SHA: ${{ inputs.expected_sha }} diff --git a/docs/content/docs/development/split-deployment.mdx b/docs/content/docs/development/split-deployment.mdx index 86be11bd4..908c6c60a 100644 --- a/docs/content/docs/development/split-deployment.mdx +++ b/docs/content/docs/development/split-deployment.mdx @@ -271,6 +271,8 @@ The configured PostHog HTTPS origin and its regional asset host are allowed when analytics is enabled. Cloudflare's analytics beacon has its own explicit origin. Changes to scripts or analytics configuration require a fresh build. A policy that exceeds Pages' 2,000-character header limit fails the build. +The policy reads analytics settings using Vite's resolved build mode and +environment directory, including mode-specific environment files. For a marketing-only update without a release tag, run **Deploy marketing Pages** on `main`, passing its reviewed full commit SHA as `expected_sha`. The manual diff --git a/site/scripts/content-security-policy.mjs b/site/scripts/content-security-policy.mjs index a0deec5fc..ce93dfbf6 100644 --- a/site/scripts/content-security-policy.mjs +++ b/site/scripts/content-security-policy.mjs @@ -2,7 +2,6 @@ import { createHash } from 'node:crypto'; import { readFile, readdir, writeFile } from 'node:fs/promises'; import { parse } from 'parse5'; import { loadEnv } from 'vite'; -import { fileURLToPath } from 'node:url'; export function inlineHashes(html) { const scripts = new Set(); @@ -55,9 +54,14 @@ export default function contentSecurityPolicyHeaders() { return { name: 'marketing-content-security-policy', hooks: { - 'astro:config:setup': ({ config, mode }) => { - const env = loadEnv(mode, fileURLToPath(config.root), 'PUBLIC_POSTHOG_'); - analyticsHost = env.PUBLIC_POSTHOG_KEY ? env.PUBLIC_POSTHOG_HOST || 'https://us.i.posthog.com' : undefined; + 'astro:config:setup': ({ updateConfig }) => { + updateConfig({ vite: { plugins: [{ + name: 'marketing-csp-environment', + configResolved: ({ mode, envDir }) => { + const env = loadEnv(mode, envDir, 'PUBLIC_POSTHOG_'); + analyticsHost = env.PUBLIC_POSTHOG_KEY ? env.PUBLIC_POSTHOG_HOST || 'https://us.i.posthog.com' : undefined; + }, + }] } }); }, 'astro:build:done': async ({ dir, logger }) => { const hashes = new Set(); @@ -74,8 +78,9 @@ export default function contentSecurityPolicyHeaders() { const file = new URL('_headers', dir); const headers = await readFile(file, 'utf8'); if (/Content-Security-Policy:/i.test(headers)) throw new Error('Marketing CSP header already configured'); - if (!headers.includes('/*\n')) throw new Error('Marketing headers require a catch-all rule'); - await writeFile(file, headers.replace('/*\n', `/*\n${header}\n`)); + const catchAll = /^\/\*[ \t]*(\r?\n)/m; + if (!catchAll.test(headers)) throw new Error('Marketing headers require a catch-all rule'); + await writeFile(file, headers.replace(catchAll, (rule, newline) => `${rule}${header}${newline}`)); logger.info(`Generated CSP for all marketing routes (${hashes.size} script hashes)`); }, }, diff --git a/site/scripts/content-security-policy.test.mjs b/site/scripts/content-security-policy.test.mjs index e14f258d1..c27b2a7a3 100644 --- a/site/scripts/content-security-policy.test.mjs +++ b/site/scripts/content-security-policy.test.mjs @@ -33,6 +33,8 @@ test('restricts executable sources while preserving configured analytics and inl test('emits one catch-all header from every generated page and refuses oversized or duplicate policies', async () => { const root = await mkdtemp(join(tmpdir(), 'marketing-csp-')); const dir = pathToFileURL(`${root}/`); + const inherited = Object.entries(process.env).filter(([name]) => name.startsWith('PUBLIC_POSTHOG_')); + for (const [name] of inherited) delete process.env[name]; try { await writeFile(join(root, '.env.production'), 'PUBLIC_POSTHOG_KEY=test\nPUBLIC_POSTHOG_HOST=https://analytics.example.com/ingest\n'); await mkdir(join(root, 'terms')); @@ -41,7 +43,9 @@ test('emits one catch-all header from every generated page and refuses oversized const baseline = '/*\n X-Frame-Options: DENY\n/_astro/*\n Cache-Control: public\n'; await writeFile(join(root, '_headers'), baseline); const { hooks } = integration(); - hooks['astro:config:setup']({ config: { root: dir }, mode: 'production' }); + let vite; + hooks['astro:config:setup']({ updateConfig: config => { vite = config.vite; } }); + vite.plugins[0].configResolved({ mode: 'production', envDir: root }); const build = () => hooks['astro:build:done']({ dir, logger: { info() {} } }); await build(); const headers = await readFile(join(root, '_headers'), 'utf8'); @@ -53,11 +57,37 @@ test('emits one catch-all header from every generated page and refuses oversized assert.ok(headers.includes('X-Frame-Options: DENY')); assert.ok(headers.includes('/_astro/*\n Cache-Control: public')); await assert.rejects(build(), /already configured/); + const assetsOnly = '/_astro/*\n Cache-Control: public\n'; + await writeFile(join(root, '_headers'), assetsOnly); + await assert.rejects(build(), /catch-all rule/); + assert.equal(await readFile(join(root, '_headers'), 'utf8'), assetsOnly); + const reordered = '/_astro/*\r\n Cache-Control: public\r\n/* \t\r\n X-Frame-Options: DENY\r\n'; + await writeFile(join(root, '_headers'), reordered); + await build(); + const reorderedHeaders = await readFile(join(root, '_headers'), 'utf8'); + assert.ok(reorderedHeaders.startsWith('/_astro/*\r\n Cache-Control: public\r\n/* \t\r\n Content-Security-Policy:')); + assert.ok(reorderedHeaders.includes('\r\n X-Frame-Options: DENY\r\n')); + await mkdir(join(root, 'config')); + await writeFile(join(root, 'config/.env.staging'), 'PUBLIC_POSTHOG_KEY=test\nPUBLIC_POSTHOG_HOST=https://staging-analytics.example.com\n'); + vite.plugins[0].configResolved({ mode: 'staging', envDir: join(root, 'config') }); + await writeFile(join(root, '_headers'), baseline); + await build(); + const stagingHeaders = await readFile(join(root, '_headers'), 'utf8'); + assert.ok(stagingHeaders.includes('https://staging-analytics.example.com')); + assert.ok(!stagingHeaders.includes('https://analytics.example.com')); + process.env.PUBLIC_POSTHOG_KEY = 'test'; + process.env.PUBLIC_POSTHOG_HOST = 'https://configured-analytics.example.com'; + vite.plugins[0].configResolved({ mode: 'production', envDir: root }); + await writeFile(join(root, '_headers'), baseline); + await build(); + assert.ok((await readFile(join(root, '_headers'), 'utf8')).includes('https://configured-analytics.example.com')); await writeFile(join(root, '_headers'), baseline); await writeFile(join(root, 'index.html'), Array.from({ length: 40 }, (_, i) => ``).join('')); await assert.rejects(build(), /header limit/); assert.equal(await readFile(join(root, '_headers'), 'utf8'), baseline); } finally { + for (const name of Object.keys(process.env).filter(name => name.startsWith('PUBLIC_POSTHOG_'))) delete process.env[name]; + for (const [name, value] of inherited) process.env[name] = value; await rm(root, { recursive: true, force: true }); } }); From 81ee60bd0ea9a1c56def97ab2119711ea1ba418d Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sat, 31 Oct 2026 20:14:45 +0100 Subject: [PATCH 047/318] feat: pin marketing deployment actions to verified upstream v4 commit references --- .github/workflows/marketing-pages.yml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/marketing-pages.yml b/.github/workflows/marketing-pages.yml index 7bc87b3ba..30f126d51 100644 --- a/.github/workflows/marketing-pages.yml +++ b/.github/workflows/marketing-pages.yml @@ -23,10 +23,10 @@ jobs: check: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: persist-credentials: false - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: "22" - run: node --test .github/scripts/pages-*.test.mjs @@ -42,7 +42,7 @@ jobs: PAGES_APP: site WRANGLER_SEND_METRICS: "false" steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: ref: ${{ github.sha }} persist-credentials: false @@ -50,7 +50,7 @@ jobs: env: EXPECTED_SHA: ${{ inputs.expected_sha }} run: test "$EXPECTED_SHA" = "$GITHUB_SHA" - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: "22" - name: Select only the configured marketing project @@ -76,10 +76,10 @@ jobs: --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/pages/projects/$CLOUDFLARE_PAGES_PROJECT_NAME" \ | node .github/scripts/pages-production-config.mjs - - uses: pnpm/action-setup@v4 + - uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4 with: version: "11.9.0" - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: "22" cache: pnpm From 38a01579694186f0848c0c04b18a15ed59806eb7 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sat, 31 Oct 2026 20:28:38 +0100 Subject: [PATCH 048/318] feat: verify marketing previews from versioned same-command Wrangler deployment receipts --- .github/scripts/pages-marketing-preview.mjs | 27 ++++++++----------- .../scripts/pages-marketing-preview.test.mjs | 18 ++++++------- .github/workflows/marketing-pages.yml | 5 ++-- .../docs/development/split-deployment.mdx | 2 ++ 4 files changed, 25 insertions(+), 27 deletions(-) diff --git a/.github/scripts/pages-marketing-preview.mjs b/.github/scripts/pages-marketing-preview.mjs index 539b5ff39..9a9051d79 100644 --- a/.github/scripts/pages-marketing-preview.mjs +++ b/.github/scripts/pages-marketing-preview.mjs @@ -2,13 +2,14 @@ import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import { fileURLToPath } from 'node:url'; -export function previewURL(deployments, project, branch, sha) { - const matches = deployments.filter(deployment => deployment.environment === 'preview' - && deployment.deployment_trigger?.metadata?.branch === branch +export function previewURL(entries, project, sha) { + const matches = entries.filter(deployment => deployment.type === 'pages-deploy-detailed' + && deployment.version === 1 + && deployment.pages_project === project + && deployment.environment === 'preview' && deployment.deployment_trigger?.metadata?.commit_hash === sha - && deployment.latest_stage?.name === 'deploy' - && deployment.latest_stage?.status === 'success'); - assert.equal(matches.length, 1, 'Require one successful preview for this run and commit'); + && typeof deployment.deployment_id === 'string' && deployment.deployment_id.length > 0); + assert.equal(matches.length, 1, 'Require one Wrangler preview receipt for this project and commit'); const url = new URL(matches[0].url); assert.equal(url.protocol, 'https:'); assert.ok(url.hostname.endsWith(`.${project}.pages.dev`), 'Require the configured Pages project'); @@ -32,16 +33,10 @@ export async function verifyPreview(url, policy, request = fetch, directory = ne } if (process.argv[1] === fileURLToPath(import.meta.url)) { - const { CLOUDFLARE_ACCOUNT_ID: account, CLOUDFLARE_PAGES_PROJECT_NAME: project, - CLOUDFLARE_API_TOKEN: token, PREVIEW_BRANCH: branch, GITHUB_SHA: sha } = process.env; - assert.ok(account && project && token && branch && sha, 'Require preview deployment configuration'); - const response = await fetch(`https://api.cloudflare.com/client/v4/accounts/${account}/pages/projects/${project}/deployments?env=preview&per_page=100`, { - headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(30000), - }); - assert.ok(response.ok, `Pages deployment lookup returned ${response.status}`); - const data = await response.json(); - assert.equal(data.success, true, 'Pages deployment lookup must succeed'); - const url = previewURL(data.result, project, branch, sha); + const { CLOUDFLARE_PAGES_PROJECT_NAME: project, WRANGLER_OUTPUT_FILE_PATH: receipt, GITHUB_SHA: sha } = process.env; + assert.ok(project && receipt && sha, 'Require preview deployment configuration'); + const entries = (await readFile(receipt, 'utf8')).split(/\r?\n/).filter(line => line.trim()).map(line => JSON.parse(line)); + const url = previewURL(entries, project, sha); const headers = await readFile(new URL('../../site/dist/_headers', import.meta.url), 'utf8'); const policies = [...headers.matchAll(/^\s+Content-Security-Policy: (.+)$/gm)]; assert.equal(policies.length, 1, 'Require one built policy'); diff --git a/.github/scripts/pages-marketing-preview.test.mjs b/.github/scripts/pages-marketing-preview.test.mjs index 067dd9e10..34ad9640d 100644 --- a/.github/scripts/pages-marketing-preview.test.mjs +++ b/.github/scripts/pages-marketing-preview.test.mjs @@ -6,19 +6,19 @@ import { pathToFileURL } from 'node:url'; import { test } from 'node:test'; import { previewURL, verifyPreview } from './pages-marketing-preview.mjs'; -test('accepts only this run successful preview on the reviewed commit and project', () => { - const deployment = { environment: 'preview', url: 'https://abc.marketing.pages.dev', - deployment_trigger: { metadata: { branch: 'check-123', commit_hash: 'sha' } }, - latest_stage: { name: 'deploy', status: 'success' } }; - const select = value => previewURL([value], 'marketing', 'check-123', 'sha'); +test('accepts only a versioned Wrangler preview receipt for the reviewed commit and project', () => { + const deployment = { type: 'pages-deploy-detailed', version: 1, pages_project: 'marketing', + deployment_id: 'deployment-id', environment: 'preview', url: 'https://abc.marketing.pages.dev', + deployment_trigger: { metadata: { commit_hash: 'sha' } } }; + const select = value => previewURL([value], 'marketing', 'sha'); assert.equal(select(deployment).origin, 'https://abc.marketing.pages.dev'); for (const override of [ { environment: 'production' }, { url: 'https://abc.other.pages.dev' }, - { latest_stage: { name: 'deploy', status: 'failure' } }, - { deployment_trigger: { metadata: { branch: 'other', commit_hash: 'sha' } } }, - { deployment_trigger: { metadata: { branch: 'check-123', commit_hash: 'old' } } }, + { type: 'pages-deploy' }, { version: 2 }, { pages_project: 'other' }, { deployment_id: null }, + { deployment_trigger: { metadata: { commit_hash: 'old' } } }, ]) assert.throws(() => select({ ...deployment, ...override })); - assert.throws(() => previewURL([deployment, deployment], 'marketing', 'check-123', 'sha')); + assert.throws(() => previewURL([deployment, deployment], 'marketing', 'sha')); + assert.equal(previewURL([{ type: 'pages-deploy' }, deployment], 'marketing', 'sha').origin, 'https://abc.marketing.pages.dev'); }); test('verifies page, error and byte-identical installer responses with the built policy', async () => { diff --git a/.github/workflows/marketing-pages.yml b/.github/workflows/marketing-pages.yml index 30f126d51..368bec519 100644 --- a/.github/workflows/marketing-pages.yml +++ b/.github/workflows/marketing-pages.yml @@ -98,15 +98,16 @@ jobs: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} PREVIEW_BRANCH: marketing-check-${{ github.run_id }}-${{ github.run_attempt }} PRODUCTION_BRANCH: ${{ steps.config.outputs.production_branch }} + WRANGLER_OUTPUT_FILE_PATH: ${{ runner.temp }}/marketing-preview-${{ github.run_id }}-${{ github.run_attempt }}.ndjson run: | test "$PREVIEW_BRANCH" != "$PRODUCTION_BRANCH" + test ! -e "$WRANGLER_OUTPUT_FILE_PATH" pnpm dlx wrangler@4.45.0 pages deploy site/dist \ --project-name "$CLOUDFLARE_PAGES_PROJECT_NAME" \ --branch "$PREVIEW_BRANCH" --commit-hash "$GITHUB_SHA" - name: Verify preview responses before production env: - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - PREVIEW_BRANCH: marketing-check-${{ github.run_id }}-${{ github.run_attempt }} + WRANGLER_OUTPUT_FILE_PATH: ${{ runner.temp }}/marketing-preview-${{ github.run_id }}-${{ github.run_attempt }}.ndjson run: node .github/scripts/pages-marketing-preview.mjs - name: Publish the verified marketing artifact env: diff --git a/docs/content/docs/development/split-deployment.mdx b/docs/content/docs/development/split-deployment.mdx index 908c6c60a..286f79be7 100644 --- a/docs/content/docs/development/split-deployment.mdx +++ b/docs/content/docs/development/split-deployment.mdx @@ -284,6 +284,8 @@ the same artifact is uploaded to the production branch. A failed preview leaves production unchanged. The workflow shares the release concurrency lock and deploys only the marketing site. The existing Pages deployment enable flag applies to this workflow too. +Preview verification reads Wrangler's structured deployment receipt for that +run and checks its project, environment and commit before requesting its URL. ## Anything the control plane cannot know From 92d81eaa8b3dace9a631a471e6cc7c344abf88fe Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 1 Nov 2026 02:08:44 +0000 Subject: [PATCH 049/318] feat: describe POST /auth/me/password/link, GET /auth/me/identities, DELETE /auth/me/identities/{provider} and the Unibox overview drafts count in openapi.json and the Unibox reference --- docs/content/docs/api/reference/unibox.mdx | 3 +- docs/public/openapi.json | 231 +++++++++++++++++++++ 2 files changed, 233 insertions(+), 1 deletion(-) diff --git a/docs/content/docs/api/reference/unibox.mdx b/docs/content/docs/api/reference/unibox.mdx index ee4f9a91e..252a113bc 100644 --- a/docs/content/docs/api/reference/unibox.mdx +++ b/docs/content/docs/api/reference/unibox.mdx @@ -86,7 +86,7 @@ Returns the number of unread conversations in the Inbox folder, optionally scope `GET /unibox/overview` -Rolls up the scope rail and top metric strip in one call: unread, today, week, snoozed, awaiting-reply, and pending-scheduled counts, plus per-folder, per-mailbox, per-tag, and per-conversation-label breakdowns. The `folders` array always lists all six canonical folders, zero-filled, in sidebar order; the headline counts exclude `spam` and `trash`. All counts are threads, not messages, except `scheduled_pending`, which counts the sends queued from the organization's mailboxes against the workspace cap in `scheduled_pending_max`. Automated conversations are counted in `automated` and `automated_unread` and left out of `unread`, `today`, `week`, the `inbox` folder and the per-mailbox and per-tag counts; `total` and the label counts still include them. Concurrent requests from the same organization share one computation, and its result is served for up to one second after it started (`generated_at` is when it started). Auth: **Scope** `READ_UNIBOX` ยท **Org permission** `access_unibox`. +Rolls up the scope rail and top metric strip in one call: unread, today, week, snoozed, awaiting-reply, draft (`drafts`, each thread once whether it holds a mailbox draft or a pending agent draft), and pending-scheduled counts, plus per-folder, per-mailbox, per-tag, and per-conversation-label breakdowns. The `folders` array always lists all six canonical folders, zero-filled, in sidebar order; the headline counts exclude `spam` and `trash`. All counts are threads, not messages, except `scheduled_pending`, which counts the sends queued from the organization's mailboxes against the workspace cap in `scheduled_pending_max`. Automated conversations are counted in `automated` and `automated_unread` and left out of `unread`, `today`, `week`, the `inbox` folder and the per-mailbox and per-tag counts; `total` and the label counts still include them. Concurrent requests from the same organization share one computation, and its result is served for up to one second after it started (`generated_at` is when it started). Auth: **Scope** `READ_UNIBOX` ยท **Org permission** `access_unibox`. ### Response @@ -100,6 +100,7 @@ Rolls up the scope rail and top metric strip in one call: unread, today, week, s "awaiting_reply": 9, "automated": 41, "automated_unread": 6, + "drafts": 4, "scheduled_pending": 2, "scheduled_pending_max": 10000, "folders": [ diff --git a/docs/public/openapi.json b/docs/public/openapi.json index 1d9d43903..5cb108bcb 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -1192,6 +1192,200 @@ } } }, + "/auth/me/password/link": { + "post": { + "operationId": "auth_send_password_link", + "summary": "Send a set-password link", + "description": "Emails the signed-in user a single-use link to set a password, to the address on the account. It is how an account created through Google, Apple or single sign-on adds email and password sign-in. The link is the one Forgot password sends: it expires after one hour, setting the password through it ends every session, and it shares that flow's budget of 2 links per address per 4 hours. No request body. Takes no Idempotency-Key, because a repeat mails another link. Requires a user session token (not an API key).", + "tags": [ + "auth" + ], + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "The link was sent." + }, + "400": { + "description": "The link budget for this address is spent.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing or invalid session token.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Password sign-in is turned off on this server (`password_login_disabled`), or the caller is not a user session.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/auth/me/identities": { + "get": { + "operationId": "auth_list_identities", + "summary": "List sign-in methods", + "description": "The providers linked to the signed-in user: Google, Apple or the deployment's single sign-on. A password and passkeys are not listed here. Requires a user session token (not an API key).", + "tags": [ + "auth" + ], + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "The linked providers.", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "data" + ], + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LinkedIdentity" + } + } + } + } + } + } + }, + "401": { + "description": "Missing or invalid session token.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Not allowed.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/auth/me/identities/{provider}": { + "delete": { + "operationId": "auth_remove_identity", + "summary": "Remove a sign-in method", + "description": "Stops the provider signing in to this account and ends every other session that signed in through it; the calling session stays signed in. Requires a fresh confirmation (`reauth_required` otherwise). A repeat converges and also returns 204, so it takes no Idempotency-Key. Refused with 409 `last_sign_in_method` when the account would be left with no password, no passkey and no other provider. Requires a user session token (not an API key).", + "tags": [ + "auth" + ], + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "provider", + "in": "path", + "required": true, + "schema": { + "type": "string", + "enum": [ + "google", + "apple", + "oidc" + ] + }, + "description": "The provider to remove." + } + ], + "responses": { + "204": { + "description": "The provider is no longer a sign-in method, also when it was already removed." + }, + "401": { + "description": "Missing or invalid session token.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Fresh confirmation required (`reauth_required`) or not a user session.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "`identity_not_found`: the provider is not google, apple or oidc.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "`last_sign_in_method`: this is the account's only way to sign in.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "`sessions_not_ended`: the provider was removed but its sessions could not all be ended. Repeat the request to finish.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, "/auth/me/password": { "post": { "operationId": "auth_change_password", @@ -38018,6 +38212,39 @@ } } }, + "LinkedIdentity": { + "type": "object", + "required": [ + "provider", + "label", + "created_at" + ], + "properties": { + "provider": { + "type": "string", + "enum": [ + "google", + "apple", + "oidc" + ] + }, + "label": { + "type": "string" + }, + "email": { + "type": "string", + "description": "The address the provider reported. For Apple it can be a Hide My Email relay address." + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "last_login_at": { + "type": "string", + "format": "date-time" + } + } + }, "UniboxOverview": { "type": "object", "required": [ @@ -38056,6 +38283,10 @@ "type": "integer", "description": "Automated conversations with an unread message." }, + "drafts": { + "type": "integer", + "description": "Visible threads with a mailbox draft or a pending agent draft, each counted once." + }, "scheduled_pending": { "type": "integer" }, From 0ab456c091ec1cc81862cdcd1f5349f547df8c20 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 1 Nov 2026 02:17:34 +0000 Subject: [PATCH 050/318] feat: document the 429 write-limit answer on the set-password link and sign-in method removal endpoints and call the Unibox drafts count per visible thread --- docs/content/docs/api/reference/unibox.mdx | 2 +- docs/public/openapi.json | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/docs/content/docs/api/reference/unibox.mdx b/docs/content/docs/api/reference/unibox.mdx index 252a113bc..0f5294534 100644 --- a/docs/content/docs/api/reference/unibox.mdx +++ b/docs/content/docs/api/reference/unibox.mdx @@ -86,7 +86,7 @@ Returns the number of unread conversations in the Inbox folder, optionally scope `GET /unibox/overview` -Rolls up the scope rail and top metric strip in one call: unread, today, week, snoozed, awaiting-reply, draft (`drafts`, each thread once whether it holds a mailbox draft or a pending agent draft), and pending-scheduled counts, plus per-folder, per-mailbox, per-tag, and per-conversation-label breakdowns. The `folders` array always lists all six canonical folders, zero-filled, in sidebar order; the headline counts exclude `spam` and `trash`. All counts are threads, not messages, except `scheduled_pending`, which counts the sends queued from the organization's mailboxes against the workspace cap in `scheduled_pending_max`. Automated conversations are counted in `automated` and `automated_unread` and left out of `unread`, `today`, `week`, the `inbox` folder and the per-mailbox and per-tag counts; `total` and the label counts still include them. Concurrent requests from the same organization share one computation, and its result is served for up to one second after it started (`generated_at` is when it started). Auth: **Scope** `READ_UNIBOX` ยท **Org permission** `access_unibox`. +Rolls up the scope rail and top metric strip in one call: unread, today, week, snoozed, awaiting-reply, draft (`drafts`, each visible thread once whether it holds a mailbox draft or a pending agent draft), and pending-scheduled counts, plus per-folder, per-mailbox, per-tag, and per-conversation-label breakdowns. The `folders` array always lists all six canonical folders, zero-filled, in sidebar order; the headline counts exclude `spam` and `trash`. All counts are threads, not messages, except `scheduled_pending`, which counts the sends queued from the organization's mailboxes against the workspace cap in `scheduled_pending_max`. Automated conversations are counted in `automated` and `automated_unread` and left out of `unread`, `today`, `week`, the `inbox` folder and the per-mailbox and per-tag counts; `total` and the label counts still include them. Concurrent requests from the same organization share one computation, and its result is served for up to one second after it started (`generated_at` is when it started). Auth: **Scope** `READ_UNIBOX` ยท **Org permission** `access_unibox`. ### Response diff --git a/docs/public/openapi.json b/docs/public/openapi.json index 5cb108bcb..5da5b05e5 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -1238,6 +1238,16 @@ } } } + }, + "429": { + "description": "Rate limited.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } } } } @@ -1382,6 +1392,16 @@ } } } + }, + "429": { + "description": "Rate limited.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } } } } From 22f9aec86f57bb54b9e9c7f2adc2a5e7aeecf892 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sun, 1 Nov 2026 06:50:07 +0100 Subject: [PATCH 051/318] feat: require release provenance by default in reusable AWS deployments and TLS redeploys --- .github/workflows/deploy-aws.yml | 4 ++++ .github/workflows/runtime-tls.yml | 1 + 2 files changed, 5 insertions(+) diff --git a/.github/workflows/deploy-aws.yml b/.github/workflows/deploy-aws.yml index 3d4ce46bd..b2fcf3528 100644 --- a/.github/workflows/deploy-aws.yml +++ b/.github/workflows/deploy-aws.yml @@ -22,6 +22,10 @@ on: description: Start a canary rollout of the workers and consumers after the services default: true type: boolean + require_attestation: + description: Refuse images without build provenance (only releases before provenance need false) + default: true + type: boolean workflow_dispatch: inputs: tag: diff --git a/.github/workflows/runtime-tls.yml b/.github/workflows/runtime-tls.yml index a97eb8b01..0022c8ef4 100644 --- a/.github/workflows/runtime-tls.yml +++ b/.github/workflows/runtime-tls.yml @@ -125,4 +125,5 @@ jobs: mode: redeploy services: backend,forms,tracking,realtime fleet: false + require_attestation: true secrets: inherit From 929e503b79cd99df62e148e3e652962606504754 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sun, 1 Nov 2026 07:27:25 +0100 Subject: [PATCH 052/318] feat: compare retained runtime TLS registrations with canonical optional ELB names --- .github/scripts/runtime-tls.sh | 6 ++++-- .github/scripts/runtime-tls.test.sh | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/.github/scripts/runtime-tls.sh b/.github/scripts/runtime-tls.sh index 99984b248..1860aaec0 100755 --- a/.github/scripts/runtime-tls.sh +++ b/.github/scripts/runtime-tls.sh @@ -15,6 +15,8 @@ check_plan() { def normalize_empty_description: .change.actions == ["update"] and same_except(["description"]) and .change.before.description == "" and .change.after.description == null; + def normalize_registration: + if .elb_name == "" then .elb_name = null else . end; def task_settings: del(.arn, .arn_without_revision, .id, .revision, .container_definitions) | .enable_fault_injection //= false | .ipc_mode //= "" | .pid_mode //= ""; @@ -37,9 +39,9 @@ check_plan() { ($stage == "drain") and (.change.before.load_balancer | length == 2) and (.change.after.load_balancer | length == 1) and - (.change.after.load_balancer[0] as $tls | + ((.change.after.load_balancer[0] | normalize_registration) as $tls | ($tls.target_group_arn | contains("-tls/")) and - (.change.before.load_balancer | index($tls) != null)) + (.change.before.load_balancer | map(normalize_registration) | index($tls) != null)) elif (.address | test("^aws_cloudwatch_metric_alarm\\.target_5xx" + service + "$")) then .change.actions == ["update"] and same_except(["metric_query"]) elif (.address | test("^aws_cloudwatch_metric_alarm\\.unhealthy_hosts" + service + "$")) then diff --git a/.github/scripts/runtime-tls.test.sh b/.github/scripts/runtime-tls.test.sh index e82a4c481..4c39feb22 100755 --- a/.github/scripts/runtime-tls.test.sh +++ b/.github/scripts/runtime-tls.test.sh @@ -35,6 +35,22 @@ for stage in route on; do exit 1 fi done +jq '.resource_changes[0].change |= ( + .before.load_balancer |= map(. + {elb_name:"",advanced_configuration:[]}) | + .after.load_balancer |= map(. + {elb_name:null,advanced_configuration:[]}))' "$work/plan.json" >"$work/normalized.json" +bash .github/scripts/runtime-tls.sh check-plan "$work/normalized.json" drain +for change in '.after.load_balancer[0].elb_name="classic-lb"' \ + '.before.load_balancer[1].elb_name="classic-lb"' \ + '.after.load_balancer[0].container_port=9443' \ + '.after.load_balancer[0].container_name="other"' \ + '.after.load_balancer[0].target_group_arn="other-tls/3"' \ + '.after.load_balancer[0].advanced_configuration=[{alternate_target_group_arn:"other-tls/3"}]'; do + jq ".resource_changes[0].change |= ($change)" "$work/normalized.json" >"$work/changed.json" + if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" drain 2>/dev/null; then + echo 'Changed HTTPS registration accepted as empty ELB name normalization' >&2 + exit 1 + fi +done jq -n '{resource_changes:[{address:"aws_vpc_security_group_ingress_rule.service[\"backend\"]",change:{actions:["update"], before:{description:"",from_port:8080},after:{description:null,from_port:8080}}}]}' >"$work/plan.json" bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" route From 6b369386f5b05e01ee37b6b432af627b92d10ea8 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sun, 1 Nov 2026 08:30:24 +0100 Subject: [PATCH 053/318] feat: declare every runtime TLS workflow stage choice as an explicit YAML string --- .github/workflows/runtime-tls.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/runtime-tls.yml b/.github/workflows/runtime-tls.yml index 0022c8ef4..a57cc1ffc 100644 --- a/.github/workflows/runtime-tls.yml +++ b/.github/workflows/runtime-tls.yml @@ -13,7 +13,7 @@ on: required: true default: route type: choice - options: [route, drain, on] + options: ["route", "drain", "on"] previous_run: description: Successful preceding stage workflow run ID (required for drain and on) required: false From 3e7be7ee2e33df93d904fa758dada1f704388634 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sun, 1 Nov 2026 08:38:01 +0100 Subject: [PATCH 054/318] feat: hide temporary sync and send failures on mailboxes that still worked within two hours across the mailbox list, drawer, health summary, advisor and toasts, show non-critical reports as amber Retrying instead of red Error, and warn on the Warmup tab when sending behaviour working days skip warmup days with a one-click fix --- docs/content/docs/guides/mailboxes.mdx | 4 +- docs/content/docs/guides/warmup.mdx | 2 +- internal/app/analytics/service.go | 32 +++++- internal/app/consumer/event_email_error.go | 23 ++++- internal/models/mail_transport.go | 34 +++++++ internal/models/mail_transport_blip_test.go | 36 +++++++ internal/repository/pg_advisor_snapshot.go | 1 + internal/repository/pg_analytics.go | 1 + .../repository/pg_mail_transport_recovery.go | 46 +++++++++ web/src/app/app/emails/page.tsx | 11 ++- .../components/app/emails/InboxDetails.tsx | 97 ++++++++++++++++--- 11 files changed, 261 insertions(+), 26 deletions(-) create mode 100644 internal/models/mail_transport_blip_test.go diff --git a/docs/content/docs/guides/mailboxes.mdx b/docs/content/docs/guides/mailboxes.mdx index 0bab80abd..73b8b832a 100644 --- a/docs/content/docs/guides/mailboxes.mdx +++ b/docs/content/docs/guides/mailboxes.mdx @@ -638,11 +638,11 @@ This is not the same as the risk band that decides which sending worker and IP h ## Health -The Accounts list groups mailboxes as **Healthy** (sending normally), **Warming** (ramping through warmup), or **Needs attention** (paused, failing, or not sending). Each row shows the mailbox with how it connects and its tags, a **Status** that says what it is doing (**Sending**, **Warming**, **Active** when it does both, **Resting**, or **Idle**, and **Error**, **Off** or **Reconnect** when something stops it), campaign emails sent today against its cap, warmup sent today against the ramp target, the inbox rate, and the health score. Hover a status for the reason, and click any column header to sort. A drop in health between refreshes notifies you rather than waiting to be noticed. +The Accounts list groups mailboxes as **Healthy** (sending normally), **Warming** (ramping through warmup), or **Needs attention** (paused, failing, or not sending). Each row shows the mailbox with how it connects and its tags, a **Status** that says what it is doing (**Sending**, **Warming**, **Active** when it does both, **Resting**, or **Idle**, and **Error**, **Off** or **Reconnect** when something stops it, or **Retrying** in amber while a warning such as a dropped connection is being retried on its own), campaign emails sent today against its cap, warmup sent today against the ramp target, the inbox rate, and the health score. Hover a status for the reason, and click any column header to sort. A drop in health between refreshes notifies you rather than waiting to be noticed. Repeated reports of the same error code count once toward the health score, at their highest unresolved severity, rather than making one problem look like several. The drawer groups identical reports while keeping different error details and sending versus sync failures separate. Connection titles name Gmail, Microsoft Outlook or the mail server. **Reported** shows the stored report time: connection and temporary provider-limit observations refresh it, while other error categories may retain their original report time. It is not proof of an ongoing outage. -A later completed sync automatically clears earlier temporary sync errors. A provider-confirmed send clears earlier temporary sending errors, including provider throttling and quota warnings. Recovered reports no longer appear under **Needs attention** or reduce the health score. Older reports that do not identify which operation failed clear once both sending and sync have succeeded after the report; existing reports with that evidence are cleared on upgrade too. A newer failure remains visible, and simply waiting or completing a queued task does not count as recovery. Recoverable connection failures retry automatically while the mailbox is on; a connection warning alone is not a reason to reconnect. Authentication, credential and policy errors retain their own instructions, and a switched-off mailbox must be switched back on before it can retry. +A later completed sync automatically clears earlier temporary sync errors. A provider-confirmed send clears earlier temporary sending errors, including provider throttling and quota warnings. Recovered reports no longer appear under **Needs attention** or reduce the health score. Older reports that do not identify which operation failed clear once both sending and sync have succeeded after the report; existing reports with that evidence are cleared on upgrade too. A newer failure remains visible, and simply waiting or completing a queued task does not count as recovery. Recoverable connection failures retry automatically while the mailbox is on; a connection warning alone is not a reason to reconnect. A temporary connection, server or throttling failure is not shown at all while the affected sync or sending has still succeeded within the last two hours, because the mailbox is working. It appears only when the failure lasts longer than that. Authentication, credential and policy errors retain their own instructions, and a switched-off mailbox must be switched back on before it can retry. A send safety hold is different from a retryable connection failure. If Warmbly cannot confirm whether the provider accepted a message, sending pauses to avoid retrying a message that might already have been sent. The mailbox is shown as needing attention even without a separate connection warning, and its health details explain the hold. A successful inbox sync does not confirm a send. The hold clears on its own and no customer action is needed. After ten minutes Warmbly sets the uncertain email aside for good: a campaign email waits for confirmation for that one contact while the mailbox sends to everyone else, and a Unibox, placement-test or Warmbly Cloud send simply never runs again. A send that never reached the worker is handed back after 30 minutes so the step can go out fresh. A late confirmed result still updates the email automatically. Only legacy sends without durable execution authorization need provider-confirmed resolution. See [send safety](/development/send-safety/). diff --git a/docs/content/docs/guides/warmup.mdx b/docs/content/docs/guides/warmup.mdx index d8145f5ec..d96282a22 100644 --- a/docs/content/docs/guides/warmup.mdx +++ b/docs/content/docs/guides/warmup.mdx @@ -220,7 +220,7 @@ The partner cap exists because a mailbox never writes to the same partner twice Warmup hours are read in the mailbox's timezone: its own when one is set on the **Settings** tab of its drawer, otherwise the workspace timezone under **Settings > Profile > Timezones**, and UTC when neither is set. Set the workspace timezone once and every mailbox that follows it reads its warmup hours in the team's day. A mailbox with its own timezone keeps it, and changing the workspace timezone does not change any mailbox's hours. -While [Sending behavior](/guides/sending-behavior/) is on, which it is for a newly connected mailbox, warmup only sends when both the warmup hours and that workday allow it, and the Warmup tab says so above the hours. A mailbox connected after its workday ends therefore sends its first warmup email the next working morning. Switch the mailbox to **Fixed schedule** on its **Sending** tab to use the warmup hours alone. Changing the warmup hours, days or timezone (the mailbox's own, or the workspace's for a mailbox that follows it), or switching sending behavior on or off, moves the queued warmup send at once. The mailbox list shows when the next warmup send is queued under the day's count. +While [Sending behavior](/guides/sending-behavior/) is on, which it is for a newly connected mailbox, warmup only sends when both the warmup hours and that workday allow it, and the Warmup tab says so above the hours. A mailbox connected after its workday ends therefore sends its first warmup email the next working morning. The workday's working days default to Monday to Friday, so warmup skips the weekend even when the warmup days include it. When that happens the Warmup tab names the skipped days, with a button that adds them to the working days (for example **Work Saturday and Sunday too**). Switch the mailbox to **Fixed schedule** on its **Sending** tab to use the warmup hours alone. Changing the warmup hours, days or timezone (the mailbox's own, or the workspace's for a mailbox that follows it), or switching sending behavior on or off, moves the queued warmup send at once. The mailbox list shows when the next warmup send is queued under the day's count. Warmup hours must end later than they start on the same day. Equal or reversed hours are rejected, including a change to only one endpoint that would invalidate the stored window. Existing invalid windows are not widened or corrected automatically: pending sends stay unstarted and recheck after five minutes, while admin monitoring shows **Invalid warmup sending hours** until the configured window is corrected. Other send protections still apply after correction; this does not replay uncertain sends or confirm mailbox recovery. diff --git a/internal/app/analytics/service.go b/internal/app/analytics/service.go index 34db0969a..ae33c1f41 100644 --- a/internal/app/analytics/service.go +++ b/internal/app/analytics/service.go @@ -276,7 +276,34 @@ func (s *analyticsService) accountErrors(ctx context.Context, accountID uuid.UUI if err != nil { return make([]models.AccountError, 0) } - return toAccountErrors(dbErrors) + success := s.lastTransportSuccess(ctx, []uuid.UUID{accountID}) + return toAccountErrors(withoutTransientBlips(dbErrors, success[accountID], time.Now())) +} + +// lastTransportSuccess reads when each mailbox last synced and sent; a failed read hides nothing. +func (s *analyticsService) lastTransportSuccess(ctx context.Context, ids []uuid.UUID) map[uuid.UUID]map[models.MailTransportOperation]time.Time { + reader, ok := s.emailAccountErrorsRepo.(interface { + LastTransportSuccess(context.Context, []uuid.UUID) (map[uuid.UUID]map[models.MailTransportOperation]time.Time, *errx.Error) + }) + if !ok { + return nil + } + success, xerr := reader.LastTransportSuccess(ctx, ids) + if xerr != nil { + return nil + } + return success +} + +// withoutTransientBlips drops temporary failures on a mailbox that is still working, so a passing blip never reads as a fault. +func withoutTransientBlips(rows []repository.EmailAccountError, success map[models.MailTransportOperation]time.Time, now time.Time) []repository.EmailAccountError { + out := rows[:0:0] + for _, row := range rows { + if !models.MailTransientBlip(row.Severity, row.ErrorCode, row.Operation, row.ObservationSource, success, now) { + out = append(out, row) + } + } + return out } // toAccountErrors maps stored error rows into the API shape, never nil. @@ -648,8 +675,9 @@ func (s *analyticsService) accountStatusesPage(ctx context.Context, orgID uuid.U if xerr != nil { return nil, xerr } + success := s.lastTransportSuccess(ctx, ids) for id, rows := range raw { - errsByID[id] = toAccountErrors(rows) + errsByID[id] = toAccountErrors(withoutTransientBlips(rows, success[id], now)) } } diff --git a/internal/app/consumer/event_email_error.go b/internal/app/consumer/event_email_error.go index 2a4d390eb..50bc775af 100644 --- a/internal/app/consumer/event_email_error.go +++ b/internal/app/consumer/event_email_error.go @@ -273,7 +273,7 @@ func (s *JobsService) HandleEmailServerError(ctx context.Context, event models.E // once a minute and relays what it got each time, so the same unresolved // failure would otherwise fill the mailbox's error list with a row a // minute for as long as the server keeps refusing (issue #405). - recorded := true + notify := true warningMessage := event.UserMessage if s.EmailAccountErrorRepository != nil { errorRecord := &repository.CreateEmailAccountError{ @@ -297,7 +297,7 @@ func (s *JobsService) HandleEmailServerError(ctx context.Context, event models.E log.Error().Str("error", xerr.Message).Msg("Failed to store server error") return xerr } - recorded = xerr == nil && row != nil + notify = xerr == nil && row != nil && !s.transientBlip(ctx, emailAccountID, row) if row != nil && row.UserMessage != nil { warningMessage = *row.UserMessage } else if row != nil && row.Message == errx.ErrMailServerUnreachable.Message { @@ -308,9 +308,9 @@ func (s *JobsService) HandleEmailServerError(ctx context.Context, event models.E // Server errors are temporary - don't change account status // The error will be auto-resolved when connectivity is restored - // Only notify for an error we just recorded: a repeat of one already in + // Only notify for an error we just recorded on a mailbox that is not still working: a repeat of one already in // the drawer must not toast the reader again every pass. - if s.StreamingPublisher != nil && event.UserVisible && recorded { + if s.StreamingPublisher != nil && event.UserVisible && notify { s.StreamingPublisher.PublishEmailWarning( ctx, event.UserID, @@ -323,6 +323,21 @@ func (s *JobsService) HandleEmailServerError(ctx context.Context, event models.E return nil } +// transientBlip is a temporary failure on a mailbox that still worked within the grace window, which is not worth a notification. +func (s *JobsService) transientBlip(ctx context.Context, accountID uuid.UUID, row *repository.EmailAccountError) bool { + reader, ok := s.EmailAccountErrorRepository.(interface { + LastTransportSuccess(context.Context, []uuid.UUID) (map[uuid.UUID]map[models.MailTransportOperation]time.Time, *errx.Error) + }) + if !ok { + return false + } + success, xerr := reader.LastTransportSuccess(ctx, []uuid.UUID{accountID}) + if xerr != nil { + return false + } + return models.MailTransientBlip(row.Severity, row.ErrorCode, row.Operation, row.ObservationSource, success[accountID], time.Now()) +} + func serverErrorObservedAt(timestamp int64) *time.Time { if timestamp <= 0 || timestamp > time.Now().Unix() { return nil diff --git a/internal/models/mail_transport.go b/internal/models/mail_transport.go index 6174229b4..a931ca5db 100644 --- a/internal/models/mail_transport.go +++ b/internal/models/mail_transport.go @@ -33,3 +33,37 @@ func (o MailTransportOperation) Conservative() MailTransportOperation { func ValidMailTransportTime(at, received time.Time) bool { return !at.IsZero() && at.Unix() > 0 && !at.After(received) } + +// MailTransientErrorGrace is how long after its last success a sync or send keeps its temporary failures out of the customer's view. +const MailTransientErrorGrace = 2 * time.Hour + +// MailTransientErrorCodes are the reports a later successful operation disproves on its own. +var MailTransientErrorCodes = []string{"SERVER_UNREACHABLE", "CONNECTION_LOST", "RESOURCE_NOT_FOUND", "IMAP_UNKNOWN", "SENDING_TOO_FAST", "QUOTA_EXCEEDED"} + +func IsMailTransientErrorCode(code string) bool { + for _, c := range MailTransientErrorCodes { + if c == code { + return true + } + } + return false +} + +// MailTransientBlip reports whether a temporary warning sits on a mailbox whose affected operation still succeeded within the grace window. +// A report that does not name its operation needs both sync and send to have succeeded. +func MailTransientBlip(severity, code string, op MailTransportOperation, source MailTransportObservationSource, lastSuccess map[MailTransportOperation]time.Time, now time.Time) bool { + if severity != "WARNING" || !IsMailTransientErrorCode(code) { + return false + } + needed := []MailTransportOperation{op} + if !op.Known() || source == MailTransportClockUnknown { + needed = []MailTransportOperation{MailTransportSync, MailTransportSend} + } + for _, need := range needed { + at, ok := lastSuccess[need] + if !ok || now.Sub(at) > MailTransientErrorGrace { + return false + } + } + return true +} diff --git a/internal/models/mail_transport_blip_test.go b/internal/models/mail_transport_blip_test.go new file mode 100644 index 000000000..49b1b56da --- /dev/null +++ b/internal/models/mail_transport_blip_test.go @@ -0,0 +1,36 @@ +package models + +import ( + "testing" + "time" +) + +func TestMailTransientBlip(t *testing.T) { + now := time.Date(2026, 11, 1, 6, 45, 0, 0, time.UTC) + recent := now.Add(-20 * time.Minute) + stale := now.Add(-MailTransientErrorGrace - time.Minute) + + cases := []struct { + name string + severity string + code string + op MailTransportOperation + source MailTransportObservationSource + success map[MailTransportOperation]time.Time + want bool + }{ + {"sync failure on a mailbox that synced recently", "WARNING", "SERVER_UNREACHABLE", MailTransportSync, MailTransportClockWorker, map[MailTransportOperation]time.Time{MailTransportSync: recent}, true}, + {"sync failure after a long outage", "WARNING", "SERVER_UNREACHABLE", MailTransportSync, MailTransportClockWorker, map[MailTransportOperation]time.Time{MailTransportSync: stale}, false}, + {"sync failure on a mailbox that never synced", "WARNING", "CONNECTION_LOST", MailTransportSync, MailTransportClockWorker, nil, false}, + {"send success does not excuse a sync failure", "WARNING", "SERVER_UNREACHABLE", MailTransportSync, MailTransportClockWorker, map[MailTransportOperation]time.Time{MailTransportSend: recent}, false}, + {"unnamed operation needs both to work", "WARNING", "SERVER_UNREACHABLE", MailTransportUnknown, MailTransportClockUnknown, map[MailTransportOperation]time.Time{MailTransportSync: recent}, false}, + {"unnamed operation with both working", "WARNING", "SERVER_UNREACHABLE", MailTransportUnknown, MailTransportClockUnknown, map[MailTransportOperation]time.Time{MailTransportSync: recent, MailTransportSend: recent}, true}, + {"critical report always shows", "CRITICAL", "SERVER_UNREACHABLE", MailTransportSync, MailTransportClockWorker, map[MailTransportOperation]time.Time{MailTransportSync: recent}, false}, + {"sign-in failure always shows", "WARNING", "AUTHENTICATION_FAILED", MailTransportSync, MailTransportClockWorker, map[MailTransportOperation]time.Time{MailTransportSync: recent}, false}, + } + for _, c := range cases { + if got := MailTransientBlip(c.severity, c.code, c.op, c.source, c.success, now); got != c.want { + t.Errorf("%s: got %v, want %v", c.name, got, c.want) + } + } +} diff --git a/internal/repository/pg_advisor_snapshot.go b/internal/repository/pg_advisor_snapshot.go index 0daf8db12..6c9c34ba6 100644 --- a/internal/repository/pg_advisor_snapshot.go +++ b/internal/repository/pg_advisor_snapshot.go @@ -141,6 +141,7 @@ func (r *advisorRepository) loadMailboxes(ctx context.Context, orgID uuid.UUID, WHERE eae.email_account_id = ea.id AND eae.resolved_at IS NULL AND eae.created_at > NOW() - INTERVAL '7 days' + AND NOT ` + mailTransientBlipSQL("eae") + ` ) err ON true LEFT JOIN LATERAL ( SELECT ` + warmupInboundColumns + ` ` + warmupInboundSQL + ` diff --git a/internal/repository/pg_analytics.go b/internal/repository/pg_analytics.go index 5a8168902..f25fcd1f7 100644 --- a/internal/repository/pg_analytics.go +++ b/internal/repository/pg_analytics.go @@ -1068,6 +1068,7 @@ func (r *analyticsRepository) GetAccountHealthSummary(ctx context.Context, orgID SELECT 1 FROM email_account_errors eae WHERE eae.email_account_id = ea.id AND eae.resolved_at IS NULL AND eae.severity = 'WARNING' + AND NOT ` + mailTransientBlipSQL("eae") + ` ) THEN 'warning' ELSE 'healthy' END AS status diff --git a/internal/repository/pg_mail_transport_recovery.go b/internal/repository/pg_mail_transport_recovery.go index dfe3d39c1..7f46fa55f 100644 --- a/internal/repository/pg_mail_transport_recovery.go +++ b/internal/repository/pg_mail_transport_recovery.go @@ -3,11 +3,14 @@ package repository import ( "context" "errors" + "fmt" + "strings" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/warmbly/warmbly/internal/errx" + "github.com/warmbly/warmbly/internal/infrastructure/db" "github.com/warmbly/warmbly/internal/models" ) @@ -78,3 +81,46 @@ func (r *emailAccountErrorRepository) RecordTransportSuccess(ctx context.Context } return nil } + +// LastTransportSuccess returns each mailbox's latest proven sync and send. +func (r *emailAccountErrorRepository) LastTransportSuccess(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID]map[models.MailTransportOperation]time.Time, *errx.Error) { + out := make(map[uuid.UUID]map[models.MailTransportOperation]time.Time, len(ids)) + if len(ids) == 0 { + return out, nil + } + query := `SELECT email_account_id, operation, recovered_at FROM email_account_transport_recovery WHERE email_account_id = ANY($1::uuid[])` + rows, err := r.DB.Query(ctx, query, ids) + if err != nil { + db.CaptureError(err, query, nil, "query") + return nil, errx.InternalError() + } + defer rows.Close() + for rows.Next() { + var id uuid.UUID + var op models.MailTransportOperation + var at time.Time + if err := rows.Scan(&id, &op, &at); err != nil { + return nil, errx.InternalError() + } + if out[id] == nil { + out[id] = map[models.MailTransportOperation]time.Time{} + } + out[id][op] = at + } + if rows.Err() != nil { + return nil, errx.InternalError() + } + return out, nil +} + +// mailTransientBlipSQL is models.MailTransientBlip for an email_account_errors row aliased as alias. +func mailTransientBlipSQL(alias string) string { + return fmt.Sprintf(`(%[1]s.severity = 'WARNING' AND %[1]s.error_code IN ('%[2]s') AND NOT EXISTS ( + SELECT 1 FROM (VALUES ('sync'), ('send')) need(op) + WHERE (need.op = %[1]s.operation OR %[1]s.operation NOT IN ('sync', 'send') OR %[1]s.observation_source = 'unknown') + AND NOT EXISTS ( + SELECT 1 FROM email_account_transport_recovery blip_rec + WHERE blip_rec.email_account_id = %[1]s.email_account_id AND blip_rec.operation = need.op + AND blip_rec.recovered_at >= NOW() - INTERVAL '%[3]d seconds')))`, + alias, strings.Join(models.MailTransientErrorCodes, "', '"), int(models.MailTransientErrorGrace/time.Second)) +} diff --git a/web/src/app/app/emails/page.tsx b/web/src/app/app/emails/page.tsx index 3315fde96..58b20957e 100644 --- a/web/src/app/app/emails/page.tsx +++ b/web/src/app/app/emails/page.tsx @@ -1466,7 +1466,8 @@ function MailboxTh({ col, sort, onSort }: { col: MailboxColumn; sort: MailboxSor // compact spells a problem out, since it is the one reading a phone must not miss. function MailboxStatusPill({ box, status, historicalIssue, warming, compact = false, pending = false }: { box: Inbox; status?: AccountStatus; historicalIssue?: { status: AccountStatus; observedAt: number }; warming: boolean; compact?: boolean; pending?: boolean }) { if (!status && historicalIssue && box.status === "active") return Last reported issue; - const error = status?.errors?.[0]; + const critical = status?.errors?.find((e) => e.severity === "CRITICAL"); + const error = critical ?? status?.errors?.[0]; const lifecycle = status?.send_lifecycle; const inCampaign = !!status?.in_campaign; const { resting, sending } = mailboxColdActivity(status); @@ -1474,7 +1475,13 @@ function MailboxStatusPill({ box, status, historicalIssue, warming, compact = fa let problem: { label: string; text: string; Icon: LucideIcon; title: string } | null = null; if (box.status === "revoked") problem = { label: "Reconnect", text: "text-rose-600", Icon: UnplugIcon, title: "Access was revoked at the provider. Reconnect the mailbox to send and warm again." }; else if (box.status !== "active") problem = { label: "Off", text: "text-slate-500", Icon: CircleSlashIcon, title: "Switched off: it neither sends, warms nor syncs. Switch it back on from the row's menu or its Settings tab." }; - else if (error) problem = { label: "Error", text: "text-rose-600", Icon: AlertTriangleIcon, title: error.action_required ? `${error.title}. ${error.action_required}` : error.title }; + else if (error) { + const title = error.action_required ? `${error.title}. ${error.action_required}` : error.title; + // Only a critical report stops the mailbox; a warning (a dropped connection, a busy server) is retried on its own. + problem = critical + ? { label: "Error", text: "text-rose-600", Icon: AlertTriangleIcon, title } + : { label: "Retrying", text: "text-amber-600", Icon: RotateCcwIcon, title }; + } if (problem) { const { Icon } = problem; return ( diff --git a/web/src/components/app/emails/InboxDetails.tsx b/web/src/components/app/emails/InboxDetails.tsx index c98dcbd82..64b835354 100644 --- a/web/src/components/app/emails/InboxDetails.tsx +++ b/web/src/components/app/emails/InboxDetails.tsx @@ -110,6 +110,7 @@ import useAuthConfig from "@/lib/api/hooks/auth/useAuthConfig"; import { Toggle } from "@/components/app/campaigns/preferences/components/CampaignPreferenceBoolBox"; import setDirectTracking from "@/lib/api/client/app/emails/setDirectTracking"; import useSendingBehavior from "@/lib/api/hooks/app/emails/useSendingBehavior"; +import useUpdateSendingBehavior from "@/lib/api/hooks/app/emails/useUpdateSendingBehavior"; import useSendingPlan from "@/lib/api/hooks/app/emails/useSendingPlan"; import { minutesToClock, secondsToLabel } from "@/lib/api/models/app/emails/SendingBehavior"; import TagSelector from "../popup/select/TagSelector"; @@ -834,20 +835,23 @@ function OverviewTab({ status, loading, mailbox }: { status?: import("@/lib/api/
Needs attention
- {status.errors.map((e: AccountError) => ( -
-
{e.title}
-
Reported {new Date(e.created_at).toLocaleString()}{e.operation === "send" ? " ยท Sending" : e.operation === "sync" ? " ยท Mailbox sync" : ""}
-
{e.message}
- {e.action_required &&
{e.action_required}
} - {e.id === firstCredentialErrorId && - (mailbox.auth_method === "delegated" ? ( - - ) : ( - - ))} -
- ))} + {status.errors.map((e: AccountError) => { + const tone = e.severity === "CRITICAL" ? errorTone.critical : errorTone.warning; + return ( +
+
{e.title}
+
Reported {new Date(e.created_at).toLocaleString()}{e.operation === "send" ? " ยท Sending" : e.operation === "sync" ? " ยท Mailbox sync" : ""}
+
{e.message}
+ {e.action_required &&
{e.action_required}
} + {e.id === firstCredentialErrorId && + (mailbox.auth_method === "delegated" ? ( + + ) : ( + + ))} +
+ ); + })}
)} @@ -996,6 +1000,12 @@ function AnalyticsTab({ warmup, loading, failed, retry }: { warmup?: import("@/l const WEEKDAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; +// A critical report stops the mailbox; a warning is retried on its own, so it reads as amber, not red. +const errorTone = { + critical: { box: "border-rose-200 bg-rose-50", title: "text-rose-800", meta: "text-rose-700/80", body: "text-rose-700/90", action: "text-rose-900" }, + warning: { box: "border-amber-200 bg-amber-50", title: "text-amber-900", meta: "text-amber-700/80", body: "text-amber-800/90", action: "text-amber-900" }, +}; + const warmupStateTone: Record = { healthy: { text: "text-emerald-600", bar: "bg-emerald-500", label: "Healthy" }, watch: { text: "text-amber-600", bar: "bg-amber-500", label: "Watch" }, @@ -1294,11 +1304,65 @@ function AuthCheckPanel({ mailbox }: { mailbox: Inbox }) { ); } +const ALL_DAYS = 127; + +const listDays = (mask: number) => { + const names = WEEKDAYS.filter((_, i) => (mask & (1 << i)) !== 0); + return names.length > 1 ? `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}` : names.join(""); +}; + +// Warmup sends only on days both calendars allow, so a day ticked here that the persona does not work is silently skipped. +function WarmupDaysNotice({ mailboxId, warmupDays, personaDays }: { mailboxId: string; warmupDays: number; personaDays: number }) { + const wanted = warmupDays || ALL_DAYS; + const skipped = wanted & ~personaDays; + const canManage = usePermission("MANAGE_EMAILS"); + const queryClient = useQueryClient(); + const mutation = useUpdateSendingBehavior(mailboxId); + if (skipped === 0) return null; + + const workDays = async () => { + try { + await mutation.mutateAsync({ weekdays: personaDays | skipped }); + await queryClient.invalidateQueries({ queryKey: ["analytics", "accounts"] }); + toast.success(`Warmup now sends on ${listDays(skipped)} too`); + } catch (e) { + toast.error(buildError(e as unknown as AppError)); + } + }; + + return ( +
+ +
+

+ {(wanted & personaDays) === 0 ? "Warmup has no day to send on" : `Warmup skips ${listDays(skipped)}`} +

+

+ Sending behaviour only works {personaDays ? listDays(personaDays) : "no days"}, and warmup follows its workdays as well as the + days picked here. +

+ {canManage && ( + + )} +
+
+ ); +} + function WarmupTab({ form, update, status, mailbox, canWarmup = true }: { form: Inbox; update: (p: Partial) => void; status?: AccountStatusModel; mailbox: Inbox; canWarmup?: boolean }) { const ws = status?.warmup_status; const wh = status?.warmup_health; const whUnavailable = cloudStandingUnavailable(wh); - const behaviorOn = !!useSendingBehavior(mailbox.id).data?.enabled; + const persona = useSendingBehavior(mailbox.id).data; + const behaviorOn = !!persona?.enabled; const inCampaign = status?.in_campaign; // Warmup on/off is a lifecycle action (immediate), not a saved form field โ€” @@ -1598,6 +1662,9 @@ function WarmupTab({ form, update, status, mailbox, canWarmup = true }: { form: /> + {behaviorOn && persona && ( + + )} ); From af4e7d27f06c44fb6a7e490cc55b78e7999f274b Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sun, 1 Nov 2026 08:46:38 +0100 Subject: [PATCH 055/318] feat: keep the mailbox status red Error for a critical report in any letter case or a status the backend already rates as error, so only non-critical reports on a running mailbox read as amber Retrying --- web/src/app/app/emails/page.tsx | 5 +++-- web/src/components/app/emails/InboxDetails.tsx | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/web/src/app/app/emails/page.tsx b/web/src/app/app/emails/page.tsx index 58b20957e..ba3ce4bfe 100644 --- a/web/src/app/app/emails/page.tsx +++ b/web/src/app/app/emails/page.tsx @@ -1466,8 +1466,9 @@ function MailboxTh({ col, sort, onSort }: { col: MailboxColumn; sort: MailboxSor // compact spells a problem out, since it is the one reading a phone must not miss. function MailboxStatusPill({ box, status, historicalIssue, warming, compact = false, pending = false }: { box: Inbox; status?: AccountStatus; historicalIssue?: { status: AccountStatus; observedAt: number }; warming: boolean; compact?: boolean; pending?: boolean }) { if (!status && historicalIssue && box.status === "active") return Last reported issue; - const critical = status?.errors?.find((e) => e.severity === "CRITICAL"); + const critical = status?.errors?.find((e) => e.severity?.toUpperCase() === "CRITICAL"); const error = critical ?? status?.errors?.[0]; + const stopped = !!critical || status?.health?.status === "error"; const lifecycle = status?.send_lifecycle; const inCampaign = !!status?.in_campaign; const { resting, sending } = mailboxColdActivity(status); @@ -1478,7 +1479,7 @@ function MailboxStatusPill({ box, status, historicalIssue, warming, compact = fa else if (error) { const title = error.action_required ? `${error.title}. ${error.action_required}` : error.title; // Only a critical report stops the mailbox; a warning (a dropped connection, a busy server) is retried on its own. - problem = critical + problem = stopped ? { label: "Error", text: "text-rose-600", Icon: AlertTriangleIcon, title } : { label: "Retrying", text: "text-amber-600", Icon: RotateCcwIcon, title }; } diff --git a/web/src/components/app/emails/InboxDetails.tsx b/web/src/components/app/emails/InboxDetails.tsx index 64b835354..3e15512e8 100644 --- a/web/src/components/app/emails/InboxDetails.tsx +++ b/web/src/components/app/emails/InboxDetails.tsx @@ -836,7 +836,7 @@ function OverviewTab({ status, loading, mailbox }: { status?: import("@/lib/api/ Needs attention
{status.errors.map((e: AccountError) => { - const tone = e.severity === "CRITICAL" ? errorTone.critical : errorTone.warning; + const tone = e.severity?.toUpperCase() === "CRITICAL" ? errorTone.critical : errorTone.warning; return (
{e.title}
From 0d34f40a37da1074662a55e45d392083e8a775d4 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sun, 1 Nov 2026 08:47:58 +0100 Subject: [PATCH 056/318] feat: correct the warmup guide so Fixed schedule keeps the warmup days as well as hours and pool-link warmup-only mailboxes are noted as starting with sending behaviour off --- docs/content/docs/guides/warmup.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/content/docs/guides/warmup.mdx b/docs/content/docs/guides/warmup.mdx index d96282a22..a851fd14a 100644 --- a/docs/content/docs/guides/warmup.mdx +++ b/docs/content/docs/guides/warmup.mdx @@ -220,7 +220,7 @@ The partner cap exists because a mailbox never writes to the same partner twice Warmup hours are read in the mailbox's timezone: its own when one is set on the **Settings** tab of its drawer, otherwise the workspace timezone under **Settings > Profile > Timezones**, and UTC when neither is set. Set the workspace timezone once and every mailbox that follows it reads its warmup hours in the team's day. A mailbox with its own timezone keeps it, and changing the workspace timezone does not change any mailbox's hours. -While [Sending behavior](/guides/sending-behavior/) is on, which it is for a newly connected mailbox, warmup only sends when both the warmup hours and that workday allow it, and the Warmup tab says so above the hours. A mailbox connected after its workday ends therefore sends its first warmup email the next working morning. The workday's working days default to Monday to Friday, so warmup skips the weekend even when the warmup days include it. When that happens the Warmup tab names the skipped days, with a button that adds them to the working days (for example **Work Saturday and Sunday too**). Switch the mailbox to **Fixed schedule** on its **Sending** tab to use the warmup hours alone. Changing the warmup hours, days or timezone (the mailbox's own, or the workspace's for a mailbox that follows it), or switching sending behavior on or off, moves the queued warmup send at once. The mailbox list shows when the next warmup send is queued under the day's count. +While [Sending behavior](/guides/sending-behavior/) is on, which it is for a newly connected mailbox (a warmup-only mailbox enrolled from a self-hosted instance starts with it off), warmup only sends when both the warmup hours and that workday allow it, and the Warmup tab says so above the hours. A mailbox connected after its workday ends therefore sends its first warmup email the next working morning. The workday's working days default to Monday to Friday, so warmup skips the weekend even when the warmup days include it. When that happens the Warmup tab names the skipped days, with a button that adds them to the working days (for example **Work Saturday and Sunday too**). Switch the mailbox to **Fixed schedule** on its **Sending** tab to send on the warmup hours and days alone, without the workday. Changing the warmup hours, days or timezone (the mailbox's own, or the workspace's for a mailbox that follows it), or switching sending behavior on or off, moves the queued warmup send at once. The mailbox list shows when the next warmup send is queued under the day's count. Warmup hours must end later than they start on the same day. Equal or reversed hours are rejected, including a change to only one endpoint that would invalidate the stored window. Existing invalid windows are not widened or corrected automatically: pending sends stay unstarted and recheck after five minutes, while admin monitoring shows **Invalid warmup sending hours** until the configured window is corrected. Other send protections still apply after correction; this does not replay uncertain sends or confirm mailbox recovery. From f38b2a1c31df63d0669eaa5a259f662b37fb0ab7 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sun, 1 Nov 2026 10:09:23 +0100 Subject: [PATCH 057/318] feat: align realtime loopback HTTP socket family while preserving configured transport settings --- realtime/lib/realtime/serve_tls.ex | 12 +++++++ realtime/test/realtime/serve_tls_test.exs | 43 ++++++++++++++++++++++- 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/realtime/lib/realtime/serve_tls.ex b/realtime/lib/realtime/serve_tls.ex index 48574074d..f19aa394a 100644 --- a/realtime/lib/realtime/serve_tls.ex +++ b/realtime/lib/realtime/serve_tls.ex @@ -36,6 +36,18 @@ defmodule Realtime.ServeTLS do end end + defp merge_listener(:http, old, [ip: {127, 0, 0, 1}] = new) when is_list(old) do + transport = Keyword.get(old, :transport_options, []) + + sockets = + transport + |> Keyword.get(:socket_opts, []) + |> Enum.reject(&(&1 in [:inet, :inet6])) + + Keyword.merge(old, new) + |> Keyword.put(:transport_options, Keyword.put(transport, :socket_opts, [:inet | sockets])) + end + defp merge_listener(_key, old, new) when is_list(old) and is_list(new), do: Keyword.merge(old, new) diff --git a/realtime/test/realtime/serve_tls_test.exs b/realtime/test/realtime/serve_tls_test.exs index f18c5a707..e2d545cbc 100644 --- a/realtime/test/realtime/serve_tls_test.exs +++ b/realtime/test/realtime/serve_tls_test.exs @@ -1,5 +1,5 @@ defmodule Realtime.ServeTLSTest do - use ExUnit.Case, async: true + use ExUnit.Case, async: false alias Realtime.ServeTLS @@ -46,6 +46,47 @@ defmodule Realtime.ServeTLSTest do refute Keyword.has_key?(overrides, :http) end + test "loopback HTTP opens with the matching socket family and retains transport settings" do + values = %{ + "SERVE_TLS" => "self-signed", + "SERVE_TLS_PORT" => "8443", + "SERVE_HTTP_LOOPBACK_ONLY" => "true" + } + + previous = Map.new(values, fn {key, _} -> {key, System.get_env(key)} end) + System.put_env(values) + + on_exit(fn -> + Enum.each(previous, fn + {key, nil} -> System.delete_env(key) + {key, value} -> System.put_env(key, value) + end) + + Application.delete_env(:serve_tls_listener_test, __MODULE__) + end) + + Application.put_env(:serve_tls_listener_test, __MODULE__, + http: [ + port: 0, + protocol_options: [invalid_response_headers: :error_terminate], + transport_options: [num_acceptors: 1, socket_opts: [:inet6, reuseaddr: true]] + ] + ) + + ServeTLS.configure_endpoint!(:serve_tls_listener_test, __MODULE__) + http = Application.fetch_env!(:serve_tls_listener_test, __MODULE__)[:http] + transport = http[:transport_options] + assert transport[:num_acceptors] == 1 + assert Keyword.get(transport[:socket_opts], :reuseaddr) + assert http[:protocol_options] == [invalid_response_headers: :error_terminate] + + {:ok, listener} = :gen_tcp.listen(http[:port], [ip: http[:ip]] ++ transport[:socket_opts]) + on_exit(fn -> :gen_tcp.close(listener) end) + assert {:ok, {{127, 0, 0, 1}, port}} = :inet.sockname(listener) + assert {:ok, client} = :gen_tcp.connect({127, 0, 0, 1}, port, [], 1_000) + :gen_tcp.close(client) + end + test "a TLS 1.2 client completes a handshake against the listener options" do {:ok, overrides} = ServeTLS.endpoint_overrides(env([{"SERVE_TLS", "self-signed"}, {"SERVE_TLS_PORT", "1"}])) From 08c0368bad53cf017cc69f5cfb4d6695faba7aa9 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sun, 1 Nov 2026 12:10:15 +0100 Subject: [PATCH 058/318] feat: refresh visible mailbox health and error reports from current server evidence every minute and on stale tab return --- docs/content/docs/guides/mailboxes.mdx | 2 + .../analytics/accountStatusRecovery.test.tsx | 131 ++++++++++++++++++ .../hooks/app/analytics/useAccountStatus.ts | 5 +- .../hooks/app/analytics/useAccountStatuses.ts | 3 + 4 files changed, 140 insertions(+), 1 deletion(-) create mode 100644 web/src/lib/api/hooks/app/analytics/accountStatusRecovery.test.tsx diff --git a/docs/content/docs/guides/mailboxes.mdx b/docs/content/docs/guides/mailboxes.mdx index 73b8b832a..ee3ceb84f 100644 --- a/docs/content/docs/guides/mailboxes.mdx +++ b/docs/content/docs/guides/mailboxes.mdx @@ -642,6 +642,8 @@ The Accounts list groups mailboxes as **Healthy** (sending normally), **Warming* Repeated reports of the same error code count once toward the health score, at their highest unresolved severity, rather than making one problem look like several. The drawer groups identical reports while keeping different error details and sending versus sync failures separate. Connection titles name Gmail, Microsoft Outlook or the mail server. **Reported** shows the stored report time: connection and temporary provider-limit observations refresh it, while other error categories may retain their original report time. It is not proof of an ongoing outage. +While visible, the Accounts list and mailbox drawer refresh their health and error reports every minute as well as on relevant live events. Returning to a tab refreshes stale reports too. These reads show the server's latest recovery evidence; they do not reconnect a mailbox or retry a send. A failed status refresh does not count as recovery. + A later completed sync automatically clears earlier temporary sync errors. A provider-confirmed send clears earlier temporary sending errors, including provider throttling and quota warnings. Recovered reports no longer appear under **Needs attention** or reduce the health score. Older reports that do not identify which operation failed clear once both sending and sync have succeeded after the report; existing reports with that evidence are cleared on upgrade too. A newer failure remains visible, and simply waiting or completing a queued task does not count as recovery. Recoverable connection failures retry automatically while the mailbox is on; a connection warning alone is not a reason to reconnect. A temporary connection, server or throttling failure is not shown at all while the affected sync or sending has still succeeded within the last two hours, because the mailbox is working. It appears only when the failure lasts longer than that. Authentication, credential and policy errors retain their own instructions, and a switched-off mailbox must be switched back on before it can retry. A send safety hold is different from a retryable connection failure. If Warmbly cannot confirm whether the provider accepted a message, sending pauses to avoid retrying a message that might already have been sent. The mailbox is shown as needing attention even without a separate connection warning, and its health details explain the hold. A successful inbox sync does not confirm a send. The hold clears on its own and no customer action is needed. After ten minutes Warmbly sets the uncertain email aside for good: a campaign email waits for confirmation for that one contact while the mailbox sends to everyone else, and a Unibox, placement-test or Warmbly Cloud send simply never runs again. A send that never reached the worker is handed back after 30 minutes so the step can go out fresh. A late confirmed result still updates the email automatically. Only legacy sends without durable execution authorization need provider-confirmed resolution. See [send safety](/development/send-safety/). diff --git a/web/src/lib/api/hooks/app/analytics/accountStatusRecovery.test.tsx b/web/src/lib/api/hooks/app/analytics/accountStatusRecovery.test.tsx new file mode 100644 index 000000000..5b64997aa --- /dev/null +++ b/web/src/lib/api/hooks/app/analytics/accountStatusRecovery.test.tsx @@ -0,0 +1,131 @@ +import type { PropsWithChildren } from "react"; +import { act, cleanup, renderHook } from "@testing-library/react"; +import { focusManager, QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import getAccountStatus from "@/lib/api/client/app/analytics/getAccountStatus"; +import getAccountStatuses from "@/lib/api/client/app/analytics/getAccountStatuses"; +import type AccountStatus from "@/lib/api/models/app/analytics/AccountStatus"; +import useAccountStatus from "./useAccountStatus"; +import useAccountStatuses from "./useAccountStatuses"; + +vi.mock("@/lib/api/client/app/analytics/getAccountStatus", () => ({ default: vi.fn() })); +vi.mock("@/lib/api/client/app/analytics/getAccountStatuses", () => ({ default: vi.fn() })); + +function mailbox(recovered: boolean): AccountStatus { + return { + id: "mailbox", email: "mailbox@example.test", provider: "smtp_imap", status: "active", + last_synced_at: recovered ? new Date() : new Date(Date.now() - 3 * 60 * 60_000), + health: { status: recovered ? "healthy" : "warning", score: recovered ? 100 : 80 }, + errors: recovered ? [] : [{ + id: "failure", error_code: "SERVER_UNREACHABLE", severity: "WARNING", operation: "sync", + title: "Mail server sync connection failed", message: "Automatic retry", created_at: new Date(), + }], + daily_usage: { date: "2026-11-01", campaign_sent: 0, campaign_limit: 10 }, in_campaign: false, + }; +} + +function harness() { + const client = new QueryClient({ defaultOptions: { queries: { + retry: false, gcTime: Infinity, staleTime: 30_000, refetchOnWindowFocus: false, + } } }); + const wrapper = ({ children }: PropsWithChildren) => {children}; + const ids = ["mailbox"]; + const hook = renderHook(({ enabled }) => ({ + drawer: useAccountStatus(enabled ? "mailbox" : ""), list: useAccountStatuses(ids, { enabled }), + }), { wrapper, initialProps: { enabled: true } }); + return { client, ...hook }; +} + +beforeEach(() => { + vi.useFakeTimers(); + vi.clearAllMocks(); + focusManager.setFocused(true); + vi.mocked(getAccountStatus).mockResolvedValue(mailbox(false)); + vi.mocked(getAccountStatuses).mockResolvedValue([mailbox(false)]); +}); + +afterEach(() => { + cleanup(); + focusManager.setFocused(undefined); + vi.useRealTimers(); +}); + +describe("mailbox status freshness without realtime events", () => { + it("replaces a recovered warning and its old success time in both open views", async () => { + const { client, result, unmount } = harness(); + await act(() => vi.advanceTimersByTimeAsync(1)); + expect(result.current.drawer.data?.errors).toHaveLength(1); + expect(result.current.list.data[0]?.errors).toHaveLength(1); + + const recovered = mailbox(true); + vi.mocked(getAccountStatus).mockResolvedValue(recovered); + vi.mocked(getAccountStatuses).mockResolvedValue([recovered]); + await act(() => vi.advanceTimersByTimeAsync(59_000)); + expect(getAccountStatus).toHaveBeenCalledTimes(1); + expect(getAccountStatuses).toHaveBeenCalledTimes(1); + await act(() => vi.advanceTimersByTimeAsync(1_001)); + expect(result.current.drawer.data?.errors).toEqual([]); + expect(result.current.drawer.data?.last_synced_at).toEqual(recovered.last_synced_at); + expect(result.current.list.data[0]?.errors).toEqual([]); + expect(result.current.list.data[0]?.last_synced_at).toEqual(recovered.last_synced_at); + unmount(); client.clear(); + }); + + it("retains a reported failure until the server confirms recovery, and stops after unmount", async () => { + const { client, result, unmount } = harness(); + await act(() => vi.advanceTimersByTimeAsync(60_002)); + expect(getAccountStatus).toHaveBeenCalledTimes(2); + expect(getAccountStatuses).toHaveBeenCalledTimes(2); + expect(result.current.drawer.data?.errors).toHaveLength(1); + expect(result.current.list.data[0]?.errors).toHaveLength(1); + unmount(); + await act(() => vi.advanceTimersByTimeAsync(120_000)); + expect(getAccountStatus).toHaveBeenCalledTimes(2); + expect(getAccountStatuses).toHaveBeenCalledTimes(2); + client.clear(); + }); + + it("pauses periodic reads while hidden and refreshes immediately on return", async () => { + const { client, result, unmount } = harness(); + await act(() => vi.advanceTimersByTimeAsync(1)); + act(() => focusManager.setFocused(false)); + const recovered = mailbox(true); + vi.mocked(getAccountStatus).mockResolvedValue(recovered); + vi.mocked(getAccountStatuses).mockResolvedValue([recovered]); + await act(() => vi.advanceTimersByTimeAsync(60_001)); + expect(getAccountStatus).toHaveBeenCalledTimes(1); + expect(getAccountStatuses).toHaveBeenCalledTimes(1); + act(() => focusManager.setFocused(true)); + await act(() => vi.advanceTimersByTimeAsync(1)); + expect(result.current.drawer.data?.errors).toEqual([]); + expect(result.current.list.data[0]?.errors).toEqual([]); + unmount(); client.clear(); + }); + + it("keeps the last report when a refresh fails instead of assuming recovery", async () => { + const { client, result, unmount } = harness(); + await act(() => vi.advanceTimersByTimeAsync(1)); + vi.mocked(getAccountStatus).mockRejectedValue(new Error("Status unavailable")); + vi.mocked(getAccountStatuses).mockRejectedValue(new Error("Status unavailable")); + await act(() => vi.advanceTimersByTimeAsync(60_001)); + expect(result.current.drawer.isError).toBe(true); + expect(result.current.list.isError).toBe(true); + expect(result.current.drawer.data?.errors).toHaveLength(1); + expect(result.current.list.data[0]?.errors).toHaveLength(1); + expect(result.current.list.observations[0]?.current).toBe(false); + unmount(); client.clear(); + }); + + it("respects disabled status reads during timer and focus changes", async () => { + const { client, rerender, unmount } = harness(); + await act(() => vi.advanceTimersByTimeAsync(1)); + rerender({ enabled: false }); + act(() => focusManager.setFocused(false)); + await act(() => vi.advanceTimersByTimeAsync(60_001)); + act(() => focusManager.setFocused(true)); + await act(() => vi.advanceTimersByTimeAsync(60_001)); + expect(getAccountStatus).toHaveBeenCalledTimes(1); + expect(getAccountStatuses).toHaveBeenCalledTimes(1); + unmount(); client.clear(); + }); +}); diff --git a/web/src/lib/api/hooks/app/analytics/useAccountStatus.ts b/web/src/lib/api/hooks/app/analytics/useAccountStatus.ts index 3a3786299..fa96edbe0 100644 --- a/web/src/lib/api/hooks/app/analytics/useAccountStatus.ts +++ b/web/src/lib/api/hooks/app/analytics/useAccountStatus.ts @@ -6,5 +6,8 @@ export default function useAccountStatus(id: string) { queryKey: ["analytics", "accounts", id], queryFn: () => getAccountStatus(id), enabled: !!id, - }) + // Routine recovery persists without a realtime event. + refetchInterval: 60_000, + refetchOnWindowFocus: true, + }); } diff --git a/web/src/lib/api/hooks/app/analytics/useAccountStatuses.ts b/web/src/lib/api/hooks/app/analytics/useAccountStatuses.ts index bfd442504..fc1279176 100644 --- a/web/src/lib/api/hooks/app/analytics/useAccountStatuses.ts +++ b/web/src/lib/api/hooks/app/analytics/useAccountStatuses.ts @@ -49,6 +49,9 @@ export default function useAccountStatuses(emailIds: string[], options?: { enabl queryKey: ["analytics", "accounts", "list", ids, sourceRevision], queryFn: ({ signal }: { signal: AbortSignal }) => getAccountStatuses(ids, signal), enabled: ids.length > 0 && enabled, + // Routine recovery persists without a realtime event. + refetchInterval: 60_000, + refetchOnWindowFocus: true, })), [chunks, enabled, sourceRevision], ); From 3495649a4f13d7d403224f52c5a3d1b6b45b1242 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sun, 1 Nov 2026 12:18:21 +0100 Subject: [PATCH 059/318] feat: require every drained HTTP target group deletion in scoped runtime TLS ON plans and explicitly target the cleanup resources --- .github/scripts/runtime-tls.sh | 7 +++++ .github/scripts/runtime-tls.test.sh | 27 ++++++++++++++++++- docs/content/docs/development/aws-fargate.mdx | 6 ++++- 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/.github/scripts/runtime-tls.sh b/.github/scripts/runtime-tls.sh index 1860aaec0..f90c105f2 100755 --- a/.github/scripts/runtime-tls.sh +++ b/.github/scripts/runtime-tls.sh @@ -7,6 +7,9 @@ check_plan() { [[ "$stage" = route || "$stage" = drain || "$stage" = on ]] jq -e --arg stage "$stage" ' def service: "\\[\\\"(backend|forms|tracking|realtime)\\\"\\]"; + def http_groups: + ["backend", "forms", "tracking", "realtime"] | + map("aws_lb_target_group.service[\"" + . + "\"]") | sort; def normalize: map(.mountPoints //= [] | .systemControls //= [] | .volumesFrom //= [] | .portMappings = ((.portMappings // []) | map(.hostPort //= .containerPort))); @@ -31,6 +34,9 @@ check_plan() { any(.environment[]; .name == "SERVE_HTTP_LOOPBACK_ONLY" and .value == "true") else all(.environment[]; .name != "SERVE_HTTP_LOOPBACK_ONLY") end); [.resource_changes[]? | select(.change.actions != ["no-op"] and .change.actions != ["read"])] as $changes | + ($stage != "on" or + ([$changes[] | select(.change.actions == ["delete"] and + (.address | test("^aws_lb_target_group\\.service" + service + "$"))) | .address] | sort) == http_groups) and all($changes[]; if (.address | test("^aws_ecs_task_definition\\.service" + service + "$")) then .change.actions == ["delete", "create"] and same_container_except_loopback and same_task_settings @@ -168,6 +174,7 @@ main() { terraform -chdir="$dir" plan -input=false -no-color -lock-timeout=5m -var-file="$vars" \ -var="state_bucket=$STATE_BUCKET" -var="target_tls=$STAGE" \ -target=aws_ecs_service.service -target=aws_lb_listener_rule.tracking_alias \ + -target=aws_lb_target_group.service \ -target=aws_vpc_security_group_ingress_rule.service -target=aws_vpc_security_group_ingress_rule.internal_backend \ -out="$WORK/runtime.tfplan" >>"$log" 2>&1 || { echo 'Runtime TLS plan failed; inspect the private runner log' >&2; return 1; } terraform -chdir="$dir" show -json "$WORK/runtime.tfplan" >"$WORK/runtime.json" diff --git a/.github/scripts/runtime-tls.test.sh b/.github/scripts/runtime-tls.test.sh index 4c39feb22..7b943a548 100755 --- a/.github/scripts/runtime-tls.test.sh +++ b/.github/scripts/runtime-tls.test.sh @@ -3,9 +3,19 @@ set -euo pipefail cd "$(dirname "$0")/../.." work=$(mktemp -d) trap 'rm -rf "$work"' EXIT +complete_cleanup() { + jq ' + [.resource_changes[].address] as $present | + .resource_changes += [ ["backend", "forms", "tracking", "realtime"][] | + {address:("aws_lb_target_group.service[\"" + . + "\"]"),change:{actions:["delete"]}} | + select(.address as $address | $present | index($address) == null)] + ' "$1" >"$work/complete.json" + mv "$work/complete.json" "$1" +} expect() { local want=$1 address=$2 actions=$3 stage=${4:-route} jq -n --arg address "$address" --argjson actions "$actions" '{resource_changes:[{address:$address,change:{actions:$actions}}]}' >"$work/plan.json" + if [ "$stage" = on ]; then complete_cleanup "$work/plan.json"; fi if bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" "$stage" 2>/dev/null; then [ "$want" = pass ] else @@ -60,12 +70,14 @@ if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" route 2>/ exit 1 fi jq -n '{resource_changes:[{address:"aws_ecs_task_definition.service[\"backend\"]",change:{actions:["delete","create"],before:{container_definitions:([{image:"pinned",environment:[]}]|tojson)},after:{container_definitions:([{image:"pinned",environment:[{name:"SERVE_HTTP_LOOPBACK_ONLY",value:"true"}]}]|tojson)}}}]}' >"$work/plan.json" +complete_cleanup "$work/plan.json" bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" on if bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" route 2>/dev/null; then echo 'Loopback-only listener accepted before HTTP registrations drained' >&2 exit 1 fi -jq '.resource_changes[0].change |= ({actions:.actions,before:.after,after:.before})' "$work/plan.json" >"$work/route.json" +jq '.resource_changes |= map(select(.address | startswith("aws_ecs_task_definition"))) | + .resource_changes[0].change |= ({actions:.actions,before:.after,after:.before})' "$work/plan.json" >"$work/route.json" bash .github/scripts/runtime-tls.sh check-plan "$work/route.json" route jq '.resource_changes[0].change.after.container_definitions |= (fromjson | .[0].image = "changed" | tojson)' "$work/plan.json" >"$work/changed.json" if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" on 2>/dev/null; then @@ -112,4 +124,17 @@ for change in '.services.services[0].pendingCount=1' '.services.services[0].depl exit 1 fi done +jq -n '{resource_changes:[]}' >"$work/deletions.json" +complete_cleanup "$work/deletions.json" +bash .github/scripts/runtime-tls.sh check-plan "$work/deletions.json" on +for change in '.resource_changes=[]' '.resource_changes|=.[1:]' \ + '.resource_changes[0].change.actions=["no-op"]' \ + '.resource_changes[0].change.actions=["delete","create"]' \ + '.resource_changes[0].address="aws_lb_target_group.service[\"consumer\"]"'; do + jq "$change" "$work/deletions.json" >"$work/changed.json" + if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" on 2>/dev/null; then + echo 'ON accepted without the exact four HTTP group deletions' >&2 + exit 1 + fi +done echo 'Runtime TLS plan guards passed' diff --git a/docs/content/docs/development/aws-fargate.mdx b/docs/content/docs/development/aws-fargate.mdx index fac16624e..2e26e2b3a 100644 --- a/docs/content/docs/development/aws-fargate.mdx +++ b/docs/content/docs/development/aws-fargate.mdx @@ -444,7 +444,11 @@ as `previous_run`. After the drain run succeeds, persist `target_tls=drain`, upl a new snapshot, and dispatch `on` with the successful drain run ID. Each stage verifies the preceding workflow completed all bakes. Cleanup is refused until HTTP references and registrations have drained. Review and approve each -plan separately. Persist `target_tls=on` only after it succeeds, then verify the +plan separately. The scoped plan explicitly targets the HTTP groups, and an +`on` plan must delete exactly the four groups for backend, forms, tracking and +realtime. A plan that omits any group is refused. This check expects the normal +drain-to-on transition; a partially completed transition requires a separately +reviewed recovery path rather than an unchanged retry. Persist `target_tls=on` only after it succeeds, then verify the effective loopback listeners and HTTPS routes. ## One-time GitHub setup From 54593d061dcd5503a3d495ae989aa85ac99ca006 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sun, 1 Nov 2026 12:26:47 +0100 Subject: [PATCH 060/318] feat: validate drained HTTP target identities against state and restrict TLS recovery plans to their exact deletions --- .github/scripts/runtime-tls-recovery.sh | 63 ++++++++++++++++++ .github/scripts/runtime-tls-recovery.test.sh | 70 ++++++++++++++++++++ .github/workflows/runtime-tls.yml | 2 + 3 files changed, 135 insertions(+) create mode 100755 .github/scripts/runtime-tls-recovery.sh create mode 100755 .github/scripts/runtime-tls-recovery.test.sh diff --git a/.github/scripts/runtime-tls-recovery.sh b/.github/scripts/runtime-tls-recovery.sh new file mode 100755 index 000000000..028b3b9cf --- /dev/null +++ b/.github/scripts/runtime-tls-recovery.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# Read-only validators for a separately reviewed hosted TLS cleanup recovery. +set -euo pipefail + +check_baseline() { + jq -e ' + def group_identity: {TargetGroupName, TargetGroupArn, Protocol, Port, VpcId}; + . as $baseline | + .account == "925323749693" and .region == "us-east-1" and + (.state.lineage | type == "string" and test("^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$")) and + (.state.serial | type == "number" and . >= 0 and floor == .) and + (.state.versionId | type == "string" and length > 0 and . != "null" and (test("[\\r\\n]") | not)) and + (.state.sha256 | type == "string" and test("^[a-f0-9]{64}$")) and + (.httpGroups | type == "array" and length == 4) and + ([.httpGroups[].TargetGroupName] | sort) == + (["backend", "forms", "tracking", "realtime"] | map("warmbly-production-" + .) | sort) and + ([.httpGroups[].TargetGroupArn] | unique | length == 4) and + ([.httpGroups[].VpcId] | unique | length == 1) and + all(.httpGroups[]; + .Protocol == "HTTP" and + (.Port | type == "number" and . > 0 and . <= 65535 and floor == .) and + (.VpcId | type == "string" and test("^vpc-[a-f0-9]+$")) and + .TargetGroupArn == ("arn:aws:elasticloadbalancing:us-east-1:925323749693:targetgroup/" + .TargetGroupName + "/" + (.TargetGroupArn | split("/")[-1])) and + (.TargetGroupArn | split("/")[-1] | test("^[a-f0-9]{16}$")) and + (.LoadBalancerArns | type == "array" and length == 0) and + (.targets | type == "array" and length == 0)) and + (.state.httpGroups | type == "array" and length == 4) and + (.state.httpGroups | map(group_identity) | sort_by(.TargetGroupName)) == + ($baseline.httpGroups | map(group_identity) | sort_by(.TargetGroupName)) + ' "$1" >/dev/null || { echo 'Recovery requires four identified, drained HTTP groups matching reviewed state' >&2; return 1; } +} + +check_plan() { + check_baseline "$2" + jq -e --slurpfile baseline "$2" ' + (.resource_changes | type == "array") and + ( + [.resource_changes[]? | select(.change.actions != ["no-op"] and .change.actions != ["read"])] as $changes | + ($baseline[0].httpGroups | map({ + address:("aws_lb_target_group.service[\"" + (.TargetGroupName | ltrimstr("warmbly-production-")) + "\"]"), + group:. + })) as $expected | + ($changes | map(.address) | sort) == ($expected | map(.address) | sort) and + all($changes[]; + . as $change | + .change.actions == ["delete"] and (.change | has("after")) and .change.after == null and + any($expected[]; + .address == $change.address and + $change.change.before.arn == .group.TargetGroupArn and + $change.change.before.id == .group.TargetGroupArn and + $change.change.before.name == .group.TargetGroupName and + $change.change.before.protocol == .group.Protocol and + $change.change.before.port == .group.Port and + $change.change.before.vpc_id == .group.VpcId)) and + ([.resource_drift[]? | select(.change.actions != ["no-op"])] | length == 0)) + ' "$1" >/dev/null || { echo 'Recovery plan must contain only the four reviewed HTTP group deletions without drift' >&2; return 1; } +} + +case "${1:-}" in + check-baseline) check_baseline "${2:?}" ;; + check-plan) check_plan "${2:?}" "${3:?}" ;; + *) echo 'Only read-only recovery validation is supported' >&2; exit 1 ;; +esac diff --git a/.github/scripts/runtime-tls-recovery.test.sh b/.github/scripts/runtime-tls-recovery.test.sh new file mode 100755 index 000000000..27ab22d55 --- /dev/null +++ b/.github/scripts/runtime-tls-recovery.test.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/../.." +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +guard=.github/scripts/runtime-tls-recovery.sh +jq -n ' + ["backend", "forms", "tracking", "realtime"] | + map({TargetGroupName:("warmbly-production-" + .), + TargetGroupArn:("arn:aws:elasticloadbalancing:us-east-1:925323749693:targetgroup/warmbly-production-" + . + "/0123456789abcdef"), + Protocol:"HTTP",Port:8080,VpcId:"vpc-0123456789abcdef0",LoadBalancerArns:[],targets:[]}) as $groups | + {account:"925323749693",region:"us-east-1",httpGroups:$groups, + state:{lineage:"01234567-89ab-cdef-0123-456789abcdef",serial:1,versionId:"reviewed-version",sha256:("a"*64),httpGroups:$groups}} +' >"$work/baseline.json" +jq '{resource_changes:[.httpGroups[] | { + address:("aws_lb_target_group.service[\"" + (.TargetGroupName | ltrimstr("warmbly-production-")) + "\"]"), + change:{actions:["delete"],after:null,before:{arn:.TargetGroupArn,id:.TargetGroupArn,name:.TargetGroupName,protocol:.Protocol,port:.Port,vpc_id:.VpcId}} +}]}' "$work/baseline.json" >"$work/plan.json" +bash "$guard" check-baseline "$work/baseline.json" +bash "$guard" check-plan "$work/plan.json" "$work/baseline.json" +jq '.httpGroups |= reverse' "$work/baseline.json" >"$work/reordered-baseline.json" +jq '.resource_changes |= reverse | + .resource_changes += [{address:"data.aws_caller_identity.current",change:{actions:["read"]}}]' "$work/plan.json" >"$work/reordered-plan.json" +bash "$guard" check-plan "$work/reordered-plan.json" "$work/reordered-baseline.json" +for change in '.account="123456789012"' '.region="us-west-2"' \ + '.httpGroups|=.[1:]' '.httpGroups[0]=.httpGroups[1]' \ + '.httpGroups[0].LoadBalancerArns=["still-referenced"]' \ + '.httpGroups[0].targets=[{Target:{Id:"still-registered"}}]' \ + '.httpGroups[0].Protocol="HTTPS"' '.httpGroups[0].Port=0' \ + '.httpGroups[0].VpcId="vpc-11111111"' \ + '.httpGroups[0].TargetGroupArn="arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/warmbly-production-backend/0123456789abcdef"' \ + '.httpGroups[0].targets=null' '.httpGroups[0].LoadBalancerArns=null' \ + '.state.httpGroups[0].TargetGroupArn="changed"' '.state.httpGroups|=.[1:]' \ + '.state.versionId=""' '.state.versionId="null"' '.state.sha256=""' \ + '.state.lineage=null' '.state.lineage=("-"*36)' '.state.serial=-1'; do + jq "$change" "$work/baseline.json" >"$work/changed.json" + if bash "$guard" check-plan "$work/plan.json" "$work/changed.json" 2>/dev/null; then + echo "Recovery accepted an invalid baseline: $change" >&2 + exit 1 + fi +done +for change in '.resource_changes=[]' '.resource_changes|=.[1:]' \ + '.resource_changes[0]=.resource_changes[1]' \ + '.resource_changes[0].change.actions=["no-op"]' \ + '.resource_changes[0].change.actions=["delete","create"]' \ + '.resource_changes[0].change.after={}' \ + 'del(.resource_changes[0].change.after)' \ + '.resource_changes[0].change.before.arn="changed"' \ + '.resource_changes[0].change.before.id="changed"' \ + '.resource_changes[0].change.before.port=465' \ + '.resource_changes[0].change.before.protocol="HTTPS"' \ + '.resource_changes[0].change.before.name="different"' \ + '.resource_changes[0].change.before.vpc_id="vpc-11111111"' \ + '.resource_changes[0].address="aws_lb_target_group.service[\"consumer\"]"' \ + '.resource_changes += [{address:"aws_ecs_service.service[\"backend\"]",change:{actions:["update"]}}]' \ + '.resource_changes += [{address:"aws_vpc_security_group_ingress_rule.internal_backend[0]",change:{actions:["delete"]}}]' \ + '.resource_drift=[{address:"aws_lb_target_group.service[\"backend\"]",change:{actions:["update"]}}]'; do + jq "$change" "$work/plan.json" >"$work/changed.json" + if bash "$guard" check-plan "$work/changed.json" "$work/baseline.json" 2>/dev/null; then + echo "Recovery accepted a different cleanup plan: $change" >&2 + exit 1 + fi +done +for action in plan apply delete; do + if bash "$guard" "$action" 2>/dev/null; then + echo 'Read-only recovery validator accepted an execution action' >&2 + exit 1 + fi +done +echo 'Read-only TLS recovery identity and scope guards passed' diff --git a/.github/workflows/runtime-tls.yml b/.github/workflows/runtime-tls.yml index a57cc1ffc..0606b67ac 100644 --- a/.github/workflows/runtime-tls.yml +++ b/.github/workflows/runtime-tls.yml @@ -44,6 +44,8 @@ jobs: persist-credentials: false - run: shellcheck .github/scripts/runtime-tls.sh .github/scripts/runtime-tls.test.sh - run: bash .github/scripts/runtime-tls.test.sh + - run: shellcheck .github/scripts/runtime-tls-recovery.sh .github/scripts/runtime-tls-recovery.test.sh + - run: bash .github/scripts/runtime-tls-recovery.test.sh plan: needs: check From ce84486f399b578573147e8ec939a1bee342cfba Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sun, 1 Nov 2026 12:34:12 +0100 Subject: [PATCH 061/318] feat: preserve cached mailbox row measurements with explicit freshness and confirmed recovery during status polling --- docs/content/docs/guides/mailboxes.mdx | 2 +- web/src/app/app/emails/page.test.tsx | 55 ++++++++++++++++++++++++-- web/src/app/app/emails/page.tsx | 50 +++++++++++++---------- 3 files changed, 82 insertions(+), 25 deletions(-) diff --git a/docs/content/docs/guides/mailboxes.mdx b/docs/content/docs/guides/mailboxes.mdx index ee3ceb84f..f347ed345 100644 --- a/docs/content/docs/guides/mailboxes.mdx +++ b/docs/content/docs/guides/mailboxes.mdx @@ -642,7 +642,7 @@ The Accounts list groups mailboxes as **Healthy** (sending normally), **Warming* Repeated reports of the same error code count once toward the health score, at their highest unresolved severity, rather than making one problem look like several. The drawer groups identical reports while keeping different error details and sending versus sync failures separate. Connection titles name Gmail, Microsoft Outlook or the mail server. **Reported** shows the stored report time: connection and temporary provider-limit observations refresh it, while other error categories may retain their original report time. It is not proof of an ongoing outage. -While visible, the Accounts list and mailbox drawer refresh their health and error reports every minute as well as on relevant live events. Returning to a tab refreshes stale reports too. These reads show the server's latest recovery evidence; they do not reconnect a mailbox or retry a send. A failed status refresh does not count as recovery. +While visible, the Accounts list and mailbox drawer refresh their health and error reports every minute as well as on relevant live events. Returning to a tab refreshes stale reports too. The list keeps cached row measurements during a refresh or after a failed read, marked **Last observed**. A retained issue stays visible until a fresh successful result confirms recovery. These reads show the server's latest recovery evidence; they do not reconnect a mailbox or retry a send. A failed status refresh does not count as recovery. A later completed sync automatically clears earlier temporary sync errors. A provider-confirmed send clears earlier temporary sending errors, including provider throttling and quota warnings. Recovered reports no longer appear under **Needs attention** or reduce the health score. Older reports that do not identify which operation failed clear once both sending and sync have succeeded after the report; existing reports with that evidence are cleared on upgrade too. A newer failure remains visible, and simply waiting or completing a queued task does not count as recovery. Recoverable connection failures retry automatically while the mailbox is on; a connection warning alone is not a reason to reconnect. A temporary connection, server or throttling failure is not shown at all while the affected sync or sending has still succeeded within the last two hours, because the mailbox is working. It appears only when the failure lasts longer than that. Authentication, credential and policy errors retain their own instructions, and a switched-off mailbox must be switched back on before it can retry. diff --git a/web/src/app/app/emails/page.test.tsx b/web/src/app/app/emails/page.test.tsx index bc5d1b667..29f2cad7e 100644 --- a/web/src/app/app/emails/page.test.tsx +++ b/web/src/app/app/emails/page.test.tsx @@ -33,7 +33,7 @@ vi.mock("@/hooks/usePermission", () => ({ usePermission: () => true })); vi.mock("@/lib/api/hooks/app/emails/useEmails", () => ({ default: ({ tag }: { tag: string }) => ({ emails: statusState.emailsLoading || statusState.emailsError ? [] : tag ? rows.filter((row) => row.tags.includes(tag)) : rows, isLoading: statusState.emailsLoading, isPending: statusState.emailsLoading, isError: statusState.emailsError || statusState.emailsIncomplete, isIncomplete: statusState.emailsIncomplete, refetch: vi.fn() }), })); -vi.mock("@/lib/api/hooks/app/analytics/useAccountStatuses", () => ({ default: () => statusState })); +vi.mock("@/lib/api/hooks/app/analytics/useAccountStatuses", () => ({ default: () => ({ ...statusState, observations: statusState.observations.length ? statusState.observations : statusState.data.map((status) => ({ status, observedAt: 0, current: !statusState.isFetching && !statusState.isError })) }) })); vi.mock("@/lib/api/hooks/app/subscription/useFeatureStatus", () => ({ default: () => ({ data: { can_use_warmup: true } }) })); vi.mock("@/lib/api/hooks/auth/useAuthConfig", () => ({ default: () => ({ data: {}, isLoading: false }) })); vi.mock("@/lib/api/hooks/app/emails/useMailboxGrants", () => ({ useSigninMigration: () => ({ data: { data: [] } }) })); @@ -215,12 +215,59 @@ describe("mailbox status while account and Cloud checks settle", () => { statusState.isFetching = true; await renderPage(); expect(screen.queryByText("Healthy 100")).not.toBeInTheDocument(); + expect(screen.getByText("Last observed: Healthy 100")).toBeInTheDocument(); + expect(screen.getByTitle("0 of 50 campaign emails sent today")).toBeInTheDocument(); statusState.isFetching = false; fireEvent.click(screen.getByRole("button", { name: "Mailbox" })); expect(screen.getAllByText("Unavailable").length).toBeGreaterThan(0); statusState.isError = true; fireEvent.click(screen.getByRole("button", { name: "Mailbox" })); expect(screen.queryByText("Healthy 100")).not.toBeInTheDocument(); + expect(screen.getByText("Last observed: Healthy 100")).toBeInTheDocument(); + expect(screen.getByTitle("0 of 50 campaign emails sent today")).toBeInTheDocument(); + }); + + it.each(["isFetching", "isError"] as const)("retains cached row metrics and marks only unconfirmed chunks stale during %s", async (state) => { + statusState.data = rows.map(measuredStatus); + statusState.data[0].daily_usage = { date: "2026-11-01", campaign_sent: 7, campaign_limit: 50 }; + statusState.observations = statusState.data.map((status) => ({ status, observedAt: Date.now(), current: true })); + await renderPage(); + + statusState[state] = true; + statusState.observations = statusState.observations.map((observation) => ({ ...observation, current: observation.status.id !== rows[0].id })); + fireEvent.click(screen.getByRole("button", { name: "Mailbox" })); + const sara = screen.getByText(rows[0].email).closest("tr"); + const kavya = screen.getByText(rows[1].email).closest("tr"); + expect(sara).not.toBeNull(); + expect(kavya).not.toBeNull(); + expect(within(sara!).getByTitle("7 of 50 campaign emails sent today")).toBeInTheDocument(); + expect(within(sara!).getByText("Last observed: Healthy 100")).toBeInTheDocument(); + expect(within(sara!).queryByText("Checkingโ€ฆ")).not.toBeInTheDocument(); + expect(within(kavya!).getByText("Healthy 100")).toBeInTheDocument(); + expect(within(kavya!).queryByText("Last observed: Healthy 100")).not.toBeInTheDocument(); + }); + + it("keeps a retained issue ahead of cached healthy data until a fresh recovery arrives", async () => { + const failed = { ...measuredStatus(rows[0]), health: { status: "error", score: 40 } } satisfies AccountStatus; + statusState.data = [failed]; + statusState.observations = [{ status: failed, observedAt: Date.now(), current: true }]; + await renderPage(); + + const recovered = measuredStatus(rows[0]); + statusState.data = [recovered]; + statusState.isError = true; + statusState.observations = [{ status: recovered, observedAt: Date.now() + 1, current: false }]; + fireEvent.click(screen.getByRole("button", { name: "Mailbox" })); + expect(screen.getAllByText("Last reported issue").length).toBeGreaterThan(0); + expect(screen.getByText("Last observed: Issue 40")).toBeInTheDocument(); + expect(screen.queryByText("Last observed: Healthy 100")).not.toBeInTheDocument(); + expect(screen.getByTitle("0 of 50 campaign emails sent today")).toBeInTheDocument(); + + statusState.isError = false; + statusState.observations = [{ status: recovered, observedAt: Date.now() + 2, current: true }]; + fireEvent.click(screen.getByRole("button", { name: "Mailbox" })); + await waitFor(() => expect(screen.queryAllByText("Last reported issue")).toHaveLength(0)); + expect(screen.getByText("Healthy 100")).toBeInTheDocument(); }); it("does not assume local-only health when the Cloud connection lookup failed", async () => { @@ -230,7 +277,7 @@ describe("mailbox status while account and Cloud checks settle", () => { await renderPage(); expect(screen.queryByText("Healthy 100")).not.toBeInTheDocument(); const sara = screen.getAllByRole("row").find((row) => row.textContent?.includes(rows[0].email)); - expect(within(sara!).getByText("Issue 40")).toBeInTheDocument(); + expect(within(sara!).getByText("Last observed: Issue 40")).toBeInTheDocument(); expect(screen.getAllByText("Unavailable").length).toBeGreaterThan(0); }); @@ -241,10 +288,11 @@ describe("mailbox status while account and Cloud checks settle", () => { await renderPage(); expect(screen.getByText("Issue 40")).toBeInTheDocument(); statusState.isFetching = true; + statusState.observations = statusState.observations.map((observation) => ({ ...observation, current: false })); fireEvent.click(screen.getByRole("button", { name: "Mailbox" })); expect(screen.getAllByText("Last reported issue").length).toBeGreaterThan(0); expect(screen.getByText("Last observed: Issue 40")).toBeInTheDocument(); - expect(screen.queryByTitle("0 of 50 campaign emails sent today")).not.toBeInTheDocument(); + expect(screen.getAllByTitle("0 of 50 campaign emails sent today")).toHaveLength(rows.length); statusState.isFetching = false; statusState.cloudLoading = true; @@ -268,6 +316,7 @@ describe("mailbox status while account and Cloud checks settle", () => { statusState.observations = statusState.data.map((status) => ({ status, observedAt, current: true })); await renderPage(); statusState.isFetching = true; + statusState.observations = statusState.observations.map((observation) => ({ ...observation, current: false })); fireEvent.click(screen.getByRole("button", { name: "Mailbox" })); expect(screen.getAllByText("Last reported issue").length).toBeGreaterThan(0); const clock = vi.spyOn(Date, "now").mockReturnValue(observedAt + 5 * 60_000 + 1); diff --git a/web/src/app/app/emails/page.tsx b/web/src/app/app/emails/page.tsx index ba3ce4bfe..f74627f59 100644 --- a/web/src/app/app/emails/page.tsx +++ b/web/src/app/app/emails/page.tsx @@ -201,14 +201,18 @@ export default function AddressesPage() { // Coerce to an array defensively: a wrong-shape (non-array) response must // never reach a `forโ€ฆof`, which would throw "{} is not iterable". const accountStatuses = useMemo( - () => (!cloudChecking && !statuses.isError && !statuses.isFetching && Array.isArray(statuses.data) ? statuses.data : []), - [cloudChecking, statuses.data, statuses.isError, statuses.isFetching], + () => (!cloudChecking && Array.isArray(statuses.data) ? statuses.data : []), + [cloudChecking, statuses.data], ); const statusById = useMemo(() => { const m = new Map(); for (const s of accountStatuses) m.set(s.id, s); return m; }, [accountStatuses]); + const currentStatusIds = useMemo( + () => new Set(statuses.observations.filter((observation) => observation.current).map(({ status }) => status.id)), + [statuses.observations], + ); const statusChecking = emailsData.isLoading || cloudChecking || statuses.isLoading || statuses.isFetching; const cloudStandingUnavailable = cloud.connected && (emailsData.emails ?? []).some((box) => { const row = cloud.rowFor(box.id); @@ -248,21 +252,20 @@ export default function AddressesPage() { // Proactively notify the user when a mailbox's health drops. const prevHealth = useRef>(new Map()); useEffect(() => { - if (accountStatuses.length === 0) return; + if (cloudChecking || cloudUnavailable) return; const prev = prevHealth.current; - const next = new Map(); - for (const s of accountStatuses) { + for (const { status: s, current } of statuses.observations) { + if (!current) continue; const cur = s.health?.status ?? "healthy"; - next.set(s.id, cur); const before = prev.get(s.id); // A reputation slowdown is on the row and recovers by itself; a toast reads as the mailbox stopping. if (before && (HEALTH_RANK[cur] ?? 0) > (HEALTH_RANK[before] ?? 0) && !reputationOnlyWarning(s)) { const reason = (!cloudHealthUnavailable(s.warmup_health) && s.warmup_health?.reason) || s.health?.issues?.[0]; toast.error(`${s.email} health dropped to ${cur}${reason ? ` โ€” ${reason}` : ""}`); } + prev.set(s.id, cur); } - prevHealth.current = next; - }, [accountStatuses]); + }, [statuses.observations, cloudChecking, cloudUnavailable]); const removeSelected = () => { if (selected.length === 0 || removing || cloudRemovalPending) return; @@ -628,6 +631,7 @@ export default function AddressesPage() { box={box} tags={p?.user.tags ?? []} status={(cloud.unavailable || cloudStandingUnavailable) && statusById.get(box.id)?.health?.status === "healthy" && !statusById.get(box.id)?.errors?.length ? undefined : statusById.get(box.id)} + statusCurrent={!cloudChecking && !cloud.unavailable && !cloudStandingUnavailable && currentStatusIds.has(box.id)} lastReportedIssue={lastReportedIssues.get(box.id)} statusPending={statusChecking && !statusUnavailable} cloudStatusPending={cloudChecking || cloud.unavailable || cloudStandingUnavailable} @@ -822,6 +826,7 @@ function MailboxRow({ box, tags, status, + statusCurrent, lastReportedIssue, statusPending, cloudStatusPending, @@ -839,6 +844,7 @@ function MailboxRow({ box: Inbox; tags: Tag[]; status?: AccountStatus; + statusCurrent: boolean; lastReportedIssue?: { status: AccountStatus; observedAt: number }; statusPending: boolean; cloudStatusPending: boolean; @@ -902,8 +908,10 @@ function MailboxRow({ // Warmup only runs on a mailbox that is on, whatever its warmup setting says. const warming = active && box.status === "active"; - const historicalIssue = !status && lastReportedIssue && Date.now() - lastReportedIssue.observedAt <= LAST_REPORTED_ISSUE_MS ? lastReportedIssue : undefined; - const tone = healthTone(status ?? historicalIssue?.status); + const historicalIssue = !statusCurrent && lastReportedIssue && Date.now() - lastReportedIssue.observedAt <= LAST_REPORTED_ISSUE_MS ? lastReportedIssue : undefined; + const stale = !!status && !statusCurrent; + const displayedHealth = historicalIssue?.status ?? status; + const tone = healthTone(displayedHealth); const ws = status?.warmup_status; const inCampaign = status?.in_campaign; @@ -1130,7 +1138,7 @@ function MailboxRow({
{/* Too narrow for the metric columns: the same readings, labelled, under the address. */}
- + Warmup {cloudStatusPending ? statusPending ? "Checkingโ€ฆ" : "Unavailable" : warmupCell} @@ -1143,8 +1151,8 @@ function MailboxRow({ Health - {historicalIssue && Last observed} - {status?.health?.score ?? historicalIssue?.status.health?.score ?? "โ€”"} + {(historicalIssue || stale) && Last observed} + {displayedHealth?.health?.score ?? "โ€”"}
@@ -1155,7 +1163,7 @@ function MailboxRow({
- + {status?.daily_usage ? ( @@ -1192,10 +1200,10 @@ function MailboxRow({ type="button" onClick={(e) => { e.stopPropagation(); onOpen(box.id, "overview"); }} className={`inline-flex items-center gap-1.5 text-[11px] font-medium max-w-full ${tone.text}`} - title={historicalIssue ? `Last observed ${new Date(historicalIssue.observedAt).toLocaleString()}. Current health unavailable.` : status?.health?.issues?.join("\n") || "View mailbox health"} + title={historicalIssue ? `Last observed ${new Date(historicalIssue.observedAt).toLocaleString()}. Current health unavailable.` : stale ? "Last known measurements. Current status is unconfirmed until a successful refresh." : status?.health?.issues?.join("\n") || "View mailbox health"} > - + e.stopPropagation()}> @@ -1464,8 +1472,8 @@ function MailboxTh({ col, sort, onSort }: { col: MailboxColumn; sort: MailboxSor // What the mailbox is doing right now. Cold sending and warmup run side by // side, so both show when both are on; a problem that stops it wins. // compact spells a problem out, since it is the one reading a phone must not miss. -function MailboxStatusPill({ box, status, historicalIssue, warming, compact = false, pending = false }: { box: Inbox; status?: AccountStatus; historicalIssue?: { status: AccountStatus; observedAt: number }; warming: boolean; compact?: boolean; pending?: boolean }) { - if (!status && historicalIssue && box.status === "active") return Last reported issue; +function MailboxStatusPill({ box, status, stale, historicalIssue, warming, compact = false, pending = false }: { box: Inbox; status?: AccountStatus; stale: boolean; historicalIssue?: { status: AccountStatus; observedAt: number }; warming: boolean; compact?: boolean; pending?: boolean }) { + if (historicalIssue && box.status === "active") return Last reported issue; const critical = status?.errors?.find((e) => e.severity?.toUpperCase() === "CRITICAL"); const error = critical ?? status?.errors?.[0]; const stopped = !!critical || status?.health?.status === "error"; @@ -1510,15 +1518,15 @@ function MailboxStatusPill({ box, status, historicalIssue, warming, compact = fa ].join(", "); const text = sending ? "text-sky-700" : resting ? "text-violet-600" : warming ? "text-orange-600" : "text-slate-400"; return ( - + {sending && } {resting && } {warming && } {!sending && !resting && !warming && } - {label} - {label} + {stale && "Last observed: "}{label} + {stale && "Last observed: "}{label} ); } From b9223108394d45ea41b9b4edae6357c92d6ff435 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sun, 1 Nov 2026 12:38:41 +0100 Subject: [PATCH 062/318] feat: bind read-only TLS recovery state validation to reviewed file hashes and exact Terraform resource identities --- .github/scripts/runtime-tls-recovery.sh | 26 +++++++++++ .github/scripts/runtime-tls-recovery.test.sh | 45 ++++++++++++++++++++ 2 files changed, 71 insertions(+) diff --git a/.github/scripts/runtime-tls-recovery.sh b/.github/scripts/runtime-tls-recovery.sh index 028b3b9cf..af515e486 100755 --- a/.github/scripts/runtime-tls-recovery.sh +++ b/.github/scripts/runtime-tls-recovery.sh @@ -30,6 +30,31 @@ check_baseline() { ' "$1" >/dev/null || { echo 'Recovery requires four identified, drained HTTP groups matching reviewed state' >&2; return 1; } } +check_state() { + check_baseline "$2" + local digest + digest=$(sha256sum "$1" | cut -d' ' -f1) + [ "$digest" = "$(jq -r '.state.sha256' "$2")" ] || { echo 'Recovery state bytes differ from the reviewed hash' >&2; return 1; } + jq -e --slurpfile baseline "$2" ' + .version == 4 and .lineage == $baseline[0].state.lineage and .serial == $baseline[0].state.serial and + ([.resources[] | select(.mode == "managed" and .type == "aws_lb_target_group" and .name == "service")] as $resources | + [$resources[].instances[] | { + key:.index_key, deposed:.deposed, status:.status, + id:.attributes.id, TargetGroupArn:.attributes.arn, TargetGroupName:.attributes.name, + Protocol:.attributes.protocol, Port:.attributes.port, VpcId:.attributes.vpc_id + }] as $groups | + ($resources | length == 1) and + all($resources[]; (.module == null) and (.instances | type == "array" and length == 4)) and + ($groups | map(.key) | sort) == (["backend", "forms", "tracking", "realtime"] | sort) and + all($groups[]; + . as $group | .deposed == null and .status == null and .id == .TargetGroupArn and + any($baseline[0].state.httpGroups[]; + .TargetGroupName == ("warmbly-production-" + $group.key) and + .TargetGroupArn == $group.TargetGroupArn and .TargetGroupName == $group.TargetGroupName and + .Protocol == $group.Protocol and .Port == $group.Port and .VpcId == $group.VpcId))) + ' "$1" >/dev/null || { echo 'Recovery state identity differs from the reviewed baseline' >&2; return 1; } +} + check_plan() { check_baseline "$2" jq -e --slurpfile baseline "$2" ' @@ -58,6 +83,7 @@ check_plan() { case "${1:-}" in check-baseline) check_baseline "${2:?}" ;; + check-state) check_state "${2:?}" "${3:?}" ;; check-plan) check_plan "${2:?}" "${3:?}" ;; *) echo 'Only read-only recovery validation is supported' >&2; exit 1 ;; esac diff --git a/.github/scripts/runtime-tls-recovery.test.sh b/.github/scripts/runtime-tls-recovery.test.sh index 27ab22d55..a172b1e78 100755 --- a/.github/scripts/runtime-tls-recovery.test.sh +++ b/.github/scripts/runtime-tls-recovery.test.sh @@ -22,6 +22,51 @@ jq '.httpGroups |= reverse' "$work/baseline.json" >"$work/reordered-baseline.jso jq '.resource_changes |= reverse | .resource_changes += [{address:"data.aws_caller_identity.current",change:{actions:["read"]}}]' "$work/plan.json" >"$work/reordered-plan.json" bash "$guard" check-plan "$work/reordered-plan.json" "$work/reordered-baseline.json" +jq '{version:4,lineage:.state.lineage,serial:.state.serial,resources:[{ + mode:"managed",type:"aws_lb_target_group",name:"service",instances:[.state.httpGroups[] | { + index_key:(.TargetGroupName | ltrimstr("warmbly-production-")), + attributes:{arn:.TargetGroupArn,id:.TargetGroupArn,name:.TargetGroupName,protocol:.Protocol,port:.Port,vpc_id:.VpcId} + }] +}]}' "$work/baseline.json" >"$work/state.json" +digest=$(sha256sum "$work/state.json" | cut -d' ' -f1) +jq --arg digest "$digest" '.state.sha256=$digest' "$work/baseline.json" >"$work/state-baseline.json" +bash "$guard" check-state "$work/state.json" "$work/state-baseline.json" +jq -c . "$work/state.json" >"$work/reformatted-state.json" +if bash "$guard" check-state "$work/reformatted-state.json" "$work/state-baseline.json" 2>/dev/null; then + echo 'Recovery accepted changed state bytes under the original hash' >&2 + exit 1 +fi +jq '.resources[0].instances |= reverse | + .resources += [{mode:"managed",type:"aws_ecs_service",name:"service",instances:[]}]' \ + "$work/state.json" >"$work/reordered-state.json" +digest=$(sha256sum "$work/reordered-state.json" | cut -d' ' -f1) +jq --arg digest "$digest" '.state.sha256=$digest' "$work/baseline.json" >"$work/reordered-state-baseline.json" +bash "$guard" check-state "$work/reordered-state.json" "$work/reordered-state-baseline.json" +if bash "$guard" check-state "$work/state.json" "$work/baseline.json" 2>/dev/null; then + echo 'Recovery accepted state bytes with a different reviewed hash' >&2 + exit 1 +fi +for change in '.version=3' '.lineage="11111111-89ab-cdef-0123-456789abcdef"' '.serial+=1' \ + '.resources=[]' '.resources+=.resources' \ + '.resources[0].module="module.other"' '.resources[0].mode="data"' \ + '.resources[0].instances|=.[1:]' \ + '.resources[0].instances[0]=.resources[0].instances[1]' \ + '.resources[0].instances[0].index_key="other"' \ + '.resources[0].instances[0].deposed="old"' '.resources[0].instances[0].status="tainted"' \ + '.resources[0].instances[0].attributes.id="different"' \ + '.resources[0].instances[0].attributes.arn="different"' \ + '.resources[0].instances[0].attributes.name="different"' \ + '.resources[0].instances[0].attributes.protocol="HTTPS"' \ + '.resources[0].instances[0].attributes.port=465' \ + '.resources[0].instances[0].attributes.vpc_id="vpc-11111111"'; do + jq "$change" "$work/state.json" >"$work/changed-state.json" + digest=$(sha256sum "$work/changed-state.json" | cut -d' ' -f1) + jq --arg digest "$digest" '.state.sha256=$digest' "$work/baseline.json" >"$work/changed-state-baseline.json" + if bash "$guard" check-state "$work/changed-state.json" "$work/changed-state-baseline.json" 2>/dev/null; then + echo "Recovery accepted different state identities despite a matching file hash: $change" >&2 + exit 1 + fi +done for change in '.account="123456789012"' '.region="us-west-2"' \ '.httpGroups|=.[1:]' '.httpGroups[0]=.httpGroups[1]' \ '.httpGroups[0].LoadBalancerArns=["still-referenced"]' \ From 35a9cd8fe2b1f220c80025eab6989f7f24da0743 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sun, 1 Nov 2026 12:41:40 +0100 Subject: [PATCH 063/318] feat: isolate runtime TLS safety fixtures for early loopback and ON registration rejection checks --- .github/scripts/runtime-tls.test.sh | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/.github/scripts/runtime-tls.test.sh b/.github/scripts/runtime-tls.test.sh index 7b943a548..c538b2b06 100755 --- a/.github/scripts/runtime-tls.test.sh +++ b/.github/scripts/runtime-tls.test.sh @@ -40,7 +40,9 @@ jq -n '{resource_changes:[{address:"aws_ecs_service.service[\"forms\"]",change:{ after:{load_balancer:[{target_group_arn:"forms-tls/2",container_port:8443}]}}}]}' >"$work/plan.json" bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" drain for stage in route on; do - if bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" "$stage" 2>/dev/null; then + cp "$work/plan.json" "$work/registration-$stage.json" + if [ "$stage" = on ]; then complete_cleanup "$work/registration-$stage.json"; fi + if bash .github/scripts/runtime-tls.sh check-plan "$work/registration-$stage.json" "$stage" 2>/dev/null; then echo 'Registration detached outside the drain stage' >&2 exit 1 fi @@ -69,10 +71,11 @@ if bash .github/scripts/runtime-tls.sh check-plan "$work/changed.json" route 2>/ echo 'Network change accepted as metadata normalization' >&2 exit 1 fi -jq -n '{resource_changes:[{address:"aws_ecs_task_definition.service[\"backend\"]",change:{actions:["delete","create"],before:{container_definitions:([{image:"pinned",environment:[]}]|tojson)},after:{container_definitions:([{image:"pinned",environment:[{name:"SERVE_HTTP_LOOPBACK_ONLY",value:"true"}]}]|tojson)}}}]}' >"$work/plan.json" +jq -n '{resource_changes:[{address:"aws_ecs_task_definition.service[\"backend\"]",change:{actions:["delete","create"],before:{container_definitions:([{image:"pinned",environment:[]}]|tojson)},after:{container_definitions:([{image:"pinned",environment:[{name:"SERVE_HTTP_LOOPBACK_ONLY",value:"true"}]}]|tojson)}}}]}' >"$work/loopback-only.json" +cp "$work/loopback-only.json" "$work/plan.json" complete_cleanup "$work/plan.json" bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" on -if bash .github/scripts/runtime-tls.sh check-plan "$work/plan.json" route 2>/dev/null; then +if bash .github/scripts/runtime-tls.sh check-plan "$work/loopback-only.json" route 2>/dev/null; then echo 'Loopback-only listener accepted before HTTP registrations drained' >&2 exit 1 fi From c8cbdaf461ba6533621ded140c8d03eba78e059b Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sun, 1 Nov 2026 12:48:02 +0100 Subject: [PATCH 064/318] feat: collect exact workflow attempts and verify historical release ancestry for read-only TLS recovery evidence --- .../scripts/runtime-tls-recovery-lineage.sh | 81 +++++++++++++ .../runtime-tls-recovery-lineage.test.sh | 109 ++++++++++++++++++ .github/workflows/runtime-tls.yml | 2 + docs/content/docs/development/aws-fargate.mdx | 32 +++++ 4 files changed, 224 insertions(+) create mode 100644 .github/scripts/runtime-tls-recovery-lineage.sh create mode 100644 .github/scripts/runtime-tls-recovery-lineage.test.sh diff --git a/.github/scripts/runtime-tls-recovery-lineage.sh b/.github/scripts/runtime-tls-recovery-lineage.sh new file mode 100644 index 000000000..58276f7da --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-lineage.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +# Preserve historical workflow identities when collecting recovery evidence. +set -euo pipefail + +check_contract() { + jq -e ' + .schemaVersion == 1 and .repository == "warmbly/warmbly" and + all(.release, .drain, .failedOn; + (.tag | type == "string" and test("^v[0-9]+\\.[0-9]+\\.[0-9]+$")) and + (.source | type == "string" and test("^[a-f0-9]{40}$")) and + (.runId | type == "number" and . > 0 and floor == .) and + (.attempt | type == "number" and . > 0 and floor == .)) and + ([.release.runId, .drain.runId, .failedOn.runId] | unique | length == 3) and + .drain.tag == .failedOn.tag and .release.tag != .drain.tag + ' "$1" >/dev/null || { echo 'Recovery requires explicit current and historical workflow identities' >&2; return 1; } +} + +check_lineage() { + local evidence=$1 contract=$2 repository=$3 tag source + check_contract "$contract" + jq -e --slurpfile contract "$contract" ' + $contract[0] as $expected | + def run_matches($identity; $path; $event; $branch; $conclusion): + .id == $identity.runId and .run_attempt == $identity.attempt and + .head_sha == $identity.source and .repository.full_name == $expected.repository and + .path == $path and .event == $event and .head_branch == $branch and + .status == "completed" and .conclusion == $conclusion; + (.runs.release | run_matches($expected.release; ".github/workflows/release.yml"; "push"; $expected.release.tag; "success")) and + (.runs.drain | run_matches($expected.drain; ".github/workflows/runtime-tls.yml"; "workflow_dispatch"; "main"; "success") and + .display_title == ("Runtime TLS drain " + $expected.drain.tag)) and + (.runs.failedOn | run_matches($expected.failedOn; ".github/workflows/runtime-tls.yml"; "workflow_dispatch"; "main"; "failure") and + .display_title == ("Runtime TLS on " + $expected.failedOn.tag)) and + (.failedOnJobs | type == "array" and length > 0) and + ([.failedOnJobs[].id] | unique | length) == (.failedOnJobs | length) and + all(.failedOnJobs[]; + .run_id == $expected.failedOn.runId and .run_attempt == $expected.failedOn.attempt and + .status == "completed") and + ([.failedOnJobs[] | select(.name == "apply")] | length == 1) and + any(.failedOnJobs[]; .name == "apply" and .conclusion == "success") and + any(.failedOnJobs[]; (.name | startswith("redeploy / ")) and .conclusion == "failure") + ' "$evidence" >/dev/null || { echo 'Recovery workflow evidence differs from the reviewed lineage' >&2; return 1; } + tag=$(jq -r '.release.tag' "$contract") + source=$(git -C "$repository" rev-parse --verify "refs/tags/$tag^{commit}") + [ "$source" = "$(jq -r '.release.source' "$contract")" ] || { echo 'Recovery release tag differs from its reviewed source' >&2; return 1; } + git -C "$repository" merge-base --is-ancestor "$(jq -r '.drain.source' "$contract")" "$(jq -r '.failedOn.source' "$contract")" || { + echo 'Recovery ON source does not descend from the reviewed drain source' >&2; return 1; + } + git -C "$repository" merge-base --is-ancestor "$(jq -r '.failedOn.source' "$contract")" "$source" || { + echo 'Recovery release does not descend from the reviewed ON source' >&2; return 1; + } +} + +collect_lineage() { + local contract=$1 work=$2 repository=$3 repo identity run attempt + check_contract "$contract" + umask 077 + mkdir "$work" + repo=$(jq -r '.repository' "$contract") + for identity in release drain failedOn; do + run=$(jq -r --arg identity "$identity" '.[$identity].runId' "$contract") + attempt=$(jq -r --arg identity "$identity" '.[$identity].attempt' "$contract") + gh api "repos/$repo/actions/runs/$run/attempts/$attempt" >"$work/$identity.json" + done + run=$(jq -r '.failedOn.runId' "$contract") + attempt=$(jq -r '.failedOn.attempt' "$contract") + gh api "repos/$repo/actions/runs/$run/attempts/$attempt/jobs?per_page=100" --paginate --slurp >"$work/job-pages.json" + jq -e '.[0].total_count == ([.[].jobs[]] | length)' "$work/job-pages.json" >/dev/null || { + echo 'Recovery requires the complete failed ON job inventory' >&2; return 1; + } + jq -n --slurpfile release "$work/release.json" --slurpfile drain "$work/drain.json" \ + --slurpfile failedOn "$work/failedOn.json" --slurpfile jobs "$work/job-pages.json" \ + '{runs:{release:$release[0],drain:$drain[0],failedOn:$failedOn[0]},failedOnJobs:[$jobs[0][].jobs[]]}' >"$work/candidate.json" + check_lineage "$work/candidate.json" "$contract" "$repository" + mv "$work/candidate.json" "$work/lineage.json" +} + +case "${1:-}" in + check) check_lineage "${2:?}" "${3:?}" "${4:?}" ;; + collect) collect_lineage "${2:?}" "${3:?}" "${4:?}" ;; + *) echo 'Only read-only recovery lineage check and collection are supported' >&2; exit 1 ;; +esac diff --git a/.github/scripts/runtime-tls-recovery-lineage.test.sh b/.github/scripts/runtime-tls-recovery-lineage.test.sh new file mode 100644 index 000000000..7974d4e0b --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-lineage.test.sh @@ -0,0 +1,109 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/../.." +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +guard=.github/scripts/runtime-tls-recovery-lineage.sh +mkdir "$work/repository" +git -C "$work/repository" init -q +git -C "$work/repository" config user.name 'Recovery fixture' +git -C "$work/repository" config user.email 'fixture@example.invalid' +git -C "$work/repository" commit -qm 'feat: establish drain fixture' --allow-empty +drain=$(git -C "$work/repository" rev-parse HEAD) +git -C "$work/repository" commit -qm 'feat: establish ON fixture' --allow-empty +on=$(git -C "$work/repository" rev-parse HEAD) +git -C "$work/repository" commit -qm 'feat: establish release fixture' --allow-empty +release=$(git -C "$work/repository" rev-parse HEAD) +git -C "$work/repository" tag v1.0.1 +jq -n --arg drain "$drain" --arg on "$on" --arg release "$release" ' + {schemaVersion:1,repository:"warmbly/warmbly", + release:{tag:"v1.0.1",source:$release,runId:101,attempt:1}, + drain:{tag:"v1.0.0",source:$drain,runId:102,attempt:1}, + failedOn:{tag:"v1.0.0",source:$on,runId:103,attempt:1}} +' >"$work/contract.json" +jq ' + def run($path; $event; $branch; $conclusion): + {id:.runId,run_attempt:.attempt,head_sha:.source,repository:{full_name:"warmbly/warmbly"}, + path:$path,event:$event,head_branch:$branch,status:"completed",conclusion:$conclusion}; + {runs:{ + release:(.release | run(".github/workflows/release.yml";"push";.tag;"success")), + drain:(.drain | run(".github/workflows/runtime-tls.yml";"workflow_dispatch";"main";"success") + {display_title:("Runtime TLS drain " + .tag)}), + failedOn:(.failedOn | run(".github/workflows/runtime-tls.yml";"workflow_dispatch";"main";"failure") + {display_title:("Runtime TLS on " + .tag)})}, + failedOnJobs:[{id:1,run_id:103,run_attempt:1,status:"completed",name:"apply",conclusion:"success"}, + {id:2,run_id:103,run_attempt:1,status:"completed",name:"redeploy / redeploy v1.0.0",conclusion:"failure"}]} +' "$work/contract.json" >"$work/evidence.json" +bash "$guard" check "$work/evidence.json" "$work/contract.json" "$work/repository" +for change in '.schemaVersion=2' '.repository="other/repo"' '.release.runId=.drain.runId' \ + '.drain.tag=.release.tag' '.failedOn.tag="v0.9.0"' '.release.tag="main"' \ + '.failedOn.attempt=0' '.drain.source="unknown"'; do + jq "$change" "$work/contract.json" >"$work/changed.json" + if bash "$guard" check "$work/evidence.json" "$work/changed.json" "$work/repository" 2>/dev/null; then + echo "Recovery accepted a different lineage contract: $change" >&2; exit 1 + fi +done +for change in '.runs.release.id=104' '.runs.release.head_sha=.runs.drain.head_sha' \ + '.runs.release.repository.full_name="other/repo"' '.runs.release.head_branch="main"' \ + '.runs.release.path=".github/workflows/deploy-aws.yml"' '.runs.release.conclusion="failure"' \ + '.runs.release.event="workflow_dispatch"' '.runs.release.status="in_progress"' \ + '.runs.drain.run_attempt=2' '.runs.drain.conclusion="failure"' \ + '.runs.drain.display_title="Runtime TLS drain v1.0.1"' \ + '.runs.failedOn.display_title="Runtime TLS on v1.0.1"' '.runs.failedOn.conclusion="success"' \ + '.failedOnJobs=[]' '.failedOnJobs += [.failedOnJobs[0]]' '.failedOnJobs[0].conclusion="failure"' \ + '.failedOnJobs[1].conclusion="success"' '.failedOnJobs[0].run_id=104' \ + '.failedOnJobs[0].run_attempt=2' '.failedOnJobs[1].status="in_progress"'; do + jq "$change" "$work/evidence.json" >"$work/changed.json" + if bash "$guard" check "$work/changed.json" "$work/contract.json" "$work/repository" 2>/dev/null; then + echo "Recovery accepted different workflow evidence: $change" >&2; exit 1 + fi +done +git -C "$work/repository" tag -f v1.0.1 "$drain" >/dev/null +if bash "$guard" check "$work/evidence.json" "$work/contract.json" "$work/repository" 2>/dev/null; then + echo 'Recovery accepted a release tag on a different source' >&2; exit 1 +fi +git -C "$work/repository" tag -f v1.0.1 "$release" >/dev/null +jq --arg source "$release" '.drain.source=$source' "$work/contract.json" >"$work/reversed-contract.json" +jq --arg source "$release" '.runs.drain.head_sha=$source' "$work/evidence.json" >"$work/reversed-evidence.json" +if bash "$guard" check "$work/reversed-evidence.json" "$work/reversed-contract.json" "$work/repository" 2>/dev/null; then + echo 'Recovery accepted reversed drain and ON ancestry' >&2; exit 1 +fi +jq --arg source "$drain" '.release.source=$source' "$work/contract.json" >"$work/reversed-contract.json" +jq --arg source "$drain" '.runs.release.head_sha=$source' "$work/evidence.json" >"$work/reversed-evidence.json" +git -C "$work/repository" tag -f v1.0.1 "$drain" >/dev/null +if bash "$guard" check "$work/reversed-evidence.json" "$work/reversed-contract.json" "$work/repository" 2>/dev/null; then + echo 'Recovery accepted a release that predates the ON source' >&2; exit 1 +fi +git -C "$work/repository" tag -f v1.0.1 "$release" >/dev/null +mkdir "$work/bin" +cat >"$work/bin/gh" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +printf '%s\n' "$*" >>"$FIXTURES/requests.log" +[ "${API_FAIL:-false}" = false ] || exit 1 +case "$2" in + */runs/101/attempts/1) jq '.runs.release' "$FIXTURES/evidence.json" ;; + */runs/102/attempts/1) jq '.runs.drain' "$FIXTURES/evidence.json" ;; + */runs/103/attempts/1) jq '.runs.failedOn' "$FIXTURES/evidence.json" ;; + */runs/103/attempts/1/jobs\?per_page=100) + [ "$3 $4" = '--paginate --slurp' ] + jq --arg mode "${JOB_MODE:-complete}" '[{total_count:2,jobs:(if $mode == "partial" then .failedOnJobs[:1] else .failedOnJobs end)}]' "$FIXTURES/evidence.json" ;; + *) exit 1 ;; +esac +SH +chmod +x "$work/bin/gh" +PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/contract.json" "$work/collected" "$work/repository" +cmp "$work/evidence.json" "$work/collected/lineage.json" +if PATH="$work/bin:$PATH" FIXTURES="$work" JOB_MODE=partial bash "$guard" collect "$work/contract.json" "$work/partial" "$work/repository" 2>/dev/null; then + echo 'Recovery accepted an incomplete job collection' >&2; exit 1 +fi +[ ! -e "$work/partial/lineage.json" ] +if PATH="$work/bin:$PATH" FIXTURES="$work" API_FAIL=true bash "$guard" collect "$work/contract.json" "$work/api-failure" "$work/repository" 2>/dev/null; then + echo 'Recovery accepted a failed GitHub API read' >&2; exit 1 +fi +[ ! -e "$work/api-failure/lineage.json" ] +if PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/contract.json" "$work/collected" "$work/repository" 2>/dev/null; then + echo 'Recovery overwrote an existing lineage collection' >&2; exit 1 +fi +if bash "$guard" apply 2>/dev/null; then + echo 'Recovery lineage collector accepted an execution action' >&2; exit 1 +fi +echo 'Read-only recovery workflow lineage collection and checks passed' diff --git a/.github/workflows/runtime-tls.yml b/.github/workflows/runtime-tls.yml index 0606b67ac..9289782f8 100644 --- a/.github/workflows/runtime-tls.yml +++ b/.github/workflows/runtime-tls.yml @@ -46,6 +46,8 @@ jobs: - run: bash .github/scripts/runtime-tls.test.sh - run: shellcheck .github/scripts/runtime-tls-recovery.sh .github/scripts/runtime-tls-recovery.test.sh - run: bash .github/scripts/runtime-tls-recovery.test.sh + - run: shellcheck .github/scripts/runtime-tls-recovery-lineage.sh .github/scripts/runtime-tls-recovery-lineage.test.sh + - run: bash .github/scripts/runtime-tls-recovery-lineage.test.sh plan: needs: check diff --git a/docs/content/docs/development/aws-fargate.mdx b/docs/content/docs/development/aws-fargate.mdx index fac16624e..967d1dac9 100644 --- a/docs/content/docs/development/aws-fargate.mdx +++ b/docs/content/docs/development/aws-fargate.mdx @@ -447,6 +447,38 @@ HTTP references and registrations have drained. Review and approve each plan separately. Persist `target_tls=on` only after it succeeds, then verify the effective loopback listeners and HTTPS routes. +### Validate recovery evidence + +The read-only recovery validators keep a recovery contract separate from the +normal route, drain and on transition checks. They do not provide a production +recovery execution workflow. The baseline identifies four drained HTTP groups +and their reviewed state projection. `check-state` verifies a supplied raw +Terraform state file against the baseline SHA-256, lineage, serial and exact +group identities. `check-plan` permits only the four corresponding deletions +without refresh drift. The baseline and state version must come from a trusted, +reviewed collection process; matching a file hash alone does not establish that +provenance. + +`runtime-tls-recovery-lineage.sh` collects and checks the GitHub portion of a +recovery contract. Its version 1 contract names `warmbly/warmbly` and three +identities, `release`, `drain` and `failedOn`, each with a stable release `tag`, +40-character commit `source`, numeric `runId` and numeric `attempt`. The current +release is distinct from the historical release retained by both TLS runs. +Collection reads the exact run attempts and the complete failed ON job inventory. +It requires the current release and historical drain to have succeeded, the ON +apply to have succeeded before a failed redeploy, and each workflow path, branch, +title and source to match its declared role. The local checkout must include the +release tag and full commit history so the checker can verify the tag and +drain-to-ON-to-release ancestry. Collection writes a new private directory and +refuses to overwrite a prior collection. + +These checks neither relabel an earlier release's drain nor change the normal +workflow's predecessor requirements. A complete recovery workflow must also +collect current service, TLS, route and target health, bind the immutable vars +snapshot and state version, and preserve separate protected approval, production +serialization, plan digest comparison, attested redeployment and final effective +verification. Do not use these validators as an alternative to those gates. + ## One-time GitHub setup 1. On the `aws-production` environment, allow the `v*.*.*` tag pattern next to From 8a0a85d3a901f5a734bf59fad267d390f2c50588 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sun, 1 Nov 2026 12:58:42 +0100 Subject: [PATCH 065/318] feat: collect reviewed private TLS recovery state and cleanup vars with exact S3 version and hash binding --- .../scripts/runtime-tls-recovery-inputs.sh | 63 ++++++++++ .../runtime-tls-recovery-inputs.test.sh | 114 ++++++++++++++++++ .github/workflows/runtime-tls.yml | 2 + docs/content/docs/development/aws-fargate.mdx | 14 +++ 4 files changed, 193 insertions(+) create mode 100644 .github/scripts/runtime-tls-recovery-inputs.sh create mode 100644 .github/scripts/runtime-tls-recovery-inputs.test.sh diff --git a/.github/scripts/runtime-tls-recovery-inputs.sh b/.github/scripts/runtime-tls-recovery-inputs.sh new file mode 100644 index 000000000..2c4364a34 --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-inputs.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# Bind private recovery inputs to their reviewed S3 versions and file hashes. +set -euo pipefail +guard="$(dirname "$0")/runtime-tls-recovery.sh" + +check_contract() { + bash "$guard" check-baseline "$1" + jq -e ' + .bucket == "warmbly-terraform-use1-925323749693" and + .state.key == "warmbly/production/runtime.tfstate" and + (.snapshot.key | type == "string" and test("^warmbly/production/vars/runtime-tls-recovery/[a-z0-9][a-z0-9-]{1,63}\\.tfvars\\.json$")) and + (.snapshot.versionId | type == "string" and length > 0 and . != "null" and (test("[\\r\\n]") | not)) and + (.snapshot.sha256 | type == "string" and test("^[a-f0-9]{64}$")) and + (.snapshot.releaseTag | type == "string" and test("^v[0-9]+\\.[0-9]+\\.[0-9]+$")) + ' "$1" >/dev/null || { echo 'Recovery requires separately versioned private state and cleanup inputs' >&2; return 1; } +} + +collect_inputs() { + local baseline=$1 work=$2 bucket key version digest kind + check_contract "$baseline" + umask 077 + mkdir "$work" + cp "$baseline" "$work/baseline.json" + baseline="$work/baseline.json" + bucket=$(jq -r '.bucket' "$baseline") + aws sts get-caller-identity --region us-east-1 >"$work/identity.json" + jq -e '.Account == "925323749693"' "$work/identity.json" >/dev/null || { + echo 'Recovery input collection requires the reviewed AWS account' >&2; return 1; + } + for kind in state snapshot; do + key=$(jq -r --arg kind "$kind" '.[$kind].key' "$baseline") + version=$(jq -r --arg kind "$kind" '.[$kind].versionId' "$baseline") + aws s3api get-object --region us-east-1 --bucket "$bucket" --key "$key" \ + --version-id "$version" --expected-bucket-owner 925323749693 "$work/$kind.json" >"$work/$kind-metadata.json" + jq -e --arg version "$version" ' + .VersionId == $version and .DeleteMarker != true and + (.ServerSideEncryption == "AES256" or .ServerSideEncryption == "aws:kms") + ' "$work/$kind-metadata.json" >/dev/null || { + echo 'Recovery object metadata differs from the reviewed version' >&2; return 1; + } + digest=$(sha256sum "$work/$kind.json" | cut -d' ' -f1) + [ "$digest" = "$(jq -r --arg kind "$kind" '.[$kind].sha256' "$baseline")" ] || { + echo 'Recovery object bytes differ from the reviewed hash' >&2; return 1; + } + done + bash "$guard" check-state "$work/state.json" "$baseline" + jq -e '.target_tls == "on" and .name == "warmbly-production"' "$work/snapshot.json" >/dev/null || { + echo 'Recovery vars must select the reviewed production cleanup stage' >&2; return 1; + } + aws s3api head-object --region us-east-1 --bucket "$bucket" --key warmbly/production/runtime.tfstate \ + --expected-bucket-owner 925323749693 >"$work/latest-state.json" + jq -e --slurpfile baseline "$baseline" '.VersionId == $baseline[0].state.versionId' "$work/latest-state.json" >/dev/null || { + echo 'Recovery state advanced beyond the reviewed version' >&2; return 1; + } + jq '{account,region,bucket,state:{key:.state.key,versionId:.state.versionId,sha256:.state.sha256,lineage:.state.lineage,serial:.state.serial},snapshot}' \ + "$baseline" >"$work/inputs.json" +} + +case "${1:-}" in + check-contract) check_contract "${2:?}" ;; + collect) collect_inputs "${2:?}" "${3:?}" ;; + *) echo 'Only read-only recovery input validation and collection are supported' >&2; exit 1 ;; +esac diff --git a/.github/scripts/runtime-tls-recovery-inputs.test.sh b/.github/scripts/runtime-tls-recovery-inputs.test.sh new file mode 100644 index 000000000..b4942bfb3 --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-inputs.test.sh @@ -0,0 +1,114 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/../.." +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +guard=.github/scripts/runtime-tls-recovery-inputs.sh +jq -n ' + ["backend","forms","tracking","realtime"] | map({ + TargetGroupName:("warmbly-production-" + .), + TargetGroupArn:("arn:aws:elasticloadbalancing:us-east-1:925323749693:targetgroup/warmbly-production-" + . + "/0123456789abcdef"), + Protocol:"HTTP",Port:8080,VpcId:"vpc-0123456789abcdef0",LoadBalancerArns:[],targets:[]}) as $groups | + {account:"925323749693",region:"us-east-1",bucket:"warmbly-terraform-use1-925323749693",httpGroups:$groups, + state:{key:"warmbly/production/runtime.tfstate",versionId:"reviewed-state",lineage:"01234567-89ab-cdef-0123-456789abcdef",serial:1,httpGroups:$groups}, + snapshot:{key:"warmbly/production/vars/runtime-tls-recovery/reviewed-cleanup.tfvars.json",versionId:"reviewed-vars",releaseTag:"v1.0.1"}} +' >"$work/baseline.json" +jq '{version:4,lineage:.state.lineage,serial:.state.serial,resources:[{mode:"managed",type:"aws_lb_target_group",name:"service", + instances:[.httpGroups[] | {index_key:(.TargetGroupName | ltrimstr("warmbly-production-")),attributes:{ + id:.TargetGroupArn,arn:.TargetGroupArn,name:.TargetGroupName,protocol:.Protocol,port:.Port,vpc_id:.VpcId}}]}]}' \ + "$work/baseline.json" >"$work/state.json" +printf '%s\n' '{"name":"warmbly-production","target_tls":"on"}' >"$work/snapshot.json" +state_digest=$(sha256sum "$work/state.json" | cut -d' ' -f1) +vars_digest=$(sha256sum "$work/snapshot.json" | cut -d' ' -f1) +jq --arg state "$state_digest" --arg vars "$vars_digest" '.state.sha256=$state | .snapshot.sha256=$vars' \ + "$work/baseline.json" >"$work/reviewed.json" +bash "$guard" check-contract "$work/reviewed.json" +for change in '.bucket="other-bucket"' '.state.key="other/state"' \ + '.snapshot.key="warmbly/production/vars/runtime-tls.tfvars.json"' \ + '.snapshot.key="warmbly/production/vars/runtime-tls-recovery/../default.tfvars.json"' \ + '.snapshot.versionId="null"' '.snapshot.sha256=""' '.snapshot.releaseTag="main"'; do + jq "$change" "$work/reviewed.json" >"$work/changed.json" + if bash "$guard" check-contract "$work/changed.json" 2>/dev/null; then + echo "Recovery accepted an unbound input contract: $change" >&2; exit 1 + fi +done +mkdir "$work/bin" +cat >"$work/bin/aws" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +printf '%s\n' "$*" >>"$FIXTURES/requests.log" +service=$1 operation=$2 +shift 2 +bucket= key= version= owner= region= output= +while [ "$#" -gt 0 ]; do + case "$1" in + --bucket) bucket=$2; shift 2 ;; + --key) key=$2; shift 2 ;; + --version-id) version=$2; shift 2 ;; + --expected-bucket-owner) owner=$2; shift 2 ;; + --region) region=$2; shift 2 ;; + *) output=$1; shift ;; + esac +done +[ "$region" = us-east-1 ] +case "$service $operation" in + 'sts get-caller-identity') + if [ "${MODE:-}" = account ]; then echo '{"Account":"123456789012"}'; else echo '{"Account":"925323749693"}'; fi ;; + 's3api get-object') + [ "$bucket" = warmbly-terraform-use1-925323749693 ] && [ "$owner" = 925323749693 ] + case "$key $version" in + 'warmbly/production/runtime.tfstate reviewed-state') kind=state ;; + 'warmbly/production/vars/runtime-tls-recovery/reviewed-cleanup.tfvars.json reviewed-vars') kind=snapshot ;; + *) exit 1 ;; + esac + [ "${MODE:-}" != api-failure ] || exit 1 + cp "$FIXTURES/$kind.json" "$output" + if [ "${MODE:-}" = hash ]; then printf '\n' >>"$output"; fi + if [ "${MODE:-}" = version ]; then version=other-version; fi + encryption=AES256 + if [ "${MODE:-}" = kms ]; then encryption=aws:kms; fi + if [ "${MODE:-}" = encryption ]; then encryption=none; fi + jq -n --arg version "$version" --arg encryption "$encryption" --arg mode "${MODE:-}" \ + '{VersionId:$version,ServerSideEncryption:$encryption,DeleteMarker:($mode=="deleted")}' ;; + 's3api head-object') + [ "$bucket" = warmbly-terraform-use1-925323749693 ] && [ "$owner" = 925323749693 ] + [ "$key" = warmbly/production/runtime.tfstate ] + version=reviewed-state + if [ "${MODE:-}" = advanced ]; then version=advanced-state; fi + jq -n --arg version "$version" '{VersionId:$version}' ;; + *) echo 'Unexpected AWS operation' >&2; exit 1 ;; +esac +SH +chmod +x "$work/bin/aws" +PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/reviewed.json" "$work/collected" +jq -e --arg state "$state_digest" --arg vars "$vars_digest" '.state.sha256==$state and .snapshot.sha256==$vars' "$work/collected/inputs.json" >/dev/null +PATH="$work/bin:$PATH" FIXTURES="$work" MODE=kms bash "$guard" collect "$work/reviewed.json" "$work/kms" +for mode in account api-failure hash version encryption deleted advanced; do + if PATH="$work/bin:$PATH" FIXTURES="$work" MODE=$mode bash "$guard" collect "$work/reviewed.json" "$work/$mode" 2>/dev/null; then + echo "Recovery accepted incompatible collected inputs: $mode" >&2; exit 1 + fi + [ ! -e "$work/$mode/inputs.json" ] +done +if PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/reviewed.json" "$work/collected" 2>/dev/null; then + echo 'Recovery overwrote an existing input collection' >&2; exit 1 +fi +printf '%s\n' '{"name":"other-deployment","target_tls":"on"}' >"$work/snapshot.json" +digest=$(sha256sum "$work/snapshot.json" | cut -d' ' -f1) +jq --arg digest "$digest" '.snapshot.sha256=$digest' "$work/reviewed.json" >"$work/changed.json" +if PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/changed.json" "$work/wrong-deployment" 2>/dev/null; then + echo 'Recovery accepted vars for a different deployment' >&2; exit 1 +fi +for stage in drain route; do + printf '%s\n' '{"name":"warmbly-production","target_tls":"on"}' >"$work/snapshot.json" + jq --arg stage "$stage" '.target_tls=$stage' "$work/snapshot.json" >"$work/changed-vars.json" + cp "$work/changed-vars.json" "$work/snapshot.json" + digest=$(sha256sum "$work/snapshot.json" | cut -d' ' -f1) + jq --arg digest "$digest" '.snapshot.sha256=$digest' "$work/reviewed.json" >"$work/changed.json" + if PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/changed.json" "$work/$stage" 2>/dev/null; then + echo 'Recovery accepted vars for a different transition stage' >&2; exit 1 + fi +done +if bash "$guard" apply 2>/dev/null; then + echo 'Recovery input collector accepted an execution action' >&2; exit 1 +fi +echo 'Read-only recovery S3 input collection and checks passed' diff --git a/.github/workflows/runtime-tls.yml b/.github/workflows/runtime-tls.yml index 9289782f8..100154fbc 100644 --- a/.github/workflows/runtime-tls.yml +++ b/.github/workflows/runtime-tls.yml @@ -48,6 +48,8 @@ jobs: - run: bash .github/scripts/runtime-tls-recovery.test.sh - run: shellcheck .github/scripts/runtime-tls-recovery-lineage.sh .github/scripts/runtime-tls-recovery-lineage.test.sh - run: bash .github/scripts/runtime-tls-recovery-lineage.test.sh + - run: shellcheck .github/scripts/runtime-tls-recovery-inputs.sh .github/scripts/runtime-tls-recovery-inputs.test.sh + - run: bash .github/scripts/runtime-tls-recovery-inputs.test.sh plan: needs: check diff --git a/docs/content/docs/development/aws-fargate.mdx b/docs/content/docs/development/aws-fargate.mdx index 967d1dac9..8b971aa1f 100644 --- a/docs/content/docs/development/aws-fargate.mdx +++ b/docs/content/docs/development/aws-fargate.mdx @@ -472,6 +472,20 @@ release tag and full commit history so the checker can verify the tag and drain-to-ON-to-release ancestry. Collection writes a new private directory and refuses to overwrite a prior collection. +`runtime-tls-recovery-inputs.sh` collects the private S3 inputs using only STS +identity and S3 get/head operations. The baseline names the production `bucket`, +the state `key`, version and hash, and a `snapshot` with its `key`, `versionId`, +`sha256` and declared `releaseTag`. The cleanup vars use a new key under +`warmbly/production/vars/runtime-tls-recovery/`, separate from the normal stage +snapshot. Collection requires the expected account and bucket owner, exact +version metadata, server-side encryption and matching file hashes. It validates +the raw state identities and requires the latest state version to remain the +reviewed one. The vars must name `warmbly-production` and `target_tls=on`. +The resulting private directory contains raw state and vars and must remain +private. Its `inputs.json` binds the selected versions and hashes; it does not +establish that the declared release matches the live services or that those +services are healthy. + These checks neither relabel an earlier release's drain nor change the normal workflow's predecessor requirements. A complete recovery workflow must also collect current service, TLS, route and target health, bind the immutable vars From 488445634484470b49991d30de447e60cab4f4b2 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sun, 1 Nov 2026 13:29:07 +0100 Subject: [PATCH 066/318] feat: gate partial TLS cleanup on reviewed live evidence and protected same-release recovery --- .../scripts/runtime-tls-recovery-archive.sh | 23 ++ .../runtime-tls-recovery-archive.test.sh | 37 ++++ .../scripts/runtime-tls-recovery-execute.sh | 130 ++++++++++++ .../runtime-tls-recovery-execute.test.sh | 166 +++++++++++++++ .../scripts/runtime-tls-recovery-inputs.sh | 15 +- .../runtime-tls-recovery-inputs.test.sh | 3 + .../runtime-tls-recovery-live.fixture.jq | 56 +++++ .github/scripts/runtime-tls-recovery-live.jq | 131 ++++++++++++ .github/scripts/runtime-tls-recovery-live.sh | 96 +++++++++ .../scripts/runtime-tls-recovery-live.test.sh | 137 ++++++++++++ .../runtime-tls-recovery-workflow.test.sh | 31 +++ .github/workflows/deploy-aws.yml | 4 + .github/workflows/runtime-tls-recovery.yml | 199 ++++++++++++++++++ docs/content/docs/development/aws-fargate.mdx | 101 ++++++++- 14 files changed, 1114 insertions(+), 15 deletions(-) create mode 100755 .github/scripts/runtime-tls-recovery-archive.sh create mode 100755 .github/scripts/runtime-tls-recovery-archive.test.sh create mode 100755 .github/scripts/runtime-tls-recovery-execute.sh create mode 100755 .github/scripts/runtime-tls-recovery-execute.test.sh create mode 100644 .github/scripts/runtime-tls-recovery-live.fixture.jq create mode 100644 .github/scripts/runtime-tls-recovery-live.jq create mode 100755 .github/scripts/runtime-tls-recovery-live.sh create mode 100755 .github/scripts/runtime-tls-recovery-live.test.sh create mode 100755 .github/scripts/runtime-tls-recovery-workflow.test.sh create mode 100644 .github/workflows/runtime-tls-recovery.yml diff --git a/.github/scripts/runtime-tls-recovery-archive.sh b/.github/scripts/runtime-tls-recovery-archive.sh new file mode 100755 index 000000000..ed233c2fb --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-archive.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# Preserve recovery raw evidence only in the dedicated private diagnostic prefix. +set -euo pipefail +[ "${GITHUB_ACTIONS:-}" = true ] && [ "${GITHUB_REPOSITORY:-}" = warmbly/warmbly ] && + [ "${GITHUB_REF:-}" = refs/heads/main ] && [ "${GITHUB_RUN_ATTEMPT:-}" = 1 ] && + [[ "${GITHUB_RUN_ID:-}" =~ ^[1-9][0-9]*$ ]] || exit 1 +phase=${1:?} +[[ "$phase" = plan || "$phase" = apply || "$phase" = verify ]] +: "${WORK:?}" +[ -d "$WORK" ] && [ ! -e "$WORK.evidence.tgz" ] +umask 077 +aws sts get-caller-identity --region us-east-1 >"$WORK/archive-identity.json" +jq -e '.Account == "925323749693" and (.Arn | test("^arn:aws:sts::925323749693:assumed-role/warmbly-production-tls-recovery-evidence/[^/]+$"))' \ + "$WORK/archive-identity.json" >/dev/null +tar -czf "$WORK.evidence.tgz" -C "$WORK" . +checksum=$(openssl dgst -sha256 -binary "$WORK.evidence.tgz" | openssl base64 -A) +aws s3api put-object --region us-east-1 --bucket warmbly-terraform-use1-925323749693 \ + --key "warmbly/production/diagnostics/runtime-tls-recovery/$GITHUB_RUN_ID/1/$phase.tgz" \ + --expected-bucket-owner 925323749693 --server-side-encryption AES256 --if-none-match '*' \ + --checksum-algorithm SHA256 --checksum-sha256 "$checksum" --body "$WORK.evidence.tgz" >"$WORK.evidence-metadata.json" +jq -e --arg checksum "$checksum" '.ServerSideEncryption == "AES256" and .ChecksumSHA256 == $checksum and + (.VersionId | type == "string" and length > 0 and . != "null")' "$WORK.evidence-metadata.json" >/dev/null +echo 'Full recovery evidence preserved in the private versioned diagnostic object' diff --git a/.github/scripts/runtime-tls-recovery-archive.test.sh b/.github/scripts/runtime-tls-recovery-archive.test.sh new file mode 100755 index 000000000..a4a1ad70d --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-archive.test.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/../.." +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +mkdir "$work/bin" +cat >"$work/bin/aws" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +if [ "$1 $2" = 'sts get-caller-identity' ]; then + jq -n --arg mode "${MODE:-}" '{Account:"925323749693",Arn:("arn:aws:sts::925323749693:assumed-role/"+(if $mode=="role" then "other" else "warmbly-production-tls-recovery-evidence" end)+"/fixture")}' + exit +fi +[ "$1 $2" = 's3api put-object' ] +[[ "$*" == *'--expected-bucket-owner 925323749693'* && "$*" == *'--server-side-encryption AES256'* && "$*" == *'--if-none-match *'* ]] +[[ "$*" == *'warmbly/production/diagnostics/runtime-tls-recovery/999/1/plan.tgz'* ]] +checksum= body= +while [ "$#" -gt 0 ]; do + case "$1" in --checksum-sha256) checksum=$2; shift 2 ;; --body) body=$2; shift 2 ;; *) shift ;; esac +done +[ "$checksum" = "$(openssl dgst -sha256 -binary "$body" | openssl base64 -A)" ] +tar -tzf "$body" | rg -q '^./full-raw.json$' +if [ "${MODE:-}" = upload ]; then exit 1; fi +jq -n --arg checksum "$checksum" --arg mode "${MODE:-}" '{VersionId:"evidence-version",ServerSideEncryption:"AES256",ChecksumSHA256:(if $mode=="checksum" then "other" else $checksum end)}' +SH +chmod +x "$work/bin/aws" +export PATH="$work/bin:$PATH" GITHUB_ACTIONS=true GITHUB_REPOSITORY=warmbly/warmbly GITHUB_REF=refs/heads/main GITHUB_RUN_ATTEMPT=1 GITHUB_RUN_ID=999 +guard=.github/scripts/runtime-tls-recovery-archive.sh +for mode in good role upload checksum; do + mkdir "$work/$mode" + printf '{"raw":"private fixture"}\n' >"$work/$mode/full-raw.json" + if [ "$mode" = good ]; then WORK="$work/$mode" bash "$guard" plan + elif WORK="$work/$mode" MODE=$mode bash "$guard" plan 2>/dev/null; then echo "Archive accepted $mode" >&2; exit 1; fi +done +if WORK="$work/good" bash "$guard" plan 2>/dev/null; then echo 'Archive overwrote prior evidence' >&2; exit 1; fi +if WORK="$work/unused" GITHUB_RUN_ATTEMPT=2 bash "$guard" plan 2>/dev/null; then echo 'Archive accepted a rerun' >&2; exit 1; fi +echo 'Private evidence archive identity, prefix, encryption, integrity and overwrite checks passed' diff --git a/.github/scripts/runtime-tls-recovery-execute.sh b/.github/scripts/runtime-tls-recovery-execute.sh new file mode 100755 index 000000000..91cead7ec --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-execute.sh @@ -0,0 +1,130 @@ +#!/usr/bin/env bash +# Keep partial cleanup separate from normal route, drain and ON transitions. +set -euo pipefail +scripts=$(cd "$(dirname "$0")" && pwd) + +check_contract() { + bash "$scripts/runtime-tls-recovery-inputs.sh" check-contract "$1" + jq -e ' + .schemaVersion == 1 and .repository == "warmbly/warmbly" and .release.tag == .snapshot.releaseTag and + (.release.imagesSha256 | type == "string" and test("^[a-f0-9]{64}$")) and + (.planChangesSha256 | type == "string" and test("^[a-f0-9]{64}$")) + ' "$1" >/dev/null || { echo 'Recovery must bind the current release artifact and reviewed complete plan changes' >&2; return 1; } +} + +check_context() { + [ "${GITHUB_ACTIONS:-}" = true ] && [ "${GITHUB_REPOSITORY:-}" = warmbly/warmbly ] && + [ "${GITHUB_REF:-}" = refs/heads/main ] && [ "${GITHUB_EVENT_NAME:-}" = workflow_dispatch ] && + [ "${GITHUB_WORKFLOW_REF:-}" = warmbly/warmbly/.github/workflows/runtime-tls-recovery.yml@refs/heads/main ] && + [ "${GITHUB_RUN_ATTEMPT:-}" = 1 ] && [[ "${GITHUB_RUN_ID:-}" =~ ^[1-9][0-9]*$ ]] || { + echo 'Recovery execution requires a new protected main workflow run; reruns are refused' >&2; return 1; + } + [ "${GITHUB_SHA:?}" = "$(git rev-parse HEAD)" ] +} + +check_approval_environment() { + gh api repos/warmbly/warmbly/environments/aws-infrastructure-approval | + jq -e '.can_admins_bypass == false and + any(.protection_rules[]; .type == "required_reviewers" and .prevent_self_review == true and (.reviewers | length > 0))' >/dev/null || { + echo 'Recovery requires a separate protected reviewer without self-review or administrator bypass' >&2; return 1; + } +} + +check_final_state() { + jq -e --slurpfile before "$2" ' + .version == 4 and .lineage == $before[0].lineage and + (.serial | type == "number" and floor == .) and .serial > $before[0].serial and + ([.resources[] | select(.mode == "managed" and .type == "aws_lb_target_group" and .name == "service")] | length == 0) and + (.resources | sort_by([.module,.mode,.type,.name])) == + ($before[0].resources | map(select((.mode == "managed" and .type == "aws_lb_target_group" and .name == "service") | not)) | sort_by([.module,.mode,.type,.name])) + ' "$1" >/dev/null || { echo 'Post-cleanup state must preserve all other reviewed resources' >&2; return 1; } +} + +prepare() { + : "${WORK:?}" "${CONTRACT_KEY:?}" "${CONTRACT_VERSION:?}" "${CONTRACT_SHA256:?}" + [[ "$CONTRACT_KEY" =~ ^warmbly/production/vars/runtime-tls-recovery/[a-z0-9][a-z0-9-]{1,63}\.contract\.json$ ]] + [[ "$CONTRACT_SHA256" =~ ^[a-f0-9]{64}$ && "$CONTRACT_VERSION" != null && -n "$CONTRACT_VERSION" && "$CONTRACT_VERSION" != *$'\n'* ]] + umask 077 + mkdir "$WORK" + export AWS_PAGER="" + aws sts get-caller-identity --region us-east-1 >"$WORK/account.json" + jq -e '.Account == "925323749693"' "$WORK/account.json" >/dev/null + aws s3api get-object --region us-east-1 --bucket warmbly-terraform-use1-925323749693 --key "$CONTRACT_KEY" \ + --version-id "$CONTRACT_VERSION" --expected-bucket-owner 925323749693 "$WORK/contract.json" >"$WORK/contract-metadata.json" + jq -e --arg version "$CONTRACT_VERSION" '.VersionId == $version and .DeleteMarker != true and + (.ServerSideEncryption == "AES256" or .ServerSideEncryption == "aws:kms")' "$WORK/contract-metadata.json" >/dev/null + [ "$(sha256sum "$WORK/contract.json" | cut -d' ' -f1)" = "$CONTRACT_SHA256" ] + check_contract "$WORK/contract.json" + check_approval_environment + bash "$scripts/runtime-tls-recovery-lineage.sh" collect "$WORK/contract.json" "$WORK/lineage" . >"$WORK/lineage.log" 2>&1 + local input_action=collect + if [ "$1" = verify ]; then input_action=collect-archived; fi + bash "$scripts/runtime-tls-recovery-inputs.sh" "$input_action" "$WORK/contract.json" "$WORK/inputs" >"$WORK/inputs.log" 2>&1 + local release key digest + release=$(jq -r '.release.tag' "$WORK/contract.json") + gh release view "$release" --repo warmbly/warmbly --json tagName,isDraft,isPrerelease >"$WORK/release.json" + jq -e --arg release "$release" '.tagName == $release and .isDraft == false and .isPrerelease == false' "$WORK/release.json" >/dev/null + gh release download "$release" --repo warmbly/warmbly --pattern images.json --dir "$WORK/inputs" + [ "$(sha256sum "$WORK/inputs/images.json" | cut -d' ' -f1)" = "$(jq -r '.release.imagesSha256' "$WORK/contract.json")" ] + jq -e --arg release "$release" '.tag == $release and .registry == "ghcr.io/warmbly/warmbly"' "$WORK/inputs/images.json" >/dev/null + for key in backend backend-kafka consumer consumer-kafka worker worker-kafka forms tracking tracking-kafka realtime; do + digest=$(jq -er --arg key "$key" '.images[$key] | select(type == "string" and test("^sha256:[a-f0-9]{64}$"))' "$WORK/inputs/images.json") + gh attestation verify "oci://ghcr.io/warmbly/warmbly/${key%-kafka}@$digest" --repo warmbly/warmbly \ + --signer-workflow warmbly/warmbly/.github/workflows/release.yml --source-ref "refs/tags/$release" \ + --source-digest "$(jq -r '.release.source' "$WORK/contract.json")" >>"$WORK/provenance.log" 2>&1 + done +} + +verify_final() { + aws s3api get-object --region us-east-1 --bucket warmbly-terraform-use1-925323749693 \ + --key warmbly/production/runtime.tfstate --expected-bucket-owner 925323749693 "$WORK/final-state.json" >"$WORK/final-state-metadata.json" + jq -e '.DeleteMarker != true and (.VersionId | type == "string" and length > 0 and . != "null") and + (.ServerSideEncryption == "AES256" or .ServerSideEncryption == "aws:kms")' "$WORK/final-state-metadata.json" >/dev/null + check_final_state "$WORK/final-state.json" "$WORK/inputs/state.json" + bash "$scripts/runtime-tls-recovery-live.sh" collect-final "$WORK/contract.json" "$WORK/inputs" "$WORK/final-live" >"$WORK/final-live.log" 2>&1 + aws s3api head-object --region us-east-1 --bucket warmbly-terraform-use1-925323749693 \ + --key warmbly/production/runtime.tfstate --expected-bucket-owner 925323749693 >"$WORK/final-state-head.json" + jq -e --slurpfile metadata "$WORK/final-state-metadata.json" '.VersionId == $metadata[0].VersionId' "$WORK/final-state-head.json" >/dev/null +} + +main() { + local action=${1:-} + if [ "$action" = check-contract ]; then check_contract "${2:?}"; return; fi + if [ "$action" = check-final-state ]; then check_final_state "${2:?}" "${3:?}"; return; fi + case "$action" in plan|apply|verify) ;; *) echo 'Unknown partial TLS recovery action' >&2; return 1 ;; esac + check_context + prepare "$action" + if [ "$action" = verify ]; then verify_final; echo 'Final recovery state and effective live checks passed'; return; fi + bash "$scripts/runtime-tls-recovery-live.sh" collect "$WORK/contract.json" "$WORK/inputs" "$WORK/live" >"$WORK/live.log" 2>&1 + local dir=deploy/terraform/aws/runtime changes digest + terraform -chdir="$dir" init -input=false -no-color -backend-config=bucket=warmbly-terraform-use1-925323749693 >"$WORK/terraform.log" 2>&1 + terraform -chdir="$dir" plan -input=false -no-color -lock-timeout=5m -var-file="$WORK/inputs/snapshot.json" \ + -var=state_bucket=warmbly-terraform-use1-925323749693 -target=aws_lb_target_group.service \ + -out="$WORK/recovery.tfplan" >>"$WORK/terraform.log" 2>&1 + terraform -chdir="$dir" show -json "$WORK/recovery.tfplan" >"$WORK/plan.json" + bash "$scripts/runtime-tls-recovery.sh" check-plan "$WORK/plan.json" "$WORK/contract.json" + changes=$(jq -cS '{resource_changes:(.resource_changes | sort_by(.address)),resource_drift:(.resource_drift // [] | sort_by(.address))}' \ + "$WORK/plan.json" | sha256sum | cut -d' ' -f1) + [ "$changes" = "$(jq -r '.planChangesSha256' "$WORK/contract.json")" ] || { + echo 'The complete recovery changes differ from the privately reviewed plan; prepare a new contract' >&2; return 1; + } + digest=$(jq -cnS --arg contract "$CONTRACT_SHA256" --arg source "$GITHUB_SHA" --arg changes "$changes" \ + '{contract:$contract,workflowSource:$source,changes:$changes}' | sha256sum | cut -d' ' -f1) + aws s3api head-object --region us-east-1 --bucket warmbly-terraform-use1-925323749693 \ + --key warmbly/production/runtime.tfstate --expected-bucket-owner 925323749693 >"$WORK/preapply-state-head.json" + jq -e --slurpfile contract "$WORK/contract.json" '.VersionId == $contract[0].state.versionId' "$WORK/preapply-state-head.json" >/dev/null + if [ "$action" = plan ]; then + printf 'digest=%s\nrelease=%s\n' "$digest" "$(jq -r '.release.tag' "$WORK/contract.json")" >>"${GITHUB_OUTPUT:?}" + printf 'Partial TLS cleanup: exactly four reviewed HTTP target-group deletions.\n\nContract SHA-256: %s\n\nComplete changes SHA-256: %s\n\nApproval digest: %s\n\nReview the matching complete private plan before approving.\n' \ + "$CONTRACT_SHA256" "$changes" "$digest" >>"${GITHUB_STEP_SUMMARY:?}" + return + fi + [ "$digest" = "${APPROVED_DIGEST:?}" ] || { echo 'Recovery approval digest changed; a new reviewed run is required' >&2; return 1; } + bash "$scripts/runtime-tls-recovery-live.sh" collect "$WORK/contract.json" "$WORK/inputs" "$WORK/preapply-live" >"$WORK/preapply-live.log" 2>&1 + terraform -chdir="$dir" apply -input=false -no-color -lock-timeout=5m "$WORK/recovery.tfplan" >>"$WORK/terraform.log" 2>&1 || { + echo 'Partial cleanup failed; inspect private state before preparing any new recovery contract' >&2; return 1; + } + verify_final + echo 'Reviewed partial cleanup and effective checks passed; attested same-release redeploy is still required' +} +main "$@" diff --git a/.github/scripts/runtime-tls-recovery-execute.test.sh b/.github/scripts/runtime-tls-recovery-execute.test.sh new file mode 100755 index 000000000..e7e9a0273 --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-execute.test.sh @@ -0,0 +1,166 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/../.." +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +mkdir -p "$work/repository/.github/scripts" "$work/bin" +cp .github/scripts/runtime-tls-recovery{,-inputs,-lineage,-execute}.sh "$work/repository/.github/scripts/" +git -C "$work/repository" init -q +git -C "$work/repository" config user.name 'Recovery fixture' +git -C "$work/repository" config user.email 'fixture@example.invalid' +git -C "$work/repository" commit -qm 'feat: establish recovery drain fixture' --allow-empty +drain=$(git -C "$work/repository" rev-parse HEAD) +git -C "$work/repository" commit -qm 'feat: establish recovery ON fixture' --allow-empty +on=$(git -C "$work/repository" rev-parse HEAD) +git -C "$work/repository" commit -qm 'feat: establish recovery release fixture' --allow-empty +release=$(git -C "$work/repository" rev-parse HEAD) +git -C "$work/repository" tag v1.2.3 +jq -n --arg digest "sha256:$(printf fixture | sha256sum | cut -d' ' -f1)" \ + -f .github/scripts/runtime-tls-recovery-live.fixture.jq >"$work/fixture.json" +jq '.state' "$work/fixture.json" >"$work/state.json" +jq '.state | .serial+=1 | .resources |= map(select(.type != "aws_lb_target_group" or .name != "service"))' "$work/fixture.json" >"$work/final-state.json" +jq '.vars' "$work/fixture.json" >"$work/snapshot.json" +jq '.images | .images += {"backend-kafka":.images.backend,"consumer-kafka":.images.consumer,"worker":.images.backend,"worker-kafka":.images.backend,"tracking-kafka":.images.tracking}' \ + "$work/fixture.json" >"$work/images.json" +jq '.baseline | {resource_changes:[.httpGroups[] | {address:("aws_lb_target_group.service[\""+(.TargetGroupName|ltrimstr("warmbly-production-"))+"\"]"), + change:{actions:["delete"],after:null,before:{arn:.TargetGroupArn,id:.TargetGroupArn,name:.TargetGroupName,protocol:.Protocol,port:.Port,vpc_id:.VpcId}}}]}' \ + "$work/fixture.json" >"$work/plan.json" +changes=$(jq -cS '{resource_changes:(.resource_changes|sort_by(.address)),resource_drift:[]}' "$work/plan.json" | sha256sum | cut -d' ' -f1) +jq --arg drain "$drain" --arg on "$on" --arg release "$release" --arg changes "$changes" \ + --arg state "$(sha256sum "$work/state.json" | cut -d' ' -f1)" --arg vars "$(sha256sum "$work/snapshot.json" | cut -d' ' -f1)" \ + --arg images "$(sha256sum "$work/images.json" | cut -d' ' -f1)" ' + .baseline + {schemaVersion:1,repository:"warmbly/warmbly",bucket:"warmbly-terraform-use1-925323749693", + release:{tag:"v1.2.3",source:$release,runId:101,attempt:1,imagesSha256:$images}, + drain:{tag:"v1.2.2",source:$drain,runId:102,attempt:1},failedOn:{tag:"v1.2.2",source:$on,runId:103,attempt:1},planChangesSha256:$changes} | + .state += {key:"warmbly/production/runtime.tfstate",sha256:$state} | + .snapshot += {key:"warmbly/production/vars/runtime-tls-recovery/fixture.tfvars.json",versionId:"vars-version",sha256:$vars}' \ + "$work/fixture.json" >"$work/contract.json" +jq ' + def run($path;$event;$branch;$conclusion): {id:.runId,run_attempt:.attempt,head_sha:.source,repository:{full_name:"warmbly/warmbly"}, + path:$path,event:$event,head_branch:$branch,status:"completed",conclusion:$conclusion}; + {runs:{release:(.release|run(".github/workflows/release.yml";"push";.tag;"success")), + drain:(.drain|run(".github/workflows/runtime-tls.yml";"workflow_dispatch";"main";"success")+{display_title:("Runtime TLS drain "+.tag)}), + failedOn:(.failedOn|run(".github/workflows/runtime-tls.yml";"workflow_dispatch";"main";"failure")+{display_title:("Runtime TLS on "+.tag)})}, + failedOnJobs:[{id:1,run_id:103,run_attempt:1,status:"completed",name:"apply",conclusion:"success"}, + {id:2,run_id:103,run_attempt:1,status:"completed",name:"redeploy / fixture",conclusion:"failure"}]}' \ + "$work/contract.json" >"$work/lineage.json" +cat >"$work/repository/.github/scripts/runtime-tls-recovery-live.sh" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +echo "live $1" >>"$FIXTURES/requests.log" +[ "${MODE:-}" != live ] || exit 1 +mkdir "$4" +echo '{}' >"$4/live.json" +SH +cat >"$work/bin/aws" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +echo "aws $*" >>"$FIXTURES/requests.log" +service=$1 operation=$2 +shift 2 +key= version= owner= bucket= region= output= +while [ "$#" -gt 0 ]; do + case "$1" in + --key) key=$2; shift 2 ;; --version-id) version=$2; shift 2 ;; --expected-bucket-owner) owner=$2; shift 2 ;; + --region) region=$2; shift 2 ;; --bucket) bucket=$2; shift 2 ;; *) output=$1; shift ;; + esac +done +[ "$region" = us-east-1 ] +case "$service $operation" in + 'sts get-caller-identity') echo '{"Account":"925323749693"}' ;; + 's3api get-object') + [ "$owner" = 925323749693 ] && [ "$bucket" = warmbly-terraform-use1-925323749693 ] + case "$key" in + */fixture.contract.json) kind=contract ;; + */fixture.tfvars.json) kind=snapshot ;; + */runtime.tfstate) kind=state ;; + *) exit 1 ;; + esac + if [ -z "$version" ]; then kind=final-state; version=final-version; fi + cp "$FIXTURES/$kind.json" "$output" + jq -n --arg version "$version" '{VersionId:$version,ServerSideEncryption:"AES256"}' ;; + 's3api head-object') + version=state-version + if [ -e "$FIXTURES/applied" ] || [ "${MODE:-}" = advanced ]; then version=final-version; fi + jq -n --arg version "$version" '{VersionId:$version}' ;; + *) exit 1 ;; +esac +SH +cat >"$work/bin/gh" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +echo "gh $*" >>"$FIXTURES/requests.log" +case "$1 $2" in + 'api repos/warmbly/warmbly/environments/aws-infrastructure-approval') + jq -n --arg mode "${MODE:-}" '{can_admins_bypass:($mode=="bypass"),protection_rules:[{type:"required_reviewers",prevent_self_review:($mode!="self-review"),reviewers:[{type:"User"}]}]}' ;; + 'api repos/warmbly/warmbly/actions/runs/101/attempts/1') jq '.runs.release' "$FIXTURES/lineage.json" ;; + 'api repos/warmbly/warmbly/actions/runs/102/attempts/1') jq '.runs.drain' "$FIXTURES/lineage.json" ;; + 'api repos/warmbly/warmbly/actions/runs/103/attempts/1') jq '.runs.failedOn' "$FIXTURES/lineage.json" ;; + 'api repos/warmbly/warmbly/actions/runs/103/attempts/1/jobs?per_page=100') jq '[{total_count:2,jobs:.failedOnJobs}]' "$FIXTURES/lineage.json" ;; + 'release view') echo '{"tagName":"v1.2.3","isDraft":false,"isPrerelease":false}' ;; + 'release download') + while [ "$1" != --dir ]; do shift; done + cp "$FIXTURES/images.json" "$2/images.json" + if [ "${MODE:-}" = artifact ]; then printf '\n' >>"$2/images.json"; fi ;; + 'attestation verify') [ "${MODE:-}" != provenance ] ;; + *) exit 1 ;; +esac +SH +cat >"$work/bin/terraform" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +echo "terraform $*" >>"$FIXTURES/requests.log" +case "$2" in + init) ;; + plan) [[ "$*" == *'-target=aws_lb_target_group.service'* && "$*" != *'-target=aws_ecs'* ]] ;; + show) + case "${MODE:-}" in + scope) jq '.resource_changes|=.[1:]' "$FIXTURES/plan.json" ;; + changes) jq '.resource_changes[0].change.before.tags={new:"tag"}' "$FIXTURES/plan.json" ;; + *) cat "$FIXTURES/plan.json" ;; + esac ;; + apply) [ "${MODE:-}" != apply-failure ] && touch "$FIXTURES/applied" ;; + *) exit 1 ;; +esac +SH +chmod +x "$work/bin/"* +export FIXTURES="$work" PATH="$work/bin:$PATH" +export GITHUB_ACTIONS=true GITHUB_REPOSITORY=warmbly/warmbly GITHUB_REF=refs/heads/main GITHUB_EVENT_NAME=workflow_dispatch +export GITHUB_WORKFLOW_REF=warmbly/warmbly/.github/workflows/runtime-tls-recovery.yml@refs/heads/main +export GITHUB_RUN_ATTEMPT=1 GITHUB_RUN_ID=999 GITHUB_SHA="$release" +export CONTRACT_KEY=warmbly/production/vars/runtime-tls-recovery/fixture.contract.json CONTRACT_VERSION=contract-version +CONTRACT_SHA256=$(sha256sum "$work/contract.json" | cut -d' ' -f1) +export CONTRACT_SHA256 +export GITHUB_OUTPUT="$work/output" GITHUB_STEP_SUMMARY="$work/summary" +guard="$work/repository/.github/scripts/runtime-tls-recovery-execute.sh" +cd "$work/repository" +WORK="$work/plan" bash "$guard" plan +approved=$(sed -n 's/^digest=//p' "$GITHUB_OUTPUT") +[ -n "$approved" ] +for mode in bypass self-review artifact provenance live advanced scope changes; do + : >"$work/requests.log" + if WORK="$work/$mode" MODE=$mode APPROVED_DIGEST="$approved" bash "$guard" apply 2>/dev/null; then + echo "Recovery applied incompatible evidence: $mode" >&2; exit 1 + fi + if rg -q '^terraform .* apply ' "$work/requests.log"; then echo "Recovery reached apply for $mode" >&2; exit 1; fi +done +if WORK="$work/wrong-approval" APPROVED_DIGEST=other bash "$guard" apply 2>/dev/null; then echo 'Recovery accepted another approval digest' >&2; exit 1; fi +if WORK="$work/retry" GITHUB_RUN_ATTEMPT=2 bash "$guard" plan 2>/dev/null; then echo 'Recovery accepted a rerun' >&2; exit 1; fi +if WORK="$work/local" GITHUB_ACTIONS=false bash "$guard" plan 2>/dev/null; then echo 'Recovery accepted local execution' >&2; exit 1; fi +: >"$work/requests.log" +if WORK="$work/apply-failure" MODE=apply-failure APPROVED_DIGEST="$approved" bash "$guard" apply 2>/dev/null; then + echo 'Recovery continued after an apply failure' >&2; exit 1 +fi +[ ! -e "$work/applied" ] +if rg -q '^live collect-final$' "$work/requests.log"; then echo 'Recovery verified a failed apply as complete' >&2; exit 1; fi +: >"$work/requests.log" +WORK="$work/apply" APPROVED_DIGEST="$approved" bash "$guard" apply +[ "$(rg -c '^live collect$' "$work/requests.log")" = 2 ] +[ "$(rg -c '^live collect-final$' "$work/requests.log")" = 1 ] +[ "$(rg -c '^gh attestation verify ' "$work/requests.log")" = 10 ] +WORK="$work/verify" bash "$guard" verify +jq '.resources[0].instances[0].attributes.arn="different"' "$work/final-state.json" >"$work/changed-state.json" +if bash "$guard" check-final-state "$work/changed-state.json" "$work/state.json" 2>/dev/null; then + echo 'Recovery accepted an unrelated retained-state change' >&2; exit 1 +fi +echo 'Protected recovery plan, approval binding, apply and final-state orchestration checks passed' diff --git a/.github/scripts/runtime-tls-recovery-inputs.sh b/.github/scripts/runtime-tls-recovery-inputs.sh index 2c4364a34..fbe4df0b3 100644 --- a/.github/scripts/runtime-tls-recovery-inputs.sh +++ b/.github/scripts/runtime-tls-recovery-inputs.sh @@ -16,7 +16,7 @@ check_contract() { } collect_inputs() { - local baseline=$1 work=$2 bucket key version digest kind + local baseline=$1 work=$2 require_latest=${3:-true} bucket key version digest kind check_contract "$baseline" umask 077 mkdir "$work" @@ -47,11 +47,13 @@ collect_inputs() { jq -e '.target_tls == "on" and .name == "warmbly-production"' "$work/snapshot.json" >/dev/null || { echo 'Recovery vars must select the reviewed production cleanup stage' >&2; return 1; } - aws s3api head-object --region us-east-1 --bucket "$bucket" --key warmbly/production/runtime.tfstate \ - --expected-bucket-owner 925323749693 >"$work/latest-state.json" - jq -e --slurpfile baseline "$baseline" '.VersionId == $baseline[0].state.versionId' "$work/latest-state.json" >/dev/null || { - echo 'Recovery state advanced beyond the reviewed version' >&2; return 1; - } + if [ "$require_latest" = true ]; then + aws s3api head-object --region us-east-1 --bucket "$bucket" --key warmbly/production/runtime.tfstate \ + --expected-bucket-owner 925323749693 >"$work/latest-state.json" + jq -e --slurpfile baseline "$baseline" '.VersionId == $baseline[0].state.versionId' "$work/latest-state.json" >/dev/null || { + echo 'Recovery state advanced beyond the reviewed version' >&2; return 1; + } + fi jq '{account,region,bucket,state:{key:.state.key,versionId:.state.versionId,sha256:.state.sha256,lineage:.state.lineage,serial:.state.serial},snapshot}' \ "$baseline" >"$work/inputs.json" } @@ -59,5 +61,6 @@ collect_inputs() { case "${1:-}" in check-contract) check_contract "${2:?}" ;; collect) collect_inputs "${2:?}" "${3:?}" ;; + collect-archived) collect_inputs "${2:?}" "${3:?}" false ;; *) echo 'Only read-only recovery input validation and collection are supported' >&2; exit 1 ;; esac diff --git a/.github/scripts/runtime-tls-recovery-inputs.test.sh b/.github/scripts/runtime-tls-recovery-inputs.test.sh index b4942bfb3..49765f569 100644 --- a/.github/scripts/runtime-tls-recovery-inputs.test.sh +++ b/.github/scripts/runtime-tls-recovery-inputs.test.sh @@ -89,6 +89,9 @@ for mode in account api-failure hash version encryption deleted advanced; do fi [ ! -e "$work/$mode/inputs.json" ] done +PATH="$work/bin:$PATH" FIXTURES="$work" MODE=advanced bash "$guard" collect-archived "$work/reviewed.json" "$work/archived" +cmp "$work/state.json" "$work/archived/state.json" +[ ! -e "$work/archived/latest-state.json" ] if PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/reviewed.json" "$work/collected" 2>/dev/null; then echo 'Recovery overwrote an existing input collection' >&2; exit 1 fi diff --git a/.github/scripts/runtime-tls-recovery-live.fixture.jq b/.github/scripts/runtime-tls-recovery-live.fixture.jq new file mode 100644 index 000000000..c3b8b9de2 --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-live.fixture.jq @@ -0,0 +1,56 @@ +def services: ["backend", "consumer", "forms", "tracking", "realtime"]; +def public_services: ["backend", "forms", "tracking", "realtime"]; +def arn($kind; $id): "arn:aws:elasticloadbalancing:us-east-1:925323749693:" + $kind + "/" + $id; +def http($name): arn("targetgroup"; "warmbly-production-"+$name+"/0123456789abcdef"); +def tls($name): arn("targetgroup"; "warmbly-production-"+$name+"-tls/1123456789abcdef"); +def service($name): "arn:aws:ecs:us-east-1:925323749693:service/warmbly-production/warmbly-production-"+$name; +def definition($name): "arn:aws:ecs:us-east-1:925323749693:task-definition/warmbly-production-"+$name+":47"; +def image($name): "ghcr.io/warmbly/warmbly/"+$name+"@"+$digest; +"arn:aws:ecs:us-east-1:925323749693:cluster/warmbly-production" as $cluster | +arn("loadbalancer"; "app/warmbly-production/0123456789abcdef") as $lb | +arn("listener"; "app/warmbly-production/0123456789abcdef/0123456789abcdef") as $listener | +"vpc-0123456789abcdef0" as $vpc | "sg-0123456789abcdef0" as $sg | +"-----BEGIN CERTIFICATE-----\nfixture\n-----END CERTIFICATE-----" as $cert | +([range(9) | . as $i | {arn:arn("listener-rule"; "app/warmbly-production/0123456789abcdef/0123456789abcdef/"+($i|tostring)), + hosts:["host"+($i|tostring)+".example.com"],target:tls(public_services[$i%4])}]) as $routes | +(public_services | map({TargetGroupName:("warmbly-production-"+.),TargetGroupArn:http(.),Protocol:"HTTP",Port:8080,VpcId:$vpc,LoadBalancerArns:[],targets:[]})) as $http | +{baseline:{account:"925323749693",region:"us-east-1",httpGroups:$http, + state:{lineage:"01234567-89ab-cdef-0123-456789abcdef",serial:64,versionId:"state-version",sha256:("a"*64),httpGroups:$http}, + snapshot:{sha256:("b"*64),releaseTag:"v1.2.3"}}, + vars:{name:"warmbly-production",target_tls:"on",backend_internal_certificate:$cert}, + images:{tag:"v1.2.3",registry:"ghcr.io/warmbly/warmbly",images:(services|map({key:.,value:$digest})|from_entries)}, + state:{version:4,lineage:"01234567-89ab-cdef-0123-456789abcdef",serial:64,resources:[ + {mode:"managed",type:"aws_lb_target_group",name:"service",instances:[$http[]|{ + index_key:(.TargetGroupName|ltrimstr("warmbly-production-")),attributes:{arn:.TargetGroupArn,id:.TargetGroupArn,name:.TargetGroupName,protocol:.Protocol,port:.Port,vpc_id:.VpcId}}]}, + {mode:"managed",type:"aws_lb_target_group",name:"service_tls",instances:[public_services[]|{index_key:.,attributes:{arn:tls(.),name:("warmbly-production-"+.+"-tls"),protocol:"HTTPS",port:8443,vpc_id:$vpc}}]}, + {mode:"managed",type:"aws_ecs_service",name:"service",instances:[services[]|{index_key:.,attributes:{id:service(.),cluster:$cluster,network_configuration:[{security_groups:[$sg]}]}}]}, + {mode:"managed",type:"aws_lb",name:"main",instances:[{attributes:{arn:$lb}}]}, + {mode:"managed",type:"aws_lb_listener",name:"https",instances:[{attributes:{arn:$listener}}]}, + {mode:"managed",type:"aws_lb_listener_rule",name:"service",instances:[$routes[]|{attributes:{arn:.arn,condition:[{host_header:[{values:.hosts}]}],action:[{target_group_arn:.target}]}}]} + ]}, + live:{account:{Account:"925323749693"},services:{failures:[],services:[services[]|. as $name|{ + serviceName:("warmbly-production-"+.),serviceArn:service(.),clusterArn:$cluster,taskDefinition:definition(.),status:"ACTIVE",desiredCount:1,runningCount:1,pendingCount:0, + deployments:[{status:"PRIMARY",rolloutState:"COMPLETED",taskDefinition:definition(.)}], + networkConfiguration:{awsvpcConfiguration:{securityGroups:[$sg]}}, + loadBalancers:(if .=="consumer" then [] else [{containerName:.,containerPort:8443,targetGroupArn:tls(.)}] end)}]}, + definitions:[services[]|. as $name|{taskDefinition:{taskDefinitionArn:definition(.),runtimePlatform:{cpuArchitecture:"X86_64"},containerDefinitions:[{ + name:.,image:image(.),environment:([ + {name:"SERVE_TLS",value:(if .=="backend" then "supplied" else "self-signed" end)}, + {name:"SERVE_TLS_PORT",value:"8443"},{name:"SERVE_HTTP_LOOPBACK_ONLY",value:"true"}]+ + (if .=="backend" then [{name:"SERVE_TLS_CERT",value:$cert}] elif .=="forms" or .=="tracking" then + [{name:"BACKEND_INTERNAL_URL",value:"https://backend.warmbly.internal:8443"},{name:"BACKEND_INTERNAL_CA",value:$cert}] else [] end))}]}, + tags:[{key:"warmbly-release",value:"v1.2.3"},{key:"warmbly-image-variant",value:"default"}]}], + tasks:[services[]|{taskArn:("task-"+.),group:("service:warmbly-production-"+.),taskDefinitionArn:definition(.),clusterArn:$cluster, + lastStatus:"RUNNING",desiredStatus:"RUNNING",healthStatus:(if .=="consumer" then "UNKNOWN" else "HEALTHY" end),overrides:{containerOverrides:[]}, + containers:[{name:.,image:image(.),imageDigest:$digest,lastStatus:"RUNNING",healthStatus:(if .=="consumer" then "UNKNOWN" else "HEALTHY" end),networkInterfaces:[{privateIpv4Address:"10.0.0.1"}]}]}], + manifests:[services[]|{image:image(.),digest:$digest,document:{schemaVersion:2}}], + httpsGroups:[public_services[]|{TargetGroupArn:tls(.),TargetGroupName:("warmbly-production-"+.+"-tls"),Protocol:"HTTPS",Port:8443,HealthCheckProtocol:"HTTPS",VpcId:$vpc,LoadBalancerArns:[$lb], + targets:[{Target:{Id:"10.0.0.1",Port:8443},TargetHealth:{State:"healthy"}}]}],httpGroups:$http, + listeners:[{ListenerArn:$listener,LoadBalancerArn:$lb,Port:443,Protocol:"HTTPS"}], + rules:([$routes[]|{RuleArn:.arn,IsDefault:false,Conditions:[{Field:"host-header",HostHeaderConfig:{Values:.hosts}}],Actions:[{Type:"forward",TargetGroupArn:.target}]}]+ + [{IsDefault:true,Actions:[{Type:"fixed-response",Order:1,FixedResponseConfig:{StatusCode:"404",ContentType:"text/plain",MessageBody:"Not found"}}]}]), + securityGroups:[{GroupId:$sg,VpcId:$vpc,IpPermissions:[{IpProtocol:"tcp",FromPort:8443,ToPort:8443}]}], + alarms:{CompositeAlarms:[],MetricAlarms:[public_services[] as $name|["target-5xx-rate","unhealthy-hosts"][]| + {AlarmName:("warmbly-production-"+$name+"-"+.),StateValue:"OK",ActionsEnabled:true, + Dimensions:[{Name:"TargetGroup",Value:(tls($name)|split(":")[-1])},{Name:"LoadBalancer",Value:($lb|split(":")[-1]|ltrimstr("loadbalancer/"))}]}]}, + public:(["https://api.warmbly.com/health","https://api.warmbly.com/v1/auth/config","https://forms.warmbly.com/health","https://realtime.warmbly.com/health","https://track.monitorably.com/health"]|map({url:.,status:200}))}} diff --git a/.github/scripts/runtime-tls-recovery-live.jq b/.github/scripts/runtime-tls-recovery-live.jq new file mode 100644 index 000000000..c2d4db18f --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-live.jq @@ -0,0 +1,131 @@ +def public_services: ["backend", "forms", "tracking", "realtime"]; +def services: ["backend", "consumer", "forms", "tracking", "realtime"]; +def instances($type; $name): + [$state[0].resources[] | select(.mode == "managed" and .module == null and .type == $type and .name == $name) | .instances[]]; +def identity: {TargetGroupName,TargetGroupArn,Protocol,Port,VpcId}; +def environment: .environment | map({key:.name,value:.value}) | from_entries; +def targets: + [.Actions[] | select(.Type == "forward") | + .TargetGroupArn?, .ForwardConfig.TargetGroups[]?.TargetGroupArn | select(. != null)] | unique; + +$baseline[0] as $b | $vars[0] as $v | $images[0] as $images | +instances("aws_ecs_service"; "service") as $expectedServices | +instances("aws_lb_target_group"; "service_tls") as $tls | +(instances("aws_lb"; "main") | map(.attributes.arn)) as $lbs | +(instances("aws_lb_listener"; "https") | map(.attributes.arn)) as $listeners | +([instances("aws_lb_listener_rule"; "service")[], instances("aws_lb_listener_rule"; "tracking_alias")[]] | + map({arn:.attributes.arn, hosts:([.attributes.condition[].host_header[].values[]] | sort), + target:.attributes.action[0].target_group_arn})) as $routes | +($expectedServices | map(.attributes.network_configuration[].security_groups[]) | unique) as $sgs | +($v.target_tls_port // 8443) as $port | +. as $live | +.account.Account == "925323749693" and +($images.tag == $b.snapshot.releaseTag and $images.registry == "ghcr.io/warmbly/warmbly") and +($expectedServices | map(.index_key) | sort) == (services | sort) and +($tls | map(.index_key) | sort) == (public_services | sort) and +($lbs | length == 1) and ($listeners | length == 1) and +($routes | length == 9) and ($routes | map(.arn) | unique | length == 9) and +all($routes[]; .hosts | length > 0) and +all($tls[]; .attributes.protocol == "HTTPS" and .attributes.port == $port and + .attributes.vpc_id == $b.httpGroups[0].VpcId) and +all($routes[]; .target as $target | any($tls[]; .attributes.arn == $target)) and +(.services.failures | length == 0) and +(.services.services | map(.serviceName) | sort) == (services | map("warmbly-production-" + .) | sort) and +all(.services.services[]; + . as $s | (.serviceName | ltrimstr("warmbly-production-")) as $name | + any($expectedServices[]; .index_key == $name and .attributes.id == $s.serviceArn and .attributes.cluster == $s.clusterArn) and + .status == "ACTIVE" and .desiredCount > 0 and .runningCount == .desiredCount and .pendingCount == 0 and + (.deployments | length == 1) and .deployments[0].status == "PRIMARY" and + .deployments[0].rolloutState == "COMPLETED" and .deployments[0].taskDefinition == .taskDefinition and + (.networkConfiguration.awsvpcConfiguration.securityGroups | sort) == $sgs and + (if $name == "consumer" then (.loadBalancers | length == 0) else + (.loadBalancers | length == 1) and .loadBalancers[0].containerName == $name and + .loadBalancers[0].containerPort == $port and + any($tls[]; .index_key == $name and .attributes.arn == $s.loadBalancers[0].targetGroupArn) end) and + ([$live.definitions[] | select(.taskDefinition.taskDefinitionArn == $s.taskDefinition)] | length == 1) and + ([$live.definitions[] | select(.taskDefinition.taskDefinitionArn == $s.taskDefinition)][0] as $d | + ([$d.tags[] | select(.key == "warmbly-image-variant") | .value]) as $variant | + ($name + (if $variant == ["kafka"] then "-kafka" else "" end)) as $key | + ($images.registry + "/" + $name + "@" + $images.images[$key]) as $image | + (if $name == "consumer" and $d.taskDefinition.containerDefinitions[0].healthCheck == null then "UNKNOWN" else "HEALTHY" end) as $health | + ([$d.tags[] | select(.key == "warmbly-release") | .value] == [$images.tag]) and + ($variant == ["default"] or $variant == ["kafka"]) and + ($images.images[$key] | type == "string" and test("^sha256:[a-f0-9]{64}$")) and + ($d.taskDefinition.containerDefinitions | length == 1) and + (["X86_64", "ARM64"] | index($d.taskDefinition.runtimePlatform.cpuArchitecture // "X86_64") != null) and + ($d.taskDefinition.runtimePlatform.operatingSystemFamily // "LINUX") == "LINUX" and + ($d.taskDefinition.containerDefinitions[0] as $c | + ($c | environment) as $env | + $c.name == $name and $c.image == $image and + ($c.environment | map(.name) | unique | length) == ($c.environment | length) and + ($c.environmentFiles // [] | length == 0) and + all($c.secrets[]?; .name | test("^(SERVE_TLS|SERVE_TLS_PORT|SERVE_TLS_CERT|SERVE_HTTP_LOOPBACK_ONLY|BACKEND_INTERNAL_URL|BACKEND_INTERNAL_CA)$") | not) and + (if $name == "consumer" then true else + $env.SERVE_TLS == (if $name == "backend" then "supplied" else "self-signed" end) and + $env.SERVE_TLS_PORT == ($port | tostring) and $env.SERVE_HTTP_LOOPBACK_ONLY == "true" and + (if $name == "backend" then $env.SERVE_TLS_CERT == $v.backend_internal_certificate else true end) and + (if $name == "forms" or $name == "tracking" then + $env.BACKEND_INTERNAL_URL == ("https://backend." + ($v.namespace // "warmbly.internal") + ":" + ($port | tostring)) and + $env.BACKEND_INTERNAL_CA == $v.backend_internal_certificate else true end) end)) and + ([$live.tasks[] | select(.group == ("service:" + $s.serviceName))] as $tasks | + ($tasks | length) == $s.desiredCount and + all($tasks[]; .taskDefinitionArn == $s.taskDefinition and .clusterArn == $s.clusterArn and + .lastStatus == "RUNNING" and .desiredStatus == "RUNNING" and .healthStatus == $health and + (.overrides.containerOverrides | all(.[]; (.environment // [] | length == 0) and (.command // [] | length == 0) and (.environmentFiles // [] | length == 0))) and + (.containers | length == 1) and .containers[0].name == $name and .containers[0].image == $image and + .containers[0].lastStatus == "RUNNING" and .containers[0].healthStatus == $health and + (.containers[0].imageDigest as $digest | + any($live.manifests[]; .image == $image and .digest == ($image | split("@")[1]) and + (if .document.manifests then + .digest as $index | + any(.document.manifests[]; (.digest == $digest or $index == $digest) and .platform.os == "linux" and + .platform.architecture == (if ($d.taskDefinition.runtimePlatform.cpuArchitecture // "X86_64") == "ARM64" then "arm64" else "amd64" end)) + else .digest == $digest end))))))) and +(.tasks | map(.taskArn) | unique | length) == (.tasks | length) and +(.tasks | length) == ([.services.services[].desiredCount] | add) and +(.definitions | length == 5) and +(.httpsGroups | map(.TargetGroupArn) | sort) == ($tls | map(.attributes.arn) | sort) and +all(.httpsGroups[]; + . as $g | .Protocol == "HTTPS" and .Port == $port and .HealthCheckProtocol == "HTTPS" and + .VpcId == $b.httpGroups[0].VpcId and .LoadBalancerArns == $lbs and + (.targets | length > 0) and all(.targets[]; .TargetHealth.State == "healthy" and .Target.Port == $port) and + ([.targets[].Target.Id] | sort) == + ([$live.tasks[] | select(.group == ("service:" + ($g.TargetGroupName | rtrimstr("-tls")))) | + .containers[0].networkInterfaces[].privateIpv4Address] | sort) and + any($tls[]; .attributes.arn == $g.TargetGroupArn and .attributes.name == $g.TargetGroupName)) and +(if $phase == "after" then .httpGroups == [] else + (.httpGroups | map(identity) | sort_by(.TargetGroupArn)) == ($b.httpGroups | map(identity) | sort_by(.TargetGroupArn)) end) and +all(.httpGroups[]; .LoadBalancerArns == [] and .targets == []) and +(.listeners | length == 1) and .listeners[0].ListenerArn == $listeners[0] and +.listeners[0].LoadBalancerArn == $lbs[0] and .listeners[0].Port == 443 and .listeners[0].Protocol == "HTTPS" and +(.rules | length == 10) and +([.rules[] | select(.IsDefault == true)] | length == 1) and +all(.rules[] | select(.IsDefault == true); .Actions == [{Type:"fixed-response",Order:1,FixedResponseConfig:{StatusCode:"404",ContentType:"text/plain",MessageBody:"Not found"}}]) and +([.rules[] | select(.IsDefault == false) | .RuleArn] | sort) == ($routes | map(.arn) | sort) and +all(.rules[] | select(.IsDefault == false); + . as $rule | (.Transforms // [] | length == 0) and (.Conditions | length == 1) and + .Conditions[0].Field == "host-header" and (.Actions | length == 1) and .Actions[0].Type == "forward" and + all(.Actions[0].ForwardConfig.TargetGroups[]?; (.Weight // 1) > 0) and + any($routes[]; .arn == $rule.RuleArn and + .hosts == ($rule.Conditions[0].HostHeaderConfig.Values | sort) and ($rule | targets) == [.target])) and +(.securityGroups | map(.GroupId) | sort) == ($sgs | sort) and ($sgs | length > 0) and +all(.securityGroups[]; .VpcId == $b.httpGroups[0].VpcId and + all(.IpPermissions[]; . as $permission | + .IpProtocol != "-1" and + (if .IpProtocol == "tcp" or .IpProtocol == "6" then + (.FromPort | type == "number") and (.ToPort | type == "number") and + all($b.httpGroups[]; .Port < $permission.FromPort or .Port > $permission.ToPort) else true end))) and +(.alarms.CompositeAlarms | length == 0) and +(.alarms.MetricAlarms | map(.AlarmName) | sort) == + ([public_services[] as $name | ["target-5xx-rate", "unhealthy-hosts"][] | "warmbly-production-" + $name + "-" + .] | sort) and +all(.alarms.MetricAlarms[]; + . as $alarm | .StateValue == "OK" and .ActionsEnabled == true and + any($tls[]; + . as $group | ($alarm.AlarmName | startswith("warmbly-production-" + $group.index_key + "-")) and + ([$alarm.Dimensions[]?, $alarm.Metrics[]?.MetricStat.Metric.Dimensions[]? | select(.Name == "TargetGroup") | .Value] | unique) == + [($group.attributes.arn | split(":")[-1])] and + ([$alarm.Dimensions[]?, $alarm.Metrics[]?.MetricStat.Metric.Dimensions[]? | select(.Name == "LoadBalancer") | .Value] | unique) == + [($lbs[0] | split(":")[-1] | ltrimstr("loadbalancer/"))])) and +(.public | map(.url) | sort) == (["https://api.warmbly.com/health", "https://api.warmbly.com/v1/auth/config", + "https://forms.warmbly.com/health", "https://realtime.warmbly.com/health", "https://track.monitorably.com/health"] | sort) and +all(.public[]; .status == 200) diff --git a/.github/scripts/runtime-tls-recovery-live.sh b/.github/scripts/runtime-tls-recovery-live.sh new file mode 100755 index 000000000..f230cd5be --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-live.sh @@ -0,0 +1,96 @@ +#!/usr/bin/env bash +# Collect fresh read-only service and traffic evidence from reviewed state identities. +set -euo pipefail +scripts=$(cd "$(dirname "$0")" && pwd) + +check_live() { + local evidence=$1 baseline=$2 vars=$3 state=$4 images=$5 phase=${6:-before} + bash "$scripts/runtime-tls-recovery.sh" check-state "$state" "$baseline" + [ "$(sha256sum "$vars" | cut -d' ' -f1)" = "$(jq -r '.snapshot.sha256' "$baseline")" ] + jq -e '.name == "warmbly-production" and .target_tls == "on" and + (.backend_internal_certificate | type == "string" and startswith("-----BEGIN CERTIFICATE-----"))' "$vars" >/dev/null + jq -e --arg phase "$phase" --slurpfile baseline "$baseline" --slurpfile vars "$vars" --slurpfile state "$state" --slurpfile images "$images" \ + -f "$scripts/runtime-tls-recovery-live.jq" "$evidence" >/dev/null || { + echo 'Recovery live service, TLS, traffic or health evidence does not match the reviewed inputs' >&2; return 1; + } +} + +collect_live() { + local baseline=$1 inputs=$2 work=$3 phase=${4:-before} cluster definition arn name image digest url status + bash "$scripts/runtime-tls-recovery.sh" check-state "$inputs/state.json" "$baseline" + umask 077 + mkdir "$work" + export AWS_PAGER="" + aws sts get-caller-identity --region us-east-1 >"$work/account.json" + jq -e '.Account == "925323749693"' "$work/account.json" >/dev/null + cluster=$(jq -er '[.resources[] | select(.mode=="managed" and .module==null and .type=="aws_ecs_service" and .name=="service") | + .instances[].attributes.cluster] | unique | if length==1 then .[0] else error("cluster identity") end' "$inputs/state.json") + aws ecs describe-services --region us-east-1 --cluster "$cluster" --services \ + warmbly-production-backend warmbly-production-consumer warmbly-production-forms warmbly-production-tracking warmbly-production-realtime >"$work/services.json" + : >"$work/definitions.jsonl" + : >"$work/tasks.jsonl" + while IFS= read -r definition; do + aws ecs describe-task-definition --region us-east-1 --task-definition "$definition" --include TAGS >>"$work/definitions.jsonl" + done < <(jq -r '.services[].taskDefinition' "$work/services.json") + while IFS= read -r name; do + aws ecs list-tasks --region us-east-1 --cluster "$cluster" --service-name "$name" --desired-status RUNNING >"$work/task-list.json" + while IFS= read -r arn; do + aws ecs describe-tasks --region us-east-1 --cluster "$cluster" --tasks "$arn" >"$work/task.json" + jq -e '.failures == [] and (.tasks | length == 1)' "$work/task.json" >/dev/null + jq -c '.tasks[]' "$work/task.json" >>"$work/tasks.jsonl" + done < <(jq -r '.taskArns[]' "$work/task-list.json") + done < <(jq -r '.services[].serviceName' "$work/services.json") + : >"$work/manifests.jsonl" + while IFS= read -r image; do + [[ "$image" =~ ^ghcr.io/warmbly/warmbly/(backend|consumer|forms|tracking|realtime)@sha256:[a-f0-9]{64}$ ]] + docker buildx imagetools inspect "$image" --raw >"$work/manifest.json" + digest="sha256:$(sha256sum "$work/manifest.json" | cut -d' ' -f1)" + [ "$digest" = "${image##*@}" ] || { echo 'Registry manifest bytes differ from the pinned image' >&2; return 1; } + jq -n --arg image "$image" --arg digest "$digest" --slurpfile document "$work/manifest.json" \ + '{image:$image,digest:$digest,document:$document[0]}' >>"$work/manifests.jsonl" + done < <(jq -r '.taskDefinition.containerDefinitions[].image' "$work/definitions.jsonl" | sort -u) + aws elbv2 describe-target-groups --region us-east-1 >"$work/all-groups.json" + : >"$work/groups.jsonl" + while IFS= read -r arn; do + aws elbv2 describe-target-health --region us-east-1 --target-group-arn "$arn" >"$work/health.json" + jq -c --arg arn "$arn" --slurpfile health "$work/health.json" \ + '.TargetGroups[] | select(.TargetGroupArn == $arn) | . + {targets:$health[0].TargetHealthDescriptions}' \ + "$work/all-groups.json" >>"$work/groups.jsonl" + done < <(jq -r '.TargetGroups[] | select(.TargetGroupName | test("^warmbly-production-(backend|forms|tracking|realtime)(-tls)?$")) | .TargetGroupArn' "$work/all-groups.json") + arn=$(jq -er '[.resources[] | select(.mode=="managed" and .module==null and .type=="aws_lb" and .name=="main") | + .instances[].attributes.arn] | if length==1 then .[0] else error("load balancer identity") end' "$inputs/state.json") + aws elbv2 describe-listeners --region us-east-1 --load-balancer-arn "$arn" >"$work/listeners.json" + : >"$work/rules.jsonl" + while IFS= read -r arn; do + aws elbv2 describe-rules --region us-east-1 --listener-arn "$arn" | jq -c '.Rules[]' >>"$work/rules.jsonl" + done < <(jq -r '.Listeners[].ListenerArn' "$work/listeners.json") + : >"$work/security-groups.jsonl" + while IFS= read -r arn; do + aws ec2 describe-security-groups --region us-east-1 --group-ids "$arn" | jq -c '.SecurityGroups[]' >>"$work/security-groups.jsonl" + done < <(jq -r '.services[].networkConfiguration.awsvpcConfiguration.securityGroups[]' "$work/services.json" | sort -u) + aws cloudwatch describe-alarms --region us-east-1 --alarm-name-prefix warmbly-production- >"$work/alarms.json" + : >"$work/public.jsonl" + for url in https://api.warmbly.com/health https://api.warmbly.com/v1/auth/config https://forms.warmbly.com/health \ + https://realtime.warmbly.com/health https://track.monitorably.com/health; do + status=$(curl --silent --show-error --proto '=https' --tlsv1.2 --connect-timeout 10 --max-time 30 --output /dev/null --write-out '%{http_code}' "$url") + jq -n --arg url "$url" --argjson status "$status" '{url:$url,status:$status}' >>"$work/public.jsonl" + done + jq -n --slurpfile account "$work/account.json" --slurpfile services "$work/services.json" \ + --slurpfile definitions "$work/definitions.jsonl" --slurpfile tasks "$work/tasks.jsonl" \ + --slurpfile manifests "$work/manifests.jsonl" --slurpfile groups "$work/groups.jsonl" \ + --slurpfile listeners "$work/listeners.json" --slurpfile rules "$work/rules.jsonl" \ + --slurpfile securityGroups "$work/security-groups.jsonl" --slurpfile alarms "$work/alarms.json" --slurpfile public "$work/public.jsonl" \ + '{account:$account[0],services:$services[0],definitions:$definitions,tasks:$tasks,manifests:$manifests, + httpsGroups:[$groups[]|select(.Protocol=="HTTPS")],httpGroups:[$groups[]|select(.Protocol=="HTTP")], + listeners:$listeners[0].Listeners,rules:$rules,securityGroups:$securityGroups,alarms:$alarms[0],public:$public}' >"$work/candidate.json" + check_live "$work/candidate.json" "$baseline" "$inputs/snapshot.json" "$inputs/state.json" "$inputs/images.json" "$phase" + mv "$work/candidate.json" "$work/live.json" +} + +case "${1:-}" in + check) check_live "${2:?}" "${3:?}" "${4:?}" "${5:?}" "${6:?}" ;; + check-final) check_live "${2:?}" "${3:?}" "${4:?}" "${5:?}" "${6:?}" after ;; + collect) collect_live "${2:?}" "${3:?}" "${4:?}" ;; + collect-final) collect_live "${2:?}" "${3:?}" "${4:?}" after ;; + *) echo 'Only read-only recovery live checks and collection are supported' >&2; exit 1 ;; +esac diff --git a/.github/scripts/runtime-tls-recovery-live.test.sh b/.github/scripts/runtime-tls-recovery-live.test.sh new file mode 100755 index 000000000..c1d527edf --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-live.test.sh @@ -0,0 +1,137 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/../.." +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +guard=.github/scripts/runtime-tls-recovery-live.sh +printf '{"schemaVersion":2}\n' >"$work/manifest.json" +digest="sha256:$(sha256sum "$work/manifest.json" | cut -d' ' -f1)" +jq -n --arg digest "$digest" -f .github/scripts/runtime-tls-recovery-live.fixture.jq >"$work/fixture.json" +for kind in baseline state vars images live; do jq ".$kind" "$work/fixture.json" >"$work/$kind.json"; done +state_hash=$(sha256sum "$work/state.json" | cut -d' ' -f1) +vars_hash=$(sha256sum "$work/vars.json" | cut -d' ' -f1) +jq --arg state "$state_hash" --arg vars "$vars_hash" '.state.sha256=$state | .snapshot.sha256=$vars' "$work/baseline.json" >"$work/reviewed.json" +check() { bash "$guard" check "$1" "$work/reviewed.json" "$work/vars.json" "$work/state.json" "$work/images.json"; } +check "$work/live.json" +for change in \ + '.account.Account="123456789012"' '.services.failures=[{}]' '.services.services|=.[1:]' \ + '.services.services[0].clusterArn="other-cluster"' '.services.services[0].serviceArn="other-service"' \ + '.services.services[0].desiredCount=0' '.services.services[0].runningCount=0' '.services.services[0].pendingCount=1' \ + '.services.services[0].deployments[0].rolloutState="IN_PROGRESS"' '.services.services[0].deployments+=.services.services[0].deployments' \ + '.services.services[0].loadBalancers[0].targetGroupArn="other-group"' \ + '.services.services[0].networkConfiguration.awsvpcConfiguration.securityGroups+=["sg-extra"]' \ + '.definitions[0].tags[0].value="v1.2.2"' '.definitions[0].taskDefinition.containerDefinitions[0].image="other-image"' \ + '.definitions[0].taskDefinition.containerDefinitions[0].secrets=[{name:"SERVE_TLS",valueFrom:"other"}]' \ + '.definitions[0].taskDefinition.containerDefinitions[0].environmentFiles=[{value:"other"}]' \ + '.definitions[0].taskDefinition.containerDefinitions[0].environment[2].value="false"' \ + '.definitions[0].taskDefinition.containerDefinitions[0].environment[0].value="self-signed"' \ + '.definitions[0].taskDefinition.containerDefinitions[0].environment[3].value="other-cert"' \ + '.definitions[2].taskDefinition.containerDefinitions[0].environment[4].value="other-ca"' \ + '.definitions[2].taskDefinition.containerDefinitions[0].environment[3].value="http://backend.warmbly.internal:8080"' \ + '.tasks|=.[1:]' '.tasks+=.tasks' '.tasks[0].taskDefinitionArn="older-definition"' \ + '.tasks[0].healthStatus="UNHEALTHY"' '.tasks[0].containers[0].imageDigest="sha256:other"' \ + '.tasks[1].healthStatus="UNHEALTHY"' '.tasks[1].containers[0].lastStatus="STOPPED"' \ + '.tasks[0].overrides.containerOverrides=[{environment:[{name:"SERVE_TLS",value:"off"}]}]' \ + '.httpsGroups|=.[1:]' '.httpsGroups[0].Protocol="HTTP"' '.httpsGroups[0].targets=[]' \ + '.httpsGroups[0].targets[0].TargetHealth.State="unhealthy"' '.httpsGroups[0].LoadBalancerArns=[]' \ + '.httpsGroups[0].targets[0].Target.Id="10.0.0.2"' \ + '.httpGroups[0].targets=[{}]' '.httpGroups[0].LoadBalancerArns=["other-lb"]' '.httpGroups[0].TargetGroupArn="other-group"' \ + '.listeners[0].Protocol="HTTP"' '.listeners[0].Port=80' '.rules|=.[1:]' \ + '.rules[0].Actions[0].TargetGroupArn=.httpGroups[0].TargetGroupArn' \ + '.rules[0].Actions[0].ForwardConfig.TargetGroups=[{TargetGroupArn:.httpGroups[0].TargetGroupArn,Weight:0}]' \ + '.rules[0].Conditions[0].HostHeaderConfig.Values=["other.example.com"]' \ + '.rules[0].Transforms=[{}]' '.securityGroups=[]' \ + '.securityGroups[0].IpPermissions+=[{IpProtocol:"tcp",FromPort:8080,ToPort:8080}]' \ + '.securityGroups[0].IpPermissions+=[{IpProtocol:"-1"}]' \ + '.alarms.MetricAlarms|=.[1:]' '.alarms.MetricAlarms[0].StateValue="ALARM"' \ + '.alarms.MetricAlarms[0].StateValue="INSUFFICIENT_DATA"' '.public[0].status=503' '.public|=.[1:]'; do + jq "$change" "$work/live.json" >"$work/changed.json" + if check "$work/changed.json" 2>/dev/null; then + echo "Recovery accepted incompatible live evidence: $change" >&2; exit 1 + fi +done +jq '.alarms.MetricAlarms[0].Dimensions[0].Value="targetgroup/old-http/0000000000000000"' "$work/live.json" >"$work/changed.json" +if check "$work/changed.json" 2>/dev/null; then echo 'Recovery accepted an alarm on a different target group' >&2; exit 1; fi +jq '.alarms.MetricAlarms[] |= (.Metrics=[{MetricStat:{Metric:{Dimensions:.Dimensions}}}] | del(.Dimensions))' "$work/live.json" >"$work/metric-math.json" +check "$work/metric-math.json" +jq --arg digest "$digest" '.tasks[].containers[0].imageDigest="sha256:platform" | + .manifests[].document={manifests:[{digest:"sha256:platform",platform:{os:"linux",architecture:"amd64"}}]}' \ + "$work/live.json" >"$work/multiarch.json" +check "$work/multiarch.json" +jq --arg digest "$digest" '.tasks[].containers[0].imageDigest=$digest' "$work/multiarch.json" >"$work/index-reported.json" +check "$work/index-reported.json" +jq '.manifests[].document.manifests[0].platform.architecture="arm64"' "$work/multiarch.json" >"$work/changed.json" +if check "$work/changed.json" 2>/dev/null; then echo 'Recovery accepted another platform manifest' >&2; exit 1; fi +jq '.httpGroups=[]' "$work/live.json" >"$work/final.json" +bash "$guard" check-final "$work/final.json" "$work/reviewed.json" "$work/vars.json" "$work/state.json" "$work/images.json" +if bash "$guard" check-final "$work/live.json" "$work/reviewed.json" "$work/vars.json" "$work/state.json" "$work/images.json" 2>/dev/null; then + echo 'Recovery final check accepted retained HTTP groups' >&2; exit 1 +fi +mkdir "$work/bin" "$work/inputs" +cp "$work/state.json" "$work/images.json" "$work/inputs/" +cp "$work/vars.json" "$work/inputs/snapshot.json" +cat >"$work/bin/aws" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +printf '%s\n' "$*" >>"$FIXTURES/requests.log" +service=$1 operation=$2 +shift 2 +region= definition= name= arn= +while [ "$#" -gt 0 ]; do + case "$1" in + --region) region=$2; shift 2 ;; + --task-definition) definition=$2; shift 2 ;; + --service-name) name=$2; shift 2 ;; + --tasks|--target-group-arn) arn=$2; shift 2 ;; + *) shift ;; + esac +done +[ "$region" = us-east-1 ] +[ "${MODE:-}" != api-failure ] || [ "$service $operation" != 'ecs describe-tasks' ] || exit 1 +case "$service $operation" in + 'sts get-caller-identity') + if [ "${MODE:-}" = account ]; then echo '{"Account":"123456789012"}'; else jq '.account' "$FIXTURES/live.json"; fi ;; + 'ecs describe-services') jq '.services' "$FIXTURES/live.json" ;; + 'ecs describe-task-definition') jq --arg definition "$definition" '.definitions[] | select(.taskDefinition.taskDefinitionArn==$definition)' "$FIXTURES/live.json" ;; + 'ecs list-tasks') jq --arg name "$name" '{taskArns:[.tasks[]|select(.group==("service:"+$name))|.taskArn]}' "$FIXTURES/live.json" ;; + 'ecs describe-tasks') jq --arg arn "$arn" '{failures:[],tasks:[.tasks[]|select(.taskArn==$arn)]}' "$FIXTURES/live.json" ;; + 'elbv2 describe-target-groups') + if [ "${MODE:-}" = final ]; then jq '{TargetGroups:.httpsGroups}' "$FIXTURES/live.json" + else jq '{TargetGroups:(.httpsGroups+.httpGroups)}' "$FIXTURES/live.json"; fi ;; + 'elbv2 describe-target-health') + jq --arg arn "$arn" '{TargetHealthDescriptions:[(.httpsGroups+.httpGroups)[]|select(.TargetGroupArn==$arn)|.targets[]]}' "$FIXTURES/live.json" ;; + 'elbv2 describe-listeners') jq '{Listeners:.listeners}' "$FIXTURES/live.json" ;; + 'elbv2 describe-rules') jq '{Rules:.rules}' "$FIXTURES/live.json" ;; + 'ec2 describe-security-groups') jq '{SecurityGroups:.securityGroups}' "$FIXTURES/live.json" ;; + 'cloudwatch describe-alarms') jq '.alarms' "$FIXTURES/live.json" ;; + *) echo 'Unexpected AWS operation in read-only collector' >&2; exit 1 ;; +esac +SH +cat >"$work/bin/docker" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +[[ "$*" == 'buildx imagetools inspect ghcr.io/warmbly/warmbly/'*' --raw' ]] +cat "$FIXTURES/manifest.json" +if [ "${MODE:-}" = manifest ]; then printf '\n'; fi +SH +cat >"$work/bin/curl" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +[[ "$*" == *"--proto =https --tlsv1.2"* && "$*" != *insecure* ]] +if [ "${MODE:-}" = public ]; then printf '503'; else printf '200'; fi +SH +chmod +x "$work/bin/aws" "$work/bin/docker" "$work/bin/curl" +PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/reviewed.json" "$work/inputs" "$work/collected" +check "$work/collected/live.json" +PATH="$work/bin:$PATH" FIXTURES="$work" MODE=final bash "$guard" collect-final "$work/reviewed.json" "$work/inputs" "$work/final-collected" +for mode in account api-failure manifest public; do + if PATH="$work/bin:$PATH" FIXTURES="$work" MODE=$mode bash "$guard" collect "$work/reviewed.json" "$work/inputs" "$work/$mode" 2>/dev/null; then + echo "Recovery collector accepted failed read-only evidence: $mode" >&2; exit 1 + fi + [ ! -e "$work/$mode/live.json" ] +done +if PATH="$work/bin:$PATH" FIXTURES="$work" bash "$guard" collect "$work/reviewed.json" "$work/inputs" "$work/collected" 2>/dev/null; then + echo 'Recovery collector overwrote an earlier collection' >&2; exit 1 +fi +if bash "$guard" apply 2>/dev/null; then echo 'Live collector accepted execution' >&2; exit 1; fi +echo 'Recovery live service, TLS, traffic, health and platform checks passed' diff --git a/.github/scripts/runtime-tls-recovery-workflow.test.sh b/.github/scripts/runtime-tls-recovery-workflow.test.sh new file mode 100755 index 000000000..dd64c8379 --- /dev/null +++ b/.github/scripts/runtime-tls-recovery-workflow.test.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/../.." +ruby -ryaml <<'RUBY' +workflow = YAML.load_file('.github/workflows/runtime-tls-recovery.yml') +jobs = workflow.fetch('jobs') +plan, apply, redeploy, verify = jobs.values_at('plan', 'apply', 'redeploy', 'verify') +raise 'plan must be manual and depend on offline checks' unless plan['if'] == "github.event_name == 'workflow_dispatch'" && plan['needs'] == 'check' +raise 'plan must use the read-only environment' unless plan['environment'] == 'aws-infrastructure-plan' +entry = plan.fetch('steps').first +raise 'explicit enablement and new main run are required' unless entry.fetch('run').include?('[ "$RECOVERY_ENABLED" = true ]') && entry.fetch('run').include?('[ "$GITHUB_RUN_ATTEMPT" = 1 ]') && entry.fetch('run').include?('[ "$GITHUB_REF" = refs/heads/main ]') +raise 'apply must follow plan approval' unless apply['needs'] == 'plan' && apply['environment'] == 'aws-infrastructure-approval' +raise 'apply must compare the exact plan approval digest' unless apply['steps'].any? { |s| s.dig('env', 'APPROVED_DIGEST') == '${{ needs.plan.outputs.digest }}' } +[apply, verify].each do |job| + raise 'production serialization must be retained' unless job.dig('concurrency', 'group') == 'aws-production' && job.dig('concurrency', 'cancel-in-progress') == false +end +raise 'redeploy must follow both plan and apply' unless redeploy['needs'].sort == ['apply', 'plan'] +raise 'redeploy must use the normal local workflow' unless redeploy['uses'] == './.github/workflows/deploy-aws.yml' +expected = {'tag'=>'${{ needs.plan.outputs.release }}', 'mode'=>'redeploy', 'services'=>'all', 'fleet'=>false, 'require_attestation'=>true, 'bake_seconds'=>'300'} +raise 'same release, all services, provenance and full bakes are required without fleet or secret-drop overrides' unless redeploy['with'] == expected +raise 'final verification must follow redeploy' unless verify['needs'] == 'redeploy' && verify['environment'] == 'aws-infrastructure-plan' +jobs.each_value do |job| + raise 'recovery cannot ignore job failures' if job['continue-on-error'] + (job['steps'] || []).each { |step| raise 'recovery cannot ignore step failures' if step['continue-on-error'] } +end +deploy = YAML.load_file('.github/workflows/deploy-aws.yml') +call = (deploy['on'] || deploy[true]).fetch('workflow_call') +raise 'existing deployment defaults must be retained' unless call.dig('inputs', 'bake_seconds', 'default') == '' +raise 'dropped-secret allowance remains disabled by default' if call.fetch('inputs').key?('allow_dropped_secrets') +puts 'Recovery workflow approval, sequencing, deployment and default compatibility checks passed' +RUBY diff --git a/.github/workflows/deploy-aws.yml b/.github/workflows/deploy-aws.yml index b2fcf3528..77ef77af1 100644 --- a/.github/workflows/deploy-aws.yml +++ b/.github/workflows/deploy-aws.yml @@ -26,6 +26,10 @@ on: description: Refuse images without build provenance (only releases before provenance need false) default: true type: boolean + bake_seconds: + description: Optional explicit service bake duration; empty retains the configured default + default: "" + type: string workflow_dispatch: inputs: tag: diff --git a/.github/workflows/runtime-tls-recovery.yml b/.github/workflows/runtime-tls-recovery.yml new file mode 100644 index 000000000..2509b3771 --- /dev/null +++ b/.github/workflows/runtime-tls-recovery.yml @@ -0,0 +1,199 @@ +name: Recover partial runtime TLS cleanup +run-name: Reviewed partial runtime TLS cleanup + +on: + pull_request: + paths: + - '.github/workflows/runtime-tls-recovery.yml' + - '.github/workflows/deploy-aws.yml' + - '.github/scripts/runtime-tls*' + workflow_dispatch: + inputs: + contract_key: + description: New private reviewed recovery contract key under runtime-tls-recovery/ + required: true + type: string + contract_version: + description: Exact version ID of the reviewed contract + required: true + type: string + contract_sha256: + description: SHA-256 of the exact reviewed contract bytes + required: true + type: string + +permissions: + contents: read + +env: + AWS_REGION: us-east-1 + TF_IN_AUTOMATION: "1" + TF_INPUT: "0" + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - run: shellcheck .github/scripts/runtime-tls*.sh + - run: | + for suite in .github/scripts/runtime-tls*.test.sh; do + bash "$suite" + done + + plan: + needs: check + if: github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + environment: aws-infrastructure-plan + permissions: + contents: read + actions: read + attestations: read + id-token: write + outputs: + digest: ${{ steps.plan.outputs.digest }} + release: ${{ steps.plan.outputs.release }} + steps: + - name: Require an explicitly enabled new main run + env: + RECOVERY_ENABLED: ${{ vars.AWS_TLS_RECOVERY_ENABLED }} + EVIDENCE_ROLE: ${{ vars.AWS_TLS_RECOVERY_EVIDENCE_ROLE_ARN }} + run: | + [ "$GITHUB_REF" = refs/heads/main ] + [ "$GITHUB_RUN_ATTEMPT" = 1 ] + [ "$RECOVERY_ENABLED" = true ] + [ "$EVIDENCE_ROLE" = arn:aws:iam::925323749693:role/warmbly-production-tls-recovery-evidence ] + - uses: actions/checkout@v4 + with: + persist-credentials: false + fetch-depth: 0 + - uses: hashicorp/setup-terraform@v3 + with: + terraform_version: "1.16.5" + terraform_wrapper: false + - uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: ${{ vars.AWS_TERRAFORM_PLAN_ROLE_ARN }} + aws-region: us-east-1 + - id: plan + env: + WORK: ${{ runner.temp }}/runtime-tls-recovery-plan + CONTRACT_KEY: ${{ inputs.contract_key }} + CONTRACT_VERSION: ${{ inputs.contract_version }} + CONTRACT_SHA256: ${{ inputs.contract_sha256 }} + GH_TOKEN: ${{ github.token }} + run: bash .github/scripts/runtime-tls-recovery-execute.sh plan + - uses: aws-actions/configure-aws-credentials@v4 + if: always() && steps.plan.outcome != 'skipped' + with: + role-to-assume: ${{ vars.AWS_TLS_RECOVERY_EVIDENCE_ROLE_ARN }} + aws-region: us-east-1 + - name: Preserve full private plan evidence + if: always() && steps.plan.outcome != 'skipped' + env: + WORK: ${{ runner.temp }}/runtime-tls-recovery-plan + run: bash .github/scripts/runtime-tls-recovery-archive.sh plan + + apply: + needs: plan + runs-on: ubuntu-latest + environment: aws-infrastructure-approval + concurrency: + group: aws-production + cancel-in-progress: false + permissions: + contents: read + actions: read + attestations: read + id-token: write + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + fetch-depth: 0 + - uses: hashicorp/setup-terraform@v3 + with: + terraform_version: "1.16.5" + terraform_wrapper: false + - uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: ${{ vars.AWS_TERRAFORM_APPLY_ROLE_ARN }} + aws-region: us-east-1 + - id: apply + env: + WORK: ${{ runner.temp }}/runtime-tls-recovery-apply + CONTRACT_KEY: ${{ inputs.contract_key }} + CONTRACT_VERSION: ${{ inputs.contract_version }} + CONTRACT_SHA256: ${{ inputs.contract_sha256 }} + APPROVED_DIGEST: ${{ needs.plan.outputs.digest }} + GH_TOKEN: ${{ github.token }} + run: bash .github/scripts/runtime-tls-recovery-execute.sh apply + - uses: aws-actions/configure-aws-credentials@v4 + if: always() && steps.apply.outcome != 'skipped' + with: + role-to-assume: ${{ vars.AWS_TLS_RECOVERY_EVIDENCE_ROLE_ARN }} + aws-region: us-east-1 + - name: Preserve full private apply evidence + if: always() && steps.apply.outcome != 'skipped' + env: + WORK: ${{ runner.temp }}/runtime-tls-recovery-apply + run: bash .github/scripts/runtime-tls-recovery-archive.sh apply + + redeploy: + needs: [plan, apply] + permissions: + contents: read + id-token: write + attestations: read + uses: ./.github/workflows/deploy-aws.yml + with: + tag: ${{ needs.plan.outputs.release }} + mode: redeploy + services: all + fleet: false + require_attestation: true + bake_seconds: "300" + secrets: inherit + + verify: + needs: redeploy + runs-on: ubuntu-latest + environment: aws-infrastructure-plan + concurrency: + group: aws-production + cancel-in-progress: false + permissions: + contents: read + actions: read + attestations: read + id-token: write + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + fetch-depth: 0 + - uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: ${{ vars.AWS_TERRAFORM_PLAN_ROLE_ARN }} + aws-region: us-east-1 + - id: verify + env: + WORK: ${{ runner.temp }}/runtime-tls-recovery-verify + CONTRACT_KEY: ${{ inputs.contract_key }} + CONTRACT_VERSION: ${{ inputs.contract_version }} + CONTRACT_SHA256: ${{ inputs.contract_sha256 }} + GH_TOKEN: ${{ github.token }} + run: bash .github/scripts/runtime-tls-recovery-execute.sh verify + - uses: aws-actions/configure-aws-credentials@v4 + if: always() && steps.verify.outcome != 'skipped' + with: + role-to-assume: ${{ vars.AWS_TLS_RECOVERY_EVIDENCE_ROLE_ARN }} + aws-region: us-east-1 + - name: Preserve full private final evidence + if: always() && steps.verify.outcome != 'skipped' + env: + WORK: ${{ runner.temp }}/runtime-tls-recovery-verify + run: bash .github/scripts/runtime-tls-recovery-archive.sh verify diff --git a/docs/content/docs/development/aws-fargate.mdx b/docs/content/docs/development/aws-fargate.mdx index 8b971aa1f..5cfa3de09 100644 --- a/docs/content/docs/development/aws-fargate.mdx +++ b/docs/content/docs/development/aws-fargate.mdx @@ -449,9 +449,8 @@ effective loopback listeners and HTTPS routes. ### Validate recovery evidence -The read-only recovery validators keep a recovery contract separate from the -normal route, drain and on transition checks. They do not provide a production -recovery execution workflow. The baseline identifies four drained HTTP groups +The recovery validators keep a recovery contract separate from the normal +route, drain and on transition checks. The baseline identifies four drained HTTP groups and their reviewed state projection. `check-state` verifies a supplied raw Terraform state file against the baseline SHA-256, lineage, serial and exact group identities. `check-plan` permits only the four corresponding deletions @@ -486,12 +485,96 @@ private. Its `inputs.json` binds the selected versions and hashes; it does not establish that the declared release matches the live services or that those services are healthy. -These checks neither relabel an earlier release's drain nor change the normal -workflow's predecessor requirements. A complete recovery workflow must also -collect current service, TLS, route and target health, bind the immutable vars -snapshot and state version, and preserve separate protected approval, production -serialization, plan digest comparison, attested redeployment and final effective -verification. Do not use these validators as an alternative to those gates. +`runtime-tls-recovery-live.sh` collects current service and task descriptions, +target health, listener rules, task security groups, alarms and public health +responses. The reviewed raw state identifies the five services, four HTTPS +groups, listener, nine forwarding rules and task security groups. All services +must be stable with running tasks on the declared release's digest-pinned +images. The four HTTP services require healthy tasks. A consumer definition +without a health check has the explicit ECS `UNKNOWN` status rather than a +synthetic healthy result. Registry manifest bytes are checked against their digest. +A task may report the pinned index digest or its matching Linux platform digest; +an index must contain the task definition's CPU architecture. An index report +does not independently identify the resolved platform digest. The collector requires configured TLS, +loopback-only HTTP, the reviewed backend certificate and pinned forms and tracking +backend URL and CA. HTTPS targets must match running task addresses. It also +requires nine HTTPS-only forwarding rules, no task ingress on the old HTTP ports, +eight OK alarms and five HTTP 200 public responses. These observations verify +configuration and health at collection time; they do not replace inspection of +deployment logs or independent internal certificate-handshake evidence. + +### Review and run partial cleanup + +`runtime-tls-recovery.yml` is a separate manual recovery path. Normal TLS stage +and predecessor checks remain unchanged. It never relabels an earlier release's +drain, creates a release or starts a worker rollout. Existing self-host deployment +and upgrade paths are unaffected. + +The recovery contract combines the baseline, S3 input and workflow-lineage +fields above. Its `release.imagesSha256` binds the exact published `images.json` +bytes. `planChangesSha256` binds the complete privately reviewed plan changes, +including read and no-op entries and refresh drift. Calculate this hash from +the private candidate plan with: + +```sh +jq -cS '{resource_changes:(.resource_changes | sort_by(.address)),resource_drift:(.resource_drift // [] | sort_by(.address))}' \ + private-plan.json | sha256sum +``` + +The private full plan must be inspected before this hash is accepted. Keep it, +the contract, state and vars outside the checkout and public workflow artifacts. +The workflow publishes only hashes and a scope summary. A dedicated evidence +role archives complete runner files, including raw collections and Terraform +logs, to a new private S3 object after each plan, apply and final verification, +including failed attempts. Archives require encryption, checksum agreement, +versioning and conditional creation without replacement. Archive failure blocks +the next job. No raw evidence is uploaded to public workflow artifacts. + +Store the reviewed contract at a new key under +`warmbly/production/vars/runtime-tls-recovery/` ending in `.contract.json`. +Dispatch accepts its exact key, S3 version and file SHA-256. Repository variable +`AWS_TLS_RECOVERY_ENABLED=true` explicitly enables this hosted-only path; it is +disabled when unset. The approval environment must have required reviewers, +prevent self-review and disallow administrator bypass. Missing configuration or +unavailable environment metadata stops recovery. No role or environment policy +is changed by the workflow. + +Before enabling recovery, provision and review the dedicated +`warmbly-production-tls-recovery-evidence` role through the normal infrastructure +approval process, then set `AWS_TLS_RECOVERY_EVIDENCE_ROLE_ARN` to its ARN in +account `925323749693`. Its OIDC trust permits only this repository's +`aws-infrastructure-plan` and `aws-infrastructure-approval` environments. Grant +only `s3:PutObject` on +`warmbly-terraform-use1-925323749693/warmbly/production/diagnostics/runtime-tls-recovery/*`, +requiring AES256 server-side encryption. It needs no object read/delete or +production management permissions. The existing plan role's state-lock-only +write policy remains unchanged. The workflow refuses a missing or differently +named evidence role; it does not create or grant permissions to that role. + +Plan and apply each re-collect exact workflow lineage, versioned S3 inputs and +fresh live evidence. All ten published image variants require release-workflow +provenance for the declared source commit. The only Terraform target is +`aws_lb_target_group.service`, and the only permitted mutations are exactly four +reviewed HTTP group deletions. Complete changes must match the contract's hash. +Approval binds that hash, the exact contract bytes and workflow source. Apply +uses `aws-infrastructure-approval` and the existing `aws-production` concurrency +group, replans after approval and repeats live checks immediately before applying +the saved plan. State advancement or any digest mismatch stops the run. + +After apply, state must retain every other resource unchanged and AWS must have +no matching HTTP groups. A same-release redeploy uses the normal attested +deployment path for all five services with explicit 300-second bakes, migration +and secret checks, dropped-secret allowance disabled and `fleet=false`. The final +job repeats state and live checks. Its `collect-archived` input mode reads the +original reviewed state version solely for comparison with the new state; normal +plan and apply collection still requires the reviewed state to be latest. + +Workflow reruns and local execution are refused. After a failure, inspect the +private plan, state and logs and prepare a new reviewed recovery contract rather +than retrying unchanged. Workflow success does not itself update a local TLS +stage or attest worker broker credentials. Inspect actual provenance, migration +and bake logs, preserve independent TLS and worker proof, and verify effective +production state before recording ON as complete. ## One-time GitHub setup From 2ce0a76b42c2fcb414a8f690172ec1c1afeb9437 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sun, 1 Nov 2026 13:33:23 +0100 Subject: [PATCH 067/318] feat: express the partial TLS recovery context gate with explicit conditional control flow --- .github/scripts/runtime-tls-recovery-execute.sh | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/.github/scripts/runtime-tls-recovery-execute.sh b/.github/scripts/runtime-tls-recovery-execute.sh index 91cead7ec..52c05df0b 100755 --- a/.github/scripts/runtime-tls-recovery-execute.sh +++ b/.github/scripts/runtime-tls-recovery-execute.sh @@ -13,13 +13,15 @@ check_contract() { } check_context() { - [ "${GITHUB_ACTIONS:-}" = true ] && [ "${GITHUB_REPOSITORY:-}" = warmbly/warmbly ] && + if [ "${GITHUB_ACTIONS:-}" = true ] && [ "${GITHUB_REPOSITORY:-}" = warmbly/warmbly ] && [ "${GITHUB_REF:-}" = refs/heads/main ] && [ "${GITHUB_EVENT_NAME:-}" = workflow_dispatch ] && [ "${GITHUB_WORKFLOW_REF:-}" = warmbly/warmbly/.github/workflows/runtime-tls-recovery.yml@refs/heads/main ] && - [ "${GITHUB_RUN_ATTEMPT:-}" = 1 ] && [[ "${GITHUB_RUN_ID:-}" =~ ^[1-9][0-9]*$ ]] || { - echo 'Recovery execution requires a new protected main workflow run; reruns are refused' >&2; return 1; - } - [ "${GITHUB_SHA:?}" = "$(git rev-parse HEAD)" ] + [ "${GITHUB_RUN_ATTEMPT:-}" = 1 ] && [[ "${GITHUB_RUN_ID:-}" =~ ^[1-9][0-9]*$ ]]; then + [ "${GITHUB_SHA:?}" = "$(git rev-parse HEAD)" ] + return + fi + echo 'Recovery execution requires a new protected main workflow run; reruns are refused' >&2 + return 1 } check_approval_environment() { From 69ff9b06c50fe59a2043c85e3235a45e0039aa20 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sun, 1 Nov 2026 13:42:35 +0100 Subject: [PATCH 068/318] feat: keep cached mailbox errors unconfirmed and campaign counts scoped to the current UTC day --- docs/content/docs/guides/mailboxes.mdx | 2 +- web/src/app/app/emails/page.test.tsx | 59 ++++++++++++++++++++++++-- web/src/app/app/emails/page.tsx | 35 +++++++++------ 3 files changed, 78 insertions(+), 18 deletions(-) diff --git a/docs/content/docs/guides/mailboxes.mdx b/docs/content/docs/guides/mailboxes.mdx index f347ed345..b52f56f0c 100644 --- a/docs/content/docs/guides/mailboxes.mdx +++ b/docs/content/docs/guides/mailboxes.mdx @@ -642,7 +642,7 @@ The Accounts list groups mailboxes as **Healthy** (sending normally), **Warming* Repeated reports of the same error code count once toward the health score, at their highest unresolved severity, rather than making one problem look like several. The drawer groups identical reports while keeping different error details and sending versus sync failures separate. Connection titles name Gmail, Microsoft Outlook or the mail server. **Reported** shows the stored report time: connection and temporary provider-limit observations refresh it, while other error categories may retain their original report time. It is not proof of an ongoing outage. -While visible, the Accounts list and mailbox drawer refresh their health and error reports every minute as well as on relevant live events. Returning to a tab refreshes stale reports too. The list keeps cached row measurements during a refresh or after a failed read, marked **Last observed**. A retained issue stays visible until a fresh successful result confirms recovery. These reads show the server's latest recovery evidence; they do not reconnect a mailbox or retry a send. A failed status refresh does not count as recovery. +While visible, the Accounts list and mailbox drawer refresh their health and error reports every minute as well as on relevant live events. Returning to a tab refreshes stale reports too. The list keeps cached row measurements during a refresh or after a failed read, marked **Last observed**, including cached **Error** and **Retrying** statuses. A recent issue is highlighted as **Last reported issue** for up to five minutes while recovery is unconfirmed; older cached reports remain marked **Last observed**. **Sent today** only shows campaign usage reported for the current UTC day. After the daily reset, an older count is withheld until today's usage arrives. These reads show the server's latest recovery evidence; they do not reconnect a mailbox or retry a send. A failed status refresh does not count as recovery. A later completed sync automatically clears earlier temporary sync errors. A provider-confirmed send clears earlier temporary sending errors, including provider throttling and quota warnings. Recovered reports no longer appear under **Needs attention** or reduce the health score. Older reports that do not identify which operation failed clear once both sending and sync have succeeded after the report; existing reports with that evidence are cleared on upgrade too. A newer failure remains visible, and simply waiting or completing a queued task does not count as recovery. Recoverable connection failures retry automatically while the mailbox is on; a connection warning alone is not a reason to reconnect. A temporary connection, server or throttling failure is not shown at all while the affected sync or sending has still succeeded within the last two hours, because the mailbox is working. It appears only when the failure lasts longer than that. Authentication, credential and policy errors retain their own instructions, and a switched-off mailbox must be switched back on before it can retry. diff --git a/web/src/app/app/emails/page.test.tsx b/web/src/app/app/emails/page.test.tsx index 29f2cad7e..b33c52f2d 100644 --- a/web/src/app/app/emails/page.test.tsx +++ b/web/src/app/app/emails/page.test.tsx @@ -6,6 +6,7 @@ import type Inbox from "@/lib/api/models/app/emails/Inbox"; import type Tag from "@/lib/api/models/app/Tag"; import type * as UserModule from "@/hooks/context/user"; import type AccountStatus from "@/lib/api/models/app/analytics/AccountStatus"; +import { utcToday } from "@/lib/campaignPeriod"; import AddressesPage from "./page"; const { tags, rows, statusState, confirm } = vi.hoisted(() => ({ @@ -74,7 +75,7 @@ function orderedEmails() { } function measuredStatus(row: Inbox): AccountStatus { - return { id: row.id, email: row.email, provider: "gmail", status: "active", last_synced_at: null, health: { status: "healthy", score: 100 }, errors: [], daily_usage: { date: "2026-10-09", campaign_sent: 0, campaign_limit: 50 }, in_campaign: false }; + return { id: row.id, email: row.email, provider: "gmail", status: "active", last_synced_at: null, health: { status: "healthy", score: 100 }, errors: [], daily_usage: { date: utcToday(), campaign_sent: 0, campaign_limit: 50 }, in_campaign: false }; } describe("mailbox ordering with a tag filter", () => { @@ -229,7 +230,7 @@ describe("mailbox status while account and Cloud checks settle", () => { it.each(["isFetching", "isError"] as const)("retains cached row metrics and marks only unconfirmed chunks stale during %s", async (state) => { statusState.data = rows.map(measuredStatus); - statusState.data[0].daily_usage = { date: "2026-11-01", campaign_sent: 7, campaign_limit: 50 }; + statusState.data[0].daily_usage = { date: utcToday(), campaign_sent: 7, campaign_limit: 50 }; statusState.observations = statusState.data.map((status) => ({ status, observedAt: Date.now(), current: true })); await renderPage(); @@ -247,6 +248,49 @@ describe("mailbox status while account and Cloud checks settle", () => { expect(within(kavya!).queryByText("Last observed: Healthy 100")).not.toBeInTheDocument(); }); + it("withholds prior-day campaign totals after UTC midnight until current usage arrives", async () => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(new Date("2026-11-01T19:59:59-04:00")); + try { + statusState.data = rows.map(measuredStatus); + statusState.data[0].daily_usage = { date: "2026-11-01", campaign_sent: 49, campaign_limit: 50 }; + await renderPage(); + expect(screen.getByTitle("49 of 50 campaign emails sent today")).toBeInTheDocument(); + + vi.setSystemTime(new Date("2026-11-01T20:00:01-04:00")); + statusState.isError = true; + statusState.data = statusState.data.map((status) => status.id === rows[1].id ? { ...status, daily_usage: { date: "2026-11-02", campaign_sent: 2, campaign_limit: 50 } } : status); + fireEvent.click(screen.getByRole("button", { name: /^Sent today/ })); + expect(screen.queryByTitle("49 of 50 campaign emails sent today")).not.toBeInTheDocument(); + expect(screen.getByTitle("2 of 50 campaign emails sent today")).toBeInTheDocument(); + expect(orderedEmails()[0]).toBe(rows[1].email); + expect(statusState.data[0].daily_usage?.campaign_sent).toBe(49); + + statusState.isError = false; + statusState.data = [{ ...measuredStatus(rows[0]), daily_usage: { date: "2026-11-02", campaign_sent: 1, campaign_limit: 50 } }]; + fireEvent.click(screen.getByRole("button", { name: "Mailbox" })); + expect(screen.getByTitle("1 of 50 campaign emails sent today")).toBeInTheDocument(); + } finally { + vi.useRealTimers(); + } + }); + + it.each(["revoked", "inactive"])("keeps inventory %s status authoritative when account measurements are stale", async (status) => { + const original = rows[0].status; + rows[0].status = status; + try { + statusState.data = rows.map(measuredStatus); + statusState.isError = true; + await renderPage(); + const mailbox = within(screen.getByText(rows[0].email).closest("tr")!); + const label = status === "revoked" ? "Reconnect" : "Off"; + expect(mailbox.getAllByText(label).length).toBeGreaterThan(0); + expect(mailbox.queryByText(`Last observed: ${label}`)).not.toBeInTheDocument(); + } finally { + rows[0].status = original; + } + }); + it("keeps a retained issue ahead of cached healthy data until a fresh recovery arrives", async () => { const failed = { ...measuredStatus(rows[0]), health: { status: "error", score: 40 } } satisfies AccountStatus; statusState.data = [failed]; @@ -309,9 +353,12 @@ describe("mailbox status while account and Cloud checks settle", () => { expect(screen.getAllByText("Healthy 100").length).toBeGreaterThan(0); }); - it("expires an old unverified issue rather than displaying it indefinitely", async () => { + it.each([ + { severity: "critical", health: "error", label: "Error" }, + { severity: "warning", health: "warning", label: "Retrying" }, + ] as const)("keeps expired cached $label reports visibly unconfirmed", async ({ severity, health, label }) => { statusState.data = rows.map(measuredStatus); - statusState.data[0] = { ...measuredStatus(rows[0]), health: { status: "error", score: 40 }, errors: [{ id: "error-1", error_code: "PROVIDER_UNAVAILABLE", severity: "critical", title: "Provider unavailable", message: "Provider refused the last attempt", created_at: new Date("2026-10-09T00:00:00Z") }] }; + statusState.data[0] = { ...measuredStatus(rows[0]), health: { status: health, score: 40 }, errors: [{ id: "error-1", error_code: "PROVIDER_UNAVAILABLE", severity, title: "Provider unavailable", message: "Provider refused the last attempt", created_at: new Date("2026-10-09T00:00:00Z") }] }; const observedAt = Date.now(); statusState.observations = statusState.data.map((status) => ({ status, observedAt, current: true })); await renderPage(); @@ -322,6 +369,10 @@ describe("mailbox status while account and Cloud checks settle", () => { const clock = vi.spyOn(Date, "now").mockReturnValue(observedAt + 5 * 60_000 + 1); fireEvent.click(screen.getByRole("button", { name: "Mailbox" })); expect(screen.queryAllByText("Last reported issue")).toHaveLength(0); + const mailbox = within(screen.getByText(rows[0].email).closest("tr")!); + expect(mailbox.getAllByText(`Last observed: ${label}`).length).toBeGreaterThan(0); + expect(mailbox.queryByText(label)).not.toBeInTheDocument(); + expect(mailbox.getAllByTitle("Last observed: Provider unavailable. Current status unconfirmed.").length).toBeGreaterThan(0); clock.mockRestore(); }); diff --git a/web/src/app/app/emails/page.tsx b/web/src/app/app/emails/page.tsx index f74627f59..75aabaa01 100644 --- a/web/src/app/app/emails/page.tsx +++ b/web/src/app/app/emails/page.tsx @@ -5,6 +5,7 @@ import { browseString, mailboxSort, mailboxTab, type MailboxTab } from "@/lib/br import { useSearchParams } from "@/hooks/useSearchParams"; import useMailboxTagFilter from "@/hooks/useMailboxTagFilter"; import groupMailboxes from "@/lib/groupMailboxes"; +import { utcToday } from "@/lib/campaignPeriod"; import { cloudStandingUnavailable as cloudHealthUnavailable, mailboxColdActivity, reputationOnlyWarning } from "@/lib/mailboxStatus"; import { useAppStore } from "@/stores/useAppStore"; import toast from "react-hot-toast/headless"; @@ -116,6 +117,10 @@ const DefaultFolder = { const HEALTH_RANK: Record = { healthy: 0, warning: 1, error: 2 }; const LAST_REPORTED_ISSUE_MS = 5 * 60_000; +function dailyUsageOn(status: AccountStatus | undefined, day: string) { + return status?.daily_usage?.date === day ? status.daily_usage : undefined; +} + function healthTone(status?: AccountStatus): { dot: string; text: string; label: string; pulse: boolean } { const h = status?.health; if (!h) return { dot: "bg-slate-300", text: "text-slate-500", label: "โ€”", pulse: false }; @@ -204,6 +209,7 @@ export default function AddressesPage() { () => (!cloudChecking && Array.isArray(statuses.data) ? statuses.data : []), [cloudChecking, statuses.data], ); + const today = utcToday(); const statusById = useMemo(() => { const m = new Map(); for (const s of accountStatuses) m.set(s.id, s); @@ -449,12 +455,12 @@ export default function AddressesPage() { const value = col.sortValue; const dir = sort.reverse ? 1 : -1; return [...list].sort((a, b) => { - const x = value(a, statusById.get(a.id)); - const y = value(b, statusById.get(b.id)); + const x = value(a, statusById.get(a.id), today); + const y = value(b, statusById.get(b.id), today); if (x === y) return 0; return (x > y ? 1 : -1) * dir; }); - }, [emailsData.emails, sort, statusById, p.user.tags]); + }, [emailsData.emails, sort, statusById, p.user.tags, today]); if (!canView) { return ; @@ -913,6 +919,7 @@ function MailboxRow({ const displayedHealth = historicalIssue?.status ?? status; const tone = healthTone(displayedHealth); const ws = status?.warmup_status; + const dailyUsage = dailyUsageOn(status, utcToday()); const inCampaign = status?.in_campaign; const cloudEnroll = useEnrollCloudLinkMailbox(); @@ -1166,15 +1173,15 @@ function MailboxRow({ - {status?.daily_usage ? ( + {dailyUsage ? ( 0 ? "text-sky-700" : "text-slate-500"}`} - title={`${status.daily_usage.campaign_sent} of ${status.daily_usage.campaign_limit || box.campaign_limit} campaign emails sent today`} + className={`inline-flex items-center gap-1.5 font-mono text-[12px] tabular-nums ${dailyUsage.campaign_sent > 0 ? "text-sky-700" : "text-slate-500"}`} + title={`${dailyUsage.campaign_sent} of ${dailyUsage.campaign_limit || box.campaign_limit} campaign emails sent today`} > - - /{status.daily_usage.campaign_limit || box.campaign_limit} + + /{dailyUsage.campaign_limit || box.campaign_limit} ) : ( @@ -1367,7 +1374,7 @@ interface MailboxColumn { align?: "right"; // Whether the first click sorts ascending (text) rather than descending. sortAsc?: boolean; - sortValue?: (box: Inbox, status?: AccountStatus) => string | number; + sortValue?: (box: Inbox, status: AccountStatus | undefined, today: string) => string | number; } interface MailboxSort { @@ -1400,7 +1407,7 @@ const MAILBOX_COLUMNS: MailboxColumn[] = [ header: , className: "w-32", show: "hidden @5xl:table-cell", - sortValue: (_, s) => s?.daily_usage?.campaign_sent ?? -1, + sortValue: (_, s, today) => dailyUsageOn(s, today)?.campaign_sent ?? -1, }, { id: "warmup", @@ -1493,11 +1500,13 @@ function MailboxStatusPill({ box, status, stale, historicalIssue, warming, compa } if (problem) { const { Icon } = problem; + const cachedError = stale && box.status === "active"; + const label = cachedError ? `Last observed: ${problem.label}` : problem.label; return ( - + - {problem.label} - {problem.label} + {label} + {label} ); } From 6cde875da1e9036821aaba3664ff301aa5172470 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sun, 1 Nov 2026 14:05:44 +0100 Subject: [PATCH 069/318] feat: gate the hosted TLS recovery evidence writer with scoped conditional uploads and infrastructure approval --- .github/scripts/terraform-stack.sh | 4 +- .github/scripts/terraform-stack.test.sh | 31 +++++ .github/workflows/terraform-aws.yml | 13 +- deploy/terraform/aws/runtime/README.md | 9 ++ .../aws/runtime/tests/target_tls.tftest.hcl | 125 ++++++++++++++++++ .../aws/runtime/tls-recovery-evidence.tf | 78 +++++++++++ docs/content/docs/development/aws-fargate.mdx | 41 +++++- 7 files changed, 293 insertions(+), 8 deletions(-) create mode 100755 .github/scripts/terraform-stack.test.sh create mode 100644 deploy/terraform/aws/runtime/tls-recovery-evidence.tf diff --git a/.github/scripts/terraform-stack.sh b/.github/scripts/terraform-stack.sh index f321467ee..5165ad581 100755 --- a/.github/scripts/terraform-stack.sh +++ b/.github/scripts/terraform-stack.sh @@ -10,13 +10,15 @@ # # plan writes $WORK/.summary (one "action address" per line) and prints # safe, gated or none. Safe means only creates, in-place updates, and new -# revisions of task definitions, which keep their old revision. +# revisions of task definitions, excluding protected recovery evidence IAM changes. set -euo pipefail classify() { jq -r ' [.resource_changes[]? | select(.change.actions != ["no-op"] and .change.actions != ["read"])] as $c | if ($c | length) == 0 then "none" + elif any($c[]; .name == "tls_recovery_evidence" and + (.type == "aws_iam_role" or .type == "aws_iam_role_policy")) then "gated" elif any($c[]; (.change.actions | index("delete")) and ((.type == "aws_ecs_task_definition" and (.change.actions | length) == 2) | not)) then "gated" else "safe" end' "$1" diff --git a/.github/scripts/terraform-stack.test.sh b/.github/scripts/terraform-stack.test.sh new file mode 100755 index 000000000..d7f978dc8 --- /dev/null +++ b/.github/scripts/terraform-stack.test.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/../.." +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +classifier=${CLASSIFIER:-.github/scripts/terraform-stack.sh} + +check() { + local expected=$1 type=$2 name=$3 actions=$4 + jq -n --arg type "$type" --arg name "$name" --argjson actions "$actions" \ + '{resource_changes:[{address:($type+"."+$name+"[0]"),type:$type,name:$name,change:{actions:$actions}}]}' >"$work/plan.json" + local actual + actual=$(bash "$classifier" classify "$work/plan.json") + if [ "$actual" != "$expected" ]; then + echo "Expected $expected for $type.$name $actions, received $actual" >&2 + exit 1 + fi +} + +for type in aws_iam_role aws_iam_role_policy; do + for actions in '["create"]' '["update"]' '["delete"]' '["delete","create"]'; do + check gated "$type" tls_recovery_evidence "$actions" + done + check none "$type" tls_recovery_evidence '["no-op"]' + check none "$type" tls_recovery_evidence '["read"]' +done +check safe aws_iam_role existing_role '["create"]' +check safe aws_ecs_task_definition service '["delete","create"]' +check gated aws_lb_target_group service '["delete"]' +check safe aws_cloudwatch_metric_alarm service '["update"]' +echo 'Protected evidence IAM changes require approval; existing plan classifications remain unchanged' diff --git a/.github/workflows/terraform-aws.yml b/.github/workflows/terraform-aws.yml index 33f097da4..3f64b86f2 100644 --- a/.github/workflows/terraform-aws.yml +++ b/.github/workflows/terraform-aws.yml @@ -1,21 +1,21 @@ name: Terraform AWS # Pull requests get a plan summary comment. On main, a stack whose plan only -# creates or updates applies on its own; one that replaces or destroys waits in -# the aws-infrastructure-approval environment. Var files live in the private +# creates or updates applies on its own; destructive or protected evidence IAM +# changes wait in aws-infrastructure-approval. Var files live in the private # state bucket, and no plan body ever reaches a log, a comment or an artifact. on: pull_request: paths: - 'deploy/terraform/aws/**' - '.github/workflows/terraform-aws.yml' - - '.github/scripts/terraform-stack.sh' + - '.github/scripts/terraform-stack*.sh' push: branches: [main] paths: - 'deploy/terraform/aws/**' - '.github/workflows/terraform-aws.yml' - - '.github/scripts/terraform-stack.sh' + - '.github/scripts/terraform-stack*.sh' workflow_dispatch: permissions: @@ -48,7 +48,8 @@ jobs: done # Mocked provider: no credentials, nothing created. - run: terraform -chdir=deploy/terraform/aws/runtime test -no-color - - run: shellcheck .github/scripts/terraform-stack.sh + - run: shellcheck .github/scripts/terraform-stack*.sh + - run: bash .github/scripts/terraform-stack.test.sh plan: name: Plan summary @@ -92,7 +93,7 @@ jobs: case "$class" in none) echo "**$stack**: no changes" ;; safe) echo "**$stack**: applies on merge" ;; - gated) echo "**$stack**: replaces or destroys, so it waits for approval in aws-infrastructure-approval" ;; + gated) echo "**$stack**: destructive or protected IAM changes wait for approval in aws-infrastructure-approval" ;; esac if [ "$class" != none ]; then echo '```' diff --git a/deploy/terraform/aws/runtime/README.md b/deploy/terraform/aws/runtime/README.md index 966daa8a3..5e09be92b 100644 --- a/deploy/terraform/aws/runtime/README.md +++ b/deploy/terraform/aws/runtime/README.md @@ -102,6 +102,15 @@ trust is applied by an administrator by hand. Var files stay in the state bucket under `warmbly/production/vars/`; only resource addresses and actions are ever printed. +`tls_recovery_evidence_writer` is a separate hosted-only opt-in, defaulting to +`false`. It creates the dedicated `warmbly-production-tls-recovery-evidence` role +and one conditional private S3 upload policy, with no read, delete or deployment +access. It requires the production account, bucket and name, the Warmbly +repository and `terraform_ci`. Every managed change to this role or its policy +requires `aws-infrastructure-approval`, including creation. Its optional output +is `tls_recovery_evidence_role_arn`. Provisioning does not enable recovery; the +runbook in `aws-fargate.mdx` describes the separate configuration and review. + The runtime sets `DB_MIGRATIONS_ON_START=false` for the backend. New application images must support that setting and schema readiness before activation. Keep migrations additive and compatible with the previous release throughout rollout diff --git a/deploy/terraform/aws/runtime/tests/target_tls.tftest.hcl b/deploy/terraform/aws/runtime/tests/target_tls.tftest.hcl index fe67e0e5c..cc5a5e99e 100644 --- a/deploy/terraform/aws/runtime/tests/target_tls.tftest.hcl +++ b/deploy/terraform/aws/runtime/tests/target_tls.tftest.hcl @@ -225,3 +225,128 @@ run "tls_needs_the_backend_key" { } expect_failures = [aws_ecs_task_definition.service] } + +run "evidence_writer_is_disabled_by_default" { + command = plan + assert { + condition = length(aws_iam_role.tls_recovery_evidence) == 0 && length(aws_iam_role_policy.tls_recovery_evidence) == 0 && output.tls_recovery_evidence_role_arn == null + error_message = "Existing installations create no evidence writer without opting in." + } +} + +run "existing_ci_does_not_enable_the_evidence_writer" { + command = plan + variables { + terraform_ci = true + github_repository = "warmbly/warmbly" + } + assert { + condition = length(aws_iam_role.tls_recovery_evidence) == 0 && length(aws_iam_role_policy.tls_recovery_evidence) == 0 + error_message = "Existing CI configuration grants no evidence upload permission." + } +} + +run "enabled_evidence_writer_has_only_conditional_archive_access" { + command = apply + override_data { + target = data.aws_caller_identity.current + values = { account_id = "925323749693" } + } + variables { + terraform_ci = true + github_repository = "warmbly/warmbly" + state_bucket = "warmbly-terraform-use1-925323749693" + tls_recovery_evidence_writer = true + } + assert { + condition = length(aws_iam_role.tls_recovery_evidence) == 1 && aws_iam_role.tls_recovery_evidence[0].name == "warmbly-production-tls-recovery-evidence" && aws_iam_role.tls_recovery_evidence[0].max_session_duration == 3600 + error_message = "The opt-in creates one bounded-session dedicated role." + } + assert { + condition = jsondecode(aws_iam_role.tls_recovery_evidence[0].assume_role_policy) == { + Version = "2012-10-17" + Statement = [{ + Sid = "MainRepositoryRecoveryEnvironments" + Effect = "Allow" + Principal = { Federated = aws_iam_openid_connect_provider.github[0].arn } + Action = "sts:AssumeRoleWithWebIdentity" + Condition = { + StringEquals = { + "token.actions.githubusercontent.com:aud" = "sts.amazonaws.com" + "token.actions.githubusercontent.com:repository_id" = "1136203389" + "token.actions.githubusercontent.com:repository_owner_id" = "216286592" + "token.actions.githubusercontent.com:ref" = "refs/heads/main" + "token.actions.githubusercontent.com:sub" = [ + "repo:warmbly/warmbly:environment:aws-infrastructure-plan", + "repo:warmbly/warmbly:environment:aws-infrastructure-approval", + ] + } + } + }] + } + error_message = "Only the expected immutable repository identity on main in the two recovery environments can assume the role." + } + assert { + condition = jsondecode(aws_iam_role_policy.tls_recovery_evidence[0].policy) == { + Version = "2012-10-17" + Statement = [{ + Sid = "WriteNewEncryptedRecoveryEvidence" + Effect = "Allow" + Action = "s3:PutObject" + Resource = [ + "arn:aws:s3:::warmbly-terraform-use1-925323749693/warmbly/production/diagnostics/runtime-tls-recovery/*/1/plan.tgz", + "arn:aws:s3:::warmbly-terraform-use1-925323749693/warmbly/production/diagnostics/runtime-tls-recovery/*/1/apply.tgz", + "arn:aws:s3:::warmbly-terraform-use1-925323749693/warmbly/production/diagnostics/runtime-tls-recovery/*/1/verify.tgz", + ] + Condition = { + StringEquals = { "s3:x-amz-server-side-encryption" = "AES256", "s3:ResourceAccount" = "925323749693" } + Bool = { "aws:SecureTransport" = "true" } + Null = { "s3:if-none-match" = "false" } + } + }] + } + error_message = "The writer grants only conditional encrypted archive uploads, with no read, delete, state, IAM or deployment permission." + } +} + +run "evidence_writer_requires_ci" { + command = plan + variables { + github_repository = "warmbly/warmbly" + state_bucket = "warmbly-terraform-use1-925323749693" + tls_recovery_evidence_writer = true + } + expect_failures = [var.tls_recovery_evidence_writer] +} + +run "evidence_writer_refuses_other_repositories" { + command = plan + variables { + terraform_ci = true + github_repository = "example/other" + state_bucket = "warmbly-terraform-use1-925323749693" + tls_recovery_evidence_writer = true + } + expect_failures = [var.tls_recovery_evidence_writer] +} + +run "evidence_writer_refuses_other_buckets" { + command = plan + variables { + terraform_ci = true + github_repository = "warmbly/warmbly" + tls_recovery_evidence_writer = true + } + expect_failures = [var.tls_recovery_evidence_writer] +} + +run "evidence_writer_refuses_other_accounts" { + command = plan + variables { + terraform_ci = true + github_repository = "warmbly/warmbly" + state_bucket = "warmbly-terraform-use1-925323749693" + tls_recovery_evidence_writer = true + } + expect_failures = [aws_iam_role.tls_recovery_evidence] +} diff --git a/deploy/terraform/aws/runtime/tls-recovery-evidence.tf b/deploy/terraform/aws/runtime/tls-recovery-evidence.tf new file mode 100644 index 000000000..b7aa3a82d --- /dev/null +++ b/deploy/terraform/aws/runtime/tls-recovery-evidence.tf @@ -0,0 +1,78 @@ +variable "tls_recovery_evidence_writer" { + description = "Create the hosted-only conditional S3 writer for private runtime TLS recovery evidence" + type = bool + default = false + validation { + condition = !var.tls_recovery_evidence_writer || ( + var.terraform_ci && var.github_repository == "warmbly/warmbly" && + var.name == "warmbly-production" && var.state_bucket == "warmbly-terraform-use1-925323749693" + ) + error_message = "The evidence writer requires the hosted production name, state bucket, repository and terraform_ci." + } +} + +locals { + tls_recovery_evidence_enabled = var.tls_recovery_evidence_writer && local.terraform_ci +} + +resource "aws_iam_role" "tls_recovery_evidence" { + count = local.tls_recovery_evidence_enabled ? 1 : 0 + name = "warmbly-production-tls-recovery-evidence" + max_session_duration = 3600 + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Sid = "MainRepositoryRecoveryEnvironments" + Effect = "Allow" + Principal = { Federated = aws_iam_openid_connect_provider.github[0].arn } + Action = "sts:AssumeRoleWithWebIdentity" + Condition = { + StringEquals = { + "token.actions.githubusercontent.com:aud" = "sts.amazonaws.com" + "token.actions.githubusercontent.com:sub" = [ + "repo:warmbly/warmbly:environment:aws-infrastructure-plan", + "repo:warmbly/warmbly:environment:aws-infrastructure-approval", + ] + "token.actions.githubusercontent.com:repository_id" = "1136203389" + "token.actions.githubusercontent.com:repository_owner_id" = "216286592" + "token.actions.githubusercontent.com:ref" = "refs/heads/main" + } + } + }] + }) + lifecycle { + precondition { + condition = data.aws_caller_identity.current.account_id == "925323749693" + error_message = "The hosted evidence writer is restricted to account 925323749693 in us-east-1." + } + } +} + +resource "aws_iam_role_policy" "tls_recovery_evidence" { + count = local.tls_recovery_evidence_enabled ? 1 : 0 + name = "conditional-private-recovery-archives" + role = aws_iam_role.tls_recovery_evidence[0].id + policy = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Sid = "WriteNewEncryptedRecoveryEvidence" + Effect = "Allow" + Action = "s3:PutObject" + Resource = [for phase in ["plan", "apply", "verify"] : + "arn:aws:s3:::warmbly-terraform-use1-925323749693/warmbly/production/diagnostics/runtime-tls-recovery/*/1/${phase}.tgz" + ] + Condition = { + StringEquals = { + "s3:x-amz-server-side-encryption" = "AES256" + "s3:ResourceAccount" = "925323749693" + } + Bool = { "aws:SecureTransport" = "true" } + Null = { "s3:if-none-match" = "false" } + } + }] + }) +} + +output "tls_recovery_evidence_role_arn" { + value = local.tls_recovery_evidence_enabled ? aws_iam_role.tls_recovery_evidence[0].arn : null +} diff --git a/docs/content/docs/development/aws-fargate.mdx b/docs/content/docs/development/aws-fargate.mdx index fac16624e..eed02ca3e 100644 --- a/docs/content/docs/development/aws-fargate.mdx +++ b/docs/content/docs/development/aws-fargate.mdx @@ -332,7 +332,8 @@ plan reaches a log, a comment or an artifact. password, which the plan role may not. - On merge, each stack is planned in order: foundation, runtime, workers. A stack that only creates and updates applies on its own. One that replaces or - destroys anything stops and waits for approval in the + destroys anything, or changes the dedicated recovery evidence IAM role or its + inline policy, stops and waits for approval in the `aws-infrastructure-approval` environment, and the stacks after it wait too. On approval it plans again and applies only if the plan is still the one that was approved. A new task definition revision counts as an update, because the @@ -344,6 +345,44 @@ The bootstrap stack stays manual. So does any change to the CI roles themselves: change its own permissions or trust, or the plan role's, so an administrator applies those by hand. +## Private recovery evidence writer + +The hosted runtime supports a separate private archive writer with +`tls_recovery_evidence_writer = true`. It defaults to `false`, including when +`terraform_ci` is already enabled, and changes no existing self-host configuration. +It requires the hosted production account, deployment name, state bucket, +`github_repository = "warmbly/warmbly"` and `terraform_ci = true`. + +The setting creates `warmbly-production-tls-recovery-evidence` and one inline +policy. The role accepts GitHub OIDC only for the immutable Warmbly repository +and owner IDs, `main`, and the `aws-infrastructure-plan` or +`aws-infrastructure-approval` environments. These claims do not uniquely identify +a workflow file; reviewed main source and environment controls remain required. +The role has no managed-policy attachments and its sessions are limited to one hour. + +Uploads are limited to `plan.tgz`, `apply.tgz` and `verify.tgz` under +`warmbly/production/diagnostics/runtime-tls-recovery/*/1/` in the hosted state +bucket. Each request must use TLS, specify AES256 encryption and the expected +resource account, and include `If-None-Match` for conditional creation. The +uploader validates its SHA-256 checksum and the returned S3 version. The IAM +wildcard does not validate numeric run IDs; the uploader must check the run and +attempt. This role grants no object reads, deletes, state writes or deployment +permissions. It does not establish Object Lock or retention protection against +other principals. + +Any managed change to this role or policy, including creation, requires the +existing `aws-infrastructure-approval` gate. Review the complete plan and require +only the two expected create-only resources when provisioning the writer. +After approval, read back its trust, inline policy and attachments before use. +The `tls_recovery_evidence_role_arn` output is present only when enabled. + +Provisioning the role does not enable or dispatch recovery. Configure its ARN as +`AWS_TLS_RECOVERY_EVIDENCE_ROLE_ARN` where both recovery job environments can read +it. A recovery workflow, its immutable private contract and snapshots, required +reviewers, self-review prevention and administrator-bypass restrictions need +separate review before enablement. Keep recovery disabled until those checks pass. +An existing environment is not proof that these additional controls are configured. + ## Encrypt traffic inside the VPC The load balancer terminates the public TLS connection. With `target_tls` set, From 7a770aa7b522eeea34e2871df17bc315fb0bc4e7 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sun, 1 Nov 2026 14:18:23 +0100 Subject: [PATCH 070/318] feat: keep runtime TLS recovery archive and execution tests portable across CI runners --- .github/scripts/runtime-tls-recovery-archive.test.sh | 2 +- .github/scripts/runtime-tls-recovery-execute.test.sh | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/scripts/runtime-tls-recovery-archive.test.sh b/.github/scripts/runtime-tls-recovery-archive.test.sh index a4a1ad70d..e62c0cd13 100755 --- a/.github/scripts/runtime-tls-recovery-archive.test.sh +++ b/.github/scripts/runtime-tls-recovery-archive.test.sh @@ -19,7 +19,7 @@ while [ "$#" -gt 0 ]; do case "$1" in --checksum-sha256) checksum=$2; shift 2 ;; --body) body=$2; shift 2 ;; *) shift ;; esac done [ "$checksum" = "$(openssl dgst -sha256 -binary "$body" | openssl base64 -A)" ] -tar -tzf "$body" | rg -q '^./full-raw.json$' +tar -tzf "$body" | grep -Fx './full-raw.json' >/dev/null if [ "${MODE:-}" = upload ]; then exit 1; fi jq -n --arg checksum "$checksum" --arg mode "${MODE:-}" '{VersionId:"evidence-version",ServerSideEncryption:"AES256",ChecksumSHA256:(if $mode=="checksum" then "other" else $checksum end)}' SH diff --git a/.github/scripts/runtime-tls-recovery-execute.test.sh b/.github/scripts/runtime-tls-recovery-execute.test.sh index e7e9a0273..2cf4d73f7 100755 --- a/.github/scripts/runtime-tls-recovery-execute.test.sh +++ b/.github/scripts/runtime-tls-recovery-execute.test.sh @@ -142,7 +142,7 @@ for mode in bypass self-review artifact provenance live advanced scope changes; if WORK="$work/$mode" MODE=$mode APPROVED_DIGEST="$approved" bash "$guard" apply 2>/dev/null; then echo "Recovery applied incompatible evidence: $mode" >&2; exit 1 fi - if rg -q '^terraform .* apply ' "$work/requests.log"; then echo "Recovery reached apply for $mode" >&2; exit 1; fi + if grep -q '^terraform .* apply ' "$work/requests.log"; then echo "Recovery reached apply for $mode" >&2; exit 1; fi done if WORK="$work/wrong-approval" APPROVED_DIGEST=other bash "$guard" apply 2>/dev/null; then echo 'Recovery accepted another approval digest' >&2; exit 1; fi if WORK="$work/retry" GITHUB_RUN_ATTEMPT=2 bash "$guard" plan 2>/dev/null; then echo 'Recovery accepted a rerun' >&2; exit 1; fi @@ -152,12 +152,12 @@ if WORK="$work/apply-failure" MODE=apply-failure APPROVED_DIGEST="$approved" bas echo 'Recovery continued after an apply failure' >&2; exit 1 fi [ ! -e "$work/applied" ] -if rg -q '^live collect-final$' "$work/requests.log"; then echo 'Recovery verified a failed apply as complete' >&2; exit 1; fi +if grep -q '^live collect-final$' "$work/requests.log"; then echo 'Recovery verified a failed apply as complete' >&2; exit 1; fi : >"$work/requests.log" WORK="$work/apply" APPROVED_DIGEST="$approved" bash "$guard" apply -[ "$(rg -c '^live collect$' "$work/requests.log")" = 2 ] -[ "$(rg -c '^live collect-final$' "$work/requests.log")" = 1 ] -[ "$(rg -c '^gh attestation verify ' "$work/requests.log")" = 10 ] +[ "$(grep -c '^live collect$' "$work/requests.log")" = 2 ] +[ "$(grep -c '^live collect-final$' "$work/requests.log")" = 1 ] +[ "$(grep -c '^gh attestation verify ' "$work/requests.log")" = 10 ] WORK="$work/verify" bash "$guard" verify jq '.resources[0].instances[0].attributes.arn="different"' "$work/final-state.json" >"$work/changed-state.json" if bash "$guard" check-final-state "$work/changed-state.json" "$work/state.json" 2>/dev/null; then From 1b98c61ef9f06a23ba2b93fc47c6b42074cb01db Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Mon, 2 Nov 2026 08:59:31 +0100 Subject: [PATCH 071/318] feat: hold mailbox warmup reply share to its configured target within existing send budgets --- docs/content/docs/api/reference/campaigns.mdx | 2 +- docs/content/docs/api/reference/mailboxes.mdx | 2 +- docs/content/docs/guides/analytics.mdx | 2 +- docs/content/docs/guides/warmup.mdx | 15 ++- internal/app/consumer/warmup_engagement.go | 19 ++-- internal/app/consumer/warmup_reply_back.go | 7 ++ internal/app/warmupramp/ramp.go | 6 +- internal/app/warmupramp/reply.go | 65 +++++++++++ internal/app/warmupramp/reply_test.go | 63 +++++++++++ internal/models/campaign.go | 4 +- internal/repository/warmup_lineage.go | 103 ++++++++++++++++-- .../warmup_reply_share_live_test.go | 76 +++++++++++++ internal/tasks/email_task.go | 9 +- internal/tasks/warmup_reply_share.go | 73 +++++++++++++ .../app/campaigns/new/EstimateInsights.tsx | 4 +- .../components/app/emails/InboxDetails.tsx | 2 +- 16 files changed, 417 insertions(+), 35 deletions(-) create mode 100644 internal/app/warmupramp/reply.go create mode 100644 internal/app/warmupramp/reply_test.go create mode 100644 internal/repository/warmup_reply_share_live_test.go create mode 100644 internal/tasks/warmup_reply_share.go diff --git a/docs/content/docs/api/reference/campaigns.mdx b/docs/content/docs/api/reference/campaigns.mdx index cbe92ba96..f59df9688 100644 --- a/docs/content/docs/api/reference/campaigns.mdx +++ b/docs/content/docs/api/reference/campaigns.mdx @@ -140,7 +140,7 @@ Project an audience against a sender pool before a campaign exists. The campaign | `steps`, `total_sends` | Emails per contact, and `recipients` times `steps`. | | `first_touch_finish_at` | The day the last contact gets their first email. | | `ramping`, `held` | Mailboxes still climbing their graduation ceiling, and mailboxes that send nothing today. | -| `warmup` | `{mailboxes, per_day, per_day_without, reply_rate}`: the warmup mail running alongside the campaign, what the same mailboxes warm at with no live campaign, and the least share of it (in percent) pool partners reply to while the campaign runs. | +| `warmup` | `{mailboxes, per_day, per_day_without, reply_rate}`: the warmup mail running alongside the campaign, what the same mailboxes warm at with no live campaign, and the least chance (in percent) that a pool partner with reply share left answers it on arrival while the campaign runs. Partners answer this warmup before other warmup mail, within their own reply rate. | | `other_campaigns_per_day` | What the pool's mailboxes sent for other campaigns on an average day over the last week. | | `bottleneck` | The clamp that costs the most sends on the first full sending day: `campaign_limit`, `warmup_graduation`, `spacing`, `other_campaigns`, `health`, `held`, `workspace_risk`, `org_daily_limit` or `sending_behavior`. Empty when the mailboxes' own caps are the limit. | | `timeline` | Up to 120 days from the start: `date`, `sending_day`, `capacity`, `sends`, `first_emails`, `follow_ups`, `warmup`. | diff --git a/docs/content/docs/api/reference/mailboxes.mdx b/docs/content/docs/api/reference/mailboxes.mdx index a12d60dc7..10aca5c28 100644 --- a/docs/content/docs/api/reference/mailboxes.mdx +++ b/docs/content/docs/api/reference/mailboxes.mdx @@ -159,7 +159,7 @@ Auth: **Scope** `WRITE_EMAILS` ยท **Org permission** `manage_emails` | `warmup_base` | integer | no | Warmup starting volume per day. | | `warmup_max` | integer | no | Warmup daily ceiling. | | `warmup_increase` | integer | no | Per-day warmup ramp increment. | -| `warmup_reply_rate` | integer | no | Percentage of warmup threads to reply to. | +| `warmup_reply_rate` | integer | no | Percentage of the mailbox's own warmup sends that are replies, held over its last seven days. `0` turns warmup replies off. | | `warmup_tag` | string | no | Tag applied to warmup threads. | | `warmup_start_time` | string | no | Daily warmup window start, `HH:MM`. | | `warmup_end_time` | string | no | Daily warmup window end, `HH:MM`. | diff --git a/docs/content/docs/guides/analytics.mdx b/docs/content/docs/guides/analytics.mdx index a2cdd8f36..765749c50 100644 --- a/docs/content/docs/guides/analytics.mdx +++ b/docs/content/docs/guides/analytics.mdx @@ -217,7 +217,7 @@ These records back the engagement rows on a contact's [activity timeline](/guide | Warmup status | Whether warmup is on, actual volume today, the target the scheduler is using, max volume, configured reply target, and elapsed warmup days | | Warmup health | Pool standing: healthy, watch, throttled, quarantined, or blocked, with the score and reason the band decided, and the block expiry | -The overview calls the configured percentage **Reply target**. It controls the chance that the mailbox answers an eligible incoming warmup message, rather than guaranteeing a fixed measured percentage. The Analytics tab's warmup reply rate is warmup replies sent by the mailbox divided by all its warmup sends in the selected range. It does not measure how many of the mailbox's outgoing messages received an answer. Its **Target met** percentage is actual warmup sends divided by planned target volume across the active days in the selected range; it can exceed 100% when volume beats the plan. +The overview calls the configured percentage **Reply target**: the target share of the mailbox's own warmup sends that are replies over its last seven UTC days (see [warmup replies](/guides/warmup/#replies)). The Analytics tab's warmup reply rate is warmup replies sent by the mailbox divided by all its warmup sends in the selected range. It approaches the target when eligible received mail is available. Small send counts, a changed target, thread limits, and partner availability can make the measured rate differ; a selected range can also include sends from before the target changed. It does not measure how many of the mailbox's outgoing messages received an answer. Its **Target met** percentage is actual warmup sends divided by planned target volume across the active days in the selected range; it can exceed 100% when volume beats the plan. Use this to find the one mailbox dragging down a campaign's bounce rate instead of blaming the campaign. diff --git a/docs/content/docs/guides/warmup.mdx b/docs/content/docs/guides/warmup.mdx index a851fd14a..1c92143ff 100644 --- a/docs/content/docs/guides/warmup.mdx +++ b/docs/content/docs/guides/warmup.mdx @@ -254,9 +254,16 @@ Replies continue the exact pinned thread and subject, each parent is answered on Replies thread properly with a real `Re:` subject and `In-Reply-To` header, and candidates must be between 45 minutes and seven days old, so nothing is answered instantly or revived indefinitely. -Receiving warmup mail can also prompt an answer directly. When a verified warmup email arrives, the recipient sometimes points its next scheduled send back at whoever wrote, 45 minutes to 5 hours later and inside its own warmup hours. That is a re-pointing, not extra work: each mailbox has one warmup send queued at a time, so a reply-back moves that send earlier and aims it, and can never push a send the mailbox had already planned sooner. When that send is already answering someone, the new email is not answered, so replies never crowd out new threads. A reply is held to the same daily receiving cap as any other warmup email: when the inbox it answers is full for the day, the thread ends there and the mailbox goes on with its normal schedule, so one busy partner never stops a mailbox's warmup. The chance is the recipient's own reply rate (raised for a sender in [recovery](#recovery-engagement), which includes every free Gmail and Outlook.com mailbox and every mailbox backing a live campaign), drawn once when the reply is scheduled rather than again when it sends, and it stops before a thread reaches its message cap so replies cannot answer replies indefinitely. A reply crosses the free and paid tiers like the mail it answers: a paid mailbox answers a free partner that wrote to it, and a free mailbox answers a paid one while it is healthy and its workspace is in good standing. +The **Reply rate** setting is the share of a mailbox's own warmup sends that are replies, and Warmbly holds the mailbox to it. Over its last seven UTC days of warmup, a mailbox set to `30%` sends about three replies for every ten warmup emails, the same figure the Analytics tab reports. Replies never add volume: each one takes the place of a send the mailbox was going to make anyway. `0%` turns replies off. -If the next send is already scheduled earlier than the reply's drawn time, it keeps that time when it is at least 45 minutes after the receipt. If it is due before that minimum delay, it stays a new send rather than being postponed for a reply. The configured percentage is a chance to answer eligible messages, so sending windows, thread limits and available capacity can make the measured rate differ from it. +Replies reach that share two ways: + +- **On arrival.** When a verified warmup email arrives and the mailbox is below its share, it sometimes points its next scheduled send back at whoever wrote, 45 minutes to 5 hours later and inside its own warmup hours. The chance is the mailbox's reply rate (raised for a sender in [recovery](#recovery-engagement)), drawn once when the reply is scheduled rather than again when it sends. Each mailbox has one warmup send queued at a time, so a reply-back moves that send earlier and aims it, and never pushes a send the mailbox had already planned sooner. If that send is due within 45 minutes of the arrival, or is already answering someone, the arrival is not answered then. +- **When a send goes out.** If the mailbox is still below its share when its next new-thread send fires, that send answers warmup mail it received instead: something at least 45 minutes and at most seven days old that it has not answered, newest first and mail from a sender in [recovery](#recovery-engagement) before any other. A mailbox ahead of its share does not reply until its sends catch up. + +Together these help the measured rate converge on the setting, including for busy mailboxes whose next send is almost always less than 45 minutes away. Small send counts and a recent setting change can make it differ temporarily. The rate can fall short when eligible received mail is unavailable, threads have reached their message caps, or the partners that wrote to it can no longer receive. Reply selection considers a bounded set of recent messages on each send, so unavailable recent partners can also delay catch-up. + +A reply is held to the same daily receiving cap as any other warmup email: a reply to an inbox that is full for the day is not sent, and the mailbox goes on with another reply or a new thread, so one busy partner never stops a mailbox's warmup. Replies stop before a thread reaches its message cap so replies cannot answer replies indefinitely. A reply crosses the free and paid tiers like the mail it answers: a paid mailbox answers a free partner that wrote to it, and a free mailbox answers a paid one while it is healthy and its workspace is in good standing. Scheduling respects windows, provider feedback, shared limits and spacing. Jitter distributes load, not human identities. Receiving participation allows probabilistic spam rescue, reads, importance and stars or flags on verified warmup messages. Filing and selected spam rescues are requested immediately; reads, importance and stars are durably scheduled after a randomized dwell. Current receiving permission and worker assignment are checked again at execution time. These actions are automation, not human feedback or a guaranteed reputation improvement. @@ -357,9 +364,9 @@ Spam placement is a folder outcome, not misconduct or evidence of diagnostic rep ### Recovery engagement -While a mailbox is on watch or throttled, the pool works harder for it instead of only slowing it down. Recipients that take part in engagement move nearly every copy of its warmup mail that lands in spam back out of spam (each mailbox at its own rate, so none does it every time) and mark more of it important, and each email has at least a `60%` chance of a reply when the recipient's next warmup send is free to answer it (unless the recipient's owner turned warmup replies off). Replies take the place of the recipient's next scheduled warmup send, so the extra engagement adds no volume. It stops on its own when the band lifts. +While a mailbox is on watch or throttled, the pool works harder for it instead of only slowing it down. Recipients that take part in engagement move nearly every copy of its warmup mail that lands in spam back out of spam (each mailbox at its own rate, so none does it every time) and mark more of it important, and its mail is answered first: a recipient below its own reply share answers it on arrival with at least a `60%` chance, and picks it before any other mail when a send comes due as a reply (unless the recipient's owner turned warmup replies off). Every recipient still holds its own reply share, so recovery decides who is answered, not how much. Replies take the place of the recipient's next scheduled warmup send, so the extra engagement adds no volume. It stops on its own when the band lifts. -A free Gmail (`gmail.com`, `googlemail.com`) or Outlook.com (`outlook.com`, `hotmail.com`, `live.com` and the other Microsoft consumer domains) mailbox gets recovery engagement all the time, whatever its standing. A personal account starts with far less sender trust than a Google Workspace or Microsoft 365 mailbox on your own domain, so the pool rescues, marks important and answers its mail at the recovery rates from the first day. Workspace and Microsoft 365 mailboxes get it while on watch or throttled, and while they back a live campaign: cold mail draws few replies, so the pool answers at least `60%` of the reduced warmup those mailboxes still send. Those replies never count as campaign replies and never raise campaign volume. +A free Gmail (`gmail.com`, `googlemail.com`) or Outlook.com (`outlook.com`, `hotmail.com`, `live.com` and the other Microsoft consumer domains) mailbox gets recovery engagement all the time, whatever its standing. A personal account starts with far less sender trust than a Google Workspace or Microsoft 365 mailbox on your own domain, so the pool rescues, marks important and answers its mail at the recovery rates from the first day. Workspace and Microsoft 365 mailboxes get it while on watch or throttled, and while they back a live campaign: cold mail draws few replies, so the pool answers the reduced warmup those mailboxes still send ahead of other warmup mail. Those replies never count as campaign replies and never raise campaign volume. Placement uses today and the preceding six UTC dates, matching the seven-day inbox rate on Deliverability and Emails. Older placement results stop affecting volume at the same boundary as the displayed rate. Complaints and mailbox tampering keep their separate rolling windows. diff --git a/internal/app/consumer/warmup_engagement.go b/internal/app/consumer/warmup_engagement.go index dc491080c..bba75c643 100644 --- a/internal/app/consumer/warmup_engagement.go +++ b/internal/app/consumer/warmup_engagement.go @@ -59,22 +59,17 @@ const ( // its standing is watch or throttled, it is a consumer Gmail or Outlook.com mailbox, // or it backs a live campaign, whose cold mail draws few replies. func (s *JobsService) senderGetsRecoveryEngagement(ctx context.Context, senderID uuid.UUID) bool { + signals := warmupramp.RecoverySignals{} if s.WarmupRepo != nil { - state, _, err := s.WarmupRepo.GetHealthState(ctx, senderID) - if err == nil && (state == models.WarmupHealthWatch || state == models.WarmupHealthThrottled) { - return true - } + signals.Health = s.WarmupRepo } if s.EmailRepository != nil { - if sender, xerr := s.EmailRepository.GetByID(ctx, senderID); xerr == nil && sender.ConsumerMailbox() { - return true - } + signals.Mailboxes = s.EmailRepository } - if s.CampaignRepo == nil { - return false + if s.CampaignRepo != nil { + signals.Campaigns = s.CampaignRepo } - n, err := s.CampaignRepo.CountActiveCampaignsForAccount(ctx, senderID) - return err == nil && n > 0 + return signals.Recovering(ctx, senderID) } // recoveryEngagement raises the positive signals for a recovering sender's mail and never lowers them. @@ -85,7 +80,7 @@ func recoveryEngagement(e models.WarmupEngagementSettings) models.WarmupEngageme return e } -// recoveryReplyChance is the recipient's reply rate, raised for a recovering sender unless the owner turned replies off. +// recoveryReplyChance is the arrival chance of a reply, raised for a recovering sender unless the owner turned replies off. func recoveryReplyChance(rate int, recovering bool) int { if recovering && rate > 0 { return max(rate, recoveryReplyRate) diff --git a/internal/app/consumer/warmup_reply_back.go b/internal/app/consumer/warmup_reply_back.go index 4d3897781..1dccbfac6 100644 --- a/internal/app/consumer/warmup_reply_back.go +++ b/internal/app/consumer/warmup_reply_back.go @@ -8,6 +8,7 @@ import ( "github.com/google/uuid" "github.com/rs/zerolog/log" + "github.com/warmbly/warmbly/internal/app/warmupramp" "github.com/warmbly/warmbly/internal/bitmask" "github.com/warmbly/warmbly/internal/models" "github.com/warmbly/warmbly/internal/repository" @@ -40,6 +41,12 @@ func (s *JobsService) scheduleWarmupReplyBack(ctx context.Context, token *models if !recipient.IsWarmingActive() { return nil } + // Arrivals only spend the reply share the mailbox has left; a send it owes is repaid when its next plain send goes out. + if share, ok := s.TaskRepo.(repository.WarmupReplyShareRepository); ok { + if sent, replied, err := share.WarmupReplyShare(ctx, recipientAccountID); err == nil && warmupramp.ReplyDeficit(recipient.WarmupReplyRate, sent, replied) <= 0 { + return nil + } + } if int(binary.BigEndian.Uint32(token.Token[:4])%100) >= recoveryReplyChance(recipient.WarmupReplyRate, senderBoosted) { return nil diff --git a/internal/app/warmupramp/ramp.go b/internal/app/warmupramp/ramp.go index ab5186ed0..c72913378 100644 --- a/internal/app/warmupramp/ramp.go +++ b/internal/app/warmupramp/ramp.go @@ -11,9 +11,9 @@ const ( // campaign, so warmup does not stack on production sending pressure. ActiveCampaignCap = 5 - // BoostedReplyRate is the least chance a pool partner answers warmup mail - // from a recovering or campaign-backing sender, so the estimate and the - // consumer quote one number. + // BoostedReplyRate is the least arrival chance a pool partner with reply + // share left answers warmup mail from a recovering or campaign-backing + // sender, so the estimate and the consumer quote one number. BoostedReplyRate = 60 // SoftThrottleMultiplier is the cut applied while a placement is fresh. diff --git a/internal/app/warmupramp/reply.go b/internal/app/warmupramp/reply.go new file mode 100644 index 000000000..b26154262 --- /dev/null +++ b/internal/app/warmupramp/reply.go @@ -0,0 +1,65 @@ +package warmupramp + +import ( + "context" + "time" + + "github.com/google/uuid" + + "github.com/warmbly/warmbly/internal/errx" + "github.com/warmbly/warmbly/internal/models" +) + +// ReplyShareWindowDays is how many UTC days of warmup sends a mailbox's reply share is read over. +const ReplyShareWindowDays = 7 + +// ReplyDeficit is how many replies a mailbox owes, counting its next send, for +// replies to be target percent of its warmup sends; zero or less is at or ahead. +func ReplyDeficit(target, sent, replied int) float64 { + if target <= 0 { + return 0 + } + return float64(min(target, 100))/100*float64(sent+1) - float64(replied) +} + +// ReplyDue reports whether the next send should be a reply. roll is uniform in +// [0,1), so a fractional deficit is a chance and a whole one is certain. +func ReplyDue(deficit, roll float64) bool { + return deficit >= 1 || (deficit > 0 && roll < deficit) +} + +// RecoverySignals are the reads that decide whether a sender gets recovery +// engagement. Any of them may be nil. +type RecoverySignals struct { + Health interface { + GetHealthState(context.Context, uuid.UUID) (models.WarmupHealthState, *time.Time, error) + } + Mailboxes interface { + GetByID(context.Context, uuid.UUID) (*models.Email, *errx.Error) + } + Campaigns interface { + CountActiveCampaignsForAccount(context.Context, uuid.UUID) (int, error) + } +} + +// Recovering reports whether the sender's warmup mail is answered and rescued +// first: its standing is watch or throttled, it is a consumer Gmail or +// Outlook.com mailbox, or it backs a live campaign, whose cold mail draws few replies. +func (r RecoverySignals) Recovering(ctx context.Context, sender uuid.UUID) bool { + if r.Health != nil { + state, _, err := r.Health.GetHealthState(ctx, sender) + if err == nil && (state == models.WarmupHealthWatch || state == models.WarmupHealthThrottled) { + return true + } + } + if r.Mailboxes != nil { + if m, xerr := r.Mailboxes.GetByID(ctx, sender); xerr == nil && m != nil && m.ConsumerMailbox() { + return true + } + } + if r.Campaigns == nil { + return false + } + n, err := r.Campaigns.CountActiveCampaignsForAccount(ctx, sender) + return err == nil && n > 0 +} diff --git a/internal/app/warmupramp/reply_test.go b/internal/app/warmupramp/reply_test.go new file mode 100644 index 000000000..bac5ae088 --- /dev/null +++ b/internal/app/warmupramp/reply_test.go @@ -0,0 +1,63 @@ +package warmupramp + +import ( + "math" + "math/rand" + "testing" +) + +func TestReplyDeficit(t *testing.T) { + for _, tc := range []struct { + name string + target, sent, replied int + want float64 + }{ + {"replies off", 0, 40, 0, 0}, + {"fresh mailbox owes a share of its first send", 30, 0, 0, 0.3}, + {"behind", 30, 19, 2, 4}, + {"on target", 50, 9, 5, 0}, + {"ahead", 30, 9, 6, -3}, + {"over 100 reads as 100", 150, 1, 0, 2}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := ReplyDeficit(tc.target, tc.sent, tc.replied); math.Abs(got-tc.want) > 1e-9 { + t.Fatalf("ReplyDeficit(%d,%d,%d)=%v, want %v", tc.target, tc.sent, tc.replied, got, tc.want) + } + }) + } +} + +func TestReplyDue(t *testing.T) { + if ReplyDue(0, 0) || ReplyDue(-1, 0) { + t.Fatal("a mailbox at or ahead of its share was made to reply") + } + if !ReplyDue(1, 0.99) || !ReplyDue(2.5, 0.99) { + t.Fatal("a mailbox a whole reply behind was left a new thread") + } + if !ReplyDue(0.4, 0.39) || ReplyDue(0.4, 0.4) { + t.Fatal("a fractional deficit is not a chance of that size") + } +} + +// The share converges on the setting whether arrivals answer most of the +// owed mail or, as at a high send rate, almost none of it. +func TestReplyShareConvergesOnTarget(t *testing.T) { + rng := rand.New(rand.NewSource(7)) + for _, target := range []int{0, 10, 30, 60, 100} { + for _, arrivalBinds := range []float64{0, 0.1, 0.9} { + sent, replied := 0, 0 + for range 2000 { + deficit := ReplyDeficit(target, sent, replied) + arrival := deficit > 0 && rng.Float64() < arrivalBinds*float64(target)/100 + if arrival || ReplyDue(deficit, rng.Float64()) { + replied++ + } + sent++ + } + share := float64(replied) / float64(sent) * 100 + if math.Abs(share-float64(target)) > 0.5 { + t.Errorf("target %d%% with arrival binds %.0f%%: share %.2f%%", target, arrivalBinds*100, share) + } + } + } +} diff --git a/internal/models/campaign.go b/internal/models/campaign.go index 7089f5d8c..1cb504daf 100644 --- a/internal/models/campaign.go +++ b/internal/models/campaign.go @@ -375,8 +375,8 @@ type CampaignEstimateWarmup struct { PerDay int `json:"per_day"` // PerDayWithout is what the same mailboxes warm at with no live campaign. PerDayWithout int `json:"per_day_without"` - // ReplyRate is the least share of their warmup mail pool partners answer - // while the campaign runs, where the partner allows replies. + // ReplyRate is the least chance a pool partner with reply share left answers + // this warmup on arrival while the campaign runs; partners answer it first. ReplyRate int `json:"reply_rate"` } diff --git a/internal/repository/warmup_lineage.go b/internal/repository/warmup_lineage.go index a3d6329cd..b9555e5f4 100644 --- a/internal/repository/warmup_lineage.go +++ b/internal/repository/warmup_lineage.go @@ -8,6 +8,7 @@ import ( "github.com/google/uuid" "github.com/jackc/pgx/v5" + "github.com/warmbly/warmbly/internal/app/warmupramp" "github.com/warmbly/warmbly/internal/pkg/mailhdr" ) @@ -138,13 +139,7 @@ func (r *taskRepository) BindWarmupSuccessor(ctx context.Context, parent, recipi JOIN tasks planned ON planned.id=$1 WHERE successor.task_id=$1 AND wt.task_id=$2 AND wr.internal_id=$3 AND wt.recipient_account_id=$4 AND (planned.scheduled_at IS NULL OR planned.scheduled_at>=wr.created_at+INTERVAL '45 minutes') - AND ea.status='active' AND ea.warmup IS NOT NULL AND ea.warmup_paused_at IS NULL - AND wr.retired_at IS NULL AND wr.created_at>NOW()-INTERVAL '7 days' - AND original.lineage_version=1 AND original.subject<>'' AND wt.conversation_id IS NOT NULL - AND wt.expires_at>NOW() AND wt.sent_retired_at IS NULL - AND wt.conversation_turn+1'' - AND wt.sent_message_id<>'' AND wr.sender_account_id=wt.sender_account_id - AND NOT EXISTS(SELECT 1 FROM warmup_tasks prior WHERE prior.parent_task_id=$2)`, id, parent, internalID, recipient) + AND `+warmupAnswerableSQL, id, parent, internalID, recipient) if err != nil { return false, err } @@ -158,6 +153,100 @@ func (r *taskRepository) BindWarmupSuccessor(ctx context.Context, parent, recipi return true, tx.Commit(ctx) } +// warmupAnswerableSQL is when received warmup mail may still be answered, over aliases wt, original, wr and ea (the recipient). +const warmupAnswerableSQL = `ea.status='active' AND ea.warmup IS NOT NULL AND ea.warmup_paused_at IS NULL + AND wr.retired_at IS NULL AND wr.created_at>NOW()-INTERVAL '7 days' + AND original.lineage_version=1 AND original.subject<>'' AND wt.conversation_id IS NOT NULL + AND wt.expires_at>NOW() AND wt.sent_retired_at IS NULL + AND wt.conversation_turn+1'' + AND wt.sent_message_id<>'' AND wr.sender_account_id=wt.sender_account_id + AND NOT EXISTS(SELECT 1 FROM warmup_tasks prior WHERE prior.parent_task_id=wt.task_id)` + +// WarmupReplyShareRepository holds a mailbox's warmup replies to its configured share of its sends. +type WarmupReplyShareRepository interface { + WarmupReplyShare(context.Context, uuid.UUID) (int, int, error) + OwedWarmupReplies(context.Context, uuid.UUID, int) ([]WarmupOwedReply, error) + BindClaimedWarmupReply(context.Context, uuid.UUID, uuid.UUID, uuid.UUID, uuid.UUID) (bool, error) +} + +// WarmupOwedReply is received warmup mail the mailbox could answer now. +type WarmupOwedReply struct { + ParentTaskID uuid.UUID + ReceivedID uuid.UUID + SenderID uuid.UUID + Parent WarmupReplyCandidate +} + +// WarmupReplyShare is the mailbox's warmup sends and replies over the share window, as the analytics count them. +func (r *taskRepository) WarmupReplyShare(ctx context.Context, mailbox uuid.UUID) (int, int, error) { + var sent, replied int + err := r.db.QueryRow(ctx, `SELECT COALESCE(SUM(emails_sent),0),COALESCE(SUM(emails_replied),0) FROM warmup_statistics + WHERE email_account_id=$1 AND date>(NOW() AT TIME ZONE 'UTC')::date-$2::int`, mailbox, warmupramp.ReplyShareWindowDays).Scan(&sent, &replied) + return sent, replied, err +} + +// OwedWarmupReplies lists verified warmup mail the mailbox received at least 45 minutes ago and can still answer, newest first. +func (r *taskRepository) OwedWarmupReplies(ctx context.Context, recipient uuid.UUID, limit int) ([]WarmupOwedReply, error) { + rows, err := r.db.Query(ctx, `SELECT wt.task_id, wr.internal_id, wt.sender_account_id, + wr.message_id, original.subject, wr.provider_thread_id, + COALESCE(wt.conversation_theme,''),COALESCE(wt.content_source,''),wt.conversation_id,wt.conversation_turn, + COALESCE(original.reference_ids,'{}'::text[]),original.scenario_version,original.rendering_version,original.max_turns + FROM warmup_received wr + JOIN warmup_tokens wt ON wt.task_id=wr.task_id AND wt.recipient_account_id=wr.email_account_id + JOIN warmup_tasks original ON original.task_id=wt.task_id + JOIN email_accounts ea ON ea.id=wr.email_account_id + WHERE wr.email_account_id=$1 AND wr.created_at<=NOW()-INTERVAL '45 minutes' + AND `+warmupAnswerableSQL+` + ORDER BY wr.created_at DESC LIMIT $2`, recipient, limit) + if err != nil { + return nil, err + } + defer rows.Close() + var out []WarmupOwedReply + for rows.Next() { + var o WarmupOwedReply + c := &o.Parent + if err := rows.Scan(&o.ParentTaskID, &o.ReceivedID, &o.SenderID, &c.MessageID, &c.Subject, &c.ThreadID, &c.ConversationTheme, &c.ContentSource, &c.ConversationID, &c.ConversationTurn, &c.References, &c.ScenarioVersion, &c.RenderingVersion, &c.MaxTurns); err != nil { + return nil, err + } + out = append(out, o) + } + return out, rows.Err() +} + +// BindClaimedWarmupReply makes the mailbox's claimed, unpublished plain send the reply to one owed message. +func (r *taskRepository) BindClaimedWarmupReply(ctx context.Context, task, recipient, parent, internalID uuid.UUID) (bool, error) { + tx, err := r.db.Begin(ctx) + if err != nil { + return false, err + } + defer tx.Rollback(ctx) + if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtext('warmup_task_' || $1::text))`, recipient); err != nil { + return false, err + } + if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtext('warmup_parent_' || $1::text))`, parent); err != nil { + return false, err + } + tag, err := tx.Exec(ctx, `UPDATE warmup_tasks successor + SET target_account_id=wt.sender_account_id, parent_task_id=$2, parent_received_id=$3, parent_message_id=wr.message_id + FROM tasks claimed, warmup_tokens wt JOIN warmup_tasks original ON original.task_id=wt.task_id + JOIN warmup_received wr ON wr.task_id=wt.task_id AND wr.email_account_id=wt.recipient_account_id + JOIN email_accounts ea ON ea.id=wt.recipient_account_id + WHERE successor.task_id=$1 AND claimed.id=$1 AND claimed.email_account_id=$4 + AND claimed.task_type='warmup' AND claimed.status='active' + AND successor.target_account_id IS NULL AND successor.parent_task_id IS NULL AND successor.dispatch_nonce IS NULL + AND wt.task_id=$2 AND wr.internal_id=$3 AND wt.recipient_account_id=$4 + AND wr.created_at<=NOW()-INTERVAL '45 minutes' + AND `+warmupAnswerableSQL, task, parent, internalID, recipient) + if err != nil { + return false, err + } + if tag.RowsAffected() == 0 { + return false, nil + } + return true, tx.Commit(ctx) +} + func (r *taskRepository) ExactWarmupParent(ctx context.Context, successor uuid.UUID) (*WarmupReplyCandidate, error) { c := &WarmupReplyCandidate{} err := r.db.QueryRow(ctx, `SELECT wr.message_id, original.subject, wr.provider_thread_id, diff --git a/internal/repository/warmup_reply_share_live_test.go b/internal/repository/warmup_reply_share_live_test.go new file mode 100644 index 000000000..7689aae0a --- /dev/null +++ b/internal/repository/warmup_reply_share_live_test.go @@ -0,0 +1,76 @@ +package repository + +import ( + "testing" + "time" + + "github.com/google/uuid" +) + +func TestLiveReplyShareAnswersOwedMailOnAClaimedSend(t *testing.T) { + f, r := lineageFixture(t) + ctx := t.Context() + exec := func(query string, args ...any) { + t.Helper() + if _, err := f.pool.Exec(ctx, query, args...); err != nil { + t.Fatal(err) + } + } + exec(`INSERT INTO warmup_tasks(task_id,lineage_version,subject,scenario_version,rendering_version,max_turns) + VALUES($1,1,'Pinned diagnostic','diagnostic-v1','canonical-v1',3)`, f.task) + exec(`INSERT INTO warmup_tokens(token,task_id,sender_account_id,recipient_account_id,conversation_id,conversation_turn,sent_message_id) + VALUES($1,$2,$3,$4,$5,0,'<[EMAIL]>')`, uuid.New(), f.task, f.sender, f.recipient, uuid.New()) + receipt := uuid.New() + exec(`INSERT INTO warmup_received(email_account_id,internal_id,sender_account_id,message_id,created_at) + VALUES($1,$2,$3,'[EMAIL]',NOW()-INTERVAL '10 minutes')`, f.recipient, receipt, f.sender) + if err := r.RecordVerifiedWarmupParent(ctx, f.task, f.recipient, receipt, "thread", WarmupReceiptProof{SenderAddress: f.senderTo}); err != nil { + t.Fatal(err) + } + + owed, err := r.OwedWarmupReplies(ctx, f.recipient, 8) + if err != nil || len(owed) != 0 { + t.Fatalf("mail younger than the reply delay was offered: %d %v", len(owed), err) + } + exec(`UPDATE warmup_received SET created_at=NOW()-INTERVAL '2 hours' WHERE internal_id=$1`, receipt) + owed, err = r.OwedWarmupReplies(ctx, f.recipient, 8) + if err != nil || len(owed) != 1 || owed[0].ParentTaskID != f.task || owed[0].SenderID != f.sender || owed[0].Parent.MessageID != "[EMAIL]" { + t.Fatalf("owed reply not offered: %+v %v", owed, err) + } + + pending, due := uuid.New(), time.Now() + created, err := r.CreateWarmupTaskWithLock(ctx, &Task{ID: pending, EmailAccountID: f.recipient, TaskType: "warmup", Status: "pending", ScheduledAt: &due}, &WarmupTask{TaskID: pending}) + if err != nil || !created { + t.Fatalf("create pending: %v %v", created, err) + } + if bound, err := r.BindClaimedWarmupReply(ctx, pending, f.recipient, f.task, receipt); err != nil || bound { + t.Fatalf("an unclaimed send was bound: %v %v", bound, err) + } + exec(`UPDATE tasks SET status='active' WHERE id=$1`, pending) + claimed := pending + if bound, err := r.BindClaimedWarmupReply(ctx, claimed, f.sender, f.task, receipt); err != nil || bound { + t.Fatalf("another mailbox answered mail it never received: %v %v", bound, err) + } + if bound, err := r.BindClaimedWarmupReply(ctx, claimed, f.recipient, f.task, receipt); err != nil || !bound { + t.Fatalf("claimed send not bound to the owed reply: %v %v", bound, err) + } + var parent, target *uuid.UUID + if err := f.pool.QueryRow(ctx, `SELECT parent_task_id,target_account_id FROM warmup_tasks WHERE task_id=$1`, claimed).Scan(&parent, &target); err != nil { + t.Fatal(err) + } + if parent == nil || *parent != f.task || target == nil || *target != f.sender { + t.Fatalf("reply authority missing: parent=%v target=%v", parent, target) + } + if c, err := r.ExactWarmupParent(ctx, claimed); err != nil || c == nil { + t.Fatalf("bound reply has no exact parent: %v %v", c, err) + } + if owed, err := r.OwedWarmupReplies(ctx, f.recipient, 8); err != nil || len(owed) != 0 { + t.Fatalf("answered mail still offered: %d %v", len(owed), err) + } + + exec(`INSERT INTO warmup_statistics(email_account_id,date,emails_sent,emails_replied,target_volume) VALUES + ($1,(NOW() AT TIME ZONE 'UTC')::date,10,3,0),($1,(NOW() AT TIME ZONE 'UTC')::date-6,4,1,0),($1,(NOW() AT TIME ZONE 'UTC')::date-7,50,0,0)`, f.recipient) + sent, replied, err := r.WarmupReplyShare(ctx, f.recipient) + if err != nil || sent != 14 || replied != 4 { + t.Fatalf("share window = %d sent %d replied (%v), want 14 and 4", sent, replied, err) + } +} diff --git a/internal/tasks/email_task.go b/internal/tasks/email_task.go index f3a4e60b4..49ba1f034 100644 --- a/internal/tasks/email_task.go +++ b/internal/tasks/email_task.go @@ -303,6 +303,10 @@ func (s *tasksService) HandleEmailTask(task *proto.ProcessTask) *errx.Error { if warmupTask.TargetAccountID != nil && (warmupTask.ParentTaskID == nil || partner == nil) { return s.closeWarmupThread(ctx, taskID, account.ID) } + // A plain send answers owed mail while the mailbox's reply share is behind its setting. + if partner == nil { + partner = s.owedWarmupReply(ctx, taskID, account, poolType) + } // A directed task IS the reply; the reply-rate draw already happened when // it was scheduled. Rolling again here would square the rate, so a 30% // reply rate would answer 9% of the time. @@ -1156,8 +1160,11 @@ func (s *tasksService) directedWarmupPartner(ctx context.Context, taskID uuid.UU if err != nil || warmupTask == nil || warmupTask.TargetAccountID == nil { return nil } - target := *warmupTask.TargetAccountID + return s.replyPartner(ctx, taskID, *warmupTask.TargetAccountID, account, poolType) +} +// replyPartner is target when this mailbox may answer it now, or nil. +func (s *tasksService) replyPartner(ctx context.Context, taskID, target uuid.UUID, account *Email, poolType string) *Email { if s.warmupHealth != nil { ok, reason, herr := s.warmupHealth.CanParticipate(ctx, target, poolType) if herr != nil { diff --git a/internal/tasks/warmup_reply_share.go b/internal/tasks/warmup_reply_share.go new file mode 100644 index 000000000..4b89e79e1 --- /dev/null +++ b/internal/tasks/warmup_reply_share.go @@ -0,0 +1,73 @@ +package tasks + +import ( + "context" + "math/rand" + "sort" + + "github.com/google/uuid" + "github.com/rs/zerolog/log" + + "github.com/warmbly/warmbly/internal/app/warmupramp" + "github.com/warmbly/warmbly/internal/repository" +) + +// owedReplyCandidates bounds how much received mail one send considers answering. +const owedReplyCandidates = 8 + +// owedWarmupReply makes a claimed plain send the reply to received warmup mail +// when the mailbox's reply share is behind its setting, answering recovering +// senders first. Nil leaves the send a new thread. +func (s *tasksService) owedWarmupReply(ctx context.Context, taskID uuid.UUID, account *Email, poolType string) *Email { + if account == nil || account.WarmupReplyRate <= 0 || !account.IsWarmingActive() { + return nil + } + share, ok := s.taskRepo.(repository.WarmupReplyShareRepository) + if !ok { + return nil + } + sent, replied, err := share.WarmupReplyShare(ctx, account.ID) + if err != nil || !warmupramp.ReplyDue(warmupramp.ReplyDeficit(account.WarmupReplyRate, sent, replied), rand.Float64()) { + return nil + } + owed, err := share.OwedWarmupReplies(ctx, account.ID, owedReplyCandidates) + if err != nil || len(owed) == 0 { + return nil + } + signals := warmupramp.RecoverySignals{} + if s.warmupRepo != nil { + signals.Health = s.warmupRepo + } + if s.emailRepo != nil { + signals.Mailboxes = s.emailRepo + } + if s.campaignRepo != nil { + signals.Campaigns = s.campaignRepo + } + recovering := make(map[uuid.UUID]bool, len(owed)) + for _, o := range owed { + if _, seen := recovering[o.SenderID]; !seen { + recovering[o.SenderID] = signals.Recovering(ctx, o.SenderID) + } + } + sort.SliceStable(owed, func(i, j int) bool { return recovering[owed[i].SenderID] && !recovering[owed[j].SenderID] }) + + for _, o := range owed { + if _, _, _, err := s.exactReplyContent(ctx, &o.Parent, *account); err != nil { + continue + } + partner := s.replyPartner(ctx, taskID, o.SenderID, account, poolType) + if partner == nil { + continue + } + bound, err := share.BindClaimedWarmupReply(ctx, taskID, account.ID, o.ParentTaskID, o.ReceivedID) + if err != nil { + log.Warn().Err(err).Str("task_id", taskID.String()).Str("email_account_id", account.ID.String()).Msg("warmup reply share: could not bind an owed reply") + return nil + } + if bound { + return partner + } + } + return nil +} diff --git a/web/src/components/app/campaigns/new/EstimateInsights.tsx b/web/src/components/app/campaigns/new/EstimateInsights.tsx index da3cc800e..cc4d9be5f 100644 --- a/web/src/components/app/campaigns/new/EstimateInsights.tsx +++ b/web/src/components/app/campaigns/new/EstimateInsights.tsx @@ -30,7 +30,7 @@ export function WarmupNote({ e, className }: { e: CampaignEstimateResult; classN Warmup keeps running on {plural(w.mailboxes, "mailbox", "mailboxes")} {without > now ? `, down from about ${without} to ${now} a day each` : `, about ${now} a day each`} while this runs. - {w.reply_rate ? ` Pool partners reply to at least ${w.reply_rate}% of it.` : ""} + {w.reply_rate ? " Pool partners answer it before other warmup mail." : ""}

); @@ -99,7 +99,7 @@ export function MailboxMix({ e, limit, className }: { e: CampaignEstimateResult; {!!w.reply_rate && ( - Pool partners reply to at least {w.reply_rate}% of that warmup (where the partner allows replies) and read, rescue from spam + Pool partners answer that warmup before other warmup mail (within each partner's own reply rate) and read, rescue from spam and mark more of it important, so each mailbox keeps getting replies while most cold leads do not answer. Those replies use the partner's own warmup sends, so they add no volume. diff --git a/web/src/components/app/emails/InboxDetails.tsx b/web/src/components/app/emails/InboxDetails.tsx index 3e15512e8..73d898153 100644 --- a/web/src/components/app/emails/InboxDetails.tsx +++ b/web/src/components/app/emails/InboxDetails.tsx @@ -1613,7 +1613,7 @@ function WarmupTab({ form, update, status, mailbox, canWarmup = true }: { form: {baseOverMax && (

Starting volume can't exceed the maximum.

)} - + update({ warmup_reply_rate: v })} suffix="%" min={cloudMin} /> {/* Warmbly Cloud writes its own content, so the segment only applies to warmup sent from here. */} From 522ea35d143f0032f7a424f5aae470ee2a9c33fb Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Mon, 2 Nov 2026 09:17:29 +0100 Subject: [PATCH 072/318] feat: prioritize eligible recovery senders before limiting warmup reply candidates and clarify reply targets --- .github/workflows/ci.yml | 2 +- docs/content/docs/api/reference/mailboxes.mdx | 2 +- docs/content/docs/guides/warmup.mdx | 8 +- internal/repository/warmup_lineage.go | 51 +++++++++--- .../warmup_reply_share_live_test.go | 81 +++++++++++++++++++ internal/tasks/warmup_reply_share.go | 19 ----- .../app/campaigns/new/EstimateInsights.tsx | 2 +- .../components/app/emails/InboxDetails.tsx | 2 +- 8 files changed, 131 insertions(+), 36 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a9597e969..b2eb66894 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -350,7 +350,7 @@ jobs: WARMBLY_TEST_DB: postgres://warmbly:warmbly@127.0.0.1:5432/warmbly_test?sslmode=disable run: | set -o pipefail - go test -race ./internal/repository -run '^TestLive(Monitoring|LastWarmupSendFailure|PersistentMailboxLoadingFailure|DispatchRetry|LineageQueueRevisions|AdminPlatformOverview|WarmupRecoversOldPreparation|WarmupPreparationRecoveryRetains|WarmupFilingRequiresAcknowledgement|WarmupFilingAuthority|WarmupTimeWindow|WarmupInvalidWindow|StoppedRecipientIsNeverAddressed)' -count=1 + go test -race ./internal/repository -run '^TestLive(Monitoring|LastWarmupSendFailure|PersistentMailboxLoadingFailure|DispatchRetry|LineageQueueRevisions|ReplyShare|AdminPlatformOverview|WarmupRecoversOldPreparation|WarmupPreparationRecoveryRetains|WarmupFilingRequiresAcknowledgement|WarmupFilingAuthority|WarmupTimeWindow|WarmupInvalidWindow|StoppedRecipientIsNeverAddressed)' -count=1 go test -race -v ./internal/tasks -run '^Test(LiveWarmup(SafetyHoldReschedules|Recovery|UnknownRetirement|TaskDoesNotApplyResults|DispatchDefersInvalidHours)|WarmupSenderDistinguishes)' -count=1 | tee warmup-recovery.log if grep -q -- '--- SKIP: TestLiveWarmupUnknownRetirement' warmup-recovery.log; then exit 1; fi for test in TestLiveWarmupUnknownRetirementPreservesEvidenceAndFencesReplayOnce TestLiveWarmupUnknownRetirementAllowsDistinctNewSendAndKeepsCooldown TestLiveWarmupUnknownRetirementAndDefinitiveResultSerialize TestLiveWarmupUnknownRetirementSkipsProtectedRowsWithoutStarvingLaterMailboxes TestLiveWarmupUnknownRetirementReconcilerSeedsOnceAndClearsActiveWarnings; do diff --git a/docs/content/docs/api/reference/mailboxes.mdx b/docs/content/docs/api/reference/mailboxes.mdx index 10aca5c28..b0de61d92 100644 --- a/docs/content/docs/api/reference/mailboxes.mdx +++ b/docs/content/docs/api/reference/mailboxes.mdx @@ -159,7 +159,7 @@ Auth: **Scope** `WRITE_EMAILS` ยท **Org permission** `manage_emails` | `warmup_base` | integer | no | Warmup starting volume per day. | | `warmup_max` | integer | no | Warmup daily ceiling. | | `warmup_increase` | integer | no | Per-day warmup ramp increment. | -| `warmup_reply_rate` | integer | no | Percentage of the mailbox's own warmup sends that are replies, held over its last seven days. `0` turns warmup replies off. | +| `warmup_reply_rate` | integer | no | Target percentage of the mailbox's own warmup sends that are replies over its last seven UTC days. Eligible received mail and partner availability can limit the measured rate. `0` turns warmup replies off. | | `warmup_tag` | string | no | Tag applied to warmup threads. | | `warmup_start_time` | string | no | Daily warmup window start, `HH:MM`. | | `warmup_end_time` | string | no | Daily warmup window end, `HH:MM`. | diff --git a/docs/content/docs/guides/warmup.mdx b/docs/content/docs/guides/warmup.mdx index 1c92143ff..ba0a6329d 100644 --- a/docs/content/docs/guides/warmup.mdx +++ b/docs/content/docs/guides/warmup.mdx @@ -254,14 +254,14 @@ Replies continue the exact pinned thread and subject, each parent is answered on Replies thread properly with a real `Re:` subject and `In-Reply-To` header, and candidates must be between 45 minutes and seven days old, so nothing is answered instantly or revived indefinitely. -The **Reply rate** setting is the share of a mailbox's own warmup sends that are replies, and Warmbly holds the mailbox to it. Over its last seven UTC days of warmup, a mailbox set to `30%` sends about three replies for every ten warmup emails, the same figure the Analytics tab reports. Replies never add volume: each one takes the place of a send the mailbox was going to make anyway. `0%` turns replies off. +The **Reply rate** setting targets the share of a mailbox's own warmup sends that are replies over its last seven UTC days. With enough eligible received mail, a mailbox set to `30%` approaches three replies for every ten warmup emails. The Analytics tab reports the measured rate over its selected range, which defaults to the last 30 days, so the figures can differ. Replies never add volume: each one takes the place of a send the mailbox was going to make anyway. `0%` turns replies off. Replies reach that share two ways: -- **On arrival.** When a verified warmup email arrives and the mailbox is below its share, it sometimes points its next scheduled send back at whoever wrote, 45 minutes to 5 hours later and inside its own warmup hours. The chance is the mailbox's reply rate (raised for a sender in [recovery](#recovery-engagement)), drawn once when the reply is scheduled rather than again when it sends. Each mailbox has one warmup send queued at a time, so a reply-back moves that send earlier and aims it, and never pushes a send the mailbox had already planned sooner. If that send is due within 45 minutes of the arrival, or is already answering someone, the arrival is not answered then. -- **When a send goes out.** If the mailbox is still below its share when its next new-thread send fires, that send answers warmup mail it received instead: something at least 45 minutes and at most seven days old that it has not answered, newest first and mail from a sender in [recovery](#recovery-engagement) before any other. A mailbox ahead of its share does not reply until its sends catch up. +- **On arrival.** When a verified warmup email arrives, Warmbly includes the next send in its target calculation. If that leaves room for a reply, it sometimes points the next scheduled send back at whoever wrote, 45 minutes to 5 hours later and inside its own warmup hours. The chance is the mailbox's reply rate (raised for a sender in [recovery](#recovery-engagement)), drawn once when the reply is scheduled rather than again when it sends. Each mailbox has one warmup send queued at a time, so a reply-back moves that send earlier and aims it, and never pushes a send the mailbox had already planned sooner. If that send is due within 45 minutes of the arrival, or is already answering someone, the arrival is not answered then. +- **When a send goes out.** Warmbly calculates the replies needed to reach the target, including the next send. A deficit of one reply or more makes the send a reply when eligible mail is available; a fractional deficit becomes a reply chance. For example, a `25%` target with ten sends and two replies gives the next send a `75%` reply chance. Because the calculation includes the next send, it can allow a reply when the current share is slightly above target. A selected reply answers mail at least 45 minutes and at most seven days old that the mailbox has not answered. Mail from senders in [recovery](#recovery-engagement) is considered first, then newest first within each group. -Together these help the measured rate converge on the setting, including for busy mailboxes whose next send is almost always less than 45 minutes away. Small send counts and a recent setting change can make it differ temporarily. The rate can fall short when eligible received mail is unavailable, threads have reached their message caps, or the partners that wrote to it can no longer receive. Reply selection considers a bounded set of recent messages on each send, so unavailable recent partners can also delay catch-up. +Together these help the measured rate converge on the setting, including for busy mailboxes whose next send is almost always less than 45 minutes away. Small send counts and a recent setting change can make it differ temporarily. The rate can fall short when eligible received mail is unavailable, threads have reached their message caps, or the partners that wrote to it can no longer receive. Reply selection considers a bounded set of messages on each send, with recovery priority applied before that limit, so unavailable partners among those candidates can also delay catch-up. A reply is held to the same daily receiving cap as any other warmup email: a reply to an inbox that is full for the day is not sent, and the mailbox goes on with another reply or a new thread, so one busy partner never stops a mailbox's warmup. Replies stop before a thread reaches its message cap so replies cannot answer replies indefinitely. A reply crosses the free and paid tiers like the mail it answers: a paid mailbox answers a free partner that wrote to it, and a free mailbox answers a paid one while it is healthy and its workspace is in good standing. diff --git a/internal/repository/warmup_lineage.go b/internal/repository/warmup_lineage.go index b9555e5f4..b7e1a41ef 100644 --- a/internal/repository/warmup_lineage.go +++ b/internal/repository/warmup_lineage.go @@ -9,6 +9,7 @@ import ( "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/warmbly/warmbly/internal/app/warmupramp" + "github.com/warmbly/warmbly/internal/models" "github.com/warmbly/warmbly/internal/pkg/mailhdr" ) @@ -185,19 +186,51 @@ func (r *taskRepository) WarmupReplyShare(ctx context.Context, mailbox uuid.UUID return sent, replied, err } -// OwedWarmupReplies lists verified warmup mail the mailbox received at least 45 minutes ago and can still answer, newest first. -func (r *taskRepository) OwedWarmupReplies(ctx context.Context, recipient uuid.UUID, limit int) ([]WarmupOwedReply, error) { - rows, err := r.db.Query(ctx, `SELECT wt.task_id, wr.internal_id, wt.sender_account_id, - wr.message_id, original.subject, wr.provider_thread_id, - COALESCE(wt.conversation_theme,''),COALESCE(wt.content_source,''),wt.conversation_id,wt.conversation_turn, - COALESCE(original.reference_ids,'{}'::text[]),original.scenario_version,original.rendering_version,original.max_turns - FROM warmup_received wr +const owedWarmupRepliesFromSQL = `FROM warmup_received wr JOIN warmup_tokens wt ON wt.task_id=wr.task_id AND wt.recipient_account_id=wr.email_account_id JOIN warmup_tasks original ON original.task_id=wt.task_id JOIN email_accounts ea ON ea.id=wr.email_account_id WHERE wr.email_account_id=$1 AND wr.created_at<=NOW()-INTERVAL '45 minutes' - AND `+warmupAnswerableSQL+` - ORDER BY wr.created_at DESC LIMIT $2`, recipient, limit) + AND ` + warmupAnswerableSQL + +// recoveringWarmupReplySenders classifies every eligible sender before limiting the messages considered for a reply. +func (r *taskRepository) recoveringWarmupReplySenders(ctx context.Context, recipient uuid.UUID) ([]uuid.UUID, error) { + rows, err := r.db.Query(ctx, `WITH senders AS (SELECT DISTINCT wt.sender_account_id AS id `+owedWarmupRepliesFromSQL+`) + SELECT sender.id, sender.mail_host, sender.provider, sender.email, COALESCE(h.health_state,'healthy'), + EXISTS (`+strings.ReplaceAll(activeCampaignsForAccountSQL, "$1", "s.id")+`) + FROM senders s JOIN email_accounts sender ON sender.id=s.id + LEFT JOIN LATERAL (`+warmupGateStandingSQL("s.id")+`) h ON true`, recipient) + if err != nil { + return nil, err + } + defer rows.Close() + priority := []uuid.UUID{} + for rows.Next() { + var sender models.Email + var health models.WarmupHealthState + var campaigning bool + if err := rows.Scan(&sender.ID, &sender.MailHost, &sender.Provider, &sender.Email, &health, &campaigning); err != nil { + return nil, err + } + if health == models.WarmupHealthWatch || health == models.WarmupHealthThrottled || sender.ConsumerMailbox() || campaigning { + priority = append(priority, sender.ID) + } + } + return priority, rows.Err() +} + +// OwedWarmupReplies applies recovery priority before the limit, then orders eligible messages newest first. +func (r *taskRepository) OwedWarmupReplies(ctx context.Context, recipient uuid.UUID, limit int) ([]WarmupOwedReply, error) { + priority, err := r.recoveringWarmupReplySenders(ctx, recipient) + if err != nil { + return nil, err + } + rows, err := r.db.Query(ctx, `SELECT wt.task_id, wr.internal_id, wt.sender_account_id, + wr.message_id, original.subject, wr.provider_thread_id, + COALESCE(wt.conversation_theme,''),COALESCE(wt.content_source,''),wt.conversation_id,wt.conversation_turn, + COALESCE(original.reference_ids,'{}'::text[]),original.scenario_version,original.rendering_version,original.max_turns + `+owedWarmupRepliesFromSQL+` + ORDER BY (wt.sender_account_id=ANY($3::uuid[])) DESC, wr.created_at DESC, wt.task_id LIMIT $2`, recipient, limit, priority) if err != nil { return nil, err } diff --git a/internal/repository/warmup_reply_share_live_test.go b/internal/repository/warmup_reply_share_live_test.go index 7689aae0a..9e3ecdd22 100644 --- a/internal/repository/warmup_reply_share_live_test.go +++ b/internal/repository/warmup_reply_share_live_test.go @@ -1,6 +1,7 @@ package repository import ( + "context" "testing" "time" @@ -74,3 +75,83 @@ func TestLiveReplyShareAnswersOwedMailOnAClaimedSend(t *testing.T) { t.Fatalf("share window = %d sent %d replied (%v), want 14 and 4", sent, replied, err) } } + +func TestLiveReplySharePrioritizesRecoveryBeforeCandidateLimit(t *testing.T) { + for _, tc := range []struct { + name, health, host, provider, address string + campaign bool + }{ + {name: "watch", health: "watch"}, + {name: "throttled", health: "throttled"}, + {name: "consumer Gmail", host: "google_workspace", provider: "gmail", address: "reply-priority@gmail.com"}, + {name: "consumer Outlook", provider: "outlook", address: "reply-priority@hotmail.co.uk"}, + {name: "stored consumer host", host: "outlook"}, + {name: "active campaign", campaign: true}, + } { + t.Run(tc.name, func(t *testing.T) { + f, r := lineageFixture(t) + ctx := t.Context() + exec := func(query string, args ...any) { + t.Helper() + if _, err := f.pool.Exec(ctx, query, args...); err != nil { + t.Fatal(err) + } + } + normal := uuid.New() + exec(`INSERT INTO email_accounts(id,user_id,organization_id,email,name,signature_plain,signature_html,provider,status) + VALUES($1,$2,$3,$4,'Partner','','','smtp_imap','active')`, normal, f.user, f.org, normal.String()+"@example.test") + seed := func(task, sender uuid.UUID, age time.Duration) { + t.Helper() + if task != f.task { + exec(`INSERT INTO tasks(id,task_type,email_account_id,status,message_id) VALUES($1,'warmup',$2,'completed','')`, task, sender) + } + exec(`INSERT INTO warmup_tasks(task_id,lineage_version,subject,scenario_version,rendering_version,max_turns) + VALUES($1,1,'Project notes','diagnostic-v1','canonical-v1',3)`, task) + messageID := task.String() + "@example.test" + exec(`INSERT INTO warmup_tokens(token,task_id,sender_account_id,recipient_account_id,conversation_id,conversation_turn,sent_message_id) + VALUES($1,$2,$3,$4,$5,0,$6)`, uuid.New(), task, sender, f.recipient, uuid.New(), "<"+messageID+">") + receipt := uuid.New() + exec(`INSERT INTO warmup_received(email_account_id,internal_id,sender_account_id,message_id,created_at) + VALUES($1,$2,$3,$4,$5)`, f.recipient, receipt, sender, messageID, time.Now().Add(-age)) + address := f.senderTo + if sender == normal { + address = normal.String() + "@example.test" + } + if err := r.RecordVerifiedWarmupParent(ctx, task, f.recipient, receipt, "thread", WarmupReceiptProof{SenderAddress: address}); err != nil { + t.Fatal(err) + } + } + seed(f.task, f.sender, 3*time.Hour) + newerRecovery := uuid.New() + seed(newerRecovery, f.sender, 2*time.Hour) + for i := range 8 { + seed(uuid.New(), normal, time.Hour+time.Duration(i)*time.Minute) + } + owed, err := r.OwedWarmupReplies(ctx, f.recipient, 8) + if err != nil || len(owed) != 8 || owed[0].SenderID != normal || owed[7].SenderID != normal { + t.Fatalf("ordinary messages not ordered newest first: %+v %v", owed, err) + } + if tc.health != "" { + exec(`INSERT INTO warmup_pool_participants(pool_id,email_account_id,health_state) + SELECT id,$1,$2 FROM warmup_pools WHERE pool_type='free'`, f.sender, tc.health) + } + if tc.host != "" || tc.provider != "" { + exec(`UPDATE email_accounts SET mail_host=$2,provider=COALESCE(NULLIF($3,''),'smtp_imap')::email_provider,email=COALESCE(NULLIF($4,''),email) WHERE id=$1`, f.sender, tc.host, tc.provider, tc.address) + } + if tc.campaign { + campaign := uuid.New() + exec(`INSERT INTO campaigns(id,user_id,organization_id,name,description,days,status,created_at,updated_at) VALUES($1,$2,$3,'Priority','',62,'active',NOW(),NOW())`, campaign, f.user, f.org) + exec(`INSERT INTO campaign_senders(campaign_id,email_account_id) VALUES($1,$2)`, campaign, f.sender) + t.Cleanup(func() { + if _, err := f.pool.Exec(context.Background(), `DELETE FROM campaigns WHERE id=$1`, campaign); err != nil { + t.Error(err) + } + }) + } + owed, err = r.OwedWarmupReplies(ctx, f.recipient, 8) + if err != nil || len(owed) != 8 || owed[0].ParentTaskID != newerRecovery || owed[1].ParentTaskID != f.task || owed[2].SenderID != normal { + t.Fatalf("older recovery mail not prioritized before the limit: %+v %v", owed, err) + } + }) + } +} diff --git a/internal/tasks/warmup_reply_share.go b/internal/tasks/warmup_reply_share.go index 4b89e79e1..b4021595f 100644 --- a/internal/tasks/warmup_reply_share.go +++ b/internal/tasks/warmup_reply_share.go @@ -3,7 +3,6 @@ package tasks import ( "context" "math/rand" - "sort" "github.com/google/uuid" "github.com/rs/zerolog/log" @@ -34,24 +33,6 @@ func (s *tasksService) owedWarmupReply(ctx context.Context, taskID uuid.UUID, ac if err != nil || len(owed) == 0 { return nil } - signals := warmupramp.RecoverySignals{} - if s.warmupRepo != nil { - signals.Health = s.warmupRepo - } - if s.emailRepo != nil { - signals.Mailboxes = s.emailRepo - } - if s.campaignRepo != nil { - signals.Campaigns = s.campaignRepo - } - recovering := make(map[uuid.UUID]bool, len(owed)) - for _, o := range owed { - if _, seen := recovering[o.SenderID]; !seen { - recovering[o.SenderID] = signals.Recovering(ctx, o.SenderID) - } - } - sort.SliceStable(owed, func(i, j int) bool { return recovering[owed[i].SenderID] && !recovering[owed[j].SenderID] }) - for _, o := range owed { if _, _, _, err := s.exactReplyContent(ctx, &o.Parent, *account); err != nil { continue diff --git a/web/src/components/app/campaigns/new/EstimateInsights.tsx b/web/src/components/app/campaigns/new/EstimateInsights.tsx index cc4d9be5f..0ee49b07f 100644 --- a/web/src/components/app/campaigns/new/EstimateInsights.tsx +++ b/web/src/components/app/campaigns/new/EstimateInsights.tsx @@ -30,7 +30,7 @@ export function WarmupNote({ e, className }: { e: CampaignEstimateResult; classN Warmup keeps running on {plural(w.mailboxes, "mailbox", "mailboxes")} {without > now ? `, down from about ${without} to ${now} a day each` : `, about ${now} a day each`} while this runs. - {w.reply_rate ? " Pool partners answer it before other warmup mail." : ""} + {w.reply_rate ? " Pool partners prioritize replies to it within their own reply settings." : ""}

); diff --git a/web/src/components/app/emails/InboxDetails.tsx b/web/src/components/app/emails/InboxDetails.tsx index 73d898153..efad8dff8 100644 --- a/web/src/components/app/emails/InboxDetails.tsx +++ b/web/src/components/app/emails/InboxDetails.tsx @@ -1613,7 +1613,7 @@ function WarmupTab({ form, update, status, mailbox, canWarmup = true }: { form: {baseOverMax && (

Starting volume can't exceed the maximum.

)} - + update({ warmup_reply_rate: v })} suffix="%" min={cloudMin} /> {/* Warmbly Cloud writes its own content, so the segment only applies to warmup sent from here. */} From 55964fa40fc94b18d7d70b6aee70c71182c97957 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Mon, 2 Nov 2026 09:30:44 +0100 Subject: [PATCH 073/318] feat: continue warmup reply selection past unavailable candidates while preserving send budgets --- .github/workflows/ci.yml | 2 +- docs/content/docs/guides/warmup.mdx | 2 +- internal/repository/warmup_lineage.go | 20 ++- .../warmup_reply_share_live_test.go | 22 ++- internal/tasks/warmup_reply_share.go | 51 ++++--- .../tasks/warmup_reply_share_live_test.go | 131 ++++++++++++++++++ 6 files changed, 197 insertions(+), 31 deletions(-) create mode 100644 internal/tasks/warmup_reply_share_live_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b2eb66894..f4aaef62c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -351,7 +351,7 @@ jobs: run: | set -o pipefail go test -race ./internal/repository -run '^TestLive(Monitoring|LastWarmupSendFailure|PersistentMailboxLoadingFailure|DispatchRetry|LineageQueueRevisions|ReplyShare|AdminPlatformOverview|WarmupRecoversOldPreparation|WarmupPreparationRecoveryRetains|WarmupFilingRequiresAcknowledgement|WarmupFilingAuthority|WarmupTimeWindow|WarmupInvalidWindow|StoppedRecipientIsNeverAddressed)' -count=1 - go test -race -v ./internal/tasks -run '^Test(LiveWarmup(SafetyHoldReschedules|Recovery|UnknownRetirement|TaskDoesNotApplyResults|DispatchDefersInvalidHours)|WarmupSenderDistinguishes)' -count=1 | tee warmup-recovery.log + go test -race -v ./internal/tasks -run '^Test(LiveWarmup(SafetyHoldReschedules|Recovery|UnknownRetirement|TaskDoesNotApplyResults|DispatchDefersInvalidHours|ReplyShare)|WarmupSenderDistinguishes)' -count=1 | tee warmup-recovery.log if grep -q -- '--- SKIP: TestLiveWarmupUnknownRetirement' warmup-recovery.log; then exit 1; fi for test in TestLiveWarmupUnknownRetirementPreservesEvidenceAndFencesReplayOnce TestLiveWarmupUnknownRetirementAllowsDistinctNewSendAndKeepsCooldown TestLiveWarmupUnknownRetirementAndDefinitiveResultSerialize TestLiveWarmupUnknownRetirementSkipsProtectedRowsWithoutStarvingLaterMailboxes TestLiveWarmupUnknownRetirementReconcilerSeedsOnceAndClearsActiveWarnings; do grep -q -- "--- PASS: $test " warmup-recovery.log || exit 1 diff --git a/docs/content/docs/guides/warmup.mdx b/docs/content/docs/guides/warmup.mdx index ba0a6329d..2ef039899 100644 --- a/docs/content/docs/guides/warmup.mdx +++ b/docs/content/docs/guides/warmup.mdx @@ -261,7 +261,7 @@ Replies reach that share two ways: - **On arrival.** When a verified warmup email arrives, Warmbly includes the next send in its target calculation. If that leaves room for a reply, it sometimes points the next scheduled send back at whoever wrote, 45 minutes to 5 hours later and inside its own warmup hours. The chance is the mailbox's reply rate (raised for a sender in [recovery](#recovery-engagement)), drawn once when the reply is scheduled rather than again when it sends. Each mailbox has one warmup send queued at a time, so a reply-back moves that send earlier and aims it, and never pushes a send the mailbox had already planned sooner. If that send is due within 45 minutes of the arrival, or is already answering someone, the arrival is not answered then. - **When a send goes out.** Warmbly calculates the replies needed to reach the target, including the next send. A deficit of one reply or more makes the send a reply when eligible mail is available; a fractional deficit becomes a reply chance. For example, a `25%` target with ten sends and two replies gives the next send a `75%` reply chance. Because the calculation includes the next send, it can allow a reply when the current share is slightly above target. A selected reply answers mail at least 45 minutes and at most seven days old that the mailbox has not answered. Mail from senders in [recovery](#recovery-engagement) is considered first, then newest first within each group. -Together these help the measured rate converge on the setting, including for busy mailboxes whose next send is almost always less than 45 minutes away. Small send counts and a recent setting change can make it differ temporarily. The rate can fall short when eligible received mail is unavailable, threads have reached their message caps, or the partners that wrote to it can no longer receive. Reply selection considers a bounded set of messages on each send, with recovery priority applied before that limit, so unavailable partners among those candidates can also delay catch-up. +Together these help the measured rate converge on the setting, including for busy mailboxes whose next send is almost always less than 45 minutes away. Small send counts and a recent setting change can make it differ temporarily. The rate can fall short when eligible received mail is unavailable, threads have reached their message caps, or the partners that wrote to it can no longer receive. Reply selection proceeds in batches with recovery priority, continuing past messages with unavailable content or partners until it finds a usable reply or exhausts the candidates. A reply is held to the same daily receiving cap as any other warmup email: a reply to an inbox that is full for the day is not sent, and the mailbox goes on with another reply or a new thread, so one busy partner never stops a mailbox's warmup. Replies stop before a thread reaches its message cap so replies cannot answer replies indefinitely. A reply crosses the free and paid tiers like the mail it answers: a paid mailbox answers a free partner that wrote to it, and a free mailbox answers a paid one while it is healthy and its workspace is in good standing. diff --git a/internal/repository/warmup_lineage.go b/internal/repository/warmup_lineage.go index b7e1a41ef..8c703576a 100644 --- a/internal/repository/warmup_lineage.go +++ b/internal/repository/warmup_lineage.go @@ -166,7 +166,7 @@ const warmupAnswerableSQL = `ea.status='active' AND ea.warmup IS NOT NULL AND ea // WarmupReplyShareRepository holds a mailbox's warmup replies to its configured share of its sends. type WarmupReplyShareRepository interface { WarmupReplyShare(context.Context, uuid.UUID) (int, int, error) - OwedWarmupReplies(context.Context, uuid.UUID, int) ([]WarmupOwedReply, error) + OwedWarmupReplies(context.Context, uuid.UUID, int, WarmupReplyExclusions) ([]WarmupOwedReply, error) BindClaimedWarmupReply(context.Context, uuid.UUID, uuid.UUID, uuid.UUID, uuid.UUID) (bool, error) } @@ -178,6 +178,12 @@ type WarmupOwedReply struct { Parent WarmupReplyCandidate } +// WarmupReplyExclusions keeps rejected messages and unavailable senders from occupying later batches. +type WarmupReplyExclusions struct { + Parents []uuid.UUID + Senders []uuid.UUID +} + // WarmupReplyShare is the mailbox's warmup sends and replies over the share window, as the analytics count them. func (r *taskRepository) WarmupReplyShare(ctx context.Context, mailbox uuid.UUID) (int, int, error) { var sent, replied int @@ -191,15 +197,17 @@ const owedWarmupRepliesFromSQL = `FROM warmup_received wr JOIN warmup_tasks original ON original.task_id=wt.task_id JOIN email_accounts ea ON ea.id=wr.email_account_id WHERE wr.email_account_id=$1 AND wr.created_at<=NOW()-INTERVAL '45 minutes' + AND wt.task_id<>ALL(COALESCE($2::uuid[],'{}'::uuid[])) + AND wt.sender_account_id<>ALL(COALESCE($3::uuid[],'{}'::uuid[])) AND ` + warmupAnswerableSQL // recoveringWarmupReplySenders classifies every eligible sender before limiting the messages considered for a reply. -func (r *taskRepository) recoveringWarmupReplySenders(ctx context.Context, recipient uuid.UUID) ([]uuid.UUID, error) { +func (r *taskRepository) recoveringWarmupReplySenders(ctx context.Context, recipient uuid.UUID, excluded WarmupReplyExclusions) ([]uuid.UUID, error) { rows, err := r.db.Query(ctx, `WITH senders AS (SELECT DISTINCT wt.sender_account_id AS id `+owedWarmupRepliesFromSQL+`) SELECT sender.id, sender.mail_host, sender.provider, sender.email, COALESCE(h.health_state,'healthy'), EXISTS (`+strings.ReplaceAll(activeCampaignsForAccountSQL, "$1", "s.id")+`) FROM senders s JOIN email_accounts sender ON sender.id=s.id - LEFT JOIN LATERAL (`+warmupGateStandingSQL("s.id")+`) h ON true`, recipient) + LEFT JOIN LATERAL (`+warmupGateStandingSQL("s.id")+`) h ON true`, recipient, excluded.Parents, excluded.Senders) if err != nil { return nil, err } @@ -220,8 +228,8 @@ func (r *taskRepository) recoveringWarmupReplySenders(ctx context.Context, recip } // OwedWarmupReplies applies recovery priority before the limit, then orders eligible messages newest first. -func (r *taskRepository) OwedWarmupReplies(ctx context.Context, recipient uuid.UUID, limit int) ([]WarmupOwedReply, error) { - priority, err := r.recoveringWarmupReplySenders(ctx, recipient) +func (r *taskRepository) OwedWarmupReplies(ctx context.Context, recipient uuid.UUID, limit int, excluded WarmupReplyExclusions) ([]WarmupOwedReply, error) { + priority, err := r.recoveringWarmupReplySenders(ctx, recipient, excluded) if err != nil { return nil, err } @@ -230,7 +238,7 @@ func (r *taskRepository) OwedWarmupReplies(ctx context.Context, recipient uuid.U COALESCE(wt.conversation_theme,''),COALESCE(wt.content_source,''),wt.conversation_id,wt.conversation_turn, COALESCE(original.reference_ids,'{}'::text[]),original.scenario_version,original.rendering_version,original.max_turns `+owedWarmupRepliesFromSQL+` - ORDER BY (wt.sender_account_id=ANY($3::uuid[])) DESC, wr.created_at DESC, wt.task_id LIMIT $2`, recipient, limit, priority) + ORDER BY (wt.sender_account_id=ANY($5::uuid[])) DESC, wr.created_at DESC, wt.task_id LIMIT $4`, recipient, excluded.Parents, excluded.Senders, limit, priority) if err != nil { return nil, err } diff --git a/internal/repository/warmup_reply_share_live_test.go b/internal/repository/warmup_reply_share_live_test.go index 9e3ecdd22..4e6a7fb25 100644 --- a/internal/repository/warmup_reply_share_live_test.go +++ b/internal/repository/warmup_reply_share_live_test.go @@ -28,12 +28,12 @@ func TestLiveReplyShareAnswersOwedMailOnAClaimedSend(t *testing.T) { t.Fatal(err) } - owed, err := r.OwedWarmupReplies(ctx, f.recipient, 8) + owed, err := r.OwedWarmupReplies(ctx, f.recipient, 8, WarmupReplyExclusions{}) if err != nil || len(owed) != 0 { t.Fatalf("mail younger than the reply delay was offered: %d %v", len(owed), err) } exec(`UPDATE warmup_received SET created_at=NOW()-INTERVAL '2 hours' WHERE internal_id=$1`, receipt) - owed, err = r.OwedWarmupReplies(ctx, f.recipient, 8) + owed, err = r.OwedWarmupReplies(ctx, f.recipient, 8, WarmupReplyExclusions{}) if err != nil || len(owed) != 1 || owed[0].ParentTaskID != f.task || owed[0].SenderID != f.sender || owed[0].Parent.MessageID != "[EMAIL]" { t.Fatalf("owed reply not offered: %+v %v", owed, err) } @@ -64,7 +64,7 @@ func TestLiveReplyShareAnswersOwedMailOnAClaimedSend(t *testing.T) { if c, err := r.ExactWarmupParent(ctx, claimed); err != nil || c == nil { t.Fatalf("bound reply has no exact parent: %v %v", c, err) } - if owed, err := r.OwedWarmupReplies(ctx, f.recipient, 8); err != nil || len(owed) != 0 { + if owed, err := r.OwedWarmupReplies(ctx, f.recipient, 8, WarmupReplyExclusions{}); err != nil || len(owed) != 0 { t.Fatalf("answered mail still offered: %d %v", len(owed), err) } @@ -127,7 +127,7 @@ func TestLiveReplySharePrioritizesRecoveryBeforeCandidateLimit(t *testing.T) { for i := range 8 { seed(uuid.New(), normal, time.Hour+time.Duration(i)*time.Minute) } - owed, err := r.OwedWarmupReplies(ctx, f.recipient, 8) + owed, err := r.OwedWarmupReplies(ctx, f.recipient, 8, WarmupReplyExclusions{}) if err != nil || len(owed) != 8 || owed[0].SenderID != normal || owed[7].SenderID != normal { t.Fatalf("ordinary messages not ordered newest first: %+v %v", owed, err) } @@ -148,10 +148,22 @@ func TestLiveReplySharePrioritizesRecoveryBeforeCandidateLimit(t *testing.T) { } }) } - owed, err = r.OwedWarmupReplies(ctx, f.recipient, 8) + owed, err = r.OwedWarmupReplies(ctx, f.recipient, 8, WarmupReplyExclusions{}) if err != nil || len(owed) != 8 || owed[0].ParentTaskID != newerRecovery || owed[1].ParentTaskID != f.task || owed[2].SenderID != normal { t.Fatalf("older recovery mail not prioritized before the limit: %+v %v", owed, err) } + excluded := WarmupReplyExclusions{} + for _, o := range owed { + excluded.Parents = append(excluded.Parents, o.ParentTaskID) + } + remaining, err := r.OwedWarmupReplies(ctx, f.recipient, 8, excluded) + if err != nil || len(remaining) != 2 || remaining[0].SenderID != normal || remaining[1].SenderID != normal { + t.Fatalf("next batch did not advance past attempted parents: %+v %v", remaining, err) + } + remaining, err = r.OwedWarmupReplies(ctx, f.recipient, 8, WarmupReplyExclusions{Senders: []uuid.UUID{f.sender}}) + if err != nil || len(remaining) != 8 || remaining[0].SenderID != normal || remaining[7].SenderID != normal { + t.Fatalf("unavailable recovery sender hid ordinary mail: %+v %v", remaining, err) + } }) } } diff --git a/internal/tasks/warmup_reply_share.go b/internal/tasks/warmup_reply_share.go index b4021595f..9e429ebc4 100644 --- a/internal/tasks/warmup_reply_share.go +++ b/internal/tasks/warmup_reply_share.go @@ -11,7 +11,7 @@ import ( "github.com/warmbly/warmbly/internal/repository" ) -// owedReplyCandidates bounds how much received mail one send considers answering. +// owedReplyCandidates bounds each batch, not the total mail considered for a send. const owedReplyCandidates = 8 // owedWarmupReply makes a claimed plain send the reply to received warmup mail @@ -29,25 +29,40 @@ func (s *tasksService) owedWarmupReply(ctx context.Context, taskID uuid.UUID, ac if err != nil || !warmupramp.ReplyDue(warmupramp.ReplyDeficit(account.WarmupReplyRate, sent, replied), rand.Float64()) { return nil } - owed, err := share.OwedWarmupReplies(ctx, account.ID, owedReplyCandidates) - if err != nil || len(owed) == 0 { - return nil - } - for _, o := range owed { - if _, _, _, err := s.exactReplyContent(ctx, &o.Parent, *account); err != nil { - continue - } - partner := s.replyPartner(ctx, taskID, o.SenderID, account, poolType) - if partner == nil { - continue - } - bound, err := share.BindClaimedWarmupReply(ctx, taskID, account.ID, o.ParentTaskID, o.ReceivedID) - if err != nil { - log.Warn().Err(err).Str("task_id", taskID.String()).Str("email_account_id", account.ID.String()).Msg("warmup reply share: could not bind an owed reply") + excluded := repository.WarmupReplyExclusions{} + partners := make(map[uuid.UUID]*Email) + for ctx.Err() == nil { + owed, err := share.OwedWarmupReplies(ctx, account.ID, owedReplyCandidates, excluded) + if err != nil || len(owed) == 0 { return nil } - if bound { - return partner + for _, o := range owed { + excluded.Parents = append(excluded.Parents, o.ParentTaskID) + if _, _, _, err := s.exactReplyContent(ctx, &o.Parent, *account); err != nil { + continue + } + partner, checked := partners[o.SenderID] + if !checked { + partner = s.replyPartner(ctx, taskID, o.SenderID, account, poolType) + partners[o.SenderID] = partner + if partner == nil { + excluded.Senders = append(excluded.Senders, o.SenderID) + } + } + if partner == nil { + continue + } + bound, err := share.BindClaimedWarmupReply(ctx, taskID, account.ID, o.ParentTaskID, o.ReceivedID) + if err != nil { + log.Warn().Err(err).Str("task_id", taskID.String()).Str("email_account_id", account.ID.String()).Msg("warmup reply share: could not bind an owed reply") + return nil + } + if bound { + return partner + } + } + if len(owed) < owedReplyCandidates { + return nil } } return nil diff --git a/internal/tasks/warmup_reply_share_live_test.go b/internal/tasks/warmup_reply_share_live_test.go new file mode 100644 index 000000000..23270c853 --- /dev/null +++ b/internal/tasks/warmup_reply_share_live_test.go @@ -0,0 +1,131 @@ +package tasks + +import ( + "context" + "testing" + "time" + + "github.com/google/uuid" + warmupapp "github.com/warmbly/warmbly/internal/app/warmup" + "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/pkg/generation" + "github.com/warmbly/warmbly/internal/repository" +) + +func TestLiveWarmupReplyShareContinuesPastUnavailableCandidates(t *testing.T) { + for _, reason := range []string{"pool eligibility", "routing exclusion", "full inbox", "missing content", "all unavailable"} { + t.Run(reason, func(t *testing.T) { + f := newPartnerRoutingFixture(t) + ctx := t.Context() + exec := func(query string, args ...any) { + t.Helper() + if _, err := f.pool.Exec(ctx, query, args...); err != nil { + t.Fatal(err) + } + } + t.Cleanup(func() { + for _, query := range []string{ + `DELETE FROM warmup_received WHERE email_account_id IN(SELECT id FROM email_accounts WHERE organization_id=$1)`, + `DELETE FROM warmup_tokens WHERE sender_account_id IN(SELECT id FROM email_accounts WHERE organization_id=$1)`, + `DELETE FROM tasks WHERE email_account_id IN(SELECT id FROM email_accounts WHERE organization_id=$1)`, + } { + if _, err := f.pool.Exec(context.Background(), query, f.org); err != nil { + t.Error(err) + } + } + }) + f.svc.taskRepo = repository.NewTaskRepository(f.pool) + f.svc.warmupHealth = warmupapp.NewService(f.svc.warmupRepo) + share := f.svc.taskRepo.(repository.WarmupReplyShareRepository) + lineage := f.svc.taskRepo.(repository.WarmupLineageRepository) + sender, xerr := f.svc.emailRepo.GetByID(ctx, f.sender.ID) + if xerr != nil { + t.Fatal(xerr) + } + f.sender = *sender + now := time.Now() + f.sender.Warmup, f.sender.WarmupReplyRate = &now, 100 + exec(`UPDATE email_accounts SET mail_host='outlook' WHERE id=$1`, f.atWorkspace) + conv := warmupConversations()[0] + seed := func(sender uuid.UUID, age time.Duration) uuid.UUID { + t.Helper() + task, receipt := uuid.New(), uuid.New() + messageID := task.String() + "@example.test" + exec(`INSERT INTO tasks(id,task_type,email_account_id,status,message_id) VALUES($1,'warmup',$2,'completed','')`, task, sender) + exec(`INSERT INTO warmup_tasks(task_id,lineage_version,subject,scenario_version,rendering_version,max_turns) + VALUES($1,1,$2,$3,$4,$5)`, task, conv.Subject, conv.Version, generation.CanonicalRenderingVersion, len(conv.Messages)+1) + exec(`INSERT INTO warmup_tokens(token,task_id,sender_account_id,recipient_account_id,conversation_id,conversation_turn,sent_message_id,content_source) + VALUES($1,$2,$3,$4,$5,0,$6,'static')`, uuid.New(), task, sender, f.sender.ID, conv.ID, "<"+messageID+">") + exec(`INSERT INTO warmup_received(email_account_id,internal_id,sender_account_id,message_id,created_at) + VALUES($1,$2,$3,$4,$5)`, f.sender.ID, receipt, sender, messageID, now.Add(-age)) + account, xerr := f.svc.emailRepo.GetByID(ctx, sender) + if xerr != nil { + t.Fatal(xerr) + } + if err := lineage.RecordVerifiedWarmupParent(ctx, task, f.sender.ID, receipt, "thread", repository.WarmupReceiptProof{SenderAddress: account.Email}); err != nil { + t.Fatal(err) + } + return task + } + ordinary := seed(f.atSmallHost, 2*time.Hour) + for range owedReplyCandidates { + seed(f.atWorkspace, time.Hour) + } + pool := "free" + switch reason { + case "pool eligibility", "all unavailable": + exec(`DELETE FROM warmup_pool_participants WHERE email_account_id=$1`, f.atWorkspace) + if reason == "all unavailable" { + exec(`DELETE FROM warmup_pool_participants WHERE email_account_id=$1`, f.atSmallHost) + } + case "routing exclusion": + pool = "premium" + exec(`UPDATE warmup_pool_participants SET pool_id=$2 WHERE email_account_id IN(SELECT id FROM email_accounts WHERE organization_id=$1)`, f.org, models.WarmupPoolPremiumID) + f.svc.warmupRoutingRepo = ruleRepo{rules: excludeDomain("acme.test")} + case "full inbox": + exec(`INSERT INTO warmup_received(email_account_id,internal_id,sender_account_id,message_id) + SELECT $1,gen_random_uuid(),$2,'' FROM generate_series(1,1000)`, f.atWorkspace, f.sender.ID) + case "missing content": + exec(`UPDATE warmup_tokens SET conversation_id=$2 WHERE sender_account_id=$1`, f.atWorkspace, uuid.New()) + } + claimed := uuid.New() + exec(`INSERT INTO tasks(id,task_type,email_account_id,status,message_id) VALUES($1,'warmup',$2,'active','')`, claimed, f.sender.ID) + warmupTask := &repository.WarmupTask{TaskID: claimed} + if err := f.svc.taskRepo.CreateWarmupTask(ctx, warmupTask); err != nil { + t.Fatal(err) + } + first, err := share.OwedWarmupReplies(ctx, f.sender.ID, owedReplyCandidates, repository.WarmupReplyExclusions{}) + if err != nil || len(first) != owedReplyCandidates || first[0].SenderID != f.atWorkspace || first[len(first)-1].SenderID != f.atWorkspace { + t.Fatalf("fixture did not put unavailable recovery mail in the first batch: %+v %v", first, err) + } + if reason != "all unavailable" { + next, err := share.OwedWarmupReplies(ctx, f.sender.ID, owedReplyCandidates, repository.WarmupReplyExclusions{Senders: []uuid.UUID{f.atWorkspace}}) + if err != nil || len(next) != 1 || next[0].ParentTaskID != ordinary { + t.Fatalf("ordinary message missing after excluding unavailable sender: %+v %v", next, err) + } + if _, _, _, err := f.svc.exactReplyContent(ctx, &next[0].Parent, f.sender); err != nil { + t.Fatalf("ordinary message cannot be rendered: %v", err) + } + if f.svc.replyPartner(ctx, claimed, f.atSmallHost, &f.sender, pool) == nil { + t.Fatal("ordinary partner cannot receive") + } + } + partner := f.svc.owedWarmupReply(ctx, claimed, &f.sender, pool) + bound, err := f.svc.taskRepo.GetWarmupTask(ctx, claimed) + if err != nil { + t.Fatal(err) + } + if reason == "all unavailable" { + if partner != nil || bound.ParentTaskID != nil { + t.Fatalf("unavailable partners were answered: %+v %+v", partner, bound) + } + } else if partner == nil || partner.ID != f.atSmallHost || bound.ParentTaskID == nil || *bound.ParentTaskID != ordinary { + t.Fatalf("usable ordinary mail beyond the first batch was not answered: %+v %+v", partner, bound) + } + var sends int + if err := f.pool.QueryRow(ctx, `SELECT COUNT(*) FROM tasks WHERE email_account_id=$1 AND task_type='warmup'`, f.sender.ID).Scan(&sends); err != nil || sends != 1 { + t.Fatalf("reply selection changed the sender's planned volume: %d %v", sends, err) + } + }) + } +} From f4a40e52e3d800c743433c64b78963aee00e236c Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Mon, 2 Nov 2026 11:12:16 +0100 Subject: [PATCH 074/318] feat: honor explicit warmup sending days independently of campaign weekdays and explain effective schedules in mailbox settings --- docs/content/docs/api/endpoints.mdx | 2 + .../docs/development/deployment-guide.mdx | 6 + docs/content/docs/guides/sending-behavior.mdx | 8 +- docs/content/docs/guides/warmbly-cloud.mdx | 4 +- docs/content/docs/guides/warmup.mdx | 8 +- internal/app/behavior/plan_test.go | 24 ++++ internal/app/behavior/service.go | 31 ++++- .../app/cloudlink/warmup_settings_test.go | 2 +- internal/models/poollink.go | 5 +- internal/scheduler/campaign_projection.go | 13 ++- internal/scheduler/warmup_dispatch.go | 3 +- internal/scheduler/warmup_scheduler.go | 80 +++---------- internal/scheduler/warmup_scheduler_test.go | 43 ++++++- qa/fixtures/warmup-schedule.sql | 18 +++ qa/flows/warmup-schedule.flow.ts | 44 +++++++ web/src/app/app/emails/page.tsx | 3 + .../app/campaigns/schedule/WeekdayBitmask.tsx | 1 + .../app/emails/BulkWarmupDialog.tsx | 15 ++- .../components/app/emails/InboxDetails.tsx | 110 ++++++------------ .../app/emails/SendingBehaviorTab.tsx | 2 +- .../app/emails/WarmupDaysPicker.test.tsx | 35 ++++++ .../app/emails/WarmupDaysPicker.tsx | 51 ++++++++ .../api/hooks/app/emails/useUpdateEmail.ts | 1 + .../app/emails/useUpdateSendingBehavior.ts | 1 + web/src/lib/warmupSchedule.ts | 9 ++ 25 files changed, 350 insertions(+), 169 deletions(-) create mode 100644 qa/fixtures/warmup-schedule.sql create mode 100644 qa/flows/warmup-schedule.flow.ts create mode 100644 web/src/components/app/emails/WarmupDaysPicker.test.tsx create mode 100644 web/src/components/app/emails/WarmupDaysPicker.tsx create mode 100644 web/src/lib/warmupSchedule.ts diff --git a/docs/content/docs/api/endpoints.mdx b/docs/content/docs/api/endpoints.mdx index 7e487c802..1073741c7 100644 --- a/docs/content/docs/api/endpoints.mdx +++ b/docs/content/docs/api/endpoints.mdx @@ -714,6 +714,8 @@ Alongside them, `api_url` is this API's own public base (for a copyable example `PATCH /cloud-link/mailboxes/:id/participation` is self-hosted JWT-only with `MANAGE_EMAILS` and organization ownership. It accepts typed `mode` (`diagnostic` or `off`), `send`, `receive` and optional positive shared/rolling limits. `receive` also authorizes probabilistic spam rescue, reads, importance and stars or flags on verified warmup messages where supported; it does not authorize replies or guarantee reputation improvement. Cloud mirrors it through instance-token-only `PATCH /pool-link/instance/mailboxes/:remoteId/participation`, scoped to the calling instance. These dedicated routes prevent an old Cloud silently ignoring additive consent fields; old state without participation is not explicit diagnostic consent. The existing native lifecycle routes select diagnostic send/receive on start/resume and complete off on stop while retaining history. See [participation and send safety](/development/send-safety/). +For locally warmed mailboxes, `PATCH /emails/:id` accepts `warmup_days` as a Monday-first bitmask (Monday = 1, Sunday = 64). A nonzero mask selects the exact warmup days: `127` includes every day and `96` selects weekends, independently of the sending plan's campaign working days. `0` follows the enabled sending plan's working days, or every day with Fixed schedule. Sending-plan hours and breaks still apply within the warmup window. Saving replaces the queued warmup time. See [warmup schedules](/guides/warmup/). + For a mailbox Warmbly Cloud warms, `PATCH /emails/:id` sends `warmup_base`, `warmup_max`, `warmup_increase`, `warmup_reply_rate`, `warmup_start_time`, `warmup_end_time`, `warmup_days` and `warmup` (as pause or resume) to Warmbly Cloud through instance-token-only `PATCH /pool-link/instance/mailboxes/:remoteId`, then stores the values Cloud reports. The rest of the patch is written locally only once Cloud has applied its part, and the timezone travels with it. `test_mode`, `test_send_enabled`, `test_receive_enabled`, `shared_daily_limit` and `rolling_recipient_limit` return `409 cloud_warmup_managed`; use the participation route above. `POST /emails/:id/warmup/start` and `/resume` resume the mailbox on Cloud, `/pause` pauses it there, and `/stop` returns `409 cloud_warmup_managed`. `GET /cloud-link/mailboxes` rows carry `settings_observed_at`, when the local copy last matched Cloud. See [warmup settings](/guides/warmbly-cloud/#warmup-settings) and [the refusals](/api/error-codes/#warmbly-cloud-warmup-refusals). Cloud-managed OAuth additionally exposes `POST /pool-link/instance/oauth/start-correlated`, `POST /pool-link/instance/oauth/finish-correlated` and `POST /pool-link/instance/mailboxes/adopt-correlated`, all instance-token only and requiring `protocol: 1`. The authenticated instance response advertises `managed_consent_protocol: 1`. Legacy routes remain unchanged; absence of the capability cannot be bypassed with fields an old replica might ignore. See [the Cloud route and recovery contract](/guides/warmbly-cloud/). diff --git a/docs/content/docs/development/deployment-guide.mdx b/docs/content/docs/development/deployment-guide.mdx index 7fb4d3ef6..42f44d636 100644 --- a/docs/content/docs/development/deployment-guide.mdx +++ b/docs/content/docs/development/deployment-guide.mdx @@ -844,6 +844,12 @@ make upgrade # git pull --ff-only, then make up; migrations appl Upgrading is safe with data in place: migrations are forward-only and apply on backend boot. +### Warmup day selection across versions + +Explicit warmup-day selection uses the existing `warmup_days` mask, with no migration or new worker message. The current and immediately previous application releases can read each other's values and queued tasks. A rollback preserves saved day selections. A zero mask retains inherited working days with an enabled sending plan and every day with Fixed schedule. + +Upgrade the backend and consumer together, including Cloud's copies when it owns warmup. An older scheduler still intersects explicit warmup days with the sending plan's working days, and an older Cloud-sync reader can normalize all seven days to zero. Explicit weekend sending is consistent once those older processes have drained. Rolling back restores the previous scheduling policy without deleting selected days; keep all writers on the current release to preserve explicit all-day choices through Cloud sync. + ### Updates without lost work A service being replaced finishes what it started, as long as the platform gives it the time to: diff --git a/docs/content/docs/guides/sending-behavior.mdx b/docs/content/docs/guides/sending-behavior.mdx index 97b3d5f7c..21bb541e2 100644 --- a/docs/content/docs/guides/sending-behavior.mdx +++ b/docs/content/docs/guides/sending-behavior.mdx @@ -41,8 +41,8 @@ Check today's rolled workday at the top of the tab to see when the mailbox will - It can only lower volume or delay a send. It never raises a mailbox above its own daily cap. - Times are local to the mailbox's timezone, or the workspace timezone when it has none. - Editing the ranges does not change today. The new ranges apply from the next roll. -- Warmup keeps the same working days and hours, but does not count against the cold limits. -- Warmup waits for the workday too, so a mailbox connected after its hours end sends its first warmup email at the start of the next working day. The mailbox list shows when the next one is queued. +- Warmup uses the workday hours and break within its own sending window. It follows working days only when its **Sending days** is set to **Follow sending plan**. Explicit warmup days, including weekends, take precedence for warmup alone. +- Warmup waits for the workday too, so a mailbox connected after its hours end sends its first warmup email at the next allowed warmup window. The mailbox list shows when the next one is queued. - Switching to Fixed schedule, back again, or changing the working days moves the mailbox's queued warmup send, and the next send of every active campaign it backs, straight away onto whichever schedule now applies. @@ -75,7 +75,7 @@ While it is off, the rest of the tab is greyed out and read-only, because none o | Setting | Default range | What it controls | |---------|---------------|------------------| -| Working days | Mon-Fri | Days this mailbox sends anything at all, cold and warmup alike | +| Working days | Mon-Fri | Campaign working days; also warmup days when following the sending plan | | Workday start | `09:03` to `09:27` | The mailbox opens at a different minute each day | | Workday finish | `17:18` to `17:56` | Nothing is scheduled after the day's rolled finish | | Lunch break | starts `12:00`-`13:30`, lasts `30`-`60` min | A quiet gap in the middle of the day | @@ -112,7 +112,7 @@ Sending behavior can only ever **lower** volume or **delay** a send. It can neve - The day's rolled target is applied as a minimum against the mailbox's daily cap and the campaign's daily limit. If the mailbox and campaign are capped at `50` and the day rolls `31`, the day is at most `31`. Setting a ceiling of `30` clips any higher roll to `30`; raise the ceiling if you want the whole configured range available. More capacity does not guarantee more sends: leads, windows, warmup graduation and other safety controls still apply. - The delay range replaces the mailbox's fixed minimum gap while behavior is on. - A campaign's own sending windows still apply. A send has to satisfy both calendars: the campaign's window in the campaign timezone, and the mailbox's workday in the mailbox timezone. -- Warmup follows the same working days, hours, and break, so warmup mail is not arriving at 03:00 from a mailbox whose campaign mail keeps office hours. Warmup is **not** charged against the cold daily or hourly ceilings; it has its own ramp. +- Warmup follows the same hours and break within its own sending window. Its selected days apply independently; **Follow sending plan** inherits the campaign working days. Warmup is **not** charged against the cold daily or hourly ceilings; it has its own ramp. - Smart send for your own replies follows the workday but is never charged against the cold budgets. diff --git a/docs/content/docs/guides/warmbly-cloud.mdx b/docs/content/docs/guides/warmbly-cloud.mdx index 694130991..d112a5d56 100644 --- a/docs/content/docs/guides/warmbly-cloud.mdx +++ b/docs/content/docs/guides/warmbly-cloud.mdx @@ -58,7 +58,7 @@ Only warmup moves to the cloud. Campaigns, contacts, the unibox, tracking and ev New connections link one local workspace to one Warmbly Cloud workspace. A Cloud workspace can have only one active self-hosted connection, including any older instance-wide link. New connections for different local workspaces need different Cloud workspaces, each with its own plan. Existing server-wide connections keep serving their local workspaces without reconnecting or buying another plan. Self-hosted workspace creation itself is unlimited; hosted creation limits and request-rate protection are unchanged. When you enroll a mailbox, the instance sends that mailbox's SMTP/IMAP credential to the cloud, sealed in transit and at rest with the same envelope encryption the hosted product uses for every customer mailbox. From then on: - Warmbly Cloud sends the mailbox's warmup mail, replies to partners, and rescues, opens and stars the warmup mail it receives, on Warmbly's own workers -- the mailbox's warmup ramp, hours and days belong to Warmbly Cloud from then on, starting from the ones it had on your instance, and its timezone stays your instance's (see [warmup settings](#warmup-settings)). Cloud does not automatically enable its weekday sending-behavior profile for these warmup-only mailboxes. A Cloud profile you explicitly configure still takes precedence while enabled. +- the mailbox's warmup ramp, hours and days belong to Warmbly Cloud from then on, starting from the ones it had on your instance, and its timezone stays your instance's (see [warmup settings](#warmup-settings)). Cloud does not automatically enable its weekday sending-behavior profile for these warmup-only mailboxes. An enabled Cloud sending plan supplies hours and breaks within the warmup window. Explicit warmup days, including weekends, take precedence over its working days. - the cloud reads only verified warmup mail from the mailbox. Everything else that arrives is dropped unread; no history is imported and nothing is stored - your instance stops its own warmup for that mailbox and takes it out of the local warmup pool, so no mailbox on your server writes to it any more, and keeps sending campaigns from it as usual - your instance recognises both received warmup and the mailbox's own Sent copies and leaves them out of your unibox, asking the cloud to vouch for anything it cannot identify on its own @@ -239,7 +239,7 @@ Warmbly Cloud owns an enrolled mailbox's starting volume, daily increase, maximu - Changing a setting on the Warmup tab, or through `PATCH /emails/:id`, sends it to Warmbly Cloud first. You can change the starting volume and other ramp settings while warmup is active without removing or enrolling the mailbox again. It is saved only once Warmbly Cloud has applied it, and the mailbox then shows the values Warmbly Cloud reports. If Warmbly Cloud cannot be reached, nothing changes. If it answers but does not apply a value, the rest of your change is not saved, the error names what was not applied, and the mailbox shows the values Warmbly Cloud reported. - The copy is refreshed whenever the Cloud mailbox list loads, after every change, and every 15 minutes in the background, so a change made in Warmbly Cloud shows up here within 15 minutes. The Warmup tab shows when it was last refreshed. - The timezone stays your instance's, because campaigns use it too. It travels with every change, and the background refresh sends it again whenever Warmbly Cloud's differs. -- Warmbly Cloud does not take 0 from an instance for the starting volume, maximum, daily increase or reply rate, so on an enrolled mailbox those fields start at 1. Sending every day is sent as all seven days. +- Warmbly Cloud does not take 0 from an instance for the starting volume, maximum, daily increase or reply rate, so on an enrolled mailbox those fields start at 1. Sending days are explicit on linked mailboxes: **Every day** is sent and mirrored as all seven days. **Follow sending plan** is available for mailboxes warmed on the current instance; linked mailboxes use the days Cloud reports. - The content segment, warmup placement, folder and retention on your instance do not apply while Warmbly Cloud warms the mailbox, and the Warmup tab hides them. - Participation and the shared daily and recipient limits are changed with the mailbox's Warmbly Cloud controls. Starting, pausing and resuming warmup are sent to Warmbly Cloud; to stop warmup, remove the mailbox from Warmbly Cloud. diff --git a/docs/content/docs/guides/warmup.mdx b/docs/content/docs/guides/warmup.mdx index 2ef039899..43d1dcc27 100644 --- a/docs/content/docs/guides/warmup.mdx +++ b/docs/content/docs/guides/warmup.mdx @@ -220,7 +220,13 @@ The partner cap exists because a mailbox never writes to the same partner twice Warmup hours are read in the mailbox's timezone: its own when one is set on the **Settings** tab of its drawer, otherwise the workspace timezone under **Settings > Profile > Timezones**, and UTC when neither is set. Set the workspace timezone once and every mailbox that follows it reads its warmup hours in the team's day. A mailbox with its own timezone keeps it, and changing the workspace timezone does not change any mailbox's hours. -While [Sending behavior](/guides/sending-behavior/) is on, which it is for a newly connected mailbox (a warmup-only mailbox enrolled from a self-hosted instance starts with it off), warmup only sends when both the warmup hours and that workday allow it, and the Warmup tab says so above the hours. A mailbox connected after its workday ends therefore sends its first warmup email the next working morning. The workday's working days default to Monday to Friday, so warmup skips the weekend even when the warmup days include it. When that happens the Warmup tab names the skipped days, with a button that adds them to the working days (for example **Work Saturday and Sunday too**). Switch the mailbox to **Fixed schedule** on its **Sending** tab to send on the warmup hours and days alone, without the workday. Changing the warmup hours, days or timezone (the mailbox's own, or the workspace's for a mailbox that follows it), or switching sending behavior on or off, moves the queued warmup send at once. The mailbox list shows when the next warmup send is queued under the day's count. +Choose **Sending days** on the **Warmup** tab. **Every day** explicitly includes Saturday and Sunday; **Weekdays** selects Monday to Friday. You can also select individual days. Every selected day applies to warmup, even when the sending plan's working days exclude it. This does not change campaign working days. + +**Follow sending plan** uses the working days on the **Sending** tab, which default to Monday to Friday. With **Fixed schedule**, it means every day. Existing mailboxes with no selected warmup days keep this inherited schedule. The day picker shows the days that apply; selecting a day switches to an explicit warmup schedule. + +While [Sending behavior](/guides/sending-behavior/) is on, warmup uses the overlap between its configured hours and the day's varied workday, including the break. A warmup window starting at 08:00 still waits until 09:15 if that day's workday opens then. On an explicitly selected weekend day, warmup rolls the same hours and break without opening that day for campaigns. The Warmup tab shows the workday's start and end ranges. Switch to **Fixed schedule** on the **Sending** tab to use the warmup hours alone. + +Changing warmup hours, days or timezone, or switching sending behavior on or off, moves the queued warmup send to the new schedule as soon as you save. To recalculate an existing queued time, choose its day preset again and save. The mailbox list refreshes its queued time and shows whether warmup follows the sending plan or an explicit set of days. **Start warmup** for several mailboxes offers the same day presets; **Follow sending plan** resolves separately for each locally warmed mailbox and is hidden when the selection includes a Cloud-linked mailbox. Volume, consent, health and provider restrictions still apply on every selected day. Warmup hours must end later than they start on the same day. Equal or reversed hours are rejected, including a change to only one endpoint that would invalidate the stored window. Existing invalid windows are not widened or corrected automatically: pending sends stay unstarted and recheck after five minutes, while admin monitoring shows **Invalid warmup sending hours** until the configured window is corrected. Other send protections still apply after correction; this does not replay uncertain sends or confirm mailbox recovery. diff --git a/internal/app/behavior/plan_test.go b/internal/app/behavior/plan_test.go index 78b5b882d..c4463b205 100644 --- a/internal/app/behavior/plan_test.go +++ b/internal/app/behavior/plan_test.go @@ -38,6 +38,30 @@ func profile() models.SendingBehavior { return b } +func TestExplicitWarmupWeekendKeepsBreakAndLeavesCampaignClosed(t *testing.T) { + b := profile() + b.WorkStartMin, b.WorkStartMax = 9*60, 9*60 + b.WorkEndMin, b.WorkEndMax = 17*60, 17*60 + b.LunchEnabled = true + b.LunchEarliest, b.LunchLatest = 12*60, 12*60 + b.LunchMinMinutes, b.LunchMaxMinutes = 60, 60 + cold := NewStandalone(b, time.UTC) + warmup := cold.ForWarmup(models.BehaviorWeekdaysAll) + sunday := time.Date(2026, time.October, 11, 12, 30, 0, 0, time.UTC) + at, plan, ok := warmup.NextOpen(sunday) + if !ok || !at.Equal(sunday.Add(30*time.Minute)) || plan.DailyLimit <= 0 || plan.HourlyLimit <= 0 { + t.Fatalf("weekend warmup lost its break or budget: at=%v plan=%+v ok=%v", at, plan, ok) + } + at, _, ok = cold.NextOpen(sunday) + if !ok || at.Weekday() != time.Monday { + t.Fatalf("warmup opened campaign working days: at=%v ok=%v", at, ok) + } + at, _, ok = cold.ForWarmup(0).NextOpen(sunday) + if !ok || at.Weekday() != time.Monday { + t.Fatalf("unconfigured warmup stopped inheriting working days: at=%v ok=%v", at, ok) + } +} + func day(t *testing.T, loc *time.Location, y int, m time.Month, d int) time.Time { t.Helper() return time.Date(y, m, d, 0, 0, 0, 0, loc) diff --git a/internal/app/behavior/service.go b/internal/app/behavior/service.go index 2e85cf292..c9ca23742 100644 --- a/internal/app/behavior/service.go +++ b/internal/app/behavior/service.go @@ -8,6 +8,7 @@ import ( "github.com/google/uuid" + "github.com/warmbly/warmbly/internal/bitmask" "github.com/warmbly/warmbly/internal/models" "github.com/warmbly/warmbly/internal/repository" ) @@ -161,10 +162,11 @@ type Resolved struct { Behavior models.SendingBehavior Loc *time.Location - accountID uuid.UUID - svc *service - ctx context.Context - cache map[string]models.DailyPlan + accountID uuid.UUID + svc *service + ctx context.Context + cache map[string]models.DailyPlan + warmupDays int } // PlanOn returns the plan for a local day. Today's plan is read from (and @@ -172,6 +174,19 @@ type Resolved struct { // are rolled on the fly, since persisting a plan for a day the mailbox has not // reached yet would only freeze settings the customer may still change. func (r Resolved) PlanOn(day time.Time) models.DailyPlan { + if r.warmupDays > 0 { + cold := r + cold.warmupDays = 0 + plan := cold.PlanOn(day) + if !bitmask.HasWeekday(uint8(r.warmupDays), day.Weekday()) { + plan.IsWorkingDay = false + } else if !plan.IsWorkingDay { + b := r.Behavior + b.Weekdays = r.warmupDays + plan = RollPlan(b, day) + } + return plan + } key := day.Format("2006-01-02") if r.cache == nil { // A Resolved built without the constructor (NewStandalone, or a zero @@ -211,6 +226,14 @@ func NewStandalone(b models.SendingBehavior, loc *time.Location) Resolved { return Resolved{Enabled: b.Enabled, Behavior: b, Loc: loc, accountID: b.EmailAccountID} } +// ForWarmup keeps the plan's hours and breaks while honoring explicitly chosen warmup days. +func (r Resolved) ForWarmup(days int) Resolved { + if r.Enabled { + r.warmupDays = days + } + return r +} + // NextOpen is Resolved's binding of the package-level window search. func (r Resolved) NextOpen(from time.Time) (time.Time, models.DailyPlan, bool) { return NextOpen(from, r.Loc, r.PlanOn) diff --git a/internal/app/cloudlink/warmup_settings_test.go b/internal/app/cloudlink/warmup_settings_test.go index f2a6dcdb1..2e330a86e 100644 --- a/internal/app/cloudlink/warmup_settings_test.go +++ b/internal/app/cloudlink/warmup_settings_test.go @@ -147,7 +147,7 @@ func TestRelaySendsOnlyTheRequestedFieldsAndMirrorsCloudsAnswer(t *testing.T) { if !ok || mirrored.Base != 15 || mirrored.Max != 40 || mirrored.StartTime != "08:00:00" { t.Fatalf("mirrored %+v, want the cloud's whole answer", mirrored) } - if got.Base != 15 || got.Days != 0 || got.StartTime != "08:00" || got.EndTime != "20:00" { + if got.Base != 15 || got.Days != models.WarmupEveryDay || got.StartTime != "08:00" || got.EndTime != "20:00" { t.Fatalf("returned %+v, want the cloud's values in local form", got) } } diff --git a/internal/models/poollink.go b/internal/models/poollink.go index 7ff75d265..a902d6c1d 100644 --- a/internal/models/poollink.go +++ b/internal/models/poollink.go @@ -147,7 +147,7 @@ type PoolLinkWarmupSettings struct { Timezone string `json:"timezone"` } -// WarmupEveryDay is the weekday bitmask with all seven days set; locally 0 means the same. +// WarmupEveryDay explicitly selects all seven days, independently of sending-plan weekdays. const WarmupEveryDay = 127 // Reported is false for a settings block an older or broken cloud left empty. @@ -158,9 +158,6 @@ func (w PoolLinkWarmupSettings) Reported() bool { // Mirrored is the cloud's settings in the form this instance stores them. func (w PoolLinkWarmupSettings) Mirrored() PoolLinkWarmupSettings { w.StartTime, w.EndTime = ClockHHMM(w.StartTime), ClockHHMM(w.EndTime) - if w.Days == WarmupEveryDay { - w.Days = 0 - } return w } diff --git a/internal/scheduler/campaign_projection.go b/internal/scheduler/campaign_projection.go index 9d5adb3fd..a2f5c6fa4 100644 --- a/internal/scheduler/campaign_projection.go +++ b/internal/scheduler/campaign_projection.go @@ -155,6 +155,10 @@ func warmupOnDay(p *projectedSender, localNoon time.Time, inCampaign bool) (int, if a.WarmupDays > 0 && !bitmask.HasWeekday(uint8(a.WarmupDays), localNoon.Weekday()) { return 0, nil } + bhv := p.bhv.ForWarmup(a.WarmupDays) + if bhv.Enabled && !bhv.PlanOn(behavior.PlanDateFor(localNoon, bhv.Loc)).IsWorkingDay { + return 0, nil + } days := 0 if a.Warmup != nil { days = max(0, int(localNoon.Sub(*a.Warmup).Hours()/24)) @@ -162,9 +166,12 @@ func warmupOnDay(p *projectedSender, localNoon time.Time, inCampaign bool) (int, n := warmupramp.Target(true, a.WarmupBase, a.WarmupIncrease, a.WarmupMax, days, inCampaign) n = warmupramp.Apply(n, warmupramp.HealthVolumeMultiplier(p.health)) startMin, endMin := parseTimeOfDay(a.WarmupStartTime), parseTimeOfDay(a.WarmupEndTime) - if p.bhv.Enabled { - plan := p.bhv.PlanOn(behavior.PlanDateFor(localNoon, p.bhv.Loc)) - startMin, endMin = plan.WorkStartMinute, plan.WorkEndMinute + if bhv.Enabled { + plan := bhv.PlanOn(behavior.PlanDateFor(localNoon, bhv.Loc)) + startMin, endMin = max(startMin, plan.WorkStartMinute), min(endMin, plan.WorkEndMinute) + if endMin <= startMin { + return 0, nil + } } if startMin == 0 && endMin <= startMin { startMin, endMin = defaultWarmupStartMinute, defaultWarmupEndMinute diff --git a/internal/scheduler/warmup_dispatch.go b/internal/scheduler/warmup_dispatch.go index 46c3f046b..40ed2faea 100644 --- a/internal/scheduler/warmup_dispatch.go +++ b/internal/scheduler/warmup_dispatch.go @@ -43,7 +43,7 @@ func (s *schedulerService) WarmupExecutionNotBefore(ctx context.Context, id, tas if err != nil { return time.Time{}, err } - bhv = behavior.NewStandalone(profile, loadLocation(a.ClockTimezone())) + bhv = behavior.NewStandalone(profile, loadLocation(a.ClockTimezone())).ForWarmup(a.WarmupDays) } at, err := warmupDispatchWindow(a, bhv, now) if err != nil { @@ -128,6 +128,7 @@ func (s *schedulerService) WarmupExecutionNotBefore(ctx context.Context, id, tas } func warmupDispatchWindow(a *models.Email, bhv behavior.Resolved, desired time.Time) (time.Time, error) { + bhv = bhv.ForWarmup(a.WarmupDays) loc := loadLocation(a.ClockTimezone()) at := desired for i := 0; i < 32; i++ { diff --git a/internal/scheduler/warmup_scheduler.go b/internal/scheduler/warmup_scheduler.go index 48ff72fbd..cbc0b9a46 100644 --- a/internal/scheduler/warmup_scheduler.go +++ b/internal/scheduler/warmup_scheduler.go @@ -152,39 +152,20 @@ func (s *schedulerService) CalculateNextWarmupTime(ctx context.Context, accountI return time.Time{}, ErrWarmupNotEnabled } - // STEP 1.5: Resolve the mailbox's sending-behaviour profile. When one is - // enabled it OWNS the mailbox's hours: warmup follows the same rolled - // workday, lunch break and working weekdays as cold sending, because a - // mailbox whose warmup mail keeps arriving at 03:00 while its campaign mail - // keeps office hours has told the receiving side exactly what it is. - // - // Warmup is NOT charged against the persona's cold daily/hourly ceilings: - // those budget cold outreach, and warmup has its own ramp. - bhv := s.behaviorFor(ctx, account) + // Warmup has its own days and ramp; the sending plan supplies hours, breaks and spacing. + bhv := s.behaviorFor(ctx, account).ForWarmup(account.WarmupDays) warmupStart, warmupEnd := account.WarmupStartTime, account.WarmupEndTime if bhv.Enabled { plan := bhv.PlanOn(behavior.PlanDateFor(time.Now(), bhv.Loc)) - warmupStart = minutesToClock(plan.WorkStartMinute) - warmupEnd = minutesToClock(plan.WorkEndMinute) + warmupStart = minutesToClock(max(models.ClockMinutes(account.WarmupStartTime, 8*60), plan.WorkStartMinute)) + warmupEnd = minutesToClock(min(models.ClockMinutes(account.WarmupEndTime, 20*60), plan.WorkEndMinute)) } - - // STEP 1.6: Ensure today is a valid warmup day - if account.WarmupDays > 0 { - loc := loadLocation(account.ClockTimezone()) - now := time.Now().In(loc) - candidateDay := findNextValidDay(now, uint8(account.WarmupDays), loc) - if candidateDay.Day() != now.Day() || candidateDay.Month() != now.Month() || candidateDay.Year() != now.Year() { - // Today is not a valid warmup day, schedule for next valid day's start time - startMinutes := parseTimeOfDay(warmupStart) - if startMinutes == 0 { - startMinutes = 8 * 60 - } - nextDay := candidateDay.In(loc) - firstSlot := time.Date(nextDay.Year(), nextDay.Month(), nextDay.Day(), - startMinutes/60, startMinutes%60, 0, 0, loc) - jitter := randomJitter(0, 60) - return s.snapWarmupToBehavior(bhv, firstSlot.Add(time.Minute*time.Duration(jitter))), nil - } + opening, err := warmupDispatchWindow(account, bhv, time.Now()) + if err != nil { + return time.Time{}, err + } + if !sameLocalDay(opening, time.Now(), loadLocation(account.ClockTimezone())) { + return s.snapWarmupToBehavior(account, bhv, opening.Add(time.Duration(randomJitter(0, 60))*time.Minute)) } // STEP 2: One shared resolve, so this target and the one the mailbox @@ -245,7 +226,7 @@ func (s *schedulerService) CalculateNextWarmupTime(ctx context.Context, accountI if err == nil { eligibleRecipients := len(candidates) if eligibleRecipients <= 0 { - return recipientRecheckTime(), nil + return s.snapWarmupToBehavior(account, bhv, recipientRecheckTime()) } if targetVolume > eligibleRecipients { targetVolume = eligibleRecipients @@ -273,7 +254,7 @@ func (s *schedulerService) CalculateNextWarmupTime(ctx context.Context, accountI // STEP 4: Check if we've hit today's limit if emailsSentToday >= targetVolume { // Move to tomorrow's first slot - return s.snapWarmupToBehavior(bhv, calculateFirstSlotTomorrowAt(account.ClockTimezone(), warmupStart)), nil + return s.snapWarmupToBehavior(account, bhv, calculateFirstSlotTomorrowAt(account.ClockTimezone(), account.WarmupStartTime)) } // STEP 5: Calculate ideal spacing @@ -283,7 +264,7 @@ func (s *schedulerService) CalculateNextWarmupTime(ctx context.Context, accountI // If business hours are over, move to tomorrow if hoursRemaining <= 0 { - return s.snapWarmupToBehavior(bhv, calculateFirstSlotTomorrowAt(account.ClockTimezone(), warmupStart)), nil + return s.snapWarmupToBehavior(account, bhv, calculateFirstSlotTomorrowAt(account.ClockTimezone(), account.WarmupStartTime)) } idealIntervalHours := hoursRemaining / float64(remainingSlots) @@ -345,39 +326,12 @@ func (s *schedulerService) CalculateNextWarmupTime(ctx context.Context, accountI candidateTime = applyDistributionCurve(candidateTime, loc) } - // STEP 13: Final day-of-week guard โ€” conflict resolution or jitter may have pushed - // the candidate into a day that isn't a valid warmup day. - if account.WarmupDays > 0 { - validDay := findNextValidDay(candidateTime, uint8(account.WarmupDays), loc) - candidateLocal := candidateTime.In(loc) - validLocal := validDay.In(loc) - if candidateLocal.Day() != validLocal.Day() || candidateLocal.Month() != validLocal.Month() || candidateLocal.Year() != validLocal.Year() { - startMinutes := parseTimeOfDay(warmupStart) - if startMinutes == 0 { - startMinutes = 8 * 60 - } - candidateTime = time.Date(validLocal.Year(), validLocal.Month(), validLocal.Day(), - startMinutes/60, startMinutes%60, 0, 0, loc) - jitter := randomJitter(0, 60) - candidateTime = candidateTime.Add(time.Minute * time.Duration(jitter)) - } - } - - // STEP 14: Final snap onto the mailbox's workday. Jitter, conflict - // resolution and the day-of-week guard can all land a candidate inside the - // lunch break or on a non-working weekday. - return s.snapWarmupToBehavior(bhv, candidateTime), nil + return s.snapWarmupToBehavior(account, bhv, candidateTime) } -// snapWarmupToBehavior moves a warmup candidate onto the mailbox's rolled -// workday and randomises its sub-minute component. A profile with no reachable -// window leaves the candidate untouched: warmup should degrade to its own -// window rather than stop. -func (s *schedulerService) snapWarmupToBehavior(r behavior.Resolved, candidate time.Time) time.Time { - if snapped, ok := behaviorWindow(r, notBefore(candidate)); ok { - candidate = snapped - } - return finalSlot(candidate) +// Scheduling and execution use the same day, hour and break constraints. +func (s *schedulerService) snapWarmupToBehavior(account *models.Email, r behavior.Resolved, candidate time.Time) (time.Time, error) { + return warmupDispatchWindow(account, r, finalSlot(candidate)) } // minutesToClock renders minutes-since-midnight as the "15:04" string the diff --git a/internal/scheduler/warmup_scheduler_test.go b/internal/scheduler/warmup_scheduler_test.go index 376793f51..c2c334fbd 100644 --- a/internal/scheduler/warmup_scheduler_test.go +++ b/internal/scheduler/warmup_scheduler_test.go @@ -26,8 +26,13 @@ func TestWarmupWindowRespectsGatewaySundayWithoutCloudWorkday(t *testing.T) { } profile.Enabled = true at, err = warmupDispatchWindow(a, behavior.NewStandalone(profile, loc), now) + if err != nil || !at.Equal(now) { + t.Fatalf("explicit Sunday selection was skipped: at=%v err=%v", at, err) + } + a.WarmupDays = 0 + at, err = warmupDispatchWindow(a, behavior.NewStandalone(profile, loc), now) if err != nil || at.In(loc).Weekday() != time.Monday || !at.After(now) { - t.Fatalf("explicit Cloud workday not preserved: at=%v err=%v", at, err) + t.Fatalf("inherited weekday schedule changed: at=%v err=%v", at, err) } } @@ -56,6 +61,42 @@ func TestWarmupDispatchWindowClassifiesInvalidHoursWithoutOpeningThem(t *testing } } +func TestWarmupSelectedDaysKeepHoursAndBreaks(t *testing.T) { + b := models.DefaultSendingBehavior(uuid.New()) + b.Enabled = true + b.WorkStartMin, b.WorkStartMax = 9*60, 9*60 + b.WorkEndMin, b.WorkEndMax = 17*60, 17*60 + b.LunchEnabled = true + b.LunchEarliest, b.LunchLatest = 12*60, 12*60 + b.LunchMinMinutes, b.LunchMaxMinutes = 60, 60 + sunday := time.Date(2026, time.October, 11, 0, 0, 0, 0, time.UTC) + for _, tc := range []struct { + name string + days, fromMinute int + wantDay, wantMin int + }{ + {"explicit weekend", 127, 10 * 60, 0, 10 * 60}, + {"inherited weekdays", 0, 10 * 60, 1, 9 * 60}, + {"warmup starts later", 127, 8 * 60, 0, 9 * 60}, + {"weekend lunch", 127, 12*60 + 30, 0, 13 * 60}, + {"after close on Sunday-only schedule", 64, 18 * 60, 7, 9 * 60}, + {"weekdays selected", 31, 10 * 60, 1, 9 * 60}, + } { + t.Run(tc.name, func(t *testing.T) { + a := &models.Email{WarmupDays: tc.days, WarmupStartTime: "08:00", WarmupEndTime: "16:00"} + at, err := warmupDispatchWindow(a, behavior.NewStandalone(b, time.UTC), sunday.Add(time.Duration(tc.fromMinute)*time.Minute)) + want := sunday.AddDate(0, 0, tc.wantDay).Add(time.Duration(tc.wantMin) * time.Minute) + if err != nil || !at.Equal(want) { + t.Fatalf("at=%v err=%v, want %v", at, err, want) + } + }) + } + a := &models.Email{WarmupDays: 127, WarmupStartTime: "18:00", WarmupEndTime: "20:00"} + if _, err := warmupDispatchWindow(a, behavior.NewStandalone(b, time.UTC), sunday); err == nil { + t.Fatal("disjoint hours must stay closed") + } +} + func TestAdjustmentFor(t *testing.T) { tests := []struct { name string diff --git a/qa/fixtures/warmup-schedule.sql b/qa/fixtures/warmup-schedule.sql new file mode 100644 index 000000000..35affd326 --- /dev/null +++ b/qa/fixtures/warmup-schedule.sql @@ -0,0 +1,18 @@ +BEGIN; + +UPDATE email_accounts +SET warmup_days = 0, warmup_start_time = '08:00', warmup_end_time = '20:00' +WHERE organization_id = '22222222-0000-0000-0000-000000000001' + AND email = 'dev.outbound@warmbly.test'; + +INSERT INTO email_account_behavior (email_account_id, enabled, weekdays, daily_limit_min, daily_limit_max) +SELECT id, true, 31, 28, 32 FROM email_accounts +WHERE organization_id = '22222222-0000-0000-0000-000000000001' + AND email = 'dev.outbound@warmbly.test' +ON CONFLICT (email_account_id) DO UPDATE +SET enabled = true, weekdays = 31; + +UPDATE users SET product_tour_completed_at = now() +WHERE id = '11111111-0000-0000-0000-000000000001' AND product_tour_completed_at IS NULL; + +COMMIT; diff --git a/qa/flows/warmup-schedule.flow.ts b/qa/flows/warmup-schedule.flow.ts new file mode 100644 index 000000000..b544e9edc --- /dev/null +++ b/qa/flows/warmup-schedule.flow.ts @@ -0,0 +1,44 @@ +import { expect, test } from "../lib/proof.ts"; + +test.skip(process.env.QA_WARMUP_SCHEDULE_FIXTURES !== "1", "Apply qa/fixtures/warmup-schedule.sql to this stack's rich-seed database and set QA_WARMUP_SCHEDULE_FIXTURES=1."); + +test("choose weekend warmup while campaigns keep weekday working days", async ({ page, proof }) => { + await page.goto("/app/emails"); + const openMailbox = async () => { + await page.getByRole("row", { name: /dev\.outbound@warmbly\.test/ }).getByText("dev.outbound@warmbly.test", { exact: true }).click(); + await page.getByRole("button", { name: "Warmup", exact: true }).click(); + }; + await openMailbox(); + await page.getByRole("button", { name: "Follow sending plan", exact: true }).scrollIntoViewIfNeeded(); + await expect(page.getByText("Following sending plan: Monday to Friday.")).toBeVisible(); + await expect(page.getByRole("button", { name: "Saturday", exact: true })).toHaveAttribute("aria-pressed", "false"); + await proof.chapter("Warmup sending days", "Local seed data: warmup starts by following a weekday sending plan"); + await proof.shot("warmup-inherited-days", { caption: "The inherited days and the remaining workday hours are explained beside the controls." }); + + await page.getByRole("button", { name: "Every day", exact: true }).click(); + for (const day of ["Saturday", "Sunday"]) { + await expect(page.getByRole("button", { name: day, exact: true })).toHaveAttribute("aria-pressed", "true"); + } + const saved = page.waitForResponse((response) => response.url().includes("/emails/") && response.request().method() === "PATCH"); + await page.getByRole("button", { name: "Save changes", exact: true }).click(); + expect((await saved).ok()).toBe(true); + await expect(page.getByRole("button", { name: "Save changes", exact: true })).toBeHidden(); + await proof.shot("warmup-every-day", { caption: "Every day explicitly selects both weekend days for warmup." }); + + await page.getByRole("button", { name: "Close", exact: true }).click(); + await page.reload(); + await openMailbox(); + await expect(page.getByRole("button", { name: "Every day", exact: true })).toHaveAttribute("aria-pressed", "true"); + await page.getByRole("button", { name: "Every day", exact: true }).click(); + await page.getByRole("button", { name: "Save changes", exact: true }).click(); + await expect(page.getByRole("button", { name: "Save changes", exact: true })).toBeHidden(); + await page.getByRole("button", { name: "Sending", exact: true }).click(); + await expect(page.getByRole("button", { name: "Sat", exact: true })).toHaveAttribute("aria-pressed", "false"); + await expect(page.getByRole("button", { name: "Sun", exact: true })).toHaveAttribute("aria-pressed", "false"); + await proof.shot("warmup-campaign-days", { caption: "Campaign working days remain Monday to Friday after saving weekend warmup." }); + + await page.getByRole("button", { name: "Warmup", exact: true }).click(); + await page.setViewportSize({ width: 390, height: 844 }); + await page.getByRole("button", { name: "Every day", exact: true }).scrollIntoViewIfNeeded(); + await proof.shot("warmup-days-phone", { caption: "The same presets, selected days and explanation on a phone." }); +}); diff --git a/web/src/app/app/emails/page.tsx b/web/src/app/app/emails/page.tsx index dbbcda777..74a626522 100644 --- a/web/src/app/app/emails/page.tsx +++ b/web/src/app/app/emails/page.tsx @@ -42,6 +42,7 @@ import { cloudSendFailure, cloudWarmupPaused } from "@/lib/cloudWarmup"; import buildError from "@/lib/helper/buildError"; import type { AppError } from "@/lib/api/client/normalizeError"; import BulkWarmupDialog from "@/components/app/emails/BulkWarmupDialog"; +import { warmupDaysLabel } from "@/lib/warmupSchedule"; import BulkTagPopover from "@/components/app/emails/BulkTagPopover"; import BulkSignatureDialog from "@/components/app/emails/BulkSignatureDialog"; import MailboxImportsMenu from "@/components/app/emails/import/MailboxImportsMenu"; @@ -783,6 +784,7 @@ export default function AddressesPage() { cloud.isEnrolled(id))} onClose={() => setBulkStart(false)} onComplete={() => setSelected([])} /> @@ -1047,6 +1049,7 @@ function MailboxRow({ {nextWarmup && !sendFailure && ( next {nextWarmup} )} + {warmupDaysLabel(box.warmup_days ?? 0)}
) : ( setValue(value ^ mask)} className={`h-12 rounded-md border flex flex-col items-center justify-center transition-colors ${ diff --git a/web/src/components/app/emails/BulkWarmupDialog.tsx b/web/src/components/app/emails/BulkWarmupDialog.tsx index ae9c9d382..bc7a8cadc 100644 --- a/web/src/components/app/emails/BulkWarmupDialog.tsx +++ b/web/src/components/app/emails/BulkWarmupDialog.tsx @@ -6,14 +6,12 @@ import { useQueryClient } from "@tanstack/react-query"; import { Label, NumberInput, TextInput } from "@/components/ui/field"; import { OptionSelect } from "@/components/app/campaigns/preferences/components/CampaignPreferenceBoolBox"; import TimeSelect from "@/components/ui/TimeSelect"; -import WeekdayBitmask from "@/components/app/campaigns/schedule/WeekdayBitmask"; +import WarmupDaysPicker from "./WarmupDaysPicker"; import { Loading } from "@/components/loader"; import updateEmail from "@/lib/api/client/app/emails/updateEmail"; import warmupLifecycle from "@/lib/api/client/app/emails/warmupLifecycle"; import type Inbox from "@/lib/api/models/app/emails/Inbox"; -const WEEKDAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; - // Bulk warmup-start dialog. Lets the user optionally apply one set of warmup // settings to every selected mailbox before starting โ€” useful when onboarding a // batch of new inboxes that should all ramp the same way. @@ -22,11 +20,13 @@ export default function BulkWarmupDialog({ ids, onClose, onComplete, + allowFollow = true, }: { open: boolean; ids: string[]; onClose: () => void; onComplete: () => void; + allowFollow?: boolean; }) { const queryClient = useQueryClient(); const [customize, setCustomize] = useState(true); @@ -44,6 +44,7 @@ export default function BulkWarmupDialog({ const n = ids.length; const baseOverMax = base > max; + const sendingDays = allowFollow ? days : (days || 127); const start = async () => { if (busy || n === 0) return; @@ -59,7 +60,7 @@ export default function BulkWarmupDialog({ warmup_reply_rate: replyRate, warmup_start_time: startTime, warmup_end_time: endTime, - warmup_days: days, + warmup_days: sendingDays, warmup_placement: placement, warmup_folder: folder.trim(), }; @@ -167,10 +168,8 @@ export default function BulkWarmupDialog({
- -

- Leave all unselected to send every day. -

+ + {!allowFollow &&

Cloud-linked mailboxes need explicit sending days.

}
diff --git a/web/src/components/app/emails/InboxDetails.tsx b/web/src/components/app/emails/InboxDetails.tsx index efad8dff8..270ca445b 100644 --- a/web/src/components/app/emails/InboxDetails.tsx +++ b/web/src/components/app/emails/InboxDetails.tsx @@ -110,15 +110,14 @@ import useAuthConfig from "@/lib/api/hooks/auth/useAuthConfig"; import { Toggle } from "@/components/app/campaigns/preferences/components/CampaignPreferenceBoolBox"; import setDirectTracking from "@/lib/api/client/app/emails/setDirectTracking"; import useSendingBehavior from "@/lib/api/hooks/app/emails/useSendingBehavior"; -import useUpdateSendingBehavior from "@/lib/api/hooks/app/emails/useUpdateSendingBehavior"; import useSendingPlan from "@/lib/api/hooks/app/emails/useSendingPlan"; -import { minutesToClock, secondsToLabel } from "@/lib/api/models/app/emails/SendingBehavior"; +import { clockToMinutes, minutesToClock, secondsToLabel } from "@/lib/api/models/app/emails/SendingBehavior"; import TagSelector from "../popup/select/TagSelector"; import { useAppStore } from "@/stores"; import { repliesGoTo } from "@/lib/unibox/replyInbox"; import TimeSelect from "@/components/ui/TimeSelect"; import { DitherBarChart } from "@/components/ui/dither"; -import WeekdayBitmask from "../campaigns/schedule/WeekdayBitmask"; +import WarmupDaysPicker from "./WarmupDaysPicker"; import { Loading } from "@/components/loader"; import { NumberInput, TextInput } from "@/components/ui/field"; import { clampWarmupRetentionDays } from "@/lib/warmupRetention"; @@ -425,12 +424,14 @@ function Detail({ mailbox, onClose, initialTab, tabIntentKey, onTabIntentConsume } }, [initialTab, tabIntentKey, onTabIntentConsumed, setTab]); const [form, setForm] = useState(mailbox); + const [daysToApply, setDaysToApply] = useState(null); // Fields the user has edited since the last save; a refresh never overwrites them. const touched = React.useRef(new Set()); const update = (patch: Partial) => { - // A field put back to the stored value is untouched again, so a refresh can still reach it. + // Choosing warmup days reapplies the schedule even when the saved selection is unchanged. + if (patch.warmup_days !== undefined) setDaysToApply(patch.warmup_days); for (const k of Object.keys(patch) as (keyof Inbox)[]) { - if (JSON.stringify(patch[k]) === JSON.stringify(mailbox[k])) touched.current.delete(k); + if (k !== "warmup_days" && JSON.stringify(patch[k]) === JSON.stringify(mailbox[k])) touched.current.delete(k); else touched.current.add(k); } setForm((f) => ({ ...f, ...patch })); @@ -449,6 +450,7 @@ function Detail({ mailbox, onClose, initialTab, tabIntentKey, onTabIntentConsume }, [mailbox]); const discard = () => { touched.current.clear(); + setDaysToApply(null); setForm(mailbox); }; @@ -467,8 +469,8 @@ function Detail({ mailbox, onClose, initialTab, tabIntentKey, onTabIntentConsume const mutation = useUpdateEmail(mailbox.id, pool.connected && pool.isEnrolled(mailbox.id) ? cloudOwnedWarmupFields : undefined); const dirty = useMemo( - () => EDITABLE.some((k) => JSON.stringify(form[k]) !== JSON.stringify(mailbox[k])), - [form, mailbox], + () => daysToApply !== null || EDITABLE.some((k) => JSON.stringify(form[k]) !== JSON.stringify(mailbox[k])), + [daysToApply, form, mailbox], ); const save = async () => { @@ -478,8 +480,10 @@ function Detail({ mailbox, onClose, initialTab, tabIntentKey, onTabIntentConsume (patch as Record)[k] = form[k]; } } + if (daysToApply !== null) patch.warmup_days = daysToApply; try { const saved = await mutation.mutateAsync(patch); + setDaysToApply((current) => current === patch.warmup_days ? null : current); // The answer is what was stored (for a Cloud mailbox, what Warmbly Cloud applied). setForm((f) => { const next = { ...f } as Record; @@ -814,7 +818,7 @@ function OverviewTab({ status, loading, mailbox }: { status?: import("@/lib/api/ today ? today.is_working_day ? `of ${today.daily_limit} rolled for today` - : "not a sending day" + : "not a campaign sending day" : usage ? `of ${usage.campaign_limit}/day cap` : undefined @@ -998,7 +1002,6 @@ function AnalyticsTab({ warmup, loading, failed, retry }: { warmup?: import("@/l /* โ”€โ”€ Warmup (editable) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */ -const WEEKDAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; // A critical report stops the mailbox; a warning is retried on its own, so it reads as amber, not red. const errorTone = { @@ -1304,59 +1307,6 @@ function AuthCheckPanel({ mailbox }: { mailbox: Inbox }) { ); } -const ALL_DAYS = 127; - -const listDays = (mask: number) => { - const names = WEEKDAYS.filter((_, i) => (mask & (1 << i)) !== 0); - return names.length > 1 ? `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}` : names.join(""); -}; - -// Warmup sends only on days both calendars allow, so a day ticked here that the persona does not work is silently skipped. -function WarmupDaysNotice({ mailboxId, warmupDays, personaDays }: { mailboxId: string; warmupDays: number; personaDays: number }) { - const wanted = warmupDays || ALL_DAYS; - const skipped = wanted & ~personaDays; - const canManage = usePermission("MANAGE_EMAILS"); - const queryClient = useQueryClient(); - const mutation = useUpdateSendingBehavior(mailboxId); - if (skipped === 0) return null; - - const workDays = async () => { - try { - await mutation.mutateAsync({ weekdays: personaDays | skipped }); - await queryClient.invalidateQueries({ queryKey: ["analytics", "accounts"] }); - toast.success(`Warmup now sends on ${listDays(skipped)} too`); - } catch (e) { - toast.error(buildError(e as unknown as AppError)); - } - }; - - return ( -
- -
-

- {(wanted & personaDays) === 0 ? "Warmup has no day to send on" : `Warmup skips ${listDays(skipped)}`} -

-

- Sending behaviour only works {personaDays ? listDays(personaDays) : "no days"}, and warmup follows its workdays as well as the - days picked here. -

- {canManage && ( - - )} -
-
- ); -} - function WarmupTab({ form, update, status, mailbox, canWarmup = true }: { form: Inbox; update: (p: Partial) => void; status?: AccountStatusModel; mailbox: Inbox; canWarmup?: boolean }) { const ws = status?.warmup_status; const wh = status?.warmup_health; @@ -1381,6 +1331,10 @@ function WarmupTab({ form, update, status, mailbox, canWarmup = true }: { form: const cloudRow = inCloud ? pool.rowFor(mailbox.id) : undefined; // Warmbly Cloud skips a 0 sent from an instance, so the form does not offer one. const cloudMin = inCloud ? 1 : 0; + const startMinute = clockToMinutes(form.warmup_start_time || "08:00"); + const endMinute = clockToMinutes(form.warmup_end_time || "20:00"); + const noOverlap = !inCloud && persona?.enabled && startMinute !== null && endMinute !== null && + (startMinute >= persona.work_end_max || endMinute <= persona.work_start_min); const run = (action: "start" | "pause" | "resume" | "stop", verb: string) => { const execute = () => life.mutate(action, { @@ -1639,10 +1593,12 @@ function WarmupTab({ form, update, status, mailbox, canWarmup = true }: { form: {/* Schedule */}
Sending window - {behaviorOn && ( + {behaviorOn && !inCloud && (

- Sending behaviour is on for this mailbox, so warmup only sends when both this window and the workday on the Sending tab - allow it. Switch it to Fixed schedule there to use these hours alone. + Sending behaviour is on. Warmup uses the overlap between these hours and the varied workday on the Sending tab, + including its break. The workday starts between {minutesToClock(persona.work_start_min)} and {minutesToClock(persona.work_start_max)} and + ends between {minutesToClock(persona.work_end_min)} and {minutesToClock(persona.work_end_max)}. + Switch to Fixed schedule on the Sending tab to use these hours alone.

)}
@@ -1653,18 +1609,20 @@ function WarmupTab({ form, update, status, mailbox, canWarmup = true }: { form: update({ warmup_end_time: v })} />
- -
- update({ warmup_days: v })} - /> -
-
- {behaviorOn && persona && ( - + {noOverlap && ( +

+ These hours do not overlap the sending plan, so warmup has no time to send. Extend this window or switch + to Fixed schedule on the Sending tab. +

)} + + update({ warmup_days })} + inheritedDays={persona ? (persona.enabled ? persona.weekdays : 127) : undefined} + allowFollow={!inCloud} + /> +
); diff --git a/web/src/components/app/emails/SendingBehaviorTab.tsx b/web/src/components/app/emails/SendingBehaviorTab.tsx index 3429a23a0..7f7a0679b 100644 --- a/web/src/components/app/emails/SendingBehaviorTab.tsx +++ b/web/src/components/app/emails/SendingBehaviorTab.tsx @@ -356,7 +356,7 @@ export default function SendingBehaviorTab({ mailboxId, timezone }: { mailboxId: setValue={(v) => update({ weekdays: v })} />

- Days this mailbox sends anything at all, cold outreach and warmup alike. + Campaign working days. Warmup follows these only when its Sending days is set to Follow sending plan.

diff --git a/web/src/components/app/emails/WarmupDaysPicker.test.tsx b/web/src/components/app/emails/WarmupDaysPicker.test.tsx new file mode 100644 index 000000000..ad34c2031 --- /dev/null +++ b/web/src/components/app/emails/WarmupDaysPicker.test.tsx @@ -0,0 +1,35 @@ +import { useState } from "react"; +import { fireEvent, render, screen } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; +import WarmupDaysPicker from "./WarmupDaysPicker"; + +function Picker() { + const [days, setDays] = useState(0); + return ; +} + +describe("warmup day selection", () => { + it("shows inherited days and lets the customer add weekends without changing campaign days", () => { + render(); + expect(screen.getByText("Following sending plan: Monday to Friday.")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Monday" })).toHaveAttribute("aria-pressed", "true"); + expect(screen.getByRole("button", { name: "Saturday" })).toHaveAttribute("aria-pressed", "false"); + fireEvent.click(screen.getByRole("button", { name: "Saturday" })); + expect(screen.getByRole("button", { name: "Saturday" })).toHaveAttribute("aria-pressed", "true"); + expect(screen.getByRole("button", { name: "Follow sending plan" })).toHaveAttribute("aria-pressed", "false"); + expect(screen.getByText(/Campaign working days stay separate/)).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Follow sending plan" })); + expect(screen.getByRole("button", { name: "Saturday" })).toHaveAttribute("aria-pressed", "false"); + }); + + it("selects every day explicitly and keeps at least one selected day", () => { + render(); + fireEvent.click(screen.getByRole("button", { name: "Every day" })); + for (const day of ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]) { + expect(screen.getByRole("button", { name: day })).toHaveAttribute("aria-pressed", "true"); + fireEvent.click(screen.getByRole("button", { name: day })); + } + expect(screen.getByRole("button", { name: "Sunday" })).toHaveAttribute("aria-pressed", "true"); + expect(screen.getByRole("button", { name: "Follow sending plan" })).toHaveAttribute("aria-pressed", "false"); + }); +}); diff --git a/web/src/components/app/emails/WarmupDaysPicker.tsx b/web/src/components/app/emails/WarmupDaysPicker.tsx new file mode 100644 index 000000000..93ad21ad5 --- /dev/null +++ b/web/src/components/app/emails/WarmupDaysPicker.tsx @@ -0,0 +1,51 @@ +import { warmupDaysLabel } from "@/lib/warmupSchedule"; +import WeekdayBitmask from "@/components/app/campaigns/schedule/WeekdayBitmask"; + +const WEEKDAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; + +export default function WarmupDaysPicker({ value, onChange, inheritedDays, allowFollow = true }: { + value: number; + onChange: (days: number) => void; + inheritedDays?: number; + allowFollow?: boolean; +}) { + const effectiveDays = value || inheritedDays; + return ( +
+
+ {[ + { days: 0, label: "Follow sending plan" }, + { days: 127, label: "Every day" }, + { days: 31, label: "Weekdays" }, + ].filter(({ days }) => allowFollow || days !== 0).map(({ days, label }) => ( + + ))} +
+ {effectiveDays !== undefined && ( + { if (days !== 0) onChange(days); }} + /> + )} +

+ {value === 0 + ? inheritedDays === undefined + ? "Uses sending-plan days, or every day with Fixed schedule." + : `Following sending plan: ${warmupDaysLabel(inheritedDays)}.` + : `Warmup days: ${warmupDaysLabel(value)}. Every selected day applies, including weekends. Campaign working days stay separate.`} +

+

+ Select at least one day. Sending-plan hours and breaks still apply while the plan is on. +

+
+ ); +} diff --git a/web/src/lib/api/hooks/app/emails/useUpdateEmail.ts b/web/src/lib/api/hooks/app/emails/useUpdateEmail.ts index 7031aeb7b..b556bb39b 100644 --- a/web/src/lib/api/hooks/app/emails/useUpdateEmail.ts +++ b/web/src/lib/api/hooks/app/emails/useUpdateEmail.ts @@ -37,6 +37,7 @@ export default function useUpdateEmail(id: string, serverOwned: readonly (keyof ["emails", id], data ); + void queryClient.invalidateQueries({ queryKey: ["analytics", "accounts"] }); } }) } diff --git a/web/src/lib/api/hooks/app/emails/useUpdateSendingBehavior.ts b/web/src/lib/api/hooks/app/emails/useUpdateSendingBehavior.ts index 161c1b6c6..519cb7973 100644 --- a/web/src/lib/api/hooks/app/emails/useUpdateSendingBehavior.ts +++ b/web/src/lib/api/hooks/app/emails/useUpdateSendingBehavior.ts @@ -13,6 +13,7 @@ export default function useUpdateSendingBehavior(id: string) { // Today's plan keeps whatever it already rolled, but the ranges it // will roll from tomorrow have changed, so drop the cached view. queryClient.invalidateQueries({ queryKey: ["emails", id, "behavior", "plan"] }); + void queryClient.invalidateQueries({ queryKey: ["analytics", "accounts"] }); }, }); } diff --git a/web/src/lib/warmupSchedule.ts b/web/src/lib/warmupSchedule.ts new file mode 100644 index 000000000..b49cba80a --- /dev/null +++ b/web/src/lib/warmupSchedule.ts @@ -0,0 +1,9 @@ +import { WEEKDAY_LABELS } from "@/lib/api/models/app/emails/SendingBehavior"; + +export function warmupDaysLabel(days: number): string { + if (days === 127) return "Every day"; + if (days === 31) return "Monday to Friday"; + if (days === 0) return "Follow sending plan"; + return WEEKDAY_LABELS.filter((_, index) => (days & (1 << index)) !== 0).join(", "); +} + From f00ba16eb4075592043889f5dd47eaa6e96ede74 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Mon, 2 Nov 2026 11:39:53 +0100 Subject: [PATCH 075/318] feat: defer incompatible warmup windows safely, wait for Cloud ownership before bulk start, and align schedule regression checks --- docs/content/docs/guides/warmup.mdx | 2 +- internal/repository/cloud_warmup_mirror_live_test.go | 4 ++-- internal/scheduler/warmup_dispatch.go | 7 ++++--- internal/scheduler/warmup_scheduler_test.go | 4 ++-- qa/flows/warmup-schedule.flow.ts | 4 ++++ web/src/app/app/emails/page.test.tsx | 8 ++++++-- web/src/app/app/emails/page.tsx | 6 ++++-- 7 files changed, 23 insertions(+), 12 deletions(-) diff --git a/docs/content/docs/guides/warmup.mdx b/docs/content/docs/guides/warmup.mdx index 43d1dcc27..2df067968 100644 --- a/docs/content/docs/guides/warmup.mdx +++ b/docs/content/docs/guides/warmup.mdx @@ -224,7 +224,7 @@ Choose **Sending days** on the **Warmup** tab. **Every day** explicitly includes **Follow sending plan** uses the working days on the **Sending** tab, which default to Monday to Friday. With **Fixed schedule**, it means every day. Existing mailboxes with no selected warmup days keep this inherited schedule. The day picker shows the days that apply; selecting a day switches to an explicit warmup schedule. -While [Sending behavior](/guides/sending-behavior/) is on, warmup uses the overlap between its configured hours and the day's varied workday, including the break. A warmup window starting at 08:00 still waits until 09:15 if that day's workday opens then. On an explicitly selected weekend day, warmup rolls the same hours and break without opening that day for campaigns. The Warmup tab shows the workday's start and end ranges. Switch to **Fixed schedule** on the **Sending** tab to use the warmup hours alone. +While [Sending behavior](/guides/sending-behavior/) is on, warmup uses the overlap between its configured hours and the day's varied workday, including the break. A warmup window starting at 08:00 still waits until 09:15 if that day's workday opens then. On an explicitly selected weekend day, warmup rolls the same hours and break without opening that day for campaigns. The Warmup tab shows the workday's start and end ranges and warns when the hours cannot overlap. Pending sends wait and recheck after five minutes until the settings allow sending. Switch to **Fixed schedule** on the **Sending** tab to use the warmup hours alone. Changing warmup hours, days or timezone, or switching sending behavior on or off, moves the queued warmup send to the new schedule as soon as you save. To recalculate an existing queued time, choose its day preset again and save. The mailbox list refreshes its queued time and shows whether warmup follows the sending plan or an explicit set of days. **Start warmup** for several mailboxes offers the same day presets; **Follow sending plan** resolves separately for each locally warmed mailbox and is hidden when the selection includes a Cloud-linked mailbox. Volume, consent, health and provider restrictions still apply on every selected day. diff --git a/internal/repository/cloud_warmup_mirror_live_test.go b/internal/repository/cloud_warmup_mirror_live_test.go index 993485bc7..077e569c7 100644 --- a/internal/repository/cloud_warmup_mirror_live_test.go +++ b/internal/repository/cloud_warmup_mirror_live_test.go @@ -58,8 +58,8 @@ func TestLiveCloudWarmupMirrorWritesOnlyEnrolledMailboxesInOrder(t *testing.T) { if err != nil || !slices.Equal(changed, []uuid.UUID{enrolled}) { t.Fatalf("changed = %v, %v, want only the enrolled mailbox", changed, err) } - if base, days, start, tz := read(enrolled); base != 12 || days != 0 || start != "09:00" || tz != "Europe/Berlin" { - t.Fatalf("enrolled mailbox = base %d days %d start %s tz %s, want the cloud's ramp, every day as 0, our timezone", base, days, start, tz) + if base, days, start, tz := read(enrolled); base != 12 || days != models.WarmupEveryDay || start != "09:00" || tz != "Europe/Berlin" { + t.Fatalf("enrolled mailbox = base %d days %d start %s tz %s, want the cloud's ramp, explicit every day, our timezone", base, days, start, tz) } for _, id := range []uuid.UUID{leaving, local} { if base, days, _, _ := read(id); base != 10 || days != 31 { diff --git a/internal/scheduler/warmup_dispatch.go b/internal/scheduler/warmup_dispatch.go index 40ed2faea..788e1ef14 100644 --- a/internal/scheduler/warmup_dispatch.go +++ b/internal/scheduler/warmup_dispatch.go @@ -3,6 +3,7 @@ package scheduler import ( "context" "errors" + "fmt" "time" "github.com/google/uuid" @@ -139,7 +140,7 @@ func warmupDispatchWindow(a *models.Email, bhv behavior.Resolved, desired time.T if bhv.Enabled { open, _, ok := bhv.NextOpen(at) if !ok { - return time.Time{}, errors.New("warmup behavior has no working days") + return time.Time{}, fmt.Errorf("%w: sending plan has no working days", ErrWarmupTimeWindowInvalid) } at = open } @@ -161,7 +162,7 @@ func warmupDispatchWindow(a *models.Email, bhv behavior.Resolved, desired time.T if bhv.Enabled { open, _, ok := bhv.NextOpen(at) if !ok { - return time.Time{}, errors.New("warmup behavior has no working days") + return time.Time{}, fmt.Errorf("%w: sending plan has no working days", ErrWarmupTimeWindowInvalid) } if open.After(at) { at = open @@ -173,5 +174,5 @@ func warmupDispatchWindow(a *models.Email, bhv behavior.Resolved, desired time.T } at = valid } - return time.Time{}, errors.New("warmup calendars have no reachable intersection") + return time.Time{}, fmt.Errorf("%w: no reachable overlap with sending plan", ErrWarmupTimeWindowInvalid) } diff --git a/internal/scheduler/warmup_scheduler_test.go b/internal/scheduler/warmup_scheduler_test.go index c2c334fbd..1bea9fa9c 100644 --- a/internal/scheduler/warmup_scheduler_test.go +++ b/internal/scheduler/warmup_scheduler_test.go @@ -92,8 +92,8 @@ func TestWarmupSelectedDaysKeepHoursAndBreaks(t *testing.T) { }) } a := &models.Email{WarmupDays: 127, WarmupStartTime: "18:00", WarmupEndTime: "20:00"} - if _, err := warmupDispatchWindow(a, behavior.NewStandalone(b, time.UTC), sunday); err == nil { - t.Fatal("disjoint hours must stay closed") + if at, err := warmupDispatchWindow(a, behavior.NewStandalone(b, time.UTC), sunday); !errors.Is(err, ErrWarmupTimeWindowInvalid) || !at.IsZero() { + t.Fatalf("disjoint hours must defer as a configuration error: at=%v err=%v", at, err) } } diff --git a/qa/flows/warmup-schedule.flow.ts b/qa/flows/warmup-schedule.flow.ts index b544e9edc..375fbfd46 100644 --- a/qa/flows/warmup-schedule.flow.ts +++ b/qa/flows/warmup-schedule.flow.ts @@ -40,5 +40,9 @@ test("choose weekend warmup while campaigns keep weekday working days", async ({ await page.getByRole("button", { name: "Warmup", exact: true }).click(); await page.setViewportSize({ width: 390, height: 844 }); await page.getByRole("button", { name: "Every day", exact: true }).scrollIntoViewIfNeeded(); + await expect(page.getByRole("button", { name: "Every day", exact: true })).toHaveAttribute("aria-pressed", "true"); + for (const day of ["Saturday", "Sunday"]) { + await expect(page.getByRole("button", { name: day, exact: true })).toHaveAttribute("aria-pressed", "true"); + } await proof.shot("warmup-days-phone", { caption: "The same presets, selected days and explanation on a phone." }); }); diff --git a/web/src/app/app/emails/page.test.tsx b/web/src/app/app/emails/page.test.tsx index cbd1674ac..9215fdded 100644 --- a/web/src/app/app/emails/page.test.tsx +++ b/web/src/app/app/emails/page.test.tsx @@ -41,7 +41,7 @@ vi.mock("@/lib/api/hooks/app/subscription/useFeatureStatus", () => ({ default: ( vi.mock("@/lib/api/hooks/auth/useAuthConfig", () => ({ default: () => ({ data: {}, isLoading: false }) })); vi.mock("@/lib/api/hooks/app/emails/useMailboxGrants", () => ({ useSigninMigration: () => ({ data: { data: [] } }) })); vi.mock("@/lib/api/hooks/app/advisor/useAdvisor", () => ({ useAdvisorEntityIndex: () => ({ get: () => [] }) })); -vi.mock("@/hooks/useCloudPool", () => ({ default: () => ({ selfHosted: false, connected: statusState.cloudConnected, loading: statusState.cloudLoading, unavailable: statusState.cloudUnavailable, observedAt: 0, rowFor: (id: string) => cloudRows.get(id) }) })); +vi.mock("@/hooks/useCloudPool", () => ({ default: () => ({ selfHosted: false, connected: statusState.cloudConnected, loading: statusState.cloudLoading, unavailable: statusState.cloudUnavailable, observedAt: 0, rowFor: (id: string) => cloudRows.get(id), isEnrolled: (id: string) => cloudRows.get(id)?.enrolled === true }) })); vi.mock("@/lib/api/hooks/app/cloudlink/useCloudLink", () => ({ useEnrollCloudLinkMailbox: () => ({}), useUnenrollCloudLinkMailbox: () => ({}), useCloudLinkMailboxLifecycle: () => ({}), })); @@ -108,17 +108,21 @@ describe("mailbox ordering with a tag filter", () => { expect(orderedEmails()).toEqual(["ananya@serveblink.example", "julie@serveblink.example", "kavya@serveblink.example", "sara@virevow.example"]); }); - it.each(["cloudLoading", "cloudUnavailable"] as const)("defers disconnect and bulk removal while ownership is %s", async (unknown) => { + it.each(["cloudLoading", "cloudUnavailable"] as const)("defers disconnect, bulk removal and warmup start while ownership is %s", async (unknown) => { statusState[unknown] = true; await renderPage(); const row = screen.getAllByRole("row")[1]; fireEvent.click(within(row).getByRole("checkbox")); expect(screen.getByRole("button", { name: "Remove" })).toBeDisabled(); + expect(screen.getByRole("button", { name: "Start warmup" })).toBeDisabled(); fireEvent.click(within(row).getByRole("button", { name: "Mailbox actions" })); const disconnect = screen.getByRole("menuitem", { name: "Disconnect mailbox" }); expect(disconnect).toBeDisabled(); fireEvent.click(disconnect); expect(confirm).not.toHaveBeenCalled(); + statusState[unknown] = false; + fireEvent.click(screen.getByRole("button", { name: "Mailbox" })); + expect(screen.getByRole("button", { name: "Start warmup" })).toBeEnabled(); }); it("keeps that order when a specific tag returns rows in creation order", async () => { diff --git a/web/src/app/app/emails/page.tsx b/web/src/app/app/emails/page.tsx index 74a626522..a877dbd24 100644 --- a/web/src/app/app/emails/page.tsx +++ b/web/src/app/app/emails/page.tsx @@ -696,7 +696,9 @@ export default function AddressesPage() { - {stats && stats.total_sent > 0 && ( + {stats && stats.sent > 0 && (
{isWinner && ( Winner )} - + - +
)} diff --git a/web/src/lib/api/models/app/campaigns/ABVariant.ts b/web/src/lib/api/models/app/campaigns/ABVariant.ts index 8e91cd419..f1c9aa922 100644 --- a/web/src/lib/api/models/app/campaigns/ABVariant.ts +++ b/web/src/lib/api/models/app/campaigns/ABVariant.ts @@ -11,6 +11,8 @@ export default interface ABVariant { body_plain: string; is_control: boolean; is_active: boolean; + // Set when auto-promotion made this arm its step's winner. + promoted_at?: string | null; created_at: Date; updated_at: Date; } @@ -51,6 +53,43 @@ export interface ABVariantStats { bounce_rate: number; } +// One arm of a step split, counted in contacts. Rates are over delivered +// contacts (sent minus bounced). variant_id is null for the Original. +export interface ABStepArmStats { + variant_id: string | null; + name: string; + is_control: boolean; + is_active: boolean; + sent: number; + bounced: number; + delivered: number; + opened: number; + clicked: number; + replied: number; + open_rate: number; + click_rate: number; + reply_rate: number; + bounce_rate: number; +} + +export interface ABStepWinner { + variant_id: string | null; + is_control: boolean; + name: string; +} + +export type ABConfidence = "none" | "low" | "medium" | "high"; + +// One step's split: every arm, and the winner once its lead is significant. +export interface ABStepAnalysis { + step_id: string; + arms: ABStepArmStats[]; + winner?: ABStepWinner | null; + confidence: ABConfidence; + p_value?: number | null; + promoted_at?: string | null; +} + // The campaign's A/B winner analysis. export interface ABWinnerAnalysis { campaign_id: string; @@ -59,4 +98,5 @@ export interface ABWinnerAnalysis { winner_name?: string; winning_rule: string; confidence: string; + steps?: ABStepAnalysis[]; } diff --git a/web/src/lib/api/models/app/outreach/OutreachSettings.ts b/web/src/lib/api/models/app/outreach/OutreachSettings.ts index 06f69e3c3..a4492687e 100644 --- a/web/src/lib/api/models/app/outreach/OutreachSettings.ts +++ b/web/src/lib/api/models/app/outreach/OutreachSettings.ts @@ -234,10 +234,20 @@ export const DEFAULT_UNSUBSCRIBE: UnsubscribeSettings = { link_text: "Unsubscribe", }; +export type ABWinningRule = "reply_rate" | "open_rate" | "click_rate"; + +// How step A/B tests pick and apply a winner (see the A/B variants guide). +export interface ABTestingSettings { + enabled: boolean; + default_winning_rule: ABWinningRule; + auto_promote_winner: boolean; + min_sample_size: number; +} + export interface OutreachSettings { bounce_pipeline: Record; task_reliability: Record; - ab_testing: Record; + ab_testing: ABTestingSettings; reply_intent: ReplyIntentSettings; inbox_tagging?: InboxTaggingSettings; send_time_optimization: SendTimeOptimizationSettings; From d1b717cc0625c1f08d6053212df05d81bca0f69d Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Tue, 3 Nov 2026 09:15:40 +0100 Subject: [PATCH 100/318] feat: fence worker sync reports by the transport generation each worker incarnation was loaded with, carried as report_generation on SYNC_STATE --- internal/app/consumer/event_sync_state.go | 2 +- .../app/consumer/event_sync_state_test.go | 18 +++++++------- internal/app/worker/wmail/wmail.go | 7 +++--- .../codec/mail_transport_registry_test.go | 18 +++++++------- internal/models/event_schema_test.go | 2 +- internal/models/sync.go | 8 ++++--- .../repository/mail_transport_live_test.go | 24 ++++++++++--------- internal/repository/pg_email_sync_state.go | 23 ++++++++++-------- 8 files changed, 57 insertions(+), 45 deletions(-) diff --git a/internal/app/consumer/event_sync_state.go b/internal/app/consumer/event_sync_state.go index 0c174b7b3..f3f1610ef 100644 --- a/internal/app/consumer/event_sync_state.go +++ b/internal/app/consumer/event_sync_state.go @@ -36,7 +36,7 @@ func (s *JobsService) HandleSyncState(ctx context.Context, e *models.JobEventSyn accepted := true if e.WorkerID != nil { - accepted, err = s.EmailSyncStateRepository.PutFromWorker(ctx, e.UserID, e.EmailID, *e.WorkerID, &e.State, recover) + accepted, 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) diff --git a/internal/app/consumer/event_sync_state_test.go b/internal/app/consumer/event_sync_state_test.go index 5be29e17a..296344cbf 100644 --- a/internal/app/consumer/event_sync_state_test.go +++ b/internal/app/consumer/event_sync_state_test.go @@ -19,11 +19,12 @@ var syncTestGeneration = uuid.New() // stubSyncStateRepo accepts what the worker relays. type stubSyncStateRepo struct { repository.EmailSyncStateRepository - put *models.SyncState - saved *models.SyncState - getErr error - reportWorker uuid.UUID - reportAccepted bool + put *models.SyncState + saved *models.SyncState + getErr error + reportWorker uuid.UUID + reportGeneration uuid.UUID + reportAccepted bool } func (s *stubSyncStateRepo) Get(context.Context, uuid.UUID) (*models.SyncState, error) { @@ -35,8 +36,9 @@ func (s *stubSyncStateRepo) Put(_ context.Context, _, _ uuid.UUID, st *models.Sy return nil } -func (s *stubSyncStateRepo) PutFromWorker(ctx context.Context, _, _, workerID 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) error) (bool, error) { s.reportWorker = workerID + s.reportGeneration = generation if s.reportAccepted { if before != nil { if err := before(ctx); err != nil { @@ -91,12 +93,12 @@ func TestSyncStateChecksReportingWorkerBeforeSaving(t *testing.T) { StreamingPublisher: pubsub.NewStreamingPublisher(bus, removeSyncAudience{org: org})} workerID := uuid.New() at := time.Now().Add(-time.Minute) - event := &models.JobEventSyncState{WorkerID: &workerID, UserID: uuid.New(), EmailID: uuid.New(), + event := &models.JobEventSyncState{WorkerID: &workerID, ReportGeneration: syncTestGeneration, UserID: uuid.New(), EmailID: uuid.New(), State: models.SyncState{TransportGeneration: syncTestGeneration, LastSyncedAt: &at, BackfillStatus: models.SyncBackfillComplete, FoldersSkippedCap: 4}} if err := s.HandleSyncState(t.Context(), event); err != nil { t.Fatal(err) } - if repo.reportWorker != workerID || (repo.put != nil) != accepted { + if repo.reportWorker != workerID || repo.reportGeneration != syncTestGeneration || (repo.put != nil) != accepted { t.Fatalf("worker=%s accepted=%t saved=%+v", repo.reportWorker, accepted, repo.put) } if (bus.calls > 0) != accepted || (errRepo.calls > 0) != accepted { diff --git a/internal/app/worker/wmail/wmail.go b/internal/app/worker/wmail/wmail.go index c47f0facc..17bb62323 100644 --- a/internal/app/worker/wmail/wmail.go +++ b/internal/app/worker/wmail/wmail.go @@ -205,9 +205,10 @@ func NewWMail( mail.gov = newGovernor(data.ID, data.OrganizationID, gcache, policy) mail.tracker = newSyncTracker(seed, func(st models.SyncState) error { return mail.onEvent(models.JobEventTypeSyncState, &models.JobEventSyncState{ - UserID: mail.UserID, - EmailID: mail.ID, - State: st, + ReportGeneration: mail.TransportGeneration, + UserID: mail.UserID, + EmailID: mail.ID, + State: st, }) }) mail.tracker.transportGeneration = mail.TransportGeneration diff --git a/internal/infrastructure/codec/mail_transport_registry_test.go b/internal/infrastructure/codec/mail_transport_registry_test.go index dee7af9d3..71f802768 100644 --- a/internal/infrastructure/codec/mail_transport_registry_test.go +++ b/internal/infrastructure/codec/mail_transport_registry_test.go @@ -51,7 +51,7 @@ func priorTransportSchema(t *testing.T, schema avro.Schema) avro.Schema { kept := fields[:0] for _, f := range fields { record := f.(map[string]any) - if record["name"] == "transport_generation" || record["name"] == "folder_coverage_observed_at" || x["name"] == "warmbly.events.EmailErrorEvent" && record["name"] == "operation" || x["name"] == "warmbly.events.JobEventSyncState" && record["name"] == "worker_id" { + if record["name"] == "transport_generation" || record["name"] == "folder_coverage_observed_at" || x["name"] == "warmbly.events.EmailErrorEvent" && record["name"] == "operation" || x["name"] == "warmbly.events.JobEventSyncState" && (record["name"] == "worker_id" || record["name"] == "report_generation") { continue } strip(f) @@ -98,12 +98,14 @@ func TestPriorTransportSchemaOmitsReportingIdentity(t *testing.T) { continue } found = true - present := false - for _, field := range record.Fields() { - present = present || field.Name() == "worker_id" - } - if present != tc.present { - t.Fatalf("worker_id present=%t want=%t", present, tc.present) + for _, name := range []string{"worker_id", "report_generation"} { + present := false + for _, field := range record.Fields() { + present = present || field.Name() == name + } + if present != tc.present { + t.Fatalf("%s present=%t want=%t", name, present, tc.present) + } } } if !found { @@ -186,7 +188,7 @@ func TestMailTransportCodecRegistryCompatibility(t *testing.T) { return v.(*models.WorkerEvent).Body.(*models.AddWorkerEmail).TransportGeneration }}, {"send", models.JobEvent{Type: models.JobEventTypeEmailSent, Body: models.SendEmailResult{TaskID: task, Success: true, SentAt: at, TransportGeneration: generation}}, models.JobEvent{}.Schema(), func() any { return &models.JobEvent{} }, func(v any) uuid.UUID { return v.(*models.JobEvent).Body.(models.SendEmailResult).TransportGeneration }}, - {"sync", models.JobEvent{Type: models.JobEventTypeSyncState, Body: &models.JobEventSyncState{WorkerID: &generation, EmailID: mailbox, State: models.SyncState{LastSyncedAt: &at, FolderCoverageObservedAt: &at, TransportGeneration: generation}}}, models.JobEvent{}.Schema(), func() any { return &models.JobEvent{} }, func(v any) uuid.UUID { + {"sync", models.JobEvent{Type: models.JobEventTypeSyncState, Body: &models.JobEventSyncState{WorkerID: &generation, ReportGeneration: generation, EmailID: mailbox, State: models.SyncState{LastSyncedAt: &at, FolderCoverageObservedAt: &at, TransportGeneration: generation}}}, models.JobEvent{}.Schema(), func() any { return &models.JobEvent{} }, func(v any) uuid.UUID { return v.(*models.JobEvent).Body.(*models.JobEventSyncState).State.TransportGeneration }}, {"error", models.JobEvent{Type: models.JobEventTypeEmailServerError, Body: models.EmailErrorEvent{EmailAccountID: mailbox.String(), Operation: models.MailTransportSync, TransportGeneration: generation}}, models.JobEvent{}.Schema(), func() any { return &models.JobEvent{} }, func(v any) uuid.UUID { return v.(*models.JobEvent).Body.(models.EmailErrorEvent).TransportGeneration }}, diff --git a/internal/models/event_schema_test.go b/internal/models/event_schema_test.go index cdc036331..59247a3fb 100644 --- a/internal/models/event_schema_test.go +++ b/internal/models/event_schema_test.go @@ -130,7 +130,7 @@ func preTransportSchema(t *testing.T, schema avro.Schema) avro.Schema { kept := fields[:0] for _, f := range fields { field := f.(map[string]any) - if slices.Contains(fieldsAfterFixtures, field["name"]) || x["name"] == "warmbly.events.EmailErrorEvent" && field["name"] == "operation" || x["name"] == "warmbly.events.JobEventSyncState" && field["name"] == "worker_id" { + if slices.Contains(fieldsAfterFixtures, field["name"]) || x["name"] == "warmbly.events.EmailErrorEvent" && field["name"] == "operation" || x["name"] == "warmbly.events.JobEventSyncState" && (field["name"] == "worker_id" || field["name"] == "report_generation") { continue } strip(f) diff --git a/internal/models/sync.go b/internal/models/sync.go index f1179c900..f975a0b34 100644 --- a/internal/models/sync.go +++ b/internal/models/sync.go @@ -145,7 +145,9 @@ type AddWorkerEmailSyncData struct { // not a delta, so a lost event is repaired by the next one. type JobEventSyncState struct { WorkerID *uuid.UUID `json:"worker_id,omitempty" avro:"worker_id"` - UserID uuid.UUID `json:"user_id" avro:"user_id"` - EmailID uuid.UUID `json:"email_id" avro:"email_id"` - State SyncState `json:"state" avro:"state"` + // ReportGeneration is the transport generation the reporting incarnation was loaded with. + ReportGeneration uuid.UUID `json:"report_generation,omitempty" avro:"report_generation"` + UserID uuid.UUID `json:"user_id" avro:"user_id"` + EmailID uuid.UUID `json:"email_id" avro:"email_id"` + State SyncState `json:"state" avro:"state"` } diff --git a/internal/repository/mail_transport_live_test.go b/internal/repository/mail_transport_live_test.go index c7a19ae12..8a1d48ae2 100644 --- a/internal/repository/mail_transport_live_test.go +++ b/internal/repository/mail_transport_live_test.go @@ -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, 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) } @@ -908,14 +908,14 @@ func TestLiveMailTransportSyncReportRequiresCurrentGeneration(t *testing.T) { 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) } - put := func(state models.SyncState, want bool) { + put := func(report uuid.UUID, state models.SyncState, want bool) { t.Helper() - accepted, err := repo.PutFromWorker(t.Context(), f.user, f.account, worker, &state, nil) + accepted, err := repo.PutFromWorker(t.Context(), f.user, f.account, worker, report, &state, nil) if err != nil || accepted != want { - t.Fatalf("generation=%s accepted=%t want=%t err=%v", state.TransportGeneration, accepted, want, err) + t.Fatalf("report=%s pass=%s accepted=%t want=%t err=%v", report, state.TransportGeneration, accepted, want, err) } } - put(models.SyncState{TransportGeneration: f.generation, BackfillStatus: models.SyncBackfillRunning, BackfillSynced: 3}, true) + put(f.generation, models.SyncState{TransportGeneration: f.generation, BackfillStatus: models.SyncBackfillRunning, BackfillSynced: 3}, true) var current uuid.UUID if err := f.pool.QueryRow(t.Context(), `UPDATE email_accounts SET transport_generation=gen_random_uuid() WHERE id=$1 RETURNING transport_generation`, f.account).Scan(¤t); err != nil { t.Fatal(err) @@ -923,13 +923,15 @@ func TestLiveMailTransportSyncReportRequiresCurrentGeneration(t *testing.T) { if _, err := f.pool.Exec(t.Context(), `UPDATE email_sync_state SET backfill_status='complete', backfill_synced=0 WHERE email_id=$1`, f.account); err != nil { t.Fatal(err) } - put(models.SyncState{TransportGeneration: f.generation, BackfillStatus: models.SyncBackfillRunning, BackfillSynced: 9}, false) + put(uuid.Nil, models.SyncState{TransportGeneration: f.generation, BackfillStatus: models.SyncBackfillRunning, BackfillSynced: 9}, false) + put(f.generation, models.SyncState{BackfillStatus: models.SyncBackfillRunning, BackfillSynced: 9}, false) got, err := repo.Get(t.Context(), f.account) if err != nil || got.BackfillStatus != models.SyncBackfillComplete || got.BackfillSynced != 0 { t.Fatalf("superseded generation wrote: %+v err=%v", got, err) } - put(models.SyncState{BackfillStatus: models.SyncBackfillComplete, BackfillSynced: 1}, true) - put(models.SyncState{TransportGeneration: current, BackfillStatus: models.SyncBackfillComplete, BackfillSynced: 2}, true) + put(current, models.SyncState{BackfillStatus: models.SyncBackfillComplete, BackfillSynced: 1}, true) + put(uuid.Nil, models.SyncState{BackfillStatus: models.SyncBackfillComplete, BackfillSynced: 2}, true) + put(current, models.SyncState{TransportGeneration: current, BackfillStatus: models.SyncBackfillComplete, BackfillSynced: 3}, true) } func TestLiveMailTransportSyncReportCommitsRecoveryAndBothClocks(t *testing.T) { @@ -964,10 +966,10 @@ func TestLiveMailTransportSyncReportCommitsRecoveryAndBothClocks(t *testing.T) { } return nil } - if accepted, err := repo.PutFromWorker(t.Context(), f.user, f.account, uuid.New(), 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, 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 @@ -983,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, 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) diff --git a/internal/repository/pg_email_sync_state.go b/internal/repository/pg_email_sync_state.go index 5f5d689e1..d9694f79a 100644 --- a/internal/repository/pg_email_sync_state.go +++ b/internal/repository/pg_email_sync_state.go @@ -21,8 +21,8 @@ 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. - PutFromWorker(ctx context.Context, userID, emailID, workerID 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. + PutFromWorker(ctx context.Context, userID, emailID, workerID, generation uuid.UUID, state *models.SyncState, before func(context.Context) error) (bool, 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 @@ -70,18 +70,18 @@ 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, 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 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) error) (bool, error) { if workerID == uuid.Nil { return false, nil } - return r.put(ctx, userID, emailID, &workerID, state, before) + return r.put(ctx, userID, emailID, &workerID, generation, state, before) } -func (r *pgEmailSyncStateRepository) put(ctx context.Context, userID, emailID uuid.UUID, workerID *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) error) (bool, error) { if state == nil { return false, nil } @@ -102,16 +102,19 @@ func (r *pgEmailSyncStateRepository) put(ctx context.Context, userID, emailID uu return false, fmt.Errorf("email_sync_state: lock: %w", err) } var assigned *uuid.UUID - var generation uuid.UUID - err = tx.QueryRow(ctx, `SELECT worker_id, transport_generation FROM email_accounts WHERE id=$1 FOR UPDATE`, emailID).Scan(&assigned, &generation) + 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) if err != nil && !errors.Is(err, pgx.ErrNoRows) { return false, fmt.Errorf("email_sync_state: owner: %w", err) } if workerID != nil && (assigned == nil || *assigned != *workerID) { return false, nil } - // A seeded incarnation reports a nil generation until its first completed pass. - if state.TransportGeneration != uuid.Nil && err == nil && state.TransportGeneration != generation { + // 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 } if before != nil { From 7a9b0445e10ef5f3abc5333cd4a6d9a51ad179e8 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Tue, 3 Nov 2026 09:23:49 +0100 Subject: [PATCH 101/318] feat: retain failed bulk warmup mailboxes for retry and deselect only confirmed successful starts --- docs/content/docs/guides/warmup.mdx | 2 +- web/src/app/app/emails/page.test.tsx | 31 +++++++++++++++++++ .../app/emails/BulkWarmupDialog.tsx | 5 +-- 3 files changed, 35 insertions(+), 3 deletions(-) diff --git a/docs/content/docs/guides/warmup.mdx b/docs/content/docs/guides/warmup.mdx index 11cbf6703..59b0f2551 100644 --- a/docs/content/docs/guides/warmup.mdx +++ b/docs/content/docs/guides/warmup.mdx @@ -228,7 +228,7 @@ While [Sending behavior](/guides/sending-behavior/) is on, warmup uses the overl Changing warmup hours, days or timezone, or switching sending behavior on or off, moves the queued warmup send to the new schedule as soon as you save. To recalculate an existing queued time, choose its day preset again and save. The mailbox list refreshes its queued time and shows whether warmup follows the sending plan or an explicit set of days. **Start warmup** for several mailboxes offers the same day presets; **Follow sending plan** resolves separately for each locally warmed mailbox and is hidden when the selection includes a Cloud-linked mailbox. Volume, consent, health and provider restrictions still apply on every selected day. -Bulk start waits until mailbox ownership is confirmed. If ownership refreshes while the dialog is open, your settings stay visible and new submissions wait for the check to finish. An operation already in progress finishes for its original mailbox selection and leaves any other selected mailboxes alone. +Bulk start waits until mailbox ownership is confirmed. If ownership refreshes while the dialog is open, your settings stay visible and new submissions wait for the check to finish. An operation already in progress finishes for its original mailbox selection and leaves any other selected mailboxes alone. Mailboxes that fail to start remain selected for retry. Warmup hours must end later than they start on the same day. Equal or reversed hours are rejected, including a change to only one endpoint that would invalidate the stored window. Existing invalid windows are not widened or corrected automatically: pending sends stay unstarted and recheck after five minutes, while admin monitoring shows **Invalid warmup sending hours** until the configured window is corrected. Other send protections still apply after correction; this does not replay uncertain sends or confirm mailbox recovery. diff --git a/web/src/app/app/emails/page.test.tsx b/web/src/app/app/emails/page.test.tsx index 3ea12a3f3..a172e2ec9 100644 --- a/web/src/app/app/emails/page.test.tsx +++ b/web/src/app/app/emails/page.test.tsx @@ -182,6 +182,37 @@ describe("mailbox ordering with a tag filter", () => { expect(within(screen.getByRole("row", { name: /julie@serveblink.example/ })).getByRole("checkbox")).toBeChecked(); }); + it("keeps failed bulk starts selected so retry only sends requests for those mailboxes", async () => { + warmupUpdate.mockImplementation(async (id: string) => { + if (id === "julie") throw new Error("Settings unavailable"); + }); + warmupStart.mockImplementation(async (id: string) => { + if (id === "kavya") throw new Error("Start unavailable"); + }); + await renderPage(); + const checkbox = (email: string) => within(screen.getByRole("row", { name: new RegExp(email.replaceAll(".", "\\.")) })).getByRole("checkbox"); + for (const row of rows.filter((row) => row.id !== "sara")) fireEvent.click(checkbox(row.email)); + fireEvent.click(screen.getByRole("button", { name: "Start warmup" })); + fireEvent.click(within(screen.getByRole("dialog", { name: "Start warmup" })).getByRole("button", { name: "Start warmup" })); + await waitFor(() => expect(screen.queryByRole("dialog", { name: "Start warmup" })).not.toBeInTheDocument()); + expect(screen.getByText("2 selected")).toBeInTheDocument(); + expect(checkbox(rows[2].email)).not.toBeChecked(); + expect(checkbox(rows[1].email)).toBeChecked(); + expect(checkbox(rows[3].email)).toBeChecked(); + expect(warmupStart).not.toHaveBeenCalledWith("julie", "start"); + + warmupUpdate.mockReset().mockResolvedValue({}); + warmupStart.mockReset().mockResolvedValue({}); + fireEvent.click(screen.getByRole("button", { name: "Start warmup" })); + fireEvent.click(within(screen.getByRole("dialog", { name: "Start warmup" })).getByRole("button", { name: "Start warmup" })); + await waitFor(() => expect(screen.queryByRole("dialog", { name: "Start warmup" })).not.toBeInTheDocument()); + expect(warmupUpdate).toHaveBeenCalledTimes(2); + expect(warmupStart).toHaveBeenCalledTimes(2); + expect(warmupStart).toHaveBeenCalledWith("julie", "start"); + expect(warmupStart).toHaveBeenCalledWith("kavya", "start"); + expect(screen.queryByText(/\d+ selected/)).not.toBeInTheDocument(); + }); + it("keeps that order when a specific tag returns rows in creation order", async () => { await renderPage("serveblink"); expect(orderedEmails()).toEqual(["ananya@serveblink.example", "julie@serveblink.example", "kavya@serveblink.example"]); diff --git a/web/src/components/app/emails/BulkWarmupDialog.tsx b/web/src/components/app/emails/BulkWarmupDialog.tsx index 06c8510de..595419f53 100644 --- a/web/src/components/app/emails/BulkWarmupDialog.tsx +++ b/web/src/components/app/emails/BulkWarmupDialog.tsx @@ -74,7 +74,8 @@ export default function BulkWarmupDialog({ await warmupLifecycle(id, "start"); }), ); - const failed = results.filter((r) => r.status === "rejected").length; + const started = ids.filter((_, index) => results[index].status === "fulfilled"); + const failed = n - started.length; await queryClient.invalidateQueries({ queryKey: ["emails"] }); await queryClient.invalidateQueries({ queryKey: ["analytics", "accounts"] }); setBusy(false); @@ -83,7 +84,7 @@ export default function BulkWarmupDialog({ } else { toast.success(`Warmup started for ${n} mailbox${n > 1 ? "es" : ""}`); } - onComplete(ids); + onComplete(started); onClose(); }; From eeb6531183bb60753c347a1352c6f7d489b96041 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Tue, 3 Nov 2026 09:26:56 +0100 Subject: [PATCH 102/318] feat: record the optional report_generation field on the published jobs.worker-events SYNC_STATE schema --- internal/app/eventschemas/testdata/jobs.worker-events.avsc | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/internal/app/eventschemas/testdata/jobs.worker-events.avsc b/internal/app/eventschemas/testdata/jobs.worker-events.avsc index 6eefb332d..ecb499ee3 100644 --- a/internal/app/eventschemas/testdata/jobs.worker-events.avsc +++ b/internal/app/eventschemas/testdata/jobs.worker-events.avsc @@ -700,6 +700,11 @@ "string" ] }, + { + "default": "", + "name": "report_generation", + "type": "string" + }, { "default": "", "name": "user_id", From 440f016c56532d783ce4b670559fe4f5fad1a36c Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Tue, 3 Nov 2026 09:31:56 +0100 Subject: [PATCH 103/318] feat: treat a reply that is only an opt-out command (STOP, remove, unsubscribe) as an opt-out, add opt-in stop_all_campaigns_on_reply holding a replying contact in their other campaigns, and add skip_active_in_other_campaigns to CSV import, bulk add and segment add-to-campaign with dashboard controls and docs --- docs/content/docs/api/reference/campaigns.mdx | 7 +- docs/content/docs/api/reference/contacts.mdx | 6 +- .../docs/api/reference/deliverability-ops.mdx | 7 +- docs/content/docs/guides/campaigns.mdx | 2 +- docs/content/docs/guides/contacts-crm.mdx | 2 + docs/content/docs/guides/segments.mdx | 2 +- docs/content/docs/guides/sequences.mdx | 6 + docs/content/docs/guides/unsubscribe.mdx | 4 +- internal/app/advanced/incoming_reply_test.go | 2 + .../app/advanced/reply_hold_others_test.go | 102 +++++++++++++++ internal/app/advanced/service.go | 30 ++++- internal/app/contact/import.go | 7 +- internal/app/replyclassify/lexicon.go | 15 ++- internal/app/replyclassify/optout_command.go | 119 ++++++++++++++++++ .../app/replyclassify/optout_command_test.go | 68 ++++++++++ internal/app/segment/service.go | 2 +- internal/models/advanced_outreach.go | 9 ++ internal/models/contact.go | 4 + internal/models/contact_import.go | 4 + internal/models/segment.go | 3 + .../repository/active_elsewhere_live_test.go | 82 ++++++++++++ internal/repository/pg_campaign_progress.go | 11 +- internal/repository/pg_contact.go | 21 +++- internal/repository/pg_segment.go | 14 ++- .../repository/segment_audience_live_test.go | 2 +- internal/repository/segment_live_test.go | 7 +- web/src/app/app/settings/sending/page.tsx | 21 +++- .../app/contacts/AddFromContactsDialog.tsx | 28 ++++- .../app/contacts/ContactsEditBulk.tsx | 10 ++ .../components/app/contacts/ImportWizard.tsx | 10 +- .../app/contacts/import/ReviewStep.tsx | 21 ++++ .../segments/AddSegmentToCampaignDialog.tsx | 16 ++- .../api/client/app/contacts/importContacts.ts | 2 + web/src/lib/api/client/app/segments/index.ts | 10 +- web/src/lib/api/hooks/app/segments/index.ts | 3 +- .../models/app/contacts/BulkEditContacts.ts | 2 + .../models/app/outreach/OutreachSettings.ts | 2 + 37 files changed, 617 insertions(+), 46 deletions(-) create mode 100644 internal/app/advanced/reply_hold_others_test.go create mode 100644 internal/app/replyclassify/optout_command.go create mode 100644 internal/app/replyclassify/optout_command_test.go create mode 100644 internal/repository/active_elsewhere_live_test.go diff --git a/docs/content/docs/api/reference/campaigns.mdx b/docs/content/docs/api/reference/campaigns.mdx index f59df9688..cb76497b3 100644 --- a/docs/content/docs/api/reference/campaigns.mdx +++ b/docs/content/docs/api/reference/campaigns.mdx @@ -392,7 +392,8 @@ A `CampaignAdvancedSettings` object: the campaign id, the `overrides` block, and "auto_pause_on_negative": false, "auto_suppress_on_unsubscribe_keyword": true, "hold_on_out_of_office": true, - "out_of_office_hold_days": 7 + "out_of_office_hold_days": 7, + "stop_all_campaigns_on_reply": false }, "send_time_optimization": { "enabled": false, @@ -439,7 +440,7 @@ Replace the campaign's advanced overrides. **Scope** `WRITE_CAMPAIGNS` ยท **Org "bounce_pipeline": { "enabled": true, "auto_suppress_on_bounce": true, "auto_suppress_on_complaint": true, "auto_suppress_on_unsubscribe": true, "auto_pause_campaign_on_spike": true, "pause_bounce_rate_threshold": 8, "pause_complaint_rate_threshold": 1.5 }, "task_reliability": { "enabled": true, "dlq_enabled": true, "max_attempts": 5, "execution_window_seconds": 300 }, "ab_testing": { "enabled": true, "default_winning_rule": "reply_rate", "auto_promote_winner": false, "min_sample_size": 30 }, - "reply_intent": { "enabled": true, "positive_keywords": [], "negative_keywords": [], "out_of_office_keywords": [], "question_keywords": [], "auto_create_crm_task": true, "crm_task_intents": ["positive", "question", "neutral", "negative"], "auto_pause_on_negative": false, "auto_suppress_on_unsubscribe_keyword": true, "hold_on_out_of_office": true, "out_of_office_hold_days": 7 }, + "reply_intent": { "enabled": true, "positive_keywords": [], "negative_keywords": [], "out_of_office_keywords": [], "question_keywords": [], "auto_create_crm_task": true, "crm_task_intents": ["positive", "question", "neutral", "negative"], "auto_pause_on_negative": false, "auto_suppress_on_unsubscribe_keyword": true, "hold_on_out_of_office": true, "out_of_office_hold_days": 7, "stop_all_campaigns_on_reply": false }, "send_time_optimization": { "enabled": true, "use_contact_timezone": true, "default_contact_timezone": "UTC", "preferred_hours": [9, 14], "weekend_weight_multiplier": 0.5 }, "preflight": { "enabled": true, "check_tracking_domain": true, "check_unsubscribe_header": true, "check_ab_variant_configured": false, "check_daily_limit": true, "check_schedule_window": true, "check_content_score": true, "min_content_score": 60 }, "dashboard": { "enabled": true, "show_suppression_log": true, "show_intent_summary": true, "show_dlq_stats": true } @@ -822,7 +823,7 @@ Read whether one contact's flow inside this campaign is currently held. A hold p } ``` -`hold` is absent when the lead is not held, including for a dated hold that has since expired. `until` is absent when the hold has no end, in which case only a resume lifts it. `source` is `out_of_office`, `inbox_tagging`, `manual`, or `cc` while the contact is [copied on another lead's emails](#set-a-leads-cc) in this campaign; a `cc` hold's `reason` is that lead's address. +`hold` is absent when the lead is not held, including for a dated hold that has since expired. `until` is absent when the hold has no end, in which case only a resume lifts it. `source` is `out_of_office`, `inbox_tagging` (a classified reply, or with `reply_intent.stop_all_campaigns_on_reply` on, a reply to another campaign), `manual`, or `cc` while the contact is [copied on another lead's emails](#set-a-leads-cc) in this campaign; a `cc` hold's `reason` is that lead's address. ### Errors diff --git a/docs/content/docs/api/reference/contacts.mdx b/docs/content/docs/api/reference/contacts.mdx index df774a9d0..f91b60f82 100644 --- a/docs/content/docs/api/reference/contacts.mdx +++ b/docs/content/docs/api/reference/contacts.mdx @@ -262,6 +262,7 @@ Auth: **Scope** `BULK_CONTACTS` ยท **Org permission** `manage_contacts` | `contacts` | string[] | Yes, unless `all` | Contact IDs to edit (1 to 10,000). | | `all`, `filters`, `exclude` | โ€” | No | Select by filter instead; see [selecting contacts](#selecting-contacts-for-a-bulk-action). | | `add_campaigns` | string[] | No | Campaign IDs to add. | +| `skip_active_in_other_campaigns` | boolean | No | Leave a contact out of `add_campaigns` while their sequence is still running in another campaign: queued, sending, or held, in a campaign that is not a draft and not completed. Contacts who replied, bounced, unsubscribed, failed or finished every step elsewhere are added. Defaults to `false`. | | `remove_campaigns` | string[] | No | Campaign IDs to remove. | | `add_categories` | string[] | No | Label IDs to add. | | `remove_categories` | string[] | No | Label IDs to remove. | @@ -428,6 +429,7 @@ Send `multipart/form-data` with a `file` field and an `options` field containing | `has_header` | boolean | Yes | Whether the first row is a header. | | `category_ids` | string[] | No | Label IDs to put on imported contacts. | | `campaign_ids` | string[] | No | Campaigns to add imported contacts to. | +| `skip_active_in_other_campaigns` | boolean | No | Keep a contact who already exists out of `campaign_ids` while their sequence is still running in another campaign, as `skip_active_in_other_campaigns` on a [bulk update](#bulk-update-contacts) defines it. The row is still imported or updated under `dedup`, and still gets its labels and segments. Defaults to `false`. | | `segment_ids` | string[] | No | Segments to pin imported contacts into, as a manual include override. Applies to imported, updated, and skipped-but-linked contacts alike. An id that is not a valid UUID, or that names no segment in the organization, is rejected with `400` before any row is written. | | `subscribed_default` | boolean | No | Subscription state for new contacts when no subscribed column is mapped. Defaults to true. | @@ -1316,9 +1318,9 @@ Sequence action steps `add_to_segment` and `remove_from_segment` take a `segment `POST /segments/:id/add-to-campaign` ```json -{ "campaign_id": "โ€ฆ" } +{ "campaign_id": "โ€ฆ", "skip_active_in_other_campaigns": true } ``` -Enrols every current member as a lead. Contacts already in the campaign are skipped, each new lead gets a `campaign_added` activity, and a running campaign is woken so the leads are scheduled. Returns `{ "campaign_id", "added", "members" }`. This is a snapshot: later members are not added until the call is repeated. Safe to retry. It counts as choosing the leads it adds, so it clears any hand-made removal and the rows it writes are never withdrawn by [detaching a segment](/api/reference/campaigns/#replace-linked-segments). Members that are already leads are left exactly as they are, provenance included. For a live link that keeps enrolling members as they join the segment, see [linked segments](/api/reference/campaigns/#list-linked-segments). +Enrols every current member as a lead. Contacts already in the campaign are skipped, each new lead gets a `campaign_added` activity, and a running campaign is woken so the leads are scheduled. With `skip_active_in_other_campaigns` (optional, default `false`), a member whose sequence is still running in another campaign is left out too, as on a [bulk update](#bulk-update-contacts), and keeps any hand-made removal. Returns `{ "campaign_id", "added", "members" }`. This is a snapshot: later members are not added until the call is repeated. Safe to retry. It counts as choosing the leads it adds, so it clears any hand-made removal and the rows it writes are never withdrawn by [detaching a segment](/api/reference/campaigns/#replace-linked-segments). Members that are already leads are left exactly as they are, provenance included. For a live link that keeps enrolling members as they join the segment, see [linked segments](/api/reference/campaigns/#list-linked-segments). Auth: **Scope** `WRITE_CAMPAIGNS` ยท **Org permission** `manage_campaigns` diff --git a/docs/content/docs/api/reference/deliverability-ops.mdx b/docs/content/docs/api/reference/deliverability-ops.mdx index bf239fb23..0c0315c5f 100644 --- a/docs/content/docs/api/reference/deliverability-ops.mdx +++ b/docs/content/docs/api/reference/deliverability-ops.mdx @@ -53,7 +53,8 @@ Returns the `AdvancedOutreachSettings` object directly (not wrapped in an envelo "auto_pause_on_negative": false, "auto_suppress_on_unsubscribe_keyword": true, "hold_on_out_of_office": true, - "out_of_office_hold_days": 7 + "out_of_office_hold_days": 7, + "stop_all_campaigns_on_reply": false }, "send_time_optimization": { "enabled": false, @@ -102,6 +103,10 @@ The `unsubscribe` block is the workspace default for the opt-out appended after `reply_intent.hold_on_out_of_office` defaults to `true`. When a recipient's mailbox answers a campaign step with an away message, the contact's next step in that campaign is held until they are back: the return date in the auto-reply when one can be read, plus a working day, and `out_of_office_hold_days` (1 to 90, default `7`) when none can. An auto-reply is never counted as a human reply, so without this the follow-up goes out on schedule while the person is away. `out_of_office_keywords` feeds the reply-intent record and is workspace-editable; detection itself carries its own multilingual vocabulary and does not depend on it. See [out of office and pausing one lead](/guides/campaigns/#out-of-office-and-pausing-one-lead) and [pause a lead](/api/reference/campaigns/#pause-a-lead).
+ +`reply_intent.stop_all_campaigns_on_reply` defaults to `false`. Set it to `true` and a human reply also holds the contact in every other campaign they are a lead of that has not completed, for 365 days, with the reason `replied to another campaign` and the source `inbox_tagging`. Automatic replies never trigger it, the answered campaign is left to its own stop on reply, and a member's own pause is never replaced. Lift it like any hold, with [resume a lead](/api/reference/campaigns/#pause-a-lead). Omitting the field keeps it off. See [other campaigns the contact is in](/guides/sequences/#other-campaigns-the-contact-is-in). + + `send_time_optimization.enabled` defaults to `false`. Set it to `true` and campaign scheduling holds each send until the recipient's local clock reaches one of `preferred_hours`, resolving the recipient's timezone from the contact's `timezone` custom field, then the country-code suffix of its email domain, then `default_contact_timezone`. It can only delay a send: the campaign window, the mailbox's sending profile, its daily cap, and the campaign end date all still bind. See [Sending behavior](/guides/sending-behavior/). diff --git a/docs/content/docs/guides/campaigns.mdx b/docs/content/docs/guides/campaigns.mdx index 5ebaff198..4ff53f320 100644 --- a/docs/content/docs/guides/campaigns.mdx +++ b/docs/content/docs/guides/campaigns.mdx @@ -258,7 +258,7 @@ Anything above `50`/day per cold mailbox needs positive reputation signals and a ### Adding leads -The **Leads** tab takes contacts four ways. **From contacts** opens a picker over the workspace contact list: search by name, email or company, filter by label, tick individual people or **Select loaded**, or **Select all matching** to add everyone the search returns, up to `250,000` at a time (narrow the search and repeat past that). Contacts already in the campaign are marked as leads and skipped. **Import** runs the file import wizard with this campaign preselected (its Options step can also pin the file into segments), **Sheet sync** attaches a Google Sheet, and **Add lead** creates a single new contact in the campaign. Any workspace member with contact access can add leads to any campaign in the workspace, whoever created it. +The **Leads** tab takes contacts four ways. **From contacts** opens a picker over the workspace contact list: search by name, email or company, filter by label, tick individual people or **Select loaded**, or **Select all matching** to add everyone the search returns, up to `250,000` at a time (narrow the search and repeat past that). Contacts already in the campaign are marked as leads and skipped. Tick **Skip anyone running in another campaign** in the picker's footer to leave out contacts whose sequence is still queued, sending or held in another campaign that is not a draft and not completed; the same option is on the import wizard, a segment's **Add to campaign** and the contacts page's bulk edit. **Import** runs the file import wizard with this campaign preselected (its Options step can also pin the file into segments), **Sheet sync** attaches a Google Sheet, and **Add lead** creates a single new contact in the campaign. Any workspace member with contact access can add leads to any campaign in the workspace, whoever created it. **Segments** on the same toolbar links [segments](/guides/segments/) to the campaign as a live audience, up to 20 per campaign. Linking enrols every current member immediately and turns on **Keep running for new leads**, and contacts who enter a linked segment later are enrolled on their own, within a couple of minutes. An active campaign wakes to send to them (a campaign waiting for leads picks up straight away), a finished one restarts through the usual launch checks, and a paused one accumulates them for later. A contact who leaves a linked segment keeps their lead row, but detaching the segment itself takes its leads back out, so swapping one segment for another leaves the campaign with the new list rather than both. Leads the campaign has already emailed stay, as do any you added by hand and anyone a segment that stayed linked still covers; the dialog asks before a save that costs leads. See [linking a segment to a campaign](/guides/segments/#linking-a-segment-to-a-campaign). diff --git a/docs/content/docs/guides/contacts-crm.mdx b/docs/content/docs/guides/contacts-crm.mdx index 25c3fecf2..818a2b70d 100644 --- a/docs/content/docs/guides/contacts-crm.mdx +++ b/docs/content/docs/guides/contacts-crm.mdx @@ -102,6 +102,8 @@ Two columns may fill the same field, which is how a `Phone` and a `Mobile` colum `Dana@Acme.com` and `dana@acme.com` are the same contact, and a contact belongs to the workspace, so an address a teammate already added counts as one you have. Choose **Leave as is** (their details stay untouched) or **Update details** (empty details are filled in from the file). The API also accepts `create_duplicate`, which updates too, since one address is one contact per workspace. Skipping still adds the contact to the campaigns, segments, and labels the import targets: it leaves their fields alone, it does not leave them out of the list. If the same address appears twice in one file it becomes one contact, and the extra rows count as skipped with the line they repeat. + +To keep people another campaign is still emailing out of this import's campaigns, tick **Skip contacts already running in another campaign** under **Campaigns** on **Review**. A contact counts as running when their sequence in a campaign that is not a draft and not completed is still queued, sending or held. One who replied, bounced, unsubscribed or finished every step there is added as usual. Skipped contacts are still imported or updated and still get the import's labels and segments; only the campaign enrolment is left out. It is off by default. An address you already hold as a contact in another workspace you belong to cannot be added to this one, and that row fails with a reason saying so; the other workspace's contact is never changed by an import here. diff --git a/docs/content/docs/guides/segments.mdx b/docs/content/docs/guides/segments.mdx index 26071aeee..8fe7844e6 100644 --- a/docs/content/docs/guides/segments.mdx +++ b/docs/content/docs/guides/segments.mdx @@ -111,7 +111,7 @@ A segment with no conditions at all is a plain list: it holds exactly the contac ## Using a segment - **Browse**: a segment page lists its current members with the same table, filters, detail drawer and bulk actions as the contacts page, including [**Select all matching**](/guides/contacts-crm/#selecting-rows) so an action covers every member and not only the rows loaded so far, for selections up to `250,000` contacts. -- **Add to campaign**: enrols every current member as a lead of the campaign you pick, from the segment page or with **From segment** on a campaign's Leads tab. Contacts already in that campaign are skipped, and a running campaign wakes up to schedule the new leads. This is a snapshot: contacts who join the segment later are not added until you run it again. To keep a campaign fed automatically, [link the segment](#linking-a-segment-to-a-campaign) instead. +- **Add to campaign**: enrols every current member as a lead of the campaign you pick, from the segment page or with **From segment** on a campaign's Leads tab. Contacts already in that campaign are skipped, and a running campaign wakes up to schedule the new leads. Tick **Skip contacts already running in another campaign** to also leave out members whose sequence is still running in another campaign. This is a snapshot: contacts who join the segment later are not added until you run it again. To keep a campaign fed automatically, [link the segment](#linking-a-segment-to-a-campaign) instead. - **Link to campaign**: attaches the segment to a campaign as a live audience, so contacts who join the segment later become leads on their own. See [below](#linking-a-segment-to-a-campaign). - **New campaign**: pick the segment as a lead list on the first step of **Campaigns** > **New campaign**, which shows how many leads it holds and how long the mailbox pool needs to reach them. See [create a campaign](/guides/campaigns/#create-a-campaign). - **Filter**: the contact list's filter bar has a **Segment** pill, and the same scope carries into an export. diff --git a/docs/content/docs/guides/sequences.mdx b/docs/content/docs/guides/sequences.mdx index 829643bdf..ce4791ecc 100644 --- a/docs/content/docs/guides/sequences.mdx +++ b/docs/content/docs/guides/sequences.mdx @@ -337,6 +337,12 @@ A new email from a contact that answers no thread of yours counts toward the las A reply that lands in the mailbox a send's reply-to named counts the same way, although that mailbox never wrote to the contact. That is what a [shared reply inbox](/guides/mailboxes/#a-shared-reply-inbox) relies on: the reply stops the sequence, runs the reply branch, and is credited to the mailbox that sent the email. +### Other campaigns the contact is in + +By default a reply stops only the campaign it answered. A contact who is also a lead of another campaign keeps receiving that campaign's steps. To stop those too, turn on **Settings > Sending > Replies > Hold the contact in every other campaign**. A human reply then holds the contact in every other campaign they are a lead of that has not completed, for a year. Out-of-office and other automatic replies never trigger it. The campaign they answered is left to its own **Stop on reply** and reply branches. + +The hold works like any other: it shows on each campaign's **Leads** tab with the reason "replied to another campaign", and **Resume now** lifts it. It never shortens or replaces a pause a member set by hand. The setting is `reply_intent.stop_all_campaigns_on_reply` in the [outreach settings](/api/reference/deliverability-ops/). + When an upgrade repairs a reply marker that was provably created by a synchronized Sent message, the contact resumes at the next due step and the campaign reply totals update with it. An upgrade also restores provable human replies that were received by one campaign mailbox but referenced a thread started by another mailbox in the workspace. Warmbly recalculates address verification from the corrected delivery, open, click, reply, and bounce evidence. It leaves ambiguous historical replies untouched. diff --git a/docs/content/docs/guides/unsubscribe.mdx b/docs/content/docs/guides/unsubscribe.mdx index 76158dc31..fe258f5de 100644 --- a/docs/content/docs/guides/unsubscribe.mdx +++ b/docs/content/docs/guides/unsubscribe.mdx @@ -37,7 +37,7 @@ To use a different mode for one campaign, set it under **Preferences** on that c ## Good to know -- A reply asking to stop, such as "remove me", puts the sender on the suppression list. A reply saying "not interested" does not. +- A reply asking to stop, such as "remove me" or just "STOP", puts the sender on the suppression list. A reply saying "not interested" does not. - **Contacts > Suppression list** is workspace-wide: no campaign emails an address on it. - A bare domain such as `acme.com` suppresses every address at it. - An unsubscribe link opens a confirmation page, and nothing happens until the recipient presses its button. @@ -121,6 +121,8 @@ Two things to know. Gmail only shows its button for mail it already classes as b Warmbly reads every reply to a campaign email. One that asks to stop, in wording such as "unsubscribe", "remove me", "stop emailing me", "opt out" or "do not contact", puts the sender on the suppression list immediately. Replies in every tagging language are read the same way, whatever languages the workspace tags in: "bitte austragen", "dรฉsinscrivez-moi", "denme de baja", "wypiszcie mnie", "ะพั‚ะฟะธัˆะธั‚ะต ะผะตะฝั" or "้…ไฟกๅœๆญข" opt the sender out too. The quoted history is cut in each of those languages as well, so a campaign that carries its own opt-out line in German or Japanese does not opt out everyone who answers it. Only the new text of the reply is read: the quoted history below it carries your own opt-out wording and is ignored. Phrases match on whole words, so "stop by our booth" does not opt anyone out. +A reply that is nothing but the command opts out too: "STOP", "Stop.", "stop please", "Remove", "Unsubscribe", "opt out", and the single-word "Stopp", "Abmelden", "Austragen", "Afmelden" or "Baja", in any case and with any punctuation. A greeting above the word, and a sign-off, signature or mobile footer such as "Sent from my iPhone" below it, are ignored. The word counts only when it is the whole message: "Stop by tomorrow", "I can't stop thinking about this" and "remove the attachment" opt nobody out, and neither does "Stop" followed by a sentence. + Only a person answering you can opt out this way: someone replying in one of your campaign threads, or one of your contacts writing to you. Everything else that lands in a mailbox is left alone, even when it says "unsubscribe": - a bounce or delivery failure, which returns your own email (and its unsubscribe header) inside the notice diff --git a/internal/app/advanced/incoming_reply_test.go b/internal/app/advanced/incoming_reply_test.go index c1513d10b..6a382b718 100644 --- a/internal/app/advanced/incoming_reply_test.go +++ b/internal/app/advanced/incoming_reply_test.go @@ -20,6 +20,7 @@ type incomingReplyAdvancedRepo struct { intents int intentOff bool holdOff bool + stopAll bool languages []string } @@ -129,6 +130,7 @@ func (r *incomingReplyAdvancedRepo) GetOutreachSettings(context.Context, uuid.UU settings := models.DefaultAdvancedOutreachSettings() settings.ReplyIntent.Enabled = !r.intentOff settings.ReplyIntent.HoldOnOutOfOffice = !r.holdOff + settings.ReplyIntent.StopAllCampaignsOnReply = r.stopAll settings.InboxTagging.Languages = r.languages return &settings, nil } diff --git a/internal/app/advanced/reply_hold_others_test.go b/internal/app/advanced/reply_hold_others_test.go new file mode 100644 index 000000000..adefa27ce --- /dev/null +++ b/internal/app/advanced/reply_hold_others_test.go @@ -0,0 +1,102 @@ +package advanced + +import ( + "context" + "testing" + "time" + + "github.com/google/uuid" + + "github.com/warmbly/warmbly/internal/models" +) + +// elsewhereRecorder records the holds a reply writes across campaigns. +type elsewhereRecorder struct { + *incomingReplyProgressRepo + except []uuid.UUID + until *time.Time + source string + everywhere int +} + +func (r *elsewhereRecorder) HoldLeadElsewhere(_ context.Context, _, except uuid.UUID, until *time.Time, _, source string) ([]uuid.UUID, error) { + r.except = append(r.except, except) + r.until, r.source = until, source + return []uuid.UUID{uuid.New()}, nil +} + +func (r *elsewhereRecorder) HoldLeadEverywhere(context.Context, uuid.UUID, *time.Time, string, string) ([]uuid.UUID, error) { + r.everywhere++ + return nil, nil +} + +func newReplyHoldService(stopAll bool) (*service, *elsewhereRecorder, uuid.UUID, uuid.UUID) { + orgID, accountID, contactID := uuid.New(), uuid.New(), uuid.New() + account := &models.Email{ID: accountID, OrganizationID: &orgID, Email: "owner@acme.test"} + svc, progress := newIncomingReplyService(account, &models.Contact{ID: contactID, Email: "lead@example.com"}, contactID) + progress.advanced.stopAll = stopAll + rec := &elsewhereRecorder{incomingReplyProgressRepo: progress} + svc.campaignProgressRepo = rec + return svc, rec, accountID, *svc.taskRepo.(incomingReplyTaskRepo).campaign.CampaignID +} + +func replyFromLead(accountID uuid.UUID, subject, body string, flags []string) *models.EmailMessageStoreData { + return &models.EmailMessageStoreData{ + ID: uuid.New(), EmailID: accountID, Folder: models.FolderInbox, + FromAddr: []string{"Lead "}, + ToAddr: []string{"owner@acme.test"}, + InReplyTo: []string{""}, + Subject: subject, Snippet: body, BodyText: body, + Flags: flags, + } +} + +// With the setting on, a human reply holds the contact in every campaign but +// the one it answered, as a dated automatic hold. +func TestHumanReplyHoldsOtherCampaignsWhenEnabled(t *testing.T) { + svc, rec, accountID, answered := newReplyHoldService(true) + if xerr := svc.ProcessIncomingReply(context.Background(), accountID, + replyFromLead(accountID, "Re: Hello", "Sounds good, let's talk Tuesday.", nil)); xerr != nil { + t.Fatal(xerr) + } + if len(rec.except) != 1 || rec.except[0] != answered { + t.Fatalf("HoldLeadElsewhere excepts %v, want once for the answered campaign %s", rec.except, answered) + } + if rec.source != models.LeadHoldSourceInboxTagging { + t.Fatalf("hold source = %q, want an automatic hold a member can resume", rec.source) + } + if rec.until == nil || time.Until(*rec.until) < 300*24*time.Hour { + t.Fatalf("hold lifts at %v, want about a year out", rec.until) + } +} + +// Off, the default, a reply stops only the campaign it answered. +func TestHumanReplyHoldsNothingElseByDefault(t *testing.T) { + if models.DefaultAdvancedOutreachSettings().ReplyIntent.StopAllCampaignsOnReply { + t.Fatal("stop_all_campaigns_on_reply defaults on, want off") + } + svc, rec, accountID, _ := newReplyHoldService(false) + if xerr := svc.ProcessIncomingReply(context.Background(), accountID, + replyFromLead(accountID, "Re: Hello", "Sounds good, let's talk Tuesday.", nil)); xerr != nil { + t.Fatal(xerr) + } + if len(rec.except) != 0 { + t.Fatalf("HoldLeadElsewhere called %d times with the setting off", len(rec.except)) + } +} + +// An auto-reply is not the person answering, so it never holds other campaigns. +func TestAutoReplyHoldsNoOtherCampaigns(t *testing.T) { + svc, rec, accountID, _ := newReplyHoldService(true) + if xerr := svc.ProcessIncomingReply(context.Background(), accountID, + replyFromLead(accountID, "Automatic reply: Hello", "I am out of the office until Monday.", + []string{"Auto-Submitted:auto-replied"})); xerr != nil { + t.Fatal(xerr) + } + if rec.replied != 0 || rec.classified != 1 { + t.Fatalf("auto-reply not read as automated: replied=%d classified=%d", rec.replied, rec.classified) + } + if len(rec.except) != 0 { + t.Fatalf("an auto-reply held other campaigns %d times", len(rec.except)) + } +} diff --git a/internal/app/advanced/service.go b/internal/app/advanced/service.go index 72ef94d7a..40f243a9c 100644 --- a/internal/app/advanced/service.go +++ b/internal/app/advanced/service.go @@ -1300,7 +1300,8 @@ func (s *service) ProcessIncomingReply(ctx context.Context, emailAccountID uuid. // when an out-of-office hold lifts, for the notification to name. replyClaimToken := uuid.Nil replyClaimCompleted := false - + // humanReply is a reply recorded as the lead's answer to a campaign. + humanReply := false var campaignID *uuid.UUID var sequenceID *uuid.UUID var contactID *uuid.UUID @@ -1502,6 +1503,7 @@ func (s *service) ProcessIncomingReply(ctx context.Context, emailAccountID uuid. } return nil } + humanReply = true } if s.evidence != nil { kind := "replied" @@ -1618,9 +1620,16 @@ func (s *service) ProcessIncomingReply(ctx context.Context, emailAccountID uuid. } actionTaken := "" + if humanReply && settings.ReplyIntent.StopAllCampaignsOnReply && s.holdOtherCampaigns(ctx, *contactID, *campaignID) { + actionTaken = "held_other_campaigns" + } if settings.ReplyIntent.AutoPauseOnNegative && intent == models.ReplyIntentNegative && campaignID != nil { _ = s.campaignRepo.UpdateStatus(ctx, *campaignID, "paused") - actionTaken = "paused_campaign" + if actionTaken == "" { + actionTaken = "paused_campaign" + } else { + actionTaken += ",paused_campaign" + } } // Reply-based opt-out is what makes the plain "just reply and I'll stop" @@ -1855,6 +1864,23 @@ func ptrTime(t time.Time) *time.Time { return &t } +// holdOtherCampaigns parks a contact who replied in every other campaign they +// are a lead of, as a dated automatic hold a member resumes from the Leads tab. +// Best-effort, like every reply action; reports whether any campaign was held. +func (s *service) holdOtherCampaigns(ctx context.Context, contactID, answered uuid.UUID) bool { + if s.campaignProgressRepo == nil { + return false + } + until := time.Now().UTC().AddDate(0, 0, models.ReplyHoldOtherCampaignsDays) + held, err := s.campaignProgressRepo.HoldLeadElsewhere(ctx, contactID, answered, &until, + "replied to another campaign", models.LeadHoldSourceInboxTagging) + if err != nil { + log.Warn().Err(err).Str("contact_id", contactID.String()).Msg("reply hold: other campaigns could not be held") + return false + } + return len(held) > 0 +} + // verifyEventOwnership refuses a deliverability event whose campaign, contact // or task belongs to another organization. Anything absent is fine; anything // present has to resolve inside the caller's workspace. diff --git a/internal/app/contact/import.go b/internal/app/contact/import.go index df695b4da..f1936f496 100644 --- a/internal/app/contact/import.go +++ b/internal/app/contact/import.go @@ -724,9 +724,10 @@ func (s *contactService) applyImportChunk( continue } if _, xerr := s.contactRepository.BulkUpdate(ctx, plan.userID, plan.orgID, &models.BulkEditContactsData{ - ContactSelection: models.ContactSelection{Contacts: group.contactIDs}, - AddCampaigns: group.campaigns, - AddCategories: group.categories, + ContactSelection: models.ContactSelection{Contacts: group.contactIDs}, + AddCampaigns: group.campaigns, + SkipActiveInOtherCampaigns: plan.opts.SkipActiveInOtherCampaigns, + AddCategories: group.categories, }); xerr != nil { for _, i := range group.members { linkErr[i] = xerr.Message diff --git a/internal/app/replyclassify/lexicon.go b/internal/app/replyclassify/lexicon.go index f5e648536..89b594e58 100644 --- a/internal/app/replyclassify/lexicon.go +++ b/internal/app/replyclassify/lexicon.go @@ -20,13 +20,14 @@ import ( // 4. Clear rejection phrases => negative. func classifyLexicon(in Input) (Result, bool) { // The subject ends its own sentence, so a negator there never reaches the body. - text := quoteFolder.Replace(strings.ToLower(strings.TrimSpace(in.Subject + ".\n" + StripQuoted(in.BodyText, slices.Concat(in.Languages, optOutLanguages)...)))) + body := StripQuoted(in.BodyText, slices.Concat(in.Languages, optOutLanguages)...) + text := quoteFolder.Replace(strings.ToLower(strings.TrimSpace(in.Subject + ".\n" + body))) if text == "" { return Result{}, false } // 1. Compliance / opt-out (highest priority). - if matchesOptOut(text) { + if matchesOptOut(text) || isOptOutCommand(body) { return Result{Class: ClassUnsubscribe, Confidence: 0.9, Source: SourceLexicon}, true } @@ -66,7 +67,8 @@ func classifyLexicon(in Input) (Result, bool) { // unsubscribeKeywords are explicit opt-out requests. Compliance-first: any of // these short-circuits to "unsubscribe" before sentiment is considered. Each -// is matched on word boundaries, so "stop" alone never fires on "stop by". +// is matched on word boundaries, so "stop" alone never fires on "stop by"; a +// reply that is only the word is isOptOutCommand's. var unsubscribeKeywords = []string{ "unsubscribe", "opt out", @@ -229,7 +231,7 @@ func matchesOptOut(lowerText string) bool { // included. It is not a decision: it finds the message an earlier reading of // the whole body acted on. func MentionsOptOut(subject, body string) bool { - return matchesOptOut(strings.ToLower(subject + "\n" + body)) + return matchesOptOut(strings.ToLower(subject+"\n"+body)) || isOptOutCommand(StripQuoted(body, optOutLanguages...)) } // IsOptOut reports whether a reply, read without its quoted history, asks to @@ -237,11 +239,12 @@ func MentionsOptOut(subject, body string) bool { // the quoted original carries the sender's own opt-out line, so matching the // whole body would opt out everyone who replies. func IsOptOut(subject, body string) bool { - text := strings.ToLower(strings.TrimSpace(subject + "\n" + StripQuoted(body, optOutLanguages...))) + reply := StripQuoted(body, optOutLanguages...) + text := strings.ToLower(strings.TrimSpace(subject + "\n" + reply)) if text == "" { return false } - return matchesOptOut(text) + return matchesOptOut(text) || isOptOutCommand(reply) } // quoteMarker begins the quoted history a mail client appends to a reply. diff --git a/internal/app/replyclassify/optout_command.go b/internal/app/replyclassify/optout_command.go new file mode 100644 index 000000000..a242d3ea8 --- /dev/null +++ b/internal/app/replyclassify/optout_command.go @@ -0,0 +1,119 @@ +package replyclassify + +import ( + "regexp" + "strings" + "unicode" + "unicode/utf8" +) + +// The command words stand alone only when the reply is nothing else, which is +// why "stop" is not in unsubscribeKeywords. Besides English, the one word a +// German, Dutch, Nordic or Spanish reader types for the same thing. +const ( + commandWords = `(?:stop|stopp|remove|remove me|unsubscribe|unsubscribe me|opt out|optout|abmelden|austragen|afmelden|baja)` + commandPolite = `(?:please|pls|plz|now|thanks|thank you|thx|ty|bitte|danke|graag|alstublieft|aub|por favor|gracias|svp|merci|tack)` +) + +// optOutCommand matches one line, read through commandText, that is only an +// opt-out command and the courtesy around it: "STOP!!", "Remove.", "please stop". +var optOutCommand = regexp.MustCompile(`^(?:` + commandPolite + ` )*` + commandWords + `(?: (?:` + commandWords + `|` + commandPolite + `))*$`) + +// commandGreeting is a salutation line above the command ("Hi John,"). +var commandGreeting = regexp.MustCompile(`^(?:hi|hello|hey|dear|hallo|hola|bonjour|hej|good morning|good afternoon|guten tag|moin)(?: \S+){0,3}$`) + +// commandSignOff opens the sign-off that ends a reply, name and all. +var commandSignOff = regexp.MustCompile(`^(?:thanks|thank you|thx|many thanks|cheers|regards|best|best regards|kind regards|warm regards|sincerely|br|kr|mfg|lg|vg|viele gruesse|beste gruesse|freundliche gruesse|mit freundlichen gruessen|gruss|gruesse|saludos|cordialement|bien a vous|met vriendelijke groet|groeten|mvh|hilsen|med vanlig halsning)(?: \S+){0,4}$`) + +// commandFooter is a line from which everything below is boilerplate: a mobile +// client's footer or a legal disclaimer. +var commandFooter = regexp.MustCompile(`^(?:sent from|sent via|sent with|get outlook|download outlook|envoye de|envoye depuis|gesendet von|von meinem|enviado desde|enviado do|verzonden vanaf|verstuurd vanaf|skickat fran|inviato da|confidential|this email|this e mail|this message|disclaimer|the information contained|diese e mail|diese nachricht)`) + +// proseWords mark a sentence rather than a signature line (a name, a title, a +// company, a phone number). +var proseWords = map[string]bool{ + "i": true, "me": true, "my": true, "we": true, "us": true, "our": true, "you": true, "your": true, + "it": true, "is": true, "are": true, "am": true, "was": true, "be": true, "but": true, "not": true, + "don": true, "do": true, "would": true, "could": true, "can": true, "will": true, "if": true, + "so": true, "just": true, "actually": true, "love": true, "like": true, "want": true, + "interested": true, "please": true, "call": true, "send": true, "tell": true, "by": true, + "ich": true, "wir": true, "sie": true, "ist": true, "aber": true, "nicht": true, +} + +// signatureMaxLines bounds the signature an unsigned-off command may carry. +const signatureMaxLines = 8 + +// commandText folds a line for the command patterns: case, accents and +// punctuation are dropped, words single-spaced. +func commandText(line string) string { + folded := []rune(foldOptOut(line)) + for i, r := range folded { + if !unicode.IsLetter(r) && !unicode.IsNumber(r) { + folded[i] = ' ' + } + } + return strings.Join(strings.Fields(string(folded)), " ") +} + +// isOptOutCommand reports a reply, quoted history already cut, that says +// nothing but an opt-out command: its first line after any greeting is the +// command, and what follows is at most a sign-off, a signature or a footer. +func isOptOutCommand(body string) bool { + lines := strings.Split(strings.ReplaceAll(body, "\r\n", "\n"), "\n") + for i, raw := range lines { + text := commandText(raw) + switch { + case optOutCommand.MatchString(text): + return signatureOnly(lines[i+1:]) + case text == "" || commandGreeting.MatchString(text): + continue + default: + return false + } + } + return false +} + +// signatureOnly reports whether the lines under the command are only a +// signature. A lowercase line straight below it continues the sentence +// ("Stop" / "by our booth"), so it is prose. +func signatureOnly(lines []string) bool { + n := 0 + for _, raw := range lines { + ln := strings.TrimSpace(raw) + if ln == "" { + continue + } + if strings.HasPrefix(ln, "--") || strings.HasPrefix(ln, "__") { + return true + } + text := commandText(ln) + if commandSignOff.MatchString(text) || commandFooter.MatchString(text) { + return true + } + if first, _ := utf8.DecodeRuneInString(ln); n == 0 && unicode.IsLower(first) { + return false + } + if n++; n > signatureMaxLines || !signatureLine(ln, text) { + return false + } + } + return true +} + +// signatureLine is a short line with no question, exclamation or prose word. +func signatureLine(raw, text string) bool { + if strings.ContainsAny(raw, "?!") { + return false + } + words := strings.Fields(text) + if len(words) > 6 { + return false + } + for _, w := range words { + if proseWords[w] { + return false + } + } + return true +} diff --git a/internal/app/replyclassify/optout_command_test.go b/internal/app/replyclassify/optout_command_test.go new file mode 100644 index 000000000..e4d0fd816 --- /dev/null +++ b/internal/app/replyclassify/optout_command_test.go @@ -0,0 +1,68 @@ +package replyclassify + +import "testing" + +// A reply that is only an opt-out command opts out; the same word inside a +// sentence does not. +func TestIsOptOutCommandReply(t *testing.T) { + optOut := map[string]string{ + "bare": "STOP", + "lower": "stop", + "period": "Stop.", + "bangs": "STOP!!", + "please after": "stop please", + "please before": "Please stop.", + "remove": "Remove", + "remove me": "remove me!", + "unsubscribe": "UNSUBSCRIBE", + "opt out": "Opt out", + "optout": "optout", + "german": "Stopp bitte", + "spanish": "Baja", + "iphone footer": "Stop\n\nSent from my iPhone", + "outlook footer": "STOP\r\n\r\nGet Outlook for Android", + "sign-off": "Stop.\n\nThanks,\nJohn", + "signature": "Stop\n\nJohn Smith\nVP Sales, Acme Inc\n+1 555 123 4567", + "delimiter": "stop\n-- \nJohn Smith\nThis line is a long company tagline that goes on and on about the company", + "greeting": "Hi Jane,\n\nStop.\n\nBest,\nJohn", + "quoted history": "STOP\n\nOn Tue, Sep 1, 2026 Jane wrote:\n> Do you have ten minutes next week?", + "crlf": "Stop\r\n", + "leading blank": "\n\n stop \n", + "thanks after": "Remove, thanks", + "repeated": "stop stop stop", + "disclaimer foot": "Stop\n\nThis email and any attachments are confidential and intended solely for the addressee.", + } + for name, body := range optOut { + if !IsOptOut("Re: Quick question", body) { + t.Errorf("%s: IsOptOut(%q) = false, want true", name, body) + } + if !MentionsOptOut("Re: Quick question", body) { + t.Errorf("%s: MentionsOptOut(%q) = false, want true", name, body) + } + if r, ok := classifyLexicon(Input{BodyText: body}); !ok || r.Class != ClassUnsubscribe { + t.Errorf("%s: classifyLexicon(%q) = %+v, want unsubscribe", name, body, r) + } + } + + notOptOut := map[string]string{ + "booth": "Stop by our booth next week!", + "stop by": "stop by tomorrow", + "cant stop": "I can't stop thinking about this.", + "attachment": "remove the attachment", + "wrapped sentence": "Stop\nby our booth next week", + "prose under": "Stop\n\nActually I'd love a demo", + "question under": "Stop.\n\nCan we talk next week?", + "stop sign": "Stop sign", + "trailing word": "Thanks for reaching out. Stop", + "stop the press": "Stop the press, this is great", + "empty": "", + "greeting only": "Hi Jane,", + "bus stop": "bus stop", + "long text below": "Stop\n\nWe looked at this last quarter and decided to build it in house instead", + } + for name, body := range notOptOut { + if IsOptOut("Re: Stop", body) { + t.Errorf("%s: IsOptOut(%q) = true, want false", name, body) + } + } +} diff --git a/internal/app/segment/service.go b/internal/app/segment/service.go index a64e28911..e30fb2aa7 100644 --- a/internal/app/segment/service.go +++ b/internal/app/segment/service.go @@ -344,7 +344,7 @@ func (s *service) AddToCampaign(ctx context.Context, orgID uuid.UUID, actor stri if err != nil { return nil, errx.New(errx.BadRequest, "invalid campaign id") } - res, xerr := s.repo.AddToCampaign(ctx, orgID, actor, id, campaignID) + res, xerr := s.repo.AddToCampaign(ctx, orgID, actor, id, campaignID, in.SkipActiveInOtherCampaigns) if xerr != nil { return nil, xerr } diff --git a/internal/models/advanced_outreach.go b/internal/models/advanced_outreach.go index a7e71a3b0..b509afb67 100644 --- a/internal/models/advanced_outreach.go +++ b/internal/models/advanced_outreach.go @@ -59,8 +59,16 @@ type ReplyIntentSettings struct { // OutOfOfficeHoldDays is the hold applied when the auto-reply carries no // return date we can read. Clamped to OOOHoldDaysMin..OOOHoldDaysMax. OutOfOfficeHoldDays int `json:"out_of_office_hold_days"` + // StopAllCampaignsOnReply holds a contact in every other campaign they are + // a lead of when they reply to one, for ReplyHoldOtherCampaignsDays. + // Off by default: a reply stops only the campaign it answered. + StopAllCampaignsOnReply bool `json:"stop_all_campaigns_on_reply"` } +// ReplyHoldOtherCampaignsDays is how long a reply holds the contact's other +// campaigns. Finite like every automatic hold; a member resumes it sooner. +const ReplyHoldOtherCampaignsDays = 365 + // InboxTaggingSettings are the actions a workspace lets a classified reply // take. The three reversible ones default on; the suppression defaults off, // because it is the one the system cannot undo. @@ -1066,6 +1074,7 @@ func DefaultAdvancedOutreachSettings() AdvancedOutreachSettings { AutoSuppressOnUnsubWord: true, HoldOnOutOfOffice: true, OutOfOfficeHoldDays: OOOHoldDaysDefault, + StopAllCampaignsOnReply: false, }, InboxTagging: InboxTaggingSettings{ // The reversible actions are on from the start, so a classified diff --git a/internal/models/contact.go b/internal/models/contact.go index 546f97e9a..6a3b0447f 100644 --- a/internal/models/contact.go +++ b/internal/models/contact.go @@ -933,6 +933,10 @@ type BulkEditContactsData struct { Fields []BulkEditContactsField `json:"fields"` Subscribe *bool `json:"subscribe"` + // SkipActiveInOtherCampaigns leaves out of add_campaigns a contact whose + // sequence is still running in another campaign. + SkipActiveInOtherCampaigns bool `json:"skip_active_in_other_campaigns,omitempty"` + // SkipRows suppresses the hydrated rows in the response. Set by the // handler for a filter-shaped selection, which can name far more contacts // than are worth serializing back. Never part of the request body. diff --git a/internal/models/contact_import.go b/internal/models/contact_import.go index 8a97587f6..b1f948e16 100644 --- a/internal/models/contact_import.go +++ b/internal/models/contact_import.go @@ -138,6 +138,10 @@ type ContactImportCommit struct { HasHeader bool `json:"has_header"` CategoryIDs []string `json:"category_ids,omitempty"` CampaignIDs []string `json:"campaign_ids,omitempty"` + // SkipActiveInOtherCampaigns keeps an existing contact out of + // CampaignIDs while their sequence is still running in another campaign. + // The row itself is imported as usual. + SkipActiveInOtherCampaigns bool `json:"skip_active_in_other_campaigns,omitempty"` // SegmentIDs pins every imported row into these segments as a manual // include override, the same write the "Add to segment" bulk action does. SegmentIDs []string `json:"segment_ids,omitempty"` diff --git a/internal/models/segment.go b/internal/models/segment.go index 8d85de1d6..af8d1957c 100644 --- a/internal/models/segment.go +++ b/internal/models/segment.go @@ -248,6 +248,9 @@ type SegmentMembersWrite struct { // SegmentAddToCampaign enrols the segment's current members as leads. type SegmentAddToCampaign struct { CampaignID string `json:"campaign_id"` + // SkipActiveInOtherCampaigns leaves out a member whose sequence is still + // running in another campaign. + SkipActiveInOtherCampaigns bool `json:"skip_active_in_other_campaigns,omitempty"` } // SegmentAddToCampaignResult reports how many leads were actually new. diff --git a/internal/repository/active_elsewhere_live_test.go b/internal/repository/active_elsewhere_live_test.go new file mode 100644 index 000000000..5d8b0cf3e --- /dev/null +++ b/internal/repository/active_elsewhere_live_test.go @@ -0,0 +1,82 @@ +package repository + +import ( + "context" + "testing" + "time" + + "github.com/warmbly/warmbly/internal/models" +) + +// A contact whose sequence is still running in a launched campaign is left out +// of another campaign when the caller asks; finished elsewhere, it joins. +func TestLiveBulkAddSkipsContactsActiveInAnotherCampaign(t *testing.T) { + handle, pool := liveContactDB(t) + f := newSharedOrgFixture(t, pool) + repo := NewContactRepostory(handle) + ctx := context.Background() + + if _, err := pool.Exec(ctx, `UPDATE campaigns SET status = 'active' WHERE id = $1`, f.other); err != nil { + t.Fatal(err) + } + if _, err := pool.Exec(ctx, `INSERT INTO campaign_leads (contact_id, campaign_id) VALUES ($1, $2)`, f.contact, f.other); err != nil { + t.Fatal(err) + } + isLead := func() bool { + var n int + if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM campaign_leads WHERE campaign_id = $1 AND contact_id = $2`, f.campaign, f.contact).Scan(&n); err != nil { + t.Fatal(err) + } + return n == 1 + } + add := func(skip bool) { + t.Helper() + if _, xerr := repo.BulkUpdate(ctx, f.owner.String(), f.org, &models.BulkEditContactsData{ + ContactSelection: models.ContactSelection{Contacts: []string{f.contact.String()}}, + AddCampaigns: []string{f.campaign.String()}, + SkipActiveInOtherCampaigns: skip, + }); xerr != nil { + t.Fatalf("bulk add: %v", xerr) + } + } + + add(true) + if isLead() { + t.Fatal("a contact queued in an active campaign was enrolled with the skip on") + } + + // A draft campaign is not running yet, so it does not hold the contact back. + if _, err := pool.Exec(ctx, `UPDATE campaigns SET status = 'draft' WHERE id = $1`, f.other); err != nil { + t.Fatal(err) + } + add(true) + if !isLead() { + t.Fatal("a contact only in a draft campaign was skipped") + } +} + +// A reply holds the contact everywhere except the campaign it answered. +func TestLiveHoldLeadElsewhereLeavesTheAnsweredCampaign(t *testing.T) { + _, pool := liveContactDB(t) + f := newSharedOrgFixture(t, pool) + ctx := context.Background() + if _, err := pool.Exec(ctx, `INSERT INTO campaign_leads (contact_id, campaign_id) VALUES ($1, $2), ($1, $3)`, f.contact, f.campaign, f.other); err != nil { + t.Fatal(err) + } + until := time.Now().Add(365 * 24 * time.Hour) + held, err := NewCampaignProgressRepository(pool).HoldLeadElsewhere(ctx, f.contact, f.campaign, &until, + "replied to another campaign", models.LeadHoldSourceInboxTagging) + if err != nil { + t.Fatal(err) + } + if len(held) != 1 || held[0] != f.other { + t.Fatalf("held %v, want only %s", held, f.other) + } + var answeredHeld bool + if err := pool.QueryRow(ctx, `SELECT paused_at IS NOT NULL FROM campaign_leads WHERE campaign_id = $1 AND contact_id = $2`, f.campaign, f.contact).Scan(&answeredHeld); err != nil { + t.Fatal(err) + } + if answeredHeld { + t.Fatal("the answered campaign was held too") + } +} diff --git a/internal/repository/pg_campaign_progress.go b/internal/repository/pg_campaign_progress.go index 6269c9b12..855d6e882 100644 --- a/internal/repository/pg_campaign_progress.go +++ b/internal/repository/pg_campaign_progress.go @@ -329,6 +329,8 @@ type CampaignProgressRepository interface { // in two live campaigns used to have one of them held while the other kept // writing to the empty desk (issue #518). HoldLeadEverywhere(ctx context.Context, contactID uuid.UUID, until *time.Time, reason, source string) ([]uuid.UUID, error) + // HoldLeadElsewhere is HoldLeadEverywhere except in exceptCampaignID. + HoldLeadElsewhere(ctx context.Context, contactID, exceptCampaignID uuid.UUID, until *time.Time, reason, source string) ([]uuid.UUID, error) // ResumeLead lifts the hold now and reports whether there was one to lift. // The held time is dropped rather than carried, because "resume now" means // now: the step's remaining wait is only preserved when a hold ends on its @@ -2536,6 +2538,12 @@ func (r *campaignProgressRepository) HoldLead(ctx context.Context, campaignID, c // desk. Every automatic hold carries an end, so one written into a campaign // that never launches expires on its own. func (r *campaignProgressRepository) HoldLeadEverywhere(ctx context.Context, contactID uuid.UUID, until *time.Time, reason, source string) ([]uuid.UUID, error) { + return r.HoldLeadElsewhere(ctx, contactID, uuid.Nil, until, reason, source) +} + +// HoldLeadElsewhere is HoldLeadEverywhere leaving out one campaign, the one a +// reply answered, whose own flow decides what that reply does. +func (r *campaignProgressRepository) HoldLeadElsewhere(ctx context.Context, contactID, exceptCampaignID uuid.UUID, until *time.Time, reason, source string) ([]uuid.UUID, error) { guard := "" if automaticHoldSource(source) { guard = automaticHoldGuard("cl", "$2") @@ -2551,9 +2559,10 @@ func (r *campaignProgressRepository) HoldLeadEverywhere(ctx context.Context, con FROM campaigns c WHERE cl.contact_id = $1 AND c.id = cl.campaign_id + AND cl.campaign_id <> $5 AND c.status <> 'completed'`+guard+` RETURNING cl.campaign_id`, - contactID, until, reason, source) + contactID, until, reason, source, exceptCampaignID) if err != nil { return nil, err } diff --git a/internal/repository/pg_contact.go b/internal/repository/pg_contact.go index b4cc0fa20..55b923553 100644 --- a/internal/repository/pg_contact.go +++ b/internal/repository/pg_contact.go @@ -2221,6 +2221,18 @@ func leadStatusClause(status, cp string) string { } } +// activeElsewhereClause matches a contact `c` whose sequence is still in +// flight (queued, processing or held) in a launched, unfinished campaign other +// than campaignCol, by the same derivation the Leads view shows. +func activeElsewhereClause(campaignCol string) string { + const cp = "ol.campaign_id" + return `EXISTS (SELECT 1 FROM campaign_leads ol JOIN campaigns oc ON oc.id = ol.campaign_id + WHERE ol.contact_id = c.id AND oc.organization_id = c.organization_id + AND ol.campaign_id <> ` + campaignCol + ` AND oc.status NOT IN ('draft', 'completed') + AND (` + leadStatusClause(models.LeadStatusPending, cp) + ` OR ` + leadStatusClause(models.LeadStatusActive, cp) + + ` OR ` + leadStatusClause(models.LeadStatusPaused, cp) + `))` +} + // leadHeldClause is the "this lead's flow is parked right now" predicate for a // contact-scoped query, built on the one definition of live in liveHold. The // Leads-view status filter, the scope-chip counts and the row-level status all @@ -2925,6 +2937,11 @@ func (r *contactRepository) BulkUpdate(ctx context.Context, userID string, orgID } if len(data.AddCampaigns) > 0 { + // A skipped pair is left exactly as it was, its removal record included. + skip := "" + if data.SkipActiveInOtherCampaigns { + skip = " AND NOT " + activeElsewhereClause("cam.id") + } // A manual add clears the removal record: the user changed their mind, // so linked segments may manage this pair again. if xerr := link(`WITH cleared AS ( @@ -2935,7 +2952,7 @@ func (r *contactRepository) BulkUpdate(ctx context.Context, userID string, orgID AND c.organization_id = $1 AND cam.organization_id = $1 AND r.contact_id = ANY($2) - AND r.campaign_id = ANY($3::uuid[]) + AND r.campaign_id = ANY($3::uuid[])`+skip+` ) INSERT INTO campaign_leads (contact_id, campaign_id) SELECT c.id, cam.id @@ -2944,7 +2961,7 @@ func (r *contactRepository) BulkUpdate(ctx context.Context, userID string, orgID WHERE c.organization_id = $1 AND c.id = ANY($2) AND cam.id = ANY($3::uuid[]) - AND cam.organization_id = $1 + AND cam.organization_id = $1`+skip+` ON CONFLICT DO NOTHING RETURNING contact_id, campaign_id`, models.ActivityCampaignAdded, logCampaignLinks, orgID, data.Contacts, data.AddCampaigns); xerr != nil { diff --git a/internal/repository/pg_segment.go b/internal/repository/pg_segment.go index b062eeaea..090d1d2a5 100644 --- a/internal/repository/pg_segment.go +++ b/internal/repository/pg_segment.go @@ -32,7 +32,7 @@ type SegmentRepository interface { // MemberModes reports the manual override of each listed contact. MemberModes(ctx context.Context, segmentID uuid.UUID, contactIDs []uuid.UUID) (map[uuid.UUID]models.SegmentMemberMode, *errx.Error) // AddToCampaign enrols every current member of the segment as a lead. - AddToCampaign(ctx context.Context, orgID uuid.UUID, actor string, segmentID, campaignID uuid.UUID) (*models.SegmentAddToCampaignResult, *errx.Error) + AddToCampaign(ctx context.Context, orgID uuid.UUID, actor string, segmentID, campaignID uuid.UUID, skipActiveElsewhere bool) (*models.SegmentAddToCampaignResult, *errx.Error) // ListForCampaign lists the segments linked to a campaign. ListForCampaign(ctx context.Context, orgID, campaignID uuid.UUID) ([]models.CampaignSegmentLink, *errx.Error) // SetForCampaign replaces the campaign's linked segments, withdrawing the @@ -369,7 +369,7 @@ func (r *segmentRepository) MemberModes(ctx context.Context, segmentID uuid.UUID return out, nil } -func (r *segmentRepository) AddToCampaign(ctx context.Context, orgID uuid.UUID, actor string, segmentID, campaignID uuid.UUID) (*models.SegmentAddToCampaignResult, *errx.Error) { +func (r *segmentRepository) AddToCampaign(ctx context.Context, orgID uuid.UUID, actor string, segmentID, campaignID uuid.UUID, skipActiveElsewhere bool) (*models.SegmentAddToCampaignResult, *errx.Error) { tx, err := r.DB.Begin(ctx) if err != nil { db.CaptureError(err, "", nil, "begin") @@ -403,7 +403,7 @@ func (r *segmentRepository) AddToCampaign(ctx context.Context, orgID uuid.UUID, return nil, errx.InternalError() } - links, err := insertSegmentLeads(ctx, tx, orgID, actorID(actor), clause, args, campaignID, leadSourceManual) + links, err := insertSegmentLeads(ctx, tx, orgID, actorID(actor), clause, args, campaignID, leadSourceManual, skipActiveElsewhere) if err != nil { db.CaptureError(err, "segment enrol", nil, "query") return nil, errx.InternalError() @@ -443,9 +443,13 @@ const claimLeadsManualSQL = `UPDATE campaign_leads SET source = 'manual' // insertSegmentLeads enrols every contact matching the precompiled segment // clause as a lead, logging a campaign_added activity for each row that was // actually new. The campaign is bound after the clause's own parameters. -func insertSegmentLeads(ctx context.Context, tx pgx.Tx, orgID uuid.UUID, actor *uuid.UUID, clause string, args []any, campaignID uuid.UUID, src leadSource) ([]contactLink, error) { +// skipActiveElsewhere leaves a member running in another campaign untouched. +func insertSegmentLeads(ctx context.Context, tx pgx.Tx, orgID uuid.UUID, actor *uuid.UUID, clause string, args []any, campaignID uuid.UUID, src leadSource, skipActiveElsewhere bool) ([]contactLink, error) { args = append(args, campaignID) cp := len(args) + if skipActiveElsewhere { + clause = "(" + clause + ") AND NOT " + activeElsewhereClause(fmt.Sprintf("$%d", cp)) + } // members is the clause as a contact-id subquery, reused by the three // statements below so they cannot drift apart. members := fmt.Sprintf(`SELECT c.id FROM contacts c WHERE c.organization_id = $1 AND (%s)`, clause) @@ -915,7 +919,7 @@ func syncCampaignSegmentsTx(ctx context.Context, tx pgx.Tx, orgID, campaignID uu if clause == "FALSE" { continue } - links, lerr := insertSegmentLeads(ctx, tx, orgID, nil, clause, args, campaignID, leadSourceSegment) + links, lerr := insertSegmentLeads(ctx, tx, orgID, nil, clause, args, campaignID, leadSourceSegment, false) if lerr != nil { db.CaptureError(lerr, "segment enrol", nil, "query") return 0, errx.InternalError() diff --git a/internal/repository/segment_audience_live_test.go b/internal/repository/segment_audience_live_test.go index 083ccc16f..216ccb262 100644 --- a/internal/repository/segment_audience_live_test.go +++ b/internal/repository/segment_audience_live_test.go @@ -315,7 +315,7 @@ func TestLiveCampaignAudienceAReimportClaimsASegmentLead(t *testing.T) { // The one-shot "add to campaign" adds nobody here and changes nobody's // provenance: re-stamping a whole linked audience because somebody pressed // "Add back" is what would put the old list back for good. - out, xerr := segments.AddToCampaign(ctx, f.org, f.owner.String(), segA, f.campaign) + out, xerr := segments.AddToCampaign(ctx, f.org, f.owner.String(), segA, f.campaign, false) if xerr != nil || out.Added != 0 { t.Fatalf("one-shot enrol = %+v, %v", out, xerr) } diff --git a/internal/repository/segment_live_test.go b/internal/repository/segment_live_test.go index 7895d25fe..4dabeaa10 100644 --- a/internal/repository/segment_live_test.go +++ b/internal/repository/segment_live_test.go @@ -217,14 +217,15 @@ func TestLiveSegmentOverridesNestingAndCampaign(t *testing.T) { } // Enrolling the segment adds only the members not already leads. - out, xerr := repo.AddToCampaign(ctx, f.org, f.mate.String(), acme.ID, f.other) + out, xerr := repo.AddToCampaign(ctx, f.org, f.mate.String(), acme.ID, f.other, false) if xerr != nil { t.Fatalf("add to campaign: %v", xerr) } if out.Added != 2 || out.Members != 2 { t.Fatalf("add to campaign = %+v", out) } - out, xerr = repo.AddToCampaign(ctx, f.org, f.mate.String(), acme.ID, f.other) + // The skip filter runs on the same statement; nobody new is added either way. + out, xerr = repo.AddToCampaign(ctx, f.org, f.mate.String(), acme.ID, f.other, true) if xerr != nil || out.Added != 0 { t.Fatalf("second add = %+v, %v", out, xerr) } @@ -326,7 +327,7 @@ func TestLiveSegmentCampaignLinks(t *testing.T) { if _, xerr := contacts.BulkUpdate(ctx, f.owner.String(), f.org, removeBob); xerr != nil { t.Fatalf("remove again: %v", xerr) } - out, xerr := repo.AddToCampaign(ctx, f.org, f.owner.String(), acme.ID, f.other) + out, xerr := repo.AddToCampaign(ctx, f.org, f.owner.String(), acme.ID, f.other, false) if xerr != nil || out.Added != 1 { t.Fatalf("one-shot after removal = %+v, %v", out, xerr) } diff --git a/web/src/app/app/settings/sending/page.tsx b/web/src/app/app/settings/sending/page.tsx index 7c4c1097c..4a0d46ecf 100644 --- a/web/src/app/app/settings/sending/page.tsx +++ b/web/src/app/app/settings/sending/page.tsx @@ -270,7 +270,7 @@ function SendingSettings() { +
+ {isLoading || !draft ? ( +
+ ) : ( + + patchReplyIntent({ stop_all_campaigns_on_reply: on })} + /> + + )} +
+
(rowSelection.emptySelection); + const [skipActive, setSkipActive] = React.useState(false); // Debounce the query so a fast typist does not fire a search per keystroke. const debounced = useBrowseDebouncedValue(query.trim(), browseName, 200); @@ -96,6 +98,7 @@ export default function AddFromContactsDialog({ open, onClose, campaign: campaig React.useEffect(() => { if (!open) { setRowSel(rowSelection.emptySelection); + setSkipActive(false); } }, [open]); @@ -135,9 +138,14 @@ export default function AddFromContactsDialog({ open, onClose, campaign: campaig ...selection, add_campaigns: [target.campaign.id], remove_campaigns: [], + skip_active_in_other_campaigns: skipActive || undefined, fields: [], }); - toast.success(`Added ${count.toLocaleString()} lead${count === 1 ? "" : "s"} to ${target.campaign.name}`); + toast.success( + skipActive + ? `Added to ${target.campaign.name}, leaving out anyone running in another campaign` + : `Added ${count.toLocaleString()} lead${count === 1 ? "" : "s"} to ${target.campaign.name}`, + ); } else { const added = await members.mutateAsync({ id: target.segment.id, selection, mode: "include" }); toast.success(`Added ${added.toLocaleString()} contact${added === 1 ? "" : "s"} to ${target.segment.name}`); @@ -377,11 +385,19 @@ export default function AddFromContactsDialog({ open, onClose, campaign: campaig
- - {target.kind === "campaign" - ? "Contacts already in this campaign are skipped." - : "Added contacts stay in the segment whatever its conditions say."} - + {target.kind === "campaign" ? ( + + ) : ( + + Added contacts stay in the segment whatever its conditions say. + + )} - )} - {/* Private plans Warmbly offered this workspace; not in the grid. */} {!sub.isPending && visibleOffers.map((o) => ( diff --git a/web/src/app/app/settings/billing/page.tsx b/web/src/app/app/settings/billing/page.tsx index 3071990b7..acf19bd85 100644 --- a/web/src/app/app/settings/billing/page.tsx +++ b/web/src/app/app/settings/billing/page.tsx @@ -45,7 +45,6 @@ import { TextInput } from "@/components/ui/field"; import BillingIntervalToggle from "@/components/app/billing/BillingIntervalToggle"; import PlanCard from "@/components/app/billing/PlanCard"; import EnterpriseInquiryDialog from "@/components/app/billing/EnterpriseInquiryDialog"; -import WarmupPlanDialog from "@/components/app/billing/WarmupPlanDialog"; import { Row, Section, SectionShell, TableSurface } from "../_components/SectionShell"; import { PAID_PLANS, getPlan, planOrder, type PlanID } from "@/lib/plans"; import { describeDiscount, fmtMoney, fromMinorUnits, type BillingInterval } from "@/lib/pricing"; @@ -83,6 +82,15 @@ export default function BillingSettingsPage() { // in-app upgrade dialog. const flow = useUpgradeFlow(); const upgradeDialog = useUpgradeDialog(); + // Overview's "Change plan" opens the same full-screen chooser the locked + // surfaces use, so there is one upgrade experience everywhere. + const openPlanChooser = React.useCallback(() => { + upgradeDialog.open({ + feature: "Your plan", + minPlan: "starter", + blurb: "Compare every plan, switch billing interval, and change your subscription in one step.", + }); + }, [upgradeDialog]); const openPortal = flow.openPortal; const redemptions = useAppliedDiscounts(); const { tab: tabSlug } = useParams({ from: "/app/settings/billing/{-$tab}" }); @@ -93,13 +101,10 @@ export default function BillingSettingsPage() { useBrowseState("settings.billing.interval", "annual", billingIntervalSchema); const [salesOpen, setSalesOpen] = React.useState(false); - // ?pool=1 is where a linked instance's "Premium" button lands (and what - // the overview's warmup-only row opens), and ?pool=done is where Stripe - // returns. Both are consumed once and stripped, so a refresh or a back - // navigation does not replay them. + // ?pool=1 is where older linked instances' upgrade button lands, now the plan chooser since the Warmup plan is retired; + // ?pool=done is where an earlier Warmup checkout returns. Both are consumed once and stripped. const [searchParams, setSearchParams] = useSearchParams(); const poolParam = searchParams.get("pool"); - const [poolOpen, setPoolOpen] = React.useState(false); const offerParam = searchParams.get("offer"); React.useEffect(() => { if (offerParam !== "done") return; @@ -110,14 +115,14 @@ export default function BillingSettingsPage() { }, [offerParam, searchParams, setSearchParams]); React.useEffect(() => { if (!poolParam) return; - if (poolParam === "1") setPoolOpen(true); + if (poolParam === "1") openPlanChooser(); if (poolParam === "done") { toast.success("Payment received. The Warmup plan applies as soon as Stripe confirms."); } const next = new URLSearchParams(searchParams); next.delete("pool"); setSearchParams(next, { replace: true }); - }, [poolParam, searchParams, setSearchParams]); + }, [poolParam, searchParams, setSearchParams, openPlanChooser]); const resolvedTab = tabForSlug(tabSlug); const tab: BillingTab = resolvedTab ?? "overview"; @@ -189,15 +194,6 @@ export default function BillingSettingsPage() { (id) => getPlan(id).featured && planOrder(id) > planOrder(currentPlan.id), ) ?? PAID_PLANS.find((id) => planOrder(id) > planOrder(currentPlan.id)); - // Overview's "Change plan" opens the same full-screen chooser the locked - // surfaces use, so there is one upgrade experience everywhere. - function openPlanChooser() { - upgradeDialog.open({ - feature: "Your plan", - minPlan: "starter", - blurb: "Compare every plan, switch billing interval, and change your subscription in one step.", - }); - } // Upgrade/switch to a plan. A valid promo code rides along to Stripe; the // flow picks Checkout, an in-place change, or the portal. @@ -263,7 +259,7 @@ export default function BillingSettingsPage() { className="divide-y divide-slate-200/70" > {tab === "overview" && ( - setPoolOpen(true)} /> + )} {tab === "plans" && ( @@ -478,7 +474,6 @@ export default function BillingSettingsPage() { setSalesOpen(false)} /> - setPoolOpen(false)} /> ); } diff --git a/web/src/app/app/settings/layout.tsx b/web/src/app/app/settings/layout.tsx index 91ae89e43..51b1d9009 100644 --- a/web/src/app/app/settings/layout.tsx +++ b/web/src/app/app/settings/layout.tsx @@ -38,6 +38,7 @@ import { useAccessRestricted, usePermission, type PermissionKey } from "@/hooks/ import { Page, PageTopbar } from "@/components/layout/Page"; import useFeatureAccess from "@/hooks/useFeatureAccess"; import useAuthConfig from "@/lib/api/hooks/auth/useAuthConfig"; +import { useCloudLinkStatus, usePoolLinkInstances } from "@/lib/api/hooks/app/cloudlink/useCloudLink"; interface SectionDef { path: string; @@ -114,9 +115,16 @@ export default function SettingsLayout() { function SettingsLayoutInner() { const pathname = useLocation({ select: (l) => l.pathname }); const access = useFeatureAccess(); - const hosted = useAuthConfig().data?.self_hosted === false; + const selfHosted = useAuthConfig().data?.self_hosted; + const hosted = selfHosted === false; const canManageApiKeys = usePermission("MANAGE_API_KEYS"); const canManageSettings = usePermission("MANAGE_SETTINGS"); + // Warmbly Cloud only shows where a link exists: an instance linked to it, or a hosted workspace with linked instances. + const cloudStatus = useCloudLinkStatus(selfHosted === true && canManageSettings); + const linkedInstances = usePoolLinkInstances(hosted && canManageSettings); + const hasCloudLink = hosted + ? (linkedInstances.data?.data ?? []).some((i) => !i.revoked_at) + : !!(cloudStatus.data?.connected || cloudStatus.data?.legacy_connected); const canViewAnalytics = usePermission("VIEW_ANALYTICS"); const restricted = useAccessRestricted(); const navRef = React.useRef(null); @@ -181,6 +189,7 @@ function SettingsLayoutInner() { (!restricted || s.scoped) && (!s.ownerOnly || access.isOwner) && (!s.billingOnly || access.billing) && + (s.path !== "warmbly-cloud" || hasCloudLink) && (s.permission !== "MANAGE_API_KEYS" || canManageApiKeys) && (s.permission !== "MANAGE_SETTINGS" || canManageSettings) && (s.permission !== "VIEW_ANALYTICS" || canViewAnalytics), diff --git a/web/src/app/app/settings/warmbly-cloud/ConnectFlow.tsx b/web/src/app/app/settings/warmbly-cloud/ConnectFlow.tsx deleted file mode 100644 index eceed9549..000000000 --- a/web/src/app/app/settings/warmbly-cloud/ConnectFlow.tsx +++ /dev/null @@ -1,321 +0,0 @@ -// Link the selected local workspace to its own Warmbly Cloud workspace, -// pick the mailboxes the cloud should warm, done. Steps slide directionally -// like NewCampaignDialog; a step cannot be skipped ahead of. - -import React from "react"; -import { cloudMailboxPickerOpened } from "@/lib/cloudMailboxConnect"; -import { AnimatePresence, motion } from "framer-motion"; -import toast from "react-hot-toast/headless"; -import { ArrowRightIcon, CheckIcon, CloudIcon, FlameIcon, InboxIcon, Loader2Icon, SparklesIcon } from "lucide-react"; -import type { AppError } from "@/lib/api/client/normalizeError"; -import buildError from "@/lib/helper/buildError"; -import type { CloudLinkMailboxRow, CloudLinkStatus } from "@/lib/api/models/app/cloudlink/CloudLink"; -import { useCloudLinkMailboxes, useEnrollCloudLinkMailbox, useUnenrollCloudLinkMailbox } from "@/lib/api/hooks/app/cloudlink/useCloudLink"; -import CloudLinkCard from "@/components/app/cloud/CloudLinkCard"; -import CloudMailboxPicker from "@/components/app/emails/CloudMailboxPicker"; -import { useMailboxSourceBusy } from "@/lib/api/hooks/app/emails/mailboxSourceBusy"; -import { Toggle } from "../_components/SectionShell"; -import { providerLabel, providerSupported } from "./providers"; - -const STEPS = [ - { label: "Link", icon: CloudIcon }, - { label: "Mailboxes", icon: InboxIcon }, - { label: "Done", icon: SparklesIcon }, -] as const; -type Step = 0 | 1 | 2; - -const paneVariants = { - enter: (dir: 1 | -1) => ({ x: dir * 28, opacity: 0 }), - center: { x: 0, opacity: 1 }, - exit: (dir: 1 | -1) => ({ x: dir * -28, opacity: 0 }), -}; - -export default function ConnectFlow({ - status, - onFinished, -}: { - status: CloudLinkStatus; - onFinished: () => void; -}) { - const [step, setStep] = React.useState(status.connected ? 1 : 0); - const [direction, setDirection] = React.useState<1 | -1>(1); - const [nudged, setNudged] = React.useState(false); - const [linked, setLinked] = React.useState(status.connected); - const [enrolledCount, setEnrolledCount] = React.useState(0); - // The status prop was read before the handshake, so the workspace name has - // to come from the poll that completed it. - const [orgName, setOrgName] = React.useState(status.link?.organization_name ?? ""); - - const sourceBusy = useMailboxSourceBusy(); - const issue = sourceBusy ? "Wait for the current mailbox connections to finish" : step === 0 && !linked ? "Approve the code on Warmbly Cloud first" : null; - React.useEffect(() => { - if (!issue) setNudged(false); - }, [issue]); - - const canReach = React.useCallback((target: Step) => (target === 0 ? true : linked), [linked]); - const goTo = React.useCallback( - (target: Step) => { - if (sourceBusy) { setNudged(true); return; } - if (target === step) return; - if (target > step && !canReach(target)) { - setNudged(true); - return; - } - setDirection(target > step ? 1 : -1); - setNudged(false); - setStep(target); - }, - [step, canReach, sourceBusy], - ); - - return ( -
-
- -
- - - {step === 0 && ( - { - setOrgName(name); - setLinked(true); - setTimeout(() => goTo(1), 650); - }} - /> - )} - {step === 1 && } - {step === 2 && } - - -
-
goTo((step - 1) as Step)} - onNext={() => { - if (issue) { - setNudged(true); - return; - } - if (step < 2) goTo((step + 1) as Step); - else onFinished(); - }} - /> -
-
- ); -} - -function Stepper({ step, canReach, goTo }: { step: Step; canReach: (s: Step) => boolean; goTo: (s: Step) => void }) { - return ( -
- {STEPS.map((s, idx) => { - const i = idx as Step; - const done = i < step; - const active = i === step; - const reachable = i <= step || canReach(i); - return ( - - - {idx < STEPS.length - 1 && ( - - - - )} - - ); - })} -
- ); -} - -function Footer({ step, issue, nudged, onBack, onNext }: { step: Step; issue: string | null; nudged: boolean; onBack: () => void; onNext: () => void }) { - return ( -
-
- - {nudged && issue && ( - - {issue} - - )} - -
- {step > 0 && ( - - )} - -
- ); -} - -// Step 1: the shared link card. -function LinkStep({ status, linked, orgName, onLinked }: { status: CloudLinkStatus; linked: boolean; orgName: string; onLinked: (orgName: string) => void }) { - return ; -} - -// Step 2: pick mailboxes. -function MailboxesStep({ onCountChange }: { onCountChange: (n: number) => void }) { - const rows = useCloudLinkMailboxes(); - const enroll = useEnrollCloudLinkMailbox(); - const unenroll = useUnenrollCloudLinkMailbox(); - const [busy, setBusy] = React.useState(null); - - React.useEffect(() => { - onCountChange((rows.data ?? []).filter((r) => r.enrolled).length); - }, [rows.data, onCountChange]); - - const flip = async (row: CloudLinkMailboxRow) => { - setBusy(row.id); - try { - if (row.enrolled) { - await unenroll.mutateAsync(row.id); - toast.success(`${row.email} removed from the pool`); - } else { - await enroll.mutateAsync(row.id); - toast.success(`${row.email} is now warming in the pool`); - } - } catch (e) { - if (!cloudMailboxPickerOpened(e)) toast.error(buildError(e as AppError)); - } finally { - setBusy(null); - } - }; - - return ( -
-
-

Choose the mailboxes to warm

-

- Each enrolled mailbox is warmed by Warmbly Cloud from now on. Its local warmup stops; campaigns keep sending from here as usual. -

-
- - {rows.isLoading ? ( -
- -
- ) : (rows.data ?? []).length === 0 ? ( -

No active mailboxes yet. Connect one under Mailboxes, then come back here.

- ) : ( -
    - {(rows.data ?? []).map((row, i) => { - const supported = providerSupported(row.provider); - return ( - -
    -

    {row.email}

    -

    - {providerLabel(row.provider)} - {!supported && " ยท connect with SMTP/IMAP to enroll"} -

    -
    - {busy === row.id ? ( - - ) : ( - void flip(row)} /> - )} -
    - ); - })} -
- )} -

- Enrolling sends the mailbox's SMTP/IMAP credential to Warmbly Cloud, sealed in transit and at rest, and used only to send and read warmup mail. - Nothing else in the mailbox is stored. -

-
- ); -} - -function DoneStep({ orgName, enrolledCount }: { orgName: string; enrolledCount: number }) { - return ( -
- - - -
-

- {enrolledCount === 0 ? "You are all set" : `${enrolledCount} mailbox${enrolledCount === 1 ? "" : "es"} warming in the pool`} -

-

- {orgName ? `Linked to ${orgName}. ` : ""} - Warmup starts on the first slot of each mailbox's window and ramps daily. Health and volume show up on this page as they arrive. -

-
-
- ); -} diff --git a/web/src/app/app/settings/warmbly-cloud/LinkedInstances.tsx b/web/src/app/app/settings/warmbly-cloud/LinkedInstances.tsx index 6371e6a22..b08686cb1 100644 --- a/web/src/app/app/settings/warmbly-cloud/LinkedInstances.tsx +++ b/web/src/app/app/settings/warmbly-cloud/LinkedInstances.tsx @@ -2,6 +2,7 @@ // workspace and the pool allowance they share. import React from "react"; +import { Navigate } from "@tanstack/react-router"; import toast from "react-hot-toast/headless"; import { Loader2Icon, ServerIcon } from "lucide-react"; import type { AppError } from "@/lib/api/client/normalizeError"; @@ -24,6 +25,8 @@ export default function LinkedInstances() { } const list = q.data?.data ?? []; const plan = q.data?.plan; + // Linking is closed, so a workspace with no live link has nothing to manage here. + if (q.isSuccess && !list.some((i) => !i.revoked_at)) return ; return (
@@ -31,50 +34,46 @@ export default function LinkedInstances() {

{plan.mailbox_limit === null ? `Unlimited mailboxes ยท ${plan.enrolled} warming` - : `${plan.enrolled} of ${plan.mailbox_limit} free mailboxes used, counting the ones connected here and through instances`} + : plan.subscription_required + ? "Linked instances keep the mailboxes they already enrolled. Adding mailboxes through one needs a paid plan." + : `${plan.enrolled} of ${plan.mailbox_limit} free mailboxes used, counting the ones connected here and through instances`}

)} - {list.length === 0 ? ( -

- No self-hosted instance is linked. On your instance, open Settings, Warmbly Cloud and press Connect; approve the code at /connect here. -

- ) : ( - -
    - {list.map((inst) => ( -
  • - - - -
    -

    {inst.name}

    -

    - {inst.mailbox_count} mailbox{inst.mailbox_count === 1 ? "" : "es"} - {inst.version && ` ยท v${inst.version}`} - {inst.last_seen_at && ` ยท seen ${new Date(inst.last_seen_at).toLocaleString()}`} -

    -
    - -
  • - ))} -
-
- )} + +
    + {list.map((inst) => ( +
  • + + + +
    +

    {inst.name}

    +

    + {inst.mailbox_count} mailbox{inst.mailbox_count === 1 ? "" : "es"} + {inst.version && ` ยท v${inst.version}`} + {inst.last_seen_at && ` ยท seen ${new Date(inst.last_seen_at).toLocaleString()}`} +

    +
    + +
  • + ))} +
+
); } diff --git a/web/src/app/app/settings/warmbly-cloud/page.test.tsx b/web/src/app/app/settings/warmbly-cloud/page.test.tsx index f7eed0188..100d9a628 100644 --- a/web/src/app/app/settings/warmbly-cloud/page.test.tsx +++ b/web/src/app/app/settings/warmbly-cloud/page.test.tsx @@ -26,8 +26,8 @@ vi.mock("@/lib/api/hooks/app/cloudlink/useCloudLink", () => ({ useUnenrollCloudLinkMailbox: () => ({ mutateAsync: vi.fn() }), useCloudLinkMailboxLifecycle: () => ({ mutateAsync: vi.fn() }), })); -vi.mock("./ConnectFlow", () => ({ default: () =>
Connection setup
})); vi.mock("./LinkedInstances", () => ({ default: () => null })); +vi.mock("@tanstack/react-router", () => ({ Navigate: ({ to }: { to: string }) =>
Redirected to {to}
})); vi.mock("@/components/app/emails/CloudMailboxPicker", () => ({ default: () =>
Existing Cloud mailboxes
})); describe("existing Cloud connections", () => { @@ -59,7 +59,6 @@ describe("existing Cloud connections", () => { expect(screen.getByText("Existing Cloud mailboxes")).toBeInTheDocument(); expect(screen.queryByText(/legacy/i)).not.toBeInTheDocument(); expect(screen.queryByText("Connect this workspace")).not.toBeInTheDocument(); - expect(screen.queryByText("Connection setup")).not.toBeInTheDocument(); expect(screen.getByRole("switch")).toBeEnabled(); fireEvent.click(screen.getByRole("switch")); await waitFor(() => expect(fixture.enroll).toHaveBeenCalledWith("mailbox")); @@ -84,7 +83,6 @@ describe("existing Cloud connections", () => { fixture.status.link!.organization_id = "local"; render(); expect(screen.queryByText(/legacy/i)).not.toBeInTheDocument(); - expect(screen.queryByText("Connection setup")).not.toBeInTheDocument(); fireEvent.click(screen.getByRole("button", { name: "Disconnect" })); expect(fixture.confirm.mock.calls[0][0]).toContain("this workspace"); await fixture.confirm.mock.calls[0][1](); @@ -95,11 +93,11 @@ describe("existing Cloud connections", () => { expect(fixture.disconnect).toHaveBeenLastCalledWith(true); }); - it("only offers connection setup when disconnected", () => { + it("has no page for an instance that is not linked, since Cloud links no new instances", () => { fixture.status.connected = false; fixture.status.legacy_connected = false; fixture.status.link = null; render(); - expect(screen.getByText("Connection setup")).toBeInTheDocument(); + expect(screen.getByText("Redirected to /app/settings/profile")).toBeInTheDocument(); }); }); diff --git a/web/src/app/app/settings/warmbly-cloud/page.tsx b/web/src/app/app/settings/warmbly-cloud/page.tsx index f2f607b87..1ef943a21 100644 --- a/web/src/app/app/settings/warmbly-cloud/page.tsx +++ b/web/src/app/app/settings/warmbly-cloud/page.tsx @@ -5,7 +5,8 @@ // instances linked to this workspace (GET /pool-link/instances). import React from "react"; -import { AnimatePresence, motion } from "framer-motion"; +import { Navigate } from "@tanstack/react-router"; +import { motion } from "framer-motion"; import toast from "react-hot-toast/headless"; import { CheckIcon, CloudIcon, ExternalLinkIcon, Loader2Icon, RefreshCwIcon, SparklesIcon } from "lucide-react"; import { useInstanceAdmin, usePermission } from "@/hooks/usePermission"; @@ -18,8 +19,8 @@ import buildError from "@/lib/helper/buildError"; import { useCloudLinkStatus, useDisconnectCloudLink } from "@/lib/api/hooks/app/cloudlink/useCloudLink"; import type { PoolLinkPlan } from "@/lib/api/models/app/cloudlink/CloudLink"; import { WARMUP_PLAN_BENEFITS, WARMUP_PLAN_PITCH } from "@/lib/plans"; +import { cloudAddsNeedSubscription } from "@/lib/cloudPlan"; import { Row, Section, SectionShell } from "../_components/SectionShell"; -import ConnectFlow from "./ConnectFlow"; import MailboxTable from "./MailboxTable"; import CloudMailboxPicker from "@/components/app/emails/CloudMailboxPicker"; import LinkedInstances from "./LinkedInstances"; @@ -59,11 +60,6 @@ function SelfHostedCloud() { const status = useCloudLinkStatus(); const disconnect = useDisconnectCloudLink(); const confirm = useConfirm(); - // The step flow stays up after linking until the user finishes it, so a - // fresh link walks through mailbox selection instead of dropping into the - // steady-state table. - const [flow, setFlow] = React.useState(null); - const showFlow = flow ?? (status.data ? !status.data.connected : false); if (status.isLoading || !status.data) { return ( @@ -75,6 +71,8 @@ function SelfHostedCloud() { ); } const st = status.data; + // Warmbly Cloud links no new instances, so an unlinked one has no page here. + if (!st.connected && !st.legacy_connected) return ; const plan = st.info?.plan; const serverWide = st.connected && !st.link?.organization_id; @@ -95,90 +93,75 @@ function SelfHostedCloud() { ) : undefined } > - - {showFlow ? ( - - { - setFlow(false); - void status.refetch(); - }} - /> - - ) : ( - -
- - - - - {st.link?.organization_name || "Warmbly Cloud"} - - } - description={ - st.reachable ? ( - Connected{st.link?.connected_at ? ` since ${new Date(st.link.connected_at).toLocaleDateString()}` : ""} - ) : ( - Cloud unreachable{st.error ? `: ${st.error}` : ""} - ) - } - /> -
- {plan && ( -
- -
- )} -
- - -
-
- - - - {st.legacy_connected && !serverWide && ( - - - - )} -
-
+ +
+ + + + + {st.link?.organization_name || "Warmbly Cloud"} + + } + description={ + st.reachable ? ( + Connected{st.link?.connected_at ? ` since ${new Date(st.link.connected_at).toLocaleDateString()}` : ""} + ) : ( + Cloud unreachable{st.error ? `: ${st.error}` : ""} + ) + } + /> +
+ {plan && ( +
+ +
)} -
+
+ + +
+
+ + + + {st.legacy_connected && !serverWide && ( + + + + )} +
+ ); } @@ -189,7 +172,8 @@ function SelfHostedCloud() { function PlanCard({ plan }: { plan: PoolLinkPlan }) { const premium = plan.tier === "paid"; const limit = plan.mailbox_limit; - const atLimit = !premium && limit !== null && plan.enrolled >= limit; + const closed = cloudAddsNeedSubscription(plan); + const atLimit = !premium && (closed || (limit !== null && plan.enrolled >= limit)); return (
@@ -202,13 +186,15 @@ function PlanCard({ plan }: { plan: PoolLinkPlan }) { - {premium ? "Unlimited" : limit === null ? "Unlimited" : `${plan.enrolled} of ${limit} mailboxes`} + {premium ? "Unlimited" : closed ? `${plan.enrolled} kept, no new` : limit === null ? "Unlimited" : `${plan.enrolled} of ${limit} mailboxes`}

{premium ? "Your mailboxes warm in the premium pool, built for inbox placement, with reputation protection and priority matching." - : atLimit + : closed + ? "Mailboxes already in Warmbly Cloud keep warming. New ones warm on this instance, which is not effective, unless the workspace moves to a paid plan. Self-hosted instances get no support from Warmbly." + : atLimit ? `Every free pool mailbox is in use. ${WARMUP_PLAN_PITCH}` : `Up to ${limit ?? 10} mailboxes in the free pool. ${WARMUP_PLAN_PITCH}`}

@@ -235,7 +221,7 @@ function PlanCard({ plan }: { plan: PoolLinkPlan }) { rel="noreferrer" className="h-7 px-2.5 rounded-md bg-sky-600 hover:bg-sky-700 text-white text-[12px] font-medium inline-flex items-center gap-1.5 transition-colors" > - Premium for ${plan.price_usd}/mo + See plans )} diff --git a/web/src/app/connect/page.tsx b/web/src/app/connect/page.tsx index 2ebab6e68..1841775b4 100644 --- a/web/src/app/connect/page.tsx +++ b/web/src/app/connect/page.tsx @@ -1,113 +1,13 @@ import { DashboardImage } from "@/components/ui/dashboard-image"; -// app.warmbly.com/connect?code=XXXX-XXXX โ€” a signed-in member approves a -// self-hosted instance's request to warm its mailboxes in this workspace. -// Standalone on the auth screen's sky: enter code, review, done. +// app.warmbly.com/connect: where older self-hosted instances still send people to approve a link. Warmbly Cloud links no new instances. -import React from "react"; -import { Link, Navigate } from "@tanstack/react-router"; -import { useSearchParams } from "@/hooks/useSearchParams"; -import { AnimatePresence, motion } from "framer-motion"; -import { REGEXP_ONLY_DIGITS_AND_CHARS } from "input-otp"; -import toast from "react-hot-toast/headless"; -import { - ArrowLeftIcon, - ArrowRightIcon, - BuildingIcon, - CheckIcon, - CloudIcon, - ExternalLinkIcon, - FlameIcon, - Loader2Icon, - LockIcon, - ServerIcon, - XIcon, -} from "lucide-react"; -import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/components/ui/input-otp"; +import { Link } from "@tanstack/react-router"; +import { motion } from "framer-motion"; +import { ArrowRightIcon, CloudIcon } from "lucide-react"; import BrandMark from "@/components/shared/BrandMark"; -import ReauthModal from "@/components/app/modals/ReauthModal"; -import getToken from "@/lib/helper/getToken"; -import type { AppError } from "@/lib/api/client/normalizeError"; -import buildError from "@/lib/helper/buildError"; -import type Organization from "@/lib/api/models/app/organizations/Organization"; -import useOrganizations from "@/lib/api/hooks/app/organizations/useOrganizations"; -import { useApprovePoolLinkCode, useDenyPoolLinkCode, usePoolLinkCode } from "@/lib/api/hooks/app/cloudlink/useCloudLink"; - -const CODE_LENGTH = 8; - -function clean(raw: string): string { - return raw.toUpperCase().replace(/[^A-Z0-9]/g, "").slice(0, CODE_LENGTH); -} - -function dashed(code: string): string { - return code.length > 4 ? `${code.slice(0, 4)}-${code.slice(4)}` : code; -} - -const slide = { - enter: (dir: number) => ({ opacity: 0, x: dir > 0 ? 28 : -28 }), - center: { opacity: 1, x: 0 }, - exit: (dir: number) => ({ opacity: 0, x: dir > 0 ? -28 : 28 }), -}; -const slideTransition = { duration: 0.28, ease: [0.16, 1, 0.3, 1] as const }; export default function ConnectPage() { - if (!getToken()) { - const next = window.location.pathname + window.location.search; - return ; - } - // Outside the /app layout, so approving (which needs a fresh confirmation) brings its own prompt. - return ( - <> - - - - ); -} - -function ConnectInner() { - const [params] = useSearchParams(); - const [code, setCode] = React.useState(() => clean(params.get("code") ?? "")); - const complete = code.length === CODE_LENGTH; - const lookup = usePoolLinkCode(dashed(code)); - const orgs = useOrganizations(); - const approve = useApprovePoolLinkCode(); - const deny = useDenyPoolLinkCode(); - const [orgId, setOrgId] = React.useState(""); - const [outcome, setOutcome] = React.useState<"approved" | "denied" | null>(null); - const [dir, setDir] = React.useState(1); - - React.useEffect(() => { - if (!orgId && orgs.data && orgs.data.length > 0) setOrgId(orgs.data[0].id); - }, [orgs.data, orgId]); - - const info = complete ? lookup.data : undefined; - const step: "code" | "review" | "done" = outcome ? "done" : info ? "review" : "code"; - - const reset = () => { - setDir(-1); - setCode(""); - setOutcome(null); - }; - - const doApprove = async () => { - try { - setDir(1); - await approve.mutateAsync({ code: dashed(code), organizationId: orgId }); - setOutcome("approved"); - } catch (e) { - toast.error(buildError(e as AppError)); - } - }; - const doDeny = async () => { - try { - setDir(1); - await deny.mutateAsync(dashed(code)); - setOutcome("denied"); - } catch (e) { - toast.error(buildError(e as AppError)); - } - }; - return (
); diff --git a/web/src/components/app/billing/WarmupPlanDialog.tsx b/web/src/components/app/billing/WarmupPlanDialog.tsx deleted file mode 100644 index a462c2439..000000000 --- a/web/src/components/app/billing/WarmupPlanDialog.tsx +++ /dev/null @@ -1,296 +0,0 @@ -// The warmup plan checkout: the premium pool, with no mailbox cap, for a -// workspace that only warms. A customer arrives here from the mailboxes page, -// the billing overview, or the Upgrade button on a linked self-hosted -// instance, so they have already chosen: this confirms what they are buying, -// which workspace it applies to, and how often they are billed. -// -// The plan is not in the public plan list, so it has no card in the plans grid -// and its price comes from /pool-link/offer rather than the static catalog. -// The layout is the same anatomy as a PlanCard in the chooser (name, blurb, -// price, bullets) so it reads as one more plan, not a promotion. - -import React from "react"; -import { createPortal } from "react-dom"; -import { AnimatePresence, motion } from "framer-motion"; -import toast from "react-hot-toast/headless"; -import { ArrowRightIcon, CheckIcon, Loader2Icon, MinusIcon, XIcon } from "lucide-react"; -import { useAppStore } from "@/stores"; -import { usePoolLinkInstances, usePoolLinkOffer, useStartPoolLinkCheckout } from "@/lib/api/hooks/app/cloudlink/useCloudLink"; -import type { AppError } from "@/lib/api/client/normalizeError"; -import buildError from "@/lib/helper/buildError"; -import BillingIntervalToggle from "@/components/app/billing/BillingIntervalToggle"; -import { DitherMeter } from "@/components/ui/dither"; -import { PLAN_ACCENT_CLASSES, WARMUP_PLAN_BENEFITS, WARMUP_PLAN_PITCH, getPlan } from "@/lib/plans"; - -type Interval = "month" | "year"; - -// Free against Premium, row by row. Each cell is a rule the pool enforces. -const COMPARISON: { label: string; free: string | false; premium: string | true }[] = [ - { label: "Warmup pool", free: "Free pool", premium: "Premium pool" }, - { label: "Partner matching", free: "After Premium", premium: "First" }, - { label: "Mailboxes", free: "10", premium: "No limit" }, - { label: "Spam-prone partners removed", free: "Yes", premium: true }, - { label: "Replies and spam rescue", free: "Yes", premium: true }, -]; - -export default function WarmupPlanDialog({ open, onClose }: { open: boolean; onClose: () => void }) { - const orgName = useAppStore((s) => s.currentOrganization?.name); - const offer = usePoolLinkOffer(open); - // The workspace's own allowance, so the right column shows why to upgrade - // rather than a made-up chart. Hidden when it cannot be read. - const instances = usePoolLinkInstances(open); - const allowance = instances.data?.plan; - const checkout = useStartPoolLinkCheckout(); - const [interval, setInterval] = React.useState("year"); - - // Yearly is the better default, but only where it exists. Applied once per - // opening: a background refetch must not move the choice under someone who - // has already picked the other period. - const defaulted = React.useRef(false); - React.useEffect(() => { - if (!open) { - defaulted.current = false; - return; - } - if (defaulted.current || !offer.data) return; - defaulted.current = true; - setInterval(offer.data.yearly_available ? "year" : "month"); - }, [open, offer.data]); - - const cardRef = React.useRef(null); - React.useEffect(() => { - if (!open) return; - const previous = document.activeElement as HTMLElement | null; - cardRef.current?.focus(); - const onKey = (e: KeyboardEvent) => { - if (e.key === "Escape" && !checkout.isPending) { - e.stopPropagation(); - onClose(); - } - }; - document.addEventListener("keydown", onKey, true); - return () => { - document.removeEventListener("keydown", onKey, true); - previous?.focus?.(); - }; - }, [open, checkout.isPending, onClose]); - - const data = offer.data; - const available = data?.available === true; - const monthly = data?.monthly_usd ?? 0; - const yearly = data?.yearly_usd ?? 0; - const annual = interval === "year" && data?.yearly_available === true; - // Only worth showing when it is actually a saving. - const yearlySaving = monthly > 0 && yearly > 0 ? Math.max(0, monthly * 12 - yearly) : 0; - const accent = PLAN_ACCENT_CLASSES[getPlan("warmup").accent]; - - async function start() { - if (checkout.isPending || !available) return; - try { - const res = await checkout.mutateAsync(interval); - if (!res.checkout_url) throw new Error("no checkout url"); - window.location.href = res.checkout_url; - } catch (e) { - toast.error(buildError(e as AppError)); - } - } - - return createPortal( - - {open && ( - { - if (e.target === e.currentTarget && !checkout.isPending) onClose(); - }} - className="fixed inset-0 z-[160] flex items-center justify-center bg-slate-900/40 backdrop-blur-[2px] px-4" - > - e.stopPropagation()} - className="w-full max-w-[720px] max-h-[calc(100dvh-3rem)] overflow-y-auto rounded-lg bg-white border border-slate-200 shadow-[0_24px_48px_-12px_rgba(15,23,42,0.18)]" - > -
- Warmup plan -
- - Premium warmup pool - - -
- -
- {/* Left: the plan, in the chooser's anatomy. */} -
-
- Premium - {!offer.isLoading && available && data?.yearly_available && data?.monthly_available && ( -
- setInterval(i === "annual" ? "year" : "month")} - /> -
- )} -
-

{WARMUP_PLAN_PITCH}

- -
- {offer.isLoading ? ( - - ) : ( - <> - - ${annual ? Math.round(yearly / 12) : monthly} - - / mo - - )} -
-
- {annual ? ( - <> - billed ${yearly} annually - {yearlySaving > 0 && ( - - save ${yearlySaving} / yr - - )} - - ) : ( - "billed monthly" - )} -
- -
    - {WARMUP_PLAN_BENEFITS.map((b) => ( -
  • -
  • - ))} -
- - {!offer.isLoading && !available && ( -
-

- {offer.isError - ? "The price could not be loaded. Try again in a moment." - : "This instance has no price set for the warmup plan yet, so it cannot be bought here."} -

-
- )} - -

- Applies to {orgName || "this workspace"} and any instance - linked to it. Billed through Stripe. Cancel anytime. -

-
- - {/* Right: where this workspace stands, and what changes. */} - -
- -
- - -
- - - )} - , - document.body, - ); -} diff --git a/web/src/components/app/cloud/CloudConnectDialog.tsx b/web/src/components/app/cloud/CloudConnectDialog.tsx deleted file mode 100644 index 4446d46e1..000000000 --- a/web/src/components/app/cloud/CloudConnectDialog.tsx +++ /dev/null @@ -1,132 +0,0 @@ -// Modal wrapper around CloudLinkCard for surfaces outside Settings (the -// mailboxes page, sending domains). Same overlay anatomy as NewCampaignDialog. -// Portaled and layered above drawers, which a transformed parent would trap. - -import React from "react"; -import { createPortal } from "react-dom"; -import { AnimatePresence, motion } from "framer-motion"; -import { LockIcon, XIcon } from "lucide-react"; -import { useQueryClient } from "@tanstack/react-query"; -import CloudLinkCard from "./CloudLinkCard"; -import { CLOUD_LINK_KEY } from "@/lib/api/hooks/app/cloudlink/useCloudLink"; -import { usePermission } from "@/hooks/usePermission"; - -export default function CloudConnectDialog({ - open, - onClose, - cloudUrl, - intro, - autoStart = false, - doneLabel = "Pick mailboxes", - onDone, -}: { - open: boolean; - onClose: () => void; - cloudUrl?: string; - /** Why the link is asked for here, shown above the code in place of the warmup pitch. */ - intro?: React.ReactNode; - /** Ask for a code straight away. */ - autoStart?: boolean; - doneLabel?: string; - /** What the button after linking does; closing is the default. */ - onDone?: () => void; -}) { - const qc = useQueryClient(); - const canLink = usePermission("MANAGE_SETTINGS"); - const [linked, setLinked] = React.useState(false); - const [orgName, setOrgName] = React.useState(""); - - React.useEffect(() => { - if (!open) { - setLinked(false); - setOrgName(""); - } - }, [open]); - - React.useEffect(() => { - if (!open) return; - const onKey = (e: KeyboardEvent) => { - if (e.key !== "Escape") return; - if (document.querySelector("[data-floating]:not([data-cloud-connect]), [role='alertdialog']")) return; - e.preventDefault(); - onClose(); - }; - document.addEventListener("keydown", onKey); - return () => document.removeEventListener("keydown", onKey); - }, [open, onClose]); - - return createPortal( - - {open && ( - { - e.stopPropagation(); - onClose(); - }} - className="fixed inset-0 z-[120] flex items-center justify-center bg-slate-900/30 backdrop-blur-[2px] px-4" - > - e.stopPropagation()} - className="w-full max-w-[520px] rounded-lg bg-white border border-slate-200 shadow-[0_24px_48px_-12px_rgba(15,23,42,0.18)] overflow-hidden" - > -
- Warmbly Cloud - -
-
- {intro && !linked &&
{intro}
} - {canLink ? ( - { - setOrgName(name); - setLinked(true); - void qc.invalidateQueries({ queryKey: CLOUD_LINK_KEY }); - }} - /> - ) : ( -

- - Connecting this instance to Warmbly Cloud is a settings change. Ask a teammate who manages settings to connect it. -

- )} -
- {linked && ( -
- -
- )} -
-
- )} -
, - document.body, - ); -} diff --git a/web/src/components/app/cloud/CloudLinkCard.tsx b/web/src/components/app/cloud/CloudLinkCard.tsx deleted file mode 100644 index 9c81c4b6a..000000000 --- a/web/src/components/app/cloud/CloudLinkCard.tsx +++ /dev/null @@ -1,276 +0,0 @@ -// The link handshake as one reusable card: pitch, then the code with a -// countdown and a live "waiting" pulse, then a linked confirmation. Used by -// Settings > Warmbly Cloud, the onboarding step and the mailboxes-page dialog. - -import React from "react"; -import { motion } from "framer-motion"; -import toast from "react-hot-toast/headless"; -import { CheckIcon, CloudIcon, CopyIcon, ExternalLinkIcon, FlameIcon, GlobeIcon, InboxIcon, Loader2Icon, LockIcon, ShieldCheckIcon } from "lucide-react"; -import type { AppError } from "@/lib/api/client/normalizeError"; -import buildError from "@/lib/helper/buildError"; -import type { CloudLinkPendingConnect } from "@/lib/api/models/app/cloudlink/CloudLink"; -import { usePollCloudLinkConnect, useStartCloudLinkConnect } from "@/lib/api/hooks/app/cloudlink/useCloudLink"; - -export default function CloudLinkCard({ - linked, - orgName, - cloudUrl, - onLinked, - compact = false, - autoStart = false, - minimal = false, - startSignal = 0, -}: { - linked: boolean; - orgName?: string; - cloudUrl?: string; - onLinked: (orgName: string) => void; - /** Tighter layout for dialogs and onboarding (no side illustration). */ - compact?: boolean; - /** Request a code immediately instead of showing the pitch first. */ - autoStart?: boolean; - /** Short pitch, no heading or button: the host owns the primary action. */ - minimal?: boolean; - /** Increment to request a code from outside (the host's primary button). */ - startSignal?: number; -}) { - const start = useStartCloudLinkConnect(); - const poll = usePollCloudLinkConnect(); - const [pending, setPending] = React.useState(null); - const [copied, setCopied] = React.useState(false); - const started = React.useRef(false); - - const begin = React.useCallback(async () => { - try { - const p = await start.mutateAsync(undefined); - setPending(p); - } catch (e) { - toast.error(buildError(e as AppError)); - } - }, [start]); - - React.useEffect(() => { - if (autoStart && !linked && !pending && !started.current) { - started.current = true; - void begin(); - } - }, [autoStart, linked, pending, begin]); - - React.useEffect(() => { - if (startSignal > 0 && !linked && !pending) void begin(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [startSignal]); - - // Poll on the cloud's interval while a code is out. - React.useEffect(() => { - if (!pending || linked) return; - let stopped = false; - const tick = async () => { - if (stopped) return; - try { - const res = await poll.mutateAsync(); - if (res.status === "approved") { - onLinked(res.link?.organization_name ?? res.info?.organization.name ?? ""); - return; - } - } catch (e) { - const err = e as AppError; - if (err.code === "cloud_link_code_expired" || err.code === "pool_link_denied" || err.code === "pool_link_code_not_found") { - toast.error(err.message); - setPending(null); - return; - } - } - if (!stopped) window.setTimeout(tick, Math.max(2, pending.interval) * 1000); - }; - const t = window.setTimeout(tick, Math.max(2, pending.interval) * 1000); - return () => { - stopped = true; - window.clearTimeout(t); - }; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [pending, linked]); - - const copy = async () => { - if (!pending) return; - try { - await navigator.clipboard.writeText(pending.user_code); - setCopied(true); - window.setTimeout(() => setCopied(false), 1500); - } catch { - toast.error("Could not copy"); - } - }; - - if (linked) { - return ( - - - - -
-

Linked{orgName ? ` to ${orgName}` : ""}

-

This instance can now warm mailboxes in the Warmbly pool.

-
-
- ); - } - - if (!pending && minimal) { - return ( -
- - - -
-

Warmbly warms your mailboxes for you.

-

- Free for 10 mailboxes. Google and Microsoft sign-in without OAuth setup, and domain redirects without proxy setup. Your data stays on - this server; only warmup runs in the cloud. -

- {start.isPending && ( -

- Getting a code -

- )} -
-
- ); - } - - if (!pending) { - return ( -
-
-
-

Warm your mailboxes with the Warmbly pool

-

- Link this instance to a Warmbly Cloud workspace. Warmbly runs warmup for the mailboxes you choose, using thousands of real - mailboxes, while everything else stays on this server. -

-
-
    - Free for up to 10 mailboxes. Premium, $15 a month, brings better deliverability to every mailbox. - Sign in Google and Microsoft mailboxes through Warmbly's own apps: no OAuth client setup on this server. - Have the cloud serve your sending domains' website redirects, with no proxy or certificate setup on this server. - - Only mailbox sign-ins live on the cloud, encrypted, for warmup and sending, plus the domain and website of any redirect you hand it. - Campaigns, contacts and inbox never leave here. - - You can remove a mailbox or disconnect at any time; the cloud forgets it immediately. -
- - {cloudUrl &&

Connecting to {cloudUrl}

} -
- {!compact && } -
- ); - } - - return ( -
-

Enter this code on Warmbly Cloud to approve the link.

- - {pending.user_code} - - {copied ? : } - - - - Open Warmbly Cloud - - -
- - - - - Waiting for approval - -
-

- No Warmbly account yet? The link takes you to sign up first; it is free. This tab keeps waiting. -

-
- ); -} - -function Countdown({ until }: { until: Date }) { - const [left, setLeft] = React.useState(() => Math.max(0, Math.floor((new Date(until).getTime() - Date.now()) / 1000))); - React.useEffect(() => { - const t = window.setInterval(() => setLeft(Math.max(0, Math.floor((new Date(until).getTime() - Date.now()) / 1000))), 1000); - return () => window.clearInterval(t); - }, [until]); - const m = Math.floor(left / 60); - const s = left % 60; - return ( - - ยท code expires in {m}:{s.toString().padStart(2, "0")} - - ); -} - -function Bullet({ icon: Icon, children }: { icon: React.ComponentType<{ className?: string }>; children: React.ReactNode }) { - return ( -
  • - - {children} -
  • - ); -} - -// A small animated diagram: this server, the cloud, and mail flowing between. -function Illustration() { - return ( -
    -
    - - - - You -
    -
    - - - - Pool -
    -
    - {[0, 1, 2].map((i) => ( - - ))} -
    - ); -} diff --git a/web/src/components/app/emails/CloudPathsPanel.tsx b/web/src/components/app/emails/CloudPathsPanel.tsx index 7618b671d..bdd97a16f 100644 --- a/web/src/components/app/emails/CloudPathsPanel.tsx +++ b/web/src/components/app/emails/CloudPathsPanel.tsx @@ -1,19 +1,16 @@ // Hosted workspace, Accounts page: how to get mailboxes warming. A free -// workspace gets one card (connect a mailbox, 10 are free) with the Warmup -// plan as the way past the allowance; self-hosting is a footnote, not a -// column, because it is optional and reads as the point of the plan when it -// sits beside it. A subscribed workspace gets a one-line strip. Full panel -// when the list is empty, one strip once mailboxes exist. +// workspace gets one card (connect a mailbox, 10 are free) with a paid plan +// as the way past the allowance; self-hosting is a footnote, not a column. +// A subscribed workspace gets a one-line strip. Full panel when the list is +// empty, one strip once mailboxes exist. -import React from "react"; import { Link } from "@tanstack/react-router"; import { motion } from "framer-motion"; import { CloudIcon, InboxIcon, PlusIcon } from "lucide-react"; import useFeatureAccess from "@/hooks/useFeatureAccess"; import useAuthConfig from "@/lib/api/hooks/auth/useAuthConfig"; import { usePoolLinkInstances } from "@/lib/api/hooks/app/cloudlink/useCloudLink"; -import { getPlan, isWarmupOnlyPlan } from "@/lib/plans"; -import WarmupPlanDialog from "@/components/app/billing/WarmupPlanDialog"; +import { isWarmupOnlyPlan } from "@/lib/plans"; const FREE_MAILBOXES = 10; @@ -22,7 +19,6 @@ export default function CloudPathsPanel({ mailboxCount, onAdd }: { mailboxCount: const access = useFeatureAccess(); const hosted = authConfig.data?.self_hosted === false; const instances = usePoolLinkInstances(hosted); - const [planOpen, setPlanOpen] = React.useState(false); // Both hops are optional: a list endpoint whose rows come back as a nil // slice serialises `data` as null, not [], so the inner one throws. const linked = instances.data?.data?.length ?? 0; @@ -40,11 +36,8 @@ export default function CloudPathsPanel({ mailboxCount, onAdd }: { mailboxCount: const free = limit !== null; const allowance = limit ?? FREE_MAILBOXES; const canBuy = free && access.billing && access.isOwner; - const warmup = getPlan("warmup"); const onWarmupPlan = isWarmupOnlyPlan(access.plan); - const dialog = setPlanOpen(false)} />; - if (total === 0 && linked === 0) { return (
    @@ -66,21 +59,13 @@ export default function CloudPathsPanel({ mailboxCount, onAdd }: { mailboxCount: Add account {canBuy && ( - + + Premium pool on a paid plan + )}
    -
    - Running Warmbly on your own server? It can warm its mailboxes here too:{" "} - - link your instance - - . -
    - {dialog}
    ); } @@ -108,18 +93,18 @@ export default function CloudPathsPanel({ mailboxCount, onAdd }: { mailboxCount: {(linkedLabel || (free && canBuy)) && ( {linkedLabel} - {free && canBuy ? ` Premium gives every mailbox better deliverability, $${warmup.priceMonthly}/mo.` : ""} + {free && canBuy ? " Paid plans warm every mailbox in the premium pool." : ""} )} {canBuy && ( - + )} {linked > 0 && ( @@ -127,7 +112,6 @@ export default function CloudPathsPanel({ mailboxCount, onAdd }: { mailboxCount: )}
    - {dialog}
    ); } diff --git a/web/src/components/app/emails/CloudPoolBanner.tsx b/web/src/components/app/emails/CloudPoolBanner.tsx index 7392b5874..1c5ad5220 100644 --- a/web/src/components/app/emails/CloudPoolBanner.tsx +++ b/web/src/components/app/emails/CloudPoolBanner.tsx @@ -1,57 +1,51 @@ -// Mailboxes page strip for self-hosted instances: invites an unlinked -// instance to connect, and shows a linked one how many mailboxes are in the -// pool. Dismissal of the invite is remembered locally. Once linked the strip -// stays quiet: one line of state, and the Premium nudge only when the free -// allowance is actually used up. +// Mailboxes page strip for self-hosted instances. Unlinked: local warmup is not +// effective and self-hosting is unsupported, so it points at Warmbly Cloud. +// Linked on a free workspace: what it enrolled keeps warming, new mailboxes +// warm here unless the workspace pays. Linked and paid: one line of state. import React from "react"; import { Link } from "@tanstack/react-router"; -import { ArrowRightIcon, CloudIcon, ExternalLinkIcon, MailCheckIcon, TrendingUpIcon, XIcon } from "lucide-react"; +import { ArrowRightIcon, CloudIcon, ExternalLinkIcon, MessagesSquareIcon, ServerIcon, XIcon } from "lucide-react"; import useCloudPool from "@/hooks/useCloudPool"; +import { COMMUNITY_URL, cloudAddsNeedSubscription } from "@/lib/cloudPlan"; -const DISMISS_KEY = "warmbly.cloud-pool-banner.dismissed"; +// A new key, so instances that dismissed the old free offer see this notice once. +const DISMISS_KEY = "warmbly.selfHostNotice.dismissed"; -export default function CloudPoolBanner({ onConnect, mailboxCount }: { onConnect: () => void; mailboxCount: number }) { +export default function CloudPoolBanner({ mailboxCount }: { mailboxCount: number }) { const pool = useCloudPool(); const [dismissed, setDismissed] = React.useState(() => localStorage.getItem(DISMISS_KEY) === "1"); if (!pool.manageable || pool.loading) return null; - if (pool.connected && !pool.workspaceConnected) { - return
    Existing Cloud mailboxes keep warming. Connect this workspace to add more.
    ; - } if (pool.connected) { const plan = pool.plan; - const limit = plan?.mailbox_limit ?? null; const premium = plan?.tier === "paid"; - // The allowance is per cloud workspace, so the cloud's count is the - // one that decides, not this instance's own enrolled count. - const used = plan?.enrolled ?? pool.enrolledCount; - const atLimit = !premium && limit !== null && used >= limit && mailboxCount > pool.enrolledCount; - if (atLimit && plan?.upgrade_url) { + const closed = cloudAddsNeedSubscription(plan); + const subscribeURL = plan?.upgrade_url || plan?.manage_url; + if (closed && mailboxCount > pool.enrolledCount) { return ( -
    -
    - -
    - - Give every mailbox better deliverability.{" "} - - All {limit} free pool mailboxes are in use. Premium warms the rest in the premium pool, built for inbox placement, for ${plan.price_usd} a month. - - - - Upgrade to Premium - - -
    -
    -
    + + {pool.enrolledCount > 0 ? `The ${pool.enrolledCount} already in Warmbly Cloud keep warming there. ` : ""} + Adding more to the Cloud pool needs a paid Warmbly Cloud plan. Self-hosted instances get no support from Warmbly. + + } + actions={ + <> + {subscribeURL && ( + + See plans + + + )} + + + } + /> ); } return ( @@ -64,9 +58,7 @@ export default function CloudPoolBanner({ onConnect, mailboxCount }: { onConnect ? "No mailbox is warming in Warmbly Cloud yet." : `${pool.enrolledCount} of ${mailboxCount} mailboxes warm in Warmbly Cloud.`} {" "} - - {premium ? "Premium pool." : limit === null ? "Unlimited." : `${used} of ${limit} free.`} - + {premium ? "Premium pool." : closed ? "Free, no new mailboxes." : "Free pool."} Manage @@ -78,43 +70,75 @@ export default function CloudPoolBanner({ onConnect, mailboxCount }: { onConnect if (dismissed) return null; + return ( + + It only pairs your own mailboxes, which providers learn to recognise. Warmbly Cloud warms mailboxes in a pool of thousands of real + ones. Self-hosting is for experienced operators, and Warmbly does not provide support for it. + + } + actions={ + <> + + Use Warmbly Cloud + + + + + } + onDismiss={() => { + localStorage.setItem(DISMISS_KEY, "1"); + setDismissed(true); + }} + /> + ); +} + +const PRIMARY = "shrink-0 h-7 px-2.5 rounded-md bg-sky-600 hover:bg-sky-700 text-white text-[12px] font-medium inline-flex items-center gap-1.5 transition-colors"; + +function Notice({ icon, title, body, actions, onDismiss }: { icon: React.ComponentType<{ className?: string }>; title: string; body: React.ReactNode; actions: React.ReactNode; onDismiss?: () => void }) { return (
    - +
    - Get these mailboxes into the inbox, not spam.{" "} - - Warm them in Warmbly Cloud's large, active pool to build sender reputation, with replies and spam rescue handled for you. - Free for 10 mailboxes, set up in a minute, and your data stays here. - + {title} {body} +
    {actions}
    +
    + {onDismiss && ( -
    - + )}
    ); } +function CommunityLink() { + return ( + + + Community on Discord + + ); +} + // A soft round badge: tinted fill and a hairline ring, lighter than a solid tile. function SoftIcon({ icon: Icon }: { icon: React.ComponentType<{ className?: string }> }) { return ( diff --git a/web/src/components/app/emails/CloudWarmupCard.tsx b/web/src/components/app/emails/CloudWarmupCard.tsx index 3f068df29..d11e155a9 100644 --- a/web/src/components/app/emails/CloudWarmupCard.tsx +++ b/web/src/components/app/emails/CloudWarmupCard.tsx @@ -3,7 +3,6 @@ // pause/resume/remove, or the way in when it is not enrolled yet. import React from "react"; -import { Link } from "@tanstack/react-router"; import toast from "react-hot-toast/headless"; import { CloudIcon, Loader2Icon, PauseIcon, PlayIcon } from "lucide-react"; import type { AppError } from "@/lib/api/client/normalizeError"; @@ -21,6 +20,7 @@ import { setCloudLinkParticipation } from "@/lib/api/client/app/cloudlink/cloudL import type { DiagnosticParticipation } from "@/lib/api/models/app/cloudlink/CloudLink"; import { Toggle } from "@/components/app/campaigns/preferences/components/CampaignPreferenceBoolBox"; import { cloudMailboxPickerOpened } from "@/lib/cloudMailboxConnect"; +import { cloudAddsNeedSubscription } from "@/lib/cloudPlan"; export default function CloudWarmupCard({ mailboxId, email, provider }: { mailboxId: string; email: string; provider: string }) { const pool = useCloudPool(); @@ -43,23 +43,28 @@ export default function CloudWarmupCard({ mailboxId, email, provider }: { mailbo } }; - if (!pool.connected) { - return ( -
    - - Warm this mailbox in the Warmbly pool instead, free for up to 10 mailboxes. - - Connect Warmbly Cloud - -
    - ); - } + if (!pool.connected) return null; const row = pool.rowFor(mailboxId); const cloud = row?.cloud; const sendFailure = cloudSendFailure(cloud); const supported = providerSupported(provider); + const subscribeURL = pool.plan?.upgrade_url || pool.plan?.manage_url; + if (!row?.enrolled && cloudAddsNeedSubscription(pool.plan)) { + return ( +
    + + This mailbox warms on this instance, which is not effective. Adding it to the Warmbly Cloud pool needs a paid plan. + {subscribeURL && ( + + See plans + + )} +
    + ); + } + if (!row?.enrolled) { return (
    @@ -119,13 +124,14 @@ export default function CloudWarmupCard({ mailboxId, email, provider }: { mailbo disabled={busy} onClick={() => confirm.show( - row.managed + (row.managed ? `Remove ${email} from this instance and stop its Cloud warmup sending and receiving? Its mailbox, sign-in and history stay in your Warmbly Cloud workspace. You can restart warmup there.` : row.independent_smtp || cloud?.managed ? `Disconnect Cloud warmup for ${email}? Its Cloud mailbox, credentials and warmup history stay on Cloud. Campaigns here keep their existing app-password connection. Cloud warmup sending and receiving stop until you restart them there.` : row.executor === "instance" ? `Stop warming ${email} in the Warmbly pool? Its credential never left this server, and local warmup takes over.` - : `Stop warming ${email} in the Warmbly pool? The cloud deletes its credential right away and local warmup takes over.`, + : `Stop warming ${email} in the Warmbly pool? The cloud deletes its credential right away and local warmup takes over.`) + + (cloudAddsNeedSubscription(pool.plan) ? " A free workspace cannot add it back without a paid plan." : ""), async () => { await run(() => unenroll.mutateAsync(mailboxId), row.managed ? `${email} removed from this instance` : `${email} removed from the pool`); }, diff --git a/web/src/components/app/emails/domains/BulkSetupDialog.tsx b/web/src/components/app/emails/domains/BulkSetupDialog.tsx index 5915489b1..ebbe21aad 100644 --- a/web/src/components/app/emails/domains/BulkSetupDialog.tsx +++ b/web/src/components/app/emails/domains/BulkSetupDialog.tsx @@ -21,7 +21,6 @@ import { Chip } from "./parts"; import { PerDomainList, type DomainOverride, type PerDomainRow } from "./PerDomainList"; import { ServedByPicker } from "./RedirectServing"; import { defaultServer, useCloudServing } from "./cloudServing"; -import CloudConnectDialog from "@/components/app/cloud/CloudConnectDialog"; export interface BulkSetupIntent { domains: string[]; @@ -68,7 +67,6 @@ function Dialog({ const [url, setUrl] = React.useState(website); const cloud = useCloudServing(); const [servedPick, setServedPick] = React.useState(null); - const [connecting, setConnecting] = React.useState(false); // A Cloud pick Cloud can no longer take falls back, so what is shown is what is sent. const server = servedPick === "cloud" && !cloud.canServe ? "instance" : (servedPick ?? defaultServer(cloud)); const [phase, setPhase] = React.useState("form"); @@ -348,7 +346,7 @@ function Dialog({ {up && url.trim() !== "" &&

    {up}

    }

    {OWN_DOMAIN_HINT}

    {cloud.choosable && ( - setConnecting(true)} cloud={cloud} /> + )} {keeping > 0 && (

    @@ -529,17 +527,6 @@ function Dialog({ )}

    - setConnecting(false)} - autoStart - intro="Link this instance to a Warmbly Cloud workspace, free to create, and Cloud serves these redirects and their certificates. Nothing on your server changes: you only point each domain's DNS at Cloud. Approve the code below on Warmbly Cloud to finish." - doneLabel="Use Warmbly Cloud" - onDone={() => { - setConnecting(false); - setServedPick("cloud"); - }} - /> ); } diff --git a/web/src/components/app/emails/domains/RedirectRescue.tsx b/web/src/components/app/emails/domains/RedirectRescue.tsx index f9e3951ce..e6a609a3b 100644 --- a/web/src/components/app/emails/domains/RedirectRescue.tsx +++ b/web/src/components/app/emails/domains/RedirectRescue.tsx @@ -8,7 +8,6 @@ import { useSetDomainRedirect } from "@/lib/api/hooks/app/emails/useSendingDomai import { useConfirm } from "@/hooks/context/confirm"; import type { AppError } from "@/lib/api/client/normalizeError"; import buildError from "@/lib/helper/buildError"; -import CloudConnectDialog from "@/components/app/cloud/CloudConnectDialog"; import { PROXY_NAMES, redirectBlocked } from "./rules"; import { useCloudServing } from "./cloudServing"; @@ -18,7 +17,6 @@ export default function RedirectRescue({ all, onOpenDomain }: { all: SendingDoma const cloud = useCloudServing(); const confirm = useConfirm(); const save = useSetDomainRedirect(); - const [connecting, setConnecting] = React.useState(false); const [moving, setMoving] = React.useState<{ done: number; of: number } | null>(null); const [hidden, setHidden] = React.useState(() => localStorage.getItem(DISMISS_KEY) ?? ""); @@ -115,19 +113,17 @@ export default function RedirectRescue({ all, onOpenDomain }: { all: SendingDoma > Fix on my server - {(cloud.canServe || !cloud.connected) && ( + {cloud.canServe && ( )} - - - ); - } else if (!cloud.offer?.available) { + if (!cloud.offer?.available) { cloudBody = "Warmbly Cloud does not serve redirects for this instance right now."; } else if (!cloudOpen && cloud.offer.used >= cloud.offer.limit) { cloudBody = `Warmbly Cloud serves up to ${cloud.offer.limit} redirects for one instance, and this one has reached it.`; @@ -417,15 +395,12 @@ export function ReachFix({ redirect, cloud, onServeFromCloud, - onConnect, switching, }: { domain: string; redirect: DomainRedirect; cloud: CloudServing; onServeFromCloud: () => void; - /** Opens the link to Warmbly Cloud in place; serving from it follows. */ - onConnect: () => void; switching: boolean; }) { const reach = redirect.reach; @@ -517,37 +492,22 @@ export function ReachFix({ )}

    After changing it, press Check now. Warmbly also checks again every 10 minutes.

    - {redirect.served_by !== "cloud" && cloud.choosable && (cloud.canServe || !cloud.connected) && ( + {redirect.served_by !== "cloud" && cloud.canServe && (

    Or skip the proxy work

    -

    - {cloud.canServe - ? "Warmbly Cloud can serve this redirect and its certificate. You replace the root records; nothing changes on your server." - : "Link this instance to a free Warmbly Cloud workspace and it can serve this redirect and its certificate, with nothing to change on your server. It takes about a minute."} -

    +

    Warmbly Cloud can serve this redirect and its certificate. You replace the root records; nothing changes on your server.

    - {cloud.canServe ? ( - - ) : ( - - )} +
    diff --git a/web/src/components/app/emails/domains/SendingDomainDrawer.tsx b/web/src/components/app/emails/domains/SendingDomainDrawer.tsx index 64766f19b..fbaa95a1a 100644 --- a/web/src/components/app/emails/domains/SendingDomainDrawer.tsx +++ b/web/src/components/app/emails/domains/SendingDomainDrawer.tsx @@ -54,7 +54,6 @@ import { cn } from "@/lib/utils"; import { DnsRecordsTable, StatusPill, VendorChip, type RecordRow } from "./parts"; import { ReachFix, RedirectProgress, ServedByPicker } from "./RedirectServing"; import { defaultServer, useCloudServing } from "./cloudServing"; -import CloudConnectDialog from "@/components/app/cloud/CloudConnectDialog"; import { OWN_DOMAIN_HINT, REDIRECT_NOT_OWN_DOMAIN, @@ -1024,8 +1023,6 @@ function DnsRedirect({ const [tried, setTried] = React.useState(false); // The record that confirms the typed website is the workspace's, once a save was refused for lack of it. const [proof, setProof] = React.useState(null); - // "serve" came from a redirect visitors do not reach, so linking moves it; "pick" only selects Cloud. - const [connecting, setConnecting] = React.useState<"pick" | "serve" | null>(null); const url = urlDraft ?? redirect?.target_url ?? ""; const www = wwwDraft ?? redirect?.include_www ?? true; @@ -1114,21 +1111,6 @@ function DnsRedirect({ ); } - // Once linked, the dialog's own button is the go-ahead. - async function afterLinked() { - const why = connecting; - setConnecting(null); - if (!redirect || why !== "serve") { - setServedDraft("cloud"); - return; - } - try { - await persist(redirect.target_url, redirect.include_www, "cloud"); - } catch (e) { - toast.error(buildError(e as AppError)); - } - } - async function checkNow() { if (verify.isPending) return; try { @@ -1180,7 +1162,6 @@ function DnsRedirect({ redirect={redirect} cloud={cloud} onServeFromCloud={serveFromCloud} - onConnect={() => setConnecting("serve")} switching={save.isPending} /> } @@ -1239,7 +1220,6 @@ function DnsRedirect({ value={server} current={redirect?.served_by} onChange={setServedDraft} - onConnect={() => setConnecting("pick")} cloud={cloud} /> )} @@ -1298,21 +1278,6 @@ function DnsRedirect({ )} - - setConnecting(null)} - autoStart - intro={ - <> - Link this instance to a Warmbly Cloud workspace, free to create, and Cloud serves{" "} - {domain.domain}'s redirect and its certificate. Nothing on your - server changes: you only point the domain's DNS at Cloud. Approve the code below on Warmbly Cloud to finish. - - } - doneLabel={redirect && connecting === "serve" ? `Serve ${domain.domain} from Warmbly Cloud` : "Use Warmbly Cloud"} - onDone={() => void afterLinked()} - /> ); } diff --git a/web/src/components/app/emails/domains/cloudServing.ts b/web/src/components/app/emails/domains/cloudServing.ts index c7872c13f..807d50aaf 100644 --- a/web/src/components/app/emails/domains/cloudServing.ts +++ b/web/src/components/app/emails/domains/cloudServing.ts @@ -6,7 +6,7 @@ import type { PoolLinkRedirectOffer } from "@/lib/api/models/app/cloudlink/Cloud import type { RedirectServer } from "@/lib/api/models/app/emails/SendingDomain"; export interface CloudServing { - /** Only a self-hosted instance's administrator picks, since it forwards credentials off the server; Warmbly Cloud always serves its own. */ + /** Only an already-linked self-hosted instance's administrator picks; Warmbly Cloud always serves its own. */ choosable: boolean; connected: boolean; offer: PoolLinkRedirectOffer | null; @@ -17,12 +17,13 @@ export interface CloudServing { export function useCloudServing(): CloudServing { const auth = useAuthConfig(); const instanceAdmin = useInstanceAdmin(); - const choosable = !!auth.data?.self_hosted && instanceAdmin.allowed; - const status = useCloudLinkStatus(choosable, 60_000); - const offer = choosable ? (status.data?.info?.redirects ?? null) : null; - const connected = choosable && !!status.data?.connected; + const admin = !!auth.data?.self_hosted && instanceAdmin.allowed; + const status = useCloudLinkStatus(admin, 60_000); + const connected = admin && !!status.data?.connected; + const offer = connected ? (status.data?.info?.redirects ?? null) : null; return { - choosable, + // Only an existing link serves redirects; Warmbly Cloud links no new instances. + choosable: connected, connected, offer, canServe: connected && !!status.data?.link?.organization_id && !!offer?.available && offer.used < offer.limit, diff --git a/web/src/components/app/modals/AddEmailModal.tsx b/web/src/components/app/modals/AddEmailModal.tsx index 037805e93..6746add5f 100644 --- a/web/src/components/app/modals/AddEmailModal.tsx +++ b/web/src/components/app/modals/AddEmailModal.tsx @@ -34,7 +34,6 @@ import { Building2Icon, CheckIcon, ChevronRightIcon, - CloudIcon, FileSpreadsheetIcon, InboxIcon, KeyRoundIcon, @@ -327,7 +326,7 @@ export default function AddEmailModal() { )} {view === "gmail" && ( notConfigured === "gmail" ? ( - + ) : ( + ) : ( = }, }; -function ProviderNotConfigured({ provider, selfHosted }: { provider: OAuthProvider; selfHosted: boolean }) { +function ProviderNotConfigured({ provider }: { provider: OAuthProvider }) { const { label, vars } = PROVIDER_SETUP[provider]; return (
    - {selfHosted && ( -
    - -
    -

    Skip the OAuth setup: connect Warmbly Cloud

    -

    - Linked instances sign mailboxes in through Warmbly's own Google and Microsoft apps, and the cloud warms them. Free for 10 mailboxes. -

    - - Connect Warmbly Cloud - -
    -
    - )}
    diff --git a/web/src/components/app/tour/PlanSlides.tsx b/web/src/components/app/tour/PlanSlides.tsx index 9ae09093c..b511e15dd 100644 --- a/web/src/components/app/tour/PlanSlides.tsx +++ b/web/src/components/app/tour/PlanSlides.tsx @@ -5,7 +5,6 @@ import type { ReactNode } from "react"; import { motion, useReducedMotion } from "framer-motion"; import { - ArrowRightIcon, ArrowUpRightIcon, CheckIcon, CloudIcon, @@ -33,6 +32,7 @@ import { EASE } from "./sceneTokens"; import { Title } from "./TourCopy"; import type { FlatSlide } from "./tourSteps"; import { EYEBROW } from "./tourUi"; +import { COMMUNITY_URL } from "@/lib/cloudPlan"; // Monthly AI credits per plan, from the allowance table in the AI credits guide. const AI_CREDITS: Partial> = { @@ -385,8 +385,8 @@ export function PlanChoose({ ); } -/** Keeping the instance: its mailboxes can still warm in the hosted pool. */ -export function CloudCallout({ onLink, docs }: { onLink?: () => void; docs: string }) { +/** Keeping the instance: it runs on its own, and the plans above are where the shared pool is. */ +export function CloudCallout() { const cls = "h-9 shrink-0 px-3.5 rounded-full inline-flex items-center justify-center gap-1.5 bg-white text-[12.5px] font-medium text-slate-800 ring-1 ring-slate-200 transition-colors hover:bg-slate-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400"; return ( @@ -395,22 +395,15 @@ export function CloudCallout({ onLink, docs }: { onLink?: () => void; docs: stri
    -

    Keeping this instance? Warm it in our pool.

    +

    Keeping this instance? It runs on its own.

    - Link it to Warmbly Cloud and its mailboxes warm against thousands of real inboxes, while campaigns, contacts and mail stay on your server. Free for up to 10 mailboxes, or $15 a month for the premium pool with no cap. + Warmup here only pairs your own mailboxes, which is not effective. A pool of thousands of real mailboxes comes with the Warmbly Cloud plans above. Warmbly does not support self-hosted instances; the community helps on Discord.

    - {onLink ? ( - - ) : ( - - How it works - - - )} + + Community on Discord + +
    ); } diff --git a/web/src/components/app/tour/ProductTour.tsx b/web/src/components/app/tour/ProductTour.tsx index cc5c81f86..0869e1a93 100644 --- a/web/src/components/app/tour/ProductTour.tsx +++ b/web/src/components/app/tour/ProductTour.tsx @@ -30,7 +30,7 @@ import { RemieCard, SlideCopy } from "./TourCopy"; import { CloudCallout, PlanChoose, PlanCompare, PlanIncluded } from "./PlanSlides"; import { TOUR_SLIDES, type FlatSlide } from "./tourSteps"; import { SHOTS } from "./tourShots"; -import { CLOUD_DOCS, PRIMARY, SECONDARY, billingPreview, hostedPlanURL } from "./tourUi"; +import { PRIMARY, SECONDARY, billingPreview, hostedPlanURL } from "./tourUi"; const CLOSE = "h-7 pl-2 pr-2.5 rounded-full inline-flex items-center gap-1 bg-white/85 text-[12px] text-slate-500 ring-1 ring-slate-900/[0.06] backdrop-blur-sm transition-colors hover:text-slate-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400"; @@ -399,10 +399,7 @@ export default function ProductTour() { hrefFor={hostedPlanURL} onOpen={(id) => capture("product_tour_hosted_plan", { plan: id })} > - act("link_cloud", () => navigate({ to: "/app/settings/warmbly-cloud" })) : undefined} - /> + ) : ( ) diff --git a/web/src/components/layout/PlanPill.tsx b/web/src/components/layout/PlanPill.tsx index d72e2d779..f59519061 100644 --- a/web/src/components/layout/PlanPill.tsx +++ b/web/src/components/layout/PlanPill.tsx @@ -12,13 +12,13 @@ import { usePermission } from "@/hooks/usePermission"; import { PLAN_ACCENT_CLASSES, getPlan } from "@/lib/plans"; import { cn } from "@/lib/utils"; import { useAppStore } from "@/stores"; +import { cloudAddsNeedSubscription } from "@/lib/cloudPlan"; export function PlanPill() { const access = useFeatureAccess(); const pool = useCloudPool(); - // The Warmbly Cloud page is manage-settings gated; everyone else lands - // on their profile rather than on a "no access" screen. - const cloudTo = usePermission("MANAGE_SETTINGS") ? "/app/settings/warmbly-cloud" : "/app/settings/profile"; + // The Warmbly Cloud page is manage-settings gated and only exists for a linked instance; everyone else lands on their profile. + const cloudTo = usePermission("MANAGE_SETTINGS") && pool.connected ? "/app/settings/warmbly-cloud" : "/app/settings/profile"; const isTest = useAppStore((s) => s.currentOrganization?.category === "test"); if (isTest) { return ( @@ -52,7 +52,9 @@ export function PlanPill() { title={ premium ? "Warmbly Cloud Premium: better deliverability for every mailbox" - : `Warmbly Cloud: ${pool.plan.enrolled} of ${pool.plan.mailbox_limit ?? 10} free pool mailboxes used` + : cloudAddsNeedSubscription(pool.plan) + ? `Warmbly Cloud: ${pool.plan.enrolled} mailboxes keep warming. Subscribe to add more` + : `Warmbly Cloud: ${pool.plan.enrolled} of ${pool.plan.mailbox_limit ?? 10} free pool mailboxes used` } icon={premium} /> @@ -64,7 +66,7 @@ export function PlanPill() { className="bg-indigo-50 text-indigo-700 border-indigo-100" dot="bg-indigo-500" label="Self-hosted" - title="Self-hosted: every feature is unlocked. Warm your mailboxes in the Warmbly pool" + title="Self-hosted: every feature is unlocked, with no support from Warmbly" icon /> ); diff --git a/web/src/components/layout/SubscriptionLockedScreen.tsx b/web/src/components/layout/SubscriptionLockedScreen.tsx index 530c2f5c4..51e137961 100644 --- a/web/src/components/layout/SubscriptionLockedScreen.tsx +++ b/web/src/components/layout/SubscriptionLockedScreen.tsx @@ -91,7 +91,7 @@ export default function SubscriptionLockedScreen({ feature }: { feature: string Self-host for free {" "} - and link it here to warm its mailboxes. + on your own: local warmup is limited and Warmbly does not support self-hosted instances. {!isOwner && Only the workspace owner can choose a plan.}
    diff --git a/web/src/hooks/useCloudPool.ts b/web/src/hooks/useCloudPool.ts index afab2a15a..809fc6924 100644 --- a/web/src/hooks/useCloudPool.ts +++ b/web/src/hooks/useCloudPool.ts @@ -35,6 +35,7 @@ export default function useCloudPool() { connected, workspaceConnected: connected && !!status.data?.link?.organization_id, reachable: status.data?.reachable === true, + cloudURL: status.data?.default_cloud_url || "https://app.warmbly.com", orgName: status.data?.link?.organization_name ?? "", plan, enrolledCount, diff --git a/web/src/lib/api/client/app/cloudlink/cloudLink.ts b/web/src/lib/api/client/app/cloudlink/cloudLink.ts index 7d622794e..4f9e2d37c 100644 --- a/web/src/lib/api/client/app/cloudlink/cloudLink.ts +++ b/web/src/lib/api/client/app/cloudlink/cloudLink.ts @@ -5,8 +5,6 @@ import type { CloudLinkExecutor, CloudLinkMailboxRow, CloudLinkOAuthStart, - CloudLinkPendingConnect, - CloudLinkPollResult, CloudLinkStatus, PoolLinkWorkspaceMailbox, DiagnosticParticipation, @@ -17,19 +15,6 @@ export async function getCloudLinkStatus(): Promise { return await Request({ method: "GET", url: "/cloud-link", authorization: true }); } -export async function startCloudLinkConnect(cloudUrl?: string): Promise { - return await Request({ - method: "POST", - url: "/cloud-link/connect", - data: { cloud_url: cloudUrl ?? "" }, - authorization: true, - }); -} - -export async function pollCloudLinkConnect(): Promise { - return await Request({ method: "POST", url: "/cloud-link/connect/poll", authorization: true }); -} - export async function disconnectCloudLink(legacy = false): Promise { await Request({ method: "DELETE", url: "/cloud-link", params: legacy ? { legacy: true } : undefined, authorization: true }); } diff --git a/web/src/lib/api/client/app/cloudlink/poolLink.ts b/web/src/lib/api/client/app/cloudlink/poolLink.ts index 031f0f8a8..6400f9e85 100644 --- a/web/src/lib/api/client/app/cloudlink/poolLink.ts +++ b/web/src/lib/api/client/app/cloudlink/poolLink.ts @@ -2,24 +2,7 @@ // managing the workspace's linked instances. import Request from "@/lib/api/client/Request"; -import type { PoolLinkCode, PoolLinkInstance, PoolLinkOffer, PoolLinkPlan } from "@/lib/api/models/app/cloudlink/CloudLink"; - -export async function describePoolLinkCode(code: string): Promise { - return await Request({ method: "GET", url: `/pool-link/codes/${encodeURIComponent(code)}`, authorization: true }); -} - -export async function approvePoolLinkCode(code: string, organizationId: string): Promise { - return await Request({ - method: "POST", - url: `/pool-link/codes/${encodeURIComponent(code)}/approve`, - data: { organization_id: organizationId }, - authorization: true, - }); -} - -export async function denyPoolLinkCode(code: string): Promise { - await Request({ method: "POST", url: `/pool-link/codes/${encodeURIComponent(code)}/deny`, authorization: true }); -} +import type { PoolLinkInstance, PoolLinkPlan } from "@/lib/api/models/app/cloudlink/CloudLink"; export async function listPoolLinkInstances(): Promise<{ data: PoolLinkInstance[]; plan: PoolLinkPlan }> { return await Request<{ data: PoolLinkInstance[]; plan: PoolLinkPlan }>({ method: "GET", url: "/pool-link/instances", authorization: true }); @@ -29,15 +12,3 @@ export async function revokePoolLinkInstance(id: string): Promise { await Request({ method: "DELETE", url: `/pool-link/instances/${id}`, authorization: true }); } -export async function getPoolLinkOffer(): Promise { - return await Request({ method: "GET", url: "/pool-link/offer", authorization: true }); -} - -export async function startPoolLinkCheckout(interval: "month" | "year"): Promise<{ checkout_url: string }> { - return await Request<{ checkout_url: string }>({ - method: "POST", - url: "/pool-link/checkout", - data: { interval }, - authorization: true, - }); -} diff --git a/web/src/lib/api/hooks/app/cloudlink/useCloudLink.ts b/web/src/lib/api/hooks/app/cloudlink/useCloudLink.ts index 08509af94..146ad7680 100644 --- a/web/src/lib/api/hooks/app/cloudlink/useCloudLink.ts +++ b/web/src/lib/api/hooks/app/cloudlink/useCloudLink.ts @@ -6,18 +6,11 @@ import { listCloudWorkspaceMailboxes, getCloudLinkStatus, listCloudLinkMailboxes, - pollCloudLinkConnect, setCloudLinkMailboxLifecycle, - startCloudLinkConnect, unenrollCloudLinkMailbox, } from "@/lib/api/client/app/cloudlink/cloudLink"; import { - approvePoolLinkCode, - denyPoolLinkCode, - describePoolLinkCode, - getPoolLinkOffer, listPoolLinkInstances, - startPoolLinkCheckout, revokePoolLinkInstance, } from "@/lib/api/client/app/cloudlink/poolLink"; @@ -44,20 +37,6 @@ export function useCloudLinkMailboxes(enabled = true) { return useQuery({ queryKey: [...CLOUD_LINK_KEY, organization.data?.id, "mailboxes"], queryFn: listCloudLinkMailboxes, enabled: enabled && !!organization.data?.id, staleTime: 10_000 }); } -export function useStartCloudLinkConnect() { - return useMutation({ mutationFn: (cloudUrl?: string) => startCloudLinkConnect(cloudUrl) }); -} - -export function usePollCloudLinkConnect() { - const qc = useQueryClient(); - return useMutation({ - mutationFn: () => pollCloudLinkConnect(), - onSuccess: (res) => { - if (res.status === "approved") void qc.invalidateQueries({ queryKey: CLOUD_LINK_KEY }); - }, - }); -} - export function useDisconnectCloudLink() { const qc = useQueryClient(); return useMutation({ @@ -136,27 +115,6 @@ export function useAdoptCloudMailbox() { // Cloud side. -export function usePoolLinkCode(code: string) { - return useQuery({ - queryKey: [...POOL_LINK_KEY, "code", code], - queryFn: () => describePoolLinkCode(code), - enabled: code.replace(/[^A-Za-z0-9]/g, "").length === 8, - retry: 0, - }); -} - -export function useApprovePoolLinkCode() { - const qc = useQueryClient(); - return useMutation({ - mutationFn: ({ code, organizationId }: { code: string; organizationId: string }) => approvePoolLinkCode(code, organizationId), - onSuccess: () => void qc.invalidateQueries({ queryKey: POOL_LINK_KEY }), - }); -} - -export function useDenyPoolLinkCode() { - return useMutation({ mutationFn: (code: string) => denyPoolLinkCode(code) }); -} - export function usePoolLinkInstances(enabled = true) { const organization = useCurrentOrganization(); return useQuery({ queryKey: [...POOL_LINK_KEY, organization.data?.id, "instances"], queryFn: listPoolLinkInstances, enabled: enabled && !!organization.data?.id, staleTime: 10_000 }); @@ -173,10 +131,3 @@ export function useRevokePoolLinkInstance() { }); } -export function usePoolLinkOffer(enabled = true) { - return useQuery({ queryKey: [...POOL_LINK_KEY, "offer"], queryFn: getPoolLinkOffer, enabled, staleTime: 60_000 }); -} - -export function useStartPoolLinkCheckout() { - return useMutation({ mutationFn: (interval: "month" | "year") => startPoolLinkCheckout(interval) }); -} diff --git a/web/src/lib/api/models/app/cloudlink/CloudLink.ts b/web/src/lib/api/models/app/cloudlink/CloudLink.ts index 5412c75cf..047abb9c4 100644 --- a/web/src/lib/api/models/app/cloudlink/CloudLink.ts +++ b/web/src/lib/api/models/app/cloudlink/CloudLink.ts @@ -6,7 +6,6 @@ import type { WarmupPartnerLimit, WarmupSendFailure } from "@/lib/api/models/app/analytics/AccountStatus"; -export type PoolLinkCodeStatus = "pending" | "approved" | "claimed" | "denied"; export interface PoolLinkOrgInfo { id: string; @@ -33,22 +32,13 @@ export interface PoolLinkPlan { /** Mailboxes with warmup on and not paused; older servers do not send it. */ warming?: number; price_usd: number; - /** The cloud's billing page with the warmup plan checkout open; only on the free tier. */ + /** Where a free workspace picks a paid plan; only on the free tier. */ upgrade_url?: string; /** The cloud's billing page; absent when the cloud runs without billing. */ manage_url?: string; warmup_entitled: boolean; -} - -/** GET /pool-link/offer โ€” the pool plan's price, and whether it can be bought - * here at all. Unavailable means billing is off or no Stripe price is set. */ -export interface PoolLinkOffer { - available: boolean; - monthly_available: boolean; - yearly_available: boolean; - monthly_usd: number; - yearly_usd: number; - currency: string; + /** True when a linked instance can add no new mailboxes until the workspace subscribes; older servers do not send it. */ + subscription_required?: boolean; } /** Root redirects Warmbly Cloud serves for this linked instance. */ @@ -79,18 +69,6 @@ export interface PoolLinkInstanceInfo { redirects?: PoolLinkRedirectOffer | null; } -export interface PoolLinkCode { - id: string; - user_code: string; - instance_name: string; - instance_url: string; - instance_version: string; - status: PoolLinkCodeStatus; - organization_id?: string; - expires_at: Date; - created_at: Date; -} - export interface PoolLinkWarmupSettings { base: number; max: number; @@ -193,20 +171,6 @@ export interface CloudLinkStatus { default_cloud_url: string; } -export interface CloudLinkPendingConnect { - user_code: string; - verification_url: string; - cloud_url: string; - expires_at: Date; - interval: number; -} - -export interface CloudLinkPollResult { - status: PoolLinkCodeStatus; - link?: CloudLink | null; - info?: PoolLinkInstanceInfo | null; -} - export interface CloudLinkMailboxRow { independent_smtp?: boolean; legacy?: boolean; diff --git a/web/src/lib/cloudPlan.ts b/web/src/lib/cloudPlan.ts new file mode 100644 index 000000000..bcd3445ed --- /dev/null +++ b/web/src/lib/cloudPlan.ts @@ -0,0 +1,11 @@ +// Warmbly Cloud is a paid plan for self-hosted instances: a free workspace keeps what it already enrolled and adds nothing. + +import type { PoolLinkPlan } from "@/lib/api/models/app/cloudlink/CloudLink"; + +/** The community server, the only help a self-hosted instance gets. */ +export const COMMUNITY_URL = "https://dc.warmbly.com"; + +/** True when the linked Cloud workspace takes no new mailboxes until it subscribes. Older clouds never say so. */ +export function cloudAddsNeedSubscription(plan: PoolLinkPlan | undefined): boolean { + return plan?.subscription_required === true; +} diff --git a/web/src/lib/plans.ts b/web/src/lib/plans.ts index 88d30dfa9..bf0572d39 100644 --- a/web/src/lib/plans.ts +++ b/web/src/lib/plans.ts @@ -65,7 +65,7 @@ export const PLAN_CATALOG: Record = { partnership: { id: "partnership", label: "Partnership", - description: "The Warmup plan for partners: the premium warmup pool and no mailbox cap, offered by Warmbly.", + description: "The premium warmup pool and no mailbox cap, offered by Warmbly to partners.", priceMonthly: 90, priceAnnual: null, sendsPerDay: 0, From 0885efeb653a1617c19f3e2b3d1b21935b4011b2 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Tue, 3 Nov 2026 16:23:53 +0100 Subject: [PATCH 119/318] feat: give the sync codec registry fixture a distinct worker id and assert report_generation round-trips and is never fabricated from an old writer --- .../codec/mail_transport_registry_test.go | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/internal/infrastructure/codec/mail_transport_registry_test.go b/internal/infrastructure/codec/mail_transport_registry_test.go index 71f802768..85208163d 100644 --- a/internal/infrastructure/codec/mail_transport_registry_test.go +++ b/internal/infrastructure/codec/mail_transport_registry_test.go @@ -175,7 +175,7 @@ func TestMailTransportCodecRegistryCompatibility(t *testing.T) { if url == "" { t.Skip("SR_URL must name an isolated local Schema Registry") } - generation, task, mailbox := uuid.New(), uuid.New(), uuid.New() + generation, worker, task, mailbox := uuid.New(), uuid.New(), uuid.New(), uuid.New() at := time.Now().UTC().Truncate(time.Millisecond) for _, tc := range []struct { name string @@ -188,7 +188,7 @@ func TestMailTransportCodecRegistryCompatibility(t *testing.T) { return v.(*models.WorkerEvent).Body.(*models.AddWorkerEmail).TransportGeneration }}, {"send", models.JobEvent{Type: models.JobEventTypeEmailSent, Body: models.SendEmailResult{TaskID: task, Success: true, SentAt: at, TransportGeneration: generation}}, models.JobEvent{}.Schema(), func() any { return &models.JobEvent{} }, func(v any) uuid.UUID { return v.(*models.JobEvent).Body.(models.SendEmailResult).TransportGeneration }}, - {"sync", models.JobEvent{Type: models.JobEventTypeSyncState, Body: &models.JobEventSyncState{WorkerID: &generation, ReportGeneration: generation, EmailID: mailbox, State: models.SyncState{LastSyncedAt: &at, FolderCoverageObservedAt: &at, TransportGeneration: generation}}}, models.JobEvent{}.Schema(), func() any { return &models.JobEvent{} }, func(v any) uuid.UUID { + {"sync", models.JobEvent{Type: models.JobEventTypeSyncState, Body: &models.JobEventSyncState{WorkerID: &worker, ReportGeneration: generation, EmailID: mailbox, State: models.SyncState{LastSyncedAt: &at, FolderCoverageObservedAt: &at, TransportGeneration: generation}}}, models.JobEvent{}.Schema(), func() any { return &models.JobEvent{} }, func(v any) uuid.UUID { return v.(*models.JobEvent).Body.(*models.JobEventSyncState).State.TransportGeneration }}, {"error", models.JobEvent{Type: models.JobEventTypeEmailServerError, Body: models.EmailErrorEvent{EmailAccountID: mailbox.String(), Operation: models.MailTransportSync, TransportGeneration: generation}}, models.JobEvent{}.Schema(), func() any { return &models.JobEvent{} }, func(v any) uuid.UUID { return v.(*models.JobEvent).Body.(models.EmailErrorEvent).TransportGeneration }}, @@ -223,6 +223,9 @@ func TestMailTransportCodecRegistryCompatibility(t *testing.T) { if tc.name == "sync" && target.(*models.JobEvent).Body.(*models.JobEventSyncState).WorkerID != nil { t.Fatal("old sync payload manufactured a reporting worker") } + if tc.name == "sync" && target.(*models.JobEvent).Body.(*models.JobEventSyncState).ReportGeneration != uuid.Nil { + t.Fatal("old sync payload manufactured a report generation") + } fresh, err := writer.Serialize(t.Context(), topic, tc.value) if err != nil { t.Fatal("FULL_TRANSITIVE registry rejected additive schema", err) @@ -235,10 +238,13 @@ func TestMailTransportCodecRegistryCompatibility(t *testing.T) { t.Fatal("typed wire lost generation") } if tc.name == "sync" { - workerID := target.(*models.JobEvent).Body.(*models.JobEventSyncState).WorkerID - if workerID == nil || *workerID != generation { + report := target.(*models.JobEvent).Body.(*models.JobEventSyncState) + if report.WorkerID == nil || *report.WorkerID != worker { t.Fatal("typed wire lost reporting worker") } + if report.ReportGeneration != generation { + t.Fatal("typed wire lost report generation") + } } id := mailbox if tc.name == "send" { From b612a94e59364adeb1a7343d825a91ebe3a587cd Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Tue, 3 Nov 2026 16:30:21 +0100 Subject: [PATCH 120/318] feat: give the sync codec registry fixture its own report generation and assert folder coverage time survives the fresh round trip --- .../infrastructure/codec/mail_transport_registry_test.go | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/internal/infrastructure/codec/mail_transport_registry_test.go b/internal/infrastructure/codec/mail_transport_registry_test.go index 85208163d..95d9ad822 100644 --- a/internal/infrastructure/codec/mail_transport_registry_test.go +++ b/internal/infrastructure/codec/mail_transport_registry_test.go @@ -175,7 +175,7 @@ func TestMailTransportCodecRegistryCompatibility(t *testing.T) { if url == "" { t.Skip("SR_URL must name an isolated local Schema Registry") } - generation, worker, task, mailbox := uuid.New(), uuid.New(), uuid.New(), uuid.New() + generation, reportGeneration, worker, task, mailbox := uuid.New(), uuid.New(), uuid.New(), uuid.New(), uuid.New() at := time.Now().UTC().Truncate(time.Millisecond) for _, tc := range []struct { name string @@ -188,7 +188,7 @@ func TestMailTransportCodecRegistryCompatibility(t *testing.T) { return v.(*models.WorkerEvent).Body.(*models.AddWorkerEmail).TransportGeneration }}, {"send", models.JobEvent{Type: models.JobEventTypeEmailSent, Body: models.SendEmailResult{TaskID: task, Success: true, SentAt: at, TransportGeneration: generation}}, models.JobEvent{}.Schema(), func() any { return &models.JobEvent{} }, func(v any) uuid.UUID { return v.(*models.JobEvent).Body.(models.SendEmailResult).TransportGeneration }}, - {"sync", models.JobEvent{Type: models.JobEventTypeSyncState, Body: &models.JobEventSyncState{WorkerID: &worker, ReportGeneration: generation, EmailID: mailbox, State: models.SyncState{LastSyncedAt: &at, FolderCoverageObservedAt: &at, TransportGeneration: generation}}}, models.JobEvent{}.Schema(), func() any { return &models.JobEvent{} }, func(v any) uuid.UUID { + {"sync", models.JobEvent{Type: models.JobEventTypeSyncState, Body: &models.JobEventSyncState{WorkerID: &worker, ReportGeneration: reportGeneration, EmailID: mailbox, State: models.SyncState{LastSyncedAt: &at, FolderCoverageObservedAt: &at, TransportGeneration: generation}}}, models.JobEvent{}.Schema(), func() any { return &models.JobEvent{} }, func(v any) uuid.UUID { return v.(*models.JobEvent).Body.(*models.JobEventSyncState).State.TransportGeneration }}, {"error", models.JobEvent{Type: models.JobEventTypeEmailServerError, Body: models.EmailErrorEvent{EmailAccountID: mailbox.String(), Operation: models.MailTransportSync, TransportGeneration: generation}}, models.JobEvent{}.Schema(), func() any { return &models.JobEvent{} }, func(v any) uuid.UUID { return v.(*models.JobEvent).Body.(models.EmailErrorEvent).TransportGeneration }}, @@ -242,9 +242,12 @@ func TestMailTransportCodecRegistryCompatibility(t *testing.T) { if report.WorkerID == nil || *report.WorkerID != worker { t.Fatal("typed wire lost reporting worker") } - if report.ReportGeneration != generation { + if report.ReportGeneration != reportGeneration { t.Fatal("typed wire lost report generation") } + if report.State.FolderCoverageObservedAt == nil || !report.State.FolderCoverageObservedAt.Equal(at) { + t.Fatal("typed wire lost folder coverage observation") + } } id := mailbox if tc.name == "send" { From d8c63c4232c9758e2c06ddda1cdeee738c34f344 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Tue, 3 Nov 2026 16:31:15 +0100 Subject: [PATCH 121/318] feat: accept Gmail watch notifications as Pub/Sub HTTPS push at /api/v1/mailbox-push/gmail, verified by a Google-signed token for GMAIL_PUSH_SERVICE_ACCOUNT, keeping the consumer pull subscription for instances Pub/Sub cannot reach --- cmd/backend/main.go | 1 + docker-compose.yml | 1 + docs/content/docs/api/endpoints.mdx | 1 + .../content/docs/development/architecture.mdx | 2 +- .../docs/development/configuration.mdx | 3 +- docs/content/docs/development/events.mdx | 2 +- .../content/docs/development/mailbox-push.mdx | 40 +++++++--- internal/api/handler/handler.go | 2 + internal/api/handler/mailbox_push.go | 37 +++++++++ internal/api/handler/mailbox_push_test.go | 28 +++++++ internal/api/routes.go | 3 + internal/app/instanceconfig/entries.go | 8 +- internal/app/mailpush/gmail_push.go | 76 +++++++++++++++++++ internal/app/mailpush/gmail_push_test.go | 69 +++++++++++++++++ internal/config/mailbox_push.go | 9 ++- 15 files changed, 266 insertions(+), 16 deletions(-) create mode 100644 internal/app/mailpush/gmail_push.go create mode 100644 internal/app/mailpush/gmail_push_test.go diff --git a/cmd/backend/main.go b/cmd/backend/main.go index b16c149bc..403977277 100644 --- a/cmd/backend/main.go +++ b/cmd/backend/main.go @@ -2613,6 +2613,7 @@ func main() { SlackService: slackService, MailPush: mailPushSettings, MailPushWaker: mailPushWaker, + GmailPush: mailpush.NewGmailPush(), ResearchService: researchService, SkillsService: skillsService, MCPService: mcpService, diff --git a/docker-compose.yml b/docker-compose.yml index 3db9b4696..9b34c8995 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -241,6 +241,7 @@ x-selfhost-env: &selfhost-env SYNC_PUSH_FALLBACK_INTERVAL: ${SYNC_PUSH_FALLBACK_INTERVAL:-} GRAPH_PUSH: ${GRAPH_PUSH:-} GMAIL_PUSH_TOPIC: ${GMAIL_PUSH_TOPIC:-} + GMAIL_PUSH_SERVICE_ACCOUNT: ${GMAIL_PUSH_SERVICE_ACCOUNT:-} GMAIL_PUSH_SUBSCRIPTION: ${GMAIL_PUSH_SUBSCRIPTION:-} GOOGLE_APPLICATION_CREDENTIALS_JSON: ${GOOGLE_APPLICATION_CREDENTIALS_JSON:-} diff --git a/docs/content/docs/api/endpoints.mdx b/docs/content/docs/api/endpoints.mdx index e95d32f0f..d8180ef70 100644 --- a/docs/content/docs/api/endpoints.mdx +++ b/docs/content/docs/api/endpoints.mdx @@ -857,6 +857,7 @@ On the backend's host but outside `/v1`, called by Slack and never by an API key On the backend's host but outside `/v1`, called by Microsoft Graph and never by an API key or a session: +- `POST /api/v1/mailbox-push/gmail` (Gmail watch notifications from a Cloud Pub/Sub push subscription, used when `GMAIL_PUSH_SERVICE_ACCOUNT` is set). Each request must carry a Google-signed bearer token whose audience is this URL and whose sender is that service account, or it gets `401`. The body is capped at 64 KiB. The answer is `204` once the mailbox's worker has been woken or when the body names no mailbox, `503` when the wake could not be sent, so Pub/Sub retries, and `404` when Gmail push is not configured. See [realtime mailbox sync](/development/mailbox-push/) - `POST /api/v1/mailbox-push/graph/:emailId` (Microsoft Graph change and lifecycle notifications for one mailbox, used when `GRAPH_PUSH` is on). A request carrying `validationToken` gets the token echoed as `text/plain`, which is how Graph confirms a new subscription. Otherwise each notification item is accepted only with the client state issued for that mailbox, and items without it are ignored. The body is capped at 1 MiB. The answer is `202` once the mailbox's worker has been woken, also for a body with nothing to act on, and `503` when the wake could not be sent, so Graph retries. See [realtime mailbox sync](/development/mailbox-push/) On the tracking service (the `TRACKING_DOMAIN` host, not the API), also public and rate-limited per source: diff --git a/docs/content/docs/development/architecture.mdx b/docs/content/docs/development/architecture.mdx index 06cedbc10..b0e016532 100644 --- a/docs/content/docs/development/architecture.mdx +++ b/docs/content/docs/development/architecture.mdx @@ -50,7 +50,7 @@ The frontend talks to the backend over REST + JWT, and to the realtime service o Realtime fanout is a separate channel: backend and consumer publish JSON events over Redis pub/sub (or Google Cloud Pub/Sub when `PUBSUB_ENABLED=true`); the Elixir realtime service subscribes and pushes to connected WebSocket clients. -Mailbox sync is pull-based with push as a shortcut. Each worker runs a sync loop per mailbox it holds and polls once a minute. When the provider announces changes, the worker is woken instead: an IMAP mailbox holds its INBOX in `IDLE` on a second connection inside the worker, Microsoft Graph posts change notifications to the backend, and Gmail publishes watch notifications to Cloud Pub/Sub, which the consumer pulls. The backend or consumer then sends `SYNC_WAKE` on the holding worker's `w.` topic and the worker runs its ordinary pass within seconds. The poll stays on as the safety net, every 3 minutes behind `IDLE` and every 10 by default behind a Gmail watch or Graph subscription. See [realtime mailbox sync](/development/mailbox-push/). +Mailbox sync is pull-based with push as a shortcut. Each worker runs a sync loop per mailbox it holds and polls once a minute. When the provider announces changes, the worker is woken instead: an IMAP mailbox holds its INBOX in `IDLE` on a second connection inside the worker, Microsoft Graph posts change notifications to the backend, and Gmail publishes watch notifications to Cloud Pub/Sub, which pushes them to the backend (or, where Pub/Sub cannot reach the backend, the consumer pulls them). The backend or consumer then sends `SYNC_WAKE` on the holding worker's `w.` topic and the worker runs its ordinary pass within seconds. The poll stays on as the safety net, every 3 minutes behind `IDLE` and every 10 by default behind a Gmail watch or Graph subscription. See [realtime mailbox sync](/development/mailbox-push/). Object storage: encrypted email bodies (EMSG format) live in the blob store (filesystem by default, S3-compatible opt-in). diff --git a/docs/content/docs/development/configuration.mdx b/docs/content/docs/development/configuration.mdx index fc49b73c8..88e255a99 100644 --- a/docs/content/docs/development/configuration.mdx +++ b/docs/content/docs/development/configuration.mdx @@ -724,7 +724,8 @@ How quickly a worker sees new mail. Workers poll every mailbox once a minute unl | `SYNC_PUSH_FALLBACK_INTERVAL` | Read by workers. How often a mailbox with a live Gmail watch or Graph subscription is still polled, as a Go duration. Bounded to `2m` to `60m`; an invalid value uses the default | `10m` | yes | | `GRAPH_PUSH` | Read by the backend. `true` has each Outlook and Microsoft 365 mailbox's worker open a Microsoft Graph change-notification subscription posting to `BACKEND_PUBLIC_URL` (else `API_PUBLIC_URL`) plus `/api/v1/mailbox-push/graph/`. Stays off unless that URL is `https` and reachable by Microsoft. Notifications are authenticated with a value derived from `AUTH_SECRET`. Unset again, workers close their subscriptions as mailboxes reload | `false` | yes | | `GMAIL_PUSH_TOPIC` | Read by the backend. The Cloud Pub/Sub topic, `projects//topics/`, each Gmail mailbox's worker watches into. Unset again, workers stop their watches as mailboxes reload | unset | yes | -| `GMAIL_PUSH_SUBSCRIPTION` | Read by the consumer. The pull subscription on that topic, `projects//subscriptions/`, it reads notifications from. Needs no public endpoint | unset | yes | +| `GMAIL_PUSH_SERVICE_ACCOUNT` | Read by the backend. The service account a Pub/Sub push subscription signs its requests with. Set, the backend accepts Gmail notifications at `BACKEND_PUBLIC_URL` (else `API_PUBLIC_URL`) plus `/api/v1/mailbox-push/gmail`, checking each request's Google-signed token. Stays off unless that URL is `https` | unset | yes | +| `GMAIL_PUSH_SUBSCRIPTION` | Read by the consumer. A pull subscription on that topic, `projects//subscriptions/`, it reads notifications from instead of a push subscription. Needs no public endpoint | unset | yes | | `GOOGLE_APPLICATION_CREDENTIALS_JSON` | Read by the consumer for Gmail push: a Google service account key (JSON) holding **Pub/Sub Subscriber** on the subscription. Unset uses Application Default Credentials. The backend reads the same variable for Cloud Tasks callbacks when `TASKS_PROVIDER=gcloud` | unset | yes | ## Integrations diff --git a/docs/content/docs/development/events.mdx b/docs/content/docs/development/events.mdx index a06ff717d..24d831561 100644 --- a/docs/content/docs/development/events.mdx +++ b/docs/content/docs/development/events.mdx @@ -74,7 +74,7 @@ The backend's worker reconciler ships `ADD_EMAIL` at once for a mailbox with no `MAILBOX_IDENTITY` asks the worker holding a mailbox to read its send-as addresses, and one signature, from the provider. It answers on a Redis channel named by the request's `process_id` rather than on the worker-events topic, the same round trip `EMAIL_VALIDATION` uses, because the caller is an HTTP request waiting for it. The control plane makes this call itself in exactly one place, the OAuth handshake, where the token came from the consent the customer just completed and the mailbox has no worker yet. -`SYNC_WAKE` asks the worker holding a mailbox to run its next sync pass now (`models.SyncWake`: `user_id`, `email_id`, and `renew`). The backend sends it when Microsoft Graph posts a change notification and the consumer when a Gmail watch notification arrives on Pub/Sub; see [realtime mailbox sync](/development/mailbox-push/). It is keyed by the mailbox and answers with nothing. The worker waits 2 seconds so one pass covers a burst, never cuts short a backoff after a failed pass, and ignores a wake for a mailbox it does not hold, since that mailbox's new worker polls it. `renew` also asks the worker to renew or reopen the mailbox's push channel, which a Graph `reauthorizationRequired` or `subscriptionRemoved` lifecycle event sets. Repeat wakes for one mailbox inside 2 seconds are dropped before publishing. It goes only to workers whose heartbeat reports `sync_wake_protocol` 1, so a worker from an earlier release never receives a command type it does not know and keeps polling. +`SYNC_WAKE` asks the worker holding a mailbox to run its next sync pass now (`models.SyncWake`: `user_id`, `email_id`, and `renew`). The backend sends it when Microsoft Graph posts a change notification and when Pub/Sub pushes a Gmail watch notification to it, and the consumer when it pulls one instead; see [realtime mailbox sync](/development/mailbox-push/). It is keyed by the mailbox and answers with nothing. The worker waits 2 seconds so one pass covers a burst, never cuts short a backoff after a failed pass, and ignores a wake for a mailbox it does not hold, since that mailbox's new worker polls it. `renew` also asks the worker to renew or reopen the mailbox's push channel, which a Graph `reauthorizationRequired` or `subscriptionRemoved` lifecycle event sets. Repeat wakes for one mailbox inside 2 seconds are dropped before publishing. It goes only to workers whose heartbeat reports `sync_wake_protocol` 1, so a worker from an earlier release never receives a command type it does not know and keeps polling. ## Worker results diff --git a/docs/content/docs/development/mailbox-push.mdx b/docs/content/docs/development/mailbox-push.mdx index 830ed4592..19c12e450 100644 --- a/docs/content/docs/development/mailbox-push.mdx +++ b/docs/content/docs/development/mailbox-push.mdx @@ -11,17 +11,17 @@ The worker that holds a mailbox syncs it on a timer. When the mailbox's provider |---|---|---|---| | IMAP and SMTP | `IDLE` on INBOX, on a second connection | every 3 minutes, for the other folders | on; `IMAP_IDLE=false` turns it off | | Microsoft 365 and Outlook | Microsoft Graph change notifications | `SYNC_PUSH_FALLBACK_INTERVAL` (10 minutes) | off until `GRAPH_PUSH=true` and a public HTTPS backend URL | -| Gmail and Google Workspace | Gmail `users.watch` into Cloud Pub/Sub | `SYNC_PUSH_FALLBACK_INTERVAL` (10 minutes) | off until `GMAIL_PUSH_TOPIC` and `GMAIL_PUSH_SUBSCRIPTION` are set | +| Gmail and Google Workspace | Gmail `users.watch` into Cloud Pub/Sub | `SYNC_PUSH_FALLBACK_INTERVAL` (10 minutes) | off until `GMAIL_PUSH_TOPIC` and either `GMAIL_PUSH_SERVICE_ACCOUNT` (push) or `GMAIL_PUSH_SUBSCRIPTION` (pull) are set | A mailbox without a live signal is polled every minute, as before. That covers an IMAP server without `IDLE`, a Gmail or Outlook mailbox on an instance that has not configured push, and any mailbox whose channel the provider refused. A self-host therefore gets IMAP `IDLE` after an upgrade and nothing else changes. Gmail and Microsoft push are opt-in because each needs something only the operator can set up: a Google Cloud topic, or a backend Microsoft can reach. Every variable is listed in the [configuration reference](/development/configuration/#mailbox-sync). -Each variable is read by one service: `GRAPH_PUSH` and `GMAIL_PUSH_TOPIC` by the backend, `GMAIL_PUSH_SUBSCRIPTION` and `GOOGLE_APPLICATION_CREDENTIALS_JSON` by the consumer, `IMAP_IDLE` and `SYNC_PUSH_FALLBACK_INTERVAL` by the workers. With the installer's Compose file every service reads `.env`. A joined worker node receives `IMAP_IDLE` and `SYNC_PUSH_FALLBACK_INTERVAL` from the control plane's own environment. A joined consumer is not handed the Gmail settings, because they carry a Google credential, so set those in its `/etc/warmbly/node.local.env` ([settings the control plane cannot know](/development/configuration/#settings-the-control-plane-cannot-know)). +Each variable is read by one service: `GRAPH_PUSH`, `GMAIL_PUSH_TOPIC` and `GMAIL_PUSH_SERVICE_ACCOUNT` by the backend, `GMAIL_PUSH_SUBSCRIPTION` and `GOOGLE_APPLICATION_CREDENTIALS_JSON` by the consumer, `IMAP_IDLE` and `SYNC_PUSH_FALLBACK_INTERVAL` by the workers. With the installer's Compose file every service reads `.env`. A joined worker node receives `IMAP_IDLE` and `SYNC_PUSH_FALLBACK_INTERVAL` from the control plane's own environment. A joined consumer is not handed the Gmail settings, because they carry a Google credential, so set those in its `/etc/warmbly/node.local.env` ([settings the control plane cannot know](/development/configuration/#settings-the-control-plane-cannot-know)). ## How a wake reaches the worker -1. The provider signals a change. Graph posts to the backend, Gmail publishes to Pub/Sub where the consumer pulls it, and an IMAP `IDLE` session runs inside the worker itself. +1. The provider signals a change. Graph posts to the backend, Gmail publishes to Pub/Sub, which pushes to the backend or is pulled by the consumer, and an IMAP `IDLE` session runs inside the worker itself. 2. The backend or consumer finds the worker holding the mailbox and sends it a [`SYNC_WAKE`](/development/events/#worker-commands) command on that worker's `w.` topic. Repeat wakes for one mailbox within 2 seconds are dropped. That check uses Redis, and when Redis is unavailable every wake is sent. 3. The worker waits 2 seconds so one pass covers a burst of changes, then runs the ordinary sync pass: Gmail history, Graph delta or IMAP CONDSTORE. 4. New mail the pass stores reaches the dashboard through the consumer, which drains stored arrivals in batches of 32 and starts the next batch at once while full ones are waiting, rather than pausing between them. @@ -68,20 +68,36 @@ How the channel behaves: ## Gmail and Google Workspace -With push on, the worker holding each Gmail mailbox calls `users.watch` daily (a watch lasts 7 days), and Gmail publishes a small notification to a Cloud Pub/Sub topic whenever the mailbox changes. The consumer reads those through a pull subscription, so no public endpoint is involved. Mailboxes connected with an app password are IMAP mailboxes and use `IDLE` instead. +With push on, the worker holding each Gmail mailbox calls `users.watch` daily (a watch lasts 7 days), and Gmail publishes a small notification to a Cloud Pub/Sub topic whenever the mailbox changes. The notification carries only the mailbox address and a history id, never mail. Mailboxes connected with an app password are IMAP mailboxes and use `IDLE` instead. + +Pub/Sub delivers notifications one of two ways: + +- **Push to the backend** (use this when the backend has a public HTTPS URL). Pub/Sub POSTs each notification to `/api/v1/mailbox-push/gmail`. Every request carries a token Google signs for a service account you choose; the backend accepts it only when Google's signature checks out, the audience is that URL and the sender is `GMAIL_PUSH_SERVICE_ACCOUNT`. It answers 204 once the worker is woken and 503 when it cannot be, and Pub/Sub retries with backoff until it gets a 2xx. +- **Pull from the consumer** (for an instance Pub/Sub cannot reach). The consumer holds a streaming connection to a pull subscription and reads notifications from it. + +Both end the same way: the mailbox's worker is sent `SYNC_WAKE` and runs its usual Gmail sync. Only one of the two should be set up for a topic. Set up, once per instance, in the Google Cloud project that holds the Gmail OAuth client (`BOX_GOOGLE_CLIENT_ID`). Gmail only accepts a topic in the project making the watch call, so a [whole-domain grant's](/development/whole-domain-connect/) delegation service account must live in the same project: 1. Under **APIs & Services > Library**, enable the **Cloud Pub/Sub API**. 2. Under **Pub/Sub > Topics**, create a topic, for example `gmail-push`. Its full name is `projects//topics/gmail-push`. 3. On the topic's **Permissions**, grant the **Pub/Sub Publisher** role to `[EMAIL]`, Gmail's push service account. An organization policy that restricts sharing to your own domain (**Domain restricted sharing**) refuses this grant; ask an Organization Policy Administrator for an exception on this project. -4. Create a **pull** subscription on the topic, for example `warmbly-consumer`. Its full name is `projects//subscriptions/warmbly-consumer`. -5. Give the identity the consumer runs as the **Pub/Sub Subscriber** role on that subscription. That is either a service account whose JSON key you pass as `GOOGLE_APPLICATION_CREDENTIALS_JSON`, or the Application Default Credentials of the machine the consumer runs on. +4. Create the subscription: + - **Push:** create a service account for signing, for example `gmail-push-signer`, and a **push** subscription on the topic with endpoint `/api/v1/mailbox-push/gmail`, **Enable authentication** on, that service account, and the audience left empty (it defaults to the endpoint). The Pub/Sub service agent needs **Service Account Token Creator** on that account, which the console offers to grant. + - **Pull:** create a **pull** subscription, for example `warmbly-consumer`, and give the identity the consumer runs as the **Pub/Sub Subscriber** role on it. That is either a service account whose JSON key you pass as `GOOGLE_APPLICATION_CREDENTIALS_JSON`, or the Application Default Credentials of the machine the consumer runs on. -Then set: +Then set, for push: ```bash -# backend: workers are told to watch into this topic +# backend: workers watch into this topic, and push requests must be signed by this account +GMAIL_PUSH_TOPIC=projects//topics/gmail-push +GMAIL_PUSH_SERVICE_ACCOUNT=gmail-push-signer@.iam.gserviceaccount.com +``` + +or, for pull: + +```bash +# backend GMAIL_PUSH_TOPIC=projects//topics/gmail-push # consumer: where it reads notifications, and as whom @@ -89,11 +105,11 @@ GMAIL_PUSH_SUBSCRIPTION=projects//subscriptions/warmbly-consumer GOOGLE_APPLICATION_CREDENTIALS_JSON='{"type":"service_account",...}' # optional with ADC ``` -No new Google scope is needed: `users.watch` accepts the `gmail.modify` grant mailboxes already have. A notification names only the mailbox address, so the consumer wakes every watched Gmail mailbox with that address and the pass works out what changed. +No new Google scope is needed: `users.watch` accepts the `gmail.modify` grant mailboxes already have. A notification names only the mailbox address, so every watched Gmail mailbox with that address is woken and the pass works out what changed. -Pub/Sub is billed by Google by volume (a list price of about $40 per TiB, with a 1 KB minimum per message). Each notification is one small message per mailbox change, so this stays small; check current pricing. The Gmail API quota per message synced is unchanged, and most of the once-a-minute history polling goes away. +Pub/Sub is billed by Google by volume (a list price of about $40 per TiB, with a 1 KB minimum per message). Push bills each delivery separately, so it costs somewhat more than pull at the same volume; both stay small next to the Gmail API work they replace. The Gmail API quota per message synced is unchanged, and most of the once-a-minute history polling goes away. -A consumer that loses its Pub/Sub connection restarts the subscriber after 30 seconds. Unacknowledged notifications stay in the subscription and are delivered when it reconnects. +With push, a backend that is down or slow is retried by Pub/Sub, which keeps unacknowledged notifications for up to 7 days. With pull, a consumer that loses its Pub/Sub connection restarts the subscriber after 30 seconds. ## Turning push off @@ -117,6 +133,8 @@ Migration `000339` adds `fleet_nodes.sync_wake_protocol` (default `0`) and the ` | Graph subscriptions are never created | Microsoft cannot reach the URL, or the proxy in front of the backend does not forward `/api/v1/mailbox-push/`. Workers retry every 30 minutes and log the refusal at debug level | | Gmail watch fails with `Invalid topicName` | The topic is in a different project from the OAuth client or delegation service account making the call. Create it in that project | | Gmail watch fails with a permission error | Gmail's push service account `[EMAIL]` lacks **Pub/Sub Publisher** on the topic, often because domain restricted sharing refused the grant | +| Pub/Sub shows push deliveries failing with `401` | The subscription signs with a different service account than `GMAIL_PUSH_SERVICE_ACCOUNT`, authentication is off, or its audience was set to something other than the endpoint URL | +| Pub/Sub shows push deliveries failing with `404` | `GMAIL_PUSH_SERVICE_ACCOUNT` is unset on the backend, or `BACKEND_PUBLIC_URL` is not `https` | | Consumer logs `Gmail push subscriber stopped` | `GMAIL_PUSH_SUBSCRIPTION` is not `projects//subscriptions/`, the subscription does not exist, or the consumer's identity lacks **Pub/Sub Subscriber** on it | | An IMAP mailbox stays on the one-minute poll | Its server does not offer `IDLE`, refuses a second session for the account, or `IMAP_IDLE=false` is set on the worker | | Mailboxes on one worker never react to push | The worker predates this release, so it reports `sync_wake_protocol` 0. Update it | diff --git a/internal/api/handler/handler.go b/internal/api/handler/handler.go index f7a85a5a2..de68f42a3 100644 --- a/internal/api/handler/handler.go +++ b/internal/api/handler/handler.go @@ -315,6 +315,8 @@ type Handler struct { // wakes the worker holding the mailbox. Nil leaves every mailbox polling. MailPush *mailpush.Settings MailPushWaker *mailpush.Waker + // GmailPush authenticates Pub/Sub push requests; nil when Gmail push is not delivered here. + GmailPush *mailpush.GmailPush // HubSpot runs a workspace's CRM on HubSpot when it chooses so. Nil on // processes built without it. diff --git a/internal/api/handler/mailbox_push.go b/internal/api/handler/mailbox_push.go index 29b4910be..1d045f72b 100644 --- a/internal/api/handler/mailbox_push.go +++ b/internal/api/handler/mailbox_push.go @@ -15,6 +15,43 @@ import ( // graphPostLimit bounds one notification POST; Graph batches but never near this. const graphPostLimit = 1 << 20 +// gmailPushLimit bounds one Pub/Sub push body; a Gmail notification is under a kilobyte. +const gmailPushLimit = 64 << 10 + +// MailboxPushGmail โ€” POST /api/v1/mailbox-push/gmail +// +// A Pub/Sub push subscription delivers Gmail watch notifications here. A 2xx +// acknowledges the message; anything else makes Pub/Sub retry it with backoff. +func (h *Handler) MailboxPushGmail(c *gin.Context) { + if h.GmailPush == nil || h.MailPushWaker == nil { + c.Status(http.StatusNotFound) + return + } + if err := h.GmailPush.Verify(c.Request.Context(), c.GetHeader("Authorization")); err != nil { + c.Status(http.StatusUnauthorized) + return + } + body, err := io.ReadAll(io.LimitReader(c.Request.Body, gmailPushLimit)) + if err != nil { + c.Status(http.StatusBadRequest) + return + } + address, ok := mailpush.GmailPushAddress(body) + if !ok { + // Nothing a retry would fix; acknowledge it. + c.Status(http.StatusNoContent) + return + } + ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Second) + defer cancel() + if err := h.MailPushWaker.WakeGmail(ctx, address); err != nil { + log.Warn().Err(err).Msg("gmail notification could not wake the mailbox; Pub/Sub will retry") + c.Status(http.StatusServiceUnavailable) + return + } + c.Status(http.StatusNoContent) +} + // MailboxPushGraph โ€” POST /api/v1/mailbox-push/graph/:emailId // // Microsoft Graph posts a mailbox's change notifications here. Each item is diff --git a/internal/api/handler/mailbox_push_test.go b/internal/api/handler/mailbox_push_test.go index 63f322b80..b7fe036e3 100644 --- a/internal/api/handler/mailbox_push_test.go +++ b/internal/api/handler/mailbox_push_test.go @@ -61,3 +61,31 @@ func TestMailboxPushGraph(t *testing.T) { t.Fatalf("an authentic lifecycle event answered %d, wakes %+v", rec.Code, wakes.got) } } + +func TestMailboxPushGmailRefusesUnsignedRequests(t *testing.T) { + gin.SetMode(gin.TestMode) + t.Setenv("BACKEND_PUBLIC_URL", "https://api.example.com") + t.Setenv("GMAIL_PUSH_SERVICE_ACCOUNT", "push@p.iam.gserviceaccount.com") + wakes := &pushWakes{} + post := func(h *Handler, auth string) int { + r := gin.New() + r.POST("/api/v1/mailbox-push/gmail", h.MailboxPushGmail) + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/v1/mailbox-push/gmail", strings.NewReader(`{"message":{"data":"e30="}}`)) + req.Header.Set("Authorization", auth) + r.ServeHTTP(rec, req) + return rec.Code + } + if code := post(&Handler{MailPushWaker: mailpush.NewWaker(pushTargets{}, wakes, nil)}, "Bearer x"); code != http.StatusNotFound { + t.Fatalf("unconfigured endpoint answered %d", code) + } + h := &Handler{GmailPush: mailpush.NewGmailPush(), MailPushWaker: mailpush.NewWaker(pushTargets{}, wakes, nil)} + for _, auth := range []string{"", "Bearer not-a-jwt", "Basic abc"} { + if code := post(h, auth); code != http.StatusUnauthorized { + t.Fatalf("authorization %q answered %d", auth, code) + } + } + if len(wakes.got) != 0 { + t.Fatal("an unsigned request woke a mailbox") + } +} diff --git a/internal/api/routes.go b/internal/api/routes.go index 09a4ee1a6..261c5fc1e 100644 --- a/internal/api/routes.go +++ b/internal/api/routes.go @@ -83,6 +83,9 @@ func Run( // Microsoft Graph change notifications, one URL per mailbox, each item // authenticated by the client state issued for that mailbox. r.POST("/api/v1/mailbox-push/graph/:emailId", h.MailboxPushGraph) + // Gmail watch notifications from a Pub/Sub push subscription, each request + // carrying a Google-signed token for the configured service account. + r.POST("/api/v1/mailbox-push/gmail", h.MailboxPushGmail) r.POST("/api/v1/integrations/slack/interactivity", h.SlackInteractivity) // HubSpot app webhooks: one URL for every portal, authenticated by the // X-HubSpot-Signature-v3 HMAC over the client secret. diff --git a/internal/app/instanceconfig/entries.go b/internal/app/instanceconfig/entries.go index 08888a772..84c1f1c26 100644 --- a/internal/app/instanceconfig/entries.go +++ b/internal/app/instanceconfig/entries.go @@ -832,9 +832,15 @@ var table = []Entry{ DocsAnchor: docsMailboxSync, Resolve: envValue("GMAIL_PUSH_TOPIC"), }, + { + Key: "GMAIL_PUSH_SERVICE_ACCOUNT", Group: GroupWorkers, RuntimeChangeable: ChangeBootOnly, + Effect: "The service account a Pub/Sub push subscription signs with. Set, the backend accepts Gmail watch notifications at its public HTTPS URL.", + DocsAnchor: docsMailboxSync, + Resolve: envValue("GMAIL_PUSH_SERVICE_ACCOUNT"), + }, { Key: "GMAIL_PUSH_SUBSCRIPTION", Group: GroupWorkers, RuntimeChangeable: ChangeBootOnly, - Effect: "The pull subscription the consumer reads Gmail watch notifications from.", + Effect: "A pull subscription the consumer reads Gmail watch notifications from, for an instance Pub/Sub cannot push to.", DocsAnchor: docsMailboxSync, Resolve: envValue("GMAIL_PUSH_SUBSCRIPTION"), }, diff --git a/internal/app/mailpush/gmail_push.go b/internal/app/mailpush/gmail_push.go new file mode 100644 index 000000000..397779bc0 --- /dev/null +++ b/internal/app/mailpush/gmail_push.go @@ -0,0 +1,76 @@ +package mailpush + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "strings" + + "github.com/warmbly/warmbly/internal/config" + "google.golang.org/api/idtoken" +) + +// GmailPushPath is the backend route a Pub/Sub push subscription posts Gmail watch notifications to. +const GmailPushPath = "/api/v1/mailbox-push/gmail" + +var errGmailPushToken = errors.New("gmail push: request not signed by the configured service account") + +// googleIssuers are the issuers Google signs Pub/Sub push tokens as. +var googleIssuers = map[string]bool{"accounts.google.com": true, "https://accounts.google.com": true} + +type tokenValidator func(ctx context.Context, token, audience string) (*idtoken.Payload, error) + +// GmailPush authenticates Pub/Sub push requests carrying Gmail watch notifications. +type GmailPush struct { + audience string + account string + validate tokenValidator +} + +// NewGmailPush is nil unless GMAIL_PUSH_SERVICE_ACCOUNT names the account the +// push subscription signs with and the backend has a public HTTPS URL. +func NewGmailPush() *GmailPush { + account := config.GmailPushServiceAccount() + base := config.BackendPublicURL() + if account == "" || !strings.HasPrefix(base, "https://") { + return nil + } + return &GmailPush{audience: base + GmailPushPath, account: account, validate: idtoken.Validate} +} + +// Verify checks the push request's bearer token: signed by Google, for this +// endpoint, from the configured service account, with a verified email. +func (g *GmailPush) Verify(ctx context.Context, authorization string) error { + token, ok := strings.CutPrefix(authorization, "Bearer ") + if !ok || token == "" { + return errGmailPushToken + } + payload, err := g.validate(ctx, token, g.audience) + if err != nil { + return errGmailPushToken + } + email, _ := payload.Claims["email"].(string) + verified, _ := payload.Claims["email_verified"].(bool) + if !googleIssuers[payload.Issuer] || !verified || !strings.EqualFold(email, g.account) { + return errGmailPushToken + } + return nil +} + +// GmailPushAddress reads the mailbox address from a Pub/Sub push body. +func GmailPushAddress(body []byte) (string, bool) { + var envelope struct { + Message struct { + Data string `json:"data"` + } `json:"message"` + } + if json.Unmarshal(body, &envelope) != nil { + return "", false + } + data, err := base64.StdEncoding.DecodeString(envelope.Message.Data) + if err != nil { + return "", false + } + return GmailAddress(data) +} diff --git a/internal/app/mailpush/gmail_push_test.go b/internal/app/mailpush/gmail_push_test.go new file mode 100644 index 000000000..ef792e32e --- /dev/null +++ b/internal/app/mailpush/gmail_push_test.go @@ -0,0 +1,69 @@ +package mailpush + +import ( + "context" + "encoding/base64" + "errors" + "testing" + + "google.golang.org/api/idtoken" +) + +// fakeGmailPush is a GmailPush that accepts tokens without contacting Google. +func fakeGmailPush(claims map[string]any, issuer string) *GmailPush { + return &GmailPush{audience: "https://api.example.com" + GmailPushPath, account: "push@p.iam.gserviceaccount.com", + validate: func(_ context.Context, token, audience string) (*idtoken.Payload, error) { + if token != "good" || audience != "https://api.example.com"+GmailPushPath { + return nil, errors.New("bad token") + } + return &idtoken.Payload{Issuer: issuer, Claims: claims}, nil + }} +} + +func TestGmailPushVerify(t *testing.T) { + valid := map[string]any{"email": "push@p.iam.gserviceaccount.com", "email_verified": true} + for _, tc := range []struct { + name string + header string + claims map[string]any + issuer string + ok bool + }{ + {"signed by the push account", "Bearer good", valid, "https://accounts.google.com", true}, + {"no bearer", "good", valid, "https://accounts.google.com", false}, + {"invalid signature", "Bearer forged", valid, "https://accounts.google.com", false}, + {"another account", "Bearer good", map[string]any{"email": "other@p.iam.gserviceaccount.com", "email_verified": true}, "accounts.google.com", false}, + {"unverified email", "Bearer good", map[string]any{"email": "push@p.iam.gserviceaccount.com"}, "accounts.google.com", false}, + {"foreign issuer", "Bearer good", valid, "https://evil.example", false}, + } { + t.Run(tc.name, func(t *testing.T) { + err := fakeGmailPush(tc.claims, tc.issuer).Verify(t.Context(), tc.header) + if (err == nil) != tc.ok { + t.Fatalf("Verify = %v, want ok=%v", err, tc.ok) + } + }) + } +} + +func TestGmailPushAddress(t *testing.T) { + data := base64.StdEncoding.EncodeToString([]byte(`{"emailAddress":"a@b.com","historyId":"9"}`)) + if got, ok := GmailPushAddress([]byte(`{"message":{"data":"` + data + `","messageId":"1"},"subscription":"s"}`)); !ok || got != "a@b.com" { + t.Fatalf("got %q %v", got, ok) + } + if _, ok := GmailPushAddress([]byte(`{"message":{"data":"!!"}}`)); ok { + t.Fatal("undecodable data parsed") + } +} + +func TestGmailPushNeedsAccountAndHTTPS(t *testing.T) { + t.Setenv("BACKEND_PUBLIC_URL", "https://api.example.com") + t.Setenv("GMAIL_PUSH_SERVICE_ACCOUNT", "") + if NewGmailPush() != nil { + t.Fatal("push accepted without a service account to check") + } + t.Setenv("GMAIL_PUSH_SERVICE_ACCOUNT", "push@p.iam.gserviceaccount.com") + t.Setenv("BACKEND_PUBLIC_URL", "http://localhost:8080") + if NewGmailPush() != nil { + t.Fatal("Pub/Sub pushes only to HTTPS") + } +} diff --git a/internal/config/mailbox_push.go b/internal/config/mailbox_push.go index 2563c9b0a..c4de89576 100644 --- a/internal/config/mailbox_push.go +++ b/internal/config/mailbox_push.go @@ -48,7 +48,14 @@ func GmailPushTopic() string { return strings.TrimSpace(os.Getenv("GMAIL_PUSH_TOPIC")) } -// GmailPushSubscription is the pull subscription on GmailPushTopic the consumer reads. +// GmailPushServiceAccount is the service account a Pub/Sub push subscription +// signs its requests to the backend with; set, the backend accepts Gmail push. +func GmailPushServiceAccount() string { + return strings.TrimSpace(os.Getenv("GMAIL_PUSH_SERVICE_ACCOUNT")) +} + +// GmailPushSubscription is the pull subscription on GmailPushTopic the consumer +// reads, for an instance Pub/Sub cannot push to. func GmailPushSubscription() string { return strings.TrimSpace(os.Getenv("GMAIL_PUSH_SUBSCRIPTION")) } From 20a715969e265a2460bf92d11034ecbc88452e10 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Tue, 3 Nov 2026 16:34:35 +0100 Subject: [PATCH 122/318] feat: validate published static asset release inputs and document custom domain rollback behavior --- .github/scripts/pages-static-assets.mjs | 3 ++- .github/scripts/pages-static-assets.test.mjs | 9 +++++++++ .github/workflows/static-assets.yml | 8 ++++++++ docs/content/docs/development/configuration.mdx | 14 ++++++++++---- 4 files changed, 29 insertions(+), 5 deletions(-) diff --git a/.github/scripts/pages-static-assets.mjs b/.github/scripts/pages-static-assets.mjs index ca5ea6867..b5d1de4b4 100644 --- a/.github/scripts/pages-static-assets.mjs +++ b/.github/scripts/pages-static-assets.mjs @@ -42,7 +42,8 @@ export function prepareStaticAssets({ target, sourceRoot, destination, sourceSha } } check(output); - if (!existsSync(join(output, "index.html")) || !existsSync(join(output, "_headers"))) throw new Error("Frontend index and response headers required"); + const isRegularFile = (name) => existsSync(join(output, name)) && lstatSync(join(output, name)).isFile(); + if (!isRegularFile("index.html") || !isRegularFile("_headers")) throw new Error("Frontend index and response headers required"); if (existsSync(join(output, "_worker.js")) || existsSync(join(output, "_routes.json"))) throw new Error("Only static artifacts are supported"); mkdirSync(dest, { recursive: true }); cpSync(output, join(dest, "assets"), { recursive: true }); diff --git a/.github/scripts/pages-static-assets.test.mjs b/.github/scripts/pages-static-assets.test.mjs index e96988949..1e10a23be 100644 --- a/.github/scripts/pages-static-assets.test.mjs +++ b/.github/scripts/pages-static-assets.test.mjs @@ -75,3 +75,12 @@ test("changed admin redirect behavior requires explicit review", () => { assert.throws(() => prepareStaticAssets({ target, sourceRoot: root, destination, sourceSha: sha, release: "v0.6.74" })); }); }); + +test("requires regular frontend entrypoint and response header files", () => { + for (const name of ["index.html", "_headers"]) fixture("web", ({ root, target, output, destination }) => { + rmSync(join(output, name)); + mkdirSync(join(output, name)); + assert.throws(() => prepareStaticAssets({ target, sourceRoot: root, destination, sourceSha: sha, release: "v0.6.74" }), /Frontend index and response headers required/); + assert.equal(existsSync(destination), false); + }); +}); diff --git a/.github/workflows/static-assets.yml b/.github/workflows/static-assets.yml index 616403559..37833c8b9 100644 --- a/.github/workflows/static-assets.yml +++ b/.github/workflows/static-assets.yml @@ -61,11 +61,19 @@ jobs: fetch-depth: 0 persist-credentials: false - name: Pin the existing release source + env: + GH_TOKEN: ${{ github.token }} run: | [[ "$RELEASE_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] [[ "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]] + gh release view "$RELEASE_TAG" --json isDraft,isPrerelease,publishedAt \ + | jq -e '.isDraft == false and .isPrerelease == false and .publishedAt != null' >/dev/null test "$(git rev-parse "refs/tags/$RELEASE_TAG^{commit}")" = "$SOURCE_SHA" git merge-base --is-ancestor "$SOURCE_SHA" origin/main + if ! git cat-file -e "$SOURCE_SHA:.github/scripts/pages-production-config.mjs"; then + echo '::error::Release does not support public Pages configuration import; select a supported release.' + exit 1 + fi git worktree add --detach "$RUNNER_TEMP/frontend-source" "$SOURCE_SHA" - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: diff --git a/docs/content/docs/development/configuration.mdx b/docs/content/docs/development/configuration.mdx index b1a0d7d19..abe9dc5a3 100644 --- a/docs/content/docs/development/configuration.mdx +++ b/docs/content/docs/development/configuration.mdx @@ -693,7 +693,9 @@ Self-hosted containers and their configuration are unchanged. For example, a staging entry is `[{"project":"dashboard-project","worker":"dashboard-assets-stage","domains":["assets-stage.example.com"]}]`. -No wildcard domain is accepted. Empty domains publish an unattached artifact; +No wildcard domain is accepted. Empty domains do not attach a new domain or +detach a custom domain attached by an earlier deployment. Remove an existing +binding in the Worker's **Settings > Domains & Routes** page when needed. `workers.dev` and preview URLs stay disabled. The publisher preserves `_headers` and the dashboard's `_redirects`. For admin it replaces the Pages catch-all rewrite with the platform's SPA fallback and keeps the other @@ -701,7 +703,9 @@ frontends' 404 behavior. It rejects symlinks, Pages Functions, files above 25 Mi and artifacts exceeding the Free plan's 20,000-file limit. The manual **Publish released static assets** workflow rebuilds an existing -stable release using its tag and exact commit SHA. It does not create a tag, +published stable release using its tag and exact commit SHA. It supports +v0.6.28 and later releases containing the public Pages configuration importer; +older tags fail the source check before publishing. It does not create a tag, release, application deployment or worker-fleet update. It uses current public Pages configuration, so a rebuilt artifact can differ from the earlier build if that configuration changed. The deployed artifact includes @@ -713,8 +717,10 @@ account's current limits and pricing before enabling any other Workers feature. Before moving a production hostname, verify the staging site's certificate, TLS policy, root and nested routes, assets, response headers and redirects. Archive its existing Pages association and DNS. If verification fails after a -cutover, restore that association and DNS, or deploy the saved asset artifact to -the same Worker name. Keep the Pages deployment and its configuration available +cutover, remove the Worker's custom-domain binding and restore that Pages +association and DNS. Redeploying the saved asset artifact to the same Worker +reapplies its custom-domain routes; it does not restore Pages or DNS. Keep the +Pages deployment and its configuration available through the rollback window. A source merge alone does not attach a domain. ### Whole-domain connects From 03cd541c6289cd80da85c636ed315bcf30f128f4 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Tue, 3 Nov 2026 16:59:57 +0100 Subject: [PATCH 123/318] feat: pace SMTP sessions per server and worker address after a 421, a 454 sign-in refusal or a dropped STARTTLS, hold due sends without contacting the server, and walk those sends back without spending a lead attempt or raising a mailbox error --- docs/content/docs/guides/mailboxes.mdx | 2 + .../campaign_loading_deferral_test.go | 24 +++ internal/app/consumer/event_send_result.go | 20 ++- internal/app/worker/event_send_email.go | 5 + internal/client/smtpimap/smtp/client.go | 7 +- internal/client/smtpimap/smtp/host_pace.go | 145 ++++++++++++++++++ .../client/smtpimap/smtp/host_pace_test.go | 145 ++++++++++++++++++ internal/errx/email.go | 4 + internal/errx/send_failure.go | 3 + internal/models/warmup_send_failure.go | 6 +- 10 files changed, 356 insertions(+), 5 deletions(-) create mode 100644 internal/client/smtpimap/smtp/host_pace.go create mode 100644 internal/client/smtpimap/smtp/host_pace_test.go diff --git a/docs/content/docs/guides/mailboxes.mdx b/docs/content/docs/guides/mailboxes.mdx index 14e4f5db4..d010c6c83 100644 --- a/docs/content/docs/guides/mailboxes.mdx +++ b/docs/content/docs/guides/mailboxes.mdx @@ -149,6 +149,8 @@ When a mail server goes down or stops answering, the mailbox is not deactivated. The same holds for a server that answers but refuses what Warmbly asked. The drawer shows one row carrying the server's own wording, not one row per retry, and it clears on the first pass that completes. +Hosting providers that serve many mailboxes from one server (shared hosting and email resellers) often limit how many connections or sign-ins they accept from one address. Every mailbox on a worker sends from that worker's address, so when such a server answers with `421`, refuses sign-in with `454`, or drops the encryption handshake, Warmbly treats it as a limit on its own address rather than a fault in the mailbox. That worker stops opening sessions to that server for 30 seconds, doubling on each further refusal up to 10 minutes, then spaces new sessions at least 3 seconds apart for the next 30 minutes. Sends that come due meanwhile are held without contacting the server and retried on their own. A held send, or one refused before any recipient was offered, costs the lead none of its send attempts, and a held send raises no mailbox error. The first refusal still shows **Retrying** with a message saying the server is limiting Warmbly's address, and it clears on the next send from that mailbox that goes through. Nothing needs to change on the mailbox. This spacing does not raise any provider limit, and a server that keeps refusing keeps sends held. + With two-factor authentication on, generate an app password in your provider's security settings and use that. Warmbly signs in using LOGIN or PLAIN over an established TLS connection, preferring LOGIN when both are offered. Hosted production requires one of these password methods or a supported OAuth connection. Self-hosted and development instances also support CRAM-MD5 when the server offers neither LOGIN nor PLAIN. A server with no supported method is refused with the methods it offers, so you can check whether another submission host or port is needed. diff --git a/internal/app/consumer/campaign_loading_deferral_test.go b/internal/app/consumer/campaign_loading_deferral_test.go index 28d9717b1..63171ad28 100644 --- a/internal/app/consumer/campaign_loading_deferral_test.go +++ b/internal/app/consumer/campaign_loading_deferral_test.go @@ -125,3 +125,27 @@ func TestLiveCampaignMailboxLoadingDefersWithoutSpendingAttempts(t *testing.T) { t.Fatalf("provider failure must stay actionable: %+v err=%v", logs, err) } } + +func TestServerPacingNeedsAnSMTPRefusalBeforeTheRecipient(t *testing.T) { + unreachable := string(errx.MailErrorCodeServerUnreachable) + for _, tc := range []struct { + name string + code string + failure *errx.SendFailure + pacing bool + }{ + {name: "held on the worker", code: unreachable, failure: &errx.SendFailure{Protocol: "smtp", Stage: "pacing", Cause: errx.SendCauseServerPacing, Disposition: errx.SendRetry}, pacing: true}, + {name: "refused at sign-in", code: unreachable, failure: &errx.SendFailure{Protocol: "smtp", Stage: "auth", Status: 454, Cause: errx.SendCauseServerPacing, Disposition: errx.SendRetry}, pacing: true}, + {name: "plain connection failure", code: unreachable, failure: &errx.SendFailure{Protocol: "smtp", Stage: "starttls", Disposition: errx.SendRetry}}, + {name: "other protocol", code: unreachable, failure: &errx.SendFailure{Protocol: "graph", Cause: errx.SendCauseServerPacing, Disposition: errx.SendRetry}}, + {name: "not a retry", code: unreachable, failure: &errx.SendFailure{Protocol: "smtp", Cause: errx.SendCauseServerPacing, Disposition: errx.SendPermanent}}, + {name: "other code", code: string(errx.MailErrorCodeInvalidCredentials), failure: &errx.SendFailure{Protocol: "smtp", Cause: errx.SendCauseServerPacing, Disposition: errx.SendRetry}}, + } { + t.Run(tc.name, func(t *testing.T) { + _, code := sendFailureReason(models.SendEmailResult{Error: &models.EmailSendError{Code: tc.code, Message: "refused", Failure: tc.failure}}) + if (code == models.ServerPacingCode) != tc.pacing { + t.Fatalf("code=%s, pacing=%t", code, tc.pacing) + } + }) + } +} diff --git a/internal/app/consumer/event_send_result.go b/internal/app/consumer/event_send_result.go index d15b6a719..efc8285e9 100644 --- a/internal/app/consumer/event_send_result.go +++ b/internal/app/consumer/event_send_result.go @@ -292,7 +292,7 @@ func (s *JobsService) failCampaignSend(ctx context.Context, task *repository.Tas // Only permanent recipient refusals are bounce evidence; deferrals may use the same wording. if s.Evidence != nil && ct.ContactID != nil && ct.SequenceID != nil && !copyRefused && - code != string(errx.MailErrorCodeServerUnreachable) && emailverify.NamesRecipient(reason) { + code != string(errx.MailErrorCodeServerUnreachable) && code != models.ServerPacingCode && emailverify.NamesRecipient(reason) { s.Evidence.RecordEvidence(ctx, *ct.ContactID, models.Step(&campaignID, ct.SequenceID), "bounced_recipient", "send:"+ct.SequenceID.String(), reason) } @@ -308,7 +308,7 @@ func (s *JobsService) failCampaignSend(ctx context.Context, task *repository.Tas attempts, exhausted, rolledBack := 0, false, false if ct.ContactID != nil && ct.SequenceID != nil && s.CampaignProgressRepo != nil { - if copyExcluded || code == models.MailboxLoadingCode { + if copyExcluded || code == models.MailboxLoadingCode || code == models.ServerPacingCode { attempts, exhausted, rolledBack, err = s.CampaignProgressRepo.WalkBackSend(ctx, campaignID, *ct.ContactID, *ct.SequenceID, reason, false) } else { attempts, exhausted, rolledBack, err = s.CampaignProgressRepo.RecordSendFailure(ctx, campaignID, *ct.ContactID, *ct.SequenceID, reason) @@ -524,6 +524,11 @@ func (s *JobsService) logCampaignSendFailure(ctx context.Context, campaignID uui meta["mailbox_loading_retry"] = true msg = fmt.Sprintf("Sending to %s was delayed while the mailbox reconnected. An automatic retry was scheduled.", who) } + if code == models.ServerPacingCode && rolledBack && !exhausted { + eventType = "email_deferred" + meta["level"] = "info" + msg = fmt.Sprintf("Sending to %s was delayed because the mailbox's mail server is limiting connections from Warmbly's sending address. Nothing was sent yet; an automatic retry was scheduled.", who) + } _ = s.CampaignLogRepo.CreateLog(ctx, &repository.CampaignLogEntry{ CampaignID: campaignID, EventType: eventType, @@ -580,12 +585,23 @@ func sendFailureReason(result models.SendEmailResult) (reason, code string) { code = models.MailboxLoadingCode } } + if f := failureOf(result); f != nil && f.Protocol == "smtp" && f.Cause == errx.SendCauseServerPacing && f.Disposition == errx.SendRetry && + code == string(errx.MailErrorCodeServerUnreachable) { + code = models.ServerPacingCode + } if code == "" { code = "SEND_FAILED" } return reason, code } +func failureOf(result models.SendEmailResult) *errx.SendFailure { + if result.Error == nil { + return nil + } + return result.Error.Failure +} + // campaignOrgID returns the campaign's organization id for org-scoped // realtime events, or "" for legacy orgless rows. func campaignOrgID(campaign *models.Campaign) string { diff --git a/internal/app/worker/event_send_email.go b/internal/app/worker/event_send_email.go index b36841a9f..2bd8a70a7 100644 --- a/internal/app/worker/event_send_email.go +++ b/internal/app/worker/event_send_email.go @@ -11,6 +11,7 @@ import ( "github.com/google/uuid" "github.com/rs/zerolog/log" "github.com/warmbly/warmbly/internal/app/worker/wmail" + "github.com/warmbly/warmbly/internal/client/smtpimap/smtp" "github.com/warmbly/warmbly/internal/errx" "github.com/warmbly/warmbly/internal/models" "github.com/warmbly/warmbly/internal/pkg/emsg" @@ -396,6 +397,10 @@ func (w *WorkerService) failUnopenedSend(ctx context.Context, sendEmail models.S // Account-level refusals additionally raise their typed mailbox event. func (w *WorkerService) sendMailboxError(taskID uuid.UUID, emailID uuid.UUID, mail *wmail.WMail, mailErr *errx.MailError) { + // A send held on the worker never reached the server, so it says nothing about the mailbox. + if mailErr.Failure != nil && mailErr.Failure.Protocol == "smtp" && mailErr.Failure.Stage == smtp.PaceStage { + return + } // Determine the appropriate event type based on error eventType := wmail.DetermineErrorEventType(mailErr) diff --git a/internal/client/smtpimap/smtp/client.go b/internal/client/smtpimap/smtp/client.go index 9b6714509..ab5366c31 100644 --- a/internal/client/smtpimap/smtp/client.go +++ b/internal/client/smtpimap/smtp/client.go @@ -319,7 +319,7 @@ func writeBase64Wrapped(w io.Writer, data []byte) { // ---------- Internal helpers ---------- -func (c *Client) sendRaw(ctx context.Context, from string, to []string, data []byte) *errx.MailError { +func (c *Client) sendRaw(ctx context.Context, from string, to []string, data []byte) (result *errx.MailError) { var host string var port int var security string @@ -359,6 +359,11 @@ func (c *Client) sendRaw(ctx context.Context, from string, to []string, data []b if resolved == models.MailSecurityNone && !models.CleartextMailAllowed(host) { return errx.ErrMailInsecureRemoteHost } + pace := paceFor(host, port, c.BindIP) + if held := pace.wait(ctx, time.Now()); held != nil { + return held + } + defer func() { result = pace.observe(time.Now(), result) }() // The socket may be 587 with STARTTLS when the mailbox's 465 never // answered; the mode to speak is the one the dial reports. dialed, err := DialSubmission(ctx, c.BindIP, host, port, security) diff --git a/internal/client/smtpimap/smtp/host_pace.go b/internal/client/smtpimap/smtp/host_pace.go new file mode 100644 index 000000000..f0c68f0d6 --- /dev/null +++ b/internal/client/smtpimap/smtp/host_pace.go @@ -0,0 +1,145 @@ +package smtp + +import ( + "context" + "net" + "strconv" + "strings" + "sync" + "time" + + "github.com/warmbly/warmbly/internal/errx" +) + +// A server limiting connections from one client address refuses every mailbox +// it hosts at once, so the worker backs off that server as a whole. +const ( + paceCooldownBase = 30 * time.Second + paceCooldownMax = 10 * time.Minute + pacedWindow = 30 * time.Minute + pacedSpacing = 3 * time.Second + paceMaxWait = 10 * time.Second + // PaceStage marks a send held on the worker without contacting the server. + PaceStage = "pacing" +) + +// hostPace is one worker address's standing with one SMTP server. +type hostPace struct { + mu sync.Mutex + coolUntil time.Time + pacedUntil time.Time + nextStart time.Time + strikes int +} + +var hostPaces sync.Map + +func paceFor(host string, port int, local *net.TCPAddr) *hostPace { + key := net.JoinHostPort(strings.ToLower(host), strconv.Itoa(port)) + "|" + if local != nil { + key += local.IP.String() + } + v, _ := hostPaces.LoadOrStore(key, &hostPace{}) + return v.(*hostPace) +} + +// admit reserves a session start, or reports when the server may be tried again. +func (p *hostPace) admit(now time.Time) (wait time.Duration, retryAt time.Time, ok bool) { + p.mu.Lock() + defer p.mu.Unlock() + if now.Before(p.coolUntil) { + return 0, p.coolUntil, false + } + if !now.Before(p.pacedUntil) { + return 0, time.Time{}, true + } + start := p.nextStart + if start.Before(now) { + start = now + } + if start.Sub(now) > paceMaxWait { + return 0, start, false + } + p.nextStart = start.Add(pacedSpacing) + return start.Sub(now), time.Time{}, true +} + +// wait holds the caller until its reserved start; a refusal is returned as a send that never left. +func (p *hostPace) wait(ctx context.Context, now time.Time) *errx.MailError { + wait, retryAt, ok := p.admit(now) + if !ok { + return pacedHold(now, retryAt) + } + if wait <= 0 { + return nil + } + timer := time.NewTimer(wait) + defer timer.Stop() + select { + case <-timer.C: + return nil + case <-ctx.Done(): + return pacedHold(now, now.Add(wait)) + } +} + +// observe records a session's outcome; one burst of refusals counts as one strike. +func (p *hostPace) observe(now time.Time, err *errx.MailError) *errx.MailError { + throttled := serverThrottled(err) + p.mu.Lock() + defer p.mu.Unlock() + if !throttled { + if err == nil && !now.Before(p.coolUntil) { + p.strikes = 0 + } + return err + } + if !now.Before(p.coolUntil) { + p.strikes++ + cool := paceCooldownBase << min(p.strikes-1, 5) + if cool > paceCooldownMax { + cool = paceCooldownMax + } + p.coolUntil = now.Add(cool) + } + p.pacedUntil = now.Add(pacedWindow) + return throttledFailure(err, p.coolUntil) +} + +// serverThrottled is a refusal of this worker's address rather than of the mailbox. +func serverThrottled(err *errx.MailError) bool { + if err == nil || err.Failure == nil { + return false + } + f := err.Failure + switch { + case f.Status == 421: + return true + case f.Stage == "auth" && f.Status == 454: + return true + case f.Stage == "starttls" && f.Status == 0: + // A dropped handshake; a refused certificate or a port without STARTTLS carries its own reason. + return strings.HasPrefix(err.Message, errx.ErrMailServerUnreachable.Message) + } + return false +} + +func throttledFailure(err *errx.MailError, retryAt time.Time) *errx.MailError { + out := *err + f := *err.Failure + f.RetryAt = &retryAt + switch f.Stage { + case "greeting", "ehlo", "starttls", "auth", "mail from": + // Refused before any recipient was offered, so the send costs the lead nothing. + f.Cause = errx.SendCauseServerPacing + } + out.Failure = &f + out.RetryAfter = retryAt.Sub(f.ObservedAt) + out.Message = errx.MailServerThrottlingMessage + strings.TrimPrefix(err.Message, errx.ErrMailServerUnreachable.Message) + return &out +} + +func pacedHold(now, retryAt time.Time) *errx.MailError { + return errx.WithSendFailure(errx.MError(errx.MailErrorWarning, errx.MailErrorCodeServerUnreachable, errx.MailServerPacedMessage, errx.MailErrorResolveMethodRetry), + errx.SendFailure{Provider: "smtp", Protocol: "smtp", Stage: PaceStage, Cause: errx.SendCauseServerPacing, Scope: "mailbox", Disposition: errx.SendRetry, ObservedAt: now.UTC(), RetryAt: &retryAt}) +} diff --git a/internal/client/smtpimap/smtp/host_pace_test.go b/internal/client/smtpimap/smtp/host_pace_test.go new file mode 100644 index 000000000..caf8a1884 --- /dev/null +++ b/internal/client/smtpimap/smtp/host_pace_test.go @@ -0,0 +1,145 @@ +package smtp + +import ( + "context" + "errors" + "io" + "net" + "net/textproto" + "strings" + "testing" + "time" + + "github.com/warmbly/warmbly/internal/errx" +) + +func throttleReply(stage string, status int) *errx.MailError { + var native error = io.EOF + if status != 0 { + native = &textproto.Error{Code: status, Msg: "4.7.0 too many connections from your IP"} + } + return sendFailure(errx.ErrMailServerUnreachable, native, stage, "mailbox") +} + +func TestServerThrottledNamesOnlyAddressRefusals(t *testing.T) { + for _, tc := range []struct { + name string + err *errx.MailError + want bool + }{ + {"greeting 421", throttleReply("greeting", 421), true}, + {"auth 454", throttleReply("auth", 454), true}, + {"rcpt 421", throttleReply("rcpt to", 421), true}, + {"dropped handshake", tlsFailure(errx.ErrMailServerUnreachable, "starttls", io.EOF), true}, + {"refused certificate", sendFailure(errx.ErrMailServerUnreachableAt("starttls", errors.New(errx.MailConnectionReasonCertificate)), io.EOF, "starttls", "mailbox"), false}, + {"no STARTTLS", sendFailure(errx.ErrMailServerUnreachableAt("starttls", errNoSTARTTLS), errNoSTARTTLS, "starttls", "mailbox"), false}, + {"lost auth connection", throttleReply("auth", 0), false}, + {"greylisted recipient", throttleReply("rcpt to", 450), false}, + {"bad password", sendFailure(errx.ErrMailInvalidCredentials, &textproto.Error{Code: 535, Msg: "5.7.8 bad"}, "auth", "mailbox"), false}, + {"success", nil, false}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := serverThrottled(tc.err); got != tc.want { + t.Fatalf("serverThrottled = %t, want %t", got, tc.want) + } + }) + } +} + +func TestHostPaceCoolsOncePerBurstAndBacksOff(t *testing.T) { + p := &hostPace{} + t0 := time.Date(2026, 11, 3, 18, 0, 0, 0, time.UTC) + + first := p.observe(t0, throttleReply("starttls", 0)) + if !first.Failure.RetryAt.Equal(t0.Add(paceCooldownBase)) || first.Failure.Cause != errx.SendCauseServerPacing { + t.Fatalf("first refusal = %+v", first.Failure) + } + if !strings.HasPrefix(first.Message, errx.MailServerThrottlingMessage) || !strings.HasSuffix(first.Message, "(SMTP starttls status 0)") { + t.Fatalf("message = %q", first.Message) + } + // The rest of the same burst lands inside the cooldown and does not extend it. + p.observe(t0.Add(time.Second), throttleReply("auth", 454)) + if p.strikes != 1 || !p.coolUntil.Equal(t0.Add(paceCooldownBase)) { + t.Fatalf("burst counted twice: strikes=%d cool=%v", p.strikes, p.coolUntil) + } + if _, retry, ok := p.admit(t0.Add(10 * time.Second)); ok || !retry.Equal(t0.Add(paceCooldownBase)) { + t.Fatalf("admitted during cooldown: ok=%t retry=%v", ok, retry) + } + + t1 := t0.Add(paceCooldownBase) + p.observe(t1, throttleReply("greeting", 421)) + if p.strikes != 2 || !p.coolUntil.Equal(t1.Add(2*paceCooldownBase)) { + t.Fatalf("second burst: strikes=%d cool=%v", p.strikes, p.coolUntil) + } + for i := 0; i < 10; i++ { + p.observe(p.coolUntil, throttleReply("greeting", 421)) + } + if got := p.coolUntil.Sub(p.pacedUntil.Add(-pacedWindow)); got != paceCooldownMax { + t.Fatalf("cooldown not capped: %v", got) + } +} + +func TestHostPaceSpacesSessionsAfterARefusalUntilItRecovers(t *testing.T) { + p := &hostPace{} + t0 := time.Date(2026, 11, 3, 18, 0, 0, 0, time.UTC) + if wait, _, ok := p.admit(t0); !ok || wait != 0 { + t.Fatalf("fresh host paced: wait=%v ok=%t", wait, ok) + } + p.observe(t0, throttleReply("auth", 454)) + open := p.coolUntil + var waits []time.Duration + for i := 0; i < 5; i++ { + wait, _, ok := p.admit(open) + if !ok { + waits = append(waits, -1) + continue + } + waits = append(waits, wait) + } + want := []time.Duration{0, pacedSpacing, 2 * pacedSpacing, 3 * pacedSpacing, -1} + for i := range want { + if waits[i] != want[i] { + t.Fatalf("waits = %v, want %v", waits, want) + } + } + if p.observe(open, nil) != nil || p.strikes != 0 { + t.Fatalf("success after the cooldown did not reset strikes: %d", p.strikes) + } + if wait, _, ok := p.admit(open.Add(pacedWindow)); !ok || wait != 0 { + t.Fatalf("still paced after the window: wait=%v ok=%t", wait, ok) + } +} + +func TestHostPaceHoldIsARetryThatNeverReachedTheServer(t *testing.T) { + p := &hostPace{} + t0 := time.Now() + p.observe(t0, throttleReply("starttls", 0)) + held := p.wait(context.Background(), t0) + if held == nil || held.Failure == nil { + t.Fatal("cooling host admitted a session") + } + f := held.Failure + if f.Stage != PaceStage || f.Disposition != errx.SendRetry || f.Cause != errx.SendCauseServerPacing || f.RetryAt == nil || !f.RetryAt.Equal(p.coolUntil) { + t.Fatalf("hold = %+v", f) + } + if held.Type == errx.MailErrorCritical || held.Code != errx.MailErrorCodeServerUnreachable { + t.Fatalf("hold type=%s code=%s", held.Type, held.Code) + } +} + +func TestHostPaceRefusalAfterRecipientsCostsTheLeadAnAttempt(t *testing.T) { + p := &hostPace{} + if got := p.observe(time.Now(), throttleReply("rcpt to", 421)); got.Failure.Cause != "" { + t.Fatalf("recipient-stage refusal marked unattempted: %+v", got.Failure) + } +} + +func TestPaceForKeysOnServerAndWorkerAddress(t *testing.T) { + a := paceFor("SMTP.Example.test", 587, &net.TCPAddr{IP: net.IPv4(192, 0, 2, 1)}) + if paceFor("smtp.example.test", 587, &net.TCPAddr{IP: net.IPv4(192, 0, 2, 1)}) != a { + t.Fatal("host case split the pace") + } + if paceFor("smtp.example.test", 587, &net.TCPAddr{IP: net.IPv4(192, 0, 2, 2)}) == a || paceFor("smtp.example.test", 587, nil) == a { + t.Fatal("another worker address shared the pace") + } +} diff --git a/internal/errx/email.go b/internal/errx/email.go index b538af6ea..50b4a492a 100644 --- a/internal/errx/email.go +++ b/internal/errx/email.go @@ -187,6 +187,10 @@ const ( MailCertificateHint = "The server's certificate is not one a recognised certificate authority vouches for, has expired, or is for another host name. Use the host name the certificate is issued for. For a server with its own certificate, choose Update credentials on the mailbox and trust the certificate when the test offers it." // MailCleartextAuthMessage is the refusal to sign in over a link that is not encrypted. MailCleartextAuthMessage = "This mail server only offers sign-in over an unencrypted connection, and Warmbly never sends a mailbox password unencrypted. Use the server's SSL/TLS port (usually 465) or a port that offers STARTTLS (usually 587)." + // MailServerThrottlingMessage replaces the generic connection text when the server limited this worker's address. + MailServerThrottlingMessage = "The mail server temporarily refused new connections or sign-ins from Warmbly's sending address, which providers do when many mailboxes they host connect from the same address. Warmbly now spaces its connections to this server and retries on its own; nothing needs to change on the mailbox." + // MailServerPacedMessage is a send held back without contacting a server that is limiting Warmbly's address. + MailServerPacedMessage = "Not sent yet: this mailbox's mail server is limiting connections from Warmbly's sending address, so Warmbly is holding the send briefly instead of adding to them. It is retried automatically." // MailNoSTARTTLSHint is what a mailbox owner reads when the port offers no encryption. MailNoSTARTTLSHint = "The server offers no STARTTLS on this port, and Warmbly only signs in over an encrypted connection. Use the server's SSL/TLS port (usually 465) or a port that offers STARTTLS (usually 587)." ) diff --git a/internal/errx/send_failure.go b/internal/errx/send_failure.go index cd01cffbc..b10eecf4a 100644 --- a/internal/errx/send_failure.go +++ b/internal/errx/send_failure.go @@ -29,6 +29,9 @@ const ( SendAmbiguous = "ambiguous" ) +// SendCauseServerPacing marks a failure caused by the server limiting the worker's address, never the mailbox. +const SendCauseServerPacing = "server_pacing" + func RetryAfterAt(value string, now time.Time) *time.Time { value = strings.TrimSpace(value) if seconds, err := strconv.ParseInt(value, 10, 64); err == nil { diff --git a/internal/models/warmup_send_failure.go b/internal/models/warmup_send_failure.go index 797085cb1..724cfeb27 100644 --- a/internal/models/warmup_send_failure.go +++ b/internal/models/warmup_send_failure.go @@ -3,8 +3,10 @@ package models import "time" const ( - MailboxNotLoadedPrefix = "The sending worker has not loaded this mailbox yet" - MailboxLoadingCode = "MAILBOX_LOADING" + MailboxNotLoadedPrefix = "The sending worker has not loaded this mailbox yet" + MailboxLoadingCode = "MAILBOX_LOADING" + // ServerPacingCode is a send the worker held, or the server refused before any message was offered, because the server is limiting the worker's address. + ServerPacingCode = "SERVER_PACING" WarmupFailureLoading = "mailbox_loading" WarmupLoadingGracePeriod = time.Hour ) From d1d43111d0a78bfd2da2b0dcbca0a76aeaf85e54 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Tue, 3 Nov 2026 17:18:48 +0100 Subject: [PATCH 124/318] feat: key SMTP pacing on the normalized server host and worker address, skip loopback relays, hold reserved starts that land in a later cooldown, measure the spaced window from the cooldown's end, classify dropped STARTTLS by transport error, and cover a long server-pacing retry time live --- internal/client/smtpimap/smtp/client.go | 20 ++++++--- internal/client/smtpimap/smtp/host_pace.go | 39 ++++++++++++++--- .../client/smtpimap/smtp/host_pace_test.go | 43 +++++++++++++++---- .../send_failure_isolation_live_test.go | 24 +++++++++++ 4 files changed, 106 insertions(+), 20 deletions(-) diff --git a/internal/client/smtpimap/smtp/client.go b/internal/client/smtpimap/smtp/client.go index ab5366c31..e838571ac 100644 --- a/internal/client/smtpimap/smtp/client.go +++ b/internal/client/smtpimap/smtp/client.go @@ -44,6 +44,15 @@ func tlsFailure(base *errx.MailError, stage string, err error) *errx.MailError { return sendFailure(base, err, stage, "mailbox") } +// startTLSFailure marks a handshake the server closed, which is how some servers shed connections. +func startTLSFailure(err error) *errx.MailError { + failure := tlsFailure(errx.ErrMailServerUnreachable, "starttls", err) + if droppedConnection(err) && failure.Failure != nil { + failure.Failure.Cause = causeDroppedHandshake + } + return failure +} + // pinFailure reports a pinned certificate refusal as a retryable mailbox // connection error, never as a credentials failure. func pinFailure(perr *mailtls.PinError) *errx.MailError { @@ -359,11 +368,12 @@ func (c *Client) sendRaw(ctx context.Context, from string, to []string, data []b if resolved == models.MailSecurityNone && !models.CleartextMailAllowed(host) { return errx.ErrMailInsecureRemoteHost } - pace := paceFor(host, port, c.BindIP) - if held := pace.wait(ctx, time.Now()); held != nil { - return held + if pace := paceFor(host, c.BindIP); pace != nil { + if held := pace.wait(ctx, time.Now()); held != nil { + return held + } + defer func() { result = pace.observe(time.Now(), result) }() } - defer func() { result = pace.observe(time.Now(), result) }() // The socket may be 587 with STARTTLS when the mailbox's 465 never // answered; the mode to speak is the one the dial reports. dialed, err := DialSubmission(ctx, c.BindIP, host, port, security) @@ -431,7 +441,7 @@ func (c *Client) sendRaw(ctx context.Context, from string, to []string, data []b if perr := mailtls.AsPinError(err, capture); perr != nil { return pinFailure(perr) } - return tlsFailure(errx.ErrMailServerUnreachable, "starttls", err) + return startTLSFailure(err) } } else if !netbind.InsecureTLS() && !c.plaintext { return sendFailure(errx.ErrMailServerUnreachableAt("starttls", errNoSTARTTLS), errNoSTARTTLS, "starttls", "mailbox") diff --git a/internal/client/smtpimap/smtp/host_pace.go b/internal/client/smtpimap/smtp/host_pace.go index f0c68f0d6..a32f2cf79 100644 --- a/internal/client/smtpimap/smtp/host_pace.go +++ b/internal/client/smtpimap/smtp/host_pace.go @@ -2,13 +2,16 @@ package smtp import ( "context" + "errors" + "io" "net" - "strconv" "strings" "sync" + "syscall" "time" "github.com/warmbly/warmbly/internal/errx" + "github.com/warmbly/warmbly/internal/models" ) // A server limiting connections from one client address refuses every mailbox @@ -21,6 +24,8 @@ const ( paceMaxWait = 10 * time.Second // PaceStage marks a send held on the worker without contacting the server. PaceStage = "pacing" + // causeDroppedHandshake marks a STARTTLS the server closed mid-handshake, as opposed to one it refused with a reason. + causeDroppedHandshake = "dropped_handshake" ) // hostPace is one worker address's standing with one SMTP server. @@ -34,8 +39,12 @@ type hostPace struct { var hostPaces sync.Map -func paceFor(host string, port int, local *net.TCPAddr) *hostPace { - key := net.JoinHostPort(strings.ToLower(host), strconv.Itoa(port)) + "|" +// paceFor keys on the server, not the port, so a 587 fallback shares the 465 standing; a relay on this machine has none. +func paceFor(host string, local *net.TCPAddr) *hostPace { + if models.LoopbackMailHost(host) { + return nil + } + key := strings.ToLower(strings.TrimSuffix(models.NormalizeMailHost(host), ".")) + "|" if local != nil { key += local.IP.String() } @@ -77,12 +86,22 @@ func (p *hostPace) wait(ctx context.Context, now time.Time) *errx.MailError { defer timer.Stop() select { case <-timer.C: - return nil + return p.heldIfCooling(time.Now()) case <-ctx.Done(): return pacedHold(now, now.Add(wait)) } } +// heldIfCooling refuses a reserved start that a refusal since the reservation put inside a cooldown. +func (p *hostPace) heldIfCooling(now time.Time) *errx.MailError { + p.mu.Lock() + defer p.mu.Unlock() + if now.Before(p.coolUntil) { + return pacedHold(now, p.coolUntil) + } + return nil +} + // observe records a session's outcome; one burst of refusals counts as one strike. func (p *hostPace) observe(now time.Time, err *errx.MailError) *errx.MailError { throttled := serverThrottled(err) @@ -102,7 +121,7 @@ func (p *hostPace) observe(now time.Time, err *errx.MailError) *errx.MailError { } p.coolUntil = now.Add(cool) } - p.pacedUntil = now.Add(pacedWindow) + p.pacedUntil = p.coolUntil.Add(pacedWindow) return throttledFailure(err, p.coolUntil) } @@ -118,16 +137,22 @@ func serverThrottled(err *errx.MailError) bool { case f.Stage == "auth" && f.Status == 454: return true case f.Stage == "starttls" && f.Status == 0: - // A dropped handshake; a refused certificate or a port without STARTTLS carries its own reason. - return strings.HasPrefix(err.Message, errx.ErrMailServerUnreachable.Message) + return f.Cause == causeDroppedHandshake } return false } +// droppedConnection is the server closing or resetting the connection, never a TLS alert or a certificate refusal. +func droppedConnection(err error) bool { + return errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) || + errors.Is(err, syscall.ECONNRESET) || errors.Is(err, syscall.ECONNABORTED) || errors.Is(err, syscall.EPIPE) +} + func throttledFailure(err *errx.MailError, retryAt time.Time) *errx.MailError { out := *err f := *err.Failure f.RetryAt = &retryAt + f.Cause = "" switch f.Stage { case "greeting", "ehlo", "starttls", "auth", "mail from": // Refused before any recipient was offered, so the send costs the lead nothing. diff --git a/internal/client/smtpimap/smtp/host_pace_test.go b/internal/client/smtpimap/smtp/host_pace_test.go index caf8a1884..1c2196cd3 100644 --- a/internal/client/smtpimap/smtp/host_pace_test.go +++ b/internal/client/smtpimap/smtp/host_pace_test.go @@ -7,6 +7,7 @@ import ( "net" "net/textproto" "strings" + "syscall" "testing" "time" @@ -30,7 +31,9 @@ func TestServerThrottledNamesOnlyAddressRefusals(t *testing.T) { {"greeting 421", throttleReply("greeting", 421), true}, {"auth 454", throttleReply("auth", 454), true}, {"rcpt 421", throttleReply("rcpt to", 421), true}, - {"dropped handshake", tlsFailure(errx.ErrMailServerUnreachable, "starttls", io.EOF), true}, + {"dropped handshake", startTLSFailure(io.EOF), true}, + {"reset handshake", startTLSFailure(&net.OpError{Op: "read", Err: syscall.ECONNRESET}), true}, + {"handshake alert", startTLSFailure(errors.New("remote error: tls: protocol version not supported")), false}, {"refused certificate", sendFailure(errx.ErrMailServerUnreachableAt("starttls", errors.New(errx.MailConnectionReasonCertificate)), io.EOF, "starttls", "mailbox"), false}, {"no STARTTLS", sendFailure(errx.ErrMailServerUnreachableAt("starttls", errNoSTARTTLS), errNoSTARTTLS, "starttls", "mailbox"), false}, {"lost auth connection", throttleReply("auth", 0), false}, @@ -50,7 +53,7 @@ func TestHostPaceCoolsOncePerBurstAndBacksOff(t *testing.T) { p := &hostPace{} t0 := time.Date(2026, 11, 3, 18, 0, 0, 0, time.UTC) - first := p.observe(t0, throttleReply("starttls", 0)) + first := p.observe(t0, startTLSFailure(io.EOF)) if !first.Failure.RetryAt.Equal(t0.Add(paceCooldownBase)) || first.Failure.Cause != errx.SendCauseServerPacing { t.Fatalf("first refusal = %+v", first.Failure) } @@ -74,9 +77,14 @@ func TestHostPaceCoolsOncePerBurstAndBacksOff(t *testing.T) { for i := 0; i < 10; i++ { p.observe(p.coolUntil, throttleReply("greeting", 421)) } - if got := p.coolUntil.Sub(p.pacedUntil.Add(-pacedWindow)); got != paceCooldownMax { + last := p.coolUntil.Add(-paceCooldownMax) + p.observe(p.coolUntil, startTLSFailure(io.EOF)) + if got := p.coolUntil.Sub(last.Add(paceCooldownMax)); got != paceCooldownMax { t.Fatalf("cooldown not capped: %v", got) } + if !p.pacedUntil.Equal(p.coolUntil.Add(pacedWindow)) { + t.Fatalf("spacing not measured from the end of the cooldown: paced=%v cool=%v", p.pacedUntil, p.coolUntil) + } } func TestHostPaceSpacesSessionsAfterARefusalUntilItRecovers(t *testing.T) { @@ -113,7 +121,7 @@ func TestHostPaceSpacesSessionsAfterARefusalUntilItRecovers(t *testing.T) { func TestHostPaceHoldIsARetryThatNeverReachedTheServer(t *testing.T) { p := &hostPace{} t0 := time.Now() - p.observe(t0, throttleReply("starttls", 0)) + p.observe(t0, startTLSFailure(io.EOF)) held := p.wait(context.Background(), t0) if held == nil || held.Failure == nil { t.Fatal("cooling host admitted a session") @@ -135,11 +143,30 @@ func TestHostPaceRefusalAfterRecipientsCostsTheLeadAnAttempt(t *testing.T) { } func TestPaceForKeysOnServerAndWorkerAddress(t *testing.T) { - a := paceFor("SMTP.Example.test", 587, &net.TCPAddr{IP: net.IPv4(192, 0, 2, 1)}) - if paceFor("smtp.example.test", 587, &net.TCPAddr{IP: net.IPv4(192, 0, 2, 1)}) != a { - t.Fatal("host case split the pace") + a := paceFor("SMTP.Example.test", &net.TCPAddr{IP: net.IPv4(192, 0, 2, 1)}) + if paceFor("smtp.example.test.", &net.TCPAddr{IP: net.IPv4(192, 0, 2, 1)}) != a { + t.Fatal("host spelling split the pace") } - if paceFor("smtp.example.test", 587, &net.TCPAddr{IP: net.IPv4(192, 0, 2, 2)}) == a || paceFor("smtp.example.test", 587, nil) == a { + if paceFor("smtp.example.test", &net.TCPAddr{IP: net.IPv4(192, 0, 2, 2)}) == a || paceFor("smtp.example.test", nil) == a { t.Fatal("another worker address shared the pace") } + if paceFor("::1", nil) != nil || paceFor("localhost", nil) != nil { + t.Fatal("a relay on this machine was paced") + } +} + +func TestHostPaceReservationYieldsToALaterCooldown(t *testing.T) { + p := &hostPace{} + now := time.Now() + p.pacedUntil = now.Add(pacedWindow) + p.nextStart = now.Add(50 * time.Millisecond) + done := make(chan *errx.MailError, 1) + go func() { done <- p.wait(context.Background(), now) }() + p.mu.Lock() + p.coolUntil = now.Add(time.Minute) + p.mu.Unlock() + held := <-done + if held == nil || held.Failure.Stage != PaceStage || !held.Failure.RetryAt.Equal(now.Add(time.Minute)) { + t.Fatalf("reserved start ran inside a cooldown: %+v", held) + } } diff --git a/internal/repository/send_failure_isolation_live_test.go b/internal/repository/send_failure_isolation_live_test.go index a8c24c474..c3c91192d 100644 --- a/internal/repository/send_failure_isolation_live_test.go +++ b/internal/repository/send_failure_isolation_live_test.go @@ -65,3 +65,27 @@ func TestLiveSendFailureKeepsRecipientAndMailboxRecoverySeparate(t *testing.T) { }) } } + +func TestLiveServerPacingHoldWaitsForItsRetryTime(t *testing.T) { + f := newCampaignIsolationFixture(t) + retryAt := time.Now().UTC().Add(9 * time.Minute) + result := models.SendEmailResult{TaskID: f.request.TaskID, Error: &models.EmailSendError{ + Code: string(errx.MailErrorCodeServerUnreachable), Message: errx.MailServerPacedMessage, + Failure: &errx.SendFailure{Provider: "smtp", Protocol: "smtp", Stage: "pacing", Cause: errx.SendCauseServerPacing, + Disposition: errx.SendRetry, Scope: "mailbox", ObservedAt: time.Now().UTC(), RetryAt: &retryAt}, + }} + if err := f.r.FinishOutbound(t.Context(), result.TaskID, f.sender, f.worker, result); err != nil { + t.Fatal(err) + } + if err := f.r.ApplySendResult(t.Context(), result, func(context.Context) error { return nil }); err != nil { + t.Fatal(err) + } + early, err := f.r.GetSendAdmission(t.Context(), f.org, f.sender, models.InboxProviderSMTPIMAP, retryAt.Add(-time.Minute)) + if err != nil || early.Allowed || early.RecoveryHold || early.RetryAt == nil || early.RetryAt.Before(retryAt.Add(-time.Second)) { + t.Fatalf("held send admitted before the server's retry time: %+v %v", early, err) + } + late, err := f.r.GetSendAdmission(t.Context(), f.org, f.sender, models.InboxProviderSMTPIMAP, retryAt.Add(time.Second)) + if err != nil || !late.Allowed || late.RecoveryHold { + t.Fatalf("held send not admitted after the retry time: %+v %v", late, err) + } +} From 14d11f9a311609e4d59fc3f599d44c9e0854faca Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Tue, 3 Nov 2026 17:31:01 +0100 Subject: [PATCH 125/318] feat: treat an implicit-TLS handshake the server closes as server pacing, exempt trailing-dot loopback relays from pacing, and make the reserved-start cooldown test wait for its reservation --- docs/content/docs/guides/mailboxes.mdx | 2 +- internal/client/smtpimap/smtp/client.go | 19 ++++++++++++++----- internal/client/smtpimap/smtp/host_pace.go | 15 ++++++++++----- .../client/smtpimap/smtp/host_pace_test.go | 19 +++++++++++++++++-- 4 files changed, 42 insertions(+), 13 deletions(-) diff --git a/docs/content/docs/guides/mailboxes.mdx b/docs/content/docs/guides/mailboxes.mdx index d010c6c83..6904a324b 100644 --- a/docs/content/docs/guides/mailboxes.mdx +++ b/docs/content/docs/guides/mailboxes.mdx @@ -149,7 +149,7 @@ When a mail server goes down or stops answering, the mailbox is not deactivated. The same holds for a server that answers but refuses what Warmbly asked. The drawer shows one row carrying the server's own wording, not one row per retry, and it clears on the first pass that completes. -Hosting providers that serve many mailboxes from one server (shared hosting and email resellers) often limit how many connections or sign-ins they accept from one address. Every mailbox on a worker sends from that worker's address, so when such a server answers with `421`, refuses sign-in with `454`, or drops the encryption handshake, Warmbly treats it as a limit on its own address rather than a fault in the mailbox. That worker stops opening sessions to that server for 30 seconds, doubling on each further refusal up to 10 minutes, then spaces new sessions at least 3 seconds apart for the next 30 minutes. Sends that come due meanwhile are held without contacting the server and retried on their own. A held send, or one refused before any recipient was offered, costs the lead none of its send attempts, and a held send raises no mailbox error. The first refusal still shows **Retrying** with a message saying the server is limiting Warmbly's address, and it clears on the next send from that mailbox that goes through. Nothing needs to change on the mailbox. This spacing does not raise any provider limit, and a server that keeps refusing keeps sends held. +Hosting providers that serve many mailboxes from one server (shared hosting and email resellers) often limit how many connections or sign-ins they accept from one address. Every mailbox on a worker sends from that worker's address, so when such a server answers with `421`, refuses sign-in with `454`, or closes the encryption handshake (on STARTTLS or on an SSL/TLS port), Warmbly treats it as a limit on its own address rather than a fault in the mailbox. That worker stops opening sessions to that server for 30 seconds, doubling on each further refusal up to 10 minutes, then spaces new sessions at least 3 seconds apart for the next 30 minutes. Sends that come due meanwhile are held without contacting the server and retried on their own. A held send, or one refused before any recipient was offered, costs the lead none of its send attempts, and a held send raises no mailbox error. The first refusal still shows **Retrying** with a message saying the server is limiting Warmbly's address, and it clears on the next send from that mailbox that goes through. Nothing needs to change on the mailbox. This spacing does not raise any provider limit, and a server that keeps refusing keeps sends held. With two-factor authentication on, generate an app password in your provider's security settings and use that. diff --git a/internal/client/smtpimap/smtp/client.go b/internal/client/smtpimap/smtp/client.go index e838571ac..890fed760 100644 --- a/internal/client/smtpimap/smtp/client.go +++ b/internal/client/smtpimap/smtp/client.go @@ -44,6 +44,19 @@ func tlsFailure(base *errx.MailError, stage string, err error) *errx.MailError { return sendFailure(base, err, stage, "mailbox") } +// dialFailure marks an implicit-TLS port closed mid-handshake, which sheds connections like a dropped STARTTLS. +func dialFailure(addr string, err error) *errx.MailError { + cause := dialCause(err) + if errors.Is(err, netbind.ErrPrivateMailHost) { + cause = errors.New(errx.MailConnectionReasonPrivateHost) + } + failure := sendFailure(errx.ErrMailServerUnreachableAt("dial "+addr, cause), err, "dial", "mailbox") + if droppedConnection(err) && failure.Failure != nil { + failure.Failure.Cause = causeDroppedHandshake + } + return failure +} + // startTLSFailure marks a handshake the server closed, which is how some servers shed connections. func startTLSFailure(err error) *errx.MailError { failure := tlsFailure(errx.ErrMailServerUnreachable, "starttls", err) @@ -384,11 +397,7 @@ func (c *Client) sendRaw(ctx context.Context, from string, to []string, data []b if err == nil { err = errors.New("dial returned no connection") } - cause := dialCause(err) - if errors.Is(err, netbind.ErrPrivateMailHost) { - cause = errors.New(errx.MailConnectionReasonPrivateHost) - } - return sendFailure(errx.ErrMailServerUnreachableAt("dial "+addr, cause), err, "dial", "mailbox") + return dialFailure(addr, err) } conn := dialed.Conn defer conn.Close() diff --git a/internal/client/smtpimap/smtp/host_pace.go b/internal/client/smtpimap/smtp/host_pace.go index a32f2cf79..5cd77b26d 100644 --- a/internal/client/smtpimap/smtp/host_pace.go +++ b/internal/client/smtpimap/smtp/host_pace.go @@ -24,7 +24,7 @@ const ( paceMaxWait = 10 * time.Second // PaceStage marks a send held on the worker without contacting the server. PaceStage = "pacing" - // causeDroppedHandshake marks a STARTTLS the server closed mid-handshake, as opposed to one it refused with a reason. + // causeDroppedHandshake marks a TLS handshake the server closed, as opposed to one it refused with a reason. causeDroppedHandshake = "dropped_handshake" ) @@ -41,10 +41,11 @@ var hostPaces sync.Map // paceFor keys on the server, not the port, so a 587 fallback shares the 465 standing; a relay on this machine has none. func paceFor(host string, local *net.TCPAddr) *hostPace { + host = strings.ToLower(strings.TrimSuffix(models.NormalizeMailHost(host), ".")) if models.LoopbackMailHost(host) { return nil } - key := strings.ToLower(strings.TrimSuffix(models.NormalizeMailHost(host), ".")) + "|" + key := host + "|" if local != nil { key += local.IP.String() } @@ -136,7 +137,7 @@ func serverThrottled(err *errx.MailError) bool { return true case f.Stage == "auth" && f.Status == 454: return true - case f.Stage == "starttls" && f.Status == 0: + case (f.Stage == "starttls" || f.Stage == "dial") && f.Status == 0: return f.Cause == causeDroppedHandshake } return false @@ -154,13 +155,17 @@ func throttledFailure(err *errx.MailError, retryAt time.Time) *errx.MailError { f.RetryAt = &retryAt f.Cause = "" switch f.Stage { - case "greeting", "ehlo", "starttls", "auth", "mail from": + case "dial", "greeting", "ehlo", "starttls", "auth", "mail from": // Refused before any recipient was offered, so the send costs the lead nothing. f.Cause = errx.SendCauseServerPacing } out.Failure = &f out.RetryAfter = retryAt.Sub(f.ObservedAt) - out.Message = errx.MailServerThrottlingMessage + strings.TrimPrefix(err.Message, errx.ErrMailServerUnreachable.Message) + detail := strings.TrimPrefix(err.Message, errx.ErrMailServerUnreachable.Message) + if detail == err.Message { + detail = " " + detail + } + out.Message = errx.MailServerThrottlingMessage + detail return &out } diff --git a/internal/client/smtpimap/smtp/host_pace_test.go b/internal/client/smtpimap/smtp/host_pace_test.go index 1c2196cd3..9de8d03eb 100644 --- a/internal/client/smtpimap/smtp/host_pace_test.go +++ b/internal/client/smtpimap/smtp/host_pace_test.go @@ -6,6 +6,7 @@ import ( "io" "net" "net/textproto" + "runtime" "strings" "syscall" "testing" @@ -33,6 +34,8 @@ func TestServerThrottledNamesOnlyAddressRefusals(t *testing.T) { {"rcpt 421", throttleReply("rcpt to", 421), true}, {"dropped handshake", startTLSFailure(io.EOF), true}, {"reset handshake", startTLSFailure(&net.OpError{Op: "read", Err: syscall.ECONNRESET}), true}, + {"dropped implicit TLS", dialFailure("smtp.example.test:465", io.EOF), true}, + {"refused dial", dialFailure("smtp.example.test:465", &net.OpError{Op: "dial", Err: syscall.ECONNREFUSED}), false}, {"handshake alert", startTLSFailure(errors.New("remote error: tls: protocol version not supported")), false}, {"refused certificate", sendFailure(errx.ErrMailServerUnreachableAt("starttls", errors.New(errx.MailConnectionReasonCertificate)), io.EOF, "starttls", "mailbox"), false}, {"no STARTTLS", sendFailure(errx.ErrMailServerUnreachableAt("starttls", errNoSTARTTLS), errNoSTARTTLS, "starttls", "mailbox"), false}, @@ -150,7 +153,7 @@ func TestPaceForKeysOnServerAndWorkerAddress(t *testing.T) { if paceFor("smtp.example.test", &net.TCPAddr{IP: net.IPv4(192, 0, 2, 2)}) == a || paceFor("smtp.example.test", nil) == a { t.Fatal("another worker address shared the pace") } - if paceFor("::1", nil) != nil || paceFor("localhost", nil) != nil { + if paceFor("::1", nil) != nil || paceFor("localhost", nil) != nil || paceFor("LocalHost.", nil) != nil { t.Fatal("a relay on this machine was paced") } } @@ -159,9 +162,21 @@ func TestHostPaceReservationYieldsToALaterCooldown(t *testing.T) { p := &hostPace{} now := time.Now() p.pacedUntil = now.Add(pacedWindow) - p.nextStart = now.Add(50 * time.Millisecond) + p.nextStart = now.Add(time.Second) done := make(chan *errx.MailError, 1) go func() { done <- p.wait(context.Background(), now) }() + for deadline := time.Now().Add(5 * time.Second); ; { + p.mu.Lock() + reserved := p.nextStart.After(now.Add(time.Second)) + p.mu.Unlock() + if reserved { + break + } + if time.Now().After(deadline) { + t.Fatal("wait did not reserve its start") + } + runtime.Gosched() + } p.mu.Lock() p.coolUntil = now.Add(time.Minute) p.mu.Unlock() From 1e4bdcd113cdde4a4d1dac0c63db362c51878c9f Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Tue, 3 Nov 2026 17:39:17 +0100 Subject: [PATCH 126/318] feat: mark an implicit-TLS handshake the server closes as a dropped handshake where the handshake runs, cover it through sendRaw, and order the reserved-start cooldown test through a replaceable timer --- internal/client/smtpimap/smtp/client.go | 29 +++----- internal/client/smtpimap/smtp/host_pace.go | 7 +- .../client/smtpimap/smtp/host_pace_test.go | 72 +++++++++++++------ 3 files changed, 63 insertions(+), 45 deletions(-) diff --git a/internal/client/smtpimap/smtp/client.go b/internal/client/smtpimap/smtp/client.go index 890fed760..24a01fc0d 100644 --- a/internal/client/smtpimap/smtp/client.go +++ b/internal/client/smtpimap/smtp/client.go @@ -44,22 +44,9 @@ func tlsFailure(base *errx.MailError, stage string, err error) *errx.MailError { return sendFailure(base, err, stage, "mailbox") } -// dialFailure marks an implicit-TLS port closed mid-handshake, which sheds connections like a dropped STARTTLS. -func dialFailure(addr string, err error) *errx.MailError { - cause := dialCause(err) - if errors.Is(err, netbind.ErrPrivateMailHost) { - cause = errors.New(errx.MailConnectionReasonPrivateHost) - } - failure := sendFailure(errx.ErrMailServerUnreachableAt("dial "+addr, cause), err, "dial", "mailbox") - if droppedConnection(err) && failure.Failure != nil { - failure.Failure.Cause = causeDroppedHandshake - } - return failure -} - -// startTLSFailure marks a handshake the server closed, which is how some servers shed connections. -func startTLSFailure(err error) *errx.MailError { - failure := tlsFailure(errx.ErrMailServerUnreachable, "starttls", err) +// handshakeFailure marks a TLS handshake the server closed, which is how some servers shed connections. +func handshakeFailure(base *errx.MailError, stage string, err error) *errx.MailError { + failure := tlsFailure(base, stage, err) if droppedConnection(err) && failure.Failure != nil { failure.Failure.Cause = causeDroppedHandshake } @@ -397,7 +384,11 @@ func (c *Client) sendRaw(ctx context.Context, from string, to []string, data []b if err == nil { err = errors.New("dial returned no connection") } - return dialFailure(addr, err) + cause := dialCause(err) + if errors.Is(err, netbind.ErrPrivateMailHost) { + cause = errors.New(errx.MailConnectionReasonPrivateHost) + } + return sendFailure(errx.ErrMailServerUnreachableAt("dial "+addr, cause), err, "dial", "mailbox") } conn := dialed.Conn defer conn.Close() @@ -418,7 +409,7 @@ func (c *Client) sendRaw(ctx context.Context, from string, to []string, data []b if perr := mailtls.AsPinError(err, capture); perr != nil { return pinFailure(perr) } - return tlsFailure(errx.ErrMailServerUnreachableAt("dial "+addr, err), "dial", err) + return handshakeFailure(errx.ErrMailServerUnreachableAt("dial "+addr, err), "dial", err) } conn = tlsConn } @@ -450,7 +441,7 @@ func (c *Client) sendRaw(ctx context.Context, from string, to []string, data []b if perr := mailtls.AsPinError(err, capture); perr != nil { return pinFailure(perr) } - return startTLSFailure(err) + return handshakeFailure(errx.ErrMailServerUnreachable, "starttls", err) } } else if !netbind.InsecureTLS() && !c.plaintext { return sendFailure(errx.ErrMailServerUnreachableAt("starttls", errNoSTARTTLS), errNoSTARTTLS, "starttls", "mailbox") diff --git a/internal/client/smtpimap/smtp/host_pace.go b/internal/client/smtpimap/smtp/host_pace.go index 5cd77b26d..841118f63 100644 --- a/internal/client/smtpimap/smtp/host_pace.go +++ b/internal/client/smtpimap/smtp/host_pace.go @@ -39,6 +39,9 @@ type hostPace struct { var hostPaces sync.Map +// paceAfter is the reserved-start timer, replaceable so a test can order a refusal before it fires. +var paceAfter = time.After + // paceFor keys on the server, not the port, so a 587 fallback shares the 465 standing; a relay on this machine has none. func paceFor(host string, local *net.TCPAddr) *hostPace { host = strings.ToLower(strings.TrimSuffix(models.NormalizeMailHost(host), ".")) @@ -83,10 +86,8 @@ func (p *hostPace) wait(ctx context.Context, now time.Time) *errx.MailError { if wait <= 0 { return nil } - timer := time.NewTimer(wait) - defer timer.Stop() select { - case <-timer.C: + case <-paceAfter(wait): return p.heldIfCooling(time.Now()) case <-ctx.Done(): return pacedHold(now, now.Add(wait)) diff --git a/internal/client/smtpimap/smtp/host_pace_test.go b/internal/client/smtpimap/smtp/host_pace_test.go index 9de8d03eb..0fec6c143 100644 --- a/internal/client/smtpimap/smtp/host_pace_test.go +++ b/internal/client/smtpimap/smtp/host_pace_test.go @@ -6,13 +6,13 @@ import ( "io" "net" "net/textproto" - "runtime" "strings" "syscall" "testing" "time" "github.com/warmbly/warmbly/internal/errx" + "github.com/warmbly/warmbly/internal/models" ) func throttleReply(stage string, status int) *errx.MailError { @@ -23,6 +23,10 @@ func throttleReply(stage string, status int) *errx.MailError { return sendFailure(errx.ErrMailServerUnreachable, native, stage, "mailbox") } +func starttlsDrop(err error) *errx.MailError { + return handshakeFailure(errx.ErrMailServerUnreachable, "starttls", err) +} + func TestServerThrottledNamesOnlyAddressRefusals(t *testing.T) { for _, tc := range []struct { name string @@ -32,11 +36,11 @@ func TestServerThrottledNamesOnlyAddressRefusals(t *testing.T) { {"greeting 421", throttleReply("greeting", 421), true}, {"auth 454", throttleReply("auth", 454), true}, {"rcpt 421", throttleReply("rcpt to", 421), true}, - {"dropped handshake", startTLSFailure(io.EOF), true}, - {"reset handshake", startTLSFailure(&net.OpError{Op: "read", Err: syscall.ECONNRESET}), true}, - {"dropped implicit TLS", dialFailure("smtp.example.test:465", io.EOF), true}, - {"refused dial", dialFailure("smtp.example.test:465", &net.OpError{Op: "dial", Err: syscall.ECONNREFUSED}), false}, - {"handshake alert", startTLSFailure(errors.New("remote error: tls: protocol version not supported")), false}, + {"dropped handshake", starttlsDrop(io.EOF), true}, + {"reset handshake", starttlsDrop(&net.OpError{Op: "read", Err: syscall.ECONNRESET}), true}, + {"dropped implicit TLS", handshakeFailure(errx.ErrMailServerUnreachableAt("dial smtp.example.test:465", io.EOF), "dial", io.EOF), true}, + {"refused dial", sendFailure(errx.ErrMailServerUnreachableAt("dial smtp.example.test:465", syscall.ECONNREFUSED), &net.OpError{Op: "dial", Err: syscall.ECONNREFUSED}, "dial", "mailbox"), false}, + {"handshake alert", starttlsDrop(errors.New("remote error: tls: protocol version not supported")), false}, {"refused certificate", sendFailure(errx.ErrMailServerUnreachableAt("starttls", errors.New(errx.MailConnectionReasonCertificate)), io.EOF, "starttls", "mailbox"), false}, {"no STARTTLS", sendFailure(errx.ErrMailServerUnreachableAt("starttls", errNoSTARTTLS), errNoSTARTTLS, "starttls", "mailbox"), false}, {"lost auth connection", throttleReply("auth", 0), false}, @@ -56,7 +60,7 @@ func TestHostPaceCoolsOncePerBurstAndBacksOff(t *testing.T) { p := &hostPace{} t0 := time.Date(2026, 11, 3, 18, 0, 0, 0, time.UTC) - first := p.observe(t0, startTLSFailure(io.EOF)) + first := p.observe(t0, starttlsDrop(io.EOF)) if !first.Failure.RetryAt.Equal(t0.Add(paceCooldownBase)) || first.Failure.Cause != errx.SendCauseServerPacing { t.Fatalf("first refusal = %+v", first.Failure) } @@ -81,7 +85,7 @@ func TestHostPaceCoolsOncePerBurstAndBacksOff(t *testing.T) { p.observe(p.coolUntil, throttleReply("greeting", 421)) } last := p.coolUntil.Add(-paceCooldownMax) - p.observe(p.coolUntil, startTLSFailure(io.EOF)) + p.observe(p.coolUntil, starttlsDrop(io.EOF)) if got := p.coolUntil.Sub(last.Add(paceCooldownMax)); got != paceCooldownMax { t.Fatalf("cooldown not capped: %v", got) } @@ -124,7 +128,7 @@ func TestHostPaceSpacesSessionsAfterARefusalUntilItRecovers(t *testing.T) { func TestHostPaceHoldIsARetryThatNeverReachedTheServer(t *testing.T) { p := &hostPace{} t0 := time.Now() - p.observe(t0, startTLSFailure(io.EOF)) + p.observe(t0, starttlsDrop(io.EOF)) held := p.wait(context.Background(), t0) if held == nil || held.Failure == nil { t.Fatal("cooling host admitted a session") @@ -159,29 +163,51 @@ func TestPaceForKeysOnServerAndWorkerAddress(t *testing.T) { } func TestHostPaceReservationYieldsToALaterCooldown(t *testing.T) { + fire := make(chan time.Time) + reserved := make(chan struct{}) + paceAfter = func(time.Duration) <-chan time.Time { close(reserved); return fire } + t.Cleanup(func() { paceAfter = time.After }) p := &hostPace{} now := time.Now() p.pacedUntil = now.Add(pacedWindow) p.nextStart = now.Add(time.Second) done := make(chan *errx.MailError, 1) go func() { done <- p.wait(context.Background(), now) }() - for deadline := time.Now().Add(5 * time.Second); ; { - p.mu.Lock() - reserved := p.nextStart.After(now.Add(time.Second)) - p.mu.Unlock() - if reserved { - break - } - if time.Now().After(deadline) { - t.Fatal("wait did not reserve its start") - } - runtime.Gosched() - } + <-reserved p.mu.Lock() - p.coolUntil = now.Add(time.Minute) + p.coolUntil = time.Now().Add(time.Minute) + cool := p.coolUntil p.mu.Unlock() + fire <- time.Now() held := <-done - if held == nil || held.Failure.Stage != PaceStage || !held.Failure.RetryAt.Equal(now.Add(time.Minute)) { + if held == nil || held.Failure.Stage != PaceStage || !held.Failure.RetryAt.Equal(cool) { t.Fatalf("reserved start ran inside a cooldown: %+v", held) } } + +func TestSendRawMarksAnImplicitTLSHandshakeTheServerClosed(t *testing.T) { + ln, err := net.Listen("tcp", net.JoinHostPort("::1", "0")) + if err != nil { + ln, err = net.Listen("tcp", net.JoinHostPort("localhost", "0")) + } + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = ln.Close() }) + go func() { + for { + conn, err := ln.Accept() + if err != nil { + return + } + _ = conn.Close() + } + }() + addr := ln.Addr().(*net.TCPAddr) + c := newTestClient(addr.IP.String(), addr.Port) + c.Credentials.Security = models.MailSecurityTLS + got := c.sendRaw(t.Context(), "a@example.test", []string{"b@example.test"}, []byte("Subject: hi\r\n\r\nbody\r\n")) + if got == nil || got.Failure == nil || got.Failure.Stage != "dial" || !serverThrottled(got) { + t.Fatalf("closed implicit-TLS handshake not read as the server shedding connections: %+v", got) + } +} From f9b8fa2255c1d1ff023675c6139da883dc4457d6 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Tue, 3 Nov 2026 18:11:18 +0100 Subject: [PATCH 127/318] feat: scale the AWS worker fleet on worker memory and CPU instead of mailbox count, publish WorkerMemoryPercent and WorkerMemoryMaxPercent from heartbeats, and let WARMBLY_WORKER_CAPACITY=auto size each worker's mailbox target from its measured memory --- .github/workflows/ci.yml | 12 ++ cmd/worker/capacity_test.go | 14 ++ cmd/worker/main.go | 22 ++- deploy/terraform/aws/workers/README.md | 14 ++ .../aws/workers/fleet-bootstrap.sh.tftpl | 13 +- deploy/terraform/aws/workers/fleet.tf | 91 ++++++++---- .../aws/workers/tests/fleet.tftest.hcl | 63 ++++++++- docs/content/docs/development/aws-workers.mdx | 85 ++++++++---- .../docs/development/configuration.mdx | 4 +- internal/app/fleetmetrics/fleetmetrics.go | 95 ++++++++----- .../fleetmetrics/fleetmetrics_live_test.go | 45 ++++++ internal/app/worker/event_sync_wake.go | 8 ++ internal/app/worker/mailmanager/manager.go | 7 + internal/pkg/nodeagent/agent.go | 14 +- internal/pkg/nodeagent/capacity.go | 68 +++++++++ internal/pkg/nodeagent/capacity_test.go | 46 +++++++ .../repository/pg_mailbox_push_live_test.go | 130 ++++++++++++++++++ 17 files changed, 637 insertions(+), 94 deletions(-) create mode 100644 internal/app/fleetmetrics/fleetmetrics_live_test.go create mode 100644 internal/pkg/nodeagent/capacity.go create mode 100644 internal/pkg/nodeagent/capacity_test.go create mode 100644 internal/repository/pg_mailbox_push_live_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ae87b7764..26d4079a7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -264,6 +264,18 @@ jobs: grep -q '^--- PASS: TestLiveCampaignLoadingLogsKeepHistoryWithoutCustomerAlerts ' campaign-reconnect.log if grep -q -- '--- SKIP:' campaign-reconnect.log; then exit 1; fi + - name: Mailbox push channels and fleet usage (PostgreSQL) + if: matrix.suite == 'live-1' + env: + WARMBLY_TEST_DB: postgres://warmbly:warmbly@127.0.0.1:5432/warmbly_test?sslmode=disable + run: | + set -o pipefail + go test -race -v -p 1 ./internal/repository ./internal/app/fleetmetrics -run '^TestLive(MailboxPushChannelsRoundTripAndScopeToTheOwner|WakeTargetsSkipWorkersThatCannotActOnAWake|ReadTakesMemoryFromHeartbeats)$' -count=1 | tee mailbox-push.log + for test in TestLiveMailboxPushChannelsRoundTripAndScopeToTheOwner TestLiveWakeTargetsSkipWorkersThatCannotActOnAWake TestLiveReadTakesMemoryFromHeartbeats; do + grep -q -- "--- PASS: $test " mailbox-push.log + done + if grep -q -- '--- SKIP:' mailbox-push.log; then exit 1; fi + - name: Contact campaign empty-step regression (PostgreSQL) if: matrix.suite == 'live-1' env: diff --git a/cmd/worker/capacity_test.go b/cmd/worker/capacity_test.go index ec402ac73..424d27996 100644 --- a/cmd/worker/capacity_test.go +++ b/cmd/worker/capacity_test.go @@ -27,3 +27,17 @@ func TestWorkerCapacityTarget(t *testing.T) { }) } } + +func TestWorkerCapacityAutoSizesFromMemory(t *testing.T) { + t.Setenv("WARMBLY_WORKER_CAPACITY", "auto") + if workerCapacityFromMemory(func() int { return 0 }) == nil { + t.Fatal("auto did not size the target from memory") + } + if got := workerCapacityTarget(); got != defaultWorkerCapacityTarget { + t.Fatalf("auto's first beat before a memory reading falls back to %v, got %v", defaultWorkerCapacityTarget, got) + } + t.Setenv("WARMBLY_WORKER_CAPACITY", "500") + if workerCapacityFromMemory(func() int { return 0 }) != nil { + t.Fatal("a fixed target was replaced by the memory sizing") + } +} diff --git a/cmd/worker/main.go b/cmd/worker/main.go index 6898879ea..166de9a15 100644 --- a/cmd/worker/main.go +++ b/cmd/worker/main.go @@ -169,9 +169,15 @@ func main() { log.Println("WARNING: BOX_GOOGLE_CLIENT_ID/SECRET not set; Gmail mailbox token refresh will fail on expiry") } - agent := newNodeAgent(workerID, bindIP) + var workerService *worker.WorkerService + agent := newNodeAgent(workerID, bindIP, func() int { + if workerService == nil { + return 0 + } + return workerService.MailboxCount() + }) // WorkerService - workerService := &worker.WorkerService{ + workerService = &worker.WorkerService{ OnMailboxMissing: agent.RequestReload, ID: workerID.String(), CipherService: cipherService, @@ -243,7 +249,7 @@ func main() { // newNodeAgent builds the shared fleet agent. It replaces the worker's own // heartbeat loop: identity, usage reporting and self-update are node concerns, // identical for every role, so they live in one place. -func newNodeAgent(workerID uuid.UUID, bindIP string) *nodeagent.Agent { +func newNodeAgent(workerID uuid.UUID, bindIP string, mailboxes func() int) *nodeagent.Agent { reportedIP := os.Getenv("WORKER_PUBLIC_IP") if reportedIP == "" && bindIP != "default route" { reportedIP = bindIP @@ -257,6 +263,7 @@ func newNodeAgent(workerID uuid.UUID, bindIP string) *nodeagent.Agent { Region: nodeRegion(), Address: reportedIP, CapacityTarget: workerCapacityTarget(), + Capacity: workerCapacityFromMemory(mailboxes), Version: buildVersion(), BaseURL: os.Getenv("ENCRYPTED_KEYS_BACKEND_URL"), Token: config.NodeAPIToken(), @@ -269,6 +276,15 @@ func newNodeAgent(workerID uuid.UUID, bindIP string) *nodeagent.Agent { const defaultWorkerCapacityTarget = 100.0 +// workerCapacityFromMemory is set when WARMBLY_WORKER_CAPACITY=auto: the +// worker then plans its mailbox target from its own memory on every beat. +func workerCapacityFromMemory(mailboxes func() int) func(models.NodeUsage) float64 { + if !strings.EqualFold(strings.TrimSpace(os.Getenv("WARMBLY_WORKER_CAPACITY")), "auto") { + return nil + } + return (&nodeagent.MemoryCapacity{Mailboxes: mailboxes}).Target +} + // workerCapacityTarget reads this machine's assigned-mailbox target. func workerCapacityTarget() float64 { raw := strings.TrimSpace(os.Getenv("WARMBLY_WORKER_CAPACITY")) diff --git a/deploy/terraform/aws/workers/README.md b/deploy/terraform/aws/workers/README.md index 0a8141dd4..508b8a9c6 100644 --- a/deploy/terraform/aws/workers/README.md +++ b/deploy/terraform/aws/workers/README.md @@ -90,6 +90,20 @@ parameter named by `fleet_join_token_parameter`. Nothing is created until `fleet_enabled` is true, and the fixed hosts above are unaffected. Apply the foundation first, since it adds the VPC's IPv6 block. +The fleet scales on server resource usage, not mailbox count. Two +target-tracking policies add workers to hold the fleet's memory in use +(`WorkerMemoryPercent`) at `fleet_target_memory` and its average CPU at +`fleet_target_cpu`. One full worker does not grow the fleet: its `auto` mailbox +target falls, so placement steers new mailboxes elsewhere. The fleet shrinks one worker at a time, and only after fleet memory, +the fullest worker's memory and the busiest worker's CPU have all stayed low +for `fleet_scale_in_after_hours`; missing data never counts as low. + +The backend publishes those metrics to `Warmbly/Fleet` with the dimension +`Fleet=` when `FLEET_METRICS_CLOUDWATCH=` is set on it, and its role +needs `cloudwatch:PutMetricData`. Each worker's `node.local.env` gets +`WARMBLY_WORKER_CAPACITY=auto` by default, so it sizes its mailbox target from +its memory, and `GOMEMLIMIT` at 80% of the instance's memory. + The design, variables, scaling metric contract, retirement of fixed hosts and cost notes are in [the AWS worker fleet guide](https://docs.warmbly.com/development/aws-workers/). diff --git a/deploy/terraform/aws/workers/fleet-bootstrap.sh.tftpl b/deploy/terraform/aws/workers/fleet-bootstrap.sh.tftpl index d82cb6412..372ea5001 100644 --- a/deploy/terraform/aws/workers/fleet-bootstrap.sh.tftpl +++ b/deploy/terraform/aws/workers/fleet-bootstrap.sh.tftpl @@ -99,12 +99,23 @@ WantedBy=multi-user.target UNIT } -# join.sh creates node.local.env only when absent, so writing it first sets this worker's capacity. +# Leaves a fifth of the machine to the host and Docker, so the worker's GC runs before the kernel OOM killer does. +go_memory_limit_mib() { + awk '/^MemTotal:/ { printf "%d\n", $2 * 0.8 / 1024 }' /proc/meminfo +} + +# join.sh creates node.local.env only when absent, so writing it first sets this worker's capacity and memory limit. write_local_env() { install -d -m 700 /etc/warmbly if [ ! -e /etc/warmbly/node.local.env ]; then + mem_limit=$(go_memory_limit_mib || true) umask 077 printf '%s\n' '# Written by the fleet launch template; join.sh never rewrites this file.' "WARMBLY_WORKER_CAPACITY=$CAPACITY" > /etc/warmbly/node.local.env + # The Go runtime refuses to start on a malformed GOMEMLIMIT, so an unreadable MemTotal leaves it unset. + case "$mem_limit" in + '' | *[!0-9]* | 0) log "MemTotal unreadable; GOMEMLIMIT left unset" ;; + *) printf 'GOMEMLIMIT=%sMiB\n' "$mem_limit" >> /etc/warmbly/node.local.env ;; + esac chmod 600 /etc/warmbly/node.local.env fi } diff --git a/deploy/terraform/aws/workers/fleet.tf b/deploy/terraform/aws/workers/fleet.tf index 28b3a9a25..64450755c 100644 --- a/deploy/terraform/aws/workers/fleet.tf +++ b/deploy/terraform/aws/workers/fleet.tf @@ -75,12 +75,12 @@ variable "fleet_desired_capacity" { } variable "fleet_worker_capacity" { - description = "WARMBLY_WORKER_CAPACITY on every fleet worker: assigned mailboxes each one is planned for" - type = number - default = 2000 + description = "WARMBLY_WORKER_CAPACITY on every fleet worker: auto sizes the mailbox target from the machine's memory, a whole number fixes it" + type = string + default = "auto" validation { - condition = var.fleet_worker_capacity >= 1 && floor(var.fleet_worker_capacity) == var.fleet_worker_capacity - error_message = "Use a positive whole number." + condition = var.fleet_worker_capacity == "auto" || can(regex("^[1-9][0-9]*$", var.fleet_worker_capacity)) + error_message = "Use auto or a positive whole number." } } @@ -104,32 +104,58 @@ variable "fleet_image_repository" { } } -variable "fleet_target_utilization" { - description = "Target for WorkerUtilizationPercent; the fleet scales out above it" +variable "fleet_target_memory" { + description = "Target for WorkerMemoryPercent, the fleet's memory in use; the fleet scales out above it" type = number - default = 70 + default = 65 + validation { + condition = var.fleet_target_memory > 0 && var.fleet_target_memory <= 100 + error_message = "Use a percentage." + } } variable "fleet_target_cpu" { description = "Target average CPU percent across the fleet; the second scale-out signal" type = number default = 60 + validation { + condition = var.fleet_target_cpu > 0 && var.fleet_target_cpu <= 100 + error_message = "Use a percentage." + } } -variable "fleet_scale_in_below" { - description = "Scale in only while WorkerUtilizationPercent stays below this" +variable "fleet_scale_in_memory_below" { + description = "Scale in only while WorkerMemoryPercent stays below this" type = number - default = 30 + default = 35 + validation { + condition = var.fleet_scale_in_memory_below > 0 && var.fleet_scale_in_memory_below <= 100 + error_message = "Use a percentage." + } +} + +variable "fleet_scale_in_memory_max_below" { + description = "Scale in only while the fullest worker's memory percent also stays below this" + type = number + default = 60 + validation { + condition = var.fleet_scale_in_memory_max_below > 0 && var.fleet_scale_in_memory_max_below <= 100 + error_message = "Use a percentage." + } } variable "fleet_scale_in_cpu_below" { description = "Scale in only while the busiest worker's CPU percent also stays below this" type = number default = 30 + validation { + condition = var.fleet_scale_in_cpu_below > 0 && var.fleet_scale_in_cpu_below <= 100 + error_message = "Use a percentage." + } } variable "fleet_scale_in_after_hours" { - description = "How long both scale-in conditions must hold before one worker is removed, and the pause before the next" + description = "How long all scale-in conditions must hold before one worker is removed, and the pause before the next" type = number default = 3 validation { @@ -170,8 +196,13 @@ locals { fleet = var.fleet_enabled fleet_join_token_name = coalesce(var.fleet_join_token_parameter, "/${var.name}/fleet/join-token") # Resolved at each launch, so new workers boot a current AMI without a template change refreshing the fleet. - al2023_arm64 = "resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-arm64" - fleet_metric = { namespace = "Warmbly/Fleet", name = "WorkerUtilizationPercent", dimension = { Fleet = var.name } } + al2023_arm64 = "resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-arm64" + fleet_metric = { + namespace = "Warmbly/Fleet" + dimension = { Fleet = var.name } + # Memory drives scaling; utilization is mailboxes over planned capacity and is published for reading only. + names = { memory = "WorkerMemoryPercent", memory_max = "WorkerMemoryMaxPercent", utilization = "WorkerUtilizationPercent" } + } fleet_scale_in_points = var.fleet_scale_in_after_hours * 12 } @@ -329,8 +360,8 @@ resource "aws_launch_template" "fleet" { error_message = "Use 1 <= fleet_min_size <= fleet_desired_capacity <= fleet_max_size." } precondition { - condition = var.fleet_scale_in_below < var.fleet_target_utilization && var.fleet_target_utilization > 0 && var.fleet_target_utilization <= 100 && var.fleet_target_cpu > 0 && var.fleet_target_cpu <= 100 - error_message = "Targets are percentages, and fleet_scale_in_below must sit under fleet_target_utilization." + condition = var.fleet_scale_in_memory_below < var.fleet_target_memory && var.fleet_scale_in_cpu_below < var.fleet_target_cpu + error_message = "Each scale-in threshold must sit under its scale-out counterpart." } } } @@ -382,17 +413,17 @@ resource "aws_autoscaling_group" "fleet" { } } -resource "aws_autoscaling_policy" "fleet_utilization" { +resource "aws_autoscaling_policy" "fleet_memory" { count = local.fleet ? 1 : 0 - name = "mailbox-utilization" + name = "memory" autoscaling_group_name = aws_autoscaling_group.fleet[0].name policy_type = "TargetTrackingScaling" target_tracking_configuration { - target_value = var.fleet_target_utilization + target_value = var.fleet_target_memory disable_scale_in = true customized_metric_specification { namespace = local.fleet_metric.namespace - metric_name = local.fleet_metric.name + metric_name = local.fleet_metric.names.memory statistic = "Average" metric_dimension { name = "Fleet" @@ -427,11 +458,11 @@ resource "aws_autoscaling_policy" "fleet_scale_in" { cooldown = var.fleet_scale_in_after_hours * 3600 } -# Missing utilization never counts as quiet, so the fleet cannot shrink while the publisher is down. +# Missing data never counts as quiet, so the fleet cannot shrink while the publisher is down. resource "aws_cloudwatch_metric_alarm" "fleet_scale_in" { count = local.fleet ? 1 : 0 alarm_name = "${var.name}-fleet-scale-in" - alarm_description = "Fleet utilization and the busiest worker's CPU stayed low for ${var.fleet_scale_in_after_hours}h; removes one worker" + alarm_description = "Fleet memory, the fullest worker's memory and the busiest worker's CPU stayed low for ${var.fleet_scale_in_after_hours}h; removes one worker" comparison_operator = "GreaterThanOrEqualToThreshold" threshold = 1 evaluation_periods = local.fleet_scale_in_points @@ -440,15 +471,25 @@ resource "aws_cloudwatch_metric_alarm" "fleet_scale_in" { alarm_actions = [aws_autoscaling_policy.fleet_scale_in[0].arn] metric_query { id = "quiet" - expression = "IF(util < ${var.fleet_scale_in_below} AND cpu < ${var.fleet_scale_in_cpu_below}, 1, 0)" + expression = "IF(mem < ${var.fleet_scale_in_memory_below} AND memmax < ${var.fleet_scale_in_memory_max_below} AND cpu < ${var.fleet_scale_in_cpu_below}, 1, 0)" label = "Quiet" return_data = true } metric_query { - id = "util" + id = "mem" metric { namespace = local.fleet_metric.namespace - metric_name = local.fleet_metric.name + metric_name = local.fleet_metric.names.memory + dimensions = local.fleet_metric.dimension + period = 300 + stat = "Maximum" + } + } + metric_query { + id = "memmax" + metric { + namespace = local.fleet_metric.namespace + metric_name = local.fleet_metric.names.memory_max dimensions = local.fleet_metric.dimension period = 300 stat = "Maximum" diff --git a/deploy/terraform/aws/workers/tests/fleet.tftest.hcl b/deploy/terraform/aws/workers/tests/fleet.tftest.hcl index f7c6d8717..4850a3c5a 100644 --- a/deploy/terraform/aws/workers/tests/fleet.tftest.hcl +++ b/deploy/terraform/aws/workers/tests/fleet.tftest.hcl @@ -89,8 +89,8 @@ run "fleet_without_public_ipv4" { error_message = "IPv6 leaves through the egress-only gateway and S3 through a gateway endpoint." } assert { - condition = strcontains(base64decode(aws_launch_template.fleet[0].user_data), "WARMBLY_WORKER_CAPACITY=$CAPACITY") && strcontains(base64decode(aws_launch_template.fleet[0].user_data), "CAPACITY='2000'") && strcontains(base64decode(aws_launch_template.fleet[0].user_data), "INSTANCE_URL='https://app.example.com'") && strcontains(base64decode(aws_launch_template.fleet[0].user_data), "TOKEN_PARAMETER='/warmbly-production/fleet/join-token'") - error_message = "User data sets the worker capacity and names the join token parameter." + condition = strcontains(base64decode(aws_launch_template.fleet[0].user_data), "WARMBLY_WORKER_CAPACITY=$CAPACITY") && strcontains(base64decode(aws_launch_template.fleet[0].user_data), "CAPACITY='auto'") && strcontains(base64decode(aws_launch_template.fleet[0].user_data), "GOMEMLIMIT=%sMiB") && strcontains(base64decode(aws_launch_template.fleet[0].user_data), "INSTANCE_URL='https://app.example.com'") && strcontains(base64decode(aws_launch_template.fleet[0].user_data), "TOKEN_PARAMETER='/warmbly-production/fleet/join-token'") + error_message = "User data sets the worker capacity to auto, a Go memory limit, and names the join token parameter." } assert { condition = aws_autoscaling_group.fleet[0].min_size == 2 && aws_autoscaling_group.fleet[0].health_check_type == "EC2" && contains(aws_autoscaling_group.fleet[0].suspended_processes, "AZRebalance") @@ -101,17 +101,37 @@ run "fleet_without_public_ipv4" { error_message = "Termination is held 15 minutes and a refresh replaces one worker at a time." } assert { - condition = aws_autoscaling_policy.fleet_utilization[0].target_tracking_configuration[0].disable_scale_in && aws_autoscaling_policy.fleet_cpu[0].target_tracking_configuration[0].disable_scale_in && aws_autoscaling_policy.fleet_scale_in[0].scaling_adjustment == -1 && aws_autoscaling_policy.fleet_scale_in[0].cooldown == 10800 + condition = aws_autoscaling_policy.fleet_memory[0].target_tracking_configuration[0].disable_scale_in && aws_autoscaling_policy.fleet_cpu[0].target_tracking_configuration[0].disable_scale_in && aws_autoscaling_policy.fleet_scale_in[0].scaling_adjustment == -1 && aws_autoscaling_policy.fleet_scale_in[0].cooldown == 10800 error_message = "Target tracking only scales out; scale-in removes one worker per three hours." } assert { - condition = aws_autoscaling_policy.fleet_utilization[0].target_tracking_configuration[0].customized_metric_specification[0].namespace == "Warmbly/Fleet" && aws_autoscaling_policy.fleet_utilization[0].target_tracking_configuration[0].customized_metric_specification[0].metric_dimension[0].value == "warmbly-production" - error_message = "Utilization is read from Warmbly/Fleet with the deployment name as its Fleet dimension." + condition = aws_autoscaling_policy.fleet_memory[0].target_tracking_configuration[0].target_value == 65 && aws_autoscaling_policy.fleet_cpu[0].target_tracking_configuration[0].target_value == 60 + error_message = "The fleet holds average memory at 65% and average CPU at 60%." + } + assert { + condition = aws_autoscaling_policy.fleet_memory[0].target_tracking_configuration[0].customized_metric_specification[0].namespace == "Warmbly/Fleet" && aws_autoscaling_policy.fleet_memory[0].target_tracking_configuration[0].customized_metric_specification[0].metric_name == "WorkerMemoryPercent" && aws_autoscaling_policy.fleet_memory[0].target_tracking_configuration[0].customized_metric_specification[0].statistic == "Average" && aws_autoscaling_policy.fleet_memory[0].target_tracking_configuration[0].customized_metric_specification[0].metric_dimension[0].value == "warmbly-production" + error_message = "Memory is read from Warmbly/Fleet WorkerMemoryPercent with the deployment name as its Fleet dimension." } assert { condition = aws_cloudwatch_metric_alarm.fleet_scale_in[0].evaluation_periods == 36 && aws_cloudwatch_metric_alarm.fleet_scale_in[0].treat_missing_data == "notBreaching" error_message = "Scale-in needs three quiet hours and never fires on missing data." } + assert { + condition = one([for q in aws_cloudwatch_metric_alarm.fleet_scale_in[0].metric_query : q.expression if q.return_data == true]) == "IF(mem < 35 AND memmax < 60 AND cpu < 30, 1, 0)" + error_message = "Scale-in is quiet only while fleet memory, the fullest worker's memory and the busiest worker's CPU are all low." + } + assert { + condition = toset(flatten([for q in aws_cloudwatch_metric_alarm.fleet_scale_in[0].metric_query : [for m in q.metric : "${q.id}=${m.metric_name}/${m.stat}"]])) == toset(["mem=WorkerMemoryPercent/Maximum", "memmax=WorkerMemoryMaxPercent/Maximum", "cpu=CPUUtilization/Maximum"]) + error_message = "Scale-in reads WorkerMemoryPercent, WorkerMemoryMaxPercent and EC2 CPUUtilization at their maximum." + } + assert { + condition = alltrue([for t in aws_autoscaling_policy.fleet_memory[0].target_tracking_configuration : alltrue([for c in t.customized_metric_specification : c.metric_name != "WorkerUtilizationPercent"])]) && alltrue([for q in aws_cloudwatch_metric_alarm.fleet_scale_in[0].metric_query : alltrue([for m in q.metric : m.metric_name != "WorkerUtilizationPercent"])]) + error_message = "Mailbox utilization is informational; no scaling decision reads it." + } + assert { + condition = output.fleet.metric.namespace == "Warmbly/Fleet" && output.fleet.metric.names.memory == "WorkerMemoryPercent" && output.fleet.metric.names.memory_max == "WorkerMemoryMaxPercent" && output.fleet.metric.names.utilization == "WorkerUtilizationPercent" + error_message = "The fleet output documents all three published metric names." + } assert { condition = length(aws_autoscaling_group.nat) == 2 && aws_autoscaling_group.nat[0].max_size == 1 && length(aws_eip.nat) == 2 && length(output.fleet.nat_ipv4_addresses) == 2 error_message = "Each zone has one self-healing NAT instance and a stable address." @@ -126,6 +146,39 @@ run "fleet_without_public_ipv4" { } } +run "fleet_worker_capacity_takes_a_number" { + command = plan + variables { + fleet_enabled = true + fleet_instance_url = "https://app.example.com" + fleet_worker_capacity = "1500" + } + assert { + condition = strcontains(base64decode(aws_launch_template.fleet[0].user_data), "CAPACITY='1500'") + error_message = "A fixed capacity reaches the worker as written." + } +} + +run "fleet_worker_capacity_rejects_garbage" { + command = plan + variables { + fleet_enabled = true + fleet_instance_url = "https://app.example.com" + fleet_worker_capacity = "0" + } + expect_failures = [var.fleet_worker_capacity] +} + +run "fleet_scale_in_sits_under_scale_out" { + command = plan + variables { + fleet_enabled = true + fleet_instance_url = "https://app.example.com" + fleet_scale_in_memory_below = 70 + } + expect_failures = [aws_launch_template.fleet[0]] +} + run "fleet_needs_instance_url" { command = plan variables { diff --git a/docs/content/docs/development/aws-workers.mdx b/docs/content/docs/development/aws-workers.mdx index f13aac855..59f213b3a 100644 --- a/docs/content/docs/development/aws-workers.mdx +++ b/docs/content/docs/development/aws-workers.mdx @@ -1,6 +1,6 @@ --- title: AWS worker fleet -description: Run mail workers in an Auto Scaling group with no public IPv4 address, scale them on mailbox load, and retire fixed worker hosts. +description: Run mail workers in an Auto Scaling group with no public IPv4 address, scale them on memory and CPU, and retire fixed worker hosts. --- The workers root in `deploy/terraform/aws/workers/` can run mail workers as an @@ -42,8 +42,11 @@ At first boot the user data: 2. Restricts instance metadata to root, so the worker container, which shares the host network, cannot use the instance role. 3. Writes `/etc/warmbly/node.local.env` with - `WARMBLY_WORKER_CAPACITY=`. `join.sh` never rewrites - that file. + `WARMBLY_WORKER_CAPACITY=` and `GOMEMLIMIT` set to + 80% of the instance's memory, read from `/proc/meminfo` at boot (about + 3,000 MiB on a `t4g.medium`). The limit makes the worker's garbage + collector work within the machine, leaving the rest to the host and Docker. + `join.sh` never rewrites that file. 4. Reads the join token from Parameter Store, downloads `join.sh` from the Warmbly instance and runs it with `--role worker`. The node is named `-fleet-`. The token is held in memory only and is not @@ -115,14 +118,15 @@ token parameter, the metric contract and `nat_ipv4_addresses`. Workers appear in | `fleet_min_size` | `2` | Smallest fleet | | `fleet_max_size` | `10` | Largest fleet | | `fleet_desired_capacity` | `null` | Starting size; scaling owns it afterwards. `null` starts at the minimum | -| `fleet_worker_capacity` | `2000` | `WARMBLY_WORKER_CAPACITY` on every fleet worker | +| `fleet_worker_capacity` | `auto` | `WARMBLY_WORKER_CAPACITY` on every fleet worker: `auto`, or a positive whole number of mailboxes | | `fleet_region_label` | empty | Optional `--region` label for placement | | `fleet_image_repository` | `ghcr.io/warmbly/warmbly` | Repository `join.sh` pulls the worker image from | -| `fleet_target_utilization` | `70` | Target for `WorkerUtilizationPercent` | +| `fleet_target_memory` | `65` | Target for `WorkerMemoryPercent`, the fleet's memory in use | | `fleet_target_cpu` | `60` | Target average CPU percent | -| `fleet_scale_in_below` | `30` | Utilization the fleet must stay under before it shrinks | +| `fleet_scale_in_memory_below` | `35` | Fleet memory percent the fleet must stay under before it shrinks | +| `fleet_scale_in_memory_max_below` | `60` | Memory percent the fullest worker must stay under before the fleet shrinks | | `fleet_scale_in_cpu_below` | `30` | CPU percent the busiest worker must stay under before the fleet shrinks | -| `fleet_scale_in_after_hours` | `3` | How long both must hold, and the pause between removals (1 to 24) | +| `fleet_scale_in_after_hours` | `3` | How long all three must hold, and the pause between removals (1 to 24) | | `fleet_termination_hook_seconds` | `900` | How long a terminating worker is held after it stops | | `fleet_instance_warmup_seconds` | `900` | Seconds before a new worker's metrics count toward scaling | | `fleet_refresh_warmup_seconds` | `1800` | Seconds an instance refresh waits after each replacement | @@ -133,27 +137,51 @@ token parameter, the metric contract and `nat_ipv4_addresses`. Workers appear in ## How the fleet scales +The fleet scales on what its machines are using: memory, which is what a +worker's mailbox sessions consume, and CPU. Mailbox counts do not move it. Moving a mailbox to another worker changes the address its provider sees and forces a reconnect, so the fleet grows readily and shrinks rarely. **Scale-out** comes from two target-tracking policies, both with scale-in disabled: -- `WorkerUtilizationPercent` held at `fleet_target_utilization` +- `WorkerMemoryPercent`, the fleet's memory in use, held at + `fleet_target_memory` - the group's average CPU held at `fleet_target_cpu` With `standard` CPU credits, a `t4g` worker that has spent its credits runs at its baseline (20% for `t4g.medium`), so the CPU signal mostly reacts to bursts. -Mailbox utilization is the primary signal. +Memory is the primary signal. + +**A full worker is a placement matter, not a fleet-size one.** Adding a worker +does not relieve a full one, because mailboxes already placed stay where they +are, so no rule grows the fleet for one hot machine. With +`WARMBLY_WORKER_CAPACITY=auto` a worker's mailbox target falls as its memory +fills, so placement stops sending it new mailboxes and the rotation loop moves +mailboxes off a worker that stays over its target. `WorkerMemoryMaxPercent` +still keeps the fleet from shrinking while any worker is full. **Scale-in** is one simple policy that removes one worker, driven by one alarm. -The alarm fires only when fleet utilization stays below `fleet_scale_in_below` -and the busiest worker's CPU stays below `fleet_scale_in_cpu_below` for -`fleet_scale_in_after_hours`. The policy's cooldown is the same length, so the -next removal needs another quiet period. Missing utilization data never counts -as quiet, so the fleet does not shrink while the metric is not published. The -group removes its newest worker, which has the fewest mailboxes, and zone -rebalancing is suspended so the group never moves workers for symmetry alone. +The alarm fires only when all of these stay true for +`fleet_scale_in_after_hours`: + +- `WorkerMemoryPercent` stays below `fleet_scale_in_memory_below` +- the fullest worker's memory stays below `fleet_scale_in_memory_max_below` +- the busiest worker's EC2 CPU stays below `fleet_scale_in_cpu_below` + +Each is read at its highest value in every five minutes. The policy's cooldown +is the same length as the quiet period, so the next removal needs another quiet +period, and the group never goes below `fleet_min_size`. Missing data never +counts as quiet, so the fleet does not shrink while the metrics are not +published. The group removes its newest worker, which has the fewest mailboxes, +and zone rebalancing is suspended so the group never moves workers for symmetry +alone. + +**Worker capacity.** With `fleet_worker_capacity` left at `auto`, each worker +sizes its own mailbox target from its memory, so a larger instance type takes +more mailboxes without a change here. A whole number fixes the target on every +fleet worker instead. Either way, the target guides placement; it does not +scale the fleet. **Termination.** A terminating worker is held by a lifecycle hook for `fleet_termination_hook_seconds`. The worker watches its own lifecycle state in @@ -170,20 +198,31 @@ existing ones. Health checks are EC2 status checks. ### Metric contract -The backend publishes the utilization metric when its +The backend publishes the fleet's metrics every minute when its [`FLEET_METRICS_CLOUDWATCH`](/development/configuration/#workers) is set to the -root's `name`. The fleet scales on it only when every field matches: +root's `name`. It uses the AWS default credential chain, so the backend's role +needs `cloudwatch:PutMetricData`. The values come from worker heartbeats: each +worker reports its host's memory in use and in total about every 100 seconds. | Field | Value | |---|---| | Namespace | `Warmbly/Fleet` | -| Metric name | `WorkerUtilizationPercent` | | Dimension | `Fleet` = the root's `name` (default `warmbly-production`) | -| Value | Assigned mailboxes across the fleet divided by the fleet's capacity target, times 100 | -| Unit | `Percent`, or none | +| Unit | `Percent` | -The policies read it at the deployment's own `Fleet` value only, so two -deployments in one account do not scale on each other's load. +| Metric | Value | Used for | +|---|---|---| +| `WorkerMemoryPercent` | Memory in use across live workers divided by their total memory, times 100 | Scale-out target and scale-in | +| `WorkerMemoryMaxPercent` | Memory percent of the fullest live worker | Scale-in guard | +| `WorkerUtilizationPercent` | Assigned mailboxes divided by the fleet's planned capacity, times 100 | Reading only; nothing scales on it | + +When no live worker reports memory, the backend publishes nothing. Missing data +triggers no scale-out and never counts as quiet for scale-in, so a fleet whose +workers stop reporting holds its size until they report again. + +The policies and alarms read the metrics at the deployment's own `Fleet` value +only, so two deployments in one account do not scale on each other's load. The +`fleet` output lists the namespace, dimension and all three metric names. ## Egress addresses diff --git a/docs/content/docs/development/configuration.mdx b/docs/content/docs/development/configuration.mdx index 88e255a99..a49027d21 100644 --- a/docs/content/docs/development/configuration.mdx +++ b/docs/content/docs/development/configuration.mdx @@ -537,7 +537,7 @@ Keep the copies private. GeoLite2 may not be redistributed, which is also why no | `WORKER_ID` | Stable uuid for this worker. Leave unset when running scaled replicas, which share one environment | derived, then random | yes | | `WORKER_BIND_IP` | Source address to bind outbound connections to, and the seed for a derived `WORKER_ID` | unset | yes | | `WORKER_PUBLIC_IP` | Public IPv4 reported by the worker, never replaced by the backend-observed address, which may be a reverse proxy. Otherwise the node discovers HTTPS egress IPv4 using `api.ipify.org` every ten minutes. Set this explicitly when mail and HTTPS have different egress routes | detected | yes | -| `WARMBLY_WORKER_CAPACITY` | Assigned-mailbox planning target for this worker. This guides placement and is not a mailbox-provider send limit | `100` | yes | +| `WARMBLY_WORKER_CAPACITY` | Assigned-mailbox planning target for this worker. This guides placement and is not a mailbox-provider send limit. `auto` sizes it on every heartbeat from the machine's memory: 70% of it, less the process's own footprint, divided by what each mailbox the worker holds has been measured to use (1 MB until 50 are loaded) | `100` | yes | | `WORKER_COMMAND_CONCURRENCY` | Worker command lanes, from `1` to `64`, on both Kafka and NATS. Commands are grouped by the mailbox in the payload, including older task-keyed sends. Each mailbox stays in order; independent lanes run concurrently, so one slow mail server holds only its own lane. On NATS a command waiting in a lane is kept from being redelivered while it waits. Invalid values use the default | `8` | yes | | `WARMBLY_NODE_REGION` | Free-form label for where this node egresses from, e.g. `eu-central`. Placement prefers a worker near where a mailbox's provider expects sign-ins; unset scores neutral. Written by the join script from `--region` | unset | yes | | `ENCRYPTED_KEYS_BACKEND_URL` | Backend base the worker fetches organization keys from, and the address a joining node is told to call back on. On hosted production it should be `https`, or a private-network address nodes reach without crossing the internet; a plain `http` address that does not name this machine is logged as a warning on every join and env refresh. A self-host may use plain `http` on its own network | unset | yes | @@ -549,7 +549,7 @@ Keep the copies private. GeoLite2 may not be redistributed, which is also why no | `WARMBLY_TARGET_VERSION_PATH` | File the node writes the control plane's `desired_version` to, for the `warmbly-node-update` timer to apply. Unset, the node never writes one and does not update itself. Written by the join script | unset | yes | | `WARMBLY_ENV_REFRESH` | Read by the host updater, not the node. `true` lets it replace `node.env` with what the control plane renders now whenever the heartbeat names a different env revision, then restart the node. `node.local.env` is never touched. Written by the join script on a new join and by `--adopt --env-refresh`; a node without it keeps its env until it rejoins | unset | no (read by the updater) | | `APP_INTERNAL_URL` | Read by the backend: the address a joining node is told to call back on when `ENCRYPTED_KEYS_BACKEND_URL` is unset on the backend. Instance health checks whichever of the two is set | unset | no (read per join) | -| `FLEET_METRICS_CLOUDWATCH` | Read by the backend: the fleet name it publishes `Warmbly/Fleet` `WorkerUtilizationPercent` under (dimension `Fleet`) every minute, the metric the [AWS worker fleet](/development/aws-workers/#metric-contract) scales on. Set it to the workers root's `name`. Uses the AWS default credential chain, so the backend's role needs `cloudwatch:PutMetricData`. Leave it unset on any other deployment | unset | yes | +| `FLEET_METRICS_CLOUDWATCH` | Read by the backend: the fleet name it publishes `Warmbly/Fleet` metrics under (dimension `Fleet`) every minute from the workers' heartbeats: `WorkerMemoryPercent` and `WorkerMemoryMaxPercent`, which the [AWS worker fleet](/development/aws-workers/#metric-contract) scales on, and `WorkerUtilizationPercent` for reading only. Set it to the workers root's `name`. Uses the AWS default credential chain, so the backend's role needs `cloudwatch:PutMetricData`. Leave it unset on any other deployment | unset | yes | An empty `ENCRYPTED_KEYS_BACKEND_URL` or `ENCRYPTED_KEYS_WORKER_TOKEN` lets the worker start, subscribe and never register. There is no log line. The `no_worker_heartbeat` check on [Instance health](/development/instance-health/#no_worker_heartbeat) is what surfaces it. diff --git a/internal/app/fleetmetrics/fleetmetrics.go b/internal/app/fleetmetrics/fleetmetrics.go index cadb15968..a9c8ae141 100644 --- a/internal/app/fleetmetrics/fleetmetrics.go +++ b/internal/app/fleetmetrics/fleetmetrics.go @@ -1,5 +1,5 @@ -// Package fleetmetrics publishes the worker fleet's planned utilization to -// CloudWatch, the signal an AWS Auto Scaling Group scales the fleet on. +// Package fleetmetrics publishes the worker fleet's resource usage to +// CloudWatch, the signals an AWS Auto Scaling Group scales the fleet on. // Optional: a deployment that does not set FLEET_METRICS_CLOUDWATCH runs none of it. package fleetmetrics @@ -19,11 +19,16 @@ import ( "github.com/warmbly/warmbly/internal/repository" ) +// Namespace and the metric names are the contract with the Auto Scaling policies in deploy/terraform/aws/workers. const ( - // Namespace and MetricName are the contract with the Auto Scaling policy in deploy/terraform/aws/workers. - Namespace = "Warmbly/Fleet" - MetricName = "WorkerUtilizationPercent" - interval = time.Minute + Namespace = "Warmbly/Fleet" + // MemoryMetric is memory in use across live workers; the fleet scales on it. + MemoryMetric = "WorkerMemoryPercent" + // MemoryMaxMetric is the fullest single worker; a hot worker adds one. + MemoryMaxMetric = "WorkerMemoryMaxPercent" + // UtilizationMetric is assigned mailboxes over planned capacity, published for dashboards only. + UtilizationMetric = "WorkerUtilizationPercent" + interval = time.Minute ) // FleetName is FLEET_METRICS_CLOUDWATCH, the Fleet dimension; empty publishes nothing. @@ -31,47 +36,71 @@ func FleetName() string { return strings.TrimSpace(os.Getenv("FLEET_METRICS_CLOUDWATCH")) } -// Utilization is active mailboxes on live workers over the live workers' summed capacity target. -func Utilization(ctx context.Context, d *db.DB) (float64, error) { - var load, capacity float64 - err := d.QueryRow(ctx, `SELECT - (SELECT count(*) FROM email_accounts a JOIN fleet_nodes n ON n.id = a.worker_id - WHERE a.status = 'active' AND n.role = 'worker' AND n.active AND n.last_seen_at > now() - $1::interval)::float8, - (SELECT COALESCE(sum(n.capacity_target), 0) FROM fleet_nodes n - WHERE n.role = 'worker' AND n.active AND n.last_seen_at > now() - $1::interval)::float8`, - repository.WorkerLivenessWindow).Scan(&load, &capacity) - if err != nil { - return 0, fmt.Errorf("fleet utilization: %w", err) - } - if capacity <= 0 { - // No live worker: report full so the fleet scales out rather than in. - return 100, nil - } - return load * 100 / capacity, nil +// Usage is what the fleet's live workers last reported. A false Known means no +// live worker reported memory; nothing is published then, which neither grows +// nor shrinks the fleet. +type Usage struct { + Known bool + MemoryPercent float64 + MemoryMaxPercent float64 + Utilization float64 } -// Run publishes the fleet's utilization every minute until ctx ends. +// Read takes the fleet's usage from the workers' heartbeats. +func Read(ctx context.Context, d *db.DB) (Usage, error) { + var used, total, hottest, load, capacity float64 + var reporting int + err := d.QueryRow(ctx, `WITH live AS ( + SELECT n.id, n.capacity_target, n.memory_used_mb, n.memory_limit_mb FROM fleet_nodes n + WHERE n.role = 'worker' AND n.active AND n.last_seen_at > now() - $1::interval) + SELECT + COALESCE(sum(memory_used_mb) FILTER (WHERE memory_limit_mb > 0), 0)::float8, + COALESCE(sum(memory_limit_mb) FILTER (WHERE memory_limit_mb > 0), 0)::float8, + COALESCE(max(memory_used_mb::float8 * 100 / memory_limit_mb) FILTER (WHERE memory_limit_mb > 0), 0)::float8, + count(*) FILTER (WHERE memory_limit_mb > 0), + (SELECT count(*) FROM email_accounts a JOIN live ON live.id = a.worker_id WHERE a.status = 'active')::float8, + COALESCE(sum(capacity_target), 0)::float8 + FROM live`, repository.WorkerLivenessWindow).Scan(&used, &total, &hottest, &reporting, &load, &capacity) + if err != nil { + return Usage{}, fmt.Errorf("fleet usage: %w", err) + } + if reporting == 0 || total <= 0 { + return Usage{}, nil + } + u := Usage{Known: true, MemoryPercent: used * 100 / total, MemoryMaxPercent: hottest} + if capacity > 0 { + u.Utilization = load * 100 / capacity + } + return u, nil +} + +// Run publishes the fleet's usage every minute until ctx ends. func Run(ctx context.Context, d *db.DB, fleet string) error { cfg, err := awsconfig.LoadDefaultConfig(ctx) if err != nil { return fmt.Errorf("fleet metrics: aws config: %w", err) } client := cloudwatch.NewFromConfig(cfg) + dimension := []types.Dimension{{Name: aws.String("Fleet"), Value: aws.String(fleet)}} + datum := func(name string, value float64) types.MetricDatum { + return types.MetricDatum{MetricName: aws.String(name), Dimensions: dimension, Unit: types.StandardUnitPercent, Value: aws.Float64(value)} + } ticker := time.NewTicker(interval) defer ticker.Stop() for { - if value, err := Utilization(ctx, d); err != nil { - log.Warn().Err(err).Msg("fleet utilization not published") + if u, err := Read(ctx, d); err != nil { + log.Warn().Err(err).Msg("fleet usage not published") + } else if !u.Known { + log.Debug().Msg("no live worker reported memory; fleet usage not published") } else if _, err := client.PutMetricData(ctx, &cloudwatch.PutMetricDataInput{ Namespace: aws.String(Namespace), - MetricData: []types.MetricDatum{{ - MetricName: aws.String(MetricName), - Dimensions: []types.Dimension{{Name: aws.String("Fleet"), Value: aws.String(fleet)}}, - Unit: types.StandardUnitPercent, - Value: aws.Float64(value), - }}, + MetricData: []types.MetricDatum{ + datum(MemoryMetric, u.MemoryPercent), + datum(MemoryMaxMetric, u.MemoryMaxPercent), + datum(UtilizationMetric, u.Utilization), + }, }); err != nil { - log.Warn().Err(err).Msg("fleet utilization not published") + log.Warn().Err(err).Msg("fleet usage not published") } select { case <-ctx.Done(): diff --git a/internal/app/fleetmetrics/fleetmetrics_live_test.go b/internal/app/fleetmetrics/fleetmetrics_live_test.go new file mode 100644 index 000000000..fc3d4fd3c --- /dev/null +++ b/internal/app/fleetmetrics/fleetmetrics_live_test.go @@ -0,0 +1,45 @@ +package fleetmetrics + +import ( + "context" + "os" + "testing" + + "github.com/google/uuid" + "github.com/warmbly/warmbly/internal/infrastructure/db" + "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/repository" +) + +func TestLiveReadTakesMemoryFromHeartbeats(t *testing.T) { + dsn := os.Getenv("WARMBLY_TEST_DB") + if dsn == "" { + t.Skip("WARMBLY_TEST_DB not set") + } + ctx := context.Background() + handle, err := db.New(ctx, dsn) + if err != nil { + t.Fatal(err) + } + defer handle.Pool.Close() + nodes := repository.NewFleetNodeRepository(handle) + hot, cool := uuid.New(), uuid.New() + defer handle.Pool.Exec(ctx, `DELETE FROM fleet_nodes WHERE id = ANY($1)`, []uuid.UUID{hot, cool}) + for id, used := range map[uuid.UUID]int{hot: 3600, cool: 400} { + limit := 4000 + if err := nodes.UpsertOnHeartbeat(ctx, models.NodeHeartbeat{NodeID: id, Role: models.NodeRoleWorker, + Usage: models.NodeUsage{MemoryUsedMB: &used, MemoryLimitMB: &limit, MemoryScope: "host"}}); err != nil { + t.Fatal(err) + } + } + u, err := Read(ctx, handle) + if err != nil { + t.Fatal(err) + } + if u.MemoryMaxPercent < 90 { + t.Fatalf("the 90%% worker did not set the hottest reading: %+v", u) + } + if u.MemoryPercent <= 0 || u.MemoryPercent >= 100 { + t.Fatalf("fleet memory %v is not a share of the reported machines", u.MemoryPercent) + } +} diff --git a/internal/app/worker/event_sync_wake.go b/internal/app/worker/event_sync_wake.go index 2b1246542..decc16536 100644 --- a/internal/app/worker/event_sync_wake.go +++ b/internal/app/worker/event_sync_wake.go @@ -17,3 +17,11 @@ func (w *WorkerService) HandleSyncWake(_ context.Context, e *models.SyncWake) er } return nil } + +// MailboxCount is how many mailboxes this worker holds, zero before it is initialised. +func (w *WorkerService) MailboxCount() int { + if w.mailManager == nil { + return 0 + } + return w.mailManager.Count() +} diff --git a/internal/app/worker/mailmanager/manager.go b/internal/app/worker/mailmanager/manager.go index 4497924cb..41368b381 100644 --- a/internal/app/worker/mailmanager/manager.go +++ b/internal/app/worker/mailmanager/manager.go @@ -80,6 +80,13 @@ func (m *MailManager) Get(id uuid.UUID) *wmail.WMail { return m.Emails[id] } +// Count is how many mailboxes the manager holds. +func (m *MailManager) Count() int { + m.RLock() + defer m.RUnlock() + return len(m.Emails) +} + // Has returns true if the manager already has this email account func (m *MailManager) Has(id uuid.UUID) bool { m.RLock() diff --git a/internal/pkg/nodeagent/agent.go b/internal/pkg/nodeagent/agent.go index e570329cb..62ec6e6b8 100644 --- a/internal/pkg/nodeagent/agent.go +++ b/internal/pkg/nodeagent/agent.go @@ -44,6 +44,9 @@ type Config struct { // CapacityTarget is meaningful for workers only. Zero leaves the control // plane's stored/default target unchanged. CapacityTarget float64 + // Capacity, when set, replaces CapacityTarget with a target derived from + // each beat's usage; a zero result keeps CapacityTarget. + Capacity func(models.NodeUsage) float64 // Version is what this build reports. Empty means "unknown", which the // control plane must not read as "needs updating". Version string @@ -161,6 +164,13 @@ func paceFrom(livenessSeconds int) time.Duration { } func (a *Agent) beat(ctx context.Context, booted, stopping bool) *models.NodeHeartbeatReply { + usage := a.sampleUsage() + capacity := a.cfg.CapacityTarget + if a.cfg.Capacity != nil { + if v := a.cfg.Capacity(usage); v > 0 { + capacity = v + } + } beat := models.NodeHeartbeat{ WarmupSendProtocol: a.cfg.WarmupSendProtocol, SyncWakeProtocol: a.cfg.SyncWakeProtocol, @@ -169,9 +179,9 @@ func (a *Agent) beat(ctx context.Context, booted, stopping bool) *models.NodeHea Name: a.cfg.Name, Region: a.cfg.Region, Address: a.address, - CapacityTarget: a.cfg.CapacityTarget, + CapacityTarget: capacity, Version: a.cfg.Version, - Usage: a.sampleUsage(), + Usage: usage, Booted: booted, Stopping: stopping, } diff --git a/internal/pkg/nodeagent/capacity.go b/internal/pkg/nodeagent/capacity.go new file mode 100644 index 000000000..d3ee6b168 --- /dev/null +++ b/internal/pkg/nodeagent/capacity.go @@ -0,0 +1,68 @@ +package nodeagent + +import ( + "math" + "sync" + + "github.com/warmbly/warmbly/internal/models" +) + +const ( + // memoryTargetShare is the share of the machine a worker plans to fill; + // the rest is headroom for bursts, the garbage collector and the host. + memoryTargetShare = 0.70 + // defaultMailboxMB is assumed until enough mailboxes are loaded to measure. + defaultMailboxMB = 1.0 + // minMailboxSample is how many mailboxes a measurement needs. + minMailboxSample = 50 + capacityFloor = 50 + capacityCeiling = 100_000 +) + +// MemoryCapacity sizes a worker's mailbox target from its own memory: what the +// machine has, and what each mailbox it holds has been measured to cost. +type MemoryCapacity struct { + // Mailboxes is how many mailboxes the worker holds now. + Mailboxes func() int + + mu sync.Mutex + baseline float64 + perMailbox float64 +} + +// Target is the mailbox count that fills memoryTargetShare of the machine, or +// zero when the beat carries no memory reading, which leaves the stored target. +func (m *MemoryCapacity) Target(u models.NodeUsage) float64 { + if u.MemoryLimitMB == nil || *u.MemoryLimitMB <= 0 || u.ResidentMB == nil { + return 0 + } + m.mu.Lock() + defer m.mu.Unlock() + resident, limit := float64(*u.ResidentMB), float64(*u.MemoryLimitMB) + held := 0 + if m.Mailboxes != nil { + held = m.Mailboxes() + } + // The process's own footprint with no mailboxes: the first beat, before any load. + if m.baseline == 0 || held == 0 && resident < m.baseline { + m.baseline = resident + } + if held >= minMailboxSample && resident > m.baseline { + sample := (resident - m.baseline) / float64(held) + if m.perMailbox == 0 { + m.perMailbox = sample + } else { + // Smoothed so one beat after a burst does not swing placement. + m.perMailbox += 0.2 * (sample - m.perMailbox) + } + } + per := defaultMailboxMB + if m.perMailbox > 0 { + per = max(m.perMailbox, 0.05) + } + budget := limit*memoryTargetShare - m.baseline + if budget <= 0 { + return capacityFloor + } + return min(max(math.Floor(budget/per), capacityFloor), capacityCeiling) +} diff --git a/internal/pkg/nodeagent/capacity_test.go b/internal/pkg/nodeagent/capacity_test.go new file mode 100644 index 000000000..60492a1f9 --- /dev/null +++ b/internal/pkg/nodeagent/capacity_test.go @@ -0,0 +1,46 @@ +package nodeagent + +import ( + "testing" + + "github.com/warmbly/warmbly/internal/models" +) + +func usage(residentMB, limitMB int) models.NodeUsage { + return models.NodeUsage{ResidentMB: &residentMB, MemoryLimitMB: &limitMB} +} + +func TestMemoryCapacityFollowsMeasuredMailboxCost(t *testing.T) { + held := 0 + c := &MemoryCapacity{Mailboxes: func() int { return held }} + + // First beat, nothing loaded: the 100 MB process is the baseline and the default cost applies. + if got := c.Target(usage(100, 4000)); got != (4000*0.7-100)/defaultMailboxMB { + t.Fatalf("empty worker planned %v", got) + } + // 1,000 mailboxes measured at 2 MB each halve the plan. + held = 1000 + if got := c.Target(usage(2100, 4000)); got != (4000*0.7-100)/2 { + t.Fatalf("measured worker planned %v", got) + } + // A bigger machine with the same mailboxes plans for more. + if got := c.Target(usage(2100, 16000)); got <= (4000*0.7-100)/2 { + t.Fatalf("a larger machine did not plan for more, got %v", got) + } +} + +func TestMemoryCapacitySmoothsAndBounds(t *testing.T) { + held := 1000 + c := &MemoryCapacity{Mailboxes: func() int { return held }} + c.Target(usage(100, 4000)) + steady := c.Target(usage(1100, 4000)) + if spike := c.Target(usage(5100, 4000)); spike < steady/5 { + t.Fatalf("one heavy beat swung the plan from %v to %v", steady, spike) + } + if got := c.Target(usage(100, 100)); got != capacityFloor { + t.Fatalf("a machine with no room planned %v, want the floor", got) + } + if got := (&MemoryCapacity{}).Target(models.NodeUsage{}); got != 0 { + t.Fatalf("a beat without memory must leave the stored target, got %v", got) + } +} diff --git a/internal/repository/pg_mailbox_push_live_test.go b/internal/repository/pg_mailbox_push_live_test.go new file mode 100644 index 000000000..72c09a8da --- /dev/null +++ b/internal/repository/pg_mailbox_push_live_test.go @@ -0,0 +1,130 @@ +package repository + +import ( + "context" + "os" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/warmbly/warmbly/internal/infrastructure/db" + "github.com/warmbly/warmbly/internal/models" +) + +func livePushDB(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(func() { handle.Pool.Close() }) + return handle +} + +type pushFixture struct { + user, org uuid.UUID + gmail, outlook, onOldWorker uuid.UUID + wakeWorker, oldWorker uuid.UUID + gmailAddress, outlookAddress string +} + +func newPushFixture(t *testing.T, handle *db.DB) *pushFixture { + t.Helper() + ctx := context.Background() + f := &pushFixture{user: uuid.New(), org: uuid.New(), gmail: uuid.New(), outlook: uuid.New(), onOldWorker: uuid.New(), + wakeWorker: uuid.New(), oldWorker: uuid.New()} + tag := "push-" + f.org.String()[:8] + f.gmailAddress, f.outlookAddress = tag+"[EMAIL]", tag+"[EMAIL]" + exec := func(sql string, args ...any) { + t.Helper() + if _, err := handle.Pool.Exec(ctx, sql, args...); err != nil { + t.Fatalf("fixture %q: %v", sql[:min(60, len(sql))], err) + } + } + nodes, workers := NewFleetNodeRepository(handle), NewWorkerRepository(handle.Pool) + for id, protocol := range map[uuid.UUID]int{f.wakeWorker: 1, f.oldWorker: 0} { + if err := nodes.UpsertOnHeartbeat(ctx, models.NodeHeartbeat{NodeID: id, Role: models.NodeRoleWorker, SyncWakeProtocol: protocol}); err != nil { + t.Fatalf("heartbeat: %v", err) + } + if err := workers.EnsureWorkerRow(ctx, id); err != nil { + t.Fatalf("worker row: %v", err) + } + } + exec(`INSERT INTO users (id, first_name, last_name, email, password_hash) VALUES ($1, 'Push', 'Live', $2, 'x')`, f.user, tag+"@test.local") + exec(`INSERT INTO organizations (id, name, slug, owner_user_id) VALUES ($1, 'Push', $2, $3)`, f.org, tag, f.user) + exec(`INSERT INTO email_accounts (id, user_id, organization_id, email, name, signature_plain, signature_html, provider, worker_id) + VALUES ($1, $2, $3, $4, 'Gmail', '', '', 'gmail', $5)`, f.gmail, f.user, f.org, strings.ToUpper(f.gmailAddress[:1])+f.gmailAddress[1:], f.wakeWorker) + exec(`INSERT INTO email_accounts (id, user_id, organization_id, email, name, signature_plain, signature_html, provider, worker_id) + VALUES ($1, $2, $3, $4, 'Outlook', '', '', 'outlook', $5)`, f.outlook, f.user, f.org, f.outlookAddress, f.wakeWorker) + exec(`INSERT INTO email_accounts (id, user_id, organization_id, email, name, signature_plain, signature_html, provider, worker_id) + VALUES ($1, $2, $3, $4, 'Old', '', '', 'outlook', $5)`, f.onOldWorker, f.user, f.org, tag+"[EMAIL]", f.oldWorker) + t.Cleanup(func() { + c := context.Background() + _, _ = handle.Pool.Exec(c, `DELETE FROM email_accounts WHERE id = ANY($1)`, []uuid.UUID{f.gmail, f.outlook, f.onOldWorker}) + _, _ = handle.Pool.Exec(c, `DELETE FROM organizations WHERE id = $1`, f.org) + _, _ = handle.Pool.Exec(c, `DELETE FROM users WHERE id = $1`, f.user) + _, _ = handle.Pool.Exec(c, `DELETE FROM workers WHERE id = ANY($1)`, []uuid.UUID{f.wakeWorker, f.oldWorker}) + _, _ = handle.Pool.Exec(c, `DELETE FROM fleet_nodes WHERE id = ANY($1)`, []uuid.UUID{f.wakeWorker, f.oldWorker}) + }) + return f +} + +func TestLiveMailboxPushChannelsRoundTripAndScopeToTheOwner(t *testing.T) { + handle := livePushDB(t) + f := newPushFixture(t, handle) + repo := NewMailboxPushRepository(handle) + ctx := context.Background() + expires := time.Now().Add(6 * 24 * time.Hour).UTC().Truncate(time.Microsecond) + + if err := repo.PutPushState(ctx, uuid.New(), f.outlook, &models.MailboxPushState{Provider: models.MailboxPushGraph, SubscriptionID: "x", ExpiresAt: expires}); err != nil { + t.Fatal(err) + } + if got, err := repo.GetPushState(ctx, f.outlook); err != nil || got != nil { + t.Fatalf("another user's report was stored: %+v, %v", got, err) + } + want := &models.MailboxPushState{Provider: models.MailboxPushGraph, SubscriptionID: "sub-1", ExpiresAt: expires, Credential: "c1"} + if err := repo.PutPushState(ctx, f.user, f.outlook, want); err != nil { + t.Fatal(err) + } + got, err := repo.GetPushState(ctx, f.outlook) + if err != nil || got == nil || got.SubscriptionID != "sub-1" || got.Credential != "c1" || !got.ExpiresAt.Equal(expires) { + t.Fatalf("round trip: %+v, %v", got, err) + } + if err := repo.PutPushState(ctx, f.user, f.outlook, nil); err != nil { + t.Fatal(err) + } + if got, _ := repo.GetPushState(ctx, f.outlook); got != nil { + t.Fatalf("a closed channel survived: %+v", got) + } +} + +func TestLiveWakeTargetsSkipWorkersThatCannotActOnAWake(t *testing.T) { + handle := livePushDB(t) + f := newPushFixture(t, handle) + repo := NewMailboxPushRepository(handle) + ctx := context.Background() + + targets, err := repo.WakeTargets(ctx, []uuid.UUID{f.outlook, f.onOldWorker}) + if err != nil { + t.Fatal(err) + } + if len(targets) != 1 || targets[0].EmailID != f.outlook || targets[0].WorkerID != f.wakeWorker || targets[0].UserID != f.user { + t.Fatalf("targets %+v, want only the mailbox on the wake-capable worker", targets) + } + + if got, _ := repo.GmailWakeTargets(ctx, f.gmailAddress); len(got) != 0 { + t.Fatalf("a Gmail mailbox with no watch was woken: %+v", got) + } + if err := repo.PutPushState(ctx, f.user, f.gmail, &models.MailboxPushState{Provider: models.MailboxPushGmail, ExpiresAt: time.Now().Add(time.Hour)}); err != nil { + t.Fatal(err) + } + got, err := repo.GmailWakeTargets(ctx, strings.ToUpper(f.gmailAddress)) + if err != nil || len(got) != 1 || got[0].EmailID != f.gmail { + t.Fatalf("a watched Gmail mailbox was not found by its address in another case: %+v, %v", got, err) + } +} From be8bf18164886d33564ded4b684688e2c7e5d7ed Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 09:06:33 +0100 Subject: [PATCH 128/318] feat: get the PostgreSQL TestLive catch-all green by materializing the follow-up states CTE so a sweep page resolves its facts once, harvesting prepared statements by constant-folding whole SQL strings and checking monitoring as assembled, scoping instance-wide monitoring and reply-repair tests to their own rows, and updating warmup, analytics, erasure, cloud-link and credential fixtures to current schema and behavior --- .../app/analytics/warmup_ramp_live_test.go | 13 +- .../app/warmup/health_evaluation_live_test.go | 11 +- .../app/warmup/pool_membership_live_test.go | 6 +- internal/jobs/mailbox_erasure_live_test.go | 2 +- .../repository/mailbox_sources_live_test.go | 11 +- internal/repository/pg_auth_live_test.go | 11 +- internal/repository/pg_inbox_follow_up.go | 3 +- .../pg_monitoring_clock_live_test.go | 9 +- .../pg_monitoring_worker_live_test.go | 56 ++++- .../pg_unibox_reply_repair_live_test.go | 7 +- .../repository/query_prepare_live_test.go | 208 +++++++++++++++--- 11 files changed, 276 insertions(+), 61 deletions(-) diff --git a/internal/app/analytics/warmup_ramp_live_test.go b/internal/app/analytics/warmup_ramp_live_test.go index 112fccefb..cace47eae 100644 --- a/internal/app/analytics/warmup_ramp_live_test.go +++ b/internal/app/analytics/warmup_ramp_live_test.go @@ -64,7 +64,8 @@ func newRampFixture(t *testing.T, daysWarming, base, increase, max int) *rampFix VALUES ($1, $2, $3, $4, 'Ramp', '', '', 'smtp_imap', 'active', 50, 600, 'UTC', $5, $6, $7, $8)`, f.mailbox, f.user, f.org, "ramp-"+f.mailbox.String()[:8]+"@test.local", - time.Now().Add(-time.Duration(daysWarming)*24*time.Hour), base, increase, max) + // timestamp without time zone: pgx writes the wall clock, so anchor in UTC, 6h off the day boundary. + time.Now().UTC().Add(-time.Duration(daysWarming)*24*time.Hour-6*time.Hour), base, increase, max) exec(`INSERT INTO email_accounts (id, user_id, organization_id, email, name, signature_plain, signature_html, provider, status, campaign_limit, min_wait_time, timezone) VALUES ($1, $2, $3, $4, 'Partner', '', '', 'gmail', 'active', 50, 600, 'UTC')`, @@ -252,13 +253,17 @@ func TestLiveWarmupTargetIsCappedByReachablePartners(t *testing.T) { }) exec(`INSERT INTO organizations (id, name, slug, owner_user_id) VALUES ($1, 'Ramp partners', $2, $3)`, other, "ramp-p-"+other.String()[:8], f.user) + exec(`UPDATE email_accounts SET test_mode = 'diagnostic', test_send_enabled = true, test_receive_enabled = true WHERE id = $1`, f.mailbox) ids := []uuid.UUID{f.mailbox} for i := 0; i < 3; i++ { id := uuid.New() + // The state a warmup start writes: warmup on, diagnostic sending and receiving. exec(`INSERT INTO email_accounts (id, user_id, organization_id, email, name, signature_plain, - signature_html, provider, status, campaign_limit, min_wait_time, timezone) - VALUES ($1, $2, $3, $4, 'Partner', '', '', 'smtp_imap', 'active', 50, 600, 'UTC')`, - id, f.user, other, "ramp-p-"+id.String()[:8]+"@test.local") + signature_html, provider, status, campaign_limit, min_wait_time, timezone, warmup, + test_mode, test_send_enabled, test_receive_enabled) + VALUES ($1, $2, $3, $4, 'Partner', '', '', 'smtp_imap', 'active', 50, 600, 'UTC', $5, + 'diagnostic', true, true)`, + id, f.user, other, "ramp-p-"+id.String()[:8]+"@test.local", time.Now().UTC()) ids = append(ids, id) } for _, id := range ids { diff --git a/internal/app/warmup/health_evaluation_live_test.go b/internal/app/warmup/health_evaluation_live_test.go index 14c7094b3..c8e6cffb9 100644 --- a/internal/app/warmup/health_evaluation_live_test.go +++ b/internal/app/warmup/health_evaluation_live_test.go @@ -197,10 +197,15 @@ func deliverWarmup(t *testing.T, handle *db.DB, sender, recipient uuid.UUID, off for i := range ids { ids[i] = "<" + uuid.NewString() + "@test.local>" } + landing := "inbox" + if junked { + landing = "spam" + } + // Placement counts only a receipt whose landing was observed (000267). execSQL(t, handle.Pool, ` - INSERT INTO warmup_received (email_account_id, internal_id, message_id, sender_account_id, created_at) - SELECT $1, gen_random_uuid(), m, $2, NOW() - $3::interval FROM unnest($4::text[]) AS m`, - recipient, sender, offset, ids) + INSERT INTO warmup_received (email_account_id, internal_id, message_id, sender_account_id, created_at, first_landing) + SELECT $1, gen_random_uuid(), m, $2, NOW() - $3::interval, $5 FROM unnest($4::text[]) AS m`, + recipient, sender, offset, ids, landing) if junked { execSQL(t, handle.Pool, ` INSERT INTO warmup_spam_reports (reporter_account_id, reported_account_id, message_id, report_type, created_at) diff --git a/internal/app/warmup/pool_membership_live_test.go b/internal/app/warmup/pool_membership_live_test.go index bb2da814f..1c2bb6259 100644 --- a/internal/app/warmup/pool_membership_live_test.go +++ b/internal/app/warmup/pool_membership_live_test.go @@ -48,9 +48,11 @@ func newPoolMailbox(t *testing.T, handle *db.DB, poolType string) *poolMailbox { f.user, "wp-"+f.user.String()[:8]+"@test.local") exec(`INSERT INTO organizations (id, name, slug, owner_user_id) VALUES ($1, 'Warmup Pool Live', $2, $3)`, f.org, "wp-"+f.org.String()[:8], f.user) + // MoveToPool admits only a mailbox that consented to send and receive test mail (000273). exec(`INSERT INTO email_accounts (id, user_id, organization_id, email, name, - signature_plain, signature_html, provider, status, campaign_limit, min_wait_time, timezone, warmup_pool_type) - VALUES ($1, $2, $3, $4, 'Pool', '', '', 'smtp_imap', 'active', 50, 600, 'UTC', $5)`, + signature_plain, signature_html, provider, status, campaign_limit, min_wait_time, timezone, warmup_pool_type, + test_mode, test_send_enabled, test_receive_enabled) + VALUES ($1, $2, $3, $4, 'Pool', '', '', 'smtp_imap', 'active', 50, 600, 'UTC', $5, 'diagnostic', true, true)`, f.account, f.user, f.org, "wp-"+f.account.String()[:8]+"@test.local", poolType) if poolType != "" { diff --git a/internal/jobs/mailbox_erasure_live_test.go b/internal/jobs/mailbox_erasure_live_test.go index 74c18e517..8580ac4d5 100644 --- a/internal/jobs/mailbox_erasure_live_test.go +++ b/internal/jobs/mailbox_erasure_live_test.go @@ -103,7 +103,7 @@ func TestLiveErasureRemovesTheStoredMailAndTheQueueRow(t *testing.T) { // The delete itself, through the repository the API uses. emails := repository.NewEmailRepostory(handle, nil) - if xerr := emails.Delete(ctx, user.String(), mailbox.String(), 1); xerr != nil { + if xerr := emails.Delete(ctx, org.String(), mailbox.String(), 1); xerr != nil { t.Fatalf("delete mailbox: %v", xerr) } diff --git a/internal/repository/mailbox_sources_live_test.go b/internal/repository/mailbox_sources_live_test.go index beb96160e..db1d70e7a 100644 --- a/internal/repository/mailbox_sources_live_test.go +++ b/internal/repository/mailbox_sources_live_test.go @@ -490,9 +490,18 @@ func TestLiveMailboxSourcesSigninConversions(t *testing.T) { } }) + // An enrollment belongs to the workspace's Cloud link, kept for every later subtest. + instance := uuid.New() + if _, err := pool.Exec(ctx, `INSERT INTO cloud_link (cloud_url, instance_id, token, organization_id) VALUES ('https://cloud.test', $1, 'fixture', $2)`, instance, f.org); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _, _ = pool.Exec(context.Background(), `DELETE FROM cloud_link WHERE instance_id = $1`, instance) + }) + t.Run("a mailbox managed elsewhere is never offered or moved", func(t *testing.T) { box := signin("managed-" + f.org.String()[:8] + "@conv.io") - if _, err := pool.Exec(ctx, `INSERT INTO cloud_link_mailboxes (email_account_id, remote_id, managed) VALUES ($1, $2, true)`, box, uuid.New()); err != nil { + if _, err := pool.Exec(ctx, `INSERT INTO cloud_link_mailboxes (email_account_id, remote_id, managed, instance_id) VALUES ($1, $2, true, $3)`, box, uuid.New(), instance); err != nil { t.Fatal(err) } list, _ := emails.ListSigninRetiring(ctx, f.org) diff --git a/internal/repository/pg_auth_live_test.go b/internal/repository/pg_auth_live_test.go index c3c72a81d..b3f342da8 100644 --- a/internal/repository/pg_auth_live_test.go +++ b/internal/repository/pg_auth_live_test.go @@ -59,11 +59,18 @@ func TestLivePasswordCredentials(t *testing.T) { assertRejected(t, "missing-"+email, "arbitrary password") }) - t.Run("malformed nonempty hash remains an internal error", func(t *testing.T) { + t.Run("malformed nonempty hash cannot be verified", func(t *testing.T) { if xerr := repo.ResetPassword(ctx, user.ID, "malformed"); xerr != nil { t.Fatal(xerr) } - id, xerr := repo.IsValidCredentials(ctx, email, "arbitrary password") + // The unparseable hash is reported to error tracking; the caller gets the uniform refusal. + assertRejected(t, email, "arbitrary password") + }) + + t.Run("a database fault is an internal error, not a refusal", func(t *testing.T) { + failed, cancel := context.WithCancel(ctx) + cancel() + id, xerr := repo.IsValidCredentials(failed, email, "arbitrary password") if id != uuid.Nil || xerr == nil || xerr.Code != errx.InternalError().Code { t.Fatalf("credentials = (%v, %v), want nil ID and internal error", id, xerr) } diff --git a/internal/repository/pg_inbox_follow_up.go b/internal/repository/pg_inbox_follow_up.go index df29b9564..5d54c84e1 100644 --- a/internal/repository/pg_inbox_follow_up.go +++ b/internal/repository/pg_inbox_follow_up.go @@ -101,7 +101,8 @@ func followUpPageSQL(keyset string) string { } // followUpStatesSQL resolves follow-up facts for the threads in a heads(id, thread_id) CTE; $1 is the org. -const followUpStatesSQL = `states AS ( +// MATERIALIZED so the facts resolve once per query, not once per page row when the planner nests the join. +const followUpStatesSQL = `states AS MATERIALIZED ( SELECT h.id, h.thread_id, agg.last_in, agg.last_out, agg.last_any, COALESCE(best.intent, '') AS intent, COALESCE(newest.kind, '') AS kind FROM heads h diff --git a/internal/repository/pg_monitoring_clock_live_test.go b/internal/repository/pg_monitoring_clock_live_test.go index e3bc6de39..a785323fc 100644 --- a/internal/repository/pg_monitoring_clock_live_test.go +++ b/internal/repository/pg_monitoring_clock_live_test.go @@ -30,7 +30,7 @@ func (tr *monitoringClockTrace) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, } } -func monitoringClockPool(t *testing.T, pool *pgxpool.Pool, trace *monitoringClockTrace) *pgxpool.Pool { +func monitoringClockPool(t *testing.T, pool *pgxpool.Pool, trace *monitoringClockTrace, scope monitoringScope) *pgxpool.Pool { t.Helper() cfg := pool.Config().Copy() cfg.MaxConns = 1 @@ -39,6 +39,7 @@ func monitoringClockPool(t *testing.T, pool *pgxpool.Pool, trace *monitoringCloc cfg.ConnConfig.RuntimeParams["statement_timeout"] = "3000" cfg.ConnConfig.RuntimeParams["timezone"] = "America/Los_Angeles" cfg.ConnConfig.Tracer = trace + scope.isolate(cfg) ro, err := pgxpool.NewWithConfig(t.Context(), cfg) if err != nil { t.Fatal(err) @@ -91,7 +92,7 @@ func TestLiveMonitoringDatabaseClockAfterRequestStart(t *testing.T) { t.Fatal("fixture receipt did not follow request start") } trace := &monitoringClockTrace{} - ro := monitoringClockPool(t, pool, trace) + ro := monitoringClockPool(t, pool, trace, monitoringScope{nodes: []uuid.UUID{worker}, orgs: []uuid.UUID{f.org}}) before := monitoringWorkerClock(t, pool) got := collectMonitoring(t, NewMonitoringRepository(ro), source, requested) after := monitoringWorkerClock(t, pool) @@ -122,7 +123,7 @@ func TestLiveMonitoringDatabaseClockWarningSemantics(t *testing.T) { f.exec(`UPDATE email_accounts SET status='active',worker_id=$2 WHERE id=$1`, f.account, worker) now := monitoringWorkerClock(t, pool) stale, future, expired := now.Add(-time.Hour), now.Add(time.Hour), now.Add(-time.Second) - r := NewMonitoringRepository(monitoringClockPool(t, pool, &monitoringClockTrace{})) + r := NewMonitoringRepository(monitoringClockPool(t, pool, &monitoringClockTrace{}, monitoringScope{nodes: []uuid.UUID{worker}, orgs: []uuid.UUID{f.org}})) for _, tc := range []struct { name, provider, metric string last, hold *time.Time @@ -277,7 +278,7 @@ func TestLiveMonitoringDatabaseClockSingleSnapshot(t *testing.T) { old := monitoringWorkerClock(t, pool).Add(-time.Hour) f.exec(`INSERT INTO email_sync_state(email_id,user_id,last_synced_at) VALUES($1,$2,$3)`, f.account, f.user, old) trace := &monitoringClockTrace{} - ro := monitoringClockPool(t, pool, trace) + ro := monitoringClockPool(t, pool, trace, monitoringScope{nodes: []uuid.UUID{worker}, orgs: []uuid.UUID{f.org}}) var pid int if err := ro.QueryRow(t.Context(), `SELECT pg_backend_pid()`).Scan(&pid); err != nil { t.Fatal(err) diff --git a/internal/repository/pg_monitoring_worker_live_test.go b/internal/repository/pg_monitoring_worker_live_test.go index a3cc21267..3122728be 100644 --- a/internal/repository/pg_monitoring_worker_live_test.go +++ b/internal/repository/pg_monitoring_worker_live_test.go @@ -35,11 +35,45 @@ func (tr *monitoringWorkerTrace) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, } } -func monitoringTracedWorkerPool(t *testing.T, pool *pgxpool.Pool, trace *monitoringWorkerTrace) *pgxpool.Pool { +// monitoringScope is the fleet and the workspaces a test owns in the shared database. +type monitoringScope struct{ nodes, orgs []uuid.UUID } + +func monitoringUUIDArray(ids []uuid.UUID) string { + parts := make([]string, len(ids)) + for i, id := range ids { + parts[i] = id.String() + } + return "'{" + strings.Join(parts, ",") + "}'::uuid[]" +} + +// isolate shadows the instance-wide tables with temp views, so unmodified monitoring SQL sees only this test's rows. +func (s monitoringScope) isolate(cfg *pgxpool.Config) { + nodes, orgs := monitoringUUIDArray(s.nodes), monitoringUUIDArray(s.orgs) + ddl := `BEGIN READ WRITE; + CREATE TEMP VIEW fleet_nodes AS SELECT * FROM public.fleet_nodes WHERE id = ANY (` + nodes + `); + CREATE TEMP VIEW worker_health_samples AS SELECT * FROM public.worker_health_samples WHERE worker_id = ANY (` + nodes + `); + CREATE TEMP VIEW email_accounts AS SELECT * FROM public.email_accounts WHERE organization_id = ANY (` + orgs + `); + CREATE TEMP VIEW email_sync_state AS SELECT s.* FROM public.email_sync_state s JOIN email_accounts e ON e.id = s.email_id; + COMMIT` + cfg.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error { + _, err := conn.Exec(ctx, ddl) + return err + } +} + +func monitoringScopedReadOnlyPool(t *testing.T, pool *pgxpool.Pool, scope monitoringScope) *pgxpool.Pool { + t.Helper() + return monitoringTracedWorkerPool(t, pool, nil, scope) +} + +func monitoringTracedWorkerPool(t *testing.T, pool *pgxpool.Pool, trace *monitoringWorkerTrace, scope monitoringScope) *pgxpool.Pool { t.Helper() cfg := pool.Config().Copy() cfg.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on" - cfg.ConnConfig.Tracer = trace + if trace != nil { + cfg.ConnConfig.Tracer = trace + } + scope.isolate(cfg) ro, err := pgxpool.NewWithConfig(t.Context(), cfg) if err != nil { t.Fatal(err) @@ -86,7 +120,7 @@ func TestLiveMonitoringWorkerHeartbeatAfterRefreshStart(t *testing.T) { if err := fleet.UpsertOnHeartbeat(t.Context(), models.NodeHeartbeat{NodeID: id, Role: models.NodeRoleWorker}); err != nil { t.Fatal(err) } - got := collectMonitoring(t, NewMonitoringRepository(monitoringReadOnlyPool(t, pool)), "workers", at) + got := collectMonitoring(t, NewMonitoringRepository(monitoringScopedReadOnlyPool(t, pool, monitoringScope{nodes: []uuid.UUID{id}})), "workers", at) m := measuredMonitoring(t, got, "workers_missing_heartbeat") if *m.Count != 0 || len(got.Metrics) != 1 || *got.ExpectedScopes != 0 || *got.MeasuredScopes != 0 { t.Fatalf("in-collection native heartbeat classified missing/future: %+v", got) @@ -107,7 +141,7 @@ func TestLiveMonitoringWorkerHeartbeatSingleSnapshot(t *testing.T) { t.Fatal(err) } }} - got := collectMonitoring(t, NewMonitoringRepository(monitoringTracedWorkerPool(t, pool, trace)), "workers", at) + got := collectMonitoring(t, NewMonitoringRepository(monitoringTracedWorkerPool(t, pool, trace, monitoringScope{nodes: []uuid.UUID{id}})), "workers", at) m := measuredMonitoring(t, got, "workers_missing_heartbeat") if *m.Count != 0 || len(got.Metrics) != 1 || *got.ExpectedScopes != 0 || *got.MeasuredScopes != 0 || trace.queries.Load() != 1 { t.Fatalf("aggregate/details observed different heartbeats (queries=%d): %+v", trace.queries.Load(), got) @@ -150,7 +184,7 @@ func TestLiveMonitoringWorkerHeartbeatStatesAndClockBoundary(t *testing.T) { } f := newWarmupUsageFixture(t, pool) f.exec(`UPDATE email_accounts SET worker_id=$1 WHERE id=$2`, id, f.account) - r := NewMonitoringRepository(monitoringReadOnlyPool(t, pool)) + r := NewMonitoringRepository(monitoringScopedReadOnlyPool(t, pool, monitoringScope{nodes: []uuid.UUID{id}, orgs: []uuid.UUID{f.org}})) snapshot := monitoring.New([]monitoring.Source{r.workerSource()}).Snapshot(t.Context(), models.AdminPermViewWorkers) got := snapshot.Sources[0] m := measuredMonitoring(t, got, "workers_missing_heartbeat") @@ -230,18 +264,22 @@ func TestLiveMonitoringWorkerHeartbeatAggregateClockUncertainty(t *testing.T) { ids[i] = monitoringWorkerNode(t, pool, "worker", true, &future) conditions[ids[i].String()] = models.MonitoringUnknown } + scope := monitoringScope{nodes: slices.Clone(ids)} if tc.stale { id := monitoringWorkerNode(t, pool, "worker", true, &stale) conditions[id.String()] = models.MonitoringTelemetryStale + scope.nodes = append(scope.nodes, id) } if tc.missing { id := monitoringWorkerNode(t, pool, "worker", true, nil) conditions[id.String()] = models.MonitoringTelemetryStale + scope.nodes = append(scope.nodes, id) } f := newWarmupUsageFixture(t, pool) + scope.orgs = []uuid.UUID{f.org} f.exec(`UPDATE email_accounts SET worker_id=$1 WHERE id=$2`, ids[0], f.account) trace := &monitoringWorkerTrace{} - r := NewMonitoringRepository(monitoringTracedWorkerPool(t, pool, trace)) + r := NewMonitoringRepository(monitoringTracedWorkerPool(t, pool, trace, scope)) got := monitoring.New([]monitoring.Source{r.workerSource()}).Snapshot(t.Context(), models.AdminPermViewWorkers).Sources[0] m := measuredMonitoring(t, got, "workers_missing_heartbeat") total := int64(len(conditions)) @@ -274,8 +312,10 @@ func TestLiveMonitoringWorkerHeartbeatSampleAndAssignments(t *testing.T) { ids[i] = monitoringWorkerNode(t, pool, "worker", true, nil) } slices.SortFunc(ids, func(a, b uuid.UUID) int { return bytes.Compare(a[:], b[:]) }) + scope := monitoringScope{nodes: ids} if total > 0 { f, other := newWarmupUsageFixture(t, pool), newWarmupUsageFixture(t, pool) + scope.orgs = []uuid.UUID{f.org, other.org} f.exec(`UPDATE email_accounts SET worker_id=$1 WHERE id=$2`, ids[0], f.account) other.exec(`UPDATE email_accounts SET worker_id=$1 WHERE id=$2`, ids[len(ids)-1], other.account) copyID := uuid.New() @@ -283,7 +323,7 @@ func TestLiveMonitoringWorkerHeartbeatSampleAndAssignments(t *testing.T) { f.exec(`UPDATE email_accounts SET worker_id=$1 WHERE id=$2`, ids[0], copyID) t.Cleanup(func() { _, _ = pool.Exec(context.Background(), `DELETE FROM email_accounts WHERE id=$1`, copyID) }) } - r := NewMonitoringRepository(monitoringReadOnlyPool(t, pool)) + r := NewMonitoringRepository(monitoringScopedReadOnlyPool(t, pool, scope)) got := monitoring.New([]monitoring.Source{r.workerSource()}).Snapshot(t.Context(), models.AdminPermViewWorkers).Sources[0] m := measuredMonitoring(t, got, "workers_missing_heartbeat") if *m.Count != total || *got.ExpectedScopes != total || *got.MeasuredScopes != min(total, 20) || len(got.Metrics) != int(min(total, 20))+1 { @@ -340,7 +380,7 @@ func TestLiveMonitoringWorkerHeartbeatConcurrentRead(t *testing.T) { } } trace := &monitoringWorkerTrace{} - r := NewMonitoringRepository(monitoringTracedWorkerPool(t, pool, trace)) + r := NewMonitoringRepository(monitoringTracedWorkerPool(t, pool, trace, monitoringScope{nodes: ids, orgs: []uuid.UUID{f.org}})) stop, started, done := make(chan struct{}), make(chan struct{}), make(chan error, 1) writerCtx, cancel := context.WithCancel(context.Background()) var writes atomic.Int64 diff --git a/internal/repository/pg_unibox_reply_repair_live_test.go b/internal/repository/pg_unibox_reply_repair_live_test.go index dddab115e..bcdf65944 100644 --- a/internal/repository/pg_unibox_reply_repair_live_test.go +++ b/internal/repository/pg_unibox_reply_repair_live_test.go @@ -22,8 +22,13 @@ func TestLiveCampaignReplyRepairDoesNotSkipMatchingMessagesAcrossRawPages(t *tes } t.Cleanup(func() { _, _ = handle.Pool.Exec(context.Background(), `DELETE FROM contacts WHERE id=$1`, contactID) }) - prefix := uuid.New().String()[:14] + "4000-8000-" + // The sweep is instance-wide, so the fixture takes the top of the id space and the pages end on its rows. + prefix := "ffffffff-" + uuid.New().String()[9:14] + "4000-8000-" id := func(i int) uuid.UUID { return uuid.MustParse(prefix + fmt.Sprintf("%012x", i)) } + var foreign bool + if err := handle.Pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM unibox_emails WHERE id > $1)`, id(0)).Scan(&foreign); err != nil || foreign { + t.Fatalf("fixture id range is not free in the shared database: foreign=%t err=%v", foreign, err) + } var values [][]any for i := 1; i <= 502; i++ { folder := "inbox" diff --git a/internal/repository/query_prepare_live_test.go b/internal/repository/query_prepare_live_test.go index f62df60f2..d2037041a 100644 --- a/internal/repository/query_prepare_live_test.go +++ b/internal/repository/query_prepare_live_test.go @@ -4,6 +4,11 @@ import ( "context" "errors" "fmt" + "go/ast" + "go/constant" + "go/parser" + "go/token" + "go/types" "os" "path/filepath" "regexp" @@ -40,8 +45,8 @@ import ( // `user_rate_limits.daily_email_limit` column and a `campaign_status` value // called 'stopped', none of which exist, and each failed 100% of the time. // -// Syntax errors stay tolerated: the extractor below is a regex over source and -// will pick up the first fragment of a statement that is assembled at runtime. +// Any other prepare error fails too: the extractor folds only complete constant +// expressions, so a statement assembled at runtime is skipped, never half-read. const ( indeterminateDatatype = "42P08" // a $n Postgres cannot assign a type to undefinedColumn = "42703" @@ -63,14 +68,14 @@ var unrunnable = map[string]string{ } var ( - // A backtick string literal in Go source. - rawLiteral = regexp.MustCompile("`([^`]*)`") // Something that starts like a complete statement. statementStart = regexp.MustCompile(`(?is)^\s*(SELECT|INSERT|UPDATE|DELETE|WITH)\b`) // Placeholders. No placeholders means no parameter to be ambiguous about. hasParam = regexp.MustCompile(`\$\d`) // Assembled with fmt: not a statement, just a template. - isTemplate = regexp.MustCompile(`%[sdvqt]`) + isTemplate = regexp.MustCompile(`%(\[\d+\])?[sdvqt]`) + // Session setup the package runs before statements that read pg_temp tables. + tempTable = regexp.MustCompile(`(?is)^\s*CREATE\s+TEMP(ORARY)?\s+TABLE\b`) ) type extractedQuery struct { @@ -79,45 +84,160 @@ type extractedQuery struct { sql string } -func extractQueries(t *testing.T, dir string) []extractedQuery { +// harvest is every complete statement in the package's source and the temp tables it creates. +type harvest struct { + queries []extractedQuery + tempTables []string + unassembled int +} + +// extractQueries type-checks the package and takes every maximal string constant expression as a statement. +func extractQueries(t *testing.T, dir string) harvest { t.Helper() entries, err := os.ReadDir(dir) if err != nil { t.Fatalf("read %s: %v", dir, err) } - - var out []extractedQuery + fset := token.NewFileSet() + var files []*ast.File for _, e := range entries { name := e.Name() if e.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") { continue } - src, err := os.ReadFile(filepath.Join(dir, name)) + f, err := parser.ParseFile(fset, filepath.Join(dir, name), nil, 0) if err != nil { - t.Fatalf("read %s: %v", name, err) + t.Fatalf("parse %s: %v", name, err) } - for _, m := range rawLiteral.FindAllSubmatchIndex(src, -1) { - sql := string(src[m[2]:m[3]]) - if !hasParam.MatchString(sql) || - !statementStart.MatchString(sql) || - isTemplate.MatchString(sql) { - continue + files = append(files, f) + } + + // Imports are not resolved; constant folding of the package's own strings does not need them. + info := &types.Info{Types: map[ast.Expr]types.TypeAndValue{}, Defs: map[*ast.Ident]types.Object{}, Uses: map[*ast.Ident]types.Object{}} + conf := types.Config{Importer: noImporter{}, Error: func(error) {}} + _, _ = conf.Check("repository", fset, files, info) + + stringConst := func(e ast.Expr) (string, bool) { + tv, ok := info.Types[e] + if !ok || tv.Value == nil || tv.Value.Kind() != constant.String { + return "", false + } + return constant.StringVal(tv.Value), true + } + + // A constant spliced into a + chain is a fragment; the chain is checked where it is assembled. + fragments := map[types.Object]bool{} + for _, f := range files { + ast.Inspect(f, func(n ast.Node) bool { + if isConcat(n) { + for _, op := range concatOperands(n.(ast.Expr)) { + if id, ok := op.(*ast.Ident); ok && info.Uses[id] != nil { + fragments[info.Uses[id]] = true + } + } } - out = append(out, extractedQuery{ - file: name, - line: strings.Count(string(src[:m[0]]), "\n") + 1, - sql: sql, - }) + return true + }) + } + + var h harvest + for _, f := range files { + skip := map[ast.Node]bool{} + ast.Inspect(f, func(n ast.Node) bool { + if n == nil || skip[n] { + return false + } + switch v := n.(type) { + case *ast.ValueSpec: + for i, name := range v.Names { + if i < len(v.Values) && fragments[info.Defs[name]] { + skip[v.Values[i]] = true + } + } + return true + case *ast.CompositeLit: + // monitoringStatement assembles these; the test prepares the assembled form. + if at, ok := v.Type.(*ast.ArrayType); ok && isIdent(at.Elt, "monitoringQuery") { + for _, el := range v.Elts { + if q, ok := el.(*ast.CompositeLit); ok { + skipMonitoringQuery(q, skip) + } + } + } + if isIdent(v.Type, "monitoringQuery") { + skipMonitoringQuery(v, skip) + } + return true + } + expr, ok := n.(ast.Expr) + if !ok { + return true + } + sql, ok := stringConst(expr) + if !ok { + if isConcat(n) { + for _, op := range concatOperands(expr) { + if _, isString := stringConst(op); isString { + // A chain with a runtime operand cannot be assembled from source. + h.unassembled++ + return false + } + } + } + return true + } + pos := fset.Position(expr.Pos()) + switch { + case tempTable.MatchString(sql): + h.tempTables = append(h.tempTables, sql) + case hasParam.MatchString(sql) && statementStart.MatchString(sql) && !isTemplate.MatchString(sql): + h.queries = append(h.queries, extractedQuery{file: filepath.Base(pos.Filename), line: pos.Line, sql: sql}) + } + return false + }) + } + sort.Slice(h.queries, func(i, j int) bool { + if h.queries[i].file != h.queries[j].file { + return h.queries[i].file < h.queries[j].file + } + return h.queries[i].line < h.queries[j].line + }) + return h +} + +type noImporter struct{} + +func (noImporter) Import(path string) (*types.Package, error) { + return nil, fmt.Errorf("not resolved: %s", path) +} + +func isIdent(e ast.Expr, name string) bool { + id, ok := e.(*ast.Ident) + return ok && id.Name == name +} + +func skipMonitoringQuery(cl *ast.CompositeLit, skip map[ast.Node]bool) { + for _, el := range cl.Elts { + if kv, ok := el.(*ast.KeyValueExpr); ok && isIdent(kv.Key, "query") { + skip[kv.Value] = true } } - sort.Slice(out, func(i, j int) bool { - if out[i].file != out[j].file { - return out[i].file < out[j].file - } - return out[i].line < out[j].line - }) - return out +} + +func isConcat(n ast.Node) bool { + b, ok := n.(*ast.BinaryExpr) + return ok && b.Op == token.ADD +} + +func concatOperands(e ast.Expr) []ast.Expr { + if p, ok := e.(*ast.ParenExpr); ok { + return concatOperands(p.X) + } + if b, ok := e.(*ast.BinaryExpr); ok && b.Op == token.ADD { + return append(concatOperands(b.X), concatOperands(b.Y)...) + } + return []ast.Expr{e} } func TestLiveEveryQueryPrepares(t *testing.T) { @@ -133,14 +253,36 @@ func TestLiveEveryQueryPrepares(t *testing.T) { } defer conn.Close(ctx) - queries := extractQueries(t, ".") + h := extractQueries(t, ".") + queries := h.queries if len(queries) < 100 { t.Fatalf("only found %d statements to check; the extractor is broken", len(queries)) } + for _, id := range monitoringSectionOrder { + queries = append(queries, extractedQuery{file: "monitoringStatement(" + id + ")", sql: monitoringStatement(monitoringSections[id])}) + } + + // Temp tables are ON COMMIT DROP, so the sweep runs in one transaction with a savepoint per statement. + tx, err := conn.Begin(ctx) + if err != nil { + t.Fatalf("begin: %v", err) + } + defer func() { _ = tx.Rollback(ctx) }() + for _, ddl := range h.tempTables { + if _, err := tx.Exec(ctx, ddl); err != nil { + t.Fatalf("create temp table: %v\n\t%s", err, oneLine(ddl)) + } + } var broken, other []string for i, q := range queries { - _, err := conn.Prepare(ctx, fmt.Sprintf("check_%d", i), strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(q.sql), ";"))) + if _, err := tx.Exec(ctx, "SAVEPOINT prepare_check"); err != nil { + t.Fatalf("savepoint: %v", err) + } + _, err := tx.Prepare(ctx, fmt.Sprintf("check_%d", i), strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(q.sql), ";"))) + if _, rbErr := tx.Exec(ctx, "ROLLBACK TO SAVEPOINT prepare_check"); rbErr != nil { + t.Fatalf("rollback to savepoint: %v", rbErr) + } if err == nil { continue } @@ -157,10 +299,8 @@ func TestLiveEveryQueryPrepares(t *testing.T) { other = append(other, fmt.Sprintf("%s: %v", where, err)) } - // Informational: a fragment of a runtime-assembled statement lands here. if len(other) > 0 { - t.Logf("%d statement(s) could not be prepared for other reasons (runtime-assembled fragments):\n%s", - len(other), strings.Join(other, "\n")) + t.Errorf("%d statement(s) could not be prepared:\n%s", len(other), strings.Join(other, "\n")) } if len(broken) > 0 { @@ -168,7 +308,7 @@ func TestLiveEveryQueryPrepares(t *testing.T) { len(broken), strings.Join(broken, "\n")) } - t.Logf("checked %d parameterised statements", len(queries)) + t.Logf("checked %d parameterised statements; %d runtime-assembled chains not checked", len(queries), h.unassembled) } func oneLine(s string) string { From 8a3949db489ddd560ce89b5dd9d9955315633bd5 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 09:18:04 +0100 Subject: [PATCH 129/318] feat: cover the warmup pool admission gate with a live test that refuses a mailbox whose test mail is off or whose diagnostic mode allows neither sending nor receiving --- .../app/warmup/pool_membership_live_test.go | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/internal/app/warmup/pool_membership_live_test.go b/internal/app/warmup/pool_membership_live_test.go index 1c2bb6259..6ceec00d8 100644 --- a/internal/app/warmup/pool_membership_live_test.go +++ b/internal/app/warmup/pool_membership_live_test.go @@ -122,6 +122,28 @@ func TestLiveJoiningTheOtherPoolMovesTheMailboxRatherThanDuplicatingIt(t *testin } } +// A mailbox that has not consented to test mail is never admitted to a pool. +func TestLiveMoveToPoolRefusesAMailboxWithoutTestMailConsent(t *testing.T) { + for name, consent := range map[string]string{ + "test mail off": `test_mode = 'off'`, + "diagnostic without send or receive": `test_send_enabled = false, test_receive_enabled = false`, + } { + t.Run(name, func(t *testing.T) { + repo, handle := liveWarmupRepo(t) + f := newPoolMailbox(t, handle, "") + ctx := context.Background() + execSQL(t, handle.Pool, `UPDATE email_accounts SET `+consent+` WHERE id = $1`, f.account) + + if err := repo.MoveToPool(ctx, models.WarmupPoolFreeID, f.account, "sender_receiver"); err == nil { + t.Fatal("admitted a mailbox without test mail consent") + } + if got := f.memberships(t); len(got) != 0 { + t.Fatalf("memberships %v, want none", got) + } + }) + } +} + // Moving pools must not launder a penalty. A fresh row would start healthy, // which is how a blocked mailbox could have re-entered the pool it was // blocked out of. From dc0c7b1eaae7339edd0376ac74354d9853790d87 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Tue, 3 Nov 2026 08:53:33 +0100 Subject: [PATCH 130/318] feat: accept snake_case, camelCase and lowercase aliases of built-in template fields through one shared tmplvars normalisation, refuse unrenderable step, variant and campaign-create copy with invalid_template, and fix the documented merge-field syntax in docs, CLI and seeds --- cmd/cli/specs.go | 2 +- cmd/seed/main.go | 6 +- docs/content/docs/api/error-codes.mdx | 1 + docs/content/docs/api/reference/campaigns.mdx | 39 ++- docs/content/docs/guides/ai-variables.mdx | 4 +- docs/content/docs/guides/expressions.mdx | 20 +- .../docs/learn/reputation-recovery.mdx | 2 +- internal/app/advanced/service.go | 24 ++ internal/app/advisor/detect_copy.go | 7 +- internal/app/advisor/detect_list.go | 10 +- internal/app/advisor/detect_test.go | 15 + internal/app/campaign/handlers.go | 15 +- internal/app/campaign/template_copy.go | 29 ++ internal/app/campaign/template_copy_test.go | 28 ++ internal/app/sequence/handler.go | 21 ++ internal/app/sequence/handler_test.go | 55 ++++ internal/errx/common.go | 11 + internal/models/form_event.go | 8 +- internal/models/sequence.go | 2 +- internal/pkg/tmplvars/normalize.go | 304 ++++++++++++++++++ internal/pkg/tmplvars/normalize_test.go | 88 +++++ internal/pkg/tmplvars/sender.go | 60 ++++ internal/pkg/tmplvars/vars.go | 134 ++++++++ internal/repository/pg_advisor.go | 2 +- internal/seed/campaigns.go | 8 +- internal/seed/dev_org.go | 14 +- internal/tasks/campaign_task.go | 2 +- internal/tasks/optout.go | 3 +- internal/tasks/template.go | 87 +---- internal/tasks/template_html.go | 2 +- internal/tasks/template_sender.go | 59 +--- internal/tasks/template_test.go | 32 ++ internal/utils/json.go | 2 +- internal/utils/json_test.go | 2 +- .../app/automations/ExpressionReference.tsx | 2 +- web/src/lib/templateVars.ts | 4 +- 36 files changed, 894 insertions(+), 210 deletions(-) create mode 100644 internal/app/campaign/template_copy.go create mode 100644 internal/app/campaign/template_copy_test.go create mode 100644 internal/app/sequence/handler_test.go create mode 100644 internal/pkg/tmplvars/normalize.go create mode 100644 internal/pkg/tmplvars/normalize_test.go create mode 100644 internal/pkg/tmplvars/sender.go create mode 100644 internal/pkg/tmplvars/vars.go diff --git a/cmd/cli/specs.go b/cmd/cli/specs.go index 3c86e9157..fa775fd39 100644 --- a/cmd/cli/specs.go +++ b/cmd/cli/specs.go @@ -144,7 +144,7 @@ ask before they do it.`, Name: "add-step", Short: "Add a sequence step", Method: http.MethodPost, Path: "/campaigns/{id}/steps", Body: bodyRequired, Args: []argSpec{{Name: "id", Help: "The campaign's id"}}, - Example: " $ warmbly campaign add-step CAMPAIGN_ID --subject \"Quick question\" --body-html \"

    Hi {{first_name}}

    \"", + Example: " $ warmbly campaign add-step CAMPAIGN_ID --subject \"Quick question\" --body-html \"

    Hi {{.FirstName}}

    \"", Flag: []flagSpec{ {Name: "subject", Help: "Subject line"}, {Name: "body-html", Help: "HTML body"}, diff --git a/cmd/seed/main.go b/cmd/seed/main.go index 42b95ab16..4860da104 100644 --- a/cmd/seed/main.go +++ b/cmd/seed/main.go @@ -348,12 +348,12 @@ func seedRich(ctx context.Context, pool *pgxpool.Pool) error { } seq1 := uuid.MustParse("55555555-0000-0000-0000-000000000001") seq2 := uuid.MustParse("55555555-0000-0000-0000-000000000002") - if err := upsertSequence(ctx, pool, seq1, campaignID, orgBeta, "Intro", "Quick question, {{first_name}}", - "Hi {{first_name}}, ...intro body...", 0); err != nil { + if err := upsertSequence(ctx, pool, seq1, campaignID, orgBeta, "Intro", "Quick question, {{.FirstName}}", + "Hi {{.FirstName}}, ...intro body...", 0); err != nil { return err } if err := upsertSequence(ctx, pool, seq2, campaignID, orgBeta, "Follow-up", "Re: Quick question", - "Hi {{first_name}}, following up...", 3); err != nil { + "Hi {{.FirstName}}, following up...", 3); err != nil { return err } diff --git a/docs/content/docs/api/error-codes.mdx b/docs/content/docs/api/error-codes.mdx index effbe7806..fec4a33bf 100644 --- a/docs/content/docs/api/error-codes.mdx +++ b/docs/content/docs/api/error-codes.mdx @@ -146,6 +146,7 @@ Resource IDs on email, campaign and contact routes must be UUIDs. Email `tags` a | `list_bounce_risk` | `POST /campaigns/:id/start` refused the launch on the list's projected bounce rate. Clean or verify the list, or repeat the request with `acknowledge_list_risk: true` | | `leads_undeliverable` | `POST /campaigns/:id/start` found nothing to send because address verification refused every remaining lead; the campaign is parked at `paused_undeliverable` until they are re-verified or marked deliverable | | `empty_step_body` | `POST /campaigns/:id/start` found an email step with nothing in either body, so it would send a blank message to every lead it reached. Write the step's body and start again | +| `invalid_template` | A step, A/B variant or new campaign was written (or a campaign started) with a subject, HTML body or plain-text body that would not render as written: an `{{if}}` with no `{{end}}`, an unknown function, an unknown `.Sender` field, or a bare name such as `{{frist_name}}` that is not a built-in field. The `message` names the field, the line and the problem. Fix the copy and send it again; see [personalization](/guides/expressions/) | | `no_leads` | `POST /campaigns/:id/start` on a campaign that has never had a lead, with `continuous` off. Add contacts, or set `continuous` so it starts empty and waits for them. A campaign whose leads have all finished is a different case: it starts and waits | | `no_remaining_leads` | A platform-initiated restart of a campaign with nothing left to send and `continuous` off found nothing to do; the campaign is `completed` again. A start you request never answers this: it turns `continuous` on and waits | | `too_many_tasks` | `PATCH /crm/tasks` or `DELETE /crm/tasks` was given more than `1000` ids in one request, or more than `50,000` exclusions. Split it into batches | diff --git a/docs/content/docs/api/reference/campaigns.mdx b/docs/content/docs/api/reference/campaigns.mdx index b045c4a88..547629c20 100644 --- a/docs/content/docs/api/reference/campaigns.mdx +++ b/docs/content/docs/api/reference/campaigns.mdx @@ -226,7 +226,7 @@ Create a campaign. Only `name` is required, every other field is optional and ap | `continuous` | boolean | no | Keep running for new leads: out of leads, the campaign stays `active` and waits instead of finishing. Linking a segment, a form or an automation that enrols leads turns it on, and so does starting a campaign whose every lead has finished. Default `false`. | | `tracking_domain` | string | no | Campaign-scoped tracking domain (honored only once verified). | | `steps` | object[] | no | Initial sequence steps in order (see create sequence input below). They are connected in order: each step routes unconditionally to the next, waiting that step's `wait_after` days. The first step's `wait_after` defaults to `0`, follow-ups to `3`. A step given no `subject`, or the same one as the conversation so far, defaults to `thread_reply: true` and is sent as a reply carrying that conversation's subject; a step with a subject of its own defaults to `false` and opens a new conversation. Set `thread_reply` explicitly to override either. | -| `variants` | object[] | no | A/B variants for the first step (same shape as create A/B variant). | +| `variants` | object[] | no | A/B variants for the first step (same shape as create A/B variant). A step or variant whose copy would not render as written refuses the whole request with `invalid_template`, naming it, and creates nothing. | | `advanced_overrides` | object | no | Advanced outreach overrides, see [advanced settings](#get-advanced-settings). | `schedule_windows` may also be supplied as a 7-element array (indexed by `time.Weekday`, Sunday = 0) of `{start, end}` minute intervals. When non-empty it supersedes `days`/`start_time`/`end_time`. @@ -249,7 +249,7 @@ Create a campaign. Only `name` is required, every other field is optional and ap "ramp_increment": 2, "ramp_ceiling": 40, "steps": [ - { "name": "Step 1", "subject": "Quick question, {{first_name}}", "body_plain": "Hi {{first_name}}...", "wait_after": 0 }, + { "name": "Step 1", "subject": "Quick question, {{.FirstName}}", "body_plain": "Hi {{.FirstName}}...", "wait_after": 0 }, { "name": "Step 2", "subject": "", "body_plain": "Just bumping this...", "wait_after": 3 } ] } @@ -479,9 +479,9 @@ A `data` array of `CampaignABVariant` objects (no pagination wrapper). "step_id": "7e3b...", "name": "Subject B", "weight": 50, - "subject": "Worth a look, {{first_name}}?", - "body_html": "

    Hi {{first_name}}...

    ", - "body_plain": "Hi {{first_name}}...", + "subject": "Worth a look, {{.FirstName}}?", + "body_html": "

    Hi {{.FirstName}}...

    ", + "body_plain": "Hi {{.FirstName}}...", "is_control": false, "is_active": true, "promoted_at": null, @@ -523,13 +523,15 @@ Add a variant to the campaign (or to one step via `step_id`). **Scope** `WRITE_C "name": "Subject B", "step_id": "7e3b...", "weight": 50, - "subject": "Worth a look, {{first_name}}?", - "body_plain": "Hi {{first_name}}...", + "subject": "Worth a look, {{.FirstName}}?", + "body_plain": "Hi {{.FirstName}}...", "is_control": false, "is_active": true } ``` +A `subject`, `body_html` or `body_plain` that would not render as written answers `400` with `code: "invalid_template"`, as for [a step](#update-a-sequence). The same check applies to an update. + ### Response `201 Created` with the created `CampaignABVariant` object (see the [list variants](#list-ab-variants) shape). @@ -826,7 +828,7 @@ Start (activate) the campaign so it begins sending real mail. Works from `draft` A start refused because every remaining lead was refused by address verification answers `leads_undeliverable` and parks the campaign at `paused_undeliverable`; re-verify the leads or mark them deliverable with [`POST /contacts/verification`](/api/reference/contacts/#verify-or-override-contacts), which resumes it. -A campaign whose email step has nothing in either body is refused with `empty_step_body` rather than started, because it would send a blank message to every lead it reached. +A campaign whose email step has nothing in either body is refused with `empty_step_body` rather than started, because it would send a blank message to every lead it reached. A step whose copy would not render as written (saved before the check on write existed) is refused with `invalid_template`, naming the step, the field, the line and the problem. ### Response @@ -1335,9 +1337,9 @@ A bare array of `Sequence` objects (no envelope). { "id": "7e3b...", "name": "Step 1", - "subject": "Quick question, {{first_name}}", - "body_plain": "Hi {{first_name}}...", - "body_html": "

    Hi {{first_name}}...

    ", + "subject": "Quick question, {{.FirstName}}", + "body_plain": "Hi {{.FirstName}}...", + "body_html": "

    Hi {{.FirstName}}...

    ", "body_sync": true, "body_code": false, "wait_after": 0, @@ -1367,7 +1369,7 @@ Optional. It takes the same fields as [update a sequence](#update-a-sequence), a ```json { "subject": "Quick question", - "body_plain": "Hi {{first_name}}, ...", + "body_plain": "Hi {{.FirstName}}, ...", "wait_after": 3 } ``` @@ -1408,7 +1410,7 @@ All fields optional. ```json { "name": "Step 2", - "subject": "Following up, {{first_name}}", + "subject": "Following up, {{.FirstName}}", "body_plain": "Just bumping this...", "wait_after": 2, "conditions": { @@ -1423,6 +1425,8 @@ All fields optional. } ``` +`subject`, `body_plain` and `body_html` are checked before anything is saved, on a running campaign too. Copy that would not render as written answers `400` with `code: "invalid_template"` and a `message` naming the field, the line and the problem: an `{{if}}` with no `{{end}}`, an unknown function, an unknown sender field, or a bare name that is not a built-in field. Built-in fields are accepted as `{{.FirstName}}` or in their snake_case, camelCase and lowercase spellings (`{{first_name}}`); see [personalization](/guides/expressions/). + ### Response The updated `Sequence` object. @@ -1463,8 +1467,8 @@ Render subject and body templates for a contact exactly as the send path would, ```json { - "subject": "Hi {{first_name}} at {{company}}", - "body_html": "

    Hey {{first_name}}, I saw {{company}} is hiring. {{unknown_token}}

    ", + "subject": "Hi {{.FirstName}} at {{.Company}}", + "body_html": "

    Hey {{.FirstName}}, I saw {{.Company}} is hiring. {{unknown_token}}

    ", "contact_id": "9a2c...", "campaign_id": "8f1d...", "account_id": "5c7d..." @@ -1480,6 +1484,7 @@ A `TemplatePreview` object. `errors` lists template parse errors that would bloc "subject": "Hi Sam at Globex", "body_html": "

    Hey Sam, I saw Globex is hiring. {{unknown_token}}



    Best, Ana

    Don't want these emails? Unsubscribe

    ", "body_plain": "Hey Sam, I saw Globex is hiring. {{unknown_token}}\n\nBest, Ana\n\nDon't want these emails? https://app.example.com/u/...", + "errors": ["body: line 1: unknown variable \"unknown_token\": write a contact field with a leading dot, like {{.unknown_token}}; the built-in fields are FirstName, LastName, Email, Company, Phone, Sender, UnsubscribeLink"], "unresolved": ["{{unknown_token}}"], "from": { "name": "Ana Silva", "email": "ana@globex.com" }, "attachments": [ @@ -1516,7 +1521,7 @@ Generate outreach copy with the AI writing assistant. Gated to paid and free-tri ```json { - "text": "Hi {{first_name}},\n\nNoticed {{company}} is scaling outbound...\n\nWorth a quick chat?", + "text": "Hi {{.FirstName}},\n\nNoticed {{.Company}} is scaling outbound...\n\nWorth a quick chat?", "credits_remaining": 248, "model": "claude-..." } @@ -1562,7 +1567,7 @@ Generate the recipient-specific snippet a per-recipient AI variable block would | `context_after` | string | no | The email text immediately after the block. | ```json -{ "mode": "instant", "prompt": "One line noting something specific about {{company}}.", "contact_id": "4f6c..." } +{ "mode": "instant", "prompt": "One line noting something specific about {{.Company}}.", "contact_id": "4f6c..." } ``` ### Response diff --git a/docs/content/docs/guides/ai-variables.mdx b/docs/content/docs/guides/ai-variables.mdx index 87b4fc078..015bbb2b0 100644 --- a/docs/content/docs/guides/ai-variables.mdx +++ b/docs/content/docs/guides/ai-variables.mdx @@ -3,13 +3,13 @@ title: AI variables description: Drop AI blocks into a campaign email that write a unique, personalized snippet for each recipient at send time. --- -An AI variable is a block you place inside a campaign email that generates its own copy for every recipient. Where a normal variable like `{{first_name}}` substitutes a stored field, an AI variable runs a short instruction against each contact and writes a snippet tailored to them, right where you dropped it. The rest of the email is yours; the AI variable fills one spot with something specific to the person receiving it. +An AI variable is a block you place inside a campaign email that generates its own copy for every recipient. Where a normal variable like `{{.FirstName}}` substitutes a stored field, an AI variable runs a short instruction against each contact and writes a snippet tailored to them, right where you dropped it. The rest of the email is yours; the AI variable fills one spot with something specific to the person receiving it. Because it runs per recipient, an AI variable costs credits for each contact it resolves. Plan for that the same way you plan send volume. ## Adding an AI variable -In the campaign email editor, place your cursor where you want the personalized copy and insert an AI variable. Give it a short instruction, for example "one line noting something specific about their company" or "a friendly opener that references `{{company}}`". The instruction is itself a template, so you can reference contact fields inside it and they render per contact before the model runs. +In the campaign email editor, place your cursor where you want the personalized copy and insert an AI variable. Give it a short instruction, for example "one line noting something specific about their company" or "a friendly opener that references `{{.Company}}`". The instruction is itself a template, so you can reference contact fields inside it and they render per contact before the model runs. By default a block writes instantly from the contact's own fields. That is the right choice for most blocks. One optional add-on personalizes deeper: diff --git a/docs/content/docs/guides/expressions.mdx b/docs/content/docs/guides/expressions.mdx index a0243d474..1f5447ea0 100644 --- a/docs/content/docs/guides/expressions.mdx +++ b/docs/content/docs/guides/expressions.mdx @@ -31,9 +31,9 @@ Open the Preview to check it renders as expected, with no leftover `{{...}}` tok ## Good to know -- Field names are case-sensitive: `{{.FirstName}}` works, `{{.firstname}}` does not. -- Unknown variables render empty rather than erroring. -- Every `{{if}}` must close with `{{end}}`. A broken one blocks launching the campaign. +- Write fields as `{{.FirstName}}`. In campaign copy, the snake_case, camelCase and lowercase spellings of the built-in fields work too: `{{first_name}}`, `{{.firstName}}`, `{{company_name}}`. +- A custom field nobody filled in renders empty rather than erroring. +- Every `{{if}}` must close with `{{end}}`. A step or variant with a broken template cannot be saved. - Spintax such as `{Hi|Hey|Hello}` varies wording in campaign subjects and bodies only. - Automations use the trigger's lowercase keys, such as `{{.contact_email}}`, still with the leading dot. @@ -67,14 +67,14 @@ Write one email and have it come out personalized for every contact, using merge ### Contact fields (campaigns) -Exact names, **capitalized**, with a leading dot: `{{.FirstName}}`, `{{.LastName}}`, `{{.Email}}`, `{{.Company}}`, `{{.Phone}}`. +Capitalized names with a leading dot: `{{.FirstName}}`, `{{.LastName}}`, `{{.Email}}`, `{{.Company}}`, `{{.Phone}}`. ``` Hi {{.FirstName}}, I noticed {{.Company}} is hiring and wanted to reach out. ``` - -`{{.FirstName}}` works. `{{.firstname}}`, `{{.firstName}}`, and `{{.FIRSTNAME}}` do not, and leave an empty value or a leftover token in your email. + +Campaign copy also accepts the snake_case, camelCase and lowercase spellings of every built-in field, with or without the dot: `{{first_name}}`, `{{.firstName}}`, `{{firstname}}`, `{{last_name}}`, `{{email}}`, `{{company}}`, `{{company_name}}`, `{{phone}}`, `{{unsubscribe_link}}`, and `{{.Sender.first_name}}` for sender fields. They work inside conditions and helpers as well (`{{if first_name}}`, `{{first_name | default "there"}}`). A contact's own custom field with one of these names keeps its value. `{{.FIRSTNAME}}` is not one of them. **Custom fields** work the same way with a dot: `{{.industry}}`, `{{.account_owner}}`. Names containing spaces or dashes also work as written (`{{if .job title}}...{{end}}`) and resolve everywhere, including inside conditions and helpers, because Warmbly rewrites them to an `index` lookup for you. @@ -263,12 +263,12 @@ hasSuffix .contact_email "@acme.com" ## Gotchas -- Standard fields are case-sensitive: `{{.FirstName}}`, not `{{.firstname}}`. +- Standard fields are written `{{.FirstName}}`; `first_name`, `firstName` and `firstname` are accepted in campaign copy, other capitalizations are not. - `{a|b}` is spintax (campaigns only); `{{...}}` is a variable, condition, or function. - Always close `{{if}}` with `{{end}}`, and quote text values. - If a comparison on a custom field behaves oddly, switch `gt`/`lt` to `gtf`/`ltf`, or wrap the value in `num`. -- Unknown variables render empty rather than erroring. A leftover `{{...}}` usually means a typo or wrong capitalization. -- In action text keep the leading dot. It is standard Go `text/template`, so a bare `{{contact_email}}` is invalid. +- A dotted field nobody filled in renders empty rather than erroring. A bare name that is not a built-in field, like `{{frist_name}}`, is refused when the step is saved; write a custom field with the dot, `{{.city}}`. +- In automation action text keep the leading dot. It is standard Go `text/template`, so a bare `{{contact_email}}` is invalid. @@ -276,7 +276,7 @@ hasSuffix .contact_email "@acme.com" ## Preview and validation -**Campaigns**: the composer's live Preview renders against a sample contact exactly as the real send does (variables, conditionals, functions, then spintax). It flags errors like a broken `{{if}}`, which block launching, and unresolved tokens left after rendering. +**Campaigns**: the composer's live Preview renders against a sample contact exactly as the real send does (variables, conditionals, functions, then spintax). It flags errors like a broken `{{if}}` and unresolved tokens left after rendering. Saving a step, an A/B variant or a new campaign checks the subject, HTML body and plain-text body, and refuses copy that would not render as written with `invalid_template`, naming the field, the line and the problem. **Automations**: an advanced expression is validated on save, so a condition that does not parse cannot be saved. The **Reference** button lists every variable and function inline. diff --git a/docs/content/docs/learn/reputation-recovery.mdx b/docs/content/docs/learn/reputation-recovery.mdx index b72947e43..a5a7e0da0 100644 --- a/docs/content/docs/learn/reputation-recovery.mdx +++ b/docs/content/docs/learn/reputation-recovery.mdx @@ -65,7 +65,7 @@ Reply-rich first sends rebuild engagement signal fast. Cold sends to brand-new c - No tracking pixels. - One link maximum, and only if necessary. - Subject under 60 characters, no all-caps, no emojis. -- Different subject and opening line per recipient (not "Hi `{{first_name}}`, just wanted to follow up" 1,000 times). +- Different subject and opening line per recipient (not "Hi `{{.FirstName}}`, just wanted to follow up" 1,000 times). - Personal signature with full name and a phone number you can be reached at. ## When to give up and switch diff --git a/internal/app/advanced/service.go b/internal/app/advanced/service.go index 9eeab4f04..cd8efb626 100644 --- a/internal/app/advanced/service.go +++ b/internal/app/advanced/service.go @@ -18,6 +18,7 @@ import ( "github.com/rs/zerolog/log" "github.com/warmbly/warmbly/internal/pkg/dsn" "github.com/warmbly/warmbly/internal/pkg/emailverify" + "github.com/warmbly/warmbly/internal/pkg/tmplvars" "github.com/warmbly/warmbly/internal/pkg/typesafe" "github.com/warmbly/warmbly/internal/utils/validate" @@ -365,6 +366,13 @@ func (s *service) CreateABVariant(ctx context.Context, campaignID uuid.UUID, req if req == nil || strings.TrimSpace(req.Name) == "" { return nil, errx.New(errx.BadRequest, "variant name is required") } + if err := tmplvars.CheckCopy( + tmplvars.Part{Name: "variant subject", Text: req.Subject}, + tmplvars.Part{Name: "variant body", Text: req.BodyHTML}, + tmplvars.Part{Name: "variant plain-text body", Text: req.BodyPlain}, + ); err != nil { + return nil, errx.InvalidTemplate(err) + } out, err := s.repo.CreateABVariant(ctx, campaignID, req) if err != nil { return nil, toErrx(err) @@ -373,6 +381,15 @@ func (s *service) CreateABVariant(ctx context.Context, campaignID uuid.UUID, req } func (s *service) UpdateABVariant(ctx context.Context, campaignID, variantID uuid.UUID, req *models.UpdateCampaignABVariantRequest) (*models.CampaignABVariant, *errx.Error) { + if req != nil { + if err := tmplvars.CheckCopy( + tmplvars.Part{Name: "variant subject", Text: deref(req.Subject)}, + tmplvars.Part{Name: "variant body", Text: deref(req.BodyHTML)}, + tmplvars.Part{Name: "variant plain-text body", Text: deref(req.BodyPlain)}, + ); err != nil { + return nil, errx.InvalidTemplate(err) + } + } out, err := s.repo.UpdateABVariant(ctx, campaignID, variantID, req) if err != nil { return nil, toErrx(err) @@ -380,6 +397,13 @@ func (s *service) UpdateABVariant(ctx context.Context, campaignID, variantID uui return out, nil } +func deref(s *string) string { + if s == nil { + return "" + } + return *s +} + func (s *service) DeleteABVariant(ctx context.Context, campaignID, variantID uuid.UUID) *errx.Error { if err := s.repo.DeleteABVariant(ctx, campaignID, variantID); err != nil { return toErrx(err) diff --git a/internal/app/advisor/detect_copy.go b/internal/app/advisor/detect_copy.go index 9ea8e3eb6..bdfcfdf3f 100644 --- a/internal/app/advisor/detect_copy.go +++ b/internal/app/advisor/detect_copy.go @@ -154,8 +154,9 @@ func detectBrokenTemplate(s *repository.AdvisorSnapshot) []Finding { for _, sc := range emailSteps(s) { broken := map[string]string{} for field, text := range map[string]string{ - "subject": sc.step.Subject, - "body": sc.step.BodyPlain, + "subject": sc.step.Subject, + "body": sc.step.BodyHTML, + "plain-text body": sc.step.BodyPlain, } { if text == "" { continue @@ -202,7 +203,7 @@ func detectBrokenTemplate(s *repository.AdvisorSnapshot) []Finding { fmt.Sprintf("Open the campaign and go to %s.", stepLabel(sc)), fmt.Sprintf("The parser stopped here: %s.", broken[fields[0]]), "Every {{if}} and {{range}} needs its own {{end}}. A missing {{end}} is the most common cause and the error usually points past it, not at it.", - "Field names are case-sensitive and start with a dot: {{.FirstName}}, not {{firstname}}. For a custom field use {{index . \"city\"}}.", + "Write a field with a leading dot, like {{.FirstName}}; the first_name and firstName spellings of built-in fields work too. A custom field is {{.city}}, or {{index . \"city\"}}.", "Save, then use the preview to check it renders against a real contact rather than trusting that it looks right.", }, Evidence: map[string]any{ diff --git a/internal/app/advisor/detect_list.go b/internal/app/advisor/detect_list.go index f91628a63..b4df29ce0 100644 --- a/internal/app/advisor/detect_list.go +++ b/internal/app/advisor/detect_list.go @@ -278,14 +278,10 @@ func detectUnsubscribedEnrolled(s *repository.AdvisorSnapshot) []Finding { return out } -// usesFirstName reports whether the copy actually greets people by first name. -// Warmbly templates are Go templates, so the field is written `.FirstName` -// (`{{.FirstName}}`, `{{if .FirstName}}`, `{{.FirstName | title}}`) or, for the -// index form a spaced custom key would take, `"first_name"`. Checking the -// property rather than one literal spelling keeps this from silently never -// firing the way a `{{first_name}}` assumption would. +// usesFirstName reports whether the copy greets people by first name, in any +// spelling the renderer accepts (`.FirstName`, `first_name`, `firstName`). func usesFirstName(text string) bool { - for _, form := range []string{".FirstName", `"first_name"`} { + for _, form := range []string{"firstname", "first_name"} { if indexFold(text, form) >= 0 { return true } diff --git a/internal/app/advisor/detect_test.go b/internal/app/advisor/detect_test.go index b75d88b8f..a0343321c 100644 --- a/internal/app/advisor/detect_test.go +++ b/internal/app/advisor/detect_test.go @@ -759,6 +759,21 @@ func TestUnparseableTemplateIsFlagged(t *testing.T) { } } +func TestUnparseableHTMLBodyIsFlagged(t *testing.T) { + campaignID := uuid.New() + snap := snapshotOf() + snap.Campaigns = []repository.AdvisorCampaign{{ID: campaignID, Name: "Outbound", Status: "paused"}} + snap.Steps = []repository.AdvisorStep{{ + ID: uuid.New(), CampaignID: campaignID, Kind: "email", Position: 1, + Subject: "quick question", + BodyPlain: "Hi {{.FirstName}}", + BodyHTML: "

    Hi {{if .FirstName}}{{.FirstName}}

    ", + }} + if _, fired := findingsByKey(Detect(snap, defaults()))["copy_broken_template"]; !fired { + t.Fatal("a broken HTML body should be flagged: it is the part most clients show") + } +} + func TestMissingFirstNameOnlyFiresWhenTheCopyUsesIt(t *testing.T) { campaignID := uuid.New() build := func(body string) *repository.AdvisorSnapshot { diff --git a/internal/app/campaign/handlers.go b/internal/app/campaign/handlers.go index eb9bf05a1..e2ebe3ba4 100644 --- a/internal/app/campaign/handlers.go +++ b/internal/app/campaign/handlers.go @@ -23,6 +23,7 @@ import ( "github.com/warmbly/warmbly/internal/models" "github.com/warmbly/warmbly/internal/observability/errs" "github.com/warmbly/warmbly/internal/pkg/mailhtml" + "github.com/warmbly/warmbly/internal/pkg/tmplvars" "github.com/warmbly/warmbly/internal/pkg/trackdns" "github.com/warmbly/warmbly/internal/repository" "github.com/warmbly/warmbly/internal/scheduler" @@ -46,6 +47,9 @@ func (s *campaignService) Create(ctx context.Context, userID string, orgID *uuid if orgID == nil { return nil, errx.ErrNoOrganization } + if err := checkCreateCopy(data); err != nil { + return nil, errx.InvalidTemplate(err) + } // Daily creation throttle (config.DailyThrottleNewCampaigns). Caps // per-day new-campaign rate per org so an unlimited plan can't be @@ -520,15 +524,8 @@ func (s *campaignService) StartCampaign(ctx context.Context, orgID uuid.UUID, ca return errx.InternalError() } for i, seq := range seqs { - for _, f := range []struct { - name, val string - }{{"subject", seq.Subject}, {"body", seq.BodyHTML}, {"plain-text body", seq.BodyPlain}} { - if terr := tasks.TemplateError(f.val); terr != nil { - return errx.New(errx.BadRequest, fmt.Sprintf( - "Step %d's %s has a template error โ€” fix the {{if}}/{{end}} or {{eq}} syntax before starting.", - i+1, f.name, - )) - } + if terr := tmplvars.CheckCopy(stepCopy(fmt.Sprintf("step %d", i+1), seq.Subject, seq.BodyHTML, seq.BodyPlain)...); terr != nil { + return errx.InvalidTemplate(terr) } // An email step with nothing in either body sends a blank message // to every lead it reaches. A step created through the API carries diff --git a/internal/app/campaign/template_copy.go b/internal/app/campaign/template_copy.go new file mode 100644 index 000000000..3903de979 --- /dev/null +++ b/internal/app/campaign/template_copy.go @@ -0,0 +1,29 @@ +package campaign + +import ( + "fmt" + + "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/pkg/tmplvars" +) + +// stepCopy names the three copy fields of one step or variant for the validator. +func stepCopy(owner, subject, bodyHTML, bodyPlain string) []tmplvars.Part { + return []tmplvars.Part{ + {Name: owner + " subject", Text: subject}, + {Name: owner + " body", Text: bodyHTML}, + {Name: owner + " plain-text body", Text: bodyPlain}, + } +} + +// checkCreateCopy refuses a new campaign whose steps or variants would not render as written. +func checkCreateCopy(data *models.CreateCampaign) error { + var parts []tmplvars.Part + for i, seq := range data.Sequences { + parts = append(parts, stepCopy(fmt.Sprintf("step %d", i+1), seq.Subject, seq.BodyHTML, seq.BodyPlain)...) + } + for _, v := range data.Variants { + parts = append(parts, stepCopy(fmt.Sprintf("variant %q", v.Name), v.Subject, v.BodyHTML, v.BodyPlain)...) + } + return tmplvars.CheckCopy(parts...) +} diff --git a/internal/app/campaign/template_copy_test.go b/internal/app/campaign/template_copy_test.go new file mode 100644 index 000000000..3be3e8e9e --- /dev/null +++ b/internal/app/campaign/template_copy_test.go @@ -0,0 +1,28 @@ +package campaign + +import ( + "strings" + "testing" + + "github.com/warmbly/warmbly/internal/models" +) + +func TestCheckCreateCopyNamesTheBrokenStepAndVariant(t *testing.T) { + ok := models.CreateSequenceInput{Subject: "Hi {{first_name}}", BodyPlain: "{{if .Company}}x{{end}}"} + cases := []struct { + data models.CreateCampaign + want string + }{ + {models.CreateCampaign{Sequences: []models.CreateSequenceInput{ok, {BodyHTML: "

    {{if .X}}

    "}}}, "step 2 body"}, + {models.CreateCampaign{Sequences: []models.CreateSequenceInput{ok}, Variants: []models.CreateCampaignABVariantRequest{{Name: "B", Subject: "{{nope}}"}}}, `variant "B" subject`}, + } + for _, tc := range cases { + err := checkCreateCopy(&tc.data) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Errorf("got %v, want an error naming %q", err, tc.want) + } + } + if err := checkCreateCopy(&models.CreateCampaign{Sequences: []models.CreateSequenceInput{ok}}); err != nil { + t.Errorf("valid copy refused: %v", err) + } +} diff --git a/internal/app/sequence/handler.go b/internal/app/sequence/handler.go index 5de5aeef2..a553caaec 100644 --- a/internal/app/sequence/handler.go +++ b/internal/app/sequence/handler.go @@ -11,6 +11,7 @@ import ( "github.com/warmbly/warmbly/internal/errx" "github.com/warmbly/warmbly/internal/models" "github.com/warmbly/warmbly/internal/pkg/mailhtml" + "github.com/warmbly/warmbly/internal/pkg/tmplvars" ) func (s *sequenceService) Create(ctx context.Context, orgID, campaignID string) (*models.Sequence, *errx.Error) { @@ -22,6 +23,9 @@ func (s *sequenceService) Get(ctx context.Context, orgID, campaignID string) ([] } func (s *sequenceService) Update(ctx context.Context, orgID, campaignID, sequenceID string, data *models.UpdateSequence) (*models.Sequence, *errx.Error) { + if err := checkCopy(data); err != nil { + return nil, errx.InvalidTemplate(err) + } s.deriveBodyHTML(ctx, orgID, campaignID, sequenceID, data) // Branch routing is resolved (and made safe against deleted/dangling targets // and loops) at schedule time in the repository's finder; the repository also @@ -30,6 +34,23 @@ func (s *sequenceService) Update(ctx context.Context, orgID, campaignID, sequenc return s.sequenceRepository.Update(ctx, orgID, campaignID, sequenceID, data) } +// checkCopy refuses any copy field in the write that would not render as written. +func checkCopy(data *models.UpdateSequence) error { + if data == nil { + return nil + } + var parts []tmplvars.Part + for _, f := range []struct { + name string + val *string + }{{"subject", data.Subject}, {"body", data.BodyHTML}, {"plain-text body", data.BodyPlain}} { + if f.val != nil { + parts = append(parts, tmplvars.Part{Name: f.name, Text: *f.val}) + } + } + return tmplvars.CheckCopy(parts...) +} + // deriveBodyHTML fills in the HTML part for a plain-only write. // // The API and the agent tools set body_plain and nothing else, while the send diff --git a/internal/app/sequence/handler_test.go b/internal/app/sequence/handler_test.go new file mode 100644 index 000000000..e757477ab --- /dev/null +++ b/internal/app/sequence/handler_test.go @@ -0,0 +1,55 @@ +package sequence + +import ( + "context" + "strings" + "testing" + + "github.com/warmbly/warmbly/internal/errx" + "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/repository" +) + +type recordingRepo struct { + repository.SequenceRepository + saved *models.UpdateSequence +} + +func (r *recordingRepo) Update(_ context.Context, _, _, _ string, data *models.UpdateSequence) (*models.Sequence, *errx.Error) { + r.saved = data + return &models.Sequence{}, nil +} + +func TestUpdateRefusesCopyThatWouldNotRender(t *testing.T) { + str := func(s string) *string { return &s } + cases := []struct { + name string + data models.UpdateSequence + want string + }{ + {"unclosed if in plain body", models.UpdateSequence{BodyPlain: str("{{if .Company}}hi"), BodyHTML: str("

    ok

    ")}, "plain-text body"}, + {"unknown bare name in html body", models.UpdateSequence{BodyHTML: str("

    Hi {{frist_name}}

    ")}, `unknown variable "frist_name"`}, + {"unknown function in subject", models.UpdateSequence{Subject: str("{{shout .FirstName}}")}, "subject"}, + } + for _, tc := range cases { + repo := &recordingRepo{} + _, xerr := NewService(repo).Update(context.Background(), "org", "c", "s", &tc.data) + if xerr == nil || xerr.Identifier != "invalid_template" || !strings.Contains(xerr.Message, tc.want) { + t.Errorf("%s: got %+v, want invalid_template naming %q", tc.name, xerr, tc.want) + } + if repo.saved != nil { + t.Errorf("%s: refused copy was saved", tc.name) + } + } +} + +func TestUpdateAcceptsAliasesAndCustomFields(t *testing.T) { + body := `

    Hi {{first_name}}, {{if .company_name}}at {{.company_name}}{{end}} {{.job title}} {{.anything_custom | default "x"}}

    ` + repo := &recordingRepo{} + if _, xerr := NewService(repo).Update(context.Background(), "org", "c", "s", &models.UpdateSequence{BodyHTML: &body}); xerr != nil { + t.Fatalf("valid copy refused: %v", xerr) + } + if repo.saved == nil || *repo.saved.BodyHTML != body { + t.Fatal("copy must be stored as written, not rewritten") + } +} diff --git a/internal/errx/common.go b/internal/errx/common.go index ec3ab32d1..51c29a7b2 100644 --- a/internal/errx/common.go +++ b/internal/errx/common.go @@ -2,6 +2,7 @@ package errx import ( "fmt" + "strings" "github.com/warmbly/warmbly/internal/config" ) @@ -335,3 +336,13 @@ func StorageLimitReached(usedBytes, limitBytes, addingBytes int64) *Error { fmt.Sprintf("Storage limit reached: %d MB of %d MB used, %d MB to add. Remove attachments or images, or upgrade your plan.", usedBytes/mb, limitBytes/mb, addingBytes/mb)) } + +// InvalidTemplate refuses campaign copy that would not render as written; the +// message is the validator's own, naming the field, the line and the variable. +func InvalidTemplate(err error) *Error { + msg := err.Error() + if msg != "" { + msg = strings.ToUpper(msg[:1]) + msg[1:] + } + return NewWithIdentifier(BadRequest, "invalid_template", msg+".") +} diff --git a/internal/models/form_event.go b/internal/models/form_event.go index 9bb0dc33c..9da301472 100644 --- a/internal/models/form_event.go +++ b/internal/models/form_event.go @@ -1,16 +1,14 @@ package models import ( - "regexp" "time" "github.com/google/uuid" + "github.com/warmbly/warmbly/internal/pkg/tmplvars" ) -// FormLinkMarkerRE matches the {{form_link:}} marker the campaign -// editor inserts; the send pipeline resolves it per recipient. Keep in sync -// with FORM_LINK_RE in web/src/lib/templateVars.ts. -var FormLinkMarkerRE = regexp.MustCompile(`\{\{\s*form_link:([a-z0-9]{1,64})\s*\}\}`) +// FormLinkMarkerRE matches the {{form_link:}} marker; see tmplvars.FormLinkMarker. +var FormLinkMarkerRE = tmplvars.FormLinkMarker // FormLink is a per-contact form URL ticket: the row id is the opaque token // in ?t=, so possession of the link identifies the contact (same posture as diff --git a/internal/models/sequence.go b/internal/models/sequence.go index f961bf61e..417b4cdb8 100644 --- a/internal/models/sequence.go +++ b/internal/models/sequence.go @@ -123,7 +123,7 @@ type ActionConfig struct { // move_deal_stage: move the contact's most-recent OPEN deal in // DealPipelineID to DealStageID; a contact with no open deal in that // pipeline is a logged no-op (not an error). - // DealName supports the same {{first_name}}/{{company}} templating other + // DealName supports the same {{.FirstName}}/{{.Company}} templating other // campaign copy uses. DealValue is optional; DealCurrency defaults to "USD". DealPipelineID *uuid.UUID `json:"deal_pipeline_id,omitempty"` DealStageID *uuid.UUID `json:"deal_stage_id,omitempty"` diff --git a/internal/pkg/tmplvars/normalize.go b/internal/pkg/tmplvars/normalize.go new file mode 100644 index 000000000..2bbddf768 --- /dev/null +++ b/internal/pkg/tmplvars/normalize.go @@ -0,0 +1,304 @@ +package tmplvars + +import ( + "errors" + "fmt" + "regexp" + "sort" + "strings" + "text/template/parse" + + "github.com/warmbly/warmbly/internal/pkg/tmplfuncs" +) + +// ActionPattern matches a single {{ ... }} action (no nested braces). +var ActionPattern = regexp.MustCompile(`\{\{[^{}]*\}\}`) + +// FormLinkMarker matches the {{form_link:}} marker the campaign +// editor inserts, which the send pipeline resolves before the template renders. +// Keep in sync with FORM_LINK_RE in web/src/lib/templateVars.ts. +var FormLinkMarker = regexp.MustCompile(`\{\{\s*form_link:([a-z0-9]{1,64})\s*\}\}`) + +// spacedFieldRefAt matches, at the start of the slice, a dotted reference whose +// key has an internal space or dash (".job title", ".first-name"), which is not +// a valid selector and is rewritten to `(index . "key")`. +var spacedFieldRefAt = regexp.MustCompile(`^\.[A-Za-z0-9_]+(?:[ \-]+[A-Za-z0-9_]+)+`) + +// builtinFuncs are text/template's own functions, which a bare name may call. +var builtinFuncs = map[string]bool{ + "and": true, "call": true, "html": true, "index": true, "slice": true, "js": true, "len": true, + "not": true, "or": true, "print": true, "printf": true, "println": true, "urlquery": true, + "eq": true, "ge": true, "gt": true, "le": true, "lt": true, "ne": true, +} + +func isFunc(name string) bool { + _, ok := tmplfuncs.FuncMap()[name] + return ok || builtinFuncs[name] +} + +// Normalize rewrites the accepted spellings of campaign copy into the form the +// engine compiles: spaced and dashed custom-field keys become index calls, a +// bare built-in name ({{first_name}}) becomes a field of the root, and Sender +// fields take their canonical names. Text outside actions and string literals +// are never touched. The error names a reference that can never resolve; the +// returned source is usable either way, so a renderer may ignore it. +func Normalize(src string) (string, error) { + if !strings.Contains(src, "{{") { + return src, nil + } + src = ActionPattern.ReplaceAllStringFunc(src, rewriteSpacedInAction) + tree := parse.New("normalize") + tree.Mode = parse.SkipFuncCheck + trees := map[string]*parse.Tree{} + if _, err := tree.Parse(src, "", "", trees); err != nil { + return src, nil // the compiler reports the syntax error itself + } + w := &walker{src: src} + names := make([]string, 0, len(trees)) + for name := range trees { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + if t := trees[name]; t != nil && t.Root != nil { + w.node(t.Root) + } + } + return w.apply(), w.err +} + +// Check reports whether campaign copy compiles as written, naming the problem +// and its line when it does not. +func Check(src string) error { + if src == "" { + return nil + } + norm, err := Normalize(FormLinkMarker.ReplaceAllString(src, "")) + if err != nil { + return err + } + if _, err := tmplfuncs.Compile("copy", norm); err != nil { + return errors.New(strings.Replace(err.Error(), "template: copy:", "line ", 1)) + } + return nil +} + +// Part is one named piece of copy to check. +type Part struct{ Name, Text string } + +// CheckCopy checks each part in order and reports the first problem with its part's name. +func CheckCopy(parts ...Part) error { + for _, p := range parts { + if err := Check(p.Text); err != nil { + return fmt.Errorf("the %s has a template error: %w", p.Name, err) + } + } + return nil +} + +type edit struct { + start, end int + text string +} + +type walker struct { + src string + edits []edit + err error +} + +func (w *walker) fail(pos int, format string, args ...any) { + if w.err == nil { + line := strings.Count(w.src[:min(pos, len(w.src))], "\n") + 1 + w.err = fmt.Errorf("line %d: %s", line, fmt.Sprintf(format, args...)) + } +} + +func (w *walker) node(n parse.Node) { + switch x := n.(type) { + case *parse.ListNode: + if x == nil { + return + } + for _, c := range x.Nodes { + w.node(c) + } + case *parse.ActionNode: + w.pipe(x.Pipe) + case *parse.IfNode: + w.branch(&x.BranchNode) + case *parse.RangeNode: + w.branch(&x.BranchNode) + case *parse.WithNode: + w.branch(&x.BranchNode) + case *parse.TemplateNode: + w.pipe(x.Pipe) + } +} + +func (w *walker) branch(b *parse.BranchNode) { + w.pipe(b.Pipe) + w.node(b.List) + if b.ElseList != nil { + w.node(b.ElseList) + } +} + +func (w *walker) pipe(p *parse.PipeNode) { + if p == nil { + return + } + for _, cmd := range p.Cmds { + for i, arg := range cmd.Args { + w.arg(arg, i == 0 && len(cmd.Args) > 1) + } + } +} + +// arg visits one operand; calls is whether it is a command head given arguments. +func (w *walker) arg(n parse.Node, calls bool) { + switch x := n.(type) { + case *parse.PipeNode: + w.pipe(x) + case *parse.IdentifierNode: + w.identifier(x, calls) + case *parse.FieldNode: + w.chain(int(x.Pos), "."+strings.Join(x.Ident, "."), ".", x.Ident) + case *parse.VariableNode: + if len(x.Ident) > 1 && x.Ident[0] == "$" { + w.chain(int(x.Pos), strings.Join(x.Ident, "."), "$.", x.Ident[1:]) + } + case *parse.ChainNode: + switch inner := x.Node.(type) { + case *parse.IdentifierNode: + if canonical := topNames[inner.Ident]; canonical == SenderField { + text := inner.Ident + "." + strings.Join(x.Field, ".") + w.chain(int(inner.Pos), text, "$.", append([]string{inner.Ident}, x.Field...)) + return + } + w.identifier(inner, false) + case *parse.PipeNode: + w.pipe(inner) + } + } +} + +func (w *walker) identifier(x *parse.IdentifierNode, calls bool) { + if isFunc(x.Ident) { + return + } + pos := int(x.Pos) + if _, ok := topNames[x.Ident]; !ok || calls { + if calls { + w.fail(pos, "function %q is not defined", x.Ident) + return + } + w.fail(pos, "%s", unknownVariable(x.Ident)) + return + } + if strings.HasPrefix(w.src[pos:], x.Ident) { + // The alias spelling is kept, so a custom field of that name still wins. + w.edits = append(w.edits, edit{pos, pos + len(x.Ident), "$." + x.Ident}) + } +} + +// chain canonicalises a reference into Sender, whose field set is fixed. idents +// starts at the root field; text is the reference as written, rewritten as +// prefix plus the canonical idents. +func (w *walker) chain(pos int, text, prefix string, idents []string) { + if len(idents) < 2 { + return + } + if canonical, ok := topNames[idents[0]]; !ok || canonical != SenderField { + return + } + start := w.locate(pos, text) + if start < 0 { + return + } + field, ok := senderNames[idents[1]] + if !ok { + w.fail(start, "unknown sender field %q; the sender fields are %s", idents[1], senderList) + return + } + out := append([]string{SenderField, field}, idents[2:]...) + if rewritten := prefix + strings.Join(out, "."); rewritten != text { + w.edits = append(w.edits, edit{start, start + len(text), rewritten}) + } +} + +// locate finds where text, which the parser reported at pos, starts in the +// source. A chained reference is reported at a later segment, so search back. +func (w *walker) locate(pos int, text string) int { + for s := min(pos, len(w.src)); s >= 0 && s >= pos-len(text); s-- { + if strings.HasPrefix(w.src[s:], text) { + return s + } + } + return -1 +} + +func (w *walker) apply() string { + if len(w.edits) == 0 { + return w.src + } + sort.Slice(w.edits, func(i, j int) bool { return w.edits[i].start < w.edits[j].start }) + var b strings.Builder + last := 0 + for _, e := range w.edits { + if e.start < last { + continue + } + b.WriteString(w.src[last:e.start]) + b.WriteString(e.text) + last = e.end + } + b.WriteString(w.src[last:]) + return b.String() +} + +func unknownVariable(name string) string { + return fmt.Sprintf("unknown variable %q: write a contact field with a leading dot, like {{.%s}}; the built-in fields are %s", name, name, canonicalList) +} + +// rewriteSpacedInAction rewrites `.job title` and `.first-name` inside one +// action to `(index . "key")`, skipping string literals. +func rewriteSpacedInAction(action string) string { + var b strings.Builder + b.Grow(len(action)) + var quote byte // 0 = not in a string literal; '"' or '`' otherwise + for i := 0; i < len(action); { + c := action[i] + switch { + case quote != 0: + b.WriteByte(c) + if c == '\\' && quote == '"' && i+1 < len(action) { + b.WriteByte(action[i+1]) // keep an escaped char verbatim + i += 2 + continue + } + if c == quote { + quote = 0 + } + i++ + case c == '"' || c == '`': + quote = c + b.WriteByte(c) + i++ + case c == '.': + // A nested struct selector must not consume the following function argument. + fieldStart := i == 0 || strings.ContainsRune("{( \t\r\n", rune(action[i-1])) + if m := spacedFieldRefAt.FindString(action[i:]); fieldStart && m != "" { + b.WriteString(`(index . "` + m[1:] + `")`) + i += len(m) + continue + } + b.WriteByte(c) + i++ + default: + b.WriteByte(c) + i++ + } + } + return b.String() +} diff --git a/internal/pkg/tmplvars/normalize_test.go b/internal/pkg/tmplvars/normalize_test.go new file mode 100644 index 000000000..d06ae3dae --- /dev/null +++ b/internal/pkg/tmplvars/normalize_test.go @@ -0,0 +1,88 @@ +package tmplvars + +import ( + "strings" + "testing" +) + +func TestNormalize(t *testing.T) { + cases := []struct{ name, in, want string }{ + {"canonical untouched", "Hi {{.FirstName}}", "Hi {{.FirstName}}"}, + {"bare snake", "Hi {{first_name}}", "Hi {{$.first_name}}"}, + {"bare camel", "Hi {{ firstName }}", "Hi {{ $.firstName }}"}, + {"bare lowercase", "{{company}} / {{company_name}}", "{{$.company}} / {{$.company_name}}"}, + {"dotted alias is a field already", "{{.first_name}}", "{{.first_name}}"}, + {"bare in if", "{{if first_name}}x{{end}}", "{{if $.first_name}}x{{end}}"}, + {"bare in pipe", `{{first_name | default "there"}}`, `{{$.first_name | default "there"}}`}, + {"bare as argument", `{{default "there" first_name}}`, `{{default "there" $.first_name}}`}, + {"bare in eq", `{{if eq company "Acme"}}y{{end}}`, `{{if eq $.company "Acme"}}y{{end}}`}, + {"literal braces outside actions", "Use first_name or {first_name} in text", "Use first_name or {first_name} in text"}, + {"string literal untouched", `{{default "first_name" .X}}`, `{{default "first_name" .X}}`}, + {"spaced custom field", "{{.job title}}", `{{(index . "job title")}}`}, + {"sender alias", "{{.Sender.first_name}}", "{{.Sender.FirstName}}"}, + {"sender bare", "{{sender.first_name}}", "{{$.Sender.FirstName}}"}, + {"sender variable", "{{$.sender.signature_html}}", "{{$.Sender.SignatureHTML}}"}, + {"function untouched", "{{upper .FirstName}}", "{{upper .FirstName}}"}, + {"unsubscribe alias", "{{unsubscribe_link}}", "{{$.unsubscribe_link}}"}, + } + for _, tc := range cases { + got, err := Normalize(tc.in) + if err != nil { + t.Errorf("%s: unexpected error %v", tc.name, err) + continue + } + if got != tc.want { + t.Errorf("%s: got %q, want %q", tc.name, got, tc.want) + } + } +} + +func TestCheckRefusesWhatCannotRender(t *testing.T) { + cases := []struct{ in, want string }{ + {"Hi {{frist_name}}", `unknown variable "frist_name"`}, + {"{{if .FirstName}}open", "unexpected EOF"}, + {"{{.Sender.Bogus}}", `unknown sender field "Bogus"`}, + {"{{shout .FirstName}}", `function "shout" is not defined`}, + } + for _, tc := range cases { + err := Check(tc.in) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Errorf("%q: got %v, want an error containing %q", tc.in, err, tc.want) + } + } + for _, ok := range []string{"", "plain", "{{.FirstName}}", "{{first_name}}", "{{.any_custom_key}}", `{{index . "city"}}`, "{{.job title}}", "book: {{form_link:abc123}}"} { + if err := Check(ok); err != nil { + t.Errorf("%q: unexpected error %v", ok, err) + } + } +} + +func TestCheckNamesTheLine(t *testing.T) { + err := Check("line one\n{{if .X}}") + if err == nil || !strings.HasPrefix(err.Error(), "line 2:") { + t.Fatalf("got %v", err) + } +} + +func TestAliasesDerivedFromCanonicalFields(t *testing.T) { + for alias, want := range map[string]string{ + "first_name": "FirstName", "firstName": "FirstName", "firstname": "FirstName", + "last_name": "LastName", "email": "Email", "company_name": "Company", + "companyName": "Company", "phone": "Phone", "unsubscribe_link": UnsubscribeLink, + } { + if got := topNames[alias]; got != want { + t.Errorf("%s: got %q, want %q", alias, got, want) + } + } + if got := senderNames["signature_html"]; got != "SignatureHTML" { + t.Errorf("signature_html: got %q", got) + } +} + +func TestAddAliasesLetsCustomFieldWin(t *testing.T) { + data := map[string]any{"FirstName": "Sam", "first_name": "custom"} + AddAliases(data, map[string]string{"first_name": "custom"}) + if data["first_name"] != "custom" || data["firstName"] != "Sam" { + t.Fatalf("got %v", data) + } +} diff --git a/internal/pkg/tmplvars/sender.go b/internal/pkg/tmplvars/sender.go new file mode 100644 index 000000000..cc95877a2 --- /dev/null +++ b/internal/pkg/tmplvars/sender.go @@ -0,0 +1,60 @@ +package tmplvars + +import htmltemplate "html/template" + +// Sender is the .Sender namespace, an explicit allowlist: never embed the mailbox model or its methods. +type Sender struct { + Name string + FirstName string + LastName string + Email string + MailboxEmail string + SendAsEmail string + ReplyTo string + SignaturePlain string + // SignatureHTML is the mailbox's own markup, so an HTML body emits it as written. + SignatureHTML htmltemplate.HTML + SignatureSync bool + SignatureCode bool + Provider string + Status string + MailHost string + AuthMethod string + Vendor string + AvatarURL string + Tags []string + Timezone string + CampaignLimit int + MinWaitTime int + SaveToSent bool + RelayFolderMoves bool + TrackingDomain string + TrackingDomainVerified bool + TrackingDomainVerifiedAt string + TrackDirectMail bool + AuthState string + AuthSPF bool + AuthDKIM bool + AuthDMARC bool + AuthDMARCPolicy string + AuthReason string + AuthCheckedAt string + AuthFailingSince string + Warmup string + WarmupPausedAt string + WarmupBase int + WarmupMax int + WarmupIncrease int + WarmupReplyRate int + WarmupTag string + WarmupPoolType string + WarmupStartTime string + WarmupEndTime string + WarmupDays int + WarmupPlacement string + WarmupFolder string + WarmupRetentionDays int + LastSyncedAt string + CreatedAt string + UpdatedAt string +} diff --git a/internal/pkg/tmplvars/vars.go b/internal/pkg/tmplvars/vars.go new file mode 100644 index 000000000..b16a0080c --- /dev/null +++ b/internal/pkg/tmplvars/vars.go @@ -0,0 +1,134 @@ +// Package tmplvars is the variable vocabulary of campaign copy: the built-in +// fields a template can name, the spellings accepted for them, and the one +// normalisation every compile and validation of campaign copy goes through. +package tmplvars + +import ( + "fmt" + "reflect" + "sort" + "strings" + "unicode" +) + +// UnsubscribeLink is the variable a step can place the opt-out link with by hand. +const UnsubscribeLink = "UnsubscribeLink" + +// SenderField is the top-level name of the typed sending-mailbox namespace. +const SenderField = "Sender" + +// builtins are the canonical top-level fields, each with any extra synonym +// whose spellings are accepted too. +var builtins = []struct { + name string + synonyms []string +}{ + {"FirstName", nil}, + {"LastName", nil}, + {"Email", nil}, + {"Company", []string{"CompanyName"}}, + {"Phone", nil}, + {SenderField, nil}, + {UnsubscribeLink, nil}, +} + +// Alias is one accepted spelling of a canonical field. +type alias struct{ name, canonical string } + +var ( + // topAliases are the non-canonical spellings, in a stable order. + topAliases []alias + // topNames resolves a canonical name or an alias to the canonical name. + topNames = map[string]string{} + // senderNames resolves a Sender field or one of its aliases to the field. + senderNames = map[string]string{} + // canonicalList and senderList name the valid fields in error messages. + canonicalList string + senderList string +) + +func init() { + names := make([]string, 0, len(builtins)) + for _, b := range builtins { + names = append(names, b.name) + topNames[b.name] = b.name + for _, form := range append([]string{b.name}, b.synonyms...) { + for _, spelling := range append(spellings(form), form) { + if spelling == b.name { + continue + } + register(topNames, spelling, b.name) + } + } + } + for spelling, canonical := range topNames { + if spelling != canonical { + topAliases = append(topAliases, alias{spelling, canonical}) + } + } + sort.Slice(topAliases, func(i, j int) bool { return topAliases[i].name < topAliases[j].name }) + canonicalList = strings.Join(names, ", ") + + typ := reflect.TypeOf(Sender{}) + fields := make([]string, 0, typ.NumField()) + for i := 0; i < typ.NumField(); i++ { + name := typ.Field(i).Name + fields = append(fields, name) + register(senderNames, name, name) + } + for _, name := range fields { + for _, spelling := range spellings(name) { + if _, taken := senderNames[spelling]; !taken { + register(senderNames, spelling, name) + } + } + } + senderList = strings.Join(fields, ", ") +} + +// register panics on a spelling claimed by two fields, so the tables can never be ambiguous. +func register(table map[string]string, spelling, canonical string) { + if prev, ok := table[spelling]; ok && prev != canonical { + panic(fmt.Sprintf("tmplvars: %q names both %s and %s", spelling, prev, canonical)) + } + table[spelling] = canonical +} + +// spellings are the snake_case, camelCase and lowercase forms of a Go field name. +func spellings(name string) []string { + r := []rune(name) + camel := string(unicode.ToLower(r[0])) + string(r[1:]) + return []string{snake(name), camel, strings.ToLower(name)} +} + +// snake turns FirstName into first_name and SignatureHTML into signature_html. +func snake(name string) string { + r := []rune(name) + var b strings.Builder + for i, c := range r { + if i > 0 && unicode.IsUpper(c) { + prevLower := unicode.IsLower(r[i-1]) || unicode.IsDigit(r[i-1]) + acronymEnd := unicode.IsUpper(r[i-1]) && i+1 < len(r) && unicode.IsLower(r[i+1]) + if prevLower || acronymEnd { + b.WriteByte('_') + } + } + b.WriteRune(unicode.ToLower(c)) + } + return b.String() +} + +// AddAliases sets every accepted alias of a built-in field in data to that +// field's value, except where the contact has a custom field of that name, +// which keeps its own value as it always has. +func AddAliases(data map[string]any, custom map[string]string) { + for _, a := range topAliases { + if _, ok := custom[a.name]; ok { + continue + } + data[a.name] = data[a.canonical] + } +} + +// AliasCount is how many keys AddAliases may add, for sizing the data map. +func AliasCount() int { return len(topAliases) } diff --git a/internal/repository/pg_advisor.go b/internal/repository/pg_advisor.go index c14498722..cf60beabc 100644 --- a/internal/repository/pg_advisor.go +++ b/internal/repository/pg_advisor.go @@ -184,7 +184,7 @@ type AdvisorListStats struct { Suppressed int // Unsubscribed counts contacts with subscribed=false. Unsubscribed int - // MissingFirstName counts contacts that would render an empty {{first_name}}. + // MissingFirstName counts contacts that would render an empty {{.FirstName}}. MissingFirstName int } diff --git a/internal/seed/campaigns.go b/internal/seed/campaigns.go index 4d1915c8f..f320ef3ad 100644 --- a/internal/seed/campaigns.go +++ b/internal/seed/campaigns.go @@ -85,11 +85,11 @@ func seedSequences(ctx context.Context, pool *pgxpool.Pool, _ *Result) error { } steps := []step{ {SequenceAcmeStep1ID, CampaignAcmeActiveID, OrgAcmeID, - "Step 1 - intro", "Quick intro from {{firstName}}", - "Hey {{firstName}},\n\nNoticed your team is hiring SDRs - quick idea.", - "

    Hey {{firstName}},

    Noticed your team is hiring SDRs - quick idea.

    ", 0}, + "Step 1 - intro", "Quick intro from {{.FirstName}}", + "Hey {{.FirstName}},\n\nNoticed your team is hiring SDRs - quick idea.", + "

    Hey {{.FirstName}},

    Noticed your team is hiring SDRs - quick idea.

    ", 0}, {SequenceAcmeStep2ID, CampaignAcmeActiveID, OrgAcmeID, - "Step 2 - bump", "Re: Quick intro from {{firstName}}", + "Step 2 - bump", "Re: Quick intro from {{.FirstName}}", "Bumping this in case it got buried.", "

    Bumping this in case it got buried.

    ", 3}, {SequenceAcmeStep3ID, CampaignAcmeActiveID, OrgAcmeID, diff --git a/internal/seed/dev_org.go b/internal/seed/dev_org.go index 1535e72f3..5790e8865 100644 --- a/internal/seed/dev_org.go +++ b/internal/seed/dev_org.go @@ -371,19 +371,19 @@ func seedDevCampaigns(ctx context.Context, pool *pgxpool.Pool) error { waitAfter int }{ {devSeqStep1, DevCampaignActiveID, "Step 1 - intro", - "Quick question about outbound at {{company}}", - "Hi {{firstName}},\n\nSaw {{company}} is scaling its sales team. Most teams we talk to run cold outbound across a handful of mailboxes and only find out something landed in spam when replies dry up.\n\nWe keep every mailbox warm, spread sends across senders, and flag deliverability dips before they hurt. Teams like yours usually see reply rates climb within two weeks.\n\nWorth a quick look? Happy to share a two-minute walkthrough.\n\nBest,\nDev", 0}, + "Quick question about outbound at {{.Company}}", + "Hi {{.FirstName}},\n\nSaw {{.Company}} is scaling its sales team. Most teams we talk to run cold outbound across a handful of mailboxes and only find out something landed in spam when replies dry up.\n\nWe keep every mailbox warm, spread sends across senders, and flag deliverability dips before they hurt. Teams like yours usually see reply rates climb within two weeks.\n\nWorth a quick look? Happy to share a two-minute walkthrough.\n\nBest,\nDev", 0}, // Carries the personalized form link, so the campaign Forms panel and // the form's campaign attribution both have live data to show. {devSeqStep2, DevCampaignActiveID, "Step 2 - bump", - "Re: Quick question about outbound at {{company}}", - "Hi {{firstName}},\n\nBumping this in case it got buried. The short version: we help outbound teams stay out of spam without slowing down sending.\n\nIf deliverability is not a problem for {{company}} right now, no worries at all. If it is, grab a slot that suits you: {{form_link:" + devFormDemoPublicID + "}}\n\nBest,\nDev", 3}, + "Re: Quick question about outbound at {{.Company}}", + "Hi {{.FirstName}},\n\nBumping this in case it got buried. The short version: we help outbound teams stay out of spam without slowing down sending.\n\nIf deliverability is not a problem for {{.Company}} right now, no worries at all. If it is, grab a slot that suits you: {{form_link:" + devFormDemoPublicID + "}}\n\nBest,\nDev", 3}, {devSeqStep3, DevCampaignActiveID, "Step 3 - break-up", "Closing the loop", - "Hi {{firstName}},\n\nClosing the loop on my side. If inbox placement becomes a priority later this quarter, just reply to this thread and I will pick it right back up.\n\nEither way, good luck with the outbound push at {{company}}.\n\nBest,\nDev", 4}, + "Hi {{.FirstName}},\n\nClosing the loop on my side. If inbox placement becomes a priority later this quarter, just reply to this thread and I will pick it right back up.\n\nEither way, good luck with the outbound push at {{.Company}}.\n\nBest,\nDev", 4}, {devSeqDraft, DevCampaignDraftID, "Partner intro", - "White-label outbound for {{company}} clients", - "Hi {{firstName}},\n\nAgencies use us to run warmed, monitored sending for their clients under their own brand. Would a partner walkthrough be useful?\n\nBest,\nDev", 0}, + "White-label outbound for {{.Company}} clients", + "Hi {{.FirstName}},\n\nAgencies use us to run warmed, monitored sending for their clients under their own brand. Would a partner walkthrough be useful?\n\nBest,\nDev", 0}, } for _, s := range steps { bodyHTML := "

    " + s.bodyPlain + "

    " diff --git a/internal/tasks/campaign_task.go b/internal/tasks/campaign_task.go index 9f3579605..4286bda35 100644 --- a/internal/tasks/campaign_task.go +++ b/internal/tasks/campaign_task.go @@ -1532,7 +1532,7 @@ func (s *tasksService) executeActionNode(ctx context.Context, campaign *models.C if perr != nil { return nil } - // Deal name supports the same {{first_name}}/{{company}} templating other + // Deal name supports the same {{.FirstName}}/{{.Company}} templating other // campaign copy uses; fall back to a contact-derived name when blank. name := RenderTemplate(strings.TrimSpace(cfg.DealName), *contact) if name == "" { diff --git a/internal/tasks/optout.go b/internal/tasks/optout.go index 38e6442e7..94a1214c1 100644 --- a/internal/tasks/optout.go +++ b/internal/tasks/optout.go @@ -11,11 +11,12 @@ import ( "github.com/warmbly/warmbly/internal/app/unsublink" "github.com/warmbly/warmbly/internal/models" "github.com/warmbly/warmbly/internal/pkg/mailhtml" + "github.com/warmbly/warmbly/internal/pkg/tmplvars" ) // UnsubscribeLinkVar is the template variable a step can place by hand // ({{.UnsubscribeLink}}); it resolves to the recipient's own opt-out link. -const UnsubscribeLinkVar = "UnsubscribeLink" +const UnsubscribeLinkVar = tmplvars.UnsubscribeLink // unsubscribePathMarker is the path segment every minted link carries, on the // API origin and on a workspace's own tracking domain alike. Click tracking diff --git a/internal/tasks/template.go b/internal/tasks/template.go index aa69bb60d..df512ecff 100644 --- a/internal/tasks/template.go +++ b/internal/tasks/template.go @@ -14,6 +14,7 @@ import ( "github.com/warmbly/warmbly/internal/pkg/generation" "github.com/warmbly/warmbly/internal/pkg/mailhtml" "github.com/warmbly/warmbly/internal/pkg/tmplfuncs" + "github.com/warmbly/warmbly/internal/pkg/tmplvars" "github.com/warmbly/warmbly/internal/pkg/warmpersona" ) @@ -34,15 +35,7 @@ type TemplateContext struct { } // templateAction matches a single {{ ... }} action (no nested braces). -var templateAction = regexp.MustCompile(`\{\{[^{}]*\}\}`) - -// spacedFieldRefAt matches, anchored at the start of the slice, a dotted field -// reference whose key contains an internal space or dash (e.g. ".job title" or -// ".first-name"). Such a key is not a valid Go-template identifier, so it cannot -// be written as a `.Selector`. We rewrite it to the equivalent `(index . "key")`, -// which IS valid everywhere โ€” standalone, inside {{if}}, and inside eq/and/... โ€” -// giving custom fields with spaces full Go-template support. -var spacedFieldRefAt = regexp.MustCompile(`^\.[A-Za-z0-9_]+(?:[ \-]+[A-Za-z0-9_]+)+`) +var templateAction = tmplvars.ActionPattern // tmplCache caches parsed templates keyed by the raw template string. A stored // nil is a "known-bad" sentinel: that body failed to compile, so future renders @@ -53,7 +46,7 @@ var tmplCache tmplfuncs.Cache // Standard fields and the typed Sender namespace take precedence over custom fields. func buildTemplateData(contact models.Contact, context TemplateContext) map[string]any { - data := make(map[string]any, len(contact.CustomFields)+7) + data := make(map[string]any, len(contact.CustomFields)+7+tmplvars.AliasCount()) for k, v := range contact.CustomFields { data[k] = v } @@ -64,62 +57,14 @@ func buildTemplateData(contact models.Contact, context TemplateContext) map[stri data["Phone"] = contact.Phone data["Sender"] = context.Sender data[UnsubscribeLinkVar] = context.UnsubscribeLink + tmplvars.AddAliases(data, contact.CustomFields) return data } -// rewriteSpacedFieldRefs rewrites a dotted custom-field reference whose key has -// a space or dash (`.job title`, `.first-name`) into `(index . "key")` inside -// each {{ }} action, so those fields work EVERYWHERE โ€” standalone, inside -// {{if}}, and inside eq/and/printf/... โ€” not just as a literal substitution. -// Plain identifier selectors ({{.FirstName}}) and any text outside an action are -// left untouched, and quoted string literals inside an action are skipped so a -// value like ".NET" is never mangled. No data is needed: the rewrite is purely -// syntactic, so it works identically at render time and at validation time. -func rewriteSpacedFieldRefs(tmpl string) string { - if !strings.Contains(tmpl, "{{") { - return tmpl - } - return templateAction.ReplaceAllStringFunc(tmpl, rewriteSpacedInAction) -} - -func rewriteSpacedInAction(action string) string { - var b strings.Builder - b.Grow(len(action)) - var quote byte // 0 = not in a string literal; '"' or '`' otherwise - for i := 0; i < len(action); { - c := action[i] - switch { - case quote != 0: - b.WriteByte(c) - if c == '\\' && quote == '"' && i+1 < len(action) { - b.WriteByte(action[i+1]) // keep an escaped char verbatim - i += 2 - continue - } - if c == quote { - quote = 0 - } - i++ - case c == '"' || c == '`': - quote = c - b.WriteByte(c) - i++ - case c == '.': - // A nested struct selector must not consume the following function argument. - fieldStart := i == 0 || strings.ContainsRune("{( \t\r\n", rune(action[i-1])) - if m := spacedFieldRefAt.FindString(action[i:]); fieldStart && m != "" { - b.WriteString(`(index . "` + m[1:] + `")`) - i += len(m) - continue - } - b.WriteByte(c) - i++ - default: - b.WriteByte(c) - i++ - } - } - return b.String() +// normalizeTemplate is the one rewrite every campaign compile goes through. +func normalizeTemplate(tmpl string) string { + out, _ := tmplvars.Normalize(tmpl) + return out } // compiledTemplate returns a parsed, cached template for tmpl, or nil if the @@ -131,7 +76,7 @@ func compiledTemplate(tmpl string) *template.Template { if t, ok := tmplCache.Load(tmpl); ok { return t // may be nil (known-bad) } - t, err := tmplfuncs.Compile("body", rewriteSpacedFieldRefs(tmpl)) + t, err := tmplfuncs.Compile("body", normalizeTemplate(tmpl)) if err != nil { tmplCache.Store(tmpl, nil) return nil @@ -140,18 +85,10 @@ func compiledTemplate(tmpl string) *template.Template { return t } -// TemplateError returns a parse error when a template's control syntax is -// malformed (e.g. an {{if}} with no {{end}}, or a bad {{eq}}), or nil when it is -// valid. Spaced/dashed custom-field references are rewritten to their `index` -// form first (exactly as the renderer does), so a valid template that uses them -// inside {{if}} does not false-fail validation. Used to block starting a -// campaign with a template that would degrade to literal {{if}} text on send. +// TemplateError reports why a template would not render as written (a parse +// error, or a reference that can never resolve), or nil when it is valid. func TemplateError(tmpl string) error { - if tmpl == "" { - return nil - } - _, err := tmplfuncs.Compile("validate", rewriteSpacedFieldRefs(tmpl)) - return err + return tmplvars.Check(tmpl) } // RenderTemplate renders a sequence template against a contact, supporting Go diff --git a/internal/tasks/template_html.go b/internal/tasks/template_html.go index ac9da1a7d..758b46409 100644 --- a/internal/tasks/template_html.go +++ b/internal/tasks/template_html.go @@ -72,7 +72,7 @@ func compiledHTMLTemplate(tmpl string) *htmlBody { return body } src, comments := shieldComments(strings.ReplaceAll(tmpl, "\x00", "")) - t, err := tmplfuncs.CompileHTML("body", rewriteSpacedFieldRefs(src)) + t, err := tmplfuncs.CompileHTML("body", normalizeTemplate(src)) if err != nil { htmlTmplCache.Store(tmpl, nil) return nil diff --git a/internal/tasks/template_sender.go b/internal/tasks/template_sender.go index aa0f896d1..ac234d537 100644 --- a/internal/tasks/template_sender.go +++ b/internal/tasks/template_sender.go @@ -6,64 +6,11 @@ import ( "time" "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/pkg/tmplvars" ) -// TemplateSender is an explicit allowlist: never embed the mailbox model or its methods. -type TemplateSender struct { - Name string - FirstName string - LastName string - Email string - MailboxEmail string - SendAsEmail string - ReplyTo string - SignaturePlain string - // SignatureHTML is the mailbox's own markup, so an HTML body emits it as written. - SignatureHTML htmltemplate.HTML - SignatureSync bool - SignatureCode bool - Provider string - Status string - MailHost string - AuthMethod string - Vendor string - AvatarURL string - Tags []string - Timezone string - CampaignLimit int - MinWaitTime int - SaveToSent bool - RelayFolderMoves bool - TrackingDomain string - TrackingDomainVerified bool - TrackingDomainVerifiedAt string - TrackDirectMail bool - AuthState string - AuthSPF bool - AuthDKIM bool - AuthDMARC bool - AuthDMARCPolicy string - AuthReason string - AuthCheckedAt string - AuthFailingSince string - Warmup string - WarmupPausedAt string - WarmupBase int - WarmupMax int - WarmupIncrease int - WarmupReplyRate int - WarmupTag string - WarmupPoolType string - WarmupStartTime string - WarmupEndTime string - WarmupDays int - WarmupPlacement string - WarmupFolder string - WarmupRetentionDays int - LastSyncedAt string - CreatedAt string - UpdatedAt string -} +// TemplateSender is the typed .Sender namespace; see tmplvars.Sender. +type TemplateSender = tmplvars.Sender func templateContext(account *models.Email, unsubscribeURL string) TemplateContext { context := TemplateContext{UnsubscribeLink: unsubscribeURL} diff --git a/internal/tasks/template_test.go b/internal/tasks/template_test.go index 23f564876..5ab5adb8b 100644 --- a/internal/tasks/template_test.go +++ b/internal/tasks/template_test.go @@ -244,6 +244,38 @@ func TestRenderTemplate_BasicVariables(t *testing.T) { } } +func TestRenderTemplate_AliasSpellings(t *testing.T) { + contact := models.Contact{FirstName: "Sam", LastName: "Lee", Company: "Acme", Email: "[EMAIL]", Phone: "555"} + cases := []struct{ tmpl, want string }{ + {"{{.FirstName}}", "Sam"}, + {"{{first_name}}", "Sam"}, + {"{{ firstName }}", "Sam"}, + {"{{.firstName}}", "Sam"}, + {"{{.first_name}} {{last_name}}", "Sam Lee"}, + {"{{company_name}}/{{.company}}/{{companyName}}", "Acme/Acme/Acme"}, + {"{{email}} {{phone}}", "[EMAIL] 555"}, + {"{{if first_name}}Hi {{first_name}}{{else}}Hi there{{end}}", "Hi Sam"}, + {`{{.nickname | default "friend"}}`, "friend"}, + {`{{first_name | upper}}`, "SAM"}, + {"Write {first_name} or first_name literally", "Write {first_name} or first_name literally"}, + } + for _, tc := range cases { + if got := RenderTemplate(tc.tmpl, contact); got != tc.want { + t.Errorf("%q: got %q, want %q", tc.tmpl, got, tc.want) + } + if got := RenderHTMLTemplateWith(tc.tmpl, contact, TemplateContext{}); got != tc.want { + t.Errorf("html %q: got %q, want %q", tc.tmpl, got, tc.want) + } + } +} + +func TestRenderTemplate_CustomFieldBeatsAlias(t *testing.T) { + contact := models.Contact{FirstName: "Sam", CustomFields: map[string]string{"first_name": "Samantha"}} + if got := RenderTemplate("{{first_name}} {{.first_name}} {{firstName}} {{.FirstName}}", contact); got != "Samantha Samantha Sam Sam" { + t.Fatalf("got %q", got) + } +} + func TestRenderTemplate_CustomFields(t *testing.T) { contact := models.Contact{ FirstName: "Bob", diff --git a/internal/utils/json.go b/internal/utils/json.go index 8221094bc..87bfd9078 100644 --- a/internal/utils/json.go +++ b/internal/utils/json.go @@ -13,7 +13,7 @@ const MaxJSONKeyLength = 255 // actually address. A key is either a plain identifier ("role") or // identifier segments joined by spaces/dashes ("Company Mobile", // "first-name"). That is exactly what the campaign template engine can -// resolve: tasks.rewriteSpacedFieldRefs turns `{{.Company Mobile}}` +// resolve: tmplvars.Normalize turns `{{.Company Mobile}}` // into `(index . "Company Mobile")`, so spaced and dashed keys work // everywhere a plain one does. Anything outside this set would produce a // field the user can never reference in an email. diff --git a/internal/utils/json_test.go b/internal/utils/json_test.go index 2ed56ba8e..d89dde111 100644 --- a/internal/utils/json_test.go +++ b/internal/utils/json_test.go @@ -5,7 +5,7 @@ import "testing" // Issue #207: this rule used to be ^[A-Za-z0-9_]+$, so a CSV column called // "Company Mobile" failed every row of the import even though the campaign // template engine has always been able to resolve a spaced key. The set below -// is exactly what tasks.rewriteSpacedFieldRefs can address, and the same rule +// is exactly what tmplvars.Normalize can address, and the same rule // is mirrored in web/src/components/app/contacts/importShared.ts. func TestIsValidJSONKey(t *testing.T) { valid := []string{"role", "Job_Title", "Company Mobile", "first-name", "plan tier 2", "a"} diff --git a/web/src/components/app/automations/ExpressionReference.tsx b/web/src/components/app/automations/ExpressionReference.tsx index a365fd240..4019b71f2 100644 --- a/web/src/components/app/automations/ExpressionReference.tsx +++ b/web/src/components/app/automations/ExpressionReference.tsx @@ -26,7 +26,7 @@ const SECTIONS: Section[] = [ title: "Variables", blurb: "Email: dotted PascalCase. Automations: the event key with a leading dot ({{.key}}).", entries: [ - { code: "{{.FirstName}}", label: "Contact field (email)", note: "Standard: .FirstName .LastName .Email .Company .Phone. Lowercase {{.firstname}} does NOT work for email merge fields." }, + { code: "{{.FirstName}}", label: "Contact field (email)", note: "Standard: .FirstName .LastName .Email .Company .Phone. Campaign email also accepts first_name, firstName and firstname spellings." }, { code: "{{.role}}", label: "Custom field by key", note: "Any key works, including names with spaces or dashes (e.g. {{.job title}}), in {{if}} and helpers too." }, { code: "{{.contact_email}}", label: "Automation event variable", note: "Standard dotted field access โ€” the leading dot is required. Unknown keys render empty." }, { code: "{{.confidence}}", label: "Reply confidence (reply trigger)", note: "Stays numeric in both conditions and action values, so native gt/lt/eq work. Use gtf only when a value might arrive as text." }, diff --git a/web/src/lib/templateVars.ts b/web/src/lib/templateVars.ts index 3e03f3453..a8f79ae39 100644 --- a/web/src/lib/templateVars.ts +++ b/web/src/lib/templateVars.ts @@ -16,7 +16,7 @@ export const STANDARD_VARS: TemplateVar[] = [ { token: "{{.Phone}}", key: "Phone", label: "Phone", desc: "The contact's phone number", sample: "+1 555-0100" }, ]; -// Keep in sync with the explicit allowlist in internal/tasks/template_sender.go. +// Keep in sync with the explicit allowlist in internal/pkg/tmplvars/sender.go. export const SENDER_VARS: TemplateVar[] = [ ["Name", "Sender name", "The sending mailbox's configured display name", "Jamie Morgan"], ["FirstName", "Sender first name", "The first word of the sending mailbox's display name", "Jamie"], @@ -157,7 +157,7 @@ export function tokenLabel(token: string): string { return parsed ? parsed.key : token; } -// keep in sync with FormLinkMarkerRE in internal/models/form_event.go +// keep in sync with FormLinkMarker in internal/pkg/tmplvars/normalize.go export const FORM_LINK_RE = /\{\{\s*form_link:([a-z0-9]{1,64})\s*\}\}/g; // buildFormLinkToken assembles the literal personalized-form-link marker the Go From 93d8a73cbb584fcfb64f1e9ce13d03851064b9d0 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Tue, 3 Nov 2026 13:16:12 +0100 Subject: [PATCH 131/318] feat: check Sender references through declared variables, with blocks and nested selectors, resolve form links in chosen A/B variant copy, check active variant copy at campaign start, keep line numbers when skipping form-link markers, and match first-name usage only inside template actions --- cmd/backend/main.go | 4 + docs/content/docs/api/reference/campaigns.mdx | 2 +- docs/content/docs/guides/expressions.mdx | 2 +- internal/app/advisor/detect_list.go | 13 +- internal/app/advisor/detect_test.go | 11 +- internal/app/campaign/handlers.go | 12 ++ internal/app/campaign/service.go | 14 ++ internal/app/campaign/template_copy.go | 11 ++ internal/app/campaign/template_copy_test.go | 16 ++ internal/app/sequence/handler_test.go | 25 +++ internal/pkg/tmplvars/normalize.go | 149 +++++++++++++----- internal/pkg/tmplvars/normalize_test.go | 14 ++ internal/tasks/campaign_render_once_test.go | 22 ++- internal/tasks/campaign_task.go | 13 +- 14 files changed, 251 insertions(+), 57 deletions(-) diff --git a/cmd/backend/main.go b/cmd/backend/main.go index f42ea4baf..c2dcd4a25 100644 --- a/cmd/backend/main.go +++ b/cmd/backend/main.go @@ -1554,6 +1554,10 @@ func main() { if aware, ok := campaignService.(campaign.AudienceAware); ok { aware.WireAudience(campaignAudienceRepository) } + // A start checks the copy of every active A/B variant, not only the steps. + if aware, ok := campaignService.(campaign.VariantAware); ok { + aware.WireVariants(advancedRepository) + } // A start with nothing left to send says whether verification is why. if aware, ok := campaignService.(campaign.ProgressAware); ok { aware.WireProgress(campaignProgressRepository) diff --git a/docs/content/docs/api/reference/campaigns.mdx b/docs/content/docs/api/reference/campaigns.mdx index 547629c20..54fe3045b 100644 --- a/docs/content/docs/api/reference/campaigns.mdx +++ b/docs/content/docs/api/reference/campaigns.mdx @@ -828,7 +828,7 @@ Start (activate) the campaign so it begins sending real mail. Works from `draft` A start refused because every remaining lead was refused by address verification answers `leads_undeliverable` and parks the campaign at `paused_undeliverable`; re-verify the leads or mark them deliverable with [`POST /contacts/verification`](/api/reference/contacts/#verify-or-override-contacts), which resumes it. -A campaign whose email step has nothing in either body is refused with `empty_step_body` rather than started, because it would send a blank message to every lead it reached. A step whose copy would not render as written (saved before the check on write existed) is refused with `invalid_template`, naming the step, the field, the line and the problem. +A campaign whose email step has nothing in either body is refused with `empty_step_body` rather than started, because it would send a blank message to every lead it reached. A step or active A/B variant whose copy would not render as written (saved before the check on write existed) is refused with `invalid_template`, naming it, the field, the line and the problem. ### Response diff --git a/docs/content/docs/guides/expressions.mdx b/docs/content/docs/guides/expressions.mdx index 1f5447ea0..a277bec7f 100644 --- a/docs/content/docs/guides/expressions.mdx +++ b/docs/content/docs/guides/expressions.mdx @@ -94,7 +94,7 @@ Values come from the **mailbox actually sending that message**, including campai `{{.Sender.Email}}` is the recipient-visible From address, including a configured send-as alias. `{{.Sender.MailboxEmail}}` is the underlying connected mailbox address. `{{.Sender.ReplyTo}}` is the explicit Reply-To header; it is empty when replies simply go to the sender. -Every field is case-sensitive. Prefix each name below with `.Sender.`, for example `{{.Sender.Provider}}`: +Prefix each name below with `.Sender.`, for example `{{.Sender.Provider}}`. The names are written as shown; campaign copy also accepts their snake_case, camelCase and lowercase spellings (`{{.Sender.first_name}}`), and any other capitalization is refused: | Details | Fields | | --- | --- | diff --git a/internal/app/advisor/detect_list.go b/internal/app/advisor/detect_list.go index b4df29ce0..28d7ae1f8 100644 --- a/internal/app/advisor/detect_list.go +++ b/internal/app/advisor/detect_list.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/pkg/tmplvars" "github.com/warmbly/warmbly/internal/repository" ) @@ -278,12 +279,14 @@ func detectUnsubscribedEnrolled(s *repository.AdvisorSnapshot) []Finding { return out } -// usesFirstName reports whether the copy greets people by first name, in any -// spelling the renderer accepts (`.FirstName`, `first_name`, `firstName`). +// usesFirstName reports whether a template action in the copy names the first +// name, in any spelling the renderer accepts (`.FirstName`, `first_name`, `firstName`). func usesFirstName(text string) bool { - for _, form := range []string{"firstname", "first_name"} { - if indexFold(text, form) >= 0 { - return true + for _, action := range tmplvars.ActionPattern.FindAllString(text, -1) { + for _, form := range []string{"firstname", "first_name"} { + if indexFold(action, form) >= 0 { + return true + } } } return false diff --git a/internal/app/advisor/detect_test.go b/internal/app/advisor/detect_test.go index a0343321c..0efcdb5bd 100644 --- a/internal/app/advisor/detect_test.go +++ b/internal/app/advisor/detect_test.go @@ -792,10 +792,13 @@ func TestMissingFirstNameOnlyFiresWhenTheCopyUsesIt(t *testing.T) { t.Error("missing-first-name fired on copy that never greets by name") } - // The real merge syntax in this product is {{.FirstName}}, not - // {{first_name}} โ€” this is the case a literal-spelling check would miss. - if _, fired := findingsByKey(Detect(build("Hi {{.FirstName}}, worth a chat?"), defaults()))["list_missing_personalization_data"]; !fired { - t.Error("missing-first-name did not fire on copy that does greet by name") + for _, body := range []string{"Hi {{.FirstName}}, worth a chat?", "Hi {{first_name}}, worth a chat?", "Hi {{.firstName | default \"there\"}}"} { + if _, fired := findingsByKey(Detect(build(body), defaults()))["list_missing_personalization_data"]; !fired { + t.Errorf("missing-first-name did not fire on copy that greets by name: %q", body) + } + } + if _, fired := findingsByKey(Detect(build("Update the firstname on file, or first_name in your CRM."), defaults()))["list_missing_personalization_data"]; fired { + t.Error("missing-first-name fired on prose that only mentions the field") } } diff --git a/internal/app/campaign/handlers.go b/internal/app/campaign/handlers.go index e2ebe3ba4..59c211681 100644 --- a/internal/app/campaign/handlers.go +++ b/internal/app/campaign/handlers.go @@ -527,6 +527,18 @@ func (s *campaignService) StartCampaign(ctx context.Context, orgID uuid.UUID, ca if terr := tmplvars.CheckCopy(stepCopy(fmt.Sprintf("step %d", i+1), seq.Subject, seq.BodyHTML, seq.BodyPlain)...); terr != nil { return errx.InvalidTemplate(terr) } + } + if s.variants != nil { + variants, verr := s.variants.ListABVariants(ctx, cID) + if verr != nil { + errs.CaptureException(verr) + return errx.InternalError() + } + if terr := checkActiveVariantCopy(variants); terr != nil { + return errx.InvalidTemplate(terr) + } + } + for i, seq := range seqs { // An email step with nothing in either body sends a blank message // to every lead it reaches. A step created through the API carries // the composer's empty placeholder, which is not an empty string, diff --git a/internal/app/campaign/service.go b/internal/app/campaign/service.go index 66568282f..9c77fc3df 100644 --- a/internal/app/campaign/service.go +++ b/internal/app/campaign/service.go @@ -153,8 +153,22 @@ type campaignService struct { planSnapshotRepo repository.CampaignSendPlanSnapshotRepository // planMaxAge overrides sendPlanSnapshotMaxAge when set (nanoseconds). planMaxAge atomic.Int64 + // variants lists A/B variants so a start checks their copy too. Optional/nil-safe. + variants VariantLister } +// VariantLister is the slice of the advanced-outreach repository Start reads. +type VariantLister interface { + ListABVariants(ctx context.Context, campaignID uuid.UUID) ([]models.CampaignABVariant, error) +} + +// VariantAware lets main hand the campaign service the variant lister. +type VariantAware interface { + WireVariants(v VariantLister) +} + +func (s *campaignService) WireVariants(v VariantLister) { s.variants = v } + // SegmentCounter is the slice of the segment service Estimate needs. // Satisfied structurally by segment.Service. type SegmentCounter interface { diff --git a/internal/app/campaign/template_copy.go b/internal/app/campaign/template_copy.go index 3903de979..326eb91c4 100644 --- a/internal/app/campaign/template_copy.go +++ b/internal/app/campaign/template_copy.go @@ -27,3 +27,14 @@ func checkCreateCopy(data *models.CreateCampaign) error { } return tmplvars.CheckCopy(parts...) } + +// checkActiveVariantCopy refuses a start while an active variant's copy would not render; a control arm sends the step's copy. +func checkActiveVariantCopy(variants []models.CampaignABVariant) error { + var parts []tmplvars.Part + for _, v := range variants { + if v.IsActive && !v.IsControl { + parts = append(parts, stepCopy(fmt.Sprintf("variant %q", v.Name), v.Subject, v.BodyHTML, v.BodyPlain)...) + } + } + return tmplvars.CheckCopy(parts...) +} diff --git a/internal/app/campaign/template_copy_test.go b/internal/app/campaign/template_copy_test.go index 3be3e8e9e..dc9bb2f54 100644 --- a/internal/app/campaign/template_copy_test.go +++ b/internal/app/campaign/template_copy_test.go @@ -26,3 +26,19 @@ func TestCheckCreateCopyNamesTheBrokenStepAndVariant(t *testing.T) { t.Errorf("valid copy refused: %v", err) } } + +func TestCheckActiveVariantCopySkipsInactiveAndControl(t *testing.T) { + broken := "{{if .Company}}x" + variants := []models.CampaignABVariant{ + {Name: "off", BodyPlain: broken, IsActive: false}, + {Name: "control", BodyPlain: broken, IsActive: true, IsControl: true}, + {Name: "ok", Subject: "Hi {{first_name}}", IsActive: true}, + } + if err := checkActiveVariantCopy(variants); err != nil { + t.Fatalf("inactive or control arms refused: %v", err) + } + variants = append(variants, models.CampaignABVariant{Name: "B", BodyHTML: "

    " + broken + "

    ", IsActive: true}) + if err := checkActiveVariantCopy(variants); err == nil || !strings.Contains(err.Error(), `variant "B" body`) { + t.Fatalf("got %v, want the broken active variant named", err) + } +} diff --git a/internal/app/sequence/handler_test.go b/internal/app/sequence/handler_test.go index e757477ab..ffe4be7e9 100644 --- a/internal/app/sequence/handler_test.go +++ b/internal/app/sequence/handler_test.go @@ -5,14 +5,22 @@ import ( "strings" "testing" + "github.com/google/uuid" + "github.com/warmbly/warmbly/internal/errx" "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/pkg/mailhtml" "github.com/warmbly/warmbly/internal/repository" ) type recordingRepo struct { repository.SequenceRepository saved *models.UpdateSequence + steps []models.Sequence +} + +func (r *recordingRepo) Get(_ context.Context, _, _ string) ([]models.Sequence, *errx.Error) { + return r.steps, nil } func (r *recordingRepo) Update(_ context.Context, _, _, _ string, data *models.UpdateSequence) (*models.Sequence, *errx.Error) { @@ -53,3 +61,20 @@ func TestUpdateAcceptsAliasesAndCustomFields(t *testing.T) { t.Fatal("copy must be stored as written, not rewritten") } } + +func TestUpdateDerivesHTMLForPlainOnlyCopy(t *testing.T) { + id := uuid.New() + plain := "Hi {{first_name}},\n\nWorth a chat?" + repo := &recordingRepo{steps: []models.Sequence{{ID: id}}} + if _, xerr := NewService(repo).Update(context.Background(), "org", "c", id.String(), &models.UpdateSequence{BodyPlain: &plain}); xerr != nil { + t.Fatalf("valid plain-only copy refused: %v", xerr) + } + if repo.saved == nil || repo.saved.BodyHTML == nil || *repo.saved.BodyHTML != mailhtml.FromText(plain) { + t.Fatalf("plain-only copy must store HTML derived from it, got %+v", repo.saved) + } + broken := "Hi {{if .Company}}" + repo = &recordingRepo{steps: []models.Sequence{{ID: id}}} + if _, xerr := NewService(repo).Update(context.Background(), "org", "c", id.String(), &models.UpdateSequence{BodyPlain: &broken}); xerr == nil || repo.saved != nil { + t.Fatal("broken plain-only copy must be refused before any HTML is derived or saved") + } +} diff --git a/internal/pkg/tmplvars/normalize.go b/internal/pkg/tmplvars/normalize.go index 2bbddf768..c6e772278 100644 --- a/internal/pkg/tmplvars/normalize.go +++ b/internal/pkg/tmplvars/normalize.go @@ -53,7 +53,7 @@ func Normalize(src string) (string, error) { if _, err := tree.Parse(src, "", "", trees); err != nil { return src, nil // the compiler reports the syntax error itself } - w := &walker{src: src} + w := &walker{src: src, vars: map[string]scope{"$": scopeRoot}} names := make([]string, 0, len(trees)) for name := range trees { names = append(names, name) @@ -61,7 +61,7 @@ func Normalize(src string) (string, error) { sort.Strings(names) for _, name := range names { if t := trees[name]; t != nil && t.Root != nil { - w.node(t.Root) + w.node(t.Root, scopeRoot) } } return w.apply(), w.err @@ -73,7 +73,10 @@ func Check(src string) error { if src == "" { return nil } - norm, err := Normalize(FormLinkMarker.ReplaceAllString(src, "")) + // A marker is dropped for the check, keeping its line breaks so line numbers stay true. + norm, err := Normalize(FormLinkMarker.ReplaceAllStringFunc(src, func(m string) string { + return strings.Repeat("\n", strings.Count(m, "\n")) + })) if err != nil { return err } @@ -101,10 +104,20 @@ type edit struct { text string } +// scope is what a dot or a variable holds, as far as the walker can tell. +type scope int + +const ( + scopeOther scope = iota // a value whose fields the walker does not know + scopeRoot // the template data + scopeSender // the typed Sender value +) + type walker struct { src string edits []edit err error + vars map[string]scope } func (w *walker) fail(pos int, format string, args ...any) { @@ -114,71 +127,115 @@ func (w *walker) fail(pos int, format string, args ...any) { } } -func (w *walker) node(n parse.Node) { +func (w *walker) node(n parse.Node, dot scope) { switch x := n.(type) { case *parse.ListNode: if x == nil { return } for _, c := range x.Nodes { - w.node(c) + w.node(c, dot) } case *parse.ActionNode: - w.pipe(x.Pipe) + w.pipe(x.Pipe, dot, false) case *parse.IfNode: - w.branch(&x.BranchNode) + w.pipe(x.Pipe, dot, false) + w.node(x.List, dot) + w.node(x.ElseList, dot) case *parse.RangeNode: - w.branch(&x.BranchNode) + w.pipe(x.Pipe, dot, true) + w.node(x.List, scopeOther) + w.node(x.ElseList, dot) case *parse.WithNode: - w.branch(&x.BranchNode) + inner := w.pipe(x.Pipe, dot, false) + w.node(x.List, inner) + w.node(x.ElseList, dot) case *parse.TemplateNode: - w.pipe(x.Pipe) + w.pipe(x.Pipe, dot, false) } } -func (w *walker) branch(b *parse.BranchNode) { - w.pipe(b.Pipe) - w.node(b.List) - if b.ElseList != nil { - w.node(b.ElseList) - } -} - -func (w *walker) pipe(p *parse.PipeNode) { +// pipe visits a pipeline, records what its declared variables hold, and +// returns what the pipeline evaluates to. +func (w *walker) pipe(p *parse.PipeNode, dot scope, ranged bool) scope { if p == nil { - return + return scopeOther } for _, cmd := range p.Cmds { for i, arg := range cmd.Args { - w.arg(arg, i == 0 && len(cmd.Args) > 1) + w.arg(arg, i == 0 && len(cmd.Args) > 1, dot) } } + value := w.valueOf(p, dot) + for _, v := range p.Decl { + if ranged { + w.vars[v.Ident[0]] = scopeOther + } else { + w.vars[v.Ident[0]] = value + } + } + return value +} + +// valueOf is what a pipeline of one bare operand holds; anything else is scopeOther. +func (w *walker) valueOf(p *parse.PipeNode, dot scope) scope { + if len(p.Cmds) != 1 || len(p.Cmds[0].Args) != 1 { + return scopeOther + } + switch x := p.Cmds[0].Args[0].(type) { + case *parse.DotNode: + return dot + case *parse.IdentifierNode: + if topNames[x.Ident] == SenderField { + return scopeSender + } + case *parse.FieldNode: + if dot == scopeRoot && len(x.Ident) == 1 && topNames[x.Ident[0]] == SenderField { + return scopeSender + } + case *parse.VariableNode: + held := w.vars[x.Ident[0]] + if len(x.Ident) == 1 { + return held + } + if held == scopeRoot && len(x.Ident) == 2 && topNames[x.Ident[1]] == SenderField { + return scopeSender + } + } + return scopeOther } // arg visits one operand; calls is whether it is a command head given arguments. -func (w *walker) arg(n parse.Node, calls bool) { +func (w *walker) arg(n parse.Node, calls bool, dot scope) { switch x := n.(type) { case *parse.PipeNode: - w.pipe(x) + w.pipe(x, dot, false) case *parse.IdentifierNode: w.identifier(x, calls) case *parse.FieldNode: - w.chain(int(x.Pos), "."+strings.Join(x.Ident, "."), ".", x.Ident) + w.fields(int(x.Pos), "."+strings.Join(x.Ident, "."), "", dot, x.Ident) case *parse.VariableNode: - if len(x.Ident) > 1 && x.Ident[0] == "$" { - w.chain(int(x.Pos), strings.Join(x.Ident, "."), "$.", x.Ident[1:]) + name := x.Ident[0] + held, known := w.vars[name] + if len(x.Ident) == 1 { + return } + if !known || held == scopeOther { + w.fail(int(x.Pos), "fields of %s cannot be checked; refer to the field directly, like {{.Sender.Email}}", name) + return + } + w.fields(int(x.Pos), strings.Join(x.Ident, "."), name, held, x.Ident[1:]) case *parse.ChainNode: switch inner := x.Node.(type) { case *parse.IdentifierNode: - if canonical := topNames[inner.Ident]; canonical == SenderField { + if topNames[inner.Ident] == SenderField { text := inner.Ident + "." + strings.Join(x.Field, ".") - w.chain(int(inner.Pos), text, "$.", append([]string{inner.Ident}, x.Field...)) + w.fields(int(inner.Pos), text, "$", scopeRoot, append([]string{inner.Ident}, x.Field...)) return } w.identifier(inner, false) case *parse.PipeNode: - w.pipe(inner) + w.pipe(inner, dot, false) } } } @@ -202,27 +259,37 @@ func (w *walker) identifier(x *parse.IdentifierNode, calls bool) { } } -// chain canonicalises a reference into Sender, whose field set is fixed. idents -// starts at the root field; text is the reference as written, rewritten as -// prefix plus the canonical idents. -func (w *walker) chain(pos int, text, prefix string, idents []string) { - if len(idents) < 2 { - return - } - if canonical, ok := topNames[idents[0]]; !ok || canonical != SenderField { +// fields checks a selector chain on a value held in scope and canonicalises the +// part that reaches into Sender, whose field set is fixed. text is the chain as +// written, head the variable it starts from ("" for dot). +func (w *walker) fields(pos int, text, head string, held scope, idents []string) { + var sender []string + prefix := head + switch held { + case scopeRoot: + if len(idents) < 2 || topNames[idents[0]] != SenderField { + return + } + sender, prefix = idents[1:], head+"."+SenderField + case scopeSender: + sender = idents + default: return } start := w.locate(pos, text) if start < 0 { return } - field, ok := senderNames[idents[1]] + field, ok := senderNames[sender[0]] if !ok { - w.fail(start, "unknown sender field %q; the sender fields are %s", idents[1], senderList) + w.fail(start, "unknown sender field %q; the sender fields are %s", sender[0], senderList) return } - out := append([]string{SenderField, field}, idents[2:]...) - if rewritten := prefix + strings.Join(out, "."); rewritten != text { + if len(sender) > 1 { + w.fail(start, "sender field %s has no field %q", field, sender[1]) + return + } + if rewritten := prefix + "." + field; rewritten != text { w.edits = append(w.edits, edit{start, start + len(text), rewritten}) } } diff --git a/internal/pkg/tmplvars/normalize_test.go b/internal/pkg/tmplvars/normalize_test.go index d06ae3dae..33ff69c9c 100644 --- a/internal/pkg/tmplvars/normalize_test.go +++ b/internal/pkg/tmplvars/normalize_test.go @@ -24,6 +24,11 @@ func TestNormalize(t *testing.T) { {"sender variable", "{{$.sender.signature_html}}", "{{$.Sender.SignatureHTML}}"}, {"function untouched", "{{upper .FirstName}}", "{{upper .FirstName}}"}, {"unsubscribe alias", "{{unsubscribe_link}}", "{{$.unsubscribe_link}}"}, + {"sender through a variable", "{{$s := .Sender}}{{$s.first_name}}", "{{$s := .Sender}}{{$s.FirstName}}"}, + {"sender through with", "{{with .sender}}{{.signature_html}}{{end}}", "{{with .sender}}{{.SignatureHTML}}{{end}}"}, + {"sender through root variable", "{{$r := .}}{{$r.Sender.email}}", "{{$r := .}}{{$r.Sender.Email}}"}, + {"range element untouched", "{{range .Sender.Tags}}{{.}}{{end}}", "{{range .Sender.Tags}}{{.}}{{end}}"}, + {"range variables untouched", "{{range $k, $v := .}}{{$k}}={{$v}}{{end}}", "{{range $k, $v := .}}{{$k}}={{$v}}{{end}}"}, } for _, tc := range cases { got, err := Normalize(tc.in) @@ -43,6 +48,10 @@ func TestCheckRefusesWhatCannotRender(t *testing.T) { {"{{if .FirstName}}open", "unexpected EOF"}, {"{{.Sender.Bogus}}", `unknown sender field "Bogus"`}, {"{{shout .FirstName}}", `function "shout" is not defined`}, + {"{{.Sender.Email.Bogus}}", `sender field Email has no field "Bogus"`}, + {"{{$s := .Sender}}{{$s.Bogus}}", `unknown sender field "Bogus"`}, + {"{{with .Sender}}{{.Bogus}}{{end}}", `unknown sender field "Bogus"`}, + {"{{range $k, $v := .}}{{$v.x}}{{end}}", "fields of $v cannot be checked"}, } for _, tc := range cases { err := Check(tc.in) @@ -62,6 +71,11 @@ func TestCheckNamesTheLine(t *testing.T) { if err == nil || !strings.HasPrefix(err.Error(), "line 2:") { t.Fatalf("got %v", err) } + // A form-link marker spanning lines keeps the lines after it numbered as written. + err = Check("{{\nform_link:abc123\n}}\n{{frist_name}}") + if err == nil || !strings.HasPrefix(err.Error(), "line 4:") { + t.Fatalf("marker shifted the line: %v", err) + } } func TestAliasesDerivedFromCanonicalFields(t *testing.T) { diff --git a/internal/tasks/campaign_render_once_test.go b/internal/tasks/campaign_render_once_test.go index fe94400b5..64a7ecf26 100644 --- a/internal/tasks/campaign_render_once_test.go +++ b/internal/tasks/campaign_render_once_test.go @@ -31,7 +31,7 @@ func TestSendRendersContactDataOnce(t *testing.T) { for name, picker := range map[string]variantSelector{"no A/B": nil, "control arm": passThrough{}, "variant": passThrough{variant: variant}} { t.Run(name, func(t *testing.T) { rendered, xerr := selectAndRender(context.Background(), picker, uuid.New(), uuid.New(), uuid.New(), contact, TemplateContext{}, "", - "Hi {{.FirstName}}", "

    Hi {{.FirstName}}

    ", "Hi {{.FirstName}}") + "Hi {{.FirstName}}", "

    Hi {{.FirstName}}

    ", "Hi {{.FirstName}}", nil) if xerr != nil { t.Fatal(xerr) } @@ -47,3 +47,23 @@ func TestSendRendersContactDataOnce(t *testing.T) { }) } } + +// A variant's own form-link markers are resolved, not sent as literal text. +func TestSendResolvesFormLinksInTheChosenVariant(t *testing.T) { + variant := &models.VariantSelection{Subject: "Book {{form_link:abc123}}", BodyHTML: "

    {{form_link:abc123}}

    ", BodyPlain: "{{form_link:abc123}}"} + resolve := func(parts ...*string) { + for _, p := range parts { + *p = models.FormLinkMarkerRE.ReplaceAllString(*p, "https://forms.example/f") + } + } + rendered, xerr := selectAndRender(context.Background(), passThrough{variant: variant}, uuid.New(), uuid.New(), uuid.New(), models.Contact{ID: uuid.New()}, TemplateContext{}, "", + "step", "

    step

    ", "step", resolve) + if xerr != nil { + t.Fatal(xerr) + } + for _, out := range []string{rendered.Subject, rendered.BodyHTML, rendered.BodyPlain} { + if strings.Contains(out, "form_link") || !strings.Contains(out, "https://forms.example/f") { + t.Fatalf("variant marker not resolved: %q", out) + } + } +} diff --git a/internal/tasks/campaign_task.go b/internal/tasks/campaign_task.go index 4286bda35..1737053b0 100644 --- a/internal/tasks/campaign_task.go +++ b/internal/tasks/campaign_task.go @@ -631,7 +631,8 @@ func (s *tasksService) HandleCampaignTask(task *proto.ProcessTask) (result *errx // STEP 10: Pick the copy, then render it with contact variables exactly // once and expand any {a|b|c} spintax per-recipient. Rendering happens after // the variant pick so a contact value is never parsed as template text. - rendered, sxerr := s.selectAndRender(ctx, orgID, campaign.ID, sequence.ID, *contact, extra, threadSubject, rawSubject, rawBodyHTML, rawBodyPlain) + resolveLinks := func(parts ...*string) { s.resolveFormLinks(ctx, orgID, campaign, contact, parts...) } + rendered, sxerr := s.selectAndRender(ctx, orgID, campaign.ID, sequence.ID, *contact, extra, threadSubject, rawSubject, rawBodyHTML, rawBodyPlain, resolveLinks) if sxerr != nil { return sxerr } @@ -1898,15 +1899,16 @@ type renderedCopy struct { } // selectAndRender picks the step's copy or an A/B variant from template text, then renders it once. -func (s *tasksService) selectAndRender(ctx context.Context, orgID, campaignID, sequenceID uuid.UUID, contact models.Contact, extra TemplateContext, threadSubject, rawSubject, rawBodyHTML, rawBodyPlain string) (renderedCopy, *errx.Error) { +// resolveLinks resolves form-link markers in the chosen copy, which a variant brings unresolved. +func (s *tasksService) selectAndRender(ctx context.Context, orgID, campaignID, sequenceID uuid.UUID, contact models.Contact, extra TemplateContext, threadSubject, rawSubject, rawBodyHTML, rawBodyPlain string, resolveLinks func(...*string)) (renderedCopy, *errx.Error) { var picker variantSelector if s.advanced != nil { picker = s.advanced } - return selectAndRender(ctx, picker, orgID, campaignID, sequenceID, contact, extra, threadSubject, rawSubject, rawBodyHTML, rawBodyPlain) + return selectAndRender(ctx, picker, orgID, campaignID, sequenceID, contact, extra, threadSubject, rawSubject, rawBodyHTML, rawBodyPlain, resolveLinks) } -func selectAndRender(ctx context.Context, picker variantSelector, orgID, campaignID, sequenceID uuid.UUID, contact models.Contact, extra TemplateContext, threadSubject, rawSubject, rawBodyHTML, rawBodyPlain string) (renderedCopy, *errx.Error) { +func selectAndRender(ctx context.Context, picker variantSelector, orgID, campaignID, sequenceID uuid.UUID, contact models.Contact, extra TemplateContext, threadSubject, rawSubject, rawBodyHTML, rawBodyPlain string, resolveLinks func(...*string)) (renderedCopy, *errx.Error) { var arm *models.StepABArm if picker != nil { selection, xerr := picker.SelectVariant(ctx, orgID, campaignID, contact.ID, sequenceID, rawSubject, rawBodyHTML, rawBodyPlain) @@ -1922,6 +1924,9 @@ func selectAndRender(ctx context.Context, picker variantSelector, orgID, campaig arm = selection.StepArm } } + if resolveLinks != nil { + resolveLinks(&rawSubject, &rawBodyHTML, &rawBodyPlain) + } out := renderedCopy{ Subject: expandSpintax(RenderTemplateWith(rawSubject, contact, extra)), BodyHTML: expandSpintax(RenderHTMLTemplateWith(rawBodyHTML, contact, extra)), From c114dd34aaee47d3a09cf3dc6ec32078b8fb695c Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Tue, 3 Nov 2026 14:33:38 +0100 Subject: [PATCH 132/318] feat: store bare template field aliases in canonical form on every copy write, check HTML bodies with html/template escaping rules, scope template branch variables, refuse selectors on text fields and unknown values, check campaign-level control arm copy, and read first-name usage from parsed field references --- docs/content/docs/api/reference/campaigns.mdx | 2 +- docs/content/docs/guides/expressions.mdx | 4 +- internal/app/advanced/service.go | 55 ++- internal/app/advanced/variant_copy_test.go | 69 +++ internal/app/advisor/detect_list.go | 45 +- internal/app/campaign/handlers.go | 1 + internal/app/campaign/template_copy.go | 18 +- internal/app/campaign/template_copy_test.go | 20 +- internal/app/sequence/handler.go | 5 +- internal/app/sequence/handler_test.go | 20 +- internal/models/advanced_outreach.go | 5 + internal/models/advanced_outreach_test.go | 16 +- internal/pkg/tmplvars/normalize.go | 395 +++++++++++++----- internal/pkg/tmplvars/normalize_test.go | 95 ++++- 14 files changed, 573 insertions(+), 177 deletions(-) create mode 100644 internal/app/advanced/variant_copy_test.go diff --git a/docs/content/docs/api/reference/campaigns.mdx b/docs/content/docs/api/reference/campaigns.mdx index 54fe3045b..2e0353aac 100644 --- a/docs/content/docs/api/reference/campaigns.mdx +++ b/docs/content/docs/api/reference/campaigns.mdx @@ -1425,7 +1425,7 @@ All fields optional. } ``` -`subject`, `body_plain` and `body_html` are checked before anything is saved, on a running campaign too. Copy that would not render as written answers `400` with `code: "invalid_template"` and a `message` naming the field, the line and the problem: an `{{if}}` with no `{{end}}`, an unknown function, an unknown sender field, or a bare name that is not a built-in field. Built-in fields are accepted as `{{.FirstName}}` or in their snake_case, camelCase and lowercase spellings (`{{first_name}}`); see [personalization](/guides/expressions/). +`subject`, `body_plain` and `body_html` are checked before anything is saved, on a running campaign too. Copy that would not render as written answers `400` with `code: "invalid_template"` and a `message` naming the field, the line and the problem: an `{{if}}` with no `{{end}}`, an unknown function, an unknown sender field, or a bare name that is not a built-in field. Built-in fields are accepted as `{{.FirstName}}` or in their snake_case, camelCase and lowercase spellings. A spelling without the dot is saved in canonical form (`{{first_name}}` is stored and returned as `{{.FirstName}}`), as are sender fields; see [personalization](/guides/expressions/). The same applies to campaign creation with `steps` and to A/B variants. A step's control arm (`is_control` with a `step_id`) sends the step's copy, so its own copy is not checked. ### Response diff --git a/docs/content/docs/guides/expressions.mdx b/docs/content/docs/guides/expressions.mdx index a277bec7f..e4cf450e1 100644 --- a/docs/content/docs/guides/expressions.mdx +++ b/docs/content/docs/guides/expressions.mdx @@ -74,7 +74,7 @@ Hi {{.FirstName}}, I noticed {{.Company}} is hiring and wanted to reach out. ``` -Campaign copy also accepts the snake_case, camelCase and lowercase spellings of every built-in field, with or without the dot: `{{first_name}}`, `{{.firstName}}`, `{{firstname}}`, `{{last_name}}`, `{{email}}`, `{{company}}`, `{{company_name}}`, `{{phone}}`, `{{unsubscribe_link}}`, and `{{.Sender.first_name}}` for sender fields. They work inside conditions and helpers as well (`{{if first_name}}`, `{{first_name | default "there"}}`). A contact's own custom field with one of these names keeps its value. `{{.FIRSTNAME}}` is not one of them. +Campaign copy also accepts the snake_case, camelCase and lowercase spellings of every built-in field, with or without the dot: `{{first_name}}`, `{{.firstName}}`, `{{firstname}}`, `{{last_name}}`, `{{email}}`, `{{company}}`, `{{company_name}}`, `{{phone}}`, `{{unsubscribe_link}}`, and `{{.Sender.first_name}}` for sender fields. They work inside conditions and helpers as well (`{{if first_name}}`, `{{first_name | default "there"}}`). A spelling without the dot is saved in canonical form, so `{{first_name}}` is stored as `{{.FirstName}}` and always reads the built-in field, and sender fields are saved under their canonical names. A dotted spelling such as `{{.first_name}}` is kept as written, and a contact's own custom field with that name keeps its value. `{{.FIRSTNAME}}` is not one of them. **Custom fields** work the same way with a dot: `{{.industry}}`, `{{.account_owner}}`. Names containing spaces or dashes also work as written (`{{if .job title}}...{{end}}`) and resolve everywhere, including inside conditions and helpers, because Warmbly rewrites them to an `index` lookup for you. @@ -94,7 +94,7 @@ Values come from the **mailbox actually sending that message**, including campai `{{.Sender.Email}}` is the recipient-visible From address, including a configured send-as alias. `{{.Sender.MailboxEmail}}` is the underlying connected mailbox address. `{{.Sender.ReplyTo}}` is the explicit Reply-To header; it is empty when replies simply go to the sender. -Prefix each name below with `.Sender.`, for example `{{.Sender.Provider}}`. The names are written as shown; campaign copy also accepts their snake_case, camelCase and lowercase spellings (`{{.Sender.first_name}}`), and any other capitalization is refused: +Prefix each name below with `.Sender.`, for example `{{.Sender.Provider}}`. The names are written as shown; campaign copy also accepts their snake_case, camelCase and lowercase spellings (`{{.Sender.first_name}}`, saved as `{{.Sender.FirstName}}`), and any other capitalization is refused. A sender field is text, a flag or a number, so a selector after it (`{{.Sender.Email.Domain}}`) is refused too: | Details | Fields | | --- | --- | diff --git a/internal/app/advanced/service.go b/internal/app/advanced/service.go index cd8efb626..feca027b0 100644 --- a/internal/app/advanced/service.go +++ b/internal/app/advanced/service.go @@ -366,13 +366,12 @@ func (s *service) CreateABVariant(ctx context.Context, campaignID uuid.UUID, req if req == nil || strings.TrimSpace(req.Name) == "" { return nil, errx.New(errx.BadRequest, "variant name is required") } - if err := tmplvars.CheckCopy( - tmplvars.Part{Name: "variant subject", Text: req.Subject}, - tmplvars.Part{Name: "variant body", Text: req.BodyHTML}, - tmplvars.Part{Name: "variant plain-text body", Text: req.BodyPlain}, - ); err != nil { - return nil, errx.InvalidTemplate(err) + if models.VariantSendsOwnCopy(req.SequenceID, req.IsControl) { + if err := checkVariantCopy(req.Subject, req.BodyHTML, req.BodyPlain); err != nil { + return nil, errx.InvalidTemplate(err) + } } + tmplvars.CanonicalizeAll(&req.Subject, &req.BodyHTML, &req.BodyPlain) out, err := s.repo.CreateABVariant(ctx, campaignID, req) if err != nil { return nil, toErrx(err) @@ -381,14 +380,17 @@ func (s *service) CreateABVariant(ctx context.Context, campaignID uuid.UUID, req } func (s *service) UpdateABVariant(ctx context.Context, campaignID, variantID uuid.UUID, req *models.UpdateCampaignABVariantRequest) (*models.CampaignABVariant, *errx.Error) { - if req != nil { - if err := tmplvars.CheckCopy( - tmplvars.Part{Name: "variant subject", Text: deref(req.Subject)}, - tmplvars.Part{Name: "variant body", Text: deref(req.BodyHTML)}, - tmplvars.Part{Name: "variant plain-text body", Text: deref(req.BodyPlain)}, - ); err != nil { - return nil, errx.InvalidTemplate(err) + if req != nil && (req.Subject != nil || req.BodyHTML != nil || req.BodyPlain != nil || req.IsControl != nil) { + sendsOwn, xerr := s.variantSendsOwnCopy(ctx, campaignID, variantID, req.IsControl) + if xerr != nil { + return nil, xerr } + if sendsOwn { + if err := checkVariantCopy(deref(req.Subject), deref(req.BodyHTML), deref(req.BodyPlain)); err != nil { + return nil, errx.InvalidTemplate(err) + } + } + tmplvars.CanonicalizeAll(req.Subject, req.BodyHTML, req.BodyPlain) } out, err := s.repo.UpdateABVariant(ctx, campaignID, variantID, req) if err != nil { @@ -397,6 +399,33 @@ func (s *service) UpdateABVariant(ctx context.Context, campaignID, variantID uui return out, nil } +func checkVariantCopy(subject, bodyHTML, bodyPlain string) error { + return tmplvars.CheckCopy( + tmplvars.Part{Name: "variant subject", Text: subject}, + tmplvars.Part{Name: "variant body", Text: bodyHTML, HTML: true}, + tmplvars.Part{Name: "variant plain-text body", Text: bodyPlain}, + ) +} + +// variantSendsOwnCopy reads whether the variant, with isControl applied, sends its own copy. +// A variant that is not found is checked, and the update reports the miss. +func (s *service) variantSendsOwnCopy(ctx context.Context, campaignID, variantID uuid.UUID, isControl *bool) (bool, *errx.Error) { + variants, err := s.repo.ListABVariants(ctx, campaignID) + if err != nil { + return false, toErrx(err) + } + for _, v := range variants { + if v.ID == variantID { + control := v.IsControl + if isControl != nil { + control = *isControl + } + return models.VariantSendsOwnCopy(v.SequenceID, control), nil + } + } + return true, nil +} + func deref(s *string) string { if s == nil { return "" diff --git a/internal/app/advanced/variant_copy_test.go b/internal/app/advanced/variant_copy_test.go new file mode 100644 index 000000000..f3a134bc6 --- /dev/null +++ b/internal/app/advanced/variant_copy_test.go @@ -0,0 +1,69 @@ +package advanced + +import ( + "context" + "testing" + + "github.com/google/uuid" + "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/repository" +) + +type variantRepo struct { + repository.AdvancedOutreachRepository + rows []models.CampaignABVariant + created *models.CreateCampaignABVariantRequest + updated *models.UpdateCampaignABVariantRequest +} + +func (r *variantRepo) ListABVariants(context.Context, uuid.UUID) ([]models.CampaignABVariant, error) { + return r.rows, nil +} + +func (r *variantRepo) CreateABVariant(_ context.Context, _ uuid.UUID, req *models.CreateCampaignABVariantRequest) (*models.CampaignABVariant, error) { + r.created = req + return &models.CampaignABVariant{}, nil +} + +func (r *variantRepo) UpdateABVariant(_ context.Context, _, _ uuid.UUID, req *models.UpdateCampaignABVariantRequest) (*models.CampaignABVariant, error) { + r.updated = req + return &models.CampaignABVariant{}, nil +} + +func TestVariantCopyIsCheckedUnlessItIsAStepControlArm(t *testing.T) { + broken := "{{if .Company}}x" + step := uuid.New() + ctx, campaign := context.Background(), uuid.New() + + repo := &variantRepo{} + svc := &service{repo: repo} + if _, xerr := svc.CreateABVariant(ctx, campaign, &models.CreateCampaignABVariantRequest{Name: "ctl", SequenceID: &step, IsControl: true, BodyPlain: broken}); xerr != nil { + t.Fatalf("a step's control arm never sends its copy: %v", xerr) + } + for _, req := range []*models.CreateCampaignABVariantRequest{ + {Name: "campaign control", IsControl: true, BodyPlain: broken}, + {Name: "B", SequenceID: &step, Subject: broken}, + } { + if _, xerr := svc.CreateABVariant(ctx, campaign, req); xerr == nil || xerr.Identifier != "invalid_template" { + t.Errorf("%s: got %v, want invalid_template", req.Name, xerr) + } + } + + if _, xerr := svc.CreateABVariant(ctx, campaign, &models.CreateCampaignABVariantRequest{Name: "B", Subject: "Hi {{first_name}}"}); xerr != nil || repo.created.Subject != "Hi {{.FirstName}}" { + t.Fatalf("a bare alias should be stored canonical: %v %+v", xerr, repo.created) + } + + id := uuid.New() + repo.rows = []models.CampaignABVariant{{ID: id, SequenceID: &step, IsControl: true}} + if _, xerr := svc.UpdateABVariant(ctx, campaign, id, &models.UpdateCampaignABVariantRequest{BodyPlain: &broken}); xerr != nil { + t.Fatalf("updating a step's control arm copy: %v", xerr) + } + off := false + if _, xerr := svc.UpdateABVariant(ctx, campaign, id, &models.UpdateCampaignABVariantRequest{BodyPlain: &broken, IsControl: &off}); xerr == nil { + t.Fatal("turning the control off makes it send its copy, so the copy is checked") + } + plain := "{{company_name}}" + if _, xerr := svc.UpdateABVariant(ctx, campaign, id, &models.UpdateCampaignABVariantRequest{BodyPlain: &plain, IsControl: &off}); xerr != nil || *repo.updated.BodyPlain != "{{.Company}}" { + t.Fatalf("a bare alias should be stored canonical on update: %v", xerr) + } +} diff --git a/internal/app/advisor/detect_list.go b/internal/app/advisor/detect_list.go index 28d7ae1f8..e5cdb9291 100644 --- a/internal/app/advisor/detect_list.go +++ b/internal/app/advisor/detect_list.go @@ -200,7 +200,7 @@ func detectMissingPersonalizationData(s *repository.AdvisorSnapshot) []Finding { if st.CampaignID != cl.Campaign.ID { continue } - if usesFirstName(st.Subject + st.BodyPlain + st.BodyHTML) { + if usesFirstName(st.Subject, st.BodyPlain, st.BodyHTML) { uses = true break } @@ -279,44 +279,13 @@ func detectUnsubscribedEnrolled(s *repository.AdvisorSnapshot) []Finding { return out } -// usesFirstName reports whether a template action in the copy names the first -// name, in any spelling the renderer accepts (`.FirstName`, `first_name`, `firstName`). -func usesFirstName(text string) bool { - for _, action := range tmplvars.ActionPattern.FindAllString(text, -1) { - for _, form := range []string{"firstname", "first_name"} { - if indexFold(action, form) >= 0 { - return true - } +// usesFirstName reports whether any part reads the contact's first name, in +// any spelling the renderer accepts (`.FirstName`, `first_name`, `firstName`). +func usesFirstName(parts ...string) bool { + for _, p := range parts { + if tmplvars.References(p)["FirstName"] { + return true } } return false } - -// indexFold is a case-insensitive substring search that avoids allocating a -// lowered copy of every email body on every run. -func indexFold(haystack, needle string) int { - n, h := len(needle), len(haystack) - if n == 0 || n > h { - return -1 - } - for i := 0; i+n <= h; i++ { - match := true - for j := 0; j < n; j++ { - a, b := haystack[i+j], needle[j] - if 'A' <= a && a <= 'Z' { - a += 'a' - 'A' - } - if 'A' <= b && b <= 'Z' { - b += 'a' - 'A' - } - if a != b { - match = false - break - } - } - if match { - return i - } - } - return -1 -} diff --git a/internal/app/campaign/handlers.go b/internal/app/campaign/handlers.go index 59c211681..4919b211d 100644 --- a/internal/app/campaign/handlers.go +++ b/internal/app/campaign/handlers.go @@ -50,6 +50,7 @@ func (s *campaignService) Create(ctx context.Context, userID string, orgID *uuid if err := checkCreateCopy(data); err != nil { return nil, errx.InvalidTemplate(err) } + canonicalizeCreateCopy(data) // Daily creation throttle (config.DailyThrottleNewCampaigns). Caps // per-day new-campaign rate per org so an unlimited plan can't be diff --git a/internal/app/campaign/template_copy.go b/internal/app/campaign/template_copy.go index 326eb91c4..9957eb1c4 100644 --- a/internal/app/campaign/template_copy.go +++ b/internal/app/campaign/template_copy.go @@ -11,7 +11,7 @@ import ( func stepCopy(owner, subject, bodyHTML, bodyPlain string) []tmplvars.Part { return []tmplvars.Part{ {Name: owner + " subject", Text: subject}, - {Name: owner + " body", Text: bodyHTML}, + {Name: owner + " body", Text: bodyHTML, HTML: true}, {Name: owner + " plain-text body", Text: bodyPlain}, } } @@ -28,11 +28,23 @@ func checkCreateCopy(data *models.CreateCampaign) error { return tmplvars.CheckCopy(parts...) } -// checkActiveVariantCopy refuses a start while an active variant's copy would not render; a control arm sends the step's copy. +// canonicalizeCreateCopy stores the new campaign's copy in canonical form. +func canonicalizeCreateCopy(data *models.CreateCampaign) { + for i := range data.Sequences { + seq := &data.Sequences[i] + tmplvars.CanonicalizeAll(&seq.Subject, &seq.BodyHTML, &seq.BodyPlain) + } + for i := range data.Variants { + v := &data.Variants[i] + tmplvars.CanonicalizeAll(&v.Subject, &v.BodyHTML, &v.BodyPlain) + } +} + +// checkActiveVariantCopy refuses a start while an active variant that sends its own copy would not render. func checkActiveVariantCopy(variants []models.CampaignABVariant) error { var parts []tmplvars.Part for _, v := range variants { - if v.IsActive && !v.IsControl { + if v.IsActive && models.VariantSendsOwnCopy(v.SequenceID, v.IsControl) { parts = append(parts, stepCopy(fmt.Sprintf("variant %q", v.Name), v.Subject, v.BodyHTML, v.BodyPlain)...) } } diff --git a/internal/app/campaign/template_copy_test.go b/internal/app/campaign/template_copy_test.go index dc9bb2f54..ef3f1cc17 100644 --- a/internal/app/campaign/template_copy_test.go +++ b/internal/app/campaign/template_copy_test.go @@ -4,6 +4,7 @@ import ( "strings" "testing" + "github.com/google/uuid" "github.com/warmbly/warmbly/internal/models" ) @@ -29,9 +30,10 @@ func TestCheckCreateCopyNamesTheBrokenStepAndVariant(t *testing.T) { func TestCheckActiveVariantCopySkipsInactiveAndControl(t *testing.T) { broken := "{{if .Company}}x" + step := uuid.New() variants := []models.CampaignABVariant{ {Name: "off", BodyPlain: broken, IsActive: false}, - {Name: "control", BodyPlain: broken, IsActive: true, IsControl: true}, + {Name: "control", BodyPlain: broken, IsActive: true, IsControl: true, SequenceID: &step}, {Name: "ok", Subject: "Hi {{first_name}}", IsActive: true}, } if err := checkActiveVariantCopy(variants); err != nil { @@ -41,4 +43,20 @@ func TestCheckActiveVariantCopySkipsInactiveAndControl(t *testing.T) { if err := checkActiveVariantCopy(variants); err == nil || !strings.Contains(err.Error(), `variant "B" body`) { t.Fatalf("got %v, want the broken active variant named", err) } + // A campaign-level control arm sends its own copy, so it is checked. + campaignControl := []models.CampaignABVariant{{Name: "campaign control", Subject: broken, IsActive: true, IsControl: true}} + if err := checkActiveVariantCopy(campaignControl); err == nil { + t.Fatal("a campaign-level control arm's broken copy should be refused") + } +} + +func TestCanonicalizeCreateCopy(t *testing.T) { + data := &models.CreateCampaign{ + Sequences: []models.CreateSequenceInput{{Subject: "Hi {{first_name}}", BodyPlain: "{{.first_name}}"}}, + Variants: []models.CreateCampaignABVariantRequest{{Name: "B", BodyHTML: "

    {{company_name}}

    "}}, + } + canonicalizeCreateCopy(data) + if data.Sequences[0].Subject != "Hi {{.FirstName}}" || data.Sequences[0].BodyPlain != "{{.first_name}}" || data.Variants[0].BodyHTML != "

    {{.Company}}

    " { + t.Fatalf("got %+v", data) + } } diff --git a/internal/app/sequence/handler.go b/internal/app/sequence/handler.go index a553caaec..32440c5f4 100644 --- a/internal/app/sequence/handler.go +++ b/internal/app/sequence/handler.go @@ -26,6 +26,9 @@ func (s *sequenceService) Update(ctx context.Context, orgID, campaignID, sequenc if err := checkCopy(data); err != nil { return nil, errx.InvalidTemplate(err) } + if data != nil { + tmplvars.CanonicalizeAll(data.Subject, data.BodyHTML, data.BodyPlain) + } s.deriveBodyHTML(ctx, orgID, campaignID, sequenceID, data) // Branch routing is resolved (and made safe against deleted/dangling targets // and loops) at schedule time in the repository's finder; the repository also @@ -45,7 +48,7 @@ func checkCopy(data *models.UpdateSequence) error { val *string }{{"subject", data.Subject}, {"body", data.BodyHTML}, {"plain-text body", data.BodyPlain}} { if f.val != nil { - parts = append(parts, tmplvars.Part{Name: f.name, Text: *f.val}) + parts = append(parts, tmplvars.Part{Name: f.name, Text: *f.val, HTML: f.val == data.BodyHTML}) } } return tmplvars.CheckCopy(parts...) diff --git a/internal/app/sequence/handler_test.go b/internal/app/sequence/handler_test.go index ffe4be7e9..ce5c902ed 100644 --- a/internal/app/sequence/handler_test.go +++ b/internal/app/sequence/handler_test.go @@ -57,8 +57,9 @@ func TestUpdateAcceptsAliasesAndCustomFields(t *testing.T) { if _, xerr := NewService(repo).Update(context.Background(), "org", "c", "s", &models.UpdateSequence{BodyHTML: &body}); xerr != nil { t.Fatalf("valid copy refused: %v", xerr) } - if repo.saved == nil || *repo.saved.BodyHTML != body { - t.Fatal("copy must be stored as written, not rewritten") + want := `

    Hi {{.FirstName}}, {{if .company_name}}at {{.company_name}}{{end}} {{.job title}} {{.anything_custom | default "x"}}

    ` + if repo.saved == nil || *repo.saved.BodyHTML != want { + t.Fatalf("only the bare alias is stored in canonical form, got %q", *repo.saved.BodyHTML) } } @@ -69,7 +70,8 @@ func TestUpdateDerivesHTMLForPlainOnlyCopy(t *testing.T) { if _, xerr := NewService(repo).Update(context.Background(), "org", "c", id.String(), &models.UpdateSequence{BodyPlain: &plain}); xerr != nil { t.Fatalf("valid plain-only copy refused: %v", xerr) } - if repo.saved == nil || repo.saved.BodyHTML == nil || *repo.saved.BodyHTML != mailhtml.FromText(plain) { + canonical := "Hi {{.FirstName}},\n\nWorth a chat?" + if repo.saved == nil || *repo.saved.BodyPlain != canonical || repo.saved.BodyHTML == nil || *repo.saved.BodyHTML != mailhtml.FromText(canonical) { t.Fatalf("plain-only copy must store HTML derived from it, got %+v", repo.saved) } broken := "Hi {{if .Company}}" @@ -78,3 +80,15 @@ func TestUpdateDerivesHTMLForPlainOnlyCopy(t *testing.T) { t.Fatal("broken plain-only copy must be refused before any HTML is derived or saved") } } + +func TestUpdateRefusesEscaperBeforePipeInHTMLOnly(t *testing.T) { + body := `{{html .FirstName | printf "%s"}}` + repo := &recordingRepo{} + if _, xerr := NewService(repo).Update(context.Background(), "org", "c", "s", &models.UpdateSequence{BodyHTML: &body}); xerr == nil || xerr.Identifier != "invalid_template" { + t.Fatalf("an HTML body the HTML renderer refuses should be refused, got %v", xerr) + } + repo = &recordingRepo{} + if _, xerr := NewService(repo).Update(context.Background(), "org", "c", "s", &models.UpdateSequence{Subject: &body}); xerr != nil { + t.Fatalf("the same text in a plain subject renders, got %v", xerr) + } +} diff --git a/internal/models/advanced_outreach.go b/internal/models/advanced_outreach.go index 3841a796a..0d98e1aa9 100644 --- a/internal/models/advanced_outreach.go +++ b/internal/models/advanced_outreach.go @@ -750,6 +750,11 @@ type CampaignABVariant struct { UpdatedAt time.Time `json:"updated_at"` } +// VariantSendsOwnCopy is false only for a step's control arm, which sends the step's copy. +func VariantSendsOwnCopy(sequenceID *uuid.UUID, isControl bool) bool { + return !isControl || sequenceID == nil +} + type CreateCampaignABVariantRequest struct { Name string `json:"name" binding:"required"` SequenceID *uuid.UUID `json:"step_id,omitempty"` diff --git a/internal/models/advanced_outreach_test.go b/internal/models/advanced_outreach_test.go index 2bdcd0c80..ff960a07d 100644 --- a/internal/models/advanced_outreach_test.go +++ b/internal/models/advanced_outreach_test.go @@ -1,6 +1,10 @@ package models -import "testing" +import ( + "testing" + + "github.com/google/uuid" +) // The content-score floor reaches the API as a plain integer. Left unclamped, a // floor above 100 flags every campaign forever and a floor at or below 0 is a @@ -110,3 +114,13 @@ func TestNilIntentListStaysNilThroughNormalize(t *testing.T) { t.Error("Normalize turned an unset list into an empty one, which means none") } } + +func TestVariantSendsOwnCopy(t *testing.T) { + step := uuid.New() + if VariantSendsOwnCopy(&step, true) { + t.Error("a step's control arm sends the step's copy") + } + if !VariantSendsOwnCopy(nil, true) || !VariantSendsOwnCopy(&step, false) || !VariantSendsOwnCopy(nil, false) { + t.Error("every other variant sends its own copy") + } +} diff --git a/internal/pkg/tmplvars/normalize.go b/internal/pkg/tmplvars/normalize.go index c6e772278..5dee99ec3 100644 --- a/internal/pkg/tmplvars/normalize.go +++ b/internal/pkg/tmplvars/normalize.go @@ -3,6 +3,8 @@ package tmplvars import ( "errors" "fmt" + htmltemplate "html/template" + "maps" "regexp" "sort" "strings" @@ -24,6 +26,8 @@ var FormLinkMarker = regexp.MustCompile(`\{\{\s*form_link:([a-z0-9]{1,64})\s*\}\ // a valid selector and is rewritten to `(index . "key")`. var spacedFieldRefAt = regexp.MustCompile(`^\.[A-Za-z0-9_]+(?:[ \-]+[A-Za-z0-9_]+)+`) +var htmlComment = regexp.MustCompile(`(?s)`) + // builtinFuncs are text/template's own functions, which a bare name may call. var builtinFuncs = map[string]bool{ "and": true, "call": true, "html": true, "index": true, "slice": true, "js": true, "len": true, @@ -36,6 +40,16 @@ func isFunc(name string) bool { return ok || builtinFuncs[name] } +// mode is what the walker's rewrites are for. +type mode int + +const ( + // forRender keeps a bare alias's spelling, so a custom field of that name wins. + forRender mode = iota + // forStore writes a bare alias as its canonical field, which every release renders. + forStore +) + // Normalize rewrites the accepted spellings of campaign copy into the form the // engine compiles: spaced and dashed custom-field keys become index calls, a // bare built-in name ({{first_name}}) becomes a field of the root, and Sender @@ -43,17 +57,65 @@ func isFunc(name string) bool { // are never touched. The error names a reference that can never resolve; the // returned source is usable either way, so a renderer may ignore it. func Normalize(src string) (string, error) { - if !strings.Contains(src, "{{") { - return src, nil + w, rewritten, _ := analyze(src, forRender) + if w == nil { + return rewritten, nil // the compiler reports a syntax error itself } - src = ActionPattern.ReplaceAllStringFunc(src, rewriteSpacedInAction) + return applyEdits(rewritten, w.edits), w.err +} + +// Canonicalize is the copy to store for src: bare built-in aliases become their +// canonical field ({{first_name}} is {{.FirstName}}) and Sender fields take +// their canonical names, so the previous release renders it too. Dotted aliases +// and everything outside actions are kept as written. +func Canonicalize(src string) string { + w, _, spans := analyze(src, forStore) + if w == nil || w.err != nil || len(w.edits) == 0 { + return src + } + edits := make([]edit, 0, len(w.edits)) + for _, e := range w.edits { + start, ok1 := toOriginal(e.start, spans) + end, ok2 := toOriginal(e.end, spans) + if ok1 && ok2 { + edits = append(edits, edit{start, end, e.text}) + } + } + return applyEdits(src, edits) +} + +// CanonicalizeAll canonicalises each non-nil copy field in place. +func CanonicalizeAll(fields ...*string) { + for _, f := range fields { + if f != nil { + *f = Canonicalize(*f) + } + } +} + +// References lists the canonical built-in fields src reads from the contact. +func References(src string) map[string]bool { + w, _, _ := analyze(src, forRender) + if w == nil { + return nil + } + return w.refs +} + +// analyze parses src with spaced references rewritten and form-link markers +// blanked, and walks it. A nil walker means src does not parse. +func analyze(src string, m mode) (*walker, string, []span) { + if !strings.Contains(src, "{{") { + return nil, src, nil + } + rewritten, spans := rewriteSpaced(src) tree := parse.New("normalize") tree.Mode = parse.SkipFuncCheck trees := map[string]*parse.Tree{} - if _, err := tree.Parse(src, "", "", trees); err != nil { - return src, nil // the compiler reports the syntax error itself + if _, err := tree.Parse(maskMarkers(rewritten), "", "", trees); err != nil { + return nil, rewritten, spans } - w := &walker{src: src, vars: map[string]scope{"$": scopeRoot}} + w := &walker{src: rewritten, mode: m, vars: map[string]scope{"$": scopeRoot}, refs: map[string]bool{}} names := make([]string, 0, len(trees)) for name := range trees { names = append(names, name) @@ -64,7 +126,21 @@ func Normalize(src string) (string, error) { w.node(t.Root, scopeRoot) } } - return w.apply(), w.err + return w, rewritten, spans +} + +// maskMarkers blanks each form-link marker, keeping offsets and line breaks. +func maskMarkers(src string) string { + return FormLinkMarker.ReplaceAllStringFunc(src, blank) +} + +func blank(s string) string { + return strings.Map(func(r rune) rune { + if r == '\n' { + return r + } + return ' ' + }, s) } // Check reports whether campaign copy compiles as written, naming the problem @@ -73,10 +149,7 @@ func Check(src string) error { if src == "" { return nil } - // A marker is dropped for the check, keeping its line breaks so line numbers stay true. - norm, err := Normalize(FormLinkMarker.ReplaceAllStringFunc(src, func(m string) string { - return strings.Repeat("\n", strings.Count(m, "\n")) - })) + norm, err := Normalize(maskMarkers(src)) if err != nil { return err } @@ -86,13 +159,49 @@ func Check(src string) error { return nil } -// Part is one named piece of copy to check. -type Part struct{ Name, Text string } +// CheckHTML reports an HTML body the HTML renderer refuses although it parses: +// a predefined escaper (html, urlquery) placed before a pipe. +func CheckHTML(src string) error { + if !strings.Contains(src, "{{") { + return nil + } + // Comments are shielded as the renderer shields them: a comment holding an action renders as text. + src = htmlComment.ReplaceAllStringFunc(src, func(c string) string { + if strings.Contains(c, "{{") { + return " " + c[4:len(c)-3] + " " + } + return blank(c) + }) + norm, err := Normalize(maskMarkers(src)) + if err != nil { + return nil // Check reports it + } + t, err := tmplfuncs.CompileHTML("copy", norm) + if err != nil { + return nil // Check reports it + } + _, err = tmplfuncs.Execute(t, map[string]any{}) + var he *htmltemplate.Error + if errors.As(err, &he) && he.ErrorCode == htmltemplate.ErrPredefinedEscaper { + return fmt.Errorf("line %d: %s", he.Line, he.Description) + } + return nil +} + +// Part is one named piece of copy to check; HTML marks a body rendered as HTML. +type Part struct { + Name, Text string + HTML bool +} // CheckCopy checks each part in order and reports the first problem with its part's name. func CheckCopy(parts ...Part) error { for _, p := range parts { - if err := Check(p.Text); err != nil { + err := Check(p.Text) + if err == nil && p.HTML { + err = CheckHTML(p.Text) + } + if err != nil { return fmt.Errorf("the %s has a template error: %w", p.Name, err) } } @@ -104,6 +213,43 @@ type edit struct { text string } +// span is one spaced-reference rewrite: [origStart, origEnd) became [newStart, newEnd). +type span struct{ origStart, origEnd, newStart, newEnd int } + +// toOriginal maps an offset in the rewritten source back to src; false inside a rewrite. +func toOriginal(pos int, spans []span) (int, bool) { + delta := 0 + for _, s := range spans { + if pos <= s.newStart { + break + } + if pos < s.newEnd { + return 0, false + } + delta += (s.newEnd - s.newStart) - (s.origEnd - s.origStart) + } + return pos - delta, true +} + +func applyEdits(src string, edits []edit) string { + if len(edits) == 0 { + return src + } + sort.Slice(edits, func(i, j int) bool { return edits[i].start < edits[j].start }) + var b strings.Builder + last := 0 + for _, e := range edits { + if e.start < last { + continue + } + b.WriteString(src[last:e.start]) + b.WriteString(e.text) + last = e.end + } + b.WriteString(src[last:]) + return b.String() +} + // scope is what a dot or a variable holds, as far as the walker can tell. type scope int @@ -114,15 +260,18 @@ const ( ) type walker struct { - src string - edits []edit - err error - vars map[string]scope + src string + mode mode + edits []edit + err error + vars map[string]scope + assigned []string // variables reassigned with =, in walk order + refs map[string]bool } func (w *walker) fail(pos int, format string, args ...any) { if w.err == nil { - line := strings.Count(w.src[:min(pos, len(w.src))], "\n") + 1 + line := strings.Count(w.src[:min(max(pos, 0), len(w.src))], "\n") + 1 w.err = fmt.Errorf("line %d: %s", line, fmt.Sprintf(format, args...)) } } @@ -139,24 +288,38 @@ func (w *walker) node(n parse.Node, dot scope) { case *parse.ActionNode: w.pipe(x.Pipe, dot, false) case *parse.IfNode: - w.pipe(x.Pipe, dot, false) - w.node(x.List, dot) - w.node(x.ElseList, dot) - case *parse.RangeNode: - w.pipe(x.Pipe, dot, true) - w.node(x.List, scopeOther) - w.node(x.ElseList, dot) + w.structure(&x.BranchNode, dot, func(scope) scope { return dot }, false) case *parse.WithNode: - inner := w.pipe(x.Pipe, dot, false) - w.node(x.List, inner) - w.node(x.ElseList, dot) + w.structure(&x.BranchNode, dot, func(v scope) scope { return v }, false) + case *parse.RangeNode: + w.structure(&x.BranchNode, dot, func(scope) scope { return scopeOther }, true) case *parse.TemplateNode: w.pipe(x.Pipe, dot, false) } } -// pipe visits a pipeline, records what its declared variables hold, and -// returns what the pipeline evaluates to. +// structure walks an if, with or range. Variables declared inside it end with +// it; the body and the else branch start from the same bindings; a variable +// either branch reassigns is unknown afterwards. +func (w *walker) structure(b *parse.BranchNode, dot scope, bodyDot func(scope) scope, ranged bool) { + outer, mark := w.vars, len(w.assigned) + w.vars = maps.Clone(outer) + value := w.pipe(b.Pipe, dot, ranged) + declared := w.vars + w.vars = maps.Clone(declared) + w.node(b.List, bodyDot(value)) + w.vars = maps.Clone(declared) + w.node(b.ElseList, dot) + w.vars = outer + for _, name := range w.assigned[mark:] { + if _, ok := outer[name]; ok { + outer[name] = scopeOther + } + } +} + +// pipe visits a pipeline, records what its variables hold, and returns what +// the pipeline evaluates to. func (w *walker) pipe(p *parse.PipeNode, dot scope, ranged bool) scope { if p == nil { return scopeOther @@ -167,22 +330,26 @@ func (w *walker) pipe(p *parse.PipeNode, dot scope, ranged bool) scope { } } value := w.valueOf(p, dot) + if ranged { + value = scopeOther + } for _, v := range p.Decl { - if ranged { - w.vars[v.Ident[0]] = scopeOther - } else { - w.vars[v.Ident[0]] = value + w.vars[v.Ident[0]] = value + if p.IsAssign { + w.assigned = append(w.assigned, v.Ident[0]) } } return value } -// valueOf is what a pipeline of one bare operand holds; anything else is scopeOther. +// valueOf is what a pipeline of one operand holds; anything else is scopeOther. func (w *walker) valueOf(p *parse.PipeNode, dot scope) scope { if len(p.Cmds) != 1 || len(p.Cmds[0].Args) != 1 { return scopeOther } switch x := p.Cmds[0].Args[0].(type) { + case *parse.PipeNode: + return w.valueOf(x, dot) case *parse.DotNode: return dot case *parse.IdentifierNode: @@ -211,41 +378,39 @@ func (w *walker) arg(n parse.Node, calls bool, dot scope) { case *parse.PipeNode: w.pipe(x, dot, false) case *parse.IdentifierNode: - w.identifier(x, calls) + w.identifier(x, calls, dot) case *parse.FieldNode: w.fields(int(x.Pos), "."+strings.Join(x.Ident, "."), "", dot, x.Ident) case *parse.VariableNode: - name := x.Ident[0] - held, known := w.vars[name] - if len(x.Ident) == 1 { - return + if len(x.Ident) > 1 { + w.fields(int(x.Pos), strings.Join(x.Ident, "."), x.Ident[0], w.vars[x.Ident[0]], x.Ident[1:]) } - if !known || held == scopeOther { - w.fail(int(x.Pos), "fields of %s cannot be checked; refer to the field directly, like {{.Sender.Email}}", name) - return - } - w.fields(int(x.Pos), strings.Join(x.Ident, "."), name, held, x.Ident[1:]) case *parse.ChainNode: switch inner := x.Node.(type) { case *parse.IdentifierNode: - if topNames[inner.Ident] == SenderField { - text := inner.Ident + "." + strings.Join(x.Field, ".") - w.fields(int(inner.Pos), text, "$", scopeRoot, append([]string{inner.Ident}, x.Field...)) + if _, builtin := topNames[inner.Ident]; !builtin { + w.identifier(inner, false, dot) return } - w.identifier(inner, false) + head := "$" + if dot == scopeRoot { + head = "" + } + text := inner.Ident + "." + strings.Join(x.Field, ".") + w.fields(int(inner.Pos), text, head, scopeRoot, append([]string{inner.Ident}, x.Field...)) case *parse.PipeNode: w.pipe(inner, dot, false) } } } -func (w *walker) identifier(x *parse.IdentifierNode, calls bool) { +func (w *walker) identifier(x *parse.IdentifierNode, calls bool, dot scope) { if isFunc(x.Ident) { return } pos := int(x.Pos) - if _, ok := topNames[x.Ident]; !ok || calls { + canonical, ok := topNames[x.Ident] + if !ok || calls { if calls { w.fail(pos, "function %q is not defined", x.Ident) return @@ -253,43 +418,69 @@ func (w *walker) identifier(x *parse.IdentifierNode, calls bool) { w.fail(pos, "%s", unknownVariable(x.Ident)) return } - if strings.HasPrefix(w.src[pos:], x.Ident) { - // The alias spelling is kept, so a custom field of that name still wins. - w.edits = append(w.edits, edit{pos, pos + len(x.Ident), "$." + x.Ident}) + w.refs[canonical] = true + if !strings.HasPrefix(w.src[pos:], x.Ident) { + return } + prefix := "$." + if dot == scopeRoot { + prefix = "." + } + name := x.Ident // the alias spelling, so a custom field of that name still wins + if w.mode == forStore { + name = canonical + } + w.edits = append(w.edits, edit{pos, pos + len(x.Ident), prefix + name}) } // fields checks a selector chain on a value held in scope and canonicalises the // part that reaches into Sender, whose field set is fixed. text is the chain as // written, head the variable it starts from ("" for dot). func (w *walker) fields(pos int, text, head string, held scope, idents []string) { - var sender []string - prefix := head - switch held { - case scopeRoot: - if len(idents) < 2 || topNames[idents[0]] != SenderField { - return - } - sender, prefix = idents[1:], head+"."+SenderField - case scopeSender: - sender = idents - default: - return - } start := w.locate(pos, text) if start < 0 { - return + start = pos } - field, ok := senderNames[sender[0]] + switch held { + case scopeRoot: + canonical, builtin := topNames[idents[0]] + if builtin { + w.refs[canonical] = true + } + if builtin && canonical == SenderField { + if len(idents) > 1 { + w.sender(start, text, head+"."+SenderField, idents[1:]) + } + return + } + // Every other field of the data is text, which has no fields. + if len(idents) > 1 { + w.fail(start, "field %s has no field %q", idents[0], idents[1]) + } + case scopeSender: + w.sender(start, text, head, idents) + default: + what := "this value" + if head != "" { + what = head + } + w.fail(start, "fields of %s cannot be checked; refer to the field directly, like {{.Sender.Email}}", what) + } +} + +// sender checks the selectors after a Sender value and canonicalises the field +// name; prefix is the canonical way to reach that value. +func (w *walker) sender(start int, text, prefix string, fields []string) { + field, ok := senderNames[fields[0]] if !ok { - w.fail(start, "unknown sender field %q; the sender fields are %s", sender[0], senderList) + w.fail(start, "unknown sender field %q; the sender fields are %s", fields[0], senderList) return } - if len(sender) > 1 { - w.fail(start, "sender field %s has no field %q", field, sender[1]) + if len(fields) > 1 { + w.fail(start, "sender field %s has no field %q", field, fields[1]) return } - if rewritten := prefix + "." + field; rewritten != text { + if rewritten := prefix + "." + field; rewritten != text && strings.HasPrefix(w.src[start:], text) { w.edits = append(w.edits, edit{start, start + len(text), rewritten}) } } @@ -305,42 +496,35 @@ func (w *walker) locate(pos int, text string) int { return -1 } -func (w *walker) apply() string { - if len(w.edits) == 0 { - return w.src - } - sort.Slice(w.edits, func(i, j int) bool { return w.edits[i].start < w.edits[j].start }) - var b strings.Builder - last := 0 - for _, e := range w.edits { - if e.start < last { - continue - } - b.WriteString(w.src[last:e.start]) - b.WriteString(e.text) - last = e.end - } - b.WriteString(w.src[last:]) - return b.String() -} - func unknownVariable(name string) string { return fmt.Sprintf("unknown variable %q: write a contact field with a leading dot, like {{.%s}}; the built-in fields are %s", name, name, canonicalList) } -// rewriteSpacedInAction rewrites `.job title` and `.first-name` inside one -// action to `(index . "key")`, skipping string literals. -func rewriteSpacedInAction(action string) string { +// rewriteSpaced rewrites `.job title` and `.first-name` inside each action to +// `(index . "key")`, skipping string literals, and reports where it did. +func rewriteSpaced(src string) (string, []span) { var b strings.Builder - b.Grow(len(action)) + b.Grow(len(src)) + var spans []span + last := 0 + for _, loc := range ActionPattern.FindAllStringIndex(src, -1) { + b.WriteString(src[last:loc[0]]) + rewriteSpacedInAction(&b, src, loc[0], loc[1], &spans) + last = loc[1] + } + b.WriteString(src[last:]) + return b.String(), spans +} + +func rewriteSpacedInAction(b *strings.Builder, src string, from, to int, spans *[]span) { var quote byte // 0 = not in a string literal; '"' or '`' otherwise - for i := 0; i < len(action); { - c := action[i] + for i := from; i < to; { + c := src[i] switch { case quote != 0: b.WriteByte(c) - if c == '\\' && quote == '"' && i+1 < len(action) { - b.WriteByte(action[i+1]) // keep an escaped char verbatim + if c == '\\' && quote == '"' && i+1 < to { + b.WriteByte(src[i+1]) // keep an escaped char verbatim i += 2 continue } @@ -354,9 +538,11 @@ func rewriteSpacedInAction(action string) string { i++ case c == '.': // A nested struct selector must not consume the following function argument. - fieldStart := i == 0 || strings.ContainsRune("{( \t\r\n", rune(action[i-1])) - if m := spacedFieldRefAt.FindString(action[i:]); fieldStart && m != "" { - b.WriteString(`(index . "` + m[1:] + `")`) + fieldStart := i == from || strings.ContainsRune("{( \t\r\n", rune(src[i-1])) + if m := spacedFieldRefAt.FindString(src[i:to]); fieldStart && m != "" { + repl := `(index . "` + m[1:] + `")` + *spans = append(*spans, span{i, i + len(m), b.Len(), b.Len() + len(repl)}) + b.WriteString(repl) i += len(m) continue } @@ -367,5 +553,4 @@ func rewriteSpacedInAction(action string) string { i++ } } - return b.String() } diff --git a/internal/pkg/tmplvars/normalize_test.go b/internal/pkg/tmplvars/normalize_test.go index 33ff69c9c..9b629a4d5 100644 --- a/internal/pkg/tmplvars/normalize_test.go +++ b/internal/pkg/tmplvars/normalize_test.go @@ -8,27 +8,29 @@ import ( func TestNormalize(t *testing.T) { cases := []struct{ name, in, want string }{ {"canonical untouched", "Hi {{.FirstName}}", "Hi {{.FirstName}}"}, - {"bare snake", "Hi {{first_name}}", "Hi {{$.first_name}}"}, - {"bare camel", "Hi {{ firstName }}", "Hi {{ $.firstName }}"}, - {"bare lowercase", "{{company}} / {{company_name}}", "{{$.company}} / {{$.company_name}}"}, + {"bare snake", "Hi {{first_name}}", "Hi {{.first_name}}"}, + {"bare camel", "Hi {{ firstName }}", "Hi {{ .firstName }}"}, + {"bare lowercase", "{{company}} / {{company_name}}", "{{.company}} / {{.company_name}}"}, {"dotted alias is a field already", "{{.first_name}}", "{{.first_name}}"}, - {"bare in if", "{{if first_name}}x{{end}}", "{{if $.first_name}}x{{end}}"}, - {"bare in pipe", `{{first_name | default "there"}}`, `{{$.first_name | default "there"}}`}, - {"bare as argument", `{{default "there" first_name}}`, `{{default "there" $.first_name}}`}, - {"bare in eq", `{{if eq company "Acme"}}y{{end}}`, `{{if eq $.company "Acme"}}y{{end}}`}, + {"bare in if", "{{if first_name}}x{{end}}", "{{if .first_name}}x{{end}}"}, + {"bare in pipe", `{{first_name | default "there"}}`, `{{.first_name | default "there"}}`}, + {"bare as argument", `{{default "there" first_name}}`, `{{default "there" .first_name}}`}, + {"bare in eq", `{{if eq company "Acme"}}y{{end}}`, `{{if eq .company "Acme"}}y{{end}}`}, {"literal braces outside actions", "Use first_name or {first_name} in text", "Use first_name or {first_name} in text"}, {"string literal untouched", `{{default "first_name" .X}}`, `{{default "first_name" .X}}`}, {"spaced custom field", "{{.job title}}", `{{(index . "job title")}}`}, {"sender alias", "{{.Sender.first_name}}", "{{.Sender.FirstName}}"}, - {"sender bare", "{{sender.first_name}}", "{{$.Sender.FirstName}}"}, + {"sender bare", "{{sender.first_name}}", "{{.Sender.FirstName}}"}, {"sender variable", "{{$.sender.signature_html}}", "{{$.Sender.SignatureHTML}}"}, {"function untouched", "{{upper .FirstName}}", "{{upper .FirstName}}"}, - {"unsubscribe alias", "{{unsubscribe_link}}", "{{$.unsubscribe_link}}"}, + {"unsubscribe alias", "{{unsubscribe_link}}", "{{.unsubscribe_link}}"}, {"sender through a variable", "{{$s := .Sender}}{{$s.first_name}}", "{{$s := .Sender}}{{$s.FirstName}}"}, {"sender through with", "{{with .sender}}{{.signature_html}}{{end}}", "{{with .sender}}{{.SignatureHTML}}{{end}}"}, {"sender through root variable", "{{$r := .}}{{$r.Sender.email}}", "{{$r := .}}{{$r.Sender.Email}}"}, {"range element untouched", "{{range .Sender.Tags}}{{.}}{{end}}", "{{range .Sender.Tags}}{{.}}{{end}}"}, {"range variables untouched", "{{range $k, $v := .}}{{$k}}={{$v}}{{end}}", "{{range $k, $v := .}}{{$k}}={{$v}}{{end}}"}, + {"bare inside with uses the root", "{{with .Sender}}{{first_name}}{{end}}", "{{with .Sender}}{{$.first_name}}{{end}}"}, + {"sender through parentheses", "{{with (.Sender)}}{{.first_name}}{{end}}", "{{with (.Sender)}}{{.FirstName}}{{end}}"}, } for _, tc := range cases { got, err := Normalize(tc.in) @@ -52,6 +54,9 @@ func TestCheckRefusesWhatCannotRender(t *testing.T) { {"{{$s := .Sender}}{{$s.Bogus}}", `unknown sender field "Bogus"`}, {"{{with .Sender}}{{.Bogus}}{{end}}", `unknown sender field "Bogus"`}, {"{{range $k, $v := .}}{{$v.x}}{{end}}", "fields of $v cannot be checked"}, + {"{{.FirstName.Bogus}}", `field FirstName has no field "Bogus"`}, + {"{{first_name.Bogus}}", `field first_name has no field "Bogus"`}, + {`{{with .Sender | default .Sender}}{{.first_name}}{{end}}`, "fields of this value cannot be checked"}, } for _, tc := range cases { err := Check(tc.in) @@ -100,3 +105,75 @@ func TestAddAliasesLetsCustomFieldWin(t *testing.T) { t.Fatalf("got %v", data) } } + +func TestCheckScopesBranchVariables(t *testing.T) { + for _, ok := range []string{ + "{{$s := .Sender}}{{if .Company}}{{$s = .Company}}{{else}}{{$s.Email}}{{end}}", + "{{$s := .Sender}}{{if .X}}{{$s := .Other}}{{else}}{{$s.first_name}}{{end}}{{$s.Email}}", + "{{$s := .Sender}}{{with .Company}}{{$s := .}}{{else}}{{$s.Email}}{{end}}{{$s.Name}}", + "{{$s := .Sender}}{{range .Sender.Tags}}{{$s := .}}{{$s}}{{end}}{{$s.Name}}", + } { + if err := Check(ok); err != nil { + t.Errorf("%q: unexpected error %v", ok, err) + } + } + // A reassignment in a branch leaves the variable unknown after the structure. + if err := Check("{{$s := .Sender}}{{if .Company}}{{$s = .Company}}{{end}}{{$s.Email}}"); err == nil { + t.Error("a field of a variable a branch reassigned should be refused") + } +} + +func TestCanonicalizeStoresBareAliasesInCanonicalForm(t *testing.T) { + cases := []struct{ in, want string }{ + {"Hi {{first_name}}", "Hi {{.FirstName}}"}, + {"{{ company_name }} and {{companyName}}", "{{ .Company }} and {{.Company}}"}, + {`{{if first_name}}{{first_name | default "there"}}{{end}}`, `{{if .FirstName}}{{.FirstName | default "there"}}{{end}}`}, + {"{{with .Sender}}{{first_name}} / {{.first_name}}{{end}}", "{{with .Sender}}{{$.FirstName}} / {{.FirstName}}{{end}}"}, + {"{{.first_name}} {{.firstName}}", "{{.first_name}} {{.firstName}}"}, + {"{{sender.email}}", "{{.Sender.Email}}"}, + {"{{.job title}} {{first_name}} {{.dept-name}} {{last_name}}", "{{.job title}} {{.FirstName}} {{.dept-name}} {{.LastName}}"}, + {"first_name {first_name} {{form_link:abc123}} {{first_name}}", "first_name {first_name} {{form_link:abc123}} {{.FirstName}}"}, + {"{{if .X}}broken {{first_name}}", "{{if .X}}broken {{first_name}}"}, + {"no actions", "no actions"}, + } + for _, tc := range cases { + if got := Canonicalize(tc.in); got != tc.want { + t.Errorf("%q: got %q, want %q", tc.in, got, tc.want) + } + } +} + +func TestCheckHTMLRefusesEscaperBeforePipe(t *testing.T) { + if err := CheckHTML(`

    {{html .FirstName | printf "%s"}}

    `); err == nil { + t.Error("an html escaper before a pipe should be refused in an HTML body") + } + for _, ok := range []string{"", "

    Hi {{.FirstName}}

    ", `x`, "

    {{.missing}}

    ", `

    {{.FirstName | html}}

    `} { + if err := CheckHTML(ok); err != nil { + t.Errorf("%q: unexpected error %v", ok, err) + } + } + if err := CheckCopy(Part{Name: "body", Text: `{{urlquery .X | printf "%s"}}`, HTML: true}); err == nil || !strings.Contains(err.Error(), "the body") { + t.Errorf("CheckCopy should run the HTML check on an HTML part: %v", err) + } +} + +func TestReferences(t *testing.T) { + cases := []struct { + in string + want bool + }{ + {"Hi {{.FirstName}}", true}, + {"Hi {{first_name}}", true}, + {`{{.firstName | default "there"}}`, true}, + {`{{$.first_name}}`, true}, + {`{{printf "firstname"}}`, false}, + {"{{.firstname_source}}", false}, + {"{{.Sender.FirstName}}", false}, + {"firstname in prose", false}, + } + for _, tc := range cases { + if got := References(tc.in)["FirstName"]; got != tc.want { + t.Errorf("%q: got %v, want %v", tc.in, got, tc.want) + } + } +} From b89e90a6412b60f69ce72b6c47b2adc2bef5dcb9 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 11:50:13 +0100 Subject: [PATCH 133/318] feat: refuse every html/template escape error in HTML copy, keep spaced custom-field keys from swallowing built-in operands, check selectors on parenthesised Sender values, render bare aliases as the built-in field in preview and send alike, and check a re-activated A/B variant's stored copy --- docs/content/docs/api/reference/campaigns.mdx | 2 +- docs/content/docs/guides/expressions.mdx | 2 +- internal/app/advanced/service.go | 41 ++++--- internal/app/advanced/variant_copy_test.go | 11 ++ internal/pkg/tmplvars/normalize.go | 108 +++++++++++++----- internal/pkg/tmplvars/normalize_test.go | 44 +++++-- internal/tasks/template_test.go | 8 +- 7 files changed, 159 insertions(+), 57 deletions(-) diff --git a/docs/content/docs/api/reference/campaigns.mdx b/docs/content/docs/api/reference/campaigns.mdx index 2e0353aac..5305df179 100644 --- a/docs/content/docs/api/reference/campaigns.mdx +++ b/docs/content/docs/api/reference/campaigns.mdx @@ -530,7 +530,7 @@ Add a variant to the campaign (or to one step via `step_id`). **Scope** `WRITE_C } ``` -A `subject`, `body_html` or `body_plain` that would not render as written answers `400` with `code: "invalid_template"`, as for [a step](#update-a-sequence). The same check applies to an update. +A `subject`, `body_html` or `body_plain` that would not render as written answers `400` with `code: "invalid_template"`, as for [a step](#update-a-sequence). The same check applies to an update, against the copy the variant will hold once the update lands, so re-activating a paused variant checks its stored copy. A step's control arm (`is_control` with a `step_id`) sends the step's copy, so its own is not checked. ### Response diff --git a/docs/content/docs/guides/expressions.mdx b/docs/content/docs/guides/expressions.mdx index e4cf450e1..b92c379a5 100644 --- a/docs/content/docs/guides/expressions.mdx +++ b/docs/content/docs/guides/expressions.mdx @@ -74,7 +74,7 @@ Hi {{.FirstName}}, I noticed {{.Company}} is hiring and wanted to reach out. ``` -Campaign copy also accepts the snake_case, camelCase and lowercase spellings of every built-in field, with or without the dot: `{{first_name}}`, `{{.firstName}}`, `{{firstname}}`, `{{last_name}}`, `{{email}}`, `{{company}}`, `{{company_name}}`, `{{phone}}`, `{{unsubscribe_link}}`, and `{{.Sender.first_name}}` for sender fields. They work inside conditions and helpers as well (`{{if first_name}}`, `{{first_name | default "there"}}`). A spelling without the dot is saved in canonical form, so `{{first_name}}` is stored as `{{.FirstName}}` and always reads the built-in field, and sender fields are saved under their canonical names. A dotted spelling such as `{{.first_name}}` is kept as written, and a contact's own custom field with that name keeps its value. `{{.FIRSTNAME}}` is not one of them. +Campaign copy also accepts the snake_case, camelCase and lowercase spellings of every built-in field, with or without the dot: `{{first_name}}`, `{{.firstName}}`, `{{firstname}}`, `{{last_name}}`, `{{email}}`, `{{company}}`, `{{company_name}}`, `{{phone}}`, `{{unsubscribe_link}}`, and `{{.Sender.first_name}}` for sender fields. They work inside conditions and helpers as well (`{{if first_name}}`, `{{first_name | default "there"}}`). A spelling without the dot always reads the built-in field, in the preview and in the sent email, and is saved in canonical form (`{{first_name}}` is stored as `{{.FirstName}}`); sender fields are saved under their canonical names. A dotted spelling such as `{{.first_name}}` is kept as written, and a contact's own custom field with that name keeps its value. `{{.FIRSTNAME}}` is not one of them. **Custom fields** work the same way with a dot: `{{.industry}}`, `{{.account_owner}}`. Names containing spaces or dashes also work as written (`{{if .job title}}...{{end}}`) and resolve everywhere, including inside conditions and helpers, because Warmbly rewrites them to an `index` lookup for you. diff --git a/internal/app/advanced/service.go b/internal/app/advanced/service.go index feca027b0..43999e562 100644 --- a/internal/app/advanced/service.go +++ b/internal/app/advanced/service.go @@ -380,13 +380,13 @@ func (s *service) CreateABVariant(ctx context.Context, campaignID uuid.UUID, req } func (s *service) UpdateABVariant(ctx context.Context, campaignID, variantID uuid.UUID, req *models.UpdateCampaignABVariantRequest) (*models.CampaignABVariant, *errx.Error) { - if req != nil && (req.Subject != nil || req.BodyHTML != nil || req.BodyPlain != nil || req.IsControl != nil) { - sendsOwn, xerr := s.variantSendsOwnCopy(ctx, campaignID, variantID, req.IsControl) + if req != nil && (req.Subject != nil || req.BodyHTML != nil || req.BodyPlain != nil || req.IsControl != nil || req.IsActive != nil) { + merged, xerr := s.mergedVariant(ctx, campaignID, variantID, req) if xerr != nil { return nil, xerr } - if sendsOwn { - if err := checkVariantCopy(deref(req.Subject), deref(req.BodyHTML), deref(req.BodyPlain)); err != nil { + if models.VariantSendsOwnCopy(merged.SequenceID, merged.IsControl) { + if err := checkVariantCopy(merged.Subject, merged.BodyHTML, merged.BodyPlain); err != nil { return nil, errx.InvalidTemplate(err) } } @@ -407,23 +407,32 @@ func checkVariantCopy(subject, bodyHTML, bodyPlain string) error { ) } -// variantSendsOwnCopy reads whether the variant, with isControl applied, sends its own copy. -// A variant that is not found is checked, and the update reports the miss. -func (s *service) variantSendsOwnCopy(ctx context.Context, campaignID, variantID uuid.UUID, isControl *bool) (bool, *errx.Error) { +// mergedVariant is the stored variant with req applied, the copy it would send +// once the update lands; a variant not found is empty, and the update reports the miss. +func (s *service) mergedVariant(ctx context.Context, campaignID, variantID uuid.UUID, req *models.UpdateCampaignABVariantRequest) (models.CampaignABVariant, *errx.Error) { variants, err := s.repo.ListABVariants(ctx, campaignID) if err != nil { - return false, toErrx(err) + return models.CampaignABVariant{}, toErrx(err) } - for _, v := range variants { - if v.ID == variantID { - control := v.IsControl - if isControl != nil { - control = *isControl - } - return models.VariantSendsOwnCopy(v.SequenceID, control), nil + var v models.CampaignABVariant + for _, row := range variants { + if row.ID == variantID { + v = row + break } } - return true, nil + for _, f := range []struct { + dst *string + src *string + }{{&v.Subject, req.Subject}, {&v.BodyHTML, req.BodyHTML}, {&v.BodyPlain, req.BodyPlain}} { + if f.src != nil { + *f.dst = *f.src + } + } + if req.IsControl != nil { + v.IsControl = *req.IsControl + } + return v, nil } func deref(s *string) string { diff --git a/internal/app/advanced/variant_copy_test.go b/internal/app/advanced/variant_copy_test.go index f3a134bc6..0888be966 100644 --- a/internal/app/advanced/variant_copy_test.go +++ b/internal/app/advanced/variant_copy_test.go @@ -62,6 +62,17 @@ func TestVariantCopyIsCheckedUnlessItIsAStepControlArm(t *testing.T) { if _, xerr := svc.UpdateABVariant(ctx, campaign, id, &models.UpdateCampaignABVariantRequest{BodyPlain: &broken, IsControl: &off}); xerr == nil { t.Fatal("turning the control off makes it send its copy, so the copy is checked") } + // Re-activating a paused variant checks the copy it stores, which it would start sending. + paused := uuid.New() + repo.rows = append(repo.rows, models.CampaignABVariant{ID: paused, BodyHTML: "

    " + broken + "

    "}) + on := true + if _, xerr := svc.UpdateABVariant(ctx, campaign, paused, &models.UpdateCampaignABVariantRequest{IsActive: &on}); xerr == nil || xerr.Identifier != "invalid_template" { + t.Fatalf("re-activating a variant with broken stored copy: got %v", xerr) + } + weight := 70 + if _, xerr := svc.UpdateABVariant(ctx, campaign, paused, &models.UpdateCampaignABVariantRequest{Weight: &weight}); xerr != nil { + t.Fatalf("a weight change does not touch copy: %v", xerr) + } plain := "{{company_name}}" if _, xerr := svc.UpdateABVariant(ctx, campaign, id, &models.UpdateCampaignABVariantRequest{BodyPlain: &plain, IsControl: &off}); xerr != nil || *repo.updated.BodyPlain != "{{.Company}}" { t.Fatalf("a bare alias should be stored canonical on update: %v", xerr) diff --git a/internal/pkg/tmplvars/normalize.go b/internal/pkg/tmplvars/normalize.go index 5dee99ec3..e6ce9728b 100644 --- a/internal/pkg/tmplvars/normalize.go +++ b/internal/pkg/tmplvars/normalize.go @@ -26,6 +26,73 @@ var FormLinkMarker = regexp.MustCompile(`\{\{\s*form_link:([a-z0-9]{1,64})\s*\}\ // a valid selector and is rewritten to `(index . "key")`. var spacedFieldRefAt = regexp.MustCompile(`^\.[A-Za-z0-9_]+(?:[ \-]+[A-Za-z0-9_]+)+`) +// keySegment splits a spaced reference into its separators and words. +var keySegment = regexp.MustCompile(`([ \-]+)([A-Za-z0-9_]+)`) + +// keywords are the words text/template reads inside an action. +var keywords = map[string]bool{ + "if": true, "else": true, "end": true, "range": true, "with": true, "template": true, "block": true, + "define": true, "break": true, "continue": true, "nil": true, "true": true, "false": true, +} + +// reserved is a word that is an operand on its own: a built-in alias, a function or a keyword. +func reserved(word string) bool { + _, builtin := topNames[word] + return builtin || isFunc(word) || keywords[word] +} + +// spacedKeyAt is the spaced or dashed custom-field reference starting at i, or +// "". As an argument, a space before a reserved word ends the key, so +// {{and .Company first_name}} keeps two operands; at the head of a command a +// field can take no arguments, so the whole run is the key. +func spacedKeyAt(src string, from, i, to int) string { + m := spacedFieldRefAt.FindString(src[i:to]) + if m == "" || commandHead(src, from, i) { + return m + } + first := strings.IndexAny(m, " -") + end := first + for _, seg := range keySegment.FindAllStringSubmatchIndex(m[first:], -1) { + sep, word := m[first+seg[2]:first+seg[3]], m[first+seg[4]:first+seg[5]] + if strings.Contains(sep, " ") && reserved(word) { + break + } + end = first + seg[1] + } + if end == first { + return "" + } + return m[:end] +} + +// commandHead reports whether the operand at i starts a command: it follows +// the action's opening, a parenthesis, a pipe, a declaration or a keyword. +func commandHead(src string, from, i int) bool { + j := i + for j > from && strings.ContainsRune(" \t\r\n", rune(src[j-1])) { + j-- + } + if j <= from+2 { + return true // straight after {{ + } + switch src[j-1] { + case '(', '|', '=': + return true + case '-': + return j-1 == from+2 // {{- trim marker + } + k := j + for k > from && (isWordByte(src[k-1])) { + k-- + } + word := src[k:j] + return word == "if" || word == "with" || word == "range" || word == "else" +} + +func isWordByte(c byte) bool { + return c == '_' || c >= '0' && c <= '9' || c|0x20 >= 'a' && c|0x20 <= 'z' +} + var htmlComment = regexp.MustCompile(`(?s)`) // builtinFuncs are text/template's own functions, which a bare name may call. @@ -40,24 +107,14 @@ func isFunc(name string) bool { return ok || builtinFuncs[name] } -// mode is what the walker's rewrites are for. -type mode int - -const ( - // forRender keeps a bare alias's spelling, so a custom field of that name wins. - forRender mode = iota - // forStore writes a bare alias as its canonical field, which every release renders. - forStore -) - // Normalize rewrites the accepted spellings of campaign copy into the form the // engine compiles: spaced and dashed custom-field keys become index calls, a -// bare built-in name ({{first_name}}) becomes a field of the root, and Sender +// bare built-in alias ({{first_name}}) becomes its canonical field, and Sender // fields take their canonical names. Text outside actions and string literals // are never touched. The error names a reference that can never resolve; the // returned source is usable either way, so a renderer may ignore it. func Normalize(src string) (string, error) { - w, rewritten, _ := analyze(src, forRender) + w, rewritten, _ := analyze(src) if w == nil { return rewritten, nil // the compiler reports a syntax error itself } @@ -69,7 +126,7 @@ func Normalize(src string) (string, error) { // their canonical names, so the previous release renders it too. Dotted aliases // and everything outside actions are kept as written. func Canonicalize(src string) string { - w, _, spans := analyze(src, forStore) + w, _, spans := analyze(src) if w == nil || w.err != nil || len(w.edits) == 0 { return src } @@ -95,7 +152,7 @@ func CanonicalizeAll(fields ...*string) { // References lists the canonical built-in fields src reads from the contact. func References(src string) map[string]bool { - w, _, _ := analyze(src, forRender) + w, _, _ := analyze(src) if w == nil { return nil } @@ -104,7 +161,7 @@ func References(src string) map[string]bool { // analyze parses src with spaced references rewritten and form-link markers // blanked, and walks it. A nil walker means src does not parse. -func analyze(src string, m mode) (*walker, string, []span) { +func analyze(src string) (*walker, string, []span) { if !strings.Contains(src, "{{") { return nil, src, nil } @@ -115,7 +172,7 @@ func analyze(src string, m mode) (*walker, string, []span) { if _, err := tree.Parse(maskMarkers(rewritten), "", "", trees); err != nil { return nil, rewritten, spans } - w := &walker{src: rewritten, mode: m, vars: map[string]scope{"$": scopeRoot}, refs: map[string]bool{}} + w := &walker{src: rewritten, vars: map[string]scope{"$": scopeRoot}, refs: map[string]bool{}} names := make([]string, 0, len(trees)) for name := range trees { names = append(names, name) @@ -159,8 +216,8 @@ func Check(src string) error { return nil } -// CheckHTML reports an HTML body the HTML renderer refuses although it parses: -// a predefined escaper (html, urlquery) placed before a pipe. +// CheckHTML reports an HTML body the HTML renderer refuses although it parses, +// such as branches ending in different contexts or an escaper before a pipe. func CheckHTML(src string) error { if !strings.Contains(src, "{{") { return nil @@ -168,7 +225,7 @@ func CheckHTML(src string) error { // Comments are shielded as the renderer shields them: a comment holding an action renders as text. src = htmlComment.ReplaceAllStringFunc(src, func(c string) string { if strings.Contains(c, "{{") { - return " " + c[4:len(c)-3] + " " + return " " + strings.ReplaceAll(c[4:len(c)-3], "{{html .FirstName | printf "%s"}}

    `); err == nil { - t.Error("an html escaper before a pipe should be refused in an HTML body") + for _, bad := range []string{ + `

    {{html .FirstName | printf "%s"}}

    `, + `{{if .Company}}`, + } { + if err := CheckHTML(bad); err == nil { + t.Errorf("%q: the HTML renderer refuses it, so the check should too", bad) + } + } + for _, ok := range []string{ + `

    {{if .Company}}At {{.Company}}{{else}}Hi{{end}}

    `, + `
    {{.Sender.Name}}`, + `

    Hi {{.FirstName | default "there"}},

    {{.Sender.SignatureHTML}}`, + } { + if err := CheckHTML(ok); err != nil { + t.Errorf("%q: unexpected error %v", ok, err) + } } for _, ok := range []string{"", "

    Hi {{.FirstName}}

    ", `x`, "

    {{.missing}}

    ", `

    {{.FirstName | html}}

    `} { if err := CheckHTML(ok); err != nil { diff --git a/internal/tasks/template_test.go b/internal/tasks/template_test.go index 5ab5adb8b..ccf32510e 100644 --- a/internal/tasks/template_test.go +++ b/internal/tasks/template_test.go @@ -8,6 +8,7 @@ import ( "time" "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/pkg/tmplvars" ) func TestCompiledTemplateCachesRawSource(t *testing.T) { @@ -271,9 +272,14 @@ func TestRenderTemplate_AliasSpellings(t *testing.T) { func TestRenderTemplate_CustomFieldBeatsAlias(t *testing.T) { contact := models.Contact{FirstName: "Sam", CustomFields: map[string]string{"first_name": "Samantha"}} - if got := RenderTemplate("{{first_name}} {{.first_name}} {{firstName}} {{.FirstName}}", contact); got != "Samantha Samantha Sam Sam" { + // A dotted alias defers to a custom field; a bare one is the built-in field, as it is once saved. + tmpl := "{{first_name}} {{.first_name}} {{firstName}} {{.FirstName}}" + if got := RenderTemplate(tmpl, contact); got != "Sam Samantha Sam Sam" { t.Fatalf("got %q", got) } + if preview := PreviewTemplates(tmpl, "", "", contact); preview.Subject != RenderTemplate(tmplvars.Canonicalize(tmpl), contact) { + t.Fatalf("preview %q differs from the saved copy's render", preview.Subject) + } } func TestRenderTemplate_CustomFields(t *testing.T) { From 67bb118866fecd9747963bbbb6bef858cb908fa6 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 11:52:08 +0100 Subject: [PATCH 134/318] feat: label every Go service's Postgres connections with application_name warmbly- and add a read-only warmblyctl db load report of connections by service, longest sessions, costliest pg_stat_statements queries and largest tables --- cmd/warmblyctl/db.go | 267 ++++++++++++++++++ cmd/warmblyctl/main.go | 3 + docs/content/docs/development/warmblyctl.mdx | 17 ++ internal/infrastructure/db/connections.go | 12 + .../infrastructure/db/connections_test.go | 13 + skills/warmbly-ops/SKILL.md | 1 + 6 files changed, 313 insertions(+) create mode 100644 cmd/warmblyctl/db.go diff --git a/cmd/warmblyctl/db.go b/cmd/warmblyctl/db.go new file mode 100644 index 000000000..349da08ae --- /dev/null +++ b/cmd/warmblyctl/db.go @@ -0,0 +1,267 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "strings" + "text/tabwriter" + "time" + + "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 { + 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 + } + } + + rows, err := pool.Query(ctx, `SELECT COALESCE(NULLIF(application_name, ''), '(unnamed)'), COALESCE(state, '(background)'), count(*)::int + FROM pg_stat_activity WHERE datname = current_database() AND 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; its text is normalized, so it holds no values. +func readStatements(ctx context.Context, pool *pgxpool.Pool, limit int, load *dbLoad) error { + var installed bool + if err := pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_stat_statements')`).Scan(&installed); err != nil { + return fmt.Errorf("check pg_stat_statements: %w", err) + } + if !installed { + 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 calls, total_exec_time, mean_exec_time, rows, left(regexp_replace(query, '\s+', ' ', 'g'), 200) + FROM pg_stat_statements 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.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 pg_stat_statements_info`).Scan(&since); err == nil { + load.Since = &since + } + return nil +} + +func printDBLoad(w io.Writer, load *dbLoad) { + used := 0 + for _, c := range load.Connections { + used += c.Count + } + fmt.Fprintf(w, "Connections: %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\tQUERY") + } + for _, s := range load.Statements { + fmt.Fprintf(tw, " %.0f\t%d\t%.2f\t%d\t%s\n", s.TotalMS, s.Calls, s.MeanMS, s.Rows, 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() +} diff --git a/cmd/warmblyctl/main.go b/cmd/warmblyctl/main.go index 10df8b64c..671a68300 100644 --- a/cmd/warmblyctl/main.go +++ b/cmd/warmblyctl/main.go @@ -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) { diff --git a/docs/content/docs/development/warmblyctl.mdx b/docs/content/docs/development/warmblyctl.mdx index 91afabfe2..bf69c40fb 100644 --- a/docs/content/docs/development/warmblyctl.mdx +++ b/docs/content/docs/development/warmblyctl.mdx @@ -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 --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** grouped by the service that opened them and their state, against `max_connections`. Every Go service names its connections `warmbly-` (`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`. Its text is normalized, so it holds no values. 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 diff --git a/internal/infrastructure/db/connections.go b/internal/infrastructure/db/connections.go index a869ded23..9f6e651dc 100644 --- a/internal/infrastructure/db/connections.go +++ b/internal/infrastructure/db/connections.go @@ -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 diff --git a/internal/infrastructure/db/connections_test.go b/internal/infrastructure/db/connections_test.go index ad37b3b6f..fd4a573eb 100644 --- a/internal/infrastructure/db/connections_test.go +++ b/internal/infrastructure/db/connections_test.go @@ -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) { diff --git a/skills/warmbly-ops/SKILL.md b/skills/warmbly-ops/SKILL.md index 62b2fe0cd..42ebb2ce4 100644 --- a/skills/warmbly-ops/SKILL.md +++ b/skills/warmbly-ops/SKILL.md @@ -44,6 +44,7 @@ for. Prefer parsing that over reasoning from the prose. | Back the instance up | `warmblyctl backup --out /data/blobs/warmbly.tar.gz`, then copy it out and delete it | | Restore one onto this instance | `warmblyctl restore --file /data/blobs/warmbly.tar.gz` | | See which key opens each stored secret | `warmblyctl keys status [--json]` | +| See what the database is busy with: connections by service, costliest queries, largest tables | `warmblyctl db load [--limit N] [--json]` | | Move secrets onto a new primary key | `warmblyctl keys reseal` (dry run), then `keys reseal --apply` | | Mint replacement keys and tokens | `warmblyctl keys generate [NAME...]` | From 88b6bf07027336a736b8748442f449ba6cbf53a1 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 12:14:18 +0100 Subject: [PATCH 135/318] feat: keep an unconfirmed send out of mailbox health until it outlasts automatic recovery, measured from when the worker last progressed it, and show one that does as a warning that costs no health score instead of an error capped at 50 --- docs/content/docs/guides/mailboxes.mdx | 2 +- internal/app/analytics/account_errors_test.go | 12 +++++++++--- internal/app/analytics/service.go | 8 +++++++- internal/config/constants.go | 3 +++ internal/repository/pg_send_recovery.go | 13 +++++++------ .../tasks/warmup_dispatch_recovery_live_test.go | 17 ++++++++++++++--- 6 files changed, 41 insertions(+), 14 deletions(-) diff --git a/docs/content/docs/guides/mailboxes.mdx b/docs/content/docs/guides/mailboxes.mdx index ca0166378..25a2fed79 100644 --- a/docs/content/docs/guides/mailboxes.mdx +++ b/docs/content/docs/guides/mailboxes.mdx @@ -654,7 +654,7 @@ While visible, the Accounts list and mailbox drawer refresh their health and err A later completed sync automatically clears earlier temporary sync errors. A provider-confirmed send clears earlier temporary sending errors, including provider throttling and quota warnings. Recovered reports no longer appear under **Needs attention** or reduce the health score. Older reports that do not identify which operation failed clear once both sending and sync have succeeded after the report; existing reports with that evidence are cleared on upgrade too. A newer failure remains visible, and simply waiting or completing a queued task does not count as recovery. Recoverable connection failures retry automatically while the mailbox is on; a connection warning alone is not a reason to reconnect. A temporary connection, server or throttling failure is not shown at all while the affected sync or sending has still succeeded within the last two hours, because the mailbox is working. It appears only when the failure lasts longer than that. Authentication, credential and policy errors retain their own instructions, and a switched-off mailbox must be switched back on before it can retry. -A send safety hold is different from a retryable connection failure. If Warmbly cannot confirm whether the provider accepted a message, sending pauses to avoid retrying a message that might already have been sent. The mailbox is shown as needing attention even without a separate connection warning, and its health details explain the hold. A successful inbox sync does not confirm a send. The hold clears on its own and no customer action is needed. After ten minutes Warmbly sets the uncertain email aside for good: a campaign email waits for confirmation for that one contact while the mailbox sends to everyone else, and a Unibox, placement-test or Warmbly Cloud send simply never runs again. A send that never reached the worker is handed back after 30 minutes so the step can go out fresh. A late confirmed result still updates the email automatically. Only legacy sends without durable execution authorization need provider-confirmed resolution. See [send safety](/development/send-safety/). +A send safety hold is different from a retryable connection failure. If Warmbly cannot confirm whether the provider accepted a message, sending pauses to avoid retrying a message that might already have been sent. A successful inbox sync does not confirm a send. The hold clears on its own and no customer action is needed, so it never lowers the health score and is not shown at all while automatic recovery is still working. Only a hold that lasts more than an hour after the send last progressed appears, as a warning that explains it. Holds that need you, such as a sign-in the server refused, show as an error straight away. After ten minutes Warmbly sets the uncertain email aside for good: a campaign email waits for confirmation for that one contact while the mailbox sends to everyone else, and a Unibox, placement-test or Warmbly Cloud send simply never runs again. A send that never reached the worker is handed back after 30 minutes so the step can go out fresh. A late confirmed result still updates the email automatically. Only legacy sends without durable execution authorization need provider-confirmed resolution. See [send safety](/development/send-safety/). Warmup scheduling automatically retires abandoned preparation tasks after ten minutes only when they have no generated message ID, verification token, reservation, dispatch or execution evidence. The normal scheduler can then continue with a new task. Tasks that might have sent a message remain protected; they are not retried just because they are old. diff --git a/internal/app/analytics/account_errors_test.go b/internal/app/analytics/account_errors_test.go index 9292306b2..9b57967d1 100644 --- a/internal/app/analytics/account_errors_test.go +++ b/internal/app/analytics/account_errors_test.go @@ -30,9 +30,15 @@ func TestSendSafetyHoldCannotAppearHealthyOrPromiseAutomaticSendRetries(t *testi status := s.assembleAccountStatus(context.Background(), &models.Email{ID: id, Status: "active", Provider: "smtp_imap"}, &models.AccountDailyUsage{}, errs, nil, false, nil, false, &statusReads{sendHolds: map[uuid.UUID]repository.SendRecoveryHold{id: {Reason: reason}}}) - if status.Health.Status != "error" || status.Health.Score > 50 || len(status.Health.Issues) == 0 { + if status.Health.Status == "healthy" || len(status.Health.Issues) == 0 { t.Fatalf("held mailbox cannot look healthy, even without an error row: %+v", status.Health) } + if reason == "unknown" && (status.Health.Status != "warning" || status.Health.Score != 100) { + t.Fatalf("an unconfirmed send recovers on its own and must not cost health: %+v", status.Health) + } + if reason != "unknown" && (status.Health.Status != "error" || status.Health.Score > 50) { + t.Fatalf("a hold that needs the owner is an error: %+v", status.Health) + } if !withError { continue } @@ -59,8 +65,8 @@ func TestUnknownWarmupHoldExplainsAutomaticRetirementWithoutPromisingResend(t *t status := s.assembleAccountStatus(t.Context(), &models.Email{ID: id, Status: "active", Provider: "smtp_imap"}, &models.AccountDailyUsage{}, []models.AccountError{{ErrorCode: string(errx.MailErrorCodeServerUnreachable), Operation: models.MailTransportSend}}, nil, false, nil, false, &statusReads{sendHolds: map[uuid.UUID]repository.SendRecoveryHold{id: {Reason: "unknown", Warmup: true}}}) - if status.Health.Status != "error" || status.Health.Score > 50 { - t.Fatalf("recovery has not completed: %+v", status.Health) + if status.Health.Status != "warning" || status.Health.Score != 100 { + t.Fatalf("an unconfirmed warmup send must not cost health: %+v", status.Health) } for _, message := range []string{status.Health.Issues[len(status.Health.Issues)-1], *status.Errors[0].ActionRequired} { if !strings.Contains(message, "automatically") || !strings.Contains(message, "new sends") || !strings.Contains(message, "never retried") || strings.Contains(message, "Provider confirmation is required") { diff --git a/internal/app/analytics/service.go b/internal/app/analytics/service.go index 16c29c03a..35229bf0f 100644 --- a/internal/app/analytics/service.go +++ b/internal/app/analytics/service.go @@ -415,7 +415,13 @@ func (s *analyticsService) assembleAccountStatus(ctx context.Context, email *mod placement = &r } applyWarmupPlacement(&health, placement) - if held { + if held && hold.Reason == "unknown" { + // Recovery is automatic and says nothing about the mailbox, so it never costs health. + if health.Status == "healthy" { + health.Status = "warning" + } + health.Issues = append(health.Issues, sendRecoveryHoldMessage(hold)) + } else if held { health.Status = "error" health.Score = min(health.Score, 50) health.Issues = append(health.Issues, sendRecoveryHoldMessage(hold)) diff --git a/internal/config/constants.go b/internal/config/constants.go index 492200b06..a0338aff4 100644 --- a/internal/config/constants.go +++ b/internal/config/constants.go @@ -270,6 +270,9 @@ const ( // it must stay well clear of a slow provider handshake. CampaignSendReclaimAfterMinutes = 30 + // UnknownSendHoldVisibleAfterMinutes keeps an unconfirmed send out of mailbox health until it outlasts automatic recovery. + UnknownSendHoldVisibleAfterMinutes = 2 * CampaignSendReclaimAfterMinutes + // WorkerReleaseGraceMinutes keeps a mailbox in its previous worker's scope after a move, until the reclaimer has resolved any send it left unanswered. WorkerReleaseGraceMinutes = CampaignSendReclaimAfterMinutes diff --git a/internal/repository/pg_send_recovery.go b/internal/repository/pg_send_recovery.go index fb5274c95..e870a9748 100644 --- a/internal/repository/pg_send_recovery.go +++ b/internal/repository/pg_send_recovery.go @@ -126,21 +126,22 @@ type SendRecoveryHold struct { } func (r *emailRepository) GetSendRecoveryHolds(ctx context.Context, ids []uuid.UUID) (map[uuid.UUID]SendRecoveryHold, error) { - // Normal in-flight sends also hold admission; only surface settled or stuck ones. + // Every send holds its mailbox in flight; an unknown outcome surfaces only once it outlasts automatic recovery. query := `SELECT ea.id,COALESCE(ea.send_recovery_reason,''),COALESCE(t.task_type='warmup',false), COALESCE(t.task_type='campaign' AND t.send_executor_nonce IS NOT NULL AND t.send_executor_started_at IS NOT NULL AND EXISTS(SELECT 1 FROM campaign_tasks ct WHERE ct.task_id=t.id),false) FROM email_accounts ea LEFT JOIN tasks t ON t.id=ea.send_recovery_task_id AND t.email_account_id=ea.id + LEFT JOIN warmup_tasks w ON w.task_id=t.id WHERE ea.id=ANY($1) AND ea.send_recovery_hold - AND (ea.send_recovery_reason IS DISTINCT FROM 'unknown' OR t.id IS NULL - OR t.send_result_applied_at IS NOT NULL OR t.send_result_evidence IS NOT NULL - OR COALESCE(t.send_reserved_at,t.completed_at,t.updated_at)$2))` var rows pgx.Rows var err error if r.transportSnapshot != nil { - rows, err = r.transportSnapshot.Query(ctx, query, ids) + rows, err = r.transportSnapshot.Query(ctx, query, ids, config.UnknownSendHoldVisibleAfterMinutes) } else { - rows, err = r.DB.Query(ctx, query, ids) + rows, err = r.DB.Query(ctx, query, ids, config.UnknownSendHoldVisibleAfterMinutes) } if err != nil { return nil, err diff --git a/internal/tasks/warmup_dispatch_recovery_live_test.go b/internal/tasks/warmup_dispatch_recovery_live_test.go index 24b9ba3ab..aa7bd8523 100644 --- a/internal/tasks/warmup_dispatch_recovery_live_test.go +++ b/internal/tasks/warmup_dispatch_recovery_live_test.go @@ -97,10 +97,21 @@ func TestLiveSendHoldReportingDoesNotFlagNormalInFlightSends(t *testing.T) { if err != nil || len(holds) != 0 { t.Fatalf("normal in-flight admission hold is not an error: holds=%v err=%v", holds, err) } - f.exec(t, `UPDATE tasks SET send_result_applied_at=NOW() WHERE id=$1`, f.task) + f.exec(t, `UPDATE tasks SET send_result_applied_at=NOW(),send_result_evidence='{"disposition":"ambiguous"}' WHERE id=$1`, f.task) holds, err = reader.GetSendRecoveryHolds(t.Context(), []uuid.UUID{f.sender.ID}) - if err != nil || holds[f.sender.ID].Reason != "unknown" { - t.Fatalf("settled unknown outcome must be visible immediately: holds=%v err=%v", holds, err) + if err != nil || len(holds) != 0 { + t.Fatalf("an unconfirmed send recovering on its own must not reach mailbox health: holds=%v err=%v", holds, err) + } + f.exec(t, `UPDATE tasks SET completed_at=NOW()-INTERVAL '3 hours',send_reserved_at=NOW()-INTERVAL '3 hours' WHERE id=$1`, f.task) + f.exec(t, `UPDATE warmup_tasks SET dispatch_started_at=NOW() WHERE task_id=$1`, f.task) + holds, err = reader.GetSendRecoveryHolds(t.Context(), []uuid.UUID{f.sender.ID}) + if err != nil || len(holds) != 0 { + t.Fatalf("a send the worker only just started is in flight, however long it queued: holds=%v err=%v", holds, err) + } + f.exec(t, `UPDATE warmup_tasks SET dispatch_started_at=NOW()-INTERVAL '3 hours' WHERE task_id=$1`, f.task) + holds, err = reader.GetSendRecoveryHolds(t.Context(), []uuid.UUID{f.sender.ID}) + if err != nil || holds[f.sender.ID].Reason != "unknown" || !holds[f.sender.ID].Warmup { + t.Fatalf("a hold that outlasted automatic recovery must be visible: holds=%v err=%v", holds, err) } f.exec(t, `UPDATE email_accounts SET send_recovery_hold=false,send_recovery_reason=NULL,send_recovery_task_id=NULL WHERE id=$1`, f.sender.ID) holds, err = reader.GetSendRecoveryHolds(t.Context(), []uuid.UUID{f.sender.ID}) From 66c840793b57d2227f335468a7436bca33506fc5 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 12:32:53 +0100 Subject: [PATCH 136/318] feat: document in the mailbox status API reference that send_recovery_reason reports unknown only once an unconfirmed send outlasts automatic recovery and that it sets a warning without lowering the health score --- docs/content/docs/api/reference/analytics.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/content/docs/api/reference/analytics.mdx b/docs/content/docs/api/reference/analytics.mdx index 2a6a1d955..a2d7a663c 100644 --- a/docs/content/docs/api/reference/analytics.mdx +++ b/docs/content/docs/api/reference/analytics.mdx @@ -644,7 +644,7 @@ Returns the detailed status for one email account: a combined health score (fold } ``` -`send_recovery_reason` is present only while a send safety hold pauses the mailbox's sending: `authentication` (cleared by reconnecting the mailbox), `permanent`, `conflict` or `unknown`. `warmup_status` is present only when warmup has ever been enabled, and its `next_send_at` is when the mailbox's next warmup send is queued for (absent while nothing is queued, for example while warmup is paused); `warmup_health` is present only when the mailbox is in a warmup pool. `in_campaign` reports whether the mailbox currently backs a live campaign. +`send_recovery_reason` is present only while a send safety hold pauses the mailbox's sending: `authentication` (cleared by reconnecting the mailbox), `permanent`, `conflict` or `unknown`. Every send briefly holds its mailbox while it is in flight, so `unknown` is reported only once an unconfirmed send has outlasted automatic recovery, an hour after the send last progressed. A held `unknown` sets `health.status` to `warning` without lowering `health.score`; the other reasons set it to `error`. `warmup_status` is present only when warmup has ever been enabled, and its `next_send_at` is when the mailbox's next warmup send is queued for (absent while nothing is queued, for example while warmup is paused); `warmup_health` is present only when the mailbox is in a warmup pool. `in_campaign` reports whether the mailbox currently backs a live campaign. `warmup_placement` is the mailbox's measured warmup inbox rate over the trailing 7 UTC days, the same figure [Get warmup placement](#get-warmup-placement) reports as `rate`, and is absent when nothing was delivered in that window. Once `inbox_rate` is present, `health.score` is capped at it (rounded down), so a mailbox landing any mail in spam no longer reads `100`, and a rate below `90` also sets `health.status` to at least `warning` with an issue naming the rate. From 686a916d421b8fd141ad2122fdfea9ad901d9780 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 12:42:28 +0100 Subject: [PATCH 137/318] feat: run the warmup, campaign, segment and tracking-domain reconcilers as claimed jobrun jobs, keep the worker reconciler, unibox body backfill and signing-secret migration on one backend behind a sticky Postgres session advisory lock (internal/leader), read warmup pool membership in one query with per-organization entitlement and risk lookups every 10 minutes, and take every jobrun run-now request for a process in one query --- cmd/backend/main.go | 13 +- .../content/docs/development/architecture.mdx | 10 ++ internal/app/consumer/event_tracking.go | 19 +-- internal/app/email/tracking_domain_sweep.go | 20 +-- internal/app/segment/service.go | 20 +-- internal/jobrun/jobrun.go | 110 ++++++++++-- internal/jobrun/schedule_test.go | 57 ++++++- internal/leader/leader.go | 153 +++++++++++++++++ internal/leader/leader_live_test.go | 111 +++++++++++++ internal/repository/job_runs_live_test.go | 37 ++++- internal/repository/pg_job_runs.go | 15 +- internal/repository/pg_warmup.go | 33 +++- .../repository/warmup_membership_live_test.go | 56 +++++++ internal/tasks/campaign_reconciler.go | 24 +-- internal/tasks/email_task.go | 31 +++- internal/tasks/warmup_pool_reconcile.go | 156 ++++++++++++++++++ internal/tasks/warmup_pool_reconcile_test.go | 84 +++++----- internal/tasks/warmup_pool_type_test.go | 24 ++- internal/tasks/warmup_reconciler.go | 116 ------------- 19 files changed, 816 insertions(+), 273 deletions(-) create mode 100644 internal/leader/leader.go create mode 100644 internal/leader/leader_live_test.go create mode 100644 internal/repository/warmup_membership_live_test.go create mode 100644 internal/tasks/warmup_pool_reconcile.go diff --git a/cmd/backend/main.go b/cmd/backend/main.go index f42ea4baf..7a1fcb2dd 100644 --- a/cmd/backend/main.go +++ b/cmd/backend/main.go @@ -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" @@ -2140,20 +2141,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) diff --git a/docs/content/docs/development/architecture.mdx b/docs/content/docs/development/architecture.mdx index c0397aaaa..378b14ae9 100644 --- a/docs/content/docs/development/architecture.mdx +++ b/docs/content/docs/development/architecture.mdx @@ -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 | diff --git a/internal/app/consumer/event_tracking.go b/internal/app/consumer/event_tracking.go index dee509eb5..380512c30 100644 --- a/internal/app/consumer/event_tracking.go +++ b/internal/app/consumer/event_tracking.go @@ -18,6 +18,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,13 +204,12 @@ 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) if tc.opens != nil { if n, err := tc.opens.Cleanup(pctx, days); err != nil { @@ -225,13 +225,8 @@ func (tc *TrackingConsumer) pruneEngagementLogs(ctx context.Context) { log.Info().Int64("deleted", n).Msg("click log pruned") } } - cancel() - select { - case <-ctx.Done(): - return - case <-ticker.C: - } - } + return nil + }) } // Close is a no-op: the event bus lifecycle is owned by the consumer main, diff --git a/internal/app/email/tracking_domain_sweep.go b/internal/app/email/tracking_domain_sweep.go index a0282fc02..4151b3d5c 100644 --- a/internal/app/email/tracking_domain_sweep.go +++ b/internal/app/email/tracking_domain_sweep.go @@ -8,6 +8,7 @@ import ( "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,19 +30,12 @@ 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() + s.runTrackingDomainSweep(sweepCtx, staleAfter) + return nil + }) } func (s *emailService) runTrackingDomainSweep(ctx context.Context, staleAfter time.Duration) { diff --git a/internal/app/segment/service.go b/internal/app/segment/service.go index e30fb2aa7..e0d996b56 100644 --- a/internal/app/segment/service.go +++ b/internal/app/segment/service.go @@ -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) { diff --git a/internal/jobrun/jobrun.go b/internal/jobrun/jobrun.go index 9543a58a6..6febef4b7 100644 --- a/internal/jobrun/jobrun.go +++ b/internal/jobrun/jobrun.go @@ -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,17 +144,95 @@ 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 + } + watchMu.Lock() + defer watchMu.Unlock() + for _, name := range taken { + for _, ch := range watchers[name] { + select { + case ch <- struct{}{}: + default: } } } diff --git a/internal/jobrun/schedule_test.go b/internal/jobrun/schedule_test.go index 23377d136..862e34573 100644 --- a/internal/jobrun/schedule_test.go +++ b/internal/jobrun/schedule_test.go @@ -20,9 +20,13 @@ type memStore struct { // write behind each one landed anyway. failClaims int applyFailed bool + requested map[string]bool + polls int } -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 +80,25 @@ 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() + defer m.mu.Unlock() + m.polls++ + var taken []string + for _, n := range names { + if m.requested[n] { + delete(m.requested, n) + taken = append(taken, n) + } + } + return taken, nil +} func (m *memStore) List(context.Context) ([]models.ScheduledJobRun, error) { return nil, nil } @@ -278,3 +299,33 @@ 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) + } + }) +} diff --git a/internal/leader/leader.go b/internal/leader/leader.go new file mode 100644 index 000000000..56cc52a2d --- /dev/null +++ b/internal/leader/leader.go @@ -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) +} diff --git a/internal/leader/leader_live_test.go b/internal/leader/leader_live_test.go new file mode 100644 index 000000000..ca86e931d --- /dev/null +++ b/internal/leader/leader_live_test.go @@ -0,0 +1,111 @@ +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 stopped atomic.Int32 + e.Go("probe", func(ctx context.Context) { + <-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 }) + waitFor(t, "leadership to be won back", 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") + } +} diff --git a/internal/repository/job_runs_live_test.go b/internal/repository/job_runs_live_test.go index d0dc0203d..1cda32fe9 100644 --- a/internal/repository/job_runs_live_test.go +++ b/internal/repository/job_runs_live_test.go @@ -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) + } +} diff --git a/internal/repository/pg_job_runs.go b/internal/repository/pg_job_runs.go index 228936d5f..d0bf4a860 100644 --- a/internal/repository/pg_job_runs.go +++ b/internal/repository/pg_job_runs.go @@ -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) { diff --git a/internal/repository/pg_warmup.go b/internal/repository/pg_warmup.go index ddef4e335..9e08c6ed8 100644 --- a/internal/repository/pg_warmup.go +++ b/internal/repository/pg_warmup.go @@ -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 @@ -2471,23 +2471,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 diff --git a/internal/repository/warmup_membership_live_test.go b/internal/repository/warmup_membership_live_test.go new file mode 100644 index 000000000..bc1af5351 --- /dev/null +++ b/internal/repository/warmup_membership_live_test.go @@ -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/?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) + } +} diff --git a/internal/tasks/campaign_reconciler.go b/internal/tasks/campaign_reconciler.go index 5872d1d7c..6573827d7 100644 --- a/internal/tasks/campaign_reconciler.go +++ b/internal/tasks/campaign_reconciler.go @@ -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) { diff --git a/internal/tasks/email_task.go b/internal/tasks/email_task.go index 49ba1f034..c5e36ba0e 100644 --- a/internal/tasks/email_task.go +++ b/internal/tasks/email_task.go @@ -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 diff --git a/internal/tasks/warmup_pool_reconcile.go b/internal/tasks/warmup_pool_reconcile.go new file mode 100644 index 000000000..887e107c4 --- /dev/null +++ b/internal/tasks/warmup_pool_reconcile.go @@ -0,0 +1,156 @@ +package tasks + +import ( + "context" + "slices" + "time" + + "github.com/google/uuid" + "github.com/rs/zerolog/log" + + "github.com/warmbly/warmbly/internal/jobrun" +) + +// 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] + } + + 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 { + 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 { + 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 { + 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") + } + } + + 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 +} diff --git a/internal/tasks/warmup_pool_reconcile_test.go b/internal/tasks/warmup_pool_reconcile_test.go index 4da218abf..660bd197b 100644 --- a/internal/tasks/warmup_pool_reconcile_test.go +++ b/internal/tasks/warmup_pool_reconcile_test.go @@ -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{}, } diff --git a/internal/tasks/warmup_pool_type_test.go b/internal/tasks/warmup_pool_type_test.go index 6a843ceeb..0cda0e406 100644 --- a/internal/tasks/warmup_pool_type_test.go +++ b/internal/tasks/warmup_pool_type_test.go @@ -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) + } } diff --git a/internal/tasks/warmup_reconciler.go b/internal/tasks/warmup_reconciler.go index 0c1537795..8643d87b4 100644 --- a/internal/tasks/warmup_reconciler.go +++ b/internal/tasks/warmup_reconciler.go @@ -4,7 +4,6 @@ import ( "context" "time" - "github.com/google/uuid" "github.com/rs/zerolog/log" "github.com/warmbly/warmbly/internal/repository" "github.com/warmbly/warmbly/internal/tasks/proto" @@ -134,118 +133,3 @@ func (s *tasksService) ReconcileWarmupSchedules(ctx context.Context, limit int) } return seeded, nil } - -// StartWarmupReconciler runs ReconcileWarmupSchedules on an interval until the -// context is cancelled. Mirrors the other background sweeps (warmup health, -// dead-worker) and is started from the backend, which owns Cloud Tasks. -func (s *tasksService) StartWarmupReconciler(ctx context.Context, interval time.Duration) { - if interval <= 0 { - interval = time.Minute - } - 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.reconcileOnce(ctx) - - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - s.reconcileOnce(ctx) - } - } -} - -func (s *tasksService) reconcileOnce(ctx context.Context) { - rctx, cancel := context.WithTimeout(ctx, 2*time.Minute) - defer cancel() - - seeded, err := s.ReconcileWarmupSchedules(rctx, warmupReconcileBatch) - if err != nil { - log.Warn().Err(err).Msg("warmup reconcile pass failed") - } else if seeded > 0 { - log.Info().Int("seeded", seeded).Msg("warmup reconcile seeded chains") - } - - moved, removed, err := s.ReconcileWarmupPoolMembership(rctx) - if err != nil { - log.Warn().Err(err).Msg("warmup pool membership reconcile pass failed") - return - } - if moved > 0 || removed > 0 { - log.Info().Int("moved", moved).Int("removed", removed).Msg("warmup pool membership reconciled") - } -} - -// 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. -func (s *tasksService) ReconcileWarmupPoolMembership(ctx context.Context) (moved int, removed int, err error) { - if s.warmupRepo == nil || s.warmupHealth == nil { - return 0, 0, nil - } - - ids, err := s.warmupRepo.GetAllParticipantAccountIDs(ctx) - if err != nil { - return 0, 0, err - } - - // One subscription lookup per organization, not per mailbox. - entitled := map[uuid.UUID]bool{} - - for _, id := range ids { - account, xerr := s.emailRepo.GetByID(ctx, id) - if xerr != nil { - continue - } - if account == nil || account.Status != "active" || account.OrganizationID == nil { - // Nothing left to check an entitlement against, so it does not belong in a shared pool. - if xerr := s.warmupHealth.RemoveFromAllPools(ctx, id); xerr == nil { - removed++ - } - continue - } - - if s.featureGate != nil { - ok, cached := entitled[*account.OrganizationID] - if !cached { - canWarmup, xerr := s.featureGate.CanUseWarmup(ctx, *account.OrganizationID) - if xerr != nil { - // Entitlement unknown: leave this mailbox exactly as it is. - continue - } - ok = canWarmup - entitled[*account.OrganizationID] = ok - } - if !ok { - if xerr := s.warmupHealth.RemoveFromAllPools(ctx, account.ID); xerr == nil { - removed++ - log.Info(). - Str("email_account_id", account.ID.String()). - Msg("warmup reconcile: mailbox left warmup, organization is no longer entitled") - } - continue - } - } - - poolType := s.resolveWarmupPoolType(ctx, account) - didMove, xerr := s.warmupHealth.MovePoolMembership(ctx, account.ID, poolType) - if xerr != nil { - continue - } - if didMove { - moved++ - log.Info(). - Str("email_account_id", account.ID.String()). - Str("pool_type", poolType). - Msg("warmup reconcile: mailbox moved to the pool its tier belongs to") - } - } - - return moved, removed, nil -} From a16774e0486e5f116f4e71222218258180859d11 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 12:47:56 +0100 Subject: [PATCH 138/318] feat: have each local task dispatcher claim due tasks with a two-minute lease in tasks.dispatch_claimed_until so backend replicas stop running the same task, claim send result effects 25 per statement, drain webhook and HubSpot and Pipedrive outboxes back to back while busy and slow their idle polls, and serve the CRM lapsed-lease claim from a partial index --- .github/workflows/ci.yml | 7 + cmd/backend/main.go | 4 + .../docs/development/configuration.mdx | 2 +- .../docs/development/instance-health.mdx | 4 + internal/app/hubspot/drain.go | 13 +- internal/app/orgtransfer/spec.go | 2 +- internal/app/pipedrive/drain.go | 13 +- internal/app/webhook/service.go | 48 ++++- .../000395_task_dispatch_claim.down.sql | 1 + .../000395_task_dispatch_claim.up.sql | 2 + ...crm_sync_jobs_running_lease_index.down.sql | 1 + ...6_crm_sync_jobs_running_lease_index.up.sql | 2 + internal/pkg/idlepoll/idlepoll.go | 26 +++ internal/pkg/idlepoll/idlepoll_test.go | 29 +++ internal/repository/pg_crm_provider.go | 31 ++- internal/repository/pg_task.go | 53 +++-- .../repository/pg_task_claim_live_test.go | 115 +++++++++++ internal/repository/queue_claim_live_test.go | 183 ++++++++++++++++++ internal/repository/send_result_effects.go | 94 +++++++-- .../warmup_send_failure_live_test.go | 17 +- internal/tasksched/local.go | 43 ++-- internal/tasksched/local_test.go | 57 +++++- 22 files changed, 670 insertions(+), 77 deletions(-) create mode 100644 internal/infrastructure/db/migrations/000395_task_dispatch_claim.down.sql create mode 100644 internal/infrastructure/db/migrations/000395_task_dispatch_claim.up.sql create mode 100644 internal/infrastructure/db/migrations/000396_crm_sync_jobs_running_lease_index.down.sql create mode 100644 internal/infrastructure/db/migrations/000396_crm_sync_jobs_running_lease_index.up.sql create mode 100644 internal/pkg/idlepoll/idlepoll.go create mode 100644 internal/pkg/idlepoll/idlepoll_test.go create mode 100644 internal/repository/pg_task_claim_live_test.go create mode 100644 internal/repository/queue_claim_live_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index db26fc059..e1df1c989 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -290,6 +290,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: diff --git a/cmd/backend/main.go b/cmd/backend/main.go index 7a1fcb2dd..f4ca9e736 100644 --- a/cmd/backend/main.go +++ b/cmd/backend/main.go @@ -867,6 +867,10 @@ func main() { Cache: cache, AppDomains: oauthService.AllowedWebhookDomains, }) + // An enqueue here wakes the worker, so an idle queue's slower poll never delays a delivery. + if w, ok := webhookService.(interface{ WireDeliveryWake(func()) }); ok { + w.WireDeliveryWake(webhookWorker.Wake) + } go webhookWorker.Run(ctx) campaignProgressRepository := repository.NewCampaignProgressRepository(primaryDB.Pool) warmupService = warmupapp.NewService(warmupRepository) diff --git a/docs/content/docs/development/configuration.mdx b/docs/content/docs/development/configuration.mdx index 36d22d3b4..0cecd9a87 100644 --- a/docs/content/docs/development/configuration.mdx +++ b/docs/content/docs/development/configuration.mdx @@ -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`) | diff --git a/docs/content/docs/development/instance-health.mdx b/docs/content/docs/development/instance-health.mdx index 39f15c338..a43d22d74 100644 --- a/docs/content/docs/development/instance-health.mdx +++ b/docs/content/docs/development/instance-health.mdx @@ -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. A webhook enqueued on a backend still starts that backend's delivery at once. 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 diff --git a/internal/app/hubspot/drain.go b/internal/app/hubspot/drain.go index 5f4ba9214..724427bb7 100644 --- a/internal/app/hubspot/drain.go +++ b/internal/app/hubspot/drain.go @@ -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)) } } } diff --git a/internal/app/orgtransfer/spec.go b/internal/app/orgtransfer/spec.go index 0452beeb5..33de0e9d5 100644 --- a/internal/app/orgtransfer/spec.go +++ b/internal/app/orgtransfer/spec.go @@ -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, diff --git a/internal/app/pipedrive/drain.go b/internal/app/pipedrive/drain.go index 1502f4371..daceee8f1 100644 --- a/internal/app/pipedrive/drain.go +++ b/internal/app/pipedrive/drain.go @@ -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)) } } } diff --git a/internal/app/webhook/service.go b/internal/app/webhook/service.go index cff251388..e1071d621 100644 --- a/internal/app/webhook/service.go +++ b/internal/app/webhook/service.go @@ -26,6 +26,7 @@ import ( "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" @@ -139,12 +140,23 @@ type service struct { cache *cache.Cache resolveLimit func(ctx context.Context, orgID uuid.UUID) int appDomains AppDomainResolver + // wake asks this process's delivery worker to poll now; nil when it runs elsewhere. + wake func() } func NewService(repo repository.WebhookRepository) Service { return &service{repo: repo, now: time.Now} } +// WireDeliveryWake lets an enqueue start this process's delivery worker at once. +func (s *service) WireDeliveryWake(wake func()) { s.wake = wake } + +func (s *service) enqueued() { + if s.wake != nil { + s.wake() + } +} + func (s *service) WireDispatchSink(sink DispatchSink) { s.sink = sink } @@ -284,6 +296,9 @@ func (s *service) Dispatch(ctx context.Context, orgID uuid.UUID, eventType model return eventID, err } } + if len(endpoints) > 0 { + s.enqueued() + } return eventID, nil } @@ -526,7 +541,9 @@ func (s *service) enqueueChallenge(ctx context.Context, endpoint *models.Webhook } if err := s.repo.EnqueueDelivery(ctx, delivery); err != nil { log.Warn().Err(err).Str("endpoint_id", endpoint.ID.String()).Msg("Failed to enqueue webhook challenge") + return } + s.enqueued() } // generateSecret returns a 32-byte cryptographically-random hex string. @@ -650,6 +667,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 +728,42 @@ 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: + } +} + +// 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 +777,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 diff --git a/internal/infrastructure/db/migrations/000395_task_dispatch_claim.down.sql b/internal/infrastructure/db/migrations/000395_task_dispatch_claim.down.sql new file mode 100644 index 000000000..6bc608c2f --- /dev/null +++ b/internal/infrastructure/db/migrations/000395_task_dispatch_claim.down.sql @@ -0,0 +1 @@ +ALTER TABLE tasks DROP COLUMN IF EXISTS dispatch_claimed_until; diff --git a/internal/infrastructure/db/migrations/000395_task_dispatch_claim.up.sql b/internal/infrastructure/db/migrations/000395_task_dispatch_claim.up.sql new file mode 100644 index 000000000..a7a42764b --- /dev/null +++ b/internal/infrastructure/db/migrations/000395_task_dispatch_claim.up.sql @@ -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; diff --git a/internal/infrastructure/db/migrations/000396_crm_sync_jobs_running_lease_index.down.sql b/internal/infrastructure/db/migrations/000396_crm_sync_jobs_running_lease_index.down.sql new file mode 100644 index 000000000..16b08ff9b --- /dev/null +++ b/internal/infrastructure/db/migrations/000396_crm_sync_jobs_running_lease_index.down.sql @@ -0,0 +1 @@ +DROP INDEX CONCURRENTLY IF EXISTS public.idx_crm_sync_jobs_running_lease; diff --git a/internal/infrastructure/db/migrations/000396_crm_sync_jobs_running_lease_index.up.sql b/internal/infrastructure/db/migrations/000396_crm_sync_jobs_running_lease_index.up.sql new file mode 100644 index 000000000..6ce7cd011 --- /dev/null +++ b/internal/infrastructure/db/migrations/000396_crm_sync_jobs_running_lease_index.up.sql @@ -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'; diff --git a/internal/pkg/idlepoll/idlepoll.go b/internal/pkg/idlepoll/idlepoll.go new file mode 100644 index 000000000..a06d6cbad --- /dev/null +++ b/internal/pkg/idlepoll/idlepoll.go @@ -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 +} diff --git a/internal/pkg/idlepoll/idlepoll_test.go b/internal/pkg/idlepoll/idlepoll_test.go new file mode 100644 index 000000000..b3d37e994 --- /dev/null +++ b/internal/pkg/idlepoll/idlepoll_test.go @@ -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) + } + } +} diff --git a/internal/repository/pg_crm_provider.go b/internal/repository/pg_crm_provider.go index 90fbb2a50..3bbd7278e 100644 --- a/internal/repository/pg_crm_provider.go +++ b/internal/repository/pg_crm_provider.go @@ -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 diff --git a/internal/repository/pg_task.go b/internal/repository/pg_task.go index ba557cbea..a453e8987 100644 --- a/internal/repository/pg_task.go +++ b/internal/repository/pg_task.go @@ -145,11 +145,12 @@ 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) + // 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. + ClaimDueTaskIDs(ctx context.Context, limit int, lease time.Duration) ([]uuid.UUID, error) RecordDispatchAttempt(ctx context.Context, taskID uuid.UUID, failed bool, retryAt time.Time) error + ReleaseDispatchClaims(ctx context.Context, taskIDs []uuid.UUID) error ListOverdueWarmupDispatches(ctx context.Context, now time.Time) ([]MailboxLoadingIncident, error) // Update operations @@ -896,19 +897,27 @@ 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, 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 ` - rows, err := r.db.Query(ctx, query, limit) + rows, err := r.db.Query(ctx, query, limit, lease.Seconds()) if err != nil { return nil, err } @@ -929,14 +938,24 @@ func (r *taskRepository) ListDuePendingTaskIDs(ctx context.Context, limit int) ( func (r *taskRepository) RecordDispatchAttempt(ctx context.Context, taskID uuid.UUID, failed bool, retryAt time.Time) error { 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() + dispatch_failure_since=COALESCE(dispatch_failure_since,NOW()),dispatch_failure_at=NOW(), + dispatch_claimed_until=NULL WHERE id=$1 AND status='pending'`, taskID, retryAt) 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,dispatch_claimed_until=NULL WHERE id=$1`, taskID, retryAt) + return err +} + +// ReleaseDispatchClaims hands claimed tasks that never ran back to the next poll. +func (r *taskRepository) ReleaseDispatchClaims(ctx context.Context, taskIDs []uuid.UUID) 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 IS NOT NULL`, taskIDs) return err } diff --git a/internal/repository/pg_task_claim_live_test.go b/internal/repository/pg_task_claim_live_test.go new file mode 100644 index 000000000..012753662 --- /dev/null +++ b/internal/repository/pg_task_claim_live_test.go @@ -0,0 +1,115 @@ +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 + var wg sync.WaitGroup + for d := range 2 { + wg.Add(1) + go func() { + defer wg.Done() + for range 40 { + got, err := repo.ClaimDueTaskIDs(ctx, 5, time.Minute) + if err != nil { + t.Error(err) + return + } + mu.Lock() + for _, id := range got { + 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. + if err := repo.ReleaseDispatchClaims(ctx, foreign); 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, 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); err != nil { + t.Fatal(err) + } + 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] + 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) + } + + // Recording an attempt releases the claim, and so does handing a claim back. + if err := repo.RecordDispatchAttempt(ctx, 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) + } + if err := repo.ReleaseDispatchClaims(ctx, ids[2:]); 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) + } +} diff --git a/internal/repository/queue_claim_live_test.go b/internal/repository/queue_claim_live_test.go new file mode 100644 index 000000000..48c2264d6 --- /dev/null +++ b/internal/repository/queue_claim_live_test.go @@ -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") + } +} diff --git a/internal/repository/send_result_effects.go b/internal/repository/send_result_effects.go index 32d302201..979eebb99 100644 --- a/internal/repository/send_result_effects.go +++ b/internal/repository/send_result_effects.go @@ -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,85 @@ 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 Date: Wed, 4 Nov 2026 12:55:41 +0100 Subject: [PATCH 139/318] feat: prune campaign feeds, notifications, webhook delivery logs, tracking dedupe marks, worker health samples, delivered send-result effects and warmup thread turns in batched ctid deletes from one jobrun table_retention job with three new retention settings, index every prune and the capacity view window, drive warmup mail retirement from the mailboxes that can act, and persist the unibox body backfill place --- .../dashboard/configuration/SettingsTab.tsx | 39 ++++- admin/src/lib/api/client/admin/instance.ts | 5 + cmd/backend/main.go | 3 + .../docs/development/configuration.mdx | 7 +- .../content/docs/development/data-control.mdx | 13 +- docs/content/docs/guides/campaigns.mdx | 2 +- docs/content/docs/guides/notifications.mdx | 2 + docs/content/docs/guides/webhooks.mdx | 2 + internal/api/handler/admin_instance.go | 3 + internal/app/instancesettings/document.go | 24 +++ internal/app/unibox/backfill_body_text.go | 26 ++- internal/config/constants.go | 7 + ...00341_email_opens_opened_at_index.down.sql | 1 + .../000341_email_opens_opened_at_index.up.sql | 3 + ...mail_link_clicks_clicked_at_index.down.sql | 1 + ..._email_link_clicks_clicked_at_index.up.sql | 3 + ...ker_health_samples_observed_index.down.sql | 1 + ...orker_health_samples_observed_index.up.sql | 3 + ...00344_campaign_logs_created_index.down.sql | 1 + .../000344_campaign_logs_created_index.up.sql | 3 + ...00345_notifications_created_index.down.sql | 1 + .../000345_notifications_created_index.up.sql | 3 + ..._webhook_deliveries_settled_index.down.sql | 1 + ...46_webhook_deliveries_settled_index.up.sql | 4 + ...armup_received_account_live_index.down.sql | 1 + ..._warmup_received_account_live_index.up.sql | 4 + ...8_warmup_tokens_sender_live_index.down.sql | 1 + ...348_warmup_tokens_sender_live_index.up.sql | 4 + internal/jobs/table_retention.go | 90 +++++++++++ internal/jobs/table_retention_test.go | 70 ++++++++ internal/repository/pg_email_opens.go | 9 +- internal/repository/pg_link_clicks.go | 9 +- internal/repository/pg_table_retention.go | 87 ++++++++++ .../pg_table_retention_live_test.go | 151 ++++++++++++++++++ internal/repository/pg_tracking_dedupe.go | 16 -- internal/repository/pg_unibox.go | 38 +++++ internal/repository/pg_warmup.go | 31 ++-- internal/repository/send_result_effects.go | 3 +- 38 files changed, 615 insertions(+), 57 deletions(-) create mode 100644 internal/infrastructure/db/migrations/000341_email_opens_opened_at_index.down.sql create mode 100644 internal/infrastructure/db/migrations/000341_email_opens_opened_at_index.up.sql create mode 100644 internal/infrastructure/db/migrations/000342_email_link_clicks_clicked_at_index.down.sql create mode 100644 internal/infrastructure/db/migrations/000342_email_link_clicks_clicked_at_index.up.sql create mode 100644 internal/infrastructure/db/migrations/000343_worker_health_samples_observed_index.down.sql create mode 100644 internal/infrastructure/db/migrations/000343_worker_health_samples_observed_index.up.sql create mode 100644 internal/infrastructure/db/migrations/000344_campaign_logs_created_index.down.sql create mode 100644 internal/infrastructure/db/migrations/000344_campaign_logs_created_index.up.sql create mode 100644 internal/infrastructure/db/migrations/000345_notifications_created_index.down.sql create mode 100644 internal/infrastructure/db/migrations/000345_notifications_created_index.up.sql create mode 100644 internal/infrastructure/db/migrations/000346_webhook_deliveries_settled_index.down.sql create mode 100644 internal/infrastructure/db/migrations/000346_webhook_deliveries_settled_index.up.sql create mode 100644 internal/infrastructure/db/migrations/000347_warmup_received_account_live_index.down.sql create mode 100644 internal/infrastructure/db/migrations/000347_warmup_received_account_live_index.up.sql create mode 100644 internal/infrastructure/db/migrations/000348_warmup_tokens_sender_live_index.down.sql create mode 100644 internal/infrastructure/db/migrations/000348_warmup_tokens_sender_live_index.up.sql create mode 100644 internal/jobs/table_retention.go create mode 100644 internal/jobs/table_retention_test.go create mode 100644 internal/repository/pg_table_retention.go create mode 100644 internal/repository/pg_table_retention_live_test.go diff --git a/admin/src/app/dashboard/configuration/SettingsTab.tsx b/admin/src/app/dashboard/configuration/SettingsTab.tsx index 8912691d5..2291c948d 100644 --- a/admin/src/app/dashboard/configuration/SettingsTab.tsx +++ b/admin/src/app/dashboard/configuration/SettingsTab.tsx @@ -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: RETENTION_MIN_DAYS, + 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.", + }, + { + key: "notificationDays", + setting: "notification_days", + label: "Notifications (days)", + min: RETENTION_MIN_DAYS, + help: "In-app notifications, read or unread. One still waiting to be emailed is kept until it is sent or skipped.", + }, + { + key: "webhookDeliveryDays", + setting: "webhook_delivery_days", + label: "Webhook delivery log (days)", + min: RETENTION_MIN_DAYS, + 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.", }, ] 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 365 / 180 / 90", values: { engagementDays: "365", formDays: "180", auditDays: "90", warmupMailDays: "30", warmupEventDays: "365", + campaignLogDays: "365", + notificationDays: "180", + webhookDeliveryDays: "90", }, }, { 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), + notificationDays: String(s.retention.notification_days), + webhookDeliveryDays: String(s.retention.webhook_delivery_days), }, tracking: { machineWindowOpen: String(s.tracking.machine_window_open_seconds), @@ -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), diff --git a/admin/src/lib/api/client/admin/instance.ts b/admin/src/lib/api/client/admin/instance.ts index b5e9ee90f..9c1830497 100644 --- a/admin/src/lib/api/client/admin/instance.ts +++ b/admin/src/lib/api/client/admin/instance.ts @@ -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 diff --git a/cmd/backend/main.go b/cmd/backend/main.go index f4ca9e736..ab2693b39 100644 --- a/cmd/backend/main.go +++ b/cmd/backend/main.go @@ -2218,6 +2218,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. diff --git a/docs/content/docs/development/configuration.mdx b/docs/content/docs/development/configuration.mdx index 0cecd9a87..3027e64d0 100644 --- a/docs/content/docs/development/configuration.mdx +++ b/docs/content/docs/development/configuration.mdx @@ -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, 1 to 3650 | `365` | How long each campaign's activity feed keeps an entry. Campaign stats, progress and sent mail are separate and unaffected | +| `retention.notification_days` | integer, 1 to 3650 | `180` | How long in-app notifications are kept, read or unread. One still waiting to be emailed is kept until it is sent or skipped | +| `retention.webhook_delivery_days` | integer, 1 to 3650 | `90` | How long a settled webhook delivery (delivered or abandoned) stays in its endpoint's delivery log. 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: diff --git a/docs/content/docs/development/data-control.mdx b/docs/content/docs/development/data-control.mdx index d94d0e860..31f6c9b36 100644 --- a/docs/content/docs/development/data-control.mdx +++ b/docs/content/docs/development/data-control.mdx @@ -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` | 365 | Each campaign's activity feed: failed and deferred sends, pauses and their reasons | +| `retention.notification_days` | 180 | In-app notifications, read or unread. One still waiting to be emailed is kept until it is sent or skipped | +| `retention.webhook_delivery_days` | 90 | 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 and the three history feeds 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. 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: the marks the consumer uses to count each open or click once follow `retention.engagement_event_days`, worker health samples are kept 7 days, and a send's queued follow-up effects 7 days after they ran. 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. + There is no grace period and no copy. Take a backup first if you are not sure. -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 diff --git a/docs/content/docs/guides/campaigns.mdx b/docs/content/docs/guides/campaigns.mdx index 46bc5b3e4..99df9fc24 100644 --- a/docs/content/docs/guides/campaigns.mdx +++ b/docs/content/docs/guides/campaigns.mdx @@ -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 for 365 days by default (`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. diff --git a/docs/content/docs/guides/notifications.mdx b/docs/content/docs/guides/notifications.mdx index 4558e7cb1..bab0b35bb 100644 --- a/docs/content/docs/guides/notifications.mdx +++ b/docs/content/docs/guides/notifications.mdx @@ -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 for 180 days by default, read or not, so one older than that 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. diff --git a/docs/content/docs/guides/webhooks.mdx b/docs/content/docs/guides/webhooks.mdx index a94099458..4777eadeb 100644 --- a/docs/content/docs/guides/webhooks.mdx +++ b/docs/content/docs/guides/webhooks.mdx @@ -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 for 90 days by default after its last attempt, after which it 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. diff --git a/internal/api/handler/admin_instance.go b/internal/api/handler/admin_instance.go index 36d16662e..9630677c8 100644 --- a/internal/api/handler/admin_instance.go +++ b/internal/api/handler/admin_instance.go @@ -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, diff --git a/internal/app/instancesettings/document.go b/internal/app/instancesettings/document.go index a104b4356..2b2112b30 100644 --- a/internal/app/instancesettings/document.go +++ b/internal/app/instancesettings/document.go @@ -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. + CampaignLogDays int `json:"campaign_log_days"` + // NotificationDays is how long in-app notifications are kept, read or not. + NotificationDays int `json:"notification_days"` + // WebhookDeliveryDays is how long a settled webhook delivery stays in its endpoint's log. + 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,9 @@ 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) + r.CampaignLogDays = clamp(r.CampaignLogDays, config.CampaignLogRetentionDaysDefault, config.RetentionDaysMin) + r.NotificationDays = clamp(r.NotificationDays, config.NotificationRetentionDaysDefault, config.RetentionDaysMin) + r.WebhookDeliveryDays = clamp(r.WebhookDeliveryDays, config.WebhookDeliveryRetentionDaysDefault, config.RetentionDaysMin) } // Normalize clamps a document into its accepted range. It is applied on read @@ -463,6 +475,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 +556,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 { diff --git a/internal/app/unibox/backfill_body_text.go b/internal/app/unibox/backfill_body_text.go index 0ad67408f..829edb210 100644 --- a/internal/app/unibox/backfill_body_text.go +++ b/internal/app/unibox/backfill_body_text.go @@ -4,10 +4,10 @@ import ( "context" "time" - "github.com/google/uuid" "github.com/rs/zerolog/log" "github.com/warmbly/warmbly/internal/config" "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 @@ -22,15 +22,23 @@ const ( // 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 for { select { @@ -45,6 +53,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") } @@ -69,5 +80,8 @@ func (s *uniboxService) StartBodyTextBackfill(ctx context.Context) { } filled++ } + if serr := s.uniboxRepository.SaveBodyBackfillProgress(ctx, repository.UniboxBodyBackfill{After: cursor}); serr != nil { + log.Warn().Err(serr).Msg("unibox body backfill: could not record progress") + } } } diff --git a/internal/config/constants.go b/internal/config/constants.go index 492200b06..980f4735b 100644 --- a/internal/config/constants.go +++ b/internal/config/constants.go @@ -339,6 +339,13 @@ const ( // shortens it under Instance settings. AuditLogRetentionDaysDefault = 90 + // CampaignLogRetentionDaysDefault is how long a campaign's activity feed keeps an entry. + CampaignLogRetentionDaysDefault = 365 + // NotificationRetentionDaysDefault is how long in-app notifications are kept, read or not. + NotificationRetentionDaysDefault = 180 + // WebhookDeliveryRetentionDaysDefault is how long a settled delivery stays in an endpoint's log. + WebhookDeliveryRetentionDaysDefault = 90 + // 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 diff --git a/internal/infrastructure/db/migrations/000341_email_opens_opened_at_index.down.sql b/internal/infrastructure/db/migrations/000341_email_opens_opened_at_index.down.sql new file mode 100644 index 000000000..82504dbad --- /dev/null +++ b/internal/infrastructure/db/migrations/000341_email_opens_opened_at_index.down.sql @@ -0,0 +1 @@ +DROP INDEX CONCURRENTLY IF EXISTS public.idx_email_opens_opened_at; diff --git a/internal/infrastructure/db/migrations/000341_email_opens_opened_at_index.up.sql b/internal/infrastructure/db/migrations/000341_email_opens_opened_at_index.up.sql new file mode 100644 index 000000000..d0534e14b --- /dev/null +++ b/internal/infrastructure/db/migrations/000341_email_opens_opened_at_index.up.sql @@ -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); diff --git a/internal/infrastructure/db/migrations/000342_email_link_clicks_clicked_at_index.down.sql b/internal/infrastructure/db/migrations/000342_email_link_clicks_clicked_at_index.down.sql new file mode 100644 index 000000000..132e096bf --- /dev/null +++ b/internal/infrastructure/db/migrations/000342_email_link_clicks_clicked_at_index.down.sql @@ -0,0 +1 @@ +DROP INDEX CONCURRENTLY IF EXISTS public.idx_email_link_clicks_clicked_at; diff --git a/internal/infrastructure/db/migrations/000342_email_link_clicks_clicked_at_index.up.sql b/internal/infrastructure/db/migrations/000342_email_link_clicks_clicked_at_index.up.sql new file mode 100644 index 000000000..bda1e7dfb --- /dev/null +++ b/internal/infrastructure/db/migrations/000342_email_link_clicks_clicked_at_index.up.sql @@ -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); diff --git a/internal/infrastructure/db/migrations/000343_worker_health_samples_observed_index.down.sql b/internal/infrastructure/db/migrations/000343_worker_health_samples_observed_index.down.sql new file mode 100644 index 000000000..22830a32a --- /dev/null +++ b/internal/infrastructure/db/migrations/000343_worker_health_samples_observed_index.down.sql @@ -0,0 +1 @@ +DROP INDEX CONCURRENTLY IF EXISTS public.idx_worker_health_samples_observed; diff --git a/internal/infrastructure/db/migrations/000343_worker_health_samples_observed_index.up.sql b/internal/infrastructure/db/migrations/000343_worker_health_samples_observed_index.up.sql new file mode 100644 index 000000000..7075089b8 --- /dev/null +++ b/internal/infrastructure/db/migrations/000343_worker_health_samples_observed_index.up.sql @@ -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); diff --git a/internal/infrastructure/db/migrations/000344_campaign_logs_created_index.down.sql b/internal/infrastructure/db/migrations/000344_campaign_logs_created_index.down.sql new file mode 100644 index 000000000..c82ef2231 --- /dev/null +++ b/internal/infrastructure/db/migrations/000344_campaign_logs_created_index.down.sql @@ -0,0 +1 @@ +DROP INDEX CONCURRENTLY IF EXISTS public.idx_campaign_logs_created; diff --git a/internal/infrastructure/db/migrations/000344_campaign_logs_created_index.up.sql b/internal/infrastructure/db/migrations/000344_campaign_logs_created_index.up.sql new file mode 100644 index 000000000..e5137f68b --- /dev/null +++ b/internal/infrastructure/db/migrations/000344_campaign_logs_created_index.up.sql @@ -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); diff --git a/internal/infrastructure/db/migrations/000345_notifications_created_index.down.sql b/internal/infrastructure/db/migrations/000345_notifications_created_index.down.sql new file mode 100644 index 000000000..bb0525eaa --- /dev/null +++ b/internal/infrastructure/db/migrations/000345_notifications_created_index.down.sql @@ -0,0 +1 @@ +DROP INDEX CONCURRENTLY IF EXISTS public.idx_notifications_created; diff --git a/internal/infrastructure/db/migrations/000345_notifications_created_index.up.sql b/internal/infrastructure/db/migrations/000345_notifications_created_index.up.sql new file mode 100644 index 000000000..dac121734 --- /dev/null +++ b/internal/infrastructure/db/migrations/000345_notifications_created_index.up.sql @@ -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); diff --git a/internal/infrastructure/db/migrations/000346_webhook_deliveries_settled_index.down.sql b/internal/infrastructure/db/migrations/000346_webhook_deliveries_settled_index.down.sql new file mode 100644 index 000000000..6977ce72c --- /dev/null +++ b/internal/infrastructure/db/migrations/000346_webhook_deliveries_settled_index.down.sql @@ -0,0 +1 @@ +DROP INDEX CONCURRENTLY IF EXISTS public.idx_webhook_deliveries_settled; diff --git a/internal/infrastructure/db/migrations/000346_webhook_deliveries_settled_index.up.sql b/internal/infrastructure/db/migrations/000346_webhook_deliveries_settled_index.up.sql new file mode 100644 index 000000000..1c7947722 --- /dev/null +++ b/internal/infrastructure/db/migrations/000346_webhook_deliveries_settled_index.up.sql @@ -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'); diff --git a/internal/infrastructure/db/migrations/000347_warmup_received_account_live_index.down.sql b/internal/infrastructure/db/migrations/000347_warmup_received_account_live_index.down.sql new file mode 100644 index 000000000..a14749d2b --- /dev/null +++ b/internal/infrastructure/db/migrations/000347_warmup_received_account_live_index.down.sql @@ -0,0 +1 @@ +DROP INDEX CONCURRENTLY IF EXISTS public.idx_warmup_received_account_live; diff --git a/internal/infrastructure/db/migrations/000347_warmup_received_account_live_index.up.sql b/internal/infrastructure/db/migrations/000347_warmup_received_account_live_index.up.sql new file mode 100644 index 000000000..461c458b8 --- /dev/null +++ b/internal/infrastructure/db/migrations/000347_warmup_received_account_live_index.up.sql @@ -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; diff --git a/internal/infrastructure/db/migrations/000348_warmup_tokens_sender_live_index.down.sql b/internal/infrastructure/db/migrations/000348_warmup_tokens_sender_live_index.down.sql new file mode 100644 index 000000000..17f63f29e --- /dev/null +++ b/internal/infrastructure/db/migrations/000348_warmup_tokens_sender_live_index.down.sql @@ -0,0 +1 @@ +DROP INDEX CONCURRENTLY IF EXISTS public.idx_warmup_tokens_sender_live; diff --git a/internal/infrastructure/db/migrations/000348_warmup_tokens_sender_live_index.up.sql b/internal/infrastructure/db/migrations/000348_warmup_tokens_sender_live_index.up.sql new file mode 100644 index 000000000..e57405b10 --- /dev/null +++ b/internal/infrastructure/db/migrations/000348_warmup_tokens_sender_live_index.up.sql @@ -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 <> ''; diff --git a/internal/jobs/table_retention.go b/internal/jobs/table_retention.go new file mode 100644 index 000000000..69f257f43 --- /dev/null +++ b/internal/jobs/table_retention.go @@ -0,0 +1,90 @@ +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) + PruneTrackingDedupe(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}, + // A dedupe mark only matters while the open and click logs it guards are kept. + {"tracking_events_processed", j.store.PruneTrackingDedupe, windows.EngagementEventDays}, + {"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...) +} diff --git a/internal/jobs/table_retention_test.go b/internal/jobs/table_retention_test.go new file mode 100644 index 000000000..6a0ee5609 --- /dev/null +++ b/internal/jobs/table_retention_test.go @@ -0,0 +1,70 @@ +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) PruneTrackingDedupe(_ context.Context, b time.Time) (int64, error) { + return f.record("tracking_events_processed", 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.WebhookDeliveryDays, windows.EngagementEventDays = 10, 20, 30 + err := NewTableRetentionJob(store, fixedRetention(windows)).Run(context.Background()) + if err == nil { + t.Fatal("a failing table was not reported") + } + if len(store.before) != 6 { + t.Fatalf("pruned %d tables, want all six despite the failure: %v", len(store.before), store.before) + } + for table, days := range map[string]int{ + "campaign_logs": 10, "webhook_deliveries": 20, "tracking_events_processed": 30, + "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) + } + } +} diff --git a/internal/repository/pg_email_opens.go b/internal/repository/pg_email_opens.go index 8491d7d1f..0abe39139 100644 --- a/internal/repository/pg_email_opens.go +++ b/internal/repository/pg_email_opens.go @@ -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 diff --git a/internal/repository/pg_link_clicks.go b/internal/repository/pg_link_clicks.go index 9205df22f..56a66aea3 100644 --- a/internal/repository/pg_link_clicks.go +++ b/internal/repository/pg_link_clicks.go @@ -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) { diff --git a/internal/repository/pg_table_retention.go b/internal/repository/pg_table_retention.go new file mode 100644 index 000000000..8880a6ab7 --- /dev/null +++ b/internal/repository/pg_table_retention.go @@ -0,0 +1,87 @@ +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) +} + +// PruneTrackingDedupe drops consumer-side tracking dedupe marks older than before. +func (r *TableRetentionRepository) PruneTrackingDedupe(ctx context.Context, before time.Time) (int64, error) { + return DeleteInBatches(ctx, r.db, "tracking_events_processed", + `SELECT ctid FROM tracking_events_processed WHERE processed_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. +func (r *TableRetentionRepository) PruneDeliveredSendResultEffects(ctx context.Context, before time.Time) (int64, error) { + return DeleteInBatches(ctx, r.db, "send_result_effects", + `SELECT ctid FROM send_result_effects WHERE delivered_at IS NOT NULL AND delivered_at < $2 LIMIT $1`, before) +} diff --git a/internal/repository/pg_table_retention_live_test.go b/internal/repository/pg_table_retention_live_test.go new file mode 100644 index 000000000..4fa9b240e --- /dev/null +++ b/internal/repository/pg_table_retention_live_test.go @@ -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 := 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) VALUES ($1, 'campaign', $2, 'completed', '')`, task, account) + t.Cleanup(func() { + c := context.Background() + _, _ = pool.Exec(c, `DELETE FROM tracking_events_processed WHERE task_id = $1`, task) + _, _ = pool.Exec(c, `DELETE FROM tasks WHERE id = $1`, task) + _, _ = 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)`, task, org, old, fresh) + // More than one batch, so the loop has to come back for the rest. + exec(`INSERT INTO tracking_events_processed (task_id, event_type, url_hash, processed_at) + SELECT $1, 'click', g::text, $2 FROM generate_series(1, $3::int) g`, task, old, PruneBatch+7) + exec(`INSERT INTO tracking_events_processed (task_id, event_type, url_hash, processed_at) VALUES ($1, 'open', '', $2)`, task, fresh) + + 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, + "tracking_events_processed": repo.PruneTrackingDedupe, "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 the fresh one", `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}, + {"dedupe marks keep only the fresh one, across batches", `SELECT count(*) FROM tracking_events_processed WHERE task_id = $1`, task, 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 tracking_events_processed WHERE processed_at < NOW() LIMIT 5000`, "idx_tracking_processed_cleanup"}, + {`SELECT ctid FROM worker_health_samples WHERE observed_at < NOW() LIMIT 5000`, "idx_worker_health_samples_observed"}, + {`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_observed"}, + {`SELECT ctid FROM send_result_effects WHERE delivered_at IS NOT NULL AND delivered_at < NOW() 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) { + t.Errorf("%s is not used by %q:\n%s", c.index, c.query, plan.String()) + } + } +} diff --git a/internal/repository/pg_tracking_dedupe.go b/internal/repository/pg_tracking_dedupe.go index b02317ca6..d086f5417 100644 --- a/internal/repository/pg_tracking_dedupe.go +++ b/internal/repository/pg_tracking_dedupe.go @@ -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 -} diff --git a/internal/repository/pg_unibox.go b/internal/repository/pg_unibox.go index 26720aa60..10a45bedf 100644 --- a/internal/repository/pg_unibox.go +++ b/internal/repository/pg_unibox.go @@ -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) diff --git a/internal/repository/pg_warmup.go b/internal/repository/pg_warmup.go index 9e08c6ed8..7b879b3bb 100644 --- a/internal/repository/pg_warmup.go +++ b/internal/repository/pg_warmup.go @@ -1990,13 +1990,20 @@ func (r *warmupRepository) GetWarmupReceived(ctx context.Context, accountID, int // 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. +// 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) ([]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 $2 + ) 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 @@ -2004,8 +2011,6 @@ func (r *warmupRepository) ListWarmupMailToRetire(ctx context.Context, defaultDa ) m ON true WHERE ea.status = 'active' 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) @@ -2017,12 +2022,19 @@ 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. +// Like the received side it starts from the mailboxes that can act. func (r *warmupRepository) ListWarmupSentCopiesToRetire(ctx context.Context, defaultDays, limit int) ([]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 $2 + ) 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 @@ -2031,9 +2043,6 @@ func (r *warmupRepository) ListWarmupSentCopiesToRetire(ctx context.Context, def WHERE ea.status = 'active' 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) @@ -2104,6 +2113,8 @@ func (r *warmupRepository) PruneWarmupEventsBefore(ctx context.Context, before t AND (sent_message_id = '' OR sent_retired_at IS NOT NULL OR sender_account_id IN (SELECT id FROM email_accounts WHERE provider = 'smtp_imap'))`, []any{before}}, {`DELETE FROM pool_link_commands WHERE status IN ('answered', 'expired', 'cancelled') AND created_at < $1`, []any{before}}, + // Thread turns go at the age of the receipts and tokens they chain back to. + {`DELETE FROM warmup_thread_messages WHERE created_at < $1`, []any{before}}, // An arrival's handle is how a retiring delete reaches the instance, so it outlives the copy it names. {`DELETE FROM pool_link_arrivals a WHERE a.reported_at < $1 AND NOT EXISTS (SELECT 1 FROM warmup_received wr WHERE wr.email_account_id = a.email_account_id diff --git a/internal/repository/send_result_effects.go b/internal/repository/send_result_effects.go index 979eebb99..377cf85ed 100644 --- a/internal/repository/send_result_effects.go +++ b/internal/repository/send_result_effects.go @@ -78,8 +78,7 @@ func (r *advancedOutreachRepository) DeliverSendResultEffects(ctx context.Contex break } } - _, err := r.db.Exec(ctx, `DELETE FROM send_result_effects WHERE delivered_at Date: Wed, 4 Nov 2026 12:57:09 +0100 Subject: [PATCH 140/318] feat: number the task dispatch claim and CRM lease index migrations 000349 and 000350 after the retention index migrations --- ...ispatch_claim.down.sql => 000349_task_dispatch_claim.down.sql} | 0 ...sk_dispatch_claim.up.sql => 000349_task_dispatch_claim.up.sql} | 0 ...down.sql => 000350_crm_sync_jobs_running_lease_index.down.sql} | 0 ...dex.up.sql => 000350_crm_sync_jobs_running_lease_index.up.sql} | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename internal/infrastructure/db/migrations/{000395_task_dispatch_claim.down.sql => 000349_task_dispatch_claim.down.sql} (100%) rename internal/infrastructure/db/migrations/{000395_task_dispatch_claim.up.sql => 000349_task_dispatch_claim.up.sql} (100%) rename internal/infrastructure/db/migrations/{000396_crm_sync_jobs_running_lease_index.down.sql => 000350_crm_sync_jobs_running_lease_index.down.sql} (100%) rename internal/infrastructure/db/migrations/{000396_crm_sync_jobs_running_lease_index.up.sql => 000350_crm_sync_jobs_running_lease_index.up.sql} (100%) diff --git a/internal/infrastructure/db/migrations/000395_task_dispatch_claim.down.sql b/internal/infrastructure/db/migrations/000349_task_dispatch_claim.down.sql similarity index 100% rename from internal/infrastructure/db/migrations/000395_task_dispatch_claim.down.sql rename to internal/infrastructure/db/migrations/000349_task_dispatch_claim.down.sql diff --git a/internal/infrastructure/db/migrations/000395_task_dispatch_claim.up.sql b/internal/infrastructure/db/migrations/000349_task_dispatch_claim.up.sql similarity index 100% rename from internal/infrastructure/db/migrations/000395_task_dispatch_claim.up.sql rename to internal/infrastructure/db/migrations/000349_task_dispatch_claim.up.sql diff --git a/internal/infrastructure/db/migrations/000396_crm_sync_jobs_running_lease_index.down.sql b/internal/infrastructure/db/migrations/000350_crm_sync_jobs_running_lease_index.down.sql similarity index 100% rename from internal/infrastructure/db/migrations/000396_crm_sync_jobs_running_lease_index.down.sql rename to internal/infrastructure/db/migrations/000350_crm_sync_jobs_running_lease_index.down.sql diff --git a/internal/infrastructure/db/migrations/000396_crm_sync_jobs_running_lease_index.up.sql b/internal/infrastructure/db/migrations/000350_crm_sync_jobs_running_lease_index.up.sql similarity index 100% rename from internal/infrastructure/db/migrations/000396_crm_sync_jobs_running_lease_index.up.sql rename to internal/infrastructure/db/migrations/000350_crm_sync_jobs_running_lease_index.up.sql From 3a7048a7c19d9ea9c81fed09e4f1d94668516846 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 13:00:34 +0100 Subject: [PATCH 141/318] feat: retire warmup mail in batches of 500 capped at 50 per mailbox and keep taking batches for up to 40 seconds a run, so the retention sweep keeps pace with large fleets instead of 100 copies a minute --- .../app/consumer/warmup_mail_retention.go | 41 +++++++++++++++---- .../app/consumer/warmup_retention_test.go | 15 +++++++ internal/repository/pg_warmup.go | 7 +++- 3 files changed, 53 insertions(+), 10 deletions(-) diff --git a/internal/app/consumer/warmup_mail_retention.go b/internal/app/consumer/warmup_mail_retention.go index bdfad36fd..88493163b 100644 --- a/internal/app/consumer/warmup_mail_retention.go +++ b/internal/app/consumer/warmup_mail_retention.go @@ -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,11 +55,20 @@ 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 := time.Now() + for { + done, err := s.retireWarmupMailBatch(batchCtx) + if err != nil { + return err + } + if done { + break + } + if time.Since(started) > warmupRetentionRunBudget { + return nil + } } if err := s.pruneWarmupEvents(batchCtx); err != nil { return err @@ -83,8 +95,7 @@ func (s *JobsService) warmupRetentionDays(ctx context.Context) (mail, events int } // 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. +// copies to the workers. It reports done when both listings came back drained. func (s *JobsService) retireWarmupMailBatch(ctx context.Context) (bool, error) { days, _ := s.warmupRetentionDays(ctx) @@ -124,7 +135,21 @@ 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 + return drained(received) && drained(sent), 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 { + if len(batch) >= warmupRetentionBatch { + return false + } + per := map[uuid.UUID]int{} + for _, m := range batch { + if per[m.EmailAccountID]++; per[m.EmailAccountID] >= repository.WarmupRetirePerMailbox { + return false + } + } + return true } // publishWarmupDelete sends the delete for one message to the worker holding diff --git a/internal/app/consumer/warmup_retention_test.go b/internal/app/consumer/warmup_retention_test.go index 85fdf66ff..c3eacb55e 100644 --- a/internal/app/consumer/warmup_retention_test.go +++ b/internal/app/consumer/warmup_retention_test.go @@ -412,3 +412,18 @@ 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") + } +} diff --git a/internal/repository/pg_warmup.go b/internal/repository/pg_warmup.go index 7b879b3bb..34f924c79 100644 --- a/internal/repository/pg_warmup.go +++ b/internal/repository/pg_warmup.go @@ -1986,6 +1986,9 @@ func (r *warmupRepository) GetWarmupReceived(ctx context.Context, accountID, int return &w, nil } +// WarmupRetirePerMailbox bounds one mailbox's share of a retirement batch, so a long backlog cannot queue a whole batch on one worker. +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 @@ -2002,7 +2005,7 @@ func (r *warmupRepository) ListWarmupMailToRetire(ctx context.Context, defaultDa 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 $2 + LIMIT LEAST($2, ` + strconv.Itoa(WarmupRetirePerMailbox) + `) ) wr LEFT JOIN LATERAL ( SELECT em.message_id FROM email_message_map em @@ -2033,7 +2036,7 @@ func (r *warmupRepository) ListWarmupSentCopiesToRetire(ctx context.Context, def 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 $2 + LIMIT LEAST($2, ` + strconv.Itoa(WarmupRetirePerMailbox) + `) ) wt LEFT JOIN LATERAL ( SELECT em.message_id FROM email_message_map em From 6a784031ab47e9909e601ce3617ca7060a37d44e Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 13:04:27 +0100 Subject: [PATCH 142/318] feat: cut consumer Postgres statements per arrival and SYNC_STATE by reading the prior sync state under the report lock, folding the last_synced_at touch into the upsert, throttling healthy recovery and account clocks to a minute, admitting arrivals in one statement, claiming 32 arrivals per statement with checkpoints only before a remaining stage, counting the arrival backlog every 30s, memoizing the mailbox row per NEW_EMAIL and caching resource organizations for realtime audiences --- .../arrival_diagnostics_shutdown_test.go | 3 +- internal/app/consumer/arrival_outbox.go | 11 + internal/app/consumer/arrival_outbox_test.go | 37 ++++ internal/app/consumer/event_new_email.go | 41 +++- internal/app/consumer/event_sync_state.go | 19 +- .../app/consumer/event_sync_state_test.go | 9 +- internal/app/consumer/mailbox_memo_test.go | 41 ++++ internal/app/consumer/service.go | 2 + .../arrival_diagnostics_live_test.go | 3 +- .../event_audience_cache_live_test.go | 27 +++ .../repository/mail_transport_live_test.go | 12 +- internal/repository/pg_email_sync_state.go | 92 +++++--- internal/repository/pg_event_audience.go | 40 +++- .../repository/pg_mail_transport_recovery.go | 36 ++- internal/repository/pg_sync_arrival.go | 209 ++++++++++++------ .../sync_arrival_batch_live_test.go | 60 +++++ .../sync_report_writes_live_test.go | 132 +++++++++++ 17 files changed, 648 insertions(+), 126 deletions(-) create mode 100644 internal/app/consumer/mailbox_memo_test.go create mode 100644 internal/repository/event_audience_cache_live_test.go create mode 100644 internal/repository/sync_arrival_batch_live_test.go create mode 100644 internal/repository/sync_report_writes_live_test.go diff --git a/internal/app/consumer/arrival_diagnostics_shutdown_test.go b/internal/app/consumer/arrival_diagnostics_shutdown_test.go index 022a3080a..477f95b60 100644 --- a/internal/app/consumer/arrival_diagnostics_shutdown_test.go +++ b/internal/app/consumer/arrival_diagnostics_shutdown_test.go @@ -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) } } diff --git a/internal/app/consumer/arrival_outbox.go b/internal/app/consumer/arrival_outbox.go index 3155aba16..dda623001 100644 --- a/internal/app/consumer/arrival_outbox.go +++ b/internal/app/consumer/arrival_outbox.go @@ -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 { diff --git a/internal/app/consumer/arrival_outbox_test.go b/internal/app/consumer/arrival_outbox_test.go index 7e0ad4369..598338995 100644 --- a/internal/app/consumer/arrival_outbox_test.go +++ b/internal/app/consumer/arrival_outbox_test.go @@ -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 +} diff --git a/internal/app/consumer/event_new_email.go b/internal/app/consumer/event_new_email.go index 5233cc30e..24f1af352 100644 --- a/internal/app/consumer/event_new_email.go +++ b/internal/app/consumer/event_new_email.go @@ -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. diff --git a/internal/app/consumer/event_sync_state.go b/internal/app/consumer/event_sync_state.go index 11e6c6df7..5c14bdcf1 100644 --- a/internal/app/consumer/event_sync_state.go +++ b/internal/app/consumer/event_sync_state.go @@ -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) } diff --git a/internal/app/consumer/event_sync_state_test.go b/internal/app/consumer/event_sync_state_test.go index 296344cbf..40ff420cd 100644 --- a/internal/app/consumer/event_sync_state_test.go +++ b/internal/app/consumer/event_sync_state_test.go @@ -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 { diff --git a/internal/app/consumer/mailbox_memo_test.go b/internal/app/consumer/mailbox_memo_test.go new file mode 100644 index 000000000..c390a6d9e --- /dev/null +++ b/internal/app/consumer/mailbox_memo_test.go @@ -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") + } +} diff --git a/internal/app/consumer/service.go b/internal/app/consumer/service.go index ebe172f67..7e97a24e6 100644 --- a/internal/app/consumer/service.go +++ b/internal/app/consumer/service.go @@ -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) { diff --git a/internal/repository/arrival_diagnostics_live_test.go b/internal/repository/arrival_diagnostics_live_test.go index 8d72473e2..b851a31c2 100644 --- a/internal/repository/arrival_diagnostics_live_test.go +++ b/internal/repository/arrival_diagnostics_live_test.go @@ -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]) } diff --git a/internal/repository/event_audience_cache_live_test.go b/internal/repository/event_audience_cache_live_test.go new file mode 100644 index 000000000..08c413d65 --- /dev/null +++ b/internal/repository/event_audience_cache_live_test.go @@ -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") + } +} diff --git a/internal/repository/mail_transport_live_test.go b/internal/repository/mail_transport_live_test.go index 8a1d48ae2..c485517e9 100644 --- a/internal/repository/mail_transport_live_test.go +++ b/internal/repository/mail_transport_live_test.go @@ -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) diff --git a/internal/repository/pg_email_sync_state.go b/internal/repository/pg_email_sync_state.go index d9694f79a..6d33e7746 100644 --- a/internal/repository/pg_email_sync_state.go +++ b/internal/repository/pg_email_sync_state.go @@ -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) { diff --git a/internal/repository/pg_event_audience.go b/internal/repository/pg_event_audience.go index d63fc5987..a0c606c1c 100644 --- a/internal/repository/pg_event_audience.go +++ b/internal/repository/pg_event_audience.go @@ -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 ( diff --git a/internal/repository/pg_mail_transport_recovery.go b/internal/repository/pg_mail_transport_recovery.go index 7f46fa55f..e60e456d5 100644 --- a/internal/repository/pg_mail_transport_recovery.go +++ b/internal/repository/pg_mail_transport_recovery.go @@ -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 { + // A healthy mailbox's sync clock moves at most once a minute; a pending error always gets the exact one. + 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 EXCLUDED.operation<>'sync' OR (SELECT open FROM pending) OR existing.recovered_at < EXCLUDED.recovered_at - INTERVAL '1 minute') + 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 } diff --git a/internal/repository/pg_sync_arrival.go b/internal/repository/pg_sync_arrival.go index 4db7a86e9..f84716e18 100644 --- a/internal/repository/pg_sync_arrival.go +++ b/internal/repository/pg_sync_arrival.go @@ -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 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 } diff --git a/internal/repository/sync_arrival_batch_live_test.go b/internal/repository/sync_arrival_batch_live_test.go new file mode 100644 index 000000000..9c55009ea --- /dev/null +++ b/internal/repository/sync_arrival_batch_live_test.go @@ -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) + } +} diff --git a/internal/repository/sync_report_writes_live_test.go b/internal/repository/sync_report_writes_live_test.go new file mode 100644 index 000000000..9c1bb68c3 --- /dev/null +++ b/internal/repository/sync_report_writes_live_test.go @@ -0,0 +1,132 @@ +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 TestLiveSyncRecoveryClockSkipsQuietRewritesButNeverAPendingError(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(20 * time.Second)) + if rowVersion(t, f, recoveryRow) != quiet { + t.Fatal("a healthy mailbox rewrote its recovery clock inside the minute") + } + // An error raised now is cleared by the very next pass, minute or not. + 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) + } +} From 1cb2bfa3b3b70210416d7a6267acf9cabcfe3993 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 13:56:27 +0100 Subject: [PATCH 143/318] feat: add verified hosted backend attachment configuration with retained release settings and guarded rollback --- .github/scripts/aws-backend-config.cjs | 154 +++++++++++++++ .github/scripts/aws-backend-config.test.cjs | 183 ++++++++++++++++++ .github/scripts/aws-deploy.cjs | 47 ++++- .github/scripts/aws-deploy.test.cjs | 52 ++++- .github/scripts/terraform-stack.sh | 4 +- .github/scripts/terraform-stack.test.sh | 5 +- .github/workflows/ci.yml | 4 +- .github/workflows/configure-backend-aws.yml | 84 ++++++++ .github/workflows/terraform-aws.yml | 2 +- deploy/terraform/aws/runtime/README.md | 14 +- deploy/terraform/aws/runtime/ci.tf | 9 + .../aws/runtime/tests/target_tls.tftest.hcl | 16 ++ docs/content/docs/development/aws-fargate.mdx | 36 +++- .../docs/development/configuration.mdx | 2 +- 14 files changed, 598 insertions(+), 14 deletions(-) create mode 100644 .github/scripts/aws-backend-config.cjs create mode 100644 .github/scripts/aws-backend-config.test.cjs create mode 100644 .github/workflows/configure-backend-aws.yml diff --git a/.github/scripts/aws-backend-config.cjs b/.github/scripts/aws-backend-config.cjs new file mode 100644 index 000000000..42ebdd70f --- /dev/null +++ b/.github/scripts/aws-backend-config.cjs @@ -0,0 +1,154 @@ +const { + ECSClient, DescribeServicesCommand, DescribeTasksCommand, UpdateServiceCommand, paginateListTasks, +} = require("@aws-sdk/client-ecs"); +const { CloudWatchClient, DescribeAlarmsCommand } = require("@aws-sdk/client-cloudwatch"); +const { + configuration: deploymentConfiguration, describe, compareTags, register, same, waitForService, + ATTACHMENT_PROXY, ATTACHMENT_PROXY_TAG, +} = require("./aws-deploy.cjs"); + +const tagValue = (tags, key) => tags.find((t) => t.key === key)?.value; +const canonicalTags = (tags) => JSON.stringify(tags.filter((t) => !t.key.startsWith("aws:")).sort((a, b) => a.key.localeCompare(b.key))); + +function configuration(env) { + const config = deploymentConfiguration({ ...env, DEPLOY_MODE: "redeploy", DEPLOY_SERVICES: "backend", DEPLOY_FLEET: "false", DEPLOY_BAKE_SECONDS: "300" }); + if (!config.tag || !config.images || config.images.tag !== config.tag || compareTags(config.tag, "v0.6.75") < 0) { + throw new Error("A published v0.6.75 or newer release and its images.json are required"); + } + const account = config.cluster.split(":")[4]; + const expected = env.CONFIG_EXPECTED_TASK_DEFINITION || ""; + const expectedPrefix = `arn:aws:ecs:us-east-1:${account}:task-definition/${config.prefix}-backend:`; + if (!expected.startsWith(expectedPrefix) || !/^[1-9]\d*$/.test(expected.slice(expectedPrefix.length))) { + throw new Error("CONFIG_EXPECTED_TASK_DEFINITION must identify this cluster's backend revision"); + } + if (!["true", "false"].includes(env.CONFIG_ATTACHMENT_DOWNLOAD_PROXY)) throw new Error("CONFIG_ATTACHMENT_DOWNLOAD_PROXY must be true or false"); + return { ...config, expected, value: env.CONFIG_ATTACHMENT_DOWNLOAD_PROXY }; +} + +async function service(ecs, config) { + const out = await ecs.send(new DescribeServicesCommand({ cluster: config.cluster, services: [`${config.prefix}-backend`] })); + const live = out.services?.[0]; + if (out.failures?.length || out.services?.length !== 1 || live.status !== "ACTIVE") throw new Error("Backend service is unavailable"); + return live; +} + +function stable(live, expected, count) { + if (live.taskDefinition !== expected || live.desiredCount < 1 || live.runningCount !== live.desiredCount || live.pendingCount !== 0 || + live.deployments?.length !== 1 || live.deployments[0].rolloutState !== "COMPLETED" || + (count !== undefined && live.desiredCount !== count)) throw new Error("Backend must be stable on the expected revision and task count"); +} + +async function verifyTasks(ecs, config, live, definition) { + stable(live, definition.taskDefinitionArn); + const arns = []; + for await (const page of paginateListTasks({ client: ecs, pageSize: 100, stopOnSameToken: true }, { + cluster: config.cluster, serviceName: live.serviceName, desiredStatus: "RUNNING", + })) arns.push(...(page.taskArns || [])); + if (new Set(arns).size !== live.desiredCount || arns.length !== live.desiredCount) throw new Error("Every running backend task must be accounted for"); + for (let offset = 0; offset < arns.length; offset += 100) { + const batch = arns.slice(offset, offset + 100); + const out = await ecs.send(new DescribeTasksCommand({ cluster: config.cluster, tasks: batch })); + if (out.failures?.length || out.tasks?.length !== batch.length || new Set(out.tasks.map((t) => t.taskArn)).size !== batch.length) { + throw new Error("Every running backend task must be described"); + } + for (const task of out.tasks) { + if (!batch.includes(task.taskArn) || task.taskDefinitionArn !== live.taskDefinition || task.group !== `service:${live.serviceName}` || + task.lastStatus !== "RUNNING" || task.desiredStatus !== "RUNNING" || task.containers?.length !== 1 || task.containers[0].name !== "backend" || + task.containers[0].image !== definition.containerDefinitions[0].image || + (definition.containerDefinitions[0].healthCheck && task.healthStatus !== "HEALTHY") || + task.overrides?.containerOverrides?.some((c) => Object.keys(c).some((k) => k !== "name"))) { + throw new Error("Every backend task must use the verified image and unmodified service configuration"); + } + } + } +} + +async function alarms(clients, config) { + const out = await clients.cloudwatch.send(new DescribeAlarmsCommand({ AlarmNamePrefix: `${config.prefix}-backend-`, StateValue: "ALARM" })); + if (out.MetricAlarms?.length || out.CompositeAlarms?.length) throw new Error("Backend alarm fired during configuration rollout"); +} + +async function observe(clients, config, definition, count, sleep, report) { + for (let waited = 0; waited <= 300; waited += 15) { + stable(await service(clients.ecs, config), definition.taskDefinitionArn, count); + await alarms(clients, config); + if (waited < 300) await sleep(15000); + } + await verifyTasks(clients.ecs, config, await service(clients.ecs, config), definition); + report("Backend configuration baked for 300s; every running task verified"); +} + +async function configure(clients, config, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), report = console.log) { + const live = await service(clients.ecs, config); + stable(live, live.taskDefinition); + const source = await describe(clients.ecs, live.taskDefinition); + const definition = source.definition; + const container = definition.containerDefinitions?.[0]; + const variant = tagValue(source.tags, "warmbly-image-variant"); + if (tagValue(source.tags, "warmbly-release") !== config.tag || !["default", "kafka"].includes(variant) || + definition.family !== `${config.prefix}-backend` || definition.containerDefinitions?.length !== 1 || container.name !== "backend") { + throw new Error("Live backend must identify the selected release, family and image variant"); + } + const digest = config.images.images?.[`backend${variant === "kafka" ? "-kafka" : ""}`]; + if (config.images.registry !== "ghcr.io/warmbly/warmbly" || !/^sha256:[a-f0-9]{64}$/.test(digest || "") || + container.image !== `${config.images.registry}/backend@${digest}`) throw new Error("Live backend image must match the attested release digest"); + if (container.secrets?.some((s) => s.name === ATTACHMENT_PROXY)) throw new Error("Attachment proxy flag must not be secret-backed"); + const values = (container.environment || []).filter((e) => e.name === ATTACHMENT_PROXY); + const managed = tagValue(source.tags, ATTACHMENT_PROXY_TAG); + if (values.length > 1 || (values.length && !["true", "false"].includes(values[0].value)) || + (managed !== undefined && (values.length !== 1 || managed !== values[0].value))) throw new Error("Attachment proxy configuration is ambiguous"); + await verifyTasks(clients.ecs, config, live, definition); + await alarms(clients, config); + if ((values[0]?.value || "false") === config.value) { + report("Backend already has the requested attachment configuration; no change"); + await observe(clients, config, definition, live.desiredCount, sleep, report); + return { taskDefinition: live.taskDefinition, previous: live.taskDefinition, changed: false }; + } + if (live.taskDefinition !== config.expected) throw new Error("Expected backend revision changed; inspect it before requesting a configuration change"); + const rendered = structuredClone(definition); + rendered.containerDefinitions[0].environment = (container.environment || []).filter((e) => e.name !== ATTACHMENT_PROXY); + rendered.containerDefinitions[0].environment.push({ name: ATTACHMENT_PROXY, value: config.value }); + const tags = source.tags.filter((t) => t.key !== ATTACHMENT_PROXY_TAG); + tags.push({ key: ATTACHMENT_PROXY_TAG, value: config.value }); + const latest = await describe(clients.ecs, definition.family); + const prepared = same(latest.definition, rendered) && canonicalTags(latest.tags) === canonicalTags(tags); + const next = prepared ? latest.definition.taskDefinitionArn : await register(clients.ecs, source, rendered, tags, config.tag, report); + stable(await service(clients.ecs, config), live.taskDefinition, live.desiredCount); + try { + await clients.ecs.send(new UpdateServiceCommand({ cluster: config.cluster, service: live.serviceName, taskDefinition: next })); + await waitForService(clients.ecs, config, "backend", next, sleep); + await observe(clients, config, { ...rendered, taskDefinitionArn: next }, live.desiredCount, sleep, report); + return { taskDefinition: next, previous: live.taskDefinition, changed: true }; + } catch (error) { + try { + const current = await service(clients.ecs, config); + if (![live.taskDefinition, next].includes(current.taskDefinition) || current.desiredCount !== live.desiredCount) { + throw new Error("Backend changed concurrently; automatic rollback refused"); + } + if (current.taskDefinition === next) await clients.ecs.send(new UpdateServiceCommand({ cluster: config.cluster, service: live.serviceName, taskDefinition: live.taskDefinition })); + await waitForService(clients.ecs, config, "backend", live.taskDefinition, sleep); + await verifyTasks(clients.ecs, config, await service(clients.ecs, config), definition); + report("Restored and verified the exact previous backend revision"); + } catch { + throw new Error("Configuration rollout failed and rollback could not be verified; inspect the backend before any further change", { cause: error }); + } + throw error; + } +} + +if (require.main === module) { + const region = { region: "us-east-1", maxAttempts: 3 }; + const clients = { ecs: new ECSClient(region), cloudwatch: new CloudWatchClient(region) }; + const lines = []; + const report = (line) => { console.log(line); lines.push(line); }; + Promise.resolve().then(() => configure(clients, configuration(process.env), undefined, report)).catch((error) => { + const message = error?.$metadata ? `AWS request failed: ${error.name}` : error.message; + report(`Failed: ${message}`); + process.exitCode = 1; + }).finally(() => { + if (process.env.GITHUB_STEP_SUMMARY) require("node:fs").appendFileSync(process.env.GITHUB_STEP_SUMMARY, `### Backend configuration\n\n\`\`\`\n${lines.join("\n")}\n\`\`\`\n`); + for (const client of Object.values(clients)) client.destroy(); + }); +} + +module.exports = { configuration, configure }; diff --git a/.github/scripts/aws-backend-config.test.cjs b/.github/scripts/aws-backend-config.test.cjs new file mode 100644 index 000000000..937733026 --- /dev/null +++ b/.github/scripts/aws-backend-config.test.cjs @@ -0,0 +1,183 @@ +const { test } = require("node:test"); +const assert = require("node:assert/strict"); +const { mkdtempSync, writeFileSync, rmSync } = require("node:fs"); +const { tmpdir } = require("node:os"); +const { join } = require("node:path"); +const { ECSClient } = require("@aws-sdk/client-ecs"); +const { configuration, configure } = require("./aws-backend-config.cjs"); +const { REGISTER_FIELDS, ATTACHMENT_PROXY, ATTACHMENT_PROXY_TAG } = require("./aws-deploy.cjs"); + +const root = "arn:aws:ecs:us-east-1:000000000000:"; +const arn = (revision) => `${root}task-definition/fixture-backend:${revision}`; +const image = `ghcr.io/warmbly/warmbly/backend@sha256:${"a".repeat(64)}`; + +function fixture(t, options = {}) { + const dir = mkdtempSync(join(tmpdir(), "backend-config-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const manifest = { tag: "v0.6.75", registry: "ghcr.io/warmbly/warmbly", images: { "backend-kafka": `sha256:${"a".repeat(64)}` } }; + writeFileSync(join(dir, "images.json"), JSON.stringify(manifest)); + const env = { AWS_ECS_CLUSTER: root + "cluster/fixture", DEPLOY_TAG: manifest.tag, DEPLOY_IMAGES_JSON: join(dir, "images.json"), + CONFIG_EXPECTED_TASK_DEFINITION: arn(1), CONFIG_ATTACHMENT_DOWNLOAD_PROXY: "true" }; + const cfg = configuration(env); + const live = { serviceName: "fixture-backend", status: "ACTIVE", taskDefinition: arn(1), desiredCount: 2, runningCount: 2, pendingCount: 0, + deployments: [{ rolloutState: "COMPLETED" }] }; + const base = { family: "fixture-backend", status: "ACTIVE", revision: 1, taskDefinitionArn: arn(1), + taskRoleArn: root + "role/task", executionRoleArn: root + "role/execution", networkMode: "awsvpc", cpu: "256", memory: "512", + requiresCompatibilities: ["FARGATE"], runtimePlatform: { cpuArchitecture: "ARM64", operatingSystemFamily: "LINUX" }, + ephemeralStorage: { sizeInGiB: 30 }, volumes: [{ name: "fixture" }], + containerDefinitions: [{ name: "backend", image, stopTimeout: 120, readonlyRootFilesystem: true, + environment: [{ name: "TLS_ONLY", value: "true" }], + secrets: [{ name: "PRIMARY_DB", valueFrom: "fixture:immutable-version" }], + healthCheck: { command: ["CMD", "/app/healthcheck"], interval: 30, retries: 3 }, + logConfiguration: { logDriver: "awslogs", options: { "awslogs-group": "/fixture" } } }] }; + const tags = [{ key: "warmbly-release", value: manifest.tag }, { key: "warmbly-image-variant", value: "kafka" }, { key: "Owner", value: "fixture" }]; + const defs = new Map([[arn(1), { definition: base, tags }]]); + const calls = []; + const sleeps = []; + let latest = arn(1); + const ecs = new ECSClient({ region: "us-east-1" }); + t.after(() => ecs.destroy()); + ecs.send = async (command) => { + const name = command.constructor.name; + calls.push({ name, input: structuredClone(command.input) }); + if (options.hook) await options.hook(name, { live, defs, calls }); + switch (name) { + case "DescribeServicesCommand": return { services: [structuredClone(live)] }; + case "DescribeTaskDefinitionCommand": { + const entry = defs.get(command.input.taskDefinition === "fixture-backend" ? latest : command.input.taskDefinition); + return { taskDefinition: structuredClone(entry.definition), tags: structuredClone(entry.tags) }; + } + case "ListTasksCommand": + if (options.pagination && !command.input.nextToken) return { taskArns: [root + "task/fixture/one"], nextToken: "next" }; + return { taskArns: options.pagination ? [root + "task/fixture/two"] : [root + "task/fixture/one", root + "task/fixture/two"] }; + case "DescribeTasksCommand": return { tasks: command.input.tasks.map((taskArn) => ({ + taskArn, taskDefinitionArn: options.wrongTask ? arn(99) : live.taskDefinition, + group: "service:fixture-backend", lastStatus: "RUNNING", desiredStatus: options.drainingTask ? "STOPPED" : "RUNNING", healthStatus: options.unhealthyTask ? "UNHEALTHY" : "HEALTHY", + containers: [{ name: "backend", image }], overrides: { containerOverrides: options.override ? [{ name: "backend", command: ["other"] }] : [{ name: "backend" }] }, + })) }; + case "RegisterTaskDefinitionCommand": { + latest = arn(defs.size + 1); + const { tags: nextTags, ...input } = structuredClone(command.input); + defs.set(latest, { definition: { ...input, status: "ACTIVE", taskDefinitionArn: latest }, tags: nextTags }); + return { taskDefinition: { taskDefinitionArn: latest } }; + } + case "UpdateServiceCommand": { + live.taskDefinition = command.input.taskDefinition; + if (options.failedRoll && live.taskDefinition !== arn(1)) live.deployments = [{ rolloutState: "FAILED" }]; + else live.deployments = [{ rolloutState: "COMPLETED" }]; + return {}; + } + default: throw new Error(`Unexpected ${name}`); + } + }; + const cloudwatch = { async send(command) { + calls.push({ name: command.constructor.name, input: structuredClone(command.input) }); + return { MetricAlarms: options.alarm && live.taskDefinition !== arn(1) ? [{ AlarmName: "fixture-backend-5xx" }] : [] }; + } }; + const run = () => configure({ ecs, cloudwatch }, cfg, async (ms) => sleeps.push(ms), () => {}); + return { env, cfg, live, base, tags, defs, calls, sleeps, run }; +} + +const mutations = (f) => f.calls.filter((c) => ["RegisterTaskDefinitionCommand", "UpdateServiceCommand"].includes(c.name)); + +test("only the allowlisted flag and ownership tag change; every live task is checked and a full bake completes", async (t) => { + const f = fixture(t, { pagination: true }); + const previous = structuredClone(f.base); + const result = await f.run(); + assert.equal(result.changed, true); + const registration = f.calls.find((c) => c.name === "RegisterTaskDefinitionCommand").input; + for (const field of REGISTER_FIELDS.filter((field) => field !== "containerDefinitions")) assert.deepEqual(registration[field], previous[field]); + const container = structuredClone(registration.containerDefinitions[0]); + assert.deepEqual(container.environment.pop(), { name: ATTACHMENT_PROXY, value: "true" }); + assert.deepEqual(container, previous.containerDefinitions[0]); + assert.deepEqual(Object.fromEntries(registration.tags.map((tag) => [tag.key, tag.value])), + Object.fromEntries([...f.tags, { key: ATTACHMENT_PROXY_TAG, value: "true" }].map((tag) => [tag.key, tag.value]))); + assert.deepEqual(f.calls.filter((c) => c.name === "UpdateServiceCommand").map((c) => c.input), [{ cluster: f.cfg.cluster, service: "fixture-backend", taskDefinition: arn(2) }]); + assert.equal(f.sleeps.reduce((a, b) => a + b, 0), 300000); + assert.equal(f.calls.filter((c) => c.name === "DescribeAlarmsCommand").length, 22); + assert.ok(f.calls.some((c) => c.name === "ListTasksCommand" && c.input.nextToken === "next")); + const count = mutations(f).length; + assert.equal((await f.run()).changed, false); + assert.equal(mutations(f).length, count, "repeated request is a no-op even with its original expected revision"); + assert.equal(f.sleeps.reduce((a, b) => a + b, 0), 600000, "an interrupted bake is always observed afresh without rolling again"); +}); + +test("disabling is explicit and preserves the remainder of the running definition", async (t) => { + const f = fixture(t); + await f.run(); + f.cfg.expected = arn(2); + f.cfg.value = "false"; + await f.run(); + const current = f.defs.get(arn(3)); + assert.equal(current.definition.containerDefinitions[0].environment.find((e) => e.name === ATTACHMENT_PROXY).value, "false"); + assert.equal(current.tags.find((tag) => tag.key === ATTACHMENT_PROXY_TAG).value, "false"); +}); + +for (const [name, options, mutate] of [ + ["mixed task definitions", { wrongTask: true }], ["unhealthy task", { unhealthyTask: true }], ["task override", { override: true }], + ["draining task", { drainingTask: true }], + ["stale expected revision", {}, (f) => { f.cfg.expected = arn(99); }], + ["wrong image", {}, (f) => { f.base.containerDefinitions[0].image += "bad"; }], + ["wrong release", {}, (f) => { f.tags[0].value = "v0.6.74"; }], + ["missing variant", {}, (f) => { f.tags.splice(1, 1); }], + ["zero tasks", {}, (f) => { f.live.desiredCount = f.live.runningCount = 0; }], + ["active rollout", {}, (f) => { f.live.deployments[0].rolloutState = "IN_PROGRESS"; }], + ["duplicate flag", {}, (f) => { f.base.containerDefinitions[0].environment.push(...["true", "false"].map((value) => ({ name: ATTACHMENT_PROXY, value }))); }], + ["secret-backed flag", {}, (f) => { f.base.containerDefinitions[0].secrets.push({ name: ATTACHMENT_PROXY, valueFrom: "secret" }); }], + ["mismatched ownership tag", {}, (f) => { f.tags.push({ key: ATTACHMENT_PROXY_TAG, value: "true" }); }], +]) test(`${name} is refused before mutations`, async (t) => { + const f = fixture(t, options); + mutate?.(f); + await assert.rejects(f.run()); + assert.deepEqual(mutations(f), []); +}); + +for (const options of [{ alarm: true }, { failedRoll: true }]) test(`${JSON.stringify(options)} restores and verifies the exact prior revision`, async (t) => { + const f = fixture(t, options); + await assert.rejects(f.run()); + assert.equal(f.live.taskDefinition, arn(1)); + assert.deepEqual(f.calls.filter((c) => c.name === "UpdateServiceCommand").map((c) => c.input.taskDefinition), [arn(2), arn(1)]); + assert.equal(f.calls.at(-1).name, "DescribeTasksCommand"); +}); + +test("a concurrent change before update is preserved", async (t) => { + const f = fixture(t, { hook: (name, { live, calls }) => { + if (name === "DescribeServicesCommand" && calls.some((c) => c.name === "RegisterTaskDefinitionCommand")) live.taskDefinition = arn(99); + } }); + await assert.rejects(f.run(), /expected revision/); + assert.equal(f.calls.filter((c) => c.name === "UpdateServiceCommand").length, 0); + assert.equal(f.live.taskDefinition, arn(99)); +}); + +test("a concurrent change during the bake is never overwritten by rollback", async (t) => { + const f = fixture(t, { hook: (name, { live, calls }) => { + if (name === "DescribeServicesCommand" && calls.some((c) => c.name === "UpdateServiceCommand")) live.taskDefinition = arn(99); + } }); + await assert.rejects(f.run(), /rollback could not be verified/); + assert.equal(f.calls.filter((c) => c.name === "UpdateServiceCommand").length, 1); + assert.equal(f.live.taskDefinition, arn(99)); +}); + +test("a prepared identical revision is reused after interruption before the service update", async (t) => { + let interrupt = true; + const f = fixture(t, { hook: (name, { calls }) => { + if (interrupt && name === "DescribeServicesCommand" && calls.some((c) => c.name === "RegisterTaskDefinitionCommand")) { + interrupt = false; + throw new Error("interrupted before update"); + } + } }); + await assert.rejects(f.run(), /interrupted/); + await f.run(); + assert.equal(f.calls.filter((c) => c.name === "RegisterTaskDefinitionCommand").length, 1); +}); + +test("configuration requires a supported release, exact backend ARN and explicit boolean", (t) => { + const f = fixture(t); + for (const overrides of [ + { DEPLOY_TAG: "v0.6.74" }, { DEPLOY_TAG: "" }, { CONFIG_ATTACHMENT_DOWNLOAD_PROXY: "yes" }, + { CONFIG_EXPECTED_TASK_DEFINITION: arn(1).replace("fixture-backend", "fixture-consumer") }, + { CONFIG_EXPECTED_TASK_DEFINITION: arn(1).replace("000000000000", "111111111111") }, + ]) assert.throws(() => configuration({ ...f.env, ...overrides })); + assert.equal(configuration({ ...f.env, DEPLOY_BAKE_SECONDS: "0", DEPLOY_FLEET: "true" }).bake, 300); + assert.equal(configuration(f.env).fleet, false); +}); diff --git a/.github/scripts/aws-deploy.cjs b/.github/scripts/aws-deploy.cjs index b344e098a..731bda184 100644 --- a/.github/scripts/aws-deploy.cjs +++ b/.github/scripts/aws-deploy.cjs @@ -21,6 +21,8 @@ const VARIANT_TAG = "warmbly-image-variant"; const TAG_RE = /^v(\d+)\.(\d+)\.(\d+)$/; const DIGEST_RE = /^sha256:[a-f0-9]{64}$/; const VERSION_RE = /^[A-Za-z0-9-]{32,64}$/; +const ATTACHMENT_PROXY = "CAMPAIGN_ATTACHMENT_DOWNLOAD_PROXY"; +const ATTACHMENT_PROXY_TAG = "warmbly-config-attachment-download-proxy"; function configuration(env) { const cluster = env.AWS_ECS_CLUSTER; @@ -136,10 +138,12 @@ function same(a, b) { return JSON.stringify(REGISTER_FIELDS.map((f) => a[f] ?? null)) === JSON.stringify(REGISTER_FIELDS.map((f) => b[f] ?? null)); } +const canonicalTags = (tags) => JSON.stringify(tags.filter((t) => !t.key.startsWith("aws:")).sort((a, b) => a.key.localeCompare(b.key))); + async function register(client, source, rendered, tags, release, report) { const carried = tags.filter((t) => t.key !== RELEASE_TAG && !t.key.startsWith("aws:")); if (release) carried.push({ key: RELEASE_TAG, value: release }); - if (same(source.definition, rendered) && tagValue(source.tags, RELEASE_TAG) === release) return source.definition.taskDefinitionArn; + if (same(source.definition, rendered) && canonicalTags(source.tags) === canonicalTags(carried)) return source.definition.taskDefinitionArn; const input = {}; for (const f of REGISTER_FIELDS) if (rendered[f] !== undefined && rendered[f] !== null) input[f] = rendered[f]; input.tags = carried; @@ -248,6 +252,38 @@ function imageFor(config, key, fallback) { return `${config.images.registry}/${key.replace(/-kafka$/, "")}@${digest}`; } +function preserveBackendConfiguration(source, live, rendered, release) { + const managed = tagValue(live.tags, ATTACHMENT_PROXY_TAG); + const explicitValues = source.definition.containerDefinitions[0].environment?.filter((e) => e.name === ATTACHMENT_PROXY) || []; + const explicit = explicitValues[0]; + const sourceManaged = tagValue(source.tags, ATTACHMENT_PROXY_TAG); + const current = live.definition.containerDefinitions[0].environment?.filter((e) => e.name === ATTACHMENT_PROXY) || []; + if (explicitValues.length > 1 || source.definition.containerDefinitions[0].secrets?.some((s) => s.name === ATTACHMENT_PROXY) || + (sourceManaged !== undefined && (explicitValues.length !== 1 || sourceManaged !== explicit.value))) { + throw new Error("Backend attachment source configuration is ambiguous"); + } + if (managed !== undefined) { + if (!["true", "false"].includes(managed) || current.length !== 1 || current[0].value !== managed) { + throw new Error("Backend attachment configuration tag and environment must agree"); + } + } + // An explicit Terraform value takes ownership; otherwise the live managed value survives rendering. + const value = explicit && sourceManaged === undefined ? explicit.value + : managed ?? (sourceManaged !== undefined ? current[0]?.value || "false" : undefined); + if (value !== undefined && !["true", "false"].includes(value)) throw new Error("Backend attachment configuration must be true or false"); + if (value === "true" && compareTags(release, "v0.6.75") < 0) { + throw new Error("Disable the attachment proxy explicitly before deploying a release older than v0.6.75"); + } + const tags = source.tags.filter((t) => t.key !== ATTACHMENT_PROXY_TAG); + if (value !== undefined) { + const container = rendered.containerDefinitions[0]; + container.environment = (container.environment || []).filter((e) => e.name !== ATTACHMENT_PROXY); + container.environment.push({ name: ATTACHMENT_PROXY, value }); + if (!(explicit && sourceManaged === undefined) && managed !== undefined) tags.push({ key: ATTACHMENT_PROXY_TAG, value }); + } + return tags; +} + async function deploy(clients, config, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), report = console.log) { const ecs = clients.ecs; const names = SERVICES.map((s) => `${config.prefix}-${s}`); @@ -313,6 +349,7 @@ async function deploy(clients, config, sleep = (ms) => new Promise((r) => setTim }; const backendKey = deployBackend || families.includes("ops") ? `backend${variant(deployBackend ? "backend" : "ops") === "kafka" ? "-kafka" : ""}` : null; const rendered = {}; + const renderedTags = {}; for (const name of families) { const def = structuredClone(sources[name].definition); const container = def.containerDefinitions?.[0]; @@ -328,6 +365,9 @@ async function deploy(clients, config, sleep = (ms) => new Promise((r) => setTim } else if (name !== "validation") { container.image = imageFor(config, backendKey, liveDefs.backend.definition.containerDefinitions[0].image); } + renderedTags[name] = name === "backend" + ? preserveBackendConfiguration(sources[name], liveDefs.backend, def, tag) + : sources[name].tags; rendered[name] = def; } @@ -349,7 +389,7 @@ async function deploy(clients, config, sleep = (ms) => new Promise((r) => setTim } const arns = {}; - for (const name of families) arns[name] = await register(ecs, sources[name], rendered[name], sources[name].tags, tag, report); + for (const name of families) arns[name] = await register(ecs, sources[name], rendered[name], renderedTags[name], tag, report); const network = backend.networkConfiguration; if (arns.validation) await runTask(clients, config, network, arns.validation, rendered.validation, "Dependency check", sleep, report); @@ -423,4 +463,5 @@ if (require.main === module) { }); } -module.exports = { configuration, deploy, runTask, describe, compareTags, parseRef, secretService, SERVICES }; +module.exports = { configuration, deploy, runTask, describe, compareTags, parseRef, secretService, SERVICES, + REGISTER_FIELDS, same, register, waitForService, ATTACHMENT_PROXY, ATTACHMENT_PROXY_TAG }; diff --git a/.github/scripts/aws-deploy.test.cjs b/.github/scripts/aws-deploy.test.cjs index 3609b4964..fcb86ec89 100644 --- a/.github/scripts/aws-deploy.test.cjs +++ b/.github/scripts/aws-deploy.test.cjs @@ -3,7 +3,7 @@ const assert = require("node:assert/strict"); const { mkdtempSync, writeFileSync } = require("node:fs"); const { join } = require("node:path"); const { tmpdir } = require("node:os"); -const { configuration, deploy, runTask, compareTags, parseRef } = require("./aws-deploy.cjs"); +const { configuration, deploy, runTask, compareTags, parseRef, ATTACHMENT_PROXY, ATTACHMENT_PROXY_TAG } = require("./aws-deploy.cjs"); const root = "arn:aws:ecs:us-east-1:000000000000:"; const registry = "ghcr.io/warmbly/warmbly"; @@ -178,6 +178,56 @@ test("a release renders from the latest revision, swaps variant digests and carr } }); +function manageAttachments(f, revision, value) { + const arn = `${root}task-definition/fixture-backend:${revision}`; + f.defs[arn].containerDefinitions[0].environment.push({ name: ATTACHMENT_PROXY, value }); + f.tagsOf[arn].push({ key: ATTACHMENT_PROXY_TAG, value }); +} + +for (const mode of ["deploy", "refresh-secrets"]) test(`${mode} preserves the live managed attachment setting`, async () => { + const f = fixture(); + manageAttachments(f, 1, "true"); + await run(f, config({ DEPLOY_MODE: mode })); + const backend = registered(f).find((r) => r.family === "fixture-backend"); + assert.deepEqual(backend.containerDefinitions[0].environment.filter((e) => e.name === ATTACHMENT_PROXY), [{ name: ATTACHMENT_PROXY, value: "true" }]); + assert.equal(backend.tags.find((t) => t.key === ATTACHMENT_PROXY_TAG).value, "true"); + assert.ok(registered(f).filter((r) => r.family !== "fixture-backend").every((r) => !r.tags.some((t) => t.key === ATTACHMENT_PROXY_TAG))); +}); + +test("an explicit Terraform attachment value takes ownership", async () => { + const f = fixture(); + manageAttachments(f, 1, "true"); + f.defs[`${root}task-definition/fixture-backend:2`].containerDefinitions[0].environment.push({ name: ATTACHMENT_PROXY, value: "false" }); + await run(f, config()); + const backend = registered(f).find((r) => r.family === "fixture-backend"); + assert.equal(backend.containerDefinitions[0].environment.find((e) => e.name === ATTACHMENT_PROXY).value, "false"); + assert.ok(!backend.tags.some((t) => t.key === ATTACHMENT_PROXY_TAG)); +}); + +test("an attachment configuration prepared but never activated is not adopted by a release", async () => { + const f = fixture(); + manageAttachments(f, 2, "true"); + await run(f, config()); + const backend = registered(f).find((r) => r.family === "fixture-backend"); + assert.equal(backend.containerDefinitions[0].environment.find((e) => e.name === ATTACHMENT_PROXY).value, "false"); + assert.ok(!backend.tags.some((t) => t.key === ATTACHMENT_PROXY_TAG)); +}); + +test("managed attachment configuration must agree with its environment", async () => { + const f = fixture(); + manageAttachments(f, 1, "true"); + f.defs[`${root}task-definition/fixture-backend:1`].containerDefinitions[0].environment.find((e) => e.name === ATTACHMENT_PROXY).value = "false"; + await assert.rejects(run(f, config()), /tag and environment must agree/); + assert.equal(registered(f).length, 0); +}); + +test("a rollback below route support requires explicitly disabling the attachment proxy", async () => { + const f = fixture({ liveTag: "v0.6.75" }); + manageAttachments(f, 1, "true"); + await assert.rejects(run(f, config({ DEPLOY_TAG: "v0.6.74", DEPLOY_MODE: "rollback" })), /Disable the attachment proxy explicitly/); + assert.equal(registered(f).length, 0); +}); + test("the newest pinned secret version wins so a stale Terraform pin cannot undo a rotation", async () => { const f = fixture(); await run(f, config()); diff --git a/.github/scripts/terraform-stack.sh b/.github/scripts/terraform-stack.sh index 5165ad581..a128be91e 100755 --- a/.github/scripts/terraform-stack.sh +++ b/.github/scripts/terraform-stack.sh @@ -10,14 +10,14 @@ # # plan writes $WORK/.summary (one "action address" per line) and prints # safe, gated or none. Safe means only creates, in-place updates, and new -# revisions of task definitions, excluding protected recovery evidence IAM changes. +# revisions of task definitions, excluding protected deployment and evidence IAM changes. set -euo pipefail classify() { jq -r ' [.resource_changes[]? | select(.change.actions != ["no-op"] and .change.actions != ["read"])] as $c | if ($c | length) == 0 then "none" - elif any($c[]; .name == "tls_recovery_evidence" and + elif any($c[]; (.name == "tls_recovery_evidence" or .name == "github_deploy") and (.type == "aws_iam_role" or .type == "aws_iam_role_policy")) then "gated" elif any($c[]; (.change.actions | index("delete")) and ((.type == "aws_ecs_task_definition" and (.change.actions | length) == 2) | not)) then "gated" diff --git a/.github/scripts/terraform-stack.test.sh b/.github/scripts/terraform-stack.test.sh index d7f978dc8..536315e73 100755 --- a/.github/scripts/terraform-stack.test.sh +++ b/.github/scripts/terraform-stack.test.sh @@ -20,12 +20,15 @@ check() { for type in aws_iam_role aws_iam_role_policy; do for actions in '["create"]' '["update"]' '["delete"]' '["delete","create"]'; do check gated "$type" tls_recovery_evidence "$actions" + check gated "$type" github_deploy "$actions" done check none "$type" tls_recovery_evidence '["no-op"]' check none "$type" tls_recovery_evidence '["read"]' + check none "$type" github_deploy '["no-op"]' + check none "$type" github_deploy '["read"]' done check safe aws_iam_role existing_role '["create"]' check safe aws_ecs_task_definition service '["delete","create"]' check gated aws_lb_target_group service '["delete"]' check safe aws_cloudwatch_metric_alarm service '["update"]' -echo 'Protected evidence IAM changes require approval; existing plan classifications remain unchanged' +echo 'Deployment and evidence IAM changes require approval; existing plan classifications remain unchanged' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index db26fc059..6f1d41fe9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -70,8 +70,10 @@ jobs: aws-deployment: - '.github/workflows/ci.yml' - '.github/workflows/deploy-aws.yml' + - '.github/workflows/configure-backend-aws.yml' - '.github/workflows/rotate-keys.yml' - '.github/scripts/aws-deploy*.cjs' + - '.github/scripts/aws-backend-config*.cjs' - '.github/scripts/aws-rotate*.cjs' - '.github/aws-deploy/**' - 'deploy/terraform/aws/runtime/rotate/**' @@ -1089,7 +1091,7 @@ jobs: - name: Check deploy, rollback and rotation gates env: NODE_PATH: ${{ github.workspace }}/.github/aws-deploy/node_modules - run: node --test .github/scripts/aws-deploy.test.cjs .github/scripts/aws-rotate.test.cjs deploy/terraform/aws/runtime/rotate/rotate.test.cjs + run: node --test .github/scripts/aws-deploy.test.cjs .github/scripts/aws-backend-config.test.cjs .github/scripts/aws-rotate.test.cjs deploy/terraform/aws/runtime/rotate/rotate.test.cjs ci-status: name: CI Status diff --git a/.github/workflows/configure-backend-aws.yml b/.github/workflows/configure-backend-aws.yml new file mode 100644 index 000000000..00ceb4806 --- /dev/null +++ b/.github/workflows/configure-backend-aws.yml @@ -0,0 +1,84 @@ +name: Configure AWS backend + +on: + workflow_dispatch: + inputs: + tag: + description: Published stable release already running on every backend (v0.6.75 or newer) + required: true + type: string + expected_task_definition: + description: Exact currently running backend task definition ARN + required: true + type: string + attachment_download_proxy: + description: Serve private campaign attachments through the backend download route + required: true + type: boolean + +permissions: + contents: read + +jobs: + configure: + runs-on: ubuntu-latest + timeout-minutes: 45 + environment: aws-production + concurrency: + group: aws-production + cancel-in-progress: false + permissions: + contents: read + attestations: read + id-token: write + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + fetch-depth: 0 + - name: Verify main and the published release provenance + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ inputs.tag }} + ENABLED: ${{ vars.AWS_DEPLOY_ENABLED }} + run: | + set -euo pipefail + [ "$GITHUB_REF" = refs/heads/main ] && [ "$ENABLED" = true ] || { + echo "::error::Backend configuration requires main and AWS_DEPLOY_ENABLED=true"; exit 1; } + printf '%s\n' "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$' || { + echo "::error::A stable release tag is required"; exit 1; } + git merge-base --is-ancestor "refs/tags/$TAG^{commit}" origin/main + state=$(gh release view "$TAG" --json isDraft,isPrerelease --jq '"\(.isDraft) \(.isPrerelease)"') + [ "$state" = "false false" ] || { echo "::error::A published stable release is required"; exit 1; } + mkdir -p /tmp/backend-config-release + gh release download "$TAG" --pattern images.json --dir /tmp/backend-config-release + manifest=/tmp/backend-config-release/images.json + jq -e --arg tag "$TAG" '.tag == $tag and .registry == "ghcr.io/warmbly/warmbly"' "$manifest" >/dev/null + registry=$(jq -r .registry "$manifest") + for key in backend backend-kafka consumer consumer-kafka worker worker-kafka forms tracking tracking-kafka realtime; do + digest=$(jq -er --arg key "$key" '.images[$key] | select(test("^sha256:[a-f0-9]{64}$"))' "$manifest") + gh attestation verify "oci://$registry/${key%-kafka}@$digest" \ + --repo "$GITHUB_REPOSITORY" \ + --signer-workflow "$GITHUB_REPOSITORY/.github/workflows/release.yml" \ + --source-ref "refs/tags/$TAG" >/dev/null + echo "verified provenance of $key" + done + - uses: actions/setup-node@v4 + with: + node-version: "22" + - name: Install deployment client + run: npm ci --prefix .github/aws-deploy --omit=dev --ignore-scripts --no-audit --no-fund + - uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: ${{ vars.AWS_DEPLOY_ROLE_ARN }} + aws-region: us-east-1 + - name: Configure and bake the backend + env: + NODE_PATH: ${{ github.workspace }}/.github/aws-deploy/node_modules + AWS_ECS_CLUSTER: ${{ vars.AWS_ECS_CLUSTER }} + AWS_ECS_SERVICE_PREFIX: ${{ vars.AWS_ECS_SERVICE_PREFIX }} + DEPLOY_TAG: ${{ inputs.tag }} + DEPLOY_IMAGES_JSON: /tmp/backend-config-release/images.json + CONFIG_EXPECTED_TASK_DEFINITION: ${{ inputs.expected_task_definition }} + CONFIG_ATTACHMENT_DOWNLOAD_PROXY: ${{ inputs.attachment_download_proxy }} + run: node .github/scripts/aws-backend-config.cjs diff --git a/.github/workflows/terraform-aws.yml b/.github/workflows/terraform-aws.yml index 05bc6de0e..3540280ed 100644 --- a/.github/workflows/terraform-aws.yml +++ b/.github/workflows/terraform-aws.yml @@ -1,7 +1,7 @@ name: Terraform AWS # Pull requests get a plan summary comment. On main, a stack whose plan only -# creates or updates applies on its own; destructive or protected evidence IAM +# creates or updates applies on its own; destructive or protected deployment/evidence IAM # changes wait in aws-infrastructure-approval. Var files live in the private # state bucket, and no plan body ever reaches a log, a comment or an artifact. on: diff --git a/deploy/terraform/aws/runtime/README.md b/deploy/terraform/aws/runtime/README.md index 5e09be92b..74a76ad78 100644 --- a/deploy/terraform/aws/runtime/README.md +++ b/deploy/terraform/aws/runtime/README.md @@ -28,7 +28,19 @@ service creation, and its task definition outputs describe prepared revisions, not necessarily running ones. Start new services at zero and use explicit counts when activating them. -`.github/workflows/deploy-aws.yml` owns only the image. A stable release tag on +`.github/workflows/deploy-aws.yml` selects the image and preserves the live managed +attachment-download setting unless Terraform explicitly supplies its environment +value. The opt-in `.github/workflows/configure-backend-aws.yml` changes only +`CAMPAIGN_ATTACHMENT_DOWNLOAD_PROXY` from a verified live backend definition, +using release provenance, individual task checks, a fixed 300-second bake and +verified rollback. Its `warmbly-config-attachment-download-proxy` task tag records +ownership across later deploys and secret refreshes. Explicit Terraform `true` or +`false` takes ownership; a rollback below v0.6.75 requires disabling the proxy +first and waiting for existing links to expire. The deploy role's cluster-scoped +`ecs:ListTasks` permission must be provisioned through infrastructure approval +before using this workflow. It does not provision permissions itself. + +A stable release tag on `main` reaches it from `release.yml` when the repository variable `AWS_DEPLOY_ENABLED` is `true`; dispatch it by hand to redeploy, roll back or roll out changed secret values. Each run verifies the release's build diff --git a/deploy/terraform/aws/runtime/ci.tf b/deploy/terraform/aws/runtime/ci.tf index 048a50ade..d065de582 100644 --- a/deploy/terraform/aws/runtime/ci.tf +++ b/deploy/terraform/aws/runtime/ci.tf @@ -90,6 +90,15 @@ data "aws_iam_policy_document" "github_deploy" { actions = ["ecs:DescribeTasks"] resources = ["${local.ecs_arn}:task/${var.name}/*"] } + statement { + actions = ["ecs:ListTasks"] + resources = ["*"] + condition { + test = "ArnEquals" + variable = "ecs:cluster" + values = [local.foundation.cluster_arn] + } + } statement { actions = ["ecs:RunTask"] resources = [for task in keys(local.github_tasks) : "${local.ecs_arn}:task-definition/${var.name}-${task}:*"] diff --git a/deploy/terraform/aws/runtime/tests/target_tls.tftest.hcl b/deploy/terraform/aws/runtime/tests/target_tls.tftest.hcl index 9315837f1..46cb205a5 100644 --- a/deploy/terraform/aws/runtime/tests/target_tls.tftest.hcl +++ b/deploy/terraform/aws/runtime/tests/target_tls.tftest.hcl @@ -75,6 +75,22 @@ variables { } } +run "deployment_inventory_is_cluster_scoped" { + command = plan + variables { + github_repository = "warmbly/warmbly" + } + assert { + condition = anytrue([for statement in data.aws_iam_policy_document.github_deploy[0].statement : + statement.actions == toset(["ecs:ListTasks"]) && statement.resources == toset(["*"]) && + anytrue([for condition in statement.condition : + condition.test == "ArnEquals" && condition.variable == "ecs:cluster" && condition.values == tolist([local.foundation.cluster_arn]) + ]) + ]) + error_message = "Deployment task inventory reads must be restricted to this runtime cluster." + } +} + run "off_is_unchanged" { command = apply variables { diff --git a/docs/content/docs/development/aws-fargate.mdx b/docs/content/docs/development/aws-fargate.mdx index a995d7560..f8d4a0289 100644 --- a/docs/content/docs/development/aws-fargate.mdx +++ b/docs/content/docs/development/aws-fargate.mdx @@ -204,7 +204,8 @@ Terraform applies share one queue, so only one change reaches production at a time and none is cancelled by the next. Terraform owns the shape of every task definition (environment, secret -references, sizes, health checks) and the workflow owns only the image. A deploy: +references, sizes, health checks). The deployment workflow selects images and +preserves the narrowly scoped attachment setting described below. A deploy: 1. Checks that the tag's commit is on `main`, that every image digest carries build provenance from the release workflow, and that the tag is not older @@ -270,6 +271,35 @@ check; dispatch those once with `require_attestation` off. The automatic redeploy after a Terraform apply cannot turn it off, so until a release with provenance is running it stops at that check and changes nothing. +### Configure private attachment downloads + +After every backend runs a published release at least `v0.6.75`, dispatch +**Configure AWS backend** on `main`. Supply the running release tag, exact live +backend task definition ARN and the desired `attachment_download_proxy` boolean. +The workflow requires `AWS_DEPLOY_ENABLED=true`, uses `aws-production` and shares +the deployment queue. Provision the runtime deploy role's cluster-scoped +`ecs:ListTasks` read permission through the normal infrastructure approval first. + +The operation verifies release provenance and every running backend task, then +clones the live definition and changes only `CAMPAIGN_ATTACHMENT_DOWNLOAD_PROXY`. +It preserves images, roles, secret references and version pins, TLS settings, +resources, health checks, stop timeout and desired count. It watches the stable +service and alarms for 300 seconds, verifies every resulting task, and restores +and verifies the exact previous revision on failure. A concurrent revision or +count change stops automatic rollback for operator inspection. It runs no +migration, one-off task or fleet rollout and does not modify another service. + +The task definition records the setting in +`warmbly-config-attachment-download-proxy`. Future deployments and secret +refreshes carry the live managed value when Terraform does not explicitly set +the environment variable. An explicit Terraform `true` or `false` value takes +ownership. A prepared revision that never reached the service cannot activate +the setting during a later release. To roll back below `v0.6.75`, explicitly +disable the proxy first; confirm existing download links have expired before +removing route support. Successful rollout is followed by an authorized download +check of the bytes and response headers. Self-host configuration remains opt-in +and defaults to `false`. + ## Rotate keys Dispatch **Rotate instance keys** from the Actions tab and choose a key and an @@ -332,8 +362,8 @@ plan reaches a log, a comment or an artifact. password, which the plan role may not. - On merge, each stack is planned in order: foundation, runtime, workers. A stack that only creates and updates applies on its own. One that replaces or - destroys anything, or changes the dedicated recovery evidence IAM role or its - inline policy, stops and waits for approval in the + destroys anything, or changes the deployment or dedicated recovery evidence + IAM roles or their inline policies, stops and waits for approval in the `aws-infrastructure-approval` environment, and the stacks after it wait too. On approval it plans again and applies only if the plan is still the one that was approved. A new task definition revision counts as an update, because the diff --git a/docs/content/docs/development/configuration.mdx b/docs/content/docs/development/configuration.mdx index 36d22d3b4..c123704d3 100644 --- a/docs/content/docs/development/configuration.mdx +++ b/docs/content/docs/development/configuration.mdx @@ -357,7 +357,7 @@ An empty `CREDENTIALS_ENCRYPTION_KEY` does not fail at boot. It disables sealing | `BLOB_FS_ROOT` | Directory for stored bodies, attachments, avatars and email body images. The backend, the consumer and every worker on the host must share it | `/data/blobs` | yes | | `BLOB_BUCKET` | Bucket name when `BLOB_PROVIDER=s3` | unset | yes | | `BLOB_PUBLIC_BASE_URL` | Public base for the backend's `/public` route. Images placed in an email body are served from here, so it has to be an address a recipient's mail client can reach | derived | yes | -| `CAMPAIGN_ATTACHMENT_DOWNLOAD_PROXY` | `true` serves private campaign downloads through the API with `nosniff`, attachment disposition and a 15-minute file-scoped capability. Upgrade every backend before enabling it | `false` | yes | +| `CAMPAIGN_ATTACHMENT_DOWNLOAD_PROXY` | `true` serves private campaign downloads through the API with `nosniff`, attachment disposition and a 15-minute file-scoped capability. Upgrade every backend before enabling it. Hosted operators can use the [scoped backend configuration workflow](/development/aws-fargate/#configure-private-attachment-downloads) | `false` | yes | | `AWS_REGION`, `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` | Credentials for S3 or SES | unset | yes | | `AWS_ENDPOINT_URL_S3` | Non-AWS S3 endpoint (MinIO, R2, B2) | unset | yes | | `AWS_CONFIG_ENABLED` | `true` reads secrets from AWS SSM or Secrets Manager | `false` | yes | From 8984e1ffdef937e60059d5c783b23c7b38781516 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 14:09:37 +0100 Subject: [PATCH 144/318] feat: keep campaign feeds, notifications and webhook delivery logs unless an operator sets a window, stop pruning tracking dedupe marks, cap warmup mail retirement at one 50-message share per mailbox per run, keep the sync recovery clock exact, and prune warmup thread turns in batches that respect each mailbox's own retention --- .../dashboard/configuration/SettingsTab.tsx | 20 +++--- .../docs/development/configuration.mdx | 6 +- .../content/docs/development/data-control.mdx | 6 +- docs/content/docs/guides/campaigns.mdx | 2 +- docs/content/docs/guides/notifications.mdx | 2 +- docs/content/docs/guides/webhooks.mdx | 2 +- .../app/consumer/warmup_mail_retention.go | 67 +++++++++++++++---- .../app/consumer/warmup_retention_test.go | 22 +++++- internal/app/instancesettings/document.go | 19 ++++-- internal/config/constants.go | 10 ++- internal/jobs/table_retention.go | 3 - internal/jobs/table_retention_test.go | 27 ++++++-- .../repository/pg_mail_transport_recovery.go | 4 +- internal/repository/pg_table_retention.go | 6 -- .../pg_table_retention_live_test.go | 18 ++--- internal/repository/pg_warmup.go | 37 ++++++---- .../sync_report_writes_live_test.go | 12 ++-- .../warmup_mail_retention_live_test.go | 6 +- 18 files changed, 173 insertions(+), 96 deletions(-) diff --git a/admin/src/app/dashboard/configuration/SettingsTab.tsx b/admin/src/app/dashboard/configuration/SettingsTab.tsx index 2291c948d..d6e84f725 100644 --- a/admin/src/app/dashboard/configuration/SettingsTab.tsx +++ b/admin/src/app/dashboard/configuration/SettingsTab.tsx @@ -115,22 +115,22 @@ const RETENTION_FIELDS = [ key: "campaignLogDays", setting: "campaign_log_days", label: "Campaign activity feed (days)", - min: RETENTION_MIN_DAYS, - 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.", + 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: RETENTION_MIN_DAYS, - help: "In-app notifications, read or unread. One still waiting to be emailed is kept until it is sent or skipped.", + 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: RETENTION_MIN_DAYS, - 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.", + 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; @@ -141,16 +141,16 @@ const RETENTION_PRESETS = [ { id: "default", label: "Defaults", - description: "365 / 180 / 90 days, warmup 30 / 365, feeds 365 / 180 / 90", + description: "365 / 180 / 90 days, warmup 30 / 365, feeds kept", values: { engagementDays: "365", formDays: "180", auditDays: "90", warmupMailDays: "30", warmupEventDays: "365", - campaignLogDays: "365", - notificationDays: "180", - webhookDeliveryDays: "90", + campaignLogDays: "0", + notificationDays: "0", + webhookDeliveryDays: "0", }, }, { diff --git a/docs/content/docs/development/configuration.mdx b/docs/content/docs/development/configuration.mdx index 3027e64d0..5beb2cee4 100644 --- a/docs/content/docs/development/configuration.mdx +++ b/docs/content/docs/development/configuration.mdx @@ -1121,9 +1121,9 @@ These are the only settings a browser can change, and no environment variable ow | `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, 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, 1 to 3650 | `365` | How long each campaign's activity feed keeps an entry. Campaign stats, progress and sent mail are separate and unaffected | -| `retention.notification_days` | integer, 1 to 3650 | `180` | How long in-app notifications are kept, read or unread. One still waiting to be emailed is kept until it is sent or skipped | -| `retention.webhook_delivery_days` | integer, 1 to 3650 | `90` | How long a settled webhook delivery (delivered or abandoned) stays in its endpoint's delivery log. A delivery still being retried is kept until it settles, and one past this window can no longer be redelivered | +| `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 | diff --git a/docs/content/docs/development/data-control.mdx b/docs/content/docs/development/data-control.mdx index 31f6c9b36..2340499cc 100644 --- a/docs/content/docs/development/data-control.mdx +++ b/docs/content/docs/development/data-control.mdx @@ -101,9 +101,9 @@ See [Automatic inbox tagging](/guides/inbox-tagging/), [Advisor](/guides/advisor | `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 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` | 365 | Each campaign's activity feed: failed and deferred sends, pauses and their reasons | -| `retention.notification_days` | 180 | In-app notifications, read or unread. One still waiting to be emailed is kept until it is sent or skipped | -| `retention.webhook_delivery_days` | 90 | 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 | +| `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 event logs and the three history feeds 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. diff --git a/docs/content/docs/guides/campaigns.mdx b/docs/content/docs/guides/campaigns.mdx index 99df9fc24..ba5498fe1 100644 --- a/docs/content/docs/guides/campaigns.mdx +++ b/docs/content/docs/guides/campaigns.mdx @@ -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. A campaign's activity log keeps its entries for 365 days by default (`retention.campaign_log_days` on a self-hosted instance); its stats and sent mail are kept separately and are unaffected. +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. diff --git a/docs/content/docs/guides/notifications.mdx b/docs/content/docs/guides/notifications.mdx index bab0b35bb..ddb036576 100644 --- a/docs/content/docs/guides/notifications.mdx +++ b/docs/content/docs/guides/notifications.mdx @@ -45,7 +45,7 @@ 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 for 180 days by default, read or not, so one older than that 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)). +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. diff --git a/docs/content/docs/guides/webhooks.mdx b/docs/content/docs/guides/webhooks.mdx index 4777eadeb..a94b629cf 100644 --- a/docs/content/docs/guides/webhooks.mdx +++ b/docs/content/docs/guides/webhooks.mdx @@ -130,7 +130,7 @@ 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 for 90 days by default after its last attempt, after which it 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)). +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. diff --git a/internal/app/consumer/warmup_mail_retention.go b/internal/app/consumer/warmup_mail_retention.go index 88493163b..adeb36279 100644 --- a/internal/app/consumer/warmup_mail_retention.go +++ b/internal/app/consumer/warmup_mail_retention.go @@ -57,9 +57,9 @@ func (s *JobsService) StartWarmupMailRetention(ctx context.Context) { } batchCtx, cancel := context.WithTimeout(ctx, 55*time.Second) defer cancel() - started := time.Now() + started, run := time.Now(), newRetireRun() for { - done, err := s.retireWarmupMailBatch(batchCtx) + done, err := s.retireWarmupMailBatch(batchCtx, run) if err != nil { return err } @@ -70,7 +70,14 @@ func (s *JobsService) StartWarmupMailRetention(ctx context.Context) { 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) @@ -94,12 +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 drained. -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 } @@ -115,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)...) } @@ -135,21 +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 drained(received) && drained(sent), 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 { - if len(batch) >= warmupRetentionBatch { - return false - } + 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 false + return true } } - return true + return false } // publishWarmupDelete sends the delete for one message to the worker holding diff --git a/internal/app/consumer/warmup_retention_test.go b/internal/app/consumer/warmup_retention_test.go index c3eacb55e..ad31d2dea 100644 --- a/internal/app/consumer/warmup_retention_test.go +++ b/internal/app/consumer/warmup_retention_test.go @@ -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 } @@ -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) } @@ -427,3 +427,19 @@ func TestRetirementPassWaitsForAMailboxAtItsShare(t *testing.T) { 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) + } +} diff --git a/internal/app/instancesettings/document.go b/internal/app/instancesettings/document.go index 2b2112b30..5ff236388 100644 --- a/internal/app/instancesettings/document.go +++ b/internal/app/instancesettings/document.go @@ -75,11 +75,11 @@ 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. + // 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. + // 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. + // WebhookDeliveryDays is how long a settled webhook delivery stays in its endpoint's log; 0 keeps them all. WebhookDeliveryDays int `json:"webhook_delivery_days"` } @@ -383,9 +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) - r.CampaignLogDays = clamp(r.CampaignLogDays, config.CampaignLogRetentionDaysDefault, config.RetentionDaysMin) - r.NotificationDays = clamp(r.NotificationDays, config.NotificationRetentionDaysDefault, config.RetentionDaysMin) - r.WebhookDeliveryDays = clamp(r.WebhookDeliveryDays, config.WebhookDeliveryRetentionDaysDefault, config.RetentionDaysMin) + // 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 diff --git a/internal/config/constants.go b/internal/config/constants.go index 980f4735b..10016151c 100644 --- a/internal/config/constants.go +++ b/internal/config/constants.go @@ -339,12 +339,10 @@ const ( // shortens it under Instance settings. AuditLogRetentionDaysDefault = 90 - // CampaignLogRetentionDaysDefault is how long a campaign's activity feed keeps an entry. - CampaignLogRetentionDaysDefault = 365 - // NotificationRetentionDaysDefault is how long in-app notifications are kept, read or not. - NotificationRetentionDaysDefault = 180 - // WebhookDeliveryRetentionDaysDefault is how long a settled delivery stays in an endpoint's log. - WebhookDeliveryRetentionDaysDefault = 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 diff --git a/internal/jobs/table_retention.go b/internal/jobs/table_retention.go index 69f257f43..8169efbd1 100644 --- a/internal/jobs/table_retention.go +++ b/internal/jobs/table_retention.go @@ -23,7 +23,6 @@ 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) - PruneTrackingDedupe(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) } @@ -63,8 +62,6 @@ func (j *TableRetentionJob) Run(ctx context.Context) error { {"campaign_logs", j.store.PruneCampaignLogs, windows.CampaignLogDays}, {"notifications", j.store.PruneNotifications, windows.NotificationDays}, {"webhook_deliveries", j.store.PruneWebhookDeliveries, windows.WebhookDeliveryDays}, - // A dedupe mark only matters while the open and click logs it guards are kept. - {"tracking_events_processed", j.store.PruneTrackingDedupe, windows.EngagementEventDays}, {"worker_health_samples", j.store.PruneWorkerHealthSamples, workerHealthSampleKeepDays}, {"send_result_effects", j.store.PruneDeliveredSendResultEffects, sendResultEffectKeepDays}, } diff --git a/internal/jobs/table_retention_test.go b/internal/jobs/table_retention_test.go index 6a0ee5609..1ec7edb0e 100644 --- a/internal/jobs/table_retention_test.go +++ b/internal/jobs/table_retention_test.go @@ -31,9 +31,6 @@ func (f *fakeTableRetention) PruneNotifications(_ context.Context, b time.Time) func (f *fakeTableRetention) PruneWebhookDeliveries(_ context.Context, b time.Time) (int64, error) { return f.record("webhook_deliveries", b) } -func (f *fakeTableRetention) PruneTrackingDedupe(_ context.Context, b time.Time) (int64, error) { - return f.record("tracking_events_processed", b) -} func (f *fakeTableRetention) PruneWorkerHealthSamples(_ context.Context, b time.Time) (int64, error) { return f.record("worker_health_samples", b) } @@ -50,16 +47,16 @@ func (r fixedRetention) RetentionWindows(context.Context) instancesettings.Reten func TestTableRetentionReadsWindowsAndSurvivesAFailingTable(t *testing.T) { store := &fakeTableRetention{before: map[string]time.Time{}, fail: "notifications"} windows := instancesettings.DefaultRetention() - windows.CampaignLogDays, windows.WebhookDeliveryDays, windows.EngagementEventDays = 10, 20, 30 + 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) != 6 { - t.Fatalf("pruned %d tables, want all six despite the failure: %v", len(store.before), store.before) + 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, "tracking_events_processed": 30, + "campaign_logs": 10, "webhook_deliveries": 20, "worker_health_samples": workerHealthSampleKeepDays, "send_result_effects": sendResultEffectKeepDays, } { age := time.Since(store.before[table]) @@ -68,3 +65,19 @@ func TestTableRetentionReadsWindowsAndSurvivesAFailingTable(t *testing.T) { } } } + +// 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) + } +} diff --git a/internal/repository/pg_mail_transport_recovery.go b/internal/repository/pg_mail_transport_recovery.go index e60e456d5..10343f257 100644 --- a/internal/repository/pg_mail_transport_recovery.go +++ b/internal/repository/pg_mail_transport_recovery.go @@ -58,7 +58,7 @@ func (r *emailAccountErrorRepository) RecordTransportSuccess(ctx context.Context // 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 { - // A healthy mailbox's sync clock moves at most once a minute; a pending error always gets the exact one. + // 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 @@ -69,7 +69,7 @@ func recordTransportSuccess(ctx context.Context, tx pgx.Tx, accountID uuid.UUID, 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 - WHERE EXCLUDED.operation<>'sync' OR (SELECT open FROM pending) OR existing.recovered_at < EXCLUDED.recovered_at - INTERVAL '1 minute') + 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() diff --git a/internal/repository/pg_table_retention.go b/internal/repository/pg_table_retention.go index 8880a6ab7..d059bcaad 100644 --- a/internal/repository/pg_table_retention.go +++ b/internal/repository/pg_table_retention.go @@ -68,12 +68,6 @@ func (r *TableRetentionRepository) PruneWebhookDeliveries(ctx context.Context, b AND updated_at < $2 LIMIT $1`, before) } -// PruneTrackingDedupe drops consumer-side tracking dedupe marks older than before. -func (r *TableRetentionRepository) PruneTrackingDedupe(ctx context.Context, before time.Time) (int64, error) { - return DeleteInBatches(ctx, r.db, "tracking_events_processed", - `SELECT ctid FROM tracking_events_processed WHERE processed_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", diff --git a/internal/repository/pg_table_retention_live_test.go b/internal/repository/pg_table_retention_live_test.go index 4fa9b240e..963cd3803 100644 --- a/internal/repository/pg_table_retention_live_test.go +++ b/internal/repository/pg_table_retention_live_test.go @@ -35,7 +35,6 @@ func TestLiveTableRetentionPrunesOnlyPastWindow(t *testing.T) { exec(`INSERT INTO tasks (id, task_type, email_account_id, status, message_id) VALUES ($1, 'campaign', $2, 'completed', '')`, task, account) t.Cleanup(func() { c := context.Background() - _, _ = pool.Exec(c, `DELETE FROM tracking_events_processed WHERE task_id = $1`, task) _, _ = pool.Exec(c, `DELETE FROM tasks WHERE id = $1`, task) _, _ = pool.Exec(c, `DELETE FROM email_accounts WHERE id = $1`, account) _, _ = pool.Exec(c, `DELETE FROM workers WHERE id = $1`, worker) @@ -57,16 +56,14 @@ func TestLiveTableRetentionPrunesOnlyPastWindow(t *testing.T) { 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)`, task, org, old, fresh) // More than one batch, so the loop has to come back for the rest. - exec(`INSERT INTO tracking_events_processed (task_id, event_type, url_hash, processed_at) - SELECT $1, 'click', g::text, $2 FROM generate_series(1, $3::int) g`, task, old, PruneBatch+7) - exec(`INSERT INTO tracking_events_processed (task_id, event_type, url_hash, processed_at) VALUES ($1, 'open', '', $2)`, task, fresh) + 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, - "tracking_events_processed": repo.PruneTrackingDedupe, "worker_health_samples": repo.PruneWorkerHealthSamples, - "send_result_effects": repo.PruneDeliveredSendResultEffects, + "worker_health_samples": repo.PruneWorkerHealthSamples, + "send_result_effects": repo.PruneDeliveredSendResultEffects, } { if _, err := prune(ctx, before); err != nil { t.Fatalf("%s: %v", name, err) @@ -93,9 +90,8 @@ func TestLiveTableRetentionPrunesOnlyPastWindow(t *testing.T) { {"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 the fresh one", `SELECT count(*) FROM worker_health_samples WHERE worker_id = $1`, worker, 1}, + {"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}, - {"dedupe marks keep only the fresh one, across batches", `SELECT count(*) FROM tracking_events_processed WHERE task_id = $1`, task, 1}, } { if got := count(c.query, c.arg); got != c.want { t.Errorf("%s: got %d rows, want %d", c.what, got, c.want) @@ -124,9 +120,9 @@ func TestLiveRetentionPrunesUseTheirIndexes(t *testing.T) { {`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 tracking_events_processed WHERE processed_at < NOW() LIMIT 5000`, "idx_tracking_processed_cleanup"}, {`SELECT ctid FROM worker_health_samples WHERE observed_at < NOW() LIMIT 5000`, "idx_worker_health_samples_observed"}, - {`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_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 ctid FROM send_result_effects WHERE delivered_at IS NOT NULL AND delivered_at < NOW() 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"}, @@ -144,7 +140,7 @@ func TestLiveRetentionPrunesUseTheirIndexes(t *testing.T) { plan.WriteString(line + "\n") } rows.Close() - if !strings.Contains(plan.String(), c.index) { + 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()) } } diff --git a/internal/repository/pg_warmup.go b/internal/repository/pg_warmup.go index 34f924c79..6d19f7123 100644 --- a/internal/repository/pg_warmup.go +++ b/internal/repository/pg_warmup.go @@ -305,9 +305,9 @@ 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 @@ -1986,7 +1986,7 @@ func (r *warmupRepository) GetWarmupReceived(ctx context.Context, accountID, int return &w, nil } -// WarmupRetirePerMailbox bounds one mailbox's share of a retirement batch, so a long backlog cannot queue a whole batch on one worker. +// 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: @@ -1995,7 +1995,7 @@ const WarmupRetirePerMailbox = 50 // from the message map by the internal id, which is what the worker's remove // 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) ([]WarmupMailToRetire, error) { +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 @@ -2012,11 +2012,11 @@ func (r *warmupRepository) ListWarmupMailToRetire(ctx context.Context, defaultDa 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") + ` 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 @@ -2026,7 +2026,7 @@ func (r *warmupRepository) ListWarmupMailToRetire(ctx context.Context, defaultDa // 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. // Like the received side it starts from the mailboxes that can act. -func (r *warmupRepository) ListWarmupSentCopiesToRetire(ctx context.Context, defaultDays, limit int) ([]WarmupMailToRetire, error) { +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 @@ -2043,16 +2043,19 @@ func (r *warmupRepository) ListWarmupSentCopiesToRetire(ctx context.Context, def 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' 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 } @@ -2116,8 +2119,6 @@ func (r *warmupRepository) PruneWarmupEventsBefore(ctx context.Context, before t AND (sent_message_id = '' OR sent_retired_at IS NOT NULL OR sender_account_id IN (SELECT id FROM email_accounts WHERE provider = 'smtp_imap'))`, []any{before}}, {`DELETE FROM pool_link_commands WHERE status IN ('answered', 'expired', 'cancelled') AND created_at < $1`, []any{before}}, - // Thread turns go at the age of the receipts and tokens they chain back to. - {`DELETE FROM warmup_thread_messages WHERE created_at < $1`, []any{before}}, // An arrival's handle is how a retiring delete reaches the instance, so it outlives the copy it names. {`DELETE FROM pool_link_arrivals a WHERE a.reported_at < $1 AND NOT EXISTS (SELECT 1 FROM warmup_received wr WHERE wr.email_account_id = a.email_account_id @@ -2129,6 +2130,16 @@ func (r *warmupRepository) PruneWarmupEventsBefore(ctx context.Context, before t } total += cmd.RowsAffected() } + // A thread turn outlives the event window while its mailbox still keeps that mail, because replies are matched against it. + 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 < $2 + AND (ea.warmup_retention_days IS NULL OR m.created_at < NOW() - make_interval(days => ea.warmup_retention_days)) + LIMIT $1`, before) + total += n + if err != nil { + return total, err + } return total, nil } diff --git a/internal/repository/sync_report_writes_live_test.go b/internal/repository/sync_report_writes_live_test.go index 9c1bb68c3..f059dd69d 100644 --- a/internal/repository/sync_report_writes_live_test.go +++ b/internal/repository/sync_report_writes_live_test.go @@ -90,7 +90,7 @@ func TestLiveSyncReportWritesOnlyWhatChanged(t *testing.T) { } } -func TestLiveSyncRecoveryClockSkipsQuietRewritesButNeverAPendingError(t *testing.T) { +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'` @@ -112,11 +112,15 @@ func TestLiveSyncRecoveryClockSkipsQuietRewritesButNeverAPendingError(t *testing base := time.Now().UTC().Add(-time.Hour).Truncate(time.Millisecond) put(base) quiet := rowVersion(t, f, recoveryRow) - put(base.Add(20 * time.Second)) + put(base.Add(-time.Second)) if rowVersion(t, f, recoveryRow) != quiet { - t.Fatal("a healthy mailbox rewrote its recovery clock inside the minute") + t.Fatal("a report older than the recovery clock rewrote it") } - // An error raised now is cleared by the very next pass, minute or not. + 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) diff --git a/internal/repository/warmup_mail_retention_live_test.go b/internal/repository/warmup_mail_retention_live_test.go index 8d9a7bf39..530bdb8a9 100644 --- a/internal/repository/warmup_mail_retention_live_test.go +++ b/internal/repository/warmup_mail_retention_live_test.go @@ -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) } From 9545a26e290d8ba68873e007832510c57cc81d50 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 14:26:27 +0100 Subject: [PATCH 145/318] feat: verify hosted backend preflight task identities with existing deployment permissions and preserve rollback counts --- .github/scripts/aws-backend-config.cjs | 28 ++++---- .github/scripts/aws-backend-config.test.cjs | 66 ++++++++++++++----- .github/scripts/terraform-stack.sh | 4 +- .github/scripts/terraform-stack.test.sh | 5 +- .github/workflows/configure-backend-aws.yml | 5 ++ .github/workflows/terraform-aws.yml | 2 +- deploy/terraform/aws/runtime/README.md | 13 ++-- deploy/terraform/aws/runtime/ci.tf | 9 --- .../aws/runtime/tests/target_tls.tftest.hcl | 16 ----- docs/content/docs/development/aws-fargate.mdx | 34 +++++++--- 10 files changed, 108 insertions(+), 74 deletions(-) diff --git a/.github/scripts/aws-backend-config.cjs b/.github/scripts/aws-backend-config.cjs index 42ebdd70f..cdf9bc3eb 100644 --- a/.github/scripts/aws-backend-config.cjs +++ b/.github/scripts/aws-backend-config.cjs @@ -1,5 +1,5 @@ const { - ECSClient, DescribeServicesCommand, DescribeTasksCommand, UpdateServiceCommand, paginateListTasks, + ECSClient, DescribeServicesCommand, DescribeTasksCommand, UpdateServiceCommand, } = require("@aws-sdk/client-ecs"); const { CloudWatchClient, DescribeAlarmsCommand } = require("@aws-sdk/client-cloudwatch"); const { @@ -22,7 +22,11 @@ function configuration(env) { throw new Error("CONFIG_EXPECTED_TASK_DEFINITION must identify this cluster's backend revision"); } if (!["true", "false"].includes(env.CONFIG_ATTACHMENT_DOWNLOAD_PROXY)) throw new Error("CONFIG_ATTACHMENT_DOWNLOAD_PROXY must be true or false"); - return { ...config, expected, value: env.CONFIG_ATTACHMENT_DOWNLOAD_PROXY }; + const tasks = JSON.parse(env.CONFIG_EXPECTED_TASKS || "null"); + const taskPrefix = `arn:aws:ecs:us-east-1:${account}:task/${config.cluster.split("/").pop()}/`; + if (!Array.isArray(tasks) || !tasks.length || tasks.some((task) => typeof task !== "string" || !task.startsWith(taskPrefix) || !/^[a-f0-9]{32}$/.test(task.slice(taskPrefix.length))) || + new Set(tasks).size !== tasks.length) throw new Error("CONFIG_EXPECTED_TASKS must list unique current task ARNs from this cluster's read-only preflight"); + return { ...config, expected, tasks, value: env.CONFIG_ATTACHMENT_DOWNLOAD_PROXY }; } async function service(ecs, config) { @@ -33,17 +37,16 @@ async function service(ecs, config) { } function stable(live, expected, count) { - if (live.taskDefinition !== expected || live.desiredCount < 1 || live.runningCount !== live.desiredCount || live.pendingCount !== 0 || + if (live.taskDefinition !== expected || !Number.isInteger(live.desiredCount) || live.desiredCount < 1 || live.runningCount !== live.desiredCount || live.pendingCount !== 0 || live.deployments?.length !== 1 || live.deployments[0].rolloutState !== "COMPLETED" || + live.deployments[0].taskDefinition !== expected || live.deployments[0].runningCount !== live.desiredCount || + live.deployments[0].desiredCount !== live.desiredCount || live.deployments[0].pendingCount !== 0 || (count !== undefined && live.desiredCount !== count)) throw new Error("Backend must be stable on the expected revision and task count"); } async function verifyTasks(ecs, config, live, definition) { stable(live, definition.taskDefinitionArn); - const arns = []; - for await (const page of paginateListTasks({ client: ecs, pageSize: 100, stopOnSameToken: true }, { - cluster: config.cluster, serviceName: live.serviceName, desiredStatus: "RUNNING", - })) arns.push(...(page.taskArns || [])); + const arns = config.tasks; if (new Set(arns).size !== live.desiredCount || arns.length !== live.desiredCount) throw new Error("Every running backend task must be accounted for"); for (let offset = 0; offset < arns.length; offset += 100) { const batch = arns.slice(offset, offset + 100); @@ -74,8 +77,9 @@ async function observe(clients, config, definition, count, sleep, report) { await alarms(clients, config); if (waited < 300) await sleep(15000); } - await verifyTasks(clients.ecs, config, await service(clients.ecs, config), definition); - report("Backend configuration baked for 300s; every running task verified"); + const current = await describe(clients.ecs, definition.taskDefinitionArn); + if (!same(current.definition, definition)) throw new Error("Backend configuration readback does not match the expected definition"); + report("Backend configuration and service counts verified after a 300s bake; independently inspect the resulting tasks and download responses"); } async function configure(clients, config, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), report = console.log) { @@ -115,6 +119,7 @@ async function configure(clients, config, sleep = (ms) => new Promise((resolve) const next = prepared ? latest.definition.taskDefinitionArn : await register(clients.ecs, source, rendered, tags, config.tag, report); stable(await service(clients.ecs, config), live.taskDefinition, live.desiredCount); try { + // Every backend writer must use the shared deployment queue. await clients.ecs.send(new UpdateServiceCommand({ cluster: config.cluster, service: live.serviceName, taskDefinition: next })); await waitForService(clients.ecs, config, "backend", next, sleep); await observe(clients, config, { ...rendered, taskDefinitionArn: next }, live.desiredCount, sleep, report); @@ -127,8 +132,9 @@ async function configure(clients, config, sleep = (ms) => new Promise((resolve) } if (current.taskDefinition === next) await clients.ecs.send(new UpdateServiceCommand({ cluster: config.cluster, service: live.serviceName, taskDefinition: live.taskDefinition })); await waitForService(clients.ecs, config, "backend", live.taskDefinition, sleep); - await verifyTasks(clients.ecs, config, await service(clients.ecs, config), definition); - report("Restored and verified the exact previous backend revision"); + stable(await service(clients.ecs, config), live.taskDefinition, live.desiredCount); + if (!same((await describe(clients.ecs, live.taskDefinition)).definition, definition)) throw new Error("Previous backend definition readback changed"); + report("Restored and verified the exact previous backend revision and service counts; independently inspect its current tasks"); } catch { throw new Error("Configuration rollout failed and rollback could not be verified; inspect the backend before any further change", { cause: error }); } diff --git a/.github/scripts/aws-backend-config.test.cjs b/.github/scripts/aws-backend-config.test.cjs index 937733026..2a840590c 100644 --- a/.github/scripts/aws-backend-config.test.cjs +++ b/.github/scripts/aws-backend-config.test.cjs @@ -3,24 +3,26 @@ const assert = require("node:assert/strict"); const { mkdtempSync, writeFileSync, rmSync } = require("node:fs"); const { tmpdir } = require("node:os"); const { join } = require("node:path"); -const { ECSClient } = require("@aws-sdk/client-ecs"); const { configuration, configure } = require("./aws-backend-config.cjs"); const { REGISTER_FIELDS, ATTACHMENT_PROXY, ATTACHMENT_PROXY_TAG } = require("./aws-deploy.cjs"); const root = "arn:aws:ecs:us-east-1:000000000000:"; const arn = (revision) => `${root}task-definition/fixture-backend:${revision}`; +const task = (number) => `${root}task/fixture/${number.toString(16).padStart(32, "0")}`; +const runningTasks = (revision, count = 2) => Array.from({ length: count }, (_, i) => task(revision * 1000 + i + 1)); const image = `ghcr.io/warmbly/warmbly/backend@sha256:${"a".repeat(64)}`; function fixture(t, options = {}) { + const count = options.taskCount || 2; const dir = mkdtempSync(join(tmpdir(), "backend-config-")); t.after(() => rmSync(dir, { recursive: true, force: true })); const manifest = { tag: "v0.6.75", registry: "ghcr.io/warmbly/warmbly", images: { "backend-kafka": `sha256:${"a".repeat(64)}` } }; writeFileSync(join(dir, "images.json"), JSON.stringify(manifest)); const env = { AWS_ECS_CLUSTER: root + "cluster/fixture", DEPLOY_TAG: manifest.tag, DEPLOY_IMAGES_JSON: join(dir, "images.json"), - CONFIG_EXPECTED_TASK_DEFINITION: arn(1), CONFIG_ATTACHMENT_DOWNLOAD_PROXY: "true" }; + CONFIG_EXPECTED_TASK_DEFINITION: arn(1), CONFIG_EXPECTED_TASKS: JSON.stringify(runningTasks(1, count)), CONFIG_ATTACHMENT_DOWNLOAD_PROXY: "true" }; const cfg = configuration(env); - const live = { serviceName: "fixture-backend", status: "ACTIVE", taskDefinition: arn(1), desiredCount: 2, runningCount: 2, pendingCount: 0, - deployments: [{ rolloutState: "COMPLETED" }] }; + const live = { serviceName: "fixture-backend", status: "ACTIVE", taskDefinition: arn(1), desiredCount: count, runningCount: count, pendingCount: 0, + deployments: [{ rolloutState: "COMPLETED", taskDefinition: arn(1), desiredCount: count, runningCount: count, pendingCount: 0 }] }; const base = { family: "fixture-backend", status: "ACTIVE", revision: 1, taskDefinitionArn: arn(1), taskRoleArn: root + "role/task", executionRoleArn: root + "role/execution", networkMode: "awsvpc", cpu: "256", memory: "512", requiresCompatibilities: ["FARGATE"], runtimePlatform: { cpuArchitecture: "ARM64", operatingSystemFamily: "LINUX" }, @@ -35,8 +37,7 @@ function fixture(t, options = {}) { const calls = []; const sleeps = []; let latest = arn(1); - const ecs = new ECSClient({ region: "us-east-1" }); - t.after(() => ecs.destroy()); + const ecs = {}; ecs.send = async (command) => { const name = command.constructor.name; calls.push({ name, input: structuredClone(command.input) }); @@ -47,12 +48,11 @@ function fixture(t, options = {}) { const entry = defs.get(command.input.taskDefinition === "fixture-backend" ? latest : command.input.taskDefinition); return { taskDefinition: structuredClone(entry.definition), tags: structuredClone(entry.tags) }; } - case "ListTasksCommand": - if (options.pagination && !command.input.nextToken) return { taskArns: [root + "task/fixture/one"], nextToken: "next" }; - return { taskArns: options.pagination ? [root + "task/fixture/two"] : [root + "task/fixture/one", root + "task/fixture/two"] }; - case "DescribeTasksCommand": return { tasks: command.input.tasks.map((taskArn) => ({ + case "DescribeTasksCommand": return { tasks: (options.missingTask ? command.input.tasks.slice(1) : command.input.tasks).map((taskArn) => ({ taskArn, taskDefinitionArn: options.wrongTask ? arn(99) : live.taskDefinition, - group: "service:fixture-backend", lastStatus: "RUNNING", desiredStatus: options.drainingTask ? "STOPPED" : "RUNNING", healthStatus: options.unhealthyTask ? "UNHEALTHY" : "HEALTHY", + group: options.foreignGroup ? "service:fixture-foreign" : "service:fixture-backend", lastStatus: "RUNNING", + desiredStatus: options.drainingTask || !runningTasks(Number(live.taskDefinition.split(":").pop()), count).includes(taskArn) ? "STOPPED" : "RUNNING", + healthStatus: options.unhealthyTask ? "UNHEALTHY" : "HEALTHY", containers: [{ name: "backend", image }], overrides: { containerOverrides: options.override ? [{ name: "backend", command: ["other"] }] : [{ name: "backend" }] }, })) }; case "RegisterTaskDefinitionCommand": { @@ -63,8 +63,8 @@ function fixture(t, options = {}) { } case "UpdateServiceCommand": { live.taskDefinition = command.input.taskDefinition; - if (options.failedRoll && live.taskDefinition !== arn(1)) live.deployments = [{ rolloutState: "FAILED" }]; - else live.deployments = [{ rolloutState: "COMPLETED" }]; + live.deployments = [{ rolloutState: options.failedRoll && live.taskDefinition !== arn(1) ? "FAILED" : "COMPLETED", + taskDefinition: live.taskDefinition, desiredCount: count, runningCount: count, pendingCount: 0 }]; return {}; } default: throw new Error(`Unexpected ${name}`); @@ -81,7 +81,7 @@ function fixture(t, options = {}) { const mutations = (f) => f.calls.filter((c) => ["RegisterTaskDefinitionCommand", "UpdateServiceCommand"].includes(c.name)); test("only the allowlisted flag and ownership tag change; every live task is checked and a full bake completes", async (t) => { - const f = fixture(t, { pagination: true }); + const f = fixture(t); const previous = structuredClone(f.base); const result = await f.run(); assert.equal(result.changed, true); @@ -95,8 +95,10 @@ test("only the allowlisted flag and ownership tag change; every live task is che assert.deepEqual(f.calls.filter((c) => c.name === "UpdateServiceCommand").map((c) => c.input), [{ cluster: f.cfg.cluster, service: "fixture-backend", taskDefinition: arn(2) }]); assert.equal(f.sleeps.reduce((a, b) => a + b, 0), 300000); assert.equal(f.calls.filter((c) => c.name === "DescribeAlarmsCommand").length, 22); - assert.ok(f.calls.some((c) => c.name === "ListTasksCommand" && c.input.nextToken === "next")); + assert.ok(!f.calls.some((c) => c.name === "ListTasksCommand"), "the operation uses existing deployment permissions"); const count = mutations(f).length; + await assert.rejects(f.run(), /unmodified service configuration/, "an old task snapshot must be refreshed before retrying"); + f.cfg.tasks = runningTasks(2); assert.equal((await f.run()).changed, false); assert.equal(mutations(f).length, count, "repeated request is a no-op even with its original expected revision"); assert.equal(f.sleeps.reduce((a, b) => a + b, 0), 600000, "an interrupted bake is always observed afresh without rolling again"); @@ -106,6 +108,7 @@ test("disabling is explicit and preserves the remainder of the running definitio const f = fixture(t); await f.run(); f.cfg.expected = arn(2); + f.cfg.tasks = runningTasks(2); f.cfg.value = "false"; await f.run(); const current = f.defs.get(arn(3)); @@ -113,14 +116,28 @@ test("disabling is explicit and preserves the remainder of the running definitio assert.equal(current.tags.find((tag) => tag.key === ATTACHMENT_PROXY_TAG).value, "false"); }); +test("every preflight task is described within the API batch limit", async (t) => { + const f = fixture(t, { taskCount: 101 }); + await f.run(); + const descriptions = f.calls.filter((c) => c.name === "DescribeTasksCommand"); + assert.deepEqual(descriptions.map((c) => c.input.tasks.length), [100, 1]); + assert.deepEqual(descriptions.flatMap((c) => c.input.tasks), f.cfg.tasks); +}); + for (const [name, options, mutate] of [ ["mixed task definitions", { wrongTask: true }], ["unhealthy task", { unhealthyTask: true }], ["task override", { override: true }], ["draining task", { drainingTask: true }], + ["missing described task", { missingTask: true }], ["foreign task group", { foreignGroup: true }], + ["incomplete preflight", {}, (f) => { f.cfg.tasks.pop(); }], + ["duplicate preflight task", {}, (f) => { f.cfg.tasks[1] = f.cfg.tasks[0]; }], ["stale expected revision", {}, (f) => { f.cfg.expected = arn(99); }], ["wrong image", {}, (f) => { f.base.containerDefinitions[0].image += "bad"; }], ["wrong release", {}, (f) => { f.tags[0].value = "v0.6.74"; }], ["missing variant", {}, (f) => { f.tags.splice(1, 1); }], ["zero tasks", {}, (f) => { f.live.desiredCount = f.live.runningCount = 0; }], + ["unknown desired count", {}, (f) => { f.live.desiredCount = f.live.runningCount = undefined; }], + ["deployment count mismatch", {}, (f) => { f.live.deployments[0].runningCount = 1; }], + ["deployment revision mismatch", {}, (f) => { f.live.deployments[0].taskDefinition = arn(99); }], ["active rollout", {}, (f) => { f.live.deployments[0].rolloutState = "IN_PROGRESS"; }], ["duplicate flag", {}, (f) => { f.base.containerDefinitions[0].environment.push(...["true", "false"].map((value) => ({ name: ATTACHMENT_PROXY, value }))); }], ["secret-backed flag", {}, (f) => { f.base.containerDefinitions[0].secrets.push({ name: ATTACHMENT_PROXY, valueFrom: "secret" }); }], @@ -137,7 +154,20 @@ for (const options of [{ alarm: true }, { failedRoll: true }]) test(`${JSON.stri await assert.rejects(f.run()); assert.equal(f.live.taskDefinition, arn(1)); assert.deepEqual(f.calls.filter((c) => c.name === "UpdateServiceCommand").map((c) => c.input.taskDefinition), [arn(2), arn(1)]); - assert.equal(f.calls.at(-1).name, "DescribeTasksCommand"); + assert.equal(f.calls.at(-1).name, "DescribeTaskDefinitionCommand"); +}); + +test("a desired-count change during rollback prevents a successful restore report", async (t) => { + const f = fixture(t, { alarm: true, hook: (name, { live, calls }) => { + if (name === "DescribeServicesCommand" && calls.filter((c) => c.name === "UpdateServiceCommand").length === 2) { + live.desiredCount = live.runningCount = 3; + live.deployments[0].desiredCount = live.deployments[0].runningCount = 3; + } + } }); + await assert.rejects(f.run(), /rollback could not be verified/); + assert.equal(f.live.taskDefinition, arn(1)); + assert.equal(f.live.desiredCount, 3, "another writer's count is preserved for operator inspection"); + assert.ok(f.calls.filter((c) => c.name === "UpdateServiceCommand").every((c) => !Object.hasOwn(c.input, "desiredCount"))); }); test("a concurrent change before update is preserved", async (t) => { @@ -177,6 +207,10 @@ test("configuration requires a supported release, exact backend ARN and explicit { DEPLOY_TAG: "v0.6.74" }, { DEPLOY_TAG: "" }, { CONFIG_ATTACHMENT_DOWNLOAD_PROXY: "yes" }, { CONFIG_EXPECTED_TASK_DEFINITION: arn(1).replace("fixture-backend", "fixture-consumer") }, { CONFIG_EXPECTED_TASK_DEFINITION: arn(1).replace("000000000000", "111111111111") }, + { CONFIG_EXPECTED_TASKS: "[]" }, { CONFIG_EXPECTED_TASKS: "null" }, + { CONFIG_EXPECTED_TASKS: JSON.stringify([task(1), task(1)]) }, + { CONFIG_EXPECTED_TASKS: JSON.stringify([task(1).replace("000000000000", "111111111111")]) }, + { CONFIG_EXPECTED_TASKS: JSON.stringify([task(1).replace("/fixture/", "/foreign/")]) }, ]) assert.throws(() => configuration({ ...f.env, ...overrides })); assert.equal(configuration({ ...f.env, DEPLOY_BAKE_SECONDS: "0", DEPLOY_FLEET: "true" }).bake, 300); assert.equal(configuration(f.env).fleet, false); diff --git a/.github/scripts/terraform-stack.sh b/.github/scripts/terraform-stack.sh index a128be91e..5165ad581 100755 --- a/.github/scripts/terraform-stack.sh +++ b/.github/scripts/terraform-stack.sh @@ -10,14 +10,14 @@ # # plan writes $WORK/.summary (one "action address" per line) and prints # safe, gated or none. Safe means only creates, in-place updates, and new -# revisions of task definitions, excluding protected deployment and evidence IAM changes. +# revisions of task definitions, excluding protected recovery evidence IAM changes. set -euo pipefail classify() { jq -r ' [.resource_changes[]? | select(.change.actions != ["no-op"] and .change.actions != ["read"])] as $c | if ($c | length) == 0 then "none" - elif any($c[]; (.name == "tls_recovery_evidence" or .name == "github_deploy") and + elif any($c[]; .name == "tls_recovery_evidence" and (.type == "aws_iam_role" or .type == "aws_iam_role_policy")) then "gated" elif any($c[]; (.change.actions | index("delete")) and ((.type == "aws_ecs_task_definition" and (.change.actions | length) == 2) | not)) then "gated" diff --git a/.github/scripts/terraform-stack.test.sh b/.github/scripts/terraform-stack.test.sh index 536315e73..d7f978dc8 100755 --- a/.github/scripts/terraform-stack.test.sh +++ b/.github/scripts/terraform-stack.test.sh @@ -20,15 +20,12 @@ check() { for type in aws_iam_role aws_iam_role_policy; do for actions in '["create"]' '["update"]' '["delete"]' '["delete","create"]'; do check gated "$type" tls_recovery_evidence "$actions" - check gated "$type" github_deploy "$actions" done check none "$type" tls_recovery_evidence '["no-op"]' check none "$type" tls_recovery_evidence '["read"]' - check none "$type" github_deploy '["no-op"]' - check none "$type" github_deploy '["read"]' done check safe aws_iam_role existing_role '["create"]' check safe aws_ecs_task_definition service '["delete","create"]' check gated aws_lb_target_group service '["delete"]' check safe aws_cloudwatch_metric_alarm service '["update"]' -echo 'Deployment and evidence IAM changes require approval; existing plan classifications remain unchanged' +echo 'Protected evidence IAM changes require approval; existing plan classifications remain unchanged' diff --git a/.github/workflows/configure-backend-aws.yml b/.github/workflows/configure-backend-aws.yml index 00ceb4806..07657c851 100644 --- a/.github/workflows/configure-backend-aws.yml +++ b/.github/workflows/configure-backend-aws.yml @@ -11,6 +11,10 @@ on: description: Exact currently running backend task definition ARN required: true type: string + expected_backend_tasks: + description: JSON array of every current RUNNING backend task ARN from the read-only preflight + required: true + type: string attachment_download_proxy: description: Serve private campaign attachments through the backend download route required: true @@ -80,5 +84,6 @@ jobs: DEPLOY_TAG: ${{ inputs.tag }} DEPLOY_IMAGES_JSON: /tmp/backend-config-release/images.json CONFIG_EXPECTED_TASK_DEFINITION: ${{ inputs.expected_task_definition }} + CONFIG_EXPECTED_TASKS: ${{ inputs.expected_backend_tasks }} CONFIG_ATTACHMENT_DOWNLOAD_PROXY: ${{ inputs.attachment_download_proxy }} run: node .github/scripts/aws-backend-config.cjs diff --git a/.github/workflows/terraform-aws.yml b/.github/workflows/terraform-aws.yml index 3540280ed..05bc6de0e 100644 --- a/.github/workflows/terraform-aws.yml +++ b/.github/workflows/terraform-aws.yml @@ -1,7 +1,7 @@ name: Terraform AWS # Pull requests get a plan summary comment. On main, a stack whose plan only -# creates or updates applies on its own; destructive or protected deployment/evidence IAM +# creates or updates applies on its own; destructive or protected evidence IAM # changes wait in aws-infrastructure-approval. Var files live in the private # state bucket, and no plan body ever reaches a log, a comment or an artifact. on: diff --git a/deploy/terraform/aws/runtime/README.md b/deploy/terraform/aws/runtime/README.md index 74a76ad78..895d717b4 100644 --- a/deploy/terraform/aws/runtime/README.md +++ b/deploy/terraform/aws/runtime/README.md @@ -32,13 +32,16 @@ when activating them. attachment-download setting unless Terraform explicitly supplies its environment value. The opt-in `.github/workflows/configure-backend-aws.yml` changes only `CAMPAIGN_ATTACHMENT_DOWNLOAD_PROXY` from a verified live backend definition, -using release provenance, individual task checks, a fixed 300-second bake and -verified rollback. Its `warmbly-config-attachment-download-proxy` task tag records +using release provenance, preflight task identities checked against the service +count and deployment, a fixed 300-second bake and verified revision/count rollback. +Its `warmbly-config-attachment-download-proxy` task tag records ownership across later deploys and secret refreshes. Explicit Terraform `true` or `false` takes ownership; a rollback below v0.6.75 requires disabling the proxy -first and waiting for existing links to expire. The deploy role's cluster-scoped -`ecs:ListTasks` permission must be provisioned through infrastructure approval -before using this workflow. It does not provision permissions itself. +first and waiting for existing links to expire. The operator collects current +task ARNs through normal read-only inventory access and supplies them to the +workflow, which uses existing deployment permissions. After the bake, independently +inspect every new running task and the actual private-download response before +claiming end-to-end verification. No additional IAM policy is provisioned. A stable release tag on `main` reaches it from `release.yml` when the repository variable diff --git a/deploy/terraform/aws/runtime/ci.tf b/deploy/terraform/aws/runtime/ci.tf index d065de582..048a50ade 100644 --- a/deploy/terraform/aws/runtime/ci.tf +++ b/deploy/terraform/aws/runtime/ci.tf @@ -90,15 +90,6 @@ data "aws_iam_policy_document" "github_deploy" { actions = ["ecs:DescribeTasks"] resources = ["${local.ecs_arn}:task/${var.name}/*"] } - statement { - actions = ["ecs:ListTasks"] - resources = ["*"] - condition { - test = "ArnEquals" - variable = "ecs:cluster" - values = [local.foundation.cluster_arn] - } - } statement { actions = ["ecs:RunTask"] resources = [for task in keys(local.github_tasks) : "${local.ecs_arn}:task-definition/${var.name}-${task}:*"] diff --git a/deploy/terraform/aws/runtime/tests/target_tls.tftest.hcl b/deploy/terraform/aws/runtime/tests/target_tls.tftest.hcl index 46cb205a5..9315837f1 100644 --- a/deploy/terraform/aws/runtime/tests/target_tls.tftest.hcl +++ b/deploy/terraform/aws/runtime/tests/target_tls.tftest.hcl @@ -75,22 +75,6 @@ variables { } } -run "deployment_inventory_is_cluster_scoped" { - command = plan - variables { - github_repository = "warmbly/warmbly" - } - assert { - condition = anytrue([for statement in data.aws_iam_policy_document.github_deploy[0].statement : - statement.actions == toset(["ecs:ListTasks"]) && statement.resources == toset(["*"]) && - anytrue([for condition in statement.condition : - condition.test == "ArnEquals" && condition.variable == "ecs:cluster" && condition.values == tolist([local.foundation.cluster_arn]) - ]) - ]) - error_message = "Deployment task inventory reads must be restricted to this runtime cluster." - } -} - run "off_is_unchanged" { command = apply variables { diff --git a/docs/content/docs/development/aws-fargate.mdx b/docs/content/docs/development/aws-fargate.mdx index f8d4a0289..d890e1ada 100644 --- a/docs/content/docs/development/aws-fargate.mdx +++ b/docs/content/docs/development/aws-fargate.mdx @@ -275,19 +275,31 @@ provenance is running it stops at that check and changes nothing. After every backend runs a published release at least `v0.6.75`, dispatch **Configure AWS backend** on `main`. Supply the running release tag, exact live -backend task definition ARN and the desired `attachment_download_proxy` boolean. +backend task definition ARN, a JSON array of every current running backend task +ARN in `expected_backend_tasks`, and the desired `attachment_download_proxy` boolean. The workflow requires `AWS_DEPLOY_ENABLED=true`, uses `aws-production` and shares -the deployment queue. Provision the runtime deploy role's cluster-scoped -`ecs:ListTasks` read permission through the normal infrastructure approval first. +the deployment queue. Collect the task identities through the operator's normal +read-only inventory access. The workflow uses the existing deployment role's +task-description and service-update permissions. -The operation verifies release provenance and every running backend task, then +Keep backend configuration changes exclusive for the entire run. Routine writers +use the shared `aws-production` queue. Before an emergency console or CLI change, +stop and settle the active workflow and inspect the current service. The expected +revision is a snapshot check: ECS `UpdateService` has no atomic expected-revision +precondition to fence a writer outside that queue. + +The operation verifies release provenance and every supplied backend task against +the service's complete deployment and running count, then clones the live definition and changes only `CAMPAIGN_ATTACHMENT_DOWNLOAD_PROXY`. It preserves images, roles, secret references and version pins, TLS settings, resources, health checks, stop timeout and desired count. It watches the stable -service and alarms for 300 seconds, verifies every resulting task, and restores -and verifies the exact previous revision on failure. A concurrent revision or +service and alarms for 300 seconds, reads back the definition, and restores +and verifies the exact previous revision and service counts on failure. A concurrent revision or count change stops automatic rollback for operator inspection. It runs no migration, one-off task or fleet rollout and does not modify another service. +Refresh the task snapshot before a repeated request. A stale, missing, duplicate, +foreign or draining task is refused. A request for the existing setting observes +another full bake without rolling again. The task definition records the setting in `warmbly-config-attachment-download-proxy`. Future deployments and secret @@ -296,8 +308,10 @@ the environment variable. An explicit Terraform `true` or `false` value takes ownership. A prepared revision that never reached the service cannot activate the setting during a later release. To roll back below `v0.6.75`, explicitly disable the proxy first; confirm existing download links have expired before -removing route support. Successful rollout is followed by an authorized download -check of the bytes and response headers. Self-host configuration remains opt-in +removing route support. After rollout, independently inventory and describe every +new running task, confirm the expected task definition and image, then perform an +authorized download check of the bytes and response headers. Workflow success +alone does not complete those independent checks. Self-host configuration remains opt-in and defaults to `false`. ## Rotate keys @@ -362,8 +376,8 @@ plan reaches a log, a comment or an artifact. password, which the plan role may not. - On merge, each stack is planned in order: foundation, runtime, workers. A stack that only creates and updates applies on its own. One that replaces or - destroys anything, or changes the deployment or dedicated recovery evidence - IAM roles or their inline policies, stops and waits for approval in the + destroys anything, or changes the dedicated recovery evidence IAM role or its + inline policy, stops and waits for approval in the `aws-infrastructure-approval` environment, and the stacks after it wait too. On approval it plans again and applies only if the plan is still the one that was approved. A new task definition revision counts as an update, because the From 801c0af93624962a240f983bf540c9361475aac1 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 14:43:26 +0100 Subject: [PATCH 146/318] feat: require deployment ownership before accepting unchanged enabled hosted backend attachment configuration --- .github/scripts/aws-backend-config.cjs | 7 +++ .github/scripts/aws-backend-config.test.cjs | 44 ++++++++++++++++++- docs/content/docs/development/aws-fargate.mdx | 4 +- 3 files changed, 53 insertions(+), 2 deletions(-) diff --git a/.github/scripts/aws-backend-config.cjs b/.github/scripts/aws-backend-config.cjs index cdf9bc3eb..d3969ff7f 100644 --- a/.github/scripts/aws-backend-config.cjs +++ b/.github/scripts/aws-backend-config.cjs @@ -104,6 +104,13 @@ async function configure(clients, config, sleep = (ms) => new Promise((resolve) await verifyTasks(clients.ecs, config, live, definition); await alarms(clients, config); if ((values[0]?.value || "false") === config.value) { + if (config.value === "true" && managed === undefined) { + const latest = await describe(clients.ecs, definition.family); + const explicit = latest.definition.containerDefinitions?.[0]?.environment?.some((e) => e.name === ATTACHMENT_PROXY); + if (tagValue(latest.tags, ATTACHMENT_PROXY_TAG) === undefined && !explicit) { + throw new Error("Enabled attachment configuration requires a management tag or an explicit Terraform value before a no-change request"); + } + } report("Backend already has the requested attachment configuration; no change"); await observe(clients, config, definition, live.desiredCount, sleep, report); return { taskDefinition: live.taskDefinition, previous: live.taskDefinition, changed: false }; diff --git a/.github/scripts/aws-backend-config.test.cjs b/.github/scripts/aws-backend-config.test.cjs index 2a840590c..0ea320dc3 100644 --- a/.github/scripts/aws-backend-config.test.cjs +++ b/.github/scripts/aws-backend-config.test.cjs @@ -75,7 +75,11 @@ function fixture(t, options = {}) { return { MetricAlarms: options.alarm && live.taskDefinition !== arn(1) ? [{ AlarmName: "fixture-backend-5xx" }] : [] }; } }; const run = () => configure({ ecs, cloudwatch }, cfg, async (ms) => sleeps.push(ms), () => {}); - return { env, cfg, live, base, tags, defs, calls, sleeps, run }; + const prepare = (definition, nextTags) => { + latest = arn(defs.size + 1); + defs.set(latest, { definition: { ...structuredClone(definition), taskDefinitionArn: latest }, tags: structuredClone(nextTags) }); + }; + return { env, cfg, live, base, tags, defs, calls, sleeps, run, prepare }; } const mutations = (f) => f.calls.filter((c) => ["RegisterTaskDefinitionCommand", "UpdateServiceCommand"].includes(c.name)); @@ -116,6 +120,44 @@ test("disabling is explicit and preserves the remainder of the running definitio assert.equal(current.tags.find((tag) => tag.key === ATTACHMENT_PROXY_TAG).value, "false"); }); +test("an enabled no-change request requires a deployment source that owns the setting", async (t) => { + const f = fixture(t); + f.prepare(f.base, f.tags); + f.base.containerDefinitions[0].environment.push({ name: ATTACHMENT_PROXY, value: "true" }); + await assert.rejects(f.run(), /requires a management tag or an explicit Terraform value/); + assert.deepEqual(mutations(f), []); + assert.deepEqual(f.sleeps, []); +}); + +for (const value of ["true", "false"]) test(`an explicit Terraform ${value} value owns an enabled no-change request`, async (t) => { + const f = fixture(t); + const template = structuredClone(f.base); + template.containerDefinitions[0].environment.push({ name: ATTACHMENT_PROXY, value }); + f.prepare(template, f.tags); + f.base.containerDefinitions[0].environment.push({ name: ATTACHMENT_PROXY, value: "true" }); + assert.equal((await f.run()).changed, false); + assert.deepEqual(mutations(f), []); + assert.equal(f.sleeps.reduce((a, b) => a + b, 0), 300000); +}); + +test("a live managed enabled setting remains owned when the latest template omits it", async (t) => { + const f = fixture(t); + f.prepare(f.base, f.tags); + f.base.containerDefinitions[0].environment.push({ name: ATTACHMENT_PROXY, value: "true" }); + f.tags.push({ key: ATTACHMENT_PROXY_TAG, value: "true" }); + assert.equal((await f.run()).changed, false); + assert.deepEqual(mutations(f), []); + assert.equal(f.sleeps.reduce((a, b) => a + b, 0), 300000); +}); + +test("an absent false setting needs no ownership change", async (t) => { + const f = fixture(t); + f.cfg.value = "false"; + assert.equal((await f.run()).changed, false); + assert.deepEqual(mutations(f), []); + assert.equal(f.sleeps.reduce((a, b) => a + b, 0), 300000); +}); + test("every preflight task is described within the API batch limit", async (t) => { const f = fixture(t, { taskCount: 101 }); await f.run(); diff --git a/docs/content/docs/development/aws-fargate.mdx b/docs/content/docs/development/aws-fargate.mdx index d890e1ada..10f9d2787 100644 --- a/docs/content/docs/development/aws-fargate.mdx +++ b/docs/content/docs/development/aws-fargate.mdx @@ -299,7 +299,9 @@ count change stops automatic rollback for operator inspection. It runs no migration, one-off task or fleet rollout and does not modify another service. Refresh the task snapshot before a repeated request. A stale, missing, duplicate, foreign or draining task is refused. A request for the existing setting observes -another full bake without rolling again. +another full bake without rolling again. An already enabled setting requires +either its live management tag or a value in the latest deployment definition. +If neither owns it, set the value explicitly in Terraform before requesting no change. The task definition records the setting in `warmbly-config-attachment-download-proxy`. Future deployments and secret From 4daa82b34e00d7819856e1dc11fe1fffb47b516d Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 16:02:52 +0100 Subject: [PATCH 147/318] feat: compare ECS named bindings independently of provider ordering while preserving task definition values --- .github/scripts/aws-backend-config.test.cjs | 18 ++++++++++++++ .github/scripts/aws-deploy.cjs | 21 +++++++++++++++- .github/scripts/aws-deploy.test.cjs | 27 ++++++++++++++++++++- 3 files changed, 64 insertions(+), 2 deletions(-) diff --git a/.github/scripts/aws-backend-config.test.cjs b/.github/scripts/aws-backend-config.test.cjs index 0ea320dc3..90272788a 100644 --- a/.github/scripts/aws-backend-config.test.cjs +++ b/.github/scripts/aws-backend-config.test.cjs @@ -58,6 +58,7 @@ function fixture(t, options = {}) { case "RegisterTaskDefinitionCommand": { latest = arn(defs.size + 1); const { tags: nextTags, ...input } = structuredClone(command.input); + if (options.reorderEnvironment) input.containerDefinitions[0].environment.reverse(); defs.set(latest, { definition: { ...input, status: "ACTIVE", taskDefinitionArn: latest }, tags: nextTags }); return { taskDefinition: { taskDefinitionArn: latest } }; } @@ -108,6 +109,23 @@ test("only the allowlisted flag and ownership tag change; every live task is che assert.equal(f.sleeps.reduce((a, b) => a + b, 0), 600000, "an interrupted bake is always observed afresh without rolling again"); }); +test("provider environment ordering preserves a successful full bake without rollback", async (t) => { + const f = fixture(t, { reorderEnvironment: true }); + assert.equal((await f.run()).changed, true); + assert.equal(f.live.taskDefinition, arn(2)); + assert.deepEqual(f.calls.filter((c) => c.name === "UpdateServiceCommand").map((c) => c.input.taskDefinition), [arn(2)]); + assert.equal(f.sleeps.reduce((a, b) => a + b, 0), 300000); +}); + +test("a prepared definition with reordered environment bindings is reused", async (t) => { + const f = fixture(t); + const prepared = structuredClone(f.base); + prepared.containerDefinitions[0].environment.unshift({ name: ATTACHMENT_PROXY, value: "true" }); + f.prepare(prepared, [...f.tags, { key: ATTACHMENT_PROXY_TAG, value: "true" }]); + assert.equal((await f.run()).taskDefinition, arn(2)); + assert.ok(!f.calls.some((c) => c.name === "RegisterTaskDefinitionCommand")); +}); + test("disabling is explicit and preserves the remainder of the running definition", async (t) => { const f = fixture(t); await f.run(); diff --git a/.github/scripts/aws-deploy.cjs b/.github/scripts/aws-deploy.cjs index 731bda184..21f50d262 100644 --- a/.github/scripts/aws-deploy.cjs +++ b/.github/scripts/aws-deploy.cjs @@ -134,8 +134,27 @@ function repin(container, pins) { } } +function canonical(value) { + if (Array.isArray(value)) return value.map(canonical); + if (value && typeof value === "object") return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])])); + return value; +} + +function comparableDefinition(definition) { + return REGISTER_FIELDS.map((field) => { + let value = definition[field] ?? null; + if (field === "containerDefinitions" && value) value = value.map((container) => { + const copy = { ...container }; + // ECS may reorder named bindings; command and other array order stays significant. + for (const key of ["environment", "secrets"]) if (copy[key]) copy[key] = [...copy[key]].sort((a, b) => a.name.localeCompare(b.name)); + return copy; + }); + return canonical(value); + }); +} + function same(a, b) { - return JSON.stringify(REGISTER_FIELDS.map((f) => a[f] ?? null)) === JSON.stringify(REGISTER_FIELDS.map((f) => b[f] ?? null)); + return JSON.stringify(comparableDefinition(a)) === JSON.stringify(comparableDefinition(b)); } const canonicalTags = (tags) => JSON.stringify(tags.filter((t) => !t.key.startsWith("aws:")).sort((a, b) => a.key.localeCompare(b.key))); diff --git a/.github/scripts/aws-deploy.test.cjs b/.github/scripts/aws-deploy.test.cjs index fcb86ec89..2528ed0de 100644 --- a/.github/scripts/aws-deploy.test.cjs +++ b/.github/scripts/aws-deploy.test.cjs @@ -3,7 +3,32 @@ const assert = require("node:assert/strict"); const { mkdtempSync, writeFileSync } = require("node:fs"); const { join } = require("node:path"); const { tmpdir } = require("node:os"); -const { configuration, deploy, runTask, compareTags, parseRef, ATTACHMENT_PROXY, ATTACHMENT_PROXY_TAG } = require("./aws-deploy.cjs"); +const { configuration, deploy, runTask, compareTags, parseRef, same, ATTACHMENT_PROXY, ATTACHMENT_PROXY_TAG } = require("./aws-deploy.cjs"); + +test("definition equality compares named bindings while preserving every value and command order", () => { + const base = { family: "fixture", containerDefinitions: [{ name: "backend", image: "fixture@sha256:fixed", + command: ["serve", "--tls"], environment: [{ name: "TLS_ONLY", value: "true" }, { name: "REGION", value: "fixture" }], + secrets: [{ name: "PRIMARY_DB", valueFrom: "database:version-one" }, { name: "AUTH_SECRET", valueFrom: "auth:version-one" }] }] }; + const reordered = structuredClone(base); + reordered.containerDefinitions[0].environment.reverse(); + reordered.containerDefinitions[0].secrets.reverse(); + reordered.containerDefinitions[0].environment = reordered.containerDefinitions[0].environment.map(({ name, value }) => ({ value, name })); + assert.ok(same(base, reordered)); + for (const mutate of [ + (c) => { c.environment[0].value = "false"; }, + (c) => { c.environment[0].name = "OTHER"; }, + (c) => { c.environment.pop(); }, + (c) => { c.environment.push({ ...c.environment[0] }); }, + (c) => { c.secrets[0].valueFrom = "database:version-two"; }, + (c) => { c.secrets.pop(); }, + (c) => { c.command.reverse(); }, + (c) => { c.image = "other@sha256:fixed"; }, + ]) { + const changed = structuredClone(base); + mutate(changed.containerDefinitions[0]); + assert.equal(same(base, changed), false); + } +}); const root = "arn:aws:ecs:us-east-1:000000000000:"; const registry = "ghcr.io/warmbly/warmbly"; From a7721887a8f9a09cd922344893cee3993dffcedc Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 16:32:27 +0100 Subject: [PATCH 148/318] feat: wake a Gmail mailbox once its push channel is stored, resend a PUSH_STATE the bus refused and report a Graph subscription that was deleted or gone even when its replacement fails, follow Graph subscription list continuations, drain a wake the timed pass covers, bound SYNC_WAKE publishes by the caller's deadline, keep the Google service account out of the compose worker, and correct the mailbox push docs on the Gmail publisher principal, what GMAIL_PUSH_TOPIC alone does, poll intervals and who calls the push routes --- docker-compose.yml | 2 ++ docs/content/docs/api/endpoints.mdx | 2 +- .../docs/development/configuration.mdx | 2 +- .../content/docs/development/mailbox-push.mdx | 10 +++--- docs/content/docs/guides/mailboxes.mdx | 2 +- internal/app/consumer/event_push_state.go | 9 +++++ internal/app/worker/wmail/push.go | 17 +++++++--- internal/app/worker/wmail/push_test.go | 3 ++ internal/app/worker/wmail/start_sync.go | 5 +++ internal/client/msgraph/subscription.go | 32 +++++++++++++---- internal/client/msgraph/subscription_test.go | 34 +++++++++++++++++++ internal/events/publisher.go | 12 ++++--- .../repository/pg_mailbox_push_live_test.go | 4 ++- 13 files changed, 111 insertions(+), 23 deletions(-) create mode 100644 internal/client/msgraph/subscription_test.go diff --git a/docker-compose.yml b/docker-compose.yml index 9b34c8995..85e2057cb 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -559,6 +559,8 @@ services: BOX_GOOGLE_CLIENT_SECRET: ${BOX_GOOGLE_CLIENT_SECRET:-} BOX_OUTLOOK_CLIENT_ID: ${BOX_OUTLOOK_CLIENT_ID:-} BOX_OUTLOOK_CLIENT_SECRET: ${BOX_OUTLOOK_CLIENT_SECRET:-} + # A worker holds no cloud credential; only the consumer reads this one. + GOOGLE_APPLICATION_CREDENTIALS_JSON: "" volumes: - ${WARMBLY_BLOBS:-blobs}:/data/blobs - ${WARMBLY_WORKER_STATE:-worker_state}:/data/state diff --git a/docs/content/docs/api/endpoints.mdx b/docs/content/docs/api/endpoints.mdx index 9537e3c30..8b26689e6 100644 --- a/docs/content/docs/api/endpoints.mdx +++ b/docs/content/docs/api/endpoints.mdx @@ -856,7 +856,7 @@ On the backend's host but outside `/v1`, called by Slack and never by an API key - `POST /api/v1/integrations/slack/events`, `POST /api/v1/integrations/slack/interactivity` (Slack signature). Each request must carry a valid Slack `X-Slack-Signature` made with the instance's signing secret over a timestamp within five minutes, and its body is capped at 1 MiB. A bad signature is `401` `unauthorized`, and nothing in the body is parsed before the signature checks out. With no `SLACK_SIGNING_SECRET` set they answer `503` `slack_not_configured`. They answer Slack within its three-second limit and do the work afterwards. See [Slack app](/development/slack-app/) -On the backend's host but outside `/v1`, called by Microsoft Graph and never by an API key or a session: +On the backend's host but outside `/v1`, called by Microsoft Graph or a Google Cloud Pub/Sub push subscription and never by an API key or a session: - `POST /api/v1/mailbox-push/gmail` (Gmail watch notifications from a Cloud Pub/Sub push subscription, used when `GMAIL_PUSH_SERVICE_ACCOUNT` is set). Each request must carry a Google-signed bearer token whose audience is this URL and whose sender is that service account, or it gets `401`. The body is capped at 64 KiB. The answer is `204` once the mailbox's worker has been woken or when the body names no mailbox, `503` when the wake could not be sent, so Pub/Sub retries, and `404` when Gmail push is not configured. See [realtime mailbox sync](/development/mailbox-push/) - `POST /api/v1/mailbox-push/graph/:emailId` (Microsoft Graph change and lifecycle notifications for one mailbox, used when `GRAPH_PUSH` is on). A request carrying `validationToken` gets the token echoed as `text/plain`, which is how Graph confirms a new subscription. Otherwise each notification item is accepted only with the client state issued for that mailbox, and items without it are ignored. The body is capped at 1 MiB. The answer is `202` once the mailbox's worker has been woken, also for a body with nothing to act on, and `503` when the wake could not be sent, so Graph retries. See [realtime mailbox sync](/development/mailbox-push/) diff --git a/docs/content/docs/development/configuration.mdx b/docs/content/docs/development/configuration.mdx index 9dfaa8be5..a33fe02ae 100644 --- a/docs/content/docs/development/configuration.mdx +++ b/docs/content/docs/development/configuration.mdx @@ -769,7 +769,7 @@ How quickly a worker sees new mail. Workers poll every mailbox once a minute unl | `IMAP_IDLE` | Read by workers. Holds each IMAP mailbox's INBOX in `IDLE` on a second connection and syncs within seconds of a change; other folders are then polled every 3 minutes. `false` keeps IMAP mailboxes on the one-minute poll | `true` | yes | | `SYNC_PUSH_FALLBACK_INTERVAL` | Read by workers. How often a mailbox with a live Gmail watch or Graph subscription is still polled, as a Go duration. Bounded to `2m` to `60m`; an invalid value uses the default | `10m` | yes | | `GRAPH_PUSH` | Read by the backend. `true` has each Outlook and Microsoft 365 mailbox's worker open a Microsoft Graph change-notification subscription posting to `BACKEND_PUBLIC_URL` (else `API_PUBLIC_URL`) plus `/api/v1/mailbox-push/graph/`. Stays off unless that URL is `https` and reachable by Microsoft. Notifications are authenticated with a value derived from `AUTH_SECRET`. Unset again, workers close their subscriptions as mailboxes reload | `false` | yes | -| `GMAIL_PUSH_TOPIC` | Read by the backend. The Cloud Pub/Sub topic, `projects//topics/`, each Gmail mailbox's worker watches into. Unset again, workers stop their watches as mailboxes reload | unset | yes | +| `GMAIL_PUSH_TOPIC` | Read by the backend. The Cloud Pub/Sub topic, `projects//topics/`, each Gmail mailbox's worker watches into. Set alone it moves Gmail mailboxes to the push fallback poll, so set it with `GMAIL_PUSH_SERVICE_ACCOUNT` or a consumer's `GMAIL_PUSH_SUBSCRIPTION`. Unset again, workers stop their watches as mailboxes reload | unset | yes | | `GMAIL_PUSH_SERVICE_ACCOUNT` | Read by the backend. The service account a Pub/Sub push subscription signs its requests with. Set, the backend accepts Gmail notifications at `BACKEND_PUBLIC_URL` (else `API_PUBLIC_URL`) plus `/api/v1/mailbox-push/gmail`, checking each request's Google-signed token. Stays off unless that URL is `https` | unset | yes | | `GMAIL_PUSH_SUBSCRIPTION` | Read by the consumer. A pull subscription on that topic, `projects//subscriptions/`, it reads notifications from instead of a push subscription. Needs no public endpoint | unset | yes | | `GOOGLE_APPLICATION_CREDENTIALS_JSON` | Read by the consumer for Gmail push: a Google service account key (JSON) holding **Pub/Sub Subscriber** on the subscription. Unset uses Application Default Credentials. The backend reads the same variable for Cloud Tasks callbacks when `TASKS_PROVIDER=gcloud` | unset | yes | diff --git a/docs/content/docs/development/mailbox-push.mdx b/docs/content/docs/development/mailbox-push.mdx index eaffe6fab..e42831714 100644 --- a/docs/content/docs/development/mailbox-push.mdx +++ b/docs/content/docs/development/mailbox-push.mdx @@ -11,7 +11,7 @@ The worker that holds a mailbox syncs it on a timer. When the mailbox's provider |---|---|---|---| | IMAP and SMTP | `IDLE` on INBOX, on a second connection | every 3 minutes, for the other folders | on; `IMAP_IDLE=false` turns it off | | Microsoft 365 and Outlook | Microsoft Graph change notifications | `SYNC_PUSH_FALLBACK_INTERVAL` (10 minutes) | off until `GRAPH_PUSH=true` and a public HTTPS backend URL | -| Gmail and Google Workspace | Gmail `users.watch` into Cloud Pub/Sub | `SYNC_PUSH_FALLBACK_INTERVAL` (10 minutes) | off until `GMAIL_PUSH_TOPIC` and either `GMAIL_PUSH_SERVICE_ACCOUNT` (push) or `GMAIL_PUSH_SUBSCRIPTION` (pull) are set | +| Gmail and Google Workspace | Gmail `users.watch` into Cloud Pub/Sub | `SYNC_PUSH_FALLBACK_INTERVAL` (10 minutes) | off until `GMAIL_PUSH_TOPIC` is set on the backend | A mailbox without a live signal is polled every minute, as before. That covers an IMAP server without `IDLE`, a Gmail or Outlook mailbox on an instance that has not configured push, and any mailbox whose channel the provider refused. @@ -75,13 +75,15 @@ Pub/Sub delivers notifications one of two ways: - **Push to the backend** (use this when the backend has a public HTTPS URL). Pub/Sub POSTs each notification to `/api/v1/mailbox-push/gmail`. Every request carries a token Google signs for a service account you choose; the backend accepts it only when Google's signature checks out, the audience is that URL and the sender is `GMAIL_PUSH_SERVICE_ACCOUNT`. It answers 204 once the worker is woken and 503 when it cannot be, and Pub/Sub retries with backoff until it gets a 2xx. - **Pull from the consumer** (for an instance Pub/Sub cannot reach). The consumer holds a streaming connection to a pull subscription and reads notifications from it. -Both end the same way: the mailbox's worker is sent `SYNC_WAKE` and runs its usual Gmail sync. Only one of the two should be set up for a topic. +Both end the same way: the mailbox's worker is sent `SYNC_WAKE` and runs its usual Gmail sync. Only one of the two should be set up for a topic. `GMAIL_PUSH_TOPIC` alone turns the watch on and moves Gmail mailboxes to the 10-minute poll, and the backend cannot tell whether anything reads the topic. Set it only once a push subscription with `GMAIL_PUSH_SERVICE_ACCOUNT` or a pull subscription with `GMAIL_PUSH_SUBSCRIPTION` is in place, or Gmail mail can take up to 10 minutes to appear. + +Gmail names a mailbox only by its address, so a notification reaches a mailbox once its channel is stored. When the consumer stores a Gmail channel it wakes that mailbox once, so a change that landed while the watch was opening is not left for the poll. Set up, once per instance, in the Google Cloud project that holds the Gmail OAuth client (`BOX_GOOGLE_CLIENT_ID`). Gmail only accepts a topic in the project making the watch call, so a [whole-domain grant's](/development/whole-domain-connect/) delegation service account must live in the same project: 1. Under **APIs & Services > Library**, enable the **Cloud Pub/Sub API**. 2. Under **Pub/Sub > Topics**, create a topic, for example `gmail-push`. Its full name is `projects//topics/gmail-push`. -3. On the topic's **Permissions**, grant the **Pub/Sub Publisher** role to `[EMAIL]`, Gmail's push service account. An organization policy that restricts sharing to your own domain (**Domain restricted sharing**) refuses this grant; ask an Organization Policy Administrator for an exception on this project. +3. On the topic's **Permissions**, grant the **Pub/Sub Publisher** role to `gmail-api-push@system.gserviceaccount.com`, Gmail's push service account. An organization policy that restricts sharing to your own domain (**Domain restricted sharing**) refuses this grant; ask an Organization Policy Administrator for an exception on this project. 4. Create the subscription: - **Push:** create a service account for signing, for example `gmail-push-signer`, and a **push** subscription on the topic with endpoint `/api/v1/mailbox-push/gmail`, **Enable authentication** on, that service account, and the audience left empty (it defaults to the endpoint). The Pub/Sub service agent needs **Service Account Token Creator** on that account, which the console offers to grant. - **Pull:** create a **pull** subscription, for example `warmbly-consumer`, and give the identity the consumer runs as the **Pub/Sub Subscriber** role on it. That is either a service account whose JSON key you pass as `GOOGLE_APPLICATION_CREDENTIALS_JSON`, or the Application Default Credentials of the machine the consumer runs on. @@ -132,7 +134,7 @@ Migration `000341` adds `fleet_nodes.sync_wake_protocol` (default `0`) and the ` | Outlook mail still takes about a minute | Check that `GRAPH_PUSH=true` and that `BACKEND_PUBLIC_URL` (or `API_PUBLIC_URL`) is an `https://` URL. Plain `http` leaves push off. From outside your network, `curl -X POST '/api/v1/mailbox-push/graph/x?validationToken=ok'` must answer `ok`; Microsoft sends the same request when it creates a subscription | | Graph subscriptions are never created | Microsoft cannot reach the URL, or the proxy in front of the backend does not forward `/api/v1/mailbox-push/`. Workers retry every 30 minutes and log the refusal at debug level | | Gmail watch fails with `Invalid topicName` | The topic is in a different project from the OAuth client or delegation service account making the call. Create it in that project | -| Gmail watch fails with a permission error | Gmail's push service account `[EMAIL]` lacks **Pub/Sub Publisher** on the topic, often because domain restricted sharing refused the grant | +| Gmail watch fails with a permission error | Gmail's push service account `gmail-api-push@system.gserviceaccount.com` lacks **Pub/Sub Publisher** on the topic, often because domain restricted sharing refused the grant | | Pub/Sub shows push deliveries failing with `401` | The subscription signs with a different service account than `GMAIL_PUSH_SERVICE_ACCOUNT`, authentication is off, or its audience was set to something other than the endpoint URL | | Pub/Sub shows push deliveries failing with `404` | `GMAIL_PUSH_SERVICE_ACCOUNT` is unset on the backend, or `BACKEND_PUBLIC_URL` is not `https` | | Consumer logs `Gmail push subscriber stopped` | `GMAIL_PUSH_SUBSCRIPTION` is not `projects//subscriptions/`, the subscription does not exist, or the consumer's identity lacks **Pub/Sub Subscriber** on it | diff --git a/docs/content/docs/guides/mailboxes.mdx b/docs/content/docs/guides/mailboxes.mdx index bde813dd9..eed1e7c02 100644 --- a/docs/content/docs/guides/mailboxes.mdx +++ b/docs/content/docs/guides/mailboxes.mdx @@ -306,7 +306,7 @@ Connecting a mailbox does two things: it imports the mailbox's recent history, a **Live sync** follows the provider's supported folders, including junk (so placement problems are visible) and sent mail (so a conversation shows both sides). Outlook follows Inbox, Sent, Junk, Drafts and Archive where Archive is available; it does not follow every custom Graph folder. Read state, flags, deletions and moves are mirrored too. -New mail usually appears within seconds when the provider tells Warmbly about it: an IMAP server that supports `IDLE` does this for the inbox, and Gmail and Outlook do it on instances whose operator has turned on [push notifications](/development/mailbox-push/). Otherwise, and for other folders, mail is picked up by a regular check, about once a minute. Providers do not promise when they announce a change, so neither does Warmbly; the regular check always runs as well. +New mail usually appears within seconds when the provider tells Warmbly about it: an IMAP server that supports `IDLE` does this for the inbox, and Gmail and Outlook do it on instances whose operator has turned on [push notifications](/development/mailbox-push/). Mail is also picked up by a regular check: about once a minute for a mailbox without one of those signals, every 3 minutes for the other folders of an IMAP mailbox whose inbox is held in `IDLE`, and every 10 minutes (the default) for a Gmail or Outlook mailbox with push on. Providers do not promise when they announce a change, so neither does Warmbly; the regular check always runs as well. The Sync card distinguishes a completed history import from a recent successful live check. An unfinished pass, provider failure, recovery scan or budget hold does not refresh the last successful check or erase the last observed deferred count. That count is an observation from sync, not a measurement of all mail still on the provider. A worker heartbeat alone is not evidence that a mailbox is current. Repeated connection failures refresh the warning's observation time without generating a new notification each pass; no later successful check means recovery is unverified. diff --git a/internal/app/consumer/event_push_state.go b/internal/app/consumer/event_push_state.go index 632ac4220..039393a45 100644 --- a/internal/app/consumer/event_push_state.go +++ b/internal/app/consumer/event_push_state.go @@ -3,6 +3,9 @@ package jobs import ( "context" + "github.com/google/uuid" + "github.com/rs/zerolog/log" + "github.com/warmbly/warmbly/internal/app/mailpush" "github.com/warmbly/warmbly/internal/models" ) @@ -16,5 +19,11 @@ func (s *JobsService) HandlePushState(ctx context.Context, e *models.JobEventPus CaptureError(e.UserID, e.EmailID, err) return err } + // Gmail reaches a mailbox only through this row, so a change that landed before it was stored is synced now. + if e.State != nil && e.State.Provider == models.MailboxPushGmail && s.Publisher != nil { + if err := mailpush.NewWaker(s.MailboxPushRepository, s.Publisher, nil).WakeMailboxes(ctx, []uuid.UUID{e.EmailID}, false); err != nil { + log.Debug().Err(err).Str("email_id", e.EmailID.String()).Msg("stored Gmail channel could not wake its mailbox; the poll covers it") + } + } return nil } diff --git a/internal/app/worker/wmail/push.go b/internal/app/worker/wmail/push.go index db7762ab8..15514783b 100644 --- a/internal/app/worker/wmail/push.go +++ b/internal/app/worker/wmail/push.go @@ -43,6 +43,8 @@ type pushChannel struct { renew atomic.Bool // failing keeps a refused channel to one warning until it opens again. failing atomic.Bool + // unsent is set while the control plane has not taken the current state. + unsent atomic.Bool // imapIdle is set while the IMAP watcher holds INBOX in IDLE. imapIdle atomic.Bool imapCred *models.Service @@ -133,18 +135,22 @@ func (w *WMail) maintainPush(ctx context.Context) { event = log.Warn() } event.Err(err).Str("email_id", w.ID.String()).Msg("mailbox push channel not opened; polling continues") - return + } else { + w.push.failing.Store(false) } - w.push.failing.Store(false) - if samePush(state, next) { + // A failed open still reports a channel it closed on the way, and a lost report is sent again next pass. + if samePush(state, next) && !w.push.unsent.Load() { return } w.push.mu.Lock() w.push.state = next w.push.mu.Unlock() if err := w.onEvent(models.JobEventTypePushState, &models.JobEventPushState{UserID: w.UserID, EmailID: w.ID, State: next}); err != nil { + w.push.unsent.Store(true) log.Debug().Err(err).Str("email_id", w.ID.String()).Msg("could not record mailbox push channel") + return } + w.push.unsent.Store(false) } func samePush(a, b *models.MailboxPushState) bool { @@ -179,8 +185,9 @@ func (w *WMail) maintainGraphPush(ctx context.Context, want *models.AddWorkerEma if !msgraph.SubscriptionGone(err) { return state, err } - } else if state != nil && state.SubscriptionID != "" { - _ = client.DeleteSubscription(ctx, state.SubscriptionID) + state = nil + } else if state != nil && state.SubscriptionID != "" && client.DeleteSubscription(ctx, state.SubscriptionID) == nil { + state = nil } sub, err := client.CreateSubscription(ctx, want.GraphNotificationURL, want.GraphClientState, now) if msgraph.SubscriptionConflict(err) { diff --git a/internal/app/worker/wmail/push_test.go b/internal/app/worker/wmail/push_test.go index 096477922..d63dc7b42 100644 --- a/internal/app/worker/wmail/push_test.go +++ b/internal/app/worker/wmail/push_test.go @@ -27,6 +27,9 @@ func TestWakeRunsTheNextPassEarlyOnlyAfterACleanPass(t *testing.T) { if time.Since(started) < 50*time.Millisecond { t.Fatal("a wake cut short the backoff after a failed pass") } + if len(w.wake) != 0 { + t.Fatal("a wake the timed pass covers was left for another pass") + } } func TestWakesCoalesce(t *testing.T) { diff --git a/internal/app/worker/wmail/start_sync.go b/internal/app/worker/wmail/start_sync.go index 23ec435df..f81052ee0 100644 --- a/internal/app/worker/wmail/start_sync.go +++ b/internal/app/worker/wmail/start_sync.go @@ -62,6 +62,11 @@ func (w *WMail) waitForPass(ctx context.Context, delay time.Duration, wakeable b case <-ctx.Done(): return false case <-timer.C: + // The pass about to run covers any wake that queued during the wait. + select { + case <-w.wake: + default: + } return true case <-wake: // Let the rest of a burst land so one pass covers it. diff --git a/internal/client/msgraph/subscription.go b/internal/client/msgraph/subscription.go index cb3b27ea5..26479a17d 100644 --- a/internal/client/msgraph/subscription.go +++ b/internal/client/msgraph/subscription.go @@ -2,6 +2,7 @@ package msgraph import ( "context" + "encoding/json" "errors" "net/http" "net/url" @@ -67,17 +68,36 @@ func (c *Client) DeleteSubscription(ctx context.Context, id string) error { return err } +// subscriptionListMaxPages bounds how many continuations ListSubscriptions follows. +const subscriptionListMaxPages = 20 + // ListSubscriptions returns the subscriptions this app holds for the signed-in mailbox. func (c *Client) ListSubscriptions(ctx context.Context) ([]Subscription, error) { - var out struct { - Value []Subscription `json:"value"` + var subs []Subscription + next := graphBase + "/subscriptions" + for range subscriptionListMaxPages { + var page struct { + Value []Subscription `json:"value"` + NextLink json.RawMessage `json:"@odata.nextLink"` + } + if err := c.doJSON(ctx, http.MethodGet, next, nil, &page); err != nil { + return nil, err + } + subs = append(subs, page.Value...) + if page.NextLink == nil { + return subs, nil + } + link, ok := graphContinuation(page.NextLink) + if !ok { + return nil, errSubscriptionListIncomplete + } + next = link } - if err := c.doJSON(ctx, http.MethodGet, graphBase+"/subscriptions", nil, &out); err != nil { - return nil, err - } - return out.Value, nil + return nil, errSubscriptionListIncomplete } +var errSubscriptionListIncomplete = errors.New("msgraph: subscription list continuation was not followed to its end") + // SubscriptionGone reports a subscription Graph no longer has. func SubscriptionGone(err error) bool { return subscriptionStatus(err) == http.StatusNotFound diff --git a/internal/client/msgraph/subscription_test.go b/internal/client/msgraph/subscription_test.go new file mode 100644 index 000000000..5de596aec --- /dev/null +++ b/internal/client/msgraph/subscription_test.go @@ -0,0 +1,34 @@ +package msgraph + +import ( + "net/http" + "testing" +) + +func TestListSubscriptionsFollowsContinuations(t *testing.T) { + c := deltaTestClient(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.URL.Query().Get("$skiptoken") == "" { + _, _ = w.Write([]byte(`{"value":[{"id":"a"}],"@odata.nextLink":"https://graph.microsoft.com/v1.0/subscriptions?$skiptoken=2"}`)) + return + } + _, _ = w.Write([]byte(`{"value":[{"id":"b","notificationUrl":"https://x"}]}`)) + }, nil) + subs, err := c.ListSubscriptions(t.Context()) + if err != nil { + t.Fatal(err) + } + if len(subs) != 2 || subs[0].ID != "a" || subs[1].ID != "b" { + t.Fatalf("subscriptions %+v, want both pages", subs) + } +} + +func TestListSubscriptionsRefusesAContinuationOffGraph(t *testing.T) { + c := deltaTestClient(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"value":[],"@odata.nextLink":"https://example.com/v1.0/subscriptions"}`)) + }, nil) + if _, err := c.ListSubscriptions(t.Context()); err == nil { + t.Fatal("a continuation off Graph's root was followed") + } +} diff --git a/internal/events/publisher.go b/internal/events/publisher.go index 74761f9f3..007077ac7 100644 --- a/internal/events/publisher.go +++ b/internal/events/publisher.go @@ -402,7 +402,8 @@ func (p *publisher) PublishSyncWake(ctx context.Context, workerID uuid.UUID, wak Type: models.WorkerEventTypeSyncWake, Body: wake, } - return p.publish(kafka.GetWorkerTopic(workerID.String()), wake.EmailID.String(), workerEvent) + // The caller's deadline holds here: a wake answers a provider that stops waiting within seconds. + return p.publishCtx(ctx, kafka.GetWorkerTopic(workerID.String()), wake.EmailID.String(), workerEvent) } // PublishEmailValidation publishes a credential-validation request to the worker. @@ -437,6 +438,10 @@ func (p *publisher) reportPublishFailure(topic string, err error) { // publish serializes (via codec) and publishes (via bus) an event. func (p *publisher) publish(topic, key string, event interface{}) error { + return p.publishCtx(context.Background(), topic, key, event) +} + +func (p *publisher) publishCtx(ctx context.Context, topic, key string, event interface{}) error { if p.bus == nil { // Bus not configured, skip publishing. return nil @@ -447,15 +452,14 @@ func (p *publisher) publish(topic, key string, event interface{}) error { return fmt.Errorf("codec not configured") } - ctx := context.Background() data, err := p.codec.Serialize(ctx, topic, event) if err != nil { errs.CaptureException(fmt.Errorf("failed to serialize event: %w", err)) return err } if err := p.bus.Publish(ctx, topic, key, data); err != nil { - // A bus closed under us is shutdown, not a fault worth an issue. - if !errors.Is(err, eventbus.ErrBusClosed) { + // A bus closed under us is shutdown, and a caller's expired deadline is the caller's; neither is worth an issue. + if !errors.Is(err, eventbus.ErrBusClosed) && ctx.Err() == nil { p.reportPublishFailure(topic, err) } return err diff --git a/internal/repository/pg_mailbox_push_live_test.go b/internal/repository/pg_mailbox_push_live_test.go index 72c09a8da..7e5101402 100644 --- a/internal/repository/pg_mailbox_push_live_test.go +++ b/internal/repository/pg_mailbox_push_live_test.go @@ -117,7 +117,9 @@ func TestLiveWakeTargetsSkipWorkersThatCannotActOnAWake(t *testing.T) { t.Fatalf("targets %+v, want only the mailbox on the wake-capable worker", targets) } - if got, _ := repo.GmailWakeTargets(ctx, f.gmailAddress); len(got) != 0 { + if got, err := repo.GmailWakeTargets(ctx, f.gmailAddress); err != nil { + t.Fatal(err) + } else if len(got) != 0 { t.Fatalf("a Gmail mailbox with no watch was woken: %+v", got) } if err := repo.PutPushState(ctx, f.user, f.gmail, &models.MailboxPushState{Provider: models.MailboxPushGmail, ExpiresAt: time.Now().Add(time.Hour)}); err != nil { From daaed572cce6dec7eeabc1df3f0ce4083a158da2 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 16:32:27 +0100 Subject: [PATCH 149/318] feat: power off a fleet worker or NAT instance whose boot script fails so the Auto Scaling group replaces it, stop an in-flight node update before the lifecycle watcher stops a terminating worker, cap fleet_worker_capacity at the 99999999 the worker accepts with a plan test, bound each CloudWatch fleet metrics publish to one interval, and document FLEET_METRICS_CLOUDWATCH as a fleet enable step and join token renewal every three weeks --- .../aws/workers/fleet-bootstrap.sh.tftpl | 18 +++++++++++++----- deploy/terraform/aws/workers/fleet.tf | 6 +++--- .../aws/workers/nat-bootstrap.sh.tftpl | 10 ++++++++++ .../aws/workers/tests/fleet.tftest.hcl | 10 ++++++++++ docs/content/docs/development/aws-workers.mdx | 11 ++++++++--- internal/app/fleetmetrics/fleetmetrics.go | 8 +++++++- 6 files changed, 51 insertions(+), 12 deletions(-) diff --git a/deploy/terraform/aws/workers/fleet-bootstrap.sh.tftpl b/deploy/terraform/aws/workers/fleet-bootstrap.sh.tftpl index 372ea5001..155ed4603 100644 --- a/deploy/terraform/aws/workers/fleet-bootstrap.sh.tftpl +++ b/deploy/terraform/aws/workers/fleet-bootstrap.sh.tftpl @@ -72,7 +72,8 @@ imds() { main() { while :; do if [ "$(imds meta-data/autoscaling/target-lifecycle-state 2>/dev/null || true)" = "Terminated" ]; then - systemctl stop warmbly-node-update.timer || true + # Stopping the service too ends an update in flight, whose rollback would restart the worker. + systemctl stop warmbly-node-update.timer warmbly-node-update.service || true systemctl stop warmbly-worker || true printf '%s\n' 'warmbly-lifecycle-watch: instance is terminating; worker stopped' return 0 @@ -120,6 +121,16 @@ write_local_env() { fi } +# Until the join succeeds, a failed step powers off, and the group replaces the instance. +on_exit() { + rc=$? + rm -f /run/warmbly-join.sh + if [ "$rc" -ne 0 ]; then + log "boot failed with status $rc; powering off" + systemctl poweroff || true + fi +} + join_once() { token=$(aws ssm get-parameter --region "$REGION" --name "$TOKEN_PARAMETER" --with-decryption --query Parameter.Value --output text) || return 1 [ -n "$token" ] || return 1 @@ -132,6 +143,7 @@ join_once() { } main() { + trap on_exit EXIT instance_id=$(retry imds meta-data/instance-id) NODE_NAME="$NAME_PREFIX-$instance_id" hostnamectl set-hostname "$NODE_NAME" @@ -149,15 +161,11 @@ main() { until join_once; do attempts=$((attempts + 1)) if [ "$attempts" -ge 20 ]; then - # Terminating lets the group launch a replacement instead of carrying a worker that never joined. log "join failed $attempts times; check the join token in $TOKEN_PARAMETER and $INSTANCE_URL" - rm -f /run/warmbly-join.sh - systemctl poweroff return 1 fi sleep 30 done - rm -f /run/warmbly-join.sh log "joined as $NODE_NAME" return 0 } diff --git a/deploy/terraform/aws/workers/fleet.tf b/deploy/terraform/aws/workers/fleet.tf index 64450755c..2f3c93ea8 100644 --- a/deploy/terraform/aws/workers/fleet.tf +++ b/deploy/terraform/aws/workers/fleet.tf @@ -2,7 +2,7 @@ # main.tf, which keep running until an operator retires them. variable "fleet_enabled" { - description = "Create the autoscaling worker fleet and its network" + description = "Create the autoscaling worker fleet and its network; the backend also needs FLEET_METRICS_CLOUDWATCH set to name, or the memory metrics it scales on are never published" type = bool default = false } @@ -79,8 +79,8 @@ variable "fleet_worker_capacity" { type = string default = "auto" validation { - condition = var.fleet_worker_capacity == "auto" || can(regex("^[1-9][0-9]*$", var.fleet_worker_capacity)) - error_message = "Use auto or a positive whole number." + condition = var.fleet_worker_capacity == "auto" || can(regex("^[1-9][0-9]{0,7}$", var.fleet_worker_capacity)) + error_message = "Use auto or a whole number from 1 to 99999999, the largest the worker accepts." } } diff --git a/deploy/terraform/aws/workers/nat-bootstrap.sh.tftpl b/deploy/terraform/aws/workers/nat-bootstrap.sh.tftpl index 1906f74a5..bc5194995 100644 --- a/deploy/terraform/aws/workers/nat-bootstrap.sh.tftpl +++ b/deploy/terraform/aws/workers/nat-bootstrap.sh.tftpl @@ -89,7 +89,17 @@ replace_route() { aws ec2 create-route --region "$REGION" --route-table-id "$ROUTE_TABLE_ID" --destination-cidr-block 0.0.0.0/0 --network-interface-id "$1" >/dev/null } +# A boot that fails leaves the zone without egress, so power off and let the group replace the instance. +on_exit() { + rc=$? + if [ "$rc" -ne 0 ]; then + log "boot failed with status $rc; powering off" + shutdown -h now || true + fi +} + main() { + trap on_exit EXIT retry dnf -y --setopt=retries=20 install iptables-nft write_kernel_settings write_rules_unit diff --git a/deploy/terraform/aws/workers/tests/fleet.tftest.hcl b/deploy/terraform/aws/workers/tests/fleet.tftest.hcl index 4850a3c5a..e11dd207a 100644 --- a/deploy/terraform/aws/workers/tests/fleet.tftest.hcl +++ b/deploy/terraform/aws/workers/tests/fleet.tftest.hcl @@ -169,6 +169,16 @@ run "fleet_worker_capacity_rejects_garbage" { expect_failures = [var.fleet_worker_capacity] } +run "fleet_worker_capacity_rejects_what_the_worker_discards" { + command = plan + variables { + fleet_enabled = true + fleet_instance_url = "https://app.example.com" + fleet_worker_capacity = "100000000" + } + expect_failures = [var.fleet_worker_capacity] +} + run "fleet_scale_in_sits_under_scale_out" { command = plan variables { diff --git a/docs/content/docs/development/aws-workers.mdx b/docs/content/docs/development/aws-workers.mdx index 59f213b3a..6a9cc61d7 100644 --- a/docs/content/docs/development/aws-workers.mdx +++ b/docs/content/docs/development/aws-workers.mdx @@ -78,8 +78,8 @@ The parameter name defaults to `//fleet/join-token` and can be changed with `fleet_join_token_parameter`. A join token works for at most 30 days, and issuing a new one revokes the previous one. Joined workers are unaffected, but a worker launched with an expired token cannot join. Issue and store a new token -before the old one expires, at least monthly, or scale-out stops producing -working workers. +before the old one expires, for example every three weeks, or scale-out stops +producing working workers. ## Enable the fleet @@ -100,6 +100,11 @@ working workers. `nats_security_group_id` is the NATS root's broker security group. Leave it unset only when workers reach the event bus some other way. +4. Set `FLEET_METRICS_CLOUDWATCH` on the backend to the root's `name` and give + its role `cloudwatch:PutMetricData` (see the [metric contract](#metric-contract)). + Without it nothing publishes `WorkerMemoryPercent`, so the fleet scales out + on CPU only and never scales in. + The `fleet` output names the group, its subnets and security group, the join token parameter, the metric contract and `nat_ipv4_addresses`. Workers appear in `warmblyctl fleet list` within a few minutes of launching. @@ -118,7 +123,7 @@ token parameter, the metric contract and `nat_ipv4_addresses`. Workers appear in | `fleet_min_size` | `2` | Smallest fleet | | `fleet_max_size` | `10` | Largest fleet | | `fleet_desired_capacity` | `null` | Starting size; scaling owns it afterwards. `null` starts at the minimum | -| `fleet_worker_capacity` | `auto` | `WARMBLY_WORKER_CAPACITY` on every fleet worker: `auto`, or a positive whole number of mailboxes | +| `fleet_worker_capacity` | `auto` | `WARMBLY_WORKER_CAPACITY` on every fleet worker: `auto`, or a whole number of mailboxes from 1 to 99999999 | | `fleet_region_label` | empty | Optional `--region` label for placement | | `fleet_image_repository` | `ghcr.io/warmbly/warmbly` | Repository `join.sh` pulls the worker image from | | `fleet_target_memory` | `65` | Target for `WorkerMemoryPercent`, the fleet's memory in use | diff --git a/internal/app/fleetmetrics/fleetmetrics.go b/internal/app/fleetmetrics/fleetmetrics.go index a9c8ae141..c5480f56e 100644 --- a/internal/app/fleetmetrics/fleetmetrics.go +++ b/internal/app/fleetmetrics/fleetmetrics.go @@ -87,7 +87,10 @@ func Run(ctx context.Context, d *db.DB, fleet string) error { } ticker := time.NewTicker(interval) defer ticker.Stop() - for { + publish := func() { + // A stalled read or request must not hold back the next minute's sample. + ctx, cancel := context.WithTimeout(ctx, interval) + defer cancel() if u, err := Read(ctx, d); err != nil { log.Warn().Err(err).Msg("fleet usage not published") } else if !u.Known { @@ -102,6 +105,9 @@ func Run(ctx context.Context, d *db.DB, fleet string) error { }); err != nil { log.Warn().Err(err).Msg("fleet usage not published") } + } + for { + publish() select { case <-ctx.Done(): return nil From 6b83ad3306e892742c43d994986c592bf81202cf Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 16:41:20 +0100 Subject: [PATCH 150/318] feat: tie each task dispatch claim to its lease so a lapsed replica cannot release a newer claim, wake webhook delivery from any process through a throttled Postgres NOTIFY on enqueue, keep delivered send-result effects whose task can still re-apply, floor warmup thread-turn pruning at the mail and recovery windows, retry transient unibox backfill failures, hand back run requests for stopped loops, report failed prunes and pool moves, and scope db load to the whole server without non-query text --- .../dashboard/configuration/SettingsTab.tsx | 6 +- cmd/backend/main.go | 6 +- cmd/warmblyctl/db.go | 17 +++--- .../docs/development/configuration.mdx | 2 +- .../content/docs/development/data-control.mdx | 4 +- .../docs/development/instance-health.mdx | 2 +- docs/content/docs/development/warmblyctl.mdx | 4 +- internal/app/consumer/event_tracking.go | 9 ++- .../app/consumer/warmup_mail_retention.go | 4 +- .../app/consumer/warmup_retention_test.go | 2 +- .../app/email/tracking_domain_live_test.go | 12 +++- internal/app/email/tracking_domain_sweep.go | 14 ++--- internal/app/unibox/backfill_body_text.go | 44 +++++++++---- internal/app/webhook/service.go | 59 +++++++++++++----- internal/jobrun/jobrun.go | 12 +++- internal/jobrun/schedule_test.go | 25 +++++++- internal/leader/leader_live_test.go | 6 +- internal/repository/pg_table_retention.go | 8 ++- .../pg_table_retention_live_test.go | 14 +++-- internal/repository/pg_task.go | 38 ++++++------ .../repository/pg_task_claim_live_test.go | 38 +++++++++--- internal/repository/pg_warmup.go | 15 +++-- internal/repository/pg_webhook.go | 24 +++++++- .../warmup_mail_retention_live_test.go | 14 ++++- .../warmup_send_failure_live_test.go | 12 ++-- .../webhook_delivery_notify_live_test.go | 61 +++++++++++++++++++ internal/tasks/warmup_pool_reconcile.go | 22 ++++++- internal/tasksched/local.go | 57 +++++++++++------ internal/tasksched/local_test.go | 10 +-- 29 files changed, 397 insertions(+), 144 deletions(-) create mode 100644 internal/repository/webhook_delivery_notify_live_test.go diff --git a/admin/src/app/dashboard/configuration/SettingsTab.tsx b/admin/src/app/dashboard/configuration/SettingsTab.tsx index d6e84f725..85f50eca1 100644 --- a/admin/src/app/dashboard/configuration/SettingsTab.tsx +++ b/admin/src/app/dashboard/configuration/SettingsTab.tsx @@ -331,9 +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), - notificationDays: String(s.retention.notification_days), - webhookDeliveryDays: String(s.retention.webhook_delivery_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), diff --git a/cmd/backend/main.go b/cmd/backend/main.go index ab2693b39..7581f14d5 100644 --- a/cmd/backend/main.go +++ b/cmd/backend/main.go @@ -867,10 +867,8 @@ func main() { Cache: cache, AppDomains: oauthService.AllowedWebhookDomains, }) - // An enqueue here wakes the worker, so an idle queue's slower poll never delays a delivery. - if w, ok := webhookService.(interface{ WireDeliveryWake(func()) }); ok { - w.WireDeliveryWake(webhookWorker.Wake) - } + // 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) diff --git a/cmd/warmblyctl/db.go b/cmd/warmblyctl/db.go index 349da08ae..05865b452 100644 --- a/cmd/warmblyctl/db.go +++ b/cmd/warmblyctl/db.go @@ -62,6 +62,7 @@ type dbBusy struct { } type dbStatement struct { + QueryID int64 `json:"queryid"` Calls int64 `json:"calls"` TotalMS float64 `json:"total_ms"` MeanMS float64 `json:"mean_ms"` @@ -122,7 +123,7 @@ func readDBLoad(ctx context.Context, pool *pgxpool.Pool, limit int) (*dbLoad, er } rows, err := pool.Query(ctx, `SELECT COALESCE(NULLIF(application_name, ''), '(unnamed)'), COALESCE(state, '(background)'), count(*)::int - FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() + 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) @@ -177,7 +178,7 @@ func readDBLoad(ctx context.Context, pool *pgxpool.Pool, limit int) (*dbLoad, er return load, rows.Err() } -// readStatements reads pg_stat_statements when the server has it; its text is normalized, so it holds no values. +// 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 installed bool if err := pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_stat_statements')`).Scan(&installed); err != nil { @@ -187,7 +188,9 @@ func readStatements(ctx context.Context, pool *pgxpool.Pool, limit int, load *db 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 calls, total_exec_time, mean_exec_time, rows, left(regexp_replace(query, '\s+', ' ', 'g'), 200) + 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 pg_stat_statements WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database()) ORDER BY total_exec_time DESC LIMIT $1`, limit) if err != nil { @@ -196,7 +199,7 @@ func readStatements(ctx context.Context, pool *pgxpool.Pool, limit int, load *db } for rows.Next() { var r dbStatement - if err := rows.Scan(&r.Calls, &r.TotalMS, &r.MeanMS, &r.Rows, &r.Query); err != nil { + 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) @@ -216,7 +219,7 @@ func printDBLoad(w io.Writer, load *dbLoad) { for _, c := range load.Connections { used += c.Count } - fmt.Fprintf(w, "Connections: %d of max_connections %d\n", used, load.MaxConnections) + fmt.Fprintf(w, "Connections to the server: %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 { @@ -246,10 +249,10 @@ func printDBLoad(w io.Writer, load *dbLoad) { } tw = tabwriter.NewWriter(w, 2, 4, 2, ' ', 0) if len(load.Statements) > 0 { - fmt.Fprintln(tw, " TOTAL MS\tCALLS\tMEAN MS\tROWS\tQUERY") + 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%s\n", s.TotalMS, s.Calls, s.MeanMS, s.Rows, strings.TrimSpace(s.Query)) + 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() diff --git a/docs/content/docs/development/configuration.mdx b/docs/content/docs/development/configuration.mdx index 5beb2cee4..6f9bded19 100644 --- a/docs/content/docs/development/configuration.mdx +++ b/docs/content/docs/development/configuration.mdx @@ -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 | diff --git a/docs/content/docs/development/data-control.mdx b/docs/content/docs/development/data-control.mdx index 2340499cc..216efed47 100644 --- a/docs/content/docs/development/data-control.mdx +++ b/docs/content/docs/development/data-control.mdx @@ -105,13 +105,13 @@ See [Automatic inbox tagging](/guides/inbox-tagging/), [Advisor](/guides/advisor | `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 event logs and the three history feeds 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: the marks the consumer uses to count each open or click once follow `retention.engagement_event_days`, worker health samples are kept 7 days, and a send's queued follow-up effects 7 days after they ran. 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. +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. There is no grace period and no copy. Take a backup first if you are not sure. diff --git a/docs/content/docs/development/instance-health.mdx b/docs/content/docs/development/instance-health.mdx index a43d22d74..223aa8454 100644 --- a/docs/content/docs/development/instance-health.mdx +++ b/docs/content/docs/development/instance-health.mdx @@ -91,7 +91,7 @@ Failed attempts keep their existing retry policy. During a mixed-version rollout 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. A webhook enqueued on a backend still starts that backend's delivery at once. Send-result effects are claimed in batches of 25. +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. diff --git a/docs/content/docs/development/warmblyctl.mdx b/docs/content/docs/development/warmblyctl.mdx index bf69c40fb..c643d64b3 100644 --- a/docs/content/docs/development/warmblyctl.mdx +++ b/docs/content/docs/development/warmblyctl.mdx @@ -707,9 +707,9 @@ warmblyctl db load --limit 30 --json It prints four sections: -- **Connections** grouped by the service that opened them and their state, against `max_connections`. Every Go service names its connections `warmbly-` (`warmbly-backend`, `warmbly-consumer`, `warmbly-warmblyctl`), unless the connection string sets its own `application_name`. +- **Connections** to the whole server, grouped by the service that opened them and their state, against `max_connections`. Every Go service names its connections `warmbly-` (`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`. Its text is normalized, so it holds no values. When the extension is not installed, the section says how to enable it. +- **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 diff --git a/internal/app/consumer/event_tracking.go b/internal/app/consumer/event_tracking.go index 380512c30..8c91e986c 100644 --- a/internal/app/consumer/event_tracking.go +++ b/internal/app/consumer/event_tracking.go @@ -5,6 +5,8 @@ import ( "crypto/sha256" "encoding/hex" "encoding/json" + "errors" + "fmt" "net/netip" "strings" "time" @@ -211,21 +213,22 @@ func (tc *TrackingConsumer) pruneEngagementLogs(ctx context.Context) { 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") } } - return nil + return errors.Join(failures...) }) } diff --git a/internal/app/consumer/warmup_mail_retention.go b/internal/app/consumer/warmup_mail_retention.go index adeb36279..21851c24a 100644 --- a/internal/app/consumer/warmup_mail_retention.go +++ b/internal/app/consumer/warmup_mail_retention.go @@ -219,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 } diff --git a/internal/app/consumer/warmup_retention_test.go b/internal/app/consumer/warmup_retention_test.go index ad31d2dea..a1628815f 100644 --- a/internal/app/consumer/warmup_retention_test.go +++ b/internal/app/consumer/warmup_retention_test.go @@ -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 } diff --git a/internal/app/email/tracking_domain_live_test.go b/internal/app/email/tracking_domain_live_test.go index 2984171fa..94327beac 100644 --- a/internal/app/email/tracking_domain_live_test.go +++ b/internal/app/email/tracking_domain_live_test.go @@ -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") diff --git a/internal/app/email/tracking_domain_sweep.go b/internal/app/email/tracking_domain_sweep.go index 4151b3d5c..e484f1726 100644 --- a/internal/app/email/tracking_domain_sweep.go +++ b/internal/app/email/tracking_domain_sweep.go @@ -2,6 +2,7 @@ package email import ( "context" + "fmt" "time" "github.com/rs/zerolog/log" @@ -33,29 +34,27 @@ func (s *emailService) StartTrackingDomainSweep(ctx context.Context, interval, s jobrun.Loop(ctx, "tracking_domain_sweep", interval, false, func(ctx context.Context) error { sweepCtx, cancel := context.WithTimeout(ctx, 5*time.Minute) defer cancel() - s.runTrackingDomainSweep(sweepCtx, staleAfter) - return nil + 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 for _, t := range due { if ctx.Err() != nil { - return + return nil } lookupCtx, cancel := context.WithTimeout(ctx, 5*time.Second) @@ -97,4 +96,5 @@ 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") } + return nil } diff --git a/internal/app/unibox/backfill_body_text.go b/internal/app/unibox/backfill_body_text.go index 829edb210..9484a4ca8 100644 --- a/internal/app/unibox/backfill_body_text.go +++ b/internal/app/unibox/backfill_body_text.go @@ -2,10 +2,13 @@ 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" ) @@ -16,6 +19,8 @@ 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 @@ -40,6 +45,17 @@ func (s *uniboxService) StartBodyTextBackfill(ctx context.Context) { 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(): @@ -63,22 +79,24 @@ 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") diff --git a/internal/app/webhook/service.go b/internal/app/webhook/service.go index e1071d621..e9cd1f3c6 100644 --- a/internal/app/webhook/service.go +++ b/internal/app/webhook/service.go @@ -21,6 +21,7 @@ import ( "time" "github.com/google/uuid" + "github.com/jackc/pgx/v5" "github.com/rs/zerolog/log" "github.com/warmbly/warmbly/internal/config" @@ -140,23 +141,12 @@ type service struct { cache *cache.Cache resolveLimit func(ctx context.Context, orgID uuid.UUID) int appDomains AppDomainResolver - // wake asks this process's delivery worker to poll now; nil when it runs elsewhere. - wake func() } func NewService(repo repository.WebhookRepository) Service { return &service{repo: repo, now: time.Now} } -// WireDeliveryWake lets an enqueue start this process's delivery worker at once. -func (s *service) WireDeliveryWake(wake func()) { s.wake = wake } - -func (s *service) enqueued() { - if s.wake != nil { - s.wake() - } -} - func (s *service) WireDispatchSink(sink DispatchSink) { s.sink = sink } @@ -296,9 +286,6 @@ func (s *service) Dispatch(ctx context.Context, orgID uuid.UUID, eventType model return eventID, err } } - if len(endpoints) > 0 { - s.enqueued() - } return eventID, nil } @@ -541,9 +528,7 @@ func (s *service) enqueueChallenge(ctx context.Context, endpoint *models.Webhook } if err := s.repo.EnqueueDelivery(ctx, delivery); err != nil { log.Warn().Err(err).Str("endpoint_id", endpoint.ID.String()).Msg("Failed to enqueue webhook challenge") - return } - s.enqueued() } // generateSecret returns a 32-byte cryptographically-random hex string. @@ -740,6 +725,48 @@ func (w *DeliveryWorker) Wake() { } } +// 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, diff --git a/internal/jobrun/jobrun.go b/internal/jobrun/jobrun.go index 6febef4b7..9950bd7c9 100644 --- a/internal/jobrun/jobrun.go +++ b/internal/jobrun/jobrun.go @@ -226,9 +226,12 @@ func takeRequests(ctx context.Context) { log.Warn().Err(err).Msg("jobrun: run request poll failed") return } + var orphaned []string watchMu.Lock() - defer watchMu.Unlock() for _, name := range taken { + if len(watchers[name]) == 0 { + orphaned = append(orphaned, name) + } for _, ch := range watchers[name] { select { case ch <- struct{}{}: @@ -236,6 +239,13 @@ func takeRequests(ctx context.Context) { } } } + watchMu.Unlock() + // The loop stopped here after the poll began; the request goes back for whichever process runs it now. + for _, name := range orphaned { + if _, err := st.RequestRun(pollCtx, name); 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 diff --git a/internal/jobrun/schedule_test.go b/internal/jobrun/schedule_test.go index 862e34573..15689c192 100644 --- a/internal/jobrun/schedule_test.go +++ b/internal/jobrun/schedule_test.go @@ -22,6 +22,8 @@ type memStore struct { 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 { @@ -88,7 +90,6 @@ func (m *memStore) RequestRun(_ context.Context, name string) (bool, error) { } func (m *memStore) TakeRunRequests(_ context.Context, names []string) ([]string, error) { m.mu.Lock() - defer m.mu.Unlock() m.polls++ var taken []string for _, n := range names { @@ -97,6 +98,11 @@ func (m *memStore) TakeRunRequests(_ context.Context, names []string) ([]string, 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) { @@ -329,3 +335,20 @@ func TestRunRequestsArePolledOncePerProcess(t *testing.T) { } }) } + +// 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") + } +} diff --git a/internal/leader/leader_live_test.go b/internal/leader/leader_live_test.go index ca86e931d..40129602c 100644 --- a/internal/leader/leader_live_test.go +++ b/internal/leader/leader_live_test.go @@ -81,8 +81,9 @@ 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 stopped atomic.Int32 + var started, stopped atomic.Int32 e.Go("probe", func(ctx context.Context) { + started.Add(1) <-ctx.Done() stopped.Add(1) }) @@ -96,7 +97,8 @@ func TestLiveALostLockConnectionStopsTheLoops(t *testing.T) { t.Fatal(err) } waitFor(t, "the loop to stop with its lock", func() bool { return stopped.Load() >= 1 }) - waitFor(t, "leadership to be won back", e.Leading) + // 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) { diff --git a/internal/repository/pg_table_retention.go b/internal/repository/pg_table_retention.go index d059bcaad..965bed9db 100644 --- a/internal/repository/pg_table_retention.go +++ b/internal/repository/pg_table_retention.go @@ -74,8 +74,12 @@ func (r *TableRetentionRepository) PruneWorkerHealthSamples(ctx context.Context, `SELECT ctid FROM worker_health_samples WHERE observed_at < $2 LIMIT $1`, before) } -// PruneDeliveredSendResultEffects drops send-result effects delivered before 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 ctid FROM send_result_effects WHERE delivered_at IS NOT NULL AND delivered_at < $2 LIMIT $1`, before) + `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) } diff --git a/internal/repository/pg_table_retention_live_test.go b/internal/repository/pg_table_retention_live_test.go index 963cd3803..1c4ab37a2 100644 --- a/internal/repository/pg_table_retention_live_test.go +++ b/internal/repository/pg_table_retention_live_test.go @@ -16,7 +16,7 @@ const ancientDays = 4000 func TestLiveTableRetentionPrunesOnlyPastWindow(t *testing.T) { _, pool := liveContactDB(t) ctx := context.Background() - user, org, campaign, worker, endpoint, account, task := uuid.New(), uuid.New(), uuid.New(), uuid.New(), uuid.New(), uuid.New(), uuid.New() + 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 { @@ -32,10 +32,11 @@ func TestLiveTableRetentionPrunesOnlyPastWindow(t *testing.T) { 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) VALUES ($1, 'campaign', $2, 'completed', '')`, task, account) + 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', '', 'sent', NOW()), ($2, 'campaign', $3, 'dead_lettered', '', 'sent', NOW())`, task, repairable, account) t.Cleanup(func() { c := context.Background() - _, _ = pool.Exec(c, `DELETE FROM tasks WHERE id = $1`, task) + _, _ = 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) @@ -54,7 +55,8 @@ func TestLiveTableRetentionPrunesOnlyPastWindow(t *testing.T) { ($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)`, task, org, old, fresh) + 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) @@ -92,6 +94,7 @@ func TestLiveTableRetentionPrunesOnlyPastWindow(t *testing.T) { {"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) @@ -123,7 +126,8 @@ func TestLiveRetentionPrunesUseTheirIndexes(t *testing.T) { {`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 ctid FROM send_result_effects WHERE delivered_at IS NOT NULL AND delivered_at < NOW() LIMIT 5000`, "idx_send_result_effects_delivered"}, + {`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"}, } { diff --git a/internal/repository/pg_task.go b/internal/repository/pg_task.go index a453e8987..eebb64707 100644 --- a/internal/repository/pg_task.go +++ b/internal/repository/pg_task.go @@ -147,10 +147,11 @@ type TaskRepository interface { GetBookedSendsForAccount(ctx context.Context, accountID uuid.UUID, around time.Time) ([]Task, 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. - ClaimDueTaskIDs(ctx context.Context, limit int, lease time.Duration) ([]uuid.UUID, error) - RecordDispatchAttempt(ctx context.Context, taskID uuid.UUID, failed bool, retryAt time.Time) error - ReleaseDispatchClaims(ctx context.Context, taskIDs []uuid.UUID) error + // 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 @@ -900,7 +901,7 @@ func (r *taskRepository) CancelOverduePendingTasks(ctx context.Context, taskType // 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, error) { +func (r *taskRepository) ClaimDueTaskIDs(ctx context.Context, limit int, lease time.Duration) ([]uuid.UUID, time.Time, error) { query := ` UPDATE tasks t SET dispatch_claimed_until = NOW() + make_interval(secs => $2) @@ -915,47 +916,50 @@ func (r *taskRepository) ClaimDueTaskIDs(ctx context.Context, limit int, lease t FOR UPDATE SKIP LOCKED ) due WHERE t.id = due.id - RETURNING t.id + RETURNING t.id, t.dispatch_claimed_until ` 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(), - dispatch_claimed_until=NULL - WHERE id=$1 AND status='pending'`, taskID, retryAt) + `+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,dispatch_claimed_until=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. -func (r *taskRepository) ReleaseDispatchClaims(ctx context.Context, taskIDs []uuid.UUID) error { +// 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 IS NOT NULL`, taskIDs) + _, 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 } diff --git a/internal/repository/pg_task_claim_live_test.go b/internal/repository/pg_task_claim_live_test.go index 012753662..a59ad3fe9 100644 --- a/internal/repository/pg_task_claim_live_test.go +++ b/internal/repository/pg_task_claim_live_test.go @@ -26,19 +26,21 @@ func TestLiveConcurrentDispatchersNeverClaimTheSameTask(t *testing.T) { 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, err := repo.ClaimDueTaskIDs(ctx, 5, time.Minute) + 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 @@ -58,8 +60,10 @@ func TestLiveConcurrentDispatchersNeverClaimTheSameTask(t *testing.T) { } wg.Wait() // Other tests' due tasks share the table; hand theirs back untouched. - if err := repo.ReleaseDispatchClaims(ctx, foreign); err != nil { - t.Fatal(err) + 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)) @@ -67,7 +71,7 @@ func TestLiveConcurrentDispatchersNeverClaimTheSameTask(t *testing.T) { claimable := func() map[uuid.UUID]bool { t.Helper() - got, err := repo.ClaimDueTaskIDs(ctx, 100000, time.Minute) + got, claim, err := repo.ClaimDueTaskIDs(ctx, 100000, time.Minute) if err != nil { t.Fatal(err) } @@ -80,9 +84,12 @@ func TestLiveConcurrentDispatchersNeverClaimTheSameTask(t *testing.T) { theirs = append(theirs, id) } } - if err := repo.ReleaseDispatchClaims(ctx, theirs); err != nil { + if err := repo.ReleaseDispatchClaims(ctx, theirs, claim); err != nil { t.Fatal(err) } + for id := range out { + claims[id] = claim + } return out } @@ -93,21 +100,36 @@ func TestLiveConcurrentDispatchersNeverClaimTheSameTask(t *testing.T) { // 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], false, time.Now().Add(-time.Hour)); err != nil { + 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) } - if err := repo.ReleaseDispatchClaims(ctx, ids[2:]); err != nil { - t.Fatal(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) diff --git a/internal/repository/pg_warmup.go b/internal/repository/pg_warmup.go index 6d19f7123..c63b2e360 100644 --- a/internal/repository/pg_warmup.go +++ b/internal/repository/pg_warmup.go @@ -313,7 +313,8 @@ type WarmupRepository interface { // 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) @@ -2094,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 { @@ -2130,12 +2134,11 @@ func (r *warmupRepository) PruneWarmupEventsBefore(ctx context.Context, before t } total += cmd.RowsAffected() } - // A thread turn outlives the event window while its mailbox still keeps that mail, because replies are matched against it. + // 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 < $2 - AND (ea.warmup_retention_days IS NULL OR m.created_at < NOW() - make_interval(days => ea.warmup_retention_days)) - LIMIT $1`, before) + 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 diff --git a/internal/repository/pg_webhook.go b/internal/repository/pg_webhook.go index 1d4dacff1..e2344a557 100644 --- a/internal/repository/pg_webhook.go +++ b/internal/repository/pg_webhook.go @@ -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, diff --git a/internal/repository/warmup_mail_retention_live_test.go b/internal/repository/warmup_mail_retention_live_test.go index 530bdb8a9..27657f4dc 100644 --- a/internal/repository/warmup_mail_retention_live_test.go +++ b/internal/repository/warmup_mail_retention_live_test.go @@ -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) diff --git a/internal/repository/warmup_send_failure_live_test.go b/internal/repository/warmup_send_failure_live_test.go index 924389e7c..91175a8cd 100644 --- a/internal/repository/warmup_send_failure_live_test.go +++ b/internal/repository/warmup_send_failure_live_test.go @@ -268,11 +268,11 @@ 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, err := repo.ClaimDueTaskIDs(ctx, 10000, time.Minute) + ids, claim, err := repo.ClaimDueTaskIDs(ctx, 10000, time.Minute) if err != nil { return nil, err } - return ids, repo.ReleaseDispatchClaims(ctx, ids) + return ids, repo.ReleaseDispatchClaims(ctx, ids, claim) } func TestLiveDispatchRetrySuccessfulPendingNoopDoesNotStarveNewerTask(t *testing.T) { @@ -283,7 +283,7 @@ 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 := claimDueForTest(ctx, repo) @@ -345,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 @@ -378,7 +378,7 @@ 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 := claimDueForTest(ctx, repo) @@ -430,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 diff --git a/internal/repository/webhook_delivery_notify_live_test.go b/internal/repository/webhook_delivery_notify_live_test.go new file mode 100644 index 000000000..8e1d46d0c --- /dev/null +++ b/internal/repository/webhook_delivery_notify_live_test.go @@ -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 TestLiveWebhookEnqueueWakesListeningWorkers(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) + } +} diff --git a/internal/tasks/warmup_pool_reconcile.go b/internal/tasks/warmup_pool_reconcile.go index 887e107c4..bd2b00ee8 100644 --- a/internal/tasks/warmup_pool_reconcile.go +++ b/internal/tasks/warmup_pool_reconcile.go @@ -2,6 +2,7 @@ package tasks import ( "context" + "fmt" "slices" "time" @@ -9,6 +10,7 @@ import ( "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. @@ -85,11 +87,21 @@ func (s *tasksService) ReconcileWarmupPoolMembership(ctx context.Context) (moved } 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 { + if xerr := s.warmupHealth.RemoveFromAllPools(ctx, m.EmailAccountID); xerr != nil { + fail(m, "leave", xerr) + } else { removed++ } continue @@ -108,7 +120,9 @@ func (s *tasksService) ReconcileWarmupPoolMembership(ctx context.Context) (moved entitled[org] = ok } if !ok { - if xerr := s.warmupHealth.RemoveFromAllPools(ctx, m.EmailAccountID); xerr == nil { + 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()). @@ -125,6 +139,7 @@ func (s *tasksService) ReconcileWarmupPoolMembership(ctx context.Context) (moved } didMove, xerr := s.warmupHealth.MovePoolMembership(ctx, m.EmailAccountID, poolType) if xerr != nil { + fail(m, "move to "+poolType, xerr) continue } if didMove { @@ -136,6 +151,9 @@ func (s *tasksService) ReconcileWarmupPoolMembership(ctx context.Context) (moved } } + if failed > 0 { + return moved, removed, fmt.Errorf("%d warmup pool membership updates failed, last: %w", failed, lastErr) + } return moved, removed, nil } diff --git a/internal/tasksched/local.go b/internal/tasksched/local.go index c41f14044..6ec277746 100644 --- a/internal/tasksched/local.go +++ b/internal/tasksched/local.go @@ -14,9 +14,9 @@ import ( // DueTaskLister claims pending tasks whose slot has arrived. // repository.TaskRepository satisfies it. type DueTaskLister interface { - ClaimDueTaskIDs(ctx context.Context, limit int, lease time.Duration) ([]uuid.UUID, error) - RecordDispatchAttempt(ctx context.Context, taskID uuid.UUID, failed bool, retryAt time.Time) error - ReleaseDispatchClaims(ctx context.Context, taskIDs []uuid.UUID) error + 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 } const ( @@ -48,7 +48,8 @@ type Local struct { interval time.Duration batch int slots chan struct{} - inflight sync.Map // taskID string -> struct{}, dedups across overlapping ticks + mu sync.Mutex + inflight map[uuid.UUID]time.Time // task -> its latest claim, dedups across overlapping ticks } // NewLocal builds a Local poller. interval<=0 defaults to 1s; batch<=0 to 200. @@ -59,7 +60,7 @@ func NewLocal(repo DueTaskLister, interval time.Duration, batch int, options ... if batch <= 0 { batch = 200 } - l := &Local{repo: repo, interval: interval, batch: batch, slots: make(chan struct{}, defaultLocalConcurrency)} + l := &Local{repo: repo, interval: interval, batch: batch, slots: make(chan struct{}, defaultLocalConcurrency), inflight: map[uuid.UUID]time.Time{}} for _, option := range options { option(l) } @@ -102,52 +103,68 @@ func (l *Local) tick(ctx context.Context, handle func(taskID string) error) { if ctx.Err() != nil || free <= 0 { return } - ids, err := l.repo.ClaimDueTaskIDs(ctx, min(l.batch, free), dispatchClaimLease) + ids, claim, err := l.repo.ClaimDueTaskIDs(ctx, min(l.batch, free), dispatchClaimLease) if err != nil { log.Error().Err(err).Msg("tasksched: claim due tasks") return } for i, id := range ids { if ctx.Err() != nil { - l.release(ids[i:]) + l.release(ids[i:], claim) return } select { case l.slots <- struct{}{}: default: - l.release(ids[i:]) + l.release(ids[i:], claim) return } - key := id.String() - // Still running here from an earlier claim; the new lease covers it. - if _, busy := l.inflight.LoadOrStore(key, struct{}{}); busy { + // Still running here from an earlier claim; the new lease covers it and is the one recorded. + if l.track(id, claim) { <-l.slots continue } - go func(taskID string) { + go func(id uuid.UUID) { defer func() { <-l.slots }() - defer l.inflight.Delete(taskID) if ctx.Err() != nil { - l.release([]uuid.UUID{id}) + l.release([]uuid.UUID{id}, l.untrack(id)) return } - err := handle(taskID) + err := handle(id.String()) + claim := l.untrack(id) if ctx.Err() != nil { - l.release([]uuid.UUID{id}) + l.release([]uuid.UUID{id}, claim) return } - if saveErr := l.repo.RecordDispatchAttempt(ctx, id, err != nil, time.Now().Add(dispatchRetryDelay)); saveErr != nil { + if saveErr := l.repo.RecordDispatchAttempt(ctx, id, claim, err != nil, time.Now().Add(dispatchRetryDelay)); saveErr != nil { log.Error().Err(saveErr).Msg("tasksched: record dispatch retry") } - }(key) + }(id) } } +// track records the task's latest claim and reports whether it was already running here. +func (l *Local) track(id uuid.UUID, claim time.Time) bool { + l.mu.Lock() + defer l.mu.Unlock() + _, busy := l.inflight[id] + l.inflight[id] = claim + return busy +} + +func (l *Local) untrack(id uuid.UUID) time.Time { + l.mu.Lock() + defer l.mu.Unlock() + claim := l.inflight[id] + delete(l.inflight, id) + return claim +} + // release hands claims back so another replica need not wait out the lease, even during shutdown. -func (l *Local) release(ids []uuid.UUID) { +func (l *Local) release(ids []uuid.UUID, claim time.Time) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - if err := l.repo.ReleaseDispatchClaims(ctx, ids); err != nil { + if err := l.repo.ReleaseDispatchClaims(ctx, ids, claim); err != nil { log.Warn().Err(err).Msg("tasksched: release dispatch claims") } } diff --git a/internal/tasksched/local_test.go b/internal/tasksched/local_test.go index 587c03192..f2f213d1a 100644 --- a/internal/tasksched/local_test.go +++ b/internal/tasksched/local_test.go @@ -19,11 +19,11 @@ type localTestRepo struct { released []uuid.UUID } -func (r *localTestRepo) ClaimDueTaskIDs(_ context.Context, limit int, lease time.Duration) ([]uuid.UUID, error) { +func (r *localTestRepo) ClaimDueTaskIDs(_ context.Context, limit int, lease time.Duration) ([]uuid.UUID, time.Time, error) { r.mu.Lock() defer r.mu.Unlock() if lease <= 0 { - return nil, errors.New("claim without a lease") + return nil, time.Time{}, errors.New("claim without a lease") } r.limits = append(r.limits, limit) var ids []uuid.UUID @@ -35,10 +35,10 @@ func (r *localTestRepo) ClaimDueTaskIDs(_ context.Context, limit int, lease time break } } - return ids, nil + return ids, time.Now().Add(lease), nil } -func (r *localTestRepo) RecordDispatchAttempt(_ context.Context, id uuid.UUID, failed bool, at time.Time) error { +func (r *localTestRepo) RecordDispatchAttempt(_ context.Context, id uuid.UUID, _ time.Time, failed bool, at time.Time) error { r.mu.Lock() r.retries[id] = failed r.mu.Unlock() @@ -49,7 +49,7 @@ func (r *localTestRepo) RecordDispatchAttempt(_ context.Context, id uuid.UUID, f return nil } -func (r *localTestRepo) ReleaseDispatchClaims(_ context.Context, ids []uuid.UUID) error { +func (r *localTestRepo) ReleaseDispatchClaims(_ context.Context, ids []uuid.UUID, _ time.Time) error { r.mu.Lock() defer r.mu.Unlock() r.released = append(r.released, ids...) From 710d857a4bae2472b614a2f8fe506b7a6eaff880 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 16:58:54 +0100 Subject: [PATCH 151/318] feat: keep an unsent mailbox push report ahead of the control plane's stored row and resend it during the retry backoff, and plan-test the largest accepted fleet worker capacity --- .../aws/workers/tests/fleet.tftest.hcl | 13 ++++++++ internal/app/worker/wmail/push.go | 15 ++++++++-- internal/app/worker/wmail/push_test.go | 30 +++++++++++++++++++ 3 files changed, 55 insertions(+), 3 deletions(-) diff --git a/deploy/terraform/aws/workers/tests/fleet.tftest.hcl b/deploy/terraform/aws/workers/tests/fleet.tftest.hcl index e11dd207a..51b9b75e6 100644 --- a/deploy/terraform/aws/workers/tests/fleet.tftest.hcl +++ b/deploy/terraform/aws/workers/tests/fleet.tftest.hcl @@ -196,3 +196,16 @@ run "fleet_needs_instance_url" { } expect_failures = [aws_launch_template.fleet[0]] } + +run "fleet_worker_capacity_takes_the_upper_bound" { + command = plan + variables { + fleet_enabled = true + fleet_instance_url = "https://app.example.com" + fleet_worker_capacity = "99999999" + } + assert { + condition = strcontains(base64decode(aws_launch_template.fleet[0].user_data), "CAPACITY='99999999'") + error_message = "The largest accepted capacity reaches the worker." + } +} diff --git a/internal/app/worker/wmail/push.go b/internal/app/worker/wmail/push.go index 15514783b..24ed87389 100644 --- a/internal/app/worker/wmail/push.go +++ b/internal/app/worker/wmail/push.go @@ -55,7 +55,8 @@ func (w *WMail) ApplyPush(data *models.AddWorkerEmailPushData) { w.push.mu.Lock() defer w.push.mu.Unlock() w.push.want = data - if w.push.state == nil && data != nil && data.State != nil { + // A report the control plane has not taken yet is newer than the row it hands back. + if w.push.state == nil && !w.push.unsent.Load() && data != nil && data.State != nil { s := *data.State w.push.state = &s } @@ -108,6 +109,9 @@ func (w *WMail) maintainPush(ctx context.Context) { w.push.mu.Unlock() renew := w.push.renew.Swap(false) if !renew && now.Before(retryAt) { + if w.push.unsent.Load() { + w.reportPush(state) + } return } var next *models.MailboxPushState @@ -143,10 +147,15 @@ func (w *WMail) maintainPush(ctx context.Context) { return } w.push.mu.Lock() + w.push.unsent.Store(true) w.push.state = next w.push.mu.Unlock() - if err := w.onEvent(models.JobEventTypePushState, &models.JobEventPushState{UserID: w.UserID, EmailID: w.ID, State: next}); err != nil { - w.push.unsent.Store(true) + w.reportPush(next) +} + +// reportPush sends the channel state to the control plane; unsent stays set until it is taken. +func (w *WMail) reportPush(state *models.MailboxPushState) { + if err := w.onEvent(models.JobEventTypePushState, &models.JobEventPushState{UserID: w.UserID, EmailID: w.ID, State: state}); err != nil { log.Debug().Err(err).Str("email_id", w.ID.String()).Msg("could not record mailbox push channel") return } diff --git a/internal/app/worker/wmail/push_test.go b/internal/app/worker/wmail/push_test.go index d63dc7b42..8cc2d7e18 100644 --- a/internal/app/worker/wmail/push_test.go +++ b/internal/app/worker/wmail/push_test.go @@ -1,6 +1,7 @@ package wmail import ( + "errors" "testing" "time" @@ -69,3 +70,32 @@ func TestWakeRenewIsRemembered(t *testing.T) { t.Fatal("a renew wake was dropped") } } + +func TestAnUnsentChannelReportOutranksTheControlPlanesRow(t *testing.T) { + var refuse bool + var sent []*models.MailboxPushState + w := &WMail{wake: make(chan struct{}, 1), onEvent: func(_ models.JobEventType, body any) error { + if refuse { + return errors.New("bus down") + } + sent = append(sent, body.(*models.JobEventPushState).State) + return nil + }} + // The channel was closed, and the report saying so was refused. + refuse = true + w.push.unsent.Store(true) + w.reportPush(nil) + if !w.push.unsent.Load() { + t.Fatal("a refused report was marked taken") + } + w.ApplyPush(&models.AddWorkerEmailPushData{GraphNotificationURL: "https://x", GraphClientState: "s", + State: &models.MailboxPushState{Provider: models.MailboxPushGraph, SubscriptionID: "closed", ExpiresAt: time.Now().Add(time.Hour)}}) + if w.push.state != nil { + t.Fatal("the control plane's stale row replaced a channel this worker closed") + } + refuse = false + w.reportPush(nil) + if w.push.unsent.Load() || len(sent) != 1 || sent[0] != nil { + t.Fatalf("the retried report was not taken: unsent=%v sent=%v", w.push.unsent.Load(), sent) + } +} From eebfaf43d85dbb93b19b8b3ee72150eb57662959 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 17:12:14 +0100 Subject: [PATCH 152/318] feat: label hidden and background sessions apart in warmblyctl db load, read pg_stat_statements from whatever schema holds it, give orphaned run-request handbacks their own deadline, report unsaved tracking-domain verdicts, treat missing retention fields as zero when checking the admin form for edits, and test the webhook delivery listener against a notification from another connection --- .../dashboard/configuration/SettingsTab.tsx | 2 +- cmd/warmblyctl/db.go | 18 +++++--- internal/app/email/tracking_domain_sweep.go | 7 ++- internal/app/webhook/listen_live_test.go | 45 +++++++++++++++++++ internal/jobrun/jobrun.go | 5 ++- .../webhook_delivery_notify_live_test.go | 2 +- 6 files changed, 68 insertions(+), 11 deletions(-) create mode 100644 internal/app/webhook/listen_live_test.go diff --git a/admin/src/app/dashboard/configuration/SettingsTab.tsx b/admin/src/app/dashboard/configuration/SettingsTab.tsx index 85f50eca1..58d0c8f0b 100644 --- a/admin/src/app/dashboard/configuration/SettingsTab.tsx +++ b/admin/src/app/dashboard/configuration/SettingsTab.tsx @@ -403,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 && diff --git a/cmd/warmblyctl/db.go b/cmd/warmblyctl/db.go index 05865b452..86a86102b 100644 --- a/cmd/warmblyctl/db.go +++ b/cmd/warmblyctl/db.go @@ -11,6 +11,7 @@ import ( "text/tabwriter" "time" + "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" ) @@ -122,7 +123,9 @@ func readDBLoad(ctx context.Context, pool *pgxpool.Pool, limit int) (*dbLoad, er } } - rows, err := pool.Query(ctx, `SELECT COALESCE(NULLIF(application_name, ''), '(unnamed)'), COALESCE(state, '(background)'), count(*)::int + // 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 { @@ -180,18 +183,19 @@ func readDBLoad(ctx context.Context, pool *pgxpool.Pool, limit int) (*dbLoad, er // 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 installed bool - if err := pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_stat_statements')`).Scan(&installed); err != nil { + 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 !installed { + 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 pg_stat_statements WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database()) + 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() @@ -208,7 +212,7 @@ func readStatements(ctx context.Context, pool *pgxpool.Pool, limit int, load *db return err } var since time.Time - if err := pool.QueryRow(ctx, `SELECT stats_reset FROM pg_stat_statements_info`).Scan(&since); err == nil { + 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 @@ -219,7 +223,7 @@ func printDBLoad(w io.Writer, load *dbLoad) { for _, c := range load.Connections { used += c.Count } - fmt.Fprintf(w, "Connections to the server: %d of max_connections %d\n", used, load.MaxConnections) + fmt.Fprintf(w, "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 { diff --git a/internal/app/email/tracking_domain_sweep.go b/internal/app/email/tracking_domain_sweep.go index e484f1726..21246d88a 100644 --- a/internal/app/email/tracking_domain_sweep.go +++ b/internal/app/email/tracking_domain_sweep.go @@ -51,7 +51,7 @@ func (s *emailService) runTrackingDomainSweep(ctx context.Context, staleAfter ti 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 nil @@ -78,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 { @@ -86,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++ @@ -96,5 +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 } diff --git a/internal/app/webhook/listen_live_test.go b/internal/app/webhook/listen_live_test.go new file mode 100644 index 000000000..5ec1e43e4 --- /dev/null +++ b/internal/app/webhook/listen_live_test.go @@ -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") +} diff --git a/internal/jobrun/jobrun.go b/internal/jobrun/jobrun.go index 9950bd7c9..ba2cd1d20 100644 --- a/internal/jobrun/jobrun.go +++ b/internal/jobrun/jobrun.go @@ -242,7 +242,10 @@ func takeRequests(ctx context.Context) { watchMu.Unlock() // The loop stopped here after the poll began; the request goes back for whichever process runs it now. for _, name := range orphaned { - if _, err := st.RequestRun(pollCtx, name); err != nil { + 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") } } diff --git a/internal/repository/webhook_delivery_notify_live_test.go b/internal/repository/webhook_delivery_notify_live_test.go index 8e1d46d0c..e89a2f894 100644 --- a/internal/repository/webhook_delivery_notify_live_test.go +++ b/internal/repository/webhook_delivery_notify_live_test.go @@ -11,7 +11,7 @@ import ( "github.com/warmbly/warmbly/internal/pkg/encrypt" ) -func TestLiveWebhookEnqueueWakesListeningWorkers(t *testing.T) { +func TestLiveWebhookEnqueueNotifiesAndStoresTheDelivery(t *testing.T) { _, pool := liveContactDB(t) f := newSharedOrgFixture(t, pool) ctx := t.Context() From 9081f93bd45d84705ab24164c79bedfdf4aa2624 Mon Sep 17 00:00:00 2001 From: bruce Date: Wed, 4 Nov 2026 16:13:34 +0000 Subject: [PATCH 153/318] feat: add org-scoped warmup templates: template rows in the shared warmup_conversations bank sent verbatim from the owning workspace as a configurable share of its warmup (template_share, templates_only) with a once-per-sender-per-day cap, /warmup/templates API with a /check analyzer, settings and per-template placement by provider group, WARMUP_TEMPLATES permission bit 24, orgtransfer registration, docs, and tests --- docs/content/docs/api/endpoints.mdx | 6 +- docs/content/docs/api/permissions.mdx | 18 +- .../docs/api/reference/deliverability-ops.mdx | 182 ++++ docs/content/docs/guides/warmup.mdx | 6 + .../docs/guides/workspace-export-import.mdx | 2 +- docs/public/openapi.json | 818 ++++++++++++++++++ internal/api/handler/warmup_templates.go | 372 ++++++++ internal/api/handler/warmup_templates_test.go | 37 + internal/api/routes.go | 15 + internal/app/orgtransfer/spec.go | 10 +- ...341_warmup_template_conversations.down.sql | 25 + ...00341_warmup_template_conversations.up.sql | 29 + internal/models/api_permission.go | 11 +- internal/models/audit.go | 1 + internal/models/warmup_content.go | 44 +- internal/pkg/warmlint/lint.go | 22 +- internal/pkg/warmupcheck/warmupcheck.go | 58 ++ internal/pkg/warmupcheck/warmupcheck_test.go | 63 ++ internal/repository/pg_warmup_content.go | 149 +++- .../repository/warmup_template_live_test.go | 189 ++++ internal/tasks/content_quality_test.go | 52 ++ internal/tasks/warmup_content.go | 70 +- web/src/hooks/useRealtimeEvents.ts | 1 + web/src/lib/api/models/app/audit/AuditLog.ts | 1 + web/src/lib/browse-other-lists.ts | 2 +- 25 files changed, 2149 insertions(+), 34 deletions(-) create mode 100644 internal/api/handler/warmup_templates.go create mode 100644 internal/api/handler/warmup_templates_test.go create mode 100644 internal/infrastructure/db/migrations/000341_warmup_template_conversations.down.sql create mode 100644 internal/infrastructure/db/migrations/000341_warmup_template_conversations.up.sql create mode 100644 internal/pkg/warmupcheck/warmupcheck.go create mode 100644 internal/pkg/warmupcheck/warmupcheck_test.go create mode 100644 internal/repository/warmup_template_live_test.go diff --git a/docs/content/docs/api/endpoints.mdx b/docs/content/docs/api/endpoints.mdx index f4b4d2a71..f2cb0bccf 100644 --- a/docs/content/docs/api/endpoints.mdx +++ b/docs/content/docs/api/endpoints.mdx @@ -479,11 +479,15 @@ The `listing` routes publish an app to the [community directory](/api/oauth/#pub | GET/PATCH | `/integrations/clay/:id` | `INTEGRATIONS` | | GET/POST/PATCH/DELETE | `/automations[/:id]` | `INTEGRATIONS` | | PATCH | `/automations/:id/layout` | `INTEGRATIONS` | +| GET/POST/PATCH/DELETE | `/warmup/routing[/:id]` | `WARMUP_ROUTING` | +| GET/POST/DELETE | `/warmup/templates[/:id]` | `WARMUP_TEMPLATES` | +| POST | `/warmup/templates/check` | `WARMUP_TEMPLATES` | +| GET/PUT | `/warmup/templates/settings` | `WARMUP_TEMPLATES` | +| GET | `/warmup/templates/:id/stats` | `WARMUP_TEMPLATES` | A signed-in member needs `manage_settings` to create, edit, enable or delete an automation, because a flow runs as the workspace; `use_integrations` is enough to list, open, test and read the run history. Starting an [Apollo](/guides/apollo/) enrichment writes contacts and spends the workspace's Apollo credits, so it needs `BULK_CONTACTS` as well as `INTEGRATIONS` (for a member, `use_integrations` and `manage_contacts`). Saving the key, imports and Clay settings need `manage_settings`; previewing and running an import need `use_integrations`. `POST /integrations/inbound/clay/:secret` is the URL a [Clay](/guides/clay/) table posts rows to. It takes no API key, because the secret in its path is the credential. -| GET/POST/PATCH/DELETE | `/warmup/routing[/:id]` | `WARMUP_ROUTING` | ### Retry safety diff --git a/docs/content/docs/api/permissions.mdx b/docs/content/docs/api/permissions.mdx index b7d55e6b4..a3e45145d 100644 --- a/docs/content/docs/api/permissions.mdx +++ b/docs/content/docs/api/permissions.mdx @@ -1,6 +1,6 @@ --- title: Permissions reference -description: Complete reference for the 22 API permissions available in Warmbly. +description: Complete reference for the 25 API permissions available in Warmbly. --- Warmbly uses a bitmask system for API permissions. Each permission is one bit in a `uint64`, so a single integer can express any combination of the permissions below. @@ -35,6 +35,7 @@ These same permissions are the [OAuth](/api/oauth/) scopes, lowercased: `READ_EM | `WARMUP_ROUTING` | 21 | 2097152 | special | Manage warmup routing rules | | `AI_AGENT` | 22 | 4194304 | special | Run the AI assistant and MCP tools | | `AI_RESEARCH` | 23 | 8388608 | special | Run AI contact research | +| `WARMUP_TEMPLATES` | 24 | 16777216 | special | Manage warmup templates | `AI_AGENT` gates the web and playbook tools (`search_web`, `fetch_url`, `load_skill`) on [`/v1/mcp`](/api/mcp/) and [`/ai/tools`](/api/agent-tools/); every other tool there checks its own scope. It also gates the [AI skills](/api/endpoints/#ai-skills) endpoints for keys; creating, editing or deleting a playbook with a key further needs the member who created the key to hold `manage_settings`. @@ -56,7 +57,7 @@ High-volume operations. These can touch large numbers of rows in a single reques ### Special -Realtime subscriptions, webhooks, integrations, warmup routing, AI assistant / MCP access, AI contact research, and self-service key management. Grant individually. +Realtime subscriptions, webhooks, integrations, warmup routing and templates, AI assistant / MCP access, AI contact research, and self-service key management. Grant individually. ## What a role can delegate @@ -72,7 +73,7 @@ An API key or an OAuth grant acts for a member of the workspace, so it never hol | `WRITE_CAMPAIGNS`, `WRITE_TEMPLATES`, `BULK_CAMPAIGNS` | `manage_campaigns` | | `WRITE_CONTACTS`, `WRITE_CRM`, `BULK_CONTACTS` | `manage_contacts` | | `SEND_CAMPAIGNS` | `send_campaigns` | -| `WEBHOOKS`, `WARMUP_ROUTING` | `manage_settings` | +| `WEBHOOKS`, `WARMUP_ROUTING`, `WARMUP_TEMPLATES` | `manage_settings` | | `API_KEYS` | `manage_api_keys` | | `INTEGRATIONS` | `use_integrations` | | `AI_AGENT` | `use_ai` | @@ -101,12 +102,12 @@ READ_EMAILS | READ_CAMPAIGNS | READ_CONTACTS | READ_UNIBOX | READ_ANALYTICS = 688159 ``` -### Full access (16777215) +### Full access (33554431) -All 24 permissions: +All 25 permissions: ``` -(1 << 24) - 1 = 16777215 +(1 << 25) - 1 = 33554431 ``` ## Working with bitmasks @@ -135,7 +136,7 @@ hasPermission(16387, 64); // false: WRITE_CAMPAIGNS missing ### Rejecting unknown bits -`POST /api-keys` rejects any request whose `permissions` field has bits outside the known set, so a stale client can't accidentally request a future permission. The current mask of valid bits is `4194303`. +`POST /api-keys` rejects any request whose `permissions` field has bits outside the known set, so a stale client can't accidentally request a future permission. The current mask of valid bits is `33554431`. ## Common permission sets @@ -217,6 +218,7 @@ export const Permissions = { WARMUP_ROUTING: 2097152, AI_AGENT: 4194304, AI_RESEARCH: 8388608, + WARMUP_TEMPLATES: 16777216, } as const; ``` @@ -250,6 +252,7 @@ class Permissions: WARMUP_ROUTING = 2097152 AI_AGENT = 4194304 AI_RESEARCH = 8388608 + WARMUP_TEMPLATES = 16777216 ``` @@ -282,6 +285,7 @@ const ( APIPermWarmupRouting // 2097152 APIPermAIAgent // 4194304 APIPermAIResearch // 8388608 + APIPermWarmupTemplates // 16777216 ) ``` diff --git a/docs/content/docs/api/reference/deliverability-ops.mdx b/docs/content/docs/api/reference/deliverability-ops.mdx index 065059dd3..f2506a49c 100644 --- a/docs/content/docs/api/reference/deliverability-ops.mdx +++ b/docs/content/docs/api/reference/deliverability-ops.mdx @@ -490,6 +490,188 @@ Auth: **Scope** `WARMUP_ROUTING` ยท **Org permission** `manage_settings` `204 No Content`. +## List warmup templates + +`GET /warmup/templates` + +Returns the organization's active warmup templates, newest first, each with its placement over a trailing window. A warmup template is a subject plus an opening body the workspace submitted itself; the warmup pool sends it verbatim, so where it lands is a real placement read on that exact copy. + +Auth: **Scope** `WARMUP_TEMPLATES` ยท **Org permission** `manage_settings` + +### Query parameters + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `days` | integer | `30` | Trailing window for `placement`, 1 to 90. | + +### Response + +Returns the templates under a `templates` key (always an array, never null) and the window under `days`. `placement.sent` counts every send of the template in the window; `inbox`, `tabs`, `spam` and `rescued` count the receipts the recipient mailboxes filed against those sends, so a send whose receipt has not arrived yet counts in `sent` only. + +```json +{ + "days": 30, + "templates": [ + { + "id": "c1d2e3f4-5061-7283-94a5-b6c7d8e9f0a1", + "name": "Q4 intro copy", + "subject": "Quick question about your Q4 plans", + "segment": "", + "usage_count": 12, + "created_at": "2026-06-01T09:00:00Z", + "placement": { "sent": 12, "inbox": 10, "tabs": 1, "spam": 1, "rescued": 1 } + } + ] +} +``` + +## Warmup template placement by provider + +`GET /warmup/templates/:id/stats` + +Splits one template's placement by the recipient's provider group, so copy that reaches the inbox at Google and the junk folder at Microsoft shows up as exactly that. + +Auth: **Scope** `WARMUP_TEMPLATES` ยท **Org permission** `manage_settings` + +| Parameter | In | Type | Description | +|-----------|----|------|-------------| +| `id` | path | uuid | The template ID. | +| `days` | query | integer | Trailing window, 1 to 90 (default `30`). | + +### Response + +```json +{ + "template_id": "c1d2e3f4-5061-7283-94a5-b6c7d8e9f0a1", + "days": 30, + "total": { "sent": 12, "inbox": 10, "tabs": 1, "spam": 1, "rescued": 1 }, + "groups": [ + { "group": "google", "sent": 7, "inbox": 6, "tabs": 1, "spam": 0, "rescued": 0 }, + { "group": "microsoft", "sent": 5, "inbox": 4, "tabs": 0, "spam": 1, "rescued": 1 } + ] +} +``` + +`groups` is always an array; a group with no sends in the window is absent. `404 Not Found` when the template is missing or belongs to another organization. + +## Get warmup template settings + +`GET /warmup/templates/settings` + +Returns how much of the organization's warmup carries its own templates. + +Auth: **Scope** `WARMUP_TEMPLATES` ยท **Org permission** `manage_settings` + +### Response + +```json +{ + "template_share": 50, + "templates_only": false +} +``` + +`template_share` is the percentage of a mailbox's new warmup openings drawn from the organization's templates when at least one is eligible (default `50`); the rest come from the shared bank. Templates are spread evenly, least used first, and each sender sends a given template at most once a day. `templates_only` sends nothing but templates; an opening with no eligible template is then skipped rather than filled from the bank. + +## Update warmup template settings + +`PUT /warmup/templates/settings` + +Auth: **Scope** `WARMUP_TEMPLATES` ยท **Org permission** `manage_settings` + +### Request body + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `template_share` | integer | Yes | 0 to 100. | +| `templates_only` | boolean | Yes | Send only the organization's templates. | + +### Response + +`200 OK` with the stored settings. `400 Bad Request` when `template_share` is outside 0 to 100. + +## Create a warmup template + +`POST /warmup/templates` + +Stores a warmup template for the organization. The copy is validated against the same guardrails the send path keeps: a non-empty subject of at most 200 characters without markup or newlines, a non-empty body of at most 50 KB, the shared wording check that refuses content describing itself as generated or a warmup, and the warmup send gate (no fabricated `Re:` prefix, no all-caps subject, no stacked punctuation, fewer than three spam-trigger terms). A template that fails the send gate is refused with `400 Bad Request` and the reason, so every stored template is one the pool will actually send. There is no cap on how many templates a workspace keeps. + +Auth: **Scope** `WARMUP_TEMPLATES` ยท **Org permission** `manage_settings` + +### Request body + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `name` | string | No | Label for the template, shown in listings. | +| `subject` | string | Yes | The exact subject sent with the template. | +| `body` | string | Yes | The exact opening body sent with the template. Markup and newlines are preserved. | +| `segment` | string | No | Restrict the template to senders tagged with this warmup segment. | + +### Response + +`201 Created` with the stored template under `template` and its static analysis under `check`. + +```json +{ + "template": { + "id": "c1d2e3f4-5061-7283-94a5-b6c7d8e9f0a1", + "name": "Q4 intro copy", + "subject": "Quick question about your Q4 plans", + "body": "Hi Sam, saw your post on outbound. Are you still comparing tools?", + "segment": "", + "usage_count": 0, + "created_at": "2026-06-01T09:00:00Z" + }, + "check": { + "subject_length": 34, + "word_count": 18, + "reading_time_seconds": 5, + "link_count": 0, + "question_count": 1, + "spam_trigger_hits": [] + } +} +``` + +`check.blocked_reason` is present only when the send gate would refuse the copy, which a create request never reaches because it is rejected first; it matters for `POST /warmup/templates/check`. + +`409 Conflict` when the subject or body already exists in the organization's own templates. + +## Check a warmup template + +`POST /warmup/templates/check` + +Runs the static analyzer over a draft subject and body without storing anything. + +Auth: **Scope** `WARMUP_TEMPLATES` ยท **Org permission** `manage_settings` + +### Request body + +| Field | Type | Required | Description | +|-------|------|----------|-------------| +| `subject` | string | Yes | The draft subject. | +| `body` | string | Yes | The draft body. | + +### Response + +`200 OK` with the analysis fields described above. When the warmup send gate would refuse the copy, `blocked_reason` carries the reason; a create request with that copy fails with `400 Bad Request`. + +## Delete a warmup template + +`DELETE /warmup/templates/:id` + +Retires one of the organization's own templates; senders stop receiving it for new sends. + +Auth: **Scope** `WARMUP_TEMPLATES` ยท **Org permission** `manage_settings` + +| Parameter | In | Type | Description | +|-----------|----|------|-------------| +| `id` | path | uuid | The template ID. | + +### Response + +`204 No Content`. `404 Not Found` when the template is missing or belongs to another organization. + ## List reply templates `GET /templates` diff --git a/docs/content/docs/guides/warmup.mdx b/docs/content/docs/guides/warmup.mdx index fb7dc494b..1d9ce2e5a 100644 --- a/docs/content/docs/guides/warmup.mdx +++ b/docs/content/docs/guides/warmup.mdx @@ -113,6 +113,12 @@ For each new thread, Warmbly picks a conversation neither mailbox has seen in th The generator refills the AI bank every six hours toward a target of at least 200 threads, rising with demand up to 5,000, in batches of at most 250 and within a default budget of 1,000 a day. Operators can adjust cadence, targets and budgets in the admin content controls; see [generation configuration](/development/warmup-generation/). None of this guarantees inbox placement or reputation improvement. +Your own template is a third source. A workspace can submit its own warmup template through the API: a subject and an opening body, sent verbatim rather than rendered. Mailbox reputation is partly shaped by content, so warming on generic conversation earns engagement for copy you will never send, while warming on your real campaign copy earns opens, important marks and spam rescues for the exact subject, wording, links and structure your campaigns use, and shows where that copy lands before it reaches a prospect. `POST /warmup/templates` stores one (there is no cap on how many a workspace keeps), `POST /warmup/templates/check` analyzes a draft without storing it (subject length, word count, reading time, link count, question count, spam-trigger hits, and whether the send gate would refuse it) and `DELETE /warmup/templates/:id` retires one. The permission is `WARMUP_TEMPLATES`, which needs `manage_settings`. + +How much of your warmup carries templates is a workspace setting, `GET` and `PUT /warmup/templates/settings`. By default half of a mailbox's new openings are drawn from your templates once you have at least one that is eligible, spread evenly across them (the least used goes first); the other half comes from the shared bank as before. `template_share` moves that percentage anywhere from 0 to 100, and `templates_only` sends nothing but your templates. With `templates_only` on, an opening with no eligible template is skipped rather than filled from the bank, so keep several templates active: each sender sends a given template at most once a day, and a lone template leaves most of that sender's openings empty. + +Only your own organization can draw your templates, and each is an opening only: templates never continue into replies. Placement is reported per template. `GET /warmup/templates` returns each template's sends and where they landed (inbox, tabs, spam, rescued) over a trailing window, and `GET /warmup/templates/:id/stats` splits one template by recipient provider group (Google, Microsoft, Yahoo, other), so a template that reaches the inbox at Google and the junk folder at Microsoft shows up as exactly that. Store one template per piece of copy you want to compare, keep the ones that land, and retire the rest. + diff --git a/docs/content/docs/guides/workspace-export-import.mdx b/docs/content/docs/guides/workspace-export-import.mdx index 1f83f20eb..b92164409 100644 --- a/docs/content/docs/guides/workspace-export-import.mdx +++ b/docs/content/docs/guides/workspace-export-import.mdx @@ -84,7 +84,7 @@ The data is split into groups. Every export includes **Workspace**; the rest are | CRM | Pipelines, deals, tasks, and meeting bookings | | Automations | Automations, connected integrations (including [Clay](/guides/clay/) defaults and events), saved [Apollo](/guides/apollo/) imports, lead sync sources, and the workspace's CRM mode: whether it runs on [HubSpot](/guides/hubspot/), its setup choices, the owner matches, and which Warmbly record is which HubSpot record | | Assistant | Remie sessions and messages (including conversations held in [Slack](/guides/slack/)), skills, MCP servers, and AI settings | -| Warmup | Warmup participation, routing rules, statistics and inbox placement history, appeals, expiring reconnect-recognition fingerprints, and the standing of every penalised address, current or removed, so a move is not a way past a block | +| Warmup | Warmup participation, routing rules, warmup templates and their template mix, statistics and inbox placement history, appeals, expiring reconnect-recognition fingerprints, and the standing of every penalised address, current or removed, so a move is not a way past a block | | Inbox | Unified inbox threads, message bodies, conversation labels, mailbox sync state, and completed automatic-tagging verdicts with their raw probabilities | | Send history | Queued and completed send tasks with their payloads | | Delivery events | Bounces, complaints, opens, clicks, [placement tests](/guides/placement-tests/) and batches with where each copy landed, and website page views with the browser records that tie them to contacts | diff --git a/docs/public/openapi.json b/docs/public/openapi.json index 1ffe4b1b0..563774bd0 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -22302,6 +22302,570 @@ } } }, + "/warmup/templates": { + "get": { + "operationId": "deliverability-ops_list_warmup_templates", + "summary": "List warmup templates", + "description": "Returns the organization's active warmup templates, newest first. A warmup template is a subject plus an opening body the workspace submitted itself; the warmup pool sends it verbatim. Requires WARMUP_TEMPLATES scope and manage_settings permission.", + "tags": [ + "deliverability-ops" + ], + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "days", + "in": "query", + "required": false, + "description": "Trailing window for placement in days, 1 to 90 (default 30).", + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 90 + } + } + ], + "responses": { + "200": { + "description": "Templates under a `templates` array (never null).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WarmupTemplateList" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Rate limited", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "post": { + "operationId": "deliverability-ops_create_warmup_template", + "summary": "Create a warmup template", + "description": "Stores a warmup template for the organization. The copy is validated against the send path's guardrails: subject up to 200 characters without markup or newlines, body up to 50 KB, the shared wording check, and the warmup send gate (a template the pool would refuse to send is rejected with 400 and the reason). No cap on templates per organization. Requires WARMUP_TEMPLATES scope and manage_settings permission.", + "tags": [ + "deliverability-ops" + ], + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WarmupTemplateInput" + } + } + } + }, + "responses": { + "201": { + "description": "Template created; the stored template and its static analysis.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WarmupTemplateCreated" + } + } + } + }, + "400": { + "description": "Invalid payload (missing subject or body, bounds exceeded, wording check failed)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Subject or body already exists in the organization's own templates", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Rate limited", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/warmup/templates/settings": { + "get": { + "operationId": "deliverability-ops_get_warmup_template_settings", + "summary": "Get warmup template settings", + "description": "How much of the organization's warmup carries its own templates. Requires WARMUP_TEMPLATES scope and manage_settings permission.", + "tags": [ + "deliverability-ops" + ], + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Template settings", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WarmupTemplateSettings" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Rate limited", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "put": { + "operationId": "deliverability-ops_update_warmup_template_settings", + "summary": "Update warmup template settings", + "description": "Sets the template share (0 to 100) and the templates-only switch. Requires WARMUP_TEMPLATES scope and manage_settings permission.", + "tags": [ + "deliverability-ops" + ], + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WarmupTemplateSettings" + } + } + } + }, + "responses": { + "200": { + "description": "Stored settings", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WarmupTemplateSettings" + } + } + } + }, + "400": { + "description": "template_share outside 0 to 100", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Rate limited", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/warmup/templates/{id}/stats": { + "get": { + "operationId": "deliverability-ops_get_warmup_template_stats", + "summary": "Warmup template placement by provider", + "description": "One template's sends and where they landed, split by recipient provider group, over a trailing window. Requires WARMUP_TEMPLATES scope and manage_settings permission.", + "tags": [ + "deliverability-ops" + ], + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The template ID.", + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "days", + "in": "query", + "required": false, + "description": "Trailing window in days, 1 to 90 (default 30).", + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 90 + } + } + ], + "responses": { + "200": { + "description": "Placement by provider group", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WarmupTemplateStats" + } + } + } + }, + "400": { + "description": "Invalid template id or days", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Warmup template not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Rate limited", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/warmup/templates/check": { + "post": { + "operationId": "deliverability-ops_check_warmup_template", + "summary": "Check a warmup template", + "description": "Runs the static analyzer over a draft subject and body without storing anything. Requires WARMUP_TEMPLATES scope and manage_settings permission.", + "tags": [ + "deliverability-ops" + ], + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WarmupTemplateCheckInput" + } + } + } + }, + "responses": { + "200": { + "description": "The static analysis of the draft.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WarmupTemplateCheckResult" + } + } + } + }, + "400": { + "description": "Subject exceeds 200 characters or body exceeds 50 KB", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Rate limited", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/warmup/templates/{id}": { + "delete": { + "operationId": "deliverability-ops_delete_warmup_template", + "summary": "Delete a warmup template", + "description": "Retires one of the organization's own templates; senders stop receiving it for new sends. Requires WARMUP_TEMPLATES scope and manage_settings permission.", + "tags": [ + "deliverability-ops" + ], + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The template ID.", + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "responses": { + "204": { + "description": "Template retired" + }, + "400": { + "description": "Invalid template id", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Warmup template not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Rate limited", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, "/templates": { "get": { "operationId": "deliverability-ops_list_templates", @@ -44305,6 +44869,260 @@ } } }, + "WarmupTemplate": { + "type": "object", + "description": "An organization-supplied warmup template: a subject plus opening body sent verbatim through that workspace's warmup pool.", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "subject": { + "type": "string" + }, + "body": { + "type": "string", + "description": "Present on create responses only." + }, + "segment": { + "type": "string" + }, + "usage_count": { + "type": "integer" + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "placement": { + "description": "Present on list responses: placement over the requested window.", + "$ref": "#/components/schemas/WarmupTemplatePlacement" + } + }, + "required": [ + "id", + "name", + "subject", + "segment", + "usage_count", + "created_at" + ] + }, + "WarmupTemplateList": { + "type": "object", + "description": "Warmup templates under a `templates` key (always an array, never null), each with its placement over the `days` window. Not cursor-paginated.", + "required": [ + "templates", + "days" + ], + "properties": { + "templates": { + "type": "array", + "items": { + "$ref": "#/components/schemas/WarmupTemplate" + } + }, + "days": { + "type": "integer", + "description": "The trailing window the placement counts cover." + } + } + }, + "WarmupTemplateInput": { + "type": "object", + "description": "Create payload for a warmup template.", + "required": [ + "subject", + "body" + ], + "properties": { + "name": { + "type": "string", + "description": "Label for the template, shown in listings." + }, + "subject": { + "type": "string", + "description": "The exact subject sent with the template." + }, + "body": { + "type": "string", + "description": "The exact opening body sent with the template." + }, + "segment": { + "type": "string", + "description": "Restrict the template to senders tagged with this warmup segment." + } + } + }, + "WarmupTemplateSettings": { + "type": "object", + "required": [ + "template_share", + "templates_only" + ], + "properties": { + "template_share": { + "type": "integer", + "minimum": 0, + "maximum": 100, + "description": "Percentage of new warmup openings drawn from the organization's templates when one is eligible. Default 50." + }, + "templates_only": { + "type": "boolean", + "description": "Send only the organization's templates; an opening with no eligible template is skipped." + } + } + }, + "WarmupTemplatePlacement": { + "type": "object", + "description": "Sends of a template and where the recipient mailboxes reported them landing.", + "required": [ + "sent", + "inbox", + "tabs", + "spam", + "rescued" + ], + "properties": { + "sent": { + "type": "integer" + }, + "inbox": { + "type": "integer" + }, + "tabs": { + "type": "integer" + }, + "spam": { + "type": "integer" + }, + "rescued": { + "type": "integer" + } + } + }, + "WarmupTemplateGroupPlacement": { + "allOf": [ + { + "$ref": "#/components/schemas/WarmupTemplatePlacement" + }, + { + "type": "object", + "required": [ + "group" + ], + "properties": { + "group": { + "type": "string", + "enum": [ + "google", + "microsoft", + "yahoo", + "other" + ] + } + } + } + ] + }, + "WarmupTemplateStats": { + "type": "object", + "required": [ + "template_id", + "days", + "total", + "groups" + ], + "properties": { + "template_id": { + "type": "string", + "format": "uuid" + }, + "days": { + "type": "integer" + }, + "total": { + "$ref": "#/components/schemas/WarmupTemplatePlacement" + }, + "groups": { + "type": "array", + "items": { + "$ref": "#/components/schemas/WarmupTemplateGroupPlacement" + } + } + } + }, + "WarmupTemplateCheckInput": { + "type": "object", + "required": [ + "subject", + "body" + ], + "properties": { + "subject": { + "type": "string" + }, + "body": { + "type": "string" + } + } + }, + "WarmupTemplateCheckResult": { + "type": "object", + "properties": { + "subject_length": { + "type": "integer" + }, + "word_count": { + "type": "integer" + }, + "reading_time_seconds": { + "type": "integer" + }, + "link_count": { + "type": "integer" + }, + "question_count": { + "type": "integer" + }, + "spam_trigger_hits": { + "type": "array", + "items": { + "type": "string" + } + }, + "blocked_reason": { + "type": "string", + "description": "Set when the warmup send gate would refuse this copy; create requests with a blocked template fail with 400." + } + }, + "required": [ + "subject_length", + "word_count", + "reading_time_seconds", + "link_count", + "question_count", + "spam_trigger_hits" + ] + }, + "WarmupTemplateCreated": { + "type": "object", + "required": [ + "template", + "check" + ], + "properties": { + "template": { + "$ref": "#/components/schemas/WarmupTemplate" + }, + "check": { + "$ref": "#/components/schemas/WarmupTemplateCheckResult" + } + } + }, "ReplyTemplate": { "type": "object", "properties": { diff --git a/internal/api/handler/warmup_templates.go b/internal/api/handler/warmup_templates.go new file mode 100644 index 000000000..29468c1d2 --- /dev/null +++ b/internal/api/handler/warmup_templates.go @@ -0,0 +1,372 @@ +package handler + +import ( + "context" + "errors" + "net/http" + "strconv" + "strings" + "time" + "unicode/utf8" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + + "github.com/warmbly/warmbly/internal/errx" + "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/pkg/generation" + "github.com/warmbly/warmbly/internal/pkg/warmlint" + "github.com/warmbly/warmbly/internal/pkg/warmupcheck" + "github.com/warmbly/warmbly/internal/repository" +) + +// Bounds for an organization-supplied warmup template. Templates go into the +// shared content bank, so they share the opening's shape: a short subject and +// a plain-text body. +const ( + warmupTemplateMaxSubject = 200 + warmupTemplateMaxBody = 50 * 1024 + warmupTemplatePoolType = "premium" +) + +// warmupTemplatePayload is the wire shape for create and check requests. +// Server-managed fields (id, organization_id, counters) cannot be set. +type warmupTemplatePayload struct { + Name string `json:"name"` + Subject string `json:"subject"` + Body string `json:"body"` + Segment string `json:"segment"` +} + +// warmupTemplate is the slim wire shape for list and create responses. +type warmupTemplate struct { + ID uuid.UUID `json:"id"` + Name string `json:"name"` + Subject string `json:"subject"` + Body string `json:"body,omitempty"` + Segment string `json:"segment"` + UsageCount int64 `json:"usage_count"` + CreatedAt time.Time `json:"created_at"` + Placement *models.WarmupTemplatePlacement `json:"placement,omitempty"` +} + +// warmupTemplateStatsDefaultDays is the trailing window for template placement. +const warmupTemplateStatsDefaultDays = 30 + +// templateStatsSince reads the optional days query (1 to 90) into a cutoff. +func templateStatsSince(c *gin.Context) (time.Time, int, bool) { + days := warmupTemplateStatsDefaultDays + if raw := strings.TrimSpace(c.Query("days")); raw != "" { + n, err := strconv.Atoi(raw) + if err != nil || n < 1 || n > 90 { + errx.JSON(c, errx.New(errx.BadRequest, "days must be between 1 and 90")) + return time.Time{}, 0, false + } + days = n + } + return time.Now().UTC().AddDate(0, 0, -days), days, true +} + +func templateResponse(c models.WarmupConversation, withBody bool) warmupTemplate { + t := warmupTemplate{ + ID: c.ID, + Name: c.Theme, + Subject: c.Subject, + Segment: c.Segment, + UsageCount: c.UsageCount, + CreatedAt: c.CreatedAt, + } + if withBody { + t.Body = c.Description + } + return t +} + +// validateTemplatePayload enforces the same guardrails the send path keeps, +// so a stored template can never fail its own send-time check. +func validateTemplatePayload(p *warmupTemplatePayload) *errx.Error { + p.Name = strings.TrimSpace(p.Name) + p.Subject = strings.TrimSpace(p.Subject) + p.Body = strings.TrimSpace(p.Body) + p.Segment = strings.TrimSpace(p.Segment) + if p.Subject == "" { + return errx.New(errx.BadRequest, "subject is required") + } + if utf8.RuneCountInString(p.Subject) > warmupTemplateMaxSubject { + return errx.New(errx.BadRequest, "subject exceeds 200 characters") + } + if strings.ContainsAny(p.Subject, "<>{}\x00\r\n") { + return errx.New(errx.BadRequest, "subject contains invalid characters") + } + if p.Name != "" && utf8.RuneCountInString(p.Name) > warmupTemplateMaxSubject { + return errx.New(errx.BadRequest, "name exceeds 200 characters") + } + if p.Body == "" { + return errx.New(errx.BadRequest, "body is required") + } + if len(p.Body) > warmupTemplateMaxBody { + return errx.New(errx.BadRequest, "body exceeds 50 KB") + } + if strings.IndexByte(p.Body, 0) >= 0 { + return errx.New(errx.BadRequest, "body contains invalid characters") + } + if utf8.RuneCountInString(p.Segment) > warmupTemplateMaxSubject { + return errx.New(errx.BadRequest, "segment exceeds 200 characters") + } + if err := generation.ValidateWarmupWording(p.Subject, p.Body); err != nil { + return errx.New(errx.BadRequest, err.Error()) + } + // The send path runs the same hard gate; rejecting here means a stored template always sends. + if err := warmlint.Check(p.Subject, p.Body, false); err != nil { + return errx.New(errx.BadRequest, "template would be blocked at send time: "+err.Error()) + } + return nil +} + +// CreateWarmupTemplate stores one organization's subject + opening body as a +// verbatim warmup conversation; there is no cap on how many a workspace +// keeps, and the pick path interleaves each into that organization's own +// sends at most once per sender per day. +func (h *Handler) CreateWarmupTemplate(c *gin.Context) { + orgID, ok := requireOrgID(c) + if !ok { + return + } + var payload warmupTemplatePayload + if err := c.ShouldBindJSON(&payload); err != nil { + errx.JSON(c, errx.InvalidBody(err)) + return + } + if xerr := validateTemplatePayload(&payload); xerr != nil { + errx.JSON(c, xerr) + return + } + scenario, rendering := generation.WarmupScenarioVersion, generation.CanonicalRenderingVersion + conv := models.WarmupConversation{ + PoolType: warmupTemplatePoolType, + Segment: payload.Segment, + Source: models.WarmupContentSourceTemplate, + Theme: payload.Name, + Subject: payload.Subject, + Description: payload.Body, + Messages: []string{}, + Status: models.WarmupConversationActive, + LintPassed: true, + ReplyEligible: true, + ScenarioVersion: &scenario, + RenderingVersion: &rendering, + SemanticReview: "passed", + OrganizationID: &orgID, + } + if err := h.WarmupContentRepo.InsertConversation(c.Request.Context(), &conv); err != nil { + if errors.Is(err, repository.ErrWarmupConversationDuplicate) { + errx.JSON(c, errx.New(errx.Conflict, "subject or body already exists in your warmup templates")) + return + } + errx.JSON(c, errx.New(errx.Internal, err.Error())) + return + } + + if stored, err := h.WarmupContentRepo.GetConversation(c.Request.Context(), conv.ID); err == nil && stored != nil { + conv = *stored + } + + h.auditOrg(c, models.AuditActionCreate, models.AuditEntityWarmupTemplate, &conv.ID, nil, map[string]string{ + "name": conv.Theme, + }) + + c.JSON(http.StatusCreated, gin.H{ + "template": templateResponse(conv, true), + "check": warmupcheck.Check(conv.Subject, conv.Description), + }) +} + +// ListWarmupTemplates returns the caller's organization's active templates +// with each one's placement over the trailing window (days, default 30). +func (h *Handler) ListWarmupTemplates(c *gin.Context) { + orgID, ok := requireOrgID(c) + if !ok { + return + } + since, days, ok := templateStatsSince(c) + if !ok { + return + } + convs, err := h.listAllWarmupTemplates(c.Request.Context(), orgID) + if err != nil { + errx.JSON(c, errx.New(errx.Internal, err.Error())) + return + } + placement, err := h.WarmupContentRepo.TemplatePlacement(c.Request.Context(), orgID, since) + if err != nil { + errx.JSON(c, errx.New(errx.Internal, err.Error())) + return + } + templates := make([]warmupTemplate, 0, len(convs)) + for _, conv := range convs { + t := templateResponse(conv, false) + p := placement[conv.ID] + t.Placement = &p + templates = append(templates, t) + } + c.JSON(http.StatusOK, gin.H{"templates": templates, "days": days}) +} + +// warmupTemplatePage is the repository page size; the list walks every page +// so a workspace with more templates than one page still sees them all. +const warmupTemplatePage = 200 + +func (h *Handler) listAllWarmupTemplates(ctx context.Context, orgID uuid.UUID) ([]models.WarmupConversation, error) { + var all []models.WarmupConversation + for offset := 0; ; offset += warmupTemplatePage { + page, total, err := h.WarmupContentRepo.ListConversations(ctx, repository.ConversationFilter{ + Source: models.WarmupContentSourceTemplate, + Status: models.WarmupConversationActive, + OrganizationID: &orgID, + Limit: warmupTemplatePage, + Offset: offset, + }) + if err != nil { + return nil, err + } + all = append(all, page...) + if len(page) < warmupTemplatePage || len(all) >= total { + return all, nil + } + } +} + +// GetWarmupTemplateStats is one template's placement split by recipient +// provider group over the trailing window (days, default 30). +func (h *Handler) GetWarmupTemplateStats(c *gin.Context) { + orgID, ok := requireOrgID(c) + if !ok { + return + } + templateID, err := uuid.Parse(c.Param("id")) + if err != nil { + errx.JSON(c, errx.New(errx.BadRequest, "invalid template id")) + return + } + since, days, ok := templateStatsSince(c) + if !ok { + return + } + conv, err := h.WarmupContentRepo.GetOrgTemplateConversation(c.Request.Context(), templateID, orgID) + if err != nil { + errx.JSON(c, errx.New(errx.Internal, err.Error())) + return + } + if conv == nil { + errx.JSON(c, errx.New(errx.NotFound, "warmup template not found")) + return + } + groups, err := h.WarmupContentRepo.TemplatePlacementByGroup(c.Request.Context(), templateID, orgID, since) + if err != nil { + errx.JSON(c, errx.New(errx.Internal, err.Error())) + return + } + var total models.WarmupTemplatePlacement + for _, g := range groups { + total.Sent += g.Sent + total.Inbox += g.Inbox + total.Tabs += g.Tabs + total.Spam += g.Spam + total.Rescued += g.Rescued + } + c.JSON(http.StatusOK, gin.H{"template_id": templateID, "days": days, "total": total, "groups": groups}) +} + +// GetWarmupTemplateSettings returns how much of the organization's warmup +// carries its own templates. +func (h *Handler) GetWarmupTemplateSettings(c *gin.Context) { + orgID, ok := requireOrgID(c) + if !ok { + return + } + settings, err := h.WarmupContentRepo.GetTemplateSettings(c.Request.Context(), orgID) + if err != nil { + errx.JSON(c, errx.New(errx.Internal, err.Error())) + return + } + c.JSON(http.StatusOK, settings) +} + +// UpdateWarmupTemplateSettings sets the template share (0 to 100) and the +// templates-only switch for the organization. +func (h *Handler) UpdateWarmupTemplateSettings(c *gin.Context) { + orgID, ok := requireOrgID(c) + if !ok { + return + } + var payload struct { + TemplateShare *int `json:"template_share"` + TemplatesOnly *bool `json:"templates_only"` + } + if err := c.ShouldBindJSON(&payload); err != nil { + errx.JSON(c, errx.InvalidBody(err)) + return + } + if payload.TemplateShare == nil || payload.TemplatesOnly == nil { + errx.JSON(c, errx.New(errx.BadRequest, "template_share and templates_only are required")) + return + } + settings := models.WarmupTemplateSettings{TemplateShare: *payload.TemplateShare, TemplatesOnly: *payload.TemplatesOnly} + if settings.TemplateShare < 0 || settings.TemplateShare > 100 { + errx.JSON(c, errx.New(errx.BadRequest, "template_share must be between 0 and 100")) + return + } + if err := h.WarmupContentRepo.UpsertTemplateSettings(c.Request.Context(), orgID, settings); err != nil { + errx.JSON(c, errx.New(errx.Internal, err.Error())) + return + } + h.auditOrg(c, models.AuditActionUpdate, models.AuditEntityWarmupTemplate, nil, nil, map[string]string{ + "template_share": strconv.Itoa(settings.TemplateShare), + "templates_only": strconv.FormatBool(settings.TemplatesOnly), + }) + c.JSON(http.StatusOK, settings) +} + +// DeleteWarmupTemplate archives one of the caller's organization's templates. +func (h *Handler) DeleteWarmupTemplate(c *gin.Context) { + orgID, ok := requireOrgID(c) + if !ok { + return + } + templateID, err := uuid.Parse(c.Param("id")) + if err != nil { + errx.JSON(c, errx.New(errx.BadRequest, "invalid template id")) + return + } + archived, err := h.WarmupContentRepo.ArchiveOrgTemplateConversation(c.Request.Context(), templateID, orgID) + if err != nil { + errx.JSON(c, errx.New(errx.Internal, err.Error())) + return + } + if !archived { + errx.JSON(c, errx.New(errx.NotFound, "warmup template not found")) + return + } + + h.auditOrg(c, models.AuditActionDelete, models.AuditEntityWarmupTemplate, &templateID, nil, nil) + + c.Status(http.StatusNoContent) +} + +// CheckWarmupTemplate runs the static analyzer over a draft subject + body +// without storing anything, so a workspace can inspect copy before submit. +func (h *Handler) CheckWarmupTemplate(c *gin.Context) { + if _, ok := requireOrgID(c); !ok { + return + } + var payload warmupTemplatePayload + if err := c.ShouldBindJSON(&payload); err != nil { + errx.JSON(c, errx.InvalidBody(err)) + return + } + if utf8.RuneCountInString(payload.Subject) > warmupTemplateMaxSubject || len(payload.Body) > warmupTemplateMaxBody { + errx.JSON(c, errx.New(errx.BadRequest, "subject exceeds 200 characters or body exceeds 50 KB")) + return + } + c.JSON(http.StatusOK, warmupcheck.Check(payload.Subject, payload.Body)) +} diff --git a/internal/api/handler/warmup_templates_test.go b/internal/api/handler/warmup_templates_test.go new file mode 100644 index 000000000..2c83313fc --- /dev/null +++ b/internal/api/handler/warmup_templates_test.go @@ -0,0 +1,37 @@ +package handler + +import ( + "strings" + "testing" +) + +func TestValidateTemplatePayload(t *testing.T) { + cases := []struct { + name string + payload warmupTemplatePayload + wantErr bool + }{ + {name: "plain copy passes", payload: warmupTemplatePayload{Subject: "Quick question", Body: "Hi Sam, saw your post. Still comparing tools?"}}, + {name: "markup in body passes verbatim", payload: warmupTemplatePayload{Subject: "Q", Body: "Hi {first_name},\nSee for the plan."}}, + {name: "missing subject", payload: warmupTemplatePayload{Body: "body"}, wantErr: true}, + {name: "missing body", payload: warmupTemplatePayload{Subject: "subject"}, wantErr: true}, + {name: "subject too long", payload: warmupTemplatePayload{Subject: strings.Repeat("a", 201), Body: "body"}, wantErr: true}, + {name: "body too long", payload: warmupTemplatePayload{Subject: "s", Body: strings.Repeat("a", 51*1024)}, wantErr: true}, + {name: "markup in subject refused", payload: warmupTemplatePayload{Subject: "Hi ", Body: "body"}, wantErr: true}, + {name: "newline in subject refused", payload: warmupTemplatePayload{Subject: "a\nb", Body: "body"}, wantErr: true}, + {name: "NUL in body refused", payload: warmupTemplatePayload{Subject: "s", Body: "a\x00b"}, wantErr: true}, + {name: "warmup wording refused", payload: warmupTemplatePayload{Subject: "s", Body: "this is a warmup email test"}, wantErr: true}, + {name: "copy the send gate would block is refused", payload: warmupTemplatePayload{Subject: "Free cash bonus", Body: "Act now to claim your free cash bonus."}, wantErr: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := validateTemplatePayload(&tc.payload) + if tc.wantErr && err == nil { + t.Fatalf("expected an error for %+v", tc.payload) + } + if !tc.wantErr && err != nil { + t.Fatalf("unexpected error: %v", err) + } + }) + } +} diff --git a/internal/api/routes.go b/internal/api/routes.go index 0344b5aa8..6be75a601 100644 --- a/internal/api/routes.go +++ b/internal/api/routes.go @@ -1404,6 +1404,21 @@ func Run( warmupRouting.DELETE("/:id", h.DeleteWarmupRoutingRule) } + // Warmup templates (org-scoped). A workspace submits its own + // subject + opening body; the pick path sends it verbatim through + // that workspace's warmup pool, at most once per sender per day. + warmupTemplates := protected.Group("/warmup/templates") + warmupTemplates.Use(m.RequireOrganization(), m.RequireAccess(models.PermManageSettings, models.APIPermWarmupTemplates), m.RateLimitMiddleware(models.RateLimitWrite)) + { + warmupTemplates.GET("", h.ListWarmupTemplates) + warmupTemplates.POST("", h.CreateWarmupTemplate) + warmupTemplates.POST("/check", h.CheckWarmupTemplate) + warmupTemplates.GET("/settings", h.GetWarmupTemplateSettings) + warmupTemplates.PUT("/settings", h.UpdateWarmupTemplateSettings) + warmupTemplates.GET("/:id/stats", h.GetWarmupTemplateStats) + warmupTemplates.DELETE("/:id", h.DeleteWarmupTemplate) + } + // Reply templates (org-scoped) templates := protected.Group("/templates") templates.Use(m.RequireOrganization(), m.RateLimitMiddleware(models.RateLimitWrite)) diff --git a/internal/app/orgtransfer/spec.go b/internal/app/orgtransfer/spec.go index 0452beeb5..dd6d12139 100644 --- a/internal/app/orgtransfer/spec.go +++ b/internal/app/orgtransfer/spec.go @@ -740,6 +740,15 @@ var Tables = []Table{ Name: "warmup_routing_rules", Group: models.OrgDataGroupWarmup, Scope: scopeOrg, }, + { + Name: "warmup_conversations", Group: models.OrgDataGroupWarmup, + Scope: scopeOrg, + Note: "Only organization-scoped rows travel: the warmup templates a workspace submitted itself. Shared library rows carry no organization_id and stay instance-global.", + }, + { + Name: "warmup_template_settings", Group: models.OrgDataGroupWarmup, + Scope: scopeOrg, + }, { Name: "warmup_statistics", Group: models.OrgDataGroupWarmup, Scope: `email_account_id IN ` + orgMailboxes, @@ -1105,7 +1114,6 @@ var ExcludedTables = map[string]string{ "cloud_link_commands": "Warmup commands Warmbly Cloud leased to this instance, sealed with the workspace key. They are bound to this instance's link and expire within minutes.", "cloud_link_reports": "Undelivered command results and observations owed to Warmbly Cloud over this instance's link, which does not travel.", "cloud_link_warmup_messages": "Handles this instance gave Warmbly Cloud for warmup mail, bound to its link and to provider coordinates on this instance.", - "warmup_conversations": "The instance's shared warmup content library, not workspace data.", "copy_judgments": "A cache of copy judgments keyed by the hash of the words judged. The destination re-reads a step the first time its Advisor runs.", "warmup_thread_messages": "Message identifiers this instance recognised as turns of a warmup conversation, so the reply to each is recognised too. The destination syncs provider mail afresh and rebuilds it from the warmup tokens, which do travel.", "sessions": "Live login sessions. They are bound to the source instance's signing key and must not survive a move.", diff --git a/internal/infrastructure/db/migrations/000341_warmup_template_conversations.down.sql b/internal/infrastructure/db/migrations/000341_warmup_template_conversations.down.sql new file mode 100644 index 000000000..bfcf7646b --- /dev/null +++ b/internal/infrastructure/db/migrations/000341_warmup_template_conversations.down.sql @@ -0,0 +1,25 @@ +-- Rolling back with workspace templates on file would discard customer data; +-- refuse and leave the operator to roll forward instead. +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM public.warmup_conversations WHERE source = 'template') + OR EXISTS (SELECT 1 FROM public.warmup_template_settings) THEN + RAISE EXCEPTION 'warmup template rows or settings exist; delete them (archived templates included) before rolling back 000341'; + END IF; +END $$; + +DROP TABLE IF EXISTS public.warmup_template_settings; + +ALTER TABLE ONLY public.warmup_conversations + DROP CONSTRAINT warmup_conversations_template_owner_check; + +DROP INDEX public.idx_warmup_conversations_org; + +ALTER TABLE ONLY public.warmup_conversations + DROP CONSTRAINT warmup_conversations_source_check; +ALTER TABLE ONLY public.warmup_conversations + ADD CONSTRAINT warmup_conversations_source_check + CHECK ((source = ANY (ARRAY['ai'::text, 'static'::text]))); + +ALTER TABLE public.warmup_conversations + DROP COLUMN organization_id; diff --git a/internal/infrastructure/db/migrations/000341_warmup_template_conversations.up.sql b/internal/infrastructure/db/migrations/000341_warmup_template_conversations.up.sql new file mode 100644 index 000000000..f35da2333 --- /dev/null +++ b/internal/infrastructure/db/migrations/000341_warmup_template_conversations.up.sql @@ -0,0 +1,29 @@ +-- Organization-scoped warmup templates live in the shared content bank: +-- a row an organization submits itself (subject plus opening body, sent +-- verbatim) that the pick pipeline interleaves into that organization's +-- own warmup sends. +ALTER TABLE public.warmup_conversations + ADD COLUMN organization_id uuid REFERENCES public.organizations(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.warmup_conversations + DROP CONSTRAINT warmup_conversations_source_check; +ALTER TABLE ONLY public.warmup_conversations + ADD CONSTRAINT warmup_conversations_source_check + CHECK ((source = ANY (ARRAY['ai'::text, 'static'::text, 'template'::text]))); + +-- A template always has an owner; shared library rows never do. +ALTER TABLE ONLY public.warmup_conversations + ADD CONSTRAINT warmup_conversations_template_owner_check + CHECK ((source = 'template') = (organization_id IS NOT NULL)); + +CREATE INDEX idx_warmup_conversations_org ON public.warmup_conversations + USING btree (organization_id) WHERE organization_id IS NOT NULL; + +-- How much of a workspace's warmup should carry its own templates. One row +-- per organization; absence means the defaults (half of sends, bank allowed). +CREATE TABLE public.warmup_template_settings ( + organization_id uuid PRIMARY KEY REFERENCES public.organizations(id) ON DELETE CASCADE, + template_share integer NOT NULL DEFAULT 50 CHECK (template_share BETWEEN 0 AND 100), + templates_only boolean NOT NULL DEFAULT false, + updated_at timestamp with time zone NOT NULL DEFAULT now() +); diff --git a/internal/models/api_permission.go b/internal/models/api_permission.go index 184a6ae89..95ad8db56 100644 --- a/internal/models/api_permission.go +++ b/internal/models/api_permission.go @@ -51,6 +51,9 @@ const ( // AI APIPermAIAgent // Run the AI assistant / agent (dashboard agent + MCP) APIPermAIResearch // Run AI contact research + + // Warmup templates submitted by the organization itself + APIPermWarmupTemplates // Manage warmup templates ) // AllAPIPermissionsMask is the OR of every defined permission bit. @@ -68,7 +71,8 @@ const AllAPIPermissionsMask uint64 = APIPermReadEmails | APIPermReadCampaigns | APIPermReadCRM | APIPermWriteCRM | APIPermReadAuditLogs | APIPermIntegrations | APIPermWarmupRouting | - APIPermAIAgent | APIPermAIResearch + APIPermAIAgent | APIPermAIResearch | + APIPermWarmupTemplates // Preset permission sets surfaced via GET /api-keys/permissions so a // caller can grant a sane default without picking bits by hand. @@ -85,7 +89,8 @@ var ( APIPermWriteTemplates | APIPermWriteCRM | APIPermRealtimeSubscribe | APIPermWebhooks | APIPermAPIKeys | APIPermIntegrations | APIPermWarmupRouting | - APIPermAIAgent | APIPermAIResearch + APIPermAIAgent | APIPermAIResearch | + APIPermWarmupTemplates ) type APIPermission struct { @@ -120,6 +125,7 @@ var AllAPIPermissions = []APIPermission{ {"WARMUP_ROUTING", APIPermWarmupRouting, "Manage warmup routing rules", "special"}, {"AI_AGENT", APIPermAIAgent, "Run the AI assistant and MCP tools", "special"}, {"AI_RESEARCH", APIPermAIResearch, "Run AI contact research", "special"}, + {"WARMUP_TEMPLATES", APIPermWarmupTemplates, "Manage warmup templates", "special"}, } // HasAPIPermission reports whether the bitmask grants every bit in `required`. @@ -158,6 +164,7 @@ var apiPermissionRoleNeeds = map[uint64]OrganizationPermission{ APIPermWarmupRouting: PermManageSettings, APIPermAIAgent: PermUseAI, APIPermAIResearch: PermViewContacts | PermUseAI, + APIPermWarmupTemplates: PermManageSettings, } // APIPermissionsForMember is the widest API scope set a member may delegate to a key or an app. diff --git a/internal/models/audit.go b/internal/models/audit.go index 0f090ee25..879aedc0b 100644 --- a/internal/models/audit.go +++ b/internal/models/audit.go @@ -87,6 +87,7 @@ const ( AuditEntityWebhook AuditEntityType = "webhook" AuditEntityIntegration AuditEntityType = "integration" AuditEntityWarmupRoutingRule AuditEntityType = "warmup_routing_rule" + AuditEntityWarmupTemplate AuditEntityType = "warmup_template" AuditEntityFolder AuditEntityType = "folder" AuditEntityTag AuditEntityType = "tag" AuditEntityCategory AuditEntityType = "category" diff --git a/internal/models/warmup_content.go b/internal/models/warmup_content.go index b99bd1848..652271e36 100644 --- a/internal/models/warmup_content.go +++ b/internal/models/warmup_content.go @@ -8,10 +8,12 @@ import ( ) // Content sources for warmup message bodies. "static" is the in-code library; -// "ai" is a thread drawn from the offline-generated warmup_conversations bank. +// "ai" is a thread drawn from the offline-generated warmup_conversations bank; +// "template" is an organization-supplied subject + opening sent verbatim. const ( - WarmupContentSourceStatic = "static" - WarmupContentSourceAI = "ai" + WarmupContentSourceStatic = "static" + WarmupContentSourceAI = "ai" + WarmupContentSourceTemplate = "template" ) // AdminSettingsKeyWarmupGeneration is the admin_settings key under which the @@ -39,6 +41,42 @@ type WarmupConversation struct { ScenarioVersion *string `json:"scenario_version,omitempty"` RenderingVersion *string `json:"rendering_version,omitempty"` SemanticReview string `json:"semantic_review"` + // OrganizationID is set only on source="template" rows: the workspace that + // submitted the template. Shared library rows keep it NULL. + OrganizationID *uuid.UUID `json:"organization_id,omitempty"` +} + +// WarmupTemplateSettings is how much of one organization's warmup carries its +// own templates. TemplateShare is the percentage of new openings drawn from +// the organization's templates when at least one is eligible; TemplatesOnly +// sends nothing else, and an opening with no eligible template is skipped. +type WarmupTemplateSettings struct { + TemplateShare int `json:"template_share"` + TemplatesOnly bool `json:"templates_only"` +} + +// DefaultWarmupTemplateSettings mirrors the mix the warmup pool applies when +// an organization has templates but never changed the setting. +func DefaultWarmupTemplateSettings() WarmupTemplateSettings { + return WarmupTemplateSettings{TemplateShare: 50} +} + +// WarmupTemplatePlacement counts where one template's sends landed, as the +// recipient mailboxes reported them. Sent counts every dispatched token; +// the landing counters cover the receipts that came back. +type WarmupTemplatePlacement struct { + Sent int `json:"sent"` + Inbox int `json:"inbox"` + Tabs int `json:"tabs"` + Spam int `json:"spam"` + Rescued int `json:"rescued"` +} + +// WarmupTemplateGroupPlacement is WarmupTemplatePlacement for one recipient +// provider group (google, microsoft, yahoo, other). +type WarmupTemplateGroupPlacement struct { + Group string `json:"group"` + WarmupTemplatePlacement } // Warmup generation job modes. "sync" runs every model call inline (the diff --git a/internal/pkg/warmlint/lint.go b/internal/pkg/warmlint/lint.go index efd935599..bc639238d 100644 --- a/internal/pkg/warmlint/lint.go +++ b/internal/pkg/warmlint/lint.go @@ -6,6 +6,7 @@ package warmlint import ( "fmt" "regexp" + "sort" "strings" "unicode" @@ -316,7 +317,7 @@ func trimURL(u string) string { return strings.TrimRight(u, ".,;:!?)]}\"'") } -func countTriggerTerms(text string) int { +func triggerTermSet(text string) map[string]struct{} { lower := strings.ToLower(text) found := map[string]struct{}{} for _, w := range wordToken.FindAllString(lower, -1) { @@ -329,5 +330,22 @@ func countTriggerTerms(text string) int { found[p] = struct{}{} } } - return len(found) + return found +} + +func countTriggerTerms(text string) int { + return len(triggerTermSet(text)) +} + +// TriggerTerms returns the distinct spam-trigger terms and phrases in text, +// sorted, for callers that report findings rather than gate on a count. URLs +// are masked first so link slugs do not read as copy. +func TriggerTerms(text string) []string { + found := triggerTermSet(withoutURLs(text)) + hits := make([]string, 0, len(found)) + for t := range found { + hits = append(hits, t) + } + sort.Strings(hits) + return hits } diff --git a/internal/pkg/warmupcheck/warmupcheck.go b/internal/pkg/warmupcheck/warmupcheck.go new file mode 100644 index 000000000..24a394883 --- /dev/null +++ b/internal/pkg/warmupcheck/warmupcheck.go @@ -0,0 +1,58 @@ +// Package warmupcheck statically analyzes an organization-supplied warmup +// template (subject + body) before it enters warmup rotation. It reports what +// the copy looks like, not a deliverability promise. +package warmupcheck + +import ( + "regexp" + "strings" + "unicode/utf8" + + "github.com/warmbly/warmbly/internal/pkg/warmlint" +) + +var linkPattern = regexp.MustCompile(`https?://[^\s"'<>)\]]*`) + +// readingWordsPerMinute is the plain-prose pace used for reading time. +const readingWordsPerMinute = 200 + +// Result is the static analysis of one template. +type Result struct { + SubjectLength int `json:"subject_length"` + WordCount int `json:"word_count"` + ReadingTimeSeconds int `json:"reading_time_seconds"` + LinkCount int `json:"link_count"` + QuestionCount int `json:"question_count"` + SpamTriggerHits []string `json:"spam_trigger_hits"` + // BlockedReason is set when the warmup send gate would refuse this copy. + BlockedReason string `json:"blocked_reason,omitempty"` +} + +// Check analyzes subject and body verbatim; templates are plain text. +func Check(subject, body string) Result { + combined := strings.TrimSpace(subject + "\n" + body) + words := len(strings.Fields(combined)) + reading := 0 + if words > 0 { + reading = (words*60 + readingWordsPerMinute/2) / readingWordsPerMinute + if reading < 1 { + reading = 1 + } + } + return Result{ + SubjectLength: utf8.RuneCountInString(strings.TrimSpace(subject)), + WordCount: words, + ReadingTimeSeconds: reading, + LinkCount: len(linkPattern.FindAllString(combined, -1)), + QuestionCount: strings.Count(combined, "?"), + SpamTriggerHits: warmlint.TriggerTerms(combined), + BlockedReason: blockedReason(subject, body), + } +} + +func blockedReason(subject, body string) string { + if err := warmlint.Check(subject, body, false); err != nil { + return err.Error() + } + return "" +} diff --git a/internal/pkg/warmupcheck/warmupcheck_test.go b/internal/pkg/warmupcheck/warmupcheck_test.go new file mode 100644 index 000000000..9ecdee32c --- /dev/null +++ b/internal/pkg/warmupcheck/warmupcheck_test.go @@ -0,0 +1,63 @@ +package warmupcheck + +import ( + "strings" + "testing" +) + +func TestCheckPlainCopy(t *testing.T) { + res := Check("Quick question about pricing", "Hi Sam,\nSaw your post on outbound. Are you still comparing tools?\nThanks,\nJo") + if res.SubjectLength != len("Quick question about pricing") { + t.Fatalf("subject length = %d", res.SubjectLength) + } + if res.WordCount != 18 { + t.Fatalf("word count = %d, want 18", res.WordCount) + } + if res.ReadingTimeSeconds != 5 { + t.Fatalf("reading time = %d, want 5", res.ReadingTimeSeconds) + } + if res.LinkCount != 0 { + t.Fatalf("link count = %d", res.LinkCount) + } + if res.QuestionCount != 1 { + t.Fatalf("question count = %d, want 1", res.QuestionCount) + } + if len(res.SpamTriggerHits) != 0 { + t.Fatalf("trigger hits = %v", res.SpamTriggerHits) + } + if res.BlockedReason != "" { + t.Fatalf("plain copy blocked: %q", res.BlockedReason) + } +} + +func TestCheckCountsLinksAndTriggers(t *testing.T) { + res := Check("Free trial inside", "Act now at https://example.com/x?free=true to claim your cash bonus.") + if res.LinkCount != 1 { + t.Fatalf("link count = %d, want 1", res.LinkCount) + } + found := map[string]bool{} + for _, h := range res.SpamTriggerHits { + found[h] = true + } + for _, want := range []string{"free", "act now", "cash", "cash bonus"} { + if !found[want] { + t.Fatalf("missing trigger hit %q in %v", want, res.SpamTriggerHits) + } + } + if !strings.Contains(res.BlockedReason, "spam-trigger") { + t.Fatalf("send gate not reported: %q", res.BlockedReason) + } + // The slug inside the URL is masked, so it must not double-count "free". + for _, h := range res.SpamTriggerHits { + if strings.Contains(h, "example.com") { + t.Fatalf("URL slug reported as copy: %v", res.SpamTriggerHits) + } + } +} + +func TestCheckEmpty(t *testing.T) { + res := Check("", " ") + if res.WordCount != 0 || res.ReadingTimeSeconds != 0 || res.SubjectLength != 0 { + t.Fatalf("empty input produced %+v", res) + } +} diff --git a/internal/repository/pg_warmup_content.go b/internal/repository/pg_warmup_content.go index 83aa3c121..f78d02a0b 100644 --- a/internal/repository/pg_warmup_content.go +++ b/internal/repository/pg_warmup_content.go @@ -15,12 +15,13 @@ import ( // ConversationFilter narrows a warmup_conversations listing. type ConversationFilter struct { - PoolType string - Segment string - Source string - Status string - Limit int - Offset int + PoolType string + Segment string + Source string + Status string + OrganizationID *uuid.UUID + Limit int + Offset int } // WarmupConversationStat is a grouped count for the admin overview. @@ -44,6 +45,12 @@ type WarmupContentPick struct { TaskID uuid.UUID SenderID uuid.UUID RecipientID uuid.UUID + // OrganizationID names the picking sender's organization, whose own + // source="template" rows are the only ones a template draw may return. + OrganizationID *uuid.UUID + // TemplatesOnly draws from the organization's templates alone; otherwise + // templates are left out and the shared bank is drawn from. + TemplatesOnly bool // IncludeAI admits generated threads; static rows are admitted only when listed in StaticIDs. IncludeAI bool StaticIDs []uuid.UUID @@ -67,6 +74,18 @@ type WarmupContentRepository interface { GetConversation(ctx context.Context, id uuid.UUID) (*models.WarmupConversation, error) ListConversations(ctx context.Context, f ConversationFilter) ([]models.WarmupConversation, int, error) SetConversationStatus(ctx context.Context, id uuid.UUID, status string) error + // ArchiveOrgTemplateConversation retires one organization's own template + // row; it reports false when the row is missing or belongs elsewhere. + ArchiveOrgTemplateConversation(ctx context.Context, id, orgID uuid.UUID) (bool, error) + // GetOrgTemplateConversation loads one organization's own template row; nil when missing or owned elsewhere. + GetOrgTemplateConversation(ctx context.Context, id, orgID uuid.UUID) (*models.WarmupConversation, error) + // GetTemplateSettings is one organization's template mix; defaults when unset. + GetTemplateSettings(ctx context.Context, orgID uuid.UUID) (models.WarmupTemplateSettings, error) + UpsertTemplateSettings(ctx context.Context, orgID uuid.UUID, s models.WarmupTemplateSettings) error + // TemplatePlacement is where each of one organization's templates landed since a time, keyed by conversation. + TemplatePlacement(ctx context.Context, orgID uuid.UUID, since time.Time) (map[uuid.UUID]models.WarmupTemplatePlacement, error) + // TemplatePlacementByGroup is one template's landing split by recipient provider group. + TemplatePlacementByGroup(ctx context.Context, id, orgID uuid.UUID, since time.Time) ([]models.WarmupTemplateGroupPlacement, error) // RefreshUnusedConversations replaces unused stock without retiring active threads. RefreshUnusedConversations(ctx context.Context, poolType, segment string, n int) (int, error) RetireRiskyConversations(ctx context.Context, since time.Time, minSends, minSpamPlacements int, maxSpamRate float64) (int, error) @@ -129,10 +148,11 @@ func (r *warmupContentRepository) InsertConversation(ctx context.Context, c *mod if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended('warmbly:approved-warmup-content',0))`); err != nil { return err } + // Duplicates are checked within one owner: the shared library against itself, an organization's templates against its own. var duplicate bool - if err := tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM warmup_conversations WHERE id<>$3 AND semantic_review='passed' AND ( + if err := tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM warmup_conversations WHERE id<>$3 AND semantic_review='passed' AND organization_id IS NOT DISTINCT FROM $4 AND (source <> 'template' OR status = 'active') AND ( lower(btrim(regexp_replace(subject,'\s+',' ','g')))=lower(btrim(regexp_replace($1::text,'\s+',' ','g'))) OR - lower(btrim(regexp_replace(description,'\s+',' ','g')))=lower(btrim(regexp_replace($2::text,'\s+',' ','g')))))`, c.Subject, c.Description, c.ID).Scan(&duplicate); err != nil { + lower(btrim(regexp_replace(description,'\s+',' ','g')))=lower(btrim(regexp_replace($2::text,'\s+',' ','g')))))`, c.Subject, c.Description, c.ID, c.OrganizationID).Scan(&duplicate); err != nil { return err } if duplicate { @@ -141,13 +161,14 @@ func (r *warmupContentRepository) InsertConversation(ctx context.Context, c *mod } query := ` INSERT INTO warmup_conversations - (id, pool_type, segment, source, theme, subject, description, messages, status, lint_passed, reply_eligible, usage_count, generated_by_job_id, scenario_version, rendering_version, semantic_review) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, COALESCE(NULLIF($16, ''), 'legacy_unknown')) + (id, pool_type, segment, source, theme, subject, description, messages, status, lint_passed, reply_eligible, usage_count, generated_by_job_id, scenario_version, rendering_version, semantic_review, organization_id) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, COALESCE(NULLIF($16, ''), 'legacy_unknown'), $17) ON CONFLICT (id) DO NOTHING ` _, err = tx.Exec(ctx, query, c.ID, c.PoolType, c.Segment, c.Source, c.Theme, c.Subject, c.Description, msgs, c.Status, c.LintPassed, c.ReplyEligible, c.UsageCount, c.GeneratedByJob, c.ScenarioVersion, c.RenderingVersion, c.SemanticReview, + c.OrganizationID, ) if err != nil { return err @@ -160,7 +181,7 @@ func scanConversation(row pgx.Row) (*models.WarmupConversation, error) { var msgs []byte err := row.Scan( &c.ID, &c.PoolType, &c.Segment, &c.Source, &c.Theme, &c.Subject, &c.Description, - &msgs, &c.Status, &c.LintPassed, &c.ReplyEligible, &c.UsageCount, &c.GeneratedByJob, &c.CreatedAt, &c.UpdatedAt, &c.ScenarioVersion, &c.RenderingVersion, &c.SemanticReview, + &msgs, &c.Status, &c.LintPassed, &c.ReplyEligible, &c.UsageCount, &c.GeneratedByJob, &c.CreatedAt, &c.UpdatedAt, &c.ScenarioVersion, &c.RenderingVersion, &c.SemanticReview, &c.OrganizationID, ) if err != nil { return nil, err @@ -171,8 +192,8 @@ func scanConversation(row pgx.Row) (*models.WarmupConversation, error) { return &c, nil } -const conversationCols = `id, pool_type, segment, source, theme, subject, description, messages, status, lint_passed, reply_eligible, usage_count, generated_by_job_id, created_at, updated_at, scenario_version, rendering_version, semantic_review` -const qualifiedConversationCols = `c.id, c.pool_type, c.segment, c.source, c.theme, c.subject, c.description, c.messages, c.status, c.lint_passed, c.reply_eligible, c.usage_count, c.generated_by_job_id, c.created_at, c.updated_at, c.scenario_version, c.rendering_version, c.semantic_review` +const conversationCols = `id, pool_type, segment, source, theme, subject, description, messages, status, lint_passed, reply_eligible, usage_count, generated_by_job_id, created_at, updated_at, scenario_version, rendering_version, semantic_review, organization_id` +const qualifiedConversationCols = `c.id, c.pool_type, c.segment, c.source, c.theme, c.subject, c.description, c.messages, c.status, c.lint_passed, c.reply_eligible, c.usage_count, c.generated_by_job_id, c.created_at, c.updated_at, c.scenario_version, c.rendering_version, c.semantic_review, c.organization_id` // Opening eligibility is independent of existing threads' continuation authority. // openingConversationWhere is the eligibility predicate for a new thread, qualified by table alias t. @@ -225,7 +246,8 @@ func (r *warmupContentRepository) PickConversation(ctx context.Context, pick War FROM warmup_conversations c LEFT JOIN seen ON seen.conversation_id = c.id WHERE ` + openingConversationWhere("c.") + ` AND (c.segment = $1 OR c.segment = '') - AND ((c.source = 'ai' AND $4) OR (c.source = 'static' AND c.id = ANY($5))) + AND ((NOT $8 AND c.organization_id IS NULL AND c.source = 'ai' AND $4) OR (NOT $8 AND c.organization_id IS NULL AND c.source = 'static' AND c.id = ANY($5)) + OR ($8 AND c.source = 'template' AND c.organization_id = $7 AND (seen.last_seen IS NULL OR seen.last_seen < NOW() - INTERVAL '1 day'))) ORDER BY (seen.last_seen IS NOT NULL AND seen.last_seen > NOW() - $6::interval), (c.segment = $1) DESC, seen.last_seen ASC NULLS FIRST, c.usage_count ASC, random() LIMIT 1 @@ -238,7 +260,7 @@ func (r *warmupContentRepository) PickConversation(ctx context.Context, pick War WHERE c.id = picked.id RETURNING ` + qualifiedConversationCols + ` ` - c, err := scanConversation(tx.QueryRow(ctx, query, pick.Segment, pick.SenderID, pick.RecipientID, pick.IncludeAI, staticIDs, WarmupContentRepeatWindow.String())) + c, err := scanConversation(tx.QueryRow(ctx, query, pick.Segment, pick.SenderID, pick.RecipientID, pick.IncludeAI, staticIDs, WarmupContentRepeatWindow.String(), pick.OrganizationID, pick.TemplatesOnly)) if errors.Is(err, pgx.ErrNoRows) { return nil, nil } @@ -299,6 +321,9 @@ func (r *warmupContentRepository) ListConversations(ctx context.Context, f Conve if f.Status != "" { add(" AND status = $"+itoa(len(args)+1), f.Status) } + if f.OrganizationID != nil { + add(" AND organization_id = $"+itoa(len(args)+1), *f.OrganizationID) + } var total int if err := r.db.QueryRow(ctx, `SELECT COUNT(*) FROM warmup_conversations `+where, args...).Scan(&total); err != nil { @@ -341,6 +366,100 @@ func (r *warmupContentRepository) SetConversationStatus(ctx context.Context, id return err } +func (r *warmupContentRepository) ArchiveOrgTemplateConversation(ctx context.Context, id, orgID uuid.UUID) (bool, error) { + tag, err := r.db.Exec(ctx, `UPDATE warmup_conversations SET status = 'archived', reply_eligible = false, updated_at = NOW() + WHERE id = $1 AND organization_id = $2 AND source = 'template' AND status = 'active'`, id, orgID) + if err != nil { + return false, err + } + return tag.RowsAffected() > 0, nil +} + +func (r *warmupContentRepository) GetOrgTemplateConversation(ctx context.Context, id, orgID uuid.UUID) (*models.WarmupConversation, error) { + c, err := scanConversation(r.db.QueryRow(ctx, `SELECT `+conversationCols+` FROM warmup_conversations WHERE id = $1 AND organization_id = $2 AND source = 'template'`, id, orgID)) + if errors.Is(err, pgx.ErrNoRows) { + return nil, nil + } + return c, err +} + +func (r *warmupContentRepository) GetTemplateSettings(ctx context.Context, orgID uuid.UUID) (models.WarmupTemplateSettings, error) { + s := models.DefaultWarmupTemplateSettings() + err := r.db.QueryRow(ctx, `SELECT template_share, templates_only FROM warmup_template_settings WHERE organization_id = $1`, orgID).Scan(&s.TemplateShare, &s.TemplatesOnly) + if errors.Is(err, pgx.ErrNoRows) { + return models.DefaultWarmupTemplateSettings(), nil + } + return s, err +} + +func (r *warmupContentRepository) UpsertTemplateSettings(ctx context.Context, orgID uuid.UUID, s models.WarmupTemplateSettings) error { + _, err := r.db.Exec(ctx, `INSERT INTO warmup_template_settings (organization_id, template_share, templates_only, updated_at) + VALUES ($1, $2, $3, NOW()) + ON CONFLICT (organization_id) DO UPDATE SET template_share = EXCLUDED.template_share, templates_only = EXCLUDED.templates_only, updated_at = NOW()`, + orgID, s.TemplateShare, s.TemplatesOnly) + return err +} + +// templatePlacementSQL joins each template send to the receipt its recipient +// filed, matched on the provider Message-ID, and tags the recipient's group. +// A send with no receipt yet counts as sent only. +func templatePlacementSQL(where string) string { + return ` + SELECT wt.conversation_id, ` + recipientGroupSQL("rec") + ` AS grp, + COUNT(*)::int AS sent, + COUNT(*) FILTER (WHERE wr.first_landing = 'inbox')::int AS inbox, + COUNT(*) FILTER (WHERE wr.first_landing = 'tabs')::int AS tabs, + COUNT(*) FILTER (WHERE wr.first_landing = 'spam' OR wr.landed_spam)::int AS spam, + COUNT(*) FILTER (WHERE wr.rescue_outcome IN ('moved', 'already_out'))::int AS rescued + FROM warmup_tokens wt + JOIN warmup_conversations c ON c.id = wt.conversation_id AND c.source = 'template' AND c.organization_id = $1 + JOIN email_accounts rec ON rec.id = wt.recipient_account_id + LEFT JOIN warmup_received wr ON wr.sender_account_id = wt.sender_account_id + AND wr.email_account_id = wt.recipient_account_id + AND wt.sent_message_id <> '' AND btrim(wr.message_id, '<>') = btrim(wt.sent_message_id, '<>') + WHERE wt.content_source = 'template' AND wt.sent_message_id <> '' AND wt.created_at >= $2 ` + where + ` + GROUP BY 1, 2` +} + +func (r *warmupContentRepository) TemplatePlacement(ctx context.Context, orgID uuid.UUID, since time.Time) (map[uuid.UUID]models.WarmupTemplatePlacement, error) { + rows, err := r.db.Query(ctx, templatePlacementSQL(""), orgID, since) + if err != nil { + return nil, err + } + defer rows.Close() + out := map[uuid.UUID]models.WarmupTemplatePlacement{} + for rows.Next() { + var id uuid.UUID + var grp string + var p models.WarmupTemplatePlacement + if err := rows.Scan(&id, &grp, &p.Sent, &p.Inbox, &p.Tabs, &p.Spam, &p.Rescued); err != nil { + return nil, err + } + t := out[id] + t.Sent, t.Inbox, t.Tabs, t.Spam, t.Rescued = t.Sent+p.Sent, t.Inbox+p.Inbox, t.Tabs+p.Tabs, t.Spam+p.Spam, t.Rescued+p.Rescued + out[id] = t + } + return out, rows.Err() +} + +func (r *warmupContentRepository) TemplatePlacementByGroup(ctx context.Context, id, orgID uuid.UUID, since time.Time) ([]models.WarmupTemplateGroupPlacement, error) { + rows, err := r.db.Query(ctx, templatePlacementSQL("AND wt.conversation_id = $3")+" ORDER BY 2", orgID, since, id) + if err != nil { + return nil, err + } + defer rows.Close() + out := []models.WarmupTemplateGroupPlacement{} + for rows.Next() { + var conv uuid.UUID + var g models.WarmupTemplateGroupPlacement + if err := rows.Scan(&conv, &g.Group, &g.Sent, &g.Inbox, &g.Tabs, &g.Spam, &g.Rescued); err != nil { + return nil, err + } + out = append(out, g) + } + return out, rows.Err() +} + func (r *warmupContentRepository) RefreshUnusedConversations(ctx context.Context, poolType, segment string, n int) (int, error) { tag, err := r.db.Exec(ctx, ` UPDATE warmup_conversations SET status = 'archived', updated_at = NOW() diff --git a/internal/repository/warmup_template_live_test.go b/internal/repository/warmup_template_live_test.go new file mode 100644 index 000000000..dedb0ebd4 --- /dev/null +++ b/internal/repository/warmup_template_live_test.go @@ -0,0 +1,189 @@ +package repository + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/google/uuid" + + "github.com/warmbly/warmbly/internal/models" +) + +// insertTemplateConversation mirrors what the /warmup/templates handler writes: +// an org-scoped row in the shared bank with no reply turns. +func insertTemplateConversation(t *testing.T, f *poolLinkFixture, segment string) uuid.UUID { + t.Helper() + id := uuid.New() + _, err := f.pool.Exec(t.Context(), `INSERT INTO warmup_conversations(id,pool_type,segment,source,subject,description,messages,status,scenario_version,rendering_version,reply_eligible,lint_passed,semantic_review,organization_id) + VALUES($1,'premium',$2,'template',$4,'Hi, quick question about your Q4 plans.','[]','active','natural-v1','canonical-v1',true,true,'passed',$3)`, + id, segment, f.org, "Template subject "+id.String()[:8]) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _, _ = f.pool.Exec(context.Background(), `DELETE FROM warmup_conversations WHERE id=$1`, id) }) + return id +} + +func templatePick(t *testing.T, f *poolLinkFixture, segment string, sender, recipient uuid.UUID) WarmupContentPick { + t.Helper() + pick := contentPoolPick(t, f, segment, sender, recipient) + pick.OrganizationID = &f.org + pick.TemplatesOnly = true + return pick +} + +// An organization's template enters its own warmup rotation, never another +// organization's, and a sender sees it at most once per day. +func TestLiveTemplatePickScopesToOrgAndCapsPerDay(t *testing.T) { + f, _ := lineageFixture(t) + r := NewWarmupContentRepository(f.pool).(*warmupContentRepository) + segment := "fixture-" + uuid.NewString() + template := insertTemplateConversation(t, f, segment) + ctx := t.Context() + + // Org A's sender picks org A's template. + c, err := r.PickConversation(ctx, templatePick(t, f, segment, f.sender, f.recipient)) + if err != nil || c == nil || c.ID != template { + t.Fatalf("own template not picked: %+v %v", c, err) + } + if c.Source != "template" || c.OrganizationID == nil || *c.OrganizationID != f.org { + t.Fatalf("picked row lost its org scope: %+v", c) + } + + // A bank draw never returns a template, whatever the organization. + bank := templatePick(t, f, segment, f.sender, f.recipient) + bank.TemplatesOnly, bank.IncludeAI = false, false + if fromBank, err := r.PickConversation(ctx, bank); err != nil || fromBank != nil { + t.Fatalf("bank draw returned a template: %+v %v", fromBank, err) + } + + // Org B's sender can never draw org A's template. + fB := newPoolLinkFixture(t) + other, err := r.PickConversation(ctx, templatePick(t, fB, segment, fB.sender, fB.recipient)) + if err != nil { + t.Fatalf("org B pick errored: %v", err) + } + if other != nil { + t.Fatalf("org B drew org A's template: %+v", other) + } + + // Same sender, new task, same day: the cap filters the template. + if again, err := r.PickConversation(ctx, templatePick(t, f, segment, f.sender, f.recipient)); err != nil || again != nil { + t.Fatalf("template resent within the day: %+v %v", again, err) + } + + // A day later it is eligible again. + if _, err := f.pool.Exec(ctx, `UPDATE warmup_conversation_mailboxes SET created_at = NOW() - INTERVAL '2 days' WHERE conversation_id=$1`, template); err != nil { + t.Fatal(err) + } + next, err := r.PickConversation(ctx, templatePick(t, f, segment, f.sender, f.recipient)) + if err != nil || next == nil || next.ID != template { + t.Fatalf("template not eligible next day: %+v %v", next, err) + } +} + +// Duplicate detection is per owner: one organization's template never blocks +// another organization or the shared library from the same wording. +func TestLiveTemplateDuplicateCheckIsPerOrganization(t *testing.T) { + f, _ := lineageFixture(t) + fB := newPoolLinkFixture(t) + r := NewWarmupContentRepository(f.pool) + ctx := t.Context() + scenario, rendering := "natural-v1", "canonical-v1" + subject := "Template subject " + uuid.NewString()[:8] + row := func(org *uuid.UUID, source string) *models.WarmupConversation { + return &models.WarmupConversation{PoolType: "premium", Source: source, Subject: subject, Description: "Body " + uuid.NewString(), Messages: []string{}, Status: "active", LintPassed: true, ReplyEligible: true, ScenarioVersion: &scenario, RenderingVersion: &rendering, SemanticReview: "passed", OrganizationID: org} + } + insert := func(c *models.WarmupConversation) error { + err := r.InsertConversation(ctx, c) + if err == nil { + t.Cleanup(func() { _, _ = f.pool.Exec(context.Background(), `DELETE FROM warmup_conversations WHERE id=$1`, c.ID) }) + } + return err + } + if err := insert(row(&f.org, "template")); err != nil { + t.Fatalf("org A template: %v", err) + } + if err := insert(row(&f.org, "template")); !errors.Is(err, ErrWarmupConversationDuplicate) { + t.Fatalf("org A repeat accepted: %v", err) + } + if err := insert(row(&fB.org, "template")); err != nil { + t.Fatalf("org B blocked by org A's template: %v", err) + } + if err := insert(row(nil, "ai")); err != nil { + t.Fatalf("shared library blocked by a template: %v", err) + } +} + +// Template settings default to a half share and round-trip per organization. +func TestLiveTemplateSettingsDefaultAndRoundTrip(t *testing.T) { + f, _ := lineageFixture(t) + r := NewWarmupContentRepository(f.pool) + ctx := t.Context() + got, err := r.GetTemplateSettings(ctx, f.org) + if err != nil || got != models.DefaultWarmupTemplateSettings() { + t.Fatalf("defaults: %+v %v", got, err) + } + want := models.WarmupTemplateSettings{TemplateShare: 80, TemplatesOnly: true} + if err := r.UpsertTemplateSettings(ctx, f.org, want); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _, _ = f.pool.Exec(context.Background(), `DELETE FROM warmup_template_settings WHERE organization_id=$1`, f.org) + }) + if got, err = r.GetTemplateSettings(ctx, f.org); err != nil || got != want { + t.Fatalf("round trip: %+v %v", got, err) + } + other := newPoolLinkFixture(t) + if got, err = r.GetTemplateSettings(ctx, other.org); err != nil || got != models.DefaultWarmupTemplateSettings() { + t.Fatalf("another organization inherited the setting: %+v %v", got, err) + } +} + +// Placement is read per template from the sender's tokens and the receipts +// the recipient filed against them, split by the recipient's provider group. +func TestLiveTemplatePlacementCountsReceipts(t *testing.T) { + f, _ := lineageFixture(t) + r := NewWarmupContentRepository(f.pool) + ctx := t.Context() + segment := "fixture-" + uuid.NewString() + template := insertTemplateConversation(t, f, segment) + pick := templatePick(t, f, segment, f.sender, f.recipient) + if c, err := r.PickConversation(ctx, pick); err != nil || c == nil { + t.Fatalf("pick: %+v %v", c, err) + } + msgID := "<" + uuid.NewString() + "@fixture>" + if _, err := f.pool.Exec(ctx, `INSERT INTO warmup_tokens(task_id,sender_account_id,recipient_account_id,content_source,conversation_id,sent_message_id) + VALUES($1,$2,$3,'template',$4,$5)`, pick.TaskID, f.sender, f.recipient, template, msgID); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _, _ = f.pool.Exec(context.Background(), `DELETE FROM warmup_tokens WHERE task_id=$1`, pick.TaskID) + }) + since := time.Now().Add(-time.Hour) + all, err := r.TemplatePlacement(ctx, f.org, since) + if err != nil || all[template].Sent != 1 || all[template].Inbox != 0 { + t.Fatalf("sent-only token: %+v %v", all[template], err) + } + if _, err := f.pool.Exec(ctx, `INSERT INTO warmup_received(email_account_id,internal_id,message_id,sender_account_id,first_landing) + VALUES($1,$2,$3,$4,'inbox')`, f.recipient, uuid.New(), msgID, f.sender); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _, _ = f.pool.Exec(context.Background(), `DELETE FROM warmup_received WHERE message_id=$1`, msgID) + }) + all, err = r.TemplatePlacement(ctx, f.org, since) + if err != nil || all[template].Sent != 1 || all[template].Inbox != 1 { + t.Fatalf("receipt not counted: %+v %v", all[template], err) + } + groups, err := r.TemplatePlacementByGroup(ctx, template, f.org, since) + if err != nil || len(groups) != 1 || groups[0].Inbox != 1 || groups[0].Group == "" { + t.Fatalf("by group: %+v %v", groups, err) + } + other := newPoolLinkFixture(t) + if foreign, err := r.TemplatePlacementByGroup(ctx, template, other.org, since); err != nil || len(foreign) != 0 { + t.Fatalf("another organization read the template's placement: %+v %v", foreign, err) + } +} diff --git a/internal/tasks/content_quality_test.go b/internal/tasks/content_quality_test.go index 6d91eb2de..be95d6559 100644 --- a/internal/tasks/content_quality_test.go +++ b/internal/tasks/content_quality_test.go @@ -17,7 +17,10 @@ type qualityContentRepo struct { conversation *models.WarmupConversation pickErr error lastPick repository.WarmupContentPick + picks []repository.WarmupContentPick seeded []models.WarmupConversation + // templateSettings is what GetTemplateSettings returns. + templateSettings models.WarmupTemplateSettings } func (r *qualityContentRepo) GetGenerationSettings(context.Context) (*models.WarmupGenerationSettings, error) { @@ -26,12 +29,19 @@ func (r *qualityContentRepo) GetGenerationSettings(context.Context) (*models.War } func (r *qualityContentRepo) PickConversation(_ context.Context, pick repository.WarmupContentPick) (*models.WarmupConversation, error) { r.lastPick = pick + r.picks = append(r.picks, pick) + if pick.TemplatesOnly && r.conversation != nil && r.conversation.Source != models.WarmupContentSourceTemplate { + return nil, r.pickErr + } return r.conversation, r.pickErr } func (r *qualityContentRepo) SeedStaticConversations(_ context.Context, rows []models.WarmupConversation) error { r.seeded = rows return nil } +func (r *qualityContentRepo) GetTemplateSettings(context.Context, uuid.UUID) (models.WarmupTemplateSettings, error) { + return r.templateSettings, nil +} func TestWarmupContentPreservesRepositoryFailure(t *testing.T) { want := errors.New("temporary content repository failure") @@ -161,3 +171,45 @@ func TestSenderIdentityIsNotHeldToTheWordingRule(t *testing.T) { } } } + +func TestDrawTemplatesFollowsShareAndOnlySwitch(t *testing.T) { + share := models.WarmupTemplateSettings{TemplateShare: 50} + if got, only := drawTemplates(share, 49); !got || only { + t.Fatalf("roll under the share must draw templates: %v %v", got, only) + } + if got, _ := drawTemplates(share, 50); got { + t.Fatal("roll at the share must draw from the bank") + } + if got, _ := drawTemplates(models.WarmupTemplateSettings{TemplateShare: 0}, 0); got { + t.Fatal("zero share never draws templates") + } + if got, only := drawTemplates(models.WarmupTemplateSettings{TemplateShare: 0, TemplatesOnly: true}, 99); !got || !only { + t.Fatal("templates-only overrides the share") + } +} + +func TestWarmupContentTemplateDrawFallsBackToBankUnlessOnly(t *testing.T) { + org := uuid.New() + account := Email{ID: uuid.New(), OrganizationID: &org, Name: "Ada"} + repo := &qualityContentRepo{templateSettings: models.WarmupTemplateSettings{TemplateShare: 100}} + s := &tasksService{warmupContentRepo: repo} + // Nothing in the repo: the template draw returns nil and the bank draw runs next. + if _, err := s.pickNewWarmupContent(t.Context(), account, uuid.New(), uuid.New()); err != nil { + t.Fatalf("static fallback failed: %v", err) + } + if len(repo.picks) != 2 || !repo.picks[0].TemplatesOnly || repo.picks[1].TemplatesOnly { + t.Fatalf("expected a template draw then a bank draw, got %+v", repo.picks) + } + if repo.picks[0].OrganizationID == nil || *repo.picks[0].OrganizationID != org { + t.Fatalf("template draw lost the organization: %+v", repo.picks[0]) + } + + only := &qualityContentRepo{templateSettings: models.WarmupTemplateSettings{TemplatesOnly: true}} + s = &tasksService{warmupContentRepo: only} + if _, err := s.pickNewWarmupContent(t.Context(), account, uuid.New(), uuid.New()); !errors.Is(err, errWarmupContentUnavailable) { + t.Fatalf("templates-only with no template must skip the send, got %v", err) + } + if len(only.picks) != 1 || !only.picks[0].TemplatesOnly { + t.Fatalf("templates-only must not draw from the bank: %+v", only.picks) + } +} diff --git a/internal/tasks/warmup_content.go b/internal/tasks/warmup_content.go index d4122a7b6..9b1adc9fb 100644 --- a/internal/tasks/warmup_content.go +++ b/internal/tasks/warmup_content.go @@ -66,7 +66,29 @@ func (s *tasksService) pickNewWarmupContent(ctx context.Context, account Email, for i, c := range library { staticIDs[i] = c.ID } - conv, err := s.warmupContentRepo.PickConversation(ctx, repository.WarmupContentPick{Segment: strings.TrimSpace(account.WarmupTag), TaskID: taskID, SenderID: account.ID, RecipientID: recipientID, IncludeAI: settings.Enabled, StaticIDs: staticIDs}) + pick := repository.WarmupContentPick{Segment: strings.TrimSpace(account.WarmupTag), TaskID: taskID, SenderID: account.ID, RecipientID: recipientID, OrganizationID: account.OrganizationID, IncludeAI: settings.Enabled, StaticIDs: staticIDs} + templates, only, err := s.templateDraw(ctx, account) + if err != nil { + return warmupContent{}, err + } + if templates { + pick.TemplatesOnly = true + conv, err := s.warmupContentRepo.PickConversation(ctx, pick) + if err != nil { + return warmupContent{}, err + } + if conv != nil { + if content, ok := pickedWarmupContent(conv, account); ok { + return content, nil + } + } + if only { + // Templates-only with nothing eligible skips the send rather than substituting bank content. + return warmupContent{}, errWarmupContentUnavailable + } + pick.TemplatesOnly = false + } + conv, err := s.warmupContentRepo.PickConversation(ctx, pick) if err != nil { return warmupContent{}, err } @@ -82,6 +104,30 @@ func (s *tasksService) pickNewWarmupContent(ctx context.Context, account Email, return staticWarmupContent(library[rand.Intn(len(library))], account), nil } +// templateDraw decides whether this opening is drawn from the organization's +// own templates, and whether the bank may stand in when none is eligible. +// A failed settings read is returned so the send retries instead of silently +// drawing from the bank against a templates-only workspace. +func (s *tasksService) templateDraw(ctx context.Context, account Email) (templates, only bool, err error) { + if account.OrganizationID == nil { + return false, false, nil + } + settings, err := s.warmupContentRepo.GetTemplateSettings(ctx, *account.OrganizationID) + if err != nil { + return false, false, err + } + templates, only = drawTemplates(settings, rand.Intn(100)) + return templates, only, nil +} + +// drawTemplates applies the template mix to one roll in [0,100). +func drawTemplates(settings models.WarmupTemplateSettings, roll int) (templates, only bool) { + if settings.TemplatesOnly { + return true, true + } + return roll < settings.TemplateShare, false +} + func pickedWarmupContent(conv *models.WarmupConversation, account Email) (warmupContent, bool) { if conv.Source == models.WarmupContentSourceStatic { c, ok := resolveStaticConversation(conv.ID) @@ -90,6 +136,28 @@ func pickedWarmupContent(conv *models.WarmupConversation, account Email) (warmup if conv.ScenarioVersion == nil || conv.RenderingVersion == nil || conv.Status != models.WarmupConversationActive || !conv.ReplyEligible || !conv.LintPassed || conv.SemanticReview != "passed" { return warmupContent{}, false } + if conv.Source == models.WarmupContentSourceTemplate { + // Templates send verbatim: the stored subject and opening are the whole turn. + subject := strings.TrimSpace(conv.Subject) + body := strings.TrimSpace(conv.Description) + if subject == "" || body == "" || strings.ContainsAny(subject, "<>{}\x00\r\n") || strings.IndexByte(body, 0) >= 0 { + return warmupContent{}, false + } + if generation.ValidateWarmupWording(subject, body) != nil { + return warmupContent{}, false + } + id := conv.ID + return warmupContent{ + subject: subject, + body: body, + theme: conv.Theme, + contentSource: models.WarmupContentSourceTemplate, + conversationID: &id, + scenarioVersion: *conv.ScenarioVersion, + renderingVersion: *conv.RenderingVersion, + maxTurns: 1, + }, true + } if generation.ValidateFreshWarmup(generation.Conversation{Subject: conv.Subject, Description: conv.Description, Messages: conv.Messages}) != nil { return warmupContent{}, false } diff --git a/web/src/hooks/useRealtimeEvents.ts b/web/src/hooks/useRealtimeEvents.ts index e96649f1e..c4537157e 100644 --- a/web/src/hooks/useRealtimeEvents.ts +++ b/web/src/hooks/useRealtimeEvents.ts @@ -598,6 +598,7 @@ export function useRealtimeEvents() { crm_deal: [['crm', 'deals'], ['contacts']], crm_task: [['crm', 'tasks'], ['crm', 'deals']], warmup_routing_rule: [['analytics', 'warmup']], + warmup_template: [['analytics', 'warmup']], // Placement tests started or stopped and campaign monitors changed. placement_test: [['placement']], placement_monitor: [['placement']], diff --git a/web/src/lib/api/models/app/audit/AuditLog.ts b/web/src/lib/api/models/app/audit/AuditLog.ts index ab337176b..f16db77c2 100644 --- a/web/src/lib/api/models/app/audit/AuditLog.ts +++ b/web/src/lib/api/models/app/audit/AuditLog.ts @@ -50,6 +50,7 @@ export type AuditEntityType = | "webhook" | "integration" | "warmup_routing_rule" + | "warmup_template" | "folder" | "tag" | "category" diff --git a/web/src/lib/browse-other-lists.ts b/web/src/lib/browse-other-lists.ts index a30053ea2..22669411b 100644 --- a/web/src/lib/browse-other-lists.ts +++ b/web/src/lib/browse-other-lists.ts @@ -15,7 +15,7 @@ export const auditActionSchema = z.enum([ ]); export const auditEntitySchema = z.enum([ "campaign", "campaign_lead", "contact", "email_account", "step", "template", "email_image", - "api_key", "webhook", "integration", "warmup_routing_rule", "organization", "organization_member", "invitation", + "api_key", "webhook", "integration", "warmup_routing_rule", "warmup_template", "organization", "organization_member", "invitation", "folder", "tag", "category", "subscription", "settings", "crm_pipeline", "crm_stage", "crm_deal", "crm_task", "crm_note", "unibox", "user", ]); From 56c3195f4b7cae15ca57502232add19056af64aa Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 17:18:20 +0100 Subject: [PATCH 154/318] feat: never adopt a stored push channel this worker already closed, matching the Graph subscription id or a Gmail watch no newer than the closed one, and test the pending push report resend during the retry backoff --- internal/app/worker/wmail/push.go | 19 ++++++++++- internal/app/worker/wmail/push_test.go | 47 ++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/internal/app/worker/wmail/push.go b/internal/app/worker/wmail/push.go index 24ed87389..65d1c6399 100644 --- a/internal/app/worker/wmail/push.go +++ b/internal/app/worker/wmail/push.go @@ -45,6 +45,8 @@ type pushChannel struct { failing atomic.Bool // unsent is set while the control plane has not taken the current state. unsent atomic.Bool + // closed is the last channel this worker closed, so a stored copy a consumer never cleared is not adopted. + closed *models.MailboxPushState // imapIdle is set while the IMAP watcher holds INBOX in IDLE. imapIdle atomic.Bool imapCred *models.Service @@ -56,7 +58,7 @@ func (w *WMail) ApplyPush(data *models.AddWorkerEmailPushData) { defer w.push.mu.Unlock() w.push.want = data // A report the control plane has not taken yet is newer than the row it hands back. - if w.push.state == nil && !w.push.unsent.Load() && data != nil && data.State != nil { + if w.push.state == nil && !w.push.unsent.Load() && data != nil && data.State != nil && !closedChannel(w.push.closed, data.State) { s := *data.State w.push.state = &s } @@ -148,11 +150,26 @@ func (w *WMail) maintainPush(ctx context.Context) { } w.push.mu.Lock() w.push.unsent.Store(true) + if state != nil && (next == nil || next.Provider != state.Provider || next.SubscriptionID != state.SubscriptionID) { + w.push.closed = state + } w.push.state = next w.push.mu.Unlock() w.reportPush(next) } +// closedChannel reports a stored row describing a channel this worker already closed: the same Graph +// subscription, or a Gmail watch no newer than the closed one (a renewal only moves the expiry later). +func closedChannel(closed, row *models.MailboxPushState) bool { + if closed == nil || row == nil || closed.Provider != row.Provider { + return false + } + if closed.SubscriptionID != "" || row.SubscriptionID != "" { + return closed.SubscriptionID == row.SubscriptionID + } + return !row.ExpiresAt.After(closed.ExpiresAt) +} + // reportPush sends the channel state to the control plane; unsent stays set until it is taken. func (w *WMail) reportPush(state *models.MailboxPushState) { if err := w.onEvent(models.JobEventTypePushState, &models.JobEventPushState{UserID: w.UserID, EmailID: w.ID, State: state}); err != nil { diff --git a/internal/app/worker/wmail/push_test.go b/internal/app/worker/wmail/push_test.go index 8cc2d7e18..0b8fdcd98 100644 --- a/internal/app/worker/wmail/push_test.go +++ b/internal/app/worker/wmail/push_test.go @@ -99,3 +99,50 @@ func TestAnUnsentChannelReportOutranksTheControlPlanesRow(t *testing.T) { t.Fatalf("the retried report was not taken: unsent=%v sent=%v", w.push.unsent.Load(), sent) } } + +func TestAClosedChannelIsNotAdoptedFromAStoredRowNobodyCleared(t *testing.T) { + live := &models.MailboxPushState{Provider: models.MailboxPushGraph, SubscriptionID: "sub-1", ExpiresAt: time.Now().Add(time.Hour)} + want := &models.AddWorkerEmailPushData{GraphNotificationURL: "https://x", GraphClientState: "s", State: live} + // The bus took the closing report, but a consumer that does not know PUSH_STATE dropped it. + w := &WMail{wake: make(chan struct{}, 1)} + w.push.closed = live + w.ApplyPush(want) + if w.push.state != nil { + t.Fatal("a closed Graph subscription was adopted from the stored row") + } + other := *live + other.SubscriptionID = "sub-2" + w.ApplyPush(&models.AddWorkerEmailPushData{GraphNotificationURL: "https://x", GraphClientState: "s", State: &other}) + if w.push.state == nil || w.push.state.SubscriptionID != "sub-2" { + t.Fatal("a different subscription was refused") + } + + gmailClosed := &models.MailboxPushState{Provider: models.MailboxPushGmail, ExpiresAt: time.Now().Add(time.Hour)} + if !closedChannel(gmailClosed, &models.MailboxPushState{Provider: models.MailboxPushGmail, ExpiresAt: gmailClosed.ExpiresAt.Add(-time.Minute)}) { + t.Fatal("an older Gmail watch than the closed one was treated as live") + } + if closedChannel(gmailClosed, &models.MailboxPushState{Provider: models.MailboxPushGmail, ExpiresAt: gmailClosed.ExpiresAt.Add(time.Hour)}) { + t.Fatal("a newer Gmail watch was treated as the closed one") + } +} + +func TestAPendingReportIsResentDuringTheRetryBackoff(t *testing.T) { + var sent []*models.MailboxPushState + reports := 0 + w := &WMail{wake: make(chan struct{}, 1), onEvent: func(_ models.JobEventType, body any) error { + reports++ + sent = append(sent, body.(*models.JobEventPushState).State) + return nil + }} + // A channel was closed, its report refused, and the provider is in backoff. + w.push.retryAt = time.Now().Add(time.Hour) + w.push.unsent.Store(true) + w.maintainPush(t.Context()) + if reports != 1 || sent[0] != nil || w.push.unsent.Load() { + t.Fatalf("the pending report was not resent in backoff: reports=%d sent=%v unsent=%v", reports, sent, w.push.unsent.Load()) + } + w.maintainPush(t.Context()) + if reports != 1 { + t.Fatalf("a report already taken was sent again: %d", reports) + } +} From 5a6fbef1b4a4d114c5e22aecf5408eb31fa2d6c9 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 17:28:38 +0100 Subject: [PATCH 155/318] feat: count only client connections against max_connections in warmblyctl db load and report unsaved tracking-domain verdicts when the sweep is cut short --- cmd/warmblyctl/db.go | 7 +++++-- docs/content/docs/development/warmblyctl.mdx | 2 +- internal/app/email/tracking_domain_sweep.go | 2 +- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/cmd/warmblyctl/db.go b/cmd/warmblyctl/db.go index 86a86102b..9331a97d7 100644 --- a/cmd/warmblyctl/db.go +++ b/cmd/warmblyctl/db.go @@ -221,9 +221,12 @@ func readStatements(ctx context.Context, pool *pgxpool.Pool, limit int, load *db func printDBLoad(w io.Writer, load *dbLoad) { used := 0 for _, c := range load.Connections { - used += c.Count + // Background processes have their own slots, outside max_connections. + if c.State != "(background)" { + used += c.Count + } } - fmt.Fprintf(w, "Connections to the server, not counting this one: %d of max_connections %d\n", used, load.MaxConnections) + 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 { diff --git a/docs/content/docs/development/warmblyctl.mdx b/docs/content/docs/development/warmblyctl.mdx index c643d64b3..9ade7d878 100644 --- a/docs/content/docs/development/warmblyctl.mdx +++ b/docs/content/docs/development/warmblyctl.mdx @@ -707,7 +707,7 @@ 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`. Every Go service names its connections `warmbly-` (`warmbly-backend`, `warmbly-consumer`, `warmbly-warmblyctl`), unless the connection string sets its own `application_name`. +- **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-` (`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. diff --git a/internal/app/email/tracking_domain_sweep.go b/internal/app/email/tracking_domain_sweep.go index 21246d88a..88dc6b6a0 100644 --- a/internal/app/email/tracking_domain_sweep.go +++ b/internal/app/email/tracking_domain_sweep.go @@ -54,7 +54,7 @@ func (s *emailService) runTrackingDomainSweep(ctx context.Context, staleAfter ti var verified, revoked, failed int for _, t := range due { if ctx.Err() != nil { - return nil + break } lookupCtx, cancel := context.WithTimeout(ctx, 5*time.Second) From 68762d4f4a38054919a924192237312c471def0d Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 18:16:34 +0100 Subject: [PATCH 156/318] feat: let a mailbox import row waiting for Google or Microsoft sign-in be fixed with an app password, filling the host's known servers, refusing a non-app password for Google rows in the API and the fix form, and returning a conflict when the row left a fixable state before requeue --- docs/content/docs/api/endpoints.mdx | 2 +- docs/content/docs/api/error-codes.mdx | 3 +- docs/content/docs/guides/mailbox-import.mdx | 2 +- .../app/mailboximport/mailboximport_test.go | 34 ++++++++++++++ internal/app/mailboximport/service.go | 46 +++++++++++++++++-- .../repository/mailbox_import_live_test.go | 4 +- internal/repository/pg_mailbox_import.go | 16 ++++--- .../app/emails/import/RowFixEditor.tsx | 19 ++++++-- 8 files changed, 106 insertions(+), 20 deletions(-) diff --git a/docs/content/docs/api/endpoints.mdx b/docs/content/docs/api/endpoints.mdx index f4b4d2a71..57c684087 100644 --- a/docs/content/docs/api/endpoints.mdx +++ b/docs/content/docs/api/endpoints.mdx @@ -627,7 +627,7 @@ Alongside them, `api_url` is this API's own public base (for a copyable example - `GET /emails/imports`: the workspace's imports, newest first - `GET /emails/imports/:id`: one import with its counts and its failures grouped by `cause` - `GET /emails/imports/:id/rows`: an import's rows by line, filtered by `status` (comma-separated) and `cause` - - `PATCH /emails/imports/:id/rows/:line`: correct one failed row (`password`, `app_password`, `username`, `smtp`, `imap`) and queue it again + - `PATCH /emails/imports/:id/rows/:line`: correct one failed row, or give a row waiting for sign-in a password instead (`password`, `app_password`, `username`, `smtp`, `imap`), and queue it again - `POST /emails/imports/:id/retry`: requeue failed rows, all of them or those with one `cause` or the listed `lines`, optionally with one new `password` for all - `POST /emails/imports/:id/cancel`: stop the rows not yet started; rows already connecting finish - `POST /emails/imports/:id/dismiss`: hide the import from `GET /emails/imports` for the workspace, stopping it first when it is still running. Its rows and history stay, and `GET /emails/imports/:id` still reads it. Answers `204`; a repeat changes nothing diff --git a/docs/content/docs/api/error-codes.mdx b/docs/content/docs/api/error-codes.mdx index effbe7806..80b41dd4c 100644 --- a/docs/content/docs/api/error-codes.mdx +++ b/docs/content/docs/api/error-codes.mdx @@ -388,8 +388,9 @@ The [mailbox import](/guides/mailbox-import/) routes (`/emails/imports`) answer | `mailbox_import_too_large` | 400 | More than 5,000 mailboxes, a file over 10 MB, a pasted list over 2 MB, or a body that is not multipart form data. Split the file and import the rest separately | | `mailbox_import_no_email_column` | 400 | `POST /emails/imports` with a mapping in which no column is `email` | | `mailbox_import_row_incomplete` | 400 | `PATCH /emails/imports/:id/rows/:line` left the row without an SMTP and IMAP server or without a password. The `message` says which | +| `google_app_password_required` | 400 | `PATCH /emails/imports/:id/rows/:line` gave a Google row a password that is not a 16-letter app password. Google refuses the account password over IMAP and SMTP | | `invalid_cursor` | 400 | `GET /emails/imports` or `GET /emails/imports/:id/rows` was given a `cursor` this API did not issue. Start again without one | -| `mailbox_import_row_not_failed` | 409 | Only a row that did not connect can be fixed; this one is queued, running, connected, updated, skipped, cancelled or waiting for sign-in | +| `mailbox_import_row_not_failed` | 409 | Only a row that did not connect or is waiting for sign-in can be fixed; this one is queued, running, connected, updated, skipped, cancelled, or still being authorized by its inbox vendor | | `mailbox_import_credentials_expired` | 409 | The row's credentials were deleted 7 days after the import finished, so it cannot be retried. Import it again | | `mailbox_import_nothing_to_retry` | 409 | `POST /emails/imports/:id/retry` matched no failed row that still holds its credentials | diff --git a/docs/content/docs/guides/mailbox-import.mdx b/docs/content/docs/guides/mailbox-import.mdx index 1d8210c2d..d142afcc7 100644 --- a/docs/content/docs/guides/mailbox-import.mdx +++ b/docs/content/docs/guides/mailbox-import.mdx @@ -157,7 +157,7 @@ Each mailbox is labelled with where it is hosted and how it signs in. The [API]( A Google row whose password is not a 16-letter app password is flagged in the preview before anything is tried: Google refuses the account password over IMAP and SMTP. On an instance that connects new Gmail mailboxes with Google sign-in (`gmail_oauth_connect` in `GET /auth/config`), such a row waits for sign-in instead, like a Microsoft row. -Google rows waiting for Google sign-in offer a **Sign in** action only on deployments where [Google mailbox OAuth is enabled](/development/configuration/#google-sign-in-per-dashboard-deployment). Otherwise use an app password or an admin grant. Microsoft sign-in is unaffected by that flag. +Google rows waiting for Google sign-in offer a **Sign in** action only on deployments where [Google mailbox OAuth is enabled](/development/configuration/#google-sign-in-per-dashboard-deployment). Otherwise use **Fix** on the row to give it a 16-letter app password, which connects it over IMAP and SMTP with Google's servers, or use an admin grant. Microsoft sign-in is unaffected by that flag. ### Microsoft diff --git a/internal/app/mailboximport/mailboximport_test.go b/internal/app/mailboximport/mailboximport_test.go index d93e6750d..af5ee4e77 100644 --- a/internal/app/mailboximport/mailboximport_test.go +++ b/internal/app/mailboximport/mailboximport_test.go @@ -259,6 +259,40 @@ func TestApplyFixSetsBothLegs(t *testing.T) { } } +func TestApplyFixTurnsSigninRowIntoPasswordConnect(t *testing.T) { + p := payload{MailHost: string(mailhost.GoogleWorkspace), Signin: true, AuthMethod: models.MailAuthOAuth} + pw := "abcd efgh ijkl mnop" + applyFix(&p, "[EMAIL]", models.MailboxImportRowFix{AppPassword: &pw}) + if p.Signin || p.AuthMethod != "app_password" { + t.Fatalf("signin = %v auth = %q", p.Signin, p.AuthMethod) + } + if p.SMTP.Host != "smtp.gmail.com" || p.SMTP.Port != 587 || p.IMAP.Host != "imap.gmail.com" || p.IMAP.Port != 993 { + t.Fatalf("legs = %+v %+v", p.SMTP, p.IMAP) + } + if p.SMTP.Password != "abcdefghijklmnop" || p.IMAP.Username != "[EMAIL]" { + t.Fatalf("credentials = %+v %+v", p.SMTP, p.IMAP) + } +} + +func TestFixableRows(t *testing.T) { + cases := []struct { + status, cause string + want bool + }{ + {models.ImportRowFailed, "google_bad_credentials", true}, + {models.ImportRowNeedsSignin, causeGoogleSignin, true}, + {models.ImportRowNeedsSignin, causeMicrosoftSignin, true}, + {models.ImportRowNeedsSignin, causeVendorAuthorizing, false}, + {models.ImportRowConnected, "", false}, + {models.ImportRowQueued, "", false}, + } + for _, c := range cases { + if got := fixable(&models.MailboxImportRow{Status: c.status, Cause: c.cause}); got != c.want { + t.Errorf("%s/%s fixable = %v, want %v", c.status, c.cause, got, c.want) + } + } +} + func TestCSVSafe(t *testing.T) { for _, v := range []string{"=HYPERLINK(1)", "+1", "-2", "@x"} { if got := csvSafe(v); got[0] != '\'' { diff --git a/internal/app/mailboximport/service.go b/internal/app/mailboximport/service.go index d86726710..79f868784 100644 --- a/internal/app/mailboximport/service.go +++ b/internal/app/mailboximport/service.go @@ -695,8 +695,8 @@ func (s *Service) FixRow(ctx context.Context, orgID, userID, id uuid.UUID, line if row == nil { return nil, errx.ErrNotFound } - if row.Status != models.ImportRowFailed { - return nil, errx.NewWithIdentifier(errx.Conflict, "mailbox_import_row_not_failed", "Only a row that did not connect can be fixed.") + if !fixable(row) { + return nil, errNotFixable } if sealed == "" { return nil, errx.NewWithIdentifier(errx.Conflict, "mailbox_import_credentials_expired", @@ -719,15 +719,23 @@ func (s *Service) FixRow(ctx context.Context, orgID, userID, id uuid.UUID, line if (p.SMTP.Password == "" || p.IMAP.Password == "") && p.VendorConnectionID == nil { return nil, errx.NewWithIdentifier(errx.BadRequest, "mailbox_import_row_incomplete", "Add a password for this row.") } + if mailhost.Host(p.MailHost).Google() && p.GrantID == nil && p.SMTP.Password != "" && !mailhost.LooksLikeGoogleAppPassword(p.SMTP.Password) { + return nil, errx.NewWithIdentifier(errx.BadRequest, "google_app_password_required", + "Google needs a 16-letter app password here, not the account password.") + } raw, _ := json.Marshal(p) resealed, err := ciph.Encrypt(ctx, string(raw)) if err != nil { errs.CaptureException(err) return nil, errx.InternalError() } - if err := s.repo.Requeue(ctx, id, line, resealed); err != nil { + queued, err := s.repo.Requeue(ctx, id, line, resealed) + if err != nil { return nil, errx.InternalError() } + if !queued { + return nil, errNotFixable + } if err := s.repo.Reopen(ctx, orgID, id); err != nil { return nil, errx.InternalError() } @@ -740,6 +748,15 @@ func (s *Service) FixRow(ctx context.Context, orgID, userID, id uuid.UUID, line return row, nil } +var errNotFixable = errx.NewWithIdentifier(errx.Conflict, "mailbox_import_row_not_failed", + "Only a row that did not connect or is waiting for sign-in can be fixed.") + +// fixable is a row that failed or waits on a sign-in; a vendor still authorizing it connects on its own. +func fixable(row *models.MailboxImportRow) bool { + return row.Status == models.ImportRowFailed || + (row.Status == models.ImportRowNeedsSignin && row.Cause != repository.ParkedVendorCause) +} + func applyFix(p *payload, email string, fix models.MailboxImportRowFix) { if p.SMTP == nil { p.SMTP = &models.Service{Username: email} @@ -789,6 +806,11 @@ func applyFix(p *payload, email string, fix models.MailboxImportRowFix) { } leg(p.SMTP, fix.SMTP, "smtp") leg(p.IMAP, fix.IMAP, "imap") + // A sign-in row carries no servers; a password connect uses its host's known ones. + if known := mailhost.SettingsFor(host); known != nil { + fillLeg(p.SMTP, known.SMTP) + fillLeg(p.IMAP, known.IMAP) + } if p.SMTP.Port == 0 { p.SMTP.Port = 587 } @@ -798,10 +820,26 @@ func applyFix(p *payload, email string, fix models.MailboxImportRowFix) { if fix.SMTP != nil && fix.SMTP.Host != nil { p.MailHost = string(mailhost.Refine(mailhost.FromServer(p.SMTP.Host), domainOf(email))) p.AuthMethod = mailhost.AuthMethodFor(mailhost.Host(p.MailHost), "") + } else if p.Signin || p.AuthMethod == models.MailAuthOAuth { + p.AuthMethod = mailhost.AuthMethodFor(host, "") } p.Signin = false } +// fillLeg gives a leg with no server the host's known one. +func fillLeg(svc *models.Service, e mailhost.Endpoint) { + if svc.Host != "" || e.Host == "" { + return + } + svc.Host = e.Host + if svc.Port == 0 { + svc.Port = e.Port + } + if svc.Security == "" { + svc.Security = e.Security + } +} + // Retry queues failed rows again, optionally with one new password for all of them. func (s *Service) Retry(ctx context.Context, orgID, userID, id uuid.UUID, req models.MailboxImportRetry) (*models.MailboxImport, *errx.Error) { if _, xerr := s.Get(ctx, orgID, id); xerr != nil { @@ -839,7 +877,7 @@ func (s *Service) Retry(ctx context.Context, orgID, userID, id uuid.UUID, req mo return nil, errx.InternalError() } } - if err := s.repo.Requeue(ctx, id, w.Line, resealed); err != nil { + if _, err := s.repo.Requeue(ctx, id, w.Line, resealed); err != nil { return nil, errx.InternalError() } } diff --git a/internal/repository/mailbox_import_live_test.go b/internal/repository/mailbox_import_live_test.go index 878dbb91b..3e8bba2ab 100644 --- a/internal/repository/mailbox_import_live_test.go +++ b/internal/repository/mailbox_import_live_test.go @@ -188,7 +188,9 @@ func TestLiveMailboxImportLifecycle(t *testing.T) { if other, _ := repo.Retryable(ctx, f.other, id, "", nil); len(other) != 0 { t.Fatal("another workspace saw retryable rows") } - mustImport(t, repo.Requeue(ctx, id, 3, "resealed")) + if queued, err := repo.Requeue(ctx, id, 3, "resealed"); err != nil || !queued { + t.Fatalf("requeue = %v, %v", queued, err) + } mustImport(t, repo.Reopen(ctx, f.org, id)) row, payload, err := repo.GetRow(ctx, f.org, id, 3) if err != nil || row.Status != models.ImportRowQueued || payload != "resealed" || row.Cause != "" { diff --git a/internal/repository/pg_mailbox_import.go b/internal/repository/pg_mailbox_import.go index 0a414a3f2..d38fadacf 100644 --- a/internal/repository/pg_mailbox_import.go +++ b/internal/repository/pg_mailbox_import.go @@ -78,8 +78,8 @@ type MailboxImportRepository interface { GetRow(ctx context.Context, orgID, id uuid.UUID, line int) (*models.MailboxImportRow, string, error) // Retryable lists failed rows that still hold credentials, optionally one cause or named lines. Retryable(ctx context.Context, orgID, id uuid.UUID, cause string, lines []int) ([]ImportWorkRow, error) - // Requeue puts one row back in the queue; an empty payload keeps the stored one. - Requeue(ctx context.Context, id uuid.UUID, line int, payload string) error + // Requeue puts one failed or sign-in row back in the queue; an empty payload keeps the stored one. + Requeue(ctx context.Context, id uuid.UUID, line int, payload string) (bool, error) // Reopen marks a finished import running again after a retry. Reopen(ctx context.Context, orgID, id uuid.UUID) error Cancel(ctx context.Context, orgID, id uuid.UUID) error @@ -415,17 +415,19 @@ func (r *mailboxImportRepository) Retryable(ctx context.Context, orgID, id uuid. return out, rows.Err() } -func (r *mailboxImportRepository) Requeue(ctx context.Context, id uuid.UUID, line int, payload string) error { +func (r *mailboxImportRepository) Requeue(ctx context.Context, id uuid.UUID, line int, payload string) (bool, error) { query := ` UPDATE mailbox_import_rows SET status = 'queued', lease_until = NULL, attempts = 0, code = '', cause = '', message = '', payload = CASE WHEN $3 = '' THEN payload ELSE $3 END, updated_at = now() - WHERE import_id = $1 AND line = $2 AND status = 'failed'` - if _, err := r.DB.Exec(ctx, query, id, line, payload); err != nil { + WHERE import_id = $1 AND line = $2 + AND (status = 'failed' OR (status = 'needs_signin' AND cause <> '` + ParkedVendorCause + `'))` + tag, err := r.DB.Exec(ctx, query, id, line, payload) + if err != nil { db.CaptureError(err, query, nil, "exec") - return err + return false, err } - return nil + return tag.RowsAffected() > 0, nil } func (r *mailboxImportRepository) Reopen(ctx context.Context, orgID, id uuid.UUID) error { diff --git a/web/src/components/app/emails/import/RowFixEditor.tsx b/web/src/components/app/emails/import/RowFixEditor.tsx index 4d6e9734c..8d3f45059 100644 --- a/web/src/components/app/emails/import/RowFixEditor.tsx +++ b/web/src/components/app/emails/import/RowFixEditor.tsx @@ -1,4 +1,4 @@ -// RowFixEditor: a failed row's new password or servers, saved with PATCH +// RowFixEditor: a failed or sign-in row's new password or servers, saved with PATCH // /emails/imports/:id/rows/:line, which re-seals the row and queues it again. import React from "react"; import { AnimatePresence, motion } from "framer-motion"; @@ -18,6 +18,9 @@ import { cn } from "@/lib/utils"; // Hosts that take only an app password over IMAP and SMTP. const APP_PASSWORD_HOSTS = new Set(["google_workspace", "gmail", "yahoo", "aol", "icloud", "fastmail", "yandex"]); +// Mirrors mailhost.LooksLikeGoogleAppPassword: 16 letters, spaces ignored. +const looksLikeGoogleAppPassword = (s: string) => /^[a-z]{16}$/i.test(s.replace(/\s/g, "")); + interface LegDraft { host: string; port: number; @@ -62,9 +65,11 @@ export default function RowFixEditor({ if (smtpFix) body.smtp = smtpFix; if (imapFix) body.imap = imapFix; const empty = Object.keys(body).length === 0; + const googleRow = (row.mail_host === "google_workspace" || row.mail_host === "gmail") && !smtp.host.trim(); + const notAppPassword = googleRow && !!secret && !looksLikeGoogleAppPassword(secret); async function save() { - if (empty || fix.isPending) return; + if (empty || notAppPassword || fix.isPending) return; try { await fix.mutateAsync({ line: row.line, fix: body }); toast.success(`${row.email || `Line ${row.line}`} is queued again`); @@ -154,8 +159,12 @@ export default function RowFixEditor({
    - - {empty ? "Enter a new password or change a server to retry this row." : "The row is checked again right after saving."} + + {notAppPassword + ? "Google needs the 16-letter app password, not the account password." + : empty + ? "Enter a new password or change a server to retry this row." + : "The row is checked again right after saving."} )} + {passwordCause && canRetry && notAppPassword && ( +

    Google needs the 16-letter app password, not the account password.

    + )}
    ); } diff --git a/web/src/components/app/emails/import/importFields.ts b/web/src/components/app/emails/import/importFields.ts index 6c373f143..90c6ecc85 100644 --- a/web/src/components/app/emails/import/importFields.ts +++ b/web/src/components/app/emails/import/importFields.ts @@ -159,6 +159,16 @@ export function isSigninCause(cause: string): boolean { return SIGNIN_CAUSE.test(cause); } +/** Mirrors mailhost.LooksLikeGoogleAppPassword: 16 letters, ends trimmed, spaces ignored. */ +export function looksLikeGoogleAppPassword(s: string): boolean { + return /^[a-z]{16}$/i.test(s.trim().replace(/ /g, "")); +} + +/** Mirrors mailhost.FromServer for Google's servers. */ +export function isGoogleServer(host: string): boolean { + return /(^|\.)(google|gmail|googlemail)\.com\.?$/i.test(host.trim()); +} + /** "3, 7, 9 and 12 more" for a list of line numbers. */ export function linesText(lines: number[], total: number, shown = 6): string { const head = lines.slice(0, shown).join(", "); From 71fb768eca5774e166fcaa3fafe523b6481603d0 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 20:02:09 +0100 Subject: [PATCH 167/318] feat: isolate AWS origin TLS probe and cleanup credentials with phase policies and failure-gated finalization --- .../scripts/aws-origin-tls-workflow.test.sh | 31 +++-- .github/scripts/aws-origin-tls.cjs | 21 ++-- .github/scripts/aws-origin-tls.test.cjs | 113 +++++++++++++----- .github/workflows/probe-origin-tls-aws.yml | 16 ++- deploy/terraform/aws/runtime/README.md | 15 ++- 5 files changed, 150 insertions(+), 46 deletions(-) diff --git a/.github/scripts/aws-origin-tls-workflow.test.sh b/.github/scripts/aws-origin-tls-workflow.test.sh index ddf18fb41..e6e97a2c2 100644 --- a/.github/scripts/aws-origin-tls-workflow.test.sh +++ b/.github/scripts/aws-origin-tls-workflow.test.sh @@ -16,17 +16,30 @@ raise 'bounded job required' unless job['timeout-minutes'] == 25 raise 'only contents and OIDC permissions needed' unless job['permissions'] == {'contents'=>'read', 'id-token'=>'write'} steps = job.fetch('steps') credentials = steps.select { |s| s['uses'] == 'aws-actions/configure-aws-credentials@v4' } -raise 'existing role with restrictive session policy required' unless credentials.length == 1 && credentials[0]['with'] == { - 'role-to-assume'=>'${{ vars.AWS_TERRAFORM_APPLY_ROLE_ARN }}', 'aws-region'=>'us-east-1', - 'inline-session-policy'=>'${{ steps.scope.outputs.policy }}' -} +raise 'separate probe and cleanup credentials required' unless credentials.map { |s| s['id'] } == ['credentials', 'cleanup_credentials'] +['probe', 'cleanup'].each_with_index do |phase, i| + raise 'existing role with phase policy and no credential reuse required' unless credentials[i]['with'] == { + 'role-to-assume'=>'${{ vars.AWS_TERRAFORM_APPLY_ROLE_ARN }}', 'aws-region'=>'us-east-1', + 'unset-current-credentials'=>true, + 'inline-session-policy'=>"${{ steps.scope.outputs.#{phase}_policy }}" + } +end scope = steps.index { |s| s['run'] == 'node .github/scripts/aws-origin-tls.cjs session-policy' } -raise 'source gate must precede credentials' unless scope && scope < steps.index(credentials[0]) +raise 'source gate must precede credentials' unless scope && steps[scope]['id'] == 'scope' && scope < steps.index(credentials[0]) +raise 'probe credentials require the successful source gate' if credentials[0]['if'] probe = steps.find { |s| s['run'] == 'node .github/scripts/aws-origin-tls.cjs probe' } -raise 'probe timeout required' unless probe && probe['timeout-minutes'] == 10 +raise 'probe requires its successful credentials and timeout' unless probe && probe['timeout-minutes'] == 10 && + probe['if'] == "success() && steps.credentials.outcome == 'success'" +raise 'probe must run once immediately after its credentials' unless steps.count { |s| s['run'] == probe['run'] } == 1 && + steps.index(probe) == steps.index(credentials[0]) + 1 +raise 'cleanup credentials must follow probe failure or credential failure after a successful source gate' unless + credentials[1]['if'] == "always() && steps.scope.outcome == 'success'" && credentials[1]['timeout-minutes'] == 2 && + steps.index(credentials[1]) == steps.index(probe) + 1 cleanup = steps.last -raise 'bounded cleanup must always follow credentials, including probe failure' unless cleanup['run'] == 'node .github/scripts/aws-origin-tls.cjs finish' && - cleanup['if'] == "always() && steps.credentials.outcome == 'success'" && cleanup['timeout-minutes'] == 8 +raise 'bounded finalizer must require successful cleanup credentials with no earlier-session fallback' unless + cleanup['run'] == 'node .github/scripts/aws-origin-tls.cjs finish' && + cleanup['if'] == "always() && steps.cleanup_credentials.outcome == 'success'" && cleanup['timeout-minutes'] == 8 && + steps.index(cleanup) == steps.index(credentials[1]) + 1 raise 'no secret inheritance, bypasses or public artifacts' if workflow.to_s.match?(/secrets|upload-artifact|AWS_TERRAFORM_ENABLED|AWS_TLS_RECOVERY|terraform apply|deploy-aws/) jobs.each_value do |j| raise 'failures must stop execution' if j['continue-on-error'] @@ -35,5 +48,5 @@ jobs.each_value do |j| raise 'checkout credentials must not persist' if s['uses'] == 'actions/checkout@v4' && s.dig('with', 'persist-credentials') != false end end -puts 'Origin TLS workflow source gate, ordinary environment, queue and unconditional bounded cleanup checks passed' +puts 'Origin TLS workflow source gate, phase credentials, failure gating, ordinary environment and bounded cleanup checks passed' RUBY diff --git a/.github/scripts/aws-origin-tls.cjs b/.github/scripts/aws-origin-tls.cjs index 94ab5a6b2..cb0a6b0ae 100644 --- a/.github/scripts/aws-origin-tls.cjs +++ b/.github/scripts/aws-origin-tls.cjs @@ -33,18 +33,24 @@ function configuration(env) { family: `warmbly-production-origin-tls-${env.GITHUB_RUN_ID}`, startedBy: `origin-tls-${env.GITHUB_RUN_ID}` }; } -function sessionPolicy(config) { - return { Version: "2012-10-17", Statement: [ +function sessionPolicy(config, phase) { + requireThat(phase === "probe" || phase === "cleanup", "Explicit diagnostic credential phase required"); + const statements = phase === "probe" ? [ { Effect: "Allow", Action: ["elasticloadbalancing:DescribeLoadBalancers", "elasticloadbalancing:DescribeListeners", - "ec2:DescribeNetworkInterfaces", "ec2:DescribeSubnets", "ecs:RegisterTaskDefinition", "ecs:ListTaskDefinitions", "ecs:ListTasks"], Resource: "*" }, + "ec2:DescribeNetworkInterfaces", "ec2:DescribeSubnets", "ecs:RegisterTaskDefinition"], Resource: "*" }, { Effect: "Allow", Action: "ecs:DescribeServices", Resource: SERVICE }, { Effect: "Allow", Action: "ecs:RunTask", Resource: `${ECS}:task-definition/${config.family}:*`, Condition: { ArnEquals: { "ecs:cluster": CLUSTER } } }, - { Effect: "Allow", Action: "ecs:DeregisterTaskDefinition", Resource: "*" }, - { Effect: "Allow", Action: ["ecs:DescribeTasks", "ecs:StopTask"], Resource: `${ECS}:task/warmbly-production/*` }, + { Effect: "Allow", Action: "ecs:DescribeTasks", Resource: `${ECS}:task/warmbly-production/*` }, { Effect: "Allow", Action: "iam:PassRole", Resource: EXECUTION, Condition: { StringEquals: { "iam:PassedToService": "ecs-tasks.amazonaws.com" } } }, + ] : [ + { Effect: "Allow", Action: ["ecs:ListTaskDefinitions", "ecs:ListTasks"], Resource: "*" }, + { Effect: "Allow", Action: "ecs:DeregisterTaskDefinition", Resource: "*" }, + { Effect: "Allow", Action: ["ecs:DescribeTasks", "ecs:StopTask"], Resource: `${ECS}:task/warmbly-production/*` }, { Effect: "Allow", Action: "logs:GetLogEvents", Resource: `arn:aws:logs:${REGION}:${ACCOUNT}:log-group:${LOG}:log-stream:origin-tls-${config.run}/*` }, + ]; + return { Version: "2012-10-17", Statement: [...statements, { Effect: "Allow", Action: "s3:PutObject", Resource: `arn:aws:s3:::${BUCKET}/${PREFIX}/${config.run}/1/*`, Condition: { StringEquals: { "s3:x-amz-server-side-encryption": "AES256", "s3:ResourceAccount": ACCOUNT }, Bool: { "aws:SecureTransport": "true" }, Null: { "s3:if-none-match": "false" } } }, @@ -290,8 +296,9 @@ if (require.main === module) { const config = configuration(process.env); const source = spawnSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }); requireThat(source.status === 0 && source.stdout.trim() === config.source, "Checkout must match main workflow source"); - if (process.argv[2] === "session-policy") appendFileSync(process.env.GITHUB_OUTPUT, `policy=${canonical(sessionPolicy(config))}\n`); - else if (process.argv[2] === "probe") await execute(awsCLI, config); + if (process.argv[2] === "session-policy") { + for (const phase of ["probe", "cleanup"]) appendFileSync(process.env.GITHUB_OUTPUT, `${phase}_policy=${canonical(sessionPolicy(config, phase))}\n`); + } else if (process.argv[2] === "probe") await execute(awsCLI, config); else if (process.argv[2] === "finish") await finish(awsCLI, config); else throw new Error("Unknown diagnostic command"); }).catch((error) => { console.error(`Origin TLS diagnostic stopped: ${error.message}`); process.exitCode = 1; }); diff --git a/.github/scripts/aws-origin-tls.test.cjs b/.github/scripts/aws-origin-tls.test.cjs index fcdf59c84..2dd487017 100644 --- a/.github/scripts/aws-origin-tls.test.cjs +++ b/.github/scripts/aws-origin-tls.test.cjs @@ -1,5 +1,6 @@ const { test } = require("node:test"); const assert = require("node:assert/strict"); +const { spawnSync } = require("node:child_process"); const { mkdtempSync, readFileSync, rmSync, writeFileSync } = require("node:fs"); const { tmpdir } = require("node:os"); const { join } = require("node:path"); @@ -92,38 +93,96 @@ test("only fresh main dispatches under normal infrastructure configuration are a } }); -test("session policy admits only diagnostics, bound roles, cluster and encrypted conditional private archives", () => { +test("each credential phase grants exactly its required operations and resource scopes", () => { const config = configuration(env()); - const policy = sessionPolicy(config); - assert.ok(JSON.stringify(policy).length < 2048); - const all = policy.Statement.flatMap((s) => s.Action); - for (const forbidden of ["ecs:UpdateService", "ecs:ExecuteCommand", "secretsmanager:GetSecretValue", "ssm:GetParameters", - "iam:PutRolePolicy", "elasticloadbalancing:ModifyListener", "ec2:AuthorizeSecurityGroupIngress"]) assert.ok(!all.includes(forbidden)); - assert.deepEqual(policy.Statement.find((s) => s.Action === "iam:PassRole").Resource, EXECUTION); - assert.equal(policy.Statement.find((s) => s.Action === "ecs:RunTask").Condition.ArnEquals["ecs:cluster"], CLUSTER); - const put = policy.Statement.find((s) => s.Action === "s3:PutObject"); - assert.ok(put.Resource.endsWith(`/origin-tls/${config.run}/1/*`)); - assert.equal(put.Condition.StringEquals["s3:x-amz-server-side-encryption"], "AES256"); - assert.equal(put.Condition.Null["s3:if-none-match"], "false"); + const allow = (Action, Resource, Condition) => ({ Effect: "Allow", Action, Resource, ...(Condition ? { Condition } : {}) }); + const archive = allow("s3:PutObject", `arn:aws:s3:::${BUCKET}/warmbly/production/diagnostics/origin-tls/${config.run}/1/*`, { + StringEquals: { "s3:x-amz-server-side-encryption": "AES256", "s3:ResourceAccount": ACCOUNT }, + Bool: { "aws:SecureTransport": "true" }, Null: { "s3:if-none-match": "false" }, + }); + const expected = { + probe: [ + allow(["elasticloadbalancing:DescribeLoadBalancers", "elasticloadbalancing:DescribeListeners", + "ec2:DescribeNetworkInterfaces", "ec2:DescribeSubnets", "ecs:RegisterTaskDefinition"], "*"), + allow("ecs:DescribeServices", SERVICE), + allow("ecs:RunTask", `${ECS}:task-definition/${config.family}:*`, { ArnEquals: { "ecs:cluster": CLUSTER } }), + allow("ecs:DescribeTasks", `${ECS}:task/warmbly-production/*`), + allow("iam:PassRole", EXECUTION, { StringEquals: { "iam:PassedToService": "ecs-tasks.amazonaws.com" } }), + archive, + ], + cleanup: [ + allow(["ecs:ListTaskDefinitions", "ecs:ListTasks"], "*"), + allow("ecs:DeregisterTaskDefinition", "*"), + allow(["ecs:DescribeTasks", "ecs:StopTask"], `${ECS}:task/warmbly-production/*`), + allow("logs:GetLogEvents", `arn:aws:logs:us-east-1:${ACCOUNT}:log-group:${LOG}:log-stream:origin-tls-${config.run}/*`), + archive, + ], + }; + for (const phase of ["probe", "cleanup"]) { + const policy = sessionPolicy(config, phase); + assert.deepEqual(policy, { Version: "2012-10-17", Statement: expected[phase] }); + assert.ok(JSON.stringify(policy).length < 2048); + } + for (const phase of [undefined, "", "finish", "all"]) assert.throws(() => sessionPolicy(config, phase), /credential phase/); }); -test("diagnostic actions use provider-supported resource scopes", () => { - const config = configuration(env()); - const statements = sessionPolicy(config).Statement; - const granting = (action) => statements.filter((s) => [s.Action].flat().includes(action)); - assert.deepEqual(granting("ecs:DeregisterTaskDefinition"), [ - { Effect: "Allow", Action: "ecs:DeregisterTaskDefinition", Resource: "*" }, - ]); - assert.deepEqual(granting("ecs:RunTask"), [ - { Effect: "Allow", Action: "ecs:RunTask", Resource: `${ECS}:task-definition/${config.family}:*`, - Condition: { ArnEquals: { "ecs:cluster": CLUSTER } } }, - ]); - assert.deepEqual(granting("logs:GetLogEvents"), [ - { Effect: "Allow", Action: "logs:GetLogEvents", - Resource: `arn:aws:logs:us-east-1:${ACCOUNT}:log-group:${LOG}:log-stream:origin-tls-${config.run}/*` }, - ]); +test("the source gate emits distinct phase policies and refuses an unverified checkout", (t) => { + const f = fixture(t); + const revision = spawnSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }); + assert.equal(revision.status, 0); + const output = join(f.config.work, "output"); + const childEnv = { ...process.env, ...env(), WORK: f.config.work, GITHUB_OUTPUT: output, GITHUB_SHA: revision.stdout.trim() }; + const run = () => spawnSync(process.execPath, [join(__dirname, "aws-origin-tls.cjs"), "session-policy"], { env: childEnv, encoding: "utf8" }); + assert.equal(run().status, 0); + const policies = Object.fromEntries(readFileSync(output, "utf8").trim().split("\n").map((line) => { + const equals = line.indexOf("="); + return [line.slice(0, equals), JSON.parse(line.slice(equals + 1))]; + })); + assert.deepEqual(policies, { probe_policy: sessionPolicy(f.config, "probe"), cleanup_policy: sessionPolicy(f.config, "cleanup") }); + writeFileSync(output, ""); + childEnv.GITHUB_SHA = "0".repeat(40); + assert.equal(run().status, 1); + assert.equal(readFileSync(output, "utf8"), ""); }); +function phaseAWS(f, phase) { + const actions = sessionPolicy(f.config, phase).Statement.flatMap((s) => s.Action); + return (service, action, args) => { + const prefix = { elbv2: "elasticloadbalancing", s3api: "s3" }[service] || service; + const name = action.split("-").map((word) => word[0].toUpperCase() + word.slice(1)).join(""); + if (service !== "sts" || action !== "get-caller-identity") assert.ok(actions.includes(`${prefix}:${name}`), `${phase} must permit ${service} ${action}`); + return f.aws(service, action, args); + }; +} + +for (const failure of [null, "register-task-definition", "run-task", "describe-tasks"]) { + test(`phase sessions support ${failure || "successful probe"} cleanup with one registration and launch at most`, async (t) => { + let lost = false; + const f = fixture(t, (action) => { + if (action === failure && !lost) { lost = true; throw new Error("Fixture lost response"); } + }); + const oldSummary = process.env.GITHUB_STEP_SUMMARY; + process.env.GITHUB_STEP_SUMMARY = join(f.config.work, "summary"); + t.after(() => { if (oldSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY; else process.env.GITHUB_STEP_SUMMARY = oldSummary; }); + const probeRun = execute(phaseAWS(f, "probe"), f.config, async () => {}); + if (failure) await assert.rejects(probeRun, /lost response/); + else await probeRun; + const boundary = f.calls.length; + if (failure && failure !== "register-task-definition") f.state.lastStatus = "RUNNING"; + const cleanup = finish(phaseAWS(f, "cleanup"), f.config, async () => {}); + if (failure) await assert.rejects(cleanup, /incomplete/); + else await cleanup; + assert.ok(!f.calls.slice(0, boundary).some((c) => c.action === "deregister-task-definition")); + assert.ok(!f.calls.slice(boundary).some((c) => ["register-task-definition", "run-task"].includes(c.action))); + assert.equal(f.calls.filter((c) => c.action === "register-task-definition").length, 1); + assert.equal(f.calls.filter((c) => c.action === "run-task").length, failure === "register-task-definition" ? 0 : 1); + assert.equal(f.evidence().cleanup.deregistered, true); + assert.equal(f.evidence().success, !failure); + assert.equal(f.calls.at(-1).action, "put-object"); + assert.deepEqual(JSON.parse(readFileSync(join(f.config.work, "result.json"))), f.evidence()); + }); +} + test("fresh definition contains only the official digest, hard-bounded TLS client and existing execution/log facilities", () => { const task = definition(configuration(env()), ["10.42.0.85", "10.42.1.12"]); assert.deepEqual(Object.keys(task).sort(), ["family", "networkMode", "requiresCompatibilities", "cpu", "memory", "executionRoleArn", "runtimePlatform", "containerDefinitions"].sort()); diff --git a/.github/workflows/probe-origin-tls-aws.yml b/.github/workflows/probe-origin-tls-aws.yml index 269934a0d..c48f5d026 100644 --- a/.github/workflows/probe-origin-tls-aws.yml +++ b/.github/workflows/probe-origin-tls-aws.yml @@ -58,14 +58,26 @@ jobs: with: role-to-assume: ${{ vars.AWS_TERRAFORM_APPLY_ROLE_ARN }} aws-region: us-east-1 - inline-session-policy: ${{ steps.scope.outputs.policy }} + unset-current-credentials: true + inline-session-policy: ${{ steps.scope.outputs.probe_policy }} - name: Run disposable secretless TLS diagnostic + if: success() && steps.credentials.outcome == 'success' timeout-minutes: 10 env: WORK: ${{ runner.temp }}/origin-tls run: node .github/scripts/aws-origin-tls.cjs probe + - name: Acquire cleanup-only diagnostic credentials + if: always() && steps.scope.outcome == 'success' + timeout-minutes: 2 + uses: aws-actions/configure-aws-credentials@v4 + id: cleanup_credentials + with: + role-to-assume: ${{ vars.AWS_TERRAFORM_APPLY_ROLE_ARN }} + aws-region: us-east-1 + unset-current-credentials: true + inline-session-policy: ${{ steps.scope.outputs.cleanup_policy }} - name: Stop, deregister and privately archive diagnostic evidence - if: always() && steps.credentials.outcome == 'success' + if: always() && steps.cleanup_credentials.outcome == 'success' timeout-minutes: 8 env: WORK: ${{ runner.temp }}/origin-tls diff --git a/deploy/terraform/aws/runtime/README.md b/deploy/terraform/aws/runtime/README.md index f47a8b7ba..accd2d84d 100644 --- a/deploy/terraform/aws/runtime/README.md +++ b/deploy/terraform/aws/runtime/README.md @@ -247,7 +247,8 @@ Operator procedure: `.github/scripts/aws-origin-tls.cjs`, plus `logs:GetLogEvents` on `/ecs/warmbly-production/validation` and conditional `s3:PutObject` on `warmbly/production/diagnostics/origin-tls//1/*` in the private state - bucket. The workflow's session policy only restricts existing permissions. + bucket. The workflow's phase-specific sessions only restrict existing + permissions. Missing access requires the normal IAM process; the workflow never expands a role or switches environments. Read-only TLS metadata does not require access to secret values, SSM parameters or application task credentials. @@ -271,6 +272,18 @@ Operator procedure: certificate chains. Success requires the complete raw handshake evidence, exact task image digest and confirmed diagnostic cleanup. +Probe credentials permit discovery, one registration and launch, task readback +and private intent archival. Cleanup uses a separate OIDC session acquired +immediately before the finalizer, with only task/definition discovery, task +readback and stop, deregistration, exact-run log retrieval and private archival. +It cannot register definitions, launch tasks or pass roles. AWS requires +`ecs:DeregisterTaskDefinition` on `Resource: "*"`; the application validates +every deregistration candidate against the exact account, region and run family +with a numeric revision. The Logs ARN names only this run's streams. +Both credential steps clear existing credentials before acquisition. Cleanup +credential acquisition runs after probe failure, and the finalizer requires its +success. Credential failures fail the workflow without reusing an earlier session. + The transport targets are freshly described private interfaces of the exact ALB, never the public API DNS address. The SNI and verified hostname stay `api.warmbly.com`; the client trusts its system public CAs. Each interface gets From 8dfa0dcec8418a588ec7c1d727685525efb53c37 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 20:19:31 +0100 Subject: [PATCH 168/318] feat: verify origin ALB certificate inventory rejects a single certificate with non-boolean default status --- .github/scripts/aws-origin-alb.test.cjs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.github/scripts/aws-origin-alb.test.cjs b/.github/scripts/aws-origin-alb.test.cjs index bd1fc790c..0effdfa99 100644 --- a/.github/scripts/aws-origin-alb.test.cjs +++ b/.github/scripts/aws-origin-alb.test.cjs @@ -308,6 +308,15 @@ test("certificate inventory requires distinct ARN and default-status pairs with } }); +test("certificate inventory rejects a single certificate with non-boolean default status", async (t) => { + for (const status of [undefined, "true"]) { + const f = fixture(t); + f.live.listenerDetails[0].certificates = [{ CertificateArn: CERT, IsDefault: status }]; + await assert.rejects(collect(f.aws), /Incomplete or duplicate ALB certificate response/); + assert.equal(f.writeCalls().length, 0); + } +}); + for (const [label, drift] of [ ["policy", (f) => { f.live.listeners[0].SslPolicy = DESIRED; }], ["certificate", (f) => { f.live.listeners[0].Certificates = []; }], From 163dcd96b753d6f0206a4f703e813664da1d1202 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 20:20:20 +0100 Subject: [PATCH 169/318] feat: normalize per-leg Google app passwords in mailbox import fixes and mark import causes holding Google rows so the dashboard retry form checks app passwords for generic causes too --- internal/app/mailboximport/mailboximport_test.go | 12 ++++++++++++ internal/app/mailboximport/service.go | 3 +++ internal/models/mailbox_import.go | 2 ++ internal/repository/mailbox_import_live_test.go | 5 +++++ internal/repository/pg_mailbox_import.go | 4 ++-- web/src/components/app/emails/import/RunStep.tsx | 5 +++-- web/src/lib/api/models/app/emails/MailboxImport.ts | 2 ++ 7 files changed, 29 insertions(+), 4 deletions(-) diff --git a/internal/app/mailboximport/mailboximport_test.go b/internal/app/mailboximport/mailboximport_test.go index 6df44089c..7f2b66010 100644 --- a/internal/app/mailboximport/mailboximport_test.go +++ b/internal/app/mailboximport/mailboximport_test.go @@ -294,6 +294,18 @@ func TestCheckGooglePassword(t *testing.T) { } } +func TestApplyFixNormalizesPerLegGooglePasswords(t *testing.T) { + p := payload{MailHost: string(mailhost.Gmail)} + smtpPw, imapPw := "abcd efgh ijkl mnop", "ponm lkji hgfe dcba" + applyFix(&p, "[EMAIL]", models.MailboxImportRowFix{ + SMTP: &models.MailboxImportLegFix{Password: &smtpPw}, + IMAP: &models.MailboxImportLegFix{Password: &imapPw}, + }) + if p.SMTP.Password != "abcdefghijklmnop" || p.IMAP.Password != "ponmlkjihgfedcba" { + t.Fatalf("passwords = %q %q", p.SMTP.Password, p.IMAP.Password) + } +} + func TestFixableRows(t *testing.T) { cases := []struct { status, cause string diff --git a/internal/app/mailboximport/service.go b/internal/app/mailboximport/service.go index 215eb546d..c7973baaf 100644 --- a/internal/app/mailboximport/service.go +++ b/internal/app/mailboximport/service.go @@ -822,6 +822,9 @@ func applyFix(p *payload, email string, fix models.MailboxImportRowFix) { } else if p.Signin || p.AuthMethod == models.MailAuthOAuth { p.AuthMethod = mailhost.AuthMethodFor(host, "") } + final := mailhost.Host(p.MailHost) + p.SMTP.Password = mailhost.NormalizeAppPassword(final, p.SMTP.Password) + p.IMAP.Password = mailhost.NormalizeAppPassword(final, p.IMAP.Password) p.Signin = false } diff --git a/internal/models/mailbox_import.go b/internal/models/mailbox_import.go index d580abb49..b1e383503 100644 --- a/internal/models/mailbox_import.go +++ b/internal/models/mailbox_import.go @@ -212,6 +212,8 @@ type MailboxImportCause struct { Fix string `json:"fix"` Count int `json:"count"` Retryable bool `json:"retryable"` + // Google is true when any row under the cause is on Gmail or Google Workspace. + Google bool `json:"google,omitempty"` } type MailboxImport struct { diff --git a/internal/repository/mailbox_import_live_test.go b/internal/repository/mailbox_import_live_test.go index b457aa5a1..4c71efcf7 100644 --- a/internal/repository/mailbox_import_live_test.go +++ b/internal/repository/mailbox_import_live_test.go @@ -174,6 +174,11 @@ func TestLiveMailboxImportLifecycle(t *testing.T) { if len(got.Causes) != 2 { t.Fatalf("causes = %+v", got.Causes) } + for _, c := range got.Causes { + if !c.Google { + t.Fatalf("cause %s on Google rows is not marked google", c.Cause) + } + } rows, err := repo.ListRows(ctx, f.org, id, []string{models.ImportRowConnected}, "", 0, 10) if err != nil || len(rows) != 1 || rows[0].Retryable || rows[0].EmailAccountID == nil { t.Fatalf("connected rows = %+v, %v", rows, err) diff --git a/internal/repository/pg_mailbox_import.go b/internal/repository/pg_mailbox_import.go index d38fadacf..a1cec8183 100644 --- a/internal/repository/pg_mailbox_import.go +++ b/internal/repository/pg_mailbox_import.go @@ -261,7 +261,7 @@ func (r *mailboxImportRepository) fillCounts(ctx context.Context, imp *models.Ma } query = ` - SELECT cause, count(*), bool_or(payload <> '' AND status = 'failed') + SELECT cause, count(*), bool_or(payload <> '' AND status = 'failed'), bool_or(mail_host IN ('gmail', 'google_workspace')) FROM mailbox_import_rows WHERE import_id = $1 AND status IN ('failed', 'needs_signin') AND cause <> '' GROUP BY cause @@ -275,7 +275,7 @@ func (r *mailboxImportRepository) fillCounts(ctx context.Context, imp *models.Ma imp.Causes = make([]models.MailboxImportCause, 0) for rows.Next() { var c models.MailboxImportCause - if err := rows.Scan(&c.Cause, &c.Count, &c.Retryable); err != nil { + if err := rows.Scan(&c.Cause, &c.Count, &c.Retryable, &c.Google); err != nil { db.CaptureError(err, query, nil, "scan") return err } diff --git a/web/src/components/app/emails/import/RunStep.tsx b/web/src/components/app/emails/import/RunStep.tsx index 8c5e7f683..f45174986 100644 --- a/web/src/components/app/emails/import/RunStep.tsx +++ b/web/src/components/app/emails/import/RunStep.tsx @@ -691,8 +691,9 @@ function CauseCard({ const canRetry = cause.retryable && !signin; const passwordCause = isPasswordCause(cause.cause); const appPassword = /app_password/.test(cause.cause); - // Google causes are named google_*; the server refuses anything but an app password for them. - const notAppPassword = cause.cause.startsWith("google_") && !!password && !looksLikeGoogleAppPassword(password); + // The server refuses anything but an app password when a Google row is in the batch. + const googleRows = cause.google === true || cause.cause.startsWith("google_"); + const notAppPassword = googleRows && !!password && !looksLikeGoogleAppPassword(password); return (
    diff --git a/web/src/lib/api/models/app/emails/MailboxImport.ts b/web/src/lib/api/models/app/emails/MailboxImport.ts index 3c3d60206..5835280fe 100644 --- a/web/src/lib/api/models/app/emails/MailboxImport.ts +++ b/web/src/lib/api/models/app/emails/MailboxImport.ts @@ -220,6 +220,8 @@ export interface ImportCause { fix: string; count: number; retryable: boolean; + /** Some row under the cause is on Gmail or Google Workspace; older servers do not send it. */ + google?: boolean; } /** Where an import's rows came from: a file, a pasted list, a vendor's API, or an admin grant. */ From 78e42be41f957faf69adc6d3d5b631b52ab7ba8a Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 20:22:57 +0100 Subject: [PATCH 170/318] feat: validate bounded campaign attachment formats and UTF-8 imports while preserving portable existing files --- docs/content/docs/api/endpoints.mdx | 2 + docs/content/docs/api/error-codes.mdx | 4 + docs/content/docs/guides/campaigns.mdx | 20 + docs/content/docs/guides/contacts-crm.mdx | 4 + docs/content/docs/guides/mailbox-import.mdx | 4 + .../docs/guides/workspace-export-import.mdx | 6 + internal/api/handler/attachment.go | 53 +-- .../api/handler/attachment_upload_test.go | 128 +++++ internal/api/handler/internal_blobs.go | 2 +- internal/api/handler/internal_blobs_test.go | 31 ++ .../campaign/attachment_compatibility_test.go | 54 +++ internal/app/campaign/handlers.go | 1 + .../attachment_compatibility_test.go | 103 ++++ internal/app/orgtransfer/import.go | 5 +- internal/app/orgtransfer/jobs.go | 2 +- internal/app/orgtransfer/manifest.go | 10 + .../worker/attachment_compatibility_test.go | 35 ++ internal/pkg/attachmenttype/attachment.go | 172 +++++++ .../pkg/attachmenttype/attachment_test.go | 277 +++++++++++ internal/pkg/attachmenttype/office.go | 240 ++++++++++ internal/pkg/attachmenttype/pdf.go | 447 ++++++++++++++++++ .../pkg/attachmenttype/testdata/README.md | 8 + .../pkg/attachmenttype/testdata/WEBP-LICENSE | 27 ++ .../pkg/attachmenttype/testdata/document.docx | Bin 0 -> 3495 bytes .../pkg/attachmenttype/testdata/raster.webp | Bin 0 -> 19574 bytes internal/pkg/spreadsheet/spreadsheet.go | 4 + internal/pkg/spreadsheet/spreadsheet_test.go | 39 ++ internal/pkg/textcontent/text.go | 23 + internal/pkg/textcontent/text_test.go | 16 + .../campaigns/sequences/StepAttachments.tsx | 3 +- 30 files changed, 1681 insertions(+), 39 deletions(-) create mode 100644 internal/api/handler/attachment_upload_test.go create mode 100644 internal/app/campaign/attachment_compatibility_test.go create mode 100644 internal/app/orgtransfer/attachment_compatibility_test.go create mode 100644 internal/app/worker/attachment_compatibility_test.go create mode 100644 internal/pkg/attachmenttype/attachment.go create mode 100644 internal/pkg/attachmenttype/attachment_test.go create mode 100644 internal/pkg/attachmenttype/office.go create mode 100644 internal/pkg/attachmenttype/pdf.go create mode 100644 internal/pkg/attachmenttype/testdata/README.md create mode 100644 internal/pkg/attachmenttype/testdata/WEBP-LICENSE create mode 100644 internal/pkg/attachmenttype/testdata/document.docx create mode 100644 internal/pkg/attachmenttype/testdata/raster.webp create mode 100644 internal/pkg/textcontent/text.go create mode 100644 internal/pkg/textcontent/text_test.go diff --git a/docs/content/docs/api/endpoints.mdx b/docs/content/docs/api/endpoints.mdx index 8b26689e6..165dd56b8 100644 --- a/docs/content/docs/api/endpoints.mdx +++ b/docs/content/docs/api/endpoints.mdx @@ -114,6 +114,8 @@ Campaigns, steps and activity logs are scoped to the selected organization for s | POST | `/email-images` | `WRITE_CAMPAIGNS` | | DELETE | `/email-images/:id` | `WRITE_CAMPAIGNS` | +`POST /campaigns/:id/attachments` takes a multipart `file` and optional `step_id`. New uploads require matching supported content and a final extension: PDF, DOCX, XLSX, PPTX, CSV, TSV, TXT, PNG, JPG/JPEG, GIF, WebP or ZIP, up to 15 MiB. The server derives canonical outgoing MIME metadata, preserves bytes, and refuses unsupported, malformed or mismatched content with `400 invalid_attachment` before storage or quota reservation. See [format profiles, parser limits and existing-file compatibility](/guides/campaigns/#campaign-attachments). Client MIME declarations do not select the type. Duplication and workspace/admin archive restore preserve existing private files without claiming new-upload validation. + With `CAMPAIGN_ATTACHMENT_DOWNLOAD_PROXY=true`, attachment responses keep the `url` field and return a 15-minute API download link. `GET /campaign-attachments/download/:token` accepts that file-scoped capability, checks the current attachment and campaign tenant, and returns bytes as an attachment with `X-Content-Type-Options: nosniff`, `Cache-Control: no-store` and a sandboxed CSP. The capability contains no dashboard session token and grants no list, upload or delete access. Deleting the attachment ends the link. Treat the link as private until it expires; changing the instance auth secret also ends outstanding links. The `hold`, `pause` and `resume` calls under `/campaigns/:id/leads/:contactId/` hold one contact's flow inside one campaign: an out-of-office auto-reply writes one automatically, and a member can write one by hand. The contact stays subscribed and stays a lead, so this is not an unsubscribe and not a suppression. Both writes state an absolute hold rather than applying a delta, and replacing a live hold keeps its original start, so a retry lands on the same row and neither needs an `Idempotency-Key`. See [pause a lead](/api/reference/campaigns/#pause-a-lead). diff --git a/docs/content/docs/api/error-codes.mdx b/docs/content/docs/api/error-codes.mdx index fec4a33bf..0f8a27371 100644 --- a/docs/content/docs/api/error-codes.mdx +++ b/docs/content/docs/api/error-codes.mdx @@ -1086,6 +1086,10 @@ A `403` whose `code` is `mailbox_allowance_reached` comes from every path that c - Submit a limit-increase request for `max_email_accounts` via `POST /organization/:orgId/limit-requests`, or move to a plan with more daily sends. An approved request raises the allowance immediately; retry the connect then - Reconnecting an existing mailbox never returns this code +#### `invalid_attachment` + +A `400` from `POST /campaigns/:id/attachments` means the new file is unsupported, malformed, outside the [documented format limits](/guides/campaigns/#campaign-attachments), or does not match its final filename extension. Supported extensions are PDF, DOCX, XLSX, PPTX, CSV, TSV, TXT, PNG, JPG/JPEG, GIF, WebP and ZIP. Export the file in a supported profile with its matching extension and try again. Changing the client MIME header does not change the detected type. This refusal stores no object and reserves no storage quota. Existing stored files and portable archive restoration keep their compatibility policy. + #### `storage_limit_reached` A `400` whose `code` is `storage_limit_reached` comes from `POST /campaigns/:id/attachments`, from `POST /email-images`, and from a campaign duplicate that would copy attachments. The workspace's stored bytes, its attachments across every campaign plus its email image library, would pass the quota. The check and the write happen together under one per-workspace lock shared by both, so two uploads racing for the last of the quota cannot both get in. Nothing was stored. diff --git a/docs/content/docs/guides/campaigns.mdx b/docs/content/docs/guides/campaigns.mdx index ba5498fe1..e7725015b 100644 --- a/docs/content/docs/guides/campaigns.mdx +++ b/docs/content/docs/guides/campaigns.mdx @@ -434,6 +434,26 @@ Every campaign has a **โ‹ฏ** menu, on its row in the list and in the header of i **Duplicate** creates a new draft from the campaign's configuration and opens its settings so you can rename it (it starts as `name (copy)`), pick a different audience, change the copy, or adjust the schedule before starting it. The copy keeps every setting, the steps with their branching, the sending accounts, folders, tags, A/B variants and attachments. It does not keep leads, progress, statistics, activity, the ramp level, an auto-pause, or a start or end date that has already passed. The original is not touched, and the two campaigns are independent from then on. A duplicate counts as a new campaign for the daily creation limit. +## Campaign attachments + +Attach a file to one step in its composer, or upload a campaign-wide file through the API. Each file is at most 15 MiB. Warmbly checks a new upload's bytes against its final filename extension, derives the outgoing MIME type, and preserves the approved bytes. The client's MIME header does not choose the type. + +| Extensions | Supported content and limits | +| --- | --- | +| `.pdf` | Unencrypted PDF 1.0โ€“1.7 or 2.0 with classic cross-reference tables, indirect objects and a catalog/page tree. Cross-reference streams and compressed object streams are outside this upload profile. Export a PDF with classic cross-reference tables when needed. | +| `.docx`, `.xlsx`, `.pptx` | Modern Office ZIP packages with matching content types, package relationships and document, workbook or presentation XML parts. XLSX needs a related worksheet; PPTX needs a related slide. Macro-enabled and encrypted packages, legacy DOC/XLS/PPT, and other Office variants are outside this profile. | +| `.csv`, `.tsv`, `.txt` | UTF-8 text, including a UTF-8 BOM and Unicode, without binary control characters. CSV supports comma, semicolon and tab separators; TSV uses tabs. CSV/TSV quoting must parse. Content sniffed as an HTML or XML document is outside this text profile. | +| `.png`, `.jpg`, `.jpeg`, `.gif`, `.webp` | Matching raster content with a successful decoder, at most 8192 pixels per side and 16 million pixels. GIFs have at most 256 frames and 16 million pixels across frames. WebP uses the supported static image decoder. | +| `.zip` | A single-volume ZIP with no executable prefix, at most 2048 entries, 16 MiB per expanded member and 64 MiB expanded in total. ZIP64 and encrypted members are outside this profile. Members remain opaque recipient content; Warmbly does not extract them for execution. | + +Office packages share the ZIP limits, with at most 64 XML nesting levels and 200,000 tokens per XML part. PDF parsing is bounded to 100,000 object numbers, 32 revisions/nesting levels, 200,000 values and a 64 MiB parsing-work budget. Unsupported extensions, mismatched names, malformed content and files beyond these limits receive `400 invalid_attachment`. Re-export the file in a supported profile and upload it with its matching extension. Format checks do not certify that a document or archive is harmless. Download responses continue to force attachment handling. + +### Existing files and portable workspaces + +Existing attachments retain their bytes and outgoing metadata, including formats outside the new-upload profile. Campaign duplication and [workspace archive import/export](/guides/workspace-export-import/) preserve those files, and accepted queued sends continue to use them. Archive preflight and import explain that restored private files are existing content, not a new-upload validation certificate. Review imported files before using a campaign. + +This staged write-boundary policy supports v0.6.75 readers and rollback to that release. Mixed-version deployments can accept uploads through either version's policy until all writers run the new release; rollback restores that release's upload behavior. There is no schema, event-envelope or required worker-field change. A later transition to validation-based send eligibility requires additive provenance/hold state, portable archival retention, coordinated readers and workers, resumable classification, and a closed rollback window before enforcement. Current stored files, duplication, archive restore and internal blob capabilities must not be treated as universally content-validated. + **Delete** asks for confirmation that spells out what goes: the campaign, its steps, lead progress and activity. Contacts and emails already sent stay. A running campaign can be deleted directly; the confirmation says so, and sending stops immediately because every task waiting for the campaign is cancelled together with it. The same action is available at the bottom of the campaign's **Settings**. Deletion cannot be undone. diff --git a/docs/content/docs/guides/contacts-crm.mdx b/docs/content/docs/guides/contacts-crm.mdx index 189750072..ef310e31e 100644 --- a/docs/content/docs/guides/contacts-crm.mdx +++ b/docs/content/docs/guides/contacts-crm.mdx @@ -403,3 +403,7 @@ This is the safe default response to a bad signal: stop sending rather than keep + +## Text import encoding + +Delimited CSV, TSV and TXT imports, including supported extensionless text files, use UTF-8 with an optional UTF-8 BOM. Unicode, comma/semicolon detection, tab-separated input, quoted multiline cells and ragged rows retain their existing parsing behavior. Binary control characters, NUL bytes and invalid UTF-8 are refused before row parsing. XLSX and XLSM imports retain their existing workbook parser and decompression limits; their support is separate from campaign attachment uploads. diff --git a/docs/content/docs/guides/mailbox-import.mdx b/docs/content/docs/guides/mailbox-import.mdx index 1d8210c2d..4f0dc7a33 100644 --- a/docs/content/docs/guides/mailbox-import.mdx +++ b/docs/content/docs/guides/mailbox-import.mdx @@ -460,3 +460,7 @@ The import is available to a signed-in session under `/emails/imports`, never to + +## Text import encoding + +File-based CSV, TSV and TXT imports, including supported extensionless text files, use UTF-8 with an optional UTF-8 BOM. Unicode, comma/semicolon detection, tab-separated input, quoted multiline cells and ragged rows retain their existing parsing behavior. Binary control characters, NUL bytes and invalid UTF-8 are refused before row parsing. XLSX and XLSM imports retain their existing workbook parser and decompression limits; their support is separate from campaign attachment uploads. diff --git a/docs/content/docs/guides/workspace-export-import.mdx b/docs/content/docs/guides/workspace-export-import.mdx index 84e67cb8a..999038259 100644 --- a/docs/content/docs/guides/workspace-export-import.mdx +++ b/docs/content/docs/guides/workspace-export-import.mdx @@ -282,3 +282,9 @@ Reply and forward drafts kept in your browser are also excluded. Finish or copy - An archive can be imported into any instance running the same or a newer release. A newer archive on an older instance is refused, with the version in the message. + +## Campaign attachment compatibility + +Campaign attachments travel with their original bytes and metadata, including files accepted by v0.6.75 and formats outside the [new-upload profile](/guides/campaigns/#campaign-attachments). Workspace and admin import use the same preservation policy. Preflight and import report that restoring private campaign files does not certify their content. Those members are retained rather than omitted because of their format. Review them before using imported campaigns. Public images keep their separate image-validation policy. + +Archive format and row contracts stay compatible with v0.6.75. The new-upload policy adds no required archive field, validation certificate or send hold. An archive filename or source version is not evidence that every private member passed that policy. diff --git a/internal/api/handler/attachment.go b/internal/api/handler/attachment.go index 87c8d29b0..5bc66348c 100644 --- a/internal/api/handler/attachment.go +++ b/internal/api/handler/attachment.go @@ -10,7 +10,6 @@ import ( "context" "fmt" "io" - "mime" "net/http" "path" "strings" @@ -25,24 +24,16 @@ import ( "github.com/warmbly/warmbly/internal/errx" "github.com/warmbly/warmbly/internal/infrastructure/storage" "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/pkg/attachmenttype" ) const ( // Per-file cap. Kept under provider message ceilings (Gmail/Outlook ~25 MB // total, and base64 inflates ~37%), so a single attachment always fits. - attachmentMaxBytes int64 = 15 * 1024 * 1024 + attachmentMaxBytes int64 = attachmenttype.MaxBytes attachmentURLTTL = 15 * time.Minute ) -// Executable / script types that must never ride an outbound email. Everything -// else (images, PDF, office docs, CSV, archives, โ€ฆ) is allowed. -var blockedAttachmentExt = map[string]bool{ - ".exe": true, ".bat": true, ".cmd": true, ".com": true, ".msi": true, - ".scr": true, ".js": true, ".jse": true, ".vbs": true, ".vbe": true, - ".ps1": true, ".sh": true, ".jar": true, ".app": true, ".dll": true, - ".cpl": true, ".hta": true, ".wsf": true, ".pif": true, -} - func sanitizeFilename(name string) string { name = path.Base(strings.ReplaceAll(name, "\\", "/")) name = strings.TrimSpace(name) @@ -140,10 +131,23 @@ func (h *Handler) UploadCampaignAttachment(c *gin.Context) { return } filename := sanitizeFilename(fh.Filename) - if blockedAttachmentExt[strings.ToLower(path.Ext(filename))] { - errx.JSON(c, errx.New(errx.BadRequest, "that file type can't be attached to email")) + src, err := fh.Open() + if err != nil { + errx.JSON(c, errx.InternalError()) return } + defer src.Close() + body, err := io.ReadAll(io.LimitReader(src, attachmentMaxBytes+1)) + if err != nil { + errx.JSON(c, errx.InternalError()) + return + } + validated, err := attachmenttype.Validate(filename, body) + if err != nil { + errx.JSON(c, errx.NewWithIdentifier(errx.BadRequest, "invalid_attachment", "Use a supported attachment with matching content and filename: PDF, DOCX, XLSX, PPTX, CSV, TSV, TXT, PNG, JPEG, GIF, WebP or ZIP. See the campaign attachment format limits.")) + return + } + mimeType := validated.MIME // Plan-based overall storage quota (org-wide). This read is only a fast // refusal before the bytes are copied to storage; the check that counts @@ -163,27 +167,8 @@ func (h *Handler) UploadCampaignAttachment(c *gin.Context) { return } - src, err := fh.Open() - if err != nil { - errx.JSON(c, errx.InternalError()) - return - } - defer src.Close() - buf := &bytes.Buffer{} - if _, err := io.Copy(buf, src); err != nil { - errx.JSON(c, errx.InternalError()) - return - } - body := buf.Bytes() - // Only the bare media type is kept: it is written into the part's headers at send. - mimeType, _, err := mime.ParseMediaType(fh.Header.Get("Content-Type")) - if err != nil { - mimeType = http.DetectContentType(body) - } - key := models.AttachmentObjectKey(campaignID, filename) - // The row keeps the declared type for the outgoing MIME part; the object - // itself is never stored as something a browser would run. + // Delivery metadata is canonical; storage retains forced-download protection. if err := h.Storage.Put(c.Request.Context(), key, bytes.NewReader(body), storage.DownloadType(mimeType)); err != nil { errx.JSON(c, errx.InternalError()) return @@ -194,7 +179,7 @@ func (h *Handler) UploadCampaignAttachment(c *gin.Context) { SequenceID: seqID, UserID: userID, Filename: filename, - Size: fh.Size, + Size: int64(len(body)), MimeType: mimeType, S3Key: key, } diff --git a/internal/api/handler/attachment_upload_test.go b/internal/api/handler/attachment_upload_test.go new file mode 100644 index 000000000..10e1f3c0b --- /dev/null +++ b/internal/api/handler/attachment_upload_test.go @@ -0,0 +1,128 @@ +package handler + +import ( + "bytes" + "context" + "io" + "mime/multipart" + "net/http" + "net/http/httptest" + "net/textproto" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/warmbly/warmbly/internal/api/middleware" + "github.com/warmbly/warmbly/internal/app/audit" + "github.com/warmbly/warmbly/internal/app/feature" + "github.com/warmbly/warmbly/internal/errx" + "github.com/warmbly/warmbly/internal/infrastructure/storage" + "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/repository" +) + +type uploadQuota struct{ feature.FeatureGateService } + +func (uploadQuota) GetStorageLimitBytes(context.Context, uuid.UUID) (int64, *errx.Error) { + return 1 << 30, nil +} + +type uploadAudit struct{ audit.AuditService } + +func (uploadAudit) LogAction(context.Context, uuid.UUID, uuid.UUID, models.AuditAction, models.AuditEntityType, *uuid.UUID, string, string, map[string]string, map[string]string) { +} + +type uploadAttachments struct { + repository.AttachmentRepository + row *models.CampaignAttachment +} + +func (r *uploadAttachments) SumStorageUsedByOrg(context.Context, uuid.UUID) (int64, error) { + return 0, nil +} +func (r *uploadAttachments) CreateWithinQuota(ctx context.Context, a *models.CampaignAttachment, org uuid.UUID, limit repository.StorageLimitFunc) (bool, int64, int64, error) { + r.row = a + a.ID = uuid.New() + l, e := limit(ctx) + return true, 0, l, e +} + +type uploadStore struct { + storage.Store + puts int +} + +func (s *uploadStore) Put(ctx context.Context, key string, body io.Reader, ct string) error { + s.puts++ + return s.Store.Put(ctx, key, body, ct) +} + +func TestAttachmentUploadUsesContentPolicyBeforeStorageAndReservation(t *testing.T) { + gin.SetMode(gin.TestMode) + org, campaign, user := uuid.New(), uuid.New(), uuid.New() + for _, tc := range []struct { + name, filename, clientMIME string + body []byte + want int + }{ + {"generic client type", "people.csv", "application/octet-stream", []byte("name;city\nRenรฉe;ๆฑไบฌ\n"), http.StatusCreated}, + {"forged client type", "people.csv", "text/html", []byte("name,city\nRenรฉe,ๆฑไบฌ\n"), http.StatusCreated}, + {"renamed binary", "document.pdf", "application/pdf", []byte("MZ\x00binary"), http.StatusBadRequest}, + {"unknown", "file.unknown", "text/plain", []byte("ordinary text"), http.StatusBadRequest}, + {"invalid container", "document.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", []byte("PK\x03\x04malformed"), http.StatusBadRequest}, + } { + t.Run(tc.name, func(t *testing.T) { + files, err := storage.NewFilesystem(t.TempDir(), "") + if err != nil { + t.Fatal(err) + } + store := &uploadStore{Store: files} + repo := &uploadAttachments{} + h := &Handler{Storage: store, CampaignService: downloadCampaigns{org: org, id: campaign}, AttachmentRepo: repo, FeatureGateService: uploadQuota{}, AuditService: uploadAudit{}} + var body bytes.Buffer + form := multipart.NewWriter(&body) + headers := textproto.MIMEHeader{} + headers.Set("Content-Disposition", `form-data; name="file"; filename="`+tc.filename+`"`) + headers.Set("Content-Type", tc.clientMIME) + part, err := form.CreatePart(headers) + if err != nil { + t.Fatal(err) + } + if _, err := part.Write(tc.body); err != nil { + t.Fatal(err) + } + if err := form.Close(); err != nil { + t.Fatal(err) + } + router := gin.New() + router.POST("/campaigns/:id/attachments", func(c *gin.Context) { + c.Set(middleware.OrganizationIDKey, org) + c.Set(middleware.UserIDKey, user.String()) + }, h.UploadCampaignAttachment) + req := httptest.NewRequest(http.MethodPost, "/campaigns/"+campaign.String()+"/attachments", &body) + req.Header.Set("Content-Type", form.FormDataContentType()) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + if w.Code != tc.want { + t.Fatalf("status=%d body=%s", w.Code, w.Body.String()) + } + if tc.want == http.StatusCreated { + if repo.row == nil || repo.row.MimeType != "text/csv" || repo.row.Size != int64(len(tc.body)) { + t.Fatalf("canonical metadata=%+v", repo.row) + } + r, err := files.Get(t.Context(), repo.row.S3Key) + if err != nil { + t.Fatal(err) + } + defer r.Close() + got, err := io.ReadAll(r) + if err != nil || !bytes.Equal(got, tc.body) { + t.Fatal("bytes changed") + } + } else if store.puts != 0 || repo.row != nil || !strings.Contains(w.Body.String(), `"code":"invalid_attachment"`) { + t.Fatal("refused content was stored/reserved or lacks stable code", w.Body.String()) + } + }) + } +} diff --git a/internal/api/handler/internal_blobs.go b/internal/api/handler/internal_blobs.go index f25d80e67..f407ba5bf 100644 --- a/internal/api/handler/internal_blobs.go +++ b/internal/api/handler/internal_blobs.go @@ -74,7 +74,7 @@ type blobPresignResponse struct { ExpiresIn int `json:"expires_in"` } -// InternalPresignBlob signs one blob operation for a node. +// InternalPresignBlob authorizes transport, not content, for one scoped node operation. func (h *Handler) InternalPresignBlob(c *gin.Context) { if h.Storage == nil { c.JSON(http.StatusNotImplemented, gin.H{"error": "no blob store configured"}) diff --git a/internal/api/handler/internal_blobs_test.go b/internal/api/handler/internal_blobs_test.go index 2fccd988e..652d57475 100644 --- a/internal/api/handler/internal_blobs_test.go +++ b/internal/api/handler/internal_blobs_test.go @@ -2,10 +2,12 @@ package handler import ( "bytes" + "context" "net/http" "net/http/httptest" "strings" "testing" + "time" "github.com/gin-gonic/gin" "github.com/rs/zerolog" @@ -49,3 +51,32 @@ func TestPresignRefusesForeignPrefixAndLogsIt(t *testing.T) { t.Fatalf("node prefix: status %d, log %s", w.Code, buf.String()) } } + +type compatiblePresigner struct { + storage.Store + calls int +} + +func (s *compatiblePresigner) PresignedURL(_ context.Context, _ storage.PresignOp, _ string, _ string, _ time.Duration) (string, error) { + s.calls++ + return "https://storage.example.test/scoped-capability", nil +} + +func TestExistingNodeAttachmentCapabilitiesRemainTransportOnly(t *testing.T) { + gin.SetMode(gin.TestMode) + store := &compatiblePresigner{} + h := &Handler{Storage: store} + router := gin.New() + router.POST("/presign", h.InternalPresignBlob) + for _, op := range []string{"get", "head", "put", "delete"} { + request := `{"op":"` + op + `","key":"attachments/existing/file.unknown","content_type":"application/x-existing"}` + w := httptest.NewRecorder() + router.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/presign", strings.NewReader(request))) + if w.Code != http.StatusOK { + t.Fatalf("%s: %d %s", op, w.Code, w.Body.String()) + } + } + if store.calls != 4 { + t.Fatal("existing transport operations changed") + } +} diff --git a/internal/app/campaign/attachment_compatibility_test.go b/internal/app/campaign/attachment_compatibility_test.go new file mode 100644 index 000000000..2b5187e74 --- /dev/null +++ b/internal/app/campaign/attachment_compatibility_test.go @@ -0,0 +1,54 @@ +package campaign + +import ( + "bytes" + "context" + "io" + "testing" + + "github.com/google/uuid" + "github.com/warmbly/warmbly/internal/infrastructure/storage" + "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/repository" +) + +type existingAttachmentRepo struct { + repository.AttachmentRepository + files []models.CampaignAttachment +} + +func (r existingAttachmentRepo) ListByCampaign(context.Context, uuid.UUID) ([]models.CampaignAttachment, error) { + return r.files, nil +} + +func TestDuplicateRetainsExistingAttachmentMetadataAndBytes(t *testing.T) { + store, err := storage.NewFilesystem(t.TempDir(), "") + if err != nil { + t.Fatal(err) + } + src, dst, org := uuid.New(), uuid.New(), uuid.New() + body := []byte("\x00\xff portable existing attachment") + att := models.CampaignAttachment{Filename: "legacy.unknown", MimeType: "application/x-existing", Size: int64(len(body)), S3Key: models.AttachmentObjectKey(src, "legacy.unknown")} + if err := store.Put(t.Context(), att.S3Key, bytes.NewReader(body), ""); err != nil { + t.Fatal(err) + } + s := &campaignService{storage: store, attachmentRepo: existingAttachmentRepo{files: []models.CampaignAttachment{att}}} + copies, _, undo, xerr := s.copyAttachments(t.Context(), org, src, dst) + defer undo() + if xerr != nil || len(copies) != 1 { + t.Fatalf("copy=%v err=%v", copies, xerr) + } + copy := copies[0] + if copy.Filename != att.Filename || copy.MimeType != att.MimeType || copy.Size != att.Size || copy.S3Key == att.S3Key { + t.Fatal("copy changed legacy metadata") + } + r, err := store.Get(t.Context(), copy.S3Key) + if err != nil { + t.Fatal(err) + } + defer r.Close() + got, err := io.ReadAll(r) + if err != nil || !bytes.Equal(got, body) { + t.Fatal("copy changed bytes") + } +} diff --git a/internal/app/campaign/handlers.go b/internal/app/campaign/handlers.go index 4919b211d..c258d3e42 100644 --- a/internal/app/campaign/handlers.go +++ b/internal/app/campaign/handlers.go @@ -388,6 +388,7 @@ func (s *campaignService) copyAttachments(ctx context.Context, orgID, src, dst u errs.CaptureException(fmt.Errorf("campaign %s duplicate: read %s: %w", src, att.S3Key, err)) continue } + // Duplication preserves accepted files, including those from previous releases. key := models.AttachmentObjectKey(dst, att.Filename) err = s.storage.Put(ctx, key, body, storage.DownloadType(att.MimeType)) body.Close() diff --git a/internal/app/orgtransfer/attachment_compatibility_test.go b/internal/app/orgtransfer/attachment_compatibility_test.go new file mode 100644 index 000000000..78897a553 --- /dev/null +++ b/internal/app/orgtransfer/attachment_compatibility_test.go @@ -0,0 +1,103 @@ +package orgtransfer + +import ( + "archive/zip" + "bytes" + "context" + "io" + "testing" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/warmbly/warmbly/internal/infrastructure/storage" + "github.com/warmbly/warmbly/internal/models" +) + +type attachmentScopeTx struct { + pgx.Tx + campaign uuid.UUID +} + +func (tx attachmentScopeTx) Query(context.Context, string, ...any) (pgx.Rows, error) { + return &attachmentScopeRows{campaign: tx.campaign}, nil +} + +type attachmentScopeRows struct { + pgx.Rows + campaign uuid.UUID + read bool +} + +func (r *attachmentScopeRows) Next() bool { + if r.read { + return false + } + r.read = true + return true +} +func (r *attachmentScopeRows) Scan(dest ...any) error { *dest[0].(*uuid.UUID) = r.campaign; return nil } +func (r *attachmentScopeRows) Close() {} +func (r *attachmentScopeRows) Err() error { return nil } + +func TestPortableAttachmentsRetainExistingBytesAcrossArchiveRoundtrip(t *testing.T) { + ctx := t.Context() + campaign, org := uuid.New(), uuid.New() + source, err := storage.NewFilesystem(t.TempDir(), "") + if err != nil { + t.Fatal(err) + } + dest, err := storage.NewFilesystem(t.TempDir(), "") + if err != nil { + t.Fatal(err) + } + files := map[string][]byte{"legacy.unknown": []byte("\x00\xfflegacy bytes"), "document.pdf": []byte("previously accepted opaque bytes"), "notes.txt": []byte("Renรฉe ๆฑไบฌ\r\n")} + collector := newBlobCollector() + for filename, body := range files { + key := models.AttachmentObjectKey(campaign, filename) + if err := source.Put(ctx, key, bytes.NewReader(body), ""); err != nil { + t.Fatal(err) + } + collector.addKey(key, "campaign_attachments", "s3_key") + } + var archive bytes.Buffer + writer := zip.NewWriter(&archive) + m := &Manifest{SourceAppVersion: "v0.6.75"} + if err := (&service{blobs: source}).writeBlobs(ctx, writer, collector, m); err != nil { + t.Fatal(err) + } + if err := writer.Close(); err != nil { + t.Fatal(err) + } + if len(m.Blobs) != len(files) || len(m.attachmentCompatibilityWarnings()) != 1 { + t.Fatal("manifest lost files or omitted compatibility notice") + } + reader, err := zip.NewReader(bytes.NewReader(archive.Bytes()), int64(archive.Len())) + if err != nil { + t.Fatal(err) + } + warnings := (&service{blobs: dest}).restoreBlobs(ctx, attachmentScopeTx{campaign: campaign}, org, indexEntries(reader), m) + if len(warnings) != 0 { + t.Fatalf("restore: %v", warnings) + } + for _, ref := range m.Blobs { + a, err := source.Get(ctx, ref.Key) + if err != nil { + t.Fatal(err) + } + b, err := dest.Get(ctx, ref.Key) + if err != nil { + a.Close() + t.Fatal(err) + } + before, e1 := io.ReadAll(a) + after, e2 := io.ReadAll(b) + a.Close() + b.Close() + if e1 != nil || e2 != nil || !bytes.Equal(before, after) { + t.Fatal("archive changed or lost attachment bytes") + } + } + if notices := (&Manifest{}).attachmentCompatibilityWarnings(); len(notices) != 0 { + t.Fatal("unrelated archive notice") + } +} diff --git a/internal/app/orgtransfer/import.go b/internal/app/orgtransfer/import.go index 9ec13c79d..4c9630172 100644 --- a/internal/app/orgtransfer/import.go +++ b/internal/app/orgtransfer/import.go @@ -73,7 +73,7 @@ func (s *service) ImportFrom( return nil, err } - result := &ImportResult{RowCounts: map[string]int64{}} + result := &ImportResult{RowCounts: map[string]int64{}, Warnings: manifest.attachmentCompatibilityWarnings()} archiveKey, err := s.resolveArchiveKey(manifest, opts.Passphrase) if err != nil { @@ -865,7 +865,8 @@ func (s *service) restoreBlobs(ctx context.Context, tx pgx.Tx, orgID uuid.UUID, } } } else { - err = s.blobs.Put(ctx, destKey, rc, "") + // Preserve portable private files independently of the new-upload policy. + err = s.blobs.Put(ctx, destKey, rc, storage.DownloadType("")) } _ = rc.Close() if err != nil { diff --git a/internal/app/orgtransfer/jobs.go b/internal/app/orgtransfer/jobs.go index 5bca9df83..5b1a018fd 100644 --- a/internal/app/orgtransfer/jobs.go +++ b/internal/app/orgtransfer/jobs.go @@ -226,7 +226,7 @@ func (s *service) Preflight( out := &models.OrgImportPreflight{ Archive: manifest.Info(), Conflicts: map[string]int64{}, - Warnings: []string{}, + Warnings: manifest.attachmentCompatibilityWarnings(), } if manifest.Secrets != nil && passphrase != "" { diff --git a/internal/app/orgtransfer/manifest.go b/internal/app/orgtransfer/manifest.go index 3f077e670..f3b560a3b 100644 --- a/internal/app/orgtransfer/manifest.go +++ b/internal/app/orgtransfer/manifest.go @@ -170,3 +170,13 @@ func blobArchivePath(index int, key string) string { } return fmt.Sprintf("%s%06d-%s", blobPrefix, index, base) } + +// attachmentCompatibilityWarnings describes private-file preservation without attesting content. +func (m *Manifest) attachmentCompatibilityWarnings() []string { + for _, b := range m.Blobs { + if strings.HasPrefix(b.Key, "attachments/") { + return []string{"Campaign attachments are restored as portable existing files, including formats outside the new-upload policy. Restore preserves their bytes and does not certify their content. Review these files before using imported campaigns."} + } + } + return nil +} diff --git a/internal/app/worker/attachment_compatibility_test.go b/internal/app/worker/attachment_compatibility_test.go new file mode 100644 index 000000000..85abe354d --- /dev/null +++ b/internal/app/worker/attachment_compatibility_test.go @@ -0,0 +1,35 @@ +package worker + +import ( + "bytes" + "testing" + + "github.com/warmbly/warmbly/internal/infrastructure/storage" + "github.com/warmbly/warmbly/internal/pkg/emsg" +) + +func TestQueuedExistingAttachmentRemainsReadable(t *testing.T) { + store, err := storage.NewFilesystem(t.TempDir(), "") + if err != nil { + t.Fatal(err) + } + body := []byte("\x00\xff accepted existing bytes") + key := "attachments/existing/file.unknown" + if err := store.Put(t.Context(), key, bytes.NewReader(body), ""); err != nil { + t.Fatal(err) + } + original := &emsg.EmailBlob{Attachments: []emsg.Attachment{{S3Key: key, Filename: "file.unknown", MimeType: "application/x-existing"}}} + encoded, err := original.EncodeBinary() + if err != nil { + t.Fatal(err) + } + decoded, err := emsg.DecodeBinary(bytes.NewReader(encoded)) + if err != nil { + t.Fatal(err) + } + w := &WorkerService{Storage: store} + got, err := w.fetchAttachments(t.Context(), decoded.Attachments) + if err != nil || len(got) != 1 || got[0].Filename != "file.unknown" || got[0].MimeType != "application/x-existing" || !bytes.Equal(got[0].Data, body) { + t.Fatalf("queued attachment=%+v err=%v", got, err) + } +} diff --git a/internal/pkg/attachmenttype/attachment.go b/internal/pkg/attachmenttype/attachment.go new file mode 100644 index 000000000..b552faa3a --- /dev/null +++ b/internal/pkg/attachmenttype/attachment.go @@ -0,0 +1,172 @@ +// Package attachmenttype validates new campaign files without rewriting approved bytes. +package attachmenttype + +import ( + "bytes" + "encoding/csv" + "errors" + "image" + "image/gif" + "image/jpeg" + "image/png" + "io" + "net/http" + "path" + "strings" + + "golang.org/x/image/webp" + + "github.com/warmbly/warmbly/internal/pkg/imagetype" + "github.com/warmbly/warmbly/internal/pkg/spreadsheet" + "github.com/warmbly/warmbly/internal/pkg/textcontent" +) + +const MaxBytes = 15 << 20 + +// Type is the canonical outgoing media type of a validated file. +type Type struct { + MIME string + Extension string +} + +var ErrInvalid = errors.New("unsupported or malformed attachment; use a supported file with its matching extension") + +// Validate checks the final filename extension and bounded content, ignoring client MIME. +func Validate(filename string, body []byte) (Type, error) { + if len(body) == 0 || len(body) > MaxBytes { + return Type{}, ErrInvalid + } + ext := strings.ToLower(path.Ext(filename)) + t := Type{Extension: ext} + var ok bool + switch ext { + case ".pdf": + t.MIME, ok = "application/pdf", validPDF(body) + case ".docx", ".xlsx", ".pptx": + t.MIME, ok = officeType(body, ext) + case ".zip": + t.MIME = "application/zip" + _, err := readZIP(body) + ok = err == nil + case ".txt", ".csv", ".tsv": + t.MIME = "text/plain" + ok = textcontent.Validate(body) == nil && strings.HasPrefix(http.DetectContentType(bytes.TrimPrefix(body, []byte("\ufeff"))), "text/plain") + if ext != ".txt" { + if ext == ".csv" { + t.MIME = "text/csv" + } else { + t.MIME = "text/tab-separated-values" + } + r := csv.NewReader(bytes.NewReader(bytes.TrimPrefix(body, []byte("\ufeff")))) + r.FieldsPerRecord = -1 + r.Comma = spreadsheet.Delimiter(body) + if ext == ".tsv" { + r.Comma = '\t' + } + if ok { + for { + _, err := r.Read() + if err == io.EOF { + break + } + if err != nil { + ok = false + break + } + } + } + } + case ".png", ".jpg", ".jpeg", ".gif", ".webp": + t.MIME, ok = rasterType(body, ext) + } + if !ok { + return Type{}, ErrInvalid + } + return t, nil +} + +func rasterType(body []byte, ext string) (string, bool) { + expected, _ := imagetype.ByExt(ext) + f, cfg, err := imagetype.Detect(body, expected) + if err != nil || cfg.Width > 8192 || cfg.Height > 8192 || int64(cfg.Width)*int64(cfg.Height) > 16_000_000 { + return "", false + } + var decoded image.Image + switch f.MIME { + case "image/png": + decoded, err = png.Decode(bytes.NewReader(body)) + case "image/jpeg": + decoded, err = jpeg.Decode(bytes.NewReader(body)) + case "image/webp": + decoded, err = webp.Decode(bytes.NewReader(body)) + case "image/gif": + // Bound all frames before DecodeAll allocates their pixel buffers. + if !boundedGIF(body) { + return "", false + } + var g *gif.GIF + g, err = gif.DecodeAll(bytes.NewReader(body)) + if err == nil && len(g.Image) > 0 { + decoded = g.Image[0] + } + } + return f.MIME, err == nil && decoded != nil +} + +func boundedGIF(b []byte) bool { + if len(b) < 13 { + return false + } + pos := 13 + if b[10]&128 != 0 { + pos += 3 * (1 << (1 + (b[10] & 7))) + } + pixels, frames := 0, 0 + blocks := func() bool { + for pos < len(b) { + n := int(b[pos]) + pos++ + if n == 0 { + return true + } + pos += n + } + return false + } + for pos < len(b) { + tag := b[pos] + pos++ + switch tag { + case 0x3b: + return frames > 0 && pos == len(b) + case 0x21: + pos++ + if !blocks() { + return false + } + case 0x2c: + if pos+9 > len(b) { + return false + } + w := int(b[pos+4]) | int(b[pos+5])<<8 + h := int(b[pos+6]) | int(b[pos+7])<<8 + pixels += w * h + frames++ + if pixels > 16_000_000 || frames > 256 { + return false + } + flags := b[pos+8] + pos += 9 + if flags&128 != 0 { + pos += 3 * (1 << (1 + (flags & 7))) + } + pos++ + if !blocks() { + return false + } + default: + return false + } + } + return false +} diff --git a/internal/pkg/attachmenttype/attachment_test.go b/internal/pkg/attachmenttype/attachment_test.go new file mode 100644 index 000000000..c67ab96a7 --- /dev/null +++ b/internal/pkg/attachmenttype/attachment_test.go @@ -0,0 +1,277 @@ +package attachmenttype + +import ( + "archive/zip" + "bytes" + "fmt" + "image" + "image/color" + "image/gif" + "image/jpeg" + "image/png" + "os" + "strings" + "testing" + + "github.com/xuri/excelize/v2" +) + +func fixture(t *testing.T, name string) []byte { + t.Helper() + b, e := os.ReadFile("testdata/" + name) + if e != nil { + t.Fatal(e) + } + return b +} +func zipped(t *testing.T, parts map[string][]byte) []byte { + t.Helper() + var b bytes.Buffer + z := zip.NewWriter(&b) + for n, v := range parts { + w, e := z.Create(n) + if e != nil { + t.Fatal(e) + } + if _, e = w.Write(v); e != nil { + t.Fatal(e) + } + } + if e := z.Close(); e != nil { + t.Fatal(e) + } + return b.Bytes() +} +func pdfFixture() []byte { + var b bytes.Buffer + b.WriteString("%PDF-1.4\n") + objects := []string{"<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Count 1 /Kids [3 0 R] >>", "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R >>", "<< /Length 0 >>\nstream\n\nendstream"} + offsets := []int{0} + for i, v := range objects { + offsets = append(offsets, b.Len()) + fmt.Fprintf(&b, "%d 0 obj\n%s\nendobj\n", i+1, v) + } + xref := b.Len() + fmt.Fprintf(&b, "xref\n0 5\n0000000000 65535 f \n") + for _, n := range offsets[1:] { + fmt.Fprintf(&b, "%010d 00000 n \n", n) + } + fmt.Fprintf(&b, "trailer\n<< /Size 5 /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n", xref) + return b.Bytes() +} +func presentation(t *testing.T) []byte { + return zipped(t, map[string][]byte{ + "[Content_Types].xml": []byte(``), + "_rels/.rels": []byte(``), + "ppt/presentation.xml": []byte(``), + "ppt/_rels/presentation.xml.rels": []byte(``), + "ppt/slides/slide1.xml": []byte(``), + }) +} +func supported(t *testing.T) map[string][]byte { + t.Helper() + files := map[string][]byte{ + "document.docx": fixture(t, "document.docx"), "slide.pptx": presentation(t), "file.pdf": pdfFixture(), "raster.webp": fixture(t, "raster.webp"), + "data.csv": []byte("\ufeffname;city\r\nRenรฉe;ๆฑไบฌ\r\n"), "data.tsv": []byte("name\tcity\nRenรฉe\tๆฑไบฌ\n"), "notes.txt": []byte("Hello ฮšฮฑฮปฮทฮผฮญฯฮฑ ๆฑไบฌ\n"), "files.zip": zipped(t, map[string][]byte{"notes.txt": []byte("recipient content")}), + } + f := excelize.NewFile() + defer f.Close() + if err := f.SetCellValue("Sheet1", "A1", "Actual workbook"); err != nil { + t.Fatal(err) + } + b, e := f.WriteToBuffer() + if e != nil { + t.Fatal(e) + } + files["sheet.xlsx"] = b.Bytes() + img := image.NewRGBA(image.Rect(0, 0, 2, 2)) + img.Set(0, 0, color.RGBA{R: 200, A: 255}) + for _, ext := range []string{"png", "jpg", "gif"} { + var b bytes.Buffer + var err error + switch ext { + case "png": + err = png.Encode(&b, img) + case "jpg": + err = jpeg.Encode(&b, img, nil) + case "gif": + err = gif.Encode(&b, img, nil) + } + if err != nil { + t.Fatal(err) + } + files["raster."+ext] = b.Bytes() + } + return files +} + +func TestSupportedAttachmentsPreserveBytesAndReturnCanonicalTypes(t *testing.T) { + want := map[string]string{".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", ".pdf": "application/pdf", ".csv": "text/csv", ".tsv": "text/tab-separated-values", ".txt": "text/plain", ".zip": "application/zip", ".png": "image/png", ".jpg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp"} + for name, body := range supported(t) { + t.Run(name, func(t *testing.T) { + before := bytes.Clone(body) + got, err := Validate(name, body) + if err != nil || got.MIME != want[got.Extension] { + t.Fatalf("type=%+v err=%v", got, err) + } + if !bytes.Equal(before, body) { + t.Fatal("input changed") + } + if _, err := Validate(strings.ToUpper(name), body); err != nil { + t.Fatal(err) + } + }) + } +} +func TestUnsupportedMalformedAndRenamedAttachments(t *testing.T) { + files := supported(t) + cases := map[string]struct { + name string + body []byte + }{ + "no extension": {"file", files["notes.txt"]}, "unknown extension": {"file.bin", files["notes.txt"]}, "legacy office": {"file.doc", []byte{0xd0, 0xcf, 0x11, 0xe0}}, "macro workbook": {"file.xlsm", files["sheet.xlsx"]}, + "renamed image": {"file.pdf", files["raster.png"]}, "wrong office family": {"file.docx", files["sheet.xlsx"]}, "zip renamed office": {"file.xlsx", files["files.zip"]}, + "binary text": {"file.txt", []byte("MZ\x00\x01binary")}, "invalid UTF8": {"file.csv", []byte{'n', ',', 0xff}}, "BOM HTML text": {"file.txt", []byte("\ufeffcontent")}, + "html text": {"file.txt", []byte("content")}, "malformed csv": {"file.csv", []byte("a,b\n\"unclosed,b")}, + "forged pdf": {"file.pdf", []byte("%PDF-1.7\nnot a document\n%%EOF")}, "truncated PDF": {"file.pdf", files["file.pdf"][:40]}, "bad xref": {"file.pdf", bytes.Replace(files["file.pdf"], []byte("0000000009"), []byte("0000000010"), 1)}, + "truncated png": {"file.png", files["raster.png"][:35]}, "truncated jpeg": {"file.jpg", files["raster.jpg"][:100]}, "truncated webp": {"file.webp", files["raster.webp"][:30]}, "gif trailer": {"file.gif", files["raster.gif"][:len(files["raster.gif"])-1]}, + "zip prefix": {"file.zip", append([]byte("MZprefix"), files["files.zip"]...)}, "truncated zip": {"file.zip", files["files.zip"][:30]}, "empty": {"file.txt", nil}, "oversize": {"file.txt", bytes.Repeat([]byte("a"), MaxBytes+1)}, + } + for label, tc := range cases { + t.Run(label, func(t *testing.T) { + if got, err := Validate(tc.name, tc.body); err == nil || got != (Type{}) { + t.Fatalf("accepted: %+v %v", got, err) + } + }) + } +} +func TestContainerBudgetsAndRequiredOfficeParts(t *testing.T) { + for label, parts := range map[string]map[string][]byte{ + "expansion": {"large": bytes.Repeat([]byte("a"), maxPart+1)}, "traversal": {"../file": []byte("x")}, + } { + t.Run(label, func(t *testing.T) { + if _, err := Validate("file.zip", zipped(t, parts)); err == nil { + t.Fatal("accepted") + } + }) + } + parts, err := readZIP(presentation(t)) + if err != nil { + t.Fatal(err) + } + for _, name := range []string{"[Content_Types].xml", "_rels/.rels", "ppt/slides/slide1.xml", "ppt/_rels/presentation.xml.rels"} { + t.Run("missing "+name, func(t *testing.T) { + v := parts[name] + delete(parts, name) + defer func() { parts[name] = v }() + if _, err := Validate("file.pptx", zipped(t, parts)); err == nil { + t.Fatal("accepted missing part") + } + }) + } + parts["ppt/slides/slide1.xml"] = []byte(``) + if _, err := Validate("file.pptx", zipped(t, parts)); err == nil { + t.Fatal("accepted malformed slide") + } +} + +func TestOfficeRequiresDeclaredRelationshipsAndCompleteXML(t *testing.T) { + original, err := readZIP(presentation(t)) + if err != nil { + t.Fatal(err) + } + for name, replacement := range map[string][]byte{ + "ppt/presentation.xml": []byte(``), + "_rels/.rels": []byte(``), + "ppt/slides/slide1.xml": []byte(``), + } { + t.Run(name, func(t *testing.T) { + parts := make(map[string][]byte, len(original)) + for k, v := range original { + parts[k] = v + } + parts[name] = replacement + if _, err := Validate("file.pptx", zipped(t, parts)); err == nil { + t.Fatal("accepted inconsistent package") + } + }) + } +} + +func TestPDFRejectsIncompleteObjectGraphAndStreamLengths(t *testing.T) { + b := pdfFixture() + // Equal-width changes keep the original xref offsets meaningful. + for _, pair := range [][2]string{{"/Size 5", "/Size 0"}, {"/Pages 2 0 R", "/Pages 9 0 R"}, {"/Parent 2 0 R", "/Parent 1 0 R"}, {"/Length 0", "/Length 9"}, {"/Count 1", "/Count 2"}, {"/MediaBox", "/OtherBox"}} { + t.Run(pair[0], func(t *testing.T) { + changed := bytes.Replace(b, []byte(pair[0]), []byte(pair[1]), 1) + if _, err := Validate("file.pdf", changed); err == nil { + t.Fatal("accepted incomplete document") + } + }) + } +} + +func TestZIPChecksCRCEntryCountAndAggregateExpansion(t *testing.T) { + var buf bytes.Buffer + w := zip.NewWriter(&buf) + f, err := w.CreateHeader(&zip.FileHeader{Name: "file", Method: zip.Store}) + if err != nil { + t.Fatal(err) + } + if _, err = f.Write([]byte("unique-member-payload")); err != nil { + t.Fatal(err) + } + if err = w.Close(); err != nil { + t.Fatal(err) + } + corrupted := bytes.Replace(buf.Bytes(), []byte("unique-member-payload"), []byte("broken-member-payload"), 1) + if _, err := Validate("file.zip", corrupted); err == nil { + t.Fatal("accepted bad CRC") + } + parts := map[string][]byte{} + for i := 0; i <= maxEntries; i++ { + parts[fmt.Sprint(i)] = []byte("x") + } + if _, err := Validate("file.zip", zipped(t, parts)); err == nil { + t.Fatal("accepted too many entries") + } + large := bytes.Repeat([]byte("a"), maxPart) + parts = map[string][]byte{} + for i := 0; i < 5; i++ { + parts[fmt.Sprint(i)] = large + } + if _, err := Validate("file.zip", zipped(t, parts)); err == nil { + t.Fatal("accepted aggregate expansion") + } +} + +func TestRasterAndXMLResourceLimits(t *testing.T) { + var large bytes.Buffer + if err := png.Encode(&large, image.NewGray(image.Rect(0, 0, 8193, 1))); err != nil { + t.Fatal(err) + } + if _, err := Validate("large.png", large.Bytes()); err == nil { + t.Fatal("accepted oversized raster dimensions") + } + frame := image.NewPaletted(image.Rect(0, 0, 1, 1), color.Palette{color.Black, color.White}) + animated := &gif.GIF{} + for i := 0; i < 257; i++ { + animated.Image = append(animated.Image, frame) + animated.Delay = append(animated.Delay, 1) + } + var frames bytes.Buffer + if err := gif.EncodeAll(&frames, animated); err != nil { + t.Fatal(err) + } + if _, err := Validate("animation.gif", frames.Bytes()); err == nil { + t.Fatal("accepted excessive animation frames") + } + parts, err := readZIP(presentation(t)) + if err != nil { + t.Fatal(err) + } + parts["ppt/slides/slide1.xml"] = []byte(strings.Repeat("", 65) + strings.Repeat("", 65)) + if _, err := Validate("file.pptx", zipped(t, parts)); err == nil { + t.Fatal("accepted excessive XML depth") + } +} diff --git a/internal/pkg/attachmenttype/office.go b/internal/pkg/attachmenttype/office.go new file mode 100644 index 000000000..c9a64189e --- /dev/null +++ b/internal/pkg/attachmenttype/office.go @@ -0,0 +1,240 @@ +package attachmenttype + +import ( + "archive/zip" + "bytes" + "encoding/binary" + "encoding/xml" + "io" + "path" + "strings" +) + +const ( + maxEntries = 2048 + maxExpanded = 64 << 20 + maxPart = 16 << 20 + packageNS = "http://schemas.openxmlformats.org/package/2006/" + officeNS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/" +) + +// readZIP verifies every member's compression and CRC within shared expansion limits. +func readZIP(body []byte) (map[string][]byte, error) { + if !bytes.HasPrefix(body, []byte("PK\x03\x04")) && !bytes.HasPrefix(body, []byte("PK\x05\x06")) { + return nil, ErrInvalid + } + // A bounded, single-volume directory excludes ZIP64 and executable prefixes. + end := -1 + for i := len(body) - 22; i >= max(0, len(body)-65557); i-- { + if string(body[i:i+4]) == "PK\x05\x06" && i+22+int(binary.LittleEndian.Uint16(body[i+20:i+22])) == len(body) { + end = i + break + } + } + if end < 0 { + return nil, ErrInvalid + } + e := body[end:] + count := int(binary.LittleEndian.Uint16(e[10:12])) + if count > maxEntries || binary.LittleEndian.Uint16(e[4:6]) != 0 || binary.LittleEndian.Uint16(e[6:8]) != 0 || int(binary.LittleEndian.Uint16(e[8:10])) != count || uint64(binary.LittleEndian.Uint32(e[12:16]))+uint64(binary.LittleEndian.Uint32(e[16:20])) != uint64(end) { + return nil, ErrInvalid + } + z, err := zip.NewReader(bytes.NewReader(body), int64(len(body))) + if err != nil || len(z.File) != count { + return nil, ErrInvalid + } + parts := make(map[string][]byte, len(z.File)) + total := 0 + for _, f := range z.File { + if _, duplicate := parts[f.Name]; duplicate || f.Flags&1 != 0 || f.UncompressedSize64 > maxPart { + return nil, ErrInvalid + } + if f.Name == "" || strings.Contains(f.Name, "\\") || strings.HasPrefix(f.Name, "/") || strings.Contains(f.Name, "../") { + return nil, ErrInvalid + } + r, err := f.Open() + if err != nil { + return nil, ErrInvalid + } + b, readErr := io.ReadAll(io.LimitReader(r, int64(min(maxPart, maxExpanded-total))+1)) + closeErr := r.Close() + total += len(b) + if readErr != nil || closeErr != nil || len(b) > maxPart || total > maxExpanded || uint64(len(b)) != f.UncompressedSize64 { + return nil, ErrInvalid + } + parts[f.Name] = b + } + return parts, nil +} + +type xmlPart struct { + root xml.Name + children []xml.StartElement + links map[string]bool +} + +func parseXML(b []byte) (xmlPart, error) { + d := xml.NewDecoder(bytes.NewReader(b)) + depth, tokens, roots := 0, 0, 0 + out := xmlPart{links: map[string]bool{}} + for { + t, err := d.Token() + if err == io.EOF { + break + } + if err != nil { + return out, ErrInvalid + } + tokens++ + if tokens > 200_000 { + return out, ErrInvalid + } + switch v := t.(type) { + case xml.StartElement: + for _, a := range v.Attr { + if a.Name.Space == strings.TrimSuffix(officeNS, "/") && a.Name.Local == "id" { + out.links[a.Value] = true + } + } + depth++ + if depth > 64 { + return out, ErrInvalid + } + if depth == 1 { + roots++ + out.root = v.Name + } + if depth == 2 { + out.children = append(out.children, xml.CopyToken(v).(xml.StartElement)) + } + case xml.EndElement: + depth-- + case xml.Directive: + return out, ErrInvalid + case xml.CharData: + if depth == 0 && len(bytes.TrimSpace(v)) != 0 { + return out, ErrInvalid + } + case xml.ProcInst: + if v.Target != "xml" { + return out, ErrInvalid + } + } + } + if roots != 1 || depth != 0 { + return out, ErrInvalid + } + return out, nil +} + +func attr(e xml.StartElement, key string) string { + for _, a := range e.Attr { + if a.Name.Space == "" && a.Name.Local == key { + return a.Value + } + } + return "" +} + +func officeType(body []byte, ext string) (string, bool) { + parts, err := readZIP(body) + if err != nil { + return "", false + } + parsed := make(map[string]xmlPart) + for name, b := range parts { + lower := strings.ToLower(name) + if strings.Contains(lower, "vbaproject") { + return "", false + } + if strings.HasSuffix(lower, ".xml") || strings.HasSuffix(lower, ".rels") { + p, err := parseXML(b) + if err != nil { + return "", false + } + parsed[name] = p + } + } + var main, mime, root, ns, child, member, memberRoot, relation string + switch ext { + case ".docx": + main, mime, root, ns, child = "word/document.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "document", "http://schemas.openxmlformats.org/wordprocessingml/2006/main", "body" + case ".xlsx": + main, mime, root, ns, child, member, memberRoot, relation = "xl/workbook.xml", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "workbook", "http://schemas.openxmlformats.org/spreadsheetml/2006/main", "sheets", "xl/", "worksheet", "worksheet" + case ".pptx": + main, mime, root, ns, child, member, memberRoot, relation = "ppt/presentation.xml", "application/vnd.openxmlformats-officedocument.presentationml.presentation", "presentation", "http://schemas.openxmlformats.org/presentationml/2006/main", "sldIdLst", "ppt/", "sld", "slide" + default: + return "", false + } + ct := parsed["[Content_Types].xml"] + if ct.root != (xml.Name{Space: packageNS + "content-types", Local: "Types"}) { + return "", false + } + found := false + for _, e := range ct.children { + v := attr(e, "ContentType") + if strings.Contains(strings.ToLower(v), "macroenabled") || strings.Contains(strings.ToLower(v), "vbaproject") { + return "", false + } + if e.Name.Local == "Override" && attr(e, "PartName") == "/"+main && v == mime+".main+xml" { + found = true + } + } + if !found || !relationship(parsed["_rels/.rels"], "", officeNS+"officeDocument", main, nil) { + return "", false + } + p := parsed[main] + if p.root != (xml.Name{Space: ns, Local: root}) { + return "", false + } + found = false + for _, e := range p.children { + if e.Name == (xml.Name{Space: ns, Local: child}) { + found = true + } + } + if !found { + return "", false + } + if member != "" { + found = false + rels := parsed[path.Dir(main)+"/_rels/"+path.Base(main)+".rels"] + for name, part := range parsed { + if strings.HasPrefix(name, member) && part.root == (xml.Name{Space: ns, Local: memberRoot}) && relationship(rels, path.Dir(main), officeNS+relation, name, p.links) { + found = true + break + } + } + if !found { + return "", false + } + } + return mime, true +} + +func relationship(p xmlPart, base, kind, target string, declared map[string]bool) bool { + if p.root != (xml.Name{Space: packageNS + "relationships", Local: "Relationships"}) { + return false + } + matches := 0 + for _, e := range p.children { + if e.Name.Space != p.root.Space || e.Name.Local != "Relationship" || attr(e, "Type") != kind { + continue + } + if declared != nil && !declared[attr(e, "Id")] { + continue + } + raw := attr(e, "Target") + if attr(e, "TargetMode") == "External" || raw == "" { + continue + } + resolved := path.Clean(path.Join(base, raw)) + if strings.HasPrefix(raw, "/") { + resolved = strings.TrimPrefix(path.Clean(raw), "/") + } + if resolved == target { + matches++ + } + } + return matches == 1 +} diff --git a/internal/pkg/attachmenttype/pdf.go b/internal/pkg/attachmenttype/pdf.go new file mode 100644 index 000000000..2e4c7303c --- /dev/null +++ b/internal/pkg/attachmenttype/pdf.go @@ -0,0 +1,447 @@ +package attachmenttype + +import ( + "bytes" + "strconv" + "strings" +) + +// This bounded structural reader supports unencrypted PDFs with classic xref tables. +type pdfName string +type pdfRef struct{ id, gen int } +type pdfDict map[string]any +type pdfEntry struct{ offset, gen int } +type pdfReader struct { + data []byte + entries map[int]pdfEntry + objects map[int]any + loading map[int]bool + work, tokens int +} +type pdfCursor struct { + p *pdfReader + at int +} + +func validPDF(b []byte) bool { + if len(b) < 20 || !bytes.HasPrefix(b, []byte("%PDF-")) || (b[8] != '\r' && b[8] != '\n') || !((b[5] == '1' && b[6] == '.' && b[7] >= '0' && b[7] <= '7') || string(b[5:8]) == "2.0") { + return false + } + end := bytes.TrimRight(b, " \t\r\n\f\x00") + if !bytes.HasSuffix(end, []byte("%%EOF")) { + return false + } + tail := bytes.LastIndex(end, []byte("startxref")) + if tail < 0 { + return false + } + offset, err := strconv.Atoi(strings.TrimSpace(string(end[tail+9 : len(end)-5]))) + if err != nil { + return false + } + p := &pdfReader{data: b, entries: map[int]pdfEntry{}, objects: map[int]any{}, loading: map[int]bool{}} + seen := map[int]bool{} + var root pdfRef + for revision := 0; ; revision++ { + if revision >= 32 || offset < 0 || offset >= len(b) || seen[offset] { + return false + } + seen[offset] = true + c := pdfCursor{p: p, at: offset} + if c.word() != "xref" { + return false + } + for { + w := c.word() + if w == "trailer" { + break + } + first, e1 := strconv.Atoi(w) + count, e2 := strconv.Atoi(c.word()) + if e1 != nil || e2 != nil || first < 0 || count < 0 || count > 100_000 || first > 100_000-count { + return false + } + for i := 0; i < count; i++ { + off, e1 := strconv.Atoi(c.word()) + gen, e2 := strconv.Atoi(c.word()) + state := c.word() + if e1 != nil || e2 != nil || off < 0 || gen < 0 || gen > 65535 || (state != "n" && state != "f") { + return false + } + if _, exists := p.entries[first+i]; !exists { + if state == "n" { + if off >= len(b) { + return false + } + p.entries[first+i] = pdfEntry{off, gen} + } else { + p.entries[first+i] = pdfEntry{-1, gen} + } + } + } + } + value, ok := c.value(0) + trailer, dict := value.(pdfDict) + size, sized := pdfInt(trailer["Size"]) + if !ok || !dict || !sized || size < 1 || size > 100_000 || trailer["Encrypt"] != nil || trailer["XRefStm"] != nil { + return false + } + if revision == 0 { + var yes bool + root, yes = trailer["Root"].(pdfRef) + if !yes { + return false + } + } + prev, exists := trailer["Prev"] + if !exists { + break + } + var yes bool + offset, yes = pdfInt(prev) + if !yes { + return false + } + } + for id, e := range p.entries { + if e.offset >= 0 { + v, ok := p.object(pdfRef{id, e.gen}) + if !ok || !p.references(v) { + return false + } + } + } + v, ok := p.object(root) + catalog, dict := v.(pdfDict) + if !ok || !dict || catalog["Type"] != pdfName("Catalog") { + return false + } + pages, ok := catalog["Pages"].(pdfRef) + if !ok { + return false + } + _, ok = p.pages(pages, pdfRef{}, false, map[int]bool{}, 0) + return ok +} + +func pdfInt(v any) (int, bool) { n, ok := v.(int); return n, ok } +func pdfSpace(b byte) bool { return b == 0 || b == 9 || b == 10 || b == 12 || b == 13 || b == 32 } +func pdfDelim(b byte) bool { return pdfSpace(b) || strings.ContainsRune("()<>[]{}/%", rune(b)) } +func (c *pdfCursor) skip() { + for c.at < len(c.p.data) && c.p.work <= maxExpanded { + c.p.work++ + if pdfSpace(c.p.data[c.at]) { + c.at++ + continue + } + if c.p.data[c.at] == '%' { + for c.at < len(c.p.data) && c.p.data[c.at] != '\r' && c.p.data[c.at] != '\n' { + c.at++ + c.p.work++ + } + continue + } + break + } +} +func (c *pdfCursor) word() string { + c.skip() + start := c.at + for c.at < len(c.p.data) && !pdfDelim(c.p.data[c.at]) { + c.at++ + c.p.work++ + } + if c.p.work > maxExpanded || c.at-start > 128 { + return "" + } + return string(c.p.data[start:c.at]) +} +func (c *pdfCursor) value(depth int) (any, bool) { + c.p.tokens++ + if depth > 32 || c.p.tokens > 200_000 || c.p.work > maxExpanded { + return nil, false + } + c.skip() + b := c.p.data + if c.at >= len(b) { + return nil, false + } + switch b[c.at] { + case '/': + c.at++ + start := c.at + for c.at < len(b) && !pdfDelim(b[c.at]) { + c.at++ + c.p.work++ + } + raw := string(b[start:c.at]) + var name strings.Builder + for i := 0; i < len(raw); i++ { + if raw[i] == '#' { + if i+2 >= len(raw) { + return nil, false + } + n, err := strconv.ParseUint(raw[i+1:i+3], 16, 8) + if err != nil { + return nil, false + } + name.WriteByte(byte(n)) + i += 2 + } else { + name.WriteByte(raw[i]) + } + } + return pdfName(name.String()), true + case '(': + c.at++ + level := 1 + for c.at < len(b) { + ch := b[c.at] + c.at++ + c.p.work++ + if ch == '\\' { + if c.at >= len(b) { + return nil, false + } + c.at++ + continue + } + if ch == '(' { + level++ + } + if ch == ')' { + level-- + if level == 0 { + return nil, true + } + } + if level > 32 { + return nil, false + } + } + return nil, false + case '[': + c.at++ + var a []any + for { + c.skip() + if c.at >= len(b) { + return nil, false + } + if b[c.at] == ']' { + c.at++ + return a, true + } + v, ok := c.value(depth + 1) + if !ok { + return nil, false + } + a = append(a, v) + } + case '<': + c.at++ + if c.at < len(b) && b[c.at] == '<' { + c.at++ + d := pdfDict{} + for { + c.skip() + if c.at+1 < len(b) && string(b[c.at:c.at+2]) == ">>" { + c.at += 2 + return d, true + } + k, ok := c.value(depth + 1) + name, yes := k.(pdfName) + if !ok || !yes { + return nil, false + } + if _, exists := d[string(name)]; exists { + return nil, false + } + v, ok := c.value(depth + 1) + if !ok { + return nil, false + } + d[string(name)] = v + } + } + for c.at < len(b) { + ch := b[c.at] + c.at++ + c.p.work++ + if ch == '>' { + return nil, true + } + if !pdfSpace(ch) && !strings.ContainsRune("0123456789abcdefABCDEF", rune(ch)) { + return nil, false + } + } + return nil, false + default: + w := c.word() + if w == "null" { + return nil, true + } + if w == "true" || w == "false" { + return w, true + } + n, err := strconv.Atoi(w) + if err != nil { + if w == "" || strings.Trim(w, "+-0123456789.") != "" { + return nil, false + } + f, err := strconv.ParseFloat(w, 64) + return f, err == nil + } + save := c.at + gen, err := strconv.Atoi(c.word()) + if err == nil && c.word() == "R" { + return pdfRef{n, gen}, true + } + c.at = save + return n, true + } +} +func (p *pdfReader) object(ref pdfRef) (any, bool) { + entry, ok := p.entries[ref.id] + if !ok || entry.offset < 0 || entry.gen != ref.gen || p.loading[ref.id] { + return nil, false + } + if v, ok := p.objects[ref.id]; ok { + return v, true + } + p.loading[ref.id] = true + defer delete(p.loading, ref.id) + c := pdfCursor{p: p, at: entry.offset} + if c.word() != strconv.Itoa(ref.id) || c.word() != strconv.Itoa(ref.gen) || c.word() != "obj" { + return nil, false + } + v, ok := c.value(0) + if !ok { + return nil, false + } + end := c.word() + if end == "stream" { + d, ok := v.(pdfDict) + if !ok { + return nil, false + } + length := d["Length"] + if r, ref := length.(pdfRef); ref { + length, ok = p.object(r) + if !ok { + return nil, false + } + } + n, ok := pdfInt(length) + if !ok || n < 0 || c.at >= len(p.data) { + return nil, false + } + if p.data[c.at] == '\r' { + c.at++ + } + if c.at < len(p.data) && p.data[c.at] == '\n' { + c.at++ + } else if c.at == 0 || p.data[c.at-1] != '\r' { + return nil, false + } + if n > len(p.data)-c.at { + return nil, false + } + c.at += n + if c.word() != "endstream" { + return nil, false + } + end = c.word() + } + if end != "endobj" { + return nil, false + } + p.objects[ref.id] = v + return v, true +} +func (p *pdfReader) pages(ref, parent pdfRef, media bool, seen map[int]bool, depth int) (int, bool) { + if depth > 32 || seen[ref.id] { + return 0, false + } + seen[ref.id] = true + v, ok := p.object(ref) + d, yes := v.(pdfDict) + if !ok || !yes { + return 0, false + } + if depth > 0 && d["Parent"] != parent { + return 0, false + } + if box, exists := d["MediaBox"]; exists { + if r, indirect := box.(pdfRef); indirect { + box, ok = p.object(r) + if !ok { + return 0, false + } + } + coords, array := box.([]any) + if !array || len(coords) != 4 { + return 0, false + } + var values [4]float64 + for i, v := range coords { + switch n := v.(type) { + case int: + values[i] = float64(n) + case float64: + values[i] = n + default: + return 0, false + } + } + if values[2] <= values[0] || values[3] <= values[1] { + return 0, false + } + media = true + } + if d["Type"] == pdfName("Page") { + return 1, media + } + if d["Type"] != pdfName("Pages") { + return 0, false + } + kids, ok := d["Kids"].([]any) + if !ok { + return 0, false + } + total := 0 + for _, k := range kids { + r, ok := k.(pdfRef) + if !ok { + return 0, false + } + n, ok := p.pages(r, ref, media, seen, depth+1) + if !ok { + return 0, false + } + total += n + } + count, ok := pdfInt(d["Count"]) + return total, ok && total > 0 && count == total +} + +func (p *pdfReader) references(v any) bool { + switch v := v.(type) { + case pdfRef: + e, ok := p.entries[v.id] + return ok && e.offset >= 0 && e.gen == v.gen + case pdfDict: + for _, v := range v { + if !p.references(v) { + return false + } + } + case []any: + for _, v := range v { + if !p.references(v) { + return false + } + } + } + return true +} diff --git a/internal/pkg/attachmenttype/testdata/README.md b/internal/pkg/attachmenttype/testdata/README.md new file mode 100644 index 000000000..505d75bee --- /dev/null +++ b/internal/pkg/attachmenttype/testdata/README.md @@ -0,0 +1,8 @@ +`document.docx` is an original short document exported by macOS textutil. +`raster.webp` is `blue-purple-pink.lossless.webp` from golang.org/x/image +v0.45.0 testdata, under the accompanying WEBP-LICENSE. + +The tests also produce a real workbook through excelize, an original minimal +presentation package, a classic-xref PDF with calculated object offsets, PNG, +JPEG, GIF and ZIP files through their encoders. All are checked without rewriting +the input bytes. diff --git a/internal/pkg/attachmenttype/testdata/WEBP-LICENSE b/internal/pkg/attachmenttype/testdata/WEBP-LICENSE new file mode 100644 index 000000000..2a7cf70da --- /dev/null +++ b/internal/pkg/attachmenttype/testdata/WEBP-LICENSE @@ -0,0 +1,27 @@ +Copyright 2009 The Go Authors. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google LLC nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/internal/pkg/attachmenttype/testdata/document.docx b/internal/pkg/attachmenttype/testdata/document.docx new file mode 100644 index 0000000000000000000000000000000000000000..f33178daf77bd9110a337f07cf56a86f008216fd GIT binary patch literal 3495 zcmaJ^2{e>#8y?viVeHG;*R0v%vy?;_dkwNQq)B2-j4ewNWe|Q0QSyn1nX+f!GV@u+ zzVF#7WXUp7_{X=L%K85Peb4he=e*~=?(^Q)y}Oma+D81c;qCuo8c8%^hv>w77)qm@GutRKI(XJA4{Fa z63M8+ufp;6V-2o}7-t{x}9gJO#(uJ|^GKcl|+SWAi zVlPta{4F*`g9<}8VVAIdBE*2L$@TRJNQoN=~XYAxc6 zd>G^!uTp@cj;^SG$c=8=eQj0H%gbE?k~59iO5n?L#uC_=y8bDt(Ww6PstlL z{vqp}_Z_Id_u;lu?`y4>2|Hg#c7KhU#7U#Ad>o!H&0 zx{>1*GqrE1;+0z8jtk;(kry_qiqjE7C^j8=!DM(RcpQJbU_!HDekrb6kcZ**rEn1QSEs?1-Jp}+Tl24d7+ykW`f4sj<>@=o23w*Gyqu&-HSt^5W_1hI` z`f#b4mJV?%SN-5+Z1uNYYYQJI$KB~-w=WBjRzLrZ(!eZ zni?AMFh_%C=!CdBK zQhV0ID{m;R%E1&cb{kdIJJp}%Dh#=J`^Msy&hI=+5kp5+S@7og&Y%v?&o*DjX}D~9 zLIA(=5#HrJ)j{Ur4LQyD$)`Wk`=-KQq})Wh_#(*JcARE^5%eEZ2$`VA>xa>aHJu#- zmu_kXu{t9~WCEBFiV%E!vNqqMYe!9c~xD~k<9aDJ|C(rkP}(slK)LtE%9#DNb(BrG@D z0cQnc%G65|5f+W@^3RWadWRMSqln^1b%#Z0C-p&%OHCrYI1ue2IiJ+ova|cs;FF3G(H*G z`zl$0VJudXY`5#$n zgd|oc>(ZNLKqskq6K)|lk(Z{|RaT&z%2{&58j};S+|M3o@%_wB6GloAdcxyr2^lHwaQPCID+uchD`Bn?>;B9m%QQsXf7<_4nuy>Zz8ITO;JfKXY zG=0>=b3ts5+bfZB1w5G~ncGu7OQ?|h_V_)QO^F>kH2_^k3`5hj#QW`t!WN# zMp-*NcTjwQD_q$Len1NP9vs13$caLthchwo?_LoFUq<1%;j4_hD@Fl;jm$}aHc_eE zMy`8s{#JWi#l?sRJ)`1h<_zmn0BAsEr}vp&!R-fYG3gt|Y*o303j>e@ExVF9^wyIj zF*)sGcp&zm>-FRZ*C*O}HU^39Lk}dDNg@SL9k(j|RRU8CuO!&BrsF#5_EVK= zXfpCUcg@|mrUq{D^hU_V8A3ZhS6#swD2Y62hEBLYRFmT}PcShudCos72`-*g#&gyR zs_Kn59i*0{5^rL+BnI}lTKhaO;_kuxJc3<46mPzO1+&o@NNptO6uy>9r;Y6i9b~#b z{^}gDCUS3NrhmLI!}K>T3rmLlHMEJl^g&)7(>-LvTo9CBey%ababSOP9``AM50>VU7qA{wbDh8)B9-D4|~+kv?0yjZ@wK*Kix#c zsHjRSdc*KLm8H7fz^ym*~7Z43!mr30Vf<+wNk1m;F%Z3)H$Kp=5GI1kCs}PeO7Ll z&mytpaI)8xSU&jah0UQ0rhM=feMB=@vhz3JYCof|f@{IGQC&-)cQb9~L(COsdGx0$ z88`)%XEY1#mdaYa=*sYG zF7ejt5JoBi99P`|?XMkS+`a1B0J#%*kbCrTezrb=l znuKtF)Rf{f9vny4gCUv7I~)b%T93<1P-ZNBP{5nQ;T2L(6tyoycQ zhQ@cgHn%nxUg0}h%L&u<1%izUx3l%}P}}Cgy!vDs8~AsVei21Fl>|`*py^1dYk1&f^z7r*fZgx>ogSC}#c!(Ft}qdj8atv@lSZ4+;| zq>^3VA}^MoDR91f_n3hfUD}LIitLYOCSj~475S${a@@GQ{PNa>s}2Atq+vnM0m*=B z63ncim7Z&VpeM`HZ<4oA|K=5-Z2lJiyV{+nvts%;!n?HSblaH{SH~PtvFt)$fJQed zl2X`EdCA6pr;t`@%8N=C+mE-NWM?_2%B8pIXba)=pkR(Sz>kd_GmOM|TZQim%dPcC zIYAANR^P?$Pa+{I#mp~%mKF-H(=(iU$G%2z?n3;S{SMl7P(Jny@ z%wT5Br9UjHJ$5k(BZjW88~S7K=>A~sglqGbp7kPftz)AUejQq>M74q?u z7(EF*sndP{UC2uI|EacMi__7kB_akN0b!7w3R3*11CU$QxGL%FbtS9421uG zhPK-c5&chDR(<8^xU%Y3);!HemUT^7#xg|6hx`!oPs(yh2^k@Wj69^IqN$dtDNbof zMTlsya8)WQs^CYiJUt#(v3!JP&$Tu=l4RS~|BHy4xd+Hv7_a8)Ee01EiK zhJoD8R8?e*R1F?P<+za~NfJGB4r#TO7W@A%UR4=Rv27$ll0;R_{rm6k|8+$`kR&&5 z<6OE0U_n3?4L{&pk|ax#B-c#a5rIq5Xs9Yh)HbQNRTAD=RW^{f4e2I zZ6iUFsP6sGKj52oNO0RolBAq-ce5hnup<&!*9San+iu#nZENrMrIb-hRkMdZrfr98 zJE$X>hoIm*2pgec+is{RB`c-$eQzL_eh#VlmL$oNB+0gjS=7uuZ;mr78;93PN-4Xl-962*ZQHgz^Xjo}n`5)x)wauBsZ=GoKG<68Mb95`+n2UI ziX`o}^}dpsxrawYW@J`o!OzT0J2ucU23x6HiX`BQK`xhVP76d5wIj}|qV0;G~+yrcZUDj^U zwBsTy0mB6X=t6)TB4Fn}$S#H}FQ!)CF9^^(y9+O9qzuvl2Jr<*AOtA{tYB8JHi&a}|<)<&(=^eB0>%P=(S*J!Hn{^U^6b$*46N}FFhNbjb_YPVC zg|Ku^5XTmD?&~T z40Io)+rbfEn9({Rlf@h&VIYX34m2z@cFz+8g#bhuRsdlI1S}_W1E5yJAkJh@&reMI zsSg5qe^0l})&13MIgPBRn3k1UmxdAEj-A;k2swMLtW2X#FwMZD4ZkhIR{IIqIPwHu z90*`QK!J{qg(ox$5CM!`gBoDB3oGOk3kHe-cP5|+AWyzvd|fsc$RIZyChAtRan z(CJg3!9}2s@6D!W?`svhVfkq3u;IXOR>WY|CTJyF*M#0Q31O2EP5f;x)8Y&S4TrUYbE z0|zuNI6+-}D|Br}z%oG(;iV@GPqGn=yN#0@9iwov zoGp=bf`KB)0l|`i_*vR+()~p^+98>d)25zuG6IlGEVwC)p+yV@1ck33Wm3Ko)A8!0 z2v9OO(AC=ct+RB99bk(mjMlK@_mMfnA%UPr(J$syD9kXdQg8}^15&9Nl`D5PD#{{Y zfWHu6L-x!g+zCE!zx!{jFS0NcRmjD2IL55)O;a&Ji;=_q5$zFcBM4+f_dZoWiX(9G zwHLjLu5gHKsK=Fp3gK>Hmhz=p&6NP^%E2obLv(5>>T5LxnG43D1v zKA%w5kVCnnbiVL5WK?z(kn6gt;O6kiPCNF1u-Vf)b+Qb5#ftw@00<%gm*|qKthYe0 zH7#Y440ZyrRsc>`faKc3mNCL0u~;y@j0kIPz=)?1!;GG7Di)$^ry{IGSCG;Wz(KnY zJwme!3|jzT9mSeKay68L3)vBjQCYIc6kouNpYterbno@-x#%)Ni4zLbd1pg0IS0*N zIASBKcuQKe%cl1t1P~ZgPnrtGN?0TT3Cp-5z}mom=m*+()4Ra}rwYQV5hnCDKOv8a z2DpSc*c3;@+2?fG{hnbel|qfqy7CwmA_O-K@W@MTR05P=MQMkDGV2hmkrz zp`6CTZrDU#T(PAEtv99aRO&f$q*N`$D^TNhb593aRLmHqEfE#(|nKwvJg{>S#aDoqC zbYi=-et#f?@(FhC9Xp5TKR(Xcs_@>o`!>1VTYzy5J0r}haK zg$bs1vT*1*7+k+GkksEZ>_#%!<85KWp@5ybg|mXDZjD0e|Ia@@G~J?+3`h|K2BQ;7 zW5au6LdM{po=fV$#{u|owtauaxYaG{()QIGPK_HohVa6M-CaN;*{C%BBWxi?hO+|! z84(M+FD|Sal~>XrCpR8&NXYTlFhWL6-5ZnN=`Pu(7GsAT z6;O2RxOuVhLGad=Q8=i4PykLgzFYu<_qQwRt*hmLpj^I$63Hy|<) zGTtSFgI*kQ{PFI}_;cw|_KcVuLDp!ogD+O|; z69^}jCxphB&^>`z<;lV9;6UhkeUR08n;Pe|^SG3gJMZiep%eIYIS~%X7lIDBF%WQiZYnnI zse>;X3@$(suDk&b?ie5sP86Y{fUK;>6(<5kakK}RH0~^`G^-|LZ_MC(50yei0Qo&% zucQcDJi?UefyaG-;@_Y~e5B=sLGBBjl`gkVI|mh18cXP;@OR8kdC&H^{9X6DKEV>ETWp4&7*gRp{NltG%o^1uCS*eTUv( zaC0c;Z+*^qnhcyPVO6zJqR8pvAY&kP)n^?umjU8bGH_hgtG>YL1a2K`m4HdPb8jVJatRu!<5J z2Q5}Ac2K$iZK|*q7D%Qrlh9EN5Jm}6B?mC13XAek0uL5ItH1nPl~JI`(gFc2yr2_A zdFnVGK~FvOG8$6Cov0n~UyP0X064~l262FqtEH5LQ5Gp^6>R`PASlp6(5SG9*+@Zj zb^xJqa65ol!Xg4;FJ@7Xg0Yg=+#kJN#7Qvi&=aXlrGS(G2!r7@MeVhaNQW z0Kl)@8fYZ~Y}Hwy4i&VnQKDP}yhsBqm;-QNpXhcV00@8$OdybnI({4?U#OL^NLfLW zYi*f9MStIv;ZK$fJJCVw_5E}pdF#1JY6cJf(QsxA`}D?W*#Ci zW30zY060`3Xk2L+;G~F11?Etofh_<6m_6P~2q2IEUHh78e#74$}$fs@05 zBGl?o2@!ILJ&43Ov19TY8jlH5@Vn>i^Z$H0A>G(xfm!BWrb9{>5iGmiR(tvOQ{Me5 z3C-bOj_uwa(vJuP2%t6OoFALZ98W&{be?vjnE)09g;lQtzF$%`PgJp&sZtZF`Ho@$ zr+Uk(uOk}i0U-ham_Q8-s*fbG{4uID7r-dCRip=H2thkMQ)houB_EOds;g*QcA$m^wSTXKB&HFrD3%y#?6KBQ2qG%+y6nx5F8SnFmX>FPXS?qH z=CRGO#Wg{Hshz(u*2|uef3WeTT3dH}9Zj+2tI0Nll(1!6GFs=s_x1EKS~j!JKY43$ z{%EssuPhU`%64ww$)0o$_R8URez!jHzgar=!FhpRDjyE(_Gj^iU$*9HYn{J1Y$KkQ z>ashJb%ob94@cJ;b6?%w_0`jxU*zAv7WV03qv-eptIOeT`B1$6FOeAPxbI)O|F~oS&r>;uwvL9Y*C_k*ZI|zDJN`nma(cZzetog)N;^?wZgO|LB+(>c zLDF1l;Z!IPu4QN1q^Mn-#!N^IVZa#Gx<$exJGc5>B{yrM+hTEQYv-36`Ss~`S&24w zkKmOY$L`yKLv~&?p}wQWBhSA0ZC}d$$?7DtWa)Wsr7ouQ8qRPd3(d69&2Gs-ww*ou z;&=bNRO1~#_lcQP*Vs7buDj*Lmc>tQkG^?(zQ&ua^RUHze{QLU%wV;&8bH|b^a%p*ieBC^m@`pM)Vm*Ad&}B#g8K>Z0l6ES#tkWdRWpBW|mXyqtBy+p4`7 zF268epI`gQA7dQ0pU!S%_ANP$drjv*j7pjA_2eIHEWU_xuehhw-SwCUr+6;?u$zWS z2=e5TwxFq`@sw)mN3Ydf4b39Ty&<(7`&O4(V>xnA>9~0gTW*x0w|UWC&rMo4avD)r z9bQ3~p)hg5E!bVb!z>Qb5T;_gOB*eW|GRs#X7mmU1p6G=eGyO^jc1?p{a*r}HTmFo zmJ;sWo~z?Le$sKaerAgC$s4}%^AG;!-&uce*A7?b`~K4PM|*s|&$pAv<^DXwx))0v zvffi+tl8JCtbDsOUfonDy4Cn3E4=Msuz5NVxALyeO_8+Qn3FJ#I!Jw5I%oer-}bNfC;#o~4PZVUupN0Eho7bFt<&dXy%jC* zyRON|!kDyww&Cy%TEDnzV&QS?&z#iZSNAUV%doj>5S-M>(r5zNJ=y7F6Jh%IKaN`{ zaw3s~Mq|U>>&jy}DxguQ*Mxw80jBCvi-0&5JS-lD&67Ld`v3nfBmn>c5D=EM*{b-I zv0eM|)g7m-^B4>iCSdp%M%$QTN zRZ&bON)nkyT3OifQOH0Dxuw=udCRe~WD_KQ*VD0*ZpXL(67cc7uibaQu^hjDk<^b@ zh*Zcd-uJHdzZw1Ah6FrPAtW`4+g|zG-=dMXNtp&A)!RR8n0hwPr_9H`%ZRK@%@r2v8|Ji5vzkB%Ca zS#w&H6zMSq1Y#~`hf|rRM#8kvTb!lzAgLe@lqZ2BZQ%ikv4=3(t<^c~!06O&eA`Yx zHN9(Fe&p?6F&CERWQxHI08vaa7>rLR?>=wWHaOqg58vp2SRt>j-&`L`Poj(q^7WE! z-!y`16IseyTdb~ru;xum$+|_g6{;Y3DTt`U8Yx4%MZIbM;8(J5+PZ-zsHHfLeuzVI zKWHaYpJFHj0RXgtZKvN;zuWerrk6UHn8OYpbXlMM>21UNeoeo7vA+Gf{@9^lBo006 zB>S?@+C$IUAN>3l-)>3ECZH6J%k}jiduNH*Q^-AYSHuOH_)^%iv!qSqp5fBNX@on79fZ8|5LrK~7*oLPAh3mBNIx z5=v8Upc*l$0u9%2r9yc1-i@pBOKQg_izQer0ZBQAK|Bmy`txD$!DoKpy4=zw2!H?p zKtMFRNXIR^f3Jqy0?)y-EGvrj?=3ffb#T>dCd!_$U1 zkKwkLH@dL}KoAVPuDpHj?o9ebz7PY#p5kok>-DGQ-%sIKLl%G>R5I4}H{JSbb!K-Z z;|?Ku(#!t)+OBzj=nseEH2Yup?=SQFfP#UTaq#f|_x`sZj{9EaU=wG0ufi9+ZrvVH zGL##XM`#O!!gCF)#~1cp7kS(h3iK0mb8-1saKU_j5jXs z=kV65khtPY$SzR{MSf&hcwncdh@axRFOeM}3}yrfCIvj%EajMwP1IZBLn;t6Fr#7r z@ctI(kVuXW{sd`*(2Ssf@(e5T&>z2xrM~6sX8X~^i9i*VAzm;YFPu!9Bn##s2w)1J zH%$Abx8t65{o4<}ZJ-E@bgVb~xNKTqiPma_lUaG}esZTaNaG>;cwZm;^^^PtSiwRB zF~q1c^(VcKfBSXp>|3ZKX}b7r1DTp39JMSVS&$Pe4W*y*HP6N?o~82Dr2Sdv{;t11 zpP!u7v3l(8?UUUoz#BU*69!isrysKYMeBUX1eH1f5V%~b#m3YM<*=41r6z;OM)NEN zD&*j*I=!%^wfQfliGV~9lDP!|qn!LkocQ`|29YBz0*p+i7H3Z6dFtrHeaMa{0RWf@ z1R6|2i3?6Y(0vhVFA=W=Za4UC_as>;8KOM;G)9*vgakwo#dI)19<%S4-~M2{UJBl_ zcopKIv0k=s$8&Fv2#7ui5G34$axgKdrPnw(9LMULzxwibC%fY7c~q*@r_3+i>7sOs z>n5=ud^1r>x*Yi>=Y?Jo0S;umO2!4#5IMiD(c-!+DI&F@dMHZ~LIWtK8CYgBRR7(Ryh&Xwyh3J*8@2-{2vNDu!ru`Z}r+FIJF<0!s)nu)!z3 z%D3Oy1q^^dQ0lQ>#~7@Q>z0R;z)5Vzn|?Ooj`(KAPb_{CXHd`1T7SxKIs zPGYgc+u_5^a^xi=QSFniwdKr?HRYt#8%rS|Fq<)$&45L%jd$Gi%Ml&i{3sa;A~0d) zJjFu{W&{|_2m&q`vm4K{H54~=TsPwF8|24cj0z7`xpJ?bMab244l}( z3^*KOuHgA^e_77g5f9c&qU_%cgc$q^2pq?4BQF0g?(4S_^fcDm-v+)I}g_V#npagD<`IKvWdx!9Wm27!Z(zfe!*L zJQvspJqF77=5*lsdB^T!c+6^y_!v9?BOC8^8#%{fgT!C!Bp|>H8AvD)Oic~c!3kj6 z!h0AepV>7>q)O|`S<;HYEPxq<85048WL`Ah=#JkEJ)l}>cN9cj>EzDf$H@Rd;L{qi z6KT%+M6twBC3#Ysn!Bj5Y)qfU{9XRkN^FNhOh#;#Awv5&t{2A5uU~nfL{RvfEkcS9tBi}>0@huf9s9!);1a6 zlAU7y>{#j*q}Spdk}>@Fp-KS*h6B-~`5N+Ir`Q(G+*kt`B9^cz)du8X*g*jt2VVgU zeFok~;u>}{y>a4YJo*!7a57IXXb^Awq`?d@D7Lyo2l>WadUet^tb_)gkVbb(pBssp zB^d`QmbS!!z|;+!M-P%5uG*HR+X0DX*|y~;jsPz!a5ScY4JER&{d4-S z3I>&B)a6JySgmE2!@x4EDR-if;OXJpW+EaHa)_81Yk&YSV4XpeLZQ;%`sZKitGRER zXSR$<&dI>Z`|)qL>#L4?2qObwhMphTBu+F2K662{|HV`@pqjB z5O8EPa{C{Z&Ka#{3CJN7{Uw$6hRD(*fPoplV)r^V%3-d z1P@Fx&0PJkuIbjRPob6b4KaZx2!QL!Q6y!@{h{rH;JEnz#-{(RfZ?X*4o-ISkllUr zZXe{M+gBd}Fd=-10#7@dL8uJxAMe)-StlCYE>u{=O58(AgcflYf|&#WGng?{HypL2MGcX3e^pNJi-p$7)~}t%-rG; zWdd;!bTA+Rs&=av2NDucf*6F!36PHoLPhcDU?5niFH0S}5gA#Iob-*43H8i&Bpx!K z2=lhpYwO*7ennxB{rj?osdA@lWQVfi$kOb4a_Wf5&|E6Wv zF1Se<5JJeqfrHXok9Axhx6?2GAK$iIOHR^Rtw+e$^Cm6kx;nkOrt#D=^M2t7Mi8Ko zx8|gXp2%_a<2<1!$bB9=_vuZUDQ2K+xU=0vZc+h)+2j9xaIq4Ab0%a>oNtXW1?7x( zVIsvs01A=`%@QbZ%(F867Tg0?%a8ybj72y7#Zm2)R!q)uksBf|u{an6he`mD5K~xC zF%ZhQNW@W6bE!g=qqPBw0bP2av{2^;=!Iao{QvPXdM%Yy2NN%xF8SQoy#D`u)HQ5` z703f2LmXV8Jc^+JrfGOYKT>Id*vhmhq61qc?wvi|oKAl;zw!KXb~7y20Nl^zu<#6gx$Jy6E8_wT0W{n;~L7%3rjj5uw(X_Os7)&4HN8delo4J=0 zO9>_`H$J2B@&A5kuRCUC!(n9<8g=xlbTK_H61EbVy;A>LU;fQ@+s2ry(e3j@T0%aK z4&0lT)q~sFb6K0jeXo%4y=R&-!faW4h)2GgqfDb)yO~CB0-zXxpo7We8nTAtuA?xi zf?F~wgqqNKIkqiwL&5h&GXO>k&N8S)5L>iVwX3Re@>N~`m$bZXJQnm~FGYFrhRL3+ zBlMVGTR|(`4&_lSBvJo5pH@$+@filurlifaWC$Sh*kLmqcgMxn@$|dPT$W8UjtI*h zAqH|c?Dd`3`AA*WSjsg&q4+d%W%w-m+yaj{YJ~wr~&0xrky#PEQR78 zO@{(tHWIM4xvkY`o|cS?g{ati7lX2D8L8BH+j-iwuz$=o_UM*M3Yj$r;I?o4^auD+ zf~6}VP%%U?TsCZ^Fca~>tC1kVg#kD^r)wp3^E8iqwHDvx7@-yP5)=wdq^mZqZR^Zo z3ZGGw_MKQ$w7icBfwz4LvAoyZ$1ri|UeXBz18W%+Z~#z`rbVlh5B;`Jz8|V(yA~*@ zL78F@i30?v1`Yt%Yt%anD=4Z~qXfoMUHH5C^2j+JKMu=O=8BR)Wh}C9r@OkgZjTo~ zel2OkaTxcg&6*anrsB@_c>UMfah@ixA+om9&yK$H{GE;K zi_)y5BEfSwjvy#kQ%i-NI0`GZU@56?iGn34AZ6EjZ^3(&4kwdSUl`|Qr73G(dJvOD znfEHDs^=}^Zo}Cqn$*d*hIUs``rSjVjI?aV>!qzWKDy%|kcCzJ zn!`c2|GcmM!08U_v^z>7N}ddwjJ5)b*9rqul5hE2aV40_>_kA6^Dgxq7X9b@)1xom zTYXyV#hQlQbd#>n!|7hHy&G5Eo#G_OZP>@L`KT}8^;V3h-eJriE@`cgz3@N2TL+)E zht`*6o_~MMEqRUHmho71IY)1O7R3_M5wayaV>--|Bwk6-b~}~S!I1J$z=)(tF)W>l zmr))v`ozfSJUD0T z7Er&tS>2UrIi<>tLCIcEj{zu~dru-2wiHoh_Ey&G$SJ9(b(|k|&T_hqta*gGF1>gA z?O%U&^zp^o9m_X1dqN7cVSHfaP}L)CHPTzN^j2$5uGO{6W6o@`LekVdF){!+)M|hn zX~ll)aVy6;xyaJvcBX`G=5nQDsKgM#Xa^&Vor&3xlchqMkq%Z3yV zOhVI$$Gj}3?3sEbzDTZ-%LoEg*>T_?OX-+4q*)QZZ%7Skwg`3-eMN^_;n8Dp8XETj z)A8k`e;Sgdu6^g*um8=*o8QKj!-9wLkv}>7hI{3&j}L!(^KjqV+%*(I2{l6^5)h&o zH3KKo;%O7;^0jQQIZZieFc#zpdw~KParx*ikvl#eMWGJQX?0XM2JU8=)>_{sHN^^SV9NeD!6pGS3KF&%EycBeFh;1tT$t~3@OcSLB->`;=p ze16Vkvf5^%PMb08YW_INj%coynFMD>!68WB98nK+Yx$~Pf8CE6?B7%y8rqGEwb-31enl)Qt zl|^c4XFDyXrWXaRr&1@p4CIPA~o z3*Wy9dZBV@Q>|s~exJS5F57Tl8Klw08QJL%-~8Yy_g}_`r?K`$&l>Gq^c2&T zyOs2`!gIT`dhHLtFJ-Il(L}}}DR@NAlrWI7jZKW@A{~>{w7P4*tZXh@#%9x&#M7`w zD@76ELn%F|OBe?cr?ZTnTh(Nt5CoLBz>r}nkpn&#Fty?$(_BWF1a;tc&jcT*g=ZoC znx;;|S~-;x*5g|vG<_2pPBJfaal*6f(HERfQN^7e!XXX+vPXe-fQZ3tg=|UY_i7rJ&Rk&357l$MV z0)Xh?lnUU>$F%ExUc0!)h-@3g4q3Pub_sLjPlo(fsYT^jG zFz&2P46~X%_nsxB5O5oNgJ~2xAQ!S!2nhiaO&u?hh-+6OH3>UF07-$XW}`aQ0QJ14 z<>4ilWM6-nPUbytw;dCeG%gv^ITM797j8D3LY}^FtJ50KSDj|g^J0>ululq)+oKNI z8l*AtCX`5SDc9JML?ARIL>?r9o5h7maRW-`>1~^t$?X%SYYa4Xm;fUH#>ex8_0v!( z)x~U0s&yqKh3vq4wj*RS9jzKR-yhQ1N0)E^~M*^3QQ)gfINm`uBHGuTP)kN zMGPg=h~yAqIuiJ1C$WkfegGb4pvf5kBn0xt=B;EAsT}{r;kFU#F`+ zZcB@qr#808t73w;GD~a-Ou%}3fAvr9um0Za^~!?QS@b)N=kwGf~O6g;h{tU9uoz;Q|M9o~$SL0}+#@;W3%gm4gWdT_8hH+6@# zXICzL9CJi+26?YRq85QLB{E-e|9=Obe=g0E{LAM*xJAFA+#KEMCQ>6@9+DUleBY>u05)?rd_z=y7XUX)4U^yG#SK)mJPj}^K#kxkf zdHtOGDY9k@1*GoC5UL7-+9ysiy+3*2-wmHm(X7xjljWA-_RrJUl@qoeJhax`+Ow(> zs8mD`)H1tXbF)`Ml23i z=hOM9ce)|BSnNYcq6C{Xo7t3ED!|Tr`nn(PlV|{ItZqw;*x_!E>+^O`>fw<26=<^z zAz=ZNSQLrsAUMGa%nSsOz*0I)^@tYNb1UgbF89HecsWrb&Hw=qm$Zik987kMIKr5i z4Mq(|D8zZr7-47!Qg3s6P^OkuuUZzj5FIN`QK*%y1>v!TVtC zuRhjCFqlIFQCb1+BHZ>!JcN`aML?k_4Gbj4ZvU^oe%Es>S>-zBWUh<5hmw;}hCJiy z3^oo+un%cUAZ~&Xg<_$($sc`#Z~d-*_M3s*a)UbenIKtQxgxQo^SO)lm2qf1Q3TCq z$xDzRvrDlE3kfHRK+6n6-(C6mF3wL0r756t z%|TQI5y?arGyA?YgK4C39G+>nN`x$PgAZ$pU~5zE(V>1}KGV z49*}H$=EVyM!u}N47a;fud@%NcxMih@Q~p`^CTxC&{|uTxp|p$)Wd6nnup#*9qqjv z(>j;Vb4Tl`)KH}S!pIn+=2~kU5J*D>hZ?hH6YA zk#bZhZl%MPGGXTeAgcNYEEFIL#3(IcL`vL%BABi6+T#h0PD1FVB7+i1XcA;1h019s zM`}}^-(C5|SGTgwfWwEP)0I7*hcPRdBoq8DhDlT3f)}9Pt3joKYmi zdY0?`_UgI(1Hu=jPtNLCL_+Lh5nJ^D^m_g}_OuaoSE_#08ls4y8hRnhF=?+2^E_|q z7cJfDQKH7;nivuY0f!2VId+cq{#l*$%*Rd2!=>dmUjsc)WYP%EgTw>_;g(5|hK0K< zX+Y(WVrA5!6dBP4PPS+k2m+3%TxUO=i!N)}^Z|n%TzO>XJVFS;yTFy(?c6tC ziqrlwdn<7M#(GBC0hQn~TY7xU?*eHCaF~;&$T`@aj*gsFl?sQBkY_QSxSjrTVNxH5C z<)WYj%(9Mgg295aQ-XfL`ZH?9Z7SFY7Bq=UAW=-Fq7!{k6ciVd&W_rj zG?A?~#fm`=q6i!z3ownteOT5AI6_~WouTgAO@N!Dp|41%L963sFZsCpI`*|8 zuBPswtrYF|p@cQ@Z0mKpK7PzU%-RAIF6W?YaNVkp z2YN?xmMi#DzySal1BhuT3`cgI$1YXCyw2<6^LE|W*Jg`9&3dDcaJ#ey_qO%)pY!u8 z?yekKi&^vQ2e8*s$`uD$+X4P5{m0nW<$;l>dfdR;@hFrRh)0=qgc_70F+%mf@6&4GT6PWd(Nm59V zW#`ek_C<01!yrE*X=0I!b7P7fllc272f8#=GQl@46DkjdgZapG~BAR*tTm~ z0#E=!o}OOB4=CLZD<{R6fhDVeERc#_via#ANymz zzNIz0!WrcmA!WZbk8f_uhjO2L|7d;5T_tMhD1VGWnDFY2YGQWas5-T&^xBVv%(e>gY;X*Uzo{&Hn#x-fDB5a&*0{T^B3i z{qTCiI1+3Tyt#jR&iLRZA?y)hLbN02FMobN;NVD&9C9M_Fyo&ZU<-?M%`8sDD1yBl zKRd5~srBqHy6$vC6@!PVp#(jbY}Nz&D}J{2 zt>NY_AD=dRS?gSRx4>V-?R8` zD1*CWW8Yg1i4`~|z-!@{Q7Ah}yT{5j(O(7g%vRMlU zWxq_Wf!!ey2*^ECmvy@5mZba7oRhnw+-5ccYqC_zP|7GL;YLNEyW~B&%8Wn=M?@Fe z4Ttm);Q#|L5CS>RXMLR9%6IeQ22JCgb6}){=GGOXTQdUG(g7!=i}Ar%UiHrZ^-6V; z2Ys21I)noN9T7}AstLrWOSDe?#s5+ZAB%`~2Ls%kj0Wg9fzrbd#|zWtiCg`UVH-sZ z?qd0sggC!4{Ih==n_zBD?r4b%+)y+z=c90t5z`d~jbIYZJ?I^KsQZ z2v`ujgJ#3EN1o2p+gK`bG&2GP*!#5v=ZfSR5u4gQSJ)^c3?@JU0TZn-N5rDp=)7{a zzIy2iX%#|N6~kkCj)q495r{wqs)fBzGYSCqs$5W3W4sOrL=vpjZ7%5u0j#oNxQGnO z8#|tkEwhIcqYQMn0~vx4076kkEcA-AqxO6;#fRAfq6c?@1AvnN#w(c{hNffIqPqKi zWuDB7KeFLz>zrSz#>ofH?&bC|)umT0or;7|riwF#N*SA8#%30TP{3*@ku3}zkao=u z*GXzoA8AO1nc^7H5U=a+!FFV04Q4R(#HIh6PFZgF!k+3i^?U@f({6B~0tI$(n`7cQ z*{%0d&(50n75adfsjW>(C7okN#u?KTCdhz<^jK;wmvIH&6@YW&k;X(J^>Xg1A~<>B zri~9Il3tV4A>!GX>q?uFT#yn16d)WxB|;+r zKpMvqwIl0?V{xb$hCig*>E3XQ-ioRAL54v4Sc4RehX zP`vP@@7}lb!bD0UCf;JHDn_NDmy{eagelP`s~9v)lQjlwt-H+jERJBuu@p%lhNM*l zrH^J%81`pYS>ch+se}>r&=EC4uiE?R^SO3^%PUXs7Pg2)Sm2CCPQ23Qukj>Kn8?85 z2z*ToW6cy=Z*H9DRR!FzvherU!>F)aYL7zW@0b_1#E=xHy38|VNqlquavNlPY| z5wfvzl*N{m<=W)#r8`!@?r4fw@!9TfImVIZZOar^Km{xZMuiAO2ppkttrMl9wo&D* zj_|<_hbkE08g#0qd5Y=@k=eNcno03+MosyrDde_$WDrhpn@!Gea$)l2&piz($3pin1z1af}p{o(d=3oEy}g%B9aS4rGWS z0|}|^>(tFLGegKW$;~h^F#EBS;vSR^+tj*q!;zQ-X}H)Y4H1P&#J^Z3+lXzT!VMF7`75dewknYS84N(zYr<;5+j zoqUvNh)|f?EdnGl%-*1~@kE6uErSw7WZ=;Pq$75KuwN=%6*I)8q$_Ha;dxu;Cy*-v zfROcA_s9|9q?vmQz8J@P$Nav=xl$Npj$%|g8y`5`8WJZ$r&5J#DS$n2y;OHk+c2W+ zqwEu4AOV^#bJM*Jepjc&oSdpDUWfoc}BS z30XqPgz@B)gZIL#dC}Cu_YjuB7F5YVF&P3W3lsowvVxQDG!6*%5;Xy%YaE;|6k=9@ zQYqnqZKG&4y0ZH4U;YyHyYBVHAN~3t$7(-e+M&*`MS~29CZEw%qXI$UY<2yi1iA}BPuXIvV#!p5f~BJu!yCP*E`PKFH>8c_jhD+AovGnm~OMqwcCpfbXVE5V5!LWzUa zNXPTz`@P>Ygb4v40L@z6{hBrN#5C$Ws@zMKffbF6%B>ldS^@+DYy@`yRGND-LP2fq04(KqCUU*;Ons1(G=iI-NDK!GQg@<3g$ zb0r<+=`x5KV5E-5iFDwoaFA&^J84fe)-8nd^`4JMxF19~NC{A7<6_e^D-7HF)QG%B zAp{B(IafL*E9`&D@eW}NEK_Dp^2jw~q09c|LhOJ303kf^(mSI@Jn*%mw(Y$io zQJ$rF(Z~apEXACLRvU4yH~@wK01SZG0D95pw)uYZeXh(+Ur(?sHKkfMAdzM>0Z|OD z^REV)X%{?4fso`&Pj6sNE}qL^%N{%icZV{1yRrS*p>-mh^yrTJx*pN2_!1(gfxg;4 z52XJv`~NI`6k5(p5 z8{g&$NdrtUz(}e=ktah>=g0!rBlT$uH|tR{g-4U8Q?I%ESnc#IWjG2Y1G)loh!~(y z%em5b695s_;*_vf~FXa$bW6L&VDlOgP3RE7wF zIKwE;Tmw8_A>quu?fT&s^5bycSC02CRTjj8Fflj^1=?P_9Rq*^ZrXAKK9-&Z+R3=cGW7Ep=rK;}fi`!qmuU}iZ9t%d)VwdU0<(Z=( zn7IS$0-$)n0qXwMj*|tF00;meF2H=#_$ZKZAHbY2Ldxhmj@8rm+C@vAUpsG z6XvwowD<&MYv38P0bph8q^o2p42V=(0SJ%xzrXDI5-CBc0)YrRgw|ptwH3k}TeQ}S z*CG4Tas8hMFcvKYNT7r~yU!N-7KgoHocP=$j`Y%9ih1roe*Wvx>&a3_YYkflq5SfE zscwS7mI#yztC?=b8|U+P&-dqsHg2DqbUDmba<|9t-haQZU)nE-K1<(X=LNZd2o{rx zK_JU<5VbG6!ajfB=)`^=-s|M)zOy_hb!+>uB1`S!5IQsn3ZV2}`5YzZY|-r!73T-v zPx9Y)y=C>8I)^KgU-=?wki-A}9&D@&C)pwhFN1SGB*2PZIg65F=6gDg@phkvY+v^q z*ZU8yk2gPmzNL@*b*{>nul=7Nzy9C%7dZ^qAh<#rq~cs%s2fQdcO)tW3wk~>P9IPA z5Y%RW*i;Gk&H2;hhDNY9CRCgv;~ahhCV>t4D4V-)^LKEVg{G5m|~ zQhAGZ-P66^sIoF}JG2JBYX8}y_s-BmU!PsjvG-f)7qjQ!g3^Hy<)ebpyo;gom%=%q zjBq_k#$W&qQ9!6@-DK;5&`?lmfxsdhexE~^ZA?@xZbU0k33{eR!3)KNi$l4XE` zA>o?(Uw{rdoFB=DpacMW16O$)*h6TsQql8pV4duN#DW2c4SrEf2+gD)@Vte`fLge> zC5GmamcroxU?0SmI06I(CC!`&!CUlj0n)nWl|qh4Jq0;9QY)R7s35?pE9`{WWLB^% zimhf*|6oFbh#-1c(zK`K1ZkO~F^hjC*tg=u-$ znrYjKJR75#rbal1IvN24&q8z{MeE|g1LUwvBtW1-cwG^BH>;&9@7qP5AOPG;ixdF+ zbk-9OI$_YL8wx;GArJsSkU=7$2;g*(Fa-8ZX(>?>ppiCIz;!4PW{Nf`iM-&~n&8?6 z-(@vUrUL{7fCL4C08qd*JUYI4z;B~xW`+k(i9(<@pd1y5E+pGQfWYB3%-9H(hSmNE z5-Mk?6exjE1tgtRfS%Ass0b7XNb<^@SHeoZCK77010jHB1c(AS02~3JE85w@%ifd+ zx=#iJf*r~eRv5Oid3bYU3V0!)Rj_0t2M4D&g-DD*0EHuga|^IAV76ctO}qj zvs<)$nsMo3pqLg1Y4crodh-GXw+?;SEZ(%-`O_h~9*5O63p&p1)UJr z0IJeL*%)L=e|a1HX5KDXltTIj5y*t?6uS?(iW%V=Ju_tI#kyL}(0Td3My;xuJ9#8$fZU zsyEp>PBP&}yNx{%lc2JatizQ=49WW6_aJ6jBw719nJ^9=nB?PPDd(mUjj}PNE0Qt{ z48JBDe`iJn8v;Za%Mm&`@X@LCPg*ETEE{WMq{lRNC+$#T)E7@CVdVx8_6%FZlQk&+ za|*J_Exs{_4`RHAb^Jvl=6-HMPj6&)!WWQYz zO}0eHQ`{7zG1xmIkPc9?6HGTXj{MXb#@1Ju`|J>9Ot-oED);#vrot2lf{-UXg({5A z5<~`xZ;a?X_j?DA2oEe6yPZ#2(nGLY>GPXX9DxR1|2ETuxL6Rj@va6S)=CedN9s2I zOFm*b`98js1p}+nNnsu(Q(g|Po&of+w8KX7dZ?1TbcKJWkqH)8a;@I~=|6pv8LI-Gbq(c9S@d?L)%KJ@wtP^G_# zWs(gLG$a(!-O~j=EIY&oB^E}8I64x5L12jy!3OxIHPr5aK{w7?5?Il@IR&?l<0hKA z)s!z&WuUV71dm`3t3{a6Ra%Sgg2F*S$wEGdK0fZ_^QGhL>HBPvaGY>y4n;4Z0T&2o znzXYH^;dmVd{Qn(BpQewF2P4of9e=-1%lou5!lUsiw_eJn0(^^mZIf=&_n|%v^TA3 z_R=AEJ$U5Wzaabk(b}v?`d1hp=O@yeo=hX0PEO>EUeh#Qzea$X!J-kx9*lEpm_-W& zwGnUuCI;$j)van64-GVJWD|i^ieP~KMCtMSA_g`x!Hf%k-*XOKVKIF>+o#+;bn6aj zb>ocs~BuS^v4{U&j*XU%U%#F&?{^dIp zL!*KHc1o=hTX0AqaLtVohZCD|fD1Of4$blV+*c6u88ja-f&iPJeeT*=+{oH2dzvij lw=mkdM$1S7J~>mL2(Z%Iqp&1txs}ewolY { @@ -160,7 +161,7 @@ export default function StepAttachments({ {upload.isPending ? "Uploadingโ€ฆ" : "Drag files here or click to upload"} - Sent with every email from this step, and no other step. + PDF, DOCX, XLSX, PPTX, text, raster images or ZIP. Up to 15 MB per file. From fdd9a1fb3333c14fb30df0df61c11c4b8d138aab Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 20:23:48 +0100 Subject: [PATCH 171/318] feat: record bounded peer alert and ClientHello evidence in the origin TLS diagnostic while omitting session secrets --- .github/scripts/aws-origin-tls.test.cjs | 21 +++- .github/scripts/origin-tls-client.cjs | 46 ++++++- .github/scripts/origin-tls-client.fixture.cjs | 15 +++ .github/scripts/origin-tls-client.test.cjs | 114 +++++++++++++++++- deploy/terraform/aws/runtime/README.md | 7 ++ 5 files changed, 195 insertions(+), 8 deletions(-) create mode 100644 .github/scripts/origin-tls-client.fixture.cjs diff --git a/.github/scripts/aws-origin-tls.test.cjs b/.github/scripts/aws-origin-tls.test.cjs index 2dd487017..7d3c2e4ed 100644 --- a/.github/scripts/aws-origin-tls.test.cjs +++ b/.github/scripts/aws-origin-tls.test.cjs @@ -7,6 +7,7 @@ const { join } = require("node:path"); const { ACCOUNT, BUCKET, ROLE, LB, LISTENER, DESIRED } = require("./aws-origin-alb.cjs"); const { configuration, sessionPolicy, discover, definition, execute, finish, verifiedLogs, IMAGE, CLUSTER, SERVICE, EXECUTION, SG, ALB_SG, VPC, ECS, LOG } = require("./aws-origin-tls.cjs"); const { probe, CBC, TLS13 } = require("./origin-tls-client.cjs"); +const { refused } = require("./origin-tls-client.fixture.cjs"); const scaledTargets = ["10.42.0.85", "10.42.1.12", "10.42.0.86", "10.42.1.13"]; @@ -17,7 +18,7 @@ function logFixture(targets = ["10.42.0.85", "10.42.1.12"]) { if (args[0] === "ciphers") return { status: 0, stdout: CBC.join(":") }; const cipher = args.at(-1); return { command: ["openssl", ...args], ...(CBC.includes(cipher) ? - { status: 1, stdout: "New, (NONE), Cipher is (NONE)", stderr: "sslv3 alert handshake failure" } : + refused(cipher) : { status: 0, stdout: `-----BEGIN CERTIFICATE-----\nfixture\nNew, ${cipher === TLS13 ? "TLSv1.3" : "TLSv1.2"}, Cipher is ${cipher}\nVerify return code: 0 (ok)`, stderr: "" }) }; }, (row) => events.push({ message: JSON.stringify(row) })); return events; @@ -448,6 +449,24 @@ test("missing or truncated raw handshake logs cannot be rescued by a successful assert.equal(verifiedLogs(logs, targets), false); }); +test("private archive verification reclassifies ambiguous or altered negative evidence", () => { + const targets = ["10.42.0.85", "10.42.1.12"]; + for (const alter of [ + (r) => { r.stdout = "CONNECTED\nclosed\nno peer certificate available\nNew, (NONE), Cipher is (NONE)\n"; r.status = 0; }, + (r) => { r.stdout = r.stdout.replace("<<<", ">>>"); }, + (r) => { r.stdout = r.stdout.replace("02 28", "01 00"); }, + (r) => { r.stdout = r.stdout.replace("c0 27", "c0 2f"); }, + ]) { + const logs = logFixture(); + const index = logs.findIndex((e) => JSON.parse(e.message).negative); + const row = JSON.parse(logs[index].message); + alter(row); + assert.equal(row.outcome, "refused"); + logs[index].message = JSON.stringify(row); + assert.equal(verifiedLogs(logs, targets), false); + } +}); + test("delayed log delivery is retried within a fixed page budget before verification", async (t) => { let reads = 0; const f = fixture(t, (action, result) => { if (action === "get-log-events" && ++reads <= 2) result.events = []; }); diff --git a/.github/scripts/origin-tls-client.cjs b/.github/scripts/origin-tls-client.cjs index 63399bbe6..93419c516 100644 --- a/.github/scripts/origin-tls-client.cjs +++ b/.github/scripts/origin-tls-client.cjs @@ -9,12 +9,46 @@ const TLS13 = "TLS_AES_128_GCM_SHA256"; const validTargets = (targets) => Array.isArray(targets) && targets.length >= 2 && new Set(targets).size === targets.length && targets.every((ip) => typeof ip === "string" && /^10\.42\.(?:0|1)\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4])$/.test(ip)); +function sanitize(output) { + let session = false; + let ticket = false; + return output.split("\n").filter((line) => { + if (/^SSL-Session:/.test(line)) session = true; + if (/^---$/.test(line)) session = false; + if (/^(?:>>>|<<<) /.test(line)) ticket = /, NewSessionTicket$/.test(line); + if (ticket && (/^(?:>>>|<<<) .*NewSessionTicket$/.test(line) || /^\s+(?:[a-f\d]{2}\s*)+$/i.test(line))) return false; + return !session || /^\s*Verify return code:/.test(line); + }).join("\n"); +} + function invoke(args, spawn = spawnSync) { const result = spawn("openssl", args, { encoding: "utf8", input: "", timeout: 12000, killSignal: "SIGKILL", maxBuffer: 128 * 1024 }); return { at: new Date().toISOString(), command: ["openssl", ...args], status: result.status, signal: result.signal || null, error: result.error?.code || null, - stdout: result.stdout || "", stderr: result.stderr || "" }; + stdout: sanitize(result.stdout || ""), stderr: sanitize(result.stderr || "") }; +} + +function peerRefusal(output, cipher) { + const messages = [...output.matchAll(/^(>>>|<<<) TLS[^\n]*, (Handshake|Alert) \[length ([a-f\d]+)\], ([^\n]+)\n((?:[ \t]+(?:[a-f\d]{2}[ \t]*)+\n)+)/gmi)]; + if (messages.length !== 2) return false; + const [hello, alert] = messages; + const bytes = (message) => Buffer.from(message[5].replace(/\s/g, ""), "hex"); + const sent = bytes(hello); + const received = bytes(alert); + if (hello[1] !== ">>>" || hello[2] !== "Handshake" || hello[4] !== "ClientHello" || + sent.length !== parseInt(hello[3], 16) || sent.length < 41 || sent[0] !== 1 || + sent.readUIntBE(1, 3) !== sent.length - 4 || sent.readUInt16BE(4) !== 0x0303) return false; + const offset = 39 + sent[38]; + if (offset + 2 > sent.length) return false; + const length = sent.readUInt16BE(offset); + const offers = sent.subarray(offset + 2, offset + 2 + length).toString("hex"); + const intended = { [CBC[0]]: "c027", [CBC[1]]: "c028" }[cipher]; + // The sole negotiable suite may be followed by the renegotiation signalling value. + return intended && length >= 2 && offset + 2 + length < sent.length && + (offers === intended || offers === intended + "00ff") && + alert[1] === "<<<" && alert[2] === "Alert" && alert[4] === "fatal handshake_failure" && + parseInt(alert[3], 16) === 2 && received.equals(Buffer.from([2, 40])); } function classify(result, version, cipher, negative = false) { @@ -22,10 +56,11 @@ function classify(result, version, cipher, negative = false) { const output = result.stdout + result.stderr; const negotiated = /New, (TLSv1\.[23]), Cipher is ([^\s]+)/.exec(output); if (negative) { - if (/certificate verify failed|Verification error|verify error|no cipher match/i.test(output)) return "inconclusive"; + if (/certificate verify failed|Verification error|verify error|no cipher match|unexpected eof|reset by peer|connect:errno/i.test(output)) return "inconclusive"; if (negotiated && negotiated[2] !== "(NONE)" && negotiated[2] !== "0000") return "accepted"; - return result.status !== 0 && /(?:sslv3|tlsv1) alert handshake failure|SSL alert number 40/i.test(output) && - /Cipher (?:is|:) (?:\(NONE\)|0000)/.test(output) ? "refused" : "inconclusive"; + return result.status === 1 && peerRefusal(result.stdout || "", cipher) && + !/-----BEGIN CERTIFICATE-----/.test(output) && /no peer certificate available/.test(output) && + /New, \(NONE\), Cipher is \(NONE\)/.test(output) ? "refused" : "inconclusive"; } return result.status === 0 && negotiated?.[1] === version && negotiated[2] === cipher && /Verify return code: 0 \(ok\)/.test(output) && /-----BEGIN CERTIFICATE-----/.test(output) ? "trusted" : "inconclusive"; @@ -51,7 +86,8 @@ function probe(targets, run = invoke, emit = (row) => console.log(JSON.stringify const handshake = (cipher, negative = false) => { const tls13 = cipher === TLS13; const result = bounded(["s_client", "-connect", `${ip}:443`, "-servername", HOST, "-verify_hostname", HOST, - "-verify_return_error", "-CAfile", CA, "-showcerts", tls13 ? "-tls1_3" : "-tls1_2", + "-verify_return_error", "-CAfile", CA, "-showcerts", "-no_ticket", + ...(negative ? ["-ign_eof", "-state", "-msg"] : []), tls13 ? "-tls1_3" : "-tls1_2", tls13 ? "-ciphersuites" : "-cipher", cipher]); const outcome = classify(result, tls13 ? "TLSv1.3" : "TLSv1.2", cipher, negative); emit({ kind: "handshake", ip, cipher, negative, outcome, ...result }); diff --git a/.github/scripts/origin-tls-client.fixture.cjs b/.github/scripts/origin-tls-client.fixture.cjs new file mode 100644 index 000000000..41867387c --- /dev/null +++ b/.github/scripts/origin-tls-client.fixture.cjs @@ -0,0 +1,15 @@ +const { CBC } = require("./origin-tls-client.cjs"); + +function refused(cipher = CBC[0]) { + const suite = cipher === CBC[0] ? "c0 27" : "c0 28"; + const hello = `01 00 00 2b 03 03 ${"00 ".repeat(32)}00 00 04 ${suite} 00 ff 01 00`; + return { status: 1, stdout: `>>> TLS 1.2, Handshake [length 002f], ClientHello + ${hello} +<<< TLS 1.2, Alert [length 0002], fatal handshake_failure + 02 28 +no peer certificate available +New, (NONE), Cipher is (NONE) +`, stderr: "SSL_connect:SSLv3/TLS write client hello\nSSL3 alert read:fatal:handshake failure\n" }; +} + +module.exports = { refused }; diff --git a/.github/scripts/origin-tls-client.test.cjs b/.github/scripts/origin-tls-client.test.cjs index 1e0daa913..6c8387af0 100644 --- a/.github/scripts/origin-tls-client.test.cjs +++ b/.github/scripts/origin-tls-client.test.cjs @@ -1,8 +1,13 @@ const { test } = require("node:test"); const assert = require("node:assert/strict"); +const { spawnSync } = require("node:child_process"); +const { mkdtempSync, readFileSync, rmSync } = require("node:fs"); +const { tmpdir } = require("node:os"); +const { join } = require("node:path"); +const { Worker } = require("node:worker_threads"); const { CBC, GCM, TLS13, HOST, CA, invoke, classify, probe } = require("./origin-tls-client.cjs"); +const { refused } = require("./origin-tls-client.fixture.cjs"); const trusted = (cipher = GCM[0]) => ({ status: 0, stdout: `-----BEGIN CERTIFICATE-----\nfixture chain\n-----END CERTIFICATE-----\nNew, ${cipher === TLS13 ? "TLSv1.3" : "TLSv1.2"}, Cipher is ${cipher}\nVerify return code: 0 (ok)\n`, stderr: "" }); -const refused = () => ({ status: 1, stdout: "New, (NONE), Cipher is (NONE)\n", stderr: "error:0A000410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure: SSL alert number 40\n" }); test("positive proof requires exact negotiation, chain, verification and successful bounded execution", () => { assert.equal(classify(trusted(), "TLSv1.2", GCM[0]), "trusted"); @@ -36,7 +41,7 @@ function fixture(change = () => {}) { if (args[0] === "ciphers") return { status: 0, stdout: CBC.join(":"), stderr: "" }; handshakes++; const cipher = args.at(-1); - const result = { ...(CBC.includes(cipher) ? refused() : trusted(cipher)), command: ["openssl", ...args] }; + const result = { ...(CBC.includes(cipher) ? refused(cipher) : trusted(cipher)), command: ["openssl", ...args] }; change(result, handshakes); return result; }; @@ -58,6 +63,8 @@ test("every private target has fresh trusted positives around both explicit CBC } assert.ok(args.includes("-verify_return_error")); assert.ok(args.includes("-showcerts")); + assert.ok(args.includes("-no_ticket")); + for (const flag of ["-ign_eof", "-state", "-msg"]) assert.equal(args.includes(flag), row.negative); assert.ok(args.includes(row.cipher === TLS13 ? "-tls1_3" : "-tls1_2")); } } @@ -122,3 +129,106 @@ test("OpenSSL processes get empty stdin, a hard timeout, bounded output and no s assert.equal(result.error, "ETIMEDOUT"); assert.equal(result.signal, "SIGKILL"); }); + +test("negative proof binds inbound alert bytes to the sole transmitted CBC suite", () => { + for (const cipher of CBC) assert.equal(classify(refused(cipher), "TLSv1.2", cipher, true), "refused"); + for (const change of [ + (s) => s.replace("<<<", ">>>"), + (s) => s.replace("02 28", "01 00"), + (s) => s.replace("fatal handshake_failure", "warning close_notify"), + (s) => s.replace("c0 27", "c0 28"), + (s) => s.replace("c0 27", "c0 2f"), + (s) => s.replace("00 04 c0 27 00 ff", "00 04 c0 27 c0 2f"), + (s) => s.replace("length 002f", "length 0030"), + (s) => s.replace("01 00 00 2b", "01 00 00 2c"), + (s) => s.replace("New, (NONE)", "-----BEGIN CERTIFICATE-----\nNew, (NONE)"), + (s) => s.replace("no peer certificate available", ""), + (s) => s + "Connection reset by peer\n", + (s) => s + "unexpected eof while reading\n", + (s) => s + "<<< TLS 1.2, Handshake [length 0004], ServerHello\n 02 00 00 00\n", + (s) => s.replace(/>>>[\s\S]*?<<< /, "<<< "), + ]) assert.equal(classify({ ...refused(), stdout: change(refused().stdout) }, "TLSv1.2", CBC[0], true), "inconclusive"); + for (const status of [0, null, 2]) assert.equal(classify({ ...refused(), status }, "TLSv1.2", CBC[0], true), "inconclusive"); + for (const stdout of ["CONNECTED\nclosed\nno peer certificate available\nNew, (NONE), Cipher is (NONE)\n", + "SSL handshake has read 7 bytes\nNew, (NONE), Cipher is (NONE)\n"]) { + assert.equal(classify({ status: 0, stdout, stderr: "" }, "TLSv1.2", CBC[0], true), "inconclusive"); + } +}); + +test("archived output retains certificate and refusal evidence without session secrets or ticket bodies", () => { + const proof = trusted().stdout + refused().stdout; + const session = "SSL-Session:\n Protocol : TLSv1.2\n Master-Key: SECRET_KEY\n Resumption PSK: SECRET_PSK\n TLS session ticket:\n 0000 - ab cd ef ...\n Verify return code: 0 (ok)\n---\n"; + const ticket = "<<< TLS 1.2, Handshake [length 0004], NewSessionTicket\n 04 00 00 00\n"; + const result = invoke(["version"], () => ({ status: 0, stdout: proof + session + ticket + refused().stdout, stderr: session })); + assert.ok(result.stdout.includes(proof)); + assert.ok(result.stdout.includes("Verify return code: 0 (ok)")); + assert.ok(result.stdout.endsWith(refused().stdout)); + assert.doesNotMatch(result.stdout + result.stderr, /SECRET|Master-Key|Resumption PSK|session ticket|NewSessionTicket|04 00 00 00|ab cd ef/); +}); + +test("loopback TLS and alert peers preserve strict refusal and trusted positive behavior", { timeout: 20000 }, async (t) => { + const dir = mkdtempSync(join(tmpdir(), "origin-tls-local-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const cert = join(dir, "cert.pem"); + const key = join(dir, "key.pem"); + const generated = spawnSync("openssl", ["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", key, + "-out", cert, "-days", "1", "-subj", "/CN=localhost", "-addext", "subjectAltName=DNS:localhost"], { timeout: 10000, encoding: "utf8" }); + assert.equal(generated.status, 0, generated.stderr); + const f = fixture(); + probe(["10.42.0.85", "10.42.1.12"], f.run, (row) => f.rows.push(row)); + for (const mode of ["tls", "fatal", "close_notify", "eof", "reset", "silent"]) { + await t.test(mode, async () => { + const worker = new Worker(` + const { parentPort, workerData: d } = require("node:worker_threads"); + const net = require("node:net"); + const tls = require("node:tls"); + const server = d.mode === "tls" ? tls.createServer({ key: d.key, cert: d.cert, + minVersion: "TLSv1.2", maxVersion: "TLSv1.2", ciphers: d.cipher }, (s) => s.end()) : net.createServer((s) => { + let input = Buffer.alloc(0); + s.on("error", () => {}); + s.on("data", (b) => { + input = Buffer.concat([input, b]); + if (input.length < 5 || input.length < 5 + input.readUInt16BE(3)) return; + if (d.mode === "silent") return; + if (d.mode === "reset") { s.resetAndDestroy(); return; } + setTimeout(() => s.end(d.mode === "eof" ? Buffer.alloc(0) : + Buffer.from([21, 3, 3, 0, 2, ...(d.mode === "fatal" ? [2, 40] : [1, 0])])), 50); + }); + }); + server.on("tlsClientError", () => {}); + server.listen(0, "127.0.0.1", () => parentPort.postMessage(server.address().port)); + `, { eval: true, workerData: { mode, key: readFileSync(key), cert: readFileSync(cert), cipher: GCM[0] } }); + try { + const port = await new Promise((resolve, reject) => { worker.once("message", resolve); worker.once("error", reject); }); + const localArgs = (cipher) => { + const args = f.rows.find((r) => r.kind === "handshake" && r.cipher === cipher).command.slice(1); + for (const [flag, value] of [["-connect", `127.0.0.1:${port}`], ["-servername", "localhost"], + ["-verify_hostname", "localhost"], ["-CAfile", cert]]) args[args.indexOf(flag) + 1] = value; + return args; + }; + for (const cipher of CBC) { + const result = invoke(localArgs(cipher), (command, args, options) => spawnSync(command, args, + { ...options, timeout: mode === "silent" ? 300 : options.timeout })); + assert.equal(classify(result, "TLSv1.2", cipher, true), ["tls", "fatal"].includes(mode) ? "refused" : "inconclusive", + JSON.stringify(result)); + if (mode === "close_notify") { + assert.match(result.stdout, /<<< TLS 1.2, Alert \[length 0002\], warning close_notify\n\s+01 00/); + const summaryOnly = invoke(localArgs(cipher).filter((arg) => !["-ign_eof", "-state", "-msg"].includes(arg))); + assert.equal(summaryOnly.status, 0); + assert.match(summaryOnly.stdout, /SSL handshake has read 7 bytes/); + assert.equal(classify(summaryOnly, "TLSv1.2", cipher, true), "inconclusive"); + } + if (mode === "silent") assert.equal(result.error, "ETIMEDOUT"); + assert.doesNotMatch(result.stdout + result.stderr, /Master-Key|Resumption PSK|TLS session ticket:/); + } + if (mode === "tls") { + const positive = invoke(localArgs(GCM[0])); + assert.equal(classify(positive, "TLSv1.2", GCM[0]), "trusted", JSON.stringify(positive)); + const accepted = invoke([...localArgs(CBC[0]).slice(0, -1), GCM[0]]); + assert.equal(classify(accepted, "TLSv1.2", CBC[0], true), "accepted"); + assert.doesNotMatch(positive.stdout + positive.stderr + accepted.stdout + accepted.stderr, /Master-Key|Resumption PSK|TLS session ticket:/); + } + } finally { await worker.terminate(); } + }); + } +}); diff --git a/deploy/terraform/aws/runtime/README.md b/deploy/terraform/aws/runtime/README.md index accd2d84d..de7b09dbb 100644 --- a/deploy/terraform/aws/runtime/README.md +++ b/deploy/terraform/aws/runtime/README.md @@ -292,6 +292,13 @@ CBC-only TLS 1.2 offers, then fresh TLS 1.2 and TLS 1.3 positives. Only explicit peer handshake-failure alerts without a negotiated cipher, bracketed by those trusted positives, establish refusal. Timeout, reset alone, unavailable local ciphers, missing CA, certificate errors or incomplete evidence are inconclusive. +Negative offers ignore stdin EOF and retain bounded OpenSSL state and message +traces. Refusal requires the transmitted TLS 1.2 ClientHello to contain only the +intended CBC suite (plus optional renegotiation signalling) followed by an inbound +fatal `handshake_failure` alert with matching bytes, no certificate and no cipher. +`close_notify` and bare EOF remain inconclusive. Session summaries and ticket +message bodies are omitted from new logs; certificate and verification evidence +is retained, and session tickets are disabled in the client. The task sends TLS handshakes only, with empty stdin and no HTTP or authentication. Each OpenSSL process has a 12-second kill bound, and the container command has a From 377e42a58c6738377bbbb7bd1a6765cf2680be49 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 4 Nov 2026 20:27:44 +0100 Subject: [PATCH 172/318] feat: keep free warmup only for workspaces that exist today through subscriptions.keeps_free_warmup (migration 000352), give new unpaid workspaces a zero mailbox allowance with warmup off, send inbox review notices only to workspaces whose plan opens the inbox, and update the locked screen, allowance dialog, billing, site pricing and docs to drop the hosted free plan and recommend Warmbly Cloud over self-hosting for deliverability --- cmd/consumer/main.go | 1 + docs/content/docs/api/endpoints.mdx | 2 +- docs/content/docs/api/error-codes.mdx | 3 +- docs/content/docs/development/install.mdx | 2 +- docs/content/docs/guides/billing.mdx | 21 +++++---- docs/content/docs/guides/mailboxes.mdx | 7 +-- docs/content/docs/guides/warmbly-cloud.mdx | 2 +- docs/content/docs/guides/warmup.mdx | 7 +-- .../consumer/action_required_notify_test.go | 37 ++++++++++++++++ internal/app/consumer/event_new_email.go | 11 +++++ internal/app/consumer/service.go | 3 ++ internal/app/email/onboarding.go | 2 +- internal/app/feature/gate.go | 10 ++--- internal/app/feature/gate_tester_test.go | 4 +- internal/app/feature/gate_warmup_plan_test.go | 31 +++++++++++++ internal/app/instanceconfig/limits.go | 2 +- internal/app/organization/service.go | 4 +- internal/errx/common.go | 4 ++ .../000352_subscription_free_warmup.down.sql | 3 ++ .../000352_subscription_free_warmup.up.sql | 5 +++ internal/models/subscriptions.go | 17 ++++++-- internal/repository/pg_subscription.go | 3 +- site/src/components/CTA.astro | 4 +- site/src/components/FeatureGrid.astro | 2 +- site/src/components/Header.astro | 4 +- site/src/components/WarmupPoolNotice.astro | 10 ++--- .../components/scenes/brand/TabScene.astro | 2 +- .../{FreeScene.astro => CloudPoolScene.astro} | 11 +++-- site/src/pages/about.astro | 2 +- site/src/pages/analytics.astro | 2 +- site/src/pages/changelog.astro | 2 +- site/src/pages/crm.astro | 2 +- site/src/pages/deliverability.astro | 2 +- site/src/pages/faq.astro | 5 ++- site/src/pages/inbox.astro | 2 +- site/src/pages/index.astro | 18 ++++---- site/src/pages/integrations.astro | 4 +- site/src/pages/pricing.astro | 34 +++++++-------- site/src/pages/referral.astro | 2 +- site/src/pages/sending.astro | 2 +- site/src/pages/use-cases/agencies.astro | 4 +- site/src/pages/use-cases/founders.astro | 2 +- site/src/pages/use-cases/recruiters.astro | 2 +- site/src/pages/use-cases/sales.astro | 2 +- site/src/pages/warmup.astro | 6 +-- .../app/app/settings/billing/OverviewTab.tsx | 10 ++++- .../app/emails/MailboxAllowanceDialog.tsx | 20 ++++++--- web/src/components/app/tour/ProductTour.tsx | 4 +- .../layout/SubscriptionLockedScreen.tsx | 43 +++++++++++-------- web/src/hooks/useFeatureAccess.ts | 4 ++ .../models/app/subscription/Subscription.ts | 2 + web/src/lib/plans.ts | 4 +- 52 files changed, 267 insertions(+), 127 deletions(-) create mode 100644 internal/infrastructure/db/migrations/000352_subscription_free_warmup.down.sql create mode 100644 internal/infrastructure/db/migrations/000352_subscription_free_warmup.up.sql rename site/src/components/scenes/pricing/{FreeScene.astro => CloudPoolScene.astro} (80%) diff --git a/cmd/consumer/main.go b/cmd/consumer/main.go index 8fb3e5240..ea9fc7e68 100644 --- a/cmd/consumer/main.go +++ b/cmd/consumer/main.go @@ -580,6 +580,7 @@ func main() { AdminRepo: repository.NewAdminRepository(primaryDB.Pool), AssignmentService: workerAssignmentSvc, Notifier: notificationService, + UniboxAccess: feature.NewService(subscriptionRepoConsumer, planRepoConsumer), OpsNotifier: opsNotifierC, TaskRepo: taskRepo, CampaignRepo: campaignRepo, diff --git a/docs/content/docs/api/endpoints.mdx b/docs/content/docs/api/endpoints.mdx index 8b26689e6..68f4a3d87 100644 --- a/docs/content/docs/api/endpoints.mdx +++ b/docs/content/docs/api/endpoints.mdx @@ -275,7 +275,7 @@ The `/unibox/drafts` endpoints hold autosaved compose drafts, scoped to the call `POST /emails/:id/hold` keeps a mailbox out of campaign sending until `POST /emails/:id/release` puts it back; warmup is unaffected and the automatic rest logic never releases a hold. `release` is also the manual exit for a mailbox that is `resting` automatically. Both are bodyless and idempotent, so they take no `Idempotency-Key`. See [holding a mailbox yourself](/guides/mailboxes/#holding-a-mailbox-yourself). -`GET /emails/allowance` reports how many mailboxes the workspace holds (`used`), how many it may hold (`allowance`, `null` for unlimited), `remaining`, and the `basis` of the number: `fair_use` (the plan's daily sends divided by `sends_per_mailbox`), `plan`, `override` (an approved request), `free`, or `unlimited`. `pending_request` is the open limit-increase request for mailboxes, if any. Every connect path refuses with `mailbox_allowance_reached` once `remaining` is `0`. See [mailbox allowance](/guides/mailboxes/#mailbox-allowance). +`GET /emails/allowance` reports how many mailboxes the workspace holds (`used`), how many it may hold (`allowance`, `null` for unlimited), `remaining`, and the `basis` of the number: `fair_use` (the plan's daily sends divided by `sends_per_mailbox`), `plan`, `override` (an approved request), `free` (no paid plan: `0`, or `10` for a workspace that kept the earlier free plan), or `unlimited`. `pending_request` is the open limit-increase request for mailboxes, if any. Every connect path refuses with `mailbox_allowance_reached` once `remaining` is `0`. See [mailbox allowance](/guides/mailboxes/#mailbox-allowance). `GET /emails/:id/identity` reports which addresses the mailbox's provider will let it send as, which one it uses, and whether its signature was imported or written here; it contacts no provider. `POST /emails/:id/identity/refresh` re-reads that list from the provider and stores it, and with `import_signature` also replaces the stored signature with the one configured at the provider. Storing the list is what a `send_as_email` choice is validated against, so the refresh needs `WRITE_EMAILS` rather than `READ_EMAILS`; it takes no `Idempotency-Key` because it writes exactly what the provider currently says. Gmail only. See [sending identity](/guides/mailboxes/#sending-identity). diff --git a/docs/content/docs/api/error-codes.mdx b/docs/content/docs/api/error-codes.mdx index fec4a33bf..78c9ea241 100644 --- a/docs/content/docs/api/error-codes.mdx +++ b/docs/content/docs/api/error-codes.mdx @@ -1070,7 +1070,7 @@ Those request URLs answer `401` `unauthorized` to a request whose Slack signatur #### `mailbox_allowance_reached` -A `403` whose `code` is `mailbox_allowance_reached` comes from every path that connects a mailbox: `POST /emails/onboarding/oauth/start`, `POST /emails/onboarding/oauth/finish`, `POST /emails/onboarding/smtp-imap`, and per row inside `POST /emails/onboarding/smtp-imap/bulk`. A [mailbox import](/guides/mailbox-import/) does not answer it over HTTP: the rows past the allowance fail with the `cause` `allowance_reached` and can be retried once it is raised. It is not a permission problem: the workspace holds its whole [mailbox allowance](/guides/mailboxes/#mailbox-allowance), which on a paid plan is one mailbox for every send a day the plan includes, and `10` on a free workspace. Nothing was connected. +A `403` whose `code` is `mailbox_allowance_reached` comes from every path that connects a mailbox: `POST /emails/onboarding/oauth/start`, `POST /emails/onboarding/oauth/finish`, `POST /emails/onboarding/smtp-imap`, and per row inside `POST /emails/onboarding/smtp-imap/bulk`. A [mailbox import](/guides/mailbox-import/) does not answer it over HTTP: the rows past the allowance fail with the `cause` `allowance_reached` and can be retried once it is raised. It is not a permission problem: the workspace holds its whole [mailbox allowance](/guides/mailboxes/#mailbox-allowance), which on a paid plan is one mailbox for every send a day the plan includes, `0` on a workspace without a paid plan, and `10` on a workspace that kept the earlier free plan. On a workspace without a plan the message says a plan is needed to connect mailboxes. Nothing was connected. ```json { @@ -1083,6 +1083,7 @@ A `403` whose `code` is `mailbox_allowance_reached` comes from every path that c **How to fix:** - Read `GET /emails/allowance` first: `remaining` says how many connects will succeed, and `pending_request` whether an increase is already asked for +- Without a paid plan, choose one: every paid plan connects mailboxes - Submit a limit-increase request for `max_email_accounts` via `POST /organization/:orgId/limit-requests`, or move to a plan with more daily sends. An approved request raises the allowance immediately; retry the connect then - Reconnecting an existing mailbox never returns this code diff --git a/docs/content/docs/development/install.mdx b/docs/content/docs/development/install.mdx index 94b595922..24eaec374 100644 --- a/docs/content/docs/development/install.mdx +++ b/docs/content/docs/development/install.mdx @@ -18,7 +18,7 @@ curl -fsSL https://warmbly.com/install.sh | sh -s -- --wizard You do not have to remember the flag. A fresh install with a terminal in front of it and no hostname given asks whether to configure itself before it writes anything, because the alternative is an instance on `localhost`: a dashboard, a tracking host and an unsubscribe address that work from that machine and nowhere else, all of which end up inside campaign mail. Answer no and it says so plainly and carries on. `--assume-yes`, `--host`, `WARMBLY_HOST` and a re-run over an existing install all skip the question, because each of them already answered it. -Self-hosting is for experienced operators. Warmbly provides no support for self-hosted instances; the community helps on [Discord](https://dc.warmbly.com). Warmup between an instance's own mailboxes works but is not effective. For a warmup pool of thousands of real mailboxes, use Warmbly Cloud on [app.warmbly.com](https://app.warmbly.com), which means keeping those mailboxes in a hosted workspace: Warmbly Cloud no longer links new self-hosted instances. A new instance registers its own [Google and Microsoft OAuth apps](/development/deployment-guide/#connect-mailboxes) and serves its own [root redirects](/guides/sending-domains/#root-redirects). +Self-hosting is for experienced operators. Warmbly provides no support for self-hosted instances; the community helps on [Discord](https://dc.warmbly.com). Warmup between an instance's own mailboxes works but is not effective. For a warmup pool of thousands of real mailboxes, use Warmbly Cloud on [app.warmbly.com](https://app.warmbly.com), which means keeping those mailboxes in a hosted workspace on a paid plan: Warmbly Cloud no longer links new self-hosted instances. A new instance registers its own [Google and Microsoft OAuth apps](/development/deployment-guide/#connect-mailboxes) and serves its own [root redirects](/guides/sending-domains/#root-redirects). ## What it installs diff --git a/docs/content/docs/guides/billing.mdx b/docs/content/docs/guides/billing.mdx index 836517ec3..d40b4a7bc 100644 --- a/docs/content/docs/guides/billing.mdx +++ b/docs/content/docs/guides/billing.mdx @@ -3,7 +3,7 @@ title: Plans and billing description: How plans unlock features, how to upgrade from anywhere in the dashboard, and what changes when you switch. --- -Every hosted workspace starts free. A paid plan turns on sending from Warmbly Cloud, the unified inbox, contacts, the CRM, automations and integrations. +Signing up for a hosted workspace is free, and so is looking around the dashboard. Connecting and warming mailboxes needs a paid plan, which also turns on sending from Warmbly Cloud, the unified inbox, contacts, the CRM, automations and integrations. ![Settings > Billing: the plan card, usage against limits, and the subscription actions](/guides/billing.webp) @@ -33,18 +33,23 @@ With no subscription yet, finish in Stripe Checkout. An existing subscription sw ## Good to know -- The free workspace warms up to 10 mailboxes. +- A new workspace without a paid plan cannot connect or warm mailboxes. Paid plans start at $29 a month with unlimited mailboxes and unlimited warmup in the premium pool. +- A workspace that already had the free plan keeps it: up to 10 mailboxes warming in the free pool, no card and no time limit. - Annual billing is 20% off the monthly price. - Only the workspace owner can change the plan. -- Cancelling keeps the plan active until the end of the paid period, and the workspace keeps its mailboxes, warmup and settings. +- Cancelling keeps the plan active until the end of the paid period. The workspace keeps its mailboxes and settings after that, and warmup stops until it picks a plan again. - The Warmup plan is no longer sold. A workspace already on it keeps it while it stays subscribed. - Some plans, like the Partnership plan, are private and can be bought only once Warmbly has [offered them](#plans-offered-to-a-workspace) to your workspace. -## What the free workspace includes +## Without a paid plan -Every hosted workspace starts free. The free workspace warms up to 10 mailboxes connected on the cloud. Warmbly Cloud no longer links new self-hosted instances on any plan; a free workspace [linked earlier](/guides/warmbly-cloud/#free-workspaces-linked-earlier) keeps what it already enrolled but adds no new mailboxes until it picks a plan. Sending from Warmbly Cloud, the unified inbox, contacts, the CRM, automations and integrations turn on with a paid plan. +Warmbly Cloud has no free plan for new workspaces. Anyone can sign up and explore the dashboard, but a workspace without a paid plan has a [mailbox allowance](/guides/mailboxes/#mailbox-allowance) of `0`: connecting a mailbox is refused with [`mailbox_allowance_reached`](/api/error-codes/#mailbox_allowance_reached), and no warmup is scheduled. Choosing any plan lifts both. + +Workspaces that had the free plan before it closed to new workspaces keep it, unchanged, for as long as they like: up to 10 mailboxes connected on the cloud, warming in the free pool, with no card. Subscribing moves those mailboxes to the premium pool with no cap. Warmbly Cloud no longer links new self-hosted instances on any plan; a free workspace [linked earlier](/guides/warmbly-cloud/#free-workspaces-linked-earlier) keeps what it already enrolled but adds no new mailboxes until it picks a plan. Sending from Warmbly Cloud, the unified inbox, contacts, the CRM, automations and integrations turn on with a paid plan. + +A [self-hosted instance](/development/install/) has no billing and no allowance: every mailbox connects and warms. Its warmup only pairs the mailboxes on that instance, with no shared pool, so it does far less for deliverability than warming on Warmbly Cloud. Self-hosting suits teams that want to own the whole stack. @@ -106,8 +111,8 @@ Only the workspace owner can change the plan. Other members see the same compari **Overview** is the control panel for the subscription. - The plan card shows the plan, its status, the price (per year on a yearly subscription), and the renewal or end date. Change plan opens the same chooser the locked features use. -- Cancel plan schedules the cancellation for the end of the paid period. The plan stays fully active until then, and Resume clears it with one click. Nothing is lost either way: the workspace returns to the free tier and keeps its mailboxes, warmup and settings. -- Usage and limits shows live counts against the limits the server actually enforces, for mailboxes, sends today (the cap the sender applies, or unlimited on a plan without one), contacts, campaigns, team members, attachment storage, sends this period, and API calls. A meter turns amber past 70% and red past 90%. A meter with no cap means that limit is unmetered on your plan. A workspace that does not send (free, or on the Warmup or Partnership plan) sees only the mailbox meter, because none of the others applies to it. The mailbox meter says where its number comes from (fair use, an approved request, or the free allowance), and the storage meter says so when a plan change left the workspace over its quota: existing attachments keep sending, and new uploads wait until you are back under. +- Cancel plan schedules the cancellation for the end of the paid period. The plan stays fully active until then, and Resume clears it with one click. Nothing is deleted either way: the workspace keeps its mailboxes and settings, and warmup stops until it picks a plan again (a workspace that kept the earlier free plan returns to it). +- Usage and limits shows live counts against the limits the server actually enforces, for mailboxes, sends today (the cap the sender applies, or unlimited on a plan without one), contacts, campaigns, team members, attachment storage, sends this period, and API calls. A meter turns amber past 70% and red past 90%. A meter with no cap means that limit is unmetered on your plan. A workspace that does not send (free, or on the Warmup or Partnership plan) sees only the mailbox meter, because none of the others applies to it. The mailbox meter says where its number comes from (fair use, an approved request, or the free allowance, which is `0` for a new workspace without a plan), and the storage meter says so when a plan change left the workspace over its quota: existing attachments keep sending, and new uploads wait until you are back under. - Banners appear only when something needs a decision: a failed payment, a scheduled cancellation, or a trial about to end. Need a single limit raised without moving plan? Request an increase from **Settings > Limits**, linked from the usage section, or straight from the connect dialog when it is mailboxes you need. An operator reviews it and the approved limit takes effect on the workspace, including the daily send allowance the sender enforces. The page shows how much of each limit the workspace uses, and a limit your plan leaves unlimited (mailboxes, on a plan whose daily sends are uncapped) is not offered, because there is nothing to raise. A workspace that does not send can only ask for more mailboxes. @@ -136,7 +141,7 @@ Upgrading a workspace with only a managed plan opens Checkout to create a Stripe Operators grant one from the admin panel on the workspace, under **Plan**. The organization list marks granted workspaces with a `managed` badge and can filter to them, so "who is paid because we said so" is answerable without checking Stripe. A grant that has lapsed keeps its reason on file and is shown as `grant lapsed` rather than disappearing. -A grant is held beside the plan a workspace pays for, never on top of it, so a paying workspace that is granted a different plan goes back to the one it pays for when the grant ends. Revoking returns the workspace to whatever it actually pays for, which for most is the free plan. +A grant is held beside the plan a workspace pays for, never on top of it, so a paying workspace that is granted a different plan goes back to the one it pays for when the grant ends. Revoking returns the workspace to whatever it actually pays for, which can be no plan at all. One thing a grant does not do: monthly AI credits are granted when an invoice is paid, and a granted plan raises no invoice, so a managed workspace does not receive a recurring credit allowance. Top up its balance directly if it needs credits. diff --git a/docs/content/docs/guides/mailboxes.mdx b/docs/content/docs/guides/mailboxes.mdx index 9438bc961..48cbfe9f7 100644 --- a/docs/content/docs/guides/mailboxes.mdx +++ b/docs/content/docs/guides/mailboxes.mdx @@ -243,7 +243,8 @@ Mailboxes are unlimited on every paid plan. What keeps that honest is a fair-use | Plan | Sends per day | Mailboxes | | --- | --- | --- | -| Free workspace | none | `10` | +| No paid plan | none | `0` | +| Free plan kept from before | none | `10` | | Starter | `150` | `150` | | Grow | `3,000` | `3,000` | | Business | `15,000` | `15,000` | @@ -251,7 +252,7 @@ Mailboxes are unlimited on every paid plan. What keeps that honest is a fair-use That is deliberately far more than safe sending ever needs: at the recommended `30` to `50` sends a day per mailbox, a Business workspace fills its volume with a few hundred mailboxes and still has room for tens of thousands. The allowance exists so that it is never the reason to run a mailbox hotter. A plan whose daily sends are uncapped holds unlimited mailboxes, and a self-hosted instance without billing never counts. -**A free workspace.** Subscribe to any plan to warm more than `10` mailboxes here. A [self-hosted instance](/development/install/) has no mailbox cap, but its warmup only pairs its own mailboxes and Warmbly Cloud no longer links new instances, so the hosted pool is only reached from a hosted workspace. +**Without a paid plan.** A new workspace connects no mailboxes until it picks a plan; the connect is refused with [`mailbox_allowance_reached`](/api/error-codes/#mailbox_allowance_reached). A workspace that had the free plan before it closed to new workspaces keeps `10` mailboxes warming in the free pool; subscribe to any plan to hold more. A [self-hosted instance](/development/install/) has no mailbox cap, but its warmup only pairs its own mailboxes, with no shared pool, so it does far less for deliverability. Warmbly Cloud no longer links new instances, so the hosted pool is only reached from a hosted workspace. The connect dialog shows the allowance up front: a quiet count while there is room, a warning near the cap, and a clear full state that leads to the request flow instead of letting you type credentials that would be refused. When a connect is refused the answer is the same dialog, not an error toast. @@ -527,7 +528,7 @@ Keep warmup running after campaigns begin rather than switching it off once a ma A mailbox marked as a [placement seed inbox](/guides/placement-tests/#your-own-seed-inboxes) is the exception: it never warms up (starting warmup on it is refused until it is unmarked) and never sends campaign mail, because a test inbox has to stay a stranger to your senders. - The model still supports separate free and premium pools, but access is gated to paid workspaces today. + On Warmbly Cloud every paid plan warms in the premium pool. Only a workspace that had the free plan before it closed to new workspaces warms without one, up to `10` mailboxes in the free pool. diff --git a/docs/content/docs/guides/warmbly-cloud.mdx b/docs/content/docs/guides/warmbly-cloud.mdx index 9eea812e4..47fd1e4ea 100644 --- a/docs/content/docs/guides/warmbly-cloud.mdx +++ b/docs/content/docs/guides/warmbly-cloud.mdx @@ -95,7 +95,7 @@ A free Cloud workspace that already has a linked instance keeps it, and every ma That connection adds no new mailbox to Cloud until the workspace subscribes to a paid Warmbly Cloud plan. Enrolling an SMTP/IMAP mailbox, signing in a Google or Microsoft mailbox through Warmbly Cloud, and connecting an existing Cloud workspace mailbox into the instance are refused with `pool_link_subscription_required` (402). New mailboxes warm locally on the instance instead. It follows that a mailbox you unenroll cannot be enrolled again without the plan. -**Settings > Warmbly Cloud** shows how many mailboxes the workspace keeps, and the **Mailboxes** page says when new ones warm locally, with a **See plans** button. Moving the linked Cloud workspace to a paid plan lifts the restriction on the existing connection; nothing needs reconnecting. This applies only to linked instances: a free workspace still warms up to 10 mailboxes connected directly on Warmbly Cloud. +**Settings > Warmbly Cloud** shows how many mailboxes the workspace keeps, and the **Mailboxes** page says when new ones warm locally, with a **See plans** button. Moving the linked Cloud workspace to a paid plan lifts the restriction on the existing connection; nothing needs reconnecting. This applies only to linked instances: a workspace that kept the free plan still warms up to 10 mailboxes connected directly on Warmbly Cloud. A new workspace has no free plan to keep and needs a paid plan to connect mailboxes; see [billing](/guides/billing/#without-a-paid-plan). Deploy the Cloud backend before upgrading self-hosted instances. Older self-hosted versions keep working against it; on a free workspace they show the refusal when they try to add a mailbox. diff --git a/docs/content/docs/guides/warmup.mdx b/docs/content/docs/guides/warmup.mdx index fb7dc494b..40f1c7e40 100644 --- a/docs/content/docs/guides/warmup.mdx +++ b/docs/content/docs/guides/warmup.mdx @@ -39,7 +39,8 @@ Pause to stop both sending and receiving warmup mail, or Stop to also turn diagn ## Good to know -- Warmup is a paid feature: free organizations can connect mailboxes, but no warmup traffic is scheduled for them. +- On Warmbly Cloud, warmup needs a paid plan, and every paid plan warms unlimited mailboxes in the premium pool. A workspace that had the free plan before it closed to new workspaces keeps warming up to 10 mailboxes in the free pool. +- A self-hosted instance warms every mailbox, but only against the other mailboxes on that instance, with no shared pool. - New mailboxes start with warmup off. Once on, it starts at `10` emails a day by default and climbs by `+1` a day to a ceiling of `40`. - Keep warmup on after campaigns start. A mailbox backing a live campaign drops to at most five warmup messages a day, and the pool replies to more of them. - Warmup mail never appears in the unibox, and it is removed from the mailbox after 30 days by default. @@ -52,7 +53,7 @@ Pause to stop both sending and receiving warmup mail, or Stop to also turn diagn Warmup sends natural plain-text threads between participating mailboxes. It measures observed placement and bounded actual-message DKIM evidence. It does not establish organic engagement or guarantee reputation improvement or inbox placement. - Free organizations can connect mailboxes, but no warmup traffic is scheduled for them; pending warmup activity is skipped rather than sent. + On Warmbly Cloud a workspace without a paid plan cannot connect mailboxes, and no warmup traffic is scheduled for it; pending warmup activity is skipped rather than sent. A workspace that had the free plan before it closed to new workspaces keeps warming up to 10 mailboxes in the free pool. See [billing](/guides/billing/#without-a-paid-plan). @@ -124,7 +125,7 @@ A pool is the set of mailboxes that warm each other. Your mailbox exchanges warm | Pool | Who is in it | |------|--------------| | `premium` | Paid organizations' mailboxes. The default for paid accounts, isolated from lower-trust traffic. | -| `free` | Lower-trust or trial mailboxes, kept separate so free traffic does not mix into premium reputation. | +| `free` | Mailboxes of workspaces that kept the earlier free plan, and lower-trust mailboxes, kept separate so free traffic does not mix into premium reputation. New workspaces do not join it without a plan. | A mailbox belongs to exactly one pool at a time. When its plan changes the mailbox moves between pools rather than joining a second one, and it takes its warmup standing with it, so a quarantine or block is not cleared by changing tier. diff --git a/internal/app/consumer/action_required_notify_test.go b/internal/app/consumer/action_required_notify_test.go index 28bb97419..20d0ead35 100644 --- a/internal/app/consumer/action_required_notify_test.go +++ b/internal/app/consumer/action_required_notify_test.go @@ -8,6 +8,7 @@ import ( "github.com/google/uuid" + "github.com/warmbly/warmbly/internal/errx" "github.com/warmbly/warmbly/internal/models" ) @@ -73,3 +74,39 @@ func TestNotifyActionRequiredWithoutNotifierIsQuiet(t *testing.T) { s := &JobsService{} s.notifyActionRequired(uuid.New(), "", &models.EmailMessageStoreData{ID: uuid.New()}) } + +type fixedUnibox struct { + ok bool + xerr *errx.Error +} + +func (f fixedUnibox) CanUseUnibox(context.Context, uuid.UUID) (bool, *errx.Error) { + return f.ok, f.xerr +} + +// A workspace whose plan locks the inbox gets no notice pointing into it; an unknown answer still notifies. +func TestNotifyActionRequiredFollowsInboxAccess(t *testing.T) { + for _, tc := range []struct { + name string + gate fixedUnibox + want bool + }{ + {"inbox locked", fixedUnibox{ok: false}, false}, + {"inbox open", fixedUnibox{ok: true}, true}, + {"access unknown", fixedUnibox{xerr: errx.New(errx.Internal, "down")}, true}, + } { + n := &captureOrgNotifier{got: make(chan capturedOrgNotice, 1)} + s := &JobsService{Notifier: n, UniboxAccess: tc.gate} + s.notifyActionRequired(uuid.New(), "[EMAIL]", &models.EmailMessageStoreData{ID: uuid.New(), ThreadID: "t"}) + select { + case <-n.got: + if !tc.want { + t.Errorf("%s: notified, want silent", tc.name) + } + case <-time.After(300 * time.Millisecond): + if tc.want { + t.Errorf("%s: silent, want a notice", tc.name) + } + } + } +} diff --git a/internal/app/consumer/event_new_email.go b/internal/app/consumer/event_new_email.go index 24f1af352..fa3c254d6 100644 --- a/internal/app/consumer/event_new_email.go +++ b/internal/app/consumer/event_new_email.go @@ -865,6 +865,11 @@ func (s *JobsService) tagInboundMessage(ctx context.Context, e *models.JobEventN } } +// UniboxGate answers whether a workspace's plan opens the inbox. +type UniboxGate interface { + CanUseUnibox(ctx context.Context, orgID uuid.UUID) (bool, *errx.Error) +} + // notifyActionRequired tells the members who keep mailboxes running that one // received mail needing action, since nobody may be reading that mailbox. The // sender's subject stays out: this mail is phishing-shaped by selection. @@ -877,6 +882,12 @@ func (s *JobsService) notifyActionRequired(orgID uuid.UUID, mailbox string, m *m title = "Message to review in " + mailbox } notify := func(ctx context.Context) { + // An unknown answer still notifies: a missed notice costs a paying workspace more. + if s.UniboxAccess != nil { + if ok, xerr := s.UniboxAccess.CanUseUnibox(ctx, orgID); xerr == nil && !ok { + return + } + } s.Notifier.NotifyOrgAboutMessage(ctx, orgID, models.PermManageEmails|models.PermAccessUnibox, m.ID, models.NotifInboxActionRequired, title, "An incoming message was marked for review. Its claims are unverified. This is an inbox notice, not a Warmbly connection check. Review it in the inbox.", diff --git a/internal/app/consumer/service.go b/internal/app/consumer/service.go index b4248ed28..a72a40ff3 100644 --- a/internal/app/consumer/service.go +++ b/internal/app/consumer/service.go @@ -116,6 +116,9 @@ type JobsService struct { // dead-worker job moves or strands their mailboxes. Nil disables it. Notifier OrgNotifier + // UniboxAccess keeps inbox notices from workspaces whose plan locks the inbox. Nil skips the check. + UniboxAccess UniboxGate + // OpsNotifier raises instance-wide operator alerts, which are a different // audience from Notifier: the operator hears about the fleet, the tenant // hears about their mailboxes. Nil disables it. diff --git a/internal/app/email/onboarding.go b/internal/app/email/onboarding.go index 73e6b59ef..be274ddd5 100644 --- a/internal/app/email/onboarding.go +++ b/internal/app/email/onboarding.go @@ -93,7 +93,7 @@ func (s *emailService) OAuthStart(ctx context.Context, userID string, orgID *uui } // guardInboxLimit refuses a connect that would take the workspace past its -// mailbox allowance (fair use for paid plans, FreeWorkspaceMailboxLimit for +// mailbox allowance (fair use for paid plans, Subscription.FreeMailboxLimit for // free ones, unlimited without billing) and returns the resolved allowance so // the insert can enforce it again under the organization's lock. The // allowance is counted per org, so no org means it cannot be applied and the diff --git a/internal/app/feature/gate.go b/internal/app/feature/gate.go index 9dd8ef0ae..3c6d9175b 100644 --- a/internal/app/feature/gate.go +++ b/internal/app/feature/gate.go @@ -28,8 +28,8 @@ type FeatureGateService interface { // CanSendCampaignEmail checks if an organization can send campaign emails CanSendCampaignEmail(ctx context.Context, orgID uuid.UUID) (bool, *errx.Error) - // CanUseWarmup checks if an organization can use the warmup feature. - // Free-trial orgs may use warmup during their 14-day window. + // CanUseWarmup checks if an organization can use the warmup feature: + // a paid plan, or a free workspace that kept the free allowance. CanUseWarmup(ctx context.Context, orgID uuid.UUID) (bool, *errx.Error) // CanUseUnibox checks if an organization can use the unibox feature. @@ -37,7 +37,7 @@ type FeatureGateService interface { CanUseUnibox(ctx context.Context, orgID uuid.UUID) (bool, *errx.Error) // CanAddInbox returns whether the org may connect another email account. - // Free workspaces are capped at FreeWorkspaceMailboxLimit connected mailboxes. + // Free workspaces are capped at their Subscription.FreeMailboxLimit. // Paid orgs are not gated here (plan limits govern sending volume). CanAddInbox(ctx context.Context, orgID uuid.UUID, currentCount int) (bool, *errx.Error) @@ -200,7 +200,7 @@ func (s *featureGateService) CanUseUnibox(ctx context.Context, orgID uuid.UUID) return sub.CanUseUnibox(), nil } -// CanAddInbox: paid workspaces are uncapped, free ones get FreeWorkspaceMailboxLimit. +// CanAddInbox: paid workspaces are uncapped, free ones get their FreeMailboxLimit. func (s *featureGateService) CanAddInbox(ctx context.Context, orgID uuid.UUID, currentCount int) (bool, *errx.Error) { if s.selfHost { return true, nil @@ -212,7 +212,7 @@ func (s *featureGateService) CanAddInbox(ctx context.Context, orgID uuid.UUID, c if sub != nil && sub.HasPaidSubscription() { return true, nil } - return currentCount < models.FreeWorkspaceMailboxLimit, nil + return currentCount < sub.FreeMailboxLimit(), nil } // GetDailyEmailLimit returns the daily email limit for an organization diff --git a/internal/app/feature/gate_tester_test.go b/internal/app/feature/gate_tester_test.go index 12acee5c5..de1f10146 100644 --- a/internal/app/feature/gate_tester_test.go +++ b/internal/app/feature/gate_tester_test.go @@ -28,14 +28,12 @@ func TestTestPlanAccessEndsWithReviewerExpiry(t *testing.T) { "Unibox": gate.CanUseUnibox, "writing assistant": gate.CanUseWritingAssistant, "inbox agent": gate.CanUseInboxAgent, + "warmup": gate.CanUseWarmup, } { allowed, xerr := check(ctx, orgID) if xerr != nil || allowed == expired { t.Errorf("%s with expired=%v: allowed=%v, error=%v", name, expired, allowed, xerr) } } - if allowed, xerr := gate.CanUseWarmup(ctx, orgID); xerr != nil || !allowed { - t.Error("expiry must not remove normal free-pool warmup access") - } } } diff --git a/internal/app/feature/gate_warmup_plan_test.go b/internal/app/feature/gate_warmup_plan_test.go index 9ed4c57b8..6a6e9de3e 100644 --- a/internal/app/feature/gate_warmup_plan_test.go +++ b/internal/app/feature/gate_warmup_plan_test.go @@ -137,3 +137,34 @@ func TestPartnershipPlanWarmsLikeTheWarmupPlan(t *testing.T) { t.Errorf("granted Partnership plan: warmupOnly=%v product=%v, want true false", sub.IsWarmupOnly(), sub.HasProductPlan()) } } + +// A free workspace warms only if it kept the free allowance; a new one needs a plan. +func TestFreeWarmupFollowsTheKeptAllowance(t *testing.T) { + ctx := context.Background() + org := uuid.New() + must := noError(t) + + kept := &featureGateService{subRepo: stubSubs{sub: &models.Subscription{KeepsFreeWarmup: true}}} + if !must(kept.CanUseWarmup(ctx, org)) { + t.Error("a workspace that kept the free allowance must still warm") + } + if !must(kept.CanAddInbox(ctx, org, models.FreeWorkspaceMailboxLimit-1)) || must(kept.CanAddInbox(ctx, org, models.FreeWorkspaceMailboxLimit)) { + t.Errorf("a kept free workspace must hold exactly %d mailboxes", models.FreeWorkspaceMailboxLimit) + } + if must(kept.HasPremiumWarmup(ctx, org)) { + t.Error("a kept free workspace warms in the free pool, not the premium one") + } + + fresh := &featureGateService{subRepo: stubSubs{sub: &models.Subscription{}}} + if must(fresh.CanUseWarmup(ctx, org)) { + t.Error("a new free workspace must not warm without a plan") + } + if must(fresh.CanAddInbox(ctx, org, 0)) { + t.Error("a new free workspace must not connect a mailbox without a plan") + } + + none := &featureGateService{subRepo: stubSubs{}} + if must(none.CanUseWarmup(ctx, org)) || must(none.CanAddInbox(ctx, org, 0)) { + t.Error("a workspace with no subscription row must not warm or connect mailboxes") + } +} diff --git a/internal/app/instanceconfig/limits.go b/internal/app/instanceconfig/limits.go index 3f61e4386..527c27ea8 100644 --- a/internal/app/instanceconfig/limits.go +++ b/internal/app/instanceconfig/limits.go @@ -52,7 +52,7 @@ func Limits() []LimitGroup { Title: "Mailbox allowance", Entries: []LimitEntry{ {"Fair-use sends per mailbox", n(config.FairUseSendsPerMailbox), "sends/day", "A paid plan holds one mailbox for every this many daily sends it includes; a plan with no daily cap holds unlimited mailboxes."}, - {"Free workspace mailboxes", n(models.FreeWorkspaceMailboxLimit), "per organization", "Without a paid plan."}, + {"Free workspace mailboxes", n(models.FreeWorkspaceMailboxLimit), "per organization", "Only workspaces that kept the free plan; new ones need a paid plan."}, {"Bulk connect batch", n(config.MailboxBulkBatchMax), "rows/request", "The most SMTP/IMAP rows one bulk connect call carries; the dashboard streams a CSV through batches of this size."}, {"Bulk connect concurrency", n(config.MailboxBulkConcurrency), "validations", "Credentials dialled at the same time within one batch."}, }, diff --git a/internal/app/organization/service.go b/internal/app/organization/service.go index d9e0e41fa..d17b43395 100644 --- a/internal/app/organization/service.go +++ b/internal/app/organization/service.go @@ -1280,7 +1280,7 @@ func (s *organizationService) CanAddCampaign(ctx context.Context, orgID uuid.UUI // // 1. no billing provider: unlimited // 2. an operator override: the override -// 3. no paid subscription: FreeWorkspaceMailboxLimit +// 3. no paid subscription: Subscription.FreeMailboxLimit (none for new workspaces) // 4. the plan's explicit mailbox column, when it carries one // 5. the plan's daily sends divided by FairUseSendsPerMailbox // 6. a plan with no daily send cap: unlimited @@ -1336,7 +1336,7 @@ func (s *organizationService) MailboxAllowance(ctx context.Context, orgID uuid.U case override != nil && override.MaxEmailAccounts > 0: set(override.MaxEmailAccounts, models.MailboxAllowanceOverride) case !a.Paid: - set(models.FreeWorkspaceMailboxLimit, models.MailboxAllowanceFree) + set(sub.FreeMailboxLimit(), models.MailboxAllowanceFree) case sub.Plan != nil && sub.Plan.MaxEmailAccounts != nil && *sub.Plan.MaxEmailAccounts > 0: set(*sub.Plan.MaxEmailAccounts, models.MailboxAllowancePlan) case a.PlanDailySends != nil: diff --git a/internal/errx/common.go b/internal/errx/common.go index 51c29a7b2..71d36e479 100644 --- a/internal/errx/common.go +++ b/internal/errx/common.go @@ -319,6 +319,10 @@ var ( // workspace holds its whole allowance. The identifier is stable so the // dashboard can open the request-more flow instead of showing the text. func MailboxAllowanceReached(used, allowance int, paid bool) *Error { + if !paid && allowance == 0 { + return NewWithIdentifier(Forbidden, "mailbox_allowance_reached", + "Connecting and warming mailboxes needs a plan. Choose one to add a mailbox.") + } if !paid { return NewWithIdentifier(Forbidden, "mailbox_allowance_reached", fmt.Sprintf("A free workspace holds up to %d mailboxes. Choose a plan to add more.", allowance)) diff --git a/internal/infrastructure/db/migrations/000352_subscription_free_warmup.down.sql b/internal/infrastructure/db/migrations/000352_subscription_free_warmup.down.sql new file mode 100644 index 000000000..872504897 --- /dev/null +++ b/internal/infrastructure/db/migrations/000352_subscription_free_warmup.down.sql @@ -0,0 +1,3 @@ +BEGIN; +ALTER TABLE subscriptions DROP COLUMN keeps_free_warmup; +COMMIT; diff --git a/internal/infrastructure/db/migrations/000352_subscription_free_warmup.up.sql b/internal/infrastructure/db/migrations/000352_subscription_free_warmup.up.sql new file mode 100644 index 000000000..a3e0d4820 --- /dev/null +++ b/internal/infrastructure/db/migrations/000352_subscription_free_warmup.up.sql @@ -0,0 +1,5 @@ +BEGIN; +-- Every workspace that exists now keeps the free warmup allowance; new ones start without it. +ALTER TABLE subscriptions ADD COLUMN keeps_free_warmup boolean NOT NULL DEFAULT true; +ALTER TABLE subscriptions ALTER COLUMN keeps_free_warmup SET DEFAULT false; +COMMIT; diff --git a/internal/models/subscriptions.go b/internal/models/subscriptions.go index 8941d04e5..ebaef1f13 100644 --- a/internal/models/subscriptions.go +++ b/internal/models/subscriptions.go @@ -169,6 +169,9 @@ type Subscription struct { // Enterprise flag IsEnterprise bool `json:"is_enterprise"` + // KeepsFreeWarmup marks a workspace that had the free warmup allowance before it was withdrawn from new ones. + KeepsFreeWarmup bool `json:"keeps_free_warmup"` + // Joined data Plan *Plan `json:"plan,omitempty"` @@ -276,10 +279,18 @@ func (s *Subscription) CanSendEmails() bool { return false } -// CanUseWarmup: every workspace may warm its mailboxes (free ones in the free -// pool, up to FreeWorkspaceMailboxLimit connected mailboxes). +// CanUseWarmup: a paid plan, or a workspace that kept the free allowance +// (the free pool, up to FreeWorkspaceMailboxLimit connected mailboxes). func (s *Subscription) CanUseWarmup() bool { - return true + return s.HasPaidSubscription() || s.KeepsFreeWarmup +} + +// FreeMailboxLimit is the mailboxes an unsubscribed workspace may hold: none unless it kept the free allowance. +func (s *Subscription) FreeMailboxLimit() int { + if s != nil && s.KeepsFreeWarmup { + return FreeWorkspaceMailboxLimit + } + return 0 } // CanUseUnibox returns true if user can use unibox feature. diff --git a/internal/repository/pg_subscription.go b/internal/repository/pg_subscription.go index 0faa29b7f..849989d0c 100644 --- a/internal/repository/pg_subscription.go +++ b/internal/repository/pg_subscription.go @@ -17,7 +17,7 @@ import ( // order. With `SELECT *`, the trailing NULL free-trial timestamps land in the // non-nullable created_at/updated_at scan slots and pgx fails with // "cannot scan NULL into *time.Time", 500-ing every subscription read. -const subscriptionColumns = `id, user_id, organization_id, plan_id, stripe_customer_id, stripe_subscription_id, stripe_price_id, status, current_period_start, current_period_end, cancel_at_period_end, canceled_at, trial_start, trial_end, free_trial_started_at, free_trial_ends_at, is_enterprise, created_at, updated_at, managed_at, managed_by, managed_reason, managed_until, managed_plan_id` +const subscriptionColumns = `id, user_id, organization_id, plan_id, stripe_customer_id, stripe_subscription_id, stripe_price_id, status, current_period_start, current_period_end, cancel_at_period_end, canceled_at, trial_start, trial_end, free_trial_started_at, free_trial_ends_at, is_enterprise, created_at, updated_at, managed_at, managed_by, managed_reason, managed_until, managed_plan_id, keeps_free_warmup` type SubscriptionRepository interface { Create(ctx context.Context, sub *models.Subscription) error @@ -139,6 +139,7 @@ func (r *subscriptionRepository) scanSubscription(ctx context.Context, query str &sub.FreeTrialStartedAt, &sub.FreeTrialEndsAt, &sub.IsEnterprise, &sub.CreatedAt, &sub.UpdatedAt, &sub.ManagedAt, &sub.ManagedBy, &sub.ManagedReason, &sub.ManagedUntil, &sub.ManagedPlanID, + &sub.KeepsFreeWarmup, ) if err == pgx.ErrNoRows { return nil, nil diff --git a/site/src/components/CTA.astro b/site/src/components/CTA.astro index c42e6655c..384a3eb29 100644 --- a/site/src/components/CTA.astro +++ b/site/src/components/CTA.astro @@ -17,8 +17,8 @@ interface Props { } const { title = 'Start sending cold email that lands.', - description = 'Connect a mailbox and start warming it today. Free to start, free to self-host.', - primaryLabel = 'Start free', + description = 'Pick a plan, connect your mailboxes and start warming them today. Unlimited mailboxes and warmup on every paid plan.', + primaryLabel = 'Get started', primaryHref = 'https://app.warmbly.com/auth/register', secondaryLabel = 'See pricing', secondaryHref = '/pricing/', diff --git a/site/src/components/FeatureGrid.astro b/site/src/components/FeatureGrid.astro index 7392c5205..a27d5c174 100644 --- a/site/src/components/FeatureGrid.astro +++ b/site/src/components/FeatureGrid.astro @@ -48,7 +48,7 @@ const body = 'mt-2 max-w-xl text-[16px] md:text-[17px] leading-[1.55] text-slate

    Open source

    -

    Use Warmbly Cloud, or install it on your own server with one command.

    +

    Use Warmbly Cloud and its shared warmup pool, or install it on your own server with one command, where warmup only pairs your own mailboxes.

    diff --git a/site/src/components/Header.astro b/site/src/components/Header.astro index e95ec6e77..8facb2266 100644 --- a/site/src/components/Header.astro +++ b/site/src/components/Header.astro @@ -230,7 +230,7 @@ function active(match?: string) { (onSky ? '' : 'bg-slate-900 text-white hover:bg-slate-800') } > - Start free + Get started - - ); -} - -function StatCard({ - label, - value, - loading, - accent, -}: { - label: string; - value: string; - loading?: boolean; - accent?: boolean; -}) { - return ( -
    -
    - {label} -
    - {loading ? ( -
    - ) : ( -
    - {value} -
    - )} -
    - ); -} - -function CountPill({ - label, - value, - tone, -}: { - label: string; - value: number; - tone: "muted" | "sky" | "emerald"; -}) { - const dot = - tone === "emerald" - ? "bg-emerald-500" - : tone === "sky" - ? "bg-sky-500" - : "bg-slate-300"; - return ( - - - {label} - {value} - - ); -} - -function AttributionsTable({ currency }: { currency: string }) { - const query = useReferralAttributions(); - const rows = query.attributions; - - if (query.isPending) { - return
    ; - } - if (rows.length === 0) { - return ( -

    - No referrals yet. Share your link to get started. -

    - ); - } - - return ( - <> - - - - - - - - - - - - {rows.map((r) => ( - - ))} - -
    Referred orgStatusRewardDate
    -
    - - - ); -} - -function AttributionRow({ - row, - fallbackCurrency, -}: { - row: ReferralAttribution; - fallbackCurrency: string; -}) { - return ( - - - - Referred org - - {shortId(row.invitee_org_id)} - - - - - - - - {row.reward_cents > 0 - ? formatMoney(row.reward_cents, row.reward_currency || fallbackCurrency) - : "โ€”"} - - - {formatDate(row.rewarded_at ?? row.qualified_at ?? row.created_at)} - - - ); -} - -function AttributionStatusBadge({ status }: { status: ReferralAttributionStatus }) { - const map: Record = { - pending: { label: "Pending", cls: "bg-slate-100 text-slate-500 border-slate-200" }, - qualified: { label: "Qualified", cls: "bg-sky-50 text-sky-700 border-sky-100" }, - rewarded: { label: "Rewarded", cls: "bg-emerald-50 text-emerald-700 border-emerald-100" }, - void: { label: "Void", cls: "bg-slate-100 text-slate-400 border-slate-200" }, - }; - const { label, cls } = map[status]; - return ( - - {label} - - ); -} - -function EarningsTable({ currency }: { currency: string }) { - const query = useReferralEarnings(); - const rows = query.earnings; - - if (query.isPending) { - return
    ; - } - if (rows.length === 0) { - return ( -

    - No earnings yet. Credit shows up here once a referral is rewarded. -

    - ); - } - - return ( - <> - - - - - - - - - - - - {rows.map((t) => ( - - ))} - -
    ReasonAmountBalanceDate
    -
    - - - ); -} - -function EarningsRow({ - row, - fallbackCurrency, -}: { - row: ReferralEarningsTransaction; - fallbackCurrency: string; -}) { - const positive = row.amount_cents >= 0; - const cur = row.currency || fallbackCurrency; - return ( - - {humanizeReason(row.reason)} - - {positive ? "+" : "โˆ’"} - {formatMoney(Math.abs(row.amount_cents), cur)} - - - {formatMoney(row.balance_after_cents, cur)} - - - {formatDate(row.created_at)} - - - ); -} - -function LoadMore({ - query, -}: { - query: { - hasNextPage: boolean; - isFetchingNextPage: boolean; - fetchNextPage: () => void; - }; -}) { - if (!query.hasNextPage) return null; - return ( - - ); -} - -// shortId masks an org id to a short, non-PII reference. -function shortId(id: string): string { - if (!id) return "โ€”"; - const trimmed = id.replace(/-/g, ""); - return `#${trimmed.slice(0, 6)}`; -} - -function humanizeReason(reason: string): string { - if (!reason) return "Adjustment"; - return reason - .replace(/[_-]+/g, " ") - .replace(/\b\w/g, (c) => c.toUpperCase()); -} - -// formatMoney renders minor units (cents) as a localized currency string. -function formatMoney(cents: number, currency: string): string { - try { - return new Intl.NumberFormat("en-US", { - style: "currency", - currency: (currency || "usd").toUpperCase(), - }).format(cents / 100); - } catch { - return `${(cents / 100).toFixed(2)} ${(currency || "usd").toUpperCase()}`; - } -} - -function formatDate(value?: string | Date): string { - if (!value) return "โ€”"; - const d = new Date(value); - if (Number.isNaN(d.getTime())) return "โ€”"; - return d.toLocaleDateString("en-US", { - month: "short", - day: "numeric", - year: "numeric", - }); -} diff --git a/web/src/hooks/useFeatureAccess.ts b/web/src/hooks/useFeatureAccess.ts index db1a57d1d..65cda11a5 100644 --- a/web/src/hooks/useFeatureAccess.ts +++ b/web/src/hooks/useFeatureAccess.ts @@ -42,7 +42,7 @@ export interface FeatureAccess { status?: Subscription["status"]; plan: PlanID; /** False on a deployment running without a billing provider: every gate - * below is open and billing/referral surfaces do not apply. */ + * below is open and billing surfaces do not apply. */ billing: boolean; /** Active subscription on any paid tier, the Warmup plan included. */ paid: boolean; diff --git a/web/src/hooks/useRealtimeEvents.ts b/web/src/hooks/useRealtimeEvents.ts index 5cf26eed8..d7f82d1a0 100644 --- a/web/src/hooks/useRealtimeEvents.ts +++ b/web/src/hooks/useRealtimeEvents.ts @@ -567,8 +567,7 @@ export function useRealtimeEvents() { lead_sync_source: [['lead-sync', 'sources']], meeting: [['meetings'], ['meetings', 'summary']], subscription: [['subscription'], ['organizations', 'limits']], - referral: [['subscription', 'referral']], - referral_credit: [['subscription', 'referral'], ['subscription']], + referral_credit: [['subscription']], // AI credits: a top-up purchase or a monthly allowance reset both // change the billing/credits view for every teammate. credit_purchase: [['subscription', 'credits'], ['subscription']], diff --git a/web/src/lib/api/client/app/referral/ensureReferralCode.ts b/web/src/lib/api/client/app/referral/ensureReferralCode.ts deleted file mode 100644 index d33f83642..000000000 --- a/web/src/lib/api/client/app/referral/ensureReferralCode.ts +++ /dev/null @@ -1,12 +0,0 @@ -import Request from "../../Request"; -import type { ReferralCode } from "@/lib/api/models/app/subscription/Referral"; - -// POST /subscription/referral โ€” idempotent "ensure" of the owner's referral -// code. GET already mints, so this is only needed for an explicit create. -export default async function ensureReferralCode(): Promise { - return await Request({ - method: "POST", - url: `/subscription/referral`, - authorization: true, - }); -} diff --git a/web/src/lib/api/client/app/referral/getReferral.ts b/web/src/lib/api/client/app/referral/getReferral.ts deleted file mode 100644 index fa641a55a..000000000 --- a/web/src/lib/api/client/app/referral/getReferral.ts +++ /dev/null @@ -1,12 +0,0 @@ -import Request from "../../Request"; -import type { ReferralSummary } from "@/lib/api/models/app/subscription/Referral"; - -// GET /subscription/referral โ€” mints the code on first view, so this always -// returns a ready code + share_url. -export default async function getReferral(): Promise { - return await Request({ - method: "GET", - url: `/subscription/referral`, - authorization: true, - }); -} diff --git a/web/src/lib/api/client/app/referral/listReferralAttributions.ts b/web/src/lib/api/client/app/referral/listReferralAttributions.ts deleted file mode 100644 index 264290d59..000000000 --- a/web/src/lib/api/client/app/referral/listReferralAttributions.ts +++ /dev/null @@ -1,25 +0,0 @@ -import Request from "../../Request"; -import type { ReferralAttributionsPage } from "@/lib/api/models/app/subscription/Referral"; - -// GET /subscription/referral/attributions โ€” the org's referrals, paginated by -// the same opaque next_cursor every other list uses. -export default async function listReferralAttributions( - cursor?: string | null, - limit = 20, -): Promise { - const qs = new URLSearchParams(); - if (cursor) qs.set("cursor", cursor); - if (limit) qs.set("limit", String(limit)); - const suffix = qs.toString() ? `?${qs.toString()}` : ""; - - const result = await Request({ - method: "GET", - url: `/subscription/referral/attributions${suffix}`, - authorization: true, - }); - - return { - data: result.data ?? [], - pagination: result.pagination ?? { has_more: false, next_cursor: null }, - }; -} diff --git a/web/src/lib/api/client/app/referral/listReferralEarnings.ts b/web/src/lib/api/client/app/referral/listReferralEarnings.ts deleted file mode 100644 index f8b0aa08d..000000000 --- a/web/src/lib/api/client/app/referral/listReferralEarnings.ts +++ /dev/null @@ -1,25 +0,0 @@ -import Request from "../../Request"; -import type { ReferralEarningsPage } from "@/lib/api/models/app/subscription/Referral"; - -// GET /subscription/referral/earnings โ€” the org's reward/clawback ledger, -// paginated by the same opaque next_cursor every other list uses. -export default async function listReferralEarnings( - cursor?: string | null, - limit = 20, -): Promise { - const qs = new URLSearchParams(); - if (cursor) qs.set("cursor", cursor); - if (limit) qs.set("limit", String(limit)); - const suffix = qs.toString() ? `?${qs.toString()}` : ""; - - const result = await Request({ - method: "GET", - url: `/subscription/referral/earnings${suffix}`, - authorization: true, - }); - - return { - data: result.data ?? [], - pagination: result.pagination ?? { has_more: false, next_cursor: null }, - }; -} diff --git a/web/src/lib/api/hooks/app/subscription/useEnsureReferralCode.ts b/web/src/lib/api/hooks/app/subscription/useEnsureReferralCode.ts deleted file mode 100644 index cf90fb43f..000000000 --- a/web/src/lib/api/hooks/app/subscription/useEnsureReferralCode.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { useMutation, useQueryClient } from "@tanstack/react-query"; -import ensureReferralCode from "@/lib/api/client/app/referral/ensureReferralCode"; - -// Explicit "ensure"/regenerate of the referral code. GET already mints on first -// view, so this is optional; on success we refresh the summary. -export default function useEnsureReferralCode() { - const queryClient = useQueryClient(); - return useMutation({ - mutationFn: () => ensureReferralCode(), - onSuccess: () => { - void queryClient.invalidateQueries({ queryKey: ["subscription", "referral"] }); - }, - }); -} diff --git a/web/src/lib/api/hooks/app/subscription/useReferral.ts b/web/src/lib/api/hooks/app/subscription/useReferral.ts deleted file mode 100644 index ef9f5293e..000000000 --- a/web/src/lib/api/hooks/app/subscription/useReferral.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { useQuery } from "@tanstack/react-query"; -import getReferral from "@/lib/api/client/app/referral/getReferral"; - -// The referral summary changes when a reward lands or the balance is spent. -// The realtime spine invalidates ["subscription", "referral"] on referral / -// referral_credit audit events, so we don't poll here. -export default function useReferral() { - return useQuery({ - queryKey: ["subscription", "referral"], - queryFn: () => getReferral(), - staleTime: 30_000, - }); -} diff --git a/web/src/lib/api/hooks/app/subscription/useReferralAttributions.ts b/web/src/lib/api/hooks/app/subscription/useReferralAttributions.ts deleted file mode 100644 index 3faee357e..000000000 --- a/web/src/lib/api/hooks/app/subscription/useReferralAttributions.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { useInfiniteQuery, type InfiniteData } from "@tanstack/react-query"; -import type { ReferralAttributionsPage } from "@/lib/api/models/app/subscription/Referral"; -import listReferralAttributions from "@/lib/api/client/app/referral/listReferralAttributions"; - -// Infinite scroll over the org's referrals, paginated by the same opaque -// next_cursor every other list uses. Pages flatten into one list. -export default function useReferralAttributions(limit = 20, enabled = true) { - const queryResult = useInfiniteQuery< - ReferralAttributionsPage, - Error, - InfiniteData, - [string, string, string, number], - string | undefined - >({ - queryKey: ["subscription", "referral", "attributions", limit], - queryFn: async ({ pageParam }) => listReferralAttributions(pageParam, limit), - initialPageParam: undefined, - getNextPageParam: (lastPage) => - lastPage.pagination.has_more ? (lastPage.pagination.next_cursor ?? undefined) : undefined, - staleTime: 30_000, - enabled, - }); - - const attributions = queryResult.data?.pages.flatMap((p) => p.data ?? []) ?? []; - - return { ...queryResult, attributions }; -} diff --git a/web/src/lib/api/hooks/app/subscription/useReferralEarnings.ts b/web/src/lib/api/hooks/app/subscription/useReferralEarnings.ts deleted file mode 100644 index f959d7d87..000000000 --- a/web/src/lib/api/hooks/app/subscription/useReferralEarnings.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { useInfiniteQuery, type InfiniteData } from "@tanstack/react-query"; -import type { ReferralEarningsPage } from "@/lib/api/models/app/subscription/Referral"; -import listReferralEarnings from "@/lib/api/client/app/referral/listReferralEarnings"; - -// Infinite scroll over the reward/clawback ledger, paginated by the same opaque -// next_cursor every other list uses. Pages flatten into one list. -export default function useReferralEarnings(limit = 20, enabled = true) { - const queryResult = useInfiniteQuery< - ReferralEarningsPage, - Error, - InfiniteData, - [string, string, string, number], - string | undefined - >({ - queryKey: ["subscription", "referral", "earnings", limit], - queryFn: async ({ pageParam }) => listReferralEarnings(pageParam, limit), - initialPageParam: undefined, - getNextPageParam: (lastPage) => - lastPage.pagination.has_more ? (lastPage.pagination.next_cursor ?? undefined) : undefined, - staleTime: 30_000, - enabled, - }); - - const earnings = queryResult.data?.pages.flatMap((p) => p.data ?? []) ?? []; - - return { ...queryResult, earnings }; -} diff --git a/web/src/lib/api/models/app/subscription/Referral.ts b/web/src/lib/api/models/app/subscription/Referral.ts deleted file mode 100644 index 899e84ac0..000000000 --- a/web/src/lib/api/models/app/subscription/Referral.ts +++ /dev/null @@ -1,67 +0,0 @@ -// Mirrors the backend referral program contract returned under -// /subscription/referral and its sub-resources. - -// GET /subscription/referral โ€” the GET mints the code on first view so it -// always returns a ready code + share_url. -export interface ReferralSummary { - code: string; - share_url: string; - currency: string; - invitee_percent_off: number; - invitee_months: number; - balance_cents: number; - lifetime_earned_cents: number; - total_referred: number; - pending: number; - qualified: number; - rewarded: number; -} - -// POST /subscription/referral โ€” idempotent "ensure" of the owner's code. -export interface ReferralCode { - id: string; - code: string; - owner_user_id: string; - owner_org_id: string; - discount_code_id: string; - created_at: Date; - updated_at: Date; -} - -export type ReferralAttributionStatus = "pending" | "qualified" | "rewarded" | "void"; - -export interface ReferralAttribution { - id: string; - status: ReferralAttributionStatus; - reward_cents: number; - reward_currency: string; - invitee_org_id: string; - qualified_at?: Date; - rewarded_at?: Date; - created_at: Date; -} - -// Positive amount = reward, negative = clawback. -export interface ReferralEarningsTransaction { - id: string; - amount_cents: number; - currency: string; - reason: string; - balance_after_cents: number; - created_at: Date; -} - -export interface ReferralPagination { - next_cursor: string | null; - has_more: boolean; -} - -export interface ReferralAttributionsPage { - data: ReferralAttribution[]; - pagination: ReferralPagination; -} - -export interface ReferralEarningsPage { - data: ReferralEarningsTransaction[]; - pagination: ReferralPagination; -} diff --git a/web/src/lib/api/models/auth/Register.ts b/web/src/lib/api/models/auth/Register.ts index 83c93119a..b883f8684 100644 --- a/web/src/lib/api/models/auth/Register.ts +++ b/web/src/lib/api/models/auth/Register.ts @@ -4,7 +4,6 @@ export default interface Register { email: string, password: string, turnstile: string, - referral_code?: string, // Team-invitation token. It is what lets a signup through on an // invite_only instance, so it must survive the whole register flow. invite?: string diff --git a/web/src/router.tsx b/web/src/router.tsx index ad7fbe059..659a3f53f 100644 --- a/web/src/router.tsx +++ b/web/src/router.tsx @@ -95,7 +95,6 @@ export const dashboardPages = { workspace: () => import("./app/app/settings/workspace/page"), aiSkills: () => import("./app/app/settings/ai-skills/page"), billing: () => import("./app/app/settings/billing/page"), - referral: () => import("./app/app/settings/referral/page"), limits: () => import("./app/app/settings/limits/page"), sending: () => import("./app/app/settings/sending/page"), tracking: () => import("./app/app/settings/tracking/page"), @@ -368,7 +367,6 @@ const settingsChildren = [ dash(settingsRoute, "workspace", dashboardPages.workspace, "Workspace"), dash(settingsRoute, "ai-skills", dashboardPages.aiSkills, "AI skills"), dash(settingsRoute, "billing/{-$tab}", dashboardPages.billing, "Billing", loaders.billingLoader), - dash(settingsRoute, "referral", dashboardPages.referral, "Refer & earn"), dash(settingsRoute, "limits", dashboardPages.limits, "Plan & limits"), dash(settingsRoute, "sending", dashboardPages.sending, "Sending"), dash(settingsRoute, "tracking", dashboardPages.tracking, "Website tracking"), From 9fcb9753148b12c293985ebf30f1549691959167 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sat, 7 Nov 2026 06:55:33 +0100 Subject: [PATCH 278/318] feat: disable a referral discount code when its referral code is deleted with its owner, disable referral discounts already left without a code, and keep the old referrals-and-discounts and promo-codes-and-referrals docs anchors working --- docs/content/docs/api/endpoints.mdx | 2 ++ .../docs/api/reference/account-org.mdx | 2 ++ ...eferral_discount_follows_its_code.down.sql | 2 ++ ..._referral_discount_follows_its_code.up.sql | 22 +++++++++++++++++++ 4 files changed, 28 insertions(+) create mode 100644 internal/infrastructure/db/migrations/000360_referral_discount_follows_its_code.down.sql create mode 100644 internal/infrastructure/db/migrations/000360_referral_discount_follows_its_code.up.sql diff --git a/docs/content/docs/api/endpoints.mdx b/docs/content/docs/api/endpoints.mdx index fae1fed5f..98c258970 100644 --- a/docs/content/docs/api/endpoints.mdx +++ b/docs/content/docs/api/endpoints.mdx @@ -740,6 +740,8 @@ Warmup actions for a deleted, unassigned or no-longer-authorized mailbox return `POST /internal/worker/warmup-actions` optionally accepts `filing_id` for a filing-only action. `filing_pending: true` is returned only for permitted, pure filing work still durably queued for that exact mailbox and its current worker. On a failed filing, this proof lets an updated worker finish the command without a `WarmupFiled` completion event; the durable recovery queue remains responsible for retrying it. Missing proof or an older backend retains the existing command retries. Deploy the backend before workers to enable this behavior. Successful filing still requires a completion event, and publication failures remain retryable. No send, arrival or retention-delete authority is added. +
    + ### Discounts Billing discount history is part of `/subscription/*`, so they are JWT only and never accept an API key. There is no API permission scope for them; browser callers are gated by the org permission below. The discount validation and checkout endpoints are listed under [Subscription and billing](/api/reference/account-org/) in the reference. diff --git a/docs/content/docs/api/reference/account-org.mdx b/docs/content/docs/api/reference/account-org.mdx index 9c65047a2..71caa04da 100644 --- a/docs/content/docs/api/reference/account-org.mdx +++ b/docs/content/docs/api/reference/account-org.mdx @@ -2351,6 +2351,8 @@ Auth: Session only (not available to API keys). } ``` + + ### Promo codes Session only, requiring org permission `manage_billing` and a selected organization. diff --git a/internal/infrastructure/db/migrations/000360_referral_discount_follows_its_code.down.sql b/internal/infrastructure/db/migrations/000360_referral_discount_follows_its_code.down.sql new file mode 100644 index 000000000..a1b166b7b --- /dev/null +++ b/internal/infrastructure/db/migrations/000360_referral_discount_follows_its_code.down.sql @@ -0,0 +1,2 @@ +DROP TRIGGER IF EXISTS referral_codes_disable_discount ON referral_codes; +DROP FUNCTION IF EXISTS disable_referral_discount(); diff --git a/internal/infrastructure/db/migrations/000360_referral_discount_follows_its_code.up.sql b/internal/infrastructure/db/migrations/000360_referral_discount_follows_its_code.up.sql new file mode 100644 index 000000000..8854db4a9 --- /dev/null +++ b/internal/infrastructure/db/migrations/000360_referral_discount_follows_its_code.up.sql @@ -0,0 +1,22 @@ +-- A referral discount is redeemable only while its referral code exists, so +-- removing the code (directly or with its owner) disables the discount. +CREATE OR REPLACE FUNCTION disable_referral_discount() RETURNS trigger AS $$ +BEGIN + IF OLD.discount_code_id IS NOT NULL THEN + UPDATE discount_codes SET status = 'disabled', updated_at = now() + WHERE id = OLD.discount_code_id AND status = 'active'; + END IF; + RETURN OLD; +END; +$$ LANGUAGE plpgsql; + +DROP TRIGGER IF EXISTS referral_codes_disable_discount ON referral_codes; +CREATE TRIGGER referral_codes_disable_discount + AFTER DELETE ON referral_codes + FOR EACH ROW EXECUTE FUNCTION disable_referral_discount(); + +-- Referral discounts whose code is already gone. +UPDATE discount_codes dc SET status = 'disabled', updated_at = now() + WHERE dc.status = 'active' + AND dc.description = 'Referral reward: 10% off for 3 months' + AND NOT EXISTS (SELECT 1 FROM referral_codes rc WHERE rc.discount_code_id = dc.id); From 755568c3850553019e6a05bc8d538ea398706c85 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sat, 7 Nov 2026 07:12:37 +0100 Subject: [PATCH 279/318] feat: load the dashboard's closed overlays (modals, compose, command palette, agent panel, tour) lazily so the shell paints sooner, and replace the boot skeleton with the real header, sidebar and list page drawn in outline under one shared soft light sweep and a sky progress line --- qa/flows/loading-frame.flow.ts | 23 ++++ web/src/app/app/layout.tsx | 33 +++--- web/src/components/layout/AppShell.tsx | 24 ++-- web/src/components/layout/RouteStates.tsx | 135 +++++++++++++++++++--- web/src/global.css | 19 ++- 5 files changed, 193 insertions(+), 41 deletions(-) create mode 100644 qa/flows/loading-frame.flow.ts diff --git a/qa/flows/loading-frame.flow.ts b/qa/flows/loading-frame.flow.ts new file mode 100644 index 000000000..7034ca6dd --- /dev/null +++ b/qa/flows/loading-frame.flow.ts @@ -0,0 +1,23 @@ +import { env } from "../lib/env.ts"; +import { expect, test } from "../lib/proof.ts"; + +test("the dashboard boots into its own frame drawn in outline", async ({ page, proof }) => { + // Holds every API call so the boot state stays on screen until the shot is taken. + let release = () => {}; + const held = new Promise((resolve) => (release = resolve)); + await page.route(`${env.apiURL}/**`, async (route) => { + await held; + await route.continue(); + }); + + await page.goto("/app/emails"); + await expect(page.getByRole("status", { name: "Loading" }).first()).toBeVisible(); + await proof.chapter("Loading", "Header, sidebar and a list page in outline, lit by one shared sweep"); + await proof.dwell(3200); + await proof.shot("loading-frame", { caption: "The boot state while the session loads" }); + + release(); + await expect(page.getByRole("row", { name: /dev\.outbound@warmbly\.test/ })).toBeVisible(); + await proof.chapter("Loaded", "The real page fills the same frame"); + await proof.shot("mailboxes-loaded", { caption: "Mailboxes once the session has loaded" }); +}); diff --git a/web/src/app/app/layout.tsx b/web/src/app/app/layout.tsx index 83e8243a3..a803591fb 100644 --- a/web/src/app/app/layout.tsx +++ b/web/src/app/app/layout.tsx @@ -10,13 +10,16 @@ import { RealtimeManager } from "@/hooks/RealtimeManager"; import { OrgGate } from "@/hooks/OrgGate"; import { RestrictedRouteGuard } from "@/hooks/RestrictedRouteGuard"; import { ErrorContext } from "@/hooks/ErrorContext"; -import TagsModal from "@/components/app/modals/TagsModal"; -import FoldersModal from "@/components/app/modals/FoldersModal"; -import AddEmailModal from "@/components/app/modals/AddEmailModal"; -import ComposeWindow from "@/components/app/unibox/compose/ComposeWindow"; -import PasskeyEnrollPrompt from "@/components/app/modals/PasskeyEnrollPrompt"; -import PermissionDeniedModal from "@/components/app/modals/PermissionDeniedModal"; -import ReauthModal from "@/components/app/modals/ReauthModal"; +import { lazy, Suspense } from "react"; + +// Closed until opened, so their code (the editor, the mailbox wizard) loads beside the page instead of ahead of the frame. +const TagsModal = lazy(() => import("@/components/app/modals/TagsModal")); +const FoldersModal = lazy(() => import("@/components/app/modals/FoldersModal")); +const AddEmailModal = lazy(() => import("@/components/app/modals/AddEmailModal")); +const ComposeWindow = lazy(() => import("@/components/app/unibox/compose/ComposeWindow")); +const PasskeyEnrollPrompt = lazy(() => import("@/components/app/modals/PasskeyEnrollPrompt")); +const PermissionDeniedModal = lazy(() => import("@/components/app/modals/PermissionDeniedModal")); +const ReauthModal = lazy(() => import("@/components/app/modals/ReauthModal")); export default function RootAppLayout() { // The route already checked the session (bootDashboard in router.tsx). @@ -56,13 +59,15 @@ export default function RootAppLayout() { - - - - - - - + + + + + + + + + diff --git a/web/src/components/layout/AppShell.tsx b/web/src/components/layout/AppShell.tsx index 9d272cc0b..434b929c7 100644 --- a/web/src/components/layout/AppShell.tsx +++ b/web/src/components/layout/AppShell.tsx @@ -15,7 +15,7 @@ // where it meets the chrome's inner corner. Reads as one continuous // frame around a clean work surface. -import { Suspense, useEffect, useRef, useState } from "react"; +import { lazy, Suspense, useEffect, useRef, useState } from "react"; import { Outlet, useLocation } from "@tanstack/react-router"; import SubscriptionGate from "./SubscriptionGate"; import { SkyChrome } from "./SkyChrome"; @@ -24,16 +24,18 @@ import { AppNav } from "./AppNav"; import PendingDeletionBar from "./PendingDeletionBar"; import SendingRestrictedBar from "./SendingRestrictedBar"; import { RouteBoundary } from "./ErrorBoundary"; -import { ShortcutsModal } from "@/components/shared/ShortcutsModal"; -import { CommandPalette } from "@/components/shared/CommandPalette"; import { useKeyboardShortcuts } from "@/hooks/useKeyboardShortcuts"; import { GlobalCursorsProvider } from "@/components/app/presence/GlobalCursors"; -import AgentPanel from "@/components/app/agent/AgentPanel"; -import ProductTourHost from "@/components/app/tour/ProductTourHost"; import { useRouteKey } from "@/hooks/useRouteKey"; import { useScrollMemory, type ScrollStore } from "@/hooks/useScrollMemory"; import { RouteFallback } from "./RouteStates"; +// Overlays closed on first paint, so the frame does not wait on their code. +const ShortcutsModal = lazy(() => import("@/components/shared/ShortcutsModal").then((m) => ({ default: m.ShortcutsModal }))); +const CommandPalette = lazy(() => import("@/components/shared/CommandPalette").then((m) => ({ default: m.CommandPalette }))); +const AgentPanel = lazy(() => import("@/components/app/agent/AgentPanel")); +const ProductTourHost = lazy(() => import("@/components/app/tour/ProductTourHost")); + // Per history entry, kept apart so ordinary browsing never evicts a list's remembered offset. const entryOffsets: ScrollStore = new Map(); @@ -99,11 +101,13 @@ export function AppShell() {
    - - - {/* Right-side AI assistant, persistent across routes. */} - - + + + + {/* Right-side AI assistant, persistent across routes. */} + + +
    ); } diff --git a/web/src/components/layout/RouteStates.tsx b/web/src/components/layout/RouteStates.tsx index b027ec524..46480daaa 100644 --- a/web/src/components/layout/RouteStates.tsx +++ b/web/src/components/layout/RouteStates.tsx @@ -1,7 +1,7 @@ -// Loading and error states for routes; the boot state is the dashboard's own empty frame, so nothing moves. +// Loading and error states for routes; the boot state is the dashboard's own frame drawn in outline, so nothing moves when it fills in. import { useRouter, type ErrorComponentProps } from "@tanstack/react-router"; -import { useEffect } from "react"; +import { useEffect, type CSSProperties } from "react"; import { Logo } from "@/components/svg"; import { cn } from "@/lib/utils"; import { captureException } from "@/lib/observability"; @@ -9,13 +9,60 @@ import { useAppStore } from "@/stores"; import { SkyChrome } from "./SkyChrome"; import { BoundaryFallback } from "./ErrorBoundary"; -// A page still loading: the same hairline blocks the pages draw themselves. +// Fixed widths, so the outline reads as real labels and never reshuffles between renders. +const LABEL_WIDTHS = [62, 78, 54, 70, 46, 84, 58, 66, 50, 74, 60, 42, 68, 56, 80, 48]; +// Rows per sidebar section, as AppNav draws them: Inbox, then Email, CRM and Resources. +const NAV_SECTIONS = [1, 7, 4, 5]; +const TABLE_ROWS = 9; + +const rise = (i: number): CSSProperties => ({ animationDelay: `${60 + i * 35}ms` }); +const RISE = "animate-in fade-in slide-in-from-bottom-1 duration-500 fill-mode-both motion-reduce:animate-none"; + +function Bar({ className, style }: { className?: string; style?: CSSProperties }) { + return
    ; +} + +// A page still loading: a list page in outline, its rows settling in one after another. export function RouteFallback() { return ( -
    -
    -
    -
    +
    +
    +
    + + +
    +
    + + +
    +
    +
    + + + +
    +
    +
    + + + + + +
    + {Array.from({ length: TABLE_ROWS }, (_, i) => ( +
    + + +
    + + +
    + + + +
    + ))} +
    ); } @@ -42,23 +89,79 @@ export function RouteError({ error, reset, info }: ErrorComponentProps) { ); } -// The dashboard frame with nothing in it yet, shown while the session boots. +function NavOutline({ collapsed }: { collapsed: boolean }) { + let row = 0; + return ( +
    + {NAV_SECTIONS.map((count, s) => ( +
    0 && "mt-4")}> + {s > 0 && !collapsed && } +
    + {Array.from({ length: count }, () => { + const i = row++; + return ( +
    + + {!collapsed && } +
    + ); + })} +
    +
    + ))} +
    +
    + + {!collapsed && } +
    +
    +
    + + {!collapsed && ( +
    + + +
    + )} +
    +
    + ); +} + +// The dashboard frame in outline, shown while the session boots: the real header, sidebar and a page, filled in place. export function ShellSkeleton() { const collapsed = useAppStore((s) => s.navCollapsed); return (
    -
    - +
    +
    + + + Warmbly + +
    +
    + + + +
    +
    + + + +
    -
    - {Array.from({ length: 7 }, (_, i) => ( -
    - ))} -
    -
    + +
    +
    +
    +
    diff --git a/web/src/global.css b/web/src/global.css index 96b4148ad..aa8d00c14 100644 --- a/web/src/global.css +++ b/web/src/global.css @@ -283,8 +283,25 @@ svg.loading circle { .dark .skeleton-shimmer { background-image: linear-gradient(90deg, #1c1d20 0%, #1c1d20 35%, #26272b 50%, #1c1d20 65%, #1c1d20 100%); } +/* One beam across the whole viewport, so every block of a loading frame lights in step. */ +@keyframes skeleton-sync { + from { background-position: -140vw 0; } + 75%, to { background-position: 40vw 0; } +} +.skeleton-sync { + background-color: rgb(100 116 139 / 0.1); + background-image: linear-gradient(100deg, transparent 32%, rgb(255 255 255 / 0.18) 41%, rgb(255 255 255 / 0.42) 50%, rgb(255 255 255 / 0.18) 59%, transparent 68%); + background-size: 200vw 100%; + background-repeat: no-repeat; + background-attachment: fixed; + animation: skeleton-sync 3.2s ease-in-out infinite; +} +.dark .skeleton-sync { + background-color: rgb(255 255 255 / 0.05); + background-image: linear-gradient(100deg, transparent 32%, rgb(255 255 255 / 0.02) 41%, rgb(255 255 255 / 0.05) 50%, rgb(255 255 255 / 0.02) 59%, transparent 68%); +} @media (prefers-reduced-motion: reduce) { - .skeleton-shimmer, .progress-sweep { animation: none; } + .skeleton-shimmer, .skeleton-sync, .progress-sweep { animation: none; } } @keyframes ai-caret-blink { 0%, 49% { opacity: 1; } From ba07007fc005c040d829786aee48860199683c38 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sat, 7 Nov 2026 07:25:24 +0100 Subject: [PATCH 280/318] feat: hand Gmail warmup engagement that fails over IMAP to the Gmail API (resolving the Gmail id when needed) and retry IMAP six hours after a refusal the worker saw, keep a vendor consent pending or settled across cache errors and racing callbacks, refuse a personal Gmail address at the end of Google sign-in, let a domain whose Google mailboxes arrived in a workspace import make its grant again, offer Google reconnects only where the instance has a Google client, batch bulk vendor reconnects by 1000, and confirm before discarding a typed app password --- docs/content/docs/api/reference/mailboxes.mdx | 4 +-- internal/app/delegation/proof.go | 10 +++++- internal/app/delegation/service.go | 2 +- internal/app/delegation/service_test.go | 15 ++++++++ internal/app/email/broker.go | 3 ++ internal/app/email/onboarding.go | 4 +++ internal/app/email/vendor_consent.go | 7 +++- internal/app/vendorconn/consent.go | 10 +++++- internal/app/worker/event_warmup_action.go | 24 ++++++++----- .../app/worker/event_warmup_gmail_imap.go | 35 ++++++++++--------- internal/app/worker/warmup_gmail_imap_test.go | 7 ++-- internal/app/worker/wmail/gmail_imap.go | 30 +++++++++++++--- internal/app/worker/wmail/wmail.go | 2 +- internal/repository/pg_email_auth.go | 10 +++++- internal/repository/pg_mailbox_sources.go | 14 ++++++++ .../app/emails/GoogleWorkspaceSigninPanel.tsx | 4 +-- .../import/vendors/VendorAccountStep.tsx | 5 ++- .../emails/migration/MailboxSigninSection.tsx | 18 ++++++++-- .../migration/SigninMigrationBanner.tsx | 10 ++++-- .../migration/SigninMigrationDialog.tsx | 4 +-- .../app/emails/migration/migrationRoute.ts | 5 +-- .../components/app/modals/AddEmailModal.tsx | 5 ++- web/src/hooks/useRealtimeEvents.ts | 2 +- .../api/hooks/app/emails/useMailboxVendors.ts | 5 +-- 24 files changed, 179 insertions(+), 56 deletions(-) diff --git a/docs/content/docs/api/reference/mailboxes.mdx b/docs/content/docs/api/reference/mailboxes.mdx index 612944043..82f0ea224 100644 --- a/docs/content/docs/api/reference/mailboxes.mdx +++ b/docs/content/docs/api/reference/mailboxes.mdx @@ -821,7 +821,7 @@ Response: `201 Created` with the new mailbox object. `POST /emails/onboarding/app-password/:id` -Moves a mailbox connected with per-mailbox Google sign-in onto Gmail's IMAP and SMTP with a Google app password. Session only, and needs the `manage_emails` organization permission. +Moves a Google mailbox connected with per-mailbox Google sign-in or through an administrator grant onto Gmail's IMAP and SMTP with a Google app password. Session only, and needs the `manage_emails` organization permission. | Field | Type | Required | Description | |-------|------|----------|-------------| @@ -835,7 +835,7 @@ Moves a mailbox connected with per-mailbox Google sign-in onto Gmail's IMAP and The password is checked against `imap.gmail.com` and `smtp.gmail.com` before anything is stored, and refused with the same codes as [Connect SMTP/IMAP](#connect-smtpimap) (such as `mailbox_auth_refused`); a refusal changes nothing. On success the mailbox becomes `smtp_imap` with `auth_method` `app_password` in place: its id, imported mail, campaigns, warmup and settings stay, and sync continues with new mail. -Response: `200 OK` with the mailbox object. `409` `mailbox_not_google_signin` when the mailbox is not on per-mailbox Google sign-in (including one already switched, so a repeat changes nothing), and `400` `app_password_invalid` when the value is not 16 letters. +Response: `200 OK` with the mailbox object. `409` `mailbox_not_google_signin` when the mailbox is on neither per-mailbox Google sign-in nor an administrator grant, or Warmbly Cloud holds its sign-in (including one already switched, so a repeat changes nothing), and `400` `app_password_invalid` when the value is not 16 letters. ## Connect many mailboxes diff --git a/internal/app/delegation/proof.go b/internal/app/delegation/proof.go index 0f16927cc..a76370e50 100644 --- a/internal/app/delegation/proof.go +++ b/internal/app/delegation/proof.go @@ -167,7 +167,7 @@ func cleanDomainAdmin(domain, admin string) (string, string, *errx.Error) { return domain, admin, nil } -// googleRetired refuses a Google grant for a domain the workspace holds no grant for; an existing one may be proved again. +// googleRetired refuses a Google grant for a domain the workspace holds no grant for; an existing or imported one may be proved again. func (s *Service) googleRetired(ctx context.Context, orgID uuid.UUID, domain string) *errx.Error { list, err := s.repo.List(ctx, orgID) if err != nil { @@ -178,6 +178,14 @@ func (s *Service) googleRetired(ctx context.Context, orgID uuid.UUID, domain str return nil } } + // Mailboxes that arrived in a workspace import without their grant are restored by making it again. + awaiting, err := s.repo.AwaitsGoogleGrant(ctx, orgID, domain) + if err != nil { + return errx.InternalError() + } + if awaiting { + return nil + } return errx.NewWithIdentifier(errx.Forbidden, ErrIDGoogleRetired, "New Google Workspace domain-wide delegation grants are no longer set up. Have a Workspace administrator mark Warmbly as a trusted app, then sign in each mailbox with Google, or connect it with an app password. Grants already made keep working. See https://docs.warmbly.com/guides/mailboxes/#google-workspace-with-google-sign-in") } diff --git a/internal/app/delegation/service.go b/internal/app/delegation/service.go index 4880b4459..c6deae000 100644 --- a/internal/app/delegation/service.go +++ b/internal/app/delegation/service.go @@ -426,7 +426,7 @@ func unavailable(err error) bool { } var re *oauth2.RetrieveError if errors.As(err, &re) { - return re.Response != nil && re.Response.StatusCode >= 500 + return re.Response != nil && (re.Response.StatusCode >= 500 || re.Response.StatusCode == http.StatusTooManyRequests) } return true } diff --git a/internal/app/delegation/service_test.go b/internal/app/delegation/service_test.go index 416e0c54b..46e6073e4 100644 --- a/internal/app/delegation/service_test.go +++ b/internal/app/delegation/service_test.go @@ -30,6 +30,8 @@ import ( type memGrants struct { mu sync.Mutex grants map[uuid.UUID]*models.DomainGrant + // awaiting is a domain with imported mailboxes waiting on their grant. + awaiting bool } func (m *memGrants) Upsert(_ context.Context, g *models.DomainGrant, _ uuid.UUID) error { @@ -95,6 +97,9 @@ func (m *memGrants) ListActive(context.Context) ([]models.DomainGrant, error) { func (m *memGrants) InactiveMailboxes(context.Context, uuid.UUID) ([]uuid.UUID, error) { return nil, nil } +func (m *memGrants) AwaitsGoogleGrant(context.Context, uuid.UUID, string) (bool, error) { + return m.awaiting, nil +} type fakeMailboxes struct{ connected []models.NewDelegatedAccount } @@ -424,6 +429,16 @@ func TestNewGoogleGrantsAreRetired(t *testing.T) { } } +// Mailboxes that arrived in a workspace import without their grant let the domain be proved again. +func TestImportedMailboxesReopenTheirGoogleGrant(t *testing.T) { + s, _, grants, _, _ := newTestService(t) + grants.awaiting = true + org, user := uuid.New(), uuid.New() + if _, xerr := s.StartGoogle(context.Background(), org, user, "acme.io", "admin"+"@acme.io"); xerr != nil { + t.Fatalf("start for imported mailboxes = %v", xerr) + } +} + // The per-mailbox sign-in client is named whenever one is configured, so a reconnect can show it too. func TestConfigNamesTheMailboxClient(t *testing.T) { s := NewService(Deps{GoogleMailboxClientID: "mailbox-client.apps.googleusercontent.com"}) diff --git a/internal/app/email/broker.go b/internal/app/email/broker.go index 47c852912..cce92f29f 100644 --- a/internal/app/email/broker.go +++ b/internal/app/email/broker.go @@ -89,6 +89,9 @@ func (s *emailService) OAuthConnectWithCodeForAccount(ctx context.Context, userI } else if existing != nil { return nil, errx.ErrEmailOnboardAlreadyExists } + if provider == models.InboxProviderGoogle && personalGmail(owner.Email) { + return nil, errx.ErrEmailOnboardGooglePersonal + } name := strings.TrimSpace(owner.Name) if name == "" { name = deriveNameFromEmail(owner.Email) diff --git a/internal/app/email/onboarding.go b/internal/app/email/onboarding.go index 1940c92b5..51f263aa0 100644 --- a/internal/app/email/onboarding.go +++ b/internal/app/email/onboarding.go @@ -222,6 +222,10 @@ func (s *emailService) OAuthFinish(ctx context.Context, userID, code, state stri } else if existing != nil { return nil, false, errx.ErrEmailOnboardAlreadyExists } + // The login hint is optional, so the address Google returned decides. + if provider == models.InboxProviderGoogle && personalGmail(owner.Email) { + return nil, false, errx.ErrEmailOnboardGooglePersonal + } acc, xerr := s.createOAuthMailbox(ctx, userID, sess.OrganizationID, allowance, provider, tok, owner) return acc, false, xerr diff --git a/internal/app/email/vendor_consent.go b/internal/app/email/vendor_consent.go index 896e8b93e..27711bd9e 100644 --- a/internal/app/email/vendor_consent.go +++ b/internal/app/email/vendor_consent.go @@ -285,7 +285,12 @@ func (s *emailService) vendorReconnectTarget(ctx context.Context, orgID, account return nil, 0, ErrVendorConsentWrongMailbox } if s.cloudLink != nil { - if m, err := s.cloudLink.GetByAccount(ctx, accountID); err == nil && m != nil && m.Managed { + m, err := s.cloudLink.GetByAccount(ctx, accountID) + if err != nil { + // Unknown is not unmanaged: no consent is asked for a mailbox Warmbly Cloud may hold. + return nil, 0, errx.InternalError() + } + if m != nil && m.Managed { return nil, 0, errx.ErrEmailReauthCloudManaged } } diff --git a/internal/app/vendorconn/consent.go b/internal/app/vendorconn/consent.go index 0d7940131..737e534fb 100644 --- a/internal/app/vendorconn/consent.go +++ b/internal/app/vendorconn/consent.go @@ -263,6 +263,14 @@ func (s *Service) consentMailbox(ctx context.Context, c *models.VendorConnection return fail(reason) } if next != st { + // The callback may have settled it while the status was read; a settled outcome is never replaced. + var cur consentState + if err := s.cache.GetJSON(ctx, key, &cur); err == nil && (cur.Done || cur.Failed != "") { + if cur.Done { + return DomainAuthorization{} + } + return DomainAuthorization{Message: cur.Failed} + } _ = s.cache.SetJSON(ctx, key, next, time.Until(next.Started.Add(consentStateTTL))) } note := pendingNote(label, "", clientID, nil, next.RequestID, mailvendor.AuthorizationStatus{Stage: next.Stage, UpdatedAt: next.UpdatedAt}, now) @@ -271,7 +279,7 @@ func (s *Service) consentMailbox(ctx context.Context, c *models.VendorConnection started, err := s.cache.SetNX(ctx, key, "{}", authStartTTL).Result() if err != nil { - return DomainAuthorization{} + return DomainAuthorization{Pending: true, SigningIn: true, Vendor: label} } if !started { return DomainAuthorization{Pending: true, SigningIn: true, Vendor: label} diff --git a/internal/app/worker/event_warmup_action.go b/internal/app/worker/event_warmup_action.go index 45f9bf399..b6812a5a7 100644 --- a/internal/app/worker/event_warmup_action.go +++ b/internal/app/worker/event_warmup_action.go @@ -280,6 +280,14 @@ func (w *WorkerService) runGoogleWarmupActions(ctx context.Context, mail *wmail. // Engagement goes over IMAP; filing, deletion and anything IMAP could not settle stay on the API. settled := w.runGmailIMAPEngagement(ctx, mail, action, rescue) + if gmailID == "" && action.RFCMessageID != "" && unsettledEngagement(action.Actions, settled) { + // A mailbox that switched sign-in while this was queued has no Gmail id yet; the API needs one. + if id, err := mail.GoogleData.Client.FindByRFCMessageID(ctx, action.RFCMessageID); err == nil { + gmailID = id + } else { + log.Error().Err(err).Str("email_id", action.EmailID.String()).Msg("Failed to find the warmup message (Gmail)") + } + } for _, act := range action.Actions { if settled[act] { continue @@ -302,24 +310,24 @@ func (w *WorkerService) runGoogleWarmupActions(ctx context.Context, mail *wmail. return err } case models.WarmupActionMarkRead: - if err := mail.GoogleData.Client.MarkAsRead(ctx, action.GmailID); err != nil { - log.Error().Err(err).Str("gmail_id", action.GmailID).Msg("Failed to mark as read") + if err := mail.GoogleData.Client.MarkAsRead(ctx, gmailID); err != nil { + log.Error().Err(err).Str("gmail_id", gmailID).Msg("Failed to mark as read") } case models.WarmupActionRescueFromSpam: toInbox := placement == models.WarmupPlacementInbox - if err := mail.GoogleData.Client.RescueFromSpam(ctx, action.GmailID, label, toInbox); err != nil { - log.Error().Err(err).Str("gmail_id", action.GmailID).Msg("Failed to rescue from spam (Gmail)") + if err := mail.GoogleData.Client.RescueFromSpam(ctx, gmailID, label, toInbox); err != nil { + log.Error().Err(err).Str("gmail_id", gmailID).Msg("Failed to rescue from spam (Gmail)") setRescue(rescue, rescueFailure(err)) } else { setRescue(rescue, models.WarmupRescueMoved) } case models.WarmupActionMarkImportant: - if err := mail.GoogleData.Client.MarkImportant(ctx, action.GmailID); err != nil { - log.Error().Err(err).Str("gmail_id", action.GmailID).Msg("Failed to mark important") + if err := mail.GoogleData.Client.MarkImportant(ctx, gmailID); err != nil { + log.Error().Err(err).Str("gmail_id", gmailID).Msg("Failed to mark important") } case models.WarmupActionStar: - if err := mail.GoogleData.Client.AddStar(ctx, action.GmailID); err != nil { - log.Error().Err(err).Str("gmail_id", action.GmailID).Msg("Failed to star warmup message") + if err := mail.GoogleData.Client.AddStar(ctx, gmailID); err != nil { + log.Error().Err(err).Str("gmail_id", gmailID).Msg("Failed to star warmup message") } default: log.Warn().Str("action", act).Msg("Unknown warmup action") diff --git a/internal/app/worker/event_warmup_gmail_imap.go b/internal/app/worker/event_warmup_gmail_imap.go index 97a9f1f6e..9c5923bd8 100644 --- a/internal/app/worker/event_warmup_gmail_imap.go +++ b/internal/app/worker/event_warmup_gmail_imap.go @@ -28,6 +28,16 @@ func gmailIMAPAction(act string) bool { return false } +// unsettledEngagement reports an engagement action IMAP left for the API. +func unsettledEngagement(acts []string, settled map[string]bool) bool { + for _, act := range acts { + if gmailIMAPAction(act) && !settled[act] { + return true + } + } + return false +} + // gmailIMAPRefusal names why IMAP can never serve this mailbox, or "" for a failure worth retrying. func gmailIMAPRefusal(err error) string { if errors.Is(err, wmail.ErrGmailIMAPScope) { @@ -79,11 +89,8 @@ func (w *WorkerService) runGmailIMAPEngagement(ctx context.Context, mail *wmail. case errors.Is(err, errGmailIMAPCannot), errors.Is(err, errGmailIMAPNotFound), imap.Refused(err): log.Debug().Err(err).Str("email_id", action.EmailID.String()).Str("action", act).Msg("Warmup action handed to the Gmail API") default: - log.Error().Err(err).Str("email_id", action.EmailID.String()).Str("action", act).Msg("Warmup action failed (Gmail IMAP)") - settled[act] = true - if act == models.WarmupActionRescueFromSpam { - setRescue(rescue, models.WarmupRescueFailed) - } + // The API gets the next try; it records the failure if it cannot do it either. + log.Warn().Err(err).Str("email_id", action.EmailID.String()).Str("action", act).Msg("Warmup action failed over Gmail IMAP; trying the Gmail API") } } return nil @@ -98,16 +105,8 @@ func (w *WorkerService) runGmailIMAPEngagement(ctx context.Context, mail *wmail. } return settled } - // A dial or listing that failed on the network is a failed attempt, like any other provider failure. - log.Error().Err(err).Str("email_id", action.EmailID.String()).Strs("actions", acts).Msg("Warmup engagement failed (Gmail IMAP)") - for _, act := range acts { - if !settled[act] { - settled[act] = true - if act == models.WarmupActionRescueFromSpam { - setRescue(rescue, models.WarmupRescueFailed) - } - } - } + // A dial or listing that failed on the network leaves the rest to the API. + log.Warn().Err(err).Str("email_id", action.EmailID.String()).Strs("actions", acts).Msg("Warmup engagement failed over Gmail IMAP; trying the Gmail API") return settled } @@ -192,9 +191,13 @@ func (e *gmailEngagement) rescue(ctx context.Context, rescue *string) error { } return nil } - if _, err := e.s.MoveToFolder(ctx, e.junk, e.filingDest, uid); err != nil { + moved, err := e.s.MoveToFolder(ctx, e.junk, e.filingDest, uid) + if err != nil { return err } + if !moved { + return errGmailIMAPCannot + } e.at.folder, e.at.uid = "", 0 setRescue(rescue, models.WarmupRescueMoved) return nil diff --git a/internal/app/worker/warmup_gmail_imap_test.go b/internal/app/worker/warmup_gmail_imap_test.go index 1b7fb1a0d..d27057ca8 100644 --- a/internal/app/worker/warmup_gmail_imap_test.go +++ b/internal/app/worker/warmup_gmail_imap_test.go @@ -122,13 +122,13 @@ func TestGmailRescueOutcomes(t *testing.T) { }{ {"already out of spam", map[string]uint32{"[Gmail]/All Mail": 3}, nil, models.WarmupRescueAlreadyOut}, {"nowhere", map[string]uint32{}, nil, models.WarmupRescueGone}, - {"search failed on the network", map[string]uint32{}, errx.ErrMailServerUnreachable, models.WarmupRescueFailed}, + {"search failed on the network, left to the API", map[string]uint32{}, errx.ErrMailServerUnreachable, ""}, } { s := &gmailSession{folders: gmailFolders(), held: tc.held, findErr: tc.findErr} outcome := "" settled := (&WorkerService{}).runGmailIMAPEngagement(context.Background(), (&gmailDialer{session: s}).mail(), gmailAction(models.WarmupPlacementFolder, models.WarmupActionRescueFromSpam), &outcome) - if !settled[models.WarmupActionRescueFromSpam] || outcome != tc.want || len(s.calls) != 0 { + if settled[models.WarmupActionRescueFromSpam] != (tc.want != "") || outcome != tc.want || len(s.calls) != 0 { t.Fatalf("%s: settled=%v outcome=%q calls=%v", tc.name, settled, outcome, s.calls) } } @@ -179,6 +179,7 @@ func TestGmailIMAPRefusalIsRememberedForTheMailbox(t *testing.T) { } } +// A network failure leaves the action to the Gmail API for this batch and is not remembered as a refusal. func TestGmailIMAPNetworkFailureIsNotAFallback(t *testing.T) { d := &gmailDialer{err: errx.ErrMailServerUnreachable} mail := d.mail() @@ -186,7 +187,7 @@ func TestGmailIMAPNetworkFailureIsNotAFallback(t *testing.T) { for range 2 { outcome := "" settled := w.runGmailIMAPEngagement(context.Background(), mail, gmailAction(models.WarmupPlacementInbox, models.WarmupActionRescueFromSpam), &outcome) - if !settled[models.WarmupActionRescueFromSpam] || outcome != models.WarmupRescueFailed { + if settled[models.WarmupActionRescueFromSpam] || outcome != "" { t.Fatalf("settled=%v outcome=%q", settled, outcome) } } diff --git a/internal/app/worker/wmail/gmail_imap.go b/internal/app/worker/wmail/gmail_imap.go index 6b785fa32..26598d203 100644 --- a/internal/app/worker/wmail/gmail_imap.go +++ b/internal/app/worker/wmail/gmail_imap.go @@ -43,7 +43,17 @@ type GmailIMAP struct { mu sync.Mutex session GmailIMAPSession gen uint64 - refused atomic.Pointer[string] + refused atomic.Pointer[gmailIMAPRefusal] +} + +// gmailIMAPRetryAfter is how long a refusal the worker saw itself holds before IMAP is tried again, so a repaired grant takes effect. +const gmailIMAPRetryAfter = 6 * time.Hour + +type gmailIMAPRefusal struct { + reason string + at time.Time + // standing is the control plane's answer, which a republished mailbox replaces. + standing bool } // NewGmailIMAP dials imap.gmail.com with the mailbox's own OAuth token source. @@ -78,15 +88,25 @@ func NewGmailIMAP(lifetime context.Context, email string, tokens oauth2.TokenSou // Refused is why this mailbox's engagement runs through the Gmail API, or "" while IMAP is in use. func (g *GmailIMAP) Refused() string { - if r := g.refused.Load(); r != nil { - return *r + r := g.refused.Load() + if r == nil { + return "" } - return "" + if !r.standing && time.Since(r.at) > gmailIMAPRetryAfter { + g.refused.CompareAndSwap(r, nil) + return "" + } + return r.reason } // Refuse records that IMAP cannot serve this mailbox; true only for the first call. func (g *GmailIMAP) Refuse(reason string) bool { - return g.refused.CompareAndSwap(nil, &reason) + return g.refused.CompareAndSwap(nil, &gmailIMAPRefusal{reason: reason, at: time.Now()}) +} + +// RefuseStanding records the control plane's refusal, which holds for the life of this mailbox. +func (g *GmailIMAP) RefuseStanding(reason string) { + g.refused.Store(&gmailIMAPRefusal{reason: reason, at: time.Now(), standing: true}) } // With runs fn on the mailbox's session, dialing it first when none is open; batches never overlap. diff --git a/internal/app/worker/wmail/wmail.go b/internal/app/worker/wmail/wmail.go index 8e87a0a62..5d1b6143c 100644 --- a/internal/app/worker/wmail/wmail.go +++ b/internal/app/worker/wmail/wmail.go @@ -268,7 +268,7 @@ func NewWMail( mail.GoogleData.IMAP = NewGmailIMAP(mailCtx, data.Email, imapTokens) // The control plane knows the stored consent lacks full mail access, so IMAP is not even tried. if f := data.Google.FullMailAccess; f != nil && !*f { - mail.GoogleData.IMAP.Refuse(ErrGmailIMAPScope.Error()) + mail.GoogleData.IMAP.RefuseStanding(ErrGmailIMAPScope.Error()) } case models.InboxProviderOutlook: // Microsoft/Outlook mailboxes run entirely on Microsoft Graph: RAW MIME diff --git a/internal/repository/pg_email_auth.go b/internal/repository/pg_email_auth.go index 394c4f50a..f3a85a0a8 100644 --- a/internal/repository/pg_email_auth.go +++ b/internal/repository/pg_email_auth.go @@ -180,6 +180,9 @@ func (r *emailRepository) RefreshBoxToken(ctx context.Context, id uuid.UUID, acc return nil } +// ErrNoOAuthRow is a token replacement for a mailbox that no longer signs in with OAuth. +var ErrNoOAuthRow = errors.New("mailbox has no OAuth sign-in to replace") + // ReplaceBoxToken is RefreshBoxToken for a new consent, which also records what it granted. func (r *emailRepository) ReplaceBoxToken(ctx context.Context, id uuid.UUID, accessToken, refreshToken string, expiresAt time.Time, scopes []string) error { orgID, err := r.mailboxOrganization(ctx, id) @@ -197,11 +200,16 @@ func (r *emailRepository) ReplaceBoxToken(ctx context.Context, id uuid.UUID, acc query := `UPDATE email_accounts_oauth SET access_token = $1, refresh_token = $2, expires_at = $3, granted_scopes = $4, updated_at = now() WHERE email_account_id = $5` - if _, err := r.DB.Exec(ctx, query, sealed[0], sealed[1], expiresAt, scopes, id); err != nil { + tag, err := r.DB.Exec(ctx, query, sealed[0], sealed[1], expiresAt, scopes, id) + if err != nil { // The parameters hold the sealed tokens; keep them out of the error report. db.CaptureError(err, query, nil, "exec") return err } + // A mailbox whose sign-in changed meanwhile has no token row; the new consent must not read as stored. + if tag.RowsAffected() == 0 { + return ErrNoOAuthRow + } return nil } diff --git a/internal/repository/pg_mailbox_sources.go b/internal/repository/pg_mailbox_sources.go index 99a77509f..c821e5cac 100644 --- a/internal/repository/pg_mailbox_sources.go +++ b/internal/repository/pg_mailbox_sources.go @@ -29,6 +29,8 @@ type DomainGrantRepository interface { ListActive(ctx context.Context) ([]models.DomainGrant, error) // InactiveMailboxes are the grant's mailboxes a failure took out of work, never one switched off by hand. InactiveMailboxes(ctx context.Context, id uuid.UUID) ([]uuid.UUID, error) + // AwaitsGoogleGrant reports Google mailboxes on the domain that sign in through a grant the workspace no longer holds, as after an import. + AwaitsGoogleGrant(ctx context.Context, orgID uuid.UUID, domain string) (bool, error) } type domainGrantRepository struct{ DB *db.DB } @@ -362,3 +364,15 @@ func (r *vendorConnectionRepository) ReconnectCandidates(ctx context.Context, li } return out, rows.Err() } + +func (r *domainGrantRepository) AwaitsGoogleGrant(ctx context.Context, orgID uuid.UUID, domain string) (bool, error) { + query := `SELECT EXISTS (SELECT 1 FROM email_accounts + WHERE organization_id = $1 AND provider = 'gmail' AND auth_method = 'delegated' AND domain_grant_id IS NULL + AND lower(split_part(email, '@', 2)) = $2)` + var ok bool + if err := r.DB.QueryRow(ctx, query, orgID, strings.ToLower(domain)).Scan(&ok); err != nil { + db.CaptureError(err, query, nil, "queryrow") + return false, err + } + return ok, nil +} diff --git a/web/src/components/app/emails/GoogleWorkspaceSigninPanel.tsx b/web/src/components/app/emails/GoogleWorkspaceSigninPanel.tsx index 43bd521a0..410dcf1b9 100644 --- a/web/src/components/app/emails/GoogleWorkspaceSigninPanel.tsx +++ b/web/src/components/app/emails/GoogleWorkspaceSigninPanel.tsx @@ -38,7 +38,7 @@ export default function GoogleWorkspaceSigninPanel({ unfinished: boolean; onConnect: (address: string) => void; onPersonalGmail: (address: string) => void; - onUseAppPassword: () => void; + onUseAppPassword: (address: string) => void; }) { const [address, setAddress] = React.useState(""); const trimmed = address.trim(); @@ -138,7 +138,7 @@ export default function GoogleWorkspaceSigninPanel({ Prefer not to use Google sign-in?{" "}
    )} diff --git a/web/src/lib/api/models/app/emails/SendingDomain.ts b/web/src/lib/api/models/app/emails/SendingDomain.ts index f31dd477f..2d578e879 100644 --- a/web/src/lib/api/models/app/emails/SendingDomain.ts +++ b/web/src/lib/api/models/app/emails/SendingDomain.ts @@ -11,7 +11,8 @@ export interface TrackingDomainUse { mailboxes: number; } -export type DNSRecordPurpose = "ownership" | "root" | "www" | "website"; +/** `edge` is a TXT the provider in front of this instance needs before it serves the name. */ +export type DNSRecordPurpose = "ownership" | "root" | "www" | "website" | "edge"; /** One record to add at the DNS provider, and whether it is in place. */ export interface DNSRecord { From 532711520910183d79de58bf9cf415d92ae3d62a Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sat, 7 Nov 2026 06:52:39 +0100 Subject: [PATCH 285/318] feat: read Cloudflare's own refusals (errors 1000, 1001 and 1014) in the redirect visit check as edge_record and edge_inactive hints, and show the records to replace or the activation record in the redirect's fix panel instead of proxy steps --- docs/content/docs/api/endpoints.mdx | 2 +- docs/content/docs/guides/sending-domains.mdx | 2 ++ internal/app/sendingdomain/reach.go | 29 +++++++++++++++++ internal/app/sendingdomain/reach_test.go | 32 +++++++++++++++++++ internal/app/sendingdomain/service.go | 7 ++++ internal/models/mailbox_import.go | 4 +++ .../app/emails/domains/RedirectServing.tsx | 28 +++++++++++++--- .../api/models/app/emails/SendingDomain.ts | 13 +++++++- 8 files changed, 110 insertions(+), 7 deletions(-) diff --git a/docs/content/docs/api/endpoints.mdx b/docs/content/docs/api/endpoints.mdx index 98c258970..0b56ff9e7 100644 --- a/docs/content/docs/api/endpoints.mdx +++ b/docs/content/docs/api/endpoints.mdx @@ -662,7 +662,7 @@ Alongside them, `api_url` is this API's own public base (for a copyable example - `POST /emails/domains/bulk`: `domains` (1 to 100), `tracking_label` (one DNS label, such as `link`; each domain gets `