diff --git a/.claude/skills/go/logging.md b/.claude/skills/go/logging.md index 8e6181a0ed..13bcf53a89 100644 --- a/.claude/skills/go/logging.md +++ b/.claude/skills/go/logging.md @@ -16,10 +16,11 @@ Read before you log a value, or read one back out of a log. ## What to log -- The ids that find a line are `customer`, `session`, `call` and `turn`. A job's are `task` and `run`. The failure is `error`. +- The ids that find a line are `app_id`, `session`, `call` and `turn`. A job's are `task` and `run`. The failure is `error`. - Some lines still use `customer_id`, `session_id`, `call_id` or `err`. Do not copy them. +- `customer` is the old name of `app_id`; ClickHouse reads it only from lines older routers wrote. - An end user's id is `user`, a call participant's `participant` (`bound` for the one a speech-to-speech model hears); `user_id` is the old name. The customer picks it and it is often an email, or `phone:` and a number for a channel user. Under these names the logger masks everything before an email's `@`, and it masks a `phone:` number anywhere. A bare numeric id is kept: its shape cannot tell it from an opaque one. A route's `{user_id}` segment is logged as `{user_id}`. Find a user's lines by `session`, `call` or `request_id`. -- Do not repeat what the logger carries: `customer`, `session`, `call` on the agent's (`agent.New`); `provider`, `model` on a provider's; `app_id`, `api_key` on a line logged with a request's context. +- Do not repeat what the logger carries: `app_id`, `session`, `call` on the agent's (`agent.New`); `provider`, `model` on a provider's; `app_id`, `api_key` on a line logged with a request's context. - Name any other field after what it holds (`connector`, not `id`) and keep its value short. There is no `component` field: the message names the thing. - Never a request body, nor a header that can hold a secret. Never a whole map or struct, unless a tool reads it back (below). - A connector logs the body of a provider's answer one way: `core.LoggedBody(exchange.ErrorBody())`, the cut, redacted start of an error body. diff --git a/.claude/skills/scheduled-tasks/SKILL.md b/.claude/skills/scheduled-tasks/SKILL.md index 4e4a216043..e99bbb62c1 100644 --- a/.claude/skills/scheduled-tasks/SKILL.md +++ b/.claude/skills/scheduled-tasks/SKILL.md @@ -245,5 +245,5 @@ it also finds the job queue's `Failed to forward scheduled tasks`, which is nois | `could not read when a scheduled task last ran` | error | `scheduled_tasks.go:637` | | `could not pause a deleted config's scheduled tasks` | error | `internal/api/configs.go:309` | -Each line carries `task`, `run` and `customer` where it has them; the `error` field holds the +Each line carries `task`, `run` and `app_id` where it has them; the `error` field holds the whole story the run's code leaves out. diff --git a/acceleration/README.md b/acceleration/README.md index 9d44acc402..fcef188268 100644 --- a/acceleration/README.md +++ b/acceleration/README.md @@ -2174,13 +2174,13 @@ Everything above is what a request *did*. That it arrived at all is a log line, request served, at info: ``` -level=INFO msg="served a request" method=POST path=/v1/agents/sessions status=201 duration=425ms customer=examples request_id=… bytes=877 app_id=examples api_key=noauth -level=INFO msg="served a request" method=GET path=/v1/agents/sessions/d84a…/events status=101 duration=94ms customer=examples request_id=… app_id=examples api_key=noauth +level=INFO msg="served a request" method=POST path=/v1/agents/sessions status=201 duration=425ms request_id=… bytes=877 app_id=examples api_key=noauth +level=INFO msg="served a request" method=GET path=/v1/agents/sessions/d84a…/events status=101 duration=94ms request_id=… app_id=examples api_key=noauth ``` An authenticated request's line, and any line logged with its context, names its app as `app_id` -and the public key it came with as `api_key`, as the Stream platform's logs do (`customer` is the -same app as `app_id`). A request nobody authenticated carries neither. A Stream hook (`PhoneHook`, +and the public key it came with as `api_key`, as the Stream platform's logs do. Every other router +line that names the app names it as `app_id` too, never twice. A request nobody authenticated carries neither. A Stream hook (`PhoneHook`, `ChatHook`, `ReceiveChatDelivery`) names the app it was verified to come from as `app_id` once its signature checked out, and no `api_key`, since no key made it; one that did not check out names no app, whatever its path says. A hook verified before the deployment knows its own app (a @@ -2335,10 +2335,10 @@ that comes back after 400 days without a request shows as new. To see why an organization's requests are refused, list its refusals by code from the access log. The router writes one `served a request` line per request, with `error_code` on every refused request. That includes a call hook or a socket that is refused with status 200 or 101, so the query -keeps those lines too. The line names the app in `customer`, or in `app_id` when the request was -turned away before it was accepted (for example a caller refused for its user level). A request refused for its usage categories names no app, so this query does not list it. +keeps those lines too. The line names the app in `app_id`, including a request turned away before it +was accepted (for example a caller refused for its user level). A request refused for its usage categories names no app, so this query does not list it. ClickHouse holds these lines in `logs.agent_access_logs`. It takes `app_id` from the line's -`app_id`, and from `customer` when that is missing. The status is `response`. It keeps 14 days. +`app_id`, and from `customer`, the key older routers named it under, when that is missing. The status is `response`. It keeps 14 days. Each cluster has its own ClickHouse: staging is `us-east1-acceleration`, and prod has three clusters, so run the query on each. Find the organization's apps in Postgres first (`SELECT app_id FROM app_organizations WHERE organization_id = ''`), then: diff --git a/acceleration/cmd/router/optouts.go b/acceleration/cmd/router/optouts.go index 503e6f006f..c13727c7b2 100644 --- a/acceleration/cmd/router/optouts.go +++ b/acceleration/cmd/router/optouts.go @@ -51,7 +51,7 @@ func runNormalizeOptOuts(ctx context.Context, settings config.Config, logger *sl done, err := pgStore.OptOuts.Normalize(ctx, batch, func(unread []store.OptOut) { for _, optOut := range unread { logger.Warn("an opt-out's recipient looks like a phone number but has no one valid reading, and was kept as it is", - "opt_out", optOut.ID, "customer", optOut.CustomerID, "channel", optOut.Channel) + "opt_out", optOut.ID, "app_id", optOut.CustomerID, "channel", optOut.Channel) } }) fmt.Fprintf(out, "%d opt-outs rewritten into E.164, %d revoked; %d name a handle, not a number, and were kept\n", diff --git a/acceleration/cmd/router/replicate.go b/acceleration/cmd/router/replicate.go index 4d375dec34..8f76a7d2f7 100644 --- a/acceleration/cmd/router/replicate.go +++ b/acceleration/cmd/router/replicate.go @@ -192,7 +192,7 @@ func copyEverything(ctx context.Context, source *deployment, pgStore *store.Stor return "", 0, err } if saved != nil { - logger.Info("carrying on from the last run here", "customer", as, "cursor", *saved) + logger.Info("carrying on from the last run here", "app_id", as, "cursor", *saved) return as, *saved, nil } } @@ -232,7 +232,7 @@ func copyEverything(ctx context.Context, source *deployment, pgStore *store.Stor return "", 0, err } if saved != nil { - logger.Info("carrying on from the last run here", "customer", customerID, "cursor", *saved) + logger.Info("carrying on from the last run here", "app_id", customerID, "cursor", *saved) return customerID, *saved, nil } } @@ -271,7 +271,7 @@ func copyEverything(ctx context.Context, source *deployment, pgStore *store.Stor return "", 0, err } if saved != nil { - logger.Info("carrying on from the last run here", "customer", customerID, "cursor", *saved) + logger.Info("carrying on from the last run here", "app_id", customerID, "cursor", *saved) return customerID, *saved, nil } } @@ -279,7 +279,7 @@ func copyEverything(ctx context.Context, source *deployment, pgStore *store.Stor return "", 0, err } - logger.Info("copied a customer", "customer", customerID, "rows", rows, "cursor", *cursor) + logger.Info("copied a customer", "app_id", customerID, "rows", rows, "cursor", *cursor) warnLeftOut(logger, customerID, leftOut) return customerID, *cursor, nil } @@ -408,7 +408,7 @@ func warnLeftOut(logger *slog.Logger, customerID string, numbers int) { return } logger.Warn("left out numbers on the app's own sip trunk that another app holds here: add them to a trunk "+ - "(POST /v1/phone/trunks/{id}/numbers) once the move is over", "customer", customerID, "numbers", numbers) + "(POST /v1/phone/trunks/{id}/numbers) once the move is over", "app_id", customerID, "numbers", numbers) } // caughtUpMessage is what --once prints when it has caught up. It names --as for the next run: diff --git a/acceleration/internal/agent/agent.go b/acceleration/internal/agent/agent.go index 37a4e5be56..44bc4e6df7 100644 --- a/acceleration/internal/agent/agent.go +++ b/acceleration/internal/agent/agent.go @@ -772,7 +772,7 @@ func New(options Options) (*Agent, error) { } } - logger := options.Logger.With("customer", options.CustomerID, "session", options.SessionID, "call", options.CallID) + logger := options.Logger.With("app_id", options.CustomerID, "session", options.SessionID, "call", options.CallID) owner := routing.Owner{ CustomerID: options.CustomerID, Attribution: options.Attribution, diff --git a/acceleration/internal/agent/approval_test.go b/acceleration/internal/agent/approval_test.go index 13d446a7c8..21b1f6af2e 100644 --- a/acceleration/internal/agent/approval_test.go +++ b/acceleration/internal/agent/approval_test.go @@ -62,16 +62,16 @@ func (s *AgentSuite) TestAYesRunsTheCallOnceWithItsOwnID() { // Keys of a line for a call that was answered with its question, as main logs them: the asked // line has only approval added to them. -var askedLineKeys = []string{"agent_id", "app_id", "call", "customer", "duration_ms", "error_code", "level", "msg", +var askedLineKeys = []string{"agent_id", "app_id", "call", "duration_ms", "error_code", "level", "msg", "outcome", "session", "success", "time", "tool", "tool_call", "turn"} // confirmationLineKeys are the keys the confirmation's line has: the run it approved has its // own line, with the connector and the error. -var confirmationLineKeys = []string{"agent_id", "app_id", "call", "customer", "duration_ms", "level", "msg", +var confirmationLineKeys = []string{"agent_id", "app_id", "call", "duration_ms", "level", "msg", "outcome", "session", "success", "time", "tool", "tool_call", "turn"} // connectorLineKeys are the keys main logs a connector's call with that asks nothing. -var connectorLineKeys = []string{"agent_id", "app_id", "call", "connector", "customer", "duration_ms", "error_code", +var connectorLineKeys = []string{"agent_id", "app_id", "call", "connector", "duration_ms", "error_code", "level", "msg", "outcome", "session", "success", "time", "tool", "tool_call", "turn"} // confirmedLines has the caller asked whether to book order 12 and answer with arguments, run @@ -105,6 +105,7 @@ func (s *AgentSuite) TestAnApprovedCallIsLoggedUnderItsOwnName() { }) s.Require().Len(lines, 3) + s.Equal([]int{1, 1, 1}, s.logs.keyCounts(toolBack, "app_id"), "the session logger's app is each line's only one") asked, ran, confirmed := lines[0], lines[1], lines[2] s.Equal("lookup_order", asked["tool"]) s.Equal("call-1", asked["tool_call"]) diff --git a/acceleration/internal/agent/telephony.go b/acceleration/internal/agent/telephony.go index 3dd66c9002..6e4415bc09 100644 --- a/acceleration/internal/agent/telephony.go +++ b/acceleration/internal/agent/telephony.go @@ -838,8 +838,8 @@ func (a *Agent) executeTool(ctx context.Context, cancel context.CancelFunc, requ }) } -// loggedTool is what "a tool call came back" says beside the agent logger's customer, session and -// call: whose agent it was, under the keys "model call timing" names them with, the connector +// loggedTool is what "a tool call came back" says beside the agent logger's app_id, session and +// call: whose agent it was, under the key "model call timing" names it with, the connector // the tool belongs to, and whether it failed and how. A call fails when it returned err or // its runner reported a failure (ToolReport); error_code is the runner's, else timeout or // cancelled for a context that ended, else error. The error a connector call returned is @@ -847,7 +847,7 @@ func (a *Agent) executeTool(ctx context.Context, cancel context.CancelFunc, requ // failed with (ToolReport.Client). What a call was asked and answered is not logged: it is the // caller's and its users'. func (a *Agent) loggedTool(report ToolReport, err error) []any { - fields := []any{"app_id", a.options.CustomerID, "agent_id", a.options.AgentID} + fields := []any{"agent_id", a.options.AgentID} if report.Connector != "" { fields = append(fields, "connector", report.Connector) } @@ -874,7 +874,7 @@ func (a *Agent) loggedTool(report ToolReport, err error) []any { // loggedAnswer is loggedTool for a confirmation: who, and whether the answer failed; no // connector, error_code or error, which belong to the line of the run it approved. func (a *Agent) loggedAnswer(err error) []any { - return []any{"app_id", a.options.CustomerID, "agent_id", a.options.AgentID, "success", err == nil} + return []any{"agent_id", a.options.AgentID, "success", err == nil} } // logToolBack writes "a tool call came back" for call, which ran in its TurnID for took and diff --git a/acceleration/internal/agent/turnlinks_test.go b/acceleration/internal/agent/turnlinks_test.go index 38dca967f9..9e420bfe7a 100644 --- a/acceleration/internal/agent/turnlinks_test.go +++ b/acceleration/internal/agent/turnlinks_test.go @@ -177,8 +177,9 @@ func (s *AgentSuite) TestAToolCallIsLoggedWhenItComesBack() { s.Contains(back, "duration_ms") s.NotContains(back, "arguments", "what a caller's tool is given is theirs") s.NotContains(back, "result", "what a caller's tool returns is theirs") - s.Equal("acme", back["customer"]) s.Equal("acme", back["app_id"], "the app is named as the model call line names it") + s.Equal([]int{1}, s.logs.keyCounts(toolBack, "app_id"), "the session logger's app is the line's only one") + s.NotContains(back, "customer") s.Equal(s.agentID, back["agent_id"]) s.Equal(true, back["success"]) s.Equal("", back["error_code"]) diff --git a/acceleration/internal/api/audit.go b/acceleration/internal/api/audit.go index 4548c4a942..336bd1ff5e 100644 --- a/acceleration/internal/api/audit.go +++ b/acceleration/internal/api/audit.go @@ -403,7 +403,7 @@ func (s *Server) auditAs(ctx context.Context, customerID string, record auditRec defer cancel() if err := s.store.AuditEntries.Insert(ctx, &entry); err != nil { s.logger.Error("could not record a configuration change", - "customer", customerID, "resource", record.ResourceType, "id", record.ResourceID, + "app_id", customerID, "resource", record.ResourceType, "id", record.ResourceID, "error", err) } } diff --git a/acceleration/internal/api/callhook.go b/acceleration/internal/api/callhook.go index 906c7d82a8..4ed7e8d3ad 100644 --- a/acceleration/internal/api/callhook.go +++ b/acceleration/internal/api/callhook.go @@ -30,7 +30,7 @@ func (s *Server) answerCall(w http.ResponseWriter, r *http.Request, logger *slog bridge, err := s.phone.InboundBridge(r.Context(), plans.vendor, to) // InboundBridge notes the number's app once the number resolves, before it refuses one. - logger = logger.With("customer", activity.NotedCustomer(r.Context())) + logger = logger.With("app_id", activity.NotedCustomer(r.Context())) if errors.Is(err, phone.ErrNoSealer) { plans.hangUp(w, logger, "hung up a "+plans.vendor+" call: this router has no key to open trunk passwords: "+ "set ROUTER_DEV_KEK (local), or ROUTER_AUTH_KEK_V1_WRAPPED with ROUTER_AUTH_KMS_KEY (hosted), then attach the number again", "to", to) diff --git a/acceleration/internal/api/callhooks.go b/acceleration/internal/api/callhooks.go index c525d7fe08..d0b2c66645 100644 --- a/acceleration/internal/api/callhooks.go +++ b/acceleration/internal/api/callhooks.go @@ -277,7 +277,7 @@ func (s *Server) dispatchArrivingCall(w http.ResponseWriter, r *http.Request, or if _, err := s.store.TelephonySuspensions.Get(r.Context(), number.CustomerID); !errors.Is(err, store.ErrNotSuspended) { 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) + "call", event.CallCid, "app_id", number.CustomerID, "error", err) return true } // The vendor bills the minutes of a call an agent answers, and the agent is billed work, @@ -286,7 +286,7 @@ func (s *Server) dispatchArrivingCall(w http.ResponseWriter, r *http.Request, or answer, _ := moneyError(err) 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) + "call", event.CallCid, "app_id", number.CustomerID, "code", answer.Code) return true } // Only a call that rings a number is worth recording as delivered: every video call in @@ -300,7 +300,7 @@ func (s *Server) dispatchArrivingCall(w http.ResponseWriter, r *http.Request, or if s.sessions == nil { 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) + "call", event.CallCid, "app_id", number.CustomerID, "number", number.E164, "config", number.ConfigID) return true } // The agent joins before it is answering, which can outlast Stream's wait for the @@ -332,16 +332,16 @@ func (s *Server) dispatchArrivingCall(w http.ResponseWriter, r *http.Request, or // Somebody is listening to a ringing phone that nothing is going to answer, which // is the most useful error this service can report. s.logger.Error("nobody could answer an arriving call", - "call", event.CallCid, "session_id", event.SessionID, "customer", number.CustomerID, + "call", event.CallCid, "session_id", event.SessionID, "app_id", number.CustomerID, "number", number.E164, "error", err) 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) + "call", event.CallCid, "app_id", number.CustomerID, "number", number.E164) return true } s.pinHook(origin, number.CustomerID, event.CallCid) s.logger.Info("handed an arriving call to a worker", - "call", event.CallCid, "session_id", event.SessionID, "customer", number.CustomerID, + "call", event.CallCid, "session_id", event.SessionID, "app_id", number.CustomerID, "number", number.E164, "caller", call.CallerNumber, "worker", worker.ID) arrived := []any{"worker", worker.ID, "stream_sip_host", phone.BridgeHost(number.BridgeURI)} if call.SessionID != "" { @@ -357,7 +357,7 @@ func (s *Server) answerWithAgent(ctx context.Context, sessions *session.Manager, config, err := s.store.AgentConfigs.Get(ctx, number.CustomerID, number.ConfigID) if err != nil { s.refuseArrivingCall(ctx, number, callType, callID, event.SessionID, "refused an arriving call to a number whose agent is gone", - "call", event.CallCid, "customer", number.CustomerID, "number", number.E164, + "call", event.CallCid, "app_id", number.CustomerID, "number", number.E164, "config", number.ConfigID, "error", err) return } @@ -393,14 +393,14 @@ func (s *Server) answerWithAgent(ctx context.Context, sessions *session.Manager, return } s.logger.Error("nobody could answer an arriving call", - "call", event.CallCid, "customer", number.CustomerID, + "call", event.CallCid, "app_id", number.CustomerID, "number", number.E164, "config", number.ConfigID, "error", err) s.refuseArrivingCall(ctx, number, callType, callID, event.SessionID, "refused an arriving call its agent could not answer", - "call", event.CallCid, "customer", number.CustomerID, "number", number.E164, "config", number.ConfigID) + "call", event.CallCid, "app_id", number.CustomerID, "number", number.E164, "config", number.ConfigID) return } s.logger.Info("an agent answered an arriving call", - "call", event.CallCid, "customer", number.CustomerID, + "call", event.CallCid, "app_id", number.CustomerID, "number", number.E164, "config", number.ConfigID, "session", created.ID()) } diff --git a/acceleration/internal/api/callhooks_test.go b/acceleration/internal/api/callhooks_test.go index 6f919842b9..7fa0f3fd1e 100644 --- a/acceleration/internal/api/callhooks_test.go +++ b/acceleration/internal/api/callhooks_test.go @@ -207,12 +207,12 @@ func (s *CallHooksSuite) TestTheAccessLineOfASignedCallNamesTheNumbersCustomer() forged, _ := s.deliver(phone.CallHookPath, s.arriving("default:"+s.callID), sign(s.arriving("default:"+s.callID), "not the secret")) s.Require().Equal(http.StatusUnauthorized, forged) s.Require().Eventually(func() bool { return served(" status=401 ") }, settleFor, 10*time.Millisecond) - s.True(served(" status=401 ", ` customer="" `)) + s.False(served(" status=401 ", "app_id="), "a call nobody signed names no app") s.Require().Equal(http.StatusOK, s.arrive("default:"+s.callID)) s.Require().Eventually(func() bool { return served(" status=200 ") }, settleFor, 10*time.Millisecond) // No worker takes it, so it is refused in a 200, with the code it is counted under. - s.True(served(" status=200 ", " customer="+s.customerID()+" ", " error_code=unavailable ")) + s.True(served(" status=200 ", " app_id="+s.customerID()+" ", " error_code=unavailable ")) } // thisTest is what the current test logged, so a line another test logged for a number diff --git a/acceleration/internal/api/channel_owner_test.go b/acceleration/internal/api/channel_owner_test.go index 48e46b0072..cad1214758 100644 --- a/acceleration/internal/api/channel_owner_test.go +++ b/acceleration/internal/api/channel_owner_test.go @@ -332,7 +332,7 @@ func (s *SlackChannelSuite) TestAMessageToAWorkspaceWhoseConnectionsNoAgentBinds s.Equal(http.StatusOK, status) s.nothingLinked() s.Contains(s.logged.String(), `msg="dropped an inbound message: one agent config must bind the connection it came in on"`+ - ` connector=slack_bot customer=`+s.customerID()+` connection=`+second.ConnectionID) + ` connector=slack_bot app_id=`+s.customerID()+` connection=`+second.ConnectionID) } // madeEarlier moves a connection's creation an hour back and sets its status, so it is the diff --git a/acceleration/internal/api/channels_imessage_test.go b/acceleration/internal/api/channels_imessage_test.go index 4181a9881f..cbf371e3ce 100644 --- a/acceleration/internal/api/channels_imessage_test.go +++ b/acceleration/internal/api/channels_imessage_test.go @@ -36,7 +36,7 @@ func (s *ChannelsSuite) TestAMessageInAGroupChatIsNotAnsweredAndKeepsThePersonsC // Until the message is dropped, or answered, so a broken rule fails on what it did. s.Require().Eventually(func() bool { - return strings.Count(s.logged.String(), `msg="not answering a message in a group chat" customer=`+s.customerID()) == i+1 || + return strings.Count(s.logged.String(), `msg="not answering a message in a group chat" app_id=`+s.customerID()) == i+1 || len(s.meta.postedIn(group)) > 0 }, settleFor, 50*time.Millisecond, "is_group %v", isGroup) held := s.contact(config, writer) @@ -57,7 +57,7 @@ func (s *ChannelsSuite) TestAMessageInAGroupChatUnderPhoneIdentityOpensNothing() "is_group %v", isGroup) s.Require().Eventually(func() bool { - return strings.Count(s.logged.String(), `msg="not answering a message in a group chat" customer=`+s.customerID()) == i+1 || + return strings.Count(s.logged.String(), `msg="not answering a message in a group chat" app_id=`+s.customerID()) == i+1 || len(s.meta.postedIn(group)) > 0 }, settleFor, 50*time.Millisecond, "is_group %v", isGroup) _, err := s.store.ContactMapEntries.GetByAddress(context.Background(), s.customerID(), config.Id, @@ -153,7 +153,7 @@ func (s *ChannelsSuite) TestAMessageInAGroupChatFromAnUnlinkedNumberOpensNothing s.Require().Equal(http.StatusAccepted, s.deliverLinq(line, s.linqSays(group, writer, "hello there", true))) s.Require().Eventually(func() bool { - return strings.Contains(s.logged.String(), `msg="not answering a message in a group chat" customer=`+s.customerID()) || + return strings.Contains(s.logged.String(), `msg="not answering a message in a group chat" app_id=`+s.customerID()) || len(s.meta.postedIn(group)) > 0 }, settleFor, 50*time.Millisecond) _, err := s.store.ContactMapEntries.GetByAddress(context.Background(), s.customerID(), config.Id, diff --git a/acceleration/internal/api/channels_test.go b/acceleration/internal/api/channels_test.go index 8a8420c0fc..2040ad40e7 100644 --- a/acceleration/internal/api/channels_test.go +++ b/acceleration/internal/api/channels_test.go @@ -579,7 +579,7 @@ func (s *ChannelsSuite) TestAMessageTheStoreCouldNotClaimIsA500WithoutTheStoresW s.NotContains(string(answered), "claim channel message", text) s.Empty(s.meta.to(writer), "%q not claimed is not answered", text) } - s.Contains(s.logged.String(), `level=ERROR msg="could not claim a channel delivery" customer=`+s.customerID()) + s.Contains(s.logged.String(), `level=ERROR msg="could not claim a channel delivery" app_id=`+s.customerID()) s.Contains(s.logged.String(), "refused by the test", "what the store said is kept in the log") } @@ -1128,7 +1128,7 @@ func (s *ChannelsSuite) TestAMessageToASuspendedOrganizationIsNotAnsweredAndWarn s.Require().Equal(http.StatusAccepted, s.deliver(line, writer, "msg-"+s.utils.uuid(), "and tomorrow?")) s.Require().Eventually(func() bool { - return strings.Contains(s.logged.String(), `level=WARN msg="not answering a channel message" channel=whatsapp customer=`+s.customerID()) + return strings.Contains(s.logged.String(), `level=WARN msg="not answering a channel message" channel=whatsapp app_id=`+s.customerID()) }, settleFor, 10*time.Millisecond, "the router never warned") s.NotContains(s.logged.String(), writer, "the log names no number") s.Len(s.meta.to(writer), 1, "only the answer to the first message") @@ -1154,7 +1154,7 @@ func (s *ChannelsSuite) TestAReplyOfASuspendedOrganizationIsNotWrittenBackAndWar model.answers() s.Require().Eventually(func() bool { - return strings.Contains(s.logged.String(), `level=WARN msg="not writing back on a channel" channel=whatsapp customer=`+s.customerID()) + return strings.Contains(s.logged.String(), `level=WARN msg="not writing back on a channel" channel=whatsapp app_id=`+s.customerID()) }, settleFor, 10*time.Millisecond, "the router never warned") s.NotContains(s.logged.String(), writer, "the log names no number") s.Len(s.meta.to(writer), 1, "only the answer to the first message") diff --git a/acceleration/internal/api/chat_episodes.go b/acceleration/internal/api/chat_episodes.go index f143e031e8..17dda39ab9 100644 --- a/acceleration/internal/api/chat_episodes.go +++ b/acceleration/internal/api/chat_episodes.go @@ -76,7 +76,7 @@ func (s *Server) chatEpisode(ctx context.Context, origin hookOrigin, event messa }) if err != nil { s.logger.Error("could not open the episode of a chat message", "channel", event.ChannelID, - "customer", answering.CustomerID, "config", answering.ConfigID, "error", err) + "app_id", answering.CustomerID, "config", answering.ConfigID, "error", err) return } // Only an episode this message opened gets its card (Cards.Write). Off a hook's request, @@ -90,7 +90,7 @@ func (s *Server) chatEpisode(ctx context.Context, origin hookOrigin, event messa defer cancel() if err := s.chatCards.Write(ctx, opened); err != nil { s.logger.Error("could not write the episode card of a chat message", "channel", event.ChannelID, - "customer", answering.CustomerID, "episode", opened.Episode.ID, "error", err) + "app_id", answering.CustomerID, "episode", opened.Episode.ID, "error", err) } }) } @@ -109,7 +109,7 @@ func (s *Server) checksTokens(ctx context.Context, origin hookOrigin, customer s } if err != nil { s.logger.Warn("could not ask Stream whether an app checks tokens, so no episode card is written", - "customer", customer, "stream_app", origin.app, "error", err) + "app_id", customer, "stream_app", origin.app, "error", err) } return checks } diff --git a/acceleration/internal/api/connector_events.go b/acceleration/internal/api/connector_events.go index a7648913fd..63abdb8e29 100644 --- a/acceleration/internal/api/connector_events.go +++ b/acceleration/internal/api/connector_events.go @@ -209,7 +209,7 @@ func (s *Server) receiveProviderAppEvent(w http.ResponseWriter, r *http.Request) manifest := definition.Manifest if !readsProviderAppEvents(manifest) { s.logger.Info("dropped a provider app's event: the connector has no channel verified with the app's own secret", - "connector", connectorID, "provider_app", appID, "customer", app.CustomerID) + "connector", connectorID, "provider_app", appID, "app_id", app.CustomerID) countEvent(manifest.ID, eventRefused) writeError(w, errNoConnectorEvents) return @@ -369,7 +369,7 @@ func (s *Server) receiveEvent(w http.ResponseWriter, r *http.Request, body []byt // delivery report, is one the manifest reads nothing from. Answered 200 like any other. if len(event.Messages) == 0 && len(event.Skipped) == 0 && len(event.Signals) == 0 { s.logger.Info("a connector event carried no message", "connector", manifest.ID, - "provider_app", app.ProviderAppID, "customer", app.CustomerID) + "provider_app", app.ProviderAppID, "app_id", app.CustomerID) } if len(event.Messages) > 0 { var unanswered *eventforward.Event diff --git a/acceleration/internal/api/connector_provider_apps.go b/acceleration/internal/api/connector_provider_apps.go index 88d3d537e1..ee12f13f9f 100644 --- a/acceleration/internal/api/connector_provider_apps.go +++ b/acceleration/internal/api/connector_provider_apps.go @@ -582,7 +582,7 @@ func (s *Server) configToken(ctx context.Context, customerID, connectorID, sent }) if err != nil { s.logger.Error("could not save a rotated app configuration token; its customer must send a new config_refresh_token", - "customer", customerID, "connector", connectorID, "attempts", attempts, "error", err) + "app_id", customerID, "connector", connectorID, "attempts", attempts, "error", err) return "", err } return rotated.Token, nil diff --git a/acceleration/internal/api/connector_provider_apps_test.go b/acceleration/internal/api/connector_provider_apps_test.go index 5785b1a9bc..6a9d60471f 100644 --- a/acceleration/internal/api/connector_provider_apps_test.go +++ b/acceleration/internal/api/connector_provider_apps_test.go @@ -241,7 +241,7 @@ func (s *ConnectorProviderAppsSuite) TestARotatedConfigTokenWhoseEverySaveFailsI s.Contains(line, s.customerID()) s.Contains(line, "slack_bot") s.Contains(line, "attempts=3") - s.Equal([]string{"time", "level", "msg", "customer", "connector", "attempts", "error"}, logAttributes(line), + s.Equal([]string{"time", "level", "msg", "app_id", "connector", "attempts", "error"}, logAttributes(line), "no field beside these, so none can hold the sealed pair or a token") // The router's logger masks a Slack token as [redacted], so a token the line held would show as that. s.NotContains(line, "[redacted]", "neither the configuration token nor its refresh token is logged") diff --git a/acceleration/internal/api/datamove.go b/acceleration/internal/api/datamove.go index 1696ebd5f4..18e3595a40 100644 --- a/acceleration/internal/api/datamove.go +++ b/acceleration/internal/api/datamove.go @@ -150,7 +150,7 @@ func (s *Server) exportData(w http.ResponseWriter, r *http.Request) { writeError(w, errWritesOpen) return } - s.logger.Error("could not start recording changes", "customer", customerID, "error", err) + s.logger.Error("could not start recording changes", "app_id", customerID, "error", err) writeError(w, unavailable("changes cannot be recorded, so an export would be a copy nothing could catch up from")) return } @@ -194,16 +194,16 @@ func (s *Server) exportData(w http.ResponseWriter, r *http.Request) { writeFailure(w, r, err) return } - s.logger.Error("export stopped partway", "customer", customerID, "error", err) + s.logger.Error("export stopped partway", "app_id", customerID, "error", err) return } now := time.Now().UTC() if err := encode(dataLine{Cursor: &cursor, Customer: customerID, At: &now}); err != nil { - s.logger.Debug("export was not finished", "customer", customerID, "error", err) + s.logger.Debug("export was not finished", "app_id", customerID, "error", err) return } - s.logger.Info("exported a customer", "customer", customerID, "rows", written, "cursor", cursor) + s.logger.Info("exported a customer", "app_id", customerID, "rows", written, "cursor", cursor) } // importData writes an export, or a batch of changes, into this deployment. @@ -267,7 +267,7 @@ func (s *Server) importData(w http.ResponseWriter, r *http.Request) { return } - s.logger.Info("imported a customer", "customer", customerID, "rows", imported.rows, "numbers_left_out", imported.leftOut, + s.logger.Info("imported a customer", "app_id", customerID, "rows", imported.rows, "numbers_left_out", imported.leftOut, "skipped", int64(len(imported.skipped))+imported.skippedMore) answer := map[string]any{"rows": imported.rows, "tables": imported.tables, "skipped": imported.skipped, "cursor": imported.cursor} if imported.skippedMore > 0 { diff --git a/acceleration/internal/api/datamove_test.go b/acceleration/internal/api/datamove_test.go index 5cfd6700ab..b12ac01cc3 100644 --- a/acceleration/internal/api/datamove_test.go +++ b/acceleration/internal/api/datamove_test.go @@ -620,7 +620,7 @@ func (s *DataMoveSuite) TestAnImportedNumberOnItsOwnTrunkAnotherAppHoldsIsLeftOu s.Equal(int64(2), answer.Rows) s.Equal(map[string]int64{"phone_numbers": 2}, answer.Tables) - s.Regexp(`customer=`+regexp.QuoteMeta(s.customerID())+` rows=2 numbers_left_out=2`, s.logged.String(), "the router logs how many it left out") + s.Regexp(`app_id=`+regexp.QuoteMeta(s.customerID())+` rows=2 numbers_left_out=2`, s.logged.String(), "the router logs how many it left out") imported, err := s.store.PhoneNumbers.Select(ctx, s.customerID(), store.PhoneNumberFilter{IncludeReleased: true}) s.Require().NoError(err) var numbers []string diff --git a/acceleration/internal/api/dispatchws.go b/acceleration/internal/api/dispatchws.go index e6ef582574..55d89fff4d 100644 --- a/acceleration/internal/api/dispatchws.go +++ b/acceleration/internal/api/dispatchws.go @@ -85,7 +85,7 @@ func (s *Server) dispatchCalls(w http.ResponseWriter, r *http.Request) { } s.logger.Info("a dispatch worker is waiting for calls", - "customer", customerID, "worker", worker.ID, "capacity", registration.Capacity, + "app_id", customerID, "worker", worker.ID, "capacity", registration.Capacity, "carried", registration.Active, "handles", registration.Handles) // A worker that goes away is noticed by the reader, and the writer is asleep on a diff --git a/acceleration/internal/api/forward.go b/acceleration/internal/api/forward.go index c87c2c0fd1..50502eba3c 100644 --- a/acceleration/internal/api/forward.go +++ b/acceleration/internal/api/forward.go @@ -129,7 +129,7 @@ func (s *Server) nodeFor(r *http.Request) (string, bool, error) { address, err := s.directory.NodeByConversation(r.Context(), customer, cid) if err != nil { s.logger.Warn("could not find out which node is answering in a conversation", - "customer", customer, "conversation", cid, "error", err) + "app_id", customer, "conversation", cid, "error", err) return "", false, nil } return address, true, nil @@ -151,7 +151,7 @@ func (s *Server) nodeFor(r *http.Request) (string, bool, error) { address, err := s.directory.Node(r.Context(), customer, id) if err != nil { s.logger.Warn("could not find out which node is running a session", - "customer", customer, "session", id, "error", err) + "app_id", customer, "session", id, "error", err) return "", false, nil } if address == "" { @@ -421,7 +421,7 @@ func (s *Server) forwardedToWorkers(ctx context.Context, handOver func(context.C addresses, err := s.directory.Waiting(ctx, customerID) if err != nil { s.logger.Warn("could not find out which nodes have a customer's workers", - "customer", customerID, "error", err) + "app_id", customerID, "error", err) return false, false } if len(addresses) == 0 { @@ -435,10 +435,10 @@ func (s *Server) forwardedToWorkers(ctx context.Context, handOver func(context.C switch { case err != nil: s.logger.Error("could not reach the node with a customer's workers", - "node", address, "customer", customerID, "error", err) + "node", address, "app_id", customerID, "error", err) case answer.GetStatus() != http.StatusOK: s.logger.Warn("the node with a customer's workers would not take a hook", - "node", address, "customer", customerID, "status", answer.GetStatus()) + "node", address, "app_id", customerID, "status", answer.GetStatus()) default: return true, true } diff --git a/acceleration/internal/api/hook_activity_test.go b/acceleration/internal/api/hook_activity_test.go index 3d9d83e65d..0ba82cf67e 100644 --- a/acceleration/internal/api/hook_activity_test.go +++ b/acceleration/internal/api/hook_activity_test.go @@ -250,7 +250,7 @@ func (s *TelnyxHookSuite) TestACallWhoseTrunkPasswordCannotBeOpenedIsCountedRefu status, _, body := s.deliver(s.call(s.e164), true) s.Require().Equal(http.StatusOK, status) s.Require().Contains(body, "") - s.Require().True(s.loggedLine("could not find its trunk", "customer="+s.customerID())) + s.Require().True(s.loggedLine("could not find its trunk", "app_id="+s.customerID())) row := s.countedOnce(activity.AreaPhoneSMS, store.AuditSourceAPI) s.Equal(int64(1), row.refused) diff --git a/acceleration/internal/api/inbound_drop_logs_test.go b/acceleration/internal/api/inbound_drop_logs_test.go index a2818e0875..49fb7055a7 100644 --- a/acceleration/internal/api/inbound_drop_logs_test.go +++ b/acceleration/internal/api/inbound_drop_logs_test.go @@ -18,7 +18,7 @@ import ( // ids is how a drop line names the test's provider app, customer, connection and config. func (s *SlackChannelSuite) ids() string { - return "connector=slack_bot provider_app=" + s.app.ProviderAppID + " customer=" + s.customerID() + + return "connector=slack_bot provider_app=" + s.app.ProviderAppID + " app_id=" + s.customerID() + " connection=" + s.bot.ConnectionID + " config=" + s.config.ID } @@ -120,7 +120,7 @@ func (s *SlackChannelSuite) TestAnEventForAProviderAppOfAConnectorWithoutAChanne s.Equal(http.StatusNotFound, status, "as before") s.Contains(s.since(before), `level=INFO msg="dropped a provider app's event: the connector has no channel verified with the app's own secret" `+ - "connector=github provider_app="+appID+" customer="+s.customerID()) + "connector=github provider_app="+appID+" app_id="+s.customerID()) } // A message the manifest skips is not "no message": its skip line says why, and the @@ -147,7 +147,7 @@ func (s *WhatsAppChannelSuite) TestADeliveryReportIsLoggedAtInfoAsCarryingNoMess s.nothingLinked() logged := s.logged.String()[before:] - s.Contains(logged, `level=INFO msg="a connector event carried no message" connector=whatsapp provider_app=`+s.app+" customer="+s.customerID()) + s.Contains(logged, `level=INFO msg="a connector event carried no message" connector=whatsapp provider_app=`+s.app+" app_id="+s.customerID()) s.NotContains(logged, "16505551234") } diff --git a/acceleration/internal/api/logapp_test.go b/acceleration/internal/api/logapp_test.go index bef9eabf13..0b36391a83 100644 --- a/acceleration/internal/api/logapp_test.go +++ b/acceleration/internal/api/logapp_test.go @@ -260,9 +260,9 @@ func (s *LogAppSuite) TestACallerOfALevelItsAppTurnsAwayHasAnAccessLineNamingThe line := s.lineOf(id) s.Equal("forbidden", s.field(line, "error_code")) s.Equal(s.customerID(), s.field(line, "app_id")) + s.Equal(1, strings.Count(line, " app_id="), line) s.Equal(s.app.key, s.field(line, "api_key")) - // It is no customer here: nothing it asked for is the app's. - s.Empty(s.field(line, "customer")) + s.NotContains(line, " customer=") } // Defect: a hook naming another numeric app answered with the bare 404 of http.NotFound and @@ -638,10 +638,13 @@ func (s *LogAppSuite) TestNoLineNamesTheKeysSecret() { s.NotContains(s.logged.String(), s.app.secret) } -func (s *LogAppSuite) TestTheAccessLineStillNamesTheCustomer() { +// The app is named once, as app_id: the customer the credential names is the same app (AI-3909). +func (s *LogAppSuite) TestTheAccessLineNamesTheAppOnce() { line := s.servedAs(s.serverClient) - s.Contains(line, " customer="+s.customerID()+" ") + s.Equal(s.customerID(), s.field(line, "app_id")) + s.Equal(1, strings.Count(line, " app_id="), line) + s.NotContains(line, " customer=") } func (s *LogAppSuite) TestTheAccessLineOfARequestNobodyAuthenticatedNamesNeither() { @@ -679,7 +682,7 @@ func (s *LogAppSuite) TestTheAccessLineOfAHookNamesNeitherEvenWhenTheCallerSends s.NotContains(line, "app_id") s.NotContains(line, "api_key") // Defect (AI-3349): the customer the caller's credential names, on a hook nobody checked. - s.Contains(line, ` customer="" `) + s.NotContains(line, "customer=") } func (s *LogAppSuite) TestALineAHandlerLogsWithTheRequestsContextNamesTheAppAndItsPublicKey() { @@ -774,7 +777,8 @@ func (s *LogAppSuite) TestTheAccessLineOfAServerErrorNamesTheAppAndItsPublicKey( // A handler's verified hook names its app on the lines withRequestLog writes after it: a 5xx // and a panic as well as a success, and on the lines the handler logs with its context. The key // whose secret signed it is no key the request was made with, so none of them names it. The -// customer the handler noted for it (activity.NoteCustomer) is the lines' customer (AI-3349). +// verified app is the lines' only app_id: the customer the handler noted for it +// (activity.NoteCustomer) is not named beside it (AI-3909). func (s *LogAppSuite) TestTheLinesAfterAHandlerVerifiedAHookNameItsApp() { customer := s.utils.uuid() for msg, answer := range map[string]func(http.ResponseWriter){ @@ -811,7 +815,8 @@ func (s *LogAppSuite) TestTheLinesAfterAHandlerVerifiedAHookNameItsApp() { return false }, 5*time.Second, 20*time.Millisecond, msg) s.Equal("1234567", s.field(line, "app_id"), msg) - s.Equal(customer, s.field(line, "customer"), msg) + s.Equal(1, strings.Count(line, " app_id="), msg) + s.NotContains(line, customer, msg) s.NotContains(line, "api_key", msg) var probe string for l := range strings.Lines(s.logged.String()) { @@ -824,6 +829,56 @@ func (s *LogAppSuite) TestTheLinesAfterAHandlerVerifiedAHookNameItsApp() { } } +// A hook whose handler noted the app it is for (activity.NoteCustomer) without marking its +// context, as an SMS or a connector event does, names that app as app_id, once, on its access +// line and its panic line; a hook nobody noted names no app (AI-3909). +func (s *LogAppSuite) TestTheAccessLineOfAHookItsHandlerOnlyNotedNamesThatApp() { + customer := s.utils.uuid() + for msg, noted := range map[string]bool{ + `msg="served a request" method=POST path=/noted-ok `: true, + `msg="a request panicked" method=POST path=/noted-panic `: true, + `msg="served a request" method=POST path=/unnoted `: false, + } { + path := strings.Fields(strings.SplitAfter(msg, "path=")[1])[0] + routes := chi.NewRouter() + routes.Post(path, func(_ http.ResponseWriter, r *http.Request) { + if noted { + activity.NoteCustomer(r.Context(), customer, activity.AreaHooksIn) + } + if strings.HasSuffix(path, "panic") { + panic("probe panic") + } + }) + node := httptest.NewUnstartedServer(s.router.withRequestLog(routes, routes)) + node.Config.ErrorLog = log.New(io.Discard, "", 0) + node.Start() + s.T().Cleanup(node.Close) + + // A panic goes on to net/http after the 500, which drops the connection. + if response, err := node.Client().Post(node.URL+path, "application/json", nil); err == nil { + s.Require().NoError(response.Body.Close()) + } + + var line string + s.Require().Eventually(func() bool { + for l := range strings.Lines(s.logged.String()) { + if strings.Contains(l, msg) { + line = l + return true + } + } + return false + }, 5*time.Second, 20*time.Millisecond, msg) + s.NotContains(line, "customer=", msg) + if !noted { + s.NotContains(line, "app_id", msg) + continue + } + s.Equal(customer, s.field(line, "app_id"), msg) + s.Equal(1, strings.Count(line, " app_id="), msg) + } +} + // servedAs is the access line of a GET by client. func (s *appLogSuite) servedAs(client *testClient) string { id := s.utils.uuid() diff --git a/acceleration/internal/api/logcontext_test.go b/acceleration/internal/api/logcontext_test.go index 2b138a6589..afc79356fc 100644 --- a/acceleration/internal/api/logcontext_test.go +++ b/acceleration/internal/api/logcontext_test.go @@ -4,11 +4,15 @@ import ( "bytes" "context" "log/slog" + "net/http" + "net/http/httptest" "strings" "sync" "testing" "github.com/stretchr/testify/suite" + + "github.com/GetStream/Vision-Agents/acceleration/internal/activity" ) type LogHandlerSuite struct { @@ -35,6 +39,19 @@ func (s *LogHandlerSuite) TestALineLoggedWithTheRequestsContextNamesItsAppAndKey s.Contains(s.out.String(), " x=1 app_id=1732479 api_key=pubkey123\n") } +// An access line whose context was marked with a key but no app names the app its handler +// noted: the log handler adds no empty app_id, so the line names it, once (AI-3909). +func (s *LogHandlerSuite) TestAnAccessLineWhoseContextNamesNoAppNamesTheNotedOne() { + ctx, note := activity.WithNote(WithLoggedApp(context.Background(), "", "pubkey123")) + activity.NoteCustomer(ctx, "1000001", activity.AreaHooksIn) + r := httptest.NewRequest(http.MethodPost, "/hook", nil).WithContext(ctx) + + s.logger.InfoContext(ctx, "served a request", loggedAppFields(ctx, r, note)...) + + s.Equal(1, strings.Count(s.out.String(), "app_id="), s.out.String()) + s.Contains(s.out.String(), " app_id=1000001 api_key=pubkey123\n") +} + func (s *LogHandlerSuite) TestALineLoggedWithoutTheContextNamesNeither() { s.logger.Info("probe") s.logger.InfoContext(context.Background(), "probe") diff --git a/acceleration/internal/api/logkeys_guard_test.go b/acceleration/internal/api/logkeys_guard_test.go new file mode 100644 index 0000000000..636cc75170 --- /dev/null +++ b/acceleration/internal/api/logkeys_guard_test.go @@ -0,0 +1,82 @@ +package api + +import ( + "go/ast" + "go/parser" + "go/token" + "io/fs" + "path/filepath" + "strconv" + "strings" +) + +// loggerMethods are the slog calls whose arguments after the message are key-value pairs. +var loggerMethods = map[string]int{ + "Debug": 1, "Info": 1, "Warn": 1, "Error": 1, + "DebugContext": 2, "InfoContext": 2, "WarnContext": 2, "ErrorContext": 2, + "Log": 3, "With": 0, + // Helpers that pass their trailing key-value pairs on to a logger. + "refuseArrivingCall": 6, "failedRead": 2, "hangUp": 3, "refuse": 3, +} + +// attrConstructors are the log/slog functions whose first argument is an attribute key. +var attrConstructors = map[string]bool{ + "String": true, "Int": true, "Int64": true, "Uint64": true, "Float64": true, + "Bool": true, "Time": true, "Duration": true, "Any": true, "Group": true, +} + +// The router names the Stream app app_id on every line (AI-3909): a line naming it customer +// is one ClickHouse files under the old key only while its fallback lasts. +func (s *LogHandlerSuite) TestNoLineNamesTheAppCustomer() { + root := filepath.Join("..", "..") + files := token.NewFileSet() + var found []string + err := filepath.WalkDir(root, func(name string, entry fs.DirEntry, err error) error { + if err != nil || entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") { + return err + } + parsed, err := parser.ParseFile(files, name, nil, parser.SkipObjectResolution) + if err != nil { + return err + } + ast.Inspect(parsed, func(node ast.Node) bool { + keys := func(args []ast.Expr, first int) { + for i := first; i < len(args); i += 2 { + if literal, ok := args[i].(*ast.BasicLit); ok && literal.Kind == token.STRING { + if key, _ := strconv.Unquote(literal.Value); key == "customer" { + found = append(found, files.Position(literal.Pos()).String()) + } + } + } + } + switch node := node.(type) { + case *ast.CompositeLit: + // The fields a line is built from: []any{"app_id", ...}. + if array, ok := node.Type.(*ast.ArrayType); ok { + if element, ok := array.Elt.(*ast.Ident); ok && element.Name == "any" { + keys(node.Elts, 0) + } + } + case *ast.CallExpr: + switch fun := node.Fun.(type) { + case *ast.SelectorExpr: + if first, ok := loggerMethods[fun.Sel.Name]; ok { + keys(node.Args, first) + } + // slog.String("app_id", v): the key is the first argument. + if pkg, ok := fun.X.(*ast.Ident); ok && pkg.Name == "slog" && attrConstructors[fun.Sel.Name] && len(node.Args) > 0 { + keys(node.Args[:1], 0) + } + case *ast.Ident: + if fun.Name == "append" { + keys(node.Args, 1) + } + } + } + return true + }) + return nil + }) + s.Require().NoError(err) + s.Empty(found, "a line names the app as customer: name it app_id") +} diff --git a/acceleration/internal/api/messagehooks.go b/acceleration/internal/api/messagehooks.go index f16918e15e..66bd6e0fe3 100644 --- a/acceleration/internal/api/messagehooks.go +++ b/acceleration/internal/api/messagehooks.go @@ -375,7 +375,7 @@ func (s *Server) routeArrivingMessage(ctx context.Context, origin hookOrigin, ev }, "") if err != nil { s.logger.Error("nobody could answer an arriving message", - "channel", event.ChannelID, "session", found.ID(), "customer", found.Spec().CustomerID, + "channel", event.ChannelID, "session", found.ID(), "app_id", found.Spec().CustomerID, "error", err) if errors.Is(err, node.ErrNoReply) { // The other node may have placed it before its reply was lost: queued @@ -416,12 +416,12 @@ func (s *Server) routeArrivingMessage(ctx context.Context, origin hookOrigin, ev if may, err := s.mayStillWrite(ctx, origin, customerID); !may { if err != nil && origin.queued { s.logger.Error("not starting work for a customer whose app could not be read", - "channel", event.ChannelID, "customer", customerID, "error", err) + "channel", event.ChannelID, "app_id", customerID, "error", err) return false } // A hook is not tried again, so it ends here as it always has. s.logger.Info("not starting work in the deployment's app for a customer no longer writing there", - "channel", event.ChannelID, "customer", customerID) + "channel", event.ChannelID, "app_id", customerID) return true } @@ -452,7 +452,7 @@ func (s *Server) routeArrivingMessage(ctx context.Context, origin hookOrigin, ev // Read before the delivery is settled, so a read that failed is tried again. if heardFor, err = s.unopenedSpec(ctx, customerID, configID, event); err != nil { s.logger.Error("could not read the config a voice recording would be heard for", - "channel", event.ChannelID, "customer", customerID, "config", configID, "error", err) + "channel", event.ChannelID, "app_id", customerID, "config", configID, "error", err) return false } } @@ -474,12 +474,12 @@ func (s *Server) routeArrivingMessage(ctx context.Context, origin hookOrigin, ev // Somebody has written to an agent that nothing is going to answer, which is the // most useful error this service can report. s.logger.Error("nobody could answer an arriving message", - "channel", event.ChannelID, "customer", customerID, "error", err) + "channel", event.ChannelID, "app_id", customerID, "error", err) s.unanswered(ctx, origin) return false } s.logger.Info("handed an arriving message to a worker", - "channel", event.ChannelID, "customer", customerID, + "channel", event.ChannelID, "app_id", customerID, "config", configID, "worker", worker.ID, "stream_app", origin.app) return true }) @@ -723,7 +723,7 @@ func (s *Server) declaredConfigOf(ctx context.Context, origin hookOrigin, event // to two routers, such as a local one and staging, sends each the other's channels too. if errors.Is(err, store.ErrNoAgentConfig) { s.logger.Info("an arriving message's channel names a config nobody in its app holds", - "channel", event.ChannelID, "config", declared, "stream_app", origin.app, "customer", origin.customer) + "channel", event.ChannelID, "config", declared, "stream_app", origin.app, "app_id", origin.customer) return store.AgentConfig{}, false, nil } if err != nil { @@ -808,7 +808,7 @@ func (s *Server) dispatchText(ctx context.Context, found *session.Session, messa return conversation.CommandReceipt{}, err } s.logger.Info("handed a message to a worker", - "session", found.ID(), "customer", spec.CustomerID, "worker", workerID) + "session", found.ID(), "app_id", spec.CustomerID, "worker", workerID) return receipt, nil } @@ -842,7 +842,7 @@ func (s *Server) followUpMessage(ctx context.Context, origin hookOrigin, found * } if err != nil { s.logger.Error("could not answer a message", "channel", event.ChannelID, "session", found.ID(), - "customer", found.Spec().CustomerID, "error", err) + "app_id", found.Spec().CustomerID, "error", err) } return } @@ -866,7 +866,7 @@ func (s *Server) answerMessage(ctx context.Context, origin hookOrigin, found *se text, images := s.messagePhotos(ctx, found.SeesImagesInWriting(), heard, event) if _, err := found.Ask(ctx, text, images...); err != nil { s.logger.Error("could not answer a message", - "channel", event.ChannelID, "session", found.ID(), "customer", found.Spec().CustomerID, "error", err) + "channel", event.ChannelID, "session", found.ID(), "app_id", found.Spec().CustomerID, "error", err) return } s.logger.Debug("answered a message in writing", diff --git a/acceleration/internal/api/phone.go b/acceleration/internal/api/phone.go index 3e51dc375d..a0a7a206e4 100644 --- a/acceleration/internal/api/phone.go +++ b/acceleration/internal/api/phone.go @@ -479,7 +479,7 @@ func (s *Server) answerPhoneCall(w http.ResponseWriter, r *http.Request) { plan, err := s.phone.Answer(r.Context(), token) // Answer notes the call's app once its token resolves. - logger := s.logger.With("customer", activity.NotedCustomer(r.Context())) + logger := s.logger.With("app_id", activity.NotedCustomer(r.Context())) if err != nil { // 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. diff --git a/acceleration/internal/api/quota.go b/acceleration/internal/api/quota.go index d4312a7c00..97430dd311 100644 --- a/acceleration/internal/api/quota.go +++ b/acceleration/internal/api/quota.go @@ -113,7 +113,7 @@ func (s *Server) withQuota(next http.Handler) http.Handler { return } s.logger.Info("refused a caller who has spent their day", - "method", r.Method, "path", loggedPath(s.mux, r), "customer", customerID) + "method", r.Method, "path", loggedPath(s.mux, r), "app_id", customerID) w.Header().Set("Retry-After", strconv.Itoa(max(int(time.Until(status.Reset).Seconds()), 1))) writeError(w, rateLimited(err.Error())) return diff --git a/acceleration/internal/api/runs_test.go b/acceleration/internal/api/runs_test.go index bff0155f74..79ab1fcd0c 100644 --- a/acceleration/internal/api/runs_test.go +++ b/acceleration/internal/api/runs_test.go @@ -354,8 +354,8 @@ func (s *RunsSuite) TestARunLogsHowManyImagesItCarried() { without := s.run(CreateRunRequest{ConfigId: config, Input: "hello"}) logged := s.logged.String() - s.Contains(logged, `msg="a run started" customer=`+s.customerID()+" session="+withImages.SessionId+" config="+config+" images=2") - s.Contains(logged, `msg="a run started" customer=`+s.customerID()+" session="+without.SessionId+" config="+config+" images=0") + s.Contains(logged, `msg="a run started" app_id=`+s.customerID()+" session="+withImages.SessionId+" config="+config+" images=2") + s.Contains(logged, `msg="a run started" app_id=`+s.customerID()+" session="+without.SessionId+" config="+config+" images=0") } func (s *RunsSuite) TestAnImageThatCannotBeFetchedIsUnavailable() { diff --git a/acceleration/internal/api/scheduled_tasks.go b/acceleration/internal/api/scheduled_tasks.go index 52ad051ab7..71dd953cf0 100644 --- a/acceleration/internal/api/scheduled_tasks.go +++ b/acceleration/internal/api/scheduled_tasks.go @@ -750,7 +750,7 @@ func (s *Server) scheduledTaskOf(ctx context.Context, task store.ScheduledTask) last, err := s.store.ScheduledTaskRuns.LastFinishedAt(ctx, task.CustomerID, []string{task.ID}) if err != nil { s.logger.Error("could not read when a scheduled task last ran", "task", task.ID, - "customer", task.CustomerID, "error", err) + "app_id", task.CustomerID, "error", err) } return scheduledTaskRendered(task, last[task.ID]) } diff --git a/acceleration/internal/api/scheduled_unpaid_test.go b/acceleration/internal/api/scheduled_unpaid_test.go index aff53649db..f19923c3c7 100644 --- a/acceleration/internal/api/scheduled_unpaid_test.go +++ b/acceleration/internal/api/scheduled_unpaid_test.go @@ -209,7 +209,7 @@ func (s *TelnyxUnpaidSuite) TestAThreadTaskOfASuspendedOrganizationIsNotRetried( s.Equal(codeAccountSuspended, *run.Error) s.Equal(int32(1), attempts, "a suspension outlasts every retry of the run") s.Len(s.telnyx().sent(), 1, "only the answer to hi") - s.Contains(s.logged.String(), `level=WARN msg="held a channel message back: the organization may not pay for it" connector=telnyx customer=`+s.customerID()) + s.Contains(s.logged.String(), `level=WARN msg="held a channel message back: the organization may not pay for it" connector=telnyx app_id=`+s.customerID()) } // A thread task whose organization's money cannot be checked, as when the router cannot share diff --git a/acceleration/internal/api/server.go b/acceleration/internal/api/server.go index 42a6623460..f4e870231d 100644 --- a/acceleration/internal/api/server.go +++ b/acceleration/internal/api/server.go @@ -1101,10 +1101,11 @@ func (s *Server) withRequestLog(routes *chi.Mux, next http.Handler) http.Handler } // ErrAbortHandler is net/http's own way of dropping a connection, not a bug. if recovered != http.ErrAbortHandler { - s.logger.ErrorContext(failure.loggedContext(r.Context()), "a request panicked", - "method", r.Method, "path", loggedPath(routes, r), "customer", loggedCustomer(r, note), - "request_id", RequestIDFrom(r.Context()), - "panic", fmt.Sprint(recovered), "stack", string(debug.Stack())) + logged := failure.loggedContext(r.Context()) + fields := append([]any{"method", r.Method, "path", loggedPath(routes, r)}, loggedAppFields(logged, r, note)...) + s.logger.ErrorContext(logged, "a request panicked", + append(fields, "request_id", RequestIDFrom(r.Context()), + "panic", fmt.Sprint(recovered), "stack", string(debug.Stack()))...) if recorder.code == 0 && recorder.written == 0 && !recorder.hijacked { writeError(recorder, internalError()) } @@ -1124,9 +1125,10 @@ func (s *Server) withRequestLog(routes *chi.Mux, next http.Handler) http.Handler "path", loggedPath(routes, r), "status", recorder.status(), "duration", time.Since(started).Round(time.Millisecond), - "customer", loggedCustomer(r, note), - "request_id", RequestIDFrom(r.Context()), } + logged := failure.loggedContext(r.Context()) + fields = append(fields, loggedAppFields(logged, r, note)...) + fields = append(fields, "request_id", RequestIDFrom(r.Context())) if recorder.written > 0 { fields = append(fields, "bytes", recorder.written) } @@ -1138,7 +1140,6 @@ func (s *Server) withRequestLog(routes *chi.Mux, next http.Handler) http.Handler fields = append(fields, "stack", failure.trace) } fields = append(fields, s.accessFields(r, recorder, failure.operation)...) - logged := failure.loggedContext(r.Context()) if recorder.status() >= http.StatusInternalServerError { s.logger.ErrorContext(logged, "served a request", fields...) return @@ -1147,14 +1148,23 @@ func (s *Server) withRequestLog(routes *chi.Mux, next http.Handler) http.Handler }) } -// loggedCustomer is the customer the request's access line names: the one its credential names, -// or, for a hook, which no credential names, the app its handler noted once it checked the hook +// loggedAppFields is the app_id the request's access line names when the log handler names none: +// a line logged with a context marked with an app (WithLoggedApp) gets that app from the handler, +// so it names app_id once. Any other line names the customer its credential names, or, for a hook, +// which no credential names, the app its handler noted once it checked the hook // (activity.NoteCustomer). A hook it did not check names none. -func loggedCustomer(r *http.Request, note *activity.Note) string { - if customer, ok := CustomerFrom(r.Context()); ok { - return customer +func loggedAppFields(logged context.Context, r *http.Request, note *activity.Note) []any { + if app, ok := logged.Value(loggedAppContextKey{}).(loggedApp); ok && app.appID != "" { + return nil + } + app, ok := CustomerFrom(r.Context()) + if !ok { + app = note.AppID + } + if app == "" { + return nil } - return note.AppID + return []any{logAppField, app} } // refuseLogged answers r with failure through withRequestLog, for a refusal made before the @@ -1605,7 +1615,7 @@ func (s *Server) recordUser(ctx context.Context, principal auth.Principal) { } if err != nil { s.logger.Error("could not record an end user", - "customer", principal.AppID, "user", principal.UserID, "error", err) + "app_id", principal.AppID, "user", principal.UserID, "error", err) } } @@ -1622,7 +1632,7 @@ func (s *Server) recordShard(ctx context.Context, principal auth.Principal) { } if err := s.store.Users.Served(ctx, principal.AppID, principal.UserID, s.directory.Shard()); err != nil { s.logger.Error("could not record the shard serving an end user", - "customer", principal.AppID, "user", principal.UserID, "error", err) + "app_id", principal.AppID, "user", principal.UserID, "error", err) } } @@ -1636,7 +1646,7 @@ func (s *Server) recordEmail(ctx context.Context, principal auth.Principal) { return } if err := s.store.Users.Email(ctx, principal.AppID, principal.UserID, principal.Email); err != nil { - s.logger.Error("could not record an end user's email", "customer", principal.AppID, "user", principal.UserID, "error", err) + s.logger.Error("could not record an end user's email", "app_id", principal.AppID, "user", principal.UserID, "error", err) } } diff --git a/acceleration/internal/api/session_create.go b/acceleration/internal/api/session_create.go index 80d88672cb..53bafec441 100644 --- a/acceleration/internal/api/session_create.go +++ b/acceleration/internal/api/session_create.go @@ -90,12 +90,12 @@ func (s *Server) createSession(ctx context.Context, request *createSessionReques func (s *Server) logNotConfigured(ctx context.Context, customerID string, err error) { if found, ok := errors.AsType[*session.UnkeptError](err); ok { s.logger.WarnContext(ctx, "a session that is not incognito has no Stream app to be kept in", - "customer", customerID, "request_id", RequestIDFrom(ctx), "error", err, "cause", found.Cause) + "app_id", customerID, "request_id", RequestIDFrom(ctx), "error", err, "cause", found.Cause) return } if errors.Is(err, session.ErrNotConfigured) { s.logger.WarnContext(ctx, "a session lacks a setting of this deployment", - "customer", customerID, "request_id", RequestIDFrom(ctx), "error", err) + "app_id", customerID, "request_id", RequestIDFrom(ctx), "error", err) } } diff --git a/acceleration/internal/api/shardhandover.go b/acceleration/internal/api/shardhandover.go index 6d81b678d9..1361aa0095 100644 --- a/acceleration/internal/api/shardhandover.go +++ b/acceleration/internal/api/shardhandover.go @@ -172,7 +172,7 @@ func (s *Server) userShard(ctx context.Context, customerID, region, userID strin } last, err := s.store.Users.Shard(ctx, customerID, userID) if err != nil { - s.logger.Warn("could not read the shard that last served a user", "customer", customerID, "user", userID, "error", err) + s.logger.Warn("could not read the shard that last served a user", "app_id", customerID, "user", userID, "error", err) } return s.shards.ForUser(region, last) } @@ -187,7 +187,7 @@ func (s *Server) configShard(ctx context.Context, customerID, configID, userID s if configID != "" { config, err := s.store.AgentConfigs.Get(ctx, customerID, configID) if err != nil && !errors.Is(err, store.ErrNoAgentConfig) { - s.logger.Warn("could not read the region of the agent answering a message", "customer", customerID, "config", configID, "error", err) + s.logger.Warn("could not read the region of the agent answering a message", "app_id", customerID, "config", configID, "error", err) } region = config.Region } diff --git a/acceleration/internal/api/streams_test.go b/acceleration/internal/api/streams_test.go index 394249b8ac..1b1c4ec24d 100644 --- a/acceleration/internal/api/streams_test.go +++ b/acceleration/internal/api/streams_test.go @@ -949,7 +949,7 @@ func (s *StreamsSuite) TestAVendorThatRefusesTheAccountHandsTheSocketToTheNextMo } s.Require().Len(failovers, 1, "%v", failovers) s.Contains(failovers[0], `level=INFO msg="the transcriber refused the session, the next model took it over" `+ - `customer=`+s.customerID()+` call=`+callID+` from=refusing/`+handingOverModel+ + `app_id=`+s.customerID()+` call=`+callID+` from=refusing/`+handingOverModel+ ` provider=echoing model=echoing-model error="`+termsRefusal+`"`) } diff --git a/acceleration/internal/api/streamws.go b/acceleration/internal/api/streamws.go index cb9e10443f..3475c162c9 100644 --- a/acceleration/internal/api/streamws.go +++ b/acceleration/internal/api/streamws.go @@ -331,7 +331,7 @@ func (s *Server) streamSTT( if failover, ok := event.(stt.Failover); ok { // The caller hears only of the next model; the vendor's reason is said here. s.logger.Info("the transcriber refused the session, the next model took it over", - "customer", request.CustomerID, "call", request.CallID, "from", failover.From, + "app_id", request.CustomerID, "call", request.CallID, "from", failover.From, "provider", failover.Provider, "model", failover.Model, "error", failover.Err) } if encoded, ok := sttFrame(event); ok { diff --git a/acceleration/internal/api/stuck_logs_test.go b/acceleration/internal/api/stuck_logs_test.go index 26721a9383..c201ac13b2 100644 --- a/acceleration/internal/api/stuck_logs_test.go +++ b/acceleration/internal/api/stuck_logs_test.go @@ -16,7 +16,7 @@ import ( // loggedOneLine is the pattern of one log line holding level and msg, then customer. func loggedOneLine(level, msg, customer string) *regexp.Regexp { - return regexp.MustCompile(`level=` + level + ` msg="` + regexp.QuoteMeta(msg) + `"[^\n]* customer=` + + return regexp.MustCompile(`level=` + level + ` msg="` + regexp.QuoteMeta(msg) + `"[^\n]* app_id=` + regexp.QuoteMeta(customer) + `( |\n)`) } diff --git a/acceleration/internal/api/suspensions.go b/acceleration/internal/api/suspensions.go index 02ef71eb68..f16a48d5d6 100644 --- a/acceleration/internal/api/suspensions.go +++ b/acceleration/internal/api/suspensions.go @@ -80,7 +80,7 @@ func (s *Server) suspendTelephony(ctx context.Context, request *suspendTelephony return nil, err } s.logger.Info("suspended an app's telephony", - "customer", suspension.CustomerID, "suspended_by", suspension.SuspendedBy) + "app_id", suspension.CustomerID, "suspended_by", suspension.SuspendedBy) return &telephonySuspensionResponse{Body: telephonySuspension(suspension)}, nil } @@ -96,7 +96,7 @@ func (s *Server) liftTelephonySuspension(ctx context.Context, request *telephony if err != nil { return nil, err } - s.logger.Info("lifted an app's telephony suspension", "customer", request.CustomerID) + s.logger.Info("lifted an app's telephony suspension", "app_id", request.CustomerID) return nil, nil } diff --git a/acceleration/internal/api/telnyx_channel_test.go b/acceleration/internal/api/telnyx_channel_test.go index cb70a4d44f..db5f5cda99 100644 --- a/acceleration/internal/api/telnyx_channel_test.go +++ b/acceleration/internal/api/telnyx_channel_test.go @@ -295,7 +295,7 @@ func (s *TelnyxChannelSuite) TestAKeywordIsAnsweredOnceWhenItsRowIsTakenAgain() s.took(1) channel := s.threadChannel(person) s.Require().Eventually(func() bool { - return strings.Contains(s.logged.String(), `msg="could not record an inbound message's attempt" connector=telnyx customer=`+s.customerID()+" channel="+channel) + return strings.Contains(s.logged.String(), `msg="could not record an inbound message's attempt" connector=telnyx app_id=`+s.customerID()+" channel="+channel) }, settleFor, 10*time.Millisecond, "the attempt was recorded") drop() diff --git a/acceleration/internal/api/telnyxhook_test.go b/acceleration/internal/api/telnyxhook_test.go index cd586a1fa7..38163c07ce 100644 --- a/acceleration/internal/api/telnyxhook_test.go +++ b/acceleration/internal/api/telnyxhook_test.go @@ -184,12 +184,13 @@ func (s *TelnyxHookSuite) TestTheAccessLineOfASignedCallNamesTheNumbersCustomer( unsigned, _, _ := s.deliver(s.call(s.e164), false) s.Require().Equal(http.StatusUnauthorized, unsigned) s.Require().Eventually(func() bool { return served(" status=401 ") }, settleFor, 10*time.Millisecond) - s.True(served(" status=401 ", ` customer="" `, " error_code=unauthenticated ")) + s.True(served(" status=401 ", " error_code=unauthenticated ")) + s.False(served(" status=401 ", "app_id="), "a call nobody signed names no app") signed, _, body := s.deliver(s.call(s.e164), true) s.Require().Equal(http.StatusOK, signed, body) s.Require().Eventually(func() bool { return served(" status=200 ") }, settleFor, 10*time.Millisecond) - s.True(served(" status=200 ", " customer="+s.customerID()+" ")) + s.True(served(" status=200 ", " app_id="+s.customerID()+" ")) } // thisTest is what the current test logged, so a line another test logged for a number diff --git a/acceleration/internal/api/user_policies.go b/acceleration/internal/api/user_policies.go index a79eb0af01..aaf0230f31 100644 --- a/acceleration/internal/api/user_policies.go +++ b/acceleration/internal/api/user_policies.go @@ -405,7 +405,7 @@ func (s *Server) userPolicyOf(ctx context.Context, appID, userID string) (UserPo held := s.quota.Effective(ctx, appID, userID) messages, tokens, reset, err := s.quota.Today(ctx, appID, userID) if err != nil { - s.logger.Error("could not read what a user spent today", "customer", appID, "error", err) + s.logger.Error("could not read what a user spent today", "app_id", appID, "error", err) } return UserPolicy{ UserId: userID, Quota: quotaFor(own.Quota), diff --git a/acceleration/internal/campaign/campaign.go b/acceleration/internal/campaign/campaign.go index da6caf354b..92123fb7c0 100644 --- a/acceleration/internal/campaign/campaign.go +++ b/acceleration/internal/campaign/campaign.go @@ -467,7 +467,7 @@ func (r *Runner) ring(ctx context.Context, campaign store.Campaign, contact stor } if err != nil { r.logger.Warn("a campaign dial failed", "campaign", campaign.ID, "contact", contact.ID, - "customer", campaign.CustomerID, "error", err) + "app_id", campaign.CustomerID, "error", err) if dialed.Result == "" && dialed.Outcome == "" { dialed = resultOf(err) } diff --git a/acceleration/internal/channelbridge/bridge.go b/acceleration/internal/channelbridge/bridge.go index f58c2f86d5..fee145d185 100644 --- a/acceleration/internal/channelbridge/bridge.go +++ b/acceleration/internal/channelbridge/bridge.go @@ -412,7 +412,7 @@ func (b *Bridge) Deliver(ctx context.Context, app store.ConnectorOAuthClient, me } answered = true b.logger.Info("accepted an inbound message", "connector", message.ConnectorID, "provider_app", app.ProviderAppID, - "customer", thread.CustomerID, "config", config.ID, "channel", thread.ChannelID) + "app_id", thread.CustomerID, "config", config.ID, "channel", thread.ChannelID) var waited func(core.InboundMessage) (store.ChannelInbound, bool, error) if waiting != nil { waited = func(reply core.InboundMessage) (store.ChannelInbound, bool, error) { @@ -430,10 +430,10 @@ func (b *Bridge) Deliver(ctx context.Context, app store.ConnectorOAuthClient, me } if !fresh { b.logger.Info("dropped a retried inbound message", "connector", message.ConnectorID, "provider_app", app.ProviderAppID, - "customer", app.CustomerID, "connection", thread.ConnectionID, "config", config.ID, "channel", thread.ChannelID) + "app_id", app.CustomerID, "connection", thread.ConnectionID, "config", config.ID, "channel", thread.ChannelID) } else { b.logger.Info("queued an inbound message", "connector", message.ConnectorID, "provider_app", app.ProviderAppID, - "customer", thread.CustomerID, "config", config.ID, "channel", thread.ChannelID) + "app_id", thread.CustomerID, "config", config.ID, "channel", thread.ChannelID) } b.wake() } @@ -647,7 +647,7 @@ func (b *Bridge) take(ctx context.Context, app store.ConnectorOAuthClient, messa connection, err := b.store.AppConnectionByAccount(ctx, app.CustomerID, message.ConnectorID, message.ProviderUnitID) if errors.Is(err, store.ErrNoConnectorConnection) { b.logger.Info("dropped an inbound message: the provider app has no connection of its provider unit", - "connector", message.ConnectorID, "customer", app.CustomerID, "provider_unit", message.ProviderUnitID) + "connector", message.ConnectorID, "app_id", app.CustomerID, "provider_unit", message.ProviderUnitID) return store.ChannelThread{}, store.AgentConfig{}, nil, nil } if err != nil { @@ -661,7 +661,7 @@ func (b *Bridge) take(ctx context.Context, app store.ConnectorOAuthClient, messa // None answers a thread nobody bound: the customer's agent configs to fix. A test copy // is not listed, so it never answers (AI-1049). b.logger.Warn("dropped an inbound message: one agent config must bind the connection it came in on", - "connector", message.ConnectorID, "customer", app.CustomerID, "connection", connection.ID, "configs", len(configs)) + "connector", message.ConnectorID, "app_id", app.CustomerID, "connection", connection.ID, "configs", len(configs)) return store.ChannelThread{}, store.AgentConfig{}, nil, nil } if len(configs) > 1 { @@ -674,7 +674,7 @@ func (b *Bridge) take(ctx context.Context, app store.ConnectorOAuthClient, messa others = append(others, other.ID) } b.logger.Warn("more than one agent config binds the connection a message came in on: the oldest answers", - "connector", message.ConnectorID, "customer", app.CustomerID, "connection", connection.ID, + "connector", message.ConnectorID, "app_id", app.CustomerID, "connection", connection.ID, "config", configs[0].ID, "not_answering", others) } definition, err := b.store.ConnectorDefinitions.Get(ctx, connection.CustomerID, connection.ConnectorID, connection.DefinitionRevision) @@ -689,7 +689,7 @@ func (b *Bridge) take(ctx context.Context, app store.ConnectorOAuthClient, messa // the same revision, so it is dropped, not answered 500. It is a warn, not an info: the // same drop is a pinned revision reading the message with another thread key or id. b.logger.Warn("dropped an inbound message the revision of its connection does not read", - "connector", message.ConnectorID, "customer", app.CustomerID, "connection", connection.ID, + "connector", message.ConnectorID, "app_id", app.CustomerID, "connection", connection.ID, "revision", connection.DefinitionRevision) return store.ChannelThread{}, store.AgentConfig{}, nil, nil } @@ -710,7 +710,7 @@ func (b *Bridge) take(ctx context.Context, app store.ConnectorOAuthClient, messa if !linked { // waiting is a reply kept for a message that links its thread to take (wait). b.logger.Info("dropped an inbound message that is not addressed to the connection on a thread nobody linked", - "connector", message.ConnectorID, "provider_app", app.ProviderAppID, "customer", app.CustomerID, + "connector", message.ConnectorID, "provider_app", app.ProviderAppID, "app_id", app.CustomerID, "connection", connection.ID, "config", configs[0].ID, "waiting", !startsThread(read)) return store.ChannelThread{}, store.AgentConfig{}, nil, nil } @@ -745,7 +745,7 @@ func (b *Bridge) take(ctx context.Context, app store.ConnectorOAuthClient, messa // not read the reply after it waited. Every retry of the message finds the same // revision, so failing it would leave it unanswered for good (AI-2743). b.logger.Warn("dropped a waiting reply the revision of its connection does not read", - "connector", reply.ConnectorID, "customer", app.CustomerID, "connection", connection.ID, + "connector", reply.ConnectorID, "app_id", app.CustomerID, "connection", connection.ID, "revision", connection.DefinitionRevision, "channel", thread.ChannelID) return reply, false, nil } diff --git a/acceleration/internal/channelbridge/gate.go b/acceleration/internal/channelbridge/gate.go index c3ac488ee7..98ad5ca8f6 100644 --- a/acceleration/internal/channelbridge/gate.go +++ b/acceleration/internal/channelbridge/gate.go @@ -85,7 +85,7 @@ func (b *Bridge) gateRefusal(ctx context.Context, customerID, connectorID, to st err = b.gate.Allow(ctx, customerID, channel, to) if errors.Is(err, dlc.ErrRefused) { // The refusal names the number, which stays out of the logs. - b.logger.Info("the sandbox gate held a channel message back", "connector", connectorID, "customer", customerID) + b.logger.Info("the sandbox gate held a channel message back", "connector", connectorID, "app_id", customerID) if dlc.TierLimit(err) != "" { // A tier limit's refusal names no number, so it goes along to say which limit held it. return fmt.Errorf("%w: %w", ErrHeldBack, err), nil @@ -96,7 +96,7 @@ func (b *Bridge) gateRefusal(ctx context.Context, customerID, connectorID, to st // The customer loses the message until it pays, so it is a warning; the refusal says // why and names no number. b.logger.Warn("held a channel message back: the organization may not pay for it", "connector", connectorID, - "customer", customerID, "reason", err) + "app_id", customerID, "reason", err) return err, nil } return nil, err @@ -191,7 +191,7 @@ func (b *Bridge) sent(thread store.ChannelThread) { to, err := b.replyTo(ctx, thread) if err != nil { b.logger.Warn("could not tell who a reply reached, counting it alone", "connector", thread.ConnectorID, - "customer", thread.CustomerID, "error", err) + "app_id", thread.CustomerID, "error", err) } b.gate.Sent(ctx, thread.CustomerID, channel, to) } diff --git a/acceleration/internal/channelbridge/inbound.go b/acceleration/internal/channelbridge/inbound.go index 7445592164..d200ba4828 100644 --- a/acceleration/internal/channelbridge/inbound.go +++ b/acceleration/internal/channelbridge/inbound.go @@ -184,7 +184,7 @@ func (b *Bridge) attempt(message store.ChannelInbound) { cancel() recording, done := context.WithTimeout(context.WithoutCancel(b.ctx), writeTimeout) defer done() - log := b.logger.With("connector", message.ConnectorID, "customer", message.CustomerID, "channel", message.ChannelID, + log := b.logger.With("connector", message.ConnectorID, "app_id", message.CustomerID, "channel", message.ChannelID, "seq", message.Seq) attempts := message.Attempts var changed bool @@ -237,7 +237,7 @@ func (b *Bridge) writeQueued(ctx context.Context, message store.ChannelInbound) } config := store.AgentConfig{ID: message.ConfigID, Name: message.ConfigName} inbound := message.Message() - log := b.logger.With("connector", message.ConnectorID, "customer", message.CustomerID, "channel", message.ChannelID, + log := b.logger.With("connector", message.ConnectorID, "app_id", message.CustomerID, "channel", message.ChannelID, "seq", message.Seq) // Before the episode opens: a message that is only files named by id, none of them a // photo that downloaded or that an earlier attempt uploaded, has nothing to write or @@ -350,7 +350,7 @@ func (b *Bridge) forwardUnanswered(message store.ChannelInbound) func(context.Co err := b.unanswered(ctx, event) if err != nil { b.logger.Error("could not forward a delivery no agent got", "connector", message.ConnectorID, - "customer", message.CustomerID, "error", err) + "app_id", message.CustomerID, "error", err) } return err } diff --git a/acceleration/internal/channelbridge/inbound_test.go b/acceleration/internal/channelbridge/inbound_test.go index bf6a6feec8..d00f47c6b6 100644 --- a/acceleration/internal/channelbridge/inbound_test.go +++ b/acceleration/internal/channelbridge/inbound_test.go @@ -838,9 +838,9 @@ func (s *InboundSuite) TestAWrittenMessageIsHandedToTheAgentAsStreamChatStoredIt stored := s.chat.Stored(thread.ChannelID) s.Require().Len(stored, 1) s.Equal(true, stored[0]["custom"].(map[string]any)[BridgedField], "the message hook leaves it to the worker") - s.Contains(s.logs.String(), `msg="an inbound message is written into its thread channel" connector=fake_line customer=`+s.customer+" channel="+thread.ChannelID) - s.Contains(s.logs.String(), `msg="an inbound message is handed to the agent" connector=fake_line customer=`+s.customer+" channel="+thread.ChannelID) - s.logged(`msg="an inbound message is done" connector=fake_line customer=`+s.customer+" channel="+thread.ChannelID, 1) // after the row is done + s.Contains(s.logs.String(), `msg="an inbound message is written into its thread channel" connector=fake_line app_id=`+s.customer+" channel="+thread.ChannelID) + s.Contains(s.logs.String(), `msg="an inbound message is handed to the agent" connector=fake_line app_id=`+s.customer+" channel="+thread.ChannelID) + s.logged(`msg="an inbound message is done" connector=fake_line app_id=`+s.customer+" channel="+thread.ChannelID, 1) // after the row is done } // An attempt that wrote the message and stopped before the agent took it leaves it queued; the @@ -912,7 +912,7 @@ func (s *InboundSuite) TestAMessageWhoseEpisodeCannotBeOpenedIsStillHandedToTheA s.Require().Eventually(func() bool { return s.row(thread, "1793125611.816139").State == store.ChannelInboundDone }, 5*time.Second, 10*time.Millisecond) s.Equal(1, s.row(thread, "1793125611.816139").Attempts) s.Never(func() bool { return len(handed) > 0 }, 200*time.Millisecond, 10*time.Millisecond, "handed to the agent twice") - s.Contains(s.logs.String(), `level=ERROR msg="could not open the episode of an inbound message" connector=slack_bot customer=`+s.customer+" channel="+thread.ChannelID) + s.Contains(s.logs.String(), `level=ERROR msg="could not open the episode of an inbound message" connector=slack_bot app_id=`+s.customer+" channel="+thread.ChannelID) } // Stream Chat bounces a message it does not keep, as a moderation block does: its answer has @@ -929,7 +929,7 @@ func (s *InboundSuite) TestAMessageStreamChatBouncesIsNotHandedToTheAgent() { s.Require().Eventually(func() bool { return s.row(thread, "m-1").State == store.ChannelInboundDone }, 5*time.Second, 10*time.Millisecond) s.Empty(handed, "the agent is handed nothing") - s.Contains(s.logs.String(), `msg="an inbound message Stream Chat bounced is not handed to the agent" connector=fake_line customer=`+ + s.Contains(s.logs.String(), `msg="an inbound message Stream Chat bounced is not handed to the agent" connector=fake_line app_id=`+ s.customer+" channel="+thread.ChannelID) } @@ -1049,7 +1049,7 @@ func (s *InboundSuite) handedOnce(thread store.ChannelThread, providerMessageID s.Equal([]string{"hello"}, s.chat.Messages(thread.ChannelID)) omni, _ := s.card(thread) s.Empty(s.chat.Stored(omni), "the card was not written") - s.Contains(s.logs.String(), `level=ERROR msg="could not write the episode card of a thread" connector=slack_bot customer=`+s.customer+" channel="+thread.ChannelID) + s.Contains(s.logs.String(), `level=ERROR msg="could not write the episode card of a thread" connector=slack_bot app_id=`+s.customer+" channel="+thread.ChannelID) } // handed waits for the next message a worker hands over. diff --git a/acceleration/internal/channels/keywords.go b/acceleration/internal/channels/keywords.go index b228a9ee68..32dc6a3356 100644 --- a/acceleration/internal/channels/keywords.go +++ b/acceleration/internal/channels/keywords.go @@ -64,7 +64,7 @@ func (s *Service) claim(ctx context.Context, account store.ChannelAccount, messa } if err != nil { s.logger.Error("could not record a keyword", "keyword", word, "channel", account.Kind, - "customer", account.CustomerID, "error", err) + "app_id", account.CustomerID, "error", err) return false, errKeywordNotRecorded } if fresh { diff --git a/acceleration/internal/channels/metering.go b/acceleration/internal/channels/metering.go index 74e0b407de..7e5d73d721 100644 --- a/acceleration/internal/channels/metering.go +++ b/acceleration/internal/channels/metering.go @@ -69,7 +69,7 @@ func (s *Service) textMeter(ctx context.Context, kind Kind, direction, other str held, err := s.gate.Sandboxed(ctx, owner.CustomerID) if err != nil { s.logger.Warn("could not tell whether the 10DLC sandbox holds an app; its texts are billed", - "customer", owner.CustomerID, "error", err) + "app_id", owner.CustomerID, "error", err) } if held { meter.Free = true diff --git a/acceleration/internal/channels/service.go b/acceleration/internal/channels/service.go index 99f33f76a5..a312358392 100644 --- a/acceleration/internal/channels/service.go +++ b/acceleration/internal/channels/service.go @@ -182,7 +182,7 @@ func (s *Service) Receive(ctx context.Context, token string, header http.Header, for _, message := range delivered { fresh, err := s.claim(ctx, account, message) if err != nil { - s.logger.Error("could not claim a channel delivery", "customer", account.CustomerID, "error", err) + s.logger.Error("could not claim a channel delivery", "app_id", account.CustomerID, "error", err) return Answer{Status: http.StatusInternalServerError, Body: failure(somethingWentWrong)} } // A provider that did not hear back in time sends the same message again. Answering @@ -392,7 +392,7 @@ func (s *Service) line(ctx context.Context, token string) (Account, store.Channe } line, err := Open(s.secrets, account) if err != nil { - s.logger.Error("could not open a channel line's credentials", "customer", account.CustomerID, + s.logger.Error("could not open a channel line's credentials", "app_id", account.CustomerID, "channel", account.Kind, "error", err) return Account{}, account, errUnopened } @@ -421,7 +421,7 @@ func (s *Service) unread(err error) Answer { func (s *Service) answer(account store.ChannelAccount, line Account, provider Provider, message Message) { ctx, cancel := context.WithTimeout(s.ctx, runTimeout) defer cancel() - logger := s.logger.With("customer", account.CustomerID) + logger := s.logger.With("app_id", account.CustomerID) if s.keyword(ctx, account, line, provider, message) { return @@ -690,7 +690,7 @@ func filesOf(attached []sandbox.Attachment) []File { // number in its text (dlc.Gate), so it is logged by its code only. func (s *Service) logGateRefusal(message, customerID, channel string, err error) { if errors.Is(err, dlc.ErrUnpaid) { - s.logger.Warn(message, "channel", channel, "customer", customerID, "reason", err) + s.logger.Warn(message, "channel", channel, "app_id", customerID, "reason", err) return } s.logger.Info(message, "channel", channel, "reason", dlc.RefusalCode(err)) diff --git a/acceleration/internal/connectors/schemes/oauth2code/credential.go b/acceleration/internal/connectors/schemes/oauth2code/credential.go index 35b2d677e2..c0dec23e0c 100644 --- a/acceleration/internal/connectors/schemes/oauth2code/credential.go +++ b/acceleration/internal/connectors/schemes/oauth2code/credential.go @@ -301,7 +301,7 @@ func (s *Scheme) warnIfLastRefresh(m core.ResolvedManifest, payload storedPayloa return } s.cfg.Logger.Warn("oauth2code: the refresh token expires before the next refresh; the connection will need a reconnect", - "connector", m.ConnectorID, "connection", payload.Ref.ConnectionID, "customer", payload.Ref.CustomerID, + "connector", m.ConnectorID, "connection", payload.Ref.ConnectionID, "app_id", payload.Ref.CustomerID, "refresh_expires_at", payload.RefreshExpiresAt) } diff --git a/acceleration/internal/connectors/schemes/oauth2code/credential_test.go b/acceleration/internal/connectors/schemes/oauth2code/credential_test.go index b50973b25c..3428d35b79 100644 --- a/acceleration/internal/connectors/schemes/oauth2code/credential_test.go +++ b/acceleration/internal/connectors/schemes/oauth2code/credential_test.go @@ -566,7 +566,7 @@ func (s *OAuth2CodeSuite) TestARefreshTokenDyingBeforeTheNextRefreshIsWarnedAbou renewed := s.accessCredentialDue(scheme, stored, resolved) s.Contains(log.String(), "the refresh token expires before the next refresh") s.Contains(log.String(), `"connection":"conn-1"`) - s.Contains(log.String(), `"customer":"`+s.ref.CustomerID+`"`, "the warning names the app that has to reconnect") + s.Contains(log.String(), `"app_id":"`+s.ref.CustomerID+`"`, "the warning names the app that has to reconnect") for _, secret := range []string{s.accessToken(renewed), s.refreshToken(renewed), s.refreshToken(stored), srv.ClientSecret} { s.NotContains(log.String(), secret) } diff --git a/acceleration/internal/conversation/branches.go b/acceleration/internal/conversation/branches.go index 38ee52201c..11b245aa05 100644 --- a/acceleration/internal/conversation/branches.go +++ b/acceleration/internal/conversation/branches.go @@ -688,7 +688,7 @@ func (s *Service) resumeSwitches(ctx context.Context, client *getstream.Stream, hidden, err := sw.resumeAll(ctx) if err != nil { logger.Warn("could not finish a branch switch an earlier router left unfinished; the conversation opens as Chat shows it", - "customer", customer, "cid", cid, "session", session, "error", err) + "app_id", customer, "cid", cid, "session", session, "error", err) } return hidden } diff --git a/acceleration/internal/conversation/chats_test.go b/acceleration/internal/conversation/chats_test.go index ecafdd6b3b..eda4db55b6 100644 --- a/acceleration/internal/conversation/chats_test.go +++ b/acceleration/internal/conversation/chats_test.go @@ -360,7 +360,7 @@ func (s *AppsSuite) TestAConversationWhoseAppCannotBeWrittenIsLoggedAsParkedOnce s.Equal(1, s.logs.count(`msg="parked a conversation`), s.logs.String()) s.Contains(s.logs.String(), "level=WARN") - s.Contains(s.logs.String(), "customer=globex cid="+c.CID()+" stream_app=99") + s.Contains(s.logs.String(), "app_id=globex cid="+c.CID()+" stream_app=99") s.Contains(s.logs.String(), streamapp.ErrStreamAppDisconnected.Error()) } @@ -374,7 +374,7 @@ func (s *AppsSuite) TestAParkedConversationIsLoggedOnceItsWritesGoThrough() { s.Contains(s.globex.Messages(strings.TrimPrefix(c.CID(), "agent:")), "waiting for globex's app") s.Equal(1, s.logs.count(`msg="unparked a conversation`), s.logs.String()) - s.Contains(s.logs.String(), "customer=globex cid="+c.CID()+" stream_app=99") + s.Contains(s.logs.String(), "app_id=globex cid="+c.CID()+" stream_app=99") } // texts is what a page of history says, in order. diff --git a/acceleration/internal/conversation/conversation.go b/acceleration/internal/conversation/conversation.go index 9454e77c03..8b2e637a8e 100644 --- a/acceleration/internal/conversation/conversation.go +++ b/acceleration/internal/conversation/conversation.go @@ -2566,10 +2566,10 @@ func (c *Conversation) flushOne() (bool, *FinishedReply, error) { // parking and unparking are logged: once each, rather than on every retry. if parked(err) && c.parkedUntil.IsZero() { c.service.logger.Warn("parked a conversation whose Stream app cannot be written", - "customer", c.data.Customer, "cid", c.data.CID, "stream_app", c.data.StreamApp, "reason", err) + "app_id", c.data.Customer, "cid", c.data.CID, "stream_app", c.data.StreamApp, "reason", err) } else if !parked(err) && !c.parkedUntil.IsZero() { c.service.logger.Info("unparked a conversation whose Stream app can be written again", - "customer", c.data.Customer, "cid", c.data.CID, "stream_app", c.data.StreamApp) + "app_id", c.data.Customer, "cid", c.data.CID, "stream_app", c.data.StreamApp) c.parkedUntil = time.Time{} } if err != nil { diff --git a/acceleration/internal/conversation/owner_kind_backfill.go b/acceleration/internal/conversation/owner_kind_backfill.go index 0510923d57..2916e1b82e 100644 --- a/acceleration/internal/conversation/owner_kind_backfill.go +++ b/acceleration/internal/conversation/owner_kind_backfill.go @@ -51,7 +51,7 @@ func (s *Service) BackfillOwnerKinds(ctx context.Context, held *store.Store, mod outcome, err := s.backfillOwnerKind(ctx, held, mode, conversation.CustomerID, conversation.ConversationID, write) if err != nil { s.logger.Warn("could not record the owner's kind on a conversation's channel", - "customer", conversation.CustomerID, "conversation", conversation.ConversationID, "error", err) + "app_id", conversation.CustomerID, "conversation", conversation.ConversationID, "error", err) } counted[outcome]++ } diff --git a/acceleration/internal/dlc/service.go b/acceleration/internal/dlc/service.go index 2da69b6e79..25f78de713 100644 --- a/acceleration/internal/dlc/service.go +++ b/acceleration/internal/dlc/service.go @@ -468,7 +468,7 @@ func (s *Service) register(ctx context.Context, useCase store.UseCase) error { if err != nil && profile.VendorBrandID == "" { // Its request stays, so it is never registered again; support records the id. s.logger.Error("could not save a brand the vendor registered; record its id on the app's business profile", - "customer", useCase.CustomerID, "vendor", s.registrar.Name(), "vendor_brand_id", brand.ID, "error", err) + "app_id", useCase.CustomerID, "vendor", s.registrar.Name(), "vendor_brand_id", brand.ID, "error", err) return nil } if err != nil { @@ -598,7 +598,7 @@ func (s *Service) unanswered(ctx context.Context, useCase store.UseCase, registr return err } s.logger.Error("a 10DLC registration was not answered; look it up at the vendor, then record its id or forget its request", - "use_case", useCase.ID, "customer", useCase.CustomerID, "vendor", s.registrar.Name(), "registration", registration, + "use_case", useCase.ID, "app_id", useCase.CustomerID, "vendor", s.registrar.Name(), "registration", registration, "requested_at", requestedAt) return nil } diff --git a/acceleration/internal/eventforward/forwarder.go b/acceleration/internal/eventforward/forwarder.go index 685b564fcb..e7600e71d9 100644 --- a/acceleration/internal/eventforward/forwarder.go +++ b/acceleration/internal/eventforward/forwarder.go @@ -522,7 +522,7 @@ func (f *Forwarder) attempt(delivery store.ClaimedEventDelivery) { } writing, done := context.WithTimeout(context.WithoutCancel(f.ctx), attemptTimeout) defer done() - log := f.logger.With("connector", delivery.ConnectorID, "customer", delivery.CustomerID, + log := f.logger.With("connector", delivery.ConnectorID, "app_id", delivery.CustomerID, "destination", delivery.DestinationID, "webhook_id", delivery.ID) var again retryable // The claim counted this attempt. @@ -594,7 +594,7 @@ func (f *Forwarder) dueOnce(key string) bool { func (f *Forwarder) giveUpUnsent(delivery store.ClaimedEventDelivery) { writing, done := context.WithTimeout(context.WithoutCancel(f.ctx), attemptTimeout) defer done() - log := f.logger.With("connector", delivery.ConnectorID, "customer", delivery.CustomerID, + log := f.logger.With("connector", delivery.ConnectorID, "app_id", delivery.CustomerID, "destination", delivery.DestinationID, "webhook_id", delivery.ID) log.Warn("gave up an event forward its earlier claims never finished", "attempts", delivery.Attempts) f.count(delivery, codeNotSent) @@ -704,7 +704,7 @@ func (f *Forwarder) openSecrets(delivery store.ClaimedEventDelivery) ([]string, if err != nil { if f.dueOnce("previous/" + delivery.DestinationID) { f.logger.Warn("this router cannot sign with an event destination's previous signing secret; its forwards are signed with the current one alone", - "connector", delivery.ConnectorID, "customer", delivery.CustomerID, "destination", delivery.DestinationID, "error", err) + "connector", delivery.ConnectorID, "app_id", delivery.CustomerID, "destination", delivery.DestinationID, "error", err) } return secrets, nil } diff --git a/acceleration/internal/imagejobs/imagejobs.go b/acceleration/internal/imagejobs/imagejobs.go index 6f7c2da865..47a2a831c7 100644 --- a/acceleration/internal/imagejobs/imagejobs.go +++ b/acceleration/internal/imagejobs/imagejobs.go @@ -362,7 +362,7 @@ func (s *Service) prune(ctx context.Context) { // run takes one claimed job as far as it goes. func (s *Service) run(job store.ImageJob) { - log := s.logger.With("job", job.ID, "customer", job.CustomerID, "channel", job.CID, "attempts", job.Attempts) + log := s.logger.With("job", job.ID, "app_id", job.CustomerID, "channel", job.CID, "attempts", job.Attempts) switch { case job.Attempts-job.Released > maxClaims: log.Error("gave up an image job claimed more times than any job should be") diff --git a/acceleration/internal/node/directory.go b/acceleration/internal/node/directory.go index 6315ed2542..217f6ac9ce 100644 --- a/acceleration/internal/node/directory.go +++ b/acceleration/internal/node/directory.go @@ -256,7 +256,7 @@ func (d *Directory) Release(ctx context.Context, customerID, sessionID string) { for _, result := range d.redis.DoMulti(ctx, deletes...) { if err := result.Error(); err != nil { d.logger.Warn("could not take back this node's claim on a session", - "customer", customerID, "session", sessionID, "error", err) + "app_id", customerID, "session", sessionID, "error", err) } } } @@ -358,7 +358,7 @@ func (d *Directory) Wait(ctx context.Context, customerID string) func() { command := d.redis.B().Zrem().Key(d.workers + customerID).Member(d.address).Build() if err := d.redis.Do(ctx, command).Error(); err != nil { d.logger.Warn("could not take back this node's claim on a customer's workers", - "customer", customerID, "error", err) + "app_id", customerID, "error", err) } } } @@ -395,7 +395,7 @@ func (d *Directory) Offer(ctx context.Context, customerID, agentID string, offer command := d.redis.B().Hdel().Key(d.offerKey(key)).Field(d.address).Build() if err := d.redis.Do(context.WithoutCancel(ctx), command).Error(); err != nil { d.logger.Warn("could not withdraw the tools this node's workers hosted", - "customer", customerID, "agent", agentID, "error", err) + "app_id", customerID, "agent", agentID, "error", err) } } @@ -425,7 +425,7 @@ func (d *Directory) HandOut(ctx context.Context, customerID, cid string, entry [ command := d.redis.B().Set().Key(d.handouts + customerID + ":" + cid).Value(string(entry)).Px(lasts).Build() if err := d.redis.Do(ctx, command).Error(); err != nil { d.logger.Warn("could not say a channel's message was handed to a worker", - "customer", customerID, "channel", cid, "error", err) + "app_id", customerID, "channel", cid, "error", err) } } @@ -510,7 +510,7 @@ func (d *Directory) write(ctx context.Context, key heldSession, held claim) { for _, result := range d.redis.DoMulti(ctx, d.writeCommands(key, held)...) { if err := result.Error(); err != nil { d.logger.Warn("could not say this node is running a session", - "customer", key.customerID, "session", key.sessionID, "error", err) + "app_id", key.customerID, "session", key.sessionID, "error", err) return } } @@ -556,7 +556,7 @@ func (d *Directory) advertise(ctx context.Context, customerID string) { for _, result := range d.redis.DoMulti(ctx, d.advertiseCommands(customerID)...) { if err := result.Error(); err != nil { d.logger.Warn("could not say this node has workers for a customer", - "customer", customerID, "error", err) + "app_id", customerID, "error", err) return } } @@ -584,7 +584,7 @@ func (d *Directory) publishOffer(ctx context.Context, key offerKey, offer []byte for _, result := range d.redis.DoMulti(ctx, commands...) { if err := result.Error(); err != nil { d.logger.Warn("could not say what this node's workers host", - "customer", key.customerID, "agent", key.agentID, "error", err) + "app_id", key.customerID, "agent", key.agentID, "error", err) return } } diff --git a/acceleration/internal/omnichannel/close.go b/acceleration/internal/omnichannel/close.go index 8790a34a9e..f5530e8488 100644 --- a/acceleration/internal/omnichannel/close.go +++ b/acceleration/internal/omnichannel/close.go @@ -253,7 +253,7 @@ func (c *Closer) summarize(parent context.Context, episode store.ClosedEpisode, // summary that took too long has used up. if err != nil { status = store.EpisodeSummaryFailed - c.logger.Error("could not summarize an episode", "episode", episode.ID, "customer", episode.CustomerID, "error", err) + c.logger.Error("could not summarize an episode", "episode", episode.ID, "app_id", episode.CustomerID, "error", err) if err := c.mark(parent, episode, author, map[string]any{statusField: status}); err != nil { c.logger.Error("could not set an episode's card summary_failed", "episode", episode.ID, "error", err) } diff --git a/acceleration/internal/phone/agentjoin.go b/acceleration/internal/phone/agentjoin.go index 7d8e280192..f6aef30de4 100644 --- a/acceleration/internal/phone/agentjoin.go +++ b/acceleration/internal/phone/agentjoin.go @@ -45,7 +45,7 @@ func (s *Service) awaitAgent(ctx context.Context, leg store.CallLeg) { // that joins between the read and the end is ended with the call. One read cannot prevent // this, and the time between the two is one Stream request. func (s *Service) checkAgent(ctx context.Context, leg store.CallLeg) { - attributes := []any{"session_id", leg.CallID, "customer", leg.CustomerID, "from", leg.LocalNumber, + attributes := []any{"session_id", leg.CallID, "app_id", leg.CustomerID, "from", leg.LocalNumber, "to", leg.RemoteNumber, "vendor", leg.Vendor, "vendor_call_id", leg.VendorCallID, "waited", s.agentJoinTimeout} reading, cancel := context.WithTimeout(ctx, agentCheckTimeout) defer cancel() diff --git a/acceleration/internal/phone/legs.go b/acceleration/internal/phone/legs.go index 6c677f325a..b3518784b5 100644 --- a/acceleration/internal/phone/legs.go +++ b/acceleration/internal/phone/legs.go @@ -73,7 +73,7 @@ func (s *Service) OpenLeg(ctx context.Context, owner routing.Owner, leg store.Ca // from its open legs. membership, err := s.store.AppOrganizations.Get(ctx, owner.CustomerID) if err != nil { - s.logger.Warn("could not tell whose organization a call leg is", "customer", owner.CustomerID, "error", err) + s.logger.Warn("could not tell whose organization a call leg is", "app_id", owner.CustomerID, "error", err) } owner.OrganizationID = membership.OrganizationID } @@ -297,7 +297,7 @@ func (s *Service) checkHooked(ctx context.Context, scope store.AppScope, callTyp return } s.logger.Error("call hook does not deliver participant events; re-run cmd/phone hooks", - "stream_app", leg.StreamAppPK, "customer", leg.CustomerID, "call", callType+":"+callID, + "stream_app", leg.StreamAppPK, "app_id", leg.CustomerID, "call", callType+":"+callID, "hint", "a placed call ended unanswered and no participant event of it, not even the agent's join, was delivered: "+ "placed calls and transfers in this app never connect, and their minutes are not billed") } @@ -443,7 +443,7 @@ func (s *Service) settleLegs(ctx context.Context, ended []store.CallLeg) { for _, leg := range ended { if !leg.Connected() { s.logger.Warn("a call leg ended without its phone joining the call; it is not billed", - "customer", leg.CustomerID, "call", leg.CallType+":"+leg.CallID, "vendor", leg.Vendor, + "app_id", leg.CustomerID, "call", leg.CallType+":"+leg.CallID, "vendor", leg.Vendor, "direction", leg.Direction, "hint", "unanswered, or the call hook does not deliver call.session_participant_joined") continue } @@ -476,7 +476,7 @@ func (s *Service) tell(ctx context.Context, leg store.CallLeg) { } if leg.StartedAt != nil { if err := s.outcomes.Answered(ctx, key, *leg.StartedAt); err != nil { - s.logger.Error("could not keep that a call was answered", "customer", leg.CustomerID, + s.logger.Error("could not keep that a call was answered", "app_id", leg.CustomerID, "call", leg.CallType+":"+leg.CallID, "error", err) } } @@ -484,7 +484,7 @@ func (s *Service) tell(ctx context.Context, leg store.CallLeg) { inbound := leg.Direction == store.Inbound ended := outcome.Leg{Vendor: leg.Vendor, Inbound: inbound, AnsweredAt: leg.StartedAt, Refused: inbound && s.refused(ctx, leg)} if err := s.outcomes.Ended(ctx, key, *leg.EndedAt, ended); err != nil { - s.logger.Error("could not keep that a call ended", "customer", leg.CustomerID, + s.logger.Error("could not keep that a call ended", "app_id", leg.CustomerID, "call", leg.CallType+":"+leg.CallID, "error", err) } } @@ -506,7 +506,7 @@ func (s *Service) Refused(ctx context.Context, customer string, app int64, callT defer cancel() if err := s.store.CallLegs.MarkRefused(ctx, customer, app, callType, callID, session, refusedFor); err != nil { s.logger.Warn("could not mark a refused arriving call; it is counted completed", - "customer", customer, "call", callType+":"+callID, "error", err) + "app_id", customer, "call", callType+":"+callID, "error", err) } } @@ -526,7 +526,7 @@ func (s *Service) refused(ctx context.Context, leg store.CallLeg) bool { found, err := s.store.CallLegs.Refused(ctx, leg) if err != nil { s.logger.Warn("could not tell whether the router refused an arriving call; it is counted completed", - "customer", leg.CustomerID, "call", leg.CallType+":"+leg.CallID, "error", err) + "app_id", leg.CustomerID, "call", leg.CallType+":"+leg.CallID, "error", err) return false } return found @@ -552,11 +552,11 @@ func (s *Service) SweepLegs(ctx context.Context) (int, error) { for _, leg := range ended { if !leg.Connected() { s.logger.Warn("ended a call leg that rang for the longest a call may last without its phone joining", - "customer", leg.CustomerID, "call", leg.CallType+":"+leg.CallID, "vendor", leg.Vendor) + "app_id", leg.CustomerID, "call", leg.CallType+":"+leg.CallID, "vendor", leg.Vendor) continue } s.logger.Error("ended a call leg nothing said had ended; it is recorded and not billed", - "customer", leg.CustomerID, "call", leg.CallType+":"+leg.CallID, "vendor", leg.Vendor, + "app_id", leg.CustomerID, "call", leg.CallType+":"+leg.CallID, "vendor", leg.Vendor, "direction", leg.Direction, "started_at", leg.StartedAt, "recorded", MaxCallLength) s.settleLeg(ctx, leg, true) } @@ -595,7 +595,7 @@ func (s *Service) rebill(ctx context.Context, now time.Time) error { continue } s.logger.Warn("a call leg that ended had no usage row; it is recorded again", - "customer", leg.CustomerID, "call", leg.CallType+":"+leg.CallID, "ended_at", leg.EndedAt) + "app_id", leg.CustomerID, "call", leg.CallType+":"+leg.CallID, "ended_at", leg.EndedAt) s.settleLeg(ctx, leg, false) } return nil diff --git a/acceleration/internal/phone/metering.go b/acceleration/internal/phone/metering.go index 9eb8ca44b9..d680305951 100644 --- a/acceleration/internal/phone/metering.go +++ b/acceleration/internal/phone/metering.go @@ -69,7 +69,7 @@ func (s *Service) sandboxed(ctx context.Context, customerID string) bool { held, err := s.gate.Sandboxed(ctx, customerID) if err != nil { s.logger.Warn("could not tell whether the 10DLC sandbox holds an app; its minutes are billed", - "customer", customerID, "error", err) + "app_id", customerID, "error", err) } return held } diff --git a/acceleration/internal/phone/metering_integration_test.go b/acceleration/internal/phone/metering_integration_test.go index 02d2f625e9..e4f0580885 100644 --- a/acceleration/internal/phone/metering_integration_test.go +++ b/acceleration/internal/phone/metering_integration_test.go @@ -1023,7 +1023,7 @@ func (s *MeteringSuite) TestAnOrderAVendorCannotSettleIsKeptAndNotAskedAboutEver s.ErrorIs(err, store.ErrNoNumber, "nothing is recorded that the vendor did not confirm") s.Equal(1, s.orders(), "kept for an operator") // Other tests' orders are in the same tables, so only this customer's lines are counted. - s.Equal(1, s.logs.count("ERROR", "customer="+s.customer), "asked about once, not every sweep") + s.Equal(1, s.logs.count("ERROR", "app_id="+s.customer), "asked about once, not every sweep") s.Contains(s.logs.String(), "could not settle a number's purchase or release") } @@ -1057,7 +1057,7 @@ func (s *MeteringSuite) TestAPurchaseFromAVendorNotImplementedLeavesNoOrder() { s.Require().NoError(err) s.Zero(s.orders()) - s.Zero(s.logs.count("ERROR", "customer="+s.customer)) + s.Zero(s.logs.count("ERROR", "app_id="+s.customer)) } // A purchase refused before the vendor was asked, for a setting the deployment lacks, leaves diff --git a/acceleration/internal/phone/outcome/keeper.go b/acceleration/internal/phone/outcome/keeper.go index d0600e9dcc..f13af4fac2 100644 --- a/acceleration/internal/phone/outcome/keeper.go +++ b/acceleration/internal/phone/outcome/keeper.go @@ -213,7 +213,7 @@ func (k *Keeper) count(ctx context.Context, key Key, vendor, direction string, o label = dropped case err != nil && !errors.Is(err, store.ErrNoSession): k.logger.Warn("could not tell whether a phone call was dropped; it is counted as it is stored", - "customer", key.CustomerID, "call", key.CallType+":"+key.CallID, "outcome", label, "error", err) + "app_id", key.CustomerID, "call", key.CallType+":"+key.CallID, "outcome", label, "error", err) } } callOutcomes.WithLabelValues(vendor, direction, label).Inc() diff --git a/acceleration/internal/phone/service.go b/acceleration/internal/phone/service.go index 99e3473c09..b4796401c5 100644 --- a/acceleration/internal/phone/service.go +++ b/acceleration/internal/phone/service.go @@ -683,7 +683,7 @@ func (s *Service) SweepOrders(ctx context.Context) (int, error) { for _, order := range orders { if err := s.settleOrder(ctx, order); err != nil { s.logger.Error("could not settle a number's purchase or release", "order", order.ID, "action", order.Action, - "vendor", order.Vendor, "customer", order.CustomerID, "error", err) + "vendor", order.Vendor, "app_id", order.CustomerID, "error", err) continue } settled++ @@ -720,7 +720,7 @@ func (s *Service) settleOrder(ctx context.Context, order store.PhoneNumberOrder) return err } s.logger.Warn("released a number given back whose release was not recorded", "order", order.ID, - "vendor", order.Vendor, "customer", order.CustomerID) + "vendor", order.Vendor, "app_id", order.CustomerID) } } return s.store.PhoneNumberOrders.Delete(ctx, order.ID) @@ -747,7 +747,7 @@ func (s *Service) recordBought(ctx context.Context, order store.PhoneNumberOrder return err } s.logger.Warn("recorded a number bought whose row was not written", "order", order.ID, "vendor", order.Vendor, - "vendor_id", vendorID, "customer", order.CustomerID) + "vendor_id", vendorID, "app_id", order.CustomerID) if unbilled[month] { s.billMonth(number, routing.Owner{ CustomerID: number.CustomerID, Attribution: routing.Attribution{APIKey: OriginNumberRental}, Tags: number.Tags, @@ -1009,7 +1009,7 @@ func (s *Service) Attach(ctx context.Context, attachment Attachment) (Attached, } // A running line is not taken down over a repair that failed: its program is asking // again on every start. - s.logger.Error("could not point the call hook of a Stream app", "customer", attachment.CustomerID, "stream_app", pin, "error", err) + s.logger.Error("could not point the call hook of a Stream app", "app_id", attachment.CustomerID, "stream_app", pin, "error", err) } // The same request is sent on every run of a program waiting for calls, so a number @@ -1900,7 +1900,7 @@ func (s *Service) Machine(ctx context.Context, token, contentType string, body [ return stack.Wrap(fmt.Errorf("%w: %w", ErrUnreadableStatus, err)) } s.logger.Info("a vendor reported who answered", "vendor", call.Vendor, "answered_by", report.Word, - "machine", report.Machine, "customer", call.CustomerID, "session", call.CallID) + "machine", report.Machine, "app_id", call.CustomerID, "session", call.CallID) if s.machine != nil { s.machine(ctx, call.CustomerID, call.CallID, report.Machine) } diff --git a/acceleration/internal/policy/injection.go b/acceleration/internal/policy/injection.go index 849ac85543..556ee97bae 100644 --- a/acceleration/internal/policy/injection.go +++ b/acceleration/internal/policy/injection.go @@ -100,7 +100,7 @@ func (e *Enforcer) judge(ctx context.Context, classifier *decisionrouter.Router, defer cancel() err := e.classify(ctx, classifier, owner, text) if errors.Is(err, ErrScreenUnavailable) { - e.logger.Warn("could not screen a response for prompt injection", "customer", owner.CustomerID, "error", err) + e.logger.Warn("could not screen a response for prompt injection", "app_id", owner.CustomerID, "error", err) return nil } return err @@ -146,7 +146,7 @@ func (e *Enforcer) classify(ctx context.Context, classifier *decisionrouter.Rout } slices.Sort(found) e.logger.Info("refused input that reads as a prompt injection", - "customer", owner.CustomerID, "agent", owner.AgentID, "harms", found, "model", answered.Model) + "app_id", owner.CustomerID, "agent", owner.AgentID, "harms", found, "model", answered.Model) return fmt.Errorf("%w: %s", ErrPromptInjection, strings.Join(found, ", ")) } diff --git a/acceleration/internal/policy/policy.go b/acceleration/internal/policy/policy.go index f1e12521c6..cd03709ae9 100644 --- a/acceleration/internal/policy/policy.go +++ b/acceleration/internal/policy/policy.go @@ -398,7 +398,7 @@ func (e *Enforcer) Quota(ctx context.Context, customerID, userID string, default if err != nil { if e.userQuotaLogs.Due(customerID, time.Minute) { e.logger.Error("could not read a user's own quota, holding them to their app's", - "customer", customerID, "error", err) + "app_id", customerID, "error", err) } held.Unread = true return held @@ -730,7 +730,7 @@ func (e *Enforcer) decide(ctx context.Context, customerID string) decision { // afford; its money is read apart. Nothing is kept, so the next request reads again, // and a read in the background keeps the decision when it lands. e.logger.Error("could not read a customer's policies, allowing the request", - "customer", customerID, "error", err) + "app_id", customerID, "error", err) decided.unread = err e.warm(ctx, customerID) return decided @@ -769,7 +769,7 @@ func (e *Enforcer) refresh(ctx context.Context, customerID string) { current.read, current.refreshing = now, false e.decisions[customerID] = current e.mu.Unlock() - e.money.failedRead("could not read a customer's policies again, answering with the last ones read", err, "customer", customerID) + e.money.failedRead("could not read a customer's policies again, answering with the last ones read", err, "app_id", customerID) return } decided.read, decided.used = now, current.used diff --git a/acceleration/internal/quota/quota.go b/acceleration/internal/quota/quota.go index c07d9654bd..6dc2db6ec9 100644 --- a/acceleration/internal/quota/quota.go +++ b/acceleration/internal/quota/quota.go @@ -323,7 +323,7 @@ func (l *Limiter) Debit(ctx context.Context, customerID string, caller routing.C if held.Unread && !customer { if l.unreadLogs.Due(customerID, time.Minute) { l.logger.Warn("could not read a user's own quota, counting what they spent anyway", - "customer", customerID) + "app_id", customerID) } } if !caller.ServerSide { diff --git a/acceleration/internal/scheduling/scheduler.go b/acceleration/internal/scheduling/scheduler.go index 0843ccc62a..dd23261820 100644 --- a/acceleration/internal/scheduling/scheduler.go +++ b/acceleration/internal/scheduling/scheduler.go @@ -376,7 +376,7 @@ func (s *Scheduler) run(draining context.Context, claim store.ClaimedScheduledTa // A stored schedule that no longer reads can never run; say so on this // occurrence and pause the task instead of retrying it forever. s.logger.Error("a scheduled task's stored schedule does not read", - "task", task.ID, "run", claim.Run.ID, "customer", task.CustomerID, "error", err) + "task", task.ID, "run", claim.Run.ID, "app_id", task.CustomerID, "error", err) s.finish(claim, store.ScheduledTaskOutcome{ RunState: store.ScheduledTaskRunFailed, Error: ReasonUnreadable, @@ -386,7 +386,7 @@ func (s *Scheduler) run(draining context.Context, claim store.ClaimedScheduledTa } if claim.WorkersLost { s.logger.Error("a scheduled task's occurrence failed: it was started this many times and its worker was lost each time", - "task", task.ID, "run", claim.Run.ID, "customer", task.CustomerID, "attempts", claim.Run.Attempts) + "task", task.ID, "run", claim.Run.ID, "app_id", task.CustomerID, "attempts", claim.Run.Attempts) } if claim.AlreadySettled { // The occurrence was settled and only the advance was lost: settle the @@ -415,7 +415,7 @@ func (s *Scheduler) run(draining context.Context, claim store.ClaimedScheduledTa s.postpone(claim, held.Until) case failure != nil && errors.As(failure, &late): s.logger.Info("a scheduled task was too late to deliver", - "task", task.ID, "run", claim.Run.ID, "customer", task.CustomerID, "error", failure) + "task", task.ID, "run", claim.Run.ID, "app_id", task.CustomerID, "error", failure) s.finish(claim, s.missedOutcome(claim, schedule)) case failure == nil: next, state := s.after(schedule, claim.Run.ScheduledFor, false, 0) @@ -427,14 +427,14 @@ func (s *Scheduler) run(draining context.Context, claim store.ClaimedScheduledTa // The router is draining and the delivery was waiting to retry: leave // the run to its lease, for another router to take up. s.logger.Info("a scheduled task's retry was left to its lease: the router is draining", - "task", task.ID, "run", claim.Run.ID, "customer", task.CustomerID, "error", failure) + "task", task.ID, "run", claim.Run.ID, "app_id", task.CustomerID, "error", failure) return case owned.Err() != nil: // Close cut the delivery short, or the claim was lost to a change // that decides instead: leave the run to its lease. if errors.Is(context.Cause(owned), errClaimLost) { s.logger.Info("a scheduled task changed under its run; its delivery was stopped", - "task", task.ID, "run", claim.Run.ID, "customer", task.CustomerID) + "task", task.ID, "run", claim.Run.ID, "app_id", task.CustomerID) } return default: @@ -442,7 +442,7 @@ func (s *Scheduler) run(draining context.Context, claim store.ClaimedScheduledTa failure = fmt.Errorf("%w after %s: %w", errOutOfTime, s.budget, failure) } s.logger.Warn("a scheduled task failed to deliver", - "task", task.ID, "run", claim.Run.ID, "customer", task.CustomerID, "error", failure) + "task", task.ID, "run", claim.Run.ID, "app_id", task.CustomerID, "error", failure) reason := ReasonOf(failure) failed := countsAsFailure(reason) failures := task.ConsecutiveFailures @@ -539,7 +539,7 @@ func (s *Scheduler) keepReason(claim store.ClaimedScheduledTask, reason string) defer cancel() if err := s.store.ScheduledTaskRuns.SetAttemptReason(ctx, claim.Task.CustomerID, claim.Run.ID, claim.LeasedBy, reason); err != nil { s.logger.Error("could not record why a scheduled task's attempt failed", - "task", claim.Task.ID, "run", claim.Run.ID, "customer", claim.Task.CustomerID, "error", err) + "task", claim.Task.ID, "run", claim.Run.ID, "app_id", claim.Task.CustomerID, "error", err) } } @@ -563,7 +563,7 @@ func (s *Scheduler) postpone(claim store.ClaimedScheduledTask, until time.Time) ctx, cancel := context.WithTimeout(context.WithoutCancel(s.ctx), 15*time.Second) defer cancel() held, err := s.store.ScheduledTasks.Postpone(ctx, claim.Task.CustomerID, claim.Task.ID, claim.Run.ID, claim.LeasedBy, until) - log := s.logger.With("task", claim.Task.ID, "run", claim.Run.ID, "customer", claim.Task.CustomerID) + log := s.logger.With("task", claim.Task.ID, "run", claim.Run.ID, "app_id", claim.Task.CustomerID) switch { case err != nil: log.Error("could not hold a scheduled task", "error", err) @@ -667,7 +667,7 @@ func (s *Scheduler) finish(claim store.ClaimedScheduledTask, outcome store.Sched } applied, err = write() } - log := s.logger.With("task", claim.Task.ID, "run", claim.Run.ID, "customer", claim.Task.CustomerID) + log := s.logger.With("task", claim.Task.ID, "run", claim.Run.ID, "app_id", claim.Task.CustomerID) switch { case err != nil: // The run is left running, and whoever takes it up again settles and counts it. A diff --git a/acceleration/internal/session/connector_call_log_test.go b/acceleration/internal/session/connector_call_log_test.go index 3f196d14ad..be902fd1a9 100644 --- a/acceleration/internal/session/connector_call_log_test.go +++ b/acceleration/internal/session/connector_call_log_test.go @@ -58,7 +58,7 @@ func (s *CallLogSuite) TestAnIsErrorAnswerLogsTheToolsWordsWithTheRowsNamesAndID s.Require().Error(err) row := s.row(app) line := s.onlyFailedLine(logged) - for _, field := range []string{"level=WARN", "customer=" + s.customerID, "connection=" + app, + for _, field := range []string{"level=WARN", "app_id=" + s.customerID, "connection=" + app, "connector=" + s.connectorID, "binding=crm", "tool=fails", "session=" + spec.ID, "invocation=" + row.ID, "error_type=external_server", fmt.Sprintf("latency_ms=%d ", row.LatencyMs), "provider_status=200", `provider_message="the record is locked"`, "provider_host=" + s.providerHost(), `provider_body=""`} { diff --git a/acceleration/internal/session/dispatcher.go b/acceleration/internal/session/dispatcher.go index 276ac21ac9..cabfb72679 100644 --- a/acceleration/internal/session/dispatcher.go +++ b/acceleration/internal/session/dispatcher.go @@ -251,7 +251,7 @@ func (d *dispatcher) record(ctx context.Context, r route, call llm.ToolCall, sta if how.kind == "" { return } - fields := []any{"customer", row.CustomerID, "connection", row.ConnectionID, + fields := []any{"app_id", row.CustomerID, "connection", row.ConnectionID, "connector", row.ConnectorID, "binding", row.Binding, "tool", row.Tool, "session", row.SessionID, "invocation", row.ID, "error_type", row.ErrorType, "latency_ms", row.LatencyMs, "provider_status", how.status, "provider_message", message, diff --git a/acceleration/internal/session/manager.go b/acceleration/internal/session/manager.go index c8cb81cd93..5aa7363284 100644 --- a/acceleration/internal/session/manager.go +++ b/acceleration/internal/session/manager.go @@ -493,7 +493,7 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er floor, err := m.options.Policies.ToolOutputRetention(ctx, spec.CustomerID) if err != nil { m.logger.Warn("could not read the tool output retention, keeping none", - "customer", spec.CustomerID, "session", spec.ID, "error", err) + "app_id", spec.CustomerID, "session", spec.ID, "error", err) } spec.ToolOutputRetention = floor.Shorter(spec.ToolOutputRetention) } @@ -1160,7 +1160,7 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er m.cards.started(created, stream) m.logger.Info("session joined", - "session", created.id, "call", spec.CallID, "customer", spec.CustomerID) + "session", created.id, "call", spec.CallID, "app_id", spec.CustomerID) opened = true return created, nil } @@ -1780,7 +1780,7 @@ func (m *Manager) end(found *Session, reason EndReason) { func (m *Manager) idTaken(created *Session) { created.idTaken.Store(true) m.logger.Warn("ending a session whose id another customer's session has", - "session", created.id, "customer", created.Spec().CustomerID) + "session", created.id, "app_id", created.Spec().CustomerID) done, held := m.take(created) if !held { return @@ -1926,7 +1926,7 @@ func (m *Manager) hangUpRinging(created *Session, spec Spec) { ctx, cancel := context.WithTimeout(created.ctx, hangUpTimeout) defer cancel() if err := m.options.Phone.HangUpUnanswered(ctx, spec.CustomerID, spec.CallID); err != nil { - m.logger.Warn("could not hang up the call its session left ringing", "session", created.id, "call", spec.CallID, "customer", spec.CustomerID, "error", err) + m.logger.Warn("could not hang up the call its session left ringing", "session", created.id, "call", spec.CallID, "app_id", spec.CustomerID, "error", err) } }() } @@ -2158,7 +2158,7 @@ func (m *Manager) box(ctx context.Context, spec Spec, connectors *dispatcher) (s slots, err := m.options.SandboxLimits.Sandbox(ctx, owner(spec), policy.SandboxAsk{Config: spec.SandboxOptions, Granted: granted}) if err != nil { m.logger.Warn("the session runs without its sandbox, which its organization's sandbox limits do not allow", - "code", policy.SandboxLimitCode, "customer", spec.CustomerID, "session", spec.ID, "error", err) + "code", policy.SandboxLimitCode, "app_id", spec.CustomerID, "session", spec.ID, "error", err) return nil, nil } asked := metered.SandboxSpec{Config: spec.SandboxOptions, Slots: slots} diff --git a/acceleration/internal/session/run.go b/acceleration/internal/session/run.go index 4cdffe7b8f..6835881aba 100644 --- a/acceleration/internal/session/run.go +++ b/acceleration/internal/session/run.go @@ -109,7 +109,7 @@ func (m *Manager) Run(ctx context.Context, spec Spec, input string, images []llm run := RunOutcome{SessionID: created.ID()} // The images are counted here because nothing else a run logs says whether it had any, // and an answer that says it saw no image is otherwise impossible to place. - m.logger.Info("a run started", "customer", spec.CustomerID, "session", created.ID(), "config", spec.ConfigID, + m.logger.Info("a run started", "app_id", spec.CustomerID, "session", created.ID(), "config", spec.ConfigID, "images", len(images)) events, detach := created.Watch() defer detach() diff --git a/acceleration/internal/store/user.go b/acceleration/internal/store/user.go index 0b7ab55bfd..4cbc7305f9 100644 --- a/acceleration/internal/store/user.go +++ b/acceleration/internal/store/user.go @@ -134,7 +134,7 @@ func (r *Users) record(ctx context.Context, customerID, userID, sighting string) return nil case err != nil && !rueidis.IsRedisNil(err): slog.Default().Error("could not read a user from redis, writing postgres", - "customer", customerID, "user", userID, "error", err) + "app_id", customerID, "user", userID, "error", err) } } @@ -165,7 +165,7 @@ func (r *Users) record(ctx context.Context, customerID, userID, sighting string) return nil } slog.Default().Error("could not cache a user in redis", - "customer", customerID, "user", userID, "error", err) + "app_id", customerID, "user", userID, "error", err) } r.seen.Keep(customerID, userID, sighting, time.Time{}) return nil @@ -188,7 +188,7 @@ func (r *Users) hold(ctx context.Context, customerID, userID, value string) { r.seen.Remove(customerID, userID) if err != nil && !rueidis.IsRedisNil(err) { slog.Default().Error("could not read a user back from redis", - "customer", customerID, "user", userID, "error", err) + "app_id", customerID, "user", userID, "error", err) } } @@ -277,7 +277,7 @@ func (r *Users) Forget(ctx context.Context, customerID, userID string) { } if err := redis.Do(ctx, redis.B().Del().Key(userKey(customerID, userID)).Build()).Error(); err != nil { slog.Default().Error("could not drop a cached user", - "customer", customerID, "user", userID, "error", err) + "app_id", customerID, "user", userID, "error", err) } }