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/api/callhooks.go b/acceleration/internal/api/callhooks.go index f31df593f4..7e9d950a80 100644 --- a/acceleration/internal/api/callhooks.go +++ b/acceleration/internal/api/callhooks.go @@ -376,7 +376,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/callhooks_test.go b/acceleration/internal/api/callhooks_test.go index 7fa0f3fd1e..68dfe90f4d 100644 --- a/acceleration/internal/api/callhooks_test.go +++ b/acceleration/internal/api/callhooks_test.go @@ -514,6 +514,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/forward_test.go b/acceleration/internal/api/forward_test.go index 1fac998f7a..1ebde4590d 100644 --- a/acceleration/internal/api/forward_test.go +++ b/acceleration/internal/api/forward_test.go @@ -274,11 +274,11 @@ func (s *ForwardedSessionSuite) TestAMessageStampedWithItsCustomerIsNotCarriedTo } } -// 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/money.go b/acceleration/internal/api/money.go index 4e61780f04..d50507e8bc 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 a0a7a206e4..72c71fcb51 100644 --- a/acceleration/internal/api/phone.go +++ b/acceleration/internal/api/phone.go @@ -407,9 +407,12 @@ 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 + if s.directory != nil { + call.Holder = s.directory.CallHolder + } } if request.Body.RingTimeoutSeconds != nil { if *request.Body.RingTimeoutSeconds < 0 { @@ -435,6 +438,12 @@ func (s *Server) placePhoneCall(ctx context.Context, request *placePhoneCallRequ if failure, over := tierLimitReached(err); over { return nil, failure } + 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()) } @@ -1007,6 +1016,11 @@ func phoneTags(tags *map[string]string) routing.Tags { return routing.Tags(*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 diff --git a/acceleration/internal/api/phone_test.go b/acceleration/internal/api/phone_test.go index fd5af64b62..be91857a3c 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" @@ -26,6 +33,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 @@ -357,6 +365,7 @@ func (s *CallStatusSuite) SetupSuite() { s.phoneVendors = s.unreachableVendors() s.phoneOnChat = true s.sessionTelephony = true + s.deploymentKnown = true s.logged = &lockedLog{} s.logs = s.logged s.RouterSuite.SetupSuite() @@ -1354,3 +1363,481 @@ 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)) +} + +// 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)) +} + +// 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)) +} + +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)) +} + +// 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()) + app := streamAppID() + s.giveApp(s.customerID(), app, "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") + _, 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. +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. +// +// 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) + 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 + } + var cut atomic.Bool + go func() { + defer upstream.Close() + 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) { + cut.Store(true) + } + } + if _, err := upstream.Write(buffer[:n]); err != nil { + return + } + } + }() + go func() { + buffer := make([]byte, 4096) + for { + n, err := upstream.Read(buffer) + if err != nil { + return + } + if deaf.Load() || cut.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 := s.sessionsWith(directory) + 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) + 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) + 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) + + // 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 }) + 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") + 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.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), + 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)) +} + +// 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) +} + +// 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/api/scheduled_delivery.go b/acceleration/internal/api/scheduled_delivery.go index d255598dc8..5e6668e516 100644 --- a/acceleration/internal/api/scheduled_delivery.go +++ b/acceleration/internal/api/scheduled_delivery.go @@ -1138,16 +1138,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, caller, 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, - }) - if err != nil { - return session.Spec{}, unpaid(overTier(err)) + MintedID: true, } - return callSpec(config, delivery, caller, found.Spec().AgentID, placed, from, to), nil } // callSpec is the session a call a task placed is held in: the config as it @@ -1155,7 +1161,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, caller routing.Caller, 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/api/scheduled_phone_test.go b/acceleration/internal/api/scheduled_phone_test.go index 3baec7992e..28cef4351e 100644 --- a/acceleration/internal/api/scheduled_phone_test.go +++ b/acceleration/internal/api/scheduled_phone_test.go @@ -85,6 +85,8 @@ func (s *ScheduledTasksSuite) placeCall(user *testClient) placedCall { caller, err := s.router.scheduledCaller(context.Background(), delivery) s.Require().NoError(err) spec := callSpec(config, delivery, caller, 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/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/api/shards_test.go b/acceleration/internal/api/shards_test.go index 0131b21afe..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" ) @@ -293,7 +294,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 +528,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)) +} diff --git a/acceleration/internal/campaign/campaign.go b/acceleration/internal/campaign/campaign.go index 92123fb7c0..6aa987f92c 100644 --- a/acceleration/internal/campaign/campaign.go +++ b/acceleration/internal/campaign/campaign.go @@ -776,6 +776,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(), } @@ -791,7 +793,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/campaign_test.go b/acceleration/internal/campaign/campaign_test.go index f22b42671c..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"}) @@ -68,6 +69,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 3999751543..110198662e 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" "math/rand/v2" @@ -26,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 @@ -62,6 +65,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: a router // of the release before reads channels, when a customer's own key is not there, as this one // does, and only an older one reads agents. @@ -86,6 +90,9 @@ type Directory struct { // held maps a session this node is running to the Stream app it acts in, the agent it // writes as and the conversation it answers in, the last two empty for a session without one. held map[heldSession]claim + // 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. @@ -98,6 +105,10 @@ type offerKey struct{ customerID, agentID string } // one id. type heldSession struct{ customerID, sessionID 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, and the Stream app it // acts in. type claim struct { @@ -135,6 +146,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:", @@ -148,6 +160,7 @@ func NewDirectory(options DirectoryOptions) (*Directory, error) { logger: logger, cancel: cancel, held: map[heldSession]claim{}, + onCalls: map[heldCall]struct{}{}, waiting: map[string]int{}, offered: map[offerKey][]byte{}, } @@ -230,7 +243,126 @@ func (d *Directory) Hold(ctx context.Context, customerID string, app int64, sess d.held[key] = held d.mu.Unlock() - d.write(ctx, key, held) + ctx, cancel := context.WithTimeout(ctx, callTimeout) + defer cancel() + _, 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", + "app_id", 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) + goroutine.Go(ctx, 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, drops 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 + else redis.call('HDEL', KEYS[1], fields[i]) 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 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 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.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() + 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) + d.mu.Unlock() + return func(context.Context) {}, ErrCallHeld + } + return func(ctx context.Context) { d.releaseCall(ctx, call) }, err +} + +// 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() + delete(d.onCalls, call) + d.mu.Unlock() + ctx, cancel := context.WithTimeout(ctx, callTimeout) + defer cancel() + _, 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", "app_id", call.customerID, "call", call.key, "error", err) + } +} + +// 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) { + ctx, cancel := context.WithTimeout(ctx, callTimeout) + defer cancel() + 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::. +func (d *Directory) callKey(app int64, id string) string { + return d.calls + strconv.FormatInt(app, 10) + ":" + id +} + +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. @@ -565,14 +697,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", - "app_id", 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 @@ -688,6 +819,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() @@ -696,6 +828,11 @@ 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 { commands = append(commands, d.advertiseCommands(customerID)...) } @@ -710,10 +847,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", + "app_id", call.customerID, "call", call.key) + } } } diff --git a/acceleration/internal/node/directory_test.go b/acceleration/internal/node/directory_test.go index 0dd1dd6994..ea37f094b7 100644 --- a/acceleration/internal/node/directory_test.go +++ b/acceleration/internal/node/directory_test.go @@ -5,8 +5,11 @@ package node import ( "bytes" "context" + "fmt" + "io" "log/slog" "maps" + "net" "os" "slices" "strconv" @@ -60,6 +63,7 @@ func (s *DirectorySuite) TestARenewalIsOneRoundTrip() { for _, session := range []string{"s1", "s2", "s3"} { directory.Hold(s.ctx, "acme", 7, session, "agent-"+session, "messaging:"+session) } + s.callOf(directory, "acme") directory.Wait(s.ctx, "acme") directory.Wait(s.ctx, "globex") directory.Offer(s.ctx, "acme", "agent-s1", []byte(`{"tools":[]}`)) @@ -67,8 +71,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 and its conversation, each under its customer and under its id alone, - // and its agent by app and customer, by customer, and by its id alone. - s.Require().Len(keys, 3*7+2+2+2) + // and its agent by app and customer, by customer, and by its id alone. And the call of one. + s.Require().Len(keys, 3*7+1+2+2+2) s.Require().NoError(s.client.Do(s.ctx, s.client.B().Del().Key(keys...).Build()).Error()) before := s.roundTrips.sent.Load() @@ -303,6 +307,318 @@ func (s *DirectorySuite) TestAReleasedSessionIsFoundNowhere() { s.Zero(exists, "a router of the release before would still forward to it") } +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 +} + +// 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() { + 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") + 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") + 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.lapsed() + s.Empty(s.holder(7, "order-42")) + directory.renewAll(s.ctx) + s.Equal("a customer:1", s.holder(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") + release := s.callOf(first, "acme") + + 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 said once the call is free. + s.lapsed() + second.renewAll(s.ctx) + s.Empty(s.holder(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")) + release() + 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(), "app_id=acme") + 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 + 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() { + 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() + // 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") }, + "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") + 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")) +} + +// 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") + 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.renewAll(s.ctx) + s.Equal("acme", s.holder(7, "order-42")) + release(s.ctx) + s.Empty(s.holder(7, "order-42")) +} + // Each claim that cannot be taken back is said, so a Redis that refuses one of the two leaves the // other's failure in the log too. func (s *DirectorySuite) TestEachClaimThatCannotBeTakenBackIsLogged() { 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) + }) +} diff --git a/acceleration/internal/phone/apps.go b/acceleration/internal/phone/apps.go index bdeaa3ff6a..deb2afc6cb 100644 --- a/acceleration/internal/phone/apps.go +++ b/acceleration/internal/phone/apps.go @@ -40,6 +40,8 @@ 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() } + func (a clientApps) Placed(ctx context.Context, customer string) (int64, error) { return a.clients.Placed(ctx, customer) } diff --git a/acceleration/internal/phone/apps_integration_test.go b/acceleration/internal/phone/apps_integration_test.go index adcc796dbe..f8458216da 100644 --- a/acceleration/internal/phone/apps_integration_test.go +++ b/acceleration/internal/phone/apps_integration_test.go @@ -1279,6 +1279,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}} } @@ -1473,7 +1475,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, @@ -3719,3 +3721,207 @@ 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{} + + 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) + 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], store.ErrCallTaken) != errors.Is(errs[1], store.ErrCallTaken), "%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) +} + +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.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() { + 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()) +} + +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/phone/outcome/keeper.go b/acceleration/internal/phone/outcome/keeper.go index f13af4fac2..2ae6cc0fa4 100644 --- a/acceleration/internal/phone/outcome/keeper.go +++ b/acceleration/internal/phone/outcome/keeper.go @@ -34,12 +34,14 @@ 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: k.store.MintToken(), @@ -57,7 +59,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 6742589db7..fbfc1d8e0b 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 // Placed is the pin of the app For makes new lines for a customer in, read without acting // for the customer, so one customer's request can ask where another's lines go. Placed(ctx context.Context, customer string) (int64, error) @@ -1227,6 +1229,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 @@ -1296,7 +1303,7 @@ func lasting(err error) bool { errors.Is(err, store.ErrNumberHeldElsewhere) || 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, 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 @@ -1392,6 +1399,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, @@ -1399,10 +1423,16 @@ 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.ErrCallUnchecked) { + s.logger.Warn("refused a phone call: could not tell whose its call is", "session", sessionID, "app_id", request.Owner.CustomerID, "error", err) + } + if errors.Is(err, store.ErrCallTaken) || errors.Is(err, store.ErrCallUnchecked) { + return Placed{}, err + } if err != nil { return Placed{}, notPlaced(ctx, err) } diff --git a/acceleration/internal/session/manager.go b/acceleration/internal/session/manager.go index ca7fc11395..b83819df45 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). @@ -543,6 +547,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) @@ -598,6 +613,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) @@ -697,6 +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, 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. @@ -2097,6 +2126,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)) @@ -2281,6 +2311,55 @@ func (m *Manager) stream(ctx context.Context, spec Spec, newCall bool) (streamap return bound, nil } +// 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 + } + 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 { + said, err := directory.HoldCall(ctx, spec.CustomerID, app, spec.ID) + release = sync.OnceFunc(func() { said(context.WithoutCancel(ctx)) }) + return 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, "app_id", spec.CustomerID, "error", err) + } + return release, 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.ErrCallUnchecked) { + m.logger.Warn("refused a session: could not tell whose its call is", "session", spec.ID, "app_id", spec.CustomerID, "error", err) + } + if errors.Is(err, store.ErrCallTaken) { + err = stack.Wrap(ErrSessionExists) + } + return func() {}, 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/session/spec.go b/acceleration/internal/session/spec.go index a60b8a3ac4..a07fd0b451 100644 --- a/acceleration/internal/session/spec.go +++ b/acceleration/internal/session/spec.go @@ -50,7 +50,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_home.go b/acceleration/internal/store/call_home.go index 8c071bc8ec..21cef28d99 100644 --- a/acceleration/internal/store/call_home.go +++ b/acceleration/internal/store/call_home.go @@ -38,7 +38,21 @@ func (r *CallHomes) Elsewhere(ctx context.Context, scope AppScope, callType, cal return "", nil } var shards []string - err := r.store.global.NewSelect().Model((*CallHome)(nil)).Column("shard"). + err := homesOf(r.store.global, scope, callType, callID).Column("shard"). + OrderExpr("opened_at DESC"). + Scan(ctx, &shards) + if err != nil { + return "", stack.Wrap(fmt.Errorf("store: call home: %w", err)) + } + if len(shards) == 0 || slices.Contains(shards, r.store.ShardName()) { + return "", nil + } + return shards[0], nil +} + +// homesOf are the homes of a call of the scope's app. +func homesOf(db bun.IDB, scope AppScope, callType, callID string) *bun.SelectQuery { + return db.NewSelect().Model((*CallHome)(nil)). Where("call_id = ?", callID). Where("call_type = ?", callType). WhereGroup(" AND ", func(q *bun.SelectQuery) *bun.SelectQuery { @@ -50,26 +64,36 @@ func (r *CallHomes) Elsewhere(ctx context.Context, scope AppScope, callType, cal q = q.WhereOr("stream_app_pk = 0") } return q - }). - OrderExpr("opened_at DESC"). - Scan(ctx, &shards) - if err != nil { - return "", stack.Wrap(fmt.Errorf("store: call home: %w", err)) + }) +} + +// anotherElsewhere reports whether a call of the scope's app lives in another shard for a customer +// other than customerID, read with db. +func (r *CallHomes) anotherElsewhere(ctx context.Context, db bun.IDB, scope AppScope, callType, callID, customerID string) (bool, error) { + if !r.store.homed { + return false, nil } - if len(shards) == 0 || slices.Contains(shards, r.store.ShardName()) { - return "", nil + found, err := homesOf(db, scope, callType, callID). + Where("customer_id <> ?", customerID).Where("shard <> ?", r.store.ShardName()).Exists(ctx) + if err != nil { + return false, stack.Wrap(fmt.Errorf("store: call homes elsewhere: %w", err)) } - return shards[0], nil + return found, nil } // 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 b642b04539..a5390b07f4 100644 --- a/acceleration/internal/store/call_leg.go +++ b/acceleration/internal/store/call_leg.go @@ -131,6 +131,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 @@ -755,39 +758,232 @@ 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 { + 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 { + 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 ( + 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, in the shared database, one +// claim at a time from whichever shard: its legs are in 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 + +// 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 + +// 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) +} + +// 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 +} + +// 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 { + 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 } - own, err := countOpen(ctx, tx, leg.OrganizationID, leg.PlacedAt.Add(-atOnce.Ringing), "", "") - if err != nil { + return r.store.CallHomes.recordWith(ctx, global, leg.CustomerID, leg.StreamAppPK, leg.CallType, leg.CallID) + }) + if err != nil { + 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 +// 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, _, _ bun.IDB) error { + if err := hold(ctx); err != nil { + return errors.Join(ErrCallUnchecked, err) + } + return nil + }) +} + +// 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. 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)) + } + defer release() + ctx, cancel := context.WithTimeout(ctx, placingFor) + defer cancel() + app := on.Scope.App + if on.Scope.Unpinned { + app = 0 + } + err = r.store.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { + if err := lockUntilCommit(ctx, tx, strconv.FormatInt(app, 10)+":"+callType+":"+callID, callLockSeed); err != nil { return err } - room, err := r.store.OpenLegs.place(ctx, leg.OrganizationID, own.Total, atOnce.Limit) + if err := on.held(ctx, customerID); err != nil { + return err + } + 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 } - if !room { - return ErrCallsAtOnce + if owner != "" && owner != customerID { + return ErrCallTaken } - _, err = tx.NewInsert().Model(leg).Returning("id").Exec(ctx) - return err + if owner == "" { + elsewhere, err := r.store.CallHomes.anotherElsewhere(ctx, tx, on.Scope, callType, callID, customerID) + if err != nil { + return err + } + if elsewhere { + return ErrCallTaken + } + } + return keep(ctx, tx, shard) }) - if errors.Is(err, ErrCallsAtOnce) { - return stack.Wrap(ErrCallsAtOnce) + if err != nil { + return stack.Wrap(fmt.Errorf("store: claim call: %w", err)) + } + return nil +} + +// 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()) } +} + +// owner is the customer a call is, by its legs in this shard: those open, dialled or about to be, +// 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, shard bun.IDB, scope AppScope, callType, callID string) (string, error) { + var owners []string + 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 { + 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("COALESCE(dialed_at, placed_at), customer_id").Limit(1).Scan(ctx, &owners) 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: call owner: %w", err)) } - return r.store.CallHomes.record(ctx, leg.CustomerID, leg.StreamAppPK, leg.CallType, leg.CallID) + if len(owners) == 0 { + return "", nil + } + return owners[0], nil } // placing waits for this router's turn to count and place a call of organization, then for a diff --git a/acceleration/internal/store/call_leg_test.go b/acceleration/internal/store/call_leg_test.go index faa1a7bedb..3ca8d717f6 100644 --- a/acceleration/internal/store/call_leg_test.go +++ b/acceleration/internal/store/call_leg_test.go @@ -791,3 +791,559 @@ func (s *StoreSuite) TestADialNamingNoOrganizationKeepsTheOneTheCallWasPlacedUnd s.Equal("org", dialed.OrganizationID, "still counted among the organization's calls") } + +// 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, s.store.shard, scope, "agent", callID) + s.Require().NoError(err) + return owner +} + +// 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 }) +} + +// 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 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) +} + +// 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() { + 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) TestACallIsTheCustomersWhoseLegWasDialledOnItFirst() { + 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) + s.onCall("a", "tied", 0, s.base) + + 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, s.store.shard, AppScope{Unpinned: true}, "default", "call") + s.Require().NoError(err) + s.Empty(other, "a call of another type") +} + +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.NoError(s.places("other", "call", on, nil)) +} + +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) + s.Empty(kept) + s.ErrorIs(s.places("mine", "free", on, &CallsAtOnce{Limit: 0, Ringing: time.Hour}), ErrCallsAtOnce) +} + +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() { + router := s.ownRouter() + 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] = 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 + for _, err := range errs { + if err == nil { + in++ + continue + } + s.ErrorIs(err, ErrCallTaken) + } + s.Equal(1, in, "%v", errs) + } +} + +// 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)) + + 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) +} + +// claimsHere says a customer's session is on a call from a router of this shard, or how that is +// refused. +func (s *ShardedStoreSuite) claimsHere(customer, call string, scope AppScope) error { + return s.store.CallLegs.Claim(s.ctx, customer, "agent", call, NamedCall{Scope: scope}, func(context.Context) error { return nil }) +} + +// A call that lives in another shard is its customer's there: one who placed it, and one whose +// caller arrived, in the app it is in, the deployment's own pinned to its id or to none. +func (s *ShardedStoreSuite) TestACallThatLivesInAnotherShardIsItsCustomersThere() { + opened := func(call string, app int64) { + leg := CallLeg{CustomerID: "theirs", StreamAppPK: app, CallType: "agent", CallID: call, StreamSessionID: "session", Vendor: "telnyx", + Direction: Inbound, LocalNumber: "+15125550150", RemoteNumber: "+15125550151", DialedAt: s.base} + _, err := s.other.CallLegs.Open(s.ctx, &leg) + s.Require().NoError(err) + } + opened("arrived", 0) + opened("pinned", 1) + opened("own app", 7) + placed := time.Now() + s.Require().NoError(s.other.CallLegs.Place(s.ctx, &CallLeg{Token: newID(), CustomerID: "theirs", CallType: "agent", CallID: "placed", + Vendor: "telnyx", Direction: Outbound, LocalNumber: "+15125550150", RemoteNumber: "+15125550151", PlacedAt: &placed})) + + for _, call := range []string{"arrived", "pinned", "placed"} { + s.ErrorIs(s.claimsHere("mine", call, AppOf(0, 1)), ErrCallTaken, call) + s.ErrorIs(s.claimsHere("mine", call, AppOf(1, 1)), ErrCallTaken, call) + s.NoError(s.claimsHere("theirs", call, AppOf(0, 1)), call) + s.NoError(s.claimsHere("mine", call, AppOf(7, 1)), call) + } + s.ErrorIs(s.claimsHere("mine", "own app", AppOf(7, 1)), ErrCallTaken) + s.NoError(s.claimsHere("mine", "own app", AppOf(0, 1))) + s.NoError(s.claimsHere("mine", "another call", AppOf(0, 1))) + s.NoError(s.store.CallLegs.Claim(s.ctx, "mine", "default", "arrived", NamedCall{Scope: AppOf(0, 1)}, func(context.Context) error { return nil }), + "a call of another type") +} + +// A call's home in this shard says nothing its legs here do not: one nobody answered is anybody's. +func (s *ShardedStoreSuite) TestACallNobodyAnsweredInThisShardIsAnybodys() { + s.onCall("theirs", "call", 0, s.base) + _, err := s.store.CallLegs.EndCall(s.ctx, AppScope{Unpinned: true}, "agent", "call", s.base.Add(time.Minute)) + s.Require().NoError(err) + + s.NoError(s.claimsHere("mine", "call", AppOf(0, 1))) +} + +// A call in another shard is its customer's until its home is swept. +func (s *ShardedStoreSuite) TestACallInAnotherShardIsItsCustomersUntilItsHomeIsSwept() { + leg := CallLeg{CustomerID: "theirs", CallType: "agent", CallID: "call", Vendor: "telnyx", VendorCallID: "v", Direction: Outbound, + LocalNumber: "+15125550150", RemoteNumber: "+15125550151", DialedAt: s.base} + _, err := s.other.CallLegs.Open(s.ctx, &leg) + s.Require().NoError(err) + _, err = s.other.CallLegs.Sweep(s.ctx, time.Now().Add(7*time.Hour), 4*time.Hour, 10) + s.Require().NoError(err) + s.ErrorIs(s.claimsHere("mine", "call", AppOf(0, 1)), ErrCallTaken) + + _, err = s.other.CallLegs.Sweep(s.ctx, time.Now().Add(9*time.Hour), 4*time.Hour, 10) + s.Require().NoError(err) + s.NoError(s.claimsHere("mine", "call", AppOf(0, 1))) +} + +// Legs of the customer's own here settle whose the call is without its homes. +func (s *ShardedStoreSuite) TestACustomersOwnLegsHereAreEnoughToCallIntoThem() { + s.onCall("mine", "call", 0, s.base) + leg := CallLeg{CustomerID: "theirs", CallType: "agent", CallID: "call", Vendor: "telnyx", VendorCallID: "v", Direction: Outbound, + LocalNumber: "+15125550150", RemoteNumber: "+15125550151", DialedAt: s.base} + _, err := s.other.CallLegs.Open(s.ctx, &leg) + s.Require().NoError(err) + + s.NoError(s.claimsHere("mine", "call", AppOf(0, 1))) +} + +// 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() { + one, elsewhere := s.ownRouter(), s.ownRouter() + blocked := func(on NamedCall) (err error) { + unpinned := NamedCall{Scope: AppScope{Unpinned: true}} + 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.CallLegs.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, asked := false, 0 + on := NamedCall{Scope: AppScope{Unpinned: true}, Holder: func(context.Context) (string, error) { + // 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) +} + +// 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() { + 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) { + 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 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) + go func() { first <- place("one", waits) }() + 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}})) + + 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() { + 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 + began := time.Now() + for i := range 64 { + wg.Go(func() { + 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(): + 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(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) + 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") +} + +// 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) +} + +// 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) +} + +// 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) + } +} + +// 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) +} + +// 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") +} diff --git a/acceleration/internal/store/hooks.go b/acceleration/internal/store/hooks.go index cd0cdd4854..a6e926a216 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 fabcafb357..5f016809ab 100644 --- a/acceleration/internal/store/store_explain_test.go +++ b/acceleration/internal/store/store_explain_test.go @@ -485,6 +485,10 @@ func (s *StoreSuite) TestEveryHotTableIsReadByIndex() { _, err := store.CallLegs.Ringing(ctx, AppScope{App: 3}, "default", "stream-101") return err }}, + {name: "CallLegs.Claim", index: "call_legs_call_idx", run: func(ctx context.Context, store *Store) error { + _, 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 { _, err := store.CallLegs.HasParticipant(ctx, app, "default", "stream-100", "phone-100") return err