diff --git a/CHANGELOG.md b/CHANGELOG.md index 38920b023f..84bb3cb5f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -865,6 +865,10 @@ Only a built-in connector takes the OAuth client the deployment keeps in its env `POST /v1/data/import` and change replays run each row's own validation before writing it, so an import is refused with a 400 naming the field where the API would refuse the same row: a campaign's concurrency above 50 or a config's sandbox over its CPU, memory or disk bounds, among the rest. A moved voice arrives with its id, name and description and without its samples or bindings, whose audio and clone stay with the deployment that made them: add a recording and prepare it again. An import that names `voice_samples` or `voice_bindings` is refused. An imported request is never billable here and counts against the importing app's organization: the one it was last seen under here, else the one it is registered under, else none. +### Only a number on the customer's own trunk moves in an import + +`/v1/data/import`, and a change applied after it, writes a `phone_numbers` row only when its vendor is exactly `sip_trunk`; any other row is skipped without an error. A number bought at a vendor stays in the vendor account of the deployment that bought it, and its bills already move with the requests, so the destination neither holds it nor bills its months again. A customer that moves keeps a bought number by buying or porting it at the destination. A number bought here and still held is never updated or deleted by an imported row or a replayed change, whatever id it names. An imported `sip_trunk` number is held to the API's rules (E.164, a vendor, a cost that is not negative), and no imported number keeps its `dlc_use_case_id`, which names a use case of the source. + ### A customer can no longer list or speak in another customer's cloned voice Clones made through `/v1/agents/voices` sit in the deployment's shared provider account, which lists them all as its own. A voice id that another customer's voice was prepared as is now refused, whether it is the session's voice or the `voice_id` of TTS overwrites. The voice library lists only the caller's own clones besides the provider's published voices, previews another customer's clone as not found, and no longer suggests one as the closest voice. diff --git a/acceleration/README.md b/acceleration/README.md index 65fed124b9..340f8a0e1c 100644 --- a/acceleration/README.md +++ b/acceleration/README.md @@ -2780,9 +2780,11 @@ exported. A moved deployment mints its own keys and re-authorizes its plugin con Voice recordings live in the bucket rather than in Postgres, so their rows move and copying the bucket is the operator's. -A phone number still held moves only in E.164 form (`+15551234567`) and only while no other -app here holds it; one given back moves as written. A moved number arrives detached: its -trunk, route and call stay behind, so it is attached again where it arrives. +Only a phone number on the app's own SIP trunk (vendor `sip_trunk`) moves, in E.164 form +(`+15551234567`), and it arrives detached: its trunk, route, call and 10DLC use case stay +behind, so it is attached again where it arrives. A number bought at a vendor does not move, +held or given back; its bills move with the requests. The app keeps it by buying or porting +it where it moves to. Changes are captured by a trigger per table writing into `data_changes`, gated on a row in `data_change_capture`: with nobody moving, the hot path costs one index probe. Exporting diff --git a/acceleration/cmd/router/replicate_ids_integration_test.go b/acceleration/cmd/router/replicate_ids_integration_test.go index 9764fc2751..fb50d4901b 100644 --- a/acceleration/cmd/router/replicate_ids_integration_test.go +++ b/acceleration/cmd/router/replicate_ids_integration_test.go @@ -167,7 +167,7 @@ func (s *ReplicateIDsSuite) held(id int64) bool { // copiedNumber is a number of acme's as an export carries it, under the source's id, which // also makes its digits, so no two copied numbers are one. func copiedNumber(id int64) json.RawMessage { - return json.RawMessage(fmt.Sprintf(`{"id":%d,"e164":"+1555%07d","vendor":"telnyx","country":"US","customer_id":"acme",`+ + return json.RawMessage(fmt.Sprintf(`{"id":%d,"e164":"+1555%07d","vendor":"sip_trunk","country":"US","customer_id":"acme",`+ `"capabilities":["voice"],"monthly_cost_micros":0,"tags":{},"purchased_at":"2026-10-30T00:00:00Z"}`, id, id)) } diff --git a/acceleration/cmd/router/replicate_repeat_integration_test.go b/acceleration/cmd/router/replicate_repeat_integration_test.go index 7b23e860ea..c760b34e6d 100644 --- a/acceleration/cmd/router/replicate_repeat_integration_test.go +++ b/acceleration/cmd/router/replicate_repeat_integration_test.go @@ -154,7 +154,7 @@ func (s *ReplicateRepeatSuite) copiedBefore() { // recorded records a number of acme's at the source, its digits the number given. func (s *ReplicateRepeatSuite) recorded(digits int) { - number := &store.PhoneNumber{E164: e164(digits), Vendor: "telnyx", Country: "US", CustomerID: "acme"} + number := &store.PhoneNumber{E164: e164(digits), Vendor: "sip_trunk", Country: "US", CustomerID: "acme"} s.Require().NoError(s.source.PhoneNumbers.Insert(s.ctx, number)) } diff --git a/acceleration/internal/api/datamove_test.go b/acceleration/internal/api/datamove_test.go index 5dee33f6ca..7fe376d302 100644 --- a/acceleration/internal/api/datamove_test.go +++ b/acceleration/internal/api/datamove_test.go @@ -299,50 +299,47 @@ func (s *DataMoveSuite) TestChangesAreAppliedToAnAppThatHoldsData() { s.Equal("edited at the source", s.instructionsOf(agent.Id)) } -func (s *DataMoveSuite) TestAnImportCannotClaimAnotherAppsNumberInAnotherForm() { +func (s *DataMoveSuite) TestAnImportedBoughtNumberIsNotStored() { ctx := context.Background() other, e164 := s.utils.uuid(), s.utils.number() s.Require().NoError(s.store.PhoneNumbers.Insert(ctx, &store.PhoneNumber{ E164: e164, Vendor: "plivo", Country: "US", CustomerID: other, })) - // Plivo reads the number without its plus as the other app's. - variant := strings.TrimPrefix(e164, "+") - row, err := json.Marshal(map[string]any{ - "id": rand.Int64N(1 << 50), "e164": variant, "vendor": "plivo", "country": "US", - "capabilities": []string{"voice"}, "monthly_cost_micros": 0, "customer_id": other, - "tags": map[string]string{}, "purchased_at": time.Now().UTC(), - }) - s.Require().NoError(err) - status, failure := s.serverClient.failure(http.MethodPost, "/v1/data/import", - ndjson([]dataLine{{Table: "phone_numbers", Row: row}})) - s.Equal(http.StatusBadRequest, status) - s.Contains(failure, "E.164") + // The other app's number, as written and as Plivo reads it. + var lines []dataLine + for _, variant := range []string{e164, strings.TrimPrefix(e164, "+")} { + row, err := json.Marshal(map[string]any{ + "id": rand.Int64N(1 << 50), "e164": variant, "vendor": "plivo", "country": "US", + "capabilities": []string{"voice"}, "monthly_cost_micros": 0, "customer_id": other, + "tags": map[string]string{}, "purchased_at": time.Now().UTC(), + }) + s.Require().NoError(err) + lines = append(lines, dataLine{Table: "phone_numbers", Row: row}) + } + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPost, "/v1/data/import", ndjson(lines), nil)) - status, _ = s.serverClient.call(http.MethodDelete, "/v1/phone/numbers/"+variant, nil) + status, _ := s.serverClient.call(http.MethodDelete, "/v1/phone/numbers/"+e164, nil) s.Equal(http.StatusNotFound, status) + imported, err := s.store.PhoneNumbers.Select(ctx, s.customerID(), store.PhoneNumberFilter{IncludeReleased: true}) + s.Require().NoError(err) + s.Empty(imported) held, err := s.store.PhoneNumbers.Select(ctx, other, store.PhoneNumberFilter{}) s.Require().NoError(err) s.Len(held, 1, "the number stays with the app that holds it") } -func (s *DataMoveSuite) TestARefusedNumberDoesNotSayWhoHoldsIt() { - other, e164 := s.utils.uuid(), s.utils.number() - s.Require().NoError(s.store.PhoneNumbers.Insert(context.Background(), &store.PhoneNumber{ - E164: e164, Vendor: "plivo", Country: "US", CustomerID: other, - })) - +func (s *DataMoveSuite) TestAnImportedNumberOnItsOwnTrunkInAnotherFormIsRefused() { row, err := json.Marshal(map[string]any{ - "id": rand.Int64N(1 << 50), "e164": e164, "vendor": "bandwidth", "country": "US", - "capabilities": []string{"voice"}, "monthly_cost_micros": 0, "customer_id": other, + "id": rand.Int64N(1 << 50), "e164": strings.TrimPrefix(s.utils.number(), "+"), "vendor": "sip_trunk", + "country": "US", "capabilities": []string{"voice"}, "monthly_cost_micros": 0, "tags": map[string]string{}, "purchased_at": time.Now().UTC(), }) s.Require().NoError(err) status, failure := s.serverClient.failure(http.MethodPost, "/v1/data/import", ndjson([]dataLine{{Table: "phone_numbers", Row: row}})) s.Equal(http.StatusBadRequest, status) - s.Contains(failure, "this number cannot be imported") - s.NotContains(failure, "app") + s.Contains(failure, "E.164") } func (s *DataMoveSuite) TestSomethingThatIsNotAnExportIsRefused() { diff --git a/acceleration/internal/phone/apps_integration_test.go b/acceleration/internal/phone/apps_integration_test.go index ac8d97a6dd..7c548a2e04 100644 --- a/acceleration/internal/phone/apps_integration_test.go +++ b/acceleration/internal/phone/apps_integration_test.go @@ -134,6 +134,16 @@ func (s *AppsSuite) vendorOnAnAllowlist() onAnAllowlist { // numberOn registers a stub for the vendor next to the suite's own and gives the suite's // customer a number on it. func (s *AppsSuite) numberOn(vendor string) string { + other := s.vendorBeside(vendor) + e164 := aNumber() + s.Require().NoError(s.store.PhoneNumbers.Insert(s.ctx, &store.PhoneNumber{ + E164: e164, Vendor: other.vendor, Country: "US", CustomerID: s.customer, PurchasedAt: time.Now().UTC(), + })) + return e164 +} + +// vendorBeside registers a stub for the vendor next to the suite's own. +func (s *AppsSuite) vendorBeside(vendor string) *stub { other := &stub{vendor: vendor} registry := NewRegistry(s.config()) registry.Register(s.vendor.vendor, func() (Provider, error) { return s.vendor, nil }) @@ -144,12 +154,7 @@ func (s *AppsSuite) numberOn(vendor string) string { service, err := NewService(ServiceOptions{Registry: registry, Store: s.store, Apps: s.apps}) s.Require().NoError(err) s.service = service - - e164 := aNumber() - s.Require().NoError(s.store.PhoneNumbers.Insert(s.ctx, &store.PhoneNumber{ - E164: e164, Vendor: other.vendor, Country: "US", CustomerID: s.customer, PurchasedAt: time.Now().UTC(), - })) - return e164 + return other } // planStub is a vendor that fetches its call plan when the call is answered, and renders @@ -311,6 +316,24 @@ func (s *AppsSuite) TestReleasingANumberDeletesItsTrunkAndRouteInItsApp() { s.Empty(s.own.Rules()) } +func (s *AppsSuite) TestAnImportedNumberIsNeverGivenBackAtTheVendor() { + telnyx := s.vendorBeside("telnyx") + e164 := aNumber() + row, err := json.Marshal(map[string]any{ + "id": rand.Int64N(1 << 50), "e164": e164, "vendor": telnyx.vendor, "country": "US", + "capabilities": []string{"voice"}, "monthly_cost_micros": 0, "customer_id": s.customer, + "tags": map[string]string{}, "purchased_at": time.Now().UTC(), + }) + s.Require().NoError(err) + s.Require().NoError(s.store.ImportRow(s.ctx, s.customer, "phone_numbers", row)) + + s.ErrorIs(s.service.Release(s.ctx, s.customer, e164), store.ErrNoNumber) + s.Empty(telnyx.released, "the vendor is not asked to give it back") + _, err = s.service.Attach(s.ctx, Attachment{CustomerID: s.customer, E164: e164}) + s.ErrorIs(err, store.ErrNoNumber, "nor are its calls pointed at an agent") + s.Empty(s.deployment.Trunks()) +} + func (s *AppsSuite) TestReleasingStopsTheVendorSendingCallsFirst() { s.ownApp() s.sealed() diff --git a/acceleration/internal/phone/metering_integration_test.go b/acceleration/internal/phone/metering_integration_test.go index 13513fb711..b5ad7f7dfc 100644 --- a/acceleration/internal/phone/metering_integration_test.go +++ b/acceleration/internal/phone/metering_integration_test.go @@ -4,8 +4,10 @@ package phone import ( "context" + "encoding/json" "errors" "log/slog" + "math/rand/v2" "os" "strconv" "strings" @@ -835,6 +837,26 @@ func (s *MeteringSuite) TestAMonthThatBeganBeforeFromIsNeverBilled() { "the month that began ten days ago began before the job was switched on") } +func (s *MeteringSuite) TestAMovedCustomersBoughtNumberIsNotBilledAgainHere() { + s.Require().NoError(s.store.PhoneNumbers.Release(s.ctx, s.customer, s.e164, s.clock.now())) + now := time.Now().UTC().Truncate(time.Second) + // The month that began three days ago is the source's to bill, which held the number then. + row, err := json.Marshal(map[string]any{ + "id": rand.Int64N(1 << 50), "e164": aNumber(), "vendor": s.vendor.vendor, "country": "US", + "capabilities": []string{"voice"}, "monthly_cost_micros": 1_000_000, "customer_id": s.customer, + "tags": map[string]string{}, "purchased_at": now.AddDate(0, -1, -3), + }) + s.Require().NoError(err) + s.Require().NoError(s.store.ImportRow(s.ctx, s.customer, "phone_numbers", row)) + rentals := Rentals{Store: s.store, Recorder: s.recorder, Logger: slog.New(slog.DiscardHandler)} + + _, err = rentals.Bill(s.ctx, now.AddDate(0, 0, -30), time.Now().UTC()) + s.Require().NoError(err) + + s.Never(func() bool { return len(s.rows(ModelNumber)) > 0 }, time.Second, 50*time.Millisecond, + "the destination bills no month of a number it does not hold") +} + // row waits for the customer's one row of a model and reads it. func (s *MeteringSuite) row(model string) store.Request { return s.rowsWhen(model, 1)[0] diff --git a/acceleration/internal/store/datamove.go b/acceleration/internal/store/datamove.go index 9316a77cc5..cf7e38e29a 100644 --- a/acceleration/internal/store/datamove.go +++ b/acceleration/internal/store/datamove.go @@ -723,7 +723,7 @@ func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table str return err } if table == "phone_numbers" { - if err := importableNumber(ctx, db, customerID, row); err != nil { + if importable, err := importableNumber(ctx, db, customerID, row); err != nil || !importable { return err } } @@ -838,6 +838,10 @@ func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table str if table == "connector_connections" { conflict += fmt.Sprintf(" AND %s.status <> '%s' AND %s.credentials_kek_version = 0", spec.name, ConnectionConnected, spec.name) } + // A number bought here and still held is this deployment's, whatever row names its id. + if table == "phone_numbers" { + conflict += " AND NOT " + boughtHere("phone_numbers") + } // Every writer of a log draws its id under its customer's lock (AgentLogs.Insert), so ids // commit in order and a reader resuming after one misses none. The row is read through the @@ -1376,64 +1380,36 @@ func moveRoom(ctx context.Context, tx bun.Tx, customerID string, marked []Schedu return limits, held, nil } -// digitsKey is a number as most vendors read the one they are given, as SQL over a text -// value: its digits. Plivo, DIDWW, Vonage and Bird drop the plus; Twilio, Telnyx and Sinch -// read it as written, which its digits only widen. -const digitsKey = `regexp_replace(%s, '[^0-9]', '', 'g')` - -// vendorKeys is a number as a vendor that reads it another way does. Bandwidth also drops -// the 1 of an 11-digit number (bandwidth.digits), so +15551234567 and +5551234567 are one -// number there. -var vendorKeys = map[string]string{ - "bandwidth": `regexp_replace(regexp_replace(%s, '[^0-9]', '', 'g'), '^1([0-9]{10})$', '\1')`, -} - -// importableNumber refuses an imported number the customer would hold in a form other than -// E.164, or that another customer holds. Every bought number is held in the deployment's one -// account at its vendor, and releasing it there is what holding it here allows, so a number -// two customers held would be one either of them could give back. The unique index on what -// is held compares the text as written, so it sees neither another form of a number nor the -// same number at another vendor. A number given back is only its bill's history and imports -// as written; one on the customer's own trunk is in no account here. -// -// Two imports of one number into two customers at the same moment can both pass this. -func importableNumber(ctx context.Context, db bun.IDB, customerID string, row json.RawMessage) error { +// importableNumber says whether an imported number is written here, and refuses one the API +// would not store. Only a number on the customer's own trunk moves. A bought one is held in +// the vendor account of the deployment that bought it, with that one's line, trunk and use +// case, and its bills move in its requests: written here it would be billed again (Rentals) +// and given back at this deployment's vendor account. So it is not written, and the customer +// keeps it by buying or porting it here. +func importableNumber(ctx context.Context, db bun.IDB, customerID string, row json.RawMessage) (bool, error) { // Read the way the insert reads it, by exact column name: a JSON decoder also matches a // key in another case, which the insert then leaves out. var e164, vendor sql.NullString - var released bool + var cost sql.NullInt64 if err := db.QueryRowContext(ctx, - "SELECT e164, vendor, released_at IS NOT NULL FROM jsonb_populate_record(NULL::phone_numbers, ?::jsonb)", - string(row)).Scan(&e164, &vendor, &released); err != nil { - return fmt.Errorf("store: read an imported number: %w", err) - } - if released { - return nil + "SELECT e164, vendor, monthly_cost_micros FROM jsonb_populate_record(NULL::phone_numbers, ?::jsonb)", + string(row)).Scan(&e164, &vendor, &cost); err != nil { + return false, fmt.Errorf("store: read an imported number: %w", err) } - if !IsE164(e164.String) { - return stack.Wrap(fmt.Errorf("%w: %q", ErrNotE164, e164.String)) + if vendor.String != sipTrunkVendor { + return false, nil } - if vendor.String == "sip_trunk" { - return nil + number := PhoneNumber{CustomerID: customerID, E164: e164.String, Vendor: vendor.String, MonthlyCostMicros: cost.Int64} + if err := number.Validate(); err != nil { + return false, stack.Wrap(err) } - // Compared as the vendor it would be given back at reads a number, so a number held in - // another form, before every write checked the form, is found as well. - key, found := vendorKeys[vendor.String] - if !found { - key = digitsKey - } - var held bool - if err := db.QueryRowContext(ctx, fmt.Sprintf(` -SELECT EXISTS (SELECT 1 FROM phone_numbers -WHERE customer_id <> ? AND released_at IS NULL AND vendor <> 'sip_trunk' AND %s = %s)`, - fmt.Sprintf(key, "e164"), fmt.Sprintf(key, "?::text")), - customerID, e164.String).Scan(&held); err != nil { - return fmt.Errorf("store: who holds an imported number: %w", err) - } - if held { - return stack.Wrap(fmt.Errorf("%w: %s", ErrNumberHeldElsewhere, e164.String)) - } - return nil + return true, nil +} + +// boughtHere is the condition that a number, as the given relation names it, was bought here +// and is still held: no import writes one (importableNumber), so none may update or delete it. +func boughtHere(relation string) string { + return fmt.Sprintf("(%[1]s.released_at IS NULL AND %[1]s.vendor <> '%[2]s')", relation, sipTrunkVendor) } // importableDefinition refuses an imported definition the API would not have stored, and gives the row the manifest as @@ -1497,10 +1473,11 @@ func (t dataTable) identity() string { } // Nor does an attached number arrive with where its calls go: the trunk, route and call it was attached to are named by whatever // the importer wrote, and a hook that finds one call under two customers' numbers answers - // it for neither (ErrAmbiguousHook). It arrives needing to be attached again. + // it for neither (ErrAmbiguousHook). It arrives needing to be attached again. Nor with its + // use case, which names one of the source's. if t.name == "phone_numbers" { return "jsonb_build_object('customer_id', ?::text, 'stream_trunk_id', NULL, 'stream_route_id', NULL," + - " 'stream_call_id', NULL, 'stream_call_type', NULL, 'attached_at', NULL)" + " 'stream_call_id', NULL, 'stream_call_type', NULL, 'attached_at', NULL, 'dlc_use_case_id', NULL)" } // A request was billed by the deployment that recorded it, so this one never ships it, and // what that one's usage service answered for it is not this one's: a reship of the rows @@ -1774,6 +1751,9 @@ func (s *Store) deleteRow(ctx context.Context, db bun.IDB, customerID string, ch conditions = append(conditions, spec.filter) } } + if spec.name == "phone_numbers" { + conditions = append(conditions, "NOT "+boughtHere("t")) + } args = append(args, customerID) query := fmt.Sprintf("DELETE FROM %s AS t WHERE %s", spec.name, strings.Join(conditions, " AND ")) diff --git a/acceleration/internal/store/datamove_test.go b/acceleration/internal/store/datamove_test.go index f0408f6a7a..d0f793dfa5 100644 --- a/acceleration/internal/store/datamove_test.go +++ b/acceleration/internal/store/datamove_test.go @@ -2979,10 +2979,8 @@ func (s *DataMoveSuite) TestAMovedSIPTrunkArrivesWithoutItsPassword() { func (s *DataMoveSuite) TestAMovedNumberLeavesItsTrunkBehind() { s.capture("acme") trunkID := "trunk-" + newID() - s.Require().NoError(s.source.PhoneNumbers.Insert(s.ctx, &PhoneNumber{ - E164: "+15550000110", Vendor: "telnyx", Country: "US", CustomerID: "acme", - })) - s.Require().NoError(s.source.StreamTrunks.InGroup(s.ctx, TrunkGroup{CustomerID: "acme", Vendor: "telnyx"}, + s.ownNumber("+15550000110") + s.Require().NoError(s.source.StreamTrunks.InGroup(s.ctx, TrunkGroup{CustomerID: "acme", Vendor: sipTrunkVendor}, func(_ context.Context, tx *TrunkGroupTx) error { if err := tx.SaveTrunk(StreamTrunk{ ID: trunkID, BridgeURI: "sip:trunk.example.com", BridgeUsername: "agent", @@ -3027,14 +3025,12 @@ func (s *DataMoveSuite) TestAMovedNumberLeavesItsTrunkBehind() { "SELECT "+column+" FROM phone_numbers WHERE e164 = ?", "+15550000110").Scan(value)) s.False(value.Valid, "%s came along as %q", column, value.String) } - _, err = s.destination.PhoneNumbers.AttachedBridge(s.ctx, "telnyx", "+15550000110") + _, err = s.destination.PhoneNumbers.AttachedBridge(s.ctx, sipTrunkVendor, "+15550000110") s.ErrorIs(err, ErrNoNumber, "it arrives needing to be attached again") } func (s *DataMoveSuite) TestAMovedNumberArrivesNotAttached() { - s.Require().NoError(s.source.PhoneNumbers.Insert(s.ctx, &PhoneNumber{ - E164: "+15550000113", Vendor: "telnyx", Country: "US", CustomerID: "acme", - })) + s.ownNumber("+15550000113") s.Require().NoError(s.source.PhoneNumbers.Attach(s.ctx, "acme", "+15550000113", NumberAttachment{ TrunkID: "trunk-1", RouteID: "route-1", CallType: "default", })) @@ -3046,17 +3042,148 @@ func (s *DataMoveSuite) TestAMovedNumberArrivesNotAttached() { s.Nil(moved.AttachedAt) } -func (s *DataMoveSuite) TestAMovedNumberIsHeldWhereItArrives() { +func (s *DataMoveSuite) TestAMovedNumberOnItsOwnTrunkIsHeldWhereItArrives() { + s.ownNumber("+15550000111") + + s.move("acme", "acme") + s.move("acme", "acme") + + held, err := s.destination.PhoneNumbers.GetByE164(s.ctx, "acme", "+15550000111") + s.Require().NoError(err) + s.Equal(sipTrunkVendor, held.Vendor) +} + +func (s *DataMoveSuite) TestAMovedBoughtNumberDoesNotArrive() { + s.Require().NoError(s.source.PhoneNumbers.Insert(s.ctx, &PhoneNumber{ + E164: "+15550000121", Vendor: "plivo", Country: "US", CustomerID: "acme", + })) s.Require().NoError(s.source.PhoneNumbers.Insert(s.ctx, &PhoneNumber{ - E164: "+15550000111", Vendor: "plivo", Country: "US", CustomerID: "acme", + E164: "+15550000126", Vendor: "telnyx", Country: "US", CustomerID: "acme", })) + s.Require().NoError(s.source.PhoneNumbers.Release(s.ctx, "acme", "+15550000126", time.Time{})) s.move("acme", "acme") s.move("acme", "acme") - held, err := s.destination.PhoneNumbers.GetByE164(s.ctx, "acme", "+15550000111") + numbers, err := s.destination.PhoneNumbers.Select(s.ctx, "acme", PhoneNumberFilter{IncludeReleased: true}) + s.Require().NoError(err) + s.Empty(numbers, "neither the one held nor the one given back") +} + +func (s *DataMoveSuite) TestAnImportedNumberNotOnItsOwnTrunkIsNotStored() { + // Only exactly sip_trunk is the customer's own trunk: anything else is a bought number. + for _, vendor := range []string{"telnyx", "SIP_TRUNK", "sip_trunk ", ""} { + e164 := fmt.Sprintf("+1555100%04d", rand.IntN(10000)) + s.NoError(s.destination.ImportRow(s.ctx, "other", "phone_numbers", s.importedNumber(e164, vendor)), "%q", vendor) + s.NoError(s.destination.ApplyChanges(s.ctx, "other", []DataChange{{ + Table: "phone_numbers", Op: ChangeInsert, Payload: s.importedNumber(e164, vendor, "released_at", time.Now().UTC()), + }}), "%q", vendor) + } + + numbers, err := s.destination.PhoneNumbers.Select(s.ctx, "other", PhoneNumberFilter{IncludeReleased: true}) + s.Require().NoError(err) + s.Empty(numbers) +} + +func (s *DataMoveSuite) TestANumberBoughtHereIsNotWrittenOverByARowWithItsID() { + before := s.boughtHere("+15550000127") + + for name, row := range map[string]json.RawMessage{ + "bought": s.importedNumber("+15550000128", "telnyx", "id", before.ID, "vendor_id", "theirs"), + "on a trunk": s.importedNumber("+15550000128", sipTrunkVendor, "id", before.ID, + "sip_trunk_id", s.trunkOf(s.destination, "other").ID), + "given back": s.importedNumber(before.E164, sipTrunkVendor, "id", before.ID, "released_at", time.Now().UTC()), + } { + s.NoError(s.destination.ImportRow(s.ctx, "other", "phone_numbers", row), name) + s.NoError(s.destination.ApplyChanges(s.ctx, "other", []DataChange{{ + Table: "phone_numbers", Op: ChangeUpdate, Payload: row, + }}), name) + } + + after, err := s.destination.PhoneNumbers.GetByE164(s.ctx, "other", before.E164) + s.Require().NoError(err) + s.Equal(before, after) +} + +func (s *DataMoveSuite) TestAReplayedDeleteLeavesANumberBoughtHere() { + before := s.boughtHere("+15550000129") + + s.Require().NoError(s.destination.ApplyChanges(s.ctx, "other", []DataChange{{ + Table: "phone_numbers", Op: ChangeDelete, Key: json.RawMessage(fmt.Sprintf(`{"id": %d}`, before.ID)), + }})) + + after, err := s.destination.PhoneNumbers.GetByE164(s.ctx, "other", before.E164) + s.Require().NoError(err) + s.Equal(before, after) +} + +func (s *DataMoveSuite) TestAnImportedNumberWithANegativeCostIsRefused() { + row := s.importedNumber("+15550000135", sipTrunkVendor, "sip_trunk_id", s.trunkOf(s.destination, "other").ID, + "monthly_cost_micros", -1) + + for _, err := range []error{ + s.destination.ImportRow(s.ctx, "other", "phone_numbers", row), + s.destination.ApplyChanges(s.ctx, "other", []DataChange{{Table: "phone_numbers", Op: ChangeInsert, Payload: row}}), + } { + var invalid *ValidationError + s.Require().ErrorAs(err, &invalid) + s.Equal("monthly_cost_micros", invalid.Field) + } + numbers, err := s.destination.PhoneNumbers.Select(s.ctx, "other", PhoneNumberFilter{IncludeReleased: true}) + s.Require().NoError(err) + s.Empty(numbers) +} + +// boughtHere is a number other bought here and attached here, as it reads here. +func (s *DataMoveSuite) boughtHere(e164 string) PhoneNumber { + s.Require().NoError(s.destination.PhoneNumbers.Insert(s.ctx, &PhoneNumber{ + E164: e164, Vendor: "telnyx", Country: "US", CustomerID: "other", VendorID: "ours", PurchasedAt: time.Now().UTC(), + })) + s.Require().NoError(s.destination.PhoneNumbers.Attach(s.ctx, "other", e164, NumberAttachment{ + TrunkID: "trunk-here", RouteID: "route-here", StreamAppPK: 42, CallType: "default", CallID: "call-" + newID(), + })) + held, err := s.destination.PhoneNumbers.GetByE164(s.ctx, "other", e164) + s.Require().NoError(err) + return held +} + +func (s *DataMoveSuite) TestAnImportedBoughtNumberIsNotHeldAndCanStillBeBoughtHere() { + s.Require().NoError(s.destination.ImportRow(s.ctx, "other", "phone_numbers", s.importedNumber("+15550000122", "telnyx"))) + s.Require().NoError(s.destination.ApplyChanges(s.ctx, "other", []DataChange{{ + Table: "phone_numbers", Op: ChangeInsert, Payload: s.importedNumber("+15550000123", "telnyx"), + }})) + + for _, e164 := range []string{"+15550000122", "+15550000123"} { + _, err := s.destination.PhoneNumbers.GetByE164(s.ctx, "other", e164) + s.ErrorIs(err, ErrNoNumber, e164) + s.ErrorContains(s.destination.PhoneNumbers.Attach(s.ctx, "other", e164, NumberAttachment{ + TrunkID: "trunk-here", RouteID: "route-here", CallType: "default", CallID: "call-here", + }), "is not a number other holds", e164) + s.NoError(s.destination.PhoneNumbers.Insert(s.ctx, &PhoneNumber{ + E164: e164, Vendor: "telnyx", Country: "US", CustomerID: "acme", + }), "%s can be bought here", e164) + } +} + +func (s *DataMoveSuite) TestAnImportedNumberOnItsOwnTrunkIsHeld() { + row := s.importedNumber("+15550000124", sipTrunkVendor, "sip_trunk_id", s.trunkOf(s.destination, "other").ID) + + s.Require().NoError(s.destination.ImportRow(s.ctx, "other", "phone_numbers", row)) + + held, err := s.destination.PhoneNumbers.GetByE164(s.ctx, "other", "+15550000124") + s.Require().NoError(err) + s.Nil(held.ReleasedAt) +} + +func (s *DataMoveSuite) TestAnImportedNumberHasNoUseCase() { + row := s.importedNumber("+15550000125", sipTrunkVendor, "sip_trunk_id", s.trunkOf(s.destination, "other").ID, + "dlc_use_case_id", "use-case-there") + + s.Require().NoError(s.destination.ImportRow(s.ctx, "other", "phone_numbers", row)) + + held, err := s.destination.PhoneNumbers.GetByE164(s.ctx, "other", "+15550000125") s.Require().NoError(err) - s.Equal("plivo", held.Vendor) + s.Empty(held.UseCaseID) } func (s *DataMoveSuite) TestCopyingAgainKeepsANumberAttachedOnTheDestination() { @@ -3086,12 +3213,10 @@ func (s *DataMoveSuite) TestAChangeAppliedLaterKeepsANumberAttachedOnTheDestinat } func (s *DataMoveSuite) TestCopyingAgainKeepsANumbersLineOnTheDestination() { - s.Require().NoError(s.source.PhoneNumbers.Insert(s.ctx, &PhoneNumber{ - E164: "+15550000132", Vendor: "telnyx", Country: "US", CustomerID: "acme", - })) + s.ownNumber("+15550000132") s.move("acme", "acme") // On a trunk to place calls, not attached. - s.Require().NoError(s.destination.StreamTrunks.InGroup(s.ctx, TrunkGroup{CustomerID: "acme", StreamAppPK: 42, Vendor: "telnyx"}, + s.Require().NoError(s.destination.StreamTrunks.InGroup(s.ctx, TrunkGroup{CustomerID: "acme", StreamAppPK: 42, Vendor: sipTrunkVendor}, func(_ context.Context, tx *TrunkGroupTx) error { return tx.SetLine("+15550000132", "trunk-here", "route-here") })) @@ -3105,9 +3230,7 @@ func (s *DataMoveSuite) TestCopyingAgainKeepsANumbersLineOnTheDestination() { } func (s *DataMoveSuite) TestCopyingAgainStillUpdatesANumberNotOnATrunkOnTheDestination() { - s.Require().NoError(s.source.PhoneNumbers.Insert(s.ctx, &PhoneNumber{ - E164: "+15550000133", Vendor: "telnyx", Country: "US", CustomerID: "acme", - })) + s.ownNumber("+15550000133") s.move("acme", "acme") there := s.seedAgentConfig(s.source, "acme", "there") s.Require().NoError(s.source.PhoneNumbers.Attach(s.ctx, "acme", "+15550000133", NumberAttachment{ @@ -3131,15 +3254,13 @@ func (s *DataMoveSuite) TestCopyingAgainStillUpdatesANumberNotOnATrunkOnTheDesti func (s *DataMoveSuite) TestCopyingAgainBringsTheSourcesAgentToANumberOnlyOnALineOnTheDestination() { first := s.seedAgentConfig(s.source, "acme", "first") - s.Require().NoError(s.source.PhoneNumbers.Insert(s.ctx, &PhoneNumber{ - E164: "+15550000134", Vendor: "telnyx", Country: "US", CustomerID: "acme", - })) + s.ownNumber("+15550000134") s.Require().NoError(s.source.PhoneNumbers.Attach(s.ctx, "acme", "+15550000134", NumberAttachment{ TrunkID: "trunk-there", RouteID: "route-there", CallType: "default", CallID: "call-there", ConfigID: first, })) s.move("acme", "acme") // On a line to place calls, which never wrote an agent. - s.Require().NoError(s.destination.StreamTrunks.InGroup(s.ctx, TrunkGroup{CustomerID: "acme", StreamAppPK: 42, Vendor: "telnyx"}, + s.Require().NoError(s.destination.StreamTrunks.InGroup(s.ctx, TrunkGroup{CustomerID: "acme", StreamAppPK: 42, Vendor: sipTrunkVendor}, func(_ context.Context, tx *TrunkGroupTx) error { return tx.SetLine("+15550000134", "trunk-here", "route-here") })) @@ -3176,12 +3297,17 @@ func (s *DataMoveSuite) TestCopyingAgainDoesNotKeepTheLineOfANumberTheSourceGave s.Empty(moved.ConfigID) } -// numberAttachedHere is a number the source holds, copied here and attached here, as it reads -// here once attached. -func (s *DataMoveSuite) numberAttachedHere(e164 string) PhoneNumber { - s.Require().NoError(s.source.PhoneNumbers.Insert(s.ctx, &PhoneNumber{ - E164: e164, Vendor: "telnyx", Country: "US", CustomerID: "acme", +// ownNumber is a number on acme's own trunk at the source: a bought one arrives given back. +func (s *DataMoveSuite) ownNumber(e164 string) { + s.Require().NoError(s.source.PhoneNumbers.InsertOnSIPTrunk(s.ctx, &PhoneNumber{ + E164: e164, Country: "US", CustomerID: "acme", SIPTrunkID: s.trunkOf(s.source, "acme").ID, })) +} + +// numberAttachedHere is a number the source holds on acme's own trunk, copied here and attached +// here, as it reads here once attached. +func (s *DataMoveSuite) numberAttachedHere(e164 string) PhoneNumber { + s.ownNumber(e164) s.move("acme", "acme") s.Require().NoError(s.destination.PhoneNumbers.Attach(s.ctx, "acme", e164, NumberAttachment{ TrunkID: "trunk-here", RouteID: "route-here", StreamAppPK: 42, CallType: "default", CallID: "call-here", @@ -3209,79 +3335,67 @@ func (s *DataMoveSuite) assertLineKept(before PhoneNumber) { } func (s *DataMoveSuite) TestANumberInAnotherFormIsNotImported() { - s.Require().NoError(s.destination.PhoneNumbers.Insert(s.ctx, &PhoneNumber{ - E164: "+15550000112", Vendor: "plivo", Country: "US", CustomerID: "acme", - })) - - // Each is a form a vendor reads as +15550000112. - for _, form := range []struct{ vendor, e164 string }{ - {"plivo", "15550000112"}, {"bandwidth", "15550000112"}, {"bandwidth", "5550000112"}, - {"didww", "15550000112"}, {"vonage", "15550000112"}, - } { - err := s.destination.ImportRow(s.ctx, "other", "phone_numbers", s.importedNumber(form.e164, form.vendor)) - s.ErrorIs(err, ErrNotE164, "%s %s", form.vendor, form.e164) + trunk := s.trunkOf(s.destination, "other").ID + for _, e164 := range []string{"15550000112", "5550000112", "+015550000112", "+1 555 000 0112"} { + row := s.importedNumber(e164, sipTrunkVendor, "sip_trunk_id", trunk) + for _, err := range []error{ + s.destination.ImportRow(s.ctx, "other", "phone_numbers", row), + s.destination.ApplyChanges(s.ctx, "other", []DataChange{{Table: "phone_numbers", Op: ChangeInsert, Payload: row}}), + } { + var invalid *ValidationError + s.Require().ErrorAs(err, &invalid, e164) + s.Equal("e164", invalid.Field, e164) + } } - err := s.destination.ApplyChanges(s.ctx, "other", []DataChange{{ - Table: "phone_numbers", Op: ChangeInsert, Payload: s.importedNumber("15550000112", "plivo"), - }}) - s.ErrorIs(err, ErrNotE164, "nor replayed as a change") held, err := s.destination.PhoneNumbers.Select(s.ctx, "other", PhoneNumberFilter{IncludeReleased: true}) s.Require().NoError(err) s.Empty(held) - _, err = s.destination.PhoneNumbers.GetByE164(s.ctx, "acme", "+15550000112") - s.NoError(err, "the number stays with who held it") } -func (s *DataMoveSuite) TestANumberAnotherCustomerHoldsIsNotImported() { +func (s *DataMoveSuite) TestABoughtNumberAnotherCustomerHoldsStaysTheirs() { s.Require().NoError(s.destination.PhoneNumbers.Insert(s.ctx, &PhoneNumber{ E164: "+15550000113", Vendor: "plivo", Country: "US", CustomerID: "acme", })) - _, err := s.destination.GlobalDB().ExecContext(s.ctx, "INSERT INTO phone_numbers (e164, vendor, country, customer_id)"+ - " VALUES ('15550000114', 'plivo', 'US', 'acme')") - s.Require().NoError(err, "held in another form, before every write checked the form") - s.Require().NoError(s.destination.PhoneNumbers.Insert(s.ctx, &PhoneNumber{ - E164: "+5550000120", Vendor: "bandwidth", Country: "US", CustomerID: "acme", - })) - // Bandwidth reads +15550000113 and +5550000113 as one number. for _, number := range []struct{ vendor, e164 string }{ - {"plivo", "+15550000113"}, {"bandwidth", "+15550000113"}, {"didww", "+15550000114"}, - {"bandwidth", "+5550000113"}, {"bandwidth", "+15550000120"}, + {"plivo", "+15550000113"}, {"plivo", "15550000113"}, {"bandwidth", "+5550000113"}, } { - err := s.destination.ImportRow(s.ctx, "other", "phone_numbers", s.importedNumber(number.e164, number.vendor)) - s.ErrorIs(err, ErrNumberHeldElsewhere, "%s %s", number.vendor, number.e164) + s.NoError(s.destination.ImportRow(s.ctx, "other", "phone_numbers", s.importedNumber(number.e164, number.vendor))) } + + held, err := s.destination.PhoneNumbers.Select(s.ctx, "other", PhoneNumberFilter{IncludeReleased: true}) + s.Require().NoError(err) + s.Empty(held) + _, err = s.destination.PhoneNumbers.GetByE164(s.ctx, "acme", "+15550000113") + s.NoError(err, "the number stays with who held it") } func (s *DataMoveSuite) TestANumberIsReadByItsColumnsAsTheyAreNamed() { - s.Require().NoError(s.destination.PhoneNumbers.Insert(s.ctx, &PhoneNumber{ - E164: "+15550000119", Vendor: "plivo", Country: "US", CustomerID: "acme", - })) - - // A key in another case names no column, so it gives nothing back. - for _, number := range []struct { - vendor, e164 string - refused error - }{ - {"bandwidth", "+15550000119", ErrNumberHeldElsewhere}, {"plivo", "15550000119", ErrNotE164}, - } { + trunk := s.trunkOf(s.destination, "other").ID + // A key in another case names no column, so the insert would leave it out. + renamed := func(from, to string) json.RawMessage { var row map[string]any - s.Require().NoError(json.Unmarshal(s.importedNumber(number.e164, number.vendor), &row)) - delete(row, "released_at") - row["Released_At"] = time.Now().UTC() + s.Require().NoError(json.Unmarshal(s.importedNumber("+15550000119", sipTrunkVendor, "sip_trunk_id", trunk), &row)) + row[to] = row[from] + delete(row, from) encoded, err := json.Marshal(row) s.Require().NoError(err) - - err = s.destination.ImportRow(s.ctx, "other", "phone_numbers", encoded) - s.ErrorIs(err, number.refused, "%s %s", number.vendor, number.e164) + return encoded } + + s.NoError(s.destination.ImportRow(s.ctx, "other", "phone_numbers", renamed("vendor", "Vendor")), + "with no vendor it is not on its own trunk") + var invalid *ValidationError + s.Require().ErrorAs(s.destination.ImportRow(s.ctx, "other", "phone_numbers", renamed("e164", "E164")), &invalid) + s.Equal("e164", invalid.Field) + held, err := s.destination.PhoneNumbers.Select(s.ctx, "other", PhoneNumberFilter{IncludeReleased: true}) s.Require().NoError(err) s.Empty(held) } -func (s *DataMoveSuite) TestANumberNobodyElseHoldsAtAVendorIsImported() { +func (s *DataMoveSuite) TestANumberOnItsOwnTrunkIsImportedWhoeverElseHoldsIt() { s.Require().NoError(s.destination.PhoneNumbers.Insert(s.ctx, &PhoneNumber{ E164: "+15550000115", Vendor: "plivo", Country: "US", CustomerID: "acme", })) @@ -3293,15 +3407,12 @@ func (s *DataMoveSuite) TestANumberNobodyElseHoldsAtAVendorIsImported() { E164: "+15550000117", Vendor: "plivo", Country: "US", CustomerID: "acme", })) - for name, row := range map[string]json.RawMessage{ - "one acme gave back": s.importedNumber("+15550000115", "plivo"), - "one acme has on its trunk": s.importedNumber("+15550000116", "plivo"), - "another one at a vendor that keeps its 1": s.importedNumber("+5550000117", "plivo"), - "one given back, in any form": s.importedNumber("15550000118", "plivo", "released_at", time.Now().UTC()), - "one acme holds, on a trunk": s.importedNumber("+15550000117", "sip_trunk", - "sip_trunk_id", s.trunkOf(s.destination, "other").ID), - } { - s.NoError(s.destination.ImportRow(s.ctx, "other", "phone_numbers", row), name) + trunk := s.trunkOf(s.destination, "other").ID + for _, e164 := range []string{"+15550000115", "+15550000116", "+15550000117"} { + s.NoError(s.destination.ImportRow(s.ctx, "other", "phone_numbers", + s.importedNumber(e164, sipTrunkVendor, "sip_trunk_id", trunk)), e164) + _, err := s.destination.PhoneNumbers.GetByE164(s.ctx, "other", e164) + s.NoError(err, e164) } } diff --git a/acceleration/internal/store/phone_number.go b/acceleration/internal/store/phone_number.go index c6cbd7e604..81d48b354c 100644 --- a/acceleration/internal/store/phone_number.go +++ b/acceleration/internal/store/phone_number.go @@ -83,10 +83,6 @@ const sipTrunkVendor = "sip_trunk" // ErrNumberHeld says the customer already holds the number, bought or on a trunk. var ErrNumberHeld = errors.New("store: the customer already holds this number") -// ErrNumberHeldElsewhere says another customer holds the number, at any vendor. It does not -// say so to the customer, who would learn from it which numbers other apps hold. -var ErrNumberHeldElsewhere = errors.New("store: this number cannot be imported") - // ErrNotE164 says a number is not written in E.164 form, the only form a number is held in. var ErrNotE164 = errors.New("store: a number is held in E.164 form, such as +15551234567")