Skip to content
Merged
58 changes: 40 additions & 18 deletions acceleration/internal/api/callhooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should Fix] Peer-shard outage answers 503 to every video call start
Issue: While a peer shard is down, every call.session_started in the app, video calls included, is answered 503 for 45 seconds after the call's created_at. Stream retries webhooks for calls no phone number reaches.
Cause: dispatchArrivingCall runs CallResources.Select at line 178, before the number lookup at line 203. The error branch at 184-188 returns 503. At ce41c39 a Select error was logged and answered 200.
Fix: Look up the number first and return the 503 only when a number reaches the call. Otherwise keep the log-and-200. Or: keep the order and accept the 503 on video calls, which costs retry traffic on calls that never involve telephony.

Evidence
  • callhooks.go:178 Select runs for every call.session_started
  • callhooks.go:184-188 a Select error within 45s of created_at returns false, which answers 503
  • callhooks.go:203-210 number lookup comes after Select
  • git show ce41c39: a Select error was logged and answered 200

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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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.
Expand All @@ -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.
Expand All @@ -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{
Expand All @@ -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",
Expand All @@ -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
Expand Down
71 changes: 71 additions & 0 deletions acceleration/internal/api/callhooks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package api

import (
"bytes"
"cmp"
"context"
"crypto/ed25519"
"crypto/hmac"
Expand All @@ -14,6 +15,7 @@ import (
"maps"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -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"}
Expand Down
5 changes: 5 additions & 0 deletions acceleration/internal/api/phone.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
3 changes: 3 additions & 0 deletions acceleration/internal/api/router_suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand Down
39 changes: 39 additions & 0 deletions acceleration/internal/api/shard_down_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
15 changes: 10 additions & 5 deletions acceleration/internal/session/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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 {
Comment thread
getstream-metis[bot] marked this conversation as resolved.
Resolved
taken, err := m.options.Store.Sessions.Exists(ctx, spec.ID)
if err != nil {
return nil, stack.Wrap(err)
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
Loading
Loading