diff --git a/acceleration/internal/api/callhooks.go b/acceleration/internal/api/callhooks.go index 9f0994109e..1054bf3699 100644 --- a/acceleration/internal/api/callhooks.go +++ b/acceleration/internal/api/callhooks.go @@ -78,8 +78,10 @@ func (p callParticipant) phone() bool { // Every outcome short of something that did not come from Stream is a 200. Stream retries a // non-2xx, and none of the reasons this cannot place a call — no worker waiting, a call // belonging to nobody — get better on a second delivery, while the caller is on the line for -// the whole of it. The one exception is a phone's join or leave the database could not take: -// its minutes are lost unless Stream delivers it again, so it is answered 503. +// the whole of it. There are two exceptions, each answered 503. A phone's join or leave the +// database could not take: its minutes are lost unless Stream delivers it again. And a call +// that arrived moments ago which a shard that did not answer may have placed +// (arrivingCallRetryFor): dispatching it could put a second agent on the call. func (s *Server) receiveCallEvent(w http.ResponseWriter, r *http.Request) { if !s.hooksConfigured() { // Refusing is the only safe answer: without the secret there is no way to tell @@ -115,7 +117,9 @@ func (s *Server) receiveCallEvent(w http.ResponseWriter, r *http.Request) { writeError(w, invalidRequest("could not read that call event")) return } - s.dispatchArrivingCall(w, r, origin, event, payload) + if !s.dispatchArrivingCall(w, r, origin, event, payload) { + return + } case getstream.EventTypeCallSessionEnded: var event callEvent @@ -149,28 +153,45 @@ func (s *Server) receiveCallEvent(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } +// arrivingCallRetryFor is how long after Stream made a call.session_started a delivery whose +// call cannot yet be told apart from one the router placed is answered for Stream to deliver +// again. A caller left ringing rarely holds on past it, so a delivery later than that would +// put a worker on a call nobody is on. An event whose time cannot be read is not retried. +const arrivingCallRetryFor = 45 * time.Second + // dispatchArrivingCall works out whose call it is and hands it to one of their workers. A call // it refuses is still answered 200, so the refusal's code is noted on w for the activity record. -func (s *Server) dispatchArrivingCall(w http.ResponseWriter, r *http.Request, origin hookOrigin, event callEvent, payload []byte) { +// False is a call it could not yet tell what to do with, answered on w for Stream to deliver +// again. +func (s *Server) dispatchArrivingCall(w http.ResponseWriter, r *http.Request, origin hookOrigin, event callEvent, payload []byte) bool { callType, callID, split := strings.Cut(event.CallCid, ":") if !split { s.logger.Debug("a call event named no call", "cid", event.CallCid) - return + return true } if s.store == nil { - return + return true } // A call the router placed has its own worker already. Its leg comes in through the // number's routing rule, which names the number too, so it would look like a call to dial. placed, err := s.store.CallResources.Select(r.Context(), origin.scope(), callType, callID) if err != nil { - s.logger.Error("could not tell whether the router placed a call", "cid", event.CallCid, "error", err) - return + // A shard that did not answer may have placed it, and dispatching it would put a second + // agent on it. While the caller may still be ringing, Stream is told to deliver it again, + // and nothing has been acted on yet. Past that, a delivery that lands once the shard is + // back would send a worker to a call its caller has left, so it is dropped as before. + if at := eventTime(event.CreatedAt); !at.IsZero() && time.Since(at) <= arrivingCallRetryFor { + s.logger.Warn("could not tell whether the router placed a call, asking for it again", "cid", event.CallCid, "error", err) + writeError(w, unavailable("could not tell whose call this is")) + return false + } + s.logger.Error("dropped an arriving call: could not tell whether the router placed it", "cid", event.CallCid, "error", err) + return true } if len(placed) > 0 { s.logger.Debug("not dispatching a call the router placed", "cid", event.CallCid) - return + return true } // Only a call one of the numbers reaches is a phone call. Every video call in the app @@ -203,7 +224,7 @@ func (s *Server) dispatchArrivingCall(w http.ResponseWriter, r *http.Request, or } s.logger.Log(r.Context(), level, "no number reaches an arriving call", "call", event.CallCid, "stream_app", origin.app, "error", err) - return + return true } // In deployment mode the number is what says whose call it is. activity.NoteCustomer(r.Context(), number.CustomerID, activity.AreaHooksIn) @@ -232,7 +253,7 @@ func (s *Server) dispatchArrivingCall(w http.ResponseWriter, r *http.Request, or noteRefusal(w, codeTelephonySuspended) s.refuseArrivingCall(r.Context(), number, callType, callID, event.SessionID, "refused an arriving call to a suspended app", "call", event.CallCid, "customer", number.CustomerID, "error", err) - return + return true } // The vendor bills the minutes of a call an agent answers, and the agent is billed work, // so an organization that may not pay has nobody answer. @@ -241,12 +262,12 @@ func (s *Server) dispatchArrivingCall(w http.ResponseWriter, r *http.Request, or noteRefusal(w, answer.Code) s.refuseArrivingCall(r.Context(), number, callType, callID, event.SessionID, "refused an arriving call to an organization that may not pay for it", "call", event.CallCid, "customer", number.CustomerID, "code", answer.Code) - return + return true } // Only a call that rings a number is worth recording as delivered: every video call in // the app arrives here too. if !s.acting(r.Context(), origin, getstream.EventTypeCallSessionStarted, payload) { - return + return true } // A number with an agent never goes to a worker, even one waiting: the router answers // it on this node. @@ -255,18 +276,18 @@ func (s *Server) dispatchArrivingCall(w http.ResponseWriter, r *http.Request, or noteRefusal(w, errNoSessions.Code) s.refuseArrivingCall(r.Context(), number, callType, callID, event.SessionID, "refused an arriving call to a number with an agent on a router that runs no sessions", "call", event.CallCid, "customer", number.CustomerID, "number", number.E164, "config", number.ConfigID) - return + return true } // The agent joins before it is answering, which can outlast Stream's wait for the // hook: answered late, Stream delivers again while the agent joins. go s.answerWithAgent(context.WithoutCancel(r.Context()), s.sessions, origin, event, number, callType, callID) - return + return true } if s.dispatch == nil { - return + return true } if elsewhere, _ := s.forwardedToWorkers(r.Context(), s.replayed(r, payload), number.CustomerID, dispatch.Calls); elsewhere { - return + return true } call := dispatch.Call{ @@ -291,7 +312,7 @@ func (s *Server) dispatchArrivingCall(w http.ResponseWriter, r *http.Request, or noteRefusal(w, unavailable("").Code) s.refuseArrivingCall(r.Context(), number, callType, callID, event.SessionID, "refused an arriving call no worker could take", "call", event.CallCid, "customer", number.CustomerID, "number", number.E164) - return + return true } s.pinHook(origin, number.CustomerID, event.CallCid) s.logger.Info("handed an arriving call to a worker", @@ -302,6 +323,7 @@ func (s *Server) dispatchArrivingCall(w http.ResponseWriter, r *http.Request, or arrived = append(arrived, "session_id", call.SessionID) } s.logger.Info("arriving call sites", arrived...) + return true } // answerWithAgent opens a session of the number's agent on the arriving call. It ends on its diff --git a/acceleration/internal/api/callhooks_test.go b/acceleration/internal/api/callhooks_test.go index bf14fbef3f..b4451be940 100644 --- a/acceleration/internal/api/callhooks_test.go +++ b/acceleration/internal/api/callhooks_test.go @@ -4,6 +4,7 @@ package api import ( "bytes" + "cmp" "context" "crypto/ed25519" "crypto/hmac" @@ -14,6 +15,7 @@ import ( "maps" "net" "net/http" + "net/http/httptest" "strings" "testing" "time" @@ -494,6 +496,75 @@ func (s *CallHooksSuite) TestAnArrivingCallToANumberIsStillDispatched() { } } +// A peer shard that is down may have placed the call, so the delivery is answered for Stream +// to make again, and nothing was acted on: delivered again once every shard answers, it is +// dispatched. +func (s *CallHooksSuite) TestAnArrivingCallAShardThatIsDownMayHavePlacedIsDeliveredAgain() { + s.hold("default", s.callID) + worker, release := s.dispatch.Register(s.customerID(), dispatch.Registration{Capacity: 1}) + defer release() + other := s.nodeWithAShardDown() + + body := s.ringingNumberAt("default", time.Now().UTC()) + s.Equal(http.StatusServiceUnavailable, s.signedlyTo(other, "/v1/phone/hooks/stream", body)) + s.nothingReaches(worker.Calls(), "a call a shard that is down may have placed was dispatched") + + s.Require().Equal(http.StatusOK, s.signedly("/v1/phone/hooks/stream", body)) + select { + case call := <-worker.Calls(): + s.Equal(s.callID, call.CallID) + case <-time.After(settleFor): + s.Fail("the call delivered again never reached the worker") + } +} + +// Past arrivingCallRetryFor, a delivery that lands once the shard is back would send a worker to +// a call its caller has left, so it is answered and dropped. +func (s *CallHooksSuite) TestAnOldArrivingCallAShardThatIsDownMayHavePlacedIsDropped() { + s.hold("default", s.callID) + worker, release := s.dispatch.Register(s.customerID(), dispatch.Registration{Capacity: 1}) + defer release() + other := s.nodeWithAShardDown() + + body := s.ringingNumberAt("default", time.Now().UTC().Add(-2*arrivingCallRetryFor)) + s.Equal(http.StatusOK, s.signedlyTo(other, "/v1/phone/hooks/stream", body)) + s.nothingReaches(worker.Calls(), "a call long past ringing was dispatched") + s.Eventually(func() bool { return strings.Contains(s.thisTest(), "dropped an arriving call") }, settleFor, 10*time.Millisecond) +} + +// nodeWithAShardDown is another node on the suite's databases whose peer shard is down: nothing +// answers on port 1. +func (s *CallHooksSuite) nodeWithAShardDown() *httptest.Server { + options := s.storeOptions + options.Shards = map[string]string{ + "here": cmp.Or(options.ShardDSN, options.DSN), "gone": "postgres://postgres:postgres@127.0.0.1:1/gone?sslmode=disable", + } + served, err := store.OpenShards(options) + s.Require().NoError(err) + s.T().Cleanup(func() { s.NoError(served.Close()) }) + logger := slog.New(NewLogHandler(slog.NewTextHandler(s.logs, &slog.HandlerOptions{Level: slog.LevelDebug, ReplaceAttr: store.RedactLogAttr}))) + other, _, _ := s.otherNodeServingFrom(served, nil, s.sealer, logger) + return other +} + +// signedlyTo is signedly to another node. +func (s *CallHooksSuite) signedlyTo(other *httptest.Server, path, body string) int { + request, err := http.NewRequest(http.MethodPost, other.URL+path, bytes.NewReader([]byte(body))) + s.Require().NoError(err) + request.Header.Set("Content-Type", "application/json") + request.Header.Set(signatureHeader, sign(body, suiteStreamSecret)) + response, err := other.Client().Do(request) + s.Require().NoError(err) + s.Require().NoError(response.Body.Close()) + return response.StatusCode +} + +// ringingNumberAt is ringingNumber made by Stream at at. +func (s *CallHooksSuite) ringingNumberAt(callType string, at time.Time) string { + return strings.Replace(arrivingCallAt(callType+":"+s.callID, at), + `"custom": {"line": "support"}`, fmt.Sprintf(`"custom": {"line": "support", "phone_number": %q}`, s.e164), 1) +} + func (s *CallHooksSuite) TestAnArrivingCallToANumberWithAnAgentIsAnsweredByIt() { s.answerable() s.numberTags = map[string]string{"line": "support", "team": "number"} diff --git a/acceleration/internal/api/phone.go b/acceleration/internal/api/phone.go index d981116f39..1ff90095e2 100644 --- a/acceleration/internal/api/phone.go +++ b/acceleration/internal/api/phone.go @@ -483,6 +483,11 @@ func (s *Server) answerPhoneCall(w http.ResponseWriter, r *http.Request) { // The vendor is about to bridge a live call to nowhere, so this is worth a log // line even though there is nobody to return the detail to. logger.Error("could not answer a placed call", "error", err) + // The vendor fetches again on a 5xx, by when the shard holding the bridge may answer. + if errors.Is(err, store.ErrShardUnanswered) { + writeError(w, unavailable("could not read the call's plan, try again")) + return + } writeError(w, notFound("that call is not waiting to be answered")) return } diff --git a/acceleration/internal/api/router_suite_test.go b/acceleration/internal/api/router_suite_test.go index c30b04d617..5e6d9a2e32 100644 --- a/acceleration/internal/api/router_suite_test.go +++ b/acceleration/internal/api/router_suite_test.go @@ -211,6 +211,8 @@ type RouterSuite struct { configs *store.Store live *live.Client sealer *auth.Sealer + // storeOptions are what the suite's store was opened with, for a node on the same databases. + storeOptions store.Options // activity is the activity record every node of the suite counts in. activity *activity.Recorder // manager runs the suite's sessions, for a test about what ends them from inside. @@ -588,6 +590,7 @@ func (s *RouterSuite) SetupSuite() { if shardDSN := os.Getenv("ROUTER_POSTGRES_SHARD_DSN"); shardDSN != "" { options.ShardDSN = testDatabase(s.T(), shardDSN) } + s.storeOptions = options pgStore, err := store.OpenShards(options) s.Require().NoError(err) pgStore.GlobalDB().SetMaxOpenConns(suiteConnections) diff --git a/acceleration/internal/api/shard_down_test.go b/acceleration/internal/api/shard_down_test.go new file mode 100644 index 0000000000..a3b392a6f9 --- /dev/null +++ b/acceleration/internal/api/shard_down_test.go @@ -0,0 +1,39 @@ +//go:build integration + +package api + +import ( + "cmp" + "log/slog" + "net/http" + + "github.com/GetStream/Vision-Agents/acceleration/internal/phone" + "github.com/GetStream/Vision-Agents/acceleration/internal/phone/vendors" + "github.com/GetStream/Vision-Agents/acceleration/internal/store" +) + +// A vendor fetching a plan while a shard that may park it is down is told to fetch again, not +// that the call is not waiting: the bridge may be on that shard. +func (s *CallStatusSuite) TestAPlanFetchWhileAShardIsDownIsAnsweredForTheVendorToRetry() { + s.useApp(s.data.createApp()) + options := s.storeOptions + // Nothing answers on port 1. + options.Shards = map[string]string{ + "here": cmp.Or(options.ShardDSN, options.DSN), "gone": "postgres://postgres:postgres@127.0.0.1:1/gone?sslmode=disable", + } + served, err := store.OpenShards(options) + s.Require().NoError(err) + s.T().Cleanup(func() { s.NoError(served.Close()) }) + config, err := phone.DefaultConfig() + s.Require().NoError(err) + telephony, err := phone.NewService(phone.ServiceOptions{Registry: vendors.Registry(config), Store: served, Logger: slog.New(slog.DiscardHandler)}) + s.Require().NoError(err) + other, _, _ := s.otherNodeHolding(nil, s.sealer, slog.New(slog.DiscardHandler), func(o *Options) { + o.Store, o.Phone = served, telephony + }) + + token := s.utils.uuid() + s.Equal(http.StatusServiceUnavailable, s.unauthenticatedClient.on(other).do(http.MethodGet, "/v1/phone/answer/"+token, nil, nil)) + s.Equal(http.StatusNotFound, s.unauthenticatedClient.do(http.MethodGet, "/v1/phone/answer/"+token, nil, nil), + "with every shard answering, it is not waiting") +} diff --git a/acceleration/internal/session/manager.go b/acceleration/internal/session/manager.go index b201465833..12c74bc3a0 100644 --- a/acceleration/internal/session/manager.go +++ b/acceleration/internal/session/manager.go @@ -408,6 +408,7 @@ func (m *Manager) channelTeam(ctx context.Context, spec Spec) (string, error) { // session would hold a model session and a place in a call that nobody holds a handle to. func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure error) { began := time.Now() + generated := spec.ID == "" if err := spec.Normalize(); err != nil { return nil, stack.Wrap(err) } @@ -445,8 +446,9 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er } // The id is the row's primary key whoever owns it, so one somebody already used would // write this session over theirs. A reopened one is the same session, its owner checked - // by whoever reopened it. - if m.options.Store != nil && spec.Reopened.IsZero() { + // by whoever reopened it. One generated just now is a UUIDv7 nobody has, and asking every + // shard about it would refuse the session whenever any one of them is down. + if m.options.Store != nil && spec.Reopened.IsZero() && !generated { taken, err := m.options.Store.Sessions.Exists(ctx, spec.ID) if err != nil { return nil, stack.Wrap(err) @@ -490,7 +492,7 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er // The Stream app the session acts in is settled once, before anything is done there, // and the whole session keeps it: its call, its transcript and the rows it writes. - stream, err := m.stream(ctx, spec) + stream, err := m.stream(ctx, spec, generated && spec.ownCall) if err != nil { return nil, err } @@ -2139,7 +2141,10 @@ func (m *Manager) guardrail(ctx context.Context, spec Spec, stream streamapp.Ide // stream is the Stream app a new session acts in. A deployment with no Stream app still // holds a text conversation, so having none is not an error here: what needs one fails // where it needs it. -func (m *Manager) stream(ctx context.Context, spec Spec) (streamapp.Bound, error) { +// +// newCall is a call named after an id generated for this session, which no line can have been +// made for yet, so no shard is asked about its lines. +func (m *Manager) stream(ctx context.Context, spec Spec, newCall bool) (streamapp.Bound, error) { nowhere := streamapp.Bound{Identity: streamapp.Identity{CustomerID: spec.CustomerID}} if m.options.Stream == nil { return nowhere, nil @@ -2154,7 +2159,7 @@ func (m *Manager) stream(ctx context.Context, spec Spec) (streamapp.Bound, error } // A call that already has lines, a number's or a placed call's, is in the app they were // made in, and the agent has to join it there. - if m.options.Store != nil && spec.CallID != "" && !spec.Text { + if m.options.Store != nil && spec.CallID != "" && !spec.Text && !newCall { pin, found, err := m.options.Store.CallResources.Pin(ctx, spec.CustomerID, spec.CallType, spec.CallID) if err != nil { return streamapp.Bound{}, err diff --git a/acceleration/internal/session/shard_down_test.go b/acceleration/internal/session/shard_down_test.go new file mode 100644 index 0000000000..d2b9c0a0cd --- /dev/null +++ b/acceleration/internal/session/shard_down_test.go @@ -0,0 +1,124 @@ +//go:build integration + +package session + +import ( + "context" + "log/slog" + "os" + "testing" + + "github.com/google/uuid" + "github.com/stretchr/testify/suite" + + "github.com/GetStream/Vision-Agents/acceleration/internal/agent" + "github.com/GetStream/Vision-Agents/acceleration/internal/conversation/chattest" + "github.com/GetStream/Vision-Agents/acceleration/internal/llm/llmtest" + "github.com/GetStream/Vision-Agents/acceleration/internal/routing" + "github.com/GetStream/Vision-Agents/acceleration/internal/store" + "github.com/GetStream/Vision-Agents/acceleration/internal/streamapp" + "github.com/GetStream/Vision-Agents/acceleration/internal/stt" + "github.com/GetStream/Vision-Agents/acceleration/internal/sttrouter" + "github.com/GetStream/Vision-Agents/acceleration/internal/testenv" + "github.com/GetStream/Vision-Agents/acceleration/internal/tts" + "github.com/GetStream/Vision-Agents/acceleration/internal/ttsrouter" +) + +// ShardDownSuite opens sessions on a router whose peer shard's database is down. +type ShardDownSuite struct { + suite.Suite + ctx context.Context + db *store.Store + manager *Manager +} + +func TestShardDownSuite(t *testing.T) { + suite.Run(t, new(ShardDownSuite)) +} + +func (s *ShardDownSuite) SetupSuite() { + dsn := os.Getenv("ROUTER_POSTGRES_DSN") + if dsn == "" { + s.T().Skip("ROUTER_POSTGRES_DSN is not set") + } + s.ctx = context.Background() + own := testenv.Database(dsn, "shard_down") + migrated, err := store.Open(own) + s.Require().NoError(err) + s.Require().NoError(migrated.Migrate(s.ctx)) + s.Require().NoError(migrated.Close()) + + // Nothing answers on port 1: the peer's dial is refused at once. + db, err := store.OpenShards(store.Options{DSN: own, Shards: map[string]string{ + "here": own, "gone": "postgres://postgres:postgres@127.0.0.1:1/gone?sslmode=disable", + }}) + s.Require().NoError(err) + s.T().Cleanup(func() { s.Require().NoError(db.Close()) }) + s.db = db + + manager, err := NewManager(ManagerOptions{ + LLM: screenedBy(&s.Suite, stubConfig(), &llmtest.Thinker{Answer: "Sure."}), + Store: db, + Logger: slog.New(slog.DiscardHandler), + Edge: func(context.Context, Spec, streamapp.Bound, *slog.Logger) (agent.Edge, error) { + return newQuietEdge(), nil + }, + }) + s.Require().NoError(err) + s.T().Cleanup(func() { _ = manager.Shutdown() }) + s.manager = manager +} + +func (s *ShardDownSuite) TestASessionWithAnIdTheRouterGeneratesOpens() { + created, err := s.manager.Create(s.ctx, Spec{Text: true, CustomerID: "shard-down-" + uuid.NewString(), LLMTarget: "en-low-latency"}) + s.Require().NoError(err) + s.NotEmpty(created.ID()) + s.Require().NoError(created.Close()) +} + +// The id a caller chose may be another session's on the shard that is down, so it is not +// taken on trust. +func (s *ShardDownSuite) TestASessionWithAnIdTheCallerChoseIsNotOpened() { + _, err := s.manager.Create(s.ctx, Spec{ID: uuid.NewString(), Text: true, CustomerID: "shard-down-" + uuid.NewString(), LLMTarget: "en-low-latency"}) + s.Require().Error(err) + s.NotErrorIs(err, ErrSessionExists) +} + +// A voice session given no call holds its own, named after the id generated for it, which no +// line can have been made for: no shard is asked which app its lines are in. +func (s *ShardDownSuite) TestAVoiceSessionWithAnIdTheRouterGeneratesOpensItsOwnCall() { + logger := slog.New(slog.DiscardHandler) + transcription := sttrouter.NewRegistry() + transcription.Register("stub", func(routing.Spec) (stt.STT, error) { return &stubSTT{emitter: stt.NewEmitter(64)}, nil }) + transcriber, err := sttrouter.New(sttrouter.Options{Config: stubConfig(), Registry: transcription, Logger: logger}) + s.Require().NoError(err) + s.T().Cleanup(transcriber.Close) + speech := ttsrouter.NewRegistry() + speech.Register("stub", func(routing.Spec) (tts.TTS, error) { return &stubTTS{emitter: tts.NewEmitter(64)}, nil }) + speaker, err := ttsrouter.New(ttsrouter.Options{Config: stubConfig(), Registry: speech, Logger: logger}) + s.Require().NoError(err) + s.T().Cleanup(speaker.Close) + chat := chattest.NewServer(s.T()) + apps := streamapp.NewClients(streamapp.NewDeployment(streamapp.DeploymentOptions{ + APIKey: streamKey, Secret: "deploy-secret", BaseURL: chat.URL, App: suiteDeploymentApp, + }), streamapp.ClientsOptions{}) + manager, err := NewManager(ManagerOptions{ + LLM: screenedBy(&s.Suite, stubConfig(), &llmtest.Thinker{Answer: "Sure."}), + STT: transcriber, + TTS: speaker, + Store: s.db, + Stream: apps, + Logger: logger, + Edge: func(context.Context, Spec, streamapp.Bound, *slog.Logger) (agent.Edge, error) { + return newQuietEdge(), nil + }, + }) + s.Require().NoError(err) + s.T().Cleanup(func() { _ = manager.Shutdown() }) + + created, err := manager.Create(s.ctx, Spec{CustomerID: "shard-down-" + uuid.NewString(), LLMTarget: "en-low-latency", + STTTarget: "en-low-latency", TTSTarget: "en-low-latency"}) + s.Require().NoError(err) + s.Equal(created.ID(), created.Spec().CallID) + s.Require().NoError(created.Close()) +} diff --git a/acceleration/internal/store/call_bridge.go b/acceleration/internal/store/call_bridge.go index 76c6192212..469dd952cb 100644 --- a/acceleration/internal/store/call_bridge.go +++ b/acceleration/internal/store/call_bridge.go @@ -87,7 +87,9 @@ func (r *CallBridges) Claim(ctx context.Context, token string) (CallBridge, erro } // The vendor's fetch lands on whichever shard is nearest it, not the one that parked it. - lists, err := everyShard(ctx, r.store, func(ctx context.Context, db bun.IDB) ([]CallBridge, error) { + // The bridge is on one shard, and its delete there is done whatever the others answer, so + // a shard that did not answer fails the claim only when no other shard held it. + lists, failed := answeringShards(ctx, r.store, "claim bridge", claimReadTimeout, func(claimed []CallBridge) bool { return len(claimed) > 0 }, func(ctx context.Context, db bun.IDB) ([]CallBridge, error) { var claimed []CallBridge err := db.NewDelete().Model((*CallBridge)(nil)). Where("token_hash = ?", callTokenHash(token)). @@ -96,16 +98,16 @@ func (r *CallBridges) Claim(ctx context.Context, token string) (CallBridge, erro Scan(ctx, &claimed) return claimed, err }) - if err != nil { - return CallBridge{}, stack.Wrap(fmt.Errorf("store: claim bridge: %w", err)) - } claimed := slices.Concat(lists...) - if len(claimed) == 0 { - // One message for a token that never existed, one that has been used and one that - // has expired: telling them apart would say whether a guessed token was ever real. - return CallBridge{}, stack.Wrap(errors.New("store: that bridge is not waiting to be claimed")) + if len(claimed) > 0 { + return claimed[0], nil + } + if err := errors.Join(failed...); err != nil { + return CallBridge{}, stack.Wrap(fmt.Errorf("store: claim bridge: %w: %w", ErrShardUnanswered, err)) } - return claimed[0], nil + // One message for a token that never existed, one that has been used and one that has + // expired: telling them apart would say whether a guessed token was ever real. + return CallBridge{}, stack.Wrap(errors.New("store: that bridge is not waiting to be claimed")) } // Sweep removes bridges nobody claimed, which is what a call that rang out leaves behind. diff --git a/acceleration/internal/store/call_resource.go b/acceleration/internal/store/call_resource.go index a409ac0e92..499ec34317 100644 --- a/acceleration/internal/store/call_resource.go +++ b/acceleration/internal/store/call_resource.go @@ -130,9 +130,14 @@ func (r *CallResources) Forget(ctx context.Context, resource CallResource) error return nil } -// Select is what Release would delete for one call, read without deleting it. +// Select is a call's lines, read without deleting them: those of the first shard found to hold +// any, which is the shard that placed the call. It answers whether the router placed a call and +// whose it is, not everything Release would delete. +// +// A call's lines are on the shard that placed it, so rows from one shard settle it while +// another does not answer; with no rows, a shard that did not answer may hold them. func (r *CallResources) Select(ctx context.Context, scope AppScope, callType, callID string) ([]CallResource, error) { - lists, err := everyShard(ctx, r.store, func(ctx context.Context, db bun.IDB) ([]CallResource, error) { + lists, failed := answeringShards(ctx, r.store, "call resources", peerReadTimeout, func(resources []CallResource) bool { return len(resources) > 0 }, func(ctx context.Context, db bun.IDB) ([]CallResource, error) { var resources []CallResource err := db.NewSelect().Model(&resources). Where("call_type = ?", callType). @@ -141,10 +146,14 @@ func (r *CallResources) Select(ctx context.Context, scope AppScope, callType, ca Scan(ctx) return resources, err }) - if err != nil { + resources := slices.Concat(lists...) + if len(resources) > 0 { + return resources, nil + } + if err := errors.Join(failed...); err != nil { return nil, stack.Wrap(fmt.Errorf("store: call resources: %w", err)) } - return slices.Concat(lists...), nil + return nil, nil } // Pin is the Stream app a customer's call has its lines in: the app the trunk carrying it diff --git a/acceleration/internal/store/shard_down_test.go b/acceleration/internal/store/shard_down_test.go new file mode 100644 index 0000000000..ca1ef9fc31 --- /dev/null +++ b/acceleration/internal/store/shard_down_test.go @@ -0,0 +1,183 @@ +//go:build integration + +package store + +import ( + "bytes" + "context" + "errors" + "log/slog" + "net" + "strings" + "sync" + "time" + + "github.com/uptrace/bun" +) + +// goneShardDSN is a shard whose database nothing answers on: the dial is refused at once. +const goneShardDSN = "postgres://postgres:postgres@127.0.0.1:1/gone?sslmode=disable" + +// withAShardDown is a store on the suite's databases beside a peer shard that is down, and +// what it logs. +func (s *StoreSuite) withAShardDown() (*Store, *syncBuffer) { + down, err := OpenShards(Options{DSN: s.dsn, ShardDSN: s.shardDSN, Shards: map[string]string{"here": s.shardDSN, "gone": goneShardDSN}}) + s.Require().NoError(err) + s.T().Cleanup(func() { s.NoError(down.Close()) }) + + logged := &syncBuffer{} + before := slog.Default() + slog.SetDefault(slog.New(slog.NewTextHandler(logged, nil))) + s.T().Cleanup(func() { slog.SetDefault(before) }) + return down, logged +} + +func (s *StoreSuite) TestABridgeOnAShardThatAnswersIsClaimedWhileAnotherIsDown() { + down, _ := s.withAShardDown() + token := newID() + s.Require().NoError(s.store.CallBridges.Insert(s.ctx, &CallBridge{Token: token, CustomerID: "acme", Vendor: "plivo", + TrunkURI: "sip:x@example.com", CallID: "call", ExpiresAt: time.Now().Add(time.Hour)})) + + claimed, err := down.CallBridges.Claim(s.ctx, token) + s.Require().NoError(err) + s.Equal("sip:x@example.com", claimed.TrunkURI) + _, err = down.CallBridges.Claim(s.ctx, token) + s.Error(err, "a token still works once") +} + +func (s *StoreSuite) TestABridgeNoAnsweringShardHoldsIsNotClaimedWhileAnotherIsDown() { + down, _ := s.withAShardDown() + + _, err := down.CallBridges.Claim(s.ctx, newID()) + s.Require().ErrorIs(err, ErrShardUnanswered, "the shard that is down may hold it") + _, err = s.store.CallBridges.Claim(s.ctx, newID()) + s.Require().Error(err) + s.NotErrorIs(err, ErrShardUnanswered, "with every shard answering, it is not there") +} + +func (s *StoreSuite) TestACallPlacedOnAShardThatAnswersIsFoundWhileAnotherIsDown() { + down, _ := s.withAShardDown() + callID := newID() + s.Require().NoError(s.store.CallResources.Insert(s.ctx, &CallResource{ + TrunkID: "trunk-1", RouteID: "route-1", CallType: "default", CallID: callID, CustomerID: "acme", + })) + + placed, err := down.CallResources.Select(s.ctx, AppScope{Unpinned: true}, "default", callID) + s.Require().NoError(err) + s.Require().Len(placed, 1) + s.Equal("trunk-1", placed[0].TrunkID) + +} + +func (s *StoreSuite) TestACallNoAnsweringShardPlacedIsNotAnsweredWhileAnotherIsDown() { + down, _ := s.withAShardDown() + + placed, err := down.CallResources.Select(s.ctx, AppScope{Unpinned: true}, "default", newID()) + s.Require().Error(err, "the shard that is down may have placed it") + s.Empty(placed) +} + +// withAShardThatNeverAnswers is a store on the suite's databases beside a peer shard whose +// host accepts a connection and then says nothing, as a partitioned one can. +func (s *StoreSuite) withAShardThatNeverAnswers() *Store { + silent, err := net.Listen("tcp", "127.0.0.1:0") + s.Require().NoError(err) + var held []net.Conn + var mu sync.Mutex + go func() { + for { + conn, err := silent.Accept() + if err != nil { + return + } + mu.Lock() + held = append(held, conn) + mu.Unlock() + } + }() + s.T().Cleanup(func() { + _ = silent.Close() + mu.Lock() + defer mu.Unlock() + for _, conn := range held { + _ = conn.Close() + } + }) + dsn := "postgres://postgres:postgres@" + silent.Addr().String() + "/silent?sslmode=disable" + down, err := OpenShards(Options{DSN: s.dsn, ShardDSN: s.shardDSN, Shards: map[string]string{"here": s.shardDSN, "silent": dsn}}) + s.Require().NoError(err) + s.T().Cleanup(func() { s.NoError(down.Close()) }) + return down +} + +func (s *StoreSuite) TestACallPlacedOnAShardThatAnswersIsFoundWithoutWaitingOnOneThatDoesNot() { + down := s.withAShardThatNeverAnswers() + callID := newID() + s.Require().NoError(s.store.CallResources.Insert(s.ctx, &CallResource{ + TrunkID: "trunk-1", RouteID: "route-1", CallType: "default", CallID: callID, CustomerID: "acme", + })) + + began := time.Now() + placed, err := down.CallResources.Select(s.ctx, AppScope{Unpinned: true}, "default", callID) + s.Require().NoError(err) + s.Len(placed, 1) + s.Less(time.Since(began), peerReadTimeout, "the answer that settled it was not held for the silent shard") +} + +func (s *StoreSuite) TestABridgeNoShardHoldsIsRefusedOnceASilentShardRunsOutOfTime() { + down := s.withAShardThatNeverAnswers() + + began := time.Now() + _, err := down.CallBridges.Claim(s.ctx, newID()) + s.Require().Error(err) + s.Less(time.Since(began), claimReadTimeout+time.Second, "the silent shard was waited on past its read's bound") +} + +// A shard that failed before the answer settled the read is logged, once a minute; one the +// settle cut off is not, since it was not known to be down. +func (s *StoreSuite) TestOnlyAShardThatFailedBeforeTheReadSettledIsLogged() { + down, logged := s.withAShardDown() + failedFirst := func(ctx context.Context, db bun.IDB) (bool, error) { + if db == bun.IDB(down.shard) { + time.Sleep(50 * time.Millisecond) + return true, nil + } + return false, errors.New("refused") + } + for range 2 { + _, failed := answeringShards(s.ctx, down, "test", peerReadTimeout, func(ok bool) bool { return ok }, failedFirst) + s.Error(failed[1]) + } + s.Equal(1, strings.Count(logged.String(), "shard=gone"), "logged, and once a minute rather than on every read") + + cutOff := &syncBuffer{} + slog.SetDefault(slog.New(slog.NewTextHandler(cutOff, nil))) + _, failed := answeringShards(s.ctx, down, "test", peerReadTimeout, func(ok bool) bool { return ok }, + func(ctx context.Context, db bun.IDB) (bool, error) { + if db == bun.IDB(down.shard) { + return true, nil + } + <-ctx.Done() + return false, ctx.Err() + }) + s.NoError(failed[1], "a read still running when the answer settled is not waited for") + s.NotContains(cutOff.String(), "shard=", "a read the settle cut off is not logged") +} + +// syncBuffer is a log the store's other goroutines may write to at the same time. +type syncBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *syncBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *syncBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} diff --git a/acceleration/internal/store/shards.go b/acceleration/internal/store/shards.go index 10a177cc0b..d734a79b53 100644 --- a/acceleration/internal/store/shards.go +++ b/acceleration/internal/store/shards.go @@ -7,9 +7,11 @@ import ( "database/sql" "encoding/hex" "errors" + "log/slog" "maps" "slices" "sync" + "time" "github.com/redis/rueidis/rueidishook" "github.com/uptrace/bun" @@ -126,6 +128,103 @@ func everyShard[T any](ctx context.Context, s *Store, read func(context.Context, return found, nil } +// ErrShardUnanswered is a read no shard that answered could settle while another did not: the +// row may be on that one, so asking again once it answers may find it. +var ErrShardUnanswered = errors.New("store: a shard that may hold it did not answer") + +// peerReadTimeout bounds a read of another shard's database that one shard's answer can settle +// (answeringShards). Each is one indexed lookup, answered in milliseconds by a peer that is up, +// even across regions. A peer partitioned away would otherwise hold the caller for pgdriver's +// 5 s dial timeout, or its 10 s read timeout on a host that accepts and never answers, and the +// callers here are a vendor and Stream waiting on a call. +const peerReadTimeout = 2 * time.Second + +// claimReadTimeout bounds a bridge claim's read of another shard, longer than peerReadTimeout. +// The claim deletes what it reads, and a peer that commits the delete after the caller stopped +// waiting has spent the bridge with nobody to hand it to. The longer bound narrows that to a +// peer slower than pgdriver's own 5 s dial timeout, which is one that is down; a vendor's fetch +// is one per answered call, so holding a peer connection that long is not load. +const claimReadTimeout = 5 * time.Second + +// answeringShards reads every shard's database at once, as everyShard does, for a read one +// shard's answer can settle: it returns what each shard answered and, apart, how each that +// did not answer failed, this shard's first. A shard down then costs only what is on it. +// +// Another shard's read is given bound. Once an answer settles the read, the others are +// cancelled and not waited for, so a slow peer gives its pool connection back at once: their +// entries stay zero. Each shard that failed before the answer settled is logged +// (settledWithout); one cut off by the settle is not known to be down, and a shard that is +// down fails the reads that do need it. +func answeringShards[T any](ctx context.Context, s *Store, read string, bound time.Duration, settles func(T) bool, query func(context.Context, bun.IDB) (T, error)) ([]T, []error) { + all := s.shards() + found := make([]T, len(all)) + failed := make([]error, len(all)) + ctx, cancel := context.WithCancel(ctx) + defer cancel() + type answer struct { + shard int + found T + err error + } + // Buffered for every shard, so a read still running when the answer is settled finishes + // into it rather than waiting on a reader that has gone. + answers := make(chan answer, len(all)) + for i, db := range all { + go func() { + readCtx := ctx + if i > 0 { + var stop context.CancelFunc + readCtx, stop = context.WithTimeout(ctx, bound) + defer stop() + } + found, err := query(readCtx, db) + answers <- answer{shard: i, found: found, err: err} + }() + } + for range all { + got := <-answers + found[got.shard], failed[got.shard] = got.found, got.err + if got.err != nil || !settles(got.found) { + continue + } + for shard, err := range failed { + s.settledWithout(ctx, read, shard, err) + } + break + } + return found, failed +} + +// settledWithout logs a shard that failed a read the others' answers settled, at most once a +// minute a shard: a shard that is down fails every call's reads until it is back. A read the +// caller cancelled says nothing of its shard. +func (s *Store) settledWithout(ctx context.Context, read string, shard int, err error) { + if err != nil && !errors.Is(err, context.Canceled) && s.shardsDown.due(s.shardNames[shard], time.Now()) { + slog.Default().WarnContext(ctx, "a shard did not answer, settled on the others", "read", read, "shard", s.shardNames[shard], "error", err) + } +} + +// shardWarnings is when each shard was last logged as not answering. Its keys are the shards' +// names, so it holds at most one entry a shard. +type shardWarnings struct { + mu sync.Mutex + last map[string]time.Time +} + +// due reports whether shard may be logged at now, and counts it as logged if so. +func (w *shardWarnings) due(shard string, now time.Time) bool { + w.mu.Lock() + defer w.mu.Unlock() + if last, ok := w.last[shard]; ok && now.Sub(last) < time.Minute { + return false + } + if w.last == nil { + w.last = map[string]time.Time{} + } + w.last[shard] = now + return true +} + // whicheverShard reads a row from the shard holding it: this one first, where the row almost // always is, then the others. read answers sql.ErrNoRows for a shard without it, and so does // whicheverShard when no shard has it. diff --git a/acceleration/internal/store/store.go b/acceleration/internal/store/store.go index 8e32dc8efb..0b423d3062 100644 --- a/acceleration/internal/store/store.go +++ b/acceleration/internal/store/store.go @@ -53,6 +53,8 @@ type Store struct { // shardNames names each of shards(), as Options.Shards does, for what is kept per shard // in the shared database. shardNames []string + // shardsDown is when each shard that did not answer was last logged (settledWithout). + shardsDown shardWarnings // globalIsShard says the shared database is also some shard's own, so its calls are not // strays to drop. globalIsShard bool