From fecd96b3c6ef3161c1951559b9508d9c7e957c7f Mon Sep 17 00:00:00 2001 From: thesyncim Date: Tue, 24 Nov 2026 23:00:32 +0000 Subject: [PATCH 01/23] fix(phone): a call is routed into a call of its own customer's --- acceleration/internal/api/phone.go | 28 ++- acceleration/internal/api/phone_test.go | 177 ++++++++++++++++++ .../internal/api/router_suite_test.go | 5 + acceleration/internal/node/directory.go | 49 ++++- acceleration/internal/node/directory_test.go | 40 ++++ acceleration/internal/phone/apps.go | 2 + .../internal/phone/apps_integration_test.go | 109 +++++++++++ acceleration/internal/phone/service.go | 28 ++- acceleration/internal/session/manager.go | 47 +++++ acceleration/internal/store/call_leg.go | 41 +++- acceleration/internal/store/call_leg_test.go | 124 ++++++++++++ acceleration/internal/store/hooks.go | 9 + .../internal/store/store_explain_test.go | 4 + 13 files changed, 650 insertions(+), 13 deletions(-) diff --git a/acceleration/internal/api/phone.go b/acceleration/internal/api/phone.go index 820a71c86e..0ecda938bc 100644 --- a/acceleration/internal/api/phone.go +++ b/acceleration/internal/api/phone.go @@ -407,7 +407,7 @@ func (s *Server) placePhoneCall(ctx context.Context, request *placePhoneCallRequ return nil, err } if theirs { - return nil, conflict("session_id is taken") + return nil, errSessionTaken } call.SessionID = held } @@ -435,6 +435,9 @@ func (s *Server) placePhoneCall(ctx context.Context, request *placePhoneCallRequ if failure, over := tierLimitReached(err); over { return nil, failure } + if errors.Is(err, phone.ErrSessionTaken) { + return nil, errSessionTaken + } if errors.Is(err, dlc.ErrRefused) || errors.Is(err, phone.ErrDestinationRefused) { return nil, forbidden(err.Error()) } @@ -1003,6 +1006,8 @@ func phoneTags(tags *map[string]string) routing.Tags { return routing.Tags(*tags) } +var errSessionTaken = conflict("session_id is taken") + var errNoTelephony = notConfigured("phone numbers are not available: no telephony configured") // callApp is the Stream app a live call is in, which a human transferred into it has to be @@ -1036,11 +1041,26 @@ func (s *Server) anotherCustomersSession(ctx context.Context, customerID, id str return false, nil } taken, err := s.store.Sessions.Exists(ctx, id) - if err != nil || !taken { + if err != nil { return false, err } - _, err = s.store.Sessions.Get(ctx, customerID, id) - return err != nil, nil + if taken { + _, err = s.store.Sessions.Get(ctx, customerID, id) + return err != nil, nil + } + // A session another node runs may have no row yet, and an incognito one never has. + if s.directory == nil || s.stream == nil { + return false, nil + } + app, err := s.stream.Pin(ctx, customerID) + if err != nil { + return false, phoneFailure(s.logger, err) + } + if app == s.stream.DeploymentApp() { + app = 0 + } + holder, err := s.directory.CallHolder(ctx, app, id) + return holder != "" && holder != customerID, err } // callPinApp is the Stream app a call no session is running in is in: the app its lines were diff --git a/acceleration/internal/api/phone_test.go b/acceleration/internal/api/phone_test.go index 9b134ec639..e1dae3fe65 100644 --- a/acceleration/internal/api/phone_test.go +++ b/acceleration/internal/api/phone_test.go @@ -26,6 +26,7 @@ import ( "github.com/GetStream/Vision-Agents/acceleration/internal/routing" "github.com/GetStream/Vision-Agents/acceleration/internal/session" "github.com/GetStream/Vision-Agents/acceleration/internal/store" + "github.com/GetStream/Vision-Agents/acceleration/internal/streamapp" ) // PhoneSuite covers the telephony surface of a deployment that declares every vendor and @@ -373,6 +374,7 @@ func (s *CallStatusSuite) SetupSuite() { s.phoneVendors = registry s.phoneOnChat = true s.sessionTelephony = true + s.deploymentKnown = true s.logged = &lockedLog{} s.logs = s.logged s.RouterSuite.SetupSuite() @@ -1348,3 +1350,178 @@ func (s *PhoneSuite) TestClearingANumbersLineRemovesItsAgent() { s.Empty(answering) s.Nil(s.listedNumber().AgentConfigId) } + +// arrivedFor opens the leg of a caller whose call was dispatched to a customer's worker. +func (s *CallStatusSuite) arrivedFor(customer string) string { + call := s.utils.uuid() + s.router.phone.OpenLeg(context.Background(), routing.Owner{CustomerID: customer}, store.CallLeg{ + CallType: "agent", CallID: call, StreamSessionID: "stream-" + call, Vendor: "twilio", Direction: store.Inbound, + LocalNumber: s.utils.number(), RemoteNumber: s.utils.number(), DialedAt: time.Now().Add(-time.Minute), + }, true) + return call +} + +// callInto places a call into a session from a number the suite's app holds. +func (s *CallStatusSuite) callInto(session string) (int, string) { + e164 := s.utils.number() + s.Require().NoError(s.store.PhoneNumbers.Insert(context.Background(), &store.PhoneNumber{ + E164: e164, Vendor: "twilio", Country: "US", CustomerID: s.customerID(), PurchasedAt: time.Now().UTC(), + })) + status, payload := s.serverClient.call(http.MethodPost, "/v1/phone/calls", PlaceCallRequest{ + From: e164, To: "+15550001111", SessionId: &session, + }) + return status, string(payload) +} + +func (s *CallStatusSuite) TestACallCannotBeRoutedIntoACallDispatchedToAnotherCustomer() { + s.useApp(s.data.createApp()) + theirs := s.arrivedFor("customer-" + s.utils.uuid()) + + status, payload := s.callInto(theirs) + + s.Equal(http.StatusConflict, status, payload) + s.Contains(payload, "session_id is taken") +} + +// A call to a vendor nothing answers is phone_vendor_failed: one let past the router's own checks. +func (s *CallStatusSuite) TestACallMayBeRoutedIntoACallDispatchedToTheCaller() { + s.useApp(s.data.createApp()) + + status, payload := s.callInto(s.arrivedFor(s.customerID())) + + s.Equal(http.StatusServiceUnavailable, status, payload) + s.Contains(payload, "phone_vendor_failed") +} + +// An incognito session has no row, so only the node running it says whose its call is. +func (s *CallStatusSuite) TestACallCannotBeRoutedIntoAnotherCustomersSessionOnAnotherNode() { + s.useApp(s.data.createApp()) + _, _, sessions := s.otherNodeHolding(nil, s.sealer, slog.New(slog.DiscardHandler)) + opened, err := sessions.Create(context.Background(), session.Spec{CustomerID: "customer-" + s.utils.uuid(), Text: true, + Incognito: true, Attribution: routing.Attribution{APIKey: "key"}}) + s.Require().NoError(err) + + status, payload := s.callInto(opened.ID()) + + s.Equal(http.StatusConflict, status, payload) +} + +func (s *CallStatusSuite) TestACallMayBeRoutedIntoTheCallersSessionOnAnotherNode() { + s.useApp(s.data.createApp()) + _, _, sessions := s.otherNodeHolding(nil, s.sealer, slog.New(slog.DiscardHandler)) + opened, err := sessions.Create(context.Background(), session.Spec{CustomerID: s.customerID(), Text: true, + Incognito: true, Attribution: routing.Attribution{APIKey: "key"}}) + s.Require().NoError(err) + + status, payload := s.callInto(opened.ID()) + + s.Equal(http.StatusServiceUnavailable, status, payload) + s.Contains(payload, "phone_vendor_failed") +} + +func (s *CallStatusSuite) TestASessionCannotBeCreatedOnACallDispatchedToAnotherCustomer() { + s.useApp(s.data.createApp()) + theirs := s.arrivedFor("customer-" + s.utils.uuid()) + + s.Equal(http.StatusConflict, s.serverClient.do(http.MethodPost, "/v1/agents/sessions", textSession(&theirs), nil)) +} + +func (s *CallStatusSuite) TestASessionMayBeCreatedOnACallDispatchedToItsCustomer() { + s.useApp(s.data.createApp()) + mine := s.arrivedFor(s.customerID()) + + s.Equal(mine, s.serverClient.createSession(textSession(&mine)).Id) +} + +func (s *CallStatusSuite) TestASessionCannotBeCreatedUnderTheIdOfAnotherCustomersOnAnotherNode() { + s.useApp(s.data.createApp()) + _, _, sessions := s.otherNodeHolding(nil, s.sealer, slog.New(slog.DiscardHandler)) + opened, err := sessions.Create(context.Background(), session.Spec{CustomerID: "customer-" + s.utils.uuid(), Text: true, + Incognito: true, Attribution: routing.Attribution{APIKey: "key"}}) + s.Require().NoError(err) + id := opened.ID() + + s.Equal(http.StatusConflict, s.serverClient.do(http.MethodPost, "/v1/agents/sessions", textSession(&id), nil)) +} + +func (s *CallStatusSuite) TestACallIntoASessionOfACustomerWhoseAppIsDisconnectedIsAnInvalidRequest() { + s.useApp(s.data.createApp()) + s.setApps(s.customerID(), func(apps *suiteApps) { + apps.refused = map[string]error{s.customerID(): streamapp.ErrStreamAppDisconnected} + }) + + status, payload := s.callInto(s.utils.uuid()) + + s.Equal(http.StatusBadRequest, status, payload) +} + +// A customer in a Stream app of its own names its sessions without regard to another app's. +func (s *CallStatusSuite) TestASessionMayBeCreatedUnderTheNameOfAnotherAppsCall() { + s.useApp(s.data.createApp()) + theirs := s.arrivedFor("customer-" + s.utils.uuid()) + s.giveApp(s.customerID(), streamAppID(), "key-"+s.customerID()) + _, _, sessions := s.otherNodeHolding(nil, s.sealer, slog.New(slog.DiscardHandler)) + opened, err := sessions.Create(context.Background(), session.Spec{CustomerID: "customer-" + s.utils.uuid(), Text: true, + Incognito: true, Attribution: routing.Attribution{APIKey: "key"}}) + s.Require().NoError(err) + + s.serverClient.createSession(textSession(&theirs)) + s.Equal(http.StatusCreated, s.serverClient.do(http.MethodPost, "/v1/agents/sessions", textSession(pointerTo(opened.ID())), nil)) +} + +func (s *CallStatusSuite) TestACallMayBeRoutedUnderTheNameOfAnotherAppsSessionOnAnotherNode() { + s.useApp(s.data.createApp()) + s.giveApp(s.customerID(), streamAppID(), "key-"+s.customerID()) + _, _, sessions := s.otherNodeHolding(nil, s.sealer, slog.New(slog.DiscardHandler)) + opened, err := sessions.Create(context.Background(), session.Spec{CustomerID: "customer-" + s.utils.uuid(), Text: true, + Incognito: true, Attribution: routing.Attribution{APIKey: "key"}}) + s.Require().NoError(err) + + status, payload := s.callInto(opened.ID()) + + s.Equal(http.StatusServiceUnavailable, status, payload) +} + +// A customer whose work is pinned to the deployment's app's id and one pinned to none act in one +// app. +func (s *CallStatusSuite) TestACallCannotBeRoutedIntoASessionOfTheDeploymentsAppWhicheverWayEitherIsPinned() { + s.useApp(s.data.createApp()) + theirs := "customer-" + s.utils.uuid() + s.giveApp(theirs, suiteStreamApp, "key-"+theirs) + _, _, sessions := s.otherNodeHolding(nil, s.sealer, slog.New(slog.DiscardHandler)) + hold := func(customer string) string { + opened, err := sessions.Create(context.Background(), session.Spec{CustomerID: customer, Text: true, + Incognito: true, Attribution: routing.Attribution{APIKey: "key"}}) + s.Require().NoError(err) + return opened.ID() + } + + status, payload := s.callInto(hold(theirs)) + s.Equal(http.StatusConflict, status, payload) + + unpinned := hold("customer-" + s.utils.uuid()) + s.giveApp(s.customerID(), suiteStreamApp, "key-"+s.customerID()) + status, payload = s.callInto(unpinned) + s.Equal(http.StatusConflict, status, payload) + s.Equal(http.StatusConflict, s.serverClient.do(http.MethodPost, "/v1/agents/sessions", textSession(&unpinned), nil)) +} + +// Customers of a deployment in app mode with no app to act in share no call. +func (s *CallStatusSuite) TestASessionOfNoStreamAppIsOnNoCallOfAnothers() { + s.useApp(s.data.createApp()) + theirs := "customer-" + s.utils.uuid() + s.setApps(theirs, func(apps *suiteApps) { + apps.perApp = true + apps.nowhere = map[string]bool{theirs: true, s.customerID(): true} + }) + s.stream.Invalidate(s.customerID()) + s.T().Cleanup(func() { s.setApps(theirs, func(apps *suiteApps) { apps.perApp = false; apps.nowhere = nil }) }) + _, _, sessions := s.otherNodeHolding(nil, s.sealer, slog.New(slog.DiscardHandler)) + opened, err := sessions.Create(context.Background(), session.Spec{CustomerID: theirs, Text: true, + Incognito: true, Attribution: routing.Attribution{APIKey: "key"}}) + s.Require().NoError(err) + request := textSession(pointerTo(opened.ID())) + request.Incognito = pointerTo(true) + + s.Equal(http.StatusCreated, s.serverClient.do(http.MethodPost, "/v1/agents/sessions", request, nil)) +} diff --git a/acceleration/internal/api/router_suite_test.go b/acceleration/internal/api/router_suite_test.go index 8cc68dfb37..4382fe6062 100644 --- a/acceleration/internal/api/router_suite_test.go +++ b/acceleration/internal/api/router_suite_test.go @@ -2688,6 +2688,8 @@ type suiteApps struct { // keyless are customers of a deployment with no Stream keys, which the deployment's own app // answers ErrNoIdentity for whatever it is asked, as an unconfigured Deployment does. keyless map[string]bool + // refused are customers the app to act in is refused for, and how. + refused map[string]error // perApp answers as app mode does, where customers act in apps of their own. perApp bool } @@ -2702,8 +2704,11 @@ func (a *suiteApps) For(ctx context.Context, customer string) (streamapp.Identit a.mu.Lock() identity, ok := a.own[customer] waiting, nowhere := a.waiting[customer], a.nowhere[customer] || a.keyless[customer] + refused := a.refused[customer] a.mu.Unlock() switch { + case refused != nil: + return streamapp.Identity{}, refused case waiting: return streamapp.Identity{}, streamapp.ErrDeploymentAppUnknown case nowhere: diff --git a/acceleration/internal/node/directory.go b/acceleration/internal/node/directory.go index 123f0cf294..11f37256d4 100644 --- a/acceleration/internal/node/directory.go +++ b/acceleration/internal/node/directory.go @@ -61,6 +61,7 @@ type Directory struct { address string shard string sessions string + calls string // agents and channels are a session's agent and conversation by their ids alone, which a // router of the release before reads. Here only channels is read, when a customer's own key // is not there. @@ -91,8 +92,9 @@ type offerKey struct{ customerID, agentID string } // one id. type heldSession struct{ customerID, sessionID string } -// claim is what a session this node holds is found by besides its own id. -type claim struct{ agentID, conversationID string } +// claim is what a session this node holds is found by besides its own id. call is the key its +// call, agent:, is held under, empty until it is (HoldCall). +type claim struct{ agentID, conversationID, call string } // offerEntry is one node's offer as Redis holds it. A hash cannot expire its fields one at // a time, so each says when it lapses. @@ -124,6 +126,7 @@ func NewDirectory(options DirectoryOptions) (*Directory, error) { address: options.Address, shard: options.Shard, sessions: prefix + ":session:", + calls: prefix + ":call:", agents: prefix + ":agent:", channels: prefix + ":channel:", writingAs: prefix + ":writing-as:", @@ -188,10 +191,37 @@ func (d *Directory) shardCommands() []rueidis.Completed { func (d *Directory) Hold(ctx context.Context, customerID, sessionID, agentID, conversationID string) { key := heldSession{customerID, sessionID} d.mu.Lock() - d.held[key] = claim{agentID, conversationID} + d.held[key] = claim{agentID: agentID, conversationID: conversationID} d.mu.Unlock() - d.write(ctx, key, claim{agentID, conversationID}) + d.write(ctx, key, claim{agentID: agentID, conversationID: conversationID}) +} + +// HoldCall says whose the call of a session this node holds is: agent:, in a Stream +// app, 0 for the deployment's own. It goes on saying so until Release. +func (d *Directory) HoldCall(ctx context.Context, customerID, sessionID string, app int64) { + key := heldSession{customerID, sessionID} + d.mu.Lock() + held, holding := d.held[key] + held.call = d.callKey(app, sessionID) + if holding { + d.held[key] = held + } + d.mu.Unlock() + if holding { + d.write(ctx, key, held) + } +} + +// CallHolder is the customer whose session some node runs on the call agent: in the Stream +// app, 0 for the deployment's own, and empty when no node says it does. +func (d *Directory) CallHolder(ctx context.Context, app int64, id string) (string, error) { + return d.lookup(ctx, d.callKey(app, id)) +} + +// callKey is where a call is held: node:call::. +func (d *Directory) callKey(app int64, id string) string { + return d.calls + strconv.FormatInt(app, 10) + ":" + id } // Release says this node is not running a customer's session any more. @@ -203,14 +233,18 @@ func (d *Directory) Hold(ctx context.Context, customerID, sessionID, agentID, co func (d *Directory) Release(ctx context.Context, customerID, sessionID string) { key := heldSession{customerID, sessionID} d.mu.Lock() - _, held := d.held[key] + released, held := d.held[key] delete(d.held, key) d.mu.Unlock() if !held { return } - if err := d.redis.Do(ctx, d.redis.B().Del().Key(d.sessionKey(key), d.sessions+sessionID).Build()).Error(); err != nil { + gone := []string{d.sessionKey(key), d.sessions + sessionID} + if released.call != "" { + gone = append(gone, released.call) + } + if err := d.redis.Do(ctx, d.redis.B().Del().Key(gone...).Build()).Error(); err != nil { d.logger.Warn("could not take back this node's claim on a session", "customer", customerID, "session", sessionID, "error", err) } @@ -451,6 +485,9 @@ func (d *Directory) writeCommands(key heldSession, held claim) []rueidis.Complet d.redis.B().Set().Key(d.sessionKey(key)).Value(d.address).Ex(holdFor).Build(), d.redis.B().Set().Key(d.sessions + key.sessionID).Value(d.address).Ex(holdFor).Build(), } + if held.call != "" { + commands = append(commands, d.redis.B().Set().Key(held.call).Value(key.customerID).Ex(holdFor).Build()) + } if held.agentID != "" { writers := d.writingAs + held.agentID until := strconv.FormatInt(time.Now().Add(holdFor).UnixMilli(), 10) diff --git a/acceleration/internal/node/directory_test.go b/acceleration/internal/node/directory_test.go index ad0c0ebf51..b24d1fe5d5 100644 --- a/acceleration/internal/node/directory_test.go +++ b/acceleration/internal/node/directory_test.go @@ -219,6 +219,46 @@ func (s *DirectorySuite) TestAReleasedSessionIsFoundNowhere() { s.Zero(exists, "a router of the release before would still forward to it") } +// A session's call is found by its id and Stream app until the session is released, and a +// renewal says it again. +func (s *DirectorySuite) TestASessionsCallIsFoundByItsAppUntilItIsReleased() { + directory := s.directoryAt("node-a:1") + directory.Hold(s.ctx, "acme", "order-42", "", "") + directory.HoldCall(s.ctx, "acme", "order-42", 7) + peer := s.directoryAt("node-b:1") + holder := func(app int64, id string) string { + customer, err := peer.CallHolder(s.ctx, app, id) + s.Require().NoError(err) + return customer + } + + s.Equal("acme", holder(7, "order-42")) + s.Empty(holder(0, "order-42"), "another app's call of the name") + s.Empty(holder(7, "order-43")) + + key := s.prefix + ":call:7:order-42" + ttl, err := s.client.Do(s.ctx, s.client.B().Pttl().Key(key).Build()).AsInt64() + s.Require().NoError(err) + s.InDelta(30000, ttl, 5000, "it lapses with the node") + s.Require().NoError(s.client.Do(s.ctx, s.client.B().Del().Key(key).Build()).Error()) + directory.renewAll(s.ctx) + s.Equal("acme", holder(7, "order-42")) + + directory.Release(s.ctx, "acme", "order-42") + s.Empty(holder(7, "order-42")) +} + +func (s *DirectorySuite) TestACallOfASessionNotHeldHereIsNotHeld() { + directory := s.directoryAt("node-a:1") + + directory.HoldCall(s.ctx, "acme", "order-42", 7) + directory.renewAll(s.ctx) + + holder, err := directory.CallHolder(s.ctx, 7, "order-42") + s.Require().NoError(err) + s.Empty(holder) +} + // directoryAt is a node's directory at address, renewing nothing for the test's length. func (s *DirectorySuite) directoryAt(address string) *Directory { directory, err := NewDirectory(DirectoryOptions{Redis: s.client, Address: address, Prefix: s.prefix}) diff --git a/acceleration/internal/phone/apps.go b/acceleration/internal/phone/apps.go index 1ea655f33f..96722863c6 100644 --- a/acceleration/internal/phone/apps.go +++ b/acceleration/internal/phone/apps.go @@ -39,3 +39,5 @@ func (a clientApps) ForAppRemoving(ctx context.Context, customer string, app int } return NewStreamFromClient(bound.Client), nil } + +func (a clientApps) DeploymentApp() int64 { return a.clients.DeploymentApp() } diff --git a/acceleration/internal/phone/apps_integration_test.go b/acceleration/internal/phone/apps_integration_test.go index d87d6d5140..cd8f18c230 100644 --- a/acceleration/internal/phone/apps_integration_test.go +++ b/acceleration/internal/phone/apps_integration_test.go @@ -1000,6 +1000,8 @@ func (a *testApps) ForAppRemoving(_ context.Context, customer string, app int64) return NewStreamFromClient(a.deployment.Client), nil } +func (a *testApps) DeploymentApp() int64 { return 1 } + func (s *AppsSuite) purchase() Purchase { return Purchase{Vendor: s.vendor.vendor, E164: aNumber(), Country: "US", Owner: routing.Owner{CustomerID: s.customer}} } @@ -2886,3 +2888,110 @@ func (s *AppsSuite) TestNoNumberIsGivenOutTwice() { given[number] = true } } + +// another is a second customer acting in the deployment's app, and a number it holds. +func (s *AppsSuite) another() (string, string) { + customer, e164 := "customer-"+uuid.NewString(), aNumber() + s.Require().NoError(s.store.PhoneNumbers.Insert(s.ctx, &store.PhoneNumber{ + E164: e164, Vendor: s.vendor.vendor, Country: "US", CustomerID: customer, PurchasedAt: time.Now().UTC(), + })) + return customer, e164 +} + +// arrived opens the leg of a caller who rang one of customer's numbers. +func (s *AppsSuite) arrived(customer, callID string, app int64) { + s.service.OpenLeg(s.ctx, routing.Owner{CustomerID: customer}, store.CallLeg{ + StreamAppPK: app, CallType: defaultCallType, CallID: callID, StreamSessionID: "session-" + callID, Vendor: "twilio", + Direction: store.Inbound, LocalNumber: s.e164, RemoteNumber: "+15125550160", DialedAt: time.Now().Add(-time.Minute), + }, true) +} + +// refusedTaken checks a call into the session is refused with nothing dialled, made at Stream or kept. +func (s *AppsSuite) refusedTaken(sessionID string) { + trunks := len(s.deployment.Trunks()) + s.vendor.dialed = Outbound{} + + s.ErrorIs(s.dialInto(sessionID, "+15550001111", map[string]string{"k": "v"}), ErrSessionTaken) + + s.Empty(s.vendor.dialed.To) + s.Len(s.deployment.Trunks(), trunks) + kept, err := s.store.CallLegs.SelectPlaced(s.ctx, s.customer, []string{sessionID}) + s.Require().NoError(err) + s.Empty(kept, "the refused call's leg is kept") +} + +func (s *AppsSuite) TestACallIsNotPlacedIntoACallThatArrivedForAnotherCustomer() { + s.sealed() + theirs, _ := s.another() + for name, app := range map[string]int64{"unpinned": 0, "pinned to the deployment's app": 1} { + s.Run(name, func() { + call := uuid.NewString() + s.arrived(theirs, call, app) + + s.refusedTaken(call) + s.Nil(s.deployment.Call(defaultCallType, call), "the other customer's call is untouched") + }) + } +} + +func (s *AppsSuite) TestACallIsNotPlacedIntoACallAnotherCustomerPlaced() { + s.sealed() + theirs, e164 := s.another() + for name, session := range map[string]string{"a session chosen": "", "a session named": uuid.NewString()} { + s.Run(name, func() { + placed, err := s.service.Call(s.ctx, CallRequest{Owner: routing.Owner{CustomerID: theirs}, From: e164, To: "+15550002222", SessionID: session}) + s.Require().NoError(err) + + s.refusedTaken(placed.SessionID) + }) + } +} + +func (s *AppsSuite) TestACallIsPlacedIntoACallThatArrivedForTheSameCustomer() { + s.sealed() + call := uuid.NewString() + s.arrived(s.customer, call, 0) + + s.Require().NoError(s.dialInto(call, "+15550001111", nil)) + s.NoError(s.dialInto(call, "+15550001112", nil), "and again") +} + +func (s *AppsSuite) TestACallIsPlacedIntoASessionOfTheNameAnotherAppsCallHas() { + s.ownApp() + s.sealed() + theirs, _ := s.another() + call := uuid.NewString() + s.arrived(theirs, call, 0) + + s.NoError(s.dialInto(call, "+15550001111", nil)) +} + +// Of two customers placing into one id at once, one at most is put on the call. +func (s *AppsSuite) TestTwoCustomersPlacingIntoOneSessionAtOnceAreNotBothOnItsCall() { + s.sealed() + theirs, e164 := s.another() + for range 10 { + session := uuid.NewString() + errs := make([]error, 2) + var wg sync.WaitGroup + for i, request := range []CallRequest{ + {Owner: routing.Owner{CustomerID: s.customer}, From: s.e164}, + {Owner: routing.Owner{CustomerID: theirs}, From: e164}, + } { + request.To, request.SessionID = "+15550001111", session + wg.Go(func() { _, errs[i] = s.service.Call(s.ctx, request) }) + } + wg.Wait() + + s.True(errors.Is(errs[0], ErrSessionTaken) != errors.Is(errs[1], ErrSessionTaken), "%v", errs) + } +} + +func (s *AppsSuite) TestACampaignDoesNotTryACallIntoATakenSessionAgain() { + s.sealed() + theirs, _ := s.another() + call := uuid.NewString() + s.arrived(theirs, call, 0) + + s.NotErrorIs(s.dialInto(call, "+15550001111", nil), ErrNotDialed) +} diff --git a/acceleration/internal/phone/service.go b/acceleration/internal/phone/service.go index c79a26ae10..328a288c9e 100644 --- a/acceleration/internal/phone/service.go +++ b/acceleration/internal/phone/service.go @@ -176,6 +176,8 @@ type Apps interface { // wherever reading that app does: a line in the deployment's app that the customer may // no longer add to is still the router's own to take down, and one left there is billed. ForAppRemoving(ctx context.Context, customer string, app int64) (*Stream, error) + // DeploymentApp is the deployment's own app's id, zero while it is not known. + DeploymentApp() int64 } // ErrNoStream is a service with no Stream app to make lines in: a deployment without Stream @@ -226,6 +228,15 @@ func (s *Service) streamFor(ctx context.Context, customer string) (*Stream, int6 return s.stream, 0, nil } +// scopeOf is the rows of the Stream app a pin names. +func (s *Service) scopeOf(pin int64) store.AppScope { + var deployment int64 + if s.apps != nil { + deployment = s.apps.DeploymentApp() + } + return store.AppOf(pin, deployment) +} + // streamForApp is the app a line already made is in. func (s *Service) streamForApp(ctx context.Context, customer string, app int64) (*Stream, error) { if s.apps != nil { @@ -1194,6 +1205,9 @@ type Placed struct { StreamApp int64 } +// ErrSessionTaken is a call into a session whose call is another customer's. +var ErrSessionTaken = errors.New("phone: the session id is taken") + // Call places an outbound call and bridges it into a Stream call. // // Stream's SIP is inbound only, so the vendor originates the call and connects it to a @@ -1222,7 +1236,7 @@ func lasting(err error) bool { return errors.Is(err, ErrInvalid) || errors.Is(err, store.ErrNoNumber) || errors.Is(err, store.ErrNoSIPTrunk) || errors.Is(err, ErrNoStream) || errors.Is(err, ErrNoSealerToCall) || errors.Is(err, ErrNotConfigured) || errors.Is(err, ErrSIPTrunksDisabled) || - errors.Is(err, errLasting) || (err != nil && streamapp.Settled(err)) + errors.Is(err, errLasting) || errors.Is(err, ErrSessionTaken) || (err != nil && streamapp.Settled(err)) } // errLasting marks a failure that has no kind of its own and that a second try meets again: a @@ -1340,6 +1354,18 @@ func (s *Service) call(ctx context.Context, request CallRequest, sent *bool) (Pl s.forgetOutcome(ctx, token, callID) } }() + // A leg is routed into agent:, so a session id somebody named has to be a call of + // the customer's. Asked once its own leg is kept, so of two customers placing into one id at + // once each sees the other's. + if request.SessionID != "" { + owner, err := s.store.CallLegs.Owner(ctx, s.scopeOf(pin), callType, callID) + if err != nil { + return Placed{}, err + } + if owner != "" && owner != request.Owner.CustomerID { + return Placed{}, stack.Wrap(ErrSessionTaken) + } + } // Its leg counts against the organization it was placed under once it is dialled too. if room.OrganizationID != "" { request.Owner.OrganizationID = room.OrganizationID diff --git a/acceleration/internal/session/manager.go b/acceleration/internal/session/manager.go index 444ef4de46..d742dd846b 100644 --- a/acceleration/internal/session/manager.go +++ b/acceleration/internal/session/manager.go @@ -511,6 +511,17 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er if stream.Client == nil && m.options.Stream != nil && m.options.Stream.PerApp() { spec.StreamApp = store.ForeignStreamApp } + // The agent joins agent:, and calls are placed and people brought into it. An id + // generated just now names no call yet, and a reopened session's is its own. + if spec.Reopened.IsZero() && !generated { + taken, err := m.callTaken(ctx, spec) + if err != nil { + return nil, stack.Wrap(err) + } + if taken { + return nil, stack.Wrap(ErrSessionExists) + } + } var remembering *metered.Memory if spec.Memory.UserID != "" { @@ -1118,6 +1129,9 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er // the strength of it has somewhere to forward it to. if m.options.Directory != nil { m.options.Directory.Hold(ctx, spec.CustomerID, created.id, spec.AgentID, spec.ConversationID) + if spec.StreamApp != store.ForeignStreamApp { + m.options.Directory.HoldCall(ctx, spec.CustomerID, created.id, m.callApp(spec.StreamApp)) + } } // Asked again now the session is held: a status that came while the call was being // joined found no session to end, and one that comes after this finds it. The session @@ -2241,6 +2255,39 @@ func (m *Manager) stream(ctx context.Context, spec Spec, newCall bool) (streamap return bound, nil } +// callApp is the Stream app pinned app as the directory holds a call in it: zero for the +// deployment's own, whether the session is pinned to its id or to none. +func (m *Manager) callApp(app int64) int64 { + if m.options.Stream != nil && app == m.options.Stream.DeploymentApp() { + return 0 + } + return app +} + +// callTaken reports whether the call a session is named after, agent: in the Stream app it +// acts in, is another customer's: by its phone legs, or by the session some node runs on it. A +// session that acts in no Stream app has no call. +func (m *Manager) callTaken(ctx context.Context, spec Spec) (bool, error) { + if spec.StreamApp == store.ForeignStreamApp { + return false, nil + } + if m.options.Store != nil { + var deployment int64 + if m.options.Stream != nil { + deployment = m.options.Stream.DeploymentApp() + } + owner, err := m.options.Store.CallLegs.Owner(ctx, store.AppOf(spec.StreamApp, deployment), streamapp.AgentCallType, spec.ID) + if err != nil || owner != "" && owner != spec.CustomerID { + return err == nil, err + } + } + if m.options.Directory == nil { + return false, nil + } + holder, err := m.options.Directory.CallHolder(ctx, m.callApp(spec.StreamApp), spec.ID) + return holder != "" && holder != spec.CustomerID, err +} + // hookPinFor is how long a hook's app is remembered for the session it starts. const hookPinFor = 10 * time.Minute diff --git a/acceleration/internal/store/call_leg.go b/acceleration/internal/store/call_leg.go index 1ca5ac181f..a2fa330810 100644 --- a/acceleration/internal/store/call_leg.go +++ b/acceleration/internal/store/call_leg.go @@ -380,8 +380,40 @@ type legMatch struct { revive bool } +// onCall keeps the legs that make a call their customer's: those open, and those a phone was on. +func onCall(q bun.QueryBuilder) bun.QueryBuilder { + return q.WhereGroup(" AND ", func(q bun.QueryBuilder) bun.QueryBuilder { + return q.Where("ended_at IS NULL").WhereOr("participant_session <> ''") + }) +} + +// Owner is the customer a call is, in one app: the one whose leg was on it first, in any shard. +// It is empty for a call no leg is on. +func (r *CallLegs) Owner(ctx context.Context, scope AppScope, callType, callID string) (string, error) { + type first struct { + CustomerID string + At time.Time + } + lists, err := everyShard(ctx, r.store, func(ctx context.Context, db bun.IDB) ([]first, error) { + var found []first + err := db.NewSelect().Model((*CallLeg)(nil)).Column("customer_id").ColumnExpr("COALESCE(placed_at, dialed_at) AS at"). + Where("call_type = ?", callType).Where("call_id = ?", callID). + ApplyQueryBuilder(scope.where).ApplyQueryBuilder(onCall). + OrderExpr("at, id").Limit(1).Scan(ctx, &found) + return found, err + }) + if err != nil { + return "", stack.Wrap(fmt.Errorf("store: call owner: %w", err)) + } + if owner := merged(lists, func(a, b first) int { return a.At.Compare(b.At) }, 1); len(owner) > 0 { + return owner[0].CustomerID, nil + } + return "", nil +} + // connectWaitingLeg gives the phone the first leg of the call, across the shards, that match -// keeps. +// keeps. A leg that came to a call after another customer's is given no phone: the call is the +// other's (Owner). func (r *CallLegs) connectWaitingLeg(ctx context.Context, scope AppScope, callType, callID, sessionID, participant string, match legMatch, at time.Time, left *time.Time) (CallLeg, Connection, error) { var leftAt any @@ -392,7 +424,12 @@ func (r *CallLegs) connectWaitingLeg(ctx context.Context, scope AppScope, callTy waiting := db.NewSelect().Model((*CallLeg)(nil)).Column("id"). Where("call_type = ?", callType).Where("call_id = ?", callID). Where("participant_session = ''"). - ApplyQueryBuilder(scope.where) + ApplyQueryBuilder(scope.where). + Where("NOT EXISTS (?)", db.NewSelect().TableExpr("call_legs AS o").ColumnExpr("1"). + Where("call_type = ?", callType).Where("call_id = ?", callID). + ApplyQueryBuilder(scope.where).ApplyQueryBuilder(onCall). + Where("o.customer_id <> cl.customer_id"). + Where("COALESCE(o.placed_at, o.dialed_at) < COALESCE(cl.placed_at, cl.dialed_at)")) if match.revive { waiting = waiting.Where("direction = ?", Outbound).Where("end_reason = ?", LegUnanswered). Where("ended_at > GREATEST(?::timestamptz, dialed_at)", at) diff --git a/acceleration/internal/store/call_leg_test.go b/acceleration/internal/store/call_leg_test.go index 1bbf6c8072..27cfe84d0c 100644 --- a/acceleration/internal/store/call_leg_test.go +++ b/acceleration/internal/store/call_leg_test.go @@ -396,6 +396,11 @@ func (s *StoreSuite) TestCallLegQueryBudgets() { s.Require().NoError(err) s.True(ringing) }), "Ringing") + s.Equal(shards, s.countQueries(func() { + owner, err := s.store.CallLegs.Owner(s.ctx, scope, "default", "call-1") + s.Require().NoError(err) + s.NotEmpty(owner) + }), "Owner") s.Equal(shards+1, s.countQueries(func() { _, connection, err := s.store.CallLegs.Connect(s.ctx, scope, "default", "call-1", "session", "phone-1", "+15125550101", s.base, nil) s.Require().NoError(err) @@ -689,3 +694,122 @@ func (s *StoreSuite) TestADialNamingNoOrganizationKeepsTheOneTheCallWasPlacedUnd s.Equal("org", dialed.OrganizationID, "still counted among the organization's calls") } + +// onCall opens a leg of customer's on the call in app, dialled at. +func (s *StoreSuite) onCall(customer, callID string, app int64, at time.Time) CallLeg { + leg := CallLeg{CustomerID: customer, StreamAppPK: app, CallType: "agent", CallID: callID, Vendor: "telnyx", + VendorCallID: customer + at.String(), Direction: Outbound, LocalNumber: "+15125550150", RemoteNumber: "+15125550151", DialedAt: at} + opened, err := s.store.CallLegs.Open(s.ctx, &leg) + s.Require().NoError(err) + s.Require().True(opened) + return leg +} + +func (s *StoreSuite) ownerOf(scope AppScope, callID string) string { + owner, err := s.store.CallLegs.Owner(s.ctx, scope, "agent", callID) + s.Require().NoError(err) + return owner +} + +func (s *StoreSuite) TestACallIsTheCustomersWhoseLegWasOnItFirst() { + s.onCall("later", "call", 0, s.base.Add(time.Second)) + s.onCall("first", "call", 0, s.base) + + s.Equal("first", s.ownerOf(AppScope{Unpinned: true}, "call")) + s.Empty(s.ownerOf(AppScope{Unpinned: true}, "another call")) + other, err := s.store.CallLegs.Owner(s.ctx, AppScope{Unpinned: true}, "default", "call") + s.Require().NoError(err) + s.Empty(other, "a call of another type") +} + +func (s *StoreSuite) TestACallIsTheCustomersWhoPlacedItBeforeItIsDialled() { + s.placedLeg("placing", func(leg *CallLeg) { leg.CallType = "agent" }) + s.onCall("later", "call", 0, s.base.Add(time.Second)) + + s.Equal("app", s.ownerOf(AppScope{Unpinned: true}, "call")) +} + +func (s *StoreSuite) TestACallIsOwnedInItsOwnStreamApp() { + s.onCall("theirs", "call", 7, s.base) + s.onCall("mine", "call", 8, s.base.Add(time.Second)) + s.onCall("pinned", "shared", 1, s.base) + + s.Equal("mine", s.ownerOf(AppOf(8, 1), "call")) + s.Empty(s.ownerOf(AppOf(0, 1), "call")) + s.Equal("pinned", s.ownerOf(AppOf(0, 1), "shared"), "the deployment's app, pinned to its id") + s.Equal("pinned", s.ownerOf(AppOf(1, 1), "shared")) + s.onCall("unpinned", "older", 0, s.base) + s.Equal("unpinned", s.ownerOf(AppOf(1, 1), "older")) +} + +func (s *StoreSuite) TestACallSomebodyWasOnStaysTheirsAndOneNobodyAnsweredDoesNot() { + s.onCall("answered", "held", 0, s.base) + s.onCall("unanswered", "rang", 0, s.base) + scope := AppScope{Unpinned: true} + _, connection, err := s.store.CallLegs.Connect(s.ctx, scope, "agent", "held", "session", "phone", "+15125550151", s.base, nil) + s.Require().NoError(err) + s.Require().Equal(LegConnected, connection) + for _, call := range []string{"held", "rang"} { + _, err := s.store.CallLegs.EndCall(s.ctx, scope, "agent", call, s.base.Add(time.Minute)) + s.Require().NoError(err) + } + + s.Equal("answered", s.ownerOf(scope, "held")) + s.Empty(s.ownerOf(scope, "rang")) +} + +func (s *StoreSuite) TestAPhoneIsNotGivenALegThatCameToAnotherCustomersCall() { + scope := AppScope{Unpinned: true} + mine := s.onCall("first", "call", 0, s.base) + s.onCall("later", "call", 0, s.base.Add(time.Second)) + + given, connection, err := s.store.CallLegs.Connect(s.ctx, scope, "agent", "call", "session", "phone-1", "", s.base.Add(time.Minute), nil) + s.Require().NoError(err) + s.Require().Equal(LegConnected, connection) + s.Equal(mine.ID, given.ID) + + _, connection, err = s.store.CallLegs.Connect(s.ctx, scope, "agent", "call", "session", "phone-2", "+15125550151", s.base.Add(time.Minute), nil) + s.Require().NoError(err) + s.Equal(NothingWaiting, connection, "the second phone is given the other customer's leg") + _, err = s.store.CallLegs.EndCall(s.ctx, scope, "agent", "call", s.base.Add(2*time.Minute)) + s.Require().NoError(err) + _, connection, err = s.store.CallLegs.Connect(s.ctx, scope, "agent", "call", "session", "phone-2", "+15125550151", s.base.Add(time.Minute), nil) + s.Require().NoError(err) + s.Equal(NothingWaiting, connection, "nor is it revived") +} + +// Another app's call of the same name, another type's call and a call nobody answered keep no +// phone from its leg, nor does a second leg of the customer's own. +func (s *StoreSuite) TestAPhoneIsGivenItsLegWhateverElseIsOfTheCallsName() { + scope := AppScope{Unpinned: true} + s.onCall("theirs", "call", 7, s.base) + s.placedLeg("another type", nil) + s.onCall("gone", "call", 0, s.base) + _, err := s.store.CallLegs.EndCall(s.ctx, scope, "agent", "call", s.base.Add(time.Second)) + s.Require().NoError(err) + first := s.onCall("mine", "call", 0, s.base.Add(time.Minute)) + second := s.onCall("mine", "call", 0, s.base.Add(2*time.Minute)) + + for i, want := range []CallLeg{first, second} { + given, connection, err := s.store.CallLegs.Connect(s.ctx, scope, "agent", "call", "session", fmt.Sprintf("phone-%d", i), "+15125550151", s.base.Add(time.Hour), nil) + s.Require().NoError(err) + s.Require().Equal(LegConnected, connection) + s.Equal(want.ID, given.ID) + } +} + +// A placed leg is on its call from when it was placed, however long its dial took. +func (s *StoreSuite) TestAPhoneIsGivenTheLegPlacedBeforeAnotherCustomersWasDialled() { + placed := s.base + mine := CallLeg{CustomerID: "mine", CallType: "agent", CallID: "call", Vendor: "telnyx", Direction: Outbound, + LocalNumber: "+15125550150", RemoteNumber: "+15125550152", PlacedAt: &placed, DialedAt: s.base.Add(time.Minute)} + opened, err := s.store.CallLegs.Open(s.ctx, &mine) + s.Require().NoError(err) + s.Require().True(opened) + s.onCall("theirs", "call", 0, s.base.Add(time.Second)) + + given, connection, err := s.store.CallLegs.Connect(s.ctx, AppScope{Unpinned: true}, "agent", "call", "session", "phone", "", s.base.Add(time.Hour), nil) + s.Require().NoError(err) + s.Require().Equal(LegConnected, connection) + s.Equal(mine.ID, given.ID) +} diff --git a/acceleration/internal/store/hooks.go b/acceleration/internal/store/hooks.go index e92841979e..d2d0864a6c 100644 --- a/acceleration/internal/store/hooks.go +++ b/acceleration/internal/store/hooks.go @@ -18,6 +18,15 @@ type AppScope struct { Unpinned bool } +// AppOf is the scope of the Stream app a pin names, deployment being the deployment's own app's +// id: the rows of that app include those written there with no pin. +func AppOf(pin, deployment int64) AppScope { + if pin == 0 || pin == deployment { + return AppScope{App: deployment, Unpinned: true} + } + return AppScope{App: pin} +} + // where narrows a query, of any kind, to the rows in the scope's app. func (a AppScope) where(query bun.QueryBuilder) bun.QueryBuilder { return query.WhereGroup(" AND ", func(q bun.QueryBuilder) bun.QueryBuilder { diff --git a/acceleration/internal/store/store_explain_test.go b/acceleration/internal/store/store_explain_test.go index e07ddd375a..a98c403154 100644 --- a/acceleration/internal/store/store_explain_test.go +++ b/acceleration/internal/store/store_explain_test.go @@ -415,6 +415,10 @@ func (s *StoreSuite) TestEveryHotTableIsReadByIndex() { _, err := store.CallLegs.Ringing(ctx, AppScope{App: 3}, "default", "stream-101") return err }}, + {name: "CallLegs.Owner", index: "call_legs_call_idx", run: func(ctx context.Context, store *Store) error { + _, err := store.CallLegs.Owner(ctx, AppScope{App: 3}, "default", "stream-101") + return err + }}, {name: "CallLegs.HasParticipant", index: "call_legs_participant_idx", run: func(ctx context.Context, store *Store) error { _, err := store.CallLegs.HasParticipant(ctx, app, "default", "stream-100", "phone-100") return err From cbc6a5ca86ac53f097ff7de60034f9243f2c7413 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Tue, 24 Nov 2026 23:30:20 +0000 Subject: [PATCH 02/23] test(phone): cover the caller's own session on another node --- acceleration/internal/api/forward_test.go | 6 +++--- acceleration/internal/api/phone_test.go | 12 ++++++++++++ acceleration/internal/api/session_create_test.go | 2 +- acceleration/internal/session/manager.go | 7 ++----- acceleration/internal/store/call_leg_test.go | 3 ++- 5 files changed, 20 insertions(+), 10 deletions(-) diff --git a/acceleration/internal/api/forward_test.go b/acceleration/internal/api/forward_test.go index 02c6e4f6af..358de866c7 100644 --- a/acceleration/internal/api/forward_test.go +++ b/acceleration/internal/api/forward_test.go @@ -178,11 +178,11 @@ func (s *ForwardedSessionSuite) TestAMessageNamingNoCustomerOnAChannelTwoCustome "one of the customers' sessions answered a message nothing says is theirs") } -// Two customers may each run a session of one id, each on a node of its own: a request reaches -// the session of the caller's own customer, wherever it lands. +// Two customers in Stream apps of their own may each run a session of one id, each on a node of +// its own: a request reaches the session of the caller's own customer, wherever it lands. func (s *ForwardedSessionSuite) TestARequestReachesTheSessionOfTheCallersCustomerOfAnIdTwoRun() { id := s.utils.uuid() - other := s.data.backendOfAnotherApp() + other := s.backendInAppOfItsOwn() mine := s.serverClient.createSession(CreateSessionRequest{Id: &id, Incognito: pointerTo(true), Llm: pointerTo("llm-flow")}) theirs := other.on(s.other).createSession(CreateSessionRequest{Id: &id, Incognito: pointerTo(true), Llm: pointerTo("echo/echo-model")}) third := s.otherNode() diff --git a/acceleration/internal/api/phone_test.go b/acceleration/internal/api/phone_test.go index e1dae3fe65..8eed866a3f 100644 --- a/acceleration/internal/api/phone_test.go +++ b/acceleration/internal/api/phone_test.go @@ -1525,3 +1525,15 @@ func (s *CallStatusSuite) TestASessionOfNoStreamAppIsOnNoCallOfAnothers() { s.Equal(http.StatusCreated, s.serverClient.do(http.MethodPost, "/v1/agents/sessions", request, nil)) } + +func (s *CallStatusSuite) TestASessionMayBeCreatedUnderTheIdOfTheCallersOnAnotherNode() { + s.useApp(s.data.createApp()) + _, _, sessions := s.otherNodeHolding(nil, s.sealer, slog.New(slog.DiscardHandler)) + opened, err := sessions.Create(context.Background(), session.Spec{CustomerID: s.customerID(), Text: true, + Incognito: true, Attribution: routing.Attribution{APIKey: "key"}}) + s.Require().NoError(err) + request := textSession(pointerTo(opened.ID())) + request.Incognito = pointerTo(true) + + s.Equal(http.StatusCreated, s.serverClient.do(http.MethodPost, "/v1/agents/sessions", request, nil)) +} diff --git a/acceleration/internal/api/session_create_test.go b/acceleration/internal/api/session_create_test.go index 64f9e4b021..918ef21a34 100644 --- a/acceleration/internal/api/session_create_test.go +++ b/acceleration/internal/api/session_create_test.go @@ -313,7 +313,7 @@ func (s *SessionCreateSuite) TestACustomerSharingAStreamAppIsRefusedAnIdAnotherH } // backendInAppOfItsOwn is the backend of a new customer acting in a Stream app of its own. -func (s *SessionCreateSuite) backendInAppOfItsOwn() *testClient { +func (s *RouterSuite) backendInAppOfItsOwn() *testClient { id := streamAppID() app := s.numberedApp(id) s.giveApp(app.app.ID, id, "key-"+app.app.ID) diff --git a/acceleration/internal/session/manager.go b/acceleration/internal/session/manager.go index d742dd846b..fb63149ccc 100644 --- a/acceleration/internal/session/manager.go +++ b/acceleration/internal/session/manager.go @@ -1129,6 +1129,7 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er // the strength of it has somewhere to forward it to. if m.options.Directory != nil { m.options.Directory.Hold(ctx, spec.CustomerID, created.id, spec.AgentID, spec.ConversationID) + // A session that acts in no Stream app has no call. if spec.StreamApp != store.ForeignStreamApp { m.options.Directory.HoldCall(ctx, spec.CustomerID, created.id, m.callApp(spec.StreamApp)) } @@ -2265,12 +2266,8 @@ func (m *Manager) callApp(app int64) int64 { } // callTaken reports whether the call a session is named after, agent: in the Stream app it -// acts in, is another customer's: by its phone legs, or by the session some node runs on it. A -// session that acts in no Stream app has no call. +// acts in, is another customer's: by its phone legs, or by the session some node runs on it. func (m *Manager) callTaken(ctx context.Context, spec Spec) (bool, error) { - if spec.StreamApp == store.ForeignStreamApp { - return false, nil - } if m.options.Store != nil { var deployment int64 if m.options.Stream != nil { diff --git a/acceleration/internal/store/call_leg_test.go b/acceleration/internal/store/call_leg_test.go index 27cfe84d0c..aa92621026 100644 --- a/acceleration/internal/store/call_leg_test.go +++ b/acceleration/internal/store/call_leg_test.go @@ -778,12 +778,13 @@ func (s *StoreSuite) TestAPhoneIsNotGivenALegThatCameToAnotherCustomersCall() { s.Equal(NothingWaiting, connection, "nor is it revived") } -// Another app's call of the same name, another type's call and a call nobody answered keep no +// Another call, another app's call of the same name, another type's and a call nobody answered keep no // phone from its leg, nor does a second leg of the customer's own. func (s *StoreSuite) TestAPhoneIsGivenItsLegWhateverElseIsOfTheCallsName() { scope := AppScope{Unpinned: true} s.onCall("theirs", "call", 7, s.base) s.placedLeg("another type", nil) + s.onCall("theirs", "another call", 0, s.base) s.onCall("gone", "call", 0, s.base) _, err := s.store.CallLegs.EndCall(s.ctx, scope, "agent", "call", s.base.Add(time.Second)) s.Require().NoError(err) From 895bbaba4250abe39527e3fa0109cccf56489bb9 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Tue, 24 Nov 2026 23:38:47 +0000 Subject: [PATCH 03/23] test(phone): a session id of the test's own --- acceleration/internal/phone/apps_integration_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/acceleration/internal/phone/apps_integration_test.go b/acceleration/internal/phone/apps_integration_test.go index cd8f18c230..d6f6a58561 100644 --- a/acceleration/internal/phone/apps_integration_test.go +++ b/acceleration/internal/phone/apps_integration_test.go @@ -1196,7 +1196,7 @@ func (s *AppsSuite) TestAnAttachedNumbersCallersEachLandInACallOfTheirOwn() { } func (s *AppsSuite) TestAPlacedCallLandsInTheCallOfTheSessionItWasPlacedFor() { - id := "0b9f2a52-5c1e-4d7a-9a3e-0f6b8f1c2d3e" + id := uuid.NewString() placed, err := s.service.Call(s.ctx, CallRequest{ Owner: routing.Owner{CustomerID: s.customer}, From: s.e164, To: "+15550001111", SessionID: id, From 493e046fd873e162ec57cafa1275d3e0ea5ee301 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 00:49:27 +0000 Subject: [PATCH 04/23] fix(phone): claim a named call under one lock --- acceleration/internal/api/callhooks.go | 2 +- acceleration/internal/api/money.go | 3 + acceleration/internal/api/phone.go | 32 +-- acceleration/internal/api/phone_test.go | 226 ++++++++++++++++-- .../internal/api/router_suite_test.go | 5 - .../internal/api/scheduled_delivery.go | 3 +- acceleration/internal/campaign/campaign.go | 2 +- acceleration/internal/campaign/dialer.go | 2 +- acceleration/internal/node/directory.go | 132 +++++++--- acceleration/internal/node/directory_test.go | 92 ++++--- .../internal/phone/apps_integration_test.go | 87 ++++++- acceleration/internal/phone/outcome/keeper.go | 14 +- acceleration/internal/phone/service.go | 53 ++-- acceleration/internal/session/manager.go | 93 ++++--- acceleration/internal/session/spec.go | 5 +- acceleration/internal/store/call_leg.go | 225 ++++++++++++----- acceleration/internal/store/call_leg_test.go | 219 +++++++++++------ .../internal/store/store_explain_test.go | 4 +- 18 files changed, 885 insertions(+), 314 deletions(-) diff --git a/acceleration/internal/api/callhooks.go b/acceleration/internal/api/callhooks.go index afa6e7b810..78ea1c7c89 100644 --- a/acceleration/internal/api/callhooks.go +++ b/acceleration/internal/api/callhooks.go @@ -338,7 +338,7 @@ func (s *Server) answerWithAgent(ctx context.Context, sessions *session.Manager, } spec := session.FromConfig(config) // The number names each caller's call for the session answering it, as dispatch does. - spec.ID = callID + spec.ID, spec.MintedID = callID, true spec.CallType, spec.CallID = callType, callID spec.Text = false spec.PersistConversation = true diff --git a/acceleration/internal/api/money.go b/acceleration/internal/api/money.go index 045b72ec9a..6cdcb5d6d2 100644 --- a/acceleration/internal/api/money.go +++ b/acceleration/internal/api/money.go @@ -15,6 +15,7 @@ import ( "github.com/GetStream/Vision-Agents/acceleration/internal/policy" "github.com/GetStream/Vision-Agents/acceleration/internal/routing" "github.com/GetStream/Vision-Agents/acceleration/internal/session" + "github.com/GetStream/Vision-Agents/acceleration/internal/store" "github.com/GetStream/Vision-Agents/acceleration/internal/streamapp" ) @@ -110,6 +111,8 @@ func refusedRequest(err error) error { return answer } switch { + case errors.Is(err, store.ErrCallUnchecked): + return errCallUnchecked case errors.Is(err, session.ErrToolNotConfigured): return toolNotConfigured(err) case errors.Is(err, session.ErrNoMemory): diff --git a/acceleration/internal/api/phone.go b/acceleration/internal/api/phone.go index 0ecda938bc..a90ef14647 100644 --- a/acceleration/internal/api/phone.go +++ b/acceleration/internal/api/phone.go @@ -410,6 +410,9 @@ func (s *Server) placePhoneCall(ctx context.Context, request *placePhoneCallRequ return nil, errSessionTaken } call.SessionID = held + if s.directory != nil { + call.Holder = s.directory.CallHolder + } } if request.Body.RingTimeoutSeconds != nil { if *request.Body.RingTimeoutSeconds < 0 { @@ -435,9 +438,12 @@ func (s *Server) placePhoneCall(ctx context.Context, request *placePhoneCallRequ if failure, over := tierLimitReached(err); over { return nil, failure } - if errors.Is(err, phone.ErrSessionTaken) { + if errors.Is(err, store.ErrCallTaken) { return nil, errSessionTaken } + if errors.Is(err, store.ErrCallUnchecked) { + return nil, errCallUnchecked + } if errors.Is(err, dlc.ErrRefused) || errors.Is(err, phone.ErrDestinationRefused) { return nil, forbidden(err.Error()) } @@ -1008,6 +1014,9 @@ func phoneTags(tags *map[string]string) routing.Tags { var errSessionTaken = conflict("session_id is taken") +// errCallUnchecked refuses a session id whose call the router could not tell the customer of. +var errCallUnchecked = unavailable("could not tell whose call that session id is, try again") + var errNoTelephony = notConfigured("phone numbers are not available: no telephony configured") // callApp is the Stream app a live call is in, which a human transferred into it has to be @@ -1041,26 +1050,11 @@ func (s *Server) anotherCustomersSession(ctx context.Context, customerID, id str return false, nil } taken, err := s.store.Sessions.Exists(ctx, id) - if err != nil { + if err != nil || !taken { return false, err } - if taken { - _, err = s.store.Sessions.Get(ctx, customerID, id) - return err != nil, nil - } - // A session another node runs may have no row yet, and an incognito one never has. - if s.directory == nil || s.stream == nil { - return false, nil - } - app, err := s.stream.Pin(ctx, customerID) - if err != nil { - return false, phoneFailure(s.logger, err) - } - if app == s.stream.DeploymentApp() { - app = 0 - } - holder, err := s.directory.CallHolder(ctx, app, id) - return holder != "" && holder != customerID, err + _, err = s.store.Sessions.Get(ctx, customerID, id) + return err != nil, nil } // callPinApp is the Stream app a call no session is running in is in: the app its lines were diff --git a/acceleration/internal/api/phone_test.go b/acceleration/internal/api/phone_test.go index 8eed866a3f..ca4d1a1ef3 100644 --- a/acceleration/internal/api/phone_test.go +++ b/acceleration/internal/api/phone_test.go @@ -5,18 +5,25 @@ package api import ( "context" "encoding/json" + "errors" "io" "log/slog" + "net" "net/http" "net/http/httptest" "net/url" "os" "strings" + "sync" + "sync/atomic" "testing" "time" getstream "github.com/GetStream/getstream-go/v5" + "github.com/redis/rueidis" + "github.com/GetStream/Vision-Agents/acceleration/internal/agent" + "github.com/GetStream/Vision-Agents/acceleration/internal/auth" "github.com/GetStream/Vision-Agents/acceleration/internal/node" "github.com/GetStream/Vision-Agents/acceleration/internal/phone" "github.com/GetStream/Vision-Agents/acceleration/internal/phone/outcome" @@ -1444,17 +1451,6 @@ func (s *CallStatusSuite) TestASessionCannotBeCreatedUnderTheIdOfAnotherCustomer s.Equal(http.StatusConflict, s.serverClient.do(http.MethodPost, "/v1/agents/sessions", textSession(&id), nil)) } -func (s *CallStatusSuite) TestACallIntoASessionOfACustomerWhoseAppIsDisconnectedIsAnInvalidRequest() { - s.useApp(s.data.createApp()) - s.setApps(s.customerID(), func(apps *suiteApps) { - apps.refused = map[string]error{s.customerID(): streamapp.ErrStreamAppDisconnected} - }) - - status, payload := s.callInto(s.utils.uuid()) - - s.Equal(http.StatusBadRequest, status, payload) -} - // A customer in a Stream app of its own names its sessions without regard to another app's. func (s *CallStatusSuite) TestASessionMayBeCreatedUnderTheNameOfAnotherAppsCall() { s.useApp(s.data.createApp()) @@ -1469,19 +1465,6 @@ func (s *CallStatusSuite) TestASessionMayBeCreatedUnderTheNameOfAnotherAppsCall( s.Equal(http.StatusCreated, s.serverClient.do(http.MethodPost, "/v1/agents/sessions", textSession(pointerTo(opened.ID())), nil)) } -func (s *CallStatusSuite) TestACallMayBeRoutedUnderTheNameOfAnotherAppsSessionOnAnotherNode() { - s.useApp(s.data.createApp()) - s.giveApp(s.customerID(), streamAppID(), "key-"+s.customerID()) - _, _, sessions := s.otherNodeHolding(nil, s.sealer, slog.New(slog.DiscardHandler)) - opened, err := sessions.Create(context.Background(), session.Spec{CustomerID: "customer-" + s.utils.uuid(), Text: true, - Incognito: true, Attribution: routing.Attribution{APIKey: "key"}}) - s.Require().NoError(err) - - status, payload := s.callInto(opened.ID()) - - s.Equal(http.StatusServiceUnavailable, status, payload) -} - // A customer whose work is pinned to the deployment's app's id and one pinned to none act in one // app. func (s *CallStatusSuite) TestACallCannotBeRoutedIntoASessionOfTheDeploymentsAppWhicheverWayEitherIsPinned() { @@ -1537,3 +1520,198 @@ func (s *CallStatusSuite) TestASessionMayBeCreatedUnderTheIdOfTheCallersOnAnothe s.Equal(http.StatusCreated, s.serverClient.do(http.MethodPost, "/v1/agents/sessions", request, nil)) } + +// heldOn opens an incognito session of a customer's with sessions, in writing. +func heldOn(sessions *session.Manager, customer, id string) error { + _, err := sessions.Create(context.Background(), session.Spec{CustomerID: customer, ID: id, Text: true, + Incognito: true, Attribution: routing.Attribution{APIKey: "key"}}) + return err +} + +func (s *CallStatusSuite) TestOfTwoCustomersCreatingOneIdAtOnceOnTwoNodesOneIsLetIn() { + s.useApp(s.data.createApp()) + _, _, first := s.otherNodeHolding(nil, s.sealer, slog.New(slog.DiscardHandler)) + _, _, second := s.otherNodeHolding(nil, s.sealer, slog.New(slog.DiscardHandler)) + for range 20 { + id := s.utils.uuid() + var errs [2]error + var wg sync.WaitGroup + for i, sessions := range []*session.Manager{first, second} { + wg.Go(func() { errs[i] = heldOn(sessions, "customer-"+s.utils.uuid(), id) }) + } + wg.Wait() + + s.True(errors.Is(errs[0], session.ErrSessionExists) != errors.Is(errs[1], session.ErrSessionExists), "%v", errs) + } +} + +// A call being kept and a session opening under its id are one before the other, however long +// the leg takes to keep. +func (s *CallStatusSuite) TestASessionOpenedWhileAnotherCustomersCallIsPlacedIntoItsIdIsRefused() { + s.useApp(s.data.createApp()) + _, _, sessions := s.otherNodeHolding(nil, s.sealer, slog.New(slog.DiscardHandler)) + ctx := context.Background() + _, err := s.store.GlobalDB().ExecContext(ctx, "CREATE OR REPLACE FUNCTION slow_call() RETURNS trigger AS $$ BEGIN IF NEW.customer_id = '"+s.customerID()+ + "' THEN PERFORM pg_sleep(1); END IF; RETURN NEW; END $$ LANGUAGE plpgsql") + s.Require().NoError(err) + _, err = s.store.GlobalDB().ExecContext(ctx, "CREATE OR REPLACE TRIGGER slow_call BEFORE INSERT ON call_legs FOR EACH ROW EXECUTE FUNCTION slow_call()") + s.Require().NoError(err) + defer func() { + _, err := s.store.GlobalDB().ExecContext(ctx, "DROP TRIGGER slow_call ON call_legs; DROP FUNCTION slow_call()") + s.Require().NoError(err) + }() + id := s.utils.uuid() + called := make(chan int, 1) + go func() { + status, _ := s.callInto(id) + called <- status + }() + s.Require().Eventually(func() bool { + var asleep bool + s.Require().NoError(s.store.GlobalDB().NewSelect().ColumnExpr("EXISTS (SELECT 1 FROM pg_stat_activity WHERE wait_event = 'PgSleep' AND datname = current_database())").Scan(ctx, &asleep)) + return asleep + }, settleFor, 5*time.Millisecond) + + err = heldOn(sessions, "customer-"+s.utils.uuid(), id) + + s.Equal(http.StatusServiceUnavailable, <-called, "the call is let in, to a vendor nothing answers") + s.ErrorIs(err, session.ErrSessionExists) +} + +// A session carrying on a conversation is on the call of the app the conversation is kept in. +func (s *CallStatusSuite) TestASessionResumedInAnotherAppIsRefusedACallOfAnotherCustomersThere() { + s.useApp(s.data.createApp()) + _, _, sessions := s.otherNodeHolding(nil, s.sealer, slog.New(slog.DiscardHandler)) + spec := session.Spec{CustomerID: s.customerID(), Text: true, PersistConversation: true, Caller: routing.Caller{UserID: "user-" + s.utils.uuid()}, + AgentID: "agent-" + s.utils.uuid(), Attribution: routing.Attribution{APIKey: "key"}} + first, err := sessions.Create(context.Background(), spec) + s.Require().NoError(err) + spec.ConversationID, spec.AgentID = first.Spec().ConversationID, first.Spec().AgentID + s.Require().True(sessions.Close(first.ID(), session.OwnerOf(first.Spec()))) + spec.ID = s.arrivedFor("customer-" + s.utils.uuid()) + s.giveApp(s.customerID(), streamAppID(), "key-"+s.customerID()) + + _, err = sessions.Create(context.Background(), spec) + s.ErrorIs(err, session.ErrSessionExists) + + spec.ID = s.utils.uuid() + resumed, err := sessions.Create(context.Background(), spec) + s.Require().NoError(err) + s.Equal(http.StatusConflict, s.data.backendOfAnotherApp().do(http.MethodPost, "/v1/agents/sessions", textSession(pointerTo(resumed.ID())), nil), + "the session holds its call in the app it acts in") +} + +// A session that ends, or fails to open, leaves its call to whoever opens it next. +func (s *CallStatusSuite) TestACallIsLeftWhenItsSessionEnds() { + s.useApp(s.data.createApp()) + _, _, sessions := s.otherNodeHolding(nil, s.sealer, slog.New(slog.DiscardHandler)) + id, mine := s.utils.uuid(), "customer-"+s.utils.uuid() + s.Require().NoError(heldOn(sessions, mine, id)) + s.ErrorIs(heldOn(s.manager, "customer-"+s.utils.uuid(), id), session.ErrSessionExists) + s.Require().True(sessions.Close(id, session.Owner{CustomerID: mine, Kind: auth.KindServer})) + failing := session.Spec{CustomerID: mine, ID: id, Text: true, PersistConversation: true, ConversationID: "agent:" + s.utils.uuid(), Attribution: routing.Attribution{APIKey: "key"}} + _, err := sessions.Create(context.Background(), failing) + s.Require().Error(err) + + s.NoError(heldOn(s.manager, "customer-"+s.utils.uuid(), id)) +} + +func (s *CallStatusSuite) TestASessionOfAMintedIdOrReopenedIsAskedNothing() { + s.useApp(s.data.createApp()) + theirs := s.arrivedFor("customer-" + s.utils.uuid()) + spec := session.Spec{CustomerID: s.customerID(), ID: theirs, Text: true, Incognito: true, Attribution: routing.Attribution{APIKey: "key"}} + _, err := s.manager.Create(context.Background(), spec) + s.Require().ErrorIs(err, session.ErrSessionExists) + + spec.MintedID = true + minted, err := s.manager.Create(context.Background(), spec) + s.Require().NoError(err) + s.Require().True(s.manager.Close(minted.ID(), session.OwnerOf(minted.Spec()))) + kept := session.Spec{CustomerID: s.customerID(), Text: true, PersistConversation: true, Caller: routing.Caller{UserID: "user-" + s.utils.uuid()}, + AgentID: "agent-" + s.utils.uuid(), Attribution: routing.Attribution{APIKey: "key"}} + first, err := s.manager.Create(context.Background(), kept) + s.Require().NoError(err) + s.Require().True(s.manager.Close(first.ID(), session.OwnerOf(first.Spec()))) + kept.ConversationID, kept.AgentID = first.Spec().ConversationID, first.Spec().AgentID + kept.Reopened, kept.ID = time.Now(), s.arrivedFor("customer-"+s.utils.uuid()) + _, err = s.manager.Create(context.Background(), kept) + s.NoError(err) +} + +// deafRedis is the suite's Redis until deaf is set: from then on it takes what is sent it and +// answers nothing, as a Redis cut off by the network does. +func (s *CallStatusSuite) deafRedis(deaf *atomic.Bool) rueidis.Client { + listener, err := net.Listen("tcp", "127.0.0.1:0") + s.Require().NoError(err) + s.T().Cleanup(func() { _ = listener.Close() }) + go func() { + for { + conn, err := listener.Accept() + if err != nil { + return + } + upstream, err := net.Dial("tcp", os.Getenv("ROUTER_REDIS_ADDR")) + if err != nil { + _ = conn.Close() + continue + } + go func() { + defer upstream.Close() + _, _ = io.Copy(upstream, conn) + }() + go func() { + buffer := make([]byte, 4096) + for { + n, err := upstream.Read(buffer) + if err != nil { + return + } + if deaf.Load() { + continue + } + if _, err := conn.Write(buffer[:n]); err != nil { + return + } + } + }() + } + }() + client, err := rueidis.NewClient(rueidis.ClientOption{InitAddress: []string{listener.Addr().String()}, DisableCache: true, ForceSingleClient: true}) + s.Require().NoError(err) + s.T().Cleanup(client.Close) + return client +} + +// With the directory not answering, a session of a chosen id is refused at once, since nobody can +// say whose its call is, and any other opens. +func (s *CallStatusSuite) TestADirectoryThatDoesNotAnswerHoldsUpNoSession() { + s.useApp(s.data.createApp()) + var deaf atomic.Bool + logger := slog.New(slog.DiscardHandler) + directory, err := node.NewDirectory(node.DirectoryOptions{Redis: s.deafRedis(&deaf), Address: "node-deaf:1", Prefix: s.relayPrefix, Logger: logger}) + s.Require().NoError(err) + s.T().Cleanup(directory.Close) + sessions, err := session.NewManager(session.ManagerOptions{ + LLM: s.streams.LLM, Conversations: s.conversations, Stream: s.stream, Store: s.store, Directory: directory, Logger: logger, + Writer: s.routerWriter(s.store, s.live, nil, logger), + Edge: func(context.Context, session.Spec, streamapp.Bound, *slog.Logger) (agent.Edge, error) { + return &silentEdge{inbound: make(chan agent.InboundAudio, 4)}, nil + }, + }) + s.Require().NoError(err) + s.T().Cleanup(func() { _ = sessions.Shutdown() }) + s.Require().NoError(heldOn(sessions, s.customerID(), s.utils.uuid())) + deaf.Store(true) + + began := time.Now() + err = heldOn(sessions, s.customerID(), s.utils.uuid()) + s.ErrorIs(err, store.ErrCallUnchecked) + var answer APIError + s.Require().ErrorAs(refusedRequest(err), &answer) + s.Equal(ErrorTypeUnavailable, answer.Type) + s.NoError(heldOn(sessions, s.customerID(), "")) + _, err = sessions.Create(context.Background(), session.Spec{CustomerID: s.customerID(), ID: s.utils.uuid(), MintedID: true, Text: true, + Incognito: true, Attribution: routing.Attribution{APIKey: "key"}}) + s.NoError(err) + s.Less(time.Since(began), 10*time.Second) +} diff --git a/acceleration/internal/api/router_suite_test.go b/acceleration/internal/api/router_suite_test.go index 4382fe6062..8cc68dfb37 100644 --- a/acceleration/internal/api/router_suite_test.go +++ b/acceleration/internal/api/router_suite_test.go @@ -2688,8 +2688,6 @@ type suiteApps struct { // keyless are customers of a deployment with no Stream keys, which the deployment's own app // answers ErrNoIdentity for whatever it is asked, as an unconfigured Deployment does. keyless map[string]bool - // refused are customers the app to act in is refused for, and how. - refused map[string]error // perApp answers as app mode does, where customers act in apps of their own. perApp bool } @@ -2704,11 +2702,8 @@ func (a *suiteApps) For(ctx context.Context, customer string) (streamapp.Identit a.mu.Lock() identity, ok := a.own[customer] waiting, nowhere := a.waiting[customer], a.nowhere[customer] || a.keyless[customer] - refused := a.refused[customer] a.mu.Unlock() switch { - case refused != nil: - return streamapp.Identity{}, refused case waiting: return streamapp.Identity{}, streamapp.ErrDeploymentAppUnknown case nowhere: diff --git a/acceleration/internal/api/scheduled_delivery.go b/acceleration/internal/api/scheduled_delivery.go index b75d07f22e..b116c35c85 100644 --- a/acceleration/internal/api/scheduled_delivery.go +++ b/acceleration/internal/api/scheduled_delivery.go @@ -1178,6 +1178,7 @@ func (s *Server) placeCall(ctx context.Context, delivery scheduledDelivery, foun From: from, To: to, SessionID: sessionID, + MintedID: true, }) if err != nil { return session.Spec{}, unpaid(overTier(err)) @@ -1190,7 +1191,7 @@ func (s *Server) placeCall(ctx context.Context, delivery scheduledDelivery, foun // The task is not in its instructions: it is the call's first turn. func callSpec(config store.AgentConfig, delivery scheduledDelivery, agentID string, placed phone.Placed, from, to string) session.Spec { spec := session.FromConfig(config) - spec.ID = placed.SessionID + spec.ID, spec.MintedID = placed.SessionID, true // A call is given an agent id of its own unless told one, and the // conversation refuses a session written as another agent. spec.AgentID = agentID diff --git a/acceleration/internal/campaign/campaign.go b/acceleration/internal/campaign/campaign.go index 875f1a4563..7f81db089f 100644 --- a/acceleration/internal/campaign/campaign.go +++ b/acceleration/internal/campaign/campaign.go @@ -787,7 +787,7 @@ func scheduledBy(campaign store.Campaign) routing.Attribution { // meet opens the session under the id the call was placed for, so the agent is in the call // the person was routed into. func meet(spec *session.Spec, placed phone.Placed) { - spec.ID = placed.SessionID + spec.ID, spec.MintedID = placed.SessionID, true spec.Text = false } diff --git a/acceleration/internal/campaign/dialer.go b/acceleration/internal/campaign/dialer.go index 5e96857a53..bcf363123b 100644 --- a/acceleration/internal/campaign/dialer.go +++ b/acceleration/internal/campaign/dialer.go @@ -70,7 +70,7 @@ func (d *phoneDialer) Dial(ctx context.Context, dial Dial) (Dialed, error) { } request := placing(dial.Campaign, dial.Contact, dial.Step) - request.SessionID = dial.SessionID + request.SessionID, request.MintedID = dial.SessionID, true placed, err := d.phone.Call(ctx, request) if err != nil { dialed := resultOf(err) diff --git a/acceleration/internal/node/directory.go b/acceleration/internal/node/directory.go index 11f37256d4..f576f81326 100644 --- a/acceleration/internal/node/directory.go +++ b/acceleration/internal/node/directory.go @@ -80,6 +80,8 @@ type Directory struct { // held maps a session this node is running to the agent it writes as and the // conversation it answers in, each empty for a session without one. held map[heldSession]claim + // onCalls counts the sessions running here by the call each is on. + onCalls map[heldCall]int // waiting counts the dispatch workers connected here, by customer. waiting map[string]int // offered is what the workers here host, by customer and agent. @@ -92,9 +94,15 @@ type offerKey struct{ customerID, agentID string } // one id. type heldSession struct{ customerID, sessionID string } -// claim is what a session this node holds is found by besides its own id. call is the key its -// call, agent:, is held under, empty until it is (HoldCall). -type claim struct{ agentID, conversationID, call string } +// heldCall is a customer's session's call, agent:, in a Stream app: 0 for the deployment's own. +type heldCall struct { + customerID string + app int64 + id string +} + +// claim is what a session this node holds is found by besides its own id. +type claim struct{ agentID, conversationID string } // offerEntry is one node's offer as Redis holds it. A hash cannot expire its fields one at // a time, so each says when it lapses. @@ -138,6 +146,7 @@ func NewDirectory(options DirectoryOptions) (*Directory, error) { logger: logger, cancel: cancel, held: map[heldSession]claim{}, + onCalls: map[heldCall]int{}, waiting: map[string]int{}, offered: map[offerKey][]byte{}, } @@ -191,32 +200,84 @@ func (d *Directory) shardCommands() []rueidis.Completed { func (d *Directory) Hold(ctx context.Context, customerID, sessionID, agentID, conversationID string) { key := heldSession{customerID, sessionID} d.mu.Lock() - d.held[key] = claim{agentID: agentID, conversationID: conversationID} + d.held[key] = claim{agentID, conversationID} d.mu.Unlock() - d.write(ctx, key, claim{agentID: agentID, conversationID: conversationID}) + ctx, cancel := context.WithTimeout(ctx, callTimeout) + defer cancel() + d.write(ctx, key, claim{agentID, conversationID}) } -// HoldCall says whose the call of a session this node holds is: agent:, in a Stream -// app, 0 for the deployment's own. It goes on saying so until Release. -func (d *Directory) HoldCall(ctx context.Context, customerID, sessionID string, app int64) { - key := heldSession{customerID, sessionID} +// callTimeout bounds saying a session is here, and asking or saying whose its call is: a session +// waits for each to open. +const callTimeout = time.Second + +// holdCallScript says a call is a customer's on a node, for a while, unless another customer's +// says so already. A renewal, whose third argument is empty, leaves the customer's own on another +// node too. +const holdCallScript = ` +local said = redis.call('GET', KEYS[1]) +if said and said ~= ARGV[1] and (ARGV[3] == '' or string.sub(said, 1, #ARGV[3]) ~= ARGV[3]) then return said end +redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2]) +return ARGV[1]` + +// releaseCallScript takes back what this node said of a call, and nothing said since. +const releaseCallScript = `if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end return 0` + +// errCallHeld is a call another customer's session holds. +var errCallHeld = errors.New("node: the call is another customer's") + +// HoldCall says a customer's session is on the call agent: in a Stream app, 0 for the +// deployment's own, and goes on saying so until ReleaseCall, which every HoldCall is followed by. +// A call another customer's session holds stays its own, which is an error. +func (d *Directory) HoldCall(ctx context.Context, customerID string, app int64, id string) error { + call := heldCall{customerID, app, id} + d.mu.Lock() + d.onCalls[call]++ + d.mu.Unlock() + ctx, cancel := context.WithTimeout(ctx, callTimeout) + defer cancel() + said, err := d.redis.Do(ctx, d.holdCall(call, customerOf(d.onCall(call)))).ToString() + if err != nil { + return err + } + if customerOf(said) != customerOf(d.onCall(call)) { + return errCallHeld + } + return nil +} + +// ReleaseCall says a session HoldCall said was on a call is not any more. +func (d *Directory) ReleaseCall(ctx context.Context, customerID string, app int64, id string) { + call := heldCall{customerID, app, id} d.mu.Lock() - held, holding := d.held[key] - held.call = d.callKey(app, sessionID) - if holding { - d.held[key] = held + d.onCalls[call]-- + last := d.onCalls[call] <= 0 + if last { + delete(d.onCalls, call) } d.mu.Unlock() - if holding { - d.write(ctx, key, held) + if !last { + return + } + ctx, cancel := context.WithTimeout(ctx, callTimeout) + defer cancel() + release := d.redis.B().Eval().Script(releaseCallScript).Numkeys(1).Key(d.callKey(app, id)).Arg(d.onCall(call)).Build() + if err := d.redis.Do(ctx, release).Error(); err != nil { + d.logger.Warn("could not take back this node's claim on a call", "customer", customerID, "call", id, "error", err) } } -// CallHolder is the customer whose session some node runs on the call agent: in the Stream -// app, 0 for the deployment's own, and empty when no node says it does. +// CallHolder is the customer whose session some node runs on the call agent: in a Stream app, +// 0 for the deployment's own, and empty when no node says it does. func (d *Directory) CallHolder(ctx context.Context, app int64, id string) (string, error) { - return d.lookup(ctx, d.callKey(app, id)) + ctx, cancel := context.WithTimeout(ctx, callTimeout) + defer cancel() + said, err := d.lookup(ctx, d.callKey(app, id)) + if err != nil || said == "" { + return "", err + } + return url.QueryUnescape(customerOf(said)) } // callKey is where a call is held: node:call::. @@ -224,6 +285,26 @@ func (d *Directory) callKey(app int64, id string) string { return d.calls + strconv.FormatInt(app, 10) + ":" + id } +// onCall is what this node says of a call: its customer, escaped so that it holds no space, and +// the node's address. +func (d *Directory) onCall(call heldCall) string { + return url.QueryEscape(call.customerID) + " " + d.address +} + +// customerOf is the escaped customer of what a node says of a call. +func customerOf(said string) string { + customer, _, _ := strings.Cut(said, " ") + return customer +} + +func (d *Directory) holdCall(call heldCall, over string) rueidis.Completed { + if over != "" { + over += " " + } + return d.redis.B().Eval().Script(holdCallScript).Numkeys(1).Key(d.callKey(call.app, call.id)). + Arg(d.onCall(call), strconv.FormatInt(holdFor.Milliseconds(), 10), over).Build() +} + // Release says this node is not running a customer's session any more. // // Only the session's own claim is dropped. The agent's and the conversation's are left to @@ -233,18 +314,14 @@ func (d *Directory) callKey(app int64, id string) string { func (d *Directory) Release(ctx context.Context, customerID, sessionID string) { key := heldSession{customerID, sessionID} d.mu.Lock() - released, held := d.held[key] + _, held := d.held[key] delete(d.held, key) d.mu.Unlock() if !held { return } - gone := []string{d.sessionKey(key), d.sessions + sessionID} - if released.call != "" { - gone = append(gone, released.call) - } - if err := d.redis.Do(ctx, d.redis.B().Del().Key(gone...).Build()).Error(); err != nil { + if err := d.redis.Do(ctx, d.redis.B().Del().Key(d.sessionKey(key), d.sessions+sessionID).Build()).Error(); err != nil { d.logger.Warn("could not take back this node's claim on a session", "customer", customerID, "session", sessionID, "error", err) } @@ -485,9 +562,6 @@ func (d *Directory) writeCommands(key heldSession, held claim) []rueidis.Complet d.redis.B().Set().Key(d.sessionKey(key)).Value(d.address).Ex(holdFor).Build(), d.redis.B().Set().Key(d.sessions + key.sessionID).Value(d.address).Ex(holdFor).Build(), } - if held.call != "" { - commands = append(commands, d.redis.B().Set().Key(held.call).Value(key.customerID).Ex(holdFor).Build()) - } if held.agentID != "" { writers := d.writingAs + held.agentID until := strconv.FormatInt(time.Now().Add(holdFor).UnixMilli(), 10) @@ -586,6 +660,7 @@ func (d *Directory) renew(ctx context.Context) { func (d *Directory) renewAll(ctx context.Context) { d.mu.Lock() held := maps.Clone(d.held) + onCalls := maps.Clone(d.onCalls) waiting := maps.Clone(d.waiting) offered := maps.Clone(d.offered) d.mu.Unlock() @@ -594,6 +669,9 @@ func (d *Directory) renewAll(ctx context.Context) { for key, claimed := range held { commands = append(commands, d.writeCommands(key, claimed)...) } + for call := range onCalls { + commands = append(commands, d.holdCall(call, "")) + } for customerID := range waiting { commands = append(commands, d.advertiseCommands(customerID)...) } diff --git a/acceleration/internal/node/directory_test.go b/acceleration/internal/node/directory_test.go index b24d1fe5d5..b03cd516a1 100644 --- a/acceleration/internal/node/directory_test.go +++ b/acceleration/internal/node/directory_test.go @@ -55,6 +55,7 @@ func (s *DirectorySuite) TestARenewalIsOneRoundTrip() { for _, session := range []string{"s1", "s2", "s3"} { directory.Hold(s.ctx, "acme", session, "agent-"+session, "messaging:"+session) } + s.Require().NoError(directory.HoldCall(s.ctx, "acme", 0, "s1")) directory.Wait(s.ctx, "acme") directory.Wait(s.ctx, "globex") directory.Offer(s.ctx, "acme", "agent-s1", []byte(`{"tools":[]}`)) @@ -62,8 +63,8 @@ func (s *DirectorySuite) TestARenewalIsOneRoundTrip() { keys, err := s.client.Do(s.ctx, s.client.B().Keys().Pattern(s.prefix+":*").Build()).AsStrSlice() s.Require().NoError(err) // Each session: itself, its agent and its conversation, each under its customer and under - // its id alone. - s.Require().Len(keys, 3*6+2+2+1) + // its id alone. And the call of one. + s.Require().Len(keys, 3*6+1+2+2+1) s.Require().NoError(s.client.Do(s.ctx, s.client.B().Del().Key(keys...).Build()).Error()) before := s.roundTrips.sent.Load() @@ -219,44 +220,77 @@ func (s *DirectorySuite) TestAReleasedSessionIsFoundNowhere() { s.Zero(exists, "a router of the release before would still forward to it") } -// A session's call is found by its id and Stream app until the session is released, and a -// renewal says it again. +func (s *DirectorySuite) holder(app int64, id string) string { + customer, err := s.directoryAt("node-x:1").CallHolder(s.ctx, app, id) + s.Require().NoError(err) + return customer +} + +// lapsed drops what a node said of a call, as its expiry does. +func (s *DirectorySuite) lapsed() { + s.Require().NoError(s.client.Do(s.ctx, s.client.B().Del().Key(s.prefix+":call:7:order-42").Build()).Error()) +} + func (s *DirectorySuite) TestASessionsCallIsFoundByItsAppUntilItIsReleased() { directory := s.directoryAt("node-a:1") - directory.Hold(s.ctx, "acme", "order-42", "", "") - directory.HoldCall(s.ctx, "acme", "order-42", 7) - peer := s.directoryAt("node-b:1") - holder := func(app int64, id string) string { - customer, err := peer.CallHolder(s.ctx, app, id) - s.Require().NoError(err) - return customer - } + s.Require().NoError(directory.HoldCall(s.ctx, "a customer:1", 7, "order-42")) - s.Equal("acme", holder(7, "order-42")) - s.Empty(holder(0, "order-42"), "another app's call of the name") - s.Empty(holder(7, "order-43")) - - key := s.prefix + ":call:7:order-42" - ttl, err := s.client.Do(s.ctx, s.client.B().Pttl().Key(key).Build()).AsInt64() + s.Equal("a customer:1", s.holder(7, "order-42")) + s.Empty(s.holder(0, "order-42"), "another app's call of the name") + s.Empty(s.holder(7, "order-43")) + ttl, err := s.client.Do(s.ctx, s.client.B().Pttl().Key(s.prefix+":call:7:order-42").Build()).AsInt64() s.Require().NoError(err) s.InDelta(30000, ttl, 5000, "it lapses with the node") - s.Require().NoError(s.client.Do(s.ctx, s.client.B().Del().Key(key).Build()).Error()) + s.lapsed() directory.renewAll(s.ctx) - s.Equal("acme", holder(7, "order-42")) + s.Equal("a customer:1", s.holder(7, "order-42")) - directory.Release(s.ctx, "acme", "order-42") - s.Empty(holder(7, "order-42")) + directory.ReleaseCall(s.ctx, "a customer:1", 7, "order-42") + s.Empty(s.holder(7, "order-42")) + directory.renewAll(s.ctx) + s.Empty(s.holder(7, "order-42")) } -func (s *DirectorySuite) TestACallOfASessionNotHeldHereIsNotHeld() { - directory := s.directoryAt("node-a:1") +func (s *DirectorySuite) TestACallAnotherCustomerHoldsStaysItsOwn() { + first, second := s.directoryAt("node-a:1"), s.directoryAt("node-b:1") + s.Require().NoError(first.HoldCall(s.ctx, "acme", 7, "order-42")) + + s.Error(second.HoldCall(s.ctx, "acm", 7, "order-42")) + s.Equal("acme", s.holder(7, "order-42")) + second.renewAll(s.ctx) + s.Equal("acme", s.holder(7, "order-42")) + second.ReleaseCall(s.ctx, "acm", 7, "order-42") + s.Equal("acme", s.holder(7, "order-42")) + + // A claim that lapsed and was taken is not renewed over. + s.lapsed() + s.Require().NoError(second.HoldCall(s.ctx, "globex", 7, "order-42")) + first.renewAll(s.ctx) + s.Equal("globex", s.holder(7, "order-42")) +} - directory.HoldCall(s.ctx, "acme", "order-42", 7) - directory.renewAll(s.ctx) +// A customer's session moving to another node holds its call there, and the node it left takes +// back nothing. +func (s *DirectorySuite) TestACallIsHeldByTheNodeItsSessionMovedTo() { + first, second := s.directoryAt("node-a:1"), s.directoryAt("node-b:1") + s.Require().NoError(first.HoldCall(s.ctx, "acme", 7, "order-42")) + s.Require().NoError(second.HoldCall(s.ctx, "acme", 7, "order-42")) + first.renewAll(s.ctx) - holder, err := directory.CallHolder(s.ctx, 7, "order-42") - s.Require().NoError(err) - s.Empty(holder) + first.ReleaseCall(s.ctx, "acme", 7, "order-42") + + s.Equal("acme", s.holder(7, "order-42")) +} + +func (s *DirectorySuite) TestACallTwoSessionsHereAreOnIsHeldUntilBothAreGone() { + directory := s.directoryAt("node-a:1") + s.Require().NoError(directory.HoldCall(s.ctx, "acme", 7, "order-42")) + s.Require().NoError(directory.HoldCall(s.ctx, "acme", 7, "order-42")) + + directory.ReleaseCall(s.ctx, "acme", 7, "order-42") + s.Equal("acme", s.holder(7, "order-42")) + directory.ReleaseCall(s.ctx, "acme", 7, "order-42") + s.Empty(s.holder(7, "order-42")) } // directoryAt is a node's directory at address, renewing nothing for the test's length. diff --git a/acceleration/internal/phone/apps_integration_test.go b/acceleration/internal/phone/apps_integration_test.go index d6f6a58561..a8feca41d2 100644 --- a/acceleration/internal/phone/apps_integration_test.go +++ b/acceleration/internal/phone/apps_integration_test.go @@ -2911,7 +2911,7 @@ func (s *AppsSuite) refusedTaken(sessionID string) { trunks := len(s.deployment.Trunks()) s.vendor.dialed = Outbound{} - s.ErrorIs(s.dialInto(sessionID, "+15550001111", map[string]string{"k": "v"}), ErrSessionTaken) + s.ErrorIs(s.dialInto(sessionID, "+15550001111", map[string]string{"k": "v"}), store.ErrCallTaken) s.Empty(s.vendor.dialed.To) s.Len(s.deployment.Trunks(), trunks) @@ -2983,7 +2983,7 @@ func (s *AppsSuite) TestTwoCustomersPlacingIntoOneSessionAtOnceAreNotBothOnItsCa } wg.Wait() - s.True(errors.Is(errs[0], ErrSessionTaken) != errors.Is(errs[1], ErrSessionTaken), "%v", errs) + s.True(errors.Is(errs[0], store.ErrCallTaken) != errors.Is(errs[1], store.ErrCallTaken), "%v", errs) } } @@ -2995,3 +2995,86 @@ func (s *AppsSuite) TestACampaignDoesNotTryACallIntoATakenSessionAgain() { s.NotErrorIs(s.dialInto(call, "+15550001111", nil), ErrNotDialed) } + +func (s *AppsSuite) TestACallIntoASessionNobodyCanTellTheCustomerOfIsNotDialled() { + s.sealed() + holder := func(context.Context, int64, string) (string, error) { return "", errors.New("redis is down") } + request := CallRequest{Owner: routing.Owner{CustomerID: s.customer}, From: s.e164, To: "+15550001111", SessionID: uuid.NewString(), Holder: holder} + + _, err := s.service.Call(s.ctx, request) + s.ErrorIs(err, store.ErrCallUnchecked) + s.ErrorIs(err, ErrNotDialed, "worth trying again") + s.Empty(s.vendor.dialed.To) + + request.MintedID = true + _, err = s.service.Call(s.ctx, request) + s.NoError(err, "an id the router made is nobody else's to ask about") +} + +func (s *AppsSuite) TestACallIntoAMintedSessionAsksNothingOfTheCallsLegs() { + s.sealed() + theirs, _ := s.another() + call := uuid.NewString() + s.arrived(theirs, call, 0) + + _, err := s.service.Call(s.ctx, CallRequest{Owner: routing.Owner{CustomerID: s.customer}, From: s.e164, To: "+15550001111", SessionID: call, MintedID: true}) + + s.NoError(err) +} + +// A call is let in or refused by whichever was kept first, not by when each was asked for. +func (s *AppsSuite) TestOfTwoCustomersCallsTheOneKeptFirstIsOnTheCallHoweverLateTheOtherIsKept() { + s.sealed() + theirs, e164 := s.another() + _, err := s.store.GlobalDB().ExecContext(s.ctx, "CREATE OR REPLACE FUNCTION slow_leg() RETURNS trigger AS $$ BEGIN IF NEW.customer_id = '"+theirs+ + "' THEN PERFORM pg_sleep(1); END IF; RETURN NEW; END $$ LANGUAGE plpgsql") + s.Require().NoError(err) + _, err = s.store.GlobalDB().ExecContext(s.ctx, "CREATE OR REPLACE TRIGGER slow_leg BEFORE INSERT ON call_legs FOR EACH ROW EXECUTE FUNCTION slow_leg()") + s.Require().NoError(err) + defer func() { + _, err := s.store.GlobalDB().ExecContext(s.ctx, "DROP TRIGGER slow_leg ON call_legs; DROP FUNCTION slow_leg()") + s.Require().NoError(err) + }() + session := uuid.NewString() + began, late := make(chan struct{}), make(chan error, 1) + go func() { + close(began) + _, err := s.service.Call(s.ctx, CallRequest{Owner: routing.Owner{CustomerID: theirs}, From: e164, To: "+15550002222", SessionID: session}) + late <- err + }() + <-began + s.Require().Eventually(func() bool { + var asleep bool + s.Require().NoError(s.store.GlobalDB().NewSelect().ColumnExpr("EXISTS (SELECT 1 FROM pg_stat_activity WHERE wait_event = 'PgSleep' AND datname = current_database())").Scan(s.ctx, &asleep)) + return asleep + }, 5*time.Second, 5*time.Millisecond) + + mine := s.dialInto(session, "+15550001111", nil) + + s.NoError(<-late) + s.ErrorIs(mine, store.ErrCallTaken) +} + +// Who is on a call is asked of the Stream app the call is placed in, the deployment's being one +// whether a customer is pinned to its id or to none. +func (s *AppsSuite) TestWhoIsOnACallIsAskedOfItsApp() { + s.sealed() + call := uuid.NewString() + asked := func() int64 { + in := int64(-1) + _, err := s.service.Call(s.ctx, CallRequest{Owner: routing.Owner{CustomerID: s.customer}, From: s.e164, To: "+15550001111", SessionID: call, + Holder: func(_ context.Context, app int64, id string) (string, error) { + s.Equal(call, id) + in = app + return "another-customer", nil + }}) + s.ErrorIs(err, store.ErrCallTaken) + return in + } + + s.Zero(asked(), "unpinned") + s.apps.give(s.customer, 1, s.deployment) + s.Zero(asked(), "pinned to the deployment's app") + s.ownApp() + s.EqualValues(4242, asked()) +} diff --git a/acceleration/internal/phone/outcome/keeper.go b/acceleration/internal/phone/outcome/keeper.go index d8b1eab9be..837a86869a 100644 --- a/acceleration/internal/phone/outcome/keeper.go +++ b/acceleration/internal/phone/outcome/keeper.go @@ -36,12 +36,13 @@ func NewKeeper(st *store.Store, now func() time.Time, vendors []string, logger * // Placed keeps a call about to be dialled, as its leg, and returns its token, for the vendor's // status URL. The leg is dialled when it opens with the token. func (k *Keeper) Placed(ctx context.Context, call Call) (string, error) { - return k.PlacedWithin(ctx, call, "", nil) + return k.PlacedWithin(ctx, call, "", nil, nil) } // PlacedWithin is Placed for a call whose leg counts among organization's calls, refused with -// store.ErrCallsAtOnce when atOnce, if set, leaves no room for it (store.CallLegs.PlaceWithin). -func (k *Keeper) PlacedWithin(ctx context.Context, call Call, organization string, atOnce *store.CallsAtOnce) (string, error) { +// store.ErrCallsAtOnce when atOnce, if set, leaves no room for it (store.CallLegs.PlaceWithin), and with store.ErrCallTaken when on, set for a call +// whose id somebody chose, finds it another customer's (store.CallLegs.PlaceOn). +func (k *Keeper) PlacedWithin(ctx context.Context, call Call, organization string, atOnce *store.CallsAtOnce, on *store.NamedCall) (string, error) { placed := k.now() row := store.CallLeg{ Token: uuid.NewString(), @@ -59,7 +60,12 @@ func (k *Keeper) PlacedWithin(ctx context.Context, call Call, organization strin OrganizationID: organization, } place := k.store.CallLegs.Place - if atOnce != nil { + switch { + case on != nil: + place = func(ctx context.Context, leg *store.CallLeg) error { + return k.store.CallLegs.PlaceOn(ctx, leg, *on, atOnce) + } + case atOnce != nil: place = func(ctx context.Context, leg *store.CallLeg) error { return k.store.CallLegs.PlaceWithin(ctx, leg, *atOnce) } diff --git a/acceleration/internal/phone/service.go b/acceleration/internal/phone/service.go index 328a288c9e..7a49898c2c 100644 --- a/acceleration/internal/phone/service.go +++ b/acceleration/internal/phone/service.go @@ -228,15 +228,6 @@ func (s *Service) streamFor(ctx context.Context, customer string) (*Stream, int6 return s.stream, 0, nil } -// scopeOf is the rows of the Stream app a pin names. -func (s *Service) scopeOf(pin int64) store.AppScope { - var deployment int64 - if s.apps != nil { - deployment = s.apps.DeploymentApp() - } - return store.AppOf(pin, deployment) -} - // streamForApp is the app a line already made is in. func (s *Service) streamForApp(ctx context.Context, customer string, app int64) (*Stream, error) { if s.apps != nil { @@ -1166,6 +1157,11 @@ type CallRequest struct { // call, agent:. Empty chooses one, because two calls from the same number // are two conversations and must not land in the same place. SessionID string + // MintedID is a SessionID the router made, which names no other customer's call. + MintedID bool + // Holder, when set, is the customer whose running session is on the call agent: in a + // Stream app, 0 for the deployment's own, or empty. A SessionID not minted is checked with it. + Holder func(ctx context.Context, app int64, id string) (string, error) // RingTimeout is how long to ring before giving up. Zero leaves the vendor's default. RingTimeout time.Duration // InitialDigits are pressed once the person answers, for reaching an extension behind @@ -1205,9 +1201,6 @@ type Placed struct { StreamApp int64 } -// ErrSessionTaken is a call into a session whose call is another customer's. -var ErrSessionTaken = errors.New("phone: the session id is taken") - // Call places an outbound call and bridges it into a Stream call. // // Stream's SIP is inbound only, so the vendor originates the call and connects it to a @@ -1236,7 +1229,7 @@ func lasting(err error) bool { return errors.Is(err, ErrInvalid) || errors.Is(err, store.ErrNoNumber) || errors.Is(err, store.ErrNoSIPTrunk) || errors.Is(err, ErrNoStream) || errors.Is(err, ErrNoSealerToCall) || errors.Is(err, ErrNotConfigured) || errors.Is(err, ErrSIPTrunksDisabled) || - errors.Is(err, errLasting) || errors.Is(err, ErrSessionTaken) || (err != nil && streamapp.Settled(err)) + errors.Is(err, errLasting) || errors.Is(err, store.ErrCallTaken) || (err != nil && streamapp.Settled(err)) } // errLasting marks a failure that has no kind of its own and that a second try meets again: a @@ -1332,6 +1325,23 @@ func (s *Service) call(ctx context.Context, request CallRequest, sent *bool) (Pl // a customer's own trunk is told by the router's own bridge. _, reader := provider.(StatusReader) reports := reader && s.publicURL != "" + // The answered leg is routed into the call, so a session id somebody chose has to be a call of + // the customer's. + var on *store.NamedCall + if request.SessionID != "" && !request.MintedID { + var deployment int64 + if s.apps != nil { + deployment = s.apps.DeploymentApp() + } + on = &store.NamedCall{Scope: store.AppOf(pin, deployment)} + if request.Holder != nil { + app := pin + if on.Scope.Unpinned { + app = 0 + } + on.Holder = func(ctx context.Context) (string, error) { return request.Holder(ctx, app, callID) } + } + } token, err := s.outcomes.PlacedWithin(ctx, outcome.Call{ Key: outcome.Key{ CustomerID: request.Owner.CustomerID, StreamAppPK: pin, CallType: callType, CallID: callID, @@ -1339,10 +1349,13 @@ func (s *Service) call(ctx context.Context, request CallRequest, sent *bool) (Pl }, Vendor: held.Vendor, Reports: reports || trunk != nil, - }, room.OrganizationID, room.AtOnce) + }, room.OrganizationID, room.AtOnce, on) if errors.Is(err, store.ErrCallsAtOnce) { return Placed{}, room.Refusal(err) } + if errors.Is(err, store.ErrCallTaken) || errors.Is(err, store.ErrCallUnchecked) { + return Placed{}, err + } if err != nil { return Placed{}, notPlaced(ctx, err) } @@ -1354,18 +1367,6 @@ func (s *Service) call(ctx context.Context, request CallRequest, sent *bool) (Pl s.forgetOutcome(ctx, token, callID) } }() - // A leg is routed into agent:, so a session id somebody named has to be a call of - // the customer's. Asked once its own leg is kept, so of two customers placing into one id at - // once each sees the other's. - if request.SessionID != "" { - owner, err := s.store.CallLegs.Owner(ctx, s.scopeOf(pin), callType, callID) - if err != nil { - return Placed{}, err - } - if owner != "" && owner != request.Owner.CustomerID { - return Placed{}, stack.Wrap(ErrSessionTaken) - } - } // Its leg counts against the organization it was placed under once it is dialled too. if room.OrganizationID != "" { request.Owner.OrganizationID = room.OrganizationID diff --git a/acceleration/internal/session/manager.go b/acceleration/internal/session/manager.go index fb63149ccc..2cc56c1559 100644 --- a/acceleration/internal/session/manager.go +++ b/acceleration/internal/session/manager.go @@ -511,18 +511,6 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er if stream.Client == nil && m.options.Stream != nil && m.options.Stream.PerApp() { spec.StreamApp = store.ForeignStreamApp } - // The agent joins agent:, and calls are placed and people brought into it. An id - // generated just now names no call yet, and a reopened session's is its own. - if spec.Reopened.IsZero() && !generated { - taken, err := m.callTaken(ctx, spec) - if err != nil { - return nil, stack.Wrap(err) - } - if taken { - return nil, stack.Wrap(ErrSessionExists) - } - } - var remembering *metered.Memory if spec.Memory.UserID != "" { if m.options.Memory == nil { @@ -539,6 +527,17 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er } opened := false + // The agent joins agent:, and calls are placed and people brought into it. + named := spec.Reopened.IsZero() && !generated && !spec.MintedID + releaseCall, err := m.claimCall(ctx, spec, named) + if err != nil { + return nil, err + } + defer func() { + if !opened { + releaseCall() + } + }() if cid, by, handed := m.handedOut(ctx, spec, stream); handed { spec.ConversationID, spec.Dispatched, spec.HandedOutBy = cid, true, by ctx = persistent.RouterOpensDispatched(ctx, cid) @@ -593,6 +592,11 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er return nil, fmt.Errorf("session: the app conversation %s is kept in: %w", conv.CID(), err) } spec.StreamApp = kept + releaseCall() + if releaseCall, err = m.claimCall(ctx, spec, named); err != nil { + conv.Release() + return nil, err + } } spec.ConversationID = conv.CID() conv.ShowTools(spec.VisibleTools) @@ -692,6 +696,7 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er }() created := m.newSession(ctx, spec, conv, skills, opening, runtime) created.loading = loading + created.closers = append(created.closers, releaseCall) // A session held ends where it closes (Session.counted); one never held ends here, // unless it was turned away for a router shutting down or for a session already held // under its id (a redelivered hook): neither is a session that failed. @@ -1129,10 +1134,6 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er // the strength of it has somewhere to forward it to. if m.options.Directory != nil { m.options.Directory.Hold(ctx, spec.CustomerID, created.id, spec.AgentID, spec.ConversationID) - // A session that acts in no Stream app has no call. - if spec.StreamApp != store.ForeignStreamApp { - m.options.Directory.HoldCall(ctx, spec.CustomerID, created.id, m.callApp(spec.StreamApp)) - } } // Asked again now the session is held: a status that came while the call was being // joined found no session to end, and one that comes after this finds it. The session @@ -2256,33 +2257,49 @@ func (m *Manager) stream(ctx context.Context, spec Spec, newCall bool) (streamap return bound, nil } -// callApp is the Stream app pinned app as the directory holds a call in it: zero for the -// deployment's own, whether the session is pinned to its id or to none. -func (m *Manager) callApp(app int64) int64 { - if m.options.Stream != nil && app == m.options.Stream.DeploymentApp() { - return 0 +// claimCall says the session's customer is on the call it is named after, agent: in the +// Stream app it acts in, until the func it returns is called. Of a named session it is refused with ErrSessionExists +// when the call is another customer's, by its legs or by a session some node runs, and with +// store.ErrCallUnchecked when that cannot be told. An id the router made names nobody else's call, +// and a reopened session's is its own, so theirs is only said. A session of no Stream app has no +// call. +func (m *Manager) claimCall(ctx context.Context, spec Spec, named bool) (func(), error) { + if spec.StreamApp == store.ForeignStreamApp { + return func() {}, nil } - return app -} - -// callTaken reports whether the call a session is named after, agent: in the Stream app it -// acts in, is another customer's: by its phone legs, or by the session some node runs on it. -func (m *Manager) callTaken(ctx context.Context, spec Spec) (bool, error) { - if m.options.Store != nil { - var deployment int64 - if m.options.Stream != nil { - deployment = m.options.Stream.DeploymentApp() + var deployment int64 + if m.options.Stream != nil { + deployment = m.options.Stream.DeploymentApp() + } + app, directory := spec.StreamApp, m.options.Directory + if app == deployment { + app = 0 + } + on := store.NamedCall{Scope: store.AppOf(app, deployment)} + hold := func(context.Context) error { return nil } + release := func() {} + if directory != nil { + on.Holder = func(ctx context.Context) (string, error) { return directory.CallHolder(ctx, app, spec.ID) } + hold = func(ctx context.Context) error { + release = sync.OnceFunc(func() { directory.ReleaseCall(context.WithoutCancel(ctx), spec.CustomerID, app, spec.ID) }) + return directory.HoldCall(ctx, spec.CustomerID, app, spec.ID) } - owner, err := m.options.Store.CallLegs.Owner(ctx, store.AppOf(spec.StreamApp, deployment), streamapp.AgentCallType, spec.ID) - if err != nil || owner != "" && owner != spec.CustomerID { - return err == nil, err + } + if !named || m.options.Store == nil { + if err := hold(ctx); err != nil { + m.logger.Warn("could not say whose call a session is on", "session", spec.ID, "customer", spec.CustomerID, "error", err) } + return release, nil } - if m.options.Directory == nil { - return false, nil + err := m.options.Store.CallLegs.Claim(ctx, spec.CustomerID, streamapp.AgentCallType, spec.ID, on, hold) + if err == nil { + return release, nil + } + release() + if errors.Is(err, store.ErrCallTaken) { + err = stack.Wrap(ErrSessionExists) } - holder, err := m.options.Directory.CallHolder(ctx, m.callApp(spec.StreamApp), spec.ID) - return holder != "" && holder != spec.CustomerID, err + return func() {}, err } // hookPinFor is how long a hook's app is remembered for the session it starts. diff --git a/acceleration/internal/session/spec.go b/acceleration/internal/session/spec.go index 39344342dc..63b15b2ca0 100644 --- a/acceleration/internal/session/spec.go +++ b/acceleration/internal/session/spec.go @@ -49,7 +49,10 @@ type Recall struct { type Spec struct { // ID is the id the session is held by. Empty is generated as a UUIDv7; one the caller // chose has to be a UUID. - ID string + ID string + // MintedID is an ID the router made, or Stream for a caller of a number, which names no + // other customer's call. + MintedID bool PersistConversation bool ConversationID string // Thread holds ConversationID on a thread channel (internal/channelbridge), which only diff --git a/acceleration/internal/store/call_leg.go b/acceleration/internal/store/call_leg.go index a2fa330810..29b08af4fa 100644 --- a/acceleration/internal/store/call_leg.go +++ b/acceleration/internal/store/call_leg.go @@ -1,6 +1,7 @@ package store import ( + "cmp" "context" "database/sql" "errors" @@ -380,40 +381,8 @@ type legMatch struct { revive bool } -// onCall keeps the legs that make a call their customer's: those open, and those a phone was on. -func onCall(q bun.QueryBuilder) bun.QueryBuilder { - return q.WhereGroup(" AND ", func(q bun.QueryBuilder) bun.QueryBuilder { - return q.Where("ended_at IS NULL").WhereOr("participant_session <> ''") - }) -} - -// Owner is the customer a call is, in one app: the one whose leg was on it first, in any shard. -// It is empty for a call no leg is on. -func (r *CallLegs) Owner(ctx context.Context, scope AppScope, callType, callID string) (string, error) { - type first struct { - CustomerID string - At time.Time - } - lists, err := everyShard(ctx, r.store, func(ctx context.Context, db bun.IDB) ([]first, error) { - var found []first - err := db.NewSelect().Model((*CallLeg)(nil)).Column("customer_id").ColumnExpr("COALESCE(placed_at, dialed_at) AS at"). - Where("call_type = ?", callType).Where("call_id = ?", callID). - ApplyQueryBuilder(scope.where).ApplyQueryBuilder(onCall). - OrderExpr("at, id").Limit(1).Scan(ctx, &found) - return found, err - }) - if err != nil { - return "", stack.Wrap(fmt.Errorf("store: call owner: %w", err)) - } - if owner := merged(lists, func(a, b first) int { return a.At.Compare(b.At) }, 1); len(owner) > 0 { - return owner[0].CustomerID, nil - } - return "", nil -} - // connectWaitingLeg gives the phone the first leg of the call, across the shards, that match -// keeps. A leg that came to a call after another customer's is given no phone: the call is the -// other's (Owner). +// keeps. func (r *CallLegs) connectWaitingLeg(ctx context.Context, scope AppScope, callType, callID, sessionID, participant string, match legMatch, at time.Time, left *time.Time) (CallLeg, Connection, error) { var leftAt any @@ -424,12 +393,7 @@ func (r *CallLegs) connectWaitingLeg(ctx context.Context, scope AppScope, callTy waiting := db.NewSelect().Model((*CallLeg)(nil)).Column("id"). Where("call_type = ?", callType).Where("call_id = ?", callID). Where("participant_session = ''"). - ApplyQueryBuilder(scope.where). - Where("NOT EXISTS (?)", db.NewSelect().TableExpr("call_legs AS o").ColumnExpr("1"). - Where("call_type = ?", callType).Where("call_id = ?", callID). - ApplyQueryBuilder(scope.where).ApplyQueryBuilder(onCall). - Where("o.customer_id <> cl.customer_id"). - Where("COALESCE(o.placed_at, o.dialed_at) < COALESCE(cl.placed_at, cl.dialed_at)")) + ApplyQueryBuilder(scope.where) if match.revive { waiting = waiting.Where("direction = ?", Outbound).Where("end_reason = ?", LegUnanswered). Where("ended_at > GREATEST(?::timestamptz, dialed_at)", at) @@ -794,16 +758,26 @@ const placingFor = 3 * time.Second // database until the leg is kept, so two calls placed at once, from any router, never both see // the last free one. func (r *CallLegs) PlaceWithin(ctx context.Context, leg *CallLeg, atOnce CallsAtOnce) error { + return r.placeOn(ctx, leg, nil, &atOnce) +} + +// PlaceOn is Place, or with atOnce PlaceWithin, for a leg of a call somebody named: it keeps leg, +// or refuses it with ErrCallTaken as a call of another customer's, under the call's lock. +func (r *CallLegs) PlaceOn(ctx context.Context, leg *CallLeg, on NamedCall, atOnce *CallsAtOnce) error { + return r.placeOn(ctx, leg, &on, atOnce) +} + +func (r *CallLegs) placeOn(ctx context.Context, leg *CallLeg, on *NamedCall, atOnce *CallsAtOnce) error { if err := placeable(leg); err != nil { return err } - if leg.OrganizationID == "" { + if atOnce != nil && leg.OrganizationID == "" { return stack.Wrap(validate("call leg").required("organization_id", leg.OrganizationID).done()) } // A campaign tick places many calls of one organization at once, and each waiting on the // advisory lock holds a connection of the shared database's pool: waiting here first keeps a // router to one per organization, and to placingAtOnce in all. - release, err := r.placing(ctx, leg.OrganizationID) + release, err := r.placing(ctx, cmp.Or(leg.OrganizationID, leg.CallID)) if err != nil { return stack.Wrap(fmt.Errorf("store: place call leg: %w", err)) } @@ -815,37 +789,45 @@ func (r *CallLegs) PlaceWithin(ctx context.Context, leg *CallLeg, atOnce CallsAt // Otherwise the insert commits on the shard before the lock's transaction does. shared := r.store.shard == r.store.global err = r.store.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { - if err := lockUntilCommit(ctx, tx, leg.OrganizationID, callsAtOnceLockSeed); err != nil { - return err - } var own bun.IDB = r.store.shard if shared { own = tx } dbs := append([]bun.IDB{own}, r.store.shards()[1:]...) - counts := make([]openCount, len(dbs)) - failed := make([]error, len(dbs)) - since := leg.PlacedAt.Add(-atOnce.Ringing) - var wg sync.WaitGroup - for i, db := range dbs { - wg.Go(func() { counts[i], failed[i] = countOpen(ctx, db, leg.OrganizationID, since, "", "") }) - } - wg.Wait() - if err := errors.Join(failed...); err != nil { - return err - } - open := 0 - for _, count := range counts { - open += count.Total + // Before the organization's lock, always: two placements never wait on each other's. + if on != nil { + if err := on.claim(ctx, tx, dbs, leg.CustomerID, leg.CallType, leg.CallID); err != nil { + return err + } } - if open >= atOnce.Limit { - return ErrCallsAtOnce + if atOnce != nil { + if err := lockUntilCommit(ctx, tx, leg.OrganizationID, callsAtOnceLockSeed); err != nil { + return err + } + counts := make([]openCount, len(dbs)) + failed := make([]error, len(dbs)) + since := leg.PlacedAt.Add(-atOnce.Ringing) + var wg sync.WaitGroup + for i, db := range dbs { + wg.Go(func() { counts[i], failed[i] = countOpen(ctx, db, leg.OrganizationID, since, "", "") }) + } + wg.Wait() + if err := errors.Join(failed...); err != nil { + return err + } + open := 0 + for _, count := range counts { + open += count.Total + } + if open >= atOnce.Limit { + return ErrCallsAtOnce + } } _, err := own.NewInsert().Model(leg).Returning("id").Exec(ctx) return err }) - if errors.Is(err, ErrCallsAtOnce) { - return stack.Wrap(ErrCallsAtOnce) + if errors.Is(err, ErrCallsAtOnce) || errors.Is(err, ErrCallTaken) || errors.Is(err, ErrCallUnchecked) { + return stack.Wrap(err) } if err != nil { // The leg may have been kept, its insert's or commit's answer lost, or on a shard of its @@ -864,6 +846,125 @@ func (r *CallLegs) PlaceWithin(ctx context.Context, leg *CallLeg, atOnce CallsAt return nil } +// ErrCallTaken is a named call that is another customer's, and ErrCallUnchecked one that could +// not be checked: where running sessions say whose call they are on did not answer. +var ( + ErrCallTaken = errors.New("store: the call is another customer's") + ErrCallUnchecked = errors.New("store: could not tell whose the call is") +) + +// callLockSeed seeds the advisory lock a named call is claimed under, one claim at a time. Its +// legs are on the shard that placed each, so no one database could refuse the second customer's. +const callLockSeed = 3744 + +// placedWait is how long a leg placed and not dialled counts as on its call. A dial takes +// seconds, so one older was left by a router that stopped before it dialled. +const placedWait = 10 * time.Minute + +// NamedCall is a call whose id somebody chose, in the Stream app of Scope. +type NamedCall struct { + Scope AppScope + // Holder, when set, is the customer whose running session is on the call, or empty. It is + // asked under the call's lock. A session holds the call before it has a leg or a row. + Holder func(context.Context) (string, error) +} + +// claim locks a call until tx ends and refuses it with ErrCallTaken when it is another customer's. +func (c NamedCall) claim(ctx context.Context, tx bun.IDB, dbs []bun.IDB, customerID, callType, callID string) error { + app := c.Scope.App + if c.Scope.Unpinned { + app = 0 + } + if err := lockUntilCommit(ctx, tx, strconv.FormatInt(app, 10)+":"+callType+":"+callID, callLockSeed); err != nil { + return err + } + if c.Holder != nil { + holder, err := c.Holder(ctx) + if err != nil { + return errors.Join(ErrCallUnchecked, err) + } + if holder != "" && holder != customerID { + return ErrCallTaken + } + } + owner, err := callOwner(ctx, dbs, c.Scope, callType, callID) + if err != nil { + return err + } + if owner != "" && owner != customerID { + return ErrCallTaken + } + return nil +} + +// Claim runs hold, which says a customer's session is on a named call, or refuses with +// ErrCallTaken when the call is another customer's. Both are under the lock PlaceOn keeps a leg +// under, so of a session and a call placed at once, or of two sessions, one sees the other. +func (r *CallLegs) Claim(ctx context.Context, customerID, callType, callID string, on NamedCall, hold func(context.Context) error) error { + release, err := r.placing(ctx, callID) + if err != nil { + return stack.Wrap(fmt.Errorf("store: claim call: %w", err)) + } + defer release() + ctx, cancel := context.WithTimeout(ctx, placingFor) + defer cancel() + err = r.store.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { + dbs := r.store.shards() + if r.store.shard == r.store.global { + dbs[0] = tx + } + if err := on.claim(ctx, tx, dbs, customerID, callType, callID); err != nil { + return err + } + if err := hold(ctx); err != nil { + return errors.Join(ErrCallUnchecked, err) + } + return nil + }) + if err != nil { + return stack.Wrap(fmt.Errorf("store: claim call: %w", err)) + } + return nil +} + +// callOwner is the customer a call is, by its legs in every shard: those open, dialled or about +// to be, and those a phone was on. It is empty for a call no leg is on. One customer alone has +// legs on a call claimed here; of more, as a release before this one may have left, it is the +// first dialled, and of two dialled at once the first by id. +func callOwner(ctx context.Context, dbs []bun.IDB, scope AppScope, callType, callID string) (string, error) { + type on struct { + CustomerID string + At time.Time + } + found, failed := make([][]on, len(dbs)), make([]error, len(dbs)) + var wg sync.WaitGroup + for i, db := range dbs { + wg.Go(func() { + failed[i] = db.NewSelect().Model((*CallLeg)(nil)).Column("customer_id").ColumnExpr("COALESCE(dialed_at, placed_at) AS at"). + Where("call_type = ?", callType).Where("call_id = ?", callID). + ApplyQueryBuilder(scope.where). + WhereGroup(" AND ", func(q *bun.SelectQuery) *bun.SelectQuery { + return q.Where("ended_at IS NULL").WhereOr("participant_session <> ''") + }). + WhereGroup(" AND ", func(q *bun.SelectQuery) *bun.SelectQuery { + return q.Where("dialed_at IS NOT NULL").WhereOr("placed_at > ?", time.Now().Add(-placedWait)) + }). + OrderExpr("at, customer_id").Limit(1).Scan(ctx, &found[i]) + }) + } + wg.Wait() + if err := errors.Join(failed...); err != nil { + return "", err + } + legs := slices.Concat(found...) + if len(legs) == 0 { + return "", nil + } + return slices.MinFunc(legs, func(a, b on) int { + return cmp.Or(a.At.Compare(b.At), strings.Compare(a.CustomerID, b.CustomerID)) + }).CustomerID, nil +} + // placing waits for this router's turn to count and place a call of organization, then for a // place among the placements under way, until ctx ends, and returns what gives both up. func (r *CallLegs) placing(ctx context.Context, organization string) (func(), error) { diff --git a/acceleration/internal/store/call_leg_test.go b/acceleration/internal/store/call_leg_test.go index aa92621026..7f279a40b3 100644 --- a/acceleration/internal/store/call_leg_test.go +++ b/acceleration/internal/store/call_leg_test.go @@ -396,11 +396,6 @@ func (s *StoreSuite) TestCallLegQueryBudgets() { s.Require().NoError(err) s.True(ringing) }), "Ringing") - s.Equal(shards, s.countQueries(func() { - owner, err := s.store.CallLegs.Owner(s.ctx, scope, "default", "call-1") - s.Require().NoError(err) - s.NotEmpty(owner) - }), "Owner") s.Equal(shards+1, s.countQueries(func() { _, connection, err := s.store.CallLegs.Connect(s.ctx, scope, "default", "call-1", "session", "phone-1", "+15125550101", s.base, nil) s.Require().NoError(err) @@ -695,38 +690,33 @@ func (s *StoreSuite) TestADialNamingNoOrganizationKeepsTheOneTheCallWasPlacedUnd s.Equal("org", dialed.OrganizationID, "still counted among the organization's calls") } -// onCall opens a leg of customer's on the call in app, dialled at. -func (s *StoreSuite) onCall(customer, callID string, app int64, at time.Time) CallLeg { - leg := CallLeg{CustomerID: customer, StreamAppPK: app, CallType: "agent", CallID: callID, Vendor: "telnyx", - VendorCallID: customer + at.String(), Direction: Outbound, LocalNumber: "+15125550150", RemoteNumber: "+15125550151", DialedAt: at} - opened, err := s.store.CallLegs.Open(s.ctx, &leg) - s.Require().NoError(err) - s.Require().True(opened) - return leg -} - +// ownerOf is the customer the call is, read as Claim reads it. func (s *StoreSuite) ownerOf(scope AppScope, callID string) string { - owner, err := s.store.CallLegs.Owner(s.ctx, scope, "agent", callID) + owner, err := callOwner(s.ctx, s.store.shards(), scope, "agent", callID) s.Require().NoError(err) return owner } -func (s *StoreSuite) TestACallIsTheCustomersWhoseLegWasOnItFirst() { - s.onCall("later", "call", 0, s.base.Add(time.Second)) - s.onCall("first", "call", 0, s.base) - - s.Equal("first", s.ownerOf(AppScope{Unpinned: true}, "call")) - s.Empty(s.ownerOf(AppScope{Unpinned: true}, "another call")) - other, err := s.store.CallLegs.Owner(s.ctx, AppScope{Unpinned: true}, "default", "call") - s.Require().NoError(err) - s.Empty(other, "a call of another type") +// claims says a customer's session is on the call, or how that is refused. +func (s *StoreSuite) claims(customer, callID string, on NamedCall) error { + return s.store.CallLegs.Claim(s.ctx, customer, "agent", callID, on, func(context.Context) error { return nil }) } -func (s *StoreSuite) TestACallIsTheCustomersWhoPlacedItBeforeItIsDialled() { - s.placedLeg("placing", func(leg *CallLeg) { leg.CallType = "agent" }) - s.onCall("later", "call", 0, s.base.Add(time.Second)) +// places keeps a leg of a call a customer is about to dial, unless it is another's. +func (s *StoreSuite) places(customer, callID string, on NamedCall, atOnce *CallsAtOnce) error { + placed := time.Now() + return s.store.CallLegs.PlaceOn(s.ctx, &CallLeg{Token: newID(), CustomerID: customer, OrganizationID: "org", CallType: "agent", CallID: callID, + Vendor: "telnyx", Direction: Outbound, LocalNumber: "+15125550150", RemoteNumber: "+15125550151", PlacedAt: &placed}, on, atOnce) +} - s.Equal("app", s.ownerOf(AppScope{Unpinned: true}, "call")) +// onCall opens a leg of customer's on the call in app, dialled at. +func (s *StoreSuite) onCall(customer, callID string, app int64, at time.Time) CallLeg { + leg := CallLeg{CustomerID: customer, StreamAppPK: app, CallType: "agent", CallID: callID, Vendor: "telnyx", + VendorCallID: customer + at.String(), Direction: Outbound, LocalNumber: "+15125550150", RemoteNumber: "+15125550151", DialedAt: at} + opened, err := s.store.CallLegs.Open(s.ctx, &leg) + s.Require().NoError(err) + s.Require().True(opened) + return leg } func (s *StoreSuite) TestACallIsOwnedInItsOwnStreamApp() { @@ -758,59 +748,146 @@ func (s *StoreSuite) TestACallSomebodyWasOnStaysTheirsAndOneNobodyAnsweredDoesNo s.Empty(s.ownerOf(scope, "rang")) } -func (s *StoreSuite) TestAPhoneIsNotGivenALegThatCameToAnotherCustomersCall() { - scope := AppScope{Unpinned: true} - mine := s.onCall("first", "call", 0, s.base) +func (s *StoreSuite) TestACallIsTheCustomersWhoseLegWasDialledOnItFirst() { s.onCall("later", "call", 0, s.base.Add(time.Second)) + s.onCall("first", "call", 0, s.base) + // Of two dialled at once, the first by id, whichever row came first. + s.onCall("b", "tied", 0, s.base) + s.onCall("a", "tied", 0, s.base) - given, connection, err := s.store.CallLegs.Connect(s.ctx, scope, "agent", "call", "session", "phone-1", "", s.base.Add(time.Minute), nil) + s.Equal("first", s.ownerOf(AppScope{Unpinned: true}, "call")) + s.Equal("a", s.ownerOf(AppScope{Unpinned: true}, "tied")) + s.Empty(s.ownerOf(AppScope{Unpinned: true}, "another call")) + other, err := callOwner(s.ctx, s.store.shards(), AppScope{Unpinned: true}, "default", "call") s.Require().NoError(err) - s.Require().Equal(LegConnected, connection) - s.Equal(mine.ID, given.ID) + s.Empty(other, "a call of another type") +} - _, connection, err = s.store.CallLegs.Connect(s.ctx, scope, "agent", "call", "session", "phone-2", "+15125550151", s.base.Add(time.Minute), nil) - s.Require().NoError(err) - s.Equal(NothingWaiting, connection, "the second phone is given the other customer's leg") - _, err = s.store.CallLegs.EndCall(s.ctx, scope, "agent", "call", s.base.Add(2*time.Minute)) - s.Require().NoError(err) - _, connection, err = s.store.CallLegs.Connect(s.ctx, scope, "agent", "call", "session", "phone-2", "+15125550151", s.base.Add(time.Minute), nil) +func (s *StoreSuite) TestALegPlacedAndNeverDialledIsOnItsCallForTenMinutes() { + on := NamedCall{Scope: AppScope{Unpinned: true}} + s.Require().NoError(s.places("app", "call", on, nil)) + s.ErrorIs(s.places("other", "call", on, nil), ErrCallTaken) + s.ErrorIs(s.claims("other", "call", on), ErrCallTaken) + s.Require().NoError(s.places("app", "call", on, nil), "the customer's own") + + _, err := s.store.shard.NewUpdate().Model((*CallLeg)(nil)).Set("placed_at = now() - interval '11 minutes'").Where("call_id = 'call'").Exec(s.ctx) s.Require().NoError(err) - s.Equal(NothingWaiting, connection, "nor is it revived") + s.NoError(s.places("other", "call", on, nil)) } -// Another call, another app's call of the same name, another type's and a call nobody answered keep no -// phone from its leg, nor does a second leg of the customer's own. -func (s *StoreSuite) TestAPhoneIsGivenItsLegWhateverElseIsOfTheCallsName() { - scope := AppScope{Unpinned: true} - s.onCall("theirs", "call", 7, s.base) - s.placedLeg("another type", nil) - s.onCall("theirs", "another call", 0, s.base) - s.onCall("gone", "call", 0, s.base) - _, err := s.store.CallLegs.EndCall(s.ctx, scope, "agent", "call", s.base.Add(time.Second)) +func (s *StoreSuite) TestARefusedPlacementKeepsNoLeg() { + on := NamedCall{Scope: AppScope{Unpinned: true}} + s.onCall("theirs", "call", 0, s.base) + + s.ErrorIs(s.places("mine", "call", on, &CallsAtOnce{Limit: 9, Ringing: time.Hour}), ErrCallTaken) + + kept, err := s.store.CallLegs.SelectPlaced(s.ctx, "mine", []string{"call"}) s.Require().NoError(err) - first := s.onCall("mine", "call", 0, s.base.Add(time.Minute)) - second := s.onCall("mine", "call", 0, s.base.Add(2*time.Minute)) + s.Empty(kept) + s.ErrorIs(s.places("mine", "free", on, &CallsAtOnce{Limit: 0, Ringing: time.Hour}), ErrCallsAtOnce) +} - for i, want := range []CallLeg{first, second} { - given, connection, err := s.store.CallLegs.Connect(s.ctx, scope, "agent", "call", "session", fmt.Sprintf("phone-%d", i), "+15125550151", s.base.Add(time.Hour), nil) - s.Require().NoError(err) - s.Require().Equal(LegConnected, connection) - s.Equal(want.ID, given.ID) +func (s *StoreSuite) TestACallARunningSessionHoldsIsItsCustomers() { + holder, failing := "theirs", error(nil) + on := NamedCall{Scope: AppScope{Unpinned: true}, Holder: func(context.Context) (string, error) { return holder, failing }} + + s.ErrorIs(s.places("mine", "call", on, nil), ErrCallTaken) + s.ErrorIs(s.claims("mine", "call", on), ErrCallTaken) + s.NoError(s.claims("theirs", "call", on)) + holder = "" + s.NoError(s.claims("mine", "call", on)) + failing = errors.New("redis is down") + s.ErrorIs(s.claims("mine", "call", on), ErrCallUnchecked) + s.ErrorIs(s.places("mine", "call", on, nil), ErrCallUnchecked) + failing = nil + s.ErrorIs(s.store.CallLegs.Claim(s.ctx, "mine", "agent", "call", on, func(context.Context) error { return errors.New("redis is down") }), + ErrCallUnchecked) +} + +// Whoever claims first is let in and the other refused, however long the first takes to keep +// what it claimed with. +func (s *StoreSuite) TestOfTwoCustomersClaimingACallAtOnceOneIsLetIn() { + on := NamedCall{Scope: AppScope{Unpinned: true}} + for i := range 10 { + call := fmt.Sprintf("call-%d", i) + var held atomic.Pointer[string] + holding := on + holding.Holder = func(context.Context) (string, error) { + if customer := held.Load(); customer != nil { + return *customer, nil + } + return "", nil + } + hold := func(customer string) func(context.Context) error { + return func(context.Context) error { + time.Sleep(20 * time.Millisecond) + held.Store(&customer) + return nil + } + } + errs := make([]error, 3) + var wg sync.WaitGroup + wg.Go(func() { errs[0] = s.store.CallLegs.Claim(s.ctx, "a", "agent", call, holding, hold("a")) }) + wg.Go(func() { errs[1] = s.store.CallLegs.Claim(s.ctx, "b", "agent", call, holding, hold("b")) }) + wg.Go(func() { errs[2] = s.places("c", call, holding, nil) }) + wg.Wait() + + in := 0 + for _, err := range errs { + if err == nil { + in++ + continue + } + s.ErrorIs(err, ErrCallTaken) + } + s.Equal(1, in, "%v", errs) } } -// A placed leg is on its call from when it was placed, however long its dial took. -func (s *StoreSuite) TestAPhoneIsGivenTheLegPlacedBeforeAnotherCustomersWasDialled() { - placed := s.base - mine := CallLeg{CustomerID: "mine", CallType: "agent", CallID: "call", Vendor: "telnyx", Direction: Outbound, - LocalNumber: "+15125550150", RemoteNumber: "+15125550152", PlacedAt: &placed, DialedAt: s.base.Add(time.Minute)} - opened, err := s.store.CallLegs.Open(s.ctx, &mine) - s.Require().NoError(err) - s.Require().True(opened) - s.onCall("theirs", "call", 0, s.base.Add(time.Second)) +// The deployment's app is one app, pinned to its id or to none, and another app's call of the +// name is claimed beside it. +func (s *StoreSuite) TestACallIsClaimedInItsOwnStreamApp() { + s.Require().NoError(s.places("theirs", "call", NamedCall{Scope: AppOf(0, 1)}, nil)) - given, connection, err := s.store.CallLegs.Connect(s.ctx, AppScope{Unpinned: true}, "agent", "call", "session", "phone", "", s.base.Add(time.Hour), nil) - s.Require().NoError(err) - s.Require().Equal(LegConnected, connection) - s.Equal(mine.ID, given.ID) + s.ErrorIs(s.claims("mine", "call", NamedCall{Scope: AppOf(1, 1)}), ErrCallTaken) + s.NoError(s.claims("mine", "call", NamedCall{Scope: AppOf(7, 1)})) +} + +// A customer's leg kept in another shard is on the call too. +func (s *ShardedStoreSuite) TestACallIsClaimedAcrossShards() { + on := NamedCall{Scope: AppScope{Unpinned: true}} + place := func(store *Store, customer string) error { + placed := time.Now() + return store.CallLegs.PlaceOn(s.ctx, &CallLeg{Token: newID(), CustomerID: customer, CallType: "agent", CallID: "call", Vendor: "telnyx", + Direction: Outbound, LocalNumber: "+15125550150", RemoteNumber: "+15125550151", PlacedAt: &placed}, on, nil) + } + errs := make([]error, 2) + var wg sync.WaitGroup + wg.Go(func() { errs[0] = place(s.store, "a") }) + wg.Go(func() { errs[1] = place(s.other, "b") }) + wg.Wait() + + s.True(errors.Is(errs[0], ErrCallTaken) != errors.Is(errs[1], ErrCallTaken), "%v", errs) +} + +// Of legs two shards hold, the first dialled is the call's owner, and of two dialled at once the +// first by id, whichever shard asks. +func (s *ShardedStoreSuite) TestACallsOwnerIsTheSameOnEveryShard() { + open := func(store *Store, customer, call string, at time.Time) { + leg := CallLeg{CustomerID: customer, CallType: "agent", CallID: call, Vendor: "telnyx", VendorCallID: customer, Direction: Outbound, + LocalNumber: "+15125550150", RemoteNumber: "+15125550151", DialedAt: at} + _, err := store.CallLegs.Open(s.ctx, &leg) + s.Require().NoError(err) + } + open(s.store, "a-later", "call", s.base.Add(time.Second)) + open(s.other, "first", "call", s.base) + open(s.store, "b", "tied", s.base) + open(s.other, "a", "tied", s.base) + for _, store := range []*Store{s.store, s.other} { + for call, want := range map[string]string{"call": "first", "tied": "a"} { + owner, err := callOwner(s.ctx, store.shards(), AppScope{Unpinned: true}, "agent", call) + s.Require().NoError(err) + s.Equal(want, owner) + } + } } diff --git a/acceleration/internal/store/store_explain_test.go b/acceleration/internal/store/store_explain_test.go index a98c403154..74fa515de0 100644 --- a/acceleration/internal/store/store_explain_test.go +++ b/acceleration/internal/store/store_explain_test.go @@ -415,8 +415,8 @@ func (s *StoreSuite) TestEveryHotTableIsReadByIndex() { _, err := store.CallLegs.Ringing(ctx, AppScope{App: 3}, "default", "stream-101") return err }}, - {name: "CallLegs.Owner", index: "call_legs_call_idx", run: func(ctx context.Context, store *Store) error { - _, err := store.CallLegs.Owner(ctx, AppScope{App: 3}, "default", "stream-101") + {name: "CallLegs.Claim", index: "call_legs_call_idx", run: func(ctx context.Context, store *Store) error { + _, err := callOwner(ctx, store.shards(), AppScope{App: 3}, "default", "stream-101") return err }}, {name: "CallLegs.HasParticipant", index: "call_legs_participant_idx", run: func(ctx context.Context, store *Store) error { From 035d9d8e8d3bee11dd4eb7702df04acc2616aa8e Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 01:08:38 +0000 Subject: [PATCH 05/23] test(phone): whose a named call is --- acceleration/internal/api/phone_test.go | 1 + .../internal/phone/apps_integration_test.go | 16 ++++++++- acceleration/internal/store/call_leg_test.go | 36 ++++++++++++++++++- 3 files changed, 51 insertions(+), 2 deletions(-) diff --git a/acceleration/internal/api/phone_test.go b/acceleration/internal/api/phone_test.go index ca4d1a1ef3..f011238727 100644 --- a/acceleration/internal/api/phone_test.go +++ b/acceleration/internal/api/phone_test.go @@ -1706,6 +1706,7 @@ func (s *CallStatusSuite) TestADirectoryThatDoesNotAnswerHoldsUpNoSession() { began := time.Now() err = heldOn(sessions, s.customerID(), s.utils.uuid()) s.ErrorIs(err, store.ErrCallUnchecked) + s.Less(time.Since(began), 2900*time.Millisecond, "asked for a second, not for as long as the claim has") var answer APIError s.Require().ErrorAs(refusedRequest(err), &answer) s.Equal(ErrorTypeUnavailable, answer.Type) diff --git a/acceleration/internal/phone/apps_integration_test.go b/acceleration/internal/phone/apps_integration_test.go index a8feca41d2..625d29533d 100644 --- a/acceleration/internal/phone/apps_integration_test.go +++ b/acceleration/internal/phone/apps_integration_test.go @@ -2911,7 +2911,9 @@ func (s *AppsSuite) refusedTaken(sessionID string) { trunks := len(s.deployment.Trunks()) s.vendor.dialed = Outbound{} - s.ErrorIs(s.dialInto(sessionID, "+15550001111", map[string]string{"k": "v"}), store.ErrCallTaken) + err := s.dialInto(sessionID, "+15550001111", map[string]string{"k": "v"}) + s.ErrorIs(err, store.ErrCallTaken) + s.NotErrorIs(err, ErrPlacingFailed, "a refusal, not a failure to count the call") s.Empty(s.vendor.dialed.To) s.Len(s.deployment.Trunks(), trunks) @@ -3004,11 +3006,15 @@ func (s *AppsSuite) TestACallIntoASessionNobodyCanTellTheCustomerOfIsNotDialled( _, err := s.service.Call(s.ctx, request) s.ErrorIs(err, store.ErrCallUnchecked) s.ErrorIs(err, ErrNotDialed, "worth trying again") + s.NotErrorIs(err, ErrPlacingFailed) s.Empty(s.vendor.dialed.To) request.MintedID = true _, err = s.service.Call(s.ctx, request) s.NoError(err, "an id the router made is nobody else's to ask about") + request.MintedID, request.SessionID = false, "" + _, err = s.service.Call(s.ctx, request) + s.NoError(err, "nor is one nobody named") } func (s *AppsSuite) TestACallIntoAMintedSessionAsksNothingOfTheCallsLegs() { @@ -3078,3 +3084,11 @@ func (s *AppsSuite) TestWhoIsOnACallIsAskedOfItsApp() { s.ownApp() s.EqualValues(4242, asked()) } + +func (s *AppsSuite) TestACallIntoANamedSessionCountsAmongItsOrganizationsCalls() { + on := &store.NamedCall{Scope: store.AppScope{Unpinned: true}} + _, err := s.service.Outcomes().PlacedWithin(s.ctx, outcome.Call{Key: outcome.Key{CustomerID: s.customer, CallType: defaultCallType, + CallID: uuid.NewString(), Local: s.e164, Remote: "+15550001111"}, Vendor: "twilio"}, "org-"+uuid.NewString(), &store.CallsAtOnce{Ringing: time.Hour}, on) + + s.ErrorIs(err, store.ErrCallsAtOnce) +} diff --git a/acceleration/internal/store/call_leg_test.go b/acceleration/internal/store/call_leg_test.go index 7f279a40b3..46d60c6987 100644 --- a/acceleration/internal/store/call_leg_test.go +++ b/acceleration/internal/store/call_leg_test.go @@ -749,7 +749,7 @@ func (s *StoreSuite) TestACallSomebodyWasOnStaysTheirsAndOneNobodyAnsweredDoesNo } func (s *StoreSuite) TestACallIsTheCustomersWhoseLegWasDialledOnItFirst() { - s.onCall("later", "call", 0, s.base.Add(time.Second)) + s.onCall("a later", "call", 0, s.base.Add(time.Second)) s.onCall("first", "call", 0, s.base) // Of two dialled at once, the first by id, whichever row came first. s.onCall("b", "tied", 0, s.base) @@ -891,3 +891,37 @@ func (s *ShardedStoreSuite) TestACallsOwnerIsTheSameOnEveryShard() { } } } + +// A call is locked while it is claimed, in the deployment's app whether a claim knows its id or +// not, and another app's call of the name is not. +func (s *StoreSuite) TestACallIsLockedWhileItIsClaimed() { + // Another router's, with turns of its own. + elsewhere := &CallLegs{store: s.store} + blocked := func(on NamedCall) (err error) { + unpinned := NamedCall{Scope: AppScope{Unpinned: true}} + s.Require().NoError(s.store.CallLegs.Claim(s.ctx, "a", "agent", "call", unpinned, func(context.Context) error { + ctx, cancel := context.WithTimeout(s.ctx, 300*time.Millisecond) + defer cancel() + err = elsewhere.Claim(ctx, "b", "agent", "call", on, func(context.Context) error { return nil }) + return nil + })) + return err + } + + s.Error(blocked(NamedCall{Scope: AppScope{App: 1, Unpinned: true}})) + s.NoError(blocked(NamedCall{Scope: AppScope{App: 7}})) +} + +func (s *StoreSuite) TestACallWhoseLegsCannotBeReadIsNotClaimed() { + ctx, cancel := context.WithCancel(s.ctx) + defer cancel() + held := false + on := NamedCall{Scope: AppScope{Unpinned: true}, Holder: func(context.Context) (string, error) { + cancel() + return "", nil + }} + + s.Error(s.store.CallLegs.Claim(ctx, "mine", "agent", "call", on, func(context.Context) error { held = true; return nil })) + + s.False(held) +} From 2d20d672f176d05ab6769e3e79f04b3f453606ba Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 01:19:14 +0000 Subject: [PATCH 06/23] fix(phone): the hold decides whose a session's call is --- acceleration/internal/api/callhooks_test.go | 1 + acceleration/internal/api/phone_test.go | 7 ++++ .../internal/api/scheduled_phone_test.go | 1 + .../internal/campaign/campaign_test.go | 1 + acceleration/internal/node/directory.go | 37 +++++++++++-------- acceleration/internal/node/directory_test.go | 11 ++++-- acceleration/internal/session/manager.go | 11 ++++-- acceleration/internal/store/call_leg.go | 6 ++- 8 files changed, 51 insertions(+), 24 deletions(-) diff --git a/acceleration/internal/api/callhooks_test.go b/acceleration/internal/api/callhooks_test.go index c346267686..b9cfa70756 100644 --- a/acceleration/internal/api/callhooks_test.go +++ b/acceleration/internal/api/callhooks_test.go @@ -585,6 +585,7 @@ func (s *CallHooksSuite) TestAnArrivingCallToANumberWithAnAgentIsAnsweredByIt() spec := found.Spec() s.Equal("default", spec.CallType, "the agent joins the call the caller is in") s.Equal(s.callID, spec.CallID) + s.True(spec.MintedID, "nobody chose the caller's call") s.Equal(config, spec.ConfigID) s.True(spec.PersistConversation, "the conversation is kept, as a worker's session keeps it") s.Empty(spec.Caller.UserID, "a caller id is easy to fake, so it names no user") diff --git a/acceleration/internal/api/phone_test.go b/acceleration/internal/api/phone_test.go index f011238727..3aa83e3b59 100644 --- a/acceleration/internal/api/phone_test.go +++ b/acceleration/internal/api/phone_test.go @@ -1715,4 +1715,11 @@ func (s *CallStatusSuite) TestADirectoryThatDoesNotAnswerHoldsUpNoSession() { Incognito: true, Attribution: routing.Attribution{APIKey: "key"}}) s.NoError(err) s.Less(time.Since(began), 10*time.Second) + + answering := s.router.directory + s.router.directory = directory + s.T().Cleanup(func() { s.router.directory = answering }) + status, payload := s.callInto(s.utils.uuid()) + s.Equal(http.StatusServiceUnavailable, status, payload) + s.Contains(payload, "could not tell whose call") } diff --git a/acceleration/internal/api/scheduled_phone_test.go b/acceleration/internal/api/scheduled_phone_test.go index 3562e4179e..c390347052 100644 --- a/acceleration/internal/api/scheduled_phone_test.go +++ b/acceleration/internal/api/scheduled_phone_test.go @@ -83,6 +83,7 @@ func (s *ScheduledTasksSuite) placeCall(user *testClient) placedCall { found, live := s.router.sessions.Get(opened.Id, delivery.owner()) s.Require().True(live) spec := callSpec(config, delivery, found.Spec().AgentID, phone.Placed{SessionID: uuid.NewString()}, s.lineNumber(), to) + s.True(spec.MintedID) // The call is taken on the run before it is placed. took, _, err := s.store.ScheduledTaskRuns.TakeCall(context.Background(), task.CustomerID, run.ID, spec.ID) s.Require().NoError(err) diff --git a/acceleration/internal/campaign/campaign_test.go b/acceleration/internal/campaign/campaign_test.go index f22b42671c..b7a7a1dc7e 100644 --- a/acceleration/internal/campaign/campaign_test.go +++ b/acceleration/internal/campaign/campaign_test.go @@ -68,6 +68,7 @@ func (s *CampaignSuite) TestACampaignSessionJoinsTheCallItRang() { s.Equal("0b9f2a52-5c1e-4d7a-9a3e-0f6b8f1c2d3e", spec.CallID) s.Equal("agent", spec.CallType) + s.True(spec.MintedID) s.False(spec.Text) } diff --git a/acceleration/internal/node/directory.go b/acceleration/internal/node/directory.go index f576f81326..93bc6ab13f 100644 --- a/acceleration/internal/node/directory.go +++ b/acceleration/internal/node/directory.go @@ -224,12 +224,12 @@ return ARGV[1]` // releaseCallScript takes back what this node said of a call, and nothing said since. const releaseCallScript = `if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end return 0` -// errCallHeld is a call another customer's session holds. -var errCallHeld = errors.New("node: the call is another customer's") +// ErrCallHeld is a call another customer's session holds. +var ErrCallHeld = errors.New("node: the call is another customer's") // HoldCall says a customer's session is on the call agent: in a Stream app, 0 for the -// deployment's own, and goes on saying so until ReleaseCall, which every HoldCall is followed by. -// A call another customer's session holds stays its own, which is an error. +// deployment's own, and goes on saying so until ReleaseCall. A call another +// customer's session holds stays its own, and is ErrCallHeld. One that failed says nothing more. func (d *Directory) HoldCall(ctx context.Context, customerID string, app int64, id string) error { call := heldCall{customerID, app, id} d.mu.Lock() @@ -238,26 +238,31 @@ func (d *Directory) HoldCall(ctx context.Context, customerID string, app int64, ctx, cancel := context.WithTimeout(ctx, callTimeout) defer cancel() said, err := d.redis.Do(ctx, d.holdCall(call, customerOf(d.onCall(call)))).ToString() + if err == nil && said != d.onCall(call) { + err = ErrCallHeld + } if err != nil { - return err + d.leaveCall(call) } - if customerOf(said) != customerOf(d.onCall(call)) { - return errCallHeld + return err +} + +// leaveCall is one session here fewer on a call, and true for the last. +func (d *Directory) leaveCall(call heldCall) bool { + d.mu.Lock() + defer d.mu.Unlock() + d.onCalls[call]-- + if d.onCalls[call] > 0 { + return false } - return nil + delete(d.onCalls, call) + return true } // ReleaseCall says a session HoldCall said was on a call is not any more. func (d *Directory) ReleaseCall(ctx context.Context, customerID string, app int64, id string) { call := heldCall{customerID, app, id} - d.mu.Lock() - d.onCalls[call]-- - last := d.onCalls[call] <= 0 - if last { - delete(d.onCalls, call) - } - d.mu.Unlock() - if !last { + if !d.leaveCall(call) { return } ctx, cancel := context.WithTimeout(ctx, callTimeout) diff --git a/acceleration/internal/node/directory_test.go b/acceleration/internal/node/directory_test.go index b03cd516a1..5cc36c1da0 100644 --- a/acceleration/internal/node/directory_test.go +++ b/acceleration/internal/node/directory_test.go @@ -255,18 +255,23 @@ func (s *DirectorySuite) TestACallAnotherCustomerHoldsStaysItsOwn() { first, second := s.directoryAt("node-a:1"), s.directoryAt("node-b:1") s.Require().NoError(first.HoldCall(s.ctx, "acme", 7, "order-42")) - s.Error(second.HoldCall(s.ctx, "acm", 7, "order-42")) + s.ErrorIs(second.HoldCall(s.ctx, "acm", 7, "order-42"), ErrCallHeld) s.Equal("acme", s.holder(7, "order-42")) second.renewAll(s.ctx) s.Equal("acme", s.holder(7, "order-42")) - second.ReleaseCall(s.ctx, "acm", 7, "order-42") - s.Equal("acme", s.holder(7, "order-42")) + // A hold refused is not renewed once the call is free. + s.lapsed() + second.renewAll(s.ctx) + s.Empty(s.holder(7, "order-42")) + first.renewAll(s.ctx) // A claim that lapsed and was taken is not renewed over. s.lapsed() s.Require().NoError(second.HoldCall(s.ctx, "globex", 7, "order-42")) first.renewAll(s.ctx) s.Equal("globex", s.holder(7, "order-42")) + first.ReleaseCall(s.ctx, "acme", 7, "order-42") + s.Equal("globex", s.holder(7, "order-42")) } // A customer's session moving to another node holds its call there, and the node it left takes diff --git a/acceleration/internal/session/manager.go b/acceleration/internal/session/manager.go index 2cc56c1559..61d79a64e4 100644 --- a/acceleration/internal/session/manager.go +++ b/acceleration/internal/session/manager.go @@ -2279,10 +2279,15 @@ func (m *Manager) claimCall(ctx context.Context, spec Spec, named bool) (func(), hold := func(context.Context) error { return nil } release := func() {} if directory != nil { - on.Holder = func(ctx context.Context) (string, error) { return directory.CallHolder(ctx, app, spec.ID) } hold = func(ctx context.Context) error { - release = sync.OnceFunc(func() { directory.ReleaseCall(context.WithoutCancel(ctx), spec.CustomerID, app, spec.ID) }) - return directory.HoldCall(ctx, spec.CustomerID, app, spec.ID) + err := directory.HoldCall(ctx, spec.CustomerID, app, spec.ID) + if errors.Is(err, node.ErrCallHeld) { + return store.ErrCallTaken + } + if err == nil { + release = sync.OnceFunc(func() { directory.ReleaseCall(context.WithoutCancel(ctx), spec.CustomerID, app, spec.ID) }) + } + return err } } if !named || m.options.Store == nil { diff --git a/acceleration/internal/store/call_leg.go b/acceleration/internal/store/call_leg.go index 29b08af4fa..185ac58bbc 100644 --- a/acceleration/internal/store/call_leg.go +++ b/acceleration/internal/store/call_leg.go @@ -898,7 +898,7 @@ func (c NamedCall) claim(ctx context.Context, tx bun.IDB, dbs []bun.IDB, custome } // Claim runs hold, which says a customer's session is on a named call, or refuses with -// ErrCallTaken when the call is another customer's. Both are under the lock PlaceOn keeps a leg +// ErrCallTaken when the call is another customer's, as hold itself may. Both are under the lock PlaceOn keeps a leg // under, so of a session and a call placed at once, or of two sessions, one sees the other. func (r *CallLegs) Claim(ctx context.Context, customerID, callType, callID string, on NamedCall, hold func(context.Context) error) error { release, err := r.placing(ctx, callID) @@ -916,7 +916,9 @@ func (r *CallLegs) Claim(ctx context.Context, customerID, callType, callID strin if err := on.claim(ctx, tx, dbs, customerID, callType, callID); err != nil { return err } - if err := hold(ctx); err != nil { + if err := hold(ctx); errors.Is(err, ErrCallTaken) { + return err + } else if err != nil { return errors.Join(ErrCallUnchecked, err) } return nil From 3dba3930eb76b44c52b46ae79040d5e4afcadcf7 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 01:57:30 +0000 Subject: [PATCH 07/23] test(phone): a claim refused, unread or unanswered --- acceleration/internal/api/phone_test.go | 2 ++ acceleration/internal/store/call_leg_test.go | 3 +++ 2 files changed, 5 insertions(+) diff --git a/acceleration/internal/api/phone_test.go b/acceleration/internal/api/phone_test.go index 3aa83e3b59..3edc4a825f 100644 --- a/acceleration/internal/api/phone_test.go +++ b/acceleration/internal/api/phone_test.go @@ -1719,7 +1719,9 @@ func (s *CallStatusSuite) TestADirectoryThatDoesNotAnswerHoldsUpNoSession() { answering := s.router.directory s.router.directory = directory s.T().Cleanup(func() { s.router.directory = answering }) + began = time.Now() status, payload := s.callInto(s.utils.uuid()) + s.Less(time.Since(began), 2900*time.Millisecond) s.Equal(http.StatusServiceUnavailable, status, payload) s.Contains(payload, "could not tell whose call") } diff --git a/acceleration/internal/store/call_leg_test.go b/acceleration/internal/store/call_leg_test.go index 46d60c6987..269d8168ea 100644 --- a/acceleration/internal/store/call_leg_test.go +++ b/acceleration/internal/store/call_leg_test.go @@ -802,6 +802,9 @@ func (s *StoreSuite) TestACallARunningSessionHoldsIsItsCustomers() { failing = nil s.ErrorIs(s.store.CallLegs.Claim(s.ctx, "mine", "agent", "call", on, func(context.Context) error { return errors.New("redis is down") }), ErrCallUnchecked) + err := s.store.CallLegs.Claim(s.ctx, "mine", "agent", "call", on, func(context.Context) error { return ErrCallTaken }) + s.ErrorIs(err, ErrCallTaken) + s.NotErrorIs(err, ErrCallUnchecked, "it could be told, and is another's") } // Whoever claims first is let in and the other refused, however long the first takes to keep From 4c94ed35d2a3437a86ec421320619a39967ed050 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 03:24:46 +0000 Subject: [PATCH 08/23] fix(phone): claim named calls apart from other placements, and hold a call by session --- acceleration/internal/api/phone_test.go | 96 +++++++++++-- .../internal/api/scheduled_delivery.go | 15 +- .../internal/api/scheduled_phone_test.go | 1 + acceleration/internal/campaign/campaign.go | 2 + .../internal/campaign/campaign_test.go | 1 + acceleration/internal/campaign/dialer.go | 2 +- acceleration/internal/node/directory.go | 135 ++++++++---------- acceleration/internal/node/directory_test.go | 92 ++++++++---- acceleration/internal/session/manager.go | 7 +- acceleration/internal/store/call_leg.go | 61 ++++++-- acceleration/internal/store/call_leg_test.go | 90 ++++++++++++ 11 files changed, 367 insertions(+), 135 deletions(-) diff --git a/acceleration/internal/api/phone_test.go b/acceleration/internal/api/phone_test.go index 3edc4a825f..858cabd584 100644 --- a/acceleration/internal/api/phone_test.go +++ b/acceleration/internal/api/phone_test.go @@ -1589,7 +1589,8 @@ func (s *CallStatusSuite) TestASessionResumedInAnotherAppIsRefusedACallOfAnother spec.ConversationID, spec.AgentID = first.Spec().ConversationID, first.Spec().AgentID s.Require().True(sessions.Close(first.ID(), session.OwnerOf(first.Spec()))) spec.ID = s.arrivedFor("customer-" + s.utils.uuid()) - s.giveApp(s.customerID(), streamAppID(), "key-"+s.customerID()) + app := streamAppID() + s.giveApp(s.customerID(), app, "key-"+s.customerID()) _, err = sessions.Create(context.Background(), spec) s.ErrorIs(err, session.ErrSessionExists) @@ -1599,6 +1600,8 @@ func (s *CallStatusSuite) TestASessionResumedInAnotherAppIsRefusedACallOfAnother s.Require().NoError(err) s.Equal(http.StatusConflict, s.data.backendOfAnotherApp().do(http.MethodPost, "/v1/agents/sessions", textSession(pointerTo(resumed.ID())), nil), "the session holds its call in the app it acts in") + _, err = s.router.directory.HoldCall(context.Background(), "another-customer", app, resumed.ID()) + s.NoError(err, "and no longer in the one it was to act in") } // A session that ends, or fails to open, leaves its call to whoever opens it next. @@ -1640,7 +1643,9 @@ func (s *CallStatusSuite) TestASessionOfAMintedIdOrReopenedIsAskedNothing() { // deafRedis is the suite's Redis until deaf is set: from then on it takes what is sent it and // answers nothing, as a Redis cut off by the network does. -func (s *CallStatusSuite) deafRedis(deaf *atomic.Bool) rueidis.Client { +// +// It goes deaf by itself on being sent any of deafTo. +func (s *CallStatusSuite) deafRedis(deaf *atomic.Bool, deafTo ...string) rueidis.Client { listener, err := net.Listen("tcp", "127.0.0.1:0") s.Require().NoError(err) s.T().Cleanup(func() { _ = listener.Close() }) @@ -1657,7 +1662,21 @@ func (s *CallStatusSuite) deafRedis(deaf *atomic.Bool) rueidis.Client { } go func() { defer upstream.Close() - _, _ = io.Copy(upstream, conn) + buffer := make([]byte, 64<<10) + for { + n, err := conn.Read(buffer) + if err != nil { + return + } + for _, word := range deafTo { + if strings.Contains(string(buffer[:n]), word) { + deaf.Store(true) + } + } + if _, err := upstream.Write(buffer[:n]); err != nil { + return + } + } }() go func() { buffer := make([]byte, 4096) @@ -1691,15 +1710,7 @@ func (s *CallStatusSuite) TestADirectoryThatDoesNotAnswerHoldsUpNoSession() { directory, err := node.NewDirectory(node.DirectoryOptions{Redis: s.deafRedis(&deaf), Address: "node-deaf:1", Prefix: s.relayPrefix, Logger: logger}) s.Require().NoError(err) s.T().Cleanup(directory.Close) - sessions, err := session.NewManager(session.ManagerOptions{ - LLM: s.streams.LLM, Conversations: s.conversations, Stream: s.stream, Store: s.store, Directory: directory, Logger: logger, - Writer: s.routerWriter(s.store, s.live, nil, logger), - Edge: func(context.Context, session.Spec, streamapp.Bound, *slog.Logger) (agent.Edge, error) { - return &silentEdge{inbound: make(chan agent.InboundAudio, 4)}, nil - }, - }) - s.Require().NoError(err) - s.T().Cleanup(func() { _ = sessions.Shutdown() }) + sessions := s.sessionsWith(directory) s.Require().NoError(heldOn(sessions, s.customerID(), s.utils.uuid())) deaf.Store(true) @@ -1716,6 +1727,13 @@ func (s *CallStatusSuite) TestADirectoryThatDoesNotAnswerHoldsUpNoSession() { s.NoError(err) s.Less(time.Since(began), 10*time.Second) + // Letting go of a call is no slower. + began = time.Now() + release, err := directory.HoldCall(context.Background(), s.customerID(), 0, s.utils.uuid()) + s.Require().Error(err) + release(context.Background()) + s.Less(time.Since(began), 2900*time.Millisecond) + answering := s.router.directory s.router.directory = directory s.T().Cleanup(func() { s.router.directory = answering }) @@ -1725,3 +1743,57 @@ func (s *CallStatusSuite) TestADirectoryThatDoesNotAnswerHoldsUpNoSession() { s.Equal(http.StatusServiceUnavailable, status, payload) s.Contains(payload, "could not tell whose call") } + +// sessionsWith is a node's sessions, said to be there by directory. +func (s *CallStatusSuite) sessionsWith(directory *node.Directory) *session.Manager { + logger := slog.New(slog.DiscardHandler) + sessions, err := session.NewManager(session.ManagerOptions{ + LLM: s.streams.LLM, Conversations: s.conversations, Stream: s.stream, Store: s.store, Directory: directory, Logger: logger, + Writer: s.routerWriter(s.store, s.live, nil, logger), + Edge: func(context.Context, session.Spec, streamapp.Bound, *slog.Logger) (agent.Edge, error) { + return &silentEdge{inbound: make(chan agent.InboundAudio, 4)}, nil + }, + }) + s.Require().NoError(err) + s.T().Cleanup(func() { _ = sessions.Shutdown() }) + return sessions +} + +// Sessions of chosen ids that the directory does not answer for hold up no other placement. +func (s *CallStatusSuite) TestSessionsNotAnsweredForHoldUpNoOtherPlacement() { + s.useApp(s.data.createApp()) + var deaf atomic.Bool + directory, err := node.NewDirectory(node.DirectoryOptions{Redis: s.deafRedis(&deaf), Address: "node-deaf:2", Prefix: s.relayPrefix}) + s.Require().NoError(err) + s.T().Cleanup(directory.Close) + sessions := s.sessionsWith(directory) + deaf.Store(true) + var wg sync.WaitGroup + began := time.Now() + for range 64 { + wg.Go(func() { s.ErrorIs(heldOn(sessions, s.customerID(), s.utils.uuid()), store.ErrCallUnchecked) }) + } + + at := time.Now() + s.Require().NoError(s.store.CallLegs.PlaceWithin(context.Background(), &store.CallLeg{Token: s.utils.uuid(), CustomerID: s.customerID(), + OrganizationID: s.utils.uuid(), CallType: "agent", CallID: s.utils.uuid(), Vendor: "telnyx", Direction: store.Outbound, + LocalNumber: s.utils.number(), RemoteNumber: s.utils.number(), PlacedAt: &at}, store.CallsAtOnce{Limit: 9, Ringing: time.Hour})) + + s.Less(time.Since(at), time.Second) + wg.Wait() + s.Less(time.Since(began), 2900*time.Millisecond) +} + +// A session refused after it said it is on its call says so no longer. +func (s *CallStatusSuite) TestASessionRefusedAfterItHeldItsCallLeavesIt() { + s.useApp(s.data.createApp()) + var deaf atomic.Bool + // Deaf to the hold, which Redis takes all the same. + directory, err := node.NewDirectory(node.DirectoryOptions{Redis: s.deafRedis(&deaf, "HSET"), Address: "node-deaf:3", Prefix: s.relayPrefix}) + s.Require().NoError(err) + s.T().Cleanup(directory.Close) + id := s.utils.uuid() + s.Require().ErrorIs(heldOn(s.sessionsWith(directory), "customer-"+s.utils.uuid(), id), store.ErrCallUnchecked) + + s.NoError(heldOn(s.manager, s.customerID(), id)) +} diff --git a/acceleration/internal/api/scheduled_delivery.go b/acceleration/internal/api/scheduled_delivery.go index b116c35c85..c0fc94d424 100644 --- a/acceleration/internal/api/scheduled_delivery.go +++ b/acceleration/internal/api/scheduled_delivery.go @@ -1173,17 +1173,22 @@ func (s *Server) placeCall(ctx context.Context, delivery scheduledDelivery, foun if deadline, ok := ctx.Deadline(); ok && time.Until(deadline) < s.phoneWindow+s.callLimit { return session.Spec{}, &scheduling.Missed{Err: fmt.Errorf("the call would have %s left to ring and be held", lateFor(time.Until(deadline)))} } - placed, err := s.phone.Call(ctx, phone.CallRequest{ + placed, err := s.phone.Call(ctx, callRequest(delivery, sessionID, from, to)) + if err != nil { + return session.Spec{}, unpaid(overTier(err)) + } + return callSpec(config, delivery, found.Spec().AgentID, placed, from, to), nil +} + +// callRequest is the call a task rings its user on, into the session the run took. +func callRequest(delivery scheduledDelivery, sessionID, from, to string) phone.CallRequest { + return phone.CallRequest{ Owner: routing.Owner{CustomerID: delivery.CustomerID, Attribution: delivery.attribution()}, From: from, To: to, SessionID: sessionID, MintedID: true, - }) - if err != nil { - return session.Spec{}, unpaid(overTier(err)) } - return callSpec(config, delivery, found.Spec().AgentID, placed, from, to), nil } // callSpec is the session a call a task placed is held in: the config as it diff --git a/acceleration/internal/api/scheduled_phone_test.go b/acceleration/internal/api/scheduled_phone_test.go index c390347052..30a6b9194f 100644 --- a/acceleration/internal/api/scheduled_phone_test.go +++ b/acceleration/internal/api/scheduled_phone_test.go @@ -84,6 +84,7 @@ func (s *ScheduledTasksSuite) placeCall(user *testClient) placedCall { s.Require().True(live) spec := callSpec(config, delivery, found.Spec().AgentID, phone.Placed{SessionID: uuid.NewString()}, s.lineNumber(), to) s.True(spec.MintedID) + s.True(callRequest(delivery, spec.ID, s.lineNumber(), to).MintedID) // The call is taken on the run before it is placed. took, _, err := s.store.ScheduledTaskRuns.TakeCall(context.Background(), task.CustomerID, run.ID, spec.ID) s.Require().NoError(err) diff --git a/acceleration/internal/campaign/campaign.go b/acceleration/internal/campaign/campaign.go index 7f81db089f..895712f0a5 100644 --- a/acceleration/internal/campaign/campaign.go +++ b/acceleration/internal/campaign/campaign.go @@ -772,6 +772,8 @@ func placing(campaign store.Campaign, contact store.Contact, step Step) phone.Ca Owner: routing.Owner{CustomerID: campaign.CustomerID, Attribution: scheduledBy(campaign), Tags: campaign.Tags}, From: campaign.FromNumber, To: contact.ToNumber, + // The session is the runner's to name (Dial.SessionID). + MintedID: true, // Only a campaign that does something on a machine asks the vendor who answered. DetectMachine: !step.Voicemail.off(), } diff --git a/acceleration/internal/campaign/campaign_test.go b/acceleration/internal/campaign/campaign_test.go index b7a7a1dc7e..450c82a62e 100644 --- a/acceleration/internal/campaign/campaign_test.go +++ b/acceleration/internal/campaign/campaign_test.go @@ -61,6 +61,7 @@ func (s *CampaignSuite) TestACampaignSessionJoinsTheCallItRang() { request := placing(store.Campaign{CustomerID: "customer-1", FromNumber: "+15550000001"}, store.Contact{ID: "contact-7", ToNumber: "+15550000002"}, Step{}) s.Empty(request.SessionID) + s.True(request.MintedID) spec := session.Spec{Text: true, CustomerID: "customer-1"} meet(&spec, phone.Placed{SessionID: "0b9f2a52-5c1e-4d7a-9a3e-0f6b8f1c2d3e"}) diff --git a/acceleration/internal/campaign/dialer.go b/acceleration/internal/campaign/dialer.go index bcf363123b..5e96857a53 100644 --- a/acceleration/internal/campaign/dialer.go +++ b/acceleration/internal/campaign/dialer.go @@ -70,7 +70,7 @@ func (d *phoneDialer) Dial(ctx context.Context, dial Dial) (Dialed, error) { } request := placing(dial.Campaign, dial.Contact, dial.Step) - request.SessionID, request.MintedID = dial.SessionID, true + request.SessionID = dial.SessionID placed, err := d.phone.Call(ctx, request) if err != nil { dialed := resultOf(err) diff --git a/acceleration/internal/node/directory.go b/acceleration/internal/node/directory.go index 93bc6ab13f..617d93e75e 100644 --- a/acceleration/internal/node/directory.go +++ b/acceleration/internal/node/directory.go @@ -15,6 +15,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "log/slog" "maps" "net/url" @@ -80,8 +81,9 @@ type Directory struct { // held maps a session this node is running to the agent it writes as and the // conversation it answers in, each empty for a session without one. held map[heldSession]claim - // onCalls counts the sessions running here by the call each is on. - onCalls map[heldCall]int + // onCalls are the calls the sessions running here are on, and holds how many were ever said. + onCalls map[heldCall]struct{} + holds uint64 // waiting counts the dispatch workers connected here, by customer. waiting map[string]int // offered is what the workers here host, by customer and agent. @@ -94,12 +96,9 @@ type offerKey struct{ customerID, agentID string } // one id. type heldSession struct{ customerID, sessionID string } -// heldCall is a customer's session's call, agent:, in a Stream app: 0 for the deployment's own. -type heldCall struct { - customerID string - app int64 - id string -} +// heldCall is what one session says of the call it is on: its customer, where the call is held, and +// the session's own field there. +type heldCall struct{ customerID, key, field string } // claim is what a session this node holds is found by besides its own id. type claim struct{ agentID, conversationID string } @@ -146,7 +145,7 @@ func NewDirectory(options DirectoryOptions) (*Directory, error) { logger: logger, cancel: cancel, held: map[heldSession]claim{}, - onCalls: map[heldCall]int{}, + onCalls: map[heldCall]struct{}{}, waiting: map[string]int{}, offered: map[offerKey][]byte{}, } @@ -212,64 +211,67 @@ func (d *Directory) Hold(ctx context.Context, customerID, sessionID, agentID, co // waits for each to open. const callTimeout = time.Second -// holdCallScript says a call is a customer's on a node, for a while, unless another customer's -// says so already. A renewal, whose third argument is empty, leaves the customer's own on another -// node too. -const holdCallScript = ` -local said = redis.call('GET', KEYS[1]) -if said and said ~= ARGV[1] and (ARGV[3] == '' or string.sub(said, 1, #ARGV[3]) ~= ARGV[3]) then return said end -redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2]) -return ARGV[1]` - -// releaseCallScript takes back what this node said of a call, and nothing said since. -const releaseCallScript = `if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end return 0` +// A call is a hash, a field for each session on it, which says when it lapses, since a hash cannot +// expire its fields one at a time, then its customer. liveCall walks the fields, passes over those +// that lapsed and runs what it is given for the customer of each other. +const liveCall = ` +local time = redis.call('TIME') +local now = time[1] * 1000 + math.floor(time[2] / 1000) +local fields = redis.call('HGETALL', KEYS[1]) +for i = 1, #fields, 2 do + local space = string.find(fields[i + 1], ' ', 1, true) + local customer = string.sub(fields[i + 1], space + 1) + if tonumber(string.sub(fields[i + 1], 1, space - 1)) > now then + %s + end +end +` + +// holdCallScript says a session of a customer's is on a call, for a while, and 1, or 0 when another +// customer's is on it. callHolderScript is the customer whose session is on a call, or empty. +var ( + holdCallScript = fmt.Sprintf(liveCall, `if customer ~= ARGV[2] then return 0 end`) + ` +redis.call('HSET', KEYS[1], ARGV[1], string.format('%d %s', now + ARGV[3], ARGV[2])) +redis.call('PEXPIRE', KEYS[1], ARGV[3]) +return 1` + callHolderScript = fmt.Sprintf(liveCall, `return customer`) + ` +return ''` +) -// ErrCallHeld is a call another customer's session holds. +// ErrCallHeld is a call another customer's session is on. var ErrCallHeld = errors.New("node: the call is another customer's") // HoldCall says a customer's session is on the call agent: in a Stream app, 0 for the -// deployment's own, and goes on saying so until ReleaseCall. A call another -// customer's session holds stays its own, and is ErrCallHeld. One that failed says nothing more. -func (d *Directory) HoldCall(ctx context.Context, customerID string, app int64, id string) error { - call := heldCall{customerID, app, id} +// deployment's own, and goes on saying so until release. It is ErrCallHeld, and says nothing, when +// another customer's session is on it. Any other error is one of saying so: it is said again with +// the next renewal, unless released. +func (d *Directory) HoldCall(ctx context.Context, customerID string, app int64, id string) (release func(context.Context), _ error) { d.mu.Lock() - d.onCalls[call]++ + d.holds++ + call := heldCall{customerID, d.callKey(app, id), d.address + "#" + strconv.FormatUint(d.holds, 10)} + d.onCalls[call] = struct{}{} d.mu.Unlock() ctx, cancel := context.WithTimeout(ctx, callTimeout) defer cancel() - said, err := d.redis.Do(ctx, d.holdCall(call, customerOf(d.onCall(call)))).ToString() - if err == nil && said != d.onCall(call) { - err = ErrCallHeld - } - if err != nil { - d.leaveCall(call) + held, err := d.redis.Do(ctx, d.holdCall(call)).AsInt64() + if err == nil && held == 0 { + d.mu.Lock() + delete(d.onCalls, call) + d.mu.Unlock() + return func(context.Context) {}, ErrCallHeld } - return err + return func(ctx context.Context) { d.releaseCall(ctx, call) }, err } -// leaveCall is one session here fewer on a call, and true for the last. -func (d *Directory) leaveCall(call heldCall) bool { +// releaseCall takes back what one session said of a call, and what no other did. +func (d *Directory) releaseCall(ctx context.Context, call heldCall) { d.mu.Lock() - defer d.mu.Unlock() - d.onCalls[call]-- - if d.onCalls[call] > 0 { - return false - } delete(d.onCalls, call) - return true -} - -// ReleaseCall says a session HoldCall said was on a call is not any more. -func (d *Directory) ReleaseCall(ctx context.Context, customerID string, app int64, id string) { - call := heldCall{customerID, app, id} - if !d.leaveCall(call) { - return - } + d.mu.Unlock() ctx, cancel := context.WithTimeout(ctx, callTimeout) defer cancel() - release := d.redis.B().Eval().Script(releaseCallScript).Numkeys(1).Key(d.callKey(app, id)).Arg(d.onCall(call)).Build() - if err := d.redis.Do(ctx, release).Error(); err != nil { - d.logger.Warn("could not take back this node's claim on a call", "customer", customerID, "call", id, "error", err) + if err := d.redis.Do(ctx, d.redis.B().Hdel().Key(call.key).Field(call.field).Build()).Error(); err != nil { + d.logger.Warn("could not take back a session's hold on a call", "customer", call.customerID, "call", call.key, "error", err) } } @@ -278,11 +280,7 @@ func (d *Directory) ReleaseCall(ctx context.Context, customerID string, app int6 func (d *Directory) CallHolder(ctx context.Context, app int64, id string) (string, error) { ctx, cancel := context.WithTimeout(ctx, callTimeout) defer cancel() - said, err := d.lookup(ctx, d.callKey(app, id)) - if err != nil || said == "" { - return "", err - } - return url.QueryUnescape(customerOf(said)) + return d.redis.Do(ctx, d.redis.B().Eval().Script(callHolderScript).Numkeys(1).Key(d.callKey(app, id)).Build()).ToString() } // callKey is where a call is held: node:call::. @@ -290,24 +288,9 @@ func (d *Directory) callKey(app int64, id string) string { return d.calls + strconv.FormatInt(app, 10) + ":" + id } -// onCall is what this node says of a call: its customer, escaped so that it holds no space, and -// the node's address. -func (d *Directory) onCall(call heldCall) string { - return url.QueryEscape(call.customerID) + " " + d.address -} - -// customerOf is the escaped customer of what a node says of a call. -func customerOf(said string) string { - customer, _, _ := strings.Cut(said, " ") - return customer -} - -func (d *Directory) holdCall(call heldCall, over string) rueidis.Completed { - if over != "" { - over += " " - } - return d.redis.B().Eval().Script(holdCallScript).Numkeys(1).Key(d.callKey(call.app, call.id)). - Arg(d.onCall(call), strconv.FormatInt(holdFor.Milliseconds(), 10), over).Build() +func (d *Directory) holdCall(call heldCall) rueidis.Completed { + return d.redis.B().Eval().Script(holdCallScript).Numkeys(1).Key(call.key). + Arg(call.field, call.customerID, strconv.FormatInt(holdFor.Milliseconds(), 10)).Build() } // Release says this node is not running a customer's session any more. @@ -675,7 +658,7 @@ func (d *Directory) renewAll(ctx context.Context) { commands = append(commands, d.writeCommands(key, claimed)...) } for call := range onCalls { - commands = append(commands, d.holdCall(call, "")) + commands = append(commands, d.holdCall(call)) } for customerID := range waiting { commands = append(commands, d.advertiseCommands(customerID)...) diff --git a/acceleration/internal/node/directory_test.go b/acceleration/internal/node/directory_test.go index 5cc36c1da0..e5e0e8c580 100644 --- a/acceleration/internal/node/directory_test.go +++ b/acceleration/internal/node/directory_test.go @@ -55,7 +55,7 @@ func (s *DirectorySuite) TestARenewalIsOneRoundTrip() { for _, session := range []string{"s1", "s2", "s3"} { directory.Hold(s.ctx, "acme", session, "agent-"+session, "messaging:"+session) } - s.Require().NoError(directory.HoldCall(s.ctx, "acme", 0, "s1")) + s.callOf(directory, "acme") directory.Wait(s.ctx, "acme") directory.Wait(s.ctx, "globex") directory.Offer(s.ctx, "acme", "agent-s1", []byte(`{"tools":[]}`)) @@ -226,14 +226,27 @@ func (s *DirectorySuite) holder(app int64, id string) string { return customer } -// lapsed drops what a node said of a call, as its expiry does. +// callOf has a directory say a customer's session is on the call order-42 of app 7. +func (s *DirectorySuite) callOf(directory *Directory, customer string) func() { + release, err := directory.HoldCall(s.ctx, customer, 7, "order-42") + s.Require().NoError(err) + return func() { release(s.ctx) } +} + +// lapsed puts what is said of the call, as a node that stopped renewing leaves it, in the past. func (s *DirectorySuite) lapsed() { - s.Require().NoError(s.client.Do(s.ctx, s.client.B().Del().Key(s.prefix+":call:7:order-42").Build()).Error()) + key := s.prefix + ":call:7:order-42" + fields, err := s.client.Do(s.ctx, s.client.B().Hgetall().Key(key).Build()).AsStrMap() + s.Require().NoError(err) + for field, said := range fields { + _, customer, _ := strings.Cut(said, " ") + s.Require().NoError(s.client.Do(s.ctx, s.client.B().Hset().Key(key).FieldValue().FieldValue(field, "1 "+customer).Build()).Error()) + } } func (s *DirectorySuite) TestASessionsCallIsFoundByItsAppUntilItIsReleased() { directory := s.directoryAt("node-a:1") - s.Require().NoError(directory.HoldCall(s.ctx, "a customer:1", 7, "order-42")) + release := s.callOf(directory, "a customer:1") s.Equal("a customer:1", s.holder(7, "order-42")) s.Empty(s.holder(0, "order-42"), "another app's call of the name") @@ -242,59 +255,84 @@ func (s *DirectorySuite) TestASessionsCallIsFoundByItsAppUntilItIsReleased() { s.Require().NoError(err) s.InDelta(30000, ttl, 5000, "it lapses with the node") s.lapsed() + s.Empty(s.holder(7, "order-42")) directory.renewAll(s.ctx) s.Equal("a customer:1", s.holder(7, "order-42")) - directory.ReleaseCall(s.ctx, "a customer:1", 7, "order-42") + release() s.Empty(s.holder(7, "order-42")) directory.renewAll(s.ctx) s.Empty(s.holder(7, "order-42")) } +func (s *DirectorySuite) TestAHoldLapsesThirtySecondsAfterItIsSaid() { + s.callOf(s.directoryAt("node-a:1"), "acme") + + fields, err := s.client.Do(s.ctx, s.client.B().Hgetall().Key(s.prefix+":call:7:order-42").Build()).AsStrMap() + s.Require().NoError(err) + s.Require().Len(fields, 1) + for _, said := range fields { + until, _, _ := strings.Cut(said, " ") + at, err := strconv.ParseInt(until, 10, 64) + s.Require().NoError(err) + s.InDelta(time.Now().Add(30*time.Second).UnixMilli(), at, 5000) + } +} + func (s *DirectorySuite) TestACallAnotherCustomerHoldsStaysItsOwn() { first, second := s.directoryAt("node-a:1"), s.directoryAt("node-b:1") - s.Require().NoError(first.HoldCall(s.ctx, "acme", 7, "order-42")) + release := s.callOf(first, "acme") - s.ErrorIs(second.HoldCall(s.ctx, "acm", 7, "order-42"), ErrCallHeld) - s.Equal("acme", s.holder(7, "order-42")) + refused, err := second.HoldCall(s.ctx, "acm", 7, "order-42") + s.ErrorIs(err, ErrCallHeld) + refused(s.ctx) second.renewAll(s.ctx) s.Equal("acme", s.holder(7, "order-42")) - // A hold refused is not renewed once the call is free. + // A hold refused is not said once the call is free. s.lapsed() second.renewAll(s.ctx) s.Empty(s.holder(7, "order-42")) - first.renewAll(s.ctx) - // A claim that lapsed and was taken is not renewed over. - s.lapsed() - s.Require().NoError(second.HoldCall(s.ctx, "globex", 7, "order-42")) + // One that lapsed and was taken is not renewed over, nor taken back with it. + s.callOf(second, "globex") first.renewAll(s.ctx) s.Equal("globex", s.holder(7, "order-42")) - first.ReleaseCall(s.ctx, "acme", 7, "order-42") + release() s.Equal("globex", s.holder(7, "order-42")) } -// A customer's session moving to another node holds its call there, and the node it left takes -// back nothing. -func (s *DirectorySuite) TestACallIsHeldByTheNodeItsSessionMovedTo() { +// A customer's sessions on one call, here and on another node, each hold it until the last is gone. +func (s *DirectorySuite) TestACallIsHeldUntilTheLastSessionOnItIsGone() { first, second := s.directoryAt("node-a:1"), s.directoryAt("node-b:1") - s.Require().NoError(first.HoldCall(s.ctx, "acme", 7, "order-42")) - s.Require().NoError(second.HoldCall(s.ctx, "acme", 7, "order-42")) - first.renewAll(s.ctx) - - first.ReleaseCall(s.ctx, "acme", 7, "order-42") + here, again, there := s.callOf(first, "acme"), s.callOf(first, "acme"), s.callOf(second, "acme") + refused := func() { + _, err := s.directoryAt("node-c:1").HoldCall(s.ctx, "globex", 7, "order-42") + s.ErrorIs(err, ErrCallHeld) + } + refused() + there() + refused() + here() + refused() s.Equal("acme", s.holder(7, "order-42")) + again() + s.Empty(s.holder(7, "order-42")) } -func (s *DirectorySuite) TestACallTwoSessionsHereAreOnIsHeldUntilBothAreGone() { +// A hold Redis did not take is said with the next renewal, until it is released. +func (s *DirectorySuite) TestAHoldThatWasNotSaidIsSaidWithTheNextRenewal() { directory := s.directoryAt("node-a:1") - s.Require().NoError(directory.HoldCall(s.ctx, "acme", 7, "order-42")) - s.Require().NoError(directory.HoldCall(s.ctx, "acme", 7, "order-42")) + cancelled, cancel := context.WithCancel(s.ctx) + cancel() + release, err := directory.HoldCall(cancelled, "acme", 7, "order-42") + s.Require().Error(err) + s.Require().NotErrorIs(err, ErrCallHeld) + s.Require().Empty(s.holder(7, "order-42")) - directory.ReleaseCall(s.ctx, "acme", 7, "order-42") + directory.renewAll(s.ctx) s.Equal("acme", s.holder(7, "order-42")) - directory.ReleaseCall(s.ctx, "acme", 7, "order-42") + release(s.ctx) s.Empty(s.holder(7, "order-42")) } diff --git a/acceleration/internal/session/manager.go b/acceleration/internal/session/manager.go index 61d79a64e4..5a3dd5b3f0 100644 --- a/acceleration/internal/session/manager.go +++ b/acceleration/internal/session/manager.go @@ -2279,14 +2279,13 @@ func (m *Manager) claimCall(ctx context.Context, spec Spec, named bool) (func(), hold := func(context.Context) error { return nil } release := func() {} if directory != nil { + on.Holder = func(ctx context.Context) (string, error) { return directory.CallHolder(ctx, app, spec.ID) } hold = func(ctx context.Context) error { - err := directory.HoldCall(ctx, spec.CustomerID, app, spec.ID) + said, err := directory.HoldCall(ctx, spec.CustomerID, app, spec.ID) + release = sync.OnceFunc(func() { said(context.WithoutCancel(ctx)) }) if errors.Is(err, node.ErrCallHeld) { return store.ErrCallTaken } - if err == nil { - release = sync.OnceFunc(func() { directory.ReleaseCall(context.WithoutCancel(ctx), spec.CustomerID, app, spec.ID) }) - } return err } } diff --git a/acceleration/internal/store/call_leg.go b/acceleration/internal/store/call_leg.go index 185ac58bbc..52c2bea6c0 100644 --- a/acceleration/internal/store/call_leg.go +++ b/acceleration/internal/store/call_leg.go @@ -133,6 +133,9 @@ type CallLegs struct { stripes [placingStripes]chan struct{} placings chan struct{} stripesOnce sync.Once + // claims are the places of the named calls being claimed, at most claimingAtOnce. + claims chan struct{} + claimsOnce sync.Once } // Open records a leg of a call in this shard: an outbound one ringing, an inbound one @@ -777,7 +780,14 @@ func (r *CallLegs) placeOn(ctx context.Context, leg *CallLeg, on *NamedCall, atO // A campaign tick places many calls of one organization at once, and each waiting on the // advisory lock holds a connection of the shared database's pool: waiting here first keeps a // router to one per organization, and to placingAtOnce in all. - release, err := r.placing(ctx, cmp.Or(leg.OrganizationID, leg.CallID)) + turn := func(ctx context.Context) (func(), error) { return r.placing(ctx, leg.OrganizationID) } + if on != nil { + turn = func(ctx context.Context) (func(), error) { return r.claiming(ctx, *on, leg.CustomerID) } + } + release, err := turn(ctx) + if errors.Is(err, ErrCallTaken) || errors.Is(err, ErrCallUnchecked) { + return stack.Wrap(err) + } if err != nil { return stack.Wrap(fmt.Errorf("store: place call leg: %w", err)) } @@ -878,14 +888,8 @@ func (c NamedCall) claim(ctx context.Context, tx bun.IDB, dbs []bun.IDB, custome if err := lockUntilCommit(ctx, tx, strconv.FormatInt(app, 10)+":"+callType+":"+callID, callLockSeed); err != nil { return err } - if c.Holder != nil { - holder, err := c.Holder(ctx) - if err != nil { - return errors.Join(ErrCallUnchecked, err) - } - if holder != "" && holder != customerID { - return ErrCallTaken - } + if err := c.held(ctx, customerID); err != nil { + return err } owner, err := callOwner(ctx, dbs, c.Scope, callType, callID) if err != nil { @@ -897,11 +901,48 @@ func (c NamedCall) claim(ctx context.Context, tx bun.IDB, dbs []bun.IDB, custome return nil } +// held refuses a call another customer's running session is on. +func (c NamedCall) held(ctx context.Context, customerID string) error { + if c.Holder == nil { + return nil + } + holder, err := c.Holder(ctx) + if err != nil { + return errors.Join(ErrCallUnchecked, err) + } + if holder != "" && holder != customerID { + return ErrCallTaken + } + return nil +} + +// claimingAtOnce is how many named calls a router claims at once, each holding a connection of +// the shared database's pool, apart from placingAtOnce so that they hold up no other placement. +const claimingAtOnce = 8 + +// claiming waits, for no longer than placingFor, for a place among the named calls being claimed, +// and returns what gives it up. Who is on the call is asked before: a holder that does not answer +// then holds no place. +func (r *CallLegs) claiming(ctx context.Context, on NamedCall, customerID string) (func(), error) { + if err := on.held(ctx, customerID); err != nil { + return nil, err + } + r.claimsOnce.Do(func() { r.claims = make(chan struct{}, claimingAtOnce) }) + ctx, cancel := context.WithTimeout(ctx, placingFor) + defer cancel() + select { + case r.claims <- struct{}{}: + return func() { <-r.claims }, nil + case <-ctx.Done(): + return nil, errors.Join(ErrCallUnchecked, ctx.Err()) + } +} + // Claim runs hold, which says a customer's session is on a named call, or refuses with // ErrCallTaken when the call is another customer's, as hold itself may. Both are under the lock PlaceOn keeps a leg // under, so of a session and a call placed at once, or of two sessions, one sees the other. func (r *CallLegs) Claim(ctx context.Context, customerID, callType, callID string, on NamedCall, hold func(context.Context) error) error { - release, err := r.placing(ctx, callID) + release, err := r.claiming(ctx, on, customerID) if err != nil { return stack.Wrap(fmt.Errorf("store: claim call: %w", err)) } diff --git a/acceleration/internal/store/call_leg_test.go b/acceleration/internal/store/call_leg_test.go index 269d8168ea..e6cc581afc 100644 --- a/acceleration/internal/store/call_leg_test.go +++ b/acceleration/internal/store/call_leg_test.go @@ -928,3 +928,93 @@ func (s *StoreSuite) TestACallWhoseLegsCannotBeReadIsNotClaimed() { s.False(held) } + +// A leg counts as on its call until ten minutes after it was placed. +func (s *StoreSuite) TestALegPlacedNineMinutesAgoIsOnItsCall() { + on := NamedCall{Scope: AppScope{Unpinned: true}} + s.Require().NoError(s.places("app", "call", on, nil)) + _, err := s.store.shard.NewUpdate().Model((*CallLeg)(nil)).Set("placed_at = now() - interval '9 minutes'").Where("call_id = 'call'").Exec(s.ctx) + s.Require().NoError(err) + + s.ErrorIs(s.places("other", "call", on, nil), ErrCallTaken) +} + +// A leg placed and dialled is on its call from its dial. +func (s *StoreSuite) TestACallIsNotTheCustomersWhoPlacedALegAndDialledItLater() { + placed := s.base.Add(-time.Minute) + leg := CallLeg{CustomerID: "placed", CallType: "agent", CallID: "call", Vendor: "telnyx", Direction: Outbound, + LocalNumber: "+15125550150", RemoteNumber: "+15125550152", PlacedAt: &placed, DialedAt: s.base.Add(time.Minute)} + _, err := s.store.CallLegs.Open(s.ctx, &leg) + s.Require().NoError(err) + s.onCall("dialled", "call", 0, s.base) + + s.Equal("dialled", s.ownerOf(AppScope{Unpinned: true}, "call")) +} + +// Named calls of no organization wait for no turn of each other's. +func (s *StoreSuite) TestNamedCallsOfNoOrganizationArePlacedBesideEachOther() { + asking, asked := make(chan struct{}), make(chan struct{}) + var once sync.Once + waits := NamedCall{Scope: AppScope{Unpinned: true}, Holder: func(ctx context.Context) (string, error) { + once.Do(func() { close(asking) }) + select { + case <-asked: + case <-ctx.Done(): + } + return "", ctx.Err() + }} + place := func(call string, on NamedCall) error { + placed := time.Now() + return s.store.CallLegs.PlaceOn(s.ctx, &CallLeg{Token: newID(), CustomerID: "app", CallType: "agent", CallID: call, Vendor: "telnyx", + Direction: Outbound, LocalNumber: "+15125550150", RemoteNumber: "+15125550151", PlacedAt: &placed}, on, nil) + } + first := make(chan error, 1) + go func() { first <- place("one", waits) }() + <-asking + + s.NoError(place("two", NamedCall{Scope: AppScope{Unpinned: true}})) + + close(asked) + s.NoError(<-first) +} + +// Named calls whose hold is not answered give up, and hold up no other placement meanwhile. +func (s *StoreSuite) TestNamedCallsNotAnsweredHoldUpNoOtherPlacement() { + on := NamedCall{Scope: AppScope{Unpinned: true}} + var holding atomic.Int64 + var wg sync.WaitGroup + began := time.Now() + for i := range 64 { + wg.Go(func() { + s.ErrorIs(s.store.CallLegs.Claim(s.ctx, "app", "agent", fmt.Sprintf("call-%d", i), on, func(ctx context.Context) error { + holding.Add(1) + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(20 * time.Second): + return nil + } + }), ErrCallUnchecked) + }) + } + s.Require().Eventually(func() bool { return holding.Load() >= 8 }, 5*time.Second, 5*time.Millisecond) + + at := time.Now() + s.Require().NoError(s.store.CallLegs.PlaceWithin(s.ctx, &CallLeg{Token: newID(), CustomerID: "other", OrganizationID: "org", CallType: "agent", + CallID: "unrelated", Vendor: "telnyx", Direction: Outbound, LocalNumber: "+15125550150", RemoteNumber: "+15125550151", PlacedAt: &at}, + CallsAtOnce{Limit: 9, Ringing: time.Hour})) + s.Less(time.Since(at), time.Second) + wg.Wait() + s.Less(time.Since(began), 10*time.Second) +} + +// Who is on a call is asked before the claim takes a place: one not answered holds none. +func (s *StoreSuite) TestACallWhoseHolderDoesNotAnswerTakesNoPlace() { + on := NamedCall{Scope: AppScope{Unpinned: true}, Holder: func(context.Context) (string, error) { return "", errors.New("redis is down") }} + legs := &CallLegs{store: s.store, claims: make(chan struct{})} + legs.claimsOnce.Do(func() {}) + + began := time.Now() + s.ErrorIs(legs.Claim(s.ctx, "app", "agent", "call", on, func(context.Context) error { return nil }), ErrCallUnchecked) + s.Less(time.Since(began), time.Second, "it waits for no place to be told so") +} From 83a9dea70cb9a85171bb216957d12965ed6bfe55 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 03:59:55 +0000 Subject: [PATCH 09/23] test(phone): a claim whose legs cannot be read --- acceleration/internal/store/call_leg_test.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/acceleration/internal/store/call_leg_test.go b/acceleration/internal/store/call_leg_test.go index e6cc581afc..3e69bc40c8 100644 --- a/acceleration/internal/store/call_leg_test.go +++ b/acceleration/internal/store/call_leg_test.go @@ -918,14 +918,18 @@ func (s *StoreSuite) TestACallIsLockedWhileItIsClaimed() { func (s *StoreSuite) TestACallWhoseLegsCannotBeReadIsNotClaimed() { ctx, cancel := context.WithCancel(s.ctx) defer cancel() - held := false + held, asked := false, 0 on := NamedCall{Scope: AppScope{Unpinned: true}, Holder: func(context.Context) (string, error) { - cancel() + // Asked again under the call's lock, just before its legs are read. + if asked++; asked == 2 { + cancel() + } return "", nil }} s.Error(s.store.CallLegs.Claim(ctx, "mine", "agent", "call", on, func(context.Context) error { held = true; return nil })) + s.Equal(2, asked) s.False(held) } From 44f8c62b4f9a5de925850b515fcb8ed00aec78e6 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 04:09:08 +0000 Subject: [PATCH 10/23] refactor(phone): one way to refuse a held call --- acceleration/internal/session/manager.go | 3 --- acceleration/internal/store/call_leg.go | 6 ++---- acceleration/internal/store/call_leg_test.go | 3 --- 3 files changed, 2 insertions(+), 10 deletions(-) diff --git a/acceleration/internal/session/manager.go b/acceleration/internal/session/manager.go index 5a3dd5b3f0..a2933437dc 100644 --- a/acceleration/internal/session/manager.go +++ b/acceleration/internal/session/manager.go @@ -2283,9 +2283,6 @@ func (m *Manager) claimCall(ctx context.Context, spec Spec, named bool) (func(), hold = func(ctx context.Context) error { said, err := directory.HoldCall(ctx, spec.CustomerID, app, spec.ID) release = sync.OnceFunc(func() { said(context.WithoutCancel(ctx)) }) - if errors.Is(err, node.ErrCallHeld) { - return store.ErrCallTaken - } return err } } diff --git a/acceleration/internal/store/call_leg.go b/acceleration/internal/store/call_leg.go index 52c2bea6c0..40aa4667a7 100644 --- a/acceleration/internal/store/call_leg.go +++ b/acceleration/internal/store/call_leg.go @@ -939,7 +939,7 @@ func (r *CallLegs) claiming(ctx context.Context, on NamedCall, customerID string } // Claim runs hold, which says a customer's session is on a named call, or refuses with -// ErrCallTaken when the call is another customer's, as hold itself may. Both are under the lock PlaceOn keeps a leg +// ErrCallTaken when the call is another customer's. Both are under the lock PlaceOn keeps a leg // under, so of a session and a call placed at once, or of two sessions, one sees the other. func (r *CallLegs) Claim(ctx context.Context, customerID, callType, callID string, on NamedCall, hold func(context.Context) error) error { release, err := r.claiming(ctx, on, customerID) @@ -957,9 +957,7 @@ func (r *CallLegs) Claim(ctx context.Context, customerID, callType, callID strin if err := on.claim(ctx, tx, dbs, customerID, callType, callID); err != nil { return err } - if err := hold(ctx); errors.Is(err, ErrCallTaken) { - return err - } else if err != nil { + if err := hold(ctx); err != nil { return errors.Join(ErrCallUnchecked, err) } return nil diff --git a/acceleration/internal/store/call_leg_test.go b/acceleration/internal/store/call_leg_test.go index 3e69bc40c8..c603e10de4 100644 --- a/acceleration/internal/store/call_leg_test.go +++ b/acceleration/internal/store/call_leg_test.go @@ -802,9 +802,6 @@ func (s *StoreSuite) TestACallARunningSessionHoldsIsItsCustomers() { failing = nil s.ErrorIs(s.store.CallLegs.Claim(s.ctx, "mine", "agent", "call", on, func(context.Context) error { return errors.New("redis is down") }), ErrCallUnchecked) - err := s.store.CallLegs.Claim(s.ctx, "mine", "agent", "call", on, func(context.Context) error { return ErrCallTaken }) - s.ErrorIs(err, ErrCallTaken) - s.NotErrorIs(err, ErrCallUnchecked, "it could be told, and is another's") } // Whoever claims first is let in and the other refused, however long the first takes to keep From e4a98299d14dfedc77c15ad75ef08ba6414c3d3c Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 04:27:06 +0000 Subject: [PATCH 11/23] test(phone): only the connection of the hold goes deaf --- acceleration/internal/api/phone_test.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/acceleration/internal/api/phone_test.go b/acceleration/internal/api/phone_test.go index 858cabd584..a6c7398a19 100644 --- a/acceleration/internal/api/phone_test.go +++ b/acceleration/internal/api/phone_test.go @@ -1644,7 +1644,7 @@ func (s *CallStatusSuite) TestASessionOfAMintedIdOrReopenedIsAskedNothing() { // deafRedis is the suite's Redis until deaf is set: from then on it takes what is sent it and // answers nothing, as a Redis cut off by the network does. // -// It goes deaf by itself on being sent any of deafTo. +// A connection it is sent any of deafTo on goes deaf by itself. func (s *CallStatusSuite) deafRedis(deaf *atomic.Bool, deafTo ...string) rueidis.Client { listener, err := net.Listen("tcp", "127.0.0.1:0") s.Require().NoError(err) @@ -1660,6 +1660,7 @@ func (s *CallStatusSuite) deafRedis(deaf *atomic.Bool, deafTo ...string) rueidis _ = conn.Close() continue } + var cut atomic.Bool go func() { defer upstream.Close() buffer := make([]byte, 64<<10) @@ -1670,7 +1671,7 @@ func (s *CallStatusSuite) deafRedis(deaf *atomic.Bool, deafTo ...string) rueidis } for _, word := range deafTo { if strings.Contains(string(buffer[:n]), word) { - deaf.Store(true) + cut.Store(true) } } if _, err := upstream.Write(buffer[:n]); err != nil { @@ -1685,7 +1686,7 @@ func (s *CallStatusSuite) deafRedis(deaf *atomic.Bool, deafTo ...string) rueidis if err != nil { return } - if deaf.Load() { + if deaf.Load() || cut.Load() { continue } if _, err := conn.Write(buffer[:n]); err != nil { From 8df99bc0a724d63485b0907a4b796255ab7dc538 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 07:09:26 +0000 Subject: [PATCH 12/23] test(phone): named call tests bound their waits and connections --- acceleration/internal/node/directory_test.go | 12 ++++++++++++ acceleration/internal/phone/outcome/keeper.go | 5 +++-- acceleration/internal/session/manager.go | 11 ++++++----- acceleration/internal/store/call_leg_test.go | 14 +++++++++++--- 4 files changed, 32 insertions(+), 10 deletions(-) diff --git a/acceleration/internal/node/directory_test.go b/acceleration/internal/node/directory_test.go index fdf89afd0a..11791a5db6 100644 --- a/acceleration/internal/node/directory_test.go +++ b/acceleration/internal/node/directory_test.go @@ -324,6 +324,18 @@ func (s *DirectorySuite) TestACallIsHeldUntilTheLastSessionOnItIsGone() { s.Empty(s.holder(7, "order-42")) } +// Two nodes' first holds of one customer's call are each their own. +func (s *DirectorySuite) TestACallTwoNodesHoldFirstIsHeldUntilBothAreGone() { + here, there := s.callOf(s.directoryAt("node-a:1"), "acme"), s.callOf(s.directoryAt("node-b:1"), "acme") + + there() + s.Equal("acme", s.holder(7, "order-42")) + _, err := s.directoryAt("node-c:1").HoldCall(s.ctx, "globex", 7, "order-42") + s.ErrorIs(err, ErrCallHeld) + here() + s.Empty(s.holder(7, "order-42")) +} + // A hold Redis did not take is said with the next renewal, until it is released. func (s *DirectorySuite) TestAHoldThatWasNotSaidIsSaidWithTheNextRenewal() { directory := s.directoryAt("node-a:1") diff --git a/acceleration/internal/phone/outcome/keeper.go b/acceleration/internal/phone/outcome/keeper.go index 837a86869a..bbf7bffff0 100644 --- a/acceleration/internal/phone/outcome/keeper.go +++ b/acceleration/internal/phone/outcome/keeper.go @@ -40,8 +40,9 @@ func (k *Keeper) Placed(ctx context.Context, call Call) (string, error) { } // PlacedWithin is Placed for a call whose leg counts among organization's calls, refused with -// store.ErrCallsAtOnce when atOnce, if set, leaves no room for it (store.CallLegs.PlaceWithin), and with store.ErrCallTaken when on, set for a call -// whose id somebody chose, finds it another customer's (store.CallLegs.PlaceOn). +// store.ErrCallsAtOnce when atOnce, if set, leaves no room for it (store.CallLegs.PlaceWithin), and +// with store.ErrCallTaken when on, set for a call whose id somebody chose, finds it another +// customer's (store.CallLegs.PlaceOn). func (k *Keeper) PlacedWithin(ctx context.Context, call Call, organization string, atOnce *store.CallsAtOnce, on *store.NamedCall) (string, error) { placed := k.now() row := store.CallLeg{ diff --git a/acceleration/internal/session/manager.go b/acceleration/internal/session/manager.go index a2933437dc..efa6332cd8 100644 --- a/acceleration/internal/session/manager.go +++ b/acceleration/internal/session/manager.go @@ -511,6 +511,7 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er if stream.Client == nil && m.options.Stream != nil && m.options.Stream.PerApp() { spec.StreamApp = store.ForeignStreamApp } + var remembering *metered.Memory if spec.Memory.UserID != "" { if m.options.Memory == nil { @@ -2258,11 +2259,11 @@ func (m *Manager) stream(ctx context.Context, spec Spec, newCall bool) (streamap } // claimCall says the session's customer is on the call it is named after, agent: in the -// Stream app it acts in, until the func it returns is called. Of a named session it is refused with ErrSessionExists -// when the call is another customer's, by its legs or by a session some node runs, and with -// store.ErrCallUnchecked when that cannot be told. An id the router made names nobody else's call, -// and a reopened session's is its own, so theirs is only said. A session of no Stream app has no -// call. +// Stream app it acts in, until the func it returns is called. Of a named session it is refused +// with ErrSessionExists when the call is another customer's, by its legs or by a session some node +// runs, and with store.ErrCallUnchecked when that cannot be told. An id the router made names +// nobody else's call, and a reopened session's is its own, so theirs is only said. A session of no +// Stream app has no call. func (m *Manager) claimCall(ctx context.Context, spec Spec, named bool) (func(), error) { if spec.StreamApp == store.ForeignStreamApp { return func() {}, nil diff --git a/acceleration/internal/store/call_leg_test.go b/acceleration/internal/store/call_leg_test.go index c603e10de4..7646a6b8f8 100644 --- a/acceleration/internal/store/call_leg_test.go +++ b/acceleration/internal/store/call_leg_test.go @@ -971,7 +971,11 @@ func (s *StoreSuite) TestNamedCallsOfNoOrganizationArePlacedBesideEachOther() { } first := make(chan error, 1) go func() { first <- place("one", waits) }() - <-asking + select { + case <-asking: + case <-time.After(10 * time.Second): + s.FailNow("nobody was asked who is on the first call") + } s.NoError(place("two", NamedCall{Scope: AppScope{Unpinned: true}})) @@ -981,13 +985,17 @@ func (s *StoreSuite) TestNamedCallsOfNoOrganizationArePlacedBesideEachOther() { // Named calls whose hold is not answered give up, and hold up no other placement meanwhile. func (s *StoreSuite) TestNamedCallsNotAnsweredHoldUpNoOtherPlacement() { + // A router of its own, closed here: the connections it opens are not the suite's to keep. + router, err := s.openRouter() + s.Require().NoError(err) + defer func() { s.NoError(router.Close()) }() on := NamedCall{Scope: AppScope{Unpinned: true}} var holding atomic.Int64 var wg sync.WaitGroup began := time.Now() for i := range 64 { wg.Go(func() { - s.ErrorIs(s.store.CallLegs.Claim(s.ctx, "app", "agent", fmt.Sprintf("call-%d", i), on, func(ctx context.Context) error { + s.ErrorIs(router.CallLegs.Claim(s.ctx, "app", "agent", fmt.Sprintf("call-%d", i), on, func(ctx context.Context) error { holding.Add(1) select { case <-ctx.Done(): @@ -1001,7 +1009,7 @@ func (s *StoreSuite) TestNamedCallsNotAnsweredHoldUpNoOtherPlacement() { s.Require().Eventually(func() bool { return holding.Load() >= 8 }, 5*time.Second, 5*time.Millisecond) at := time.Now() - s.Require().NoError(s.store.CallLegs.PlaceWithin(s.ctx, &CallLeg{Token: newID(), CustomerID: "other", OrganizationID: "org", CallType: "agent", + s.Require().NoError(router.CallLegs.PlaceWithin(s.ctx, &CallLeg{Token: newID(), CustomerID: "other", OrganizationID: "org", CallType: "agent", CallID: "unrelated", Vendor: "telnyx", Direction: Outbound, LocalNumber: "+15125550150", RemoteNumber: "+15125550151", PlacedAt: &at}, CallsAtOnce{Limit: 9, Ringing: time.Hour})) s.Less(time.Since(at), time.Second) From 77d97675a7ce9e5cb8622a86ea26ac62ed828a09 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 07:47:43 +0000 Subject: [PATCH 13/23] test(phone): tests of claims made at once close their connections --- acceleration/internal/store/call_leg_test.go | 37 +++++++++++++------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/acceleration/internal/store/call_leg_test.go b/acceleration/internal/store/call_leg_test.go index 7646a6b8f8..cc4b1cac18 100644 --- a/acceleration/internal/store/call_leg_test.go +++ b/acceleration/internal/store/call_leg_test.go @@ -702,10 +702,23 @@ func (s *StoreSuite) claims(customer, callID string, on NamedCall) error { return s.store.CallLegs.Claim(s.ctx, customer, "agent", callID, on, func(context.Context) error { return nil }) } +// ownRouter is a router of the test's own, closed with it, so that the connections a test makes many +// of at once are not kept by the suite's. +func (s *StoreSuite) ownRouter() *Store { + router, err := s.openRouter() + s.Require().NoError(err) + s.T().Cleanup(func() { s.NoError(router.Close()) }) + return router +} + // places keeps a leg of a call a customer is about to dial, unless it is another's. func (s *StoreSuite) places(customer, callID string, on NamedCall, atOnce *CallsAtOnce) error { + return s.placesWith(s.store, customer, callID, on, atOnce) +} + +func (s *StoreSuite) placesWith(router *Store, customer, callID string, on NamedCall, atOnce *CallsAtOnce) error { placed := time.Now() - return s.store.CallLegs.PlaceOn(s.ctx, &CallLeg{Token: newID(), CustomerID: customer, OrganizationID: "org", CallType: "agent", CallID: callID, + return router.CallLegs.PlaceOn(s.ctx, &CallLeg{Token: newID(), CustomerID: customer, OrganizationID: "org", CallType: "agent", CallID: callID, Vendor: "telnyx", Direction: Outbound, LocalNumber: "+15125550150", RemoteNumber: "+15125550151", PlacedAt: &placed}, on, atOnce) } @@ -807,6 +820,7 @@ func (s *StoreSuite) TestACallARunningSessionHoldsIsItsCustomers() { // Whoever claims first is let in and the other refused, however long the first takes to keep // what it claimed with. func (s *StoreSuite) TestOfTwoCustomersClaimingACallAtOnceOneIsLetIn() { + router := s.ownRouter() on := NamedCall{Scope: AppScope{Unpinned: true}} for i := range 10 { call := fmt.Sprintf("call-%d", i) @@ -827,9 +841,9 @@ func (s *StoreSuite) TestOfTwoCustomersClaimingACallAtOnceOneIsLetIn() { } errs := make([]error, 3) var wg sync.WaitGroup - wg.Go(func() { errs[0] = s.store.CallLegs.Claim(s.ctx, "a", "agent", call, holding, hold("a")) }) - wg.Go(func() { errs[1] = s.store.CallLegs.Claim(s.ctx, "b", "agent", call, holding, hold("b")) }) - wg.Go(func() { errs[2] = s.places("c", call, holding, nil) }) + wg.Go(func() { errs[0] = router.CallLegs.Claim(s.ctx, "a", "agent", call, holding, hold("a")) }) + wg.Go(func() { errs[1] = router.CallLegs.Claim(s.ctx, "b", "agent", call, holding, hold("b")) }) + wg.Go(func() { errs[2] = s.placesWith(router, "c", call, holding, nil) }) wg.Wait() in := 0 @@ -895,14 +909,13 @@ func (s *ShardedStoreSuite) TestACallsOwnerIsTheSameOnEveryShard() { // A call is locked while it is claimed, in the deployment's app whether a claim knows its id or // not, and another app's call of the name is not. func (s *StoreSuite) TestACallIsLockedWhileItIsClaimed() { - // Another router's, with turns of its own. - elsewhere := &CallLegs{store: s.store} + one, elsewhere := s.ownRouter(), s.ownRouter() blocked := func(on NamedCall) (err error) { unpinned := NamedCall{Scope: AppScope{Unpinned: true}} - s.Require().NoError(s.store.CallLegs.Claim(s.ctx, "a", "agent", "call", unpinned, func(context.Context) error { + s.Require().NoError(one.CallLegs.Claim(s.ctx, "a", "agent", "call", unpinned, func(context.Context) error { ctx, cancel := context.WithTimeout(s.ctx, 300*time.Millisecond) defer cancel() - err = elsewhere.Claim(ctx, "b", "agent", "call", on, func(context.Context) error { return nil }) + err = elsewhere.CallLegs.Claim(ctx, "b", "agent", "call", on, func(context.Context) error { return nil }) return nil })) return err @@ -954,6 +967,7 @@ func (s *StoreSuite) TestACallIsNotTheCustomersWhoPlacedALegAndDialledItLater() // Named calls of no organization wait for no turn of each other's. func (s *StoreSuite) TestNamedCallsOfNoOrganizationArePlacedBesideEachOther() { + router := s.ownRouter() asking, asked := make(chan struct{}), make(chan struct{}) var once sync.Once waits := NamedCall{Scope: AppScope{Unpinned: true}, Holder: func(ctx context.Context) (string, error) { @@ -966,7 +980,7 @@ func (s *StoreSuite) TestNamedCallsOfNoOrganizationArePlacedBesideEachOther() { }} place := func(call string, on NamedCall) error { placed := time.Now() - return s.store.CallLegs.PlaceOn(s.ctx, &CallLeg{Token: newID(), CustomerID: "app", CallType: "agent", CallID: call, Vendor: "telnyx", + return router.CallLegs.PlaceOn(s.ctx, &CallLeg{Token: newID(), CustomerID: "app", CallType: "agent", CallID: call, Vendor: "telnyx", Direction: Outbound, LocalNumber: "+15125550150", RemoteNumber: "+15125550151", PlacedAt: &placed}, on, nil) } first := make(chan error, 1) @@ -985,10 +999,7 @@ func (s *StoreSuite) TestNamedCallsOfNoOrganizationArePlacedBesideEachOther() { // Named calls whose hold is not answered give up, and hold up no other placement meanwhile. func (s *StoreSuite) TestNamedCallsNotAnsweredHoldUpNoOtherPlacement() { - // A router of its own, closed here: the connections it opens are not the suite's to keep. - router, err := s.openRouter() - s.Require().NoError(err) - defer func() { s.NoError(router.Close()) }() + router := s.ownRouter() on := NamedCall{Scope: AppScope{Unpinned: true}} var holding atomic.Int64 var wg sync.WaitGroup From e6d272bc34cb384b59b9bf7b270ac0cbb02f0c3a Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 16:43:48 +0000 Subject: [PATCH 14/23] fix(phone): a wait on the directory ends in its own time, and what refuses a call is logged --- acceleration/internal/api/phone.go | 1 + acceleration/internal/api/phone_test.go | 23 ++++- acceleration/internal/node/directory.go | 58 ++++++++++-- acceleration/internal/node/directory_test.go | 96 ++++++++++++++++++++ acceleration/internal/session/manager.go | 18 +++- acceleration/internal/store/call_leg_test.go | 46 ++++++++++ 6 files changed, 231 insertions(+), 11 deletions(-) diff --git a/acceleration/internal/api/phone.go b/acceleration/internal/api/phone.go index bc4c2461ff..97929f1379 100644 --- a/acceleration/internal/api/phone.go +++ b/acceleration/internal/api/phone.go @@ -442,6 +442,7 @@ func (s *Server) placePhoneCall(ctx context.Context, request *placePhoneCallRequ return nil, errSessionTaken } if errors.Is(err, store.ErrCallUnchecked) { + s.logger.Warn("refused a phone call: could not tell whose its call is", "session", call.SessionID, "customer", customerID, "error", err) return nil, errCallUnchecked } if errors.Is(err, dlc.ErrRefused) || errors.Is(err, phone.ErrDestinationRefused) { diff --git a/acceleration/internal/api/phone_test.go b/acceleration/internal/api/phone_test.go index a6c7398a19..4c240e762d 100644 --- a/acceleration/internal/api/phone_test.go +++ b/acceleration/internal/api/phone_test.go @@ -1718,6 +1718,7 @@ func (s *CallStatusSuite) TestADirectoryThatDoesNotAnswerHoldsUpNoSession() { began := time.Now() err = heldOn(sessions, s.customerID(), s.utils.uuid()) s.ErrorIs(err, store.ErrCallUnchecked) + s.Contains(s.logged.String(), "refused a session: could not tell whose its call is") s.Less(time.Since(began), 2900*time.Millisecond, "asked for a second, not for as long as the claim has") var answer APIError s.Require().ErrorAs(refusedRequest(err), &answer) @@ -1743,11 +1744,12 @@ func (s *CallStatusSuite) TestADirectoryThatDoesNotAnswerHoldsUpNoSession() { s.Less(time.Since(began), 2900*time.Millisecond) s.Equal(http.StatusServiceUnavailable, status, payload) s.Contains(payload, "could not tell whose call") + s.Contains(s.logged.String(), "refused a phone call: could not tell whose its call is") } // sessionsWith is a node's sessions, said to be there by directory. func (s *CallStatusSuite) sessionsWith(directory *node.Directory) *session.Manager { - logger := slog.New(slog.DiscardHandler) + logger := slog.New(slog.NewTextHandler(s.logged, nil)) sessions, err := session.NewManager(session.ManagerOptions{ LLM: s.streams.LLM, Conversations: s.conversations, Stream: s.stream, Store: s.store, Directory: directory, Logger: logger, Writer: s.routerWriter(s.store, s.live, nil, logger), @@ -1798,3 +1800,22 @@ func (s *CallStatusSuite) TestASessionRefusedAfterItHeldItsCallLeavesIt() { s.NoError(heldOn(s.manager, s.customerID(), id)) } + +// Sessions closed as the router stops do not each wait for a directory that does not answer. +func (s *CallStatusSuite) TestARouterStopsThoughTheDirectoryDoesNotAnswer() { + s.useApp(s.data.createApp()) + var deaf atomic.Bool + directory, err := node.NewDirectory(node.DirectoryOptions{Redis: s.deafRedis(&deaf), Address: "node-deaf:4", Prefix: s.relayPrefix}) + s.Require().NoError(err) + s.T().Cleanup(directory.Close) + sessions := s.sessionsWith(directory) + for range 5 { + s.Require().NoError(heldOn(sessions, s.customerID(), s.utils.uuid())) + } + deaf.Store(true) + + began := time.Now() + s.NoError(sessions.Shutdown()) + + s.Less(time.Since(began), 2900*time.Millisecond) +} diff --git a/acceleration/internal/node/directory.go b/acceleration/internal/node/directory.go index 636b07b97c..1a995506ec 100644 --- a/acceleration/internal/node/directory.go +++ b/acceleration/internal/node/directory.go @@ -241,13 +241,39 @@ func (d *Directory) Hold(ctx context.Context, customerID string, app int64, sess ctx, cancel := context.WithTimeout(ctx, callTimeout) defer cancel() - d.write(ctx, key, held) + _, err := inTime(ctx, func() (struct{}, error) { return struct{}{}, d.write(ctx, key, held) }) + if err != nil { + d.logger.Warn("could not say this node is running a session", + "customer", customerID, "session", sessionID, "error", err) + } } // callTimeout bounds saying a session is here, and asking or saying whose its call is: a session // waits for each to open. const callTimeout = time.Second +// inTime is what do answers, or ctx's error once that ends. A client redialling Redis has every +// caller on the connection wait for the dial of the one that began it, whatever their own context +// says: do is left to wait on its own, and that dial ends it. +func inTime[T any](ctx context.Context, do func() (T, error)) (T, error) { + type answer struct { + answered T + err error + } + answers := make(chan answer, 1) + go func() { + answered, err := do() + answers <- answer{answered, err} + }() + select { + case got := <-answers: + return got.answered, got.err + case <-ctx.Done(): + var none T + return none, ctx.Err() + } +} + // A call is a hash, a field for each session on it, which says when it lapses, since a hash cannot // expire its fields one at a time, then its customer. liveCall walks the fields, passes over those // that lapsed and runs what it is given for the customer of each other. @@ -290,7 +316,7 @@ func (d *Directory) HoldCall(ctx context.Context, customerID string, app int64, d.mu.Unlock() ctx, cancel := context.WithTimeout(ctx, callTimeout) defer cancel() - held, err := d.redis.Do(ctx, d.holdCall(call)).AsInt64() + held, err := inTime(ctx, func() (int64, error) { return d.redis.Do(ctx, d.holdCall(call)).AsInt64() }) if err == nil && held == 0 { d.mu.Lock() delete(d.onCalls, call) @@ -307,7 +333,10 @@ func (d *Directory) releaseCall(ctx context.Context, call heldCall) { d.mu.Unlock() ctx, cancel := context.WithTimeout(ctx, callTimeout) defer cancel() - if err := d.redis.Do(ctx, d.redis.B().Hdel().Key(call.key).Field(call.field).Build()).Error(); err != nil { + _, err := inTime(ctx, func() (int64, error) { + return d.redis.Do(ctx, d.redis.B().Hdel().Key(call.key).Field(call.field).Build()).AsInt64() + }) + if err != nil { d.logger.Warn("could not take back a session's hold on a call", "customer", call.customerID, "call", call.key, "error", err) } } @@ -317,7 +346,9 @@ func (d *Directory) releaseCall(ctx context.Context, call heldCall) { func (d *Directory) CallHolder(ctx context.Context, app int64, id string) (string, error) { ctx, cancel := context.WithTimeout(ctx, callTimeout) defer cancel() - return d.redis.Do(ctx, d.redis.B().Eval().Script(callHolderScript).Numkeys(1).Key(d.callKey(app, id)).Build()).ToString() + return inTime(ctx, func() (string, error) { + return d.redis.Do(ctx, d.redis.B().Eval().Script(callHolderScript).Numkeys(1).Key(d.callKey(app, id)).Build()).ToString() + }) } // callKey is where a call is held: node:call::. @@ -605,14 +636,13 @@ func (d *Directory) answeringKey(customerID, conversationID string) string { } // write says this node holds a session, for holdFor. -func (d *Directory) write(ctx context.Context, key heldSession, held claim) { +func (d *Directory) write(ctx context.Context, key heldSession, held claim) error { for _, result := range d.redis.DoMulti(ctx, d.writeCommands(key, held)...) { if err := result.Error(); err != nil { - d.logger.Warn("could not say this node is running a session", - "customer", key.customerID, "session", key.sessionID, "error", err) - return + return err } } + return nil } // writeCommands hold the session, its agent and its conversation under its customer, and under @@ -737,7 +767,9 @@ func (d *Directory) renewAll(ctx context.Context) { for key, claimed := range held { commands = append(commands, d.writeCommands(key, claimed)...) } + renewed := map[int]heldCall{} for call := range onCalls { + renewed[len(commands)] = call commands = append(commands, d.holdCall(call)) } for customerID := range waiting { @@ -754,10 +786,18 @@ func (d *Directory) renewAll(ctx context.Context) { if len(commands) == 0 { return } - for _, result := range d.redis.DoMulti(ctx, commands...) { + for i, result := range d.redis.DoMulti(ctx, commands...) { if err := result.Error(); err != nil { d.logger.Warn("could not renew what this node holds", "error", err) return } + call, ok := renewed[i] + if !ok { + continue + } + if held, err := result.AsInt64(); err == nil && held == 0 { + d.logger.Warn("the call of a session here is another customer's: its hold is not renewed", + "customer", call.customerID, "call", call.key) + } } } diff --git a/acceleration/internal/node/directory_test.go b/acceleration/internal/node/directory_test.go index 6a2ddd1777..6805157a2c 100644 --- a/acceleration/internal/node/directory_test.go +++ b/acceleration/internal/node/directory_test.go @@ -5,7 +5,9 @@ package node import ( "bytes" "context" + "io" "log/slog" + "net" "os" "slices" "strconv" @@ -384,6 +386,100 @@ func (s *DirectorySuite) TestACallAnotherCustomerHoldsStaysItsOwn() { s.Equal("globex", s.holder(7, "order-42")) } +// A renewal another customer's hold refuses is said, and no other is. +func (s *DirectorySuite) TestARenewalAnotherCustomersHoldRefusesIsLogged() { + var logged bytes.Buffer + directory, err := NewDirectory(DirectoryOptions{ + Redis: s.client, Address: "node-a:1", Prefix: s.prefix, + Logger: slog.New(slog.NewTextHandler(&logged, nil)), + }) + s.Require().NoError(err) + directory.Close() + s.callOf(directory, "acme") + _, err = directory.HoldCall(s.ctx, "acme", 7, "order-43") + s.Require().NoError(err) + directory.renewAll(s.ctx) + s.Empty(logged.String()) + s.lapsed() + s.callOf(s.directoryAt("node-b:1"), "globex") + + directory.renewAll(s.ctx) + + s.Equal(1, strings.Count(logged.String(), "its hold is not renewed")) + s.Contains(logged.String(), "level=WARN") + s.Contains(logged.String(), "customer=acme") + s.Contains(logged.String(), s.prefix+":call:7:order-42") +} + +// A client redialling a Redis that does not answer keeps every caller on the connection waiting +// for the dial of another: one with less time is answered in its own all the same. +func (s *DirectorySuite) TestACallerIsAnsweredInTimeBesideAnothersRedial() { + listener, err := net.Listen("tcp", "127.0.0.1:0") + s.Require().NoError(err) + defer listener.Close() + dialled := make(chan struct{}, 8) + var hung atomic.Bool + go func() { + for { + conn, err := listener.Accept() + if err != nil { + return + } + if hung.Load() { + dialled <- struct{}{} + defer conn.Close() + continue + } + upstream, err := net.Dial("tcp", os.Getenv("ROUTER_REDIS_ADDR")) + if err != nil { + _ = conn.Close() + return + } + go func() { _, _ = io.Copy(upstream, conn); _ = upstream.Close() }() + go func() { _, _ = io.Copy(conn, upstream) }() + s.T().Cleanup(func() { _ = conn.Close() }) + go func() { + for !hung.Load() { + time.Sleep(5 * time.Millisecond) + } + _ = conn.Close() + }() + } + }() + client, err := rueidis.NewClient(rueidis.ClientOption{InitAddress: []string{listener.Addr().String()}, DisableCache: true, ForceSingleClient: true}) + s.Require().NoError(err) + s.T().Cleanup(client.Close) + directory, err := NewDirectory(DirectoryOptions{Redis: client, Address: "node-a:1", Prefix: s.prefix}) + s.Require().NoError(err) + directory.Close() + hung.Store(true) + redialling, stop := context.WithTimeout(s.ctx, 20*time.Second) + defer stop() + go func() { + for redialling.Err() == nil { + _, _ = directory.Node(redialling, "acme", "order-42") + } + }() + select { + case <-dialled: + case <-time.After(10 * time.Second): + s.FailNow("nobody redialled") + } + + for what, call := range map[string]func(){ + "asking": func() { _, _ = directory.CallHolder(s.ctx, 7, "order-42") }, + "holding": func() { _, _ = directory.HoldCall(s.ctx, "acme", 7, "order-42") }, + "letting go": func() { + directory.releaseCall(s.ctx, heldCall{"acme", directory.callKey(7, "order-42"), "field"}) + }, + "saying": func() { directory.Hold(s.ctx, "acme", 7, "order-42", "", "") }, + } { + began := time.Now() + call() + s.Less(time.Since(began), 1500*time.Millisecond, what) + } +} + // A customer's sessions on one call, here and on another node, each hold it until the last is gone. func (s *DirectorySuite) TestACallIsHeldUntilTheLastSessionOnItIsGone() { first, second := s.directoryAt("node-a:1"), s.directoryAt("node-b:1") diff --git a/acceleration/internal/session/manager.go b/acceleration/internal/session/manager.go index 27373d3760..27dc1be7a1 100644 --- a/acceleration/internal/session/manager.go +++ b/acceleration/internal/session/manager.go @@ -14,6 +14,7 @@ import ( "sort" "strings" "sync" + "sync/atomic" "time" "github.com/google/uuid" @@ -23,6 +24,7 @@ import ( "github.com/GetStream/Vision-Agents/acceleration/internal/auth" persistent "github.com/GetStream/Vision-Agents/acceleration/internal/conversation" "github.com/GetStream/Vision-Agents/acceleration/internal/decisionrouter" + "github.com/GetStream/Vision-Agents/acceleration/internal/goroutine" "github.com/GetStream/Vision-Agents/acceleration/internal/guardrail" "github.com/GetStream/Vision-Agents/acceleration/internal/harness" "github.com/GetStream/Vision-Agents/acceleration/internal/imagejobs" @@ -233,6 +235,8 @@ type Manager struct { // makes or changes a task (SetSchedulerKick); nil where no worker runs. kickScheduler func() closed bool + // stopping is set as Shutdown starts. + stopping atomic.Bool // closing counts the sessions taken off the map whose Close has not returned. They are // still writing how they ended, so a draining router waits on them and Shutdown keeps // the recorders open for them (ended). @@ -713,7 +717,15 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er }() created := m.newSession(ctx, spec, conv, skills, opening, runtime) created.loading = loading - created.closers = append(created.closers, releaseCall) + created.closers = append(created.closers, func() { + // Sessions are closed one after another as the router stops, and a Redis that does not + // answer would have each wait. A hold not taken back lapses. + if m.stopping.Load() { + goroutine.Go(context.WithoutCancel(ctx), releaseCall) + return + } + releaseCall() + }) // A session held ends where it closes (Session.counted); one never held ends here, // unless it was turned away for a router shutting down or for a session already held // under its id (a redelivered hook): neither is a session that failed. @@ -2117,6 +2129,7 @@ func forgetting(ctx context.Context, customerID string) routing.Owner { // Shutdown ends every session, which is what a router does on its way down rather than // dropping calls by exiting. func (m *Manager) Shutdown() error { + m.stopping.Store(true) m.mu.Lock() m.closed = true running := make([]*Session, 0, len(m.sessions)) @@ -2341,6 +2354,9 @@ func (m *Manager) claimCall(ctx context.Context, spec Spec, named bool) (func(), return release, nil } release() + if errors.Is(err, store.ErrCallUnchecked) { + m.logger.Warn("refused a session: could not tell whose its call is", "session", spec.ID, "customer", spec.CustomerID, "error", err) + } if errors.Is(err, store.ErrCallTaken) { err = stack.Wrap(ErrSessionExists) } diff --git a/acceleration/internal/store/call_leg_test.go b/acceleration/internal/store/call_leg_test.go index cc4b1cac18..58a587f452 100644 --- a/acceleration/internal/store/call_leg_test.go +++ b/acceleration/internal/store/call_leg_test.go @@ -1038,3 +1038,49 @@ func (s *StoreSuite) TestACallWhoseHolderDoesNotAnswerTakesNoPlace() { s.ErrorIs(legs.Claim(s.ctx, "app", "agent", "call", on, func(context.Context) error { return nil }), ErrCallUnchecked) s.Less(time.Since(began), time.Second, "it waits for no place to be told so") } + +// A named call waiting on its call's lock holds no lock of its organization's: another placement +// of the organization goes ahead meanwhile. +func (s *StoreSuite) TestANamedCallWaitingOnItsCallHoldsUpNoOtherPlacementOfItsOrganization() { + router := s.ownRouter() + unpinned := NamedCall{Scope: AppScope{Unpinned: true}} + leg := func(call string) *CallLeg { + at := time.Now() + return &CallLeg{Token: newID(), CustomerID: "app", OrganizationID: "org", CallType: "agent", CallID: call, Vendor: "telnyx", + Direction: Outbound, LocalNumber: "+15125550150", RemoteNumber: "+15125550151", PlacedAt: &at} + } + atOnce := CallsAtOnce{Limit: 9, Ringing: time.Hour} + claimed, release := make(chan struct{}), make(chan struct{}) + held := make(chan error, 1) + go func() { + held <- router.CallLegs.Claim(s.ctx, "app", "agent", "call", unpinned, func(ctx context.Context) error { + close(claimed) + select { + case <-release: + case <-ctx.Done(): + } + return nil + }) + }() + select { + case <-claimed: + case <-time.After(10 * time.Second): + s.FailNow("the call was never claimed") + } + waiting := make(chan error, 1) + go func() { waiting <- router.CallLegs.PlaceOn(s.ctx, leg("call"), unpinned, &atOnce) }() + s.Require().Eventually(func() bool { + var blocked int + err := s.store.global.QueryRowContext(s.ctx, "SELECT count(*) FROM pg_locks WHERE locktype = 'advisory' AND NOT granted "+ + "AND database = (SELECT oid FROM pg_database WHERE datname = current_database())").Scan(&blocked) + return err == nil && blocked > 0 + }, 5*time.Second, 10*time.Millisecond) + + began := time.Now() + s.Require().NoError(s.store.CallLegs.PlaceWithin(s.ctx, leg("other"), atOnce)) + s.Less(time.Since(began), time.Second) + + close(release) + s.NoError(<-held) + s.NoError(<-waiting) +} From 39ad9fb398b9f6e0a068f4d17b3478127c371baf Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 17:03:15 +0000 Subject: [PATCH 15/23] test(phone): the redial test reaches every connection --- acceleration/internal/api/phone.go | 1 - acceleration/internal/node/directory_test.go | 39 +++++++++++++++++--- acceleration/internal/phone/service.go | 3 ++ 3 files changed, 37 insertions(+), 6 deletions(-) diff --git a/acceleration/internal/api/phone.go b/acceleration/internal/api/phone.go index 97929f1379..bc4c2461ff 100644 --- a/acceleration/internal/api/phone.go +++ b/acceleration/internal/api/phone.go @@ -442,7 +442,6 @@ func (s *Server) placePhoneCall(ctx context.Context, request *placePhoneCallRequ return nil, errSessionTaken } if errors.Is(err, store.ErrCallUnchecked) { - s.logger.Warn("refused a phone call: could not tell whose its call is", "session", call.SessionID, "customer", customerID, "error", err) return nil, errCallUnchecked } if errors.Is(err, dlc.ErrRefused) || errors.Is(err, phone.ErrDestinationRefused) { diff --git a/acceleration/internal/node/directory_test.go b/acceleration/internal/node/directory_test.go index 6805157a2c..842c3ad02e 100644 --- a/acceleration/internal/node/directory_test.go +++ b/acceleration/internal/node/directory_test.go @@ -5,6 +5,7 @@ package node import ( "bytes" "context" + "fmt" "io" "log/slog" "net" @@ -411,6 +412,23 @@ func (s *DirectorySuite) TestARenewalAnotherCustomersHoldRefusesIsLogged() { s.Contains(logged.String(), s.prefix+":call:7:order-42") } +// A session Redis could not be told of is logged. +func (s *DirectorySuite) TestASessionThatCannotBeSaidIsLogged() { + var logged bytes.Buffer + client, err := redisready.NewClient(rueidis.ClientOption{InitAddress: []string{os.Getenv("ROUTER_REDIS_ADDR")}, DisableCache: true}) + s.Require().NoError(err) + directory, err := NewDirectory(DirectoryOptions{ + Redis: client, Address: "node-a:1", Prefix: s.prefix, Logger: slog.New(slog.NewTextHandler(&logged, nil)), + }) + s.Require().NoError(err) + directory.Close() + client.Close() + + directory.Hold(s.ctx, "acme", 7, "order-42", "", "") + + s.Equal(1, strings.Count(logged.String(), "could not say this node is running a session")) +} + // A client redialling a Redis that does not answer keeps every caller on the connection waiting // for the dial of another: one with less time is answered in its own all the same. func (s *DirectorySuite) TestACallerIsAnsweredInTimeBesideAnothersRedial() { @@ -455,16 +473,27 @@ func (s *DirectorySuite) TestACallerIsAnsweredInTimeBesideAnothersRedial() { hung.Store(true) redialling, stop := context.WithTimeout(s.ctx, 20*time.Second) defer stop() - go func() { - for redialling.Err() == nil { - _, _ = directory.Node(redialling, "acme", "order-42") - } - }() + // The client has several connections, and a key is always asked of the same one: these are + // enough keys for every connection to be redialled. + for i := range 32 { + go func() { + for redialling.Err() == nil { + _, _ = directory.Node(redialling, "acme", fmt.Sprintf("order-%d", i)) + } + }() + } select { case <-dialled: case <-time.After(10 * time.Second): s.FailNow("nobody redialled") } + for more := true; more; { + select { + case <-dialled: + case <-time.After(300 * time.Millisecond): + more = false + } + } for what, call := range map[string]func(){ "asking": func() { _, _ = directory.CallHolder(s.ctx, 7, "order-42") }, diff --git a/acceleration/internal/phone/service.go b/acceleration/internal/phone/service.go index 496e1d7aee..371da0cae4 100644 --- a/acceleration/internal/phone/service.go +++ b/acceleration/internal/phone/service.go @@ -1396,6 +1396,9 @@ func (s *Service) call(ctx context.Context, request CallRequest, sent *bool) (Pl if errors.Is(err, store.ErrCallsAtOnce) { return Placed{}, room.Refusal(err) } + if errors.Is(err, store.ErrCallUnchecked) { + s.logger.Warn("refused a phone call: could not tell whose its call is", "session", sessionID, "customer", request.Owner.CustomerID, "error", err) + } if errors.Is(err, store.ErrCallTaken) || errors.Is(err, store.ErrCallUnchecked) { return Placed{}, err } From c91e64c0cb3168224d337a47948d61a1850cddd3 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 18:14:37 +0000 Subject: [PATCH 16/23] test(phone): a slow Redis is waited for, and a router that stops leaves its calls --- acceleration/internal/api/phone_test.go | 16 +++++ acceleration/internal/node/directory.go | 22 +++---- acceleration/internal/node/directory_test.go | 62 ++++++++++++++++++++ acceleration/internal/node/intime_test.go | 27 +++++++++ 4 files changed, 117 insertions(+), 10 deletions(-) create mode 100644 acceleration/internal/node/intime_test.go diff --git a/acceleration/internal/api/phone_test.go b/acceleration/internal/api/phone_test.go index 4c240e762d..9055293bae 100644 --- a/acceleration/internal/api/phone_test.go +++ b/acceleration/internal/api/phone_test.go @@ -1819,3 +1819,19 @@ func (s *CallStatusSuite) TestARouterStopsThoughTheDirectoryDoesNotAnswer() { s.Less(time.Since(began), 2900*time.Millisecond) } + +// A router that stops takes back what its sessions said of their calls. +func (s *CallStatusSuite) TestACallIsLeftWhenItsRouterStops() { + s.useApp(s.data.createApp()) + var deaf atomic.Bool + directory, err := node.NewDirectory(node.DirectoryOptions{Redis: s.deafRedis(&deaf), Address: "node-stops:1", Prefix: s.relayPrefix}) + s.Require().NoError(err) + s.T().Cleanup(directory.Close) + sessions, other, id := s.sessionsWith(directory), s.sessionsWith(directory), s.utils.uuid() + s.Require().NoError(heldOn(sessions, "customer-"+s.utils.uuid(), id)) + s.Require().ErrorIs(heldOn(other, "customer-"+s.utils.uuid(), id), session.ErrSessionExists) + + s.Require().NoError(sessions.Shutdown()) + + s.Eventually(func() bool { return heldOn(other, "customer-"+s.utils.uuid(), id) == nil }, 5*time.Second, 50*time.Millisecond) +} diff --git a/acceleration/internal/node/directory.go b/acceleration/internal/node/directory.go index 1a995506ec..fa894b5ced 100644 --- a/acceleration/internal/node/directory.go +++ b/acceleration/internal/node/directory.go @@ -27,6 +27,8 @@ import ( "time" "github.com/redis/rueidis" + + "github.com/GetStream/Vision-Agents/acceleration/internal/goroutine" ) // holdFor is how long a node's claim on a session lasts unrenewed. A node that crashes @@ -241,7 +243,7 @@ func (d *Directory) Hold(ctx context.Context, customerID string, app int64, sess ctx, cancel := context.WithTimeout(ctx, callTimeout) defer cancel() - _, err := inTime(ctx, func() (struct{}, error) { return struct{}{}, d.write(ctx, key, held) }) + _, err := InTime(ctx, func() (struct{}, error) { return struct{}{}, d.write(ctx, key, held) }) if err != nil { d.logger.Warn("could not say this node is running a session", "customer", customerID, "session", sessionID, "error", err) @@ -252,19 +254,19 @@ func (d *Directory) Hold(ctx context.Context, customerID string, app int64, sess // waits for each to open. const callTimeout = time.Second -// inTime is what do answers, or ctx's error once that ends. A client redialling Redis has every +// InTime is what do answers, or ctx's error once that ends. A client redialling Redis has every // caller on the connection wait for the dial of the one that began it, whatever their own context // says: do is left to wait on its own, and that dial ends it. -func inTime[T any](ctx context.Context, do func() (T, error)) (T, error) { +func InTime[T any](ctx context.Context, do func() (T, error)) (T, error) { type answer struct { answered T err error } answers := make(chan answer, 1) - go func() { + goroutine.Go(ctx, func() { answered, err := do() answers <- answer{answered, err} - }() + }) select { case got := <-answers: return got.answered, got.err @@ -275,7 +277,7 @@ func inTime[T any](ctx context.Context, do func() (T, error)) (T, error) { } // A call is a hash, a field for each session on it, which says when it lapses, since a hash cannot -// expire its fields one at a time, then its customer. liveCall walks the fields, passes over those +// expire its fields one at a time, then its customer. liveCall walks the fields, drops those // that lapsed and runs what it is given for the customer of each other. const liveCall = ` local time = redis.call('TIME') @@ -286,7 +288,7 @@ for i = 1, #fields, 2 do local customer = string.sub(fields[i + 1], space + 1) if tonumber(string.sub(fields[i + 1], 1, space - 1)) > now then %s - end + else redis.call('HDEL', KEYS[1], fields[i]) end end ` @@ -316,7 +318,7 @@ func (d *Directory) HoldCall(ctx context.Context, customerID string, app int64, d.mu.Unlock() ctx, cancel := context.WithTimeout(ctx, callTimeout) defer cancel() - held, err := inTime(ctx, func() (int64, error) { return d.redis.Do(ctx, d.holdCall(call)).AsInt64() }) + held, err := InTime(ctx, func() (int64, error) { return d.redis.Do(ctx, d.holdCall(call)).AsInt64() }) if err == nil && held == 0 { d.mu.Lock() delete(d.onCalls, call) @@ -333,7 +335,7 @@ func (d *Directory) releaseCall(ctx context.Context, call heldCall) { d.mu.Unlock() ctx, cancel := context.WithTimeout(ctx, callTimeout) defer cancel() - _, err := inTime(ctx, func() (int64, error) { + _, err := InTime(ctx, func() (int64, error) { return d.redis.Do(ctx, d.redis.B().Hdel().Key(call.key).Field(call.field).Build()).AsInt64() }) if err != nil { @@ -346,7 +348,7 @@ func (d *Directory) releaseCall(ctx context.Context, call heldCall) { func (d *Directory) CallHolder(ctx context.Context, app int64, id string) (string, error) { ctx, cancel := context.WithTimeout(ctx, callTimeout) defer cancel() - return inTime(ctx, func() (string, error) { + return InTime(ctx, func() (string, error) { return d.redis.Do(ctx, d.redis.B().Eval().Script(callHolderScript).Numkeys(1).Key(d.callKey(app, id)).Build()).ToString() }) } diff --git a/acceleration/internal/node/directory_test.go b/acceleration/internal/node/directory_test.go index 842c3ad02e..a67617b3f6 100644 --- a/acceleration/internal/node/directory_test.go +++ b/acceleration/internal/node/directory_test.go @@ -412,6 +412,68 @@ func (s *DirectorySuite) TestARenewalAnotherCustomersHoldRefusesIsLogged() { s.Contains(logged.String(), s.prefix+":call:7:order-42") } +// A node that stopped renewing leaves its sessions' fields behind: the next hold drops them. +func (s *DirectorySuite) TestAHoldDropsWhatLapsed() { + s.callOf(s.directoryAt("node-a:1"), "acme") + s.callOf(s.directoryAt("node-b:1"), "acme") + s.lapsed() + + s.callOf(s.directoryAt("node-c:1"), "globex") + + fields, err := s.client.Do(s.ctx, s.client.B().Hkeys().Key(s.prefix+":call:7:order-42").Build()).AsStrSlice() + s.Require().NoError(err) + s.Equal([]string{"node-c:1#1"}, fields) +} + +// A Redis that takes most of the time there is to answer is waited for. +func (s *DirectorySuite) TestACallIsHeldAndFoundThoughRedisIsSlow() { + listener, err := net.Listen("tcp", "127.0.0.1:0") + s.Require().NoError(err) + defer listener.Close() + go func() { + for { + conn, err := listener.Accept() + if err != nil { + return + } + upstream, err := net.Dial("tcp", os.Getenv("ROUTER_REDIS_ADDR")) + if err != nil { + _ = conn.Close() + return + } + go func() { _, _ = io.Copy(upstream, conn); _ = upstream.Close() }() + go func() { + defer conn.Close() + answer := make([]byte, 64<<10) + for { + n, err := upstream.Read(answer) + if err != nil { + return + } + time.Sleep(700 * time.Millisecond) + if _, err := conn.Write(answer[:n]); err != nil { + return + } + } + }() + } + }() + client, err := rueidis.NewClient(rueidis.ClientOption{ + InitAddress: []string{listener.Addr().String()}, DisableCache: true, ForceSingleClient: true, PipelineMultiplex: -1, + }) + s.Require().NoError(err) + s.T().Cleanup(client.Close) + directory, err := NewDirectory(DirectoryOptions{Redis: client, Address: "node-a:1", Prefix: s.prefix}) + s.Require().NoError(err) + directory.Close() + + _, err = directory.HoldCall(s.ctx, "acme", 7, "order-42") + s.Require().NoError(err) + customer, err := directory.CallHolder(s.ctx, 7, "order-42") + s.Require().NoError(err) + s.Equal("acme", customer) +} + // A session Redis could not be told of is logged. func (s *DirectorySuite) TestASessionThatCannotBeSaidIsLogged() { var logged bytes.Buffer diff --git a/acceleration/internal/node/intime_test.go b/acceleration/internal/node/intime_test.go new file mode 100644 index 0000000000..1dc6c1c5d3 --- /dev/null +++ b/acceleration/internal/node/intime_test.go @@ -0,0 +1,27 @@ +package node + +import ( + "context" + "testing" + "testing/synctest" + "time" + + "github.com/stretchr/testify/require" +) + +// The bubble fails a test that leaves a goroutine blocked in it. +func TestARequestNotWaitedForEndsWhenItIsAnswered(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), time.Second) + defer cancel() + answered := make(chan struct{}) + + _, err := InTime(ctx, func() (int, error) { + <-answered + return 1, nil + }) + + require.ErrorIs(t, err, context.DeadlineExceeded) + close(answered) + }) +} From 7e417fdfc407cf51312d36b01f757ba35aeed794 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 19:42:35 +0000 Subject: [PATCH 17/23] test(phone): a call another shard answered is its customer's here too --- acceleration/internal/api/shards_test.go | 35 +++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/acceleration/internal/api/shards_test.go b/acceleration/internal/api/shards_test.go index 0131b21afe..422211036d 100644 --- a/acceleration/internal/api/shards_test.go +++ b/acceleration/internal/api/shards_test.go @@ -293,7 +293,7 @@ func (s *CallShardSuite) TestTwoShardsPlacingAtOnceCannotRingPastTheOrganization Key: outcome.Key{CustomerID: s.customerID(), CallType: "default", CallID: s.utils.uuid(), Local: s.utils.number(), Remote: s.utils.number()}, Vendor: "telnyx", - }, organization, &atOnce) + }, organization, &atOnce, nil) if err == nil { placed.Add(1) return @@ -527,3 +527,36 @@ func (s *ShardRowsSuite) TestAnotherShardsInvocationsAreListedOnlyWhenItsRegionI s.Equal([]string{there.ID}, remote) s.Equal("there", shard) } + +// A call another shard answered is its customer's here too: another customer's call is not routed +// into it, nor a session opened under its id, and its own customer's are. +func (s *CallShardSuite) TestACallAnotherShardAnsweredIsItsCustomersHereToo() { + arrived := func(customer string) string { + call := s.utils.uuid() + s.otherPhone.OpenLeg(context.Background(), routing.Owner{CustomerID: customer}, store.CallLeg{ + CallType: "agent", CallID: call, StreamSessionID: "stream-" + call, Vendor: "twilio", Direction: store.Inbound, + LocalNumber: s.utils.number(), RemoteNumber: s.utils.number(), DialedAt: time.Now().Add(-time.Minute), + }, true) + return call + } + e164 := s.utils.number() + s.Require().NoError(s.store.PhoneNumbers.Insert(context.Background(), &store.PhoneNumber{ + E164: e164, Vendor: "twilio", Country: "US", CustomerID: s.customerID(), PurchasedAt: time.Now().UTC(), + })) + callInto := func(session string) (int, string) { + status, payload := s.serverClient.call(http.MethodPost, "/v1/phone/calls", PlaceCallRequest{ + From: e164, To: "+15550001111", SessionId: &session, + }) + return status, string(payload) + } + theirs, mine := arrived("customer-"+s.utils.uuid()), arrived(s.customerID()) + + status, payload := callInto(theirs) + s.Equal(http.StatusConflict, status, payload) + s.Contains(payload, "session_id is taken") + s.Equal(http.StatusConflict, s.serverClient.do(http.MethodPost, "/v1/agents/sessions", textSession(&theirs), nil)) + status, payload = callInto(mine) + s.Equal(http.StatusServiceUnavailable, status, payload) + s.Contains(payload, "phone_vendor_failed") + s.Equal(http.StatusCreated, s.serverClient.do(http.MethodPost, "/v1/agents/sessions", textSession(&mine), nil)) +} From 645b5436f2c708c6b408606e1a032099213d47fb Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 19:42:53 +0000 Subject: [PATCH 18/23] test(phone): import routing --- acceleration/internal/api/shards_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/acceleration/internal/api/shards_test.go b/acceleration/internal/api/shards_test.go index 422211036d..aef7873b06 100644 --- a/acceleration/internal/api/shards_test.go +++ b/acceleration/internal/api/shards_test.go @@ -23,6 +23,7 @@ import ( "github.com/GetStream/Vision-Agents/acceleration/internal/node" "github.com/GetStream/Vision-Agents/acceleration/internal/phone" "github.com/GetStream/Vision-Agents/acceleration/internal/phone/outcome" + "github.com/GetStream/Vision-Agents/acceleration/internal/routing" "github.com/GetStream/Vision-Agents/acceleration/internal/store" ) From e5e29811019d8a1a4a1a1be2525f9d6c3afead08 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 20:46:45 +0000 Subject: [PATCH 19/23] test(phone): a claim whose homes cannot be read, and fewer connections for the claims at once --- acceleration/internal/store/call_leg_test.go | 22 ++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/acceleration/internal/store/call_leg_test.go b/acceleration/internal/store/call_leg_test.go index 35340229d8..65d7d6388f 100644 --- a/acceleration/internal/store/call_leg_test.go +++ b/acceleration/internal/store/call_leg_test.go @@ -1150,6 +1150,10 @@ func (s *StoreSuite) TestNamedCallsOfNoOrganizationArePlacedBesideEachOther() { // Named calls whose hold is not answered give up, and hold up no other placement meanwhile. func (s *StoreSuite) TestNamedCallsNotAnsweredHoldUpNoOtherPlacement() { router := s.ownRouter() + if router.shard != router.global { + // Each claim holds a connection of the shared database, which is what is tested. + router.shard.SetMaxOpenConns(1) + } on := NamedCall{Scope: AppScope{Unpinned: true}} var holding atomic.Int64 var wg sync.WaitGroup @@ -1234,3 +1238,21 @@ func (s *StoreSuite) TestANamedCallWaitingOnItsCallHoldsUpNoOtherPlacementOfItsO s.NoError(<-held) s.NoError(<-waiting) } + +// A call whose homes cannot be read is not claimed. +func (s *ShardedStoreSuite) TestACallWhoseHomesCannotBeReadIsNotClaimed() { + _, err := s.store.global.ExecContext(s.ctx, "ALTER TABLE call_homes RENAME TO call_homes_unmigrated") + s.Require().NoError(err) + defer func() { + _, err := s.store.global.ExecContext(context.WithoutCancel(s.ctx), "ALTER TABLE call_homes_unmigrated RENAME TO call_homes") + s.Require().NoError(err) + }() + held := false + + s.Error(s.store.CallLegs.Claim(s.ctx, "mine", "agent", "call", NamedCall{Scope: AppScope{Unpinned: true}}, func(context.Context) error { + held = true + return nil + })) + + s.False(held) +} From debdd515ea71eb0bc75b4674c3e21c7964d170f3 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 21:42:04 +0000 Subject: [PATCH 20/23] fix(phone): a named call is claimed on the one connection its lock is held on --- acceleration/internal/store/call_home.go | 7 +- acceleration/internal/store/call_leg.go | 114 ++++++++++++------ acceleration/internal/store/call_leg_test.go | 32 ++++- .../internal/store/store_explain_test.go | 2 +- 4 files changed, 113 insertions(+), 42 deletions(-) diff --git a/acceleration/internal/store/call_home.go b/acceleration/internal/store/call_home.go index 28f5d80737..21cef28d99 100644 --- a/acceleration/internal/store/call_home.go +++ b/acceleration/internal/store/call_home.go @@ -83,12 +83,17 @@ func (r *CallHomes) anotherElsewhere(ctx context.Context, db bun.IDB, scope AppS // record makes this shard the home of a customer's call in app, unless it has one. func (r *CallHomes) record(ctx context.Context, customerID string, app int64, callType, callID string) error { + return r.recordWith(ctx, r.store.global, customerID, app, callType, callID) +} + +// recordWith is record with db, the shared database or a transaction of it. +func (r *CallHomes) recordWith(ctx context.Context, db bun.IDB, customerID string, app int64, callType, callID string) error { if !r.store.homed { return nil } home := CallHome{CallID: callID, CallType: callType, StreamAppPK: app, CustomerID: customerID, Shard: r.store.ShardName(), OpenedAt: time.Now().UTC()} - if _, err := r.store.global.NewInsert().Model(&home).On("CONFLICT DO NOTHING").Exec(ctx); err != nil { + if _, err := db.NewInsert().Model(&home).On("CONFLICT DO NOTHING").Exec(ctx); err != nil { return stack.Wrap(fmt.Errorf("store: record call home: %w", err)) } return nil diff --git a/acceleration/internal/store/call_leg.go b/acceleration/internal/store/call_leg.go index 810b06bde9..7990025a4d 100644 --- a/acceleration/internal/store/call_leg.go +++ b/acceleration/internal/store/call_leg.go @@ -758,41 +758,49 @@ func (r *CallLegs) PlaceWithin(ctx context.Context, leg *CallLeg, atOnce CallsAt defer release() ctx, cancel := context.WithTimeout(ctx, placingFor) defer cancel() - err = r.store.shard.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { - if err := lockUntilCommit(ctx, tx, leg.OrganizationID, callsAtOnceLockSeed); err != nil { - return err - } - own, err := countOpen(ctx, tx, leg.OrganizationID, leg.PlacedAt.Add(-atOnce.Ringing), "", "") - if err != nil { - return err - } - room, err := r.store.OpenLegs.place(ctx, leg.OrganizationID, own.Total, atOnce.Limit) - if err != nil { - return err - } - if !room { - return ErrCallsAtOnce - } - _, err = tx.NewInsert().Model(leg).Returning("id").Exec(ctx) - return err - }) + err = r.store.shard.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { return r.keepWithin(ctx, tx, leg, atOnce) }) if errors.Is(err, ErrCallsAtOnce) { return stack.Wrap(ErrCallsAtOnce) } if err != nil { - // The leg may have been kept, its commit's answer lost, and the caller dials nothing: the - // leg would hold a call of the organization's for as long as it could ring. Deleting a - // leg that was never kept deletes nothing. The shared count drops it at the next Heal. - gone, stop := context.WithTimeout(context.WithoutCancel(ctx), placingFor) - if _, derr := r.store.shard.NewDelete().Model((*CallLeg)(nil)).Where("token_hash = ?", leg.TokenHash).Exec(gone); derr != nil { - err = errors.Join(err, derr) - } - stop() - return stack.Wrap(fmt.Errorf("store: place call leg: %w", err)) + return stack.Wrap(fmt.Errorf("store: place call leg: %w", r.unkeep(ctx, leg, err))) } return r.store.CallHomes.record(ctx, leg.CustomerID, leg.StreamAppPK, leg.CallType, leg.CallID) } +// keepWithin is the step of PlaceWithin, in a transaction of this shard's. +func (r *CallLegs) keepWithin(ctx context.Context, tx bun.IDB, leg *CallLeg, atOnce CallsAtOnce) error { + if err := lockUntilCommit(ctx, tx, leg.OrganizationID, callsAtOnceLockSeed); err != nil { + return err + } + own, err := countOpen(ctx, tx, leg.OrganizationID, leg.PlacedAt.Add(-atOnce.Ringing), "", "") + if err != nil { + return err + } + room, err := r.store.OpenLegs.place(ctx, leg.OrganizationID, own.Total, atOnce.Limit) + if err != nil { + return err + } + if !room { + return ErrCallsAtOnce + } + _, err = tx.NewInsert().Model(leg).Returning("id").Exec(ctx) + return err +} + +// unkeep deletes a leg whose placement failed with err. It may have been kept, its commit's answer +// lost, and the caller dials nothing: the leg would hold a call of the organization's for as long +// as it could ring. Deleting a leg that was never kept deletes nothing. The shared count drops it +// at the next Heal. +func (r *CallLegs) unkeep(ctx context.Context, leg *CallLeg, err error) error { + gone, stop := context.WithTimeout(context.WithoutCancel(ctx), placingFor) + defer stop() + if _, derr := r.store.shard.NewDelete().Model((*CallLeg)(nil)).Where("token_hash = ?", leg.TokenHash).Exec(gone); derr != nil { + return errors.Join(err, derr) + } + return err +} + // ErrCallTaken is a named call that is another customer's, and ErrCallUnchecked one that could // not be checked: where running sessions say whose call they are on did not answer. var ( @@ -839,19 +847,43 @@ func (c NamedCall) held(ctx context.Context, customerID string) error { // PlaceOn is Place, or with atOnce PlaceWithin, for a leg of a call somebody named: it keeps leg, // or refuses it with ErrCallTaken as a call of another customer's, under the call's lock. func (r *CallLegs) PlaceOn(ctx context.Context, leg *CallLeg, on NamedCall, atOnce *CallsAtOnce) error { - return r.claim(ctx, leg.CustomerID, leg.CallType, leg.CallID, on, func(ctx context.Context) error { - if atOnce != nil { - return r.PlaceWithin(ctx, leg, *atOnce) + if err := placeable(leg); err != nil { + return err + } + if atOnce != nil && leg.OrganizationID == "" { + return stack.Wrap(validate("call leg").required("organization_id", leg.OrganizationID).done()) + } + err := r.claim(ctx, leg.CustomerID, leg.CallType, leg.CallID, on, func(ctx context.Context, global, shard bun.IDB) error { + if err := r.keep(ctx, shard, leg, atOnce); err != nil { + return err } - return r.Place(ctx, leg) + return r.store.CallHomes.recordWith(ctx, global, leg.CustomerID, leg.StreamAppPK, leg.CallType, leg.CallID) }) + if err == nil || errors.Is(err, ErrCallTaken) || errors.Is(err, ErrCallUnchecked) || errors.Is(err, ErrCallsAtOnce) { + return err + } + return r.unkeep(ctx, leg, err) +} + +// keep inserts a placed leg with db, within what atOnce leaves room for when it is set. db is a +// transaction, or with a shard of its own the shard's pool, which a step of more than one +// statement takes a transaction of. +func (r *CallLegs) keep(ctx context.Context, db bun.IDB, leg *CallLeg, atOnce *CallsAtOnce) error { + if atOnce == nil { + _, err := db.NewInsert().Model(leg).Returning("id").Exec(ctx) + return err + } + if db != bun.IDB(r.store.shard) { + return r.keepWithin(ctx, db, leg, *atOnce) + } + return r.store.shard.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { return r.keepWithin(ctx, tx, leg, *atOnce) }) } // Claim runs hold, which says a customer's session is on a named call, or refuses with // ErrCallTaken when the call is another customer's. Both are under the lock PlaceOn keeps a leg // under, so of a session and a call placed at once, or of two sessions, one sees the other. func (r *CallLegs) Claim(ctx context.Context, customerID, callType, callID string, on NamedCall, hold func(context.Context) error) error { - return r.claim(ctx, customerID, callType, callID, on, func(ctx context.Context) error { + return r.claim(ctx, customerID, callType, callID, on, func(ctx context.Context, _, _ bun.IDB) error { if err := hold(ctx); err != nil { return errors.Join(ErrCallUnchecked, err) } @@ -861,8 +893,10 @@ func (r *CallLegs) Claim(ctx context.Context, customerID, callType, callID strin // claim runs keep under the call's lock, unless the call is another customer's: by a session some // node runs, by its legs in this shard, or by its home in another (CallHomes). keep leaves its leg -// and the leg's home, or its hold, behind before the lock is let go. -func (r *CallLegs) claim(ctx context.Context, customerID, callType, callID string, on NamedCall, keep func(context.Context) error) error { +// and the leg's home, or its hold, behind before the lock is let go. It is given what to write the +// shared database and the shard with: the lock's own transaction, also for the shard when they are +// one database, so a claim never waits on a second connection of the pool it holds one of. +func (r *CallLegs) claim(ctx context.Context, customerID, callType, callID string, on NamedCall, keep func(ctx context.Context, global, shard bun.IDB) error) error { release, err := r.claiming(ctx, on, customerID) if err != nil { return stack.Wrap(fmt.Errorf("store: claim call: %w", err)) @@ -881,7 +915,11 @@ func (r *CallLegs) claim(ctx context.Context, customerID, callType, callID strin if err := on.held(ctx, customerID); err != nil { return err } - owner, err := r.owner(ctx, on.Scope, callType, callID) + var shard bun.IDB = r.store.shard + if r.store.shard == r.store.global { + shard = tx + } + owner, err := r.owner(ctx, shard, on.Scope, callType, callID) if err != nil { return err } @@ -897,7 +935,7 @@ func (r *CallLegs) claim(ctx context.Context, customerID, callType, callID strin return ErrCallTaken } } - return keep(ctx) + return keep(ctx, tx, shard) }) if err != nil { return stack.Wrap(fmt.Errorf("store: claim call: %w", err)) @@ -927,9 +965,9 @@ func (r *CallLegs) claiming(ctx context.Context, on NamedCall, customerID string // and those a phone was on. It is empty for a call no leg here is on. One customer alone has legs // on a call claimed here; of more, as a release before this one may have left, it is the first // dialled, and of two dialled at once the first by id. -func (r *CallLegs) owner(ctx context.Context, scope AppScope, callType, callID string) (string, error) { +func (r *CallLegs) owner(ctx context.Context, shard bun.IDB, scope AppScope, callType, callID string) (string, error) { var owners []string - err := r.store.shard.NewSelect().Model((*CallLeg)(nil)).Column("customer_id"). + err := shard.NewSelect().Model((*CallLeg)(nil)).Column("customer_id"). Where("call_type = ?", callType).Where("call_id = ?", callID). ApplyQueryBuilder(scope.where). WhereGroup(" AND ", func(q *bun.SelectQuery) *bun.SelectQuery { diff --git a/acceleration/internal/store/call_leg_test.go b/acceleration/internal/store/call_leg_test.go index 65d7d6388f..966d862ee2 100644 --- a/acceleration/internal/store/call_leg_test.go +++ b/acceleration/internal/store/call_leg_test.go @@ -794,7 +794,7 @@ func (s *StoreSuite) TestADialNamingNoOrganizationKeepsTheOneTheCallWasPlacedUnd // ownerOf is the customer the call is, read as Claim reads it. func (s *StoreSuite) ownerOf(scope AppScope, callID string) string { - owner, err := s.store.CallLegs.owner(s.ctx, scope, "agent", callID) + owner, err := s.store.CallLegs.owner(s.ctx, s.store.shard, scope, "agent", callID) s.Require().NoError(err) return owner } @@ -873,7 +873,7 @@ func (s *StoreSuite) TestACallIsTheCustomersWhoseLegWasDialledOnItFirst() { s.Equal("first", s.ownerOf(AppScope{Unpinned: true}, "call")) s.Equal("a", s.ownerOf(AppScope{Unpinned: true}, "tied")) s.Empty(s.ownerOf(AppScope{Unpinned: true}, "another call")) - other, err := s.store.CallLegs.owner(s.ctx, AppScope{Unpinned: true}, "default", "call") + other, err := s.store.CallLegs.owner(s.ctx, s.store.shard, AppScope{Unpinned: true}, "default", "call") s.Require().NoError(err) s.Empty(other, "a call of another type") } @@ -1256,3 +1256,31 @@ func (s *ShardedStoreSuite) TestACallWhoseHomesCannotBeReadIsNotClaimed() { s.False(held) } + +// A claim waits on no second connection of the pool it holds one of: more of them than the pool +// has connections all go through. +func (s *StoreSuite) TestMoreNamedCallsThanThePoolHasConnectionsAreAllPlaced() { + router := s.ownRouter() + router.global.SetMaxOpenConns(2) + on := NamedCall{Scope: AppScope{Unpinned: true}} + errs := make([]error, 24) + var wg sync.WaitGroup + for i := range errs { + wg.Go(func() { + call := fmt.Sprintf("call-%d", i) + switch i % 3 { + case 0: + errs[i] = router.CallLegs.Claim(s.ctx, "app", "agent", call, on, func(context.Context) error { return nil }) + case 1: + errs[i] = s.placesWith(router, "app", call, on, nil) + default: + errs[i] = s.placesWith(router, "app", call, on, &CallsAtOnce{Limit: 100, Ringing: time.Hour}) + } + }) + } + wg.Wait() + + for _, err := range errs { + s.NoError(err) + } +} diff --git a/acceleration/internal/store/store_explain_test.go b/acceleration/internal/store/store_explain_test.go index 6c4e522ff0..8ead6791ef 100644 --- a/acceleration/internal/store/store_explain_test.go +++ b/acceleration/internal/store/store_explain_test.go @@ -478,7 +478,7 @@ func (s *StoreSuite) TestEveryHotTableIsReadByIndex() { return err }}, {name: "CallLegs.Claim", index: "call_legs_call_idx", run: func(ctx context.Context, store *Store) error { - _, err := store.CallLegs.owner(ctx, AppScope{App: 3}, "default", "stream-101") + _, err := store.CallLegs.owner(ctx, store.shard, AppScope{App: 3}, "default", "stream-101") return err }}, {name: "CallLegs.HasParticipant", index: "call_legs_participant_idx", run: func(ctx context.Context, store *Store) error { From 78eba8bf015c84d4a763790b10c1a364c719945b Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 22:32:20 +0000 Subject: [PATCH 21/23] test(phone): named calls of one organization keep to its limit --- acceleration/internal/store/call_leg.go | 6 ++-- acceleration/internal/store/call_leg_test.go | 33 ++++++++++++++++++++ 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/acceleration/internal/store/call_leg.go b/acceleration/internal/store/call_leg.go index 7990025a4d..a5390b07f4 100644 --- a/acceleration/internal/store/call_leg.go +++ b/acceleration/internal/store/call_leg.go @@ -859,10 +859,10 @@ func (r *CallLegs) PlaceOn(ctx context.Context, leg *CallLeg, on NamedCall, atOn } return r.store.CallHomes.recordWith(ctx, global, leg.CustomerID, leg.StreamAppPK, leg.CallType, leg.CallID) }) - if err == nil || errors.Is(err, ErrCallTaken) || errors.Is(err, ErrCallUnchecked) || errors.Is(err, ErrCallsAtOnce) { - return err + if err != nil { + return r.unkeep(ctx, leg, err) } - return r.unkeep(ctx, leg, err) + return nil } // keep inserts a placed leg with db, within what atOnce leaves room for when it is set. db is a diff --git a/acceleration/internal/store/call_leg_test.go b/acceleration/internal/store/call_leg_test.go index 966d862ee2..b8effa70b1 100644 --- a/acceleration/internal/store/call_leg_test.go +++ b/acceleration/internal/store/call_leg_test.go @@ -1284,3 +1284,36 @@ func (s *StoreSuite) TestMoreNamedCallsThanThePoolHasConnectionsAreAllPlaced() { s.NoError(err) } } + +// Named calls of one organization placed at once are kept to the calls it may have at once, in +// this shard's own transaction, and each is found by its token. +func (s *StoreSuite) TestNamedCallsPlacedAtOnceKeepToTheOrganizationsLimit() { + on := NamedCall{Scope: AppScope{Unpinned: true}} + organization := newID() + tokens := make([]string, 12) + errs := make([]error, len(tokens)) + var wg sync.WaitGroup + for i := range tokens { + tokens[i] = newID() + wg.Go(func() { + placed := time.Now() + errs[i] = s.store.CallLegs.PlaceOn(s.ctx, &CallLeg{Token: tokens[i], CustomerID: "app", OrganizationID: organization, CallType: "agent", + CallID: fmt.Sprintf("call-%d", i), Vendor: "telnyx", Direction: Outbound, LocalNumber: "+15125550150", RemoteNumber: "+15125550151", + PlacedAt: &placed}, on, &CallsAtOnce{Limit: 3, Ringing: time.Hour}) + }) + } + wg.Wait() + + kept := 0 + for i, err := range errs { + if err != nil { + s.ErrorIs(err, ErrCallsAtOnce) + continue + } + kept++ + leg, err := s.store.CallLegs.GetByToken(s.ctx, tokens[i]) + s.Require().NoError(err) + s.Equal(fmt.Sprintf("call-%d", i), leg.CallID) + } + s.Equal(3, kept) +} From 5fd26d0eee00a0bf6069685bea0eea3131586fe6 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 23:14:08 +0000 Subject: [PATCH 22/23] test(phone): a named call names its organization and keeps no leg whose home is refused --- acceleration/internal/store/call_leg_test.go | 30 ++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/acceleration/internal/store/call_leg_test.go b/acceleration/internal/store/call_leg_test.go index b8effa70b1..3ca8d717f6 100644 --- a/acceleration/internal/store/call_leg_test.go +++ b/acceleration/internal/store/call_leg_test.go @@ -1317,3 +1317,33 @@ func (s *StoreSuite) TestNamedCallsPlacedAtOnceKeepToTheOrganizationsLimit() { } s.Equal(3, kept) } + +// A named call kept to its organization's limit names its organization. +func (s *StoreSuite) TestANamedCallKeptToALimitNamesItsOrganization() { + placed := time.Now() + err := s.store.CallLegs.PlaceOn(s.ctx, &CallLeg{Token: newID(), CustomerID: "app", CallType: "agent", CallID: "call-" + newID(), + Vendor: "telnyx", Direction: Outbound, LocalNumber: "+15125550150", RemoteNumber: "+15125550151", PlacedAt: &placed}, + NamedCall{Scope: AppScope{Unpinned: true}}, &CallsAtOnce{Limit: 3, Ringing: time.Hour}) + + s.ErrorContains(err, "organization_id") +} + +// A named call whose home the shared database refuses keeps no leg in this shard. +func (s *ShardedStoreSuite) TestANamedCallWhoseHomeIsRefusedKeepsNoLeg() { + _, err := s.store.global.ExecContext(s.ctx, `CREATE FUNCTION refuse_home() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'no home'; END $$; +CREATE TRIGGER refuse_home BEFORE INSERT ON call_homes FOR EACH ROW EXECUTE FUNCTION refuse_home()`) + s.Require().NoError(err) + s.T().Cleanup(func() { + _, err := s.store.global.ExecContext(s.ctx, "DROP TRIGGER refuse_home ON call_homes; DROP FUNCTION refuse_home()") + s.NoError(err) + }) + token, placed := newID(), time.Now() + + err = s.store.CallLegs.PlaceOn(s.ctx, &CallLeg{Token: token, CustomerID: "app", OrganizationID: "org", CallType: "agent", CallID: "call-" + newID(), + Vendor: "telnyx", Direction: Outbound, LocalNumber: "+15125550150", RemoteNumber: "+15125550151", PlacedAt: &placed}, + NamedCall{Scope: AppScope{Unpinned: true}}, &CallsAtOnce{Limit: 3, Ringing: time.Hour}) + + s.Require().ErrorContains(err, "no home") + _, err = s.store.CallLegs.GetByToken(s.ctx, token) + s.Error(err, "the leg was kept") +} From 4340d4106ea9c7c87b25b968e64abe54e1ee37be Mon Sep 17 00:00:00 2001 From: thesyncim Date: Thu, 26 Nov 2026 08:55:53 +0000 Subject: [PATCH 23/23] phone move test's fake Stream apps names the deployment app; gofmt --- acceleration/cmd/router/phonemove_integration_test.go | 2 ++ acceleration/internal/node/directory_test.go | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/acceleration/cmd/router/phonemove_integration_test.go b/acceleration/cmd/router/phonemove_integration_test.go index c581870f3d..f5fdc4722c 100644 --- a/acceleration/cmd/router/phonemove_integration_test.go +++ b/acceleration/cmd/router/phonemove_integration_test.go @@ -363,6 +363,8 @@ func (a oneApp) ForAppRemoving(ctx context.Context, customer string, app int64) func (a oneApp) Placed(context.Context, string) (int64, error) { return 0, nil } +func (a oneApp) DeploymentApp() int64 { return 0 } + // 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() { diff --git a/acceleration/internal/node/directory_test.go b/acceleration/internal/node/directory_test.go index 403d146772..ea37f094b7 100644 --- a/acceleration/internal/node/directory_test.go +++ b/acceleration/internal/node/directory_test.go @@ -8,8 +8,8 @@ import ( "fmt" "io" "log/slog" - "net" "maps" + "net" "os" "slices" "strconv"