From 5506d040fee6445fdcea776b7041ad144e4b84ac Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 19:39:29 +0100 Subject: [PATCH 01/12] fix(dlc): create a use case with its numbers in one transaction dlc.Service.Create inserted the use case, then checked and assigned its numbers in a second transaction, so a refused or failed assignment left a use case without them. The numbers are now checked first and assigned in the transaction that inserts the use case. Two creates at once for an app's first use case both found none, and the second insert hit dlc_use_cases_default_idx: a 500. The insert now uses ON CONFLICT on that index and is tried again once, when the app has a default and the new use case is its second. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/dlc_test.go | 19 +++- acceleration/internal/dlc/service.go | 54 +++++++----- acceleration/internal/store/use_case.go | 92 +++++++++++++------- acceleration/internal/store/use_case_test.go | 39 +++++++++ 4 files changed, 146 insertions(+), 58 deletions(-) diff --git a/acceleration/internal/api/dlc_test.go b/acceleration/internal/api/dlc_test.go index 1d4f013b27..4eb284d71e 100644 --- a/acceleration/internal/api/dlc_test.go +++ b/acceleration/internal/api/dlc_test.go @@ -549,14 +549,26 @@ func (s *DLCSuite) TestAUseCaseNamingANumberTheAppDoesNotHoldIsRefusedNamingIt() s.Equal(http.StatusBadRequest, status) s.Contains(failure, stranger+" is not a number this app holds") s.NotContains(failure, "store:") + s.Empty(s.useCases(), "a refused create leaves no use case") +} + +// useCases are the app's use cases. +func (s *dlcRegistration) useCases() []UseCase { + var page UseCasePage + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/phone/use-cases", nil, &page)) + return page.Items } // Assigning numbers that the database fails is the router's failure: a 500 that says nothing -// of the database, not a 400 the app could not act on. +// of the database, not a 400 the app could not act on. The use case is not made without them. func (s *DLCSuite) TestAUseCaseWhoseNumbersTheDatabaseFailsIsAnInternalError() { - s.failQueries("dlc_use_case_id = NULL") + held := store.PhoneNumber{CustomerID: s.customerID(), E164: s.utils.number(), Vendor: "telnyx"} + s.Require().NoError(s.store.PhoneNumbers.Insert(context.Background(), &held)) + request := completeUseCase("support") + request.Numbers = []string{held.E164} + s.failQueries("SET dlc_use_case_id = '") - status, payload := s.serverClient.call(http.MethodPost, "/v1/phone/use-cases", completeUseCase("support")) + status, payload := s.serverClient.call(http.MethodPost, "/v1/phone/use-cases", request) s.Equal(http.StatusInternalServerError, status, string(payload)) var failure ErrorResponse @@ -566,6 +578,7 @@ func (s *DLCSuite) TestAUseCaseWhoseNumbersTheDatabaseFailsIsAnInternalError() { for _, internal := range []string{"store:", "dlc:", "deadline", "assign numbers"} { s.NotContains(string(payload), internal) } + s.Empty(s.useCases(), "a use case without the numbers it was made with is not left behind") } func (s *DLCSuite) TestOnlyStreamStaffReviewUseCases() { diff --git a/acceleration/internal/dlc/service.go b/acceleration/internal/dlc/service.go index 2eddf3cf0a..0ddd29af10 100644 --- a/acceleration/internal/dlc/service.go +++ b/acceleration/internal/dlc/service.go @@ -157,13 +157,14 @@ func (s *Service) poll(ctx context.Context, after *store.CreatedPosition) *store return after } -// Create records a new draft use case and the numbers that send as it. +// Create records a new draft use case and the numbers that send as it, as one: a use case whose +// numbers cannot be assigned is not left behind. func (s *Service) Create(ctx context.Context, useCase *store.UseCase, numbers []string) error { - useCase.Status = Draft - if err := s.store.UseCases.Insert(ctx, useCase); err != nil { + if err := s.checkNumbers(ctx, useCase.CustomerID, numbers); err != nil { return err } - return s.assign(ctx, *useCase, numbers) + useCase.Status = Draft + return s.store.UseCases.Insert(ctx, useCase, numbers...) } // Update replaces what an app wrote on a use case it may still edit. numbers nil leaves @@ -181,28 +182,37 @@ func (s *Service) Update(ctx context.Context, useCase *store.UseCase, numbers [] return s.assign(ctx, *useCase, numbers) } -// assign sends numbers as the use case. A number the app does not hold, or one named twice, -// is the caller's to correct; a store failure is not. +// assign sends numbers as the use case. func (s *Service) assign(ctx context.Context, useCase store.UseCase, numbers []string) error { - if len(numbers) > 0 { - held, err := s.store.PhoneNumbers.Select(ctx, useCase.CustomerID, store.PhoneNumberFilter{}) - if err != nil { - return err - } - holds := make(map[string]bool, len(held)) - for _, number := range held { - holds[number.E164] = true + if err := s.checkNumbers(ctx, useCase.CustomerID, numbers); err != nil { + return err + } + return s.store.UseCases.AssignNumbers(ctx, useCase.CustomerID, useCase.ID, numbers) +} + +// checkNumbers refuses numbers a use case of the app could not send from. A number the app +// does not hold, or one named twice, is the caller's to correct; a store failure is not. +func (s *Service) checkNumbers(ctx context.Context, customerID string, numbers []string) error { + if len(numbers) == 0 { + return nil + } + held, err := s.store.PhoneNumbers.Select(ctx, customerID, store.PhoneNumberFilter{}) + if err != nil { + return err + } + holds := make(map[string]bool, len(held)) + for _, number := range held { + holds[number.E164] = true + } + for i, number := range numbers { + if !holds[number] { + return stack.Wrap(fmt.Errorf("%w: %s is not a number this app holds", ErrInvalid, number)) } - for i, number := range numbers { - if !holds[number] { - return stack.Wrap(fmt.Errorf("%w: %s is not a number this app holds", ErrInvalid, number)) - } - if slices.Contains(numbers[:i], number) { - return stack.Wrap(fmt.Errorf("%w: %s is named twice", ErrInvalid, number)) - } + if slices.Contains(numbers[:i], number) { + return stack.Wrap(fmt.Errorf("%w: %s is named twice", ErrInvalid, number)) } } - return s.store.UseCases.AssignNumbers(ctx, useCase.CustomerID, useCase.ID, numbers) + return nil } // Delete removes a use case the vendor does not hold. diff --git a/acceleration/internal/store/use_case.go b/acceleration/internal/store/use_case.go index d979dee691..a5b8cd154d 100644 --- a/acceleration/internal/store/use_case.go +++ b/acceleration/internal/store/use_case.go @@ -268,9 +268,13 @@ func (r *UseCases) HasIn(ctx context.Context, customerID string, statuses ...str return found, nil } -// Insert records a new use case. An app's first one is its default, and a new -// default takes over from the old one. -func (r *UseCases) Insert(ctx context.Context, useCase *UseCase) error { +// errDefaultTaken rolls back a create whose use case would be the app's default when another +// create made one meanwhile. +var errDefaultTaken = errors.New("store: another use case became the app's default meanwhile") + +// Insert records a new use case and makes numbers the ones that send as it, as one. An app's +// first one is its default, and a new default takes over from the old one. +func (r *UseCases) Insert(ctx context.Context, useCase *UseCase, numbers ...string) error { if err := useCase.Validate(); err != nil { return stack.Wrap(err) } @@ -280,22 +284,39 @@ func (r *UseCases) Insert(ctx context.Context, useCase *UseCase) error { if useCase.MessageSamples == nil { useCase.MessageSamples = []string{} } - return stack.Wrap(r.store.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { - held, err := tx.NewSelect().Model((*UseCase)(nil)).Where("customer_id = ?", useCase.CustomerID).Exists(ctx) - if err != nil { - return fmt.Errorf("store: create use case: %w", err) - } - useCase.IsDefault = useCase.IsDefault || !held - if useCase.IsDefault { - if err := clearDefaultUseCase(ctx, tx, useCase.CustomerID, ""); err != nil { - return err + asked := useCase.IsDefault + var err error + // Twice at most: two creates at once for an app with no use case both find none, and the + // one whose default lands second is made again as what it is then. + for range 2 { + useCase.IsDefault = asked + err = r.store.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { + held, err := tx.NewSelect().Model((*UseCase)(nil)).Where("customer_id = ?", useCase.CustomerID).Exists(ctx) + if err != nil { + return fmt.Errorf("store: create use case: %w", err) } + useCase.IsDefault = useCase.IsDefault || !held + if useCase.IsDefault { + if err := clearDefaultUseCase(ctx, tx, useCase.CustomerID, ""); err != nil { + return err + } + } + result, err := tx.NewInsert().Model(useCase).On("CONFLICT (customer_id) WHERE is_default DO NOTHING").Exec(ctx) + if err != nil { + return fmt.Errorf("store: create use case: %w", err) + } + if inserted, err := result.RowsAffected(); err != nil { + return fmt.Errorf("store: create use case: %w", err) + } else if inserted == 0 { + return errDefaultTaken + } + return assignNumbers(ctx, tx, useCase.CustomerID, useCase.ID, numbers) + }) + if !errors.Is(err, errDefaultTaken) { + return stack.Wrap(err) } - if _, err := tx.NewInsert().Model(useCase).Exec(ctx); err != nil { - return fmt.Errorf("store: create use case: %w", err) - } - return nil - })) + } + return stack.Wrap(fmt.Errorf("store: create use case: %w", err)) } // Update replaces what an app wrote on a use case. Its status, vendor fields and @@ -417,25 +438,30 @@ func (r *UseCases) AssignNumbers(ctx context.Context, customerID, useCaseID stri if err != nil { return fmt.Errorf("store: assign numbers: %w", err) } - if len(numbers) == 0 { - return nil - } - result, err := tx.NewUpdate().Model((*PhoneNumber)(nil)). - Set("dlc_use_case_id = ?", useCaseID). - Where("customer_id = ?", customerID). - Where("e164 IN (?)", bun.In(numbers)). - Where("released_at IS NULL"). - Exec(ctx) - if err != nil { - return fmt.Errorf("store: assign numbers: %w", err) - } - if affected, _ := result.RowsAffected(); int(affected) != len(numbers) { - return fmt.Errorf("store: assign numbers: not every number is one %s holds", customerID) - } - return nil + return assignNumbers(ctx, tx, customerID, useCaseID, numbers) })) } +// assignNumbers makes numbers send as a use case, in tx. +func assignNumbers(ctx context.Context, tx bun.Tx, customerID, useCaseID string, numbers []string) error { + if len(numbers) == 0 { + return nil + } + result, err := tx.NewUpdate().Model((*PhoneNumber)(nil)). + Set("dlc_use_case_id = ?", useCaseID). + Where("customer_id = ?", customerID). + Where("e164 IN (?)", bun.In(numbers)). + Where("released_at IS NULL"). + Exec(ctx) + if err != nil { + return fmt.Errorf("store: assign numbers: %w", err) + } + if affected, _ := result.RowsAffected(); int(affected) != len(numbers) { + return fmt.Errorf("store: assign numbers: not every number is one %s holds", customerID) + } + return nil +} + // AssignedNumbers returns the numbers assigned to a use case by name, in order. func (r *UseCases) AssignedNumbers(ctx context.Context, customerID, useCaseID string) ([]string, error) { numbers := []string{} diff --git a/acceleration/internal/store/use_case_test.go b/acceleration/internal/store/use_case_test.go index 5b81ea8b39..4941242a4b 100644 --- a/acceleration/internal/store/use_case_test.go +++ b/acceleration/internal/store/use_case_test.go @@ -4,6 +4,7 @@ package store import ( "fmt" + "time" ) // useCase creates a draft use case for a customer. @@ -31,6 +32,44 @@ func (s *StoreSuite) TestAnAppsFirstUseCaseIsItsDefaultUntilAnotherTakesOver() { s.ErrorIs(err, ErrUnknownUseCase, "another app does not see it") } +// Two creates at once for an app with no use case both find none. The one whose default lands +// second is the app's second use case, not a failed create. +func (s *StoreSuite) TestACreateRacingTheAppsFirstUseCaseIsItsSecond() { + customerID := newID() + tx, err := s.store.GlobalDB().BeginTx(s.ctx, nil) + s.Require().NoError(err) + defer tx.Rollback() //nolint:errcheck // a no-op once committed + first := UseCase{ID: newID(), CustomerID: customerID, Name: "support", IsDefault: true, Status: "draft", + UseCaseType: "CUSTOMER_CARE", MessageSamples: []string{}, CreatedAt: s.base, UpdatedAt: s.base} + _, err = tx.NewInsert().Model(&first).Exec(s.ctx) + s.Require().NoError(err) + second := UseCase{CustomerID: customerID, Name: "reminders", Status: "draft", UseCaseType: "CUSTOMER_CARE"} + created := make(chan error, 1) + go func() { created <- s.store.UseCases.Insert(s.ctx, &second) }() + s.Require().Eventually(func() bool { + var waiting int + s.Require().NoError(s.store.GlobalDB().QueryRowContext(s.ctx, + "SELECT count(*) FROM pg_stat_activity WHERE wait_event_type = 'Lock' AND datname = current_database() AND query LIKE 'INSERT INTO \"dlc_use_cases\"%'").Scan(&waiting)) + return waiting == 1 + }, 5*time.Second, 10*time.Millisecond, "the second create found no use case, and waits on the first's default") + + s.Require().NoError(tx.Commit()) + + select { + case err := <-created: + s.Require().NoError(err) + case <-time.After(5 * time.Second): + s.FailNow("the second create never returned") + } + s.False(second.IsDefault) + held, err := s.store.UseCases.Select(s.ctx, customerID, 10, nil) + s.Require().NoError(err) + s.Len(held, 2) + first, err = s.store.UseCases.Get(s.ctx, customerID, first.ID) + s.Require().NoError(err) + s.True(first.IsDefault) +} + // Two reviewers acting on the same use case at once must not both win. func (s *StoreSuite) TestMovingAUseCaseFromAStatusItLeftWritesNothing() { useCase := s.useCase(newID(), "support") From 89c9dfb8e9a1ea0c5f1a06b604c4a1d220ec6049 Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 19:42:39 +0100 Subject: [PATCH 02/12] fix(phone): retry a call leg's write and leave a lost one to the sweep When the row of a call leg could not be written, OpenLeg logged that its minutes were not billed and moved on: the call was up and nobody was billed for it. OpenLeg now writes it twice more, 100 ms and 200 ms apart, and then keeps it, at most 1000 per process, for the leg sweep, which writes it with the join and leave its phone had meanwhile (as a leg written late already is) and bills it. A leg still kept when the sweep stops is logged at ERROR, as before. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/phone/legs.go | 103 +++++++++++++++++- .../phone/metering_integration_test.go | 80 ++++++++++++++ acceleration/internal/phone/service.go | 2 + 3 files changed, 180 insertions(+), 5 deletions(-) diff --git a/acceleration/internal/phone/legs.go b/acceleration/internal/phone/legs.go index f284dd1ca3..abb55f7e17 100644 --- a/acceleration/internal/phone/legs.go +++ b/acceleration/internal/phone/legs.go @@ -2,6 +2,7 @@ package phone import ( "context" + "errors" "maps" "slices" "strconv" @@ -39,6 +40,17 @@ const ( // the leg that opens after it: far longer than any delivery is late. const keepParticipantsFor = 24 * time.Hour +// openAttempts and openFirstPause bound how often OpenLeg writes a leg's row before leaving it +// to the leg sweep: the first write and two more, 100 ms and then 200 ms after the one before, +// for a dropped connection or a failover. The call is up by then, so a leg with no row is a +// call nobody is billed for. unopenedMost bounds the legs a process keeps for the sweep until +// it stops; one past it is logged and not billed. +const ( + openAttempts = 3 + openFirstPause = 100 * time.Millisecond + unopenedMost = 1000 +) + // AttributeEndedBy says what ended a leg billed by anything other than its phone leaving or // the call ending: the sweep. const AttributeEndedBy = "ended_by" @@ -48,7 +60,8 @@ const AttributeEndedBy = "ended_by" // (Connect); pass started for one already connected, as a call that arrived is, from the leg's // DialedAt, when the event announcing it was made, or now. Its country is where it rang unless // the leg names its own. An inbound leg its Stream session already has is not opened again. A -// leg that cannot be recorded is logged, since the call is already up and its minutes are lost. +// leg whose row cannot be written is tried again, then kept for the leg sweep (SweepLegs), which +// writes it with the join and leave its phone had meanwhile, as a leg written late is. func (s *Service) OpenLeg(ctx context.Context, owner routing.Owner, leg store.CallLeg, started bool) { if s.store == nil { return @@ -78,6 +91,29 @@ func (s *Service) OpenLeg(ctx context.Context, owner routing.Owner, leg store.Ca leg.StartedAt = &leg.DialedAt } opened, err := s.store.CallLegs.Open(ctx, &leg) + pause := openFirstPause + for attempt := 1; attempt < openAttempts && err != nil && !opened && openAgain(err); attempt++ { + time.Sleep(pause) + pause *= 2 + opened, err = s.store.CallLegs.Open(ctx, &leg) + } + if err != nil && !opened && openAgain(err) && s.unopened.add(leg) { + s.logger.Warn("could not record a call leg; the leg sweep records it", "call", leg.CallType+":"+leg.CallID, + "vendor", leg.Vendor, "direction", leg.Direction, "error", err) + return + } + s.recorded(ctx, leg, opened, err) +} + +// openAgain says whether writing a leg's row again may pass: not when the store or Postgres +// refused the row itself, nor for a placed leg that is gone or dialled already. +func openAgain(err error) bool { + return !store.Unwritable(err) && !errors.Is(err, store.ErrNoPlacedCall) +} + +// recorded follows a leg's write: a leg its phone joined, and maybe left, before it was written +// is billed or started, and one that could not be written is logged. +func (s *Service) recorded(ctx context.Context, leg store.CallLeg, opened bool, err error) { switch { case err != nil && !opened: s.logger.Error("could not record a call leg; its minutes are not billed", "call", leg.CallType+":"+leg.CallID, @@ -310,6 +346,61 @@ func (r *recently) forget(key string) { delete(r.until, key) } +// unopenedLegs are the legs whose row OpenLeg could not write, kept for the leg sweep, at most +// unopenedMost of them. +type unopenedLegs struct { + mu sync.Mutex + legs []store.CallLeg +} + +// add keeps leg, and reports false when unopenedMost are kept already. +func (u *unopenedLegs) add(leg store.CallLeg) bool { + u.mu.Lock() + defer u.mu.Unlock() + if len(u.legs) >= unopenedMost { + return false + } + u.legs = append(u.legs, leg) + return true +} + +// take hands over every leg kept. +func (u *unopenedLegs) take() []store.CallLeg { + u.mu.Lock() + defer u.mu.Unlock() + legs := u.legs + u.legs = nil + return legs +} + +// openUnopened writes the row of each leg OpenLeg could not, and follows it as OpenLeg would. A +// write that fails in a way a retry may pass leaves it and those after it for the next sweep. +func (s *Service) openUnopened(ctx context.Context) { + legs := s.unopened.take() + for i := range legs { + leg := legs[i] + opened, err := s.store.CallLegs.Open(ctx, &leg) + if err != nil && !opened && openAgain(err) { + for _, left := range legs[i:] { + if !s.unopened.add(left) { + s.recorded(ctx, left, false, err) + } + } + return + } + s.recorded(ctx, leg, opened, err) + } +} + +// loseUnopened logs each leg still kept for the sweep when the sweep stops: its minutes are not +// billed. +func (s *Service) loseUnopened() { + for _, leg := range s.unopened.take() { + s.logger.Error("could not record a call leg before the router stopped; its minutes are not billed", + "call", leg.CallType+":"+leg.CallID, "vendor", leg.Vendor, "direction", leg.Direction) + } +} + // settleLegs bills the legs that ended whose phone joined. One that never connected was not // answered, which a vendor does not bill: it is logged, since a call hook that does not deliver // call.session_participant_joined would leave every placed call looking so. @@ -406,9 +497,9 @@ func (s *Service) refused(ctx context.Context, leg store.CallLeg) bool { return found } -// SweepLegs ends the legs of this shard open longer than MaxCallLength, and checks the legs -// that ended lately have their row, writing again any a process lost between ending the leg and -// writing it. It reports how many legs it ended. +// SweepLegs writes the legs OpenLeg could not, ends the legs of this shard open longer than +// MaxCallLength, and checks the legs that ended lately have their row, writing again any a +// process lost between ending the leg and writing it. It reports how many legs it ended. // // A leg whose phone joined and that nothing ended is logged at ERROR and recorded priced and // given away at MaxCallLength: a call that ran four hours is rare, a lost session_ended is not, @@ -417,6 +508,7 @@ func (s *Service) SweepLegs(ctx context.Context) (int, error) { if s.store == nil { return 0, nil } + s.openUnopened(ctx) now := s.now() ended, err := s.store.CallLegs.Sweep(ctx, now, MaxCallLength, legSweepBatch) if err != nil { @@ -474,13 +566,14 @@ func (s *Service) rebill(ctx context.Context, now time.Time) error { return nil } -// RunLegSweep sweeps every interval until ctx ends. +// RunLegSweep sweeps every interval until ctx ends, and then logs the legs it never wrote. func (s *Service) RunLegSweep(ctx context.Context, every time.Duration) { ticker := time.NewTicker(every) defer ticker.Stop() for { select { case <-ctx.Done(): + s.loseUnopened() return case <-ticker.C: if _, err := s.SweepLegs(ctx); err != nil { diff --git a/acceleration/internal/phone/metering_integration_test.go b/acceleration/internal/phone/metering_integration_test.go index df2f027e0d..dfb555cb11 100644 --- a/acceleration/internal/phone/metering_integration_test.go +++ b/acceleration/internal/phone/metering_integration_test.go @@ -18,6 +18,7 @@ import ( "github.com/google/uuid" "github.com/redis/rueidis" "github.com/stretchr/testify/suite" + "github.com/uptrace/bun" "github.com/GetStream/Vision-Agents/acceleration/internal/conversation/chattest" "github.com/GetStream/Vision-Agents/acceleration/internal/dlc" @@ -50,6 +51,8 @@ type MeteringSuite struct { deployment *chattest.Server customer string e164 string + // failing fails the writes of new legs' rows a test asks it to. + failing *failingLegWrites } func TestMeteringSuite(t *testing.T) { suite.Run(t, new(MeteringSuite)) } @@ -65,12 +68,15 @@ func (s *MeteringSuite) SetupSuite() { s.Require().NoError(opened.Migrate(s.ctx)) s.store = opened s.T().Cleanup(func() { s.Require().NoError(opened.Close()) }) + s.failing = &failingLegWrites{} + opened.ShardDB().AddQueryHook(s.failing) s.redis, err = redisready.NewClient(rueidis.ClientOption{InitAddress: []string{address}, DisableCache: true}) s.Require().NoError(err) s.T().Cleanup(s.redis.Close) } func (s *MeteringSuite) SetupTest() { + s.failing.fail(0) s.withSandbox(dlc.Sandbox{}) } @@ -701,6 +707,46 @@ func (s *MeteringSuite) TestALegWhoseRowWasLostIsRecordedAgainByTheSweep() { s.Len(s.rows(ModelCallMinutes), 1) } +// A leg whose row a dropped connection fails to write is written again at once, and its call +// billed. +func (s *MeteringSuite) TestALegWhoseFirstWriteFailsIsBilled() { + callID := "call-" + uuid.NewString() + s.failing.fail(1) + s.arrived(callID) + s.clock.advance(2 * time.Minute) + + s.ended(defaultCallType, callID) + + minutes := s.row(ModelCallMinutes) + s.Equal(pricing.Quantities{pricing.CallSeconds: 120}, minutes.Meters) + s.True(minutes.Billable) +} + +// A leg whose row cannot be written while its call is up is written by the leg sweep, which +// bills it from the join and the leave its phone had meanwhile. +func (s *MeteringSuite) TestALegThatCouldNotBeWrittenIsWrittenAndBilledByTheSweep() { + callID := "call-" + uuid.NewString() + s.failing.fail(openAttempts) + s.arrived(callID) + s.Empty(s.openLegs()) + s.joined(defaultCallType, callID, "caller-1", "15125550199") + s.clock.advance(90 * time.Second) + s.left(defaultCallType, callID, "caller-1") + s.ended(defaultCallType, callID) + + _, err := s.service.SweepLegs(s.ctx) + s.Require().NoError(err) + + minutes := s.row(ModelCallMinutes) + s.Equal(pricing.Quantities{pricing.CallSeconds: 90}, minutes.Meters) + s.True(minutes.Billable) + s.Zero(s.kept(callID), "the join and the leave went to the leg") + _, err = s.service.SweepLegs(s.ctx) + s.Require().NoError(err) + s.Never(func() bool { return len(s.rows(ModelCallMinutes)) > 1 }, time.Second, 50*time.Millisecond, + "the next sweep writes it no more") +} + func (s *MeteringSuite) TestEveryLegOfAnEndedCallCountsTowardTheSandboxsMinutes() { s.withSandbox(dlc.Sandbox{Enabled: true}) s.Require().NoError(s.service.gate.SetRecipients(s.ctx, s.customer, []string{"+15125550123", "+15125550124"})) @@ -972,6 +1018,40 @@ func (l *meteringLogs) count(level, message string) int { return lines } +// failingLegWrites fails the next writes of a new leg's row, as a database that does not answer +// in time does. +type failingLegWrites struct { + mu sync.Mutex + left int +} + +// fail fails the next times writes. +func (f *failingLegWrites) fail(times int) { + f.mu.Lock() + defer f.mu.Unlock() + f.left = times +} + +func (f *failingLegWrites) BeforeQuery(ctx context.Context, event *bun.QueryEvent) context.Context { + if !strings.HasPrefix(event.Query, `INSERT INTO "call_legs"`) { + return ctx + } + f.mu.Lock() + failing := f.left > 0 + if failing { + f.left-- + } + f.mu.Unlock() + if !failing { + return ctx + } + expired, cancel := context.WithDeadline(ctx, time.Time{}) + cancel() + return expired +} + +func (*failingLegWrites) AfterQuery(context.Context, *bun.QueryEvent) {} + // meteringClock is the service's clock, moved by the test. type meteringClock struct { mu sync.Mutex diff --git a/acceleration/internal/phone/service.go b/acceleration/internal/phone/service.go index b5dcefbe55..d527c7b1dc 100644 --- a/acceleration/internal/phone/service.go +++ b/acceleration/internal/phone/service.go @@ -58,6 +58,8 @@ type Service struct { // heard is the calls whose participant events this process recorded lately (Heard), and // unhooked the apps it lately logged as not delivering them. heard, unhooked recently + // unopened are the legs OpenLeg could not write, for the leg sweep (RunLegSweep) to. + unopened unopenedLegs // connecting, when set, runs in Connect between reading the phone's kept leave and // connecting its leg, where a leave delivered at the same moment lands. connecting func() From 1769315e8010aec39e012e292de74f2d909e1fbe Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 20:06:49 +0100 Subject: [PATCH 03/12] fix(phone): keep an order before buying or releasing a number Buy asked the vendor and then inserted the number's row once: a failed insert left a number Stream paid for every month that no customer held. Release asked the vendor and then marked the row released once: a failed update left a number given back that kept being billed to the customer. Both now write a phone_number_orders row before the vendor is asked and delete it with the write that records the outcome. The phone sweeper settles orders older than 10 minutes by asking the vendor whether it holds the number (phone.NumberFinder, for Telnyx and Twilio): a number bought and held gets its row, as of the purchase, and its first month if the purchase did not bill it; a number given back and no longer held is released as of when it was. A vendor that cannot be asked leaves the order and an ERROR line for an operator. Co-Authored-By: Claude Opus 5.5 --- acceleration/cmd/router/phonesweep.go | 10 +- .../internal/phone/apps_integration_test.go | 2 +- .../phone/metering_integration_test.go | 113 +++++++++-- acceleration/internal/phone/phone.go | 7 + acceleration/internal/phone/phone_test.go | 20 +- acceleration/internal/phone/service.go | 177 +++++++++++++++--- acceleration/internal/phone/telnyx/telnyx.go | 36 +++- .../internal/phone/telnyx/telnyx_test.go | 28 +++ acceleration/internal/phone/twilio/twilio.go | 17 +- .../internal/phone/twilio/twilio_test.go | 20 ++ acceleration/internal/store/datamove.go | 4 +- acceleration/internal/store/phone_number.go | 7 +- .../internal/store/phone_number_order.go | 119 ++++++++++++ .../internal/store/phone_number_order_test.go | 70 +++++++ .../store/phone_number_order_unit_test.go | 31 +++ acceleration/internal/store/repos.go | 2 + .../20270201000300_phone_number_orders.sql | 22 +++ acceleration/schema/global.sql | 14 ++ 18 files changed, 643 insertions(+), 56 deletions(-) create mode 100644 acceleration/internal/store/phone_number_order.go create mode 100644 acceleration/internal/store/phone_number_order_test.go create mode 100644 acceleration/internal/store/phone_number_order_unit_test.go create mode 100644 acceleration/migrations/global/20270201000300_phone_number_orders.sql diff --git a/acceleration/cmd/router/phonesweep.go b/acceleration/cmd/router/phonesweep.go index d02b1fd6ce..59f786fa00 100644 --- a/acceleration/cmd/router/phonesweep.go +++ b/acceleration/cmd/router/phonesweep.go @@ -16,8 +16,8 @@ var phoneSweepEvery = 10 * time.Minute const phoneCallMaxAge = 6 * time.Hour // startPhoneSweeper deletes the per-call trunks of calls that never reported their end and the -// bridges of calls nobody answered, and retires the status urls of old placed calls, until ctx -// is done. +// bridges of calls nobody answered, settles the purchases and releases of numbers whose outcome +// was not recorded, and retires the status urls of old placed calls, until ctx is done. func startPhoneSweeper(ctx context.Context, service *phone.Service, logger *slog.Logger) { // Read before the goroutine, so a test that sets it back after run returns does not race it. every := phoneSweepEvery @@ -41,6 +41,12 @@ func startPhoneSweeper(ctx context.Context, service *phone.Service, logger *slog } else if bridges > 0 { logger.Info("swept the bridges of calls nobody answered", "bridges", bridges) } + orders, err := service.SweepOrders(ctx) + if err != nil { + logger.Error("could not settle the purchases and releases of numbers left unrecorded", "error", err) + } else if orders > 0 { + logger.Info("settled the purchases and releases of numbers left unrecorded", "orders", orders) + } retired, err := service.SweepStatusTokens(ctx) if err != nil { logger.Error("could not retire the status urls of old placed calls", "error", err) diff --git a/acceleration/internal/phone/apps_integration_test.go b/acceleration/internal/phone/apps_integration_test.go index 94753b63c6..33743671a2 100644 --- a/acceleration/internal/phone/apps_integration_test.go +++ b/acceleration/internal/phone/apps_integration_test.go @@ -2638,7 +2638,7 @@ func (s *AppsSuite) TestReleasingANumberLinedSinceItWasReadTakesItOffItsTrunk() lined, err := s.lineFor(s.customer, s.e164) s.Require().NoError(err) - s.Require().NoError(s.service.unline(s.ctx, stale, "released a number", true)) + s.Require().NoError(s.service.unline(s.ctx, stale, "released a number", time.Now().UTC())) s.Equal([]string{second}, s.own.TrunkNumbers(lined.TrunkID)) s.Equal([]string{other.RouteID}, s.own.Rules()) diff --git a/acceleration/internal/phone/metering_integration_test.go b/acceleration/internal/phone/metering_integration_test.go index dfb555cb11..4ba88d618b 100644 --- a/acceleration/internal/phone/metering_integration_test.go +++ b/acceleration/internal/phone/metering_integration_test.go @@ -51,8 +51,8 @@ type MeteringSuite struct { deployment *chattest.Server customer string e164 string - // failing fails the writes of new legs' rows a test asks it to. - failing *failingLegWrites + // failing fails the queries a test asks it to. + failing *failingQueries } func TestMeteringSuite(t *testing.T) { suite.Run(t, new(MeteringSuite)) } @@ -68,7 +68,7 @@ func (s *MeteringSuite) SetupSuite() { s.Require().NoError(opened.Migrate(s.ctx)) s.store = opened s.T().Cleanup(func() { s.Require().NoError(opened.Close()) }) - s.failing = &failingLegWrites{} + s.failing = &failingQueries{} opened.ShardDB().AddQueryHook(s.failing) s.redis, err = redisready.NewClient(rueidis.ClientOption{InitAddress: []string{address}, DisableCache: true}) s.Require().NoError(err) @@ -76,7 +76,7 @@ func (s *MeteringSuite) SetupSuite() { } func (s *MeteringSuite) SetupTest() { - s.failing.fail(0) + s.failing.fail("", 0) s.withSandbox(dlc.Sandbox{}) } @@ -711,7 +711,7 @@ func (s *MeteringSuite) TestALegWhoseRowWasLostIsRecordedAgainByTheSweep() { // billed. func (s *MeteringSuite) TestALegWhoseFirstWriteFailsIsBilled() { callID := "call-" + uuid.NewString() - s.failing.fail(1) + s.failing.fail(`INSERT INTO "call_legs"`, 1) s.arrived(callID) s.clock.advance(2 * time.Minute) @@ -726,7 +726,7 @@ func (s *MeteringSuite) TestALegWhoseFirstWriteFailsIsBilled() { // bills it from the join and the leave its phone had meanwhile. func (s *MeteringSuite) TestALegThatCouldNotBeWrittenIsWrittenAndBilledByTheSweep() { callID := "call-" + uuid.NewString() - s.failing.fail(openAttempts) + s.failing.fail(`INSERT INTO "call_legs"`, openAttempts) s.arrived(callID) s.Empty(s.openLegs()) s.joined(defaultCallType, callID, "caller-1", "15125550199") @@ -812,6 +812,81 @@ func (s *MeteringSuite) TestABoughtNumberIsBilledItsFirstMonth() { s.Equal(bought.PurchasedAt, month.StartedAt.UTC()) } +// A number bought whose row could not be written is recorded by the sweep, from the vendor's +// account, as of when it was bought, and its first month is billed once. +func (s *MeteringSuite) TestANumberBoughtWithoutItsRowIsRecordedByTheSweep() { + e164 := aNumber() + s.vendor.offers = []Available{{E164: e164, MonthlyCostMicros: 1_000_000}} + s.failing.fail(`INSERT INTO "phone_numbers"`, 1) + _, err := s.service.Buy(s.ctx, Purchase{Vendor: s.vendor.vendor, E164: e164, Owner: s.owner()}) + s.Require().ErrorContains(err, "was not recorded") + _, err = s.store.PhoneNumbers.GetByE164(s.ctx, s.customer, e164) + s.Require().ErrorIs(err, store.ErrNoNumber) + month := s.row(ModelNumber) + s.clock.advance(orderSettles + time.Minute) + + _, err = s.service.SweepOrders(s.ctx) + + s.Require().NoError(err) + held, err := s.store.PhoneNumbers.GetByE164(s.ctx, s.customer, e164) + s.Require().NoError(err) + s.Equal(month.StartedAt.UTC(), held.PurchasedAt.UTC(), "bought when the purchase billed its first month") + s.Equal(int64(1_000_000), held.MonthlyCostMicros) + s.Never(func() bool { return len(s.rows(ModelNumber)) > 1 }, time.Second, 50*time.Millisecond, + "the first month is billed once") + s.Zero(s.orders(), "nothing is left to settle") +} + +// A number given back at the vendor whose release could not be written is released by the +// sweep, as of when it was given back, rather than billed every month. +func (s *MeteringSuite) TestANumberGivenBackWithoutItsReleaseIsReleasedByTheSweep() { + s.failing.fail(`SET released_at = `, 1) + s.Require().Error(s.service.Release(s.ctx, s.customer, s.e164)) + returned := time.Now() + _, err := s.store.PhoneNumbers.GetByE164(s.ctx, s.customer, s.e164) + s.Require().NoError(err, "the vendor has it back, and the row still holds it") + s.clock.advance(orderSettles + time.Minute) + + _, err = s.service.SweepOrders(s.ctx) + + s.Require().NoError(err) + _, err = s.store.PhoneNumbers.GetByE164(s.ctx, s.customer, s.e164) + s.ErrorIs(err, store.ErrNoNumber) + s.Zero(s.orders()) + numbers, err := s.store.PhoneNumbers.Select(s.ctx, s.customer, store.PhoneNumberFilter{IncludeReleased: true}) + s.Require().NoError(err) + s.Require().Len(numbers, 1) + s.Require().NotNil(numbers[0].ReleasedAt) + s.False(numbers[0].ReleasedAt.After(returned), "released as of when the vendor took it back, not when the sweep ran") +} + +// A purchase the vendor refused, whose order could not be forgotten, leaves no number. +func (s *MeteringSuite) TestAnOrderTheVendorDoesNotHoldIsForgottenWithoutANumber() { + e164 := aNumber() + s.failing.fail(`DELETE FROM "phone_number_orders"`, 1) + s.vendor.err = errors.New("the vendor refused") + _, err := s.service.Buy(s.ctx, Purchase{Vendor: s.vendor.vendor, E164: e164, Owner: s.owner()}) + s.Require().Error(err) + s.vendor.err = nil + s.Require().Equal(1, s.orders()) + s.clock.advance(orderSettles + time.Minute) + + _, err = s.service.SweepOrders(s.ctx) + + s.Require().NoError(err) + _, err = s.store.PhoneNumbers.GetByE164(s.ctx, s.customer, e164) + s.ErrorIs(err, store.ErrNoNumber) + s.Zero(s.orders()) +} + +// orders counts the customer's orders still to settle. +func (s *MeteringSuite) orders() int { + count, err := s.store.GlobalDB().NewSelect().Model((*store.PhoneNumberOrder)(nil)). + Where("customer_id = ?", s.customer).Count(s.ctx) + s.Require().NoError(err) + return count +} + func (s *MeteringSuite) TestANumberWhosePriceIsOnlyInItsOfferIsBilledTheOffer() { e164 := aNumber() s.vendor.monthly = 0 @@ -1018,26 +1093,24 @@ func (l *meteringLogs) count(level, message string) int { return lines } -// failingLegWrites fails the next writes of a new leg's row, as a database that does not answer -// in time does. -type failingLegWrites struct { - mu sync.Mutex - left int +// failingQueries fails the next queries holding a text, as a database that does not answer in +// time does. +type failingQueries struct { + mu sync.Mutex + query string + left int } -// fail fails the next times writes. -func (f *failingLegWrites) fail(times int) { +// fail fails the next times queries holding query. +func (f *failingQueries) fail(query string, times int) { f.mu.Lock() defer f.mu.Unlock() - f.left = times + f.query, f.left = query, times } -func (f *failingLegWrites) BeforeQuery(ctx context.Context, event *bun.QueryEvent) context.Context { - if !strings.HasPrefix(event.Query, `INSERT INTO "call_legs"`) { - return ctx - } +func (f *failingQueries) BeforeQuery(ctx context.Context, event *bun.QueryEvent) context.Context { f.mu.Lock() - failing := f.left > 0 + failing := f.left > 0 && strings.Contains(event.Query, f.query) if failing { f.left-- } @@ -1050,7 +1123,7 @@ func (f *failingLegWrites) BeforeQuery(ctx context.Context, event *bun.QueryEven return expired } -func (*failingLegWrites) AfterQuery(context.Context, *bun.QueryEvent) {} +func (*failingQueries) AfterQuery(context.Context, *bun.QueryEvent) {} // meteringClock is the service's clock, moved by the test. type meteringClock struct { diff --git a/acceleration/internal/phone/phone.go b/acceleration/internal/phone/phone.go index 86827e1eb4..076102daf8 100644 --- a/acceleration/internal/phone/phone.go +++ b/acceleration/internal/phone/phone.go @@ -486,6 +486,13 @@ type InboundStopper interface { StopInbound(ctx context.Context, e164 string) error } +// NumberFinder is a vendor that can say whether its account holds a number, which settles a +// purchase or a release whose outcome was not recorded (Service.SweepOrders). +type NumberFinder interface { + // HoldsNumber reports whether the account holds e164, and the vendor's id for it. + HoldsNumber(ctx context.Context, e164 string) (string, bool, error) +} + // Hanger is a vendor that can hang up a call it placed, ringing or answered. type Hanger interface { HangUp(ctx context.Context, vendorCallID string) error diff --git a/acceleration/internal/phone/phone_test.go b/acceleration/internal/phone/phone_test.go index 297fa1128d..ca846310e4 100644 --- a/acceleration/internal/phone/phone_test.go +++ b/acceleration/internal/phone/phone_test.go @@ -613,9 +613,10 @@ type stub struct { monthly int64 vendorID string // ordered counts the numbers this vendor was asked to sell, and released the numbers it - // was told to take back. + // was told to take back. holds is the numbers it sold and still holds. ordered int released []string + holds map[string]bool // releaseErr is what a release answers, the vendor's other answers left to err. releaseErr error // stopped are the numbers this vendor was told to stop sending callers to the trunk. @@ -648,12 +649,27 @@ func (s *stub) BuyNumber(_ context.Context, order Order) (Number, error) { if s.err != nil { return Number{}, s.err } + if s.holds == nil { + s.holds = map[string]bool{} + } + s.holds[order.E164] = true return Number{E164: order.E164, Vendor: s.vendor, VendorID: s.vendorID, Country: "US", MonthlyCostMicros: s.monthly}, nil } func (s *stub) ReleaseNumber(_ context.Context, e164 string) error { s.released = append(s.released, e164) - return cmp.Or(s.releaseErr, s.err) + if err := cmp.Or(s.releaseErr, s.err); err != nil { + return err + } + delete(s.holds, e164) + return nil +} + +func (s *stub) HoldsNumber(_ context.Context, e164 string) (string, bool, error) { + if s.err != nil { + return "", false, s.err + } + return s.vendorID, s.holds[e164], nil } func (s *stub) ConfigureInbound(_ context.Context, inbound Inbound) error { diff --git a/acceleration/internal/phone/service.go b/acceleration/internal/phone/service.go index d527c7b1dc..d08c6750b5 100644 --- a/acceleration/internal/phone/service.go +++ b/acceleration/internal/phone/service.go @@ -435,8 +435,9 @@ const unverifiedTier = "not-verified" // Buy buys a number and records that the customer now holds it. // -// The vendor is the side that costs money, so it goes first: a row without a number is a -// lie, while a number without a row is a reconcilable mistake that is also logged. +// The vendor is the side that costs money, so it goes before the number's row: a row without a +// number would be a lie. An order kept before the vendor is asked makes a number whose row is +// not written one the sweep records (SweepOrders), rather than one paid for and held by nobody. func (s *Service) Buy(ctx context.Context, purchase Purchase) (store.PhoneNumber, error) { if purchase.Owner.CustomerID == "" { return store.PhoneNumber{}, stack.Wrap(errors.New("phone: a number must belong to a customer")) @@ -492,6 +493,20 @@ func (s *Service) Buy(ctx context.Context, purchase Purchase) (store.PhoneNumber if err != nil { return store.PhoneNumber{}, err } + // To the microsecond Postgres keeps, so a month billed now and one billed from the stored + // row name the same purchase. + purchasedAt := s.now().UTC().Truncate(time.Microsecond) + order := store.PhoneNumberOrder{ + CustomerID: purchase.Owner.CustomerID, Vendor: purchase.Vendor, E164: purchase.E164, Action: store.OrderBuy, + Country: cmp.Or(purchase.Country, Country(purchase.E164)), MonthlyCostMicros: quoted, Tags: purchase.Owner.Tags, + CreatedAt: purchasedAt, + } + if s.store != nil { + if err := s.store.PhoneNumberOrders.Insert(ctx, &order); err != nil { + booked.Release() + return store.PhoneNumber{}, err + } + } // A failed purchase is a row of its own; a bought number is billed by its months, the // first of them below. buying := routing.Meter{ @@ -506,6 +521,7 @@ func (s *Service) Buy(ctx context.Context, purchase Purchase) (store.PhoneNumber }) if err != nil { booked.Release() + s.forgetOrder(ctx, order) return store.PhoneNumber{}, err } if bought.MonthlyCostMicros == 0 { @@ -521,9 +537,7 @@ func (s *Service) Buy(ctx context.Context, purchase Purchase) (store.PhoneNumber CustomerID: purchase.Owner.CustomerID, Tags: purchase.Owner.Tags, VendorID: bought.VendorID, - // To the microsecond Postgres keeps, so a month billed now and one billed from the - // stored row name the same purchase. - PurchasedAt: s.now().UTC().Truncate(time.Microsecond), + PurchasedAt: purchasedAt, } // The month it was bought in is charged at once, whether or not the row below is kept. s.billMonth(held, purchase.Owner, held.PurchasedAt) @@ -531,9 +545,9 @@ func (s *Service) Buy(ctx context.Context, purchase Purchase) (store.PhoneNumber if s.store == nil { return held, nil } - if err := s.store.PhoneNumbers.Insert(ctx, &held); err != nil { + if _, err := s.store.PhoneNumberOrders.Bought(ctx, order.ID, &held); err != nil { // The number is bought either way, so saying so is more useful than failing and - // leaving the caller thinking it was not. + // leaving the caller thinking it was not. Its order is kept for the sweep. // Support finds the number at the vendor by its order, and the log holds no number. return held, stack.Wrap(fmt.Errorf("phone: a number bought from %s as %q was not recorded: %w", held.Vendor, held.VendorID, err)) @@ -554,17 +568,27 @@ func (s *Service) Release(ctx context.Context, customerID, e164 string) error { } // Off its trunk first: a trunk Stream would not delete fails the release before the // number is given back, so the release can be tried again. - if err := s.unline(ctx, held, "released a number", false); err != nil { + if err := s.unline(ctx, held, "released a number", time.Time{}); err != nil { return err } seller, err := s.seller(held.Vendor) if err != nil { return err } + releasedAt := time.Now().UTC() + var order store.PhoneNumberOrder // A number on the customer's own trunk was never bought here, so there is nobody to // give it back to. if seller != nil { + // Kept before the vendor is asked, so a number given back whose row is not released + // below is released by the sweep (SweepOrders), rather than billed every month. + order = store.PhoneNumberOrder{CustomerID: held.CustomerID, Vendor: held.Vendor, E164: e164, Action: store.OrderRelease, + CreatedAt: releasedAt} + if err := s.store.PhoneNumberOrders.Insert(ctx, &order); err != nil { + return err + } if err := seller.ReleaseNumber(ctx, e164); err != nil { + s.forgetOrder(ctx, order) if age := s.now().Sub(held.PurchasedAt); age < NumberSettles && errors.As(err, new(*VendorError)) { return stack.Wrap(fmt.Errorf("%w: %s was bought %s ago: %w", ErrNumberSettling, e164, age.Round(time.Second), err)) } @@ -573,7 +597,118 @@ func (s *Service) Release(ctx context.Context, customerID, e164 string) error { } // The trunk and rule the number was attached with would otherwise outlive it, billed // and pointing a number nobody holds at a call. - return s.unline(ctx, held, "released a number", true) + if err := s.unline(ctx, held, "released a number", releasedAt); err != nil { + return err + } + s.forgetOrder(ctx, order) + return nil +} + +// forgetOrder forgets an order whose outcome is recorded, or that the vendor refused. One that +// cannot be forgotten is left to the sweep, which asks the vendor again. +func (s *Service) forgetOrder(ctx context.Context, order store.PhoneNumberOrder) { + if s.store == nil || order.ID == 0 { + return + } + if err := s.store.PhoneNumberOrders.Delete(context.WithoutCancel(ctx), order.ID); err != nil { + s.logger.Warn("could not forget a number's order; the sweep settles it", "order", order.ID, "error", err) + } +} + +// orderSettles is how old an order is before the sweep settles it: far longer than a purchase +// or a release takes, so one still running is never settled under it. orderSweepBatch bounds +// how many one sweep settles. +const ( + orderSettles = 10 * time.Minute + orderSweepBatch = 100 +) + +// SweepOrders settles the purchases and releases of numbers whose outcome was not recorded, +// by asking each vendor whether it holds the number: one bought and held gets its row, and its +// first month if the purchase did not bill it; one given back and no longer held is released, +// as of when it was. Any other order changed nothing and is forgotten. An order whose vendor +// cannot say is logged for an operator and kept. It reports how many it settled. +func (s *Service) SweepOrders(ctx context.Context) (int, error) { + if s.store == nil { + return 0, nil + } + orders, err := s.store.PhoneNumberOrders.SelectBefore(ctx, s.now().Add(-orderSettles), orderSweepBatch) + if err != nil { + return 0, err + } + settled := 0 + for _, order := range orders { + if err := s.settleOrder(ctx, order); err != nil { + s.logger.Error("could not settle a number's purchase or release", "order", order.ID, "action", order.Action, + "vendor", order.Vendor, "customer", order.CustomerID, "error", err) + continue + } + settled++ + } + return settled, nil +} + +// settleOrder settles one order by what its vendor holds, and forgets it. +func (s *Service) settleOrder(ctx context.Context, order store.PhoneNumberOrder) error { + provider, err := s.registry.Open(order.Vendor) + if err != nil { + return err + } + finder, ok := provider.(NumberFinder) + if !ok { + return stack.Wrap(fmt.Errorf("phone: %s cannot say whether it holds a number, so the order is settled by hand", order.Vendor)) + } + vendorID, held, err := finder.HoldsNumber(ctx, order.E164) + if err != nil { + return err + } + switch { + case order.Action == store.OrderBuy && held: + return s.recordBought(ctx, order, vendorID) + case order.Action == store.OrderRelease && !held: + number, err := s.store.PhoneNumbers.GetByE164(ctx, order.CustomerID, order.E164) + if err != nil && !errors.Is(err, store.ErrNoNumber) { + return err + } + if err == nil { + if err := s.unline(ctx, number, "released a number", order.CreatedAt); err != nil { + return err + } + s.logger.Warn("released a number given back whose release was not recorded", "order", order.ID, + "vendor", order.Vendor, "customer", order.CustomerID) + } + } + return s.store.PhoneNumberOrders.Delete(ctx, order.ID) +} + +// recordBought writes the row of a number an order bought, from the order, and bills its first +// month unless the purchase did. A row that already holds the number, another purchase's, leaves +// nothing to record. +func (s *Service) recordBought(ctx context.Context, order store.PhoneNumberOrder, vendorID string) error { + number := store.PhoneNumber{ + E164: order.E164, Vendor: order.Vendor, Country: order.Country, MonthlyCostMicros: order.MonthlyCostMicros, + CustomerID: order.CustomerID, Tags: order.Tags, VendorID: vendorID, PurchasedAt: order.CreatedAt, + } + month := numberMonth(number, number.PurchasedAt).UsageID + billed, err := s.store.RecordedUsage(ctx, []uuid.UUID{month}) + if err != nil { + return err + } + bought, err := s.store.PhoneNumberOrders.Bought(ctx, order.ID, &number) + if errors.Is(err, store.ErrNumberRecorded) { + return s.store.PhoneNumberOrders.Delete(ctx, order.ID) + } + if err != nil || !bought { + return err + } + s.logger.Warn("recorded a number bought whose row was not written", "order", order.ID, "vendor", order.Vendor, + "vendor_id", vendorID, "customer", order.CustomerID) + if !billed[month] { + s.billMonth(number, routing.Owner{ + CustomerID: number.CustomerID, Attribution: routing.Attribution{APIKey: OriginNumberRental}, Tags: number.Tags, + }, number.PurchasedAt) + } + return nil } // Detach stops a number's callers reaching the agent. The number keeps its trunk and rule, @@ -631,11 +766,11 @@ func (s *Service) seller(vendor string) (Provider, error) { } // unline takes a number off its trunk and deletes its rule, in the app they are in, and -// forgets them on the number. With release it also gives the number back under the same -// lock, so a line made for it meanwhile cannot put it back on a trunk. A Stream failure is -// logged, not returned, so the number is still taken off, save a trunk Stream would not -// delete (see offTrunk). -func (s *Service) unline(ctx context.Context, held store.PhoneNumber, why string, release bool) error { +// forgets them on the number. With a releasedAt it also gives the number back, as of then, +// under the same lock, so a line made for it meanwhile cannot put it back on a trunk. A Stream +// failure is logged, not returned, so the number is still taken off, save a trunk Stream would +// not delete (see offTrunk). +func (s *Service) unline(ctx context.Context, held store.PhoneNumber, why string, releasedAt time.Time) error { app := held.StreamAppPK // A call or attach lining the number in another app while this waited for its lock // moves it there, and a release follows it. @@ -659,12 +794,12 @@ func (s *Service) unline(ctx context.Context, held store.PhoneNumber, why string return err } } - if release { - return tx.ReleaseNumber(number.E164, time.Now().UTC()) + if !releasedAt.IsZero() { + return tx.ReleaseNumber(number.E164, releasedAt) } return nil }) - if err != nil || !moved || !release { + if err != nil || !moved || releasedAt.IsZero() { return err } } @@ -827,7 +962,7 @@ func (s *Service) Attach(ctx context.Context, attachment Attachment) (Attached, // A number lined in another app is taken off there first: the customer's app is where // its calls go now. if held.StreamTrunkID != "" && held.StreamAppPK != pin { - if err := s.unline(ctx, held, "re-attached a number in another app", false); err != nil { + if err := s.unline(ctx, held, "re-attached a number in another app", time.Time{}); err != nil { return Attached{}, err } held.StreamTrunkID, held.StreamRouteID = "", "" @@ -848,13 +983,13 @@ func (s *Service) Attach(ctx context.Context, attachment Attachment) (Attached, } // Attached before its trunk's password was kept, so its trunk cannot be shared: it is // replaced by one of its own, which keeps it. - if err := s.unline(ctx, held, "re-attached a number", false); err != nil { + if err := s.unline(ctx, held, "re-attached a number", time.Time{}); err != nil { return Attached{}, err } } else if held.StreamTrunkID != "" { // Still on a trunk of its own (detached, or lined for calls out), and Stream refuses a // second trunk naming it. - if err := s.unline(ctx, held, "re-attached a number", false); err != nil { + if err := s.unline(ctx, held, "re-attached a number", time.Time{}); err != nil { return Attached{}, err } } @@ -1802,7 +1937,7 @@ func (s *Service) sharedLine(ctx context.Context, stream *Stream, pin int64, pro // An attached number stays where its callers are sent. Stream lets a number be on one // trunk per app, so the call can still have one of its own here. if held.StreamTrunkID != "" && held.StreamAppPK != pin && held.AttachedAt == nil { - if err := s.unline(ctx, held, "lined a number in another app", false); err != nil { + if err := s.unline(ctx, held, "lined a number in another app", time.Time{}); err != nil { return TrunkLine{}, false, err } } diff --git a/acceleration/internal/phone/telnyx/telnyx.go b/acceleration/internal/phone/telnyx/telnyx.go index 24cb08c197..d2469706d9 100644 --- a/acceleration/internal/phone/telnyx/telnyx.go +++ b/acceleration/internal/phone/telnyx/telnyx.go @@ -19,6 +19,7 @@ import ( "net/http" "net/url" "os" + "slices" "strconv" "strings" "time" @@ -431,22 +432,48 @@ func (p *Provider) priceOf(ctx context.Context, e164 string) (int64, error) { // idFor finds Telnyx's own identifier for a number this account owns, which is what // changing or releasing it needs. func (p *Provider) idFor(ctx context.Context, e164 string) (string, error) { + number, listed, err := p.listed(ctx, e164) + if err != nil { + return "", err + } + if !listed { + return "", stack.Wrap(fmt.Errorf("telnyx: %s is not one of this account's numbers", e164)) + } + return number.ID, nil +} + +// notHeld are the statuses of a number Telnyx lists that the account does not hold: one whose +// purchase or port failed, one given back, and one ported away. +var notHeld = []string{"purchase-failed", "port-failed", "deleted", "ported-out"} + +// HoldsNumber reports whether this account holds a number, its purchase still pending or done, +// and Telnyx's id for it. +func (p *Provider) HoldsNumber(ctx context.Context, e164 string) (string, bool, error) { + number, listed, err := p.listed(ctx, e164) + if err != nil || !listed || slices.Contains(notHeld, number.Status) { + return "", false, err + } + return number.ID, true, nil +} + +// listed is the number as Telnyx lists it among this account's, in whatever status. +func (p *Provider) listed(ctx context.Context, e164 string) (ownedNumber, bool, error) { if e164 == "" { - return "", stack.Wrap(errors.New("telnyx: a number is required")) + return ownedNumber{}, false, stack.Wrap(errors.New("telnyx: a number is required")) } query := url.Values{"filter[phone_number]": {e164}} var response envelope[[]ownedNumber] if err := p.do(ctx, http.MethodGet, "/v2/phone_numbers", query, nil, &response); err != nil { - return "", err + return ownedNumber{}, false, err } for _, number := range response.Data { if number.PhoneNumber == e164 { - return number.ID, nil + return number, true, nil } } - return "", stack.Wrap(fmt.Errorf("telnyx: %s is not one of this account's numbers", e164)) + return ownedNumber{}, false, nil } func (p *Provider) do(ctx context.Context, method, path string, query url.Values, body, into any) error { @@ -604,6 +631,7 @@ type availableNumber struct { type ownedNumber struct { ID string `json:"id"` PhoneNumber string `json:"phone_number"` + Status string `json:"status"` } type orderedNumber struct { diff --git a/acceleration/internal/phone/telnyx/telnyx_test.go b/acceleration/internal/phone/telnyx/telnyx_test.go index b758af439e..dd38eecc6c 100644 --- a/acceleration/internal/phone/telnyx/telnyx_test.go +++ b/acceleration/internal/phone/telnyx/telnyx_test.go @@ -176,6 +176,34 @@ func (s *TelnyxSuite) TestANumberThisAccountDoesNotOwnCannotBeReleased() { s.ErrorContains(err, "not one of this account's numbers") } +func (s *TelnyxSuite) TestANumberThisAccountHoldsIsFoundByItsNumber() { + s.answer(`{"data":[{"id":"num-3","phone_number":"+15125551234","status":"purchase-pending"}]}`) + + id, held, err := s.provider.HoldsNumber(s.ctx, "+15125551234") + + s.Require().NoError(err) + s.True(held, "a purchase still pending is the account's number") + s.Equal("num-3", id) + s.Equal("+15125551234", s.seen.query.Get("filter[phone_number]")) +} + +// A number Telnyx still lists after its purchase failed, or after it was given back or ported +// away, is not one the account holds. +func (s *TelnyxSuite) TestANumberListedAsFailedOrGoneIsNotHeld() { + for _, status := range []string{"purchase-failed", "port-failed", "deleted", "ported-out"} { + s.answer(`{"data":[{"id":"num-3","phone_number":"+15125551234","status":"` + status + `"}]}`) + + _, held, err := s.provider.HoldsNumber(s.ctx, "+15125551234") + + s.Require().NoError(err) + s.False(held, status) + } + s.answer(`{"data":[]}`) + _, held, err := s.provider.HoldsNumber(s.ctx, "+15125551234") + s.Require().NoError(err) + s.False(held, "not listed at all") +} + func (s *TelnyxSuite) TestConfiguringInboundAssignsTheNumberToTheConnection() { s.answer(`{"data":[{"id":"num-3","phone_number":"+15125551234"}]}`) diff --git a/acceleration/internal/phone/twilio/twilio.go b/acceleration/internal/phone/twilio/twilio.go index 89be9e7e3d..14332e7f9f 100644 --- a/acceleration/internal/phone/twilio/twilio.go +++ b/acceleration/internal/phone/twilio/twilio.go @@ -521,22 +521,31 @@ func (p *Provider) Client() *http.Client { return p.client } // sidFor finds Twilio's own identifier for a number this account owns, which is what // changing or releasing it needs. func (p *Provider) sidFor(ctx context.Context, e164 string) (string, error) { + sid, held, err := p.HoldsNumber(ctx, e164) + if err == nil && !held { + return "", stack.Wrap(fmt.Errorf("twilio: %s is not one of this account's numbers", e164)) + } + return sid, err +} + +// HoldsNumber reports whether this account holds a number, and Twilio's sid for it. +func (p *Provider) HoldsNumber(ctx context.Context, e164 string) (string, bool, error) { if e164 == "" { - return "", stack.Wrap(errors.New("twilio: a number is required")) + return "", false, stack.Wrap(errors.New("twilio: a number is required")) } path := fmt.Sprintf("/2010-04-01/Accounts/%s/IncomingPhoneNumbers.json", p.accountSID) var owned incomingNumbers if err := p.get(ctx, path, url.Values{"PhoneNumber": {e164}}, &owned); err != nil { - return "", err + return "", false, err } for _, number := range owned.IncomingPhoneNumbers { if number.PhoneNumber == e164 { - return number.SID, nil + return number.SID, true, nil } } - return "", stack.Wrap(fmt.Errorf("twilio: %s is not one of this account's numbers", e164)) + return "", false, nil } func (p *Provider) get(ctx context.Context, path string, query url.Values, into any) error { diff --git a/acceleration/internal/phone/twilio/twilio_test.go b/acceleration/internal/phone/twilio/twilio_test.go index dc0f034eba..dfa3255fb1 100644 --- a/acceleration/internal/phone/twilio/twilio_test.go +++ b/acceleration/internal/phone/twilio/twilio_test.go @@ -426,6 +426,26 @@ func (s *TwilioSuite) TestANumberThisAccountDoesNotOwnCannotBeReleased() { s.ErrorContains(err, "not one of this account's numbers") } +func (s *TwilioSuite) TestANumberThisAccountHoldsIsFoundByItsNumber() { + s.answer(`{"incoming_phone_numbers":[{"sid":"PN9","phone_number":"+15125551234"}]}`) + + sid, held, err := s.provider.HoldsNumber(s.ctx, "+15125551234") + + s.Require().NoError(err) + s.True(held) + s.Equal("PN9", sid) + s.Equal("+15125551234", s.seen.query.Get("PhoneNumber")) +} + +func (s *TwilioSuite) TestANumberThisAccountDoesNotListIsNotHeld() { + s.answer(`{"incoming_phone_numbers":[]}`) + + _, held, err := s.provider.HoldsNumber(s.ctx, "+15125551234") + + s.Require().NoError(err) + s.False(held) +} + func (s *TwilioSuite) TestConfiguringInboundPointsTheNumberAtTheBridge() { s.answer(`{"incoming_phone_numbers":[{"sid":"PN9","phone_number":"+15125551234"}], "sid":"PN9","phone_number":"+15125551234"}`) diff --git a/acceleration/internal/store/datamove.go b/acceleration/internal/store/datamove.go index 96d3f8186d..e5ac4dc68d 100644 --- a/acceleration/internal/store/datamove.go +++ b/acceleration/internal/store/datamove.go @@ -105,7 +105,9 @@ func (t dataTable) rollup() bool { // deployment's key. And voice_samples and voice_bindings: a sample's audio is in this // deployment's bucket and a binding's clone in this deployment's account at the provider, so // like a knowledge file's, neither means anything where the customer moves. A voice arrives -// with its name and description, to be given a recording and prepared again. +// with its name and description, to be given a recording and prepared again. And +// phone_number_orders: a purchase or release in flight at this deployment's vendor accounts, +// which only this deployment's sweep can settle. var dataTables = []dataTable{ {name: "agent_configs", customer: "customer_id"}, {name: "skills", customer: "customer_id"}, diff --git a/acceleration/internal/store/phone_number.go b/acceleration/internal/store/phone_number.go index 5897f7230a..9b9f47d4b0 100644 --- a/acceleration/internal/store/phone_number.go +++ b/acceleration/internal/store/phone_number.go @@ -149,6 +149,11 @@ type PhoneNumbers struct { // Insert stores a number a customer now holds. func (r *PhoneNumbers) Insert(ctx context.Context, number *PhoneNumber) error { + return insertNumber(ctx, r.store.global, number) +} + +// insertNumber stores a number a customer now holds, in db. +func insertNumber(ctx context.Context, db bun.IDB, number *PhoneNumber) error { if err := number.Validate(); err != nil { return stack.Wrap(err) } @@ -161,7 +166,7 @@ func (r *PhoneNumbers) Insert(ctx context.Context, number *PhoneNumber) error { number.Capabilities = []string{} } - if _, err := r.store.global.NewInsert().Model(number).Exec(ctx); err != nil { + if _, err := db.NewInsert().Model(number).Exec(ctx); err != nil { return stack.Wrap(fmt.Errorf("store: record number: %w", err)) } return nil diff --git a/acceleration/internal/store/phone_number_order.go b/acceleration/internal/store/phone_number_order.go new file mode 100644 index 0000000000..b2f88790e3 --- /dev/null +++ b/acceleration/internal/store/phone_number_order.go @@ -0,0 +1,119 @@ +package store + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/uptrace/bun" + + "github.com/GetStream/Vision-Agents/acceleration/internal/stack" +) + +// What a PhoneNumberOrder asks a vendor to do. +const ( + OrderBuy = "buy" + OrderRelease = "release" +) + +// PhoneNumberOrder is a purchase or a release of a number, kept from before the vendor is asked +// until the number's row says what the vendor did. One left behind is an outcome that was not +// recorded, which the vendor's own account settles. +type PhoneNumberOrder struct { + bun.BaseModel `bun:"table:phone_number_orders,alias:pno"` + + ID int64 `bun:"id,pk,autoincrement"` + CustomerID string `bun:"customer_id,notnull"` + Vendor string `bun:"vendor,notnull"` + E164 string `bun:"e164,notnull"` + // Action is OrderBuy or OrderRelease. + Action string `bun:"action,notnull"` + // Country, MonthlyCostMicros and Tags are what a purchase's row is written with when the + // vendor's answer was lost: the country it was offered from and the price it was quoted. + Country string `bun:"country,notnull"` + MonthlyCostMicros int64 `bun:"monthly_cost_micros,notnull"` + Tags map[string]string `bun:"tags,type:jsonb,nullzero"` + // CreatedAt is when the number was bought or released, as its row says. + CreatedAt time.Time `bun:"created_at,notnull"` +} + +// Validate refuses an order no vendor could be asked about. +func (o *PhoneNumberOrder) Validate() error { + return validate("phone number order"). + required("customer_id", o.CustomerID). + required("vendor", o.Vendor). + phoneNumber("e164", o.E164). + oneOf("action", o.Action, OrderBuy, OrderRelease). + check(!o.CreatedAt.IsZero(), "created_at", "is required"). + done() +} + +// ErrNumberRecorded is Bought's error when a row already holds the number. +var ErrNumberRecorded = errors.New("store: a row already holds the number") + +// PhoneNumberOrders are the purchases and releases of numbers whose outcome is not recorded +// yet, in the shared database. +type PhoneNumberOrders struct { + store *Store +} + +// Insert keeps an order, before the vendor is asked. +func (r *PhoneNumberOrders) Insert(ctx context.Context, order *PhoneNumberOrder) error { + if err := order.Validate(); err != nil { + return stack.Wrap(err) + } + order.CreatedAt = order.CreatedAt.UTC().Truncate(time.Microsecond) + if _, err := r.store.global.NewInsert().Model(order).Returning("id").Exec(ctx); err != nil { + return stack.Wrap(fmt.Errorf("store: record number order: %w", err)) + } + return nil +} + +// Delete forgets an order whose outcome is recorded. One already gone is no error. +func (r *PhoneNumberOrders) Delete(ctx context.Context, id int64) error { + if _, err := r.store.global.NewDelete().Model((*PhoneNumberOrder)(nil)).Where("id = ?", id).Exec(ctx); err != nil { + return stack.Wrap(fmt.Errorf("store: forget number order: %w", err)) + } + return nil +} + +// SelectBefore returns at most limit orders made before before, oldest first. +func (r *PhoneNumberOrders) SelectBefore(ctx context.Context, before time.Time, limit int) ([]PhoneNumberOrder, error) { + var orders []PhoneNumberOrder + err := r.store.global.NewSelect().Model(&orders). + Where("created_at < ?", before.UTC()). + Order("created_at", "id"). + Limit(limit). + Scan(ctx) + if err != nil { + return nil, stack.Wrap(fmt.Errorf("store: number orders: %w", err)) + } + return orders, nil +} + +// Bought records the number an order bought and forgets the order, as one. It reports false, +// and records nothing, for an order that is gone, settled by another router. A row already +// holding the number is ErrNumberRecorded, and keeps the order. +func (r *PhoneNumberOrders) Bought(ctx context.Context, id int64, number *PhoneNumber) (bool, error) { + var bought bool + err := r.store.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { + result, err := tx.NewDelete().Model((*PhoneNumberOrder)(nil)).Where("id = ?", id).Exec(ctx) + if err != nil { + return fmt.Errorf("store: forget number order: %w", err) + } + if deleted, _ := result.RowsAffected(); deleted == 0 { + return nil + } + err = insertNumber(ctx, tx, number) + if isViolation(err, uniqueViolation) { + return ErrNumberRecorded + } + bought = err == nil + return err + }) + if err != nil { + return false, stack.Wrap(err) + } + return bought, nil +} diff --git a/acceleration/internal/store/phone_number_order_test.go b/acceleration/internal/store/phone_number_order_test.go new file mode 100644 index 0000000000..0c6c331eb6 --- /dev/null +++ b/acceleration/internal/store/phone_number_order_test.go @@ -0,0 +1,70 @@ +//go:build integration + +package store + +import ( + "time" +) + +// order keeps a purchase of e164 for a customer. +func (s *StoreSuite) order(customerID, e164 string) PhoneNumberOrder { + order := PhoneNumberOrder{CustomerID: customerID, Vendor: "telnyx", E164: e164, Action: OrderBuy, CreatedAt: s.base} + s.Require().NoError(s.store.PhoneNumberOrders.Insert(s.ctx, &order)) + return order +} + +// Two routers settling the same purchase record one number: the order goes with the first. +func (s *StoreSuite) TestAPurchaseSettledTwiceRecordsOneNumber() { + customerID := newID() + order := s.order(customerID, "+15125550100") + first := PhoneNumber{CustomerID: customerID, Vendor: "telnyx", E164: order.E164, PurchasedAt: order.CreatedAt} + second := first + + bought, err := s.store.PhoneNumberOrders.Bought(s.ctx, order.ID, &first) + s.Require().NoError(err) + s.True(bought) + bought, err = s.store.PhoneNumberOrders.Bought(s.ctx, order.ID, &second) + s.Require().NoError(err) + s.False(bought, "the order was settled") + + held, err := s.store.PhoneNumbers.Select(s.ctx, customerID, PhoneNumberFilter{}) + s.Require().NoError(err) + s.Len(held, 1) + left, err := s.store.PhoneNumberOrders.SelectBefore(s.ctx, s.base.Add(time.Hour), 10) + s.Require().NoError(err) + s.Empty(left) +} + +// A number a row already holds is not recorded again, and its order is kept. +func (s *StoreSuite) TestAPurchaseOfANumberARowHoldsRecordsNothing() { + customerID := newID() + held := PhoneNumber{CustomerID: customerID, Vendor: "telnyx", E164: "+15125550100", PurchasedAt: s.base} + s.Require().NoError(s.store.PhoneNumbers.Insert(s.ctx, &held)) + order := s.order(newID(), held.E164) + + _, err := s.store.PhoneNumberOrders.Bought(s.ctx, order.ID, + &PhoneNumber{CustomerID: order.CustomerID, Vendor: "telnyx", E164: order.E164, PurchasedAt: order.CreatedAt}) + + s.ErrorIs(err, ErrNumberRecorded) + left, err := s.store.PhoneNumberOrders.SelectBefore(s.ctx, s.base.Add(time.Hour), 10) + s.Require().NoError(err) + s.Len(left, 1) +} + +func (s *StoreSuite) TestPhoneNumberOrderQueryBudgets() { + customerID := newID() + var order PhoneNumberOrder + s.Equal(1, s.countQueries(func() { order = s.order(customerID, "+15125550100") }), "Insert") + s.Equal(1, s.countQueries(func() { + left, err := s.store.PhoneNumberOrders.SelectBefore(s.ctx, s.base.Add(time.Hour), 10) + s.Require().NoError(err) + s.Len(left, 1) + }), "SelectBefore") + s.Equal(2+2, s.countQueries(func() { + bought, err := s.store.PhoneNumberOrders.Bought(s.ctx, order.ID, + &PhoneNumber{CustomerID: customerID, Vendor: "telnyx", E164: order.E164, PurchasedAt: order.CreatedAt}) + s.Require().NoError(err) + s.True(bought) + }), "Bought forgets the order, then records the number") + s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.PhoneNumberOrders.Delete(s.ctx, order.ID)) }), "Delete") +} diff --git a/acceleration/internal/store/phone_number_order_unit_test.go b/acceleration/internal/store/phone_number_order_unit_test.go new file mode 100644 index 0000000000..188c7ec261 --- /dev/null +++ b/acceleration/internal/store/phone_number_order_unit_test.go @@ -0,0 +1,31 @@ +package store + +import ( + "errors" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestPhoneNumberOrderValidate(t *testing.T) { + valid := func() PhoneNumberOrder { + return PhoneNumberOrder{CustomerID: "app", Vendor: "telnyx", E164: "+15551234567", Action: OrderBuy, CreatedAt: time.Now()} + } + model := valid() + require.NoError(t, model.Validate()) + + for field, broken := range map[string]func(*PhoneNumberOrder){ + "customer_id": func(m *PhoneNumberOrder) { m.CustomerID = "" }, + "vendor": func(m *PhoneNumberOrder) { m.Vendor = "" }, + "e164": func(m *PhoneNumberOrder) { m.E164 = "15551234567" }, + "action": func(m *PhoneNumberOrder) { m.Action = "port" }, + "created_at": func(m *PhoneNumberOrder) { m.CreatedAt = time.Time{} }, + } { + model := valid() + broken(&model) + var invalid *ValidationError + require.True(t, errors.As(model.Validate(), &invalid), field) + require.Equal(t, field, invalid.Field) + } +} diff --git a/acceleration/internal/store/repos.go b/acceleration/internal/store/repos.go index c6bc0c9480..fa441f6150 100644 --- a/acceleration/internal/store/repos.go +++ b/acceleration/internal/store/repos.go @@ -64,6 +64,7 @@ type repos struct { OptOuts *OptOuts OrganizationTiers *OrganizationTiers Organizations *Organizations + PhoneNumberOrders *PhoneNumberOrders PhoneNumbers *PhoneNumbers Policies *Policies PriceChanges *PriceChanges @@ -168,6 +169,7 @@ func (s *Store) wire() { OptOuts: &OptOuts{store: s}, OrganizationTiers: &OrganizationTiers{store: s}, Organizations: &Organizations{store: s}, + PhoneNumberOrders: &PhoneNumberOrders{store: s}, PhoneNumbers: &PhoneNumbers{store: s}, Policies: &Policies{store: s}, PriceChanges: &PriceChanges{store: s}, diff --git a/acceleration/migrations/global/20270201000300_phone_number_orders.sql b/acceleration/migrations/global/20270201000300_phone_number_orders.sql new file mode 100644 index 0000000000..6767f2ae90 --- /dev/null +++ b/acceleration/migrations/global/20270201000300_phone_number_orders.sql @@ -0,0 +1,22 @@ +-- +goose Up +SET LOCAL lock_timeout = '5s'; + +-- A purchase or a release of a number, written before the vendor is asked and deleted once the +-- number's row says what the vendor did. A row left behind is one whose outcome was not +-- recorded: the phone sweep asks the vendor whether it holds the number, and writes the row or +-- the release it says. created_at is when the number was bought or released. +CREATE TABLE IF NOT EXISTS phone_number_orders ( + id BIGSERIAL PRIMARY KEY, + customer_id TEXT NOT NULL, + vendor TEXT NOT NULL, + e164 TEXT NOT NULL, + action TEXT NOT NULL CHECK (action IN ('buy', 'release')), + country TEXT NOT NULL DEFAULT '', + monthly_cost_micros BIGINT NOT NULL DEFAULT 0, + tags JSONB NOT NULL DEFAULT '{}', + created_at TIMESTAMPTZ NOT NULL +); +CREATE INDEX IF NOT EXISTS phone_number_orders_created_idx ON phone_number_orders (created_at); + +-- +goose Down +DROP TABLE phone_number_orders; diff --git a/acceleration/schema/global.sql b/acceleration/schema/global.sql index 53b9684181..15dd2bfe17 100644 --- a/acceleration/schema/global.sql +++ b/acceleration/schema/global.sql @@ -987,6 +987,20 @@ TABLE organizations name text NOT NULL CONSTRAINT organizations_pkey PRIMARY KEY (id) +TABLE phone_number_orders + action text NOT NULL + country text NOT NULL DEFAULT ''::text + created_at timestamp with time zone NOT NULL + customer_id text NOT NULL + e164 text NOT NULL + id bigint NOT NULL DEFAULT nextval('phone_number_orders_id_seq'::regclass) + monthly_cost_micros bigint NOT NULL DEFAULT 0 + tags jsonb NOT NULL DEFAULT '{}'::jsonb + vendor text NOT NULL + CONSTRAINT phone_number_orders_action_check CHECK ((action = ANY (ARRAY['buy'::text, 'release'::text]))) + CONSTRAINT phone_number_orders_pkey PRIMARY KEY (id) + CREATE INDEX phone_number_orders_created_idx ON public.phone_number_orders USING btree (created_at) + TABLE phone_numbers attached_at timestamp with time zone capabilities text[] NOT NULL DEFAULT '{}'::text[] From e4875394d61d28f61415d6746ed63e32b0719124 Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 20:11:52 +0100 Subject: [PATCH 04/12] fix(dlc): ask the vendor once for a brand or campaign A brand or campaign registration whose answer was lost (a timeout, a 5xx, or the row not written after it) left no id behind, so the next poll registered, and the vendor billed, a second one. Two routers polling at once could do the same. The router now records when it asked (business_profiles. brand_requested_at, dlc_use_cases.campaign_requested_at) with a conditional update before the vendor is asked, so only one caller asks. A 4xx from Telnyx (dlc.ErrVendorRefused) registered nothing and forgets the request; any other failure keeps it, and each poll then logs at ERROR for an operator instead of asking again. Telnyx takes no idempotency key on these calls, so there is no safe automatic retry. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/dlc_test.go | 70 +++++++++++++++++++ acceleration/internal/dlc/dlc.go | 4 ++ acceleration/internal/dlc/service.go | 31 +++++++- acceleration/internal/dlc/telnyx/telnyx.go | 7 +- .../internal/store/business_profile.go | 43 ++++++++++-- .../internal/store/business_profile_test.go | 7 ++ acceleration/internal/store/use_case.go | 49 +++++++++++-- acceleration/internal/store/use_case_test.go | 7 ++ ...270201000310_dlc_registration_requests.sql | 12 ++++ acceleration/schema/global.sql | 2 + 10 files changed, 219 insertions(+), 13 deletions(-) create mode 100644 acceleration/migrations/global/20270201000310_dlc_registration_requests.sql diff --git a/acceleration/internal/api/dlc_test.go b/acceleration/internal/api/dlc_test.go index 4eb284d71e..af68b8e69c 100644 --- a/acceleration/internal/api/dlc_test.go +++ b/acceleration/internal/api/dlc_test.go @@ -37,6 +37,11 @@ type campaignRegistry struct { mu sync.Mutex campaigns map[string]string assigned map[string]string + // brandAnswers and campaignAnswers are the statuses the next registrations are answered + // with, each registered whatever the answer; past them every one is answered 200. brands + // and campaignsAsked count the registrations asked for. + brandAnswers, campaignAnswers []int + brandsAsked, campaignsAsked int } // campaignRegistryFails is a campaign status no vendor sends: the fake answers a read of a @@ -52,12 +57,22 @@ func (r *campaignRegistry) ServeHTTP(w http.ResponseWriter, request *http.Reques path := request.URL.Path switch { case request.Method == http.MethodPost && path == "/v2/10dlc/brand": + r.brandsAsked++ + if answer := nextAnswer(&r.brandAnswers); answer != http.StatusOK { + w.WriteHeader(answer) + return + } fmt.Fprintf(w, `{"brandId":%q,"status":"OK","identityStatus":"VERIFIED"}`, uuid.NewString()) case request.Method == http.MethodGet && strings.HasPrefix(path, "/v2/10dlc/brand/"): fmt.Fprintf(w, `{"brandId":%q,"status":"OK","identityStatus":"VERIFIED"}`, strings.TrimPrefix(path, "/v2/10dlc/brand/")) case request.Method == http.MethodPost && path == "/v2/10dlc/campaignBuilder": + r.campaignsAsked++ id := uuid.NewString() r.campaigns[id] = "TCR_PENDING" + if answer := nextAnswer(&r.campaignAnswers); answer != http.StatusOK { + w.WriteHeader(answer) + return + } fmt.Fprintf(w, `{"campaignId":%q,"campaignStatus":"TCR_PENDING"}`, id) case request.Method == http.MethodGet && strings.HasPrefix(path, "/v2/10dlc/campaign/"): id := strings.TrimPrefix(path, "/v2/10dlc/campaign/") @@ -74,6 +89,28 @@ func (r *campaignRegistry) ServeHTTP(w http.ResponseWriter, request *http.Reques } } +// nextAnswer takes the first of answers, or 200 when there is none. +func nextAnswer(answers *[]int) int { + if len(*answers) == 0 { + return http.StatusOK + } + answer := (*answers)[0] + *answers = (*answers)[1:] + return answer +} + +// answer has the next brand and campaign registrations answered with brands and campaigns, +// and reports how many of each were asked for so far. +func (r *campaignRegistry) answer(brands, campaigns []int) (int, int) { + r.mu.Lock() + defer r.mu.Unlock() + r.brandAnswers, r.campaignAnswers = brands, campaigns + return r.brandsAsked, r.campaignsAsked +} + +// asked is how many brand and campaign registrations were asked for so far. +func (r *campaignRegistry) asked() (int, int) { return r.answer(nil, nil) } + func (r *campaignRegistry) set(campaignID, status string) { r.mu.Lock() defer r.mu.Unlock() @@ -247,6 +284,39 @@ func (s *DLCSuite) TestAUseCaseIsApprovedByStreamAndThenByTheVendor() { s.Contains(failure, "no Stream app") } +// A brand Telnyx refused registered nothing, and is asked for again. One whose registration was +// answered with a failure may be registered, and billed, all the same, so it is not asked for +// again, however often the poller looks. +func (s *DLCSuite) TestABrandWhoseRegistrationWasNotAnsweredIsNotRegisteredTwice() { + brands, _ := s.registry.answer([]int{http.StatusBadRequest, http.StatusInternalServerError}, nil) + sent := s.submitted() + + status, reviewed := s.review(sent.Id, dlc.Approve, "") + s.Require().Equal(http.StatusOK, status) + s.Equal(UseCaseStatus(dlc.VendorPending), reviewed.Status) + s.Equal(http.StatusNoContent, s.report(`{"brandId":"another"}`, s.signing), "the poller asks again after the refusal") + s.Equal(http.StatusNoContent, s.report(`{"brandId":"another"}`, s.signing)) + + asked, _ := s.registry.asked() + s.Equal(2, asked-brands, "refused, then asked once more") + s.Contains(s.logged.String(), "its answer was not recorded") +} + +// A campaign whose registration was answered with a failure may be registered, and billed, all +// the same, so it is not asked for again. +func (s *DLCSuite) TestACampaignWhoseRegistrationWasNotAnsweredIsNotRegisteredTwice() { + _, campaigns := s.registry.answer(nil, []int{http.StatusInternalServerError}) + sent := s.submitted() + + status, reviewed := s.review(sent.Id, dlc.Approve, "") + s.Require().Equal(http.StatusOK, status) + s.Nil(reviewed.VendorCampaignId) + s.Equal(http.StatusNoContent, s.report(`{"brandId":"another"}`, s.signing)) + + _, asked := s.registry.asked() + s.Equal(1, asked-campaigns) +} + // pendingWithTheVendor is a use case Stream approved and Telnyx holds a campaign for. func (s *dlcRegistration) pendingWithTheVendor() (string, string) { sent := s.submitted() diff --git a/acceleration/internal/dlc/dlc.go b/acceleration/internal/dlc/dlc.go index 3d350cebaf..9b6d2df4ed 100644 --- a/acceleration/internal/dlc/dlc.go +++ b/acceleration/internal/dlc/dlc.go @@ -67,6 +67,10 @@ var ErrLocked = errors.New("dlc: the use case cannot do that in its status") // ErrRefused is a text or call the gate would not let through. var ErrRefused = errors.New("dlc: refused") +// ErrVendorRefused is a vendor answering that it refused a request, and so did not carry it +// out: a registration it refused registered nothing, and may be asked for again. +var ErrVendorRefused = errors.New("dlc: the vendor refused") + // ErrUnpaid is a text, call or number refused because the organization may not pay for it. // The refusal it wraps says why: suspended, out of credit, or past a spend limit. var ErrUnpaid = errors.New("dlc: the organization may not pay for this") diff --git a/acceleration/internal/dlc/service.go b/acceleration/internal/dlc/service.go index 0ddd29af10..a27b1ac1b7 100644 --- a/acceleration/internal/dlc/service.go +++ b/acceleration/internal/dlc/service.go @@ -407,8 +407,15 @@ func (s *Service) refresh(ctx context.Context, useCase store.UseCase, report []b return nil } +// errUnanswered is a brand or campaign the vendor was asked to register, with no answer +// recorded: it may be registered, and billed, at the vendor, and the vendor takes no key that +// would make asking again safe. An operator looks it up there, and records its id or forgets +// the request. +var errUnanswered = errors.New("dlc: the vendor was asked to register this before and its answer was not recorded") + // register registers the app's brand if it has none, and the campaign once the brand is -// verified. A brand the vendor refused leaves nothing to register the campaign under. +// verified. A brand the vendor refused leaves nothing to register the campaign under. Each is +// asked for once (requested): only a refusal lets it be asked for again. func (s *Service) register(ctx context.Context, useCase store.UseCase) error { profile, err := s.store.BusinessProfiles.Get(ctx, useCase.CustomerID) if err != nil { @@ -420,10 +427,17 @@ func (s *Service) register(ctx context.Context, useCase store.UseCase) error { if err != nil { return err } + if err := requested(s.store.BusinessProfiles.RequestBrand(ctx, useCase.CustomerID, s.now())); err != nil { + booked.Release() + return fmt.Errorf("%w: the brand of %s", err, useCase.CustomerID) + } brand, err = routing.Call(ctx, s.feeMeter(ctx, ModelBrand, useCase.CustomerID, nil), func(ctx context.Context) (Brand, error) { return s.registrar.RegisterBrand(ctx, profile) }) if err != nil { booked.Release() + if errors.Is(err, ErrVendorRefused) { + err = errors.Join(err, s.store.BusinessProfiles.ForgetBrandRequest(ctx, useCase.CustomerID)) + } return err } booked.Charged() @@ -452,6 +466,10 @@ func (s *Service) register(ctx context.Context, useCase store.UseCase) error { if err != nil { return err } + if err := requested(s.store.UseCases.RequestCampaign(ctx, useCase.ID, s.now())); err != nil { + booked.Release() + return fmt.Errorf("%w: the campaign of use case %s", err, useCase.ID) + } campaign, err := routing.Call(ctx, s.feeMeter(ctx, ModelCampaign, useCase.CustomerID, map[string]string{AttributeUseCaseType: useCaseType(useCase)}), func(ctx context.Context) (Campaign, error) { @@ -459,6 +477,9 @@ func (s *Service) register(ctx context.Context, useCase store.UseCase) error { }) if err != nil { booked.Release() + if errors.Is(err, ErrVendorRefused) { + err = errors.Join(err, s.store.UseCases.ForgetCampaignRequest(ctx, useCase.ID)) + } return err } defer booked.Charged() @@ -472,6 +493,14 @@ func (s *Service) register(ctx context.Context, useCase store.UseCase) error { return s.store.UseCases.Move(ctx, &useCase, VendorPending, log) } +// requested is a request's outcome as an error: errUnanswered for one asked for before. +func requested(requested bool, err error) error { + if err == nil && !requested { + return stack.Wrap(errUnanswered) + } + return err +} + // assignAtVendor tells the vendor which of its numbers send as the campaign. A number from // another vendor is not the registrar's to assign. func (s *Service) assignAtVendor(ctx context.Context, useCase store.UseCase) error { diff --git a/acceleration/internal/dlc/telnyx/telnyx.go b/acceleration/internal/dlc/telnyx/telnyx.go index d0ce1cf43d..42b691e462 100644 --- a/acceleration/internal/dlc/telnyx/telnyx.go +++ b/acceleration/internal/dlc/telnyx/telnyx.go @@ -294,7 +294,12 @@ func (r *Registrar) do(ctx context.Context, method, path string, body, into any) defer response.Body.Close() if response.StatusCode < 200 || response.StatusCode >= 300 { detail, _ := io.ReadAll(io.LimitReader(response.Body, errorBodyLimit)) - return nil, stack.Wrap(fmt.Errorf("telnyx: %s: %s: %s", path, response.Status, strings.TrimSpace(string(detail)))) + err := fmt.Errorf("telnyx: %s: %s: %s", path, response.Status, strings.TrimSpace(string(detail))) + // A 4xx is Telnyx refusing the request; a 5xx may follow work it did. + if response.StatusCode < http.StatusInternalServerError { + err = fmt.Errorf("%w: %w", dlc.ErrVendorRefused, err) + } + return nil, stack.Wrap(err) } raw, err := io.ReadAll(response.Body) if err != nil { diff --git a/acceleration/internal/store/business_profile.go b/acceleration/internal/store/business_profile.go index b7e352b384..b988080dc2 100644 --- a/acceleration/internal/store/business_profile.go +++ b/acceleration/internal/store/business_profile.go @@ -40,10 +40,13 @@ type BusinessProfile struct { VerificationDocuments []string `bun:"business_verification_documents,array"` // VendorBrandID is the brand the vendor registered the app as, and BrandStatus the // vendor's own word for where it stands. Empty until a use case was sent. - VendorBrandID string `bun:"vendor_brand_id,notnull"` - BrandStatus string `bun:"brand_status,notnull"` - CreatedAt time.Time `bun:"created_at,notnull"` - UpdatedAt time.Time `bun:"updated_at,notnull"` + VendorBrandID string `bun:"vendor_brand_id,notnull"` + BrandStatus string `bun:"brand_status,notnull"` + // BrandRequestedAt is when the vendor was asked to register the brand (RequestBrand). Set + // with no VendorBrandID, the vendor's answer was lost. + BrandRequestedAt *time.Time `bun:"brand_requested_at"` + CreatedAt time.Time `bun:"created_at,notnull"` + UpdatedAt time.Time `bun:"updated_at,notnull"` } // PostalAddress is where a business is registered. @@ -157,3 +160,35 @@ func (r *BusinessProfiles) SetBrand(ctx context.Context, customerID, brandID, st } return nil } + +// RequestBrand records that the vendor is about to be asked to register the app's brand. It +// reports false, and records nothing, for an app with a brand, or one the vendor was asked for +// already: that registration may be running, or its answer was lost, and asking again could +// register and bill a second brand. +func (r *BusinessProfiles) RequestBrand(ctx context.Context, customerID string, at time.Time) (bool, error) { + result, err := r.store.global.NewUpdate().Model((*BusinessProfile)(nil)). + Set("brand_requested_at = ?", at.UTC()). + Where("customer_id = ?", customerID). + Where("vendor_brand_id = ''"). + Where("brand_requested_at IS NULL"). + Exec(ctx) + if err != nil { + return false, stack.Wrap(fmt.Errorf("store: request brand: %w", err)) + } + requested, _ := result.RowsAffected() + return requested == 1, nil +} + +// ForgetBrandRequest forgets a brand request the vendor refused, so the brand may be asked for +// again. +func (r *BusinessProfiles) ForgetBrandRequest(ctx context.Context, customerID string) error { + _, err := r.store.global.NewUpdate().Model((*BusinessProfile)(nil)). + Set("brand_requested_at = NULL"). + Where("customer_id = ?", customerID). + Where("vendor_brand_id = ''"). + Exec(ctx) + if err != nil { + return stack.Wrap(fmt.Errorf("store: forget brand request: %w", err)) + } + return nil +} diff --git a/acceleration/internal/store/business_profile_test.go b/acceleration/internal/store/business_profile_test.go index 0bbc8f5bbf..668589d903 100644 --- a/acceleration/internal/store/business_profile_test.go +++ b/acceleration/internal/store/business_profile_test.go @@ -23,6 +23,13 @@ func (s *StoreSuite) TestBusinessProfileQueryBudgets() { customerID := newID() profile := BusinessProfile{CustomerID: customerID, LegalBusinessName: "Acme Inc"} s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.BusinessProfiles.Upsert(s.ctx, &profile)) }), "Upsert") + s.Equal(1, s.countQueries(func() { + requested, err := s.store.BusinessProfiles.RequestBrand(s.ctx, customerID, s.base) + s.Require().NoError(err) + s.True(requested) + }), "RequestBrand") + s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.BusinessProfiles.ForgetBrandRequest(s.ctx, customerID)) }), + "ForgetBrandRequest") s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.BusinessProfiles.SetBrand(s.ctx, customerID, "brand-1", "VERIFIED")) }), "SetBrand") diff --git a/acceleration/internal/store/use_case.go b/acceleration/internal/store/use_case.go index a5b8cd154d..c090025bd9 100644 --- a/acceleration/internal/store/use_case.go +++ b/acceleration/internal/store/use_case.go @@ -40,13 +40,16 @@ type UseCase struct { Channels UseCaseChannels `bun:"channels,type:jsonb,notnull"` // Vendor is who the campaign was registered with, VendorCampaignID its id there and // VendorStatus the vendor's own word for where it stands. - Vendor string `bun:"vendor,notnull"` - VendorCampaignID string `bun:"vendor_campaign_id,notnull"` - VendorStatus string `bun:"vendor_status,notnull"` - CreatedAt time.Time `bun:"created_at,notnull"` - UpdatedAt time.Time `bun:"updated_at,notnull"` - SubmittedAt *time.Time `bun:"submitted_at"` - ApprovedAt *time.Time `bun:"approved_at"` + Vendor string `bun:"vendor,notnull"` + VendorCampaignID string `bun:"vendor_campaign_id,notnull"` + VendorStatus string `bun:"vendor_status,notnull"` + // CampaignRequestedAt is when the vendor was asked to register the campaign + // (RequestCampaign). Set with no VendorCampaignID, the vendor's answer was lost. + CampaignRequestedAt *time.Time `bun:"campaign_requested_at"` + CreatedAt time.Time `bun:"created_at,notnull"` + UpdatedAt time.Time `bun:"updated_at,notnull"` + SubmittedAt *time.Time `bun:"submitted_at"` + ApprovedAt *time.Time `bun:"approved_at"` } // UseCaseChannels are the fields the channels besides 10DLC ask for. Each is absent for a @@ -426,6 +429,38 @@ func (r *UseCases) Move(ctx context.Context, useCase *UseCase, from string, log })) } +// RequestCampaign records that the vendor is about to be asked to register a use case's +// campaign. It reports false, and records nothing, for a use case with a campaign, or one the +// vendor was asked for already: that registration may be running, or its answer was lost, and +// asking again could register and bill a second campaign. +func (r *UseCases) RequestCampaign(ctx context.Context, id string, at time.Time) (bool, error) { + result, err := r.store.global.NewUpdate().Model((*UseCase)(nil)). + Set("campaign_requested_at = ?", at.UTC()). + Where("id = ?", id). + Where("vendor_campaign_id = ''"). + Where("campaign_requested_at IS NULL"). + Exec(ctx) + if err != nil { + return false, stack.Wrap(fmt.Errorf("store: request campaign: %w", err)) + } + requested, _ := result.RowsAffected() + return requested == 1, nil +} + +// ForgetCampaignRequest forgets a campaign request the vendor refused, so the campaign may be +// asked for again. +func (r *UseCases) ForgetCampaignRequest(ctx context.Context, id string) error { + _, err := r.store.global.NewUpdate().Model((*UseCase)(nil)). + Set("campaign_requested_at = NULL"). + Where("id = ?", id). + Where("vendor_campaign_id = ''"). + Exec(ctx) + if err != nil { + return stack.Wrap(fmt.Errorf("store: forget campaign request: %w", err)) + } + return nil +} + // AssignNumbers makes numbers exactly the ones that send as a use case. A number named // leaves whatever use case it sent as before; one no longer named goes back to the default. func (r *UseCases) AssignNumbers(ctx context.Context, customerID, useCaseID string, numbers []string) error { diff --git a/acceleration/internal/store/use_case_test.go b/acceleration/internal/store/use_case_test.go index 4941242a4b..9d083d4585 100644 --- a/acceleration/internal/store/use_case_test.go +++ b/acceleration/internal/store/use_case_test.go @@ -160,6 +160,13 @@ func (s *StoreSuite) TestUseCaseQueryBudgets() { _, err := s.store.UseCases.GetByID(s.ctx, useCase.ID) s.Require().NoError(err) }), "GetByID") + s.Equal(1, s.countQueries(func() { + requested, err := s.store.UseCases.RequestCampaign(s.ctx, useCase.ID, s.base) + s.Require().NoError(err) + s.True(requested) + }), "RequestCampaign") + s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.UseCases.ForgetCampaignRequest(s.ctx, useCase.ID)) }), + "ForgetCampaignRequest") useCase.Status, useCase.Vendor, useCase.VendorCampaignID = "submitted", "telnyx", "campaign-"+useCase.ID s.Equal(2+2, s.countQueries(func() { s.Require().NoError(s.store.UseCases.Move(s.ctx, &useCase, "draft", &ReviewLog{Actor: "vendor", Notes: "Registered campaign-" + useCase.ID + "."})) diff --git a/acceleration/migrations/global/20270201000310_dlc_registration_requests.sql b/acceleration/migrations/global/20270201000310_dlc_registration_requests.sql new file mode 100644 index 0000000000..e81e2bcaff --- /dev/null +++ b/acceleration/migrations/global/20270201000310_dlc_registration_requests.sql @@ -0,0 +1,12 @@ +-- +goose Up +SET LOCAL lock_timeout = '5s'; + +-- When the vendor was asked to register an app's brand, and a use case's campaign, written +-- before it is asked. One with no brand or campaign id recorded is a registration whose answer +-- was lost: the vendor may hold it, and have billed it, so it is not asked again. +ALTER TABLE business_profiles ADD COLUMN IF NOT EXISTS brand_requested_at TIMESTAMPTZ; +ALTER TABLE dlc_use_cases ADD COLUMN IF NOT EXISTS campaign_requested_at TIMESTAMPTZ; + +-- +goose Down +ALTER TABLE dlc_use_cases DROP COLUMN campaign_requested_at; +ALTER TABLE business_profiles DROP COLUMN brand_requested_at; diff --git a/acceleration/schema/global.sql b/acceleration/schema/global.sql index 15dd2bfe17..fd9745a67a 100644 --- a/acceleration/schema/global.sql +++ b/acceleration/schema/global.sql @@ -147,6 +147,7 @@ TABLE business_profiles authorized_contact_phone text NOT NULL DEFAULT ''::text authorized_contact_title text NOT NULL DEFAULT ''::text brand_name text NOT NULL DEFAULT ''::text + brand_requested_at timestamp with time zone brand_status text NOT NULL DEFAULT ''::text business_registration_country text NOT NULL DEFAULT ''::text business_verification_documents text[] NOT NULL DEFAULT '{}'::text[] @@ -738,6 +739,7 @@ TABLE dlc_review_logs TABLE dlc_use_cases age_gated boolean NOT NULL DEFAULT false approved_at timestamp with time zone + campaign_requested_at timestamp with time zone channels jsonb NOT NULL DEFAULT '{}'::jsonb created_at timestamp with time zone NOT NULL customer_id text NOT NULL From a9a9b7d1123203470e9cb05ed21d65722214afce Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 21:30:00 +0100 Subject: [PATCH 05/12] fix(phone): leave an order the vendor answered with an error to a sweep A purchase or release whose vendor call timed out or answered a 5xx may have been carried out, so its order now stays for the sweep to settle by what the vendor holds; only a 4xx refusal forgets it at once. The sweep claims due orders with FOR UPDATE SKIP LOCKED and moves each one's next attempt an hour on, so one router asks about an order at a time and an order no vendor can settle no longer starves newer ones. A swept release only releases the row the order gave back (same vendor, bought before it), a Telnyx number found by the sweep records no other kind of vendor id, and a purchase whose order a sweep settled first says it was not recorded. Co-Authored-By: Claude Opus 5.5 --- .../phone/metering_integration_test.go | 92 ++++++++++++++++++- acceleration/internal/phone/phone.go | 3 +- acceleration/internal/phone/phone_test.go | 11 ++- acceleration/internal/phone/service.go | 42 +++++++-- acceleration/internal/phone/telnyx/telnyx.go | 7 +- .../internal/phone/telnyx/telnyx_test.go | 2 +- .../internal/store/phone_number_order.go | 26 +++--- .../internal/store/phone_number_order_test.go | 48 +++++++--- .../store/phone_number_order_unit_test.go | 14 +-- .../20270201000300_phone_number_orders.sql | 14 ++- acceleration/schema/global.sql | 4 +- 11 files changed, 209 insertions(+), 54 deletions(-) diff --git a/acceleration/internal/phone/metering_integration_test.go b/acceleration/internal/phone/metering_integration_test.go index 4ba88d618b..b2a7bb4634 100644 --- a/acceleration/internal/phone/metering_integration_test.go +++ b/acceleration/internal/phone/metering_integration_test.go @@ -8,6 +8,7 @@ import ( "errors" "log/slog" "math/rand/v2" + "net/http" "os" "strconv" "strings" @@ -51,6 +52,8 @@ type MeteringSuite struct { deployment *chattest.Server customer string e164 string + // registry is where the service opens s.vendor. + registry *Registry // failing fails the queries a test asks it to. failing *failingQueries } @@ -96,6 +99,7 @@ func (s *MeteringSuite) withSandbox(sandbox dlc.Sandbox) { s.Require().NoError(err) registry := NewRegistry(config) registry.Register(s.vendor.vendor, func() (Provider, error) { return s.vendor, nil }) + s.registry = registry declared, _ := config.Lookup(s.vendor.vendor) for _, name := range declared.Credentials { s.T().Setenv(name, "set") @@ -860,11 +864,97 @@ func (s *MeteringSuite) TestANumberGivenBackWithoutItsReleaseIsReleasedByTheSwee s.False(numbers[0].ReleasedAt.After(returned), "released as of when the vendor took it back, not when the sweep ran") } +// A number the vendor bought, whose answer was lost to a timeout, is recorded by the sweep and +// its first month billed. +func (s *MeteringSuite) TestANumberBoughtWhoseAnswerWasLostIsRecordedByTheSweep() { + e164 := aNumber() + s.vendor.offers = []Available{{E164: e164, MonthlyCostMicros: 1_000_000}} + s.vendor.doneErr = &VendorError{Vendor: s.vendor.vendor, Path: "/v2/number_orders", Message: "no answer", Cause: context.DeadlineExceeded} + _, err := s.service.Buy(s.ctx, Purchase{Vendor: s.vendor.vendor, E164: e164, Owner: s.owner()}) + s.Require().Error(err) + s.clock.advance(orderSettles + time.Minute) + + _, err = s.service.SweepOrders(s.ctx) + + s.Require().NoError(err) + held, err := s.store.PhoneNumbers.GetByE164(s.ctx, s.customer, e164) + s.Require().NoError(err, "the vendor holds it, so the customer does") + s.Equal(int64(1_000_000), held.MonthlyCostMicros) + var months []store.Request + for _, row := range s.rowsWhen(ModelNumber, 2) { + if row.Success { + months = append(months, row) + } + } + s.Require().Len(months, 1, "its first month, beside the purchase's failure") + s.Equal(held.PurchasedAt.UTC(), months[0].StartedAt.UTC()) + s.Zero(s.orders()) +} + +// A number the vendor took back, whose answer was a 5xx, is released by the sweep rather than +// billed every month. +func (s *MeteringSuite) TestANumberGivenBackWhoseAnswerWasAFailureIsReleasedByTheSweep() { + s.vendor.holds = map[string]bool{s.e164: true} + s.vendor.doneErr = &VendorError{Vendor: s.vendor.vendor, Path: "/v2/phone_numbers", Status: http.StatusBadGateway} + s.Require().Error(s.service.Release(s.ctx, s.customer, s.e164)) + s.clock.advance(orderSettles + time.Minute) + + _, err := s.service.SweepOrders(s.ctx) + + s.Require().NoError(err) + _, err = s.store.PhoneNumbers.GetByE164(s.ctx, s.customer, s.e164) + s.ErrorIs(err, store.ErrNoNumber) + s.Zero(s.orders()) +} + +// A release that failed at a vendor still holding the number leaves the customer holding it: +// the sweep releases only what the vendor no longer has. +func (s *MeteringSuite) TestANumberTheVendorStillHoldsAfterAFailedReleaseStaysHeld() { + s.vendor.holds = map[string]bool{s.e164: true} + s.vendor.releaseErr = &VendorError{Vendor: s.vendor.vendor, Path: "/v2/phone_numbers", Status: http.StatusServiceUnavailable} + s.Require().Error(s.service.Release(s.ctx, s.customer, s.e164)) + s.Require().Equal(1, s.orders()) + s.clock.advance(orderSettles + time.Minute) + + _, err := s.service.SweepOrders(s.ctx) + + s.Require().NoError(err) + held, err := s.store.PhoneNumbers.GetByE164(s.ctx, s.customer, s.e164) + s.Require().NoError(err) + s.Nil(held.ReleasedAt) + s.Zero(s.orders()) +} + +// An order at a vendor that cannot say what it holds records nothing and is kept for an +// operator, and the sweeps that follow do not ask about it again until it is due once more. +func (s *MeteringSuite) TestAnOrderAVendorCannotSettleIsKeptAndNotAskedAboutEverySweep() { + e164 := aNumber() + s.vendor.offers = []Available{{E164: e164, MonthlyCostMicros: 1_000_000}} + s.vendor.doneErr = &VendorError{Vendor: s.vendor.vendor, Path: "/v2/number_orders", Status: http.StatusGatewayTimeout} + _, err := s.service.Buy(s.ctx, Purchase{Vendor: s.vendor.vendor, E164: e164, Owner: s.owner()}) + s.Require().Error(err) + // The vendor as one that has no NumberFinder. + s.registry.Register(s.vendor.vendor, func() (Provider, error) { return struct{ Provider }{s.vendor}, nil }) + s.clock.advance(orderSettles + time.Minute) + + _, err = s.service.SweepOrders(s.ctx) + s.Require().NoError(err) + _, err = s.service.SweepOrders(s.ctx) + s.Require().NoError(err) + + _, err = s.store.PhoneNumbers.GetByE164(s.ctx, s.customer, e164) + s.ErrorIs(err, store.ErrNoNumber, "nothing is recorded that the vendor did not confirm") + s.Equal(1, s.orders(), "kept for an operator") + // Other tests' orders are in the same tables, so only this customer's lines are counted. + s.Equal(1, s.logs.count("ERROR", "customer="+s.customer), "asked about once, not every sweep") + s.Contains(s.logs.String(), "could not settle a number's purchase or release") +} + // A purchase the vendor refused, whose order could not be forgotten, leaves no number. func (s *MeteringSuite) TestAnOrderTheVendorDoesNotHoldIsForgottenWithoutANumber() { e164 := aNumber() s.failing.fail(`DELETE FROM "phone_number_orders"`, 1) - s.vendor.err = errors.New("the vendor refused") + s.vendor.err = &VendorError{Vendor: s.vendor.vendor, Path: "/v2/number_orders", Status: http.StatusUnprocessableEntity} _, err := s.service.Buy(s.ctx, Purchase{Vendor: s.vendor.vendor, E164: e164, Owner: s.owner()}) s.Require().Error(err) s.vendor.err = nil diff --git a/acceleration/internal/phone/phone.go b/acceleration/internal/phone/phone.go index 076102daf8..4ed2462e56 100644 --- a/acceleration/internal/phone/phone.go +++ b/acceleration/internal/phone/phone.go @@ -489,7 +489,8 @@ type InboundStopper interface { // NumberFinder is a vendor that can say whether its account holds a number, which settles a // purchase or a release whose outcome was not recorded (Service.SweepOrders). type NumberFinder interface { - // HoldsNumber reports whether the account holds e164, and the vendor's id for it. + // HoldsNumber reports whether the account holds e164, and the id its purchase is recorded + // by (Number.VendorID), empty when the vendor's listing cannot name it. HoldsNumber(ctx context.Context, e164 string) (string, bool, error) } diff --git a/acceleration/internal/phone/phone_test.go b/acceleration/internal/phone/phone_test.go index ca846310e4..b3458efb54 100644 --- a/acceleration/internal/phone/phone_test.go +++ b/acceleration/internal/phone/phone_test.go @@ -617,8 +617,10 @@ type stub struct { ordered int released []string holds map[string]bool - // releaseErr is what a release answers, the vendor's other answers left to err. - releaseErr error + // releaseErr is what a release answers, the vendor's other answers left to err. doneErr is + // what a purchase or a release answers once the vendor has done it, as an answer lost to a + // timeout is. + releaseErr, doneErr error // stopped are the numbers this vendor was told to stop sending callers to the trunk. stopped []string // leg is how this vendor's leg reaches Stream: per call unless a test says otherwise. @@ -653,6 +655,9 @@ func (s *stub) BuyNumber(_ context.Context, order Order) (Number, error) { s.holds = map[string]bool{} } s.holds[order.E164] = true + if s.doneErr != nil { + return Number{}, s.doneErr + } return Number{E164: order.E164, Vendor: s.vendor, VendorID: s.vendorID, Country: "US", MonthlyCostMicros: s.monthly}, nil } @@ -662,7 +667,7 @@ func (s *stub) ReleaseNumber(_ context.Context, e164 string) error { return err } delete(s.holds, e164) - return nil + return s.doneErr } func (s *stub) HoldsNumber(_ context.Context, e164 string) (string, bool, error) { diff --git a/acceleration/internal/phone/service.go b/acceleration/internal/phone/service.go index d08c6750b5..bfbeb917d3 100644 --- a/acceleration/internal/phone/service.go +++ b/acceleration/internal/phone/service.go @@ -499,7 +499,7 @@ func (s *Service) Buy(ctx context.Context, purchase Purchase) (store.PhoneNumber order := store.PhoneNumberOrder{ CustomerID: purchase.Owner.CustomerID, Vendor: purchase.Vendor, E164: purchase.E164, Action: store.OrderBuy, Country: cmp.Or(purchase.Country, Country(purchase.E164)), MonthlyCostMicros: quoted, Tags: purchase.Owner.Tags, - CreatedAt: purchasedAt, + CreatedAt: purchasedAt, NextAttemptAt: purchasedAt.Add(orderSettles), } if s.store != nil { if err := s.store.PhoneNumberOrders.Insert(ctx, &order); err != nil { @@ -521,7 +521,7 @@ func (s *Service) Buy(ctx context.Context, purchase Purchase) (store.PhoneNumber }) if err != nil { booked.Release() - s.forgetOrder(ctx, order) + s.forgetRefusedOrder(ctx, order, err) return store.PhoneNumber{}, err } if bought.MonthlyCostMicros == 0 { @@ -545,7 +545,12 @@ func (s *Service) Buy(ctx context.Context, purchase Purchase) (store.PhoneNumber if s.store == nil { return held, nil } - if _, err := s.store.PhoneNumberOrders.Bought(ctx, order.ID, &held); err != nil { + recorded, err := s.store.PhoneNumberOrders.Bought(ctx, order.ID, &held) + if err == nil && !recorded { + // A sweep took the order first, and recorded the number or found the vendor without it. + err = errors.New("its order was settled by the sweep") + } + if err != nil { // The number is bought either way, so saying so is more useful than failing and // leaving the caller thinking it was not. Its order is kept for the sweep. // Support finds the number at the vendor by its order, and the log holds no number. @@ -583,12 +588,12 @@ func (s *Service) Release(ctx context.Context, customerID, e164 string) error { // Kept before the vendor is asked, so a number given back whose row is not released // below is released by the sweep (SweepOrders), rather than billed every month. order = store.PhoneNumberOrder{CustomerID: held.CustomerID, Vendor: held.Vendor, E164: e164, Action: store.OrderRelease, - CreatedAt: releasedAt} + CreatedAt: releasedAt, NextAttemptAt: s.now().Add(orderSettles)} if err := s.store.PhoneNumberOrders.Insert(ctx, &order); err != nil { return err } if err := seller.ReleaseNumber(ctx, e164); err != nil { - s.forgetOrder(ctx, order) + s.forgetRefusedOrder(ctx, order, err) if age := s.now().Sub(held.PurchasedAt); age < NumberSettles && errors.As(err, new(*VendorError)) { return stack.Wrap(fmt.Errorf("%w: %s was bought %s ago: %w", ErrNumberSettling, e164, age.Round(time.Second), err)) } @@ -604,6 +609,16 @@ func (s *Service) Release(ctx context.Context, customerID, e164 string) error { return nil } +// forgetRefusedOrder forgets an order the vendor answered err to, when err is the vendor refusing +// it: a 4xx, which it did not carry out. Any other failure, a timeout, a dropped connection or a +// 5xx, may come after the vendor bought or released the number, so the order is left to the +// sweep, which asks the vendor what it holds. +func (s *Service) forgetRefusedOrder(ctx context.Context, order store.PhoneNumberOrder, err error) { + if refused, ok := errors.AsType[*VendorError](err); ok && refused.Status >= 400 && refused.Status < 500 { + s.forgetOrder(ctx, order) + } +} + // forgetOrder forgets an order whose outcome is recorded, or that the vendor refused. One that // cannot be forgotten is left to the sweep, which asks the vendor again. func (s *Service) forgetOrder(ctx context.Context, order store.PhoneNumberOrder) { @@ -616,10 +631,12 @@ func (s *Service) forgetOrder(ctx context.Context, order store.PhoneNumberOrder) } // orderSettles is how old an order is before the sweep settles it: far longer than a purchase -// or a release takes, so one still running is never settled under it. orderSweepBatch bounds -// how many one sweep settles. +// or a release takes, so one still running is never settled under it. orderRetry is how long a +// sweep holds the orders it claimed, and so when one it could not settle is tried again, by any +// router. orderSweepBatch bounds how many one sweep claims. const ( orderSettles = 10 * time.Minute + orderRetry = time.Hour orderSweepBatch = 100 ) @@ -627,12 +644,15 @@ const ( // by asking each vendor whether it holds the number: one bought and held gets its row, and its // first month if the purchase did not bill it; one given back and no longer held is released, // as of when it was. Any other order changed nothing and is forgotten. An order whose vendor -// cannot say is logged for an operator and kept. It reports how many it settled. +// cannot say is logged for an operator and kept, to be tried again after orderRetry behind the +// orders due before then. Every router sweeps, and each order is claimed by one of them at a +// time. It reports how many it settled. func (s *Service) SweepOrders(ctx context.Context) (int, error) { if s.store == nil { return 0, nil } - orders, err := s.store.PhoneNumberOrders.SelectBefore(ctx, s.now().Add(-orderSettles), orderSweepBatch) + now := s.now() + orders, err := s.store.PhoneNumberOrders.Claim(ctx, now, now.Add(orderRetry), orderSweepBatch) if err != nil { return 0, err } @@ -670,7 +690,9 @@ func (s *Service) settleOrder(ctx context.Context, order store.PhoneNumberOrder) if err != nil && !errors.Is(err, store.ErrNoNumber) { return err } - if err == nil { + // Only the row the order gave back: the number may have been bought again since, or put + // on the customer's own trunk. + if err == nil && number.Vendor == order.Vendor && !number.PurchasedAt.After(order.CreatedAt) { if err := s.unline(ctx, number, "released a number", order.CreatedAt); err != nil { return err } diff --git a/acceleration/internal/phone/telnyx/telnyx.go b/acceleration/internal/phone/telnyx/telnyx.go index d2469706d9..119ab83bee 100644 --- a/acceleration/internal/phone/telnyx/telnyx.go +++ b/acceleration/internal/phone/telnyx/telnyx.go @@ -446,14 +446,15 @@ func (p *Provider) idFor(ctx context.Context, e164 string) (string, error) { // purchase or port failed, one given back, and one ported away. var notHeld = []string{"purchase-failed", "port-failed", "deleted", "ported-out"} -// HoldsNumber reports whether this account holds a number, its purchase still pending or done, -// and Telnyx's id for it. +// HoldsNumber reports whether this account holds a number, its purchase still pending or done. +// It names no purchase id: a purchase is recorded by its number order's id (BuyNumber), and the +// numbers Telnyx lists do not name the order that bought them. func (p *Provider) HoldsNumber(ctx context.Context, e164 string) (string, bool, error) { number, listed, err := p.listed(ctx, e164) if err != nil || !listed || slices.Contains(notHeld, number.Status) { return "", false, err } - return number.ID, true, nil + return "", true, nil } // listed is the number as Telnyx lists it among this account's, in whatever status. diff --git a/acceleration/internal/phone/telnyx/telnyx_test.go b/acceleration/internal/phone/telnyx/telnyx_test.go index dd38eecc6c..8dc3219276 100644 --- a/acceleration/internal/phone/telnyx/telnyx_test.go +++ b/acceleration/internal/phone/telnyx/telnyx_test.go @@ -183,7 +183,7 @@ func (s *TelnyxSuite) TestANumberThisAccountHoldsIsFoundByItsNumber() { s.Require().NoError(err) s.True(held, "a purchase still pending is the account's number") - s.Equal("num-3", id) + s.Empty(id, "the number's own id is not the purchase's, which is its order's") s.Equal("+15125551234", s.seen.query.Get("filter[phone_number]")) } diff --git a/acceleration/internal/store/phone_number_order.go b/acceleration/internal/store/phone_number_order.go index b2f88790e3..8a10fc1e47 100644 --- a/acceleration/internal/store/phone_number_order.go +++ b/acceleration/internal/store/phone_number_order.go @@ -36,6 +36,10 @@ type PhoneNumberOrder struct { Tags map[string]string `bun:"tags,type:jsonb,nullzero"` // CreatedAt is when the number was bought or released, as its row says. CreatedAt time.Time `bun:"created_at,notnull"` + // NextAttemptAt is when the sweep may settle the order, and Attempts how often a sweep + // claimed it (phoneNumberOrders). + Attempts int `bun:"attempts,notnull"` + NextAttemptAt time.Time `bun:"next_attempt_at,notnull"` } // Validate refuses an order no vendor could be asked about. @@ -46,6 +50,7 @@ func (o *PhoneNumberOrder) Validate() error { phoneNumber("e164", o.E164). oneOf("action", o.Action, OrderBuy, OrderRelease). check(!o.CreatedAt.IsZero(), "created_at", "is required"). + check(!o.NextAttemptAt.IsZero(), "next_attempt_at", "is required"). done() } @@ -64,6 +69,7 @@ func (r *PhoneNumberOrders) Insert(ctx context.Context, order *PhoneNumberOrder) return stack.Wrap(err) } order.CreatedAt = order.CreatedAt.UTC().Truncate(time.Microsecond) + order.NextAttemptAt = order.NextAttemptAt.UTC().Truncate(time.Microsecond) if _, err := r.store.global.NewInsert().Model(order).Returning("id").Exec(ctx); err != nil { return stack.Wrap(fmt.Errorf("store: record number order: %w", err)) } @@ -78,18 +84,14 @@ func (r *PhoneNumberOrders) Delete(ctx context.Context, id int64) error { return nil } -// SelectBefore returns at most limit orders made before before, oldest first. -func (r *PhoneNumberOrders) SelectBefore(ctx context.Context, before time.Time, limit int) ([]PhoneNumberOrder, error) { - var orders []PhoneNumberOrder - err := r.store.global.NewSelect().Model(&orders). - Where("created_at < ?", before.UTC()). - Order("created_at", "id"). - Limit(limit). - Scan(ctx) - if err != nil { - return nil, stack.Wrap(fmt.Errorf("store: number orders: %w", err)) - } - return orders, nil +// phoneNumberOrders is the queue of orders the sweep settles. +var phoneNumberOrders = queue{name: "phone number orders", alias: "pno", key: "id"} + +// Claim takes up to limit orders due by now, oldest due first, and moves each one's next +// attempt to leaseUntil: another router's claim skips them, and one the sweep could not settle +// is tried again behind the orders due before it. +func (r *PhoneNumberOrders) Claim(ctx context.Context, now, leaseUntil time.Time, limit int) ([]PhoneNumberOrder, error) { + return claim[PhoneNumberOrder](ctx, r.store.global, phoneNumberOrders, now, leaseUntil, limit, nil, "pno.*") } // Bought records the number an order bought and forgets the order, as one. It reports false, diff --git a/acceleration/internal/store/phone_number_order_test.go b/acceleration/internal/store/phone_number_order_test.go index 0c6c331eb6..f75155d16b 100644 --- a/acceleration/internal/store/phone_number_order_test.go +++ b/acceleration/internal/store/phone_number_order_test.go @@ -8,7 +8,8 @@ import ( // order keeps a purchase of e164 for a customer. func (s *StoreSuite) order(customerID, e164 string) PhoneNumberOrder { - order := PhoneNumberOrder{CustomerID: customerID, Vendor: "telnyx", E164: e164, Action: OrderBuy, CreatedAt: s.base} + order := PhoneNumberOrder{CustomerID: customerID, Vendor: "telnyx", E164: e164, Action: OrderBuy, CreatedAt: s.base, + NextAttemptAt: s.base} s.Require().NoError(s.store.PhoneNumberOrders.Insert(s.ctx, &order)) return order } @@ -30,9 +31,7 @@ func (s *StoreSuite) TestAPurchaseSettledTwiceRecordsOneNumber() { held, err := s.store.PhoneNumbers.Select(s.ctx, customerID, PhoneNumberFilter{}) s.Require().NoError(err) s.Len(held, 1) - left, err := s.store.PhoneNumberOrders.SelectBefore(s.ctx, s.base.Add(time.Hour), 10) - s.Require().NoError(err) - s.Empty(left) + s.Empty(s.claimOrders(s.base.Add(time.Hour))) } // A number a row already holds is not recorded again, and its order is kept. @@ -46,20 +45,47 @@ func (s *StoreSuite) TestAPurchaseOfANumberARowHoldsRecordsNothing() { &PhoneNumber{CustomerID: order.CustomerID, Vendor: "telnyx", E164: order.E164, PurchasedAt: order.CreatedAt}) s.ErrorIs(err, ErrNumberRecorded) - left, err := s.store.PhoneNumberOrders.SelectBefore(s.ctx, s.base.Add(time.Hour), 10) + s.Len(s.claimOrders(s.base.Add(time.Hour)), 1) +} + +// An order one router claimed is not claimed by another until its lease ends, and is then +// claimed behind the orders due before it. +func (s *StoreSuite) TestAClaimedOrderWaitsForItsLeaseBehindTheOrdersDueFirst() { + stuck := s.order(newID(), "+15125550100") + + s.Equal([]int64{stuck.ID}, s.orderIDs(s.claimOrders(s.base))) + s.Empty(s.claimOrders(s.base), "another router's claim skips it") + newer := s.order(newID(), "+15125550101") + newer.NextAttemptAt = s.base.Add(time.Minute) + _, err := s.store.global.NewUpdate().Model(&newer).Column("next_attempt_at").WherePK().Exec(s.ctx) + s.Require().NoError(err) + + first, err := s.store.PhoneNumberOrders.Claim(s.ctx, s.base.Add(time.Hour), s.base.Add(2*time.Hour), 1) s.Require().NoError(err) - s.Len(left, 1) + s.Equal([]int64{newer.ID}, s.orderIDs(first), "the order claimed before is due after the one made since") +} + +// claimOrders claims what is due at now, leased for an hour. +func (s *StoreSuite) claimOrders(now time.Time) []PhoneNumberOrder { + claimed, err := s.store.PhoneNumberOrders.Claim(s.ctx, now, now.Add(time.Hour), 10) + s.Require().NoError(err) + return claimed +} + +// orderIDs are the ids of orders, in the order a claim took them. +func (s *StoreSuite) orderIDs(orders []PhoneNumberOrder) []int64 { + var ids []int64 + for _, order := range orders { + ids = append(ids, order.ID) + } + return ids } func (s *StoreSuite) TestPhoneNumberOrderQueryBudgets() { customerID := newID() var order PhoneNumberOrder s.Equal(1, s.countQueries(func() { order = s.order(customerID, "+15125550100") }), "Insert") - s.Equal(1, s.countQueries(func() { - left, err := s.store.PhoneNumberOrders.SelectBefore(s.ctx, s.base.Add(time.Hour), 10) - s.Require().NoError(err) - s.Len(left, 1) - }), "SelectBefore") + s.Equal(1, s.countQueries(func() { s.Len(s.claimOrders(s.base.Add(time.Hour)), 1) }), "Claim") s.Equal(2+2, s.countQueries(func() { bought, err := s.store.PhoneNumberOrders.Bought(s.ctx, order.ID, &PhoneNumber{CustomerID: customerID, Vendor: "telnyx", E164: order.E164, PurchasedAt: order.CreatedAt}) diff --git a/acceleration/internal/store/phone_number_order_unit_test.go b/acceleration/internal/store/phone_number_order_unit_test.go index 188c7ec261..b74cc19a8c 100644 --- a/acceleration/internal/store/phone_number_order_unit_test.go +++ b/acceleration/internal/store/phone_number_order_unit_test.go @@ -10,17 +10,19 @@ import ( func TestPhoneNumberOrderValidate(t *testing.T) { valid := func() PhoneNumberOrder { - return PhoneNumberOrder{CustomerID: "app", Vendor: "telnyx", E164: "+15551234567", Action: OrderBuy, CreatedAt: time.Now()} + return PhoneNumberOrder{CustomerID: "app", Vendor: "telnyx", E164: "+15551234567", Action: OrderBuy, CreatedAt: time.Now(), + NextAttemptAt: time.Now()} } model := valid() require.NoError(t, model.Validate()) for field, broken := range map[string]func(*PhoneNumberOrder){ - "customer_id": func(m *PhoneNumberOrder) { m.CustomerID = "" }, - "vendor": func(m *PhoneNumberOrder) { m.Vendor = "" }, - "e164": func(m *PhoneNumberOrder) { m.E164 = "15551234567" }, - "action": func(m *PhoneNumberOrder) { m.Action = "port" }, - "created_at": func(m *PhoneNumberOrder) { m.CreatedAt = time.Time{} }, + "customer_id": func(m *PhoneNumberOrder) { m.CustomerID = "" }, + "vendor": func(m *PhoneNumberOrder) { m.Vendor = "" }, + "e164": func(m *PhoneNumberOrder) { m.E164 = "15551234567" }, + "action": func(m *PhoneNumberOrder) { m.Action = "port" }, + "created_at": func(m *PhoneNumberOrder) { m.CreatedAt = time.Time{} }, + "next_attempt_at": func(m *PhoneNumberOrder) { m.NextAttemptAt = time.Time{} }, } { model := valid() broken(&model) diff --git a/acceleration/migrations/global/20270201000300_phone_number_orders.sql b/acceleration/migrations/global/20270201000300_phone_number_orders.sql index 6767f2ae90..937b2b32d6 100644 --- a/acceleration/migrations/global/20270201000300_phone_number_orders.sql +++ b/acceleration/migrations/global/20270201000300_phone_number_orders.sql @@ -2,9 +2,11 @@ SET LOCAL lock_timeout = '5s'; -- A purchase or a release of a number, written before the vendor is asked and deleted once the --- number's row says what the vendor did. A row left behind is one whose outcome was not --- recorded: the phone sweep asks the vendor whether it holds the number, and writes the row or --- the release it says. created_at is when the number was bought or released. +-- number's row says what the vendor did, or the vendor refused. A row left behind is one whose +-- outcome was not recorded: the phone sweep claims it once next_attempt_at is due, asks the +-- vendor whether it holds the number, and writes the row or the release it says. A claim moves +-- next_attempt_at on, so one router asks at a time and an order no vendor can settle goes to +-- the back. created_at is when the number was bought or released. CREATE TABLE IF NOT EXISTS phone_number_orders ( id BIGSERIAL PRIMARY KEY, customer_id TEXT NOT NULL, @@ -14,9 +16,11 @@ CREATE TABLE IF NOT EXISTS phone_number_orders ( country TEXT NOT NULL DEFAULT '', monthly_cost_micros BIGINT NOT NULL DEFAULT 0, tags JSONB NOT NULL DEFAULT '{}', - created_at TIMESTAMPTZ NOT NULL + created_at TIMESTAMPTZ NOT NULL, + attempts INTEGER NOT NULL DEFAULT 0, + next_attempt_at TIMESTAMPTZ NOT NULL ); -CREATE INDEX IF NOT EXISTS phone_number_orders_created_idx ON phone_number_orders (created_at); +CREATE INDEX IF NOT EXISTS phone_number_orders_due_idx ON phone_number_orders (next_attempt_at, id); -- +goose Down DROP TABLE phone_number_orders; diff --git a/acceleration/schema/global.sql b/acceleration/schema/global.sql index fd9745a67a..15c5d81482 100644 --- a/acceleration/schema/global.sql +++ b/acceleration/schema/global.sql @@ -991,17 +991,19 @@ TABLE organizations TABLE phone_number_orders action text NOT NULL + attempts integer NOT NULL DEFAULT 0 country text NOT NULL DEFAULT ''::text created_at timestamp with time zone NOT NULL customer_id text NOT NULL e164 text NOT NULL id bigint NOT NULL DEFAULT nextval('phone_number_orders_id_seq'::regclass) monthly_cost_micros bigint NOT NULL DEFAULT 0 + next_attempt_at timestamp with time zone NOT NULL tags jsonb NOT NULL DEFAULT '{}'::jsonb vendor text NOT NULL CONSTRAINT phone_number_orders_action_check CHECK ((action = ANY (ARRAY['buy'::text, 'release'::text]))) CONSTRAINT phone_number_orders_pkey PRIMARY KEY (id) - CREATE INDEX phone_number_orders_created_idx ON public.phone_number_orders USING btree (created_at) + CREATE INDEX phone_number_orders_due_idx ON public.phone_number_orders USING btree (next_attempt_at, id) TABLE phone_numbers attached_at timestamp with time zone From b4ad7e02dde83b0c0f387a33e68c1ed25b567197 Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 21:30:13 +0100 Subject: [PATCH 06/12] fix(phone): write a transfer leg once, however often it is tried OpenLeg's retry and the leg sweep write a leg again after a write whose answer may have been lost. An inbound or placed leg has a key that makes that a no-op; a transfer leg had none, so a lost commit could leave a second ringing leg that a phone with an unknown number could be given, billing the transfer twice. call_legs_transfer_idx makes a tokenless leg unique by its call and the vendor's call id, so the insert's ON CONFLICT DO NOTHING writes nothing the second time. It is built concurrently after clearing the vendor id of older duplicates (only a test vendor's fixed id made them), and is rebuilt by usageIndexes if a build fails. The phone tests' stub vendor now gives each dial an id of its own, as vendors do. Co-Authored-By: Claude Opus 5.5 --- .../phone/agentjoin_integration_test.go | 2 +- .../phone/metering_integration_test.go | 6 ++--- acceleration/internal/phone/phone_test.go | 8 ++++-- acceleration/internal/store/call_leg_test.go | 25 +++++++++++++++++++ acceleration/internal/store/migrate.go | 3 +++ .../20270201000320_call_legs_transfer_idx.sql | 23 +++++++++++++++++ acceleration/schema/shard.sql | 1 + 7 files changed, 62 insertions(+), 6 deletions(-) create mode 100644 acceleration/migrations/shard/20270201000320_call_legs_transfer_idx.sql diff --git a/acceleration/internal/phone/agentjoin_integration_test.go b/acceleration/internal/phone/agentjoin_integration_test.go index cb119b34d4..6f3abd576d 100644 --- a/acceleration/internal/phone/agentjoin_integration_test.go +++ b/acceleration/internal/phone/agentjoin_integration_test.go @@ -73,7 +73,7 @@ func (s *MeteringSuite) TestACallAnsweredWithNoAgentInItIsEndedAfterTheWait() { s.checked("INFO", noAgent) s.Eventually(func() bool { return s.endedAtStream(placed.CallType, placed.CallID) }, 5*time.Second, 10*time.Millisecond) s.Contains(s.logs.String(), "session_id="+placed.CallID) - s.Contains(s.logs.String(), "vendor_call_id=telnyx-call") + s.Contains(s.logs.String(), "vendor_call_id="+s.vendor.called) s.Contains(s.logs.String(), "waited=10s") } diff --git a/acceleration/internal/phone/metering_integration_test.go b/acceleration/internal/phone/metering_integration_test.go index b2a7bb4634..e5d7bb8e29 100644 --- a/acceleration/internal/phone/metering_integration_test.go +++ b/acceleration/internal/phone/metering_integration_test.go @@ -169,14 +169,14 @@ func (s *MeteringSuite) transfer(callID, human string) { func (s *MeteringSuite) TestTheCustomerWhoTransferredCanPressDigitsOnTheTransferLeg() { s.transfer("call-"+uuid.NewString(), "+15125550124") - s.Require().NoError(s.service.SendDigits(s.ctx, s.customer, s.vendor.vendor, s.vendor.vendor+"-call", "12")) - s.Equal([]string{s.vendor.vendor + "-call:12"}, s.vendor.pressed) + s.Require().NoError(s.service.SendDigits(s.ctx, s.customer, s.vendor.vendor, s.vendor.called, "12")) + s.Equal([]string{s.vendor.called + ":12"}, s.vendor.pressed) } func (s *MeteringSuite) TestAnotherCustomerCannotPressDigitsOnATransferLeg() { s.transfer("call-"+uuid.NewString(), "+15125550124") - err := s.service.SendDigits(s.ctx, "customer-"+uuid.NewString(), s.vendor.vendor, s.vendor.vendor+"-call", "12") + err := s.service.SendDigits(s.ctx, "customer-"+uuid.NewString(), s.vendor.vendor, s.vendor.called, "12") s.ErrorIs(err, ErrCallNotFound) s.Empty(s.vendor.pressed) } diff --git a/acceleration/internal/phone/phone_test.go b/acceleration/internal/phone/phone_test.go index b3458efb54..706422a992 100644 --- a/acceleration/internal/phone/phone_test.go +++ b/acceleration/internal/phone/phone_test.go @@ -13,6 +13,7 @@ import ( "testing" "time" + "github.com/google/uuid" "github.com/stretchr/testify/suite" "github.com/GetStream/Vision-Agents/acceleration/internal/pricing" @@ -603,8 +604,10 @@ type stub struct { // apart from an empty answer. searched int // dialed is the last call this vendor was asked to place, so a test can see what the - // service passed on rather than only that it passed something. + // service passed on rather than only that it passed something, and called the id it + // gave that call, a new one each dial as a vendor's is. dialed Outbound + called string // inbound is the last number this vendor was told to send to a bridge, so a test can see // the address the service passed on. inbound Inbound @@ -687,7 +690,8 @@ func (s *stub) Dial(_ context.Context, outbound Outbound) (Dialed, error) { if s.err != nil { return Dialed{}, s.err } - return Dialed{VendorCallID: s.vendor + "-call", Status: "dialing"}, nil + s.called = s.vendor + "-call-" + uuid.NewString() + return Dialed{VendorCallID: s.called, Status: "dialing"}, nil } func (s *stub) SendDigits(_ context.Context, vendorCallID, digits string) error { diff --git a/acceleration/internal/store/call_leg_test.go b/acceleration/internal/store/call_leg_test.go index a33e350c9b..6f7250b950 100644 --- a/acceleration/internal/store/call_leg_test.go +++ b/acceleration/internal/store/call_leg_test.go @@ -235,6 +235,31 @@ func (s *StoreSuite) TestOpeningAPlacedLegDialsItOnce() { s.False(opened) } +// A transfer leg written again, as a write whose answer was lost is, is the one leg: a second +// ringing leg could be given to a phone of the call and bill the transfer twice. +func (s *StoreSuite) TestATransferLegWrittenTwiceIsOneLeg() { + transfer := CallLeg{CustomerID: "app", StreamAppPK: 7, CallType: "default", CallID: "call", Vendor: "telnyx", + VendorCallID: "vendor-1", Direction: Outbound, LocalNumber: "+15125550100", RemoteNumber: "+15125550199", + DialedAt: s.base} + first, again := transfer, transfer + + opened, err := s.store.CallLegs.Open(s.ctx, &first) + s.Require().NoError(err) + s.True(opened) + opened, err = s.store.CallLegs.Open(s.ctx, &again) + s.Require().NoError(err) + s.False(opened) + + legs, err := s.store.shard.NewSelect().Model((*CallLeg)(nil)).Where("call_id = ?", "call").Count(s.ctx) + s.Require().NoError(err) + s.Equal(1, legs) + other := transfer + other.VendorCallID = "vendor-2" + opened, err = s.store.CallLegs.Open(s.ctx, &other) + s.Require().NoError(err) + s.True(opened, "another transfer in the same call is a leg of its own") +} + func (s *StoreSuite) TestALegNotDialledYetRingsForNobody() { s.placedLeg("one", nil) scope := AppScope{} diff --git a/acceleration/internal/store/migrate.go b/acceleration/internal/store/migrate.go index 54fb1eb4e8..b0f09b9395 100644 --- a/acceleration/internal/store/migrate.go +++ b/acceleration/internal/store/migrate.go @@ -223,6 +223,9 @@ var usageIndexes = []struct{ set, name, create string }{ // The legs a join delivered after its call ended revives. {"shard", "call_legs_unanswered_idx", "CREATE INDEX CONCURRENTLY IF NOT EXISTS call_legs_unanswered_idx ON call_legs (call_type, call_id) " + "WHERE direction = 'outbound' AND end_reason = 'unanswered'"}, + // A transfer leg, by its call and the vendor's id for it, which a write tried again hits. + {"shard", "call_legs_transfer_idx", "CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS call_legs_transfer_idx ON call_legs " + + "(call_type, call_id, COALESCE(stream_app_pk, 0), vendor_call_id) WHERE placed_at IS NULL AND vendor_call_id IS NOT NULL"}, // The placed leg a status post is about, by its token's hash, and the legs whose status // url is still open. {"shard", "call_legs_token_hash_key", "CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS call_legs_token_hash_key ON call_legs (token_hash)"}, diff --git a/acceleration/migrations/shard/20270201000320_call_legs_transfer_idx.sql b/acceleration/migrations/shard/20270201000320_call_legs_transfer_idx.sql new file mode 100644 index 0000000000..ab460b9eb4 --- /dev/null +++ b/acceleration/migrations/shard/20270201000320_call_legs_transfer_idx.sql @@ -0,0 +1,23 @@ +-- +goose NO TRANSACTION +-- +goose Up + +-- A leg written with no token is a transfer: known by its call and the vendor's id for the +-- call it placed, so writing it again after a write whose answer was lost (OpenLeg's retry, +-- the leg sweep) writes nothing. Each dial has an id of its own, but legs that share one, as a +-- test vendor's fixed id left, would keep the index from building and the router from +-- starting: every one but the newest forgets the id, which only pressing digits reads. The +-- update locks only those rows. Built without stopping the writes of legs; a build that fails +-- is built again in Go (store.usageIndexes). +UPDATE call_legs AS l SET vendor_call_id = NULL +FROM call_legs AS newer +WHERE l.placed_at IS NULL AND l.vendor_call_id IS NOT NULL + AND newer.placed_at IS NULL AND newer.vendor_call_id = l.vendor_call_id + AND newer.call_type = l.call_type AND newer.call_id = l.call_id + AND COALESCE(newer.stream_app_pk, 0) = COALESCE(l.stream_app_pk, 0) + AND newer.id > l.id; +CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS call_legs_transfer_idx + ON call_legs (call_type, call_id, COALESCE(stream_app_pk, 0), vendor_call_id) + WHERE placed_at IS NULL AND vendor_call_id IS NOT NULL; + +-- +goose Down +DROP INDEX CONCURRENTLY IF EXISTS call_legs_transfer_idx; diff --git a/acceleration/schema/shard.sql b/acceleration/schema/shard.sql index 8817cf453f..740231a910 100644 --- a/acceleration/schema/shard.sql +++ b/acceleration/schema/shard.sql @@ -197,6 +197,7 @@ TABLE call_legs CREATE UNIQUE INDEX call_legs_token_hash_key ON public.call_legs USING btree (token_hash) CREATE INDEX call_legs_token_hash_placed_idx ON public.call_legs USING btree (placed_at) WHERE (token_hash IS NOT NULL) CREATE INDEX call_legs_token_placed_idx ON public.call_legs USING btree (placed_at) WHERE (token IS NOT NULL) + CREATE UNIQUE INDEX call_legs_transfer_idx ON public.call_legs USING btree (call_type, call_id, COALESCE(stream_app_pk, (0)::bigint), vendor_call_id) WHERE ((placed_at IS NULL) AND (vendor_call_id IS NOT NULL)) CREATE INDEX call_legs_unanswered_idx ON public.call_legs USING btree (call_type, call_id) WHERE ((direction = 'outbound'::text) AND (end_reason = 'unanswered'::text)) CREATE INDEX call_legs_vendor_call_idx ON public.call_legs USING btree (vendor_call_id) WHERE (vendor_call_id IS NOT NULL) From 559217bcbad0404481dbca438d4be36d34053f0c Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 21:30:13 +0100 Subject: [PATCH 07/12] fix(phone): write kept legs after the drain, and end them with the call The legs OpenLeg could not write were given up as soon as shutdown began, before the HTTP and session drains, and a leg kept after that was never written nor logged at ERROR. The router now calls StopLegSweep once the drains are over: it writes the kept legs a last time, and from then on a leg that cannot be written is logged at ERROR, not kept. A kept leg whose call ended (session_ended on this router) before the sweep wrote it is now ended at the call's end, rather than left open for MaxCallLength, counted against the organization's concurrent calls and then given away unbilled. Co-Authored-By: Claude Opus 5.5 --- acceleration/cmd/router/main.go | 10 +++ acceleration/internal/phone/legs.go | 88 +++++++++++++------ .../phone/metering_integration_test.go | 48 ++++++++++ 3 files changed, 119 insertions(+), 27 deletions(-) diff --git a/acceleration/cmd/router/main.go b/acceleration/cmd/router/main.go index 6a5ac25aa1..d0690908a8 100644 --- a/acceleration/cmd/router/main.go +++ b/acceleration/cmd/router/main.go @@ -170,6 +170,9 @@ const ( // runs first, and the HTTP drain gets the rest of shutdownGrace, so both fit inside the // orchestrator's termination grace period. phoneHangupGrace = 5 * time.Second + // legFlushTimeout bounds the last write of the call legs the leg sweep still holds, once + // the HTTP and session drains are over: one insert a leg, of at most a few, normally. + legFlushTimeout = 5 * time.Second // usageDrainTimeout is how long the usage writer has to write what is queued once // everything that records has stopped: it starts after the HTTP drain, any session drain // and sessions.Shutdown, and counts none of them. What is still queued after it is lost, @@ -1196,6 +1199,13 @@ func run(settings config.Config, logger *slog.Logger) error { // leg whose row was lost is recorded again. Months of numbers and of 10DLC campaigns are // billed by jobs of their own (router usage numbers, router usage dlc). go telephony.RunLegSweep(ctx, legSweepEvery) + // Deferred here, it runs after the drain and sessions.Shutdown, so the legs a webhook or + // a session still kept get their last write, and before the usage writer closes. + defer func() { + ctx, cancel := context.WithTimeout(context.Background(), legFlushTimeout) + defer cancel() + telephony.StopLegSweep(ctx) + }() go checkCallHook(ctx, settings, logger) startPhoneSweeper(ctx, telephony, logger) } diff --git a/acceleration/internal/phone/legs.go b/acceleration/internal/phone/legs.go index abb55f7e17..cfede0e8f9 100644 --- a/acceleration/internal/phone/legs.go +++ b/acceleration/internal/phone/legs.go @@ -97,7 +97,7 @@ func (s *Service) OpenLeg(ctx context.Context, owner routing.Owner, leg store.Ca pause *= 2 opened, err = s.store.CallLegs.Open(ctx, &leg) } - if err != nil && !opened && openAgain(err) && s.unopened.add(leg) { + if err != nil && !opened && openAgain(err) && s.unopened.add(unopenedLeg{leg: leg}) { s.logger.Warn("could not record a call leg; the leg sweep records it", "call", leg.CallType+":"+leg.CallID, "vendor", leg.Vendor, "direction", leg.Direction, "error", err) return @@ -230,7 +230,9 @@ func (s *Service) EndLegs(ctx context.Context, scope store.AppScope, callType, c if s.store == nil { return nil } - ended, err := s.store.CallLegs.EndCall(ctx, scope, callType, callID, s.eventAt(at)) + at = s.eventAt(at) + s.unopened.end(scope, callType, callID, at) + ended, err := s.store.CallLegs.EndCall(ctx, scope, callType, callID, at) if err != nil { return err } @@ -347,58 +349,90 @@ func (r *recently) forget(key string) { } // unopenedLegs are the legs whose row OpenLeg could not write, kept for the leg sweep, at most -// unopenedMost of them. +// unopenedMost of them, until the sweep writes them a last time (StopLegSweep). type unopenedLegs struct { mu sync.Mutex - legs []store.CallLeg + legs []unopenedLeg + // stopped refuses every leg once the sweep has stopped, so none is kept that nothing writes. + stopped bool +} + +// unopenedLeg is a leg kept for the sweep, and when its call ended, zero until this router +// hears of it (EndLegs). +type unopenedLeg struct { + leg store.CallLeg + ended time.Time } -// add keeps leg, and reports false when unopenedMost are kept already. -func (u *unopenedLegs) add(leg store.CallLeg) bool { +// add keeps a leg, and reports false when unopenedMost are kept already or the sweep stopped. +func (u *unopenedLegs) add(kept unopenedLeg) bool { u.mu.Lock() defer u.mu.Unlock() - if len(u.legs) >= unopenedMost { + if u.stopped || len(u.legs) >= unopenedMost { return false } - u.legs = append(u.legs, leg) + u.legs = append(u.legs, kept) return true } -// take hands over every leg kept. -func (u *unopenedLegs) take() []store.CallLeg { +// end says the call callType:callID of the scope's app ended at at, to the legs kept of it. +func (u *unopenedLegs) end(scope store.AppScope, callType, callID string, at time.Time) { + u.mu.Lock() + defer u.mu.Unlock() + for i, kept := range u.legs { + inScope := (scope.App != 0 && kept.leg.StreamAppPK == scope.App) || (scope.Unpinned && kept.leg.StreamAppPK == 0) + if inScope && kept.leg.CallType == callType && kept.leg.CallID == callID && kept.ended.IsZero() { + u.legs[i].ended = at + } + } +} + +// take hands over every leg kept, and with stop refuses any kept after. +func (u *unopenedLegs) take(stop bool) []unopenedLeg { u.mu.Lock() defer u.mu.Unlock() legs := u.legs u.legs = nil + u.stopped = u.stopped || stop return legs } -// openUnopened writes the row of each leg OpenLeg could not, and follows it as OpenLeg would. A -// write that fails in a way a retry may pass leaves it and those after it for the next sweep. -func (s *Service) openUnopened(ctx context.Context) { - legs := s.unopened.take() - for i := range legs { - leg := legs[i] +// openUnopened writes the row of each leg OpenLeg could not, and follows it as OpenLeg would. +// A leg whose call ended meanwhile ends then, as EndLegs would have ended its row: its phone's +// leave may never come. A write that fails in a way a retry may pass leaves it and those after +// it for the next sweep, or, once the sweep has stopped, logs them. +func (s *Service) openUnopened(ctx context.Context, stop bool) { + kept := s.unopened.take(stop) + for i := range kept { + leg := kept[i].leg opened, err := s.store.CallLegs.Open(ctx, &leg) if err != nil && !opened && openAgain(err) { - for _, left := range legs[i:] { + for _, left := range kept[i:] { if !s.unopened.add(left) { - s.recorded(ctx, left, false, err) + s.recorded(ctx, left.leg, false, err) } } return } s.recorded(ctx, leg, opened, err) + if opened && leg.EndedAt == nil && !kept[i].ended.IsZero() { + scope := store.AppScope{App: leg.StreamAppPK, Unpinned: leg.StreamAppPK == 0} + if err := s.EndLegs(ctx, scope, leg.CallType, leg.CallID, kept[i].ended); err != nil { + s.logger.Error("could not end a call leg written after its call ended; the sweep ends it at the longest a call lasts", + "call", leg.CallType+":"+leg.CallID, "vendor", leg.Vendor, "error", err) + } + } } } -// loseUnopened logs each leg still kept for the sweep when the sweep stops: its minutes are not -// billed. -func (s *Service) loseUnopened() { - for _, leg := range s.unopened.take() { - s.logger.Error("could not record a call leg before the router stopped; its minutes are not billed", - "call", leg.CallType+":"+leg.CallID, "vendor", leg.Vendor, "direction", leg.Direction) +// StopLegSweep writes the legs OpenLeg could not, a last time, and logs at ERROR each it still +// could not, and every leg OpenLeg cannot write from then on: their minutes are not billed. A +// router calls it once what it serves has drained, after RunLegSweep's ctx ended. +func (s *Service) StopLegSweep(ctx context.Context) { + if s.store == nil { + return } + s.openUnopened(ctx, true) } // settleLegs bills the legs that ended whose phone joined. One that never connected was not @@ -508,7 +542,7 @@ func (s *Service) SweepLegs(ctx context.Context) (int, error) { if s.store == nil { return 0, nil } - s.openUnopened(ctx) + s.openUnopened(ctx, false) now := s.now() ended, err := s.store.CallLegs.Sweep(ctx, now, MaxCallLength, legSweepBatch) if err != nil { @@ -566,14 +600,14 @@ func (s *Service) rebill(ctx context.Context, now time.Time) error { return nil } -// RunLegSweep sweeps every interval until ctx ends, and then logs the legs it never wrote. +// RunLegSweep sweeps every interval until ctx ends. The legs it has not written by then get a +// last write from StopLegSweep. func (s *Service) RunLegSweep(ctx context.Context, every time.Duration) { ticker := time.NewTicker(every) defer ticker.Stop() for { select { case <-ctx.Done(): - s.loseUnopened() return case <-ticker.C: if _, err := s.SweepLegs(ctx); err != nil { diff --git a/acceleration/internal/phone/metering_integration_test.go b/acceleration/internal/phone/metering_integration_test.go index e5d7bb8e29..67d5c9672c 100644 --- a/acceleration/internal/phone/metering_integration_test.go +++ b/acceleration/internal/phone/metering_integration_test.go @@ -751,6 +751,54 @@ func (s *MeteringSuite) TestALegThatCouldNotBeWrittenIsWrittenAndBilledByTheSwee "the next sweep writes it no more") } +// A leg written by the sweep after its call ended, its phone's leave never heard, ends when the +// call did: it is billed to then, and no longer counts against the organization's calls. +func (s *MeteringSuite) TestALegWrittenAfterItsCallEndedEndsWithTheCall() { + callID := "call-" + uuid.NewString() + s.failing.fail(`INSERT INTO "call_legs"`, openAttempts) + s.arrived(callID) + s.clock.advance(90 * time.Second) + s.ended(defaultCallType, callID) + s.clock.advance(10 * time.Minute) + + _, err := s.service.SweepLegs(s.ctx) + + s.Require().NoError(err) + s.Empty(s.openLegs()) + minutes := s.row(ModelCallMinutes) + s.Equal(pricing.Quantities{pricing.CallSeconds: 90}, minutes.Meters) + s.True(minutes.Billable) +} + +// The legs the sweep still holds when the router stops get a last write, once the database is +// back, and are billed as the sweep would have. +func (s *MeteringSuite) TestALegKeptWhenTheRouterStopsIsWrittenOnceMore() { + callID := "call-" + uuid.NewString() + s.failing.fail(`INSERT INTO "call_legs"`, openAttempts) + s.arrived(callID) + s.Require().Empty(s.openLegs()) + + s.service.StopLegSweep(s.ctx) + + s.Len(s.openLegs(), 1) + s.Zero(s.logs.count("ERROR", "could not record a call leg")) +} + +// A leg that cannot be written once the sweep has stopped is logged at ERROR, not kept for a +// sweep that will never write it. +func (s *MeteringSuite) TestALegThatCannotBeWrittenAfterTheSweepStoppedIsLogged() { + s.service.StopLegSweep(s.ctx) + callID := "call-" + uuid.NewString() + s.failing.fail(`INSERT INTO "call_legs"`, openAttempts) + + s.arrived(callID) + + s.Equal(1, s.logs.count("ERROR", "could not record a call leg; its minutes are not billed")) + _, err := s.service.SweepLegs(s.ctx) + s.Require().NoError(err) + s.Empty(s.openLegs(), "nothing was kept to write") +} + func (s *MeteringSuite) TestEveryLegOfAnEndedCallCountsTowardTheSandboxsMinutes() { s.withSandbox(dlc.Sandbox{Enabled: true}) s.Require().NoError(s.service.gate.SetRecipients(s.ctx, s.customer, []string{"+15125550123", "+15125550124"})) From 0d383f2a48f96e87a277d19b57bf54e769af2f22 Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 21:52:49 +0100 Subject: [PATCH 08/12] fix(dlc): settle a lost 10DLC answer and keep what was registered A request whose answer was lost blocked the app's 10DLC for good, even when the request never reached Telnyx, and an id the router held when a save failed was dropped unlogged. - A request never written whole (dial, DNS, TLS, context done first) is dlc.ErrNotCarriedOut, as a 4xx is, and its mark is cleared; only the mark of that request is cleared. - A request under 10 minutes old may still be running and is left alone, so it is no longer logged as lost. - A campaign is registered with the use case's id as its referenceId, which Telnyx keeps unique; an older request is settled by finding the campaign under its brand (CampaignFinder): found, it is recorded and billed under its own id; missing, it is asked for again. - Telnyx takes no reference on a brand, so an older brand request moves the use case to vendor_rejected with a note to contact support, which the app may edit or delete, and is not asked for again. - The save after a registration is tried 3 times on a context the caller cannot end; a last failure is logged at ERROR with the id. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/dlc_test.go | 185 +++++++++++++++++- acceleration/internal/dlc/dlc.go | 18 +- acceleration/internal/dlc/service.go | 174 +++++++++++++--- acceleration/internal/dlc/telnyx/telnyx.go | 53 ++++- .../internal/dlc/telnyx/telnyx_test.go | 52 +++++ .../internal/store/business_profile.go | 7 +- .../internal/store/business_profile_test.go | 2 +- acceleration/internal/store/use_case.go | 8 +- acceleration/internal/store/use_case_test.go | 2 +- ...270201000310_dlc_registration_requests.sql | 5 +- 10 files changed, 463 insertions(+), 43 deletions(-) diff --git a/acceleration/internal/api/dlc_test.go b/acceleration/internal/api/dlc_test.go index af68b8e69c..9041bbc838 100644 --- a/acceleration/internal/api/dlc_test.go +++ b/acceleration/internal/api/dlc_test.go @@ -22,6 +22,7 @@ import ( "time" "github.com/google/uuid" + "github.com/uptrace/bun" "github.com/GetStream/Vision-Agents/acceleration/internal/dlc" dlctelnyx "github.com/GetStream/Vision-Agents/acceleration/internal/dlc/telnyx" @@ -42,8 +43,15 @@ type campaignRegistry struct { // and campaignsAsked count the registrations asked for. brandAnswers, campaignAnswers []int brandsAsked, campaignsAsked int + // brands are the ids of the brands registered, and listed the campaigns a list of a + // brand's answers, with the reference each was registered with. + brands []string + listed []listedCampaign } +// listedCampaign is a campaign as a list of its brand's names it. +type listedCampaign struct{ id, brand, reference string } + // campaignRegistryFails is a campaign status no vendor sends: the fake answers a read of a // campaign set to it with a 500. const campaignRegistryFails = "REGISTRY_FAILS" @@ -62,18 +70,29 @@ func (r *campaignRegistry) ServeHTTP(w http.ResponseWriter, request *http.Reques w.WriteHeader(answer) return } - fmt.Fprintf(w, `{"brandId":%q,"status":"OK","identityStatus":"VERIFIED"}`, uuid.NewString()) + r.brands = append(r.brands, uuid.NewString()) + fmt.Fprintf(w, `{"brandId":%q,"status":"OK","identityStatus":"VERIFIED"}`, r.brands[len(r.brands)-1]) case request.Method == http.MethodGet && strings.HasPrefix(path, "/v2/10dlc/brand/"): fmt.Fprintf(w, `{"brandId":%q,"status":"OK","identityStatus":"VERIFIED"}`, strings.TrimPrefix(path, "/v2/10dlc/brand/")) case request.Method == http.MethodPost && path == "/v2/10dlc/campaignBuilder": r.campaignsAsked++ id := uuid.NewString() r.campaigns[id] = "TCR_PENDING" + r.listed = append(r.listed, listedCampaign{id: id, brand: body["brandId"], reference: body["referenceId"]}) if answer := nextAnswer(&r.campaignAnswers); answer != http.StatusOK { w.WriteHeader(answer) return } fmt.Fprintf(w, `{"campaignId":%q,"campaignStatus":"TCR_PENDING"}`, id) + case request.Method == http.MethodGet && path == "/v2/10dlc/campaign": + var records []string + for _, listed := range r.listed { + if listed.brand == request.URL.Query().Get("brandId") { + records = append(records, fmt.Sprintf(`{"campaignId":%q,"campaignStatus":%q,"referenceId":%q}`, + listed.id, r.campaigns[listed.id], listed.reference)) + } + } + fmt.Fprintf(w, `{"records":[%s],"page":1,"totalRecords":%d}`, strings.Join(records, ","), len(records)) case request.Method == http.MethodGet && strings.HasPrefix(path, "/v2/10dlc/campaign/"): id := strings.TrimPrefix(path, "/v2/10dlc/campaign/") if r.campaigns[id] == campaignRegistryFails { @@ -111,6 +130,32 @@ func (r *campaignRegistry) answer(brands, campaigns []int) (int, int) { // asked is how many brand and campaign registrations were asked for so far. func (r *campaignRegistry) asked() (int, int) { return r.answer(nil, nil) } +// campaignFor is the campaign registered with reference, empty when there is none. +func (r *campaignRegistry) campaignFor(reference string) string { + r.mu.Lock() + defer r.mu.Unlock() + for _, listed := range r.listed { + if listed.reference == reference { + return listed.id + } + } + return "" +} + +// lastBrand is the brand registered last. +func (r *campaignRegistry) lastBrand() string { + r.mu.Lock() + defer r.mu.Unlock() + return r.brands[len(r.brands)-1] +} + +// unlist forgets every campaign registered so far, as a registration Telnyx never carried out. +func (r *campaignRegistry) unlist() { + r.mu.Lock() + defer r.mu.Unlock() + r.listed = nil +} + func (r *campaignRegistry) set(campaignID, status string) { r.mu.Lock() defer r.mu.Unlock() @@ -299,7 +344,143 @@ func (s *DLCSuite) TestABrandWhoseRegistrationWasNotAnsweredIsNotRegisteredTwice asked, _ := s.registry.asked() s.Equal(2, asked-brands, "refused, then asked once more") - s.Contains(s.logged.String(), "its answer was not recorded") + s.Empty(s.loggedLines("a 10DLC registration was not answered", s.customerID()), "one that may still be registering is not reported lost") +} + +// A brand whose registration was not answered, and still has no answer once it could no longer +// be running, may be registered and billed at Telnyx, which keeps no reference of ours to find +// it by: the use case is handed back to the app as vendor_rejected, which it may delete, and the +// brand is not asked for again until support has looked it up. +func (s *DLCSuite) TestABrandWhoseAnswerWasLostIsLeftToSupportAndFreesTheUseCase() { + brands, _ := s.registry.answer([]int{http.StatusInternalServerError}, nil) + sent := s.submitted() + status, _ := s.review(sent.Id, dlc.Approve, "") + s.Require().Equal(http.StatusOK, status) + s.backdate("business_profiles", "brand_requested_at", "customer_id", s.customerID()) + + s.Equal(http.StatusNoContent, s.report(`{"brandId":"another"}`, s.signing)) + s.Equal(http.StatusNoContent, s.report(`{"brandId":"another"}`, s.signing)) + + s.Equal(UseCaseStatus(dlc.VendorRejected), s.useCase(sent.Id).Status) + asked, _ := s.registry.asked() + s.Equal(1, asked-brands, "never asked for again") + s.Len(s.loggedLines("a 10DLC registration was not answered", s.customerID()), 1) + s.Equal(http.StatusNoContent, s.serverClient.do(http.MethodDelete, "/v1/phone/use-cases/"+sent.Id, nil, nil)) +} + +// A campaign whose registration was not answered is found at Telnyx by the use case it was +// registered for, and recorded, without asking for a second one. +func (s *DLCSuite) TestACampaignWhoseAnswerWasLostIsFoundAtTheVendor() { + _, campaigns := s.registry.answer(nil, []int{http.StatusInternalServerError}) + sent := s.submitted() + status, reviewed := s.review(sent.Id, dlc.Approve, "") + s.Require().Equal(http.StatusOK, status) + s.Require().Nil(reviewed.VendorCampaignId) + s.backdate("dlc_use_cases", "campaign_requested_at", "id", sent.Id) + + s.Equal(http.StatusNoContent, s.report(`{"brandId":"another"}`, s.signing)) + + found := s.useCase(sent.Id) + s.Require().NotNil(found.VendorCampaignId) + s.Equal(s.registry.campaignFor(sent.Id), *found.VendorCampaignId) + _, asked := s.registry.asked() + s.Equal(1, asked-campaigns) +} + +// A campaign Telnyx does not hold, its registration answered with a failure, was never +// registered: it is asked for again. +func (s *DLCSuite) TestACampaignTheVendorNeverRegisteredIsAskedForAgain() { + _, campaigns := s.registry.answer(nil, []int{http.StatusInternalServerError}) + sent := s.submitted() + status, _ := s.review(sent.Id, dlc.Approve, "") + s.Require().Equal(http.StatusOK, status) + s.registry.unlist() + s.backdate("dlc_use_cases", "campaign_requested_at", "id", sent.Id) + + s.Equal(http.StatusNoContent, s.report(`{"brandId":"another"}`, s.signing)) + s.Equal(http.StatusNoContent, s.report(`{"brandId":"another"}`, s.signing)) + + found := s.useCase(sent.Id) + s.Require().NotNil(found.VendorCampaignId) + s.Equal(s.registry.campaignFor(sent.Id), *found.VendorCampaignId) + _, asked := s.registry.asked() + s.Equal(2, asked-campaigns) +} + +// A brand Telnyx registered whose id the database would not take is logged with its id, so +// support can record it, and is not asked for again. +func (s *DLCSuite) TestABrandRegisteredWhoseIdCouldNotBeSavedIsLoggedWithIt() { + s.failQueries(`SET vendor_brand_id = '`) + sent := s.submitted() + + status, _ := s.review(sent.Id, dlc.Approve, "") + + s.Require().Equal(http.StatusOK, status) + line := s.loggedLine("could not save a brand the vendor registered", s.customerID()) + s.Contains(line, "level=ERROR") + s.Contains(line, "vendor_brand_id="+s.registry.lastBrand()) +} + +// A campaign Telnyx registered whose save the database failed is logged with its id, and found +// at Telnyx by the poller once the database is back. +func (s *DLCSuite) TestACampaignRegisteredWhoseSaveFailedIsFoundAtTheVendorLater() { + _, campaigns := s.registry.asked() + s.failQueries(registeredNote) + sent := s.submitted() + status, _ := s.review(sent.Id, dlc.Approve, "") + s.Require().Equal(http.StatusOK, status) + line := s.loggedLine("could not save a campaign the vendor registered", sent.Id) + s.Contains(line, "level=ERROR") + s.Contains(line, "vendor_campaign_id="+s.registry.campaignFor(sent.Id)) + s.failQueries("no query holds this") + s.backdate("dlc_use_cases", "campaign_requested_at", "id", sent.Id) + + s.Equal(http.StatusNoContent, s.report(`{"brandId":"another"}`, s.signing)) + + found := s.useCase(sent.Id) + s.Require().NotNil(found.VendorCampaignId) + s.Equal(s.registry.campaignFor(sent.Id), *found.VendorCampaignId) + _, asked := s.registry.asked() + s.Equal(1, asked-campaigns) +} + +// registeredNote begins the review entry a campaign's registration writes. +const registeredNote = "Registered as campaign " + +// backdate moves a registration's request time past the time one may still be running, as if +// it had been asked for long ago. +func (s *dlcRegistration) backdate(table, column, key, value string) { + _, err := s.store.GlobalDB().NewUpdate().Table(table). + Set("? = ? - interval '11 minutes'", bun.Ident(column), bun.Ident(column)). + Where("? = ?", bun.Ident(key), value). + Exec(context.Background()) + s.Require().NoError(err) +} + +// loggedLines are the lines logged with message that name about, the suite's tests sharing +// one log. +func (s *dlcRegistration) loggedLines(message, about string) []string { + var found []string + for line := range strings.Lines(s.logged.String()) { + if strings.Contains(line, `msg="`+message) && strings.Contains(line, "="+about+" ") { + found = append(found, line) + } + } + return found +} + +// loggedLine is the one line logged with message that names about. +func (s *dlcRegistration) loggedLine(message, about string) string { + found := s.loggedLines(message, about) + s.Require().Len(found, 1, "one line %q about %s", message, about) + return found[0] +} + +// useCase is one of the app's use cases. +func (s *dlcRegistration) useCase(id string) UseCase { + var found UseCase + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/phone/use-cases/"+id, nil, &found)) + return found } // A campaign whose registration was answered with a failure may be registered, and billed, all diff --git a/acceleration/internal/dlc/dlc.go b/acceleration/internal/dlc/dlc.go index 9b6d2df4ed..68ddb85bc2 100644 --- a/acceleration/internal/dlc/dlc.go +++ b/acceleration/internal/dlc/dlc.go @@ -67,9 +67,10 @@ var ErrLocked = errors.New("dlc: the use case cannot do that in its status") // ErrRefused is a text or call the gate would not let through. var ErrRefused = errors.New("dlc: refused") -// ErrVendorRefused is a vendor answering that it refused a request, and so did not carry it -// out: a registration it refused registered nothing, and may be asked for again. -var ErrVendorRefused = errors.New("dlc: the vendor refused") +// ErrNotCarriedOut is a request the vendor did not carry out: it answered refusing it, or the +// request never reached it. A registration so failed registered nothing, and may be asked for +// again. +var ErrNotCarriedOut = errors.New("dlc: the vendor did not carry out the request") // ErrUnpaid is a text, call or number refused because the organization may not pay for it. // The refusal it wraps says why: suspended, out of credit, or past a spend limit. @@ -92,7 +93,8 @@ type Registrar interface { Name() string RegisterBrand(ctx context.Context, profile store.BusinessProfile) (Brand, error) Brand(ctx context.Context, brandID string) (Brand, error) - // RegisterCampaign registers a use case under a brand, reporting on hookURL. + // RegisterCampaign registers a use case under a brand, reporting on hookURL, with the use + // case's id as its reference where the vendor keeps one (CampaignFinder). RegisterCampaign(ctx context.Context, brandID string, useCase store.UseCase, hookURL string) (Campaign, error) Campaign(ctx context.Context, campaignID string) (Campaign, error) // AssignNumber makes a number send as a campaign. @@ -103,6 +105,14 @@ type Registrar interface { HookSubject(body []byte) (campaignID, brandID string) } +// CampaignFinder is a registrar that can find a campaign by the reference RegisterCampaign +// registered it with, the use case's id, which settles a registration whose answer was lost. +type CampaignFinder interface { + // FindCampaign returns the campaign registered under brandID with reference, and false + // when the vendor holds none. + FindCampaign(ctx context.Context, brandID, reference string) (Campaign, bool, error) +} + // Outcome is where a vendor's word for a brand or campaign leaves it. type Outcome int diff --git a/acceleration/internal/dlc/service.go b/acceleration/internal/dlc/service.go index a27b1ac1b7..2da69b6e79 100644 --- a/acceleration/internal/dlc/service.go +++ b/acceleration/internal/dlc/service.go @@ -407,15 +407,24 @@ func (s *Service) refresh(ctx context.Context, useCase store.UseCase, report []b return nil } -// errUnanswered is a brand or campaign the vendor was asked to register, with no answer -// recorded: it may be registered, and billed, at the vendor, and the vendor takes no key that -// would make asking again safe. An operator looks it up there, and records its id or forgets -// the request. -var errUnanswered = errors.New("dlc: the vendor was asked to register this before and its answer was not recorded") +// requestSettles is how long a registration asked for may still be running, on this router +// or another: far longer than the registrar's timeout, so one asked for longer ago had its +// answer lost. +const requestSettles = 10 * time.Minute + +// saveAttempts and saveFirstPause bound how often what the vendor answered to a registration +// is saved: the first save and two more, 100 ms and then 200 ms after the one before, for a +// dropped connection or a failover. The vendor has registered it, and billed it, by then, so +// the save is what is tried again, never the registration. +const ( + saveAttempts = 3 + saveFirstPause = 100 * time.Millisecond +) // register registers the app's brand if it has none, and the campaign once the brand is // verified. A brand the vendor refused leaves nothing to register the campaign under. Each is -// asked for once (requested): only a refusal lets it be asked for again. +// asked for once (requested): only a request the vendor did not carry out is asked for again, +// and one whose answer was lost is settled (brandUnanswered, campaignUnanswered). func (s *Service) register(ctx context.Context, useCase store.UseCase) error { profile, err := s.store.BusinessProfiles.Get(ctx, useCase.CustomerID) if err != nil { @@ -427,16 +436,21 @@ func (s *Service) register(ctx context.Context, useCase store.UseCase) error { if err != nil { return err } - if err := requested(s.store.BusinessProfiles.RequestBrand(ctx, useCase.CustomerID, s.now())); err != nil { + requestedAt := s.now().UTC().Truncate(time.Microsecond) + requested, err := s.store.BusinessProfiles.RequestBrand(ctx, useCase.CustomerID, requestedAt) + if err != nil || !requested { booked.Release() - return fmt.Errorf("%w: the brand of %s", err, useCase.CustomerID) + if err != nil { + return err + } + return s.brandUnanswered(ctx, useCase, profile) } brand, err = routing.Call(ctx, s.feeMeter(ctx, ModelBrand, useCase.CustomerID, nil), func(ctx context.Context) (Brand, error) { return s.registrar.RegisterBrand(ctx, profile) }) if err != nil { booked.Release() - if errors.Is(err, ErrVendorRefused) { - err = errors.Join(err, s.store.BusinessProfiles.ForgetBrandRequest(ctx, useCase.CustomerID)) + if errors.Is(err, ErrNotCarriedOut) { + err = errors.Join(err, s.store.BusinessProfiles.ForgetBrandRequest(ctx, useCase.CustomerID, requestedAt)) } return err } @@ -448,59 +462,167 @@ func (s *Service) register(ctx context.Context, useCase store.UseCase) error { return err } if brand.ID != profile.VendorBrandID || brand.Status != profile.BrandStatus { - if err := s.store.BusinessProfiles.SetBrand(ctx, useCase.CustomerID, brand.ID, brand.Status); err != nil { + err := saved(ctx, func(ctx context.Context) error { + return s.store.BusinessProfiles.SetBrand(ctx, useCase.CustomerID, brand.ID, brand.Status) + }) + if err != nil && profile.VendorBrandID == "" { + // Its request stays, so it is never registered again; support records the id. + s.logger.Error("could not save a brand the vendor registered; record its id on the app's business profile", + "customer", useCase.CustomerID, "vendor", s.registrar.Name(), "vendor_brand_id", brand.ID, "error", err) + return nil + } + if err != nil { return err } } - log := &store.ReviewLog{Actor: ActorVendor, ActorName: s.registrar.Name()} switch brand.Outcome { case Pending: return nil case Failed: useCase.Status, useCase.VendorStatus = VendorRejected, brand.Status - log.Notes, log.VendorPayload = "The vendor refused the brand: "+brand.Status+".", brand.Raw + log := &store.ReviewLog{Actor: ActorVendor, ActorName: s.registrar.Name(), + Notes: "The vendor refused the brand: " + brand.Status + ".", VendorPayload: brand.Raw} return s.store.UseCases.Move(ctx, &useCase, VendorPending, log) } booked, err := s.book(ctx, useCase.CustomerID, s.campaignFees(ctx, useCase)) if err != nil { return err } - if err := requested(s.store.UseCases.RequestCampaign(ctx, useCase.ID, s.now())); err != nil { + requestedAt := s.now().UTC().Truncate(time.Microsecond) + requested, err := s.store.UseCases.RequestCampaign(ctx, useCase.ID, requestedAt) + if err != nil || !requested { booked.Release() - return fmt.Errorf("%w: the campaign of use case %s", err, useCase.ID) + if err != nil { + return err + } + return s.campaignUnanswered(ctx, useCase, brand.ID) } - campaign, err := routing.Call(ctx, s.feeMeter(ctx, ModelCampaign, useCase.CustomerID, - map[string]string{AttributeUseCaseType: useCaseType(useCase)}), + campaign, err := routing.Call(ctx, s.feeMeter(ctx, ModelCampaign, useCase.CustomerID, campaignAttributes(useCase)), func(ctx context.Context) (Campaign, error) { return s.registrar.RegisterCampaign(ctx, brand.ID, useCase, s.hookURL) }) if err != nil { booked.Release() - if errors.Is(err, ErrVendorRefused) { - err = errors.Join(err, s.store.UseCases.ForgetCampaignRequest(ctx, useCase.ID)) + if errors.Is(err, ErrNotCarriedOut) { + err = errors.Join(err, s.store.UseCases.ForgetCampaignRequest(ctx, useCase.ID, requestedAt)) } return err } defer booked.Charged() + return s.registered(ctx, useCase, campaign, requestedAt) +} + +// registered records the campaign the vendor registered for a use case, asked for at +// requestedAt, and bills the months the registrar charged for it then. A save that does not +// land is logged with the campaign's id, and the use case's request stays: campaignUnanswered +// finds the campaign at the vendor later. +func (s *Service) registered(ctx context.Context, useCase store.UseCase, campaign Campaign, requestedAt time.Time) error { useCase.VendorCampaignID, useCase.VendorStatus = campaign.ID, campaign.Status if useCase.Vendor == "" { useCase.Vendor = s.registrar.Name() } // A registrar charges a campaign's first months when it registers it. - s.billUpfront(useCase, s.now().UTC()) - log.Notes, log.VendorPayload = registeredNote+campaign.ID+".", campaign.Raw - return s.store.UseCases.Move(ctx, &useCase, VendorPending, log) + s.billUpfront(useCase, requestedAt) + err := saved(ctx, func(ctx context.Context) error { + log := &store.ReviewLog{Actor: ActorVendor, ActorName: s.registrar.Name(), + Notes: registeredNote + campaign.ID + ".", VendorPayload: campaign.Raw} + return s.store.UseCases.Move(ctx, &useCase, VendorPending, log) + }) + if err != nil && !errors.Is(err, store.ErrUseCaseMoved) { + s.logger.Error("could not save a campaign the vendor registered; the poller finds it at the vendor", + "use_case", useCase.ID, "vendor", s.registrar.Name(), "vendor_campaign_id", campaign.ID, "error", err) + return nil + } + return err +} + +// brandUnanswered settles the app's brand asked for before, with no answer recorded. One asked +// for less than requestSettles ago may still be registering and is left to it. The vendor +// keeps no reference of the caller's on a brand, so one whose answer was lost cannot be found +// there for sure: it is unanswered. +func (s *Service) brandUnanswered(ctx context.Context, useCase store.UseCase, profile store.BusinessProfile) error { + requestedAt := profile.BrandRequestedAt + if requestedAt == nil || s.now().Sub(*requestedAt) < requestSettles { + return nil + } + return s.unanswered(ctx, useCase, "brand", *requestedAt) } -// requested is a request's outcome as an error: errUnanswered for one asked for before. -func requested(requested bool, err error) error { - if err == nil && !requested { - return stack.Wrap(errUnanswered) +// campaignUnanswered settles a use case's campaign asked for before, with no answer recorded. +// One asked for less than requestSettles ago may still be registering and is left to it. +// Otherwise the vendor is asked for it by the use case's id (CampaignFinder): one it holds is +// recorded and billed as its answer would have been, under its own id, so nothing billed +// already is billed again; one it does not hold was never registered, so the request is +// forgotten and the next poll asks for it again. A registrar that cannot be asked leaves it +// unanswered. +func (s *Service) campaignUnanswered(ctx context.Context, useCase store.UseCase, brandID string) error { + requestedAt := useCase.CampaignRequestedAt + if requestedAt == nil || s.now().Sub(*requestedAt) < requestSettles { + return nil + } + finder, ok := s.registrar.(CampaignFinder) + if !ok { + return s.unanswered(ctx, useCase, "campaign", *requestedAt) + } + campaign, found, err := finder.FindCampaign(ctx, brandID, useCase.ID) + if err != nil { + return err + } + if !found { + return s.store.UseCases.ForgetCampaignRequest(ctx, useCase.ID, *requestedAt) + } + if err := routing.Settle(s.feeMeter(ctx, ModelCampaign, useCase.CustomerID, campaignAttributes(useCase)), campaign); err != nil { + s.logger.Error("could not bill a 10DLC fee", "model", ModelCampaign, "error", err) + } + s.logger.Warn("recorded a campaign the vendor registered whose answer was lost", "use_case", useCase.ID, + "vendor", s.registrar.Name(), "vendor_campaign_id", campaign.ID) + return s.registered(ctx, useCase, campaign, *requestedAt) +} + +// unanswered hands a use case whose brand or campaign registration was not answered to the app +// and to support: it moves to vendor_rejected, which the app may edit and delete, with a note +// saying why. The request stays, so nothing is registered, and billed, again until support has +// looked it up at the vendor, then recorded its id or forgotten the request. +func (s *Service) unanswered(ctx context.Context, useCase store.UseCase, registration string, requestedAt time.Time) error { + useCase.Status = VendorRejected + log := &store.ReviewLog{Actor: ActorVendor, ActorName: s.registrar.Name(), + Notes: "The vendor did not answer when it was asked to register the " + registration + + ", so it may hold it. Contact support: it is not asked for again until they have looked it up."} + err := s.store.UseCases.Move(ctx, &useCase, VendorPending, log) + if errors.Is(err, store.ErrUseCaseMoved) { + // Another router's poll moved it first. + return nil + } + if err != nil { + return err + } + s.logger.Error("a 10DLC registration was not answered; look it up at the vendor, then record its id or forget its request", + "use_case", useCase.ID, "customer", useCase.CustomerID, "vendor", s.registrar.Name(), "registration", registration, + "requested_at", requestedAt) + return nil +} + +// saved runs save on a context a caller that went away does not end, until it lands or +// saveAttempts ran, while its failure is one a retry may fix: not a row the store or Postgres +// refused, nor a use case that moved meanwhile. +func saved(ctx context.Context, save func(context.Context) error) error { + ctx = context.WithoutCancel(ctx) + err := save(ctx) + pause := saveFirstPause + for attempt := 1; attempt < saveAttempts && err != nil && !store.Unwritable(err) && !errors.Is(err, store.ErrUseCaseMoved); attempt++ { + time.Sleep(pause) + pause *= 2 + err = save(ctx) } return err } +// campaignAttributes are what a use case's campaign fee is priced by. +func campaignAttributes(useCase store.UseCase) map[string]string { + return map[string]string{AttributeUseCaseType: useCaseType(useCase)} +} + // assignAtVendor tells the vendor which of its numbers send as the campaign. A number from // another vendor is not the registrar's to assign. func (s *Service) assignAtVendor(ctx context.Context, useCase store.UseCase) error { diff --git a/acceleration/internal/dlc/telnyx/telnyx.go b/acceleration/internal/dlc/telnyx/telnyx.go index 42b691e462..93f824ff36 100644 --- a/acceleration/internal/dlc/telnyx/telnyx.go +++ b/acceleration/internal/dlc/telnyx/telnyx.go @@ -15,10 +15,13 @@ import ( "fmt" "io" "net/http" + "net/http/httptrace" + "net/url" "os" "slices" "strconv" "strings" + "sync/atomic" "time" "github.com/GetStream/Vision-Agents/acceleration/internal/dlc" @@ -188,6 +191,8 @@ func (r *Registrar) RegisterCampaign(ctx context.Context, brandID string, useCas "helpKeywords": "HELP", "optinKeywords": "START", "autoRenewal": true, + // Telnyx refuses a second campaign with the same reference, and FindCampaign finds it. + "referenceId": useCase.ID, } if hookURL != "" { request["webhookURL"] = hookURL @@ -213,6 +218,39 @@ func (r *Registrar) Campaign(ctx context.Context, campaignID string) (dlc.Campai return campaignOf(answered, raw), nil } +// campaignsPerPage is the most campaigns Telnyx lists on a page. +const campaignsPerPage = 500 + +// FindCampaign finds the campaign registered under a brand with reference as its referenceId, +// which RegisterCampaign sets to the use case's id. +func (r *Registrar) FindCampaign(ctx context.Context, brandID, reference string) (dlc.Campaign, bool, error) { + for page := 1; ; page++ { + var listed struct { + Records []json.RawMessage `json:"records"` + TotalRecords int `json:"totalRecords"` + } + query := url.Values{"brandId": {brandID}, "page": {strconv.Itoa(page)}, "recordsPerPage": {strconv.Itoa(campaignsPerPage)}} + if _, err := r.do(ctx, http.MethodGet, "/v2/10dlc/campaign?"+query.Encode(), nil, &listed); err != nil { + return dlc.Campaign{}, false, err + } + for _, raw := range listed.Records { + var record struct { + campaign + ReferenceID string `json:"referenceId"` + } + if err := json.Unmarshal(raw, &record); err != nil { + return dlc.Campaign{}, false, stack.Wrap(fmt.Errorf("telnyx: decode a campaign of brand %s: %w", brandID, err)) + } + if record.ReferenceID == reference { + return campaignOf(record.campaign, raw), true, nil + } + } + if len(listed.Records) == 0 || page*campaignsPerPage >= listed.TotalRecords { + return dlc.Campaign{}, false, nil + } + } +} + // campaignOf reads a campaign's outcome: usable once carriers provisioned it, failed when // any step on the way refused it or it lapsed. func campaignOf(answered campaign, raw []byte) dlc.Campaign { @@ -287,8 +325,21 @@ func (r *Registrar) do(ctx context.Context, method, path string, body, into any) request.Header.Set("Content-Type", "application/json") } + var written atomic.Bool + request = request.WithContext(httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{ + WroteRequest: func(wrote httptrace.WroteRequestInfo) { + if wrote.Err == nil { + written.Store(true) + } + }, + })) response, err := r.client.Do(request) if err != nil { + // A request never written whole, its dial, lookup or handshake failed or its context + // ended first, never reached Telnyx, which did nothing. + if !written.Load() { + err = fmt.Errorf("%w: %w", dlc.ErrNotCarriedOut, err) + } return nil, stack.Wrap(fmt.Errorf("telnyx: %s: %w", path, err)) } defer response.Body.Close() @@ -297,7 +348,7 @@ func (r *Registrar) do(ctx context.Context, method, path string, body, into any) err := fmt.Errorf("telnyx: %s: %s: %s", path, response.Status, strings.TrimSpace(string(detail))) // A 4xx is Telnyx refusing the request; a 5xx may follow work it did. if response.StatusCode < http.StatusInternalServerError { - err = fmt.Errorf("%w: %w", dlc.ErrVendorRefused, err) + err = fmt.Errorf("%w: %w", dlc.ErrNotCarriedOut, err) } return nil, stack.Wrap(err) } diff --git a/acceleration/internal/dlc/telnyx/telnyx_test.go b/acceleration/internal/dlc/telnyx/telnyx_test.go index 4f153ec84f..c5e80f8149 100644 --- a/acceleration/internal/dlc/telnyx/telnyx_test.go +++ b/acceleration/internal/dlc/telnyx/telnyx_test.go @@ -28,6 +28,8 @@ type fakeTelnyx struct { campaigns map[string]string bodies map[string]map[string]any assigned []string + // listed is what a list of a brand's campaigns answers, and listedFor the brand asked for. + listed, listedFor string } func (f *fakeTelnyx) ServeHTTP(w http.ResponseWriter, r *http.Request) { @@ -47,6 +49,9 @@ func (f *fakeTelnyx) ServeHTTP(w http.ResponseWriter, r *http.Request) { case r.Method == http.MethodPost && r.URL.Path == "/v2/10dlc/campaignBuilder": f.campaigns["C1"] = "TCR_PENDING" _, _ = io.WriteString(w, `{"campaignId":"C1","campaignStatus":"TCR_PENDING"}`) + case r.Method == http.MethodGet && r.URL.Path == "/v2/10dlc/campaign": + f.listedFor = r.URL.Query().Get("brandId") + _, _ = io.WriteString(w, f.listed) case r.Method == http.MethodGet && r.URL.Path == "/v2/10dlc/campaign/C1": _, _ = io.WriteString(w, `{"campaignId":"C1","campaignStatus":"`+f.campaigns["C1"]+`"}`) case r.Method == http.MethodPost && r.URL.Path == "/v2/10dlc/phone_number_campaigns": @@ -108,6 +113,53 @@ func (s *TelnyxSuite) TestAVerifiedBrandIsReadyForACampaign() { s.Equal("TECHNOLOGY", sent["vertical"]) } +// A request that never reached Telnyx, its dial refused, was not carried out and may be asked +// for again; one Telnyx read and never answered may have been. +func (s *TelnyxSuite) TestOnlyARequestThatNeverReachedTelnyxIsNotCarriedOut() { + closed := httptest.NewServer(http.NotFoundHandler()) + closed.Close() + unreachable, err := New(Options{APIKey: "key", BaseURL: closed.URL}) + s.Require().NoError(err) + + _, err = unreachable.RegisterBrand(s.ctx, store.BusinessProfile{LegalBusinessName: "Acme Inc"}) + s.ErrorIs(err, dlc.ErrNotCarriedOut) + + silent := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.ReadAll(r.Body) + if connection, _, err := http.NewResponseController(w).Hijack(); err == nil { + _ = connection.Close() + } + })) + s.T().Cleanup(silent.Close) + unanswered, err := New(Options{APIKey: "key", BaseURL: silent.URL}) + s.Require().NoError(err) + + _, err = unanswered.RegisterBrand(s.ctx, store.BusinessProfile{LegalBusinessName: "Acme Inc"}) + s.Require().Error(err) + s.NotErrorIs(err, dlc.ErrNotCarriedOut, "Telnyx had the whole request") +} + +// A campaign is registered with its use case's id as its reference, and found under its brand +// by it. +func (s *TelnyxSuite) TestACampaignIsFoundByTheUseCaseItWasRegisteredFor() { + _, err := s.registrar.RegisterCampaign(s.ctx, "B1", store.UseCase{ID: "use-case-2"}, "") + s.Require().NoError(err) + s.Equal("use-case-2", s.fake.bodies["POST /v2/10dlc/campaignBuilder"]["referenceId"]) + s.fake.listed = `{"records":[{"campaignId":"C0","campaignStatus":"ACTIVE","referenceId":"use-case-1"},` + + `{"campaignId":"C1","campaignStatus":"TCR_PENDING","referenceId":"use-case-2"}],"page":1,"totalRecords":2}` + + campaign, found, err := s.registrar.FindCampaign(s.ctx, "B1", "use-case-2") + + s.Require().NoError(err) + s.True(found) + s.Equal("C1", campaign.ID) + s.Equal("TCR_PENDING", campaign.Status) + s.Equal("B1", s.fake.listedFor) + _, found, err = s.registrar.FindCampaign(s.ctx, "B1", "use-case-3") + s.Require().NoError(err) + s.False(found) +} + func (s *TelnyxSuite) TestACampaignIsOnlyApprovedOnceCarriersProvisionedIt() { built, err := s.registrar.RegisterCampaign(s.ctx, "B1", store.UseCase{ UseCaseType: "CUSTOMER_CARE", MessageSamples: []string{"one", "two"}, diff --git a/acceleration/internal/store/business_profile.go b/acceleration/internal/store/business_profile.go index b988080dc2..0048139b2d 100644 --- a/acceleration/internal/store/business_profile.go +++ b/acceleration/internal/store/business_profile.go @@ -179,13 +179,14 @@ func (r *BusinessProfiles) RequestBrand(ctx context.Context, customerID string, return requested == 1, nil } -// ForgetBrandRequest forgets a brand request the vendor refused, so the brand may be asked for -// again. -func (r *BusinessProfiles) ForgetBrandRequest(ctx context.Context, customerID string) error { +// ForgetBrandRequest forgets the brand request made at at, which the vendor did not carry out, +// so the brand may be asked for again. A request made since is another's, and is kept. +func (r *BusinessProfiles) ForgetBrandRequest(ctx context.Context, customerID string, at time.Time) error { _, err := r.store.global.NewUpdate().Model((*BusinessProfile)(nil)). Set("brand_requested_at = NULL"). Where("customer_id = ?", customerID). Where("vendor_brand_id = ''"). + Where("brand_requested_at = ?", at.UTC()). Exec(ctx) if err != nil { return stack.Wrap(fmt.Errorf("store: forget brand request: %w", err)) diff --git a/acceleration/internal/store/business_profile_test.go b/acceleration/internal/store/business_profile_test.go index 668589d903..e35ee1d0e0 100644 --- a/acceleration/internal/store/business_profile_test.go +++ b/acceleration/internal/store/business_profile_test.go @@ -28,7 +28,7 @@ func (s *StoreSuite) TestBusinessProfileQueryBudgets() { s.Require().NoError(err) s.True(requested) }), "RequestBrand") - s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.BusinessProfiles.ForgetBrandRequest(s.ctx, customerID)) }), + s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.BusinessProfiles.ForgetBrandRequest(s.ctx, customerID, s.base)) }), "ForgetBrandRequest") s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.BusinessProfiles.SetBrand(s.ctx, customerID, "brand-1", "VERIFIED")) diff --git a/acceleration/internal/store/use_case.go b/acceleration/internal/store/use_case.go index c090025bd9..ddd4810a09 100644 --- a/acceleration/internal/store/use_case.go +++ b/acceleration/internal/store/use_case.go @@ -447,13 +447,15 @@ func (r *UseCases) RequestCampaign(ctx context.Context, id string, at time.Time) return requested == 1, nil } -// ForgetCampaignRequest forgets a campaign request the vendor refused, so the campaign may be -// asked for again. -func (r *UseCases) ForgetCampaignRequest(ctx context.Context, id string) error { +// ForgetCampaignRequest forgets the campaign request made at at, which the vendor did not carry +// out or does not hold, so the campaign may be asked for again. A request made since is +// another's, and is kept. +func (r *UseCases) ForgetCampaignRequest(ctx context.Context, id string, at time.Time) error { _, err := r.store.global.NewUpdate().Model((*UseCase)(nil)). Set("campaign_requested_at = NULL"). Where("id = ?", id). Where("vendor_campaign_id = ''"). + Where("campaign_requested_at = ?", at.UTC()). Exec(ctx) if err != nil { return stack.Wrap(fmt.Errorf("store: forget campaign request: %w", err)) diff --git a/acceleration/internal/store/use_case_test.go b/acceleration/internal/store/use_case_test.go index 9d083d4585..0fad6804d5 100644 --- a/acceleration/internal/store/use_case_test.go +++ b/acceleration/internal/store/use_case_test.go @@ -165,7 +165,7 @@ func (s *StoreSuite) TestUseCaseQueryBudgets() { s.Require().NoError(err) s.True(requested) }), "RequestCampaign") - s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.UseCases.ForgetCampaignRequest(s.ctx, useCase.ID)) }), + s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.UseCases.ForgetCampaignRequest(s.ctx, useCase.ID, s.base)) }), "ForgetCampaignRequest") useCase.Status, useCase.Vendor, useCase.VendorCampaignID = "submitted", "telnyx", "campaign-"+useCase.ID s.Equal(2+2, s.countQueries(func() { diff --git a/acceleration/migrations/global/20270201000310_dlc_registration_requests.sql b/acceleration/migrations/global/20270201000310_dlc_registration_requests.sql index e81e2bcaff..5c79ae5280 100644 --- a/acceleration/migrations/global/20270201000310_dlc_registration_requests.sql +++ b/acceleration/migrations/global/20270201000310_dlc_registration_requests.sql @@ -2,8 +2,9 @@ SET LOCAL lock_timeout = '5s'; -- When the vendor was asked to register an app's brand, and a use case's campaign, written --- before it is asked. One with no brand or campaign id recorded is a registration whose answer --- was lost: the vendor may hold it, and have billed it, so it is not asked again. +-- before it is asked. One with no brand or campaign id recorded is a registration still running +-- or whose answer was lost: the vendor may hold it, and have billed it, so it is not asked +-- again until it is found, or found missing, at the vendor. ALTER TABLE business_profiles ADD COLUMN IF NOT EXISTS brand_requested_at TIMESTAMPTZ; ALTER TABLE dlc_use_cases ADD COLUMN IF NOT EXISTS campaign_requested_at TIMESTAMPTZ; From 5f9cb26b8b48ba0d02324b5168411635d21da86c Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 21:52:49 +0100 Subject: [PATCH 09/12] fix(connectors): save a renewal whose saves failed on its next use A refresh whose 3 saves all failed dropped the renewed tokens, so a Postgres failure longer than ~300 ms cost the person a reconnect when the provider had rotated the refresh token. The resolver now holds such a renewal in memory, one per connection and at most 1000, when the last error is one a retry may fix. The next Resolve of that connection on the same router saves it, while the row is still as the checkpoint left it, writes the refresh's audit row, and resolves as usual. A reconnect or revocation that came first leaves it forgotten; a process that stops loses it, as before. Co-Authored-By: Claude Opus 5.5 --- .../internal/connectors/resolver/AGENTS.md | 2 +- .../internal/connectors/resolver/resolver.go | 99 ++++++++++++++++--- .../internal/connectors/resolver/save_test.go | 28 ++++++ 3 files changed, 114 insertions(+), 15 deletions(-) diff --git a/acceleration/internal/connectors/resolver/AGENTS.md b/acceleration/internal/connectors/resolver/AGENTS.md index 6e83177b32..fbcde9e76f 100644 --- a/acceleration/internal/connectors/resolver/AGENTS.md +++ b/acceleration/internal/connectors/resolver/AGENTS.md @@ -65,7 +65,7 @@ Revoke(ref, why, endedAt) why is revoked, uninstalled or rotated, else r - **Retrieve runs detached from the caller.** A caller whose ctx ends during a refresh gets ctx's error at once. The refresh finishes, is committed, and the connection stays `connected` with the rotated credentials, never `needs_reauthorization`. Check: `go test -tags integration -run TestResolverSuite/TestCancellingTheCaller ./internal/connectors/resolver`. - **The checkpoint is committed before the refresh token leaves**, and a lost answer is never followed by the same token. Check: `go test -tags integration -run 'TestResolverSuite/(TestNeedsReauthorizationIsCommitted|TestALostRefresh)' ./internal/connectors/resolver`, and the scheme side: `go test -run 'TestOAuth2CodeSuite/(TestARefreshCheckpoints|TestARefreshWhoseCheckpoint|TestAccessCredentialThatIsNotDueNever)' ./internal/connectors/schemes/oauth2code`. -- **A renewal's save that fails after its checkpoint is tried again.** Until it lands, the connection says `needs_reauthorization` and the tokens the provider may have rotated are only in memory. `saveAgain` saves the same state again, up to `saveAttempts` (3) saves with pauses from `saveFirstPause` (100 ms, then 200 ms), on the refresh's detached context. Each try is a new `CredentialStore.Update`, so it holds the lock again: the lock is the pool connection's session, and the pg driver closes that connection on every failure but a Postgres `ERROR` (`isBadConn` in `pgdriver` v1.2.18), so after a dropped connection no retry on it can work. What bounds the tries is `retrieveTimeout` (30 s from the refresh's lock), which ends the detached context; each try has its own dial, lock, read, save and unlock timeouts, so no fixed sum does. The caller is not held: `Resolve` returns when its ctx ends. Between two tries the lock is free and the row says `needs_reauthorization`, so a `Resolve` on any router gets `ErrNotConnected` (a session reports it as `customer_auth`, `session/dispatcher.go`), where during the refresh it waits on the lock. A `Revoke` between two tries writes its `last_error` on the checkpoint's row, so the next try finds the connection moved and the revocation stands. A try writes only while the row is still as the checkpoint left it: a reconnect, new credentials or a delete that came first stay. A save that landed with its answer lost is found done. `store.ErrConnectorConnectionChanged`, `store.ErrNoConnectorConnection` and what `store.Unwritable` names are not tried again. When it gives up it logs one error line with the connection id and the number of saves, and the connection keeps the checkpoint's `needs_reauthorization`. A save no checkpoint went before is not tried again: the row still holds what it held. Example: router A renews Alice's token, which rotates it; its save hits a dropped connection; 100 ms later A saves again on a new connection, and Alice's connection reads `connected` with the new refresh token. Check: `go test -tags integration -run TestResolverSuite -testify.m 'TestARefreshWhose|TestASave|TestARetried|TestAFailedSave' ./internal/connectors/resolver`. +- **A renewal's save that fails after its checkpoint is tried again.** Until it lands, the connection says `needs_reauthorization` and the tokens the provider may have rotated are only in memory. `saveAgain` saves the same state again, up to `saveAttempts` (3) saves with pauses from `saveFirstPause` (100 ms, then 200 ms), on the refresh's detached context. Each try is a new `CredentialStore.Update`, so it holds the lock again: the lock is the pool connection's session, and the pg driver closes that connection on every failure but a Postgres `ERROR` (`isBadConn` in `pgdriver` v1.2.18), so after a dropped connection no retry on it can work. What bounds the tries is `retrieveTimeout` (30 s from the refresh's lock), which ends the detached context; each try has its own dial, lock, read, save and unlock timeouts, so no fixed sum does. The caller is not held: `Resolve` returns when its ctx ends. Between two tries the lock is free and the row says `needs_reauthorization`, so a `Resolve` on any router gets `ErrNotConnected` (a session reports it as `customer_auth`, `session/dispatcher.go`), where during the refresh it waits on the lock. A `Revoke` between two tries writes its `last_error` on the checkpoint's row, so the next try finds the connection moved and the revocation stands. A try writes only while the row is still as the checkpoint left it: a reconnect, new credentials or a delete that came first stay. A save that landed with its answer lost is found done. `store.ErrConnectorConnectionChanged`, `store.ErrNoConnectorConnection` and what `store.Unwritable` names are not tried again. When it gives up it logs one error line with the connection id and the number of saves, and the connection keeps the checkpoint's `needs_reauthorization`. A renewal it gave up on with an error a retry can fix is held in the resolver's memory, one per connection and at most `unsavedMost` (1000), and the next `Resolve` of that connection on the same router saves it (`saveUnsaved`) and writes its audit row before resolving; on any other router, and after a process stops, the connection still needs a reconnect. A save no checkpoint went before is not tried again: the row still holds what it held. Example: router A renews Alice's token, which rotates it; its save hits a dropped connection; 100 ms later A saves again on a new connection, and Alice's connection reads `connected` with the new refresh token. Check: `go test -tags integration -run TestResolverSuite -testify.m 'TestARefreshWhose|TestASave|TestARetried|TestAFailedSave' ./internal/connectors/resolver`. - **One refresh across routers.** Check: `go test -tags integration -run TestResolverSuite/TestRoutersResolving ./internal/connectors/resolver`. - **A deleted connection does not resolve, even from the cache.** Check: `go test -tags integration -run 'TestResolverSuite/(TestADeleted|TestAnotherCustomers)' ./internal/connectors/resolver`. - **The cache is keyed by revision.** Check: `go test -tags integration -run TestResolverSuite/TestAReconnect ./internal/connectors/resolver`. diff --git a/acceleration/internal/connectors/resolver/resolver.go b/acceleration/internal/connectors/resolver/resolver.go index 3d1e6c8eb5..1b8a2ea21f 100644 --- a/acceleration/internal/connectors/resolver/resolver.go +++ b/acceleration/internal/connectors/resolver/resolver.go @@ -62,6 +62,11 @@ const ( saveFirstPause = 100 * time.Millisecond ) +// unsavedMost bounds the renewals a router holds in memory once their saves all failed (held), +// one a connection, each saved on its connection's next Resolve here. One past it is lost, and +// so is every one held when the process stops: its connection then needs a reconnect. +const unsavedMost = 1000 + // What LastError says after each outcome. core.CredentialState.LastError is shown to whoever // has to reconnect, so each says what to do. The wording follows the prototype's // (ResolveCredentials in internal/connectors/runtime.go:98-115 at cf62af0d), without the word @@ -135,6 +140,9 @@ type Resolver struct { mu sync.Mutex cache map[core.ConnectionRef]entry + // unsaved are the renewals whose saves all failed with an error a retry may fix, for + // the connection's next Resolve to save (saveUnsaved). + unsaved map[core.ConnectionRef]unsavedRenewal // swept is when expired entries were last dropped, so connections nobody resolves any // more do not keep theirs. swept time.Time @@ -151,6 +159,12 @@ type entry struct { renewed bool } +// unsavedRenewal is a renewal saveAgain could not save: the state its checkpoint committed and +// the one it left. +type unsavedRenewal struct { + atCheckpoint, final core.CredentialState +} + // New is a Resolver over cfg. func New(cfg Config) (*Resolver, error) { if cfg.Store == nil || cfg.Credentials == nil { @@ -166,7 +180,7 @@ func New(cfg Config) (*Resolver, error) { logger = slog.Default() } return &Resolver{store: cfg.Store, credentials: cfg.Credentials, schemes: cfg.Schemes, now: now, - logger: logger, cache: map[core.ConnectionRef]entry{}}, nil + logger: logger, cache: map[core.ConnectionRef]entry{}, unsaved: map[core.ConnectionRef]unsavedRenewal{}}, nil } // Resolve returns an access credential for ref. @@ -184,6 +198,11 @@ func (r *Resolver) Resolve(ctx context.Context, ref core.ConnectionRef, req core r.drop(ref) return core.AccessCredential{}, err } + if connection.Status == store.ConnectionNeedsReauthorization { + if err := r.saveUnsaved(ctx, ref, connection); err != nil { + return core.AccessCredential{}, err + } + } // A refused credential is never served again from the cache (core.CredentialRequest.Refused). if connection.Status == store.ConnectionConnected && req.Refused == nil { if credential, found := r.cached(ref, connection.Revision, req.Deadline); found { @@ -465,27 +484,79 @@ func (r *Resolver) saveAgain(ctx context.Context, ref core.ConnectionRef, atChec for attempts < saveAttempts && retryable(err) && wait(ctx, pause) { attempts, pause = attempts+1, 2*pause var committed *core.CredentialState - err = r.credentials.Update(ctx, ref, func(state *core.CredentialState, _ func() error) (bool, error) { - committed = state - if !changed(final, *state) { - return false, nil - } - if changed(atCheckpoint, *state) { - return false, stack.Wrap(errMovedSinceCheckpoint) - } - state.Credentials, state.ExpiresAt = final.Credentials, final.ExpiresAt - state.Status, state.LastError = final.Status, final.LastError - return true, nil - }) - if err == nil { + if committed, err = r.saveFinal(ctx, ref, atCheckpoint, final); err == nil { return committed, nil } } + if retryable(err) && r.hold(ref, unsavedRenewal{atCheckpoint: atCheckpoint, final: final}) { + r.logger.Error("could not save a connector credential refresh; this router saves it on the connection's next use, or the connection needs a reconnect", + "connection", ref.ConnectionID, "attempts", attempts, "error", err) + return nil, err + } r.logger.Error("could not save a connector credential refresh; the connection needs a reconnect", "connection", ref.ConnectionID, "attempts", attempts, "error", err) return nil, err } +// saveFinal saves final, in an Update of its own, while the connection is still as the +// checkpoint left it (atCheckpoint). A save that landed with its answer lost is found done. +func (r *Resolver) saveFinal(ctx context.Context, ref core.ConnectionRef, atCheckpoint, final core.CredentialState) (*core.CredentialState, error) { + var committed *core.CredentialState + err := r.credentials.Update(ctx, ref, func(state *core.CredentialState, _ func() error) (bool, error) { + committed = state + if !changed(final, *state) { + return false, nil + } + if changed(atCheckpoint, *state) { + return false, stack.Wrap(errMovedSinceCheckpoint) + } + state.Credentials, state.ExpiresAt = final.Credentials, final.ExpiresAt + state.Status, state.LastError = final.Status, final.LastError + return true, nil + }) + return committed, err +} + +// saveUnsaved saves the renewal held for ref, if there is one, before connection, which still +// says needs_reauthorization, is resolved: the renewed credentials the provider may have rotated +// to are only here. It is forgotten once saved, or once the connection moved since its +// checkpoint, a reconnect or a revocation coming first; a save that fails in a way a retry may +// fix keeps it, and fails the call. +func (r *Resolver) saveUnsaved(ctx context.Context, ref core.ConnectionRef, connection store.ConnectorConnection) error { + r.mu.Lock() + held, found := r.unsaved[ref] + r.mu.Unlock() + if !found { + return nil + } + committed, err := r.saveFinal(ctx, ref, held.atCheckpoint, held.final) + if err != nil && retryable(err) { + return stack.Wrap(err) + } + r.mu.Lock() + delete(r.unsaved, ref) + r.mu.Unlock() + if err == nil { + r.audit(ctx, ref, &connection, store.AuditGrantRefreshed, "", committed.Revision, core.CredentialChange{ + Previous: core.FingerprintsOf(r.schemes, held.atCheckpoint.Credentials), + Current: core.FingerprintsOf(r.schemes, committed.Credentials), + }) + } + return nil +} + +// hold keeps a renewal whose saves failed for the connection's next Resolve, and reports false +// when unsavedMost are held already. +func (r *Resolver) hold(ref core.ConnectionRef, renewal unsavedRenewal) bool { + r.mu.Lock() + defer r.mu.Unlock() + if _, found := r.unsaved[ref]; !found && len(r.unsaved) >= unsavedMost { + return false + } + r.unsaved[ref] = renewal + return true +} + // retryable says whether saving the same state again may pass: not when the connection moved // or is gone (store.ErrConnectorConnectionChanged, store.ErrNoConnectorConnection, // errMovedSinceCheckpoint), nor when the store or Postgres refused the row itself diff --git a/acceleration/internal/connectors/resolver/save_test.go b/acceleration/internal/connectors/resolver/save_test.go index 046882b356..8bafec13f1 100644 --- a/acceleration/internal/connectors/resolver/save_test.go +++ b/acceleration/internal/connectors/resolver/save_test.go @@ -8,6 +8,7 @@ import ( "fmt" "net/http" "sync" + "sync/atomic" "time" "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/core" @@ -136,6 +137,33 @@ func (s *ResolverSuite) TestARefreshWhoseSavesAllFailKeepsTheCheckpointAndIsLogg s.noTokenLogged(access, refresh) } +// A refresh whose saves all failed keeps what it renewed on the router that renewed it, which +// saves it on the connection's next use once the database takes it again: the provider may +// have rotated the refresh token, and the person does not have to reconnect. +func (s *ResolverSuite) TestARefreshWhoseSavesAllFailedIsSavedOnTheNextUse() { + ref := s.f.connected() + s.f.due() + var failing atomic.Bool + failing.Store(true) + router := s.f.routerSaving(s.f.srv.Client(), &failingSaves{fail: func(int) (error, bool) { + if failing.Load() { + return dropped, false + } + return nil, false + }}) + _, err := router.Resolve(s.f.ctx, ref, core.CredentialRequest{}) + s.Require().ErrorIs(err, driver.ErrBadConn) + s.Require().Equal(store.ConnectionNeedsReauthorization, s.f.stored(ref).Status) + failing.Store(false) + + credential, err := router.Resolve(s.f.ctx, ref, core.CredentialRequest{}) + + s.Require().NoError(err) + s.True(s.f.works(credential)) + s.Equal(store.ConnectionConnected, s.f.stored(ref).Status) + s.Empty(s.f.stored(ref).LastError) +} + func (s *ResolverSuite) TestASaveIsRetriedOnlyAfterAFailureARetryCanFix() { invalid := (&store.ConnectorConnection{}).Validate() s.Require().Error(invalid) From 87079690188ccfc0b7aa4a80bda7a70820a1707d Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 22:07:12 +0100 Subject: [PATCH 10/12] test(dlc): poll directly, and read each app's registrations in the fake Since #2254 a brand report refreshes only the use cases of the app that holds the brand, so a report naming no app's brand polls nothing. The 10DLC registration tests run a poll themselves instead. A poll refreshes every held use case in the shared test database, so the fake registry now answers and counts each app's registrations apart, telling apps by their profile's contact email. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/dlc_test.go | 134 +++++++++++++++----------- 1 file changed, 76 insertions(+), 58 deletions(-) diff --git a/acceleration/internal/api/dlc_test.go b/acceleration/internal/api/dlc_test.go index 9041bbc838..bfda0cf1f4 100644 --- a/acceleration/internal/api/dlc_test.go +++ b/acceleration/internal/api/dlc_test.go @@ -38,15 +38,17 @@ type campaignRegistry struct { mu sync.Mutex campaigns map[string]string assigned map[string]string - // brandAnswers and campaignAnswers are the statuses the next registrations are answered - // with, each registered whatever the answer; past them every one is answered 200. brands - // and campaignsAsked count the registrations asked for. - brandAnswers, campaignAnswers []int - brandsAsked, campaignsAsked int - // brands are the ids of the brands registered, and listed the campaigns a list of a - // brand's answers, with the reference each was registered with. - brands []string - listed []listedCampaign + // brandAnswers and campaignAnswers are the statuses an app's next registrations are + // answered with, each registered whatever the answer; past them every one is answered 200. + // brandsAsked and campaignsAsked count each app's registrations asked for. A poll asks + // about every app's use cases, so each test reads its own app's: one known by its + // profile's contact email, and a campaign by its brand's app. + brandAnswers, campaignAnswers map[string][]int + brandsAsked, campaignsAsked map[string]int + // brands are the brand registered for each app and owners the app of each brand, and + // listed the campaigns a list of a brand's answers, with the reference each carried. + brands, owners map[string]string + listed []listedCampaign } // listedCampaign is a campaign as a list of its brand's names it. @@ -65,21 +67,24 @@ func (r *campaignRegistry) ServeHTTP(w http.ResponseWriter, request *http.Reques path := request.URL.Path switch { case request.Method == http.MethodPost && path == "/v2/10dlc/brand": - r.brandsAsked++ - if answer := nextAnswer(&r.brandAnswers); answer != http.StatusOK { + app := body["email"] + r.brandsAsked[app]++ + if answer := nextAnswer(r.brandAnswers, app); answer != http.StatusOK { w.WriteHeader(answer) return } - r.brands = append(r.brands, uuid.NewString()) - fmt.Fprintf(w, `{"brandId":%q,"status":"OK","identityStatus":"VERIFIED"}`, r.brands[len(r.brands)-1]) + r.brands[app] = uuid.NewString() + r.owners[r.brands[app]] = app + fmt.Fprintf(w, `{"brandId":%q,"status":"OK","identityStatus":"VERIFIED"}`, r.brands[app]) case request.Method == http.MethodGet && strings.HasPrefix(path, "/v2/10dlc/brand/"): fmt.Fprintf(w, `{"brandId":%q,"status":"OK","identityStatus":"VERIFIED"}`, strings.TrimPrefix(path, "/v2/10dlc/brand/")) case request.Method == http.MethodPost && path == "/v2/10dlc/campaignBuilder": - r.campaignsAsked++ + app := r.owners[body["brandId"]] + r.campaignsAsked[app]++ id := uuid.NewString() r.campaigns[id] = "TCR_PENDING" r.listed = append(r.listed, listedCampaign{id: id, brand: body["brandId"], reference: body["referenceId"]}) - if answer := nextAnswer(&r.campaignAnswers); answer != http.StatusOK { + if answer := nextAnswer(r.campaignAnswers, app); answer != http.StatusOK { w.WriteHeader(answer) return } @@ -108,27 +113,31 @@ func (r *campaignRegistry) ServeHTTP(w http.ResponseWriter, request *http.Reques } } -// nextAnswer takes the first of answers, or 200 when there is none. -func nextAnswer(answers *[]int) int { - if len(*answers) == 0 { +// nextAnswer takes the first of app's answers, or 200 when there is none. +func nextAnswer(answers map[string][]int, app string) int { + if len(answers[app]) == 0 { return http.StatusOK } - answer := (*answers)[0] - *answers = (*answers)[1:] + answer := answers[app][0] + answers[app] = answers[app][1:] return answer } -// answer has the next brand and campaign registrations answered with brands and campaigns, -// and reports how many of each were asked for so far. -func (r *campaignRegistry) answer(brands, campaigns []int) (int, int) { +// answer has app's next brand and campaign registrations answered with brands and campaigns, +// and reports how many of each it asked for so far. +func (r *campaignRegistry) answer(app string, brands, campaigns []int) (int, int) { r.mu.Lock() defer r.mu.Unlock() - r.brandAnswers, r.campaignAnswers = brands, campaigns - return r.brandsAsked, r.campaignsAsked + r.brandAnswers[app], r.campaignAnswers[app] = brands, campaigns + return r.brandsAsked[app], r.campaignsAsked[app] } -// asked is how many brand and campaign registrations were asked for so far. -func (r *campaignRegistry) asked() (int, int) { return r.answer(nil, nil) } +// asked is how many brand and campaign registrations app asked for so far. +func (r *campaignRegistry) asked(app string) (int, int) { + r.mu.Lock() + defer r.mu.Unlock() + return r.brandsAsked[app], r.campaignsAsked[app] +} // campaignFor is the campaign registered with reference, empty when there is none. func (r *campaignRegistry) campaignFor(reference string) string { @@ -142,18 +151,19 @@ func (r *campaignRegistry) campaignFor(reference string) string { return "" } -// lastBrand is the brand registered last. -func (r *campaignRegistry) lastBrand() string { +// brandOf is the brand registered for app. +func (r *campaignRegistry) brandOf(app string) string { r.mu.Lock() defer r.mu.Unlock() - return r.brands[len(r.brands)-1] + return r.brands[app] } -// unlist forgets every campaign registered so far, as a registration Telnyx never carried out. -func (r *campaignRegistry) unlist() { +// unlist forgets every campaign registered for app so far, as registrations Telnyx never +// carried out. +func (r *campaignRegistry) unlist(app string) { r.mu.Lock() defer r.mu.Unlock() - r.listed = nil + r.listed = slices.DeleteFunc(r.listed, func(listed listedCampaign) bool { return r.owners[listed.brand] == app }) } func (r *campaignRegistry) set(campaignID, status string) { @@ -192,7 +202,9 @@ type dlcRegistration struct { } func (s *dlcRegistration) SetupSuite() { - s.registry = &campaignRegistry{campaigns: map[string]string{}, assigned: map[string]string{}} + s.registry = &campaignRegistry{campaigns: map[string]string{}, assigned: map[string]string{}, + brandAnswers: map[string][]int{}, campaignAnswers: map[string][]int{}, brandsAsked: map[string]int{}, + campaignsAsked: map[string]int{}, brands: map[string]string{}, owners: map[string]string{}} fake := httptest.NewServer(s.registry) s.T().Cleanup(fake.Close) public, private, err := ed25519.GenerateKey(rand.Reader) @@ -220,10 +232,16 @@ func (s *dlcRegistration) completeProfile() { LegalBusinessName: "Acme Inc", LegalEntityType: "corporation", OrganizationType: "private", BusinessRegistrationCountry: "US", TaxId: "12-3456789", RegisteredAddress: &address, WebsiteUrl: "https://acme.example", Industry: "technology", - AuthorizedContactEmail: "ops@acme.example", AuthorizedContactPhone: "+15551230000", + AuthorizedContactEmail: s.contactEmail(), AuthorizedContactPhone: "+15551230000", }, nil)) } +// contactEmail is the app's profile's contact email, which tells the fake registry its +// registrations from other apps'. +func (s *dlcRegistration) contactEmail() string { + return "ops+" + s.customerID() + "@acme.example" +} + func completeUseCase(name string) UseCaseRequest { return UseCaseRequest{ Name: name, @@ -333,16 +351,16 @@ func (s *DLCSuite) TestAUseCaseIsApprovedByStreamAndThenByTheVendor() { // answered with a failure may be registered, and billed, all the same, so it is not asked for // again, however often the poller looks. func (s *DLCSuite) TestABrandWhoseRegistrationWasNotAnsweredIsNotRegisteredTwice() { - brands, _ := s.registry.answer([]int{http.StatusBadRequest, http.StatusInternalServerError}, nil) + brands, _ := s.registry.answer(s.contactEmail(), []int{http.StatusBadRequest, http.StatusInternalServerError}, nil) sent := s.submitted() status, reviewed := s.review(sent.Id, dlc.Approve, "") s.Require().Equal(http.StatusOK, status) s.Equal(UseCaseStatus(dlc.VendorPending), reviewed.Status) - s.Equal(http.StatusNoContent, s.report(`{"brandId":"another"}`, s.signing), "the poller asks again after the refusal") - s.Equal(http.StatusNoContent, s.report(`{"brandId":"another"}`, s.signing)) + s.registrar10DLC.Poll(context.Background()) // asks again after the refusal + s.registrar10DLC.Poll(context.Background()) - asked, _ := s.registry.asked() + asked, _ := s.registry.asked(s.contactEmail()) s.Equal(2, asked-brands, "refused, then asked once more") s.Empty(s.loggedLines("a 10DLC registration was not answered", s.customerID()), "one that may still be registering is not reported lost") } @@ -352,17 +370,17 @@ func (s *DLCSuite) TestABrandWhoseRegistrationWasNotAnsweredIsNotRegisteredTwice // it by: the use case is handed back to the app as vendor_rejected, which it may delete, and the // brand is not asked for again until support has looked it up. func (s *DLCSuite) TestABrandWhoseAnswerWasLostIsLeftToSupportAndFreesTheUseCase() { - brands, _ := s.registry.answer([]int{http.StatusInternalServerError}, nil) + brands, _ := s.registry.answer(s.contactEmail(), []int{http.StatusInternalServerError}, nil) sent := s.submitted() status, _ := s.review(sent.Id, dlc.Approve, "") s.Require().Equal(http.StatusOK, status) s.backdate("business_profiles", "brand_requested_at", "customer_id", s.customerID()) - s.Equal(http.StatusNoContent, s.report(`{"brandId":"another"}`, s.signing)) - s.Equal(http.StatusNoContent, s.report(`{"brandId":"another"}`, s.signing)) + s.registrar10DLC.Poll(context.Background()) + s.registrar10DLC.Poll(context.Background()) s.Equal(UseCaseStatus(dlc.VendorRejected), s.useCase(sent.Id).Status) - asked, _ := s.registry.asked() + asked, _ := s.registry.asked(s.contactEmail()) s.Equal(1, asked-brands, "never asked for again") s.Len(s.loggedLines("a 10DLC registration was not answered", s.customerID()), 1) s.Equal(http.StatusNoContent, s.serverClient.do(http.MethodDelete, "/v1/phone/use-cases/"+sent.Id, nil, nil)) @@ -371,39 +389,39 @@ func (s *DLCSuite) TestABrandWhoseAnswerWasLostIsLeftToSupportAndFreesTheUseCase // A campaign whose registration was not answered is found at Telnyx by the use case it was // registered for, and recorded, without asking for a second one. func (s *DLCSuite) TestACampaignWhoseAnswerWasLostIsFoundAtTheVendor() { - _, campaigns := s.registry.answer(nil, []int{http.StatusInternalServerError}) + _, campaigns := s.registry.answer(s.contactEmail(), nil, []int{http.StatusInternalServerError}) sent := s.submitted() status, reviewed := s.review(sent.Id, dlc.Approve, "") s.Require().Equal(http.StatusOK, status) s.Require().Nil(reviewed.VendorCampaignId) s.backdate("dlc_use_cases", "campaign_requested_at", "id", sent.Id) - s.Equal(http.StatusNoContent, s.report(`{"brandId":"another"}`, s.signing)) + s.registrar10DLC.Poll(context.Background()) found := s.useCase(sent.Id) s.Require().NotNil(found.VendorCampaignId) s.Equal(s.registry.campaignFor(sent.Id), *found.VendorCampaignId) - _, asked := s.registry.asked() + _, asked := s.registry.asked(s.contactEmail()) s.Equal(1, asked-campaigns) } // A campaign Telnyx does not hold, its registration answered with a failure, was never // registered: it is asked for again. func (s *DLCSuite) TestACampaignTheVendorNeverRegisteredIsAskedForAgain() { - _, campaigns := s.registry.answer(nil, []int{http.StatusInternalServerError}) + _, campaigns := s.registry.answer(s.contactEmail(), nil, []int{http.StatusInternalServerError}) sent := s.submitted() status, _ := s.review(sent.Id, dlc.Approve, "") s.Require().Equal(http.StatusOK, status) - s.registry.unlist() + s.registry.unlist(s.contactEmail()) s.backdate("dlc_use_cases", "campaign_requested_at", "id", sent.Id) - s.Equal(http.StatusNoContent, s.report(`{"brandId":"another"}`, s.signing)) - s.Equal(http.StatusNoContent, s.report(`{"brandId":"another"}`, s.signing)) + s.registrar10DLC.Poll(context.Background()) + s.registrar10DLC.Poll(context.Background()) found := s.useCase(sent.Id) s.Require().NotNil(found.VendorCampaignId) s.Equal(s.registry.campaignFor(sent.Id), *found.VendorCampaignId) - _, asked := s.registry.asked() + _, asked := s.registry.asked(s.contactEmail()) s.Equal(2, asked-campaigns) } @@ -418,13 +436,13 @@ func (s *DLCSuite) TestABrandRegisteredWhoseIdCouldNotBeSavedIsLoggedWithIt() { s.Require().Equal(http.StatusOK, status) line := s.loggedLine("could not save a brand the vendor registered", s.customerID()) s.Contains(line, "level=ERROR") - s.Contains(line, "vendor_brand_id="+s.registry.lastBrand()) + s.Contains(line, "vendor_brand_id="+s.registry.brandOf(s.contactEmail())) } // A campaign Telnyx registered whose save the database failed is logged with its id, and found // at Telnyx by the poller once the database is back. func (s *DLCSuite) TestACampaignRegisteredWhoseSaveFailedIsFoundAtTheVendorLater() { - _, campaigns := s.registry.asked() + _, campaigns := s.registry.asked(s.contactEmail()) s.failQueries(registeredNote) sent := s.submitted() status, _ := s.review(sent.Id, dlc.Approve, "") @@ -435,12 +453,12 @@ func (s *DLCSuite) TestACampaignRegisteredWhoseSaveFailedIsFoundAtTheVendorLater s.failQueries("no query holds this") s.backdate("dlc_use_cases", "campaign_requested_at", "id", sent.Id) - s.Equal(http.StatusNoContent, s.report(`{"brandId":"another"}`, s.signing)) + s.registrar10DLC.Poll(context.Background()) found := s.useCase(sent.Id) s.Require().NotNil(found.VendorCampaignId) s.Equal(s.registry.campaignFor(sent.Id), *found.VendorCampaignId) - _, asked := s.registry.asked() + _, asked := s.registry.asked(s.contactEmail()) s.Equal(1, asked-campaigns) } @@ -486,15 +504,15 @@ func (s *dlcRegistration) useCase(id string) UseCase { // A campaign whose registration was answered with a failure may be registered, and billed, all // the same, so it is not asked for again. func (s *DLCSuite) TestACampaignWhoseRegistrationWasNotAnsweredIsNotRegisteredTwice() { - _, campaigns := s.registry.answer(nil, []int{http.StatusInternalServerError}) + _, campaigns := s.registry.answer(s.contactEmail(), nil, []int{http.StatusInternalServerError}) sent := s.submitted() status, reviewed := s.review(sent.Id, dlc.Approve, "") s.Require().Equal(http.StatusOK, status) s.Nil(reviewed.VendorCampaignId) - s.Equal(http.StatusNoContent, s.report(`{"brandId":"another"}`, s.signing)) + s.registrar10DLC.Poll(context.Background()) - _, asked := s.registry.asked() + _, asked := s.registry.asked(s.contactEmail()) s.Equal(1, asked-campaigns) } From fa246a36b0b73fc5fb08e14b9fcd7a6f5fe7d7fd Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 22:07:40 +0100 Subject: [PATCH 11/12] chore(migrations): renumber AI-3514 migrations after AI-3515 and AI-3516 #2279 (20270201000500) and #2276 (20270201000700) merge first, and goose refuses a migration older than the newest one applied, so this branch's migrations move above both: global 20270201001100 (phone_number_orders), global 20270201001110 (dlc registration requests) and shard 20270201001120 (call_legs_transfer_idx). Nothing else names the versions; the schema files are unchanged. Co-Authored-By: Claude Opus 5.5 --- ...e_number_orders.sql => 20270201001100_phone_number_orders.sql} | 0 ..._requests.sql => 20270201001110_dlc_registration_requests.sql} | 0 ...transfer_idx.sql => 20270201001120_call_legs_transfer_idx.sql} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename acceleration/migrations/global/{20270201000300_phone_number_orders.sql => 20270201001100_phone_number_orders.sql} (100%) rename acceleration/migrations/global/{20270201000310_dlc_registration_requests.sql => 20270201001110_dlc_registration_requests.sql} (100%) rename acceleration/migrations/shard/{20270201000320_call_legs_transfer_idx.sql => 20270201001120_call_legs_transfer_idx.sql} (100%) diff --git a/acceleration/migrations/global/20270201000300_phone_number_orders.sql b/acceleration/migrations/global/20270201001100_phone_number_orders.sql similarity index 100% rename from acceleration/migrations/global/20270201000300_phone_number_orders.sql rename to acceleration/migrations/global/20270201001100_phone_number_orders.sql diff --git a/acceleration/migrations/global/20270201000310_dlc_registration_requests.sql b/acceleration/migrations/global/20270201001110_dlc_registration_requests.sql similarity index 100% rename from acceleration/migrations/global/20270201000310_dlc_registration_requests.sql rename to acceleration/migrations/global/20270201001110_dlc_registration_requests.sql diff --git a/acceleration/migrations/shard/20270201000320_call_legs_transfer_idx.sql b/acceleration/migrations/shard/20270201001120_call_legs_transfer_idx.sql similarity index 100% rename from acceleration/migrations/shard/20270201000320_call_legs_transfer_idx.sql rename to acceleration/migrations/shard/20270201001120_call_legs_transfer_idx.sql From 730f8c8211347f55b5dfa469add706fde983ff81 Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 22:40:47 +0100 Subject: [PATCH 12/12] fix(phone): forget an order no vendor was asked about A purchase or release refused before the vendor was asked (a vendor not implemented, one missing a setting, or an order it cannot take as asked) kept its order. No vendor can settle such an order, so the sweep logged it at ERROR every hour, and a customer could create one at will by buying from a declared vendor that is not implemented. Co-Authored-By: Claude Opus 5.5 --- .../phone/metering_integration_test.go | 35 +++++++++++++++++++ acceleration/internal/phone/service.go | 13 ++++--- 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/acceleration/internal/phone/metering_integration_test.go b/acceleration/internal/phone/metering_integration_test.go index 67d5c9672c..bb81dcb9c4 100644 --- a/acceleration/internal/phone/metering_integration_test.go +++ b/acceleration/internal/phone/metering_integration_test.go @@ -1017,6 +1017,41 @@ func (s *MeteringSuite) TestAnOrderTheVendorDoesNotHoldIsForgottenWithoutANumber s.Zero(s.orders()) } +// A purchase from a vendor not implemented, which no vendor was asked about and none can settle, +// leaves no order for the sweep to log every hour. +func (s *MeteringSuite) TestAPurchaseFromAVendorNotImplementedLeavesNoOrder() { + _, err := s.service.Buy(s.ctx, Purchase{Vendor: "bics", E164: aNumber(), Owner: s.owner()}) + s.Require().ErrorIs(err, ErrNotImplemented) + s.clock.advance(orderSettles + time.Minute) + + _, err = s.service.SweepOrders(s.ctx) + + s.Require().NoError(err) + s.Zero(s.orders()) + s.Zero(s.logs.count("ERROR", "customer="+s.customer)) +} + +// A purchase refused before the vendor was asked, for a setting the deployment lacks, leaves +// no order. +func (s *MeteringSuite) TestAPurchaseFromAVendorMissingASettingLeavesNoOrder() { + s.vendor.err = NotConfigured(errors.New("telnyx: a setting is required to order a number")) + + _, err := s.service.Buy(s.ctx, Purchase{Vendor: s.vendor.vendor, E164: aNumber(), Owner: s.owner()}) + + s.Require().ErrorIs(err, ErrNotConfigured) + s.Zero(s.orders()) +} + +// A purchase refused before the vendor was asked, as one it cannot take, leaves no order. +func (s *MeteringSuite) TestAPurchaseTheVendorCannotTakeAsAskedLeavesNoOrder() { + s.vendor.err = Invalid(errors.New("telnyx: buying a number needs the country it is sold in")) + + _, err := s.service.Buy(s.ctx, Purchase{Vendor: s.vendor.vendor, E164: aNumber(), Owner: s.owner()}) + + s.Require().ErrorIs(err, ErrInvalid) + s.Zero(s.orders()) +} + // orders counts the customer's orders still to settle. func (s *MeteringSuite) orders() int { count, err := s.store.GlobalDB().NewSelect().Model((*store.PhoneNumberOrder)(nil)). diff --git a/acceleration/internal/phone/service.go b/acceleration/internal/phone/service.go index bfbeb917d3..cdf41e9214 100644 --- a/acceleration/internal/phone/service.go +++ b/acceleration/internal/phone/service.go @@ -609,12 +609,15 @@ func (s *Service) Release(ctx context.Context, customerID, e164 string) error { return nil } -// forgetRefusedOrder forgets an order the vendor answered err to, when err is the vendor refusing -// it: a 4xx, which it did not carry out. Any other failure, a timeout, a dropped connection or a -// 5xx, may come after the vendor bought or released the number, so the order is left to the -// sweep, which asks the vendor what it holds. +// forgetRefusedOrder forgets an order the vendor answered err to, when err shows the vendor did +// nothing: a 4xx, which it did not carry out, or a refusal before it was asked, by a vendor not +// implemented or missing a setting, or of an order it cannot take as asked. Any other failure, +// a timeout, a dropped connection or a 5xx, may come after the vendor bought or released the +// number, so the order is left to the sweep, which asks the vendor what it holds. func (s *Service) forgetRefusedOrder(ctx context.Context, order store.PhoneNumberOrder, err error) { - if refused, ok := errors.AsType[*VendorError](err); ok && refused.Status >= 400 && refused.Status < 500 { + refused, ok := errors.AsType[*VendorError](err) + if ok && refused.Status >= 400 && refused.Status < 500 || + errors.Is(err, ErrNotImplemented) || errors.Is(err, ErrNotConfigured) || errors.Is(err, ErrInvalid) { s.forgetOrder(ctx, order) } }