diff --git a/acceleration/internal/api/app_hooks_test.go b/acceleration/internal/api/app_hooks_test.go index d1017693b1..f9ea7d3f75 100644 --- a/acceleration/internal/api/app_hooks_test.go +++ b/acceleration/internal/api/app_hooks_test.go @@ -230,6 +230,25 @@ func (s *AppHooksSuite) TestAMessageInTheDeploymentAppIsAnsweredThereWhateverRun } } +// The same across nodes: the session in a customer's own app runs on one, the session in the +// deployment's app on another, and the message lands on a third. Only the second is in the app +// the message was written in, so it is carried there. +func (s *AppHooksSuite) TestAMessageInTheDeploymentAppReachesItsSessionOnAnotherNodeWhateverRunsInAnotherApp() { + written := "is my order on its way? " + s.utils.uuid() + s.serverClient.on(s.otherNode()).createSession(CreateSessionRequest{ + AgentId: &s.channelID, Llm: pointerTo("vision/vision-model"), Incognito: pointerTo(true), + }) + s.useApp(s.data.createApp()) + s.serverClient.on(s.otherNode()).createSession(CreateSessionRequest{ + AgentId: &s.channelID, Llm: pointerTo("vision/vision-model"), Incognito: pointerTo(true), + }) + + s.Equal(http.StatusOK, s.hook("/v1/chat/hooks/stream", writtenTo(s.channelID, `{}`, written), suiteStreamSecret, "")) + + s.Eventually(func() bool { return s.wasAsked(written) }, settleFor, 10*time.Millisecond, + "the session in the deployment's app was asked nothing") +} + func (s *AppHooksSuite) TestAMessageInTheDeploymentAppIsNotDispatchedToACustomerNowElsewhere() { // A channel in the router's own app names this customer's config, but the customer // now acts in its own app, so a deployment-signed hook starts nothing of theirs. diff --git a/acceleration/internal/api/forward.go b/acceleration/internal/api/forward.go index 876766277c..c5b3d28b90 100644 --- a/acceleration/internal/api/forward.go +++ b/acceleration/internal/api/forward.go @@ -225,24 +225,23 @@ func (s *Server) forwardedMessage(ctx context.Context, origin hookOrigin, event return true, false } -// answeringNode is the node running the session that answers a message, by customer as -// liveSessionOn picks one here: the hook's customer's, and in the deployment's app the customer's -// the channel names or else the store does. While neither does, it is the only customer's writing -// as the agent, and store.ErrAmbiguousHook when there are more. A claim does not say which app -// its session is in, so a session in another app is counted among them, and the node a claim -// names checks the app again (origin.owns). +// answeringNode is the node running the session that answers a message, among the sessions in +// the hook's app (origin.owns), by customer as liveSessionOn picks one here: the hook's +// customer's, and in the deployment's app the customer's the channel names or else the store +// does. While neither does, it is the only customer's writing as the agent, and +// store.ErrAmbiguousHook when there are more. func (s *Server) answeringNode(ctx context.Context, origin hookOrigin, event messageEvent) (string, error) { if !origin.deployment { - return s.directory.NodeByAgent(ctx, origin.customer, event.ChannelID) + return s.directory.NodeByAgent(ctx, origin.customer, origin.app, event.ChannelID) } - if owner, stamped := event.ChannelCustom[conversation.CustomerField]; stamped { - customer, _ := owner.(string) - return s.directory.NodeByAgent(ctx, customer, event.ChannelID) - } - nodes, err := s.directory.NodesByAgent(ctx, event.ChannelID) + nodes, err := s.directory.NodesByAgent(ctx, event.ChannelID, origin.owns) if err != nil || len(nodes) == 0 { return "", err } + if owner, stamped := event.ChannelCustom[conversation.CustomerField]; stamped { + customer, _ := owner.(string) + return nodes[customer], nil + } owner, known, err := s.storedOwnerOf(ctx, origin, event) if err != nil { return "", err diff --git a/acceleration/internal/api/forward_test.go b/acceleration/internal/api/forward_test.go index 02c6e4f6af..1fac998f7a 100644 --- a/acceleration/internal/api/forward_test.go +++ b/acceleration/internal/api/forward_test.go @@ -7,11 +7,16 @@ import ( "log/slog" "net/http" "net/http/httptest" + "net/url" "testing" "time" + "github.com/redis/rueidis" + "github.com/GetStream/Vision-Agents/acceleration/internal/conversation" "github.com/GetStream/Vision-Agents/acceleration/internal/dispatch" + "github.com/GetStream/Vision-Agents/acceleration/internal/node" + "github.com/GetStream/Vision-Agents/acceleration/internal/testenv/redisready" ) // ForwardedSessionSuite covers what is asked of a session over HTTP when the request does @@ -178,6 +183,97 @@ func (s *ForwardedSessionSuite) TestAMessageNamingNoCustomerOnAChannelTwoCustome "one of the customers' sessions answered a message nothing says is theirs") } +// The same when the message lands on the node running one of the two: that session is no more +// the channel's than the other. +func (s *ForwardedSessionSuite) TestAMessageNamingNoCustomerLandingBesideOneOfTwoCustomersWritingInItIsAnsweredByNeither() { + channel, written := "chat-"+s.utils.uuid(), "is anybody there? "+s.utils.uuid() + s.onTheOtherNode(CreateSessionRequest{AgentId: &channel, Llm: pointerTo("vision/vision-model")}) + s.data.backendOfAnotherApp().createSession(CreateSessionRequest{ + AgentId: &channel, Llm: pointerTo("vision/vision-model"), Incognito: pointerTo(true), + }) + + s.Require().Equal(http.StatusOK, + s.signedly("/v1/chat/hooks/stream", writtenTo(channel, `{}`, written))) + + s.Never(func() bool { return s.wasAsked(written) }, time.Second, 10*time.Millisecond, + "the session where the message landed answered a message nothing says is its customer's") +} + +// A session that ended here leaves its claim on the agent behind until it lapses, and is no +// second customer writing in the channel: the session still running here answers. +func (s *ForwardedSessionSuite) TestAMessageNamingNoCustomerIsAnsweredHereThoughAnotherCustomersSessionEndedHere() { + channel, written := "chat-"+s.utils.uuid(), "is anybody there? "+s.utils.uuid() + another := s.data.backendOfAnotherApp() + ended := another.createSession(CreateSessionRequest{ + AgentId: &channel, Llm: pointerTo("vision/vision-model"), Incognito: pointerTo(true), + }) + another.stopSession(ended.Id) + s.serverClient.createSession(CreateSessionRequest{ + AgentId: &channel, Llm: pointerTo("vision/vision-model"), Incognito: pointerTo(true), + }) + + s.Require().Equal(http.StatusOK, + s.signedly("/v1/chat/hooks/stream", writtenTo(channel, `{}`, written))) + + s.Require().Eventually(func() bool { return s.wasAsked(written) }, + settleFor, 10*time.Millisecond, "the session running here was asked nothing") +} + +// The customer of the session running here writing as the agent on another node too is no second +// customer writing in the channel: the session here answers. +func (s *ForwardedSessionSuite) TestAMessageNamingNoCustomerIsAnsweredHereThoughItsCustomerWritesElsewhereToo() { + channel, written := "chat-"+s.utils.uuid(), "is anybody there? "+s.utils.uuid() + s.serverClient.createSession(CreateSessionRequest{AgentId: &channel, Llm: pointerTo("vision/vision-model"), Incognito: pointerTo(true)}) + // Second, so the claim by customer and app names the other node. + s.onTheOtherNode(CreateSessionRequest{AgentId: &channel, Llm: pointerTo("vision/vision-model")}) + + s.Require().Equal(http.StatusOK, s.signedly("/v1/chat/hooks/stream", writtenTo(channel, `{}`, written))) + + s.Require().Eventually(func() bool { return s.wasAsked(written) }, + settleFor, 10*time.Millisecond, "the customer's session here was asked nothing") +} + +// A directory that cannot be read says nobody writes as the agent elsewhere, as forwardedMessage +// answers here when it cannot find the node: the session running where the message landed +// answers it. +func (s *ForwardedSessionSuite) TestAMessageNamingNoCustomerIsAnsweredHereWhenTheDirectoryCannotBeRead() { + channel, written := "chat-"+s.utils.uuid(), "is anybody there? "+s.utils.uuid() + unread, _, _ := s.otherNodeHolding(nil, s.sealer, slog.New(slog.DiscardHandler), + func(options *Options) { options.Directory = s.unreadableDirectory() }) + s.serverClient.on(unread).createSession(CreateSessionRequest{ + AgentId: &channel, Llm: pointerTo("vision/vision-model"), Incognito: pointerTo(true), + }) + + s.Require().Equal(http.StatusOK, s.signedlyOn(unread, "/v1/chat/hooks/stream", writtenTo(channel, `{}`, written))) + + s.Require().Eventually(func() bool { return s.wasAsked(written) }, + settleFor, 10*time.Millisecond, "the session where the message landed was asked nothing") +} + +// A channel stamped with its customer is answered in the hook's app: that customer's session +// writing as the agent in another app is not where the message goes, and with nothing of theirs +// running in this app, their worker here is handed it. +func (s *ForwardedSessionSuite) TestAMessageStampedWithItsCustomerIsNotCarriedToTheirSessionInAnotherApp() { + channel := "chat-" + s.utils.uuid() + config := s.data.instructedAgent("answer whatever is asked") + // Another customer writing as the agent in this app is what has the stamp read at all. + s.heldWhereNothingAnswers("another-customer", s.utils.uuid(), channel, "") + s.heldInWhereNothingAnswers(streamAppID(), s.customerID(), s.utils.uuid(), channel, "") + worker, release := s.dispatch.Register(s.customerID(), dispatch.Registration{Capacity: 1}) + defer release() + + stamped := fmt.Sprintf(`{%q: %q, %q: %q}`, conversation.CustomerField, s.customerID(), ConfigField, *config) + s.Require().Equal(http.StatusOK, + s.signedly("/v1/chat/hooks/stream", writtenTo(channel, stamped, "is anybody there?"))) + + select { + case message := <-worker.Messages(): + s.Equal(channel, message.ChannelID) + case <-time.After(settleFor): + s.Fail("the message was carried to the customer's session in another app") + } +} + // 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. func (s *ForwardedSessionSuite) TestARequestReachesTheSessionOfTheCallersCustomerOfAnIdTwoRun() { @@ -224,7 +320,7 @@ func (s *ForwardedSessionSuite) TestAnApprovalIsCarriedToTheCallersNodeThoughAno cid := "messaging:" + s.utils.uuid() s.heldWhereNothingAnswers(s.customerID(), s.utils.uuid(), "", cid) s.nodeDirectory(s.server, s.shard, slog.New(slog.DiscardHandler)). - Hold(s.T().Context(), "another-customer", s.utils.uuid(), "", cid) + Hold(s.T().Context(), "another-customer", 0, s.utils.uuid(), "", cid) s.Equal(http.StatusServiceUnavailable, s.serverClient.do(http.MethodPost, approvalsIn(cid), anApproval, nil), "answered on the node of the customer that held the cid last") @@ -251,12 +347,43 @@ func approvalsIn(cid string) string { } // heldWhereNothingAnswers has the directory say a node that cannot be reached runs a customer's -// session id, writing as agent and answering in the conversation cid. +// session id in the deployment's own app, writing as agent and answering in the conversation cid. func (s *RouterSuite) heldWhereNothingAnswers(customer, id, agent, cid string) { + s.heldInWhereNothingAnswers(0, customer, id, agent, cid) +} + +// heldInWhereNothingAnswers is heldWhereNothingAnswers in a Stream app. +func (s *RouterSuite) heldInWhereNothingAnswers(app int64, customer, id, agent, cid string) { gone := httptest.NewUnstartedServer(nil) directory := s.nodeDirectory(gone, s.shard, slog.New(slog.DiscardHandler)) gone.Close() - directory.Hold(s.T().Context(), customer, id, agent, cid) + directory.Hold(s.T().Context(), customer, app, id, agent, cid) +} + +// unreadableDirectory is a node's directory over a Redis connection already closed, so every read +// of it fails, as one with Redis down does. +func (s *RouterSuite) unreadableDirectory() *node.Directory { + redis, err := redisready.NewClient(rueidis.ClientOption{InitAddress: []string{s.redisAddr}, DisableCache: true}) + s.Require().NoError(err) + redis.Close() + directory, err := node.NewDirectory(node.DirectoryOptions{ + Redis: redis, Address: "unreadable", Prefix: s.relayPrefix, Logger: slog.New(slog.DiscardHandler), + }) + s.Require().NoError(err) + s.T().Cleanup(directory.Close) + return directory +} + +// signedlyOn is signedly delivered to the node at rather than the suite's own. +func (s *RouterSuite) signedlyOn(at *httptest.Server, path, body string) int { + request := s.request(path, body, sign(body, suiteStreamSecret)) + target, err := url.Parse(at.URL + path) + s.Require().NoError(err) + request.URL, request.Host = target, target.Host + response, err := at.Client().Do(request) + s.Require().NoError(err) + s.Require().NoError(response.Body.Close()) + return response.StatusCode } // wasAsked reports whether the model was given something to answer. diff --git a/acceleration/internal/api/messagehooks.go b/acceleration/internal/api/messagehooks.go index eb9031c76c..81503fa2cd 100644 --- a/acceleration/internal/api/messagehooks.go +++ b/acceleration/internal/api/messagehooks.go @@ -566,8 +566,8 @@ func (s *Server) heardText(ctx context.Context, spec session.Spec, origin hookOr // or for a channel naming nobody the customer ownerOf reads from the store: its last calls, // else the customer holding the config it names. Unlike the customer ownerOf works out, this // one only ever narrows: it admits only sessions the hook already admits. A channel the store -// names no customer for is answered by a session only while the sessions on it are one -// customer's, as a hook matching rows of more than one customer is acted on for nobody. +// names no customer for is answered by a session only while the sessions on it, on any node, are +// one customer's, as a hook matching rows of more than one customer is acted on for nobody. func (s *Server) liveSessionOn(ctx context.Context, origin hookOrigin, event messageEvent) (*session.Session, bool, error) { if !origin.deployment { found, running := s.sessions.ByAgentWhere(event.ChannelID, origin.owns) @@ -588,9 +588,10 @@ func (s *Server) liveSessionOn(ctx context.Context, origin hookOrigin, event mes owner = stored if !known { theirs := found.Spec().CustomerID - if _, another := s.sessions.ByAgentWhere(event.ChannelID, func(customer string, app int64) bool { + another := func(customer string, app int64) bool { return customer != theirs && origin.owns(customer, app) - }); another { + } + if _, here := s.sessions.ByAgentWhere(event.ChannelID, another); here || s.writesElsewhere(ctx, event.ChannelID, another) { return nil, false, store.ErrAmbiguousHook } return found, true, nil @@ -602,6 +603,21 @@ func (s *Server) liveSessionOn(ctx context.Context, origin hookOrigin, event mes return found, running, nil } +// writesElsewhere reports whether the directory says a session admits takes, by its customer and +// Stream app, writes as an agent on any node. A directory that cannot be read says none does, as +// forwardedMessage answers here when it cannot find the node answering. +func (s *Server) writesElsewhere(ctx context.Context, agentID string, admits func(customer string, app int64) bool) bool { + if s.directory == nil { + return false + } + nodes, err := s.directory.NodesByAgent(ctx, agentID, admits) + if err != nil { + s.logger.Warn("could not find out which nodes write as an agent", "agent", agentID, "error", err) + return false + } + return len(nodes) > 0 +} + // storedOwnerOf is the customer the store says a channel in the hook's app is: its last call's, // else the one holding the config it names. known is false when it says neither. func (s *Server) storedOwnerOf(ctx context.Context, origin hookOrigin, event messageEvent) (owner string, known bool, err error) { diff --git a/acceleration/internal/api/scheduled_session_look_test.go b/acceleration/internal/api/scheduled_session_look_test.go index e58b5919f3..a58bc37c6e 100644 --- a/acceleration/internal/api/scheduled_session_look_test.go +++ b/acceleration/internal/api/scheduled_session_look_test.go @@ -51,12 +51,12 @@ func (s *ScheduledTasksSuite) refusingPeer(sessionID string) (asked <-chan struc peer.Start() s.T().Cleanup(peer.Close) agent := rand.Text() - directory.Hold(context.Background(), s.customerID(), sessionID, agent, "") + directory.Hold(context.Background(), s.customerID(), 0, sessionID, agent, "") s.T().Cleanup(func() { directory.Release(context.Background(), s.customerID(), sessionID) }) return got, func(here bool) { directory.Release(context.Background(), s.customerID(), sessionID) if here { - s.router.directory.Hold(context.Background(), s.customerID(), sessionID, agent, "") + s.router.directory.Hold(context.Background(), s.customerID(), 0, sessionID, agent, "") s.T().Cleanup(func() { s.router.directory.Release(context.Background(), s.customerID(), sessionID) }) } } diff --git a/acceleration/internal/node/directory.go b/acceleration/internal/node/directory.go index cae360e482..83425ecdf0 100644 --- a/acceleration/internal/node/directory.go +++ b/acceleration/internal/node/directory.go @@ -61,12 +61,15 @@ type Directory struct { address string shard string sessions string - // agents and channels are a session's agent and conversation by their ids alone, which a - // router of the release before reads. Here only channels is read, when a customer's own key - // is not there. - agents string - channels 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. + agents string + channels string + // writingAs is a claim on an agent by customer alone, which a router of the release before + // reads, and writingAsIn the same by the Stream app as well, which is what is read here. writingAs string + writingAsIn string answeringIn string workers string hosted string @@ -76,8 +79,8 @@ type Directory struct { cancel context.CancelFunc mu sync.Mutex - // held maps a session this node is running to the agent it writes as and the - // conversation it answers in, each empty for a session without one. + // held 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 // waiting counts the dispatch workers connected here, by customer. waiting map[string]int @@ -91,8 +94,12 @@ type offerKey struct{ customerID, agentID string } // one id. type heldSession struct{ customerID, sessionID string } -// claim is what a session this node holds is found by besides its own id. -type claim struct{ agentID, conversationID string } +// claim is what a session this node holds is found by besides its own id, and the Stream app it +// acts in. +type claim struct { + app int64 + agentID, conversationID string +} // offerEntry is one node's offer as Redis holds it. A hash cannot expire its fields one at // a time, so each says when it lapses. @@ -127,6 +134,7 @@ func NewDirectory(options DirectoryOptions) (*Directory, error) { agents: prefix + ":agent:", channels: prefix + ":channel:", writingAs: prefix + ":writing-as:", + writingAsIn: prefix + ":writing-as-in:", answeringIn: prefix + ":answering-in:", workers: prefix + ":workers:", hosted: prefix + ":hosted:", @@ -177,21 +185,22 @@ func (d *Directory) shardCommands() []rueidis.Completed { return []rueidis.Completed{d.redis.B().Set().Key(d.shards + d.address).Value(d.shard).Ex(holdFor).Build()} } -// Hold says this node is running a customer's session, and goes on saying so until Release. +// Hold says this node is running a customer's session in a Stream app, and goes on saying so +// until Release. // // The agent id is held beside it because an arriving message names a channel and no // session at all, so the node that can answer it has to be findable by the agent writing -// there. The conversation id (the channel's cid) is held too, because a person's answer to -// a call held for their approval names the conversation and no session either: the -// Router's own session in a channel of a type an agent config answers in runs on whichever -// node took the hook. -func (d *Directory) Hold(ctx context.Context, customerID, sessionID, agentID, conversationID string) { - key := heldSession{customerID, sessionID} +// there, and by the app, which is the only thing a hook says is whose. The conversation id (the +// channel's cid) is held too, because a person's answer to a call held for their approval names +// the conversation and no session either: the Router's own session in a channel of a type an +// agent config answers in runs on whichever node took the hook. +func (d *Directory) Hold(ctx context.Context, customerID string, app int64, sessionID, agentID, conversationID string) { + key, held := heldSession{customerID, sessionID}, claim{app, agentID, conversationID} d.mu.Lock() - d.held[key] = claim{agentID, conversationID} + d.held[key] = held d.mu.Unlock() - d.write(ctx, key, claim{agentID, conversationID}) + d.write(ctx, key, held) } // Release says this node is not running a customer's session any more. @@ -234,12 +243,13 @@ func (d *Directory) Node(ctx context.Context, customerID, sessionID string) (str return d.lookup(ctx, d.sessionKey(heldSession{customerID, sessionID}), d.sessions+sessionID) } -// NodeByAgent is the same for a customer's session writing as an agent, which is what an -// arriving message has to be answered by. An agent id is any customer's to choose, so each -// customer's is held apart, and one customer starting a session as another's agent does not -// move where the other's messages go. -func (d *Directory) NodeByAgent(ctx context.Context, customerID, agentID string) (string, error) { - entry, err := d.redis.Do(ctx, d.redis.B().Hget().Key(d.writingAs+agentID).Field(customerID).Build()).ToString() +// NodeByAgent is the same for a customer's session in a Stream app writing as an agent, which is +// what an arriving message has to be answered by. An agent id is any customer's to choose, so +// each customer's is held apart, and one customer starting a session as another's agent does not +// move where the other's messages go. Each app's is held apart too, as a message is answered only +// in the app it was written in. +func (d *Directory) NodeByAgent(ctx context.Context, customerID string, app int64, agentID string) (string, error) { + entry, err := d.redis.Do(ctx, d.redis.B().Hget().Key(d.writingAsIn+agentID).Field(writerField(customerID, app)).Build()).ToString() if rueidis.IsRedisNil(err) { return "", nil } @@ -252,18 +262,25 @@ func (d *Directory) NodeByAgent(ctx context.Context, customerID, agentID string) return "", nil } -// NodesByAgent is where the nodes running every customer's sessions that write as an agent can -// be reached, by customer, for a message that names none. -func (d *Directory) NodesByAgent(ctx context.Context, agentID string) (map[string]string, error) { - entries, err := d.redis.Do(ctx, d.redis.B().Hgetall().Key(d.writingAs+agentID).Build()).AsStrMap() +// NodesByAgent is where the other nodes running the sessions that write as an agent can be +// reached, by customer, among the sessions admits takes by their customer and Stream app, for a +// message that names no customer. A customer with sessions in two apps it admits is one entry, +// either node. This node is never among them: what runs here is what its own sessions say, and a +// claim of a session that ended here lasts until it lapses. +func (d *Directory) NodesByAgent(ctx context.Context, agentID string, admits func(customer string, app int64) bool) (map[string]string, error) { + entries, err := d.redis.Do(ctx, d.redis.B().Hgetall().Key(d.writingAsIn+agentID).Build()).AsStrMap() if err != nil { return nil, err } now := time.Now().UnixMilli() var nodes map[string]string - for customerID, entry := range entries { + for field, entry := range entries { + customerID, app, ok := parseWriterField(field) + if !ok || !admits(customerID, app) { + continue + } address, live := liveClaim(entry, now) - if !live { + if !live || address == d.address { continue } if nodes == nil { @@ -421,6 +438,19 @@ func (d *Directory) sessionKey(key heldSession) string { return d.sessions + key.customerID + ":" + key.sessionID } +// writerField is the field of a customer's claim on an agent in a Stream app: :. An +// app id holds no colon, so the first one ends it. +func writerField(customerID string, app int64) string { + return strconv.FormatInt(app, 10) + ":" + customerID +} + +// parseWriterField is the customer and app of a writerField, false for a field that is not one. +func parseWriterField(field string) (string, int64, bool) { + prefix, customerID, found := strings.Cut(field, ":") + app, err := strconv.ParseInt(prefix, 10, 64) + return customerID, app, found && err == nil +} + // liveClaim is the address a customer's claim on an agent names, as writeCommands writes it, and // false once it lapsed: when, then the address. func liveClaim(entry string, now int64) (string, bool) { @@ -448,23 +478,26 @@ func (d *Directory) write(ctx context.Context, key heldSession, held claim) { } // writeCommands hold the session, its agent and its conversation under its customer, and under -// their ids alone as well, which is all a router of the release before reads. +// their ids alone as well, which is all an older router reads. // -// The agent is one hash for every customer writing as it, a field each, because a message in -// the deployment's app may name no customer, and the node answering it is then picked from all -// of theirs. A hash cannot expire its fields one at a time, so each says when it lapses, before -// the address. +// The agent is one hash for every customer and Stream app writing as it, a field each, because a +// message in the deployment's app may name no customer, and the node answering it is then picked +// from all of theirs in that app. A hash cannot expire its fields one at a time, so each says when +// it lapses, before the address. The hash by customer alone is the one a router of the release +// before reads, and the agent by its id alone a router older than that. func (d *Directory) writeCommands(key heldSession, held claim) []rueidis.Completed { commands := []rueidis.Completed{ d.redis.B().Set().Key(d.sessionKey(key)).Value(d.address).Ex(holdFor).Build(), d.redis.B().Set().Key(d.sessions + key.sessionID).Value(d.address).Ex(holdFor).Build(), } if held.agentID != "" { - writers := d.writingAs + held.agentID - until := strconv.FormatInt(time.Now().Add(holdFor).UnixMilli(), 10) + entry := strconv.FormatInt(time.Now().Add(holdFor).UnixMilli(), 10) + " " + d.address + writers, byCustomer := d.writingAsIn+held.agentID, d.writingAs+held.agentID commands = append(commands, - d.redis.B().Hset().Key(writers).FieldValue().FieldValue(key.customerID, until+" "+d.address).Build(), + d.redis.B().Hset().Key(writers).FieldValue().FieldValue(writerField(key.customerID, held.app), entry).Build(), d.redis.B().Pexpire().Key(writers).Milliseconds(holdFor.Milliseconds()).Build(), + d.redis.B().Hset().Key(byCustomer).FieldValue().FieldValue(key.customerID, entry).Build(), + d.redis.B().Pexpire().Key(byCustomer).Milliseconds(holdFor.Milliseconds()).Build(), d.redis.B().Set().Key(d.agents+held.agentID).Value(d.address).Ex(holdFor).Build()) } if held.conversationID != "" { diff --git a/acceleration/internal/node/directory_test.go b/acceleration/internal/node/directory_test.go index 22c06f10e4..89650274d4 100644 --- a/acceleration/internal/node/directory_test.go +++ b/acceleration/internal/node/directory_test.go @@ -57,7 +57,7 @@ func (s *DirectorySuite) TestARenewalIsOneRoundTrip() { s.Require().NoError(err) directory.Close() for _, session := range []string{"s1", "s2", "s3"} { - directory.Hold(s.ctx, "acme", session, "agent-"+session, "messaging:"+session) + directory.Hold(s.ctx, "acme", 7, session, "agent-"+session, "messaging:"+session) } directory.Wait(s.ctx, "acme") directory.Wait(s.ctx, "globex") @@ -65,9 +65,9 @@ func (s *DirectorySuite) TestARenewalIsOneRoundTrip() { directory.Offer(s.ctx, "globex", "agent-s2", []byte(`{"tools":[]}`)) keys, err := s.client.Do(s.ctx, s.client.B().Keys().Pattern(s.prefix+":*").Build()).AsStrSlice() s.Require().NoError(err) - // Each session: itself, its agent and its conversation, each under its customer and under - // its id alone. - s.Require().Len(keys, 3*6+2+2+1) + // 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+1) s.Require().NoError(s.client.Do(s.ctx, s.client.B().Del().Key(keys...).Build()).Error()) before := s.roundTrips.sent.Load() @@ -85,7 +85,7 @@ func (s *DirectorySuite) TestARenewalIsOneRoundTrip() { held, err := peer.NodeByConversation(s.ctx, "acme", "messaging:s3") s.Require().NoError(err) s.Equal("node-a:1", held) - writing, err := peer.NodesByAgent(s.ctx, "agent-s2") + writing, err := peer.NodesByAgent(s.ctx, "agent-s2", everyApp) s.Require().NoError(err) s.Equal(map[string]string{"acme": "node-a:1"}, writing) waiting, err := peer.Waiting(s.ctx, "globex") @@ -101,8 +101,8 @@ func (s *DirectorySuite) TestARenewalIsOneRoundTrip() { func (s *DirectorySuite) TestTwoCustomersSessionsOfOneIdAreFoundApart() { first := s.directoryAt("node-a:1") second := s.directoryAt("node-b:1") - first.Hold(s.ctx, "acme", "order-42", "", "") - second.Hold(s.ctx, "globex", "order-42", "", "") + first.Hold(s.ctx, "acme", 0, "order-42", "", "") + second.Hold(s.ctx, "globex", 0, "order-42", "", "") peer := s.directoryAt("node-c:1") s.Equal("node-a:1", s.nodeOf(peer, "acme", "order-42")) @@ -118,7 +118,7 @@ func (s *DirectorySuite) TestASessionHeldUnderItsIdAloneIsFound() { // A router of the release before reads a session's node by its id alone. func (s *DirectorySuite) TestASessionHeldHereIsFoundByItsIdAlone() { - s.directoryAt("node-a:1").Hold(s.ctx, "acme", "order-42", "", "") + s.directoryAt("node-a:1").Hold(s.ctx, "acme", 0, "order-42", "", "") held, err := s.client.Do(s.ctx, s.client.B().Get().Key(s.prefix+":session:order-42").Build()).ToString() s.Require().NoError(err) @@ -128,21 +128,100 @@ func (s *DirectorySuite) TestASessionHeldHereIsFoundByItsIdAlone() { // Two customers may each run a session writing as one agent: each customer's is found, whichever // node said so last. func (s *DirectorySuite) TestTwoCustomersWritingAsOneAgentAreFoundApart() { - s.directoryAt("node-a:1").Hold(s.ctx, "acme", "s1", "support", "") - s.directoryAt("node-b:1").Hold(s.ctx, "globex", "s2", "support", "") + s.directoryAt("node-a:1").Hold(s.ctx, "acme", 7, "s1", "support", "") + s.directoryAt("node-b:1").Hold(s.ctx, "globex", 7, "s2", "support", "") peer := s.directoryAt("node-c:1") - s.Equal("node-a:1", s.writingAs(peer, "acme", "support")) - s.Equal("node-b:1", s.writingAs(peer, "globex", "support")) - writing, err := peer.NodesByAgent(s.ctx, "support") + s.Equal("node-a:1", s.writingAs(peer, "acme", 7, "support")) + s.Equal("node-b:1", s.writingAs(peer, "globex", 7, "support")) + writing, err := peer.NodesByAgent(s.ctx, "support", everyApp) s.Require().NoError(err) s.Equal(map[string]string{"acme": "node-a:1", "globex": "node-b:1"}, writing) } +// A customer may run a session writing as one agent in each of two Stream apps: each app's is +// found, and none in a third. +func (s *DirectorySuite) TestOneCustomerWritingAsOneAgentInTwoAppsIsFoundApartByApp() { + s.directoryAt("node-a:1").Hold(s.ctx, "acme", 7, "s1", "support", "") + s.directoryAt("node-b:1").Hold(s.ctx, "acme", 8, "s2", "support", "") + + peer := s.directoryAt("node-c:1") + s.Equal("node-a:1", s.writingAs(peer, "acme", 7, "support")) + s.Equal("node-b:1", s.writingAs(peer, "acme", 8, "support")) + s.Empty(s.writingAs(peer, "acme", 0, "support")) +} + +// The nodes writing as an agent are those of the sessions the caller admits by customer and app, +// as a message in one app is answered only by a session there. +func (s *DirectorySuite) TestTheNodesWritingAsAnAgentAreThoseOfTheSessionsAdmitted() { + s.directoryAt("node-a:1").Hold(s.ctx, "acme", 7, "s1", "support", "") + s.directoryAt("node-b:1").Hold(s.ctx, "globex", 8, "s2", "support", "") + s.directoryAt("node-c:1").Hold(s.ctx, "initech", 0, "s3", "support", "") + peer := s.directoryAt("node-d:1") + + inTheDeploymentsApp, err := peer.NodesByAgent(s.ctx, "support", func(_ string, app int64) bool { return app == 0 || app == 7 }) + s.Require().NoError(err) + globexes, err := peer.NodesByAgent(s.ctx, "support", func(customer string, _ int64) bool { return customer == "globex" }) + s.Require().NoError(err) + + s.Equal(map[string]string{"acme": "node-a:1", "initech": "node-c:1"}, inTheDeploymentsApp) + s.Equal(map[string]string{"globex": "node-b:1"}, globexes) +} + +// The nodes writing as an agent are the others: a node's own claim names a session it runs, which +// it finds among its own, or one that ended there and has not lapsed yet. +func (s *DirectorySuite) TestTheNodesWritingAsAnAgentAreNeverTheOneAsking() { + here := s.directoryAt("node-a:1") + here.Hold(s.ctx, "acme", 7, "s1", "support", "") + s.directoryAt("node-b:1").Hold(s.ctx, "globex", 7, "s2", "support", "") + + writing, err := here.NodesByAgent(s.ctx, "support", everyApp) + + s.Require().NoError(err) + s.Equal(map[string]string{"globex": "node-b:1"}, writing) +} + +// A customer id may hold a colon, and an app id holds none: the customer is all that follows the +// first. +func (s *DirectorySuite) TestACustomerWritingAsAnAgentIsFoundByItsWholeIdThoughItHoldsAColon() { + s.directoryAt("node-a:1").Hold(s.ctx, "a:7", 7, "s1", "support", "") + + peer := s.directoryAt("node-c:1") + writing, err := peer.NodesByAgent(s.ctx, "support", func(customer string, app int64) bool { return customer == "a:7" && app == 7 }) + s.Require().NoError(err) + s.Equal(map[string]string{"a:7": "node-a:1"}, writing) + s.Equal("node-a:1", s.writingAs(peer, "a:7", 7, "support")) +} + +// A claim on an agent that says no app, as a router of the release before writes it, is read +// nowhere: an app it does not say may be one the message was not written in. +func (s *DirectorySuite) TestAClaimOnAnAgentByItsCustomerAloneIsFoundNowhere() { + live := strconv.FormatInt(time.Now().Add(time.Minute).UnixMilli(), 10) + s.Require().NoError(s.client.Do(s.ctx, s.client.B().Hset().Key(s.prefix+":writing-as:support"). + FieldValue().FieldValue("acme", live+" node-a:1").Build()).Error()) + + peer := s.directoryAt("node-c:1") + s.Empty(s.writingAs(peer, "acme", 0, "support")) + writing, err := peer.NodesByAgent(s.ctx, "support", everyApp) + s.Require().NoError(err) + s.Empty(writing) +} + +// A router of the release before reads a claim on an agent by its customer alone. +func (s *DirectorySuite) TestASessionWritingAsAnAgentIsFoundByItsCustomerAlone() { + s.directoryAt("node-a:1").Hold(s.ctx, "acme", 7, "s1", "support", "") + + entry, err := s.client.Do(s.ctx, s.client.B().Hget().Key(s.prefix+":writing-as:support").Field("acme").Build()).ToString() + s.Require().NoError(err) + address, live := liveClaim(entry, time.Now().UnixMilli()) + s.True(live) + s.Equal("node-a:1", address) +} + // The same for two customers answering in conversations of one cid. func (s *DirectorySuite) TestTwoCustomersAnsweringInOneConversationAreFoundApart() { - s.directoryAt("node-a:1").Hold(s.ctx, "acme", "s1", "", "messaging:general") - s.directoryAt("node-b:1").Hold(s.ctx, "globex", "s2", "", "messaging:general") + s.directoryAt("node-a:1").Hold(s.ctx, "acme", 0, "s1", "", "messaging:general") + s.directoryAt("node-b:1").Hold(s.ctx, "globex", 0, "s2", "", "messaging:general") peer := s.directoryAt("node-c:1") s.Equal("node-a:1", s.answeringIn(peer, "acme", "messaging:general")) @@ -152,8 +231,8 @@ func (s *DirectorySuite) TestTwoCustomersAnsweringInOneConversationAreFoundApart // A customer id may hold a colon, as a cid does, so customer "a:b" in "c:d" and customer "a" in // "b:c:d" are two conversations. func (s *DirectorySuite) TestACustomerAndCidAreNotTakenForAnother() { - s.directoryAt("node-a:1").Hold(s.ctx, "a:b", "s1", "", "c:d") - s.directoryAt("node-b:1").Hold(s.ctx, "a", "s2", "", "b:c:d") + s.directoryAt("node-a:1").Hold(s.ctx, "a:b", 0, "s1", "", "c:d") + s.directoryAt("node-b:1").Hold(s.ctx, "a", 0, "s2", "", "b:c:d") peer := s.directoryAt("node-c:1") s.Equal("node-a:1", s.answeringIn(peer, "a:b", "c:d")) @@ -164,13 +243,13 @@ func (s *DirectorySuite) TestACustomerAndCidAreNotTakenForAnother() { // renewals keep the agent's entry alive: that claim lapses all the same. func (s *DirectorySuite) TestAClaimOnAnAgentThatLapsedIsFoundNowhere() { lapsed := strconv.FormatInt(time.Now().Add(-time.Second).UnixMilli(), 10) - s.Require().NoError(s.client.Do(s.ctx, s.client.B().Hset().Key(s.prefix+":writing-as:support"). - FieldValue().FieldValue("acme", lapsed+" node-a:1").Build()).Error()) - s.directoryAt("node-b:1").Hold(s.ctx, "globex", "s2", "support", "") + s.Require().NoError(s.client.Do(s.ctx, s.client.B().Hset().Key(s.prefix+":writing-as-in:support"). + FieldValue().FieldValue("7:acme", lapsed+" node-a:1").Build()).Error()) + s.directoryAt("node-b:1").Hold(s.ctx, "globex", 7, "s2", "support", "") peer := s.directoryAt("node-c:1") - s.Empty(s.writingAs(peer, "acme", "support")) - writing, err := peer.NodesByAgent(s.ctx, "support") + s.Empty(s.writingAs(peer, "acme", 7, "support")) + writing, err := peer.NodesByAgent(s.ctx, "support", everyApp) s.Require().NoError(err) s.Equal(map[string]string{"globex": "node-b:1"}, writing) } @@ -187,10 +266,10 @@ func (s *DirectorySuite) TestAConversationHeldUnderItsCidAloneIsFound() { // other customers' renewals keep the agent's entry alive. func (s *DirectorySuite) TestAClaimOnAnAgentLapsesThirtySecondsAfterItIsMade() { before := time.Now() - s.directoryAt("node-a:1").Hold(s.ctx, "acme", "s1", "support", "") + s.directoryAt("node-a:1").Hold(s.ctx, "acme", 7, "s1", "support", "") after := time.Now() - entry, err := s.client.Do(s.ctx, s.client.B().Hget().Key(s.prefix+":writing-as:support").Field("acme").Build()).ToString() + entry, err := s.client.Do(s.ctx, s.client.B().Hget().Key(s.prefix+":writing-as-in:support").Field("7:acme").Build()).ToString() s.Require().NoError(err) until, address, _ := strings.Cut(entry, " ") lapses, err := strconv.ParseInt(until, 10, 64) @@ -202,7 +281,7 @@ func (s *DirectorySuite) TestAClaimOnAnAgentLapsesThirtySecondsAfterItIsMade() { // A router of the release before reads a session's agent and conversation by their ids alone. func (s *DirectorySuite) TestASessionHeldHereIsFoundByItsAgentAndConversationAlone() { - s.directoryAt("node-a:1").Hold(s.ctx, "acme", "s1", "support", "messaging:general") + s.directoryAt("node-a:1").Hold(s.ctx, "acme", 7, "s1", "support", "messaging:general") for _, key := range []string{s.prefix + ":agent:support", s.prefix + ":channel:messaging:general"} { held, err := s.client.Do(s.ctx, s.client.B().Get().Key(key).Build()).ToString() @@ -213,7 +292,7 @@ func (s *DirectorySuite) TestASessionHeldHereIsFoundByItsAgentAndConversationAlo func (s *DirectorySuite) TestAReleasedSessionIsFoundNowhere() { directory := s.directoryAt("node-a:1") - directory.Hold(s.ctx, "acme", "order-42", "", "") + directory.Hold(s.ctx, "acme", 0, "order-42", "", "") directory.Release(s.ctx, "acme", "order-42") @@ -233,7 +312,7 @@ func (s *DirectorySuite) TestEachClaimThatCannotBeTakenBackIsLogged() { }) s.Require().NoError(err) directory.Close() - directory.Hold(s.ctx, "acme", "order-42", "", "") + directory.Hold(s.ctx, "acme", 0, "order-42", "", "") gone, cancel := context.WithCancel(s.ctx) cancel() @@ -249,7 +328,7 @@ func (s *DirectorySuite) TestAReleasedSessionsKeysAreDeletedOneCommandEach() { directory, err := NewDirectory(DirectoryOptions{Redis: rueidishook.WithHook(s.client, sent), Address: "node-a:1", Prefix: s.prefix}) s.Require().NoError(err) directory.Close() - directory.Hold(s.ctx, "acme", "order-42", "", "") + directory.Hold(s.ctx, "acme", 0, "order-42", "", "") sent.reset() directory.Release(s.ctx, "acme", "order-42") @@ -290,7 +369,7 @@ func (s *DirectorySuite) TestAReleasedSessionIsFoundNowhereOnACluster() { slots[slot] = true } s.Require().Len(slots, 2, "the two keys of a session sit in different slots") - directory.Hold(s.ctx, "acme", "order-42", "", "") + directory.Hold(s.ctx, "acme", 0, "order-42", "", "") for _, key := range keys { exists, err := cluster.Do(s.ctx, cluster.B().Exists().Key(key).Build()).AsInt64() s.Require().NoError(err) @@ -321,13 +400,16 @@ func (s *DirectorySuite) nodeOf(directory *Directory, customer, session string) return address } -// writingAs is where directory says a customer's session writing as an agent runs. -func (s *DirectorySuite) writingAs(directory *Directory, customer, agent string) string { - address, err := directory.NodeByAgent(s.ctx, customer, agent) +// writingAs is where directory says a customer's session in app writing as an agent runs. +func (s *DirectorySuite) writingAs(directory *Directory, customer string, app int64, agent string) string { + address, err := directory.NodeByAgent(s.ctx, customer, app, agent) s.Require().NoError(err) return address } +// everyApp admits every customer's sessions in every app. +func everyApp(string, int64) bool { return true } + // answeringIn is where directory says a customer's session answering in a conversation runs. func (s *DirectorySuite) answeringIn(directory *Directory, customer, cid string) string { address, err := directory.NodeByConversation(s.ctx, customer, cid) diff --git a/acceleration/internal/sandbox/daytona/sweep_test.go b/acceleration/internal/sandbox/daytona/sweep_test.go index f08ea3e34c..457803de3b 100644 --- a/acceleration/internal/sandbox/daytona/sweep_test.go +++ b/acceleration/internal/sandbox/daytona/sweep_test.go @@ -210,7 +210,7 @@ func (s *SweepSuite) TearDownTest() { // live has the directory say the customer's session runs on this router. func (s *SweepSuite) live(session string) { - s.directory.Hold(s.ctx, s.customer, session, "", "") + s.directory.Hold(s.ctx, s.customer, 0, session, "", "") s.keys = append(s.keys, "w15sweep:"+s.prefix+":session:"+session, "w15sweep:"+s.prefix+":session:"+s.customer+":"+session) } diff --git a/acceleration/internal/session/manager.go b/acceleration/internal/session/manager.go index c497fd265f..ccdf683396 100644 --- a/acceleration/internal/session/manager.go +++ b/acceleration/internal/session/manager.go @@ -1133,7 +1133,7 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er // Said after the session is here to be found, so a peer that forwards a request on // the strength of it has somewhere to forward it to. if m.options.Directory != nil { - m.options.Directory.Hold(ctx, spec.CustomerID, created.id, spec.AgentID, spec.ConversationID) + m.options.Directory.Hold(ctx, spec.CustomerID, spec.StreamApp, created.id, spec.AgentID, spec.ConversationID) } // Asked again now the session is held: a status that came while the call was being // joined found no session to end, and one that comes after this finds it. The session