diff --git a/acceleration/README.md b/acceleration/README.md index 9d44acc402..18be2d0716 100644 --- a/acceleration/README.md +++ b/acceleration/README.md @@ -2729,6 +2729,18 @@ Only Twilio and Telnyx also `attach`, which is the inbound direction: pointing a trunk so calling it reaches an agent. For the other five that is a per-vendor application rather than a property of the number, and it is declared missing rather than half-done. +A Twilio number attached before the router answered its calls itself still has its old voice URL. +`router phone move-twilio` points those numbers at `/v1/phone/hooks/twilio`, as an attach does now; +attaching such a number again does the same for that one number. Run it from the image the router +runs (the same tag), with the router's own config: it opens the database as the router does, which +migrates it unless a migrate DSN is set, so a newer image would migrate the shared database. Run +it first with no flag, which only lists each number and what it would do; then with `--apply +--one `, and call that number; then with `--apply` for the rest (`--app ` keeps one Stream +app's). A number already on the webhook is left alone, and so is one whose trunk credentials were +not kept (`no stored bridge`): it needs a detach and an attach. It refuses before it asks Twilio +anything when the webhook token, an https `ROUTER_PUBLIC_URL`, the Twilio account or the keyring +is missing. + A customer who already has numbers and a SIP trunk at their own carrier can call out from them without buying anything here. `POST /v1/phone/trunks` stores the trunk (host, port, transport, username, codecs, and whether it accepts an INVITE without SDP); the password is diff --git a/acceleration/cmd/router/main.go b/acceleration/cmd/router/main.go index d8d73a5f22..8975815985 100644 --- a/acceleration/cmd/router/main.go +++ b/acceleration/cmd/router/main.go @@ -199,6 +199,7 @@ const usage = `usage: router [--config path] [command] stream-apps look after the Stream apps customers registered in app mode conversations look after the conversations kept in Stream Chat prices read and check the price list (router prices for its commands) + phone move-twilio point Twilio numbers attached earlier at the router's call webhook (--apply, --one, --app) opt-outs normalize rewrite opt-outs stored before E.164 was enforced into E.164 usage replay write the usage rows a log says were lost, once each (--from path) usage reship send this shard's shipped or refused rows to the usage service again (--since, --rejected) @@ -293,6 +294,8 @@ func dispatchCommand(command string, args []string, settings config.Config, logg return runOptOuts(args, settings, logger) case "usage": return runUsage(args, settings, os.Stdout) + case "phone": + return runPhone(args, settings, logger) case "help", "-h", "--help": fmt.Print(usage) return nil diff --git a/acceleration/cmd/router/phonemove.go b/acceleration/cmd/router/phonemove.go new file mode 100644 index 0000000000..3f205fb715 --- /dev/null +++ b/acceleration/cmd/router/phonemove.go @@ -0,0 +1,117 @@ +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "log/slog" + "os" + "strconv" + + "github.com/GetStream/Vision-Agents/acceleration/internal/config" + "github.com/GetStream/Vision-Agents/acceleration/internal/phone" + "github.com/GetStream/Vision-Agents/acceleration/internal/phone/vendors" + "github.com/GetStream/Vision-Agents/acceleration/internal/store" + "github.com/GetStream/Vision-Agents/acceleration/internal/streamapp" +) + +const phoneUsage = `usage: router phone [flags] + + move-twilio point the Twilio numbers attached before the router answered their calls itself at + its call webhook (ROUTER_PUBLIC_URL + /v1/phone/hooks/twilio), as attaching one does + now. Says what it would do, a line a number, unless --apply. A number already there + is left alone, and so is one whose trunk credentials were not kept, which needs a + re-attach. Refuses before asking Twilio anything without TWILIO_WEBHOOK_AUTH_TOKEN, + an https ROUTER_PUBLIC_URL, the Twilio account or the keyring. + --apply point the numbers at the webhook + --one only this number, in E.164: move one first and call it + --app only the numbers made in this Stream app +` + +// runPhone looks after the numbers the shared database holds. +func runPhone(args []string, settings config.Config, logger *slog.Logger) error { + if len(args) == 0 { + return errors.New(phoneUsage) + } + ctx := context.Background() + switch args[0] { + case "move-twilio": + service, pgStore, err := numberMover(ctx, settings, logger) + if err != nil { + return err + } + defer pgStore.Close() + return moveTwilioNumbers(ctx, args[1:], service, os.Stdout) + } + return fmt.Errorf("unknown phone command %q\n\n%s", args[0], phoneUsage) +} + +// numberMover is the phone service with what moving a number needs: the database, the keyring +// the webhook opens trunk passwords with, the vendors and the public URL. +// The store is the caller's to close. +func numberMover(ctx context.Context, settings config.Config, logger *slog.Logger) ( + *phone.Service, *store.Store, error, +) { + vendorConfig, err := phone.LoadConfig(settings.PhoneConfig) + if err != nil { + return nil, nil, err + } + secrets, err := newSecretSealer(ctx, settings) + if err != nil { + return nil, nil, err + } + pgStore, err := openStore(ctx, settings) + if err != nil { + return nil, nil, err + } + service, err := phone.NewService(phone.ServiceOptions{ + Registry: vendors.Registry(vendorConfig), Store: pgStore, Sealer: secrets, + PublicURL: settings.PublicURL, Logger: logger, + }) + if err != nil { + pgStore.Close() + return nil, nil, err + } + return service, pgStore, nil +} + +// moveTwilioNumbers runs router phone move-twilio on service, writing a line a number to out. +// A line names the number and its app only. +func moveTwilioNumbers(ctx context.Context, args []string, service *phone.Service, out io.Writer) error { + flags := flag.NewFlagSet("phone move-twilio", flag.ContinueOnError) + apply := flags.Bool("apply", false, "point the numbers at the webhook") + one := flags.String("one", "", "only this number, in E.164") + app := flags.String("app", "", "only the numbers made in this Stream app") + if err := flags.Parse(args); err != nil { + return err + } + move := phone.CallHookMove{Vendor: "twilio", E164: *one, Apply: *apply} + if *one != "" && !store.IsE164(*one) { + return fmt.Errorf("--one is a number in E.164, such as +15125551234, not %q", *one) + } + if *app != "" { + pin, ok := streamapp.ParseAppID(*app) + if !ok { + return fmt.Errorf("--app is a Stream app id, not %q", *app) + } + move.App = &pin + } + + counted := map[phone.Move]int{} + err := service.MoveToCallHook(ctx, move, func(number phone.MovedNumber) { + counted[number.Move]++ + app := "deployment" + if number.App != 0 { + app = strconv.FormatInt(number.App, 10) + } + fmt.Fprintf(out, "%s\tapp %s\t%s\n", number.E164, app, number.Move) + }) + fmt.Fprintf(out, "%d moved, %d to move, %d already moved, %d with no stored bridge\n", + counted[phone.Moved], counted[phone.WouldMove], counted[phone.AlreadyMoved], counted[phone.NoStoredBridge]) + if !*apply { + fmt.Fprintln(out, "nothing was written at Twilio: --apply points the numbers at the webhook") + } + return err +} diff --git a/acceleration/cmd/router/phonemove_integration_test.go b/acceleration/cmd/router/phonemove_integration_test.go new file mode 100644 index 0000000000..702a630f26 --- /dev/null +++ b/acceleration/cmd/router/phonemove_integration_test.go @@ -0,0 +1,636 @@ +//go:build integration + +package main + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/json" + "fmt" + "log/slog" + "math/big" + "net/http" + "net/http/httptest" + "net/url" + "os" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/suite" + + "github.com/GetStream/Vision-Agents/acceleration/internal/auth" + "github.com/GetStream/Vision-Agents/acceleration/internal/config" + "github.com/GetStream/Vision-Agents/acceleration/internal/conversation/chattest" + "github.com/GetStream/Vision-Agents/acceleration/internal/phone" + "github.com/GetStream/Vision-Agents/acceleration/internal/phone/telnyx" + "github.com/GetStream/Vision-Agents/acceleration/internal/phone/twilio" + "github.com/GetStream/Vision-Agents/acceleration/internal/phone/vendors" + "github.com/GetStream/Vision-Agents/acceleration/internal/store" + "github.com/GetStream/Vision-Agents/acceleration/internal/testenv" +) + +// moveTestPublicURL is the router's public URL in these tests; the hook URL is it plus the path. +const ( + moveTestPublicURL = "https://router.example.test" + moveTestHookURL = moveTestPublicURL + "/v1/phone/hooks/twilio" + // moveTestOldURL stands for the voice URL a number attached before the webhook has. + moveTestOldURL = "https://twimlets.com/echo?Twiml=old" + moveTestKEK = "phone move suite" +) + +// PhoneMoveSuite runs router phone move-twilio against Postgres, a fake Stream and a fake +// Twilio, with numbers attached as the router attaches them. +type PhoneMoveSuite struct { + suite.Suite + ctx context.Context + store *store.Store + chat *chattest.Server + twilio *fakeTwilio + telnyx *fakeTwilio + token string + customer string +} + +func TestPhoneMoveSuite(t *testing.T) { + suite.Run(t, new(PhoneMoveSuite)) +} + +func (s *PhoneMoveSuite) SetupSuite() { + dsn := os.Getenv("ROUTER_POSTGRES_DSN") + if dsn == "" { + s.T().Skip("ROUTER_POSTGRES_DSN not set") + } + s.ctx = context.Background() + settings := config.Defaults() + settings.Postgres.DSN = testenv.Database(dsn, "phone_move") + opened, err := openStore(s.ctx, settings) + s.Require().NoError(err) + s.store = opened + s.T().Cleanup(func() { s.Require().NoError(opened.Close()) }) +} + +func (s *PhoneMoveSuite) SetupTest() { + // The database is the suite's own, and a run lists every customer's numbers: none of an + // earlier test's may be left attached. + s.releaseAll() + // A token exported in the shell would let a test of a router without one pass. + s.T().Setenv("TWILIO_WEBHOOK_AUTH_TOKEN", "") + s.chat = chattest.NewServer(s.T()) + s.twilio = newFakeTwilio(s.T()) + s.telnyx = newFakeTwilio(s.T()) + s.token = rand.Text() + s.customer = uuid.NewString() +} + +// A dry run, the default, says what it would do with each number and writes nothing at Twilio. +func (s *PhoneMoveSuite) TestADryRunSaysWhatItWouldMoveAndWritesNothing() { + first, second := s.attachedEarlier(), s.attachedEarlier() + kept := s.attachedWithNoStoredBridge() + + out, err := s.move(s.ready()) + + s.Require().NoError(err) + s.Contains(out, first+"\tapp deployment\twould move\n") + s.Contains(out, second+"\tapp deployment\twould move\n") + s.Contains(out, kept+"\tapp deployment\tno stored bridge, needs a re-attach\n") + s.Contains(out, "0 moved, 2 to move, 0 already moved, 1 with no stored bridge\n") + s.Contains(out, "nothing was written at Twilio") + s.Empty(s.twilio.posted(), "nothing was written at Twilio") + s.Equal(moveTestOldURL, s.twilio.voiceURL(first)) +} + +// --apply points each number at the webhook once, by POST; a second run finds them there and +// writes nothing. A number whose trunk was not kept is not asked about at all. +func (s *PhoneMoveSuite) TestApplyMovesEachNumberOnceAndAgainMovesNone() { + first, second := s.attachedEarlier(), s.attachedEarlier() + kept := s.attachedWithNoStoredBridge() + + out, err := s.move(s.ready(), "--apply") + + s.Require().NoError(err) + s.Contains(out, first+"\tapp deployment\tmoved\n") + s.Contains(out, second+"\tapp deployment\tmoved\n") + s.Contains(out, "2 moved, 0 to move, 0 already moved, 1 with no stored bridge\n") + s.NotContains(out, "nothing was written") + posted := s.twilio.posted() + s.Require().Len(posted, 2) + for _, form := range posted { + s.Equal(url.Values{"VoiceUrl": {moveTestHookURL}, "VoiceMethod": {http.MethodPost}}, form) + } + s.Equal(moveTestHookURL, s.twilio.voiceURL(first)) + s.Equal(moveTestHookURL, s.twilio.voiceURL(second)) + s.NotContains(strings.Join(s.twilio.asked(), "\n"), url.QueryEscape(kept)) + for _, trunk := range s.chat.Trunks() { + password, _ := s.chat.TrunkAuth(trunk) + s.Require().NotEmpty(password) + s.NotContains(out, password, "the output names numbers only") + } + + again, err := s.move(s.ready(), "--apply") + + s.Require().NoError(err) + s.Contains(again, first+"\tapp deployment\talready moved\n") + s.Contains(again, "0 moved, 0 to move, 2 already moved, 1 with no stored bridge\n") + s.Len(s.twilio.posted(), 2, "nothing more was written") +} + +// A run reads past one page of the store, and reports each number once. +func (s *PhoneMoveSuite) TestARunReportsEveryNumberPastOnePageOnce() { + numbers := map[string]bool{} + for range 101 { + numbers[s.attachedWithNoStoredBridge()] = true + } + + out, err := s.move(s.ready()) + + s.Require().NoError(err) + s.Contains(out, "0 moved, 0 to move, 0 already moved, 101 with no stored bridge\n") + for number := range numbers { + s.Equal(1, strings.Count(out, number+"\t"), number) + } +} + +// A number on the webhook by GET is moved: Twilio would ask it without the body the webhook reads. +func (s *PhoneMoveSuite) TestANumberOnTheWebhookByGetIsMoved() { + number := s.attachedEarlier() + s.twilio.point(number, moveTestHookURL, http.MethodGet) + + out, err := s.move(s.ready()) + + s.Require().NoError(err) + s.Contains(out, number+"\tapp deployment\twould move\n") +} + +// --one moves that number only, as the first step of a move. +func (s *PhoneMoveSuite) TestOneMovesOnlyThatNumber() { + first, second := s.attachedEarlier(), s.attachedEarlier() + + out, err := s.move(s.ready(), "--apply", "--one", second) + + s.Require().NoError(err) + s.Equal(second+"\tapp deployment\tmoved\n1 moved, 0 to move, 0 already moved, 0 with no stored bridge\n", out) + s.Equal(moveTestOldURL, s.twilio.voiceURL(first)) + s.Equal(moveTestHookURL, s.twilio.voiceURL(second)) +} + +// --app moves the numbers made in that Stream app only. +func (s *PhoneMoveSuite) TestAppMovesOnlyTheNumbersOfThatApp() { + deployments, theApps := s.attachedEarlier(), s.attachedEarlier() + _, err := s.store.GlobalDB().ExecContext(s.ctx, "UPDATE phone_numbers SET stream_app_pk = 4242 WHERE e164 = ?", theApps) + s.Require().NoError(err) + + out, err := s.move(s.ready(), "--apply", "--app", "4242") + + s.Require().NoError(err) + s.Equal(theApps+"\tapp 4242\tmoved\n1 moved, 0 to move, 0 already moved, 0 with no stored bridge\n", out) + s.Equal(moveTestOldURL, s.twilio.voiceURL(deployments)) +} + +// Without what the webhook needs to answer, nothing is moved and Twilio is asked nothing, so no +// number is pointed at a webhook that would refuse its calls. +func (s *PhoneMoveSuite) TestARouterThatCouldNotAnswerTheWebhookMovesNothing() { + ready := s.ready() + for name, test := range map[string]struct { + settings moverSettings + refusal string + }{ + "no webhook token": {settings: ready.with(func(m *moverSettings) { m.token = "" }), refusal: "TWILIO_WEBHOOK_AUTH_TOKEN"}, + "no public URL": {settings: ready.with(func(m *moverSettings) { m.publicURL = "" }), refusal: "ROUTER_PUBLIC_URL"}, + "a plain http URL": {settings: ready.with(func(m *moverSettings) { m.publicURL = "http://router.example.test" }), refusal: "https"}, + "no account SID": {settings: ready.with(func(m *moverSettings) { m.account = "" }), refusal: "TWILIO_ACCOUNT_SID"}, + "no keyring": {settings: ready.with(func(m *moverSettings) { m.sealed = false }), refusal: "stored trunk"}, + } { + s.Run(name, func() { + s.releaseAll() + kept := s.attachedWithNoStoredBridge() + number := s.attachedEarlier() + + out, err := s.move(test.settings, "--apply") + + s.ErrorContains(err, test.refusal) + s.NotContains(out, kept, "refused before any number was read") + s.Empty(s.twilio.asked(), "twilio was asked nothing") + s.Equal(moveTestOldURL, s.twilio.voiceURL(number)) + }) + } +} + +// A Telnyx number is not listed, and Telnyx is asked nothing; the service refuses to move a +// vendor whose numbers do not ask the router's webhook. +func (s *PhoneMoveSuite) TestATelnyxNumberIsNeverTouched() { + twilioNumber := s.attachedEarlier() + telnyxNumber := moveTestNumber() + s.telnyx.hold(telnyxNumber) + s.hold(telnyxNumber, "telnyx") + s.Require().NoError(s.store.PhoneNumbers.Attach(s.ctx, s.customer, telnyxNumber, + store.NumberAttachment{TrunkID: "telnyx-trunk-" + uuid.NewString(), CallType: "default"})) + + out, err := s.move(s.ready(), "--apply") + + s.Require().NoError(err) + s.Contains(out, twilioNumber+"\tapp deployment\tmoved\n") + s.NotContains(out, telnyxNumber) + s.Empty(s.telnyx.asked()) + + err = s.service(s.ready()).MoveToCallHook(s.ctx, phone.CallHookMove{Vendor: "telnyx", Apply: true}, + func(phone.MovedNumber) { s.Fail("a telnyx number was reported") }) + s.ErrorIs(err, phone.ErrInvalid) + s.Empty(s.telnyx.asked()) +} + +// A number or an app written wrong is refused before anything is read. +func (s *PhoneMoveSuite) TestAFlagWrittenWrongIsRefused() { + s.attachedEarlier() + for name, args := range map[string][]string{ + "a number not in E.164": {"--one", "15125551234"}, + "an app that is not an id": {"--app", "my-app"}, + "an app id of zero": {"--app", "0"}, + "an unknown flag": {"--dry"}, + } { + s.Run(name, func() { + out, err := s.move(s.ready(), append([]string{"--apply"}, args...)...) + + s.Error(err) + s.Empty(out) + s.Empty(s.twilio.asked()) + }) + } +} + +// Attaching a number attached earlier again points it at the webhook, so an app can move a +// number itself; attaching it once more writes nothing. +func (s *PhoneMoveSuite) TestAttachingANumberAttachedEarlierAgainMovesIt() { + number := s.attachedEarlier() + + _, err := s.service(s.ready()).Attach(s.ctx, phone.Attachment{CustomerID: s.customer, E164: number}) + + s.Require().NoError(err) + s.Equal(moveTestHookURL, s.twilio.voiceURL(number)) + s.Len(s.twilio.posted(), 1) + + _, err = s.service(s.ready()).Attach(s.ctx, phone.Attachment{CustomerID: s.customer, E164: number}) + + s.Require().NoError(err) + s.Len(s.twilio.posted(), 1, "a number on the webhook is not written again") +} + +// A run stops at the first number it could not move, naming it, and moves none after it: a +// password the keyring does not open, a number Twilio does not hold, an update Twilio refused. +func (s *PhoneMoveSuite) TestARunStopsAtTheFirstNumberItCouldNotMove() { + for name, test := range map[string]struct { + breakNumber func(number string) moverSettings + failure string + dryRun bool + }{ + "a password the keyring does not open": {breakNumber: func(string) moverSettings { + return s.ready().with(func(m *moverSettings) { m.kek = "another key" }) + }, failure: "open the trunk password"}, + "a number twilio does not hold": {breakNumber: func(number string) moverSettings { + s.twilio.release(number) + return s.ready() + }, failure: "not one of this account's numbers"}, + "an update twilio refused": {breakNumber: func(number string) moverSettings { + s.twilio.refuse(number) + return s.ready() + }, failure: "500"}, + "a number twilio does not hold, in a dry run": {breakNumber: func(number string) moverSettings { + s.twilio.release(number) + return s.ready() + }, failure: "not one of this account's numbers", dryRun: true}, + } { + s.Run(name, func() { + s.releaseAll() + broken, after := s.attachedEarlier(), s.attachedEarlier() + settings := test.breakNumber(broken) + args := []string{"--apply"} + if test.dryRun { + args = nil + } + + _, err := s.move(settings, args...) + + s.ErrorContains(err, test.failure) + s.ErrorContains(err, broken) + s.Equal(moveTestOldURL, s.twilio.voiceURL(after), "no number after it was moved") + }) + } +} + +// Attaching an attached number again with the router unable to answer the webhook neither asks +// Twilio nor logs; a move that fails is logged, and the attach still answers. +func (s *PhoneMoveSuite) TestAttachingAgainNeverFailsOverTheMove() { + number := s.attachedEarlier() + var logs bytes.Buffer + unready := s.ready().with(func(m *moverSettings) { m.token, m.logs = "", &logs }) + + _, err := s.service(unready).Attach(s.ctx, phone.Attachment{CustomerID: s.customer, E164: number}) + + s.Require().NoError(err) + s.Empty(s.twilio.asked()) + s.Empty(logs.String()) + + s.twilio.refuse(number) + _, err = s.service(s.ready().with(func(m *moverSettings) { m.logs = &logs })). + Attach(s.ctx, phone.Attachment{CustomerID: s.customer, E164: number}) + + s.Require().NoError(err) + s.Contains(logs.String(), "could not point an attached number at the router's call webhook") + s.Equal(moveTestOldURL, s.twilio.voiceURL(number)) +} + +// A run whose attached numbers cannot be read fails saying so, rather than reporting none to move. +func (s *PhoneMoveSuite) TestARunWhoseNumbersCannotBeReadFails() { + s.attachedEarlier() + settings := config.Defaults() + settings.Postgres.DSN = testenv.Database(os.Getenv("ROUTER_POSTGRES_DSN"), "phone_move") + closed, err := openStore(s.ctx, settings) + s.Require().NoError(err) + s.Require().NoError(closed.Close()) + + var out bytes.Buffer + err = moveTwilioNumbers(s.ctx, []string{"--apply"}, s.serviceOn(closed, s.ready()), &out) + + s.ErrorContains(err, "attached numbers") + s.Empty(s.twilio.asked()) +} + +// Attaching an attached number again answers within a short deadline when Twilio never answers +// the move, and the number stays attached. +func (s *PhoneMoveSuite) TestAttachingAgainAnswersWhenTwilioNeverDoes() { + number := s.attachedEarlier() + s.twilio.hanging.Store(true) + var logs bytes.Buffer + service := s.service(s.ready().with(func(m *moverSettings) { m.logs = &logs })) + + start := time.Now() + attached, err := service.Attach(s.ctx, phone.Attachment{CustomerID: s.customer, E164: number}) + + s.Require().NoError(err) + s.Less(time.Since(start), 15*time.Second, "the attach waited on Twilio's client timeout") + s.NotEmpty(attached.TrunkID) + s.Contains(logs.String(), "could not point an attached number at the router's call webhook") + held, err := s.store.PhoneNumbers.GetByE164(s.ctx, s.customer, number) + s.Require().NoError(err) + s.NotNil(held.AttachedAt) +} + +// The command is built from the router's config: without a keyring it refuses, and with one it +// gets as far as the public URL, which this config lacks. +func (s *PhoneMoveSuite) TestTheCommandRunsTheChecksOnTheRoutersConfig() { + settings := config.Defaults() + settings.Postgres.DSN = testenv.Database(os.Getenv("ROUTER_POSTGRES_DSN"), "phone_move") + settings.PublicURL = "" + s.T().Setenv("TWILIO_ACCOUNT_SID", "AC"+strings.Repeat("0", 32)) + s.T().Setenv("TWILIO_AUTH_TOKEN", "api-secret") + s.T().Setenv("TWILIO_WEBHOOK_AUTH_TOKEN", s.token) + s.T().Setenv(devKEKEnvVar, "") + + err := dispatchCommand("phone", []string{"move-twilio"}, settings, slog.New(slog.DiscardHandler)) + s.ErrorContains(err, "stored trunk") + + s.T().Setenv(devKEKEnvVar, moveTestKEK) + err = dispatchCommand("phone", []string{"move-twilio"}, settings, slog.New(slog.DiscardHandler)) + s.ErrorContains(err, "ROUTER_PUBLIC_URL") + + s.ErrorContains(dispatchCommand("phone", nil, settings, nil), "move-twilio") + s.ErrorContains(dispatchCommand("phone", []string{"move"}, settings, nil), `unknown phone command "move"`) +} + +// releaseAll gives back every number an earlier test or subtest left held. +func (s *PhoneMoveSuite) releaseAll() { + _, err := s.store.GlobalDB().ExecContext(s.ctx, "UPDATE phone_numbers SET released_at = now() WHERE released_at IS NULL") + s.Require().NoError(err) +} + +// move runs router phone move-twilio with args on a service with settings. +func (s *PhoneMoveSuite) move(settings moverSettings, args ...string) (string, error) { + var out bytes.Buffer + err := moveTwilioNumbers(s.ctx, args, s.service(settings), &out) + return out.String(), err +} + +// moverSettings are what a deployment has for its Twilio numbers. +type moverSettings struct { + token, account, publicURL string + // sealed is a deployment with a keyring, of kek. + sealed bool + kek string + // logs, when set, is where the service logs. + logs *bytes.Buffer +} + +func (s *PhoneMoveSuite) ready() moverSettings { + return moverSettings{ + token: s.token, account: "AC" + strings.Repeat("0", 32), publicURL: moveTestPublicURL, sealed: true, kek: moveTestKEK, + } +} + +// with is the settings with change made to a copy. +func (m moverSettings) with(change func(*moverSettings)) moverSettings { + change(&m) + return m +} + +// service is a phone service with Twilio and Telnyx at the suite's fakes and the settings given. +func (s *PhoneMoveSuite) service(settings moverSettings) *phone.Service { + return s.serviceOn(s.store, settings) +} + +// serviceOn is service on the store given. +func (s *PhoneMoveSuite) serviceOn(db *store.Store, settings moverSettings) *phone.Service { + vendorConfig, err := phone.DefaultConfig() + s.Require().NoError(err) + for i := range vendorConfig.Vendors { + vendorConfig.Vendors[i].Credentials = nil + } + registry := vendors.Registry(vendorConfig) + registry.Register("twilio", func() (phone.Provider, error) { + return twilio.New(twilio.Options{ + AccountSID: settings.account, AuthToken: "api-secret", WebhookAuthToken: settings.token, BaseURL: s.twilio.URL, + }) + }) + registry.Register("telnyx", func() (phone.Provider, error) { + return telnyx.New(telnyx.Options{APIKey: "k", ConnectionID: "texml-1", BaseURL: s.telnyx.URL}) + }) + var sealer *auth.Sealer + if settings.sealed { + sealer, err = auth.NewSealer(settings.kek) + s.Require().NoError(err) + } + logger := slog.New(slog.DiscardHandler) + if settings.logs != nil { + logger = slog.New(slog.NewTextHandler(settings.logs, &slog.HandlerOptions{Level: slog.LevelError})) + } + service, err := phone.NewService(phone.ServiceOptions{ + Registry: registry, Store: db, Stream: phone.NewStreamFromClient(s.chat.Client), Sealer: sealer, + PublicURL: settings.publicURL, Logger: logger, + }) + s.Require().NoError(err) + return service +} + +// attachedEarlier is a Twilio number attached as the router attaches one, then left on the voice +// URL a number attached before the webhook has, with what Twilio was asked forgotten. +func (s *PhoneMoveSuite) attachedEarlier() string { + number := moveTestNumber() + s.twilio.hold(number) + s.hold(number, "twilio") + _, err := s.service(s.ready()).Attach(s.ctx, phone.Attachment{CustomerID: s.customer, E164: number}) + s.Require().NoError(err) + s.twilio.point(number, moveTestOldURL, http.MethodGet) + s.twilio.forget() + return number +} + +// attachedWithNoStoredBridge is a Twilio number attached with no trunk credentials kept, as one +// that arrived by a data move is. +func (s *PhoneMoveSuite) attachedWithNoStoredBridge() string { + number := moveTestNumber() + s.twilio.hold(number) + s.twilio.point(number, moveTestOldURL, http.MethodGet) + s.hold(number, "twilio") + s.Require().NoError(s.store.PhoneNumbers.Attach(s.ctx, s.customer, number, + store.NumberAttachment{TrunkID: "moved-trunk-" + uuid.NewString(), CallType: "default"})) + return number +} + +// hold records the number as the suite's customer's, bought from vendor. +func (s *PhoneMoveSuite) hold(e164, vendor string) { + s.Require().NoError(s.store.PhoneNumbers.Insert(s.ctx, &store.PhoneNumber{ + E164: e164, Vendor: vendor, Country: "US", CustomerID: s.customer, PurchasedAt: time.Now().UTC(), + })) +} + +// moveTestNumber is a US number of its own for one test. +func moveTestNumber() string { + digits, err := rand.Int(rand.Reader, big.NewInt(10_000_000)) + if err != nil { + panic(err) + } + return fmt.Sprintf("+1555%07d", digits.Int64()) +} + +// fakeTwilio is Twilio's numbers API for the numbers it holds: a list read by PhoneNumber that +// answers each number's voice URL and method, and an update that sets them, as Twilio's does. +// Telnyx's tests use it only to record that nothing was asked. +type fakeTwilio struct { + *httptest.Server + mu sync.Mutex + numbers map[string]*fakeTwilioNumber + requests []string + forms []url.Values + // hanging holds every request until its caller gives up. + hanging atomic.Bool +} + +type fakeTwilioNumber struct { + sid, voiceURL, voiceMethod string + // refused answers its updates 500, and gone leaves it out of the list. + refused, gone bool +} + +func newFakeTwilio(t *testing.T) *fakeTwilio { + fake := &fakeTwilio{numbers: map[string]*fakeTwilioNumber{}} + fake.Server = httptest.NewServer(http.HandlerFunc(fake.serve)) + t.Cleanup(fake.Close) + return fake +} + +func (f *fakeTwilio) serve(w http.ResponseWriter, r *http.Request) { + if f.hanging.Load() { + <-r.Context().Done() + return + } + _ = r.ParseForm() + f.mu.Lock() + defer f.mu.Unlock() + f.requests = append(f.requests, r.Method+" "+r.URL.RequestURI()) + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/IncomingPhoneNumbers.json"): + listed := []map[string]string{} + if number, ok := f.numbers[r.URL.Query().Get("PhoneNumber")]; ok && !number.gone { + listed = append(listed, map[string]string{ + "sid": number.sid, "phone_number": r.URL.Query().Get("PhoneNumber"), + "voice_url": number.voiceURL, "voice_method": number.voiceMethod, + }) + } + _ = json.NewEncoder(w).Encode(map[string]any{"incoming_phone_numbers": listed}) + case r.Method == http.MethodPost && strings.Contains(r.URL.Path, "/IncomingPhoneNumbers/"): + f.forms = append(f.forms, r.PostForm) + for _, number := range f.numbers { + if strings.HasSuffix(r.URL.Path, "/"+number.sid+".json") { + if number.refused { + w.WriteHeader(http.StatusInternalServerError) + return + } + number.voiceURL, number.voiceMethod = r.PostForm.Get("VoiceUrl"), r.PostForm.Get("VoiceMethod") + _ = json.NewEncoder(w).Encode(map[string]string{"sid": number.sid}) + return + } + } + w.WriteHeader(http.StatusNotFound) + default: + w.WriteHeader(http.StatusNotFound) + } +} + +// hold makes the number one the account holds. +func (f *fakeTwilio) hold(e164 string) { + f.mu.Lock() + defer f.mu.Unlock() + f.numbers[e164] = &fakeTwilioNumber{sid: "PN" + strings.ToLower(rand.Text())} +} + +// point sets the number's voice URL and method, as a change at Twilio would. +func (f *fakeTwilio) point(e164, voiceURL, method string) { + f.mu.Lock() + defer f.mu.Unlock() + f.numbers[e164].voiceURL, f.numbers[e164].voiceMethod = voiceURL, method +} + +// release makes the account no longer hold the number, keeping its voice URL to read. +func (f *fakeTwilio) release(e164 string) { + f.mu.Lock() + defer f.mu.Unlock() + f.numbers[e164].gone = true +} + +// refuse makes Twilio answer the number's updates 500. +func (f *fakeTwilio) refuse(e164 string) { + f.mu.Lock() + defer f.mu.Unlock() + f.numbers[e164].refused = true +} + +func (f *fakeTwilio) voiceURL(e164 string) string { + f.mu.Lock() + defer f.mu.Unlock() + return f.numbers[e164].voiceURL +} + +// forget drops what the fake was asked so far. +func (f *fakeTwilio) forget() { + f.mu.Lock() + defer f.mu.Unlock() + f.requests, f.forms = nil, nil +} + +// asked is every request, as method, path and query. +func (f *fakeTwilio) asked() []string { + f.mu.Lock() + defer f.mu.Unlock() + return append([]string(nil), f.requests...) +} + +// posted is the form of every update. +func (f *fakeTwilio) posted() []url.Values { + f.mu.Lock() + defer f.mu.Unlock() + return append([]url.Values(nil), f.forms...) +} diff --git a/acceleration/internal/phone/callhookmove.go b/acceleration/internal/phone/callhookmove.go new file mode 100644 index 0000000000..881fe0d1bc --- /dev/null +++ b/acceleration/internal/phone/callhookmove.go @@ -0,0 +1,126 @@ +package phone + +import ( + "context" + "errors" + "fmt" + + "github.com/GetStream/Vision-Agents/acceleration/internal/stack" + "github.com/GetStream/Vision-Agents/acceleration/internal/store" +) + +// Move is what MoveToCallHook did, or would do, with one number. +type Move string + +const ( + // Moved is a number now pointed at the router's call webhook. + Moved Move = "moved" + // WouldMove is a number a run with Apply points at the router's call webhook. + WouldMove Move = "would move" + // AlreadyMoved is a number already pointed at the router's call webhook, left as it is. + AlreadyMoved Move = "already moved" + // NoStoredBridge is a number whose trunk credentials were not kept, left as it is: the + // webhook would hang up its calls. Detaching and attaching it again keeps them. + NoStoredBridge Move = "no stored bridge, needs a re-attach" +) + +// MovedNumber is one number MoveToCallHook went through. +type MovedNumber struct { + E164 string + // App is the Stream app the number is lined in. Zero is the deployment's own. + App int64 + Move Move +} + +// CallHookMove picks the numbers MoveToCallHook points at the router's call webhook. +type CallHookMove struct { + Vendor string + // App, when set, keeps the numbers made in that Stream app. Zero is the deployment's own. + App *int64 + // E164, when set, keeps that one number. + E164 string + // Apply writes at the vendor. Without it nothing is written there, and each number is + // reported with what a run with it would do. + Apply bool +} + +// callHookMovePage is how many numbers MoveToCallHook reads from the store at a time. +const callHookMovePage = 100 + +// MoveToCallHook points the attached numbers of a vendor whose numbers ask the router's call +// webhook (CallHooked) at that webhook, as Attach does for a number it attaches, and reports +// each number as it goes. It refuses before anything is read at the vendor when the router +// could not answer the webhook. Running it again moves nothing already moved. It stops at the +// first number it could not read or move. +func (s *Service) MoveToCallHook(ctx context.Context, move CallHookMove, report func(MovedNumber)) error { + if s.store == nil { + return stack.Wrap(errors.New("phone: moving numbers needs a database to know which are attached")) + } + if s.sealer == nil { + return stack.Wrap(fmt.Errorf("phone: %s numbers are answered with their stored trunk: %w", move.Vendor, ErrNoSealer)) + } + provider, err := s.registry.Open(move.Vendor) + if err != nil { + return stack.Wrap(err) + } + hooked, ok := provider.(CallHooked) + if !ok { + return stack.Wrap(Invalid(fmt.Errorf("phone: %s numbers do not ask a webhook of the router's", move.Vendor))) + } + if err := hooked.CallHookReady(s.publicURL); err != nil { + return err + } + + filter := store.AttachedFilter{Vendor: move.Vendor, App: move.App, E164: move.E164, Limit: callHookMovePage} + for { + numbers, err := s.store.PhoneNumbers.Attached(ctx, filter) + if err != nil { + return err + } + for _, number := range numbers { + moved, err := s.moveToCallHook(ctx, provider, hooked, number, move.Apply) + if err != nil { + return fmt.Errorf("phone: move %s: %w", number.E164, err) + } + report(MovedNumber{E164: number.E164, App: number.StreamAppPK, Move: moved}) + } + if len(numbers) < filter.Limit { + return nil + } + filter.After = numbers[len(numbers)-1].ID + } +} + +// moveToCallHook points one attached number at the router's call webhook, unless it is there +// already, or its trunk was not kept for the webhook to answer with, or apply is false. +func (s *Service) moveToCallHook(ctx context.Context, provider Provider, hooked CallHooked, number store.PhoneNumber, + apply bool) (Move, error) { + stored, err := s.store.PhoneNumbers.AttachedBridge(ctx, number.Vendor, number.E164) + if errors.Is(err, store.ErrNoStoredBridge) { + return NoStoredBridge, nil + } + if err != nil { + return "", err + } + // Opened here as the webhook opens it, so a number is not moved to answer calls with a + // password that does not open. + bridge, err := s.openBridge(stored, number.E164) + if err != nil { + return "", err + } + on, err := hooked.OnCallHook(ctx, number.E164, s.publicURL) + if err != nil { + return "", err + } + if on { + return AlreadyMoved, nil + } + if !apply { + return WouldMove, nil + } + err = provider.ConfigureInbound(ctx, Inbound{E164: number.E164, Bridge: bridge, PublicURL: s.publicURL}) + if err != nil { + return "", stack.Wrap(err) + } + return Moved, nil +} diff --git a/acceleration/internal/phone/phone.go b/acceleration/internal/phone/phone.go index 463d6e40a7..b27f9d60ca 100644 --- a/acceleration/internal/phone/phone.go +++ b/acceleration/internal/phone/phone.go @@ -496,6 +496,9 @@ type CallHooked interface { // CallHookReady reports which setting the router lacks to answer the vendor's call webhook // at publicURL, or nil when it lacks none. CallHookReady(publicURL string) error + // OnCallHook reports whether the number already asks the router's call webhook at + // publicURL, and so needs no moving. + OnCallHook(ctx context.Context, e164, publicURL string) (bool, error) } // NumberFinder is a vendor that can say whether its account holds a number, which settles a diff --git a/acceleration/internal/phone/service.go b/acceleration/internal/phone/service.go index 99e3473c09..8d2ba5ee13 100644 --- a/acceleration/internal/phone/service.go +++ b/acceleration/internal/phone/service.go @@ -960,11 +960,18 @@ var ErrNoSealer = errors.New("phone: no key to seal a number's trunk password: s // fetches on answer, so a call on that vendor cannot be placed. var ErrNoSealerToCall = errors.New("phone: no key to seal the trunk password the vendor fetches on answer, so the call cannot be placed: set ROUTER_DEV_KEK (local), or ROUTER_AUTH_KEK_V1_WRAPPED with ROUTER_AUTH_KMS_KEY (hosted)") +// reattachMoveTimeout bounds the move of an attached number's voice URL that an attach of it +// makes. Programs send that attach on every start, and the move is up to three vendor +// requests. A vendor answers each in well under a second, so five seconds is a vendor that is +// down or hung, not a slow one; the move is tried again at the next attach. +const reattachMoveTimeout = 5 * time.Second + // Attach puts a number on the trunk it shares with the customer's other numbers of its // vendor, with a rule of its own, and tells the vendor to send calls there. This is what // turns a bought number into one that reaches an agent. Without a key to seal the trunk's // password, the number gets a trunk of its own. Attaching a number already attached in this -// app changes nothing and answers what it has. +// app creates nothing and answers what it has; a Twilio number still on its old voice URL is +// pointed at the router's call webhook. func (s *Service) Attach(ctx context.Context, attachment Attachment) (Attached, error) { if s.store == nil { return Attached{}, stack.Wrap(errors.New("phone: attaching a number needs a database to know who holds it")) @@ -1027,6 +1034,17 @@ func (s *Service) Attach(ctx context.Context, attachment Attachment) (Attached, if err != nil { return Attached{}, err } + // A number attached before its vendor asked the router's webhook is pointed there now, + // when the router can answer it. A running line is not refused over a move that failed. + if hooked, ok := provider.(CallHooked); ok && hooked.CallHookReady(s.publicURL) == nil { + moveCtx, cancel := context.WithTimeout(ctx, reattachMoveTimeout) + _, err := s.moveToCallHook(moveCtx, provider, hooked, held, true) + cancel() + if err != nil { + s.logger.Error("could not point an attached number at the router's call webhook", + "customer", held.CustomerID, "vendor", held.Vendor, "error", err) + } + } return attached, nil } if err := s.clearLinesFor(ctx, held, pin); err != nil { @@ -1182,6 +1200,11 @@ func (s *Service) InboundBridge(ctx context.Context, vendor, e164 string) (Bridg if err := s.gate.Admit(ctx, stored.CustomerID); err != nil { return Bridge{}, err } + return s.openBridge(stored, e164) +} + +// openBridge is the stored trunk of the number e164 with its password opened. +func (s *Service) openBridge(stored store.AttachedBridge, e164 string) (Bridge, error) { aad := trunkAAD(stored.CustomerID, stored.TrunkID) if stored.Own { aad = bridgeAAD(stored.CustomerID, e164) diff --git a/acceleration/internal/phone/twilio/twilio.go b/acceleration/internal/phone/twilio/twilio.go index 88bd35c05c..fb38b56095 100644 --- a/acceleration/internal/phone/twilio/twilio.go +++ b/acceleration/internal/phone/twilio/twilio.go @@ -382,6 +382,23 @@ func (p *Provider) CallHookReady(publicURL string) error { return err } +// OnCallHook reports whether the number's voice URL is already the router's call webhook on +// publicURL, asked by POST, so moving it again would change nothing. +func (p *Provider) OnCallHook(ctx context.Context, e164, publicURL string) (bool, error) { + hook, err := p.callHook(publicURL) + if err != nil { + return false, err + } + number, held, err := p.incoming(ctx, e164) + if err != nil { + return false, err + } + if !held { + return false, stack.Wrap(fmt.Errorf("twilio: %s is not one of this account's numbers", e164)) + } + return number.VoiceURL == hook && number.VoiceMethod == http.MethodPost, nil +} + // callHook is the router's Twilio call webhook on publicURL. It is only given when the router // checks the webhook's signature, and publicURL is a bare https address: a query or a // fragment would reach Twilio as part of the URL, and a user would put a credential in it. @@ -576,22 +593,28 @@ func (p *Provider) sidFor(ctx context.Context, e164 string) (string, error) { // 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) { + number, held, err := p.incoming(ctx, e164) + return number.SID, held, err +} + +// incoming is the account's number e164, and whether the account holds it. +func (p *Provider) incoming(ctx context.Context, e164 string) (incomingNumber, bool, error) { if e164 == "" { - return "", false, stack.Wrap(errors.New("twilio: a number is required")) + return incomingNumber{}, 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 "", false, err + return incomingNumber{}, false, err } for _, number := range owned.IncomingPhoneNumbers { if number.PhoneNumber == e164 { - return number.SID, true, nil + return number, true, nil } } - return "", false, nil + return incomingNumber{}, false, nil } func (p *Provider) get(ctx context.Context, path string, query url.Values, into any) error { @@ -758,6 +781,10 @@ type incomingNumber struct { // Twilio does not quote a price on the number itself, so this is only set when a // deployment's account exposes one. MonthlyPrice string `json:"monthly_price"` + // VoiceURL and VoiceMethod are where and how Twilio asks what to do with a call to the + // number (https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource). + VoiceURL string `json:"voice_url"` + VoiceMethod string `json:"voice_method"` } type incomingNumbers struct { diff --git a/acceleration/internal/phone/twilio/twilio_test.go b/acceleration/internal/phone/twilio/twilio_test.go index 1781feba0c..897ff13b54 100644 --- a/acceleration/internal/phone/twilio/twilio_test.go +++ b/acceleration/internal/phone/twilio/twilio_test.go @@ -1130,3 +1130,41 @@ func (s *TwilioSuite) TestACallThatEndedOnItsOwnIsNotCompletedAgain() { s.Len(*forms, 1) } + +// A number is on the call webhook only when Twilio asks the router's hook URL by POST; a number +// the account does not hold is an error, and without the webhook token Twilio is asked nothing. +func (s *TwilioSuite) TestANumberIsOnTheCallHookOnlyAtTheHookURLByPost() { + for name, test := range map[string]struct { + listed string + on bool + }{ + "the hook by POST": {listed: `{"sid":"PN1","phone_number":"+15125551234","voice_url":"https://router.example.test/v1/phone/hooks/twilio","voice_method":"POST"}`, on: true}, + "the hook by GET": {listed: `{"sid":"PN1","phone_number":"+15125551234","voice_url":"https://router.example.test/v1/phone/hooks/twilio","voice_method":"GET"}`}, + "another router": {listed: `{"sid":"PN1","phone_number":"+15125551234","voice_url":"https://other.example.test/v1/phone/hooks/twilio","voice_method":"POST"}`}, + "the echo URL": {listed: `{"sid":"PN1","phone_number":"+15125551234","voice_url":"https://twimlets.com/echo?Twiml=x","voice_method":"GET"}`}, + "no voice URL": {listed: `{"sid":"PN1","phone_number":"+15125551234","voice_url":"","voice_method":"POST"}`}, + } { + s.Run(name, func() { + s.respond = func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(`{"incoming_phone_numbers":[` + test.listed + `]}`)) + } + + on, err := s.provider.OnCallHook(s.ctx, "+15125551234", "https://router.example.test/") + + s.Require().NoError(err) + s.Equal(test.on, on) + s.Equal("+15125551234", s.seen.query.Get("PhoneNumber")) + }) + } + + s.respond = func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(`{"incoming_phone_numbers":[]}`)) } + _, err := s.provider.OnCallHook(s.ctx, "+15125551234", "https://router.example.test") + s.ErrorContains(err, "not one of this account's numbers") + + unsigned, err := New(Options{AccountSID: "AC123", AuthToken: "secret", BaseURL: s.server.URL}) + s.Require().NoError(err) + s.seen = request{} + _, err = unsigned.OnCallHook(s.ctx, "+15125551234", "https://router.example.test") + s.ErrorIs(err, phone.ErrNotConfigured) + s.Empty(s.seen.path, "twilio was not asked anything") +} diff --git a/acceleration/internal/store/phone_number.go b/acceleration/internal/store/phone_number.go index e6a08589ce..b5163dfd41 100644 --- a/acceleration/internal/store/phone_number.go +++ b/acceleration/internal/store/phone_number.go @@ -322,6 +322,43 @@ func (r *PhoneNumbers) AttachedBridge(ctx context.Context, vendor, e164 string) return AttachedBridge(bridge), nil } +// AttachedFilter picks the attached numbers of one vendor, every customer's, a page at a time. +type AttachedFilter struct { + Vendor string + // App, when set, keeps the numbers made in that Stream app. Zero is the deployment's own. + App *int64 + // E164, when set, keeps that one number. + E164 string + // After is the id of the last number of the page before. Zero starts at the first. + After int64 + Limit int +} + +// Attached returns the attached numbers of a vendor that are held now, every customer's, by id. +func (r *PhoneNumbers) Attached(ctx context.Context, filter AttachedFilter) ([]PhoneNumber, error) { + if filter.Vendor == "" || filter.Limit <= 0 { + return nil, stack.Wrap(errors.New("store: a vendor and a page size are required")) + } + query := r.store.global.NewSelect().Model((*PhoneNumber)(nil)). + Where("vendor = ?", filter.Vendor). + Where("released_at IS NULL"). + Where("attached_at IS NOT NULL"). + Where("id > ?", filter.After). + Order("id"). + Limit(filter.Limit) + if filter.App != nil { + query = query.ApplyQueryBuilder(r.store.pinnedTo(*filter.App).where) + } + if filter.E164 != "" { + query = query.Where("e164 = ?", filter.E164) + } + var numbers []PhoneNumber + if err := query.Scan(ctx, &numbers); err != nil { + return nil, stack.Wrap(fmt.Errorf("store: attached numbers: %w", err)) + } + return numbers, nil +} + // Select returns the numbers a customer holds, newest first. func (r *PhoneNumbers) Select(ctx context.Context, customerID string, filter PhoneNumberFilter) ([]PhoneNumber, error) { if customerID == "" { diff --git a/acceleration/internal/store/phone_number_test.go b/acceleration/internal/store/phone_number_test.go index cdf54bf713..a61d855e1d 100644 --- a/acceleration/internal/store/phone_number_test.go +++ b/acceleration/internal/store/phone_number_test.go @@ -339,3 +339,50 @@ func customersHolding(numbers []PhoneNumber) []string { } return customers } + +// Attached lists the attached numbers of one vendor that are held now, every customer's, by id, +// a page at a time, kept to one app or one number when asked. +func (s *StoreSuite) TestAttachedListsTheHeldAttachedNumbersOfOneVendorAPageAtATime() { + add := func(customer, e164, vendor string, app int64, attached bool) { + s.Require().NoError(s.store.PhoneNumbers.Insert(s.ctx, &PhoneNumber{ + E164: e164, Vendor: vendor, Country: "US", CustomerID: customer, PurchasedAt: s.base, + })) + if attached { + s.Require().NoError(s.store.PhoneNumbers.Attach(s.ctx, customer, e164, + NumberAttachment{TrunkID: "trunk-" + e164, StreamAppPK: app, CallType: "default"})) + } + } + add("acme", "+15125550001", "twilio", 0, true) + add("globex", "+15125550002", "twilio", 7, true) + add("acme", "+15125550003", "twilio", 0, false) + add("acme", "+15125550004", "telnyx", 0, true) + add("acme", "+15125550005", "twilio", 0, true) + s.Require().NoError(giveBack(s.ctx, s.store, "acme", "+15125550005", s.base)) + add("acme", "+15125550006", "twilio", 7, true) + + listed := func(filter AttachedFilter) []string { + numbers, err := s.store.PhoneNumbers.Attached(s.ctx, filter) + s.Require().NoError(err) + var e164s []string + for _, number := range numbers { + e164s = append(e164s, number.E164) + } + return e164s + } + s.Equal([]string{"+15125550001", "+15125550002", "+15125550006"}, listed(AttachedFilter{Vendor: "twilio", Limit: 10})) + + first, err := s.store.PhoneNumbers.Attached(s.ctx, AttachedFilter{Vendor: "twilio", Limit: 2}) + s.Require().NoError(err) + s.Require().Len(first, 2) + s.Equal([]string{"+15125550006"}, listed(AttachedFilter{Vendor: "twilio", After: first[1].ID, Limit: 2})) + + app, deployment := int64(7), int64(0) + s.Equal([]string{"+15125550002", "+15125550006"}, listed(AttachedFilter{Vendor: "twilio", App: &app, Limit: 10})) + s.Equal([]string{"+15125550001"}, listed(AttachedFilter{Vendor: "twilio", App: &deployment, Limit: 10})) + s.Equal([]string{"+15125550002"}, listed(AttachedFilter{Vendor: "twilio", E164: "+15125550002", Limit: 10})) + + _, err = s.store.PhoneNumbers.Attached(s.ctx, AttachedFilter{Limit: 10}) + s.Error(err, "a vendor is required") + _, err = s.store.PhoneNumbers.Attached(s.ctx, AttachedFilter{Vendor: "twilio"}) + s.Error(err, "a page size is required") +}