Merge pull request 'fix(outbox): dead-letter after a week; ERP mock names unique per boot' (#106) from fix/outbox-dead-letter into main
This commit was merged in pull request #106.
This commit is contained in:
commit
43731da8f1
10 files changed
+114
-1
No files matched your search
@@ -29,6 +29,8 @@ func main() {
|
||||
APISecret: env("ERP_API_SECRET", "mock"),
|
||||
WebhookURL: os.Getenv("ERP_WEBHOOK_URL"),
|
||||
WebhookSecret: os.Getenv("ERP_WEBHOOK_SECRET"),
|
||||
// One token per boot keeps assigned names unique across restarts.
|
||||
NameToken: time.Now().UTC().Format("060102150405"),
|
||||
}
|
||||
addr := env("ERPMOCK_ADDR", ":8000")
|
||||
if cfg.WebhookURL == "" {
|
||||
|
||||
@@ -47,6 +47,12 @@ type Config struct {
|
||||
WebhookSecret string
|
||||
// SKUs seeded as Item + Subscription Plan docs.
|
||||
SKUs []string
|
||||
// NameToken goes into every name the mock assigns (CUST-<token>-00001).
|
||||
// The mock keeps its docs in memory, so after a restart its counter
|
||||
// starts again; without a token a new customer would get a name an older
|
||||
// tenant in the registry is still linked to (unique erp_customer_id).
|
||||
// Empty in tests: plain CUST-00001.
|
||||
NameToken string
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
@@ -115,7 +121,11 @@ func (s *Server) put(doctype string, d Doc) Doc {
|
||||
name, _ := d["name"].(string)
|
||||
if name == "" {
|
||||
s.seq[doctype]++
|
||||
name = fmt.Sprintf("%s-%05d", prefix(doctype), s.seq[doctype])
|
||||
if s.cfg.NameToken != "" {
|
||||
name = fmt.Sprintf("%s-%s-%05d", prefix(doctype), s.cfg.NameToken, s.seq[doctype])
|
||||
} else {
|
||||
name = fmt.Sprintf("%s-%05d", prefix(doctype), s.seq[doctype])
|
||||
}
|
||||
d["name"] = name
|
||||
}
|
||||
now := time.Now().UTC().Format("2006-01-02 15:04:05.000000")
|
||||
|
||||
@@ -155,3 +155,14 @@ func TestMock_noWebhookURL(t *testing.T) {
|
||||
t.Fatalf("got %d %s", code, raw)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNameToken: with a token, assigned names carry it, so a restarted mock
|
||||
// (counter back at 1) never hands out a name it gave before.
|
||||
func TestNameToken(t *testing.T) {
|
||||
srv := httptest.NewServer(New(Config{APIKey: "k", APISecret: "s", NameToken: "boot1"}))
|
||||
defer srv.Close()
|
||||
code, raw := call(t, srv.URL, "POST", "/api/resource/Customer", map[string]any{"customer_name": "A"}, true)
|
||||
if code != 200 || !bytes.Contains(raw, []byte(`"name":"CUST-boot1-00001"`)) {
|
||||
t.Fatalf("create: %d %s", code, raw)
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/erp"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/erpmock"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/server"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
@@ -445,3 +446,42 @@ func TestReconcile_overdueInvoicesDriveTheLadder(t *testing.T) {
|
||||
_ = paid
|
||||
})
|
||||
}
|
||||
|
||||
// TestOutbox_deadLettersAfterMaxAttempts: an item that keeps failing is
|
||||
// retried with backoff, then given up after server.MaxOutboxAttempts (kept, with
|
||||
// "dead letter: " in last_error) instead of being retried forever.
|
||||
func TestOutbox_deadLettersAfterMaxAttempts(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
down := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
http.Error(w, `{"exception":"down"}`, http.StatusInternalServerError)
|
||||
}))
|
||||
defer down.Close()
|
||||
h.app.ERP = erp.New(erp.Config{BaseURL: down.URL, APIKey: "k", APISecret: "s"})
|
||||
newTenant(t, h, "dead-co") // enqueues the customer upsert
|
||||
|
||||
start := time.Now()
|
||||
defer func() { h.app.Now = nil }()
|
||||
for i := 1; i <= server.MaxOutboxAttempts; i++ {
|
||||
at := start.Add(time.Duration(i) * 2 * time.Hour) // always past the last backoff
|
||||
h.app.Now = func() time.Time { return at }
|
||||
if _, err := h.app.DrainOutbox(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pending, err := h.app.Store.PendingOutbox(t.Context())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := 1; i < server.MaxOutboxAttempts && pending != want {
|
||||
t.Fatalf("attempt %d: pending %d, want %d", i, pending, want)
|
||||
}
|
||||
if i == server.MaxOutboxAttempts && pending != 0 {
|
||||
t.Fatalf("not dead-lettered after %d attempts: pending %d", i, pending)
|
||||
}
|
||||
}
|
||||
// a later drain claims nothing: the item is done, not retried
|
||||
h.app.Now = func() time.Time { return start.Add(1000 * time.Hour) }
|
||||
if n, err := h.app.DrainOutbox(t.Context()); err != nil || n != 0 {
|
||||
t.Fatalf("drain after dead letter: n=%d err=%v", n, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package server
|
||||
|
||||
// MaxOutboxAttempts exposes the dead-letter threshold to the external tests.
|
||||
const MaxOutboxAttempts = maxOutboxAttempts
|
||||
@@ -19,6 +19,12 @@ import (
|
||||
|
||||
var outboxBackoff = []time.Duration{time.Minute, 5 * time.Minute, 15 * time.Minute, time.Hour}
|
||||
|
||||
// maxOutboxAttempts: after that many failures (about a week at the 1 h cap)
|
||||
// the item is dead-lettered instead of retried forever. Long enough that an
|
||||
// ERP outage never drops usage; the ERROR line makes it an alert, and the row
|
||||
// keeps its payload so it can be re-queued (done_at = NULL, attempts = 0).
|
||||
const maxOutboxAttempts = 170
|
||||
|
||||
// EnqueueCustomerUpsert is called on tenant creation.
|
||||
func (s *Server) EnqueueCustomerUpsert(ctx context.Context, t *store.Tenant) {
|
||||
if _, err := s.Store.EnqueueOutbox(ctx, store.OutboxItem{Kind: store.OutboxCustomerUpsert, TenantID: t.ID,
|
||||
@@ -62,6 +68,13 @@ func (s *Server) DrainOutbox(ctx context.Context) (int, error) {
|
||||
}
|
||||
for _, it := range items {
|
||||
if err := s.processOutbox(ctx, it); err != nil {
|
||||
if it.Attempts+1 >= maxOutboxAttempts {
|
||||
s.Log.Error("outbox item dead-lettered", "id", it.ID, "kind", it.Kind, "tenant_id", it.TenantID, "attempts", it.Attempts+1, "err", err)
|
||||
if derr := s.Store.DeadLetterOutbox(ctx, it.ID, err.Error(), s.now()); derr != nil {
|
||||
return len(items), derr
|
||||
}
|
||||
continue
|
||||
}
|
||||
delay := outboxBackoff[min(it.Attempts, len(outboxBackoff)-1)]
|
||||
s.Log.Warn("outbox item failed", "id", it.ID, "kind", it.Kind, "attempt", it.Attempts+1, "retry_in", delay, "err", err)
|
||||
if ferr := s.Store.FailOutbox(ctx, it.ID, err.Error(), s.now().Add(delay)); ferr != nil {
|
||||
|
||||
@@ -201,6 +201,21 @@ func (m *Memory) CompleteOutbox(_ context.Context, id int64, at time.Time) error
|
||||
return ErrNotFound
|
||||
}
|
||||
|
||||
func (m *Memory) DeadLetterOutbox(_ context.Context, id int64, errMsg string, at time.Time) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
for _, o := range m.outbox {
|
||||
if o.ID == id {
|
||||
o.Attempts++
|
||||
o.LastError = DeadLetterPrefix + errMsg
|
||||
t := at
|
||||
o.DoneAt = &t
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return ErrNotFound
|
||||
}
|
||||
|
||||
func (m *Memory) FailOutbox(_ context.Context, id int64, errMsg string, nextAttempt time.Time) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
@@ -294,6 +294,18 @@ func (p *Postgres) CompleteOutbox(ctx context.Context, id int64, at time.Time) e
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Postgres) DeadLetterOutbox(ctx context.Context, id int64, errMsg string, at time.Time) error {
|
||||
tag, err := p.pool.Exec(ctx, `UPDATE erp_outbox SET attempts = attempts + 1, last_error = $2, done_at = $3 WHERE id = $1`,
|
||||
id, DeadLetterPrefix+errMsg, at)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Postgres) FailOutbox(ctx context.Context, id int64, errMsg string, nextAttempt time.Time) error {
|
||||
tag, err := p.pool.Exec(ctx, `UPDATE erp_outbox SET attempts = attempts + 1, last_error = $2, next_attempt_at = $3 WHERE id = $1`, id, errMsg, nextAttempt)
|
||||
if err != nil {
|
||||
|
||||
@@ -137,6 +137,9 @@ type Store interface {
|
||||
ClaimOutbox(ctx context.Context, limit int, now time.Time, lease time.Duration) ([]OutboxItem, error)
|
||||
CompleteOutbox(ctx context.Context, id int64, at time.Time) error
|
||||
FailOutbox(ctx context.Context, id int64, errMsg string, nextAttempt time.Time) error
|
||||
// DeadLetterOutbox gives up on an item: done, with the reason kept in
|
||||
// last_error (prefixed "dead letter: ") so it can be found and re-queued.
|
||||
DeadLetterOutbox(ctx context.Context, id int64, errMsg string, at time.Time) error
|
||||
PendingOutbox(ctx context.Context) (int, error)
|
||||
|
||||
// Webhook idempotency: true when eventID was not seen before.
|
||||
|
||||
@@ -248,6 +248,9 @@ const (
|
||||
OutboxLeadCreate = "lead.create"
|
||||
)
|
||||
|
||||
// DeadLetterPrefix marks an outbox item the worker gave up on (last_error).
|
||||
const DeadLetterPrefix = "dead letter: "
|
||||
|
||||
// Licence — revocation + heartbeat record of an issued CLI licence JWT.
|
||||
type Licence struct {
|
||||
ID string `json:"id"`
|
||||
|
||||
Reference in new issue
Block a user