From 7dee5f4e30c22d35f59bdcf21514376da43c9ab5 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Mon, 23 Nov 2026 14:18:27 +0000 Subject: [PATCH] fix(api): an app runs one export at a time and an import line is bounded - An app runs one export at a time on a router, answered 409 otherwise, and a router runs at most four exports at once, answered 503 otherwise. - An export ends after an hour, or when one line has taken a minute to write. - An export reads each table through a cursor, 100 rows at a time, so one that ends partway reads at most the rest of its batch. - An import line over 64 MiB is answered 413. - A name that no agent config, router config or voice holds is cached for a minute rather than an hour. --- acceleration/api/openapi.yaml | 17 +- acceleration/internal/api/datamove.go | 96 ++++++++- acceleration/internal/api/datamove_test.go | 193 ++++++++++++++++++ acceleration/internal/api/handwritten.go | 10 +- acceleration/internal/api/server.go | 9 + acceleration/internal/store/agent_config.go | 6 +- .../internal/store/agent_config_test.go | 22 ++ acceleration/internal/store/datamove.go | 52 ++++- acceleration/internal/store/redis.go | 5 + acceleration/internal/store/router_config.go | 4 +- .../internal/store/router_config_test.go | 14 ++ acceleration/internal/store/voice.go | 4 +- acceleration/internal/store/voice_test.go | 13 ++ .../_generated/api/default/export_data.py | 13 ++ .../_generated/api/default/import_data.py | 41 ++-- sdks/go/acceleration/generated.go | 40 +++- sdks/js/src/generated/api.ts | 23 ++- 17 files changed, 512 insertions(+), 50 deletions(-) diff --git a/acceleration/api/openapi.yaml b/acceleration/api/openapi.yaml index c6b38248c4..0115489eb7 100644 --- a/acceleration/api/openapi.yaml +++ b/acceleration/api/openapi.yaml @@ -22040,6 +22040,7 @@ paths: One line per row, `{"table": ..., "row": {...}}`, and a last line `{"cursor": ..., "customer": ..., "at": ...}`. The cursor comes last because it is also what says the export finished: a stream that broke halfway has no cursor line, so half a copy cannot be mistaken for a whole one. The rows are read at one moment rather than stitched together, and exporting starts recording changes so that `listDataChanges` carries on from exactly where this left off. Only the calling app's rows are here, and credentials are not: an API key secret, an OAuth access token and an OAuth refresh token stay with the deployment that holds them, so an imported plugin connection has to be authorized again. The audio behind a voice sample and a call recording lives in an object bucket rather than in this database; the rows naming those objects are here, and copying the bucket is yours to do. A router with shards cannot be the source of a move and answers 400 `not_configured`. + An app runs one export at a time, and an export ends after an hour, or when one line has taken a minute to write: an export with no cursor line is one to run again. Server-side only, and refused entirely when the router runs with ROUTER_AUTH_MODE=noauth, where naming a customer is all it takes to be one. operationId: exportData responses: @@ -22066,6 +22067,12 @@ paths: $ref: '#/components/responses/PaymentRequired' "403": $ref: '#/components/responses/Forbidden' + "409": + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + description: 'An export of this app is already running on this router: one runs at a time.' "500": $ref: '#/components/responses/InternalError' "503": @@ -22073,12 +22080,12 @@ paths: application/json: schema: $ref: '#/components/schemas/ErrorResponse' - description: 'This deployment has no database to export from, or cannot record changes; or a write that was open when the export started is still open after 30 seconds: try again.' + description: 'This deployment has no database to export from, or cannot record changes; or this router is running as many exports as it takes at once; or a write that was open when the export started is still open after 30 seconds: try again.' summary: Everything this app has, as newline-delimited JSON /v1/data/import: post: description: |- - Takes what `exportData` produced, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. + Takes what `exportData` produced, one JSON object per line of at most 64 MiB, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. An export's rows are written as the source had them, so an export is refused with 409 `conflict`, before any of its rows is written, for an app that already has a row here in a table of the shared database: it would undo what was done here since. `full=true` writes it over them anyway, and importing the same export twice that way leaves what importing it once would. Changes are applied whatever the app holds. An import that stopped partway is run again with `full=true`, since the app then holds its first rows. Server-side only, and refused when the router runs with ROUTER_AUTH_MODE=noauth. operationId: importData @@ -22127,6 +22134,12 @@ paths: schema: $ref: '#/components/schemas/ErrorResponse' description: The file carries an export's rows, the app already has data here and `full` is not true. + "413": + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + description: A line of the file is over 64 MiB. "500": $ref: '#/components/responses/InternalError' "503": diff --git a/acceleration/internal/api/datamove.go b/acceleration/internal/api/datamove.go index 81ff3bc68f..9463532c10 100644 --- a/acceleration/internal/api/datamove.go +++ b/acceleration/internal/api/datamove.go @@ -1,9 +1,12 @@ package api import ( + "bufio" + "bytes" + "context" "encoding/json" "errors" - "io" + "fmt" "net/http" "strconv" "time" @@ -28,6 +31,38 @@ const ( // an export is a rare call whose caller can come back, so it is told to rather than held. const exportWritesWait = 30 * time.Second +// exportLineWait bounds the write of one line of an export. The export reads in one +// transaction, which holds a database connection until the last line is written, so a client +// that stops reading lets go of it after this rather than holding it for as long as it likes. +// A line is one row, which a client still reading takes in well under a minute. +const exportLineWait = time.Minute + +// exportWait bounds a whole export. Its rows are read in one repeatable-read transaction, and +// Postgres vacuums none of the rows that snapshot can see while it is open. An hour is a +// choice: it reads 36 GB at 10 MB/s. +const exportWait = time.Hour + +// maxExports bounds the exports running on one router at once, each holding a connection of +// its pool: a tenth of the 40 the store opens (store.maxConns), so the rest are left to +// requests. +const maxExports = 4 + +// maxImportLine bounds one line of an import, which is read into memory whole. A line is one +// row, and the largest row the router writes is a conversation document's text, read from a +// file of at most maxFetchedDocument (20 MiB): 64 MiB holds that with room for its JSON +// escaping. +const maxImportLine = 64 << 20 + +// errExportRunning refuses a second export of an app while one is running on this router. Each +// export holds a connection of this router's pool until its client has read it all. +var errExportRunning = conflict("an export of this app is already running: wait for it to finish") + +// errExportTooLong is an export whose exportWait passed before its first row was read. +var errExportTooLong = unavailable("the export ran out of time before its first row: try again") + +// errExportsBusy refuses an export while maxExports are running on this router. +var errExportsBusy = unavailable("this router is running as many exports as it takes at once: try again later") + // errWritesOpen is a capture start, or the export after it, that gave up on a write from before // the start (store.ErrWritesOpen). var errWritesOpen = unavailable("a write that started before the changes were recorded is still open: try again") @@ -66,6 +101,19 @@ func (s *Server) exportData(w http.ResponseWriter, r *http.Request) { writeError(w, errShardedSource) return } + if _, running := s.exporting.LoadOrStore(customerID, struct{}{}); running { + writeError(w, errExportRunning) + return + } + defer s.exporting.Delete(customerID) + select { + case s.exports <- struct{}{}: + default: + writeError(w, errExportsBusy) + return + } + defer func() { <-s.exports }() + ends := time.Now().Add(s.exportWait) // Recording starts before the snapshot is read rather than after, so a write that // lands while the export is being streamed is in one of the two and not in neither. @@ -94,16 +142,35 @@ func (s *Server) exportData(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/x-ndjson") w.Header().Set("Cache-Control", "no-store") encoder := json.NewEncoder(w) + controller := http.NewResponseController(w) + encode := func(line dataLine) error { + if err := controller.SetWriteDeadline(time.Now().Add(min(s.exportLineWait, time.Until(ends)))); err != nil { + return fmt.Errorf("api: export write deadline: %w", err) + } + return encoder.Encode(line) + } // A failure before the first line is still an error document. One after it is a // truncated stream, which the missing cursor line on the end is what says. written := int64(0) - cursor, err := s.store.ExportCustomer(r.Context(), customerID, func(table string, row json.RawMessage) error { + ctx, cancel := context.WithDeadline(r.Context(), ends) + defer cancel() + cursor, err := s.store.ExportCustomer(ctx, customerID, func(table string, row json.RawMessage) error { written++ - return encoder.Encode(dataLine{Table: table, Row: row}) + return encode(dataLine{Table: table, Row: row}) }) if err != nil { if written == 0 { + // The error document is written under a deadline of its own, not the export's, + // which may be what passed. + if err := controller.SetWriteDeadline(time.Now().Add(s.exportLineWait)); err != nil { + writeFailure(w, r, fmt.Errorf("api: export write deadline: %w", err)) + return + } + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + writeError(w, errExportTooLong) + return + } writeFailure(w, r, err) return } @@ -112,7 +179,7 @@ func (s *Server) exportData(w http.ResponseWriter, r *http.Request) { } now := time.Now().UTC() - if err := encoder.Encode(dataLine{Cursor: &cursor, Customer: customerID, At: &now}); err != nil { + if err := encode(dataLine{Cursor: &cursor, Customer: customerID, At: &now}); err != nil { s.logger.Debug("export was not finished", "customer", customerID, "error", err) return } @@ -144,13 +211,14 @@ func (s *Server) importData(w http.ResponseWriter, r *http.Request) { rows := int64(0) tables := map[string]int64{} - decoder := json.NewDecoder(r.Body) - for { + scanner := bufio.NewScanner(r.Body) + scanner.Buffer(nil, maxImportLine) + for scanner.Scan() { + if len(bytes.TrimSpace(scanner.Bytes())) == 0 { + continue + } var line dataLine - if err := decoder.Decode(&line); err != nil { - if errors.Is(err, io.EOF) { - break - } + if err := json.Unmarshal(scanner.Bytes(), &line); err != nil { writeError(w, invalidRequest("this is not an export: "+err.Error())) return } @@ -188,6 +256,14 @@ func (s *Server) importData(w http.ResponseWriter, r *http.Request) { cursor = line.Cursor } } + if errors.Is(scanner.Err(), bufio.ErrTooLong) { + writeError(w, payloadTooLarge(fmt.Sprintf("a line of an import is at most %d MiB", maxImportLine>>20))) + return + } + if err := scanner.Err(); err != nil { + writeError(w, invalidRequest("this is not an export: "+err.Error())) + return + } s.logger.Info("imported a customer", "customer", customerID, "rows", rows) writeJSON(w, map[string]any{"rows": rows, "tables": tables, "cursor": cursor}) diff --git a/acceleration/internal/api/datamove_test.go b/acceleration/internal/api/datamove_test.go index 7fe376d302..3d94e7c08b 100644 --- a/acceleration/internal/api/datamove_test.go +++ b/acceleration/internal/api/datamove_test.go @@ -3,6 +3,7 @@ package api import ( + "bufio" "context" "database/sql" "encoding/json" @@ -37,7 +38,18 @@ func TestDataMoveSuite(t *testing.T) { suite.Run(t, new(DataMoveSuite)) } +// letGoWithin is how long a test waits for an export to end and let go of its place: well past +// the deadlines the tests set, for a machine running other suites beside this one. A wait ends +// as soon as the export has. +const letGoWithin = 30 * time.Second + func (s *DataMoveSuite) SetupTest() { + // Last of the test's cleanups: the router's places for exports are shared by the tests + // after it, so the exports a test left unread have ended before the next one starts. + s.T().Cleanup(func() { + s.Eventually(func() bool { return len(s.router.exports) == 0 }, letGoWithin, 10*time.Millisecond, + "an export of this test is still running") + }) s.useApp(s.data.createApp()) } @@ -342,6 +354,148 @@ func (s *DataMoveSuite) TestAnImportedNumberOnItsOwnTrunkInAnotherFormIsRefused( s.Contains(failure, "E.164") } +func (s *DataMoveSuite) TestAnImportLineOverTheLimitIsRefused() { + line := `{"table":"agent_configs","row":{"instructions":"` + strings.Repeat("x", maxImportLine) + `"}}` + + status, failure := s.serverClient.failure(http.MethodPost, "/v1/data/import", line) + + s.Require().Equal(http.StatusRequestEntityTooLarge, status, failure[:min(len(failure), 200)]) + s.Contains(failure, "64 MiB") +} + +func (s *DataMoveSuite) TestAnImportLineJustUnderTheLimitIsRead() { + s.data.createAgentConfig() + var row json.RawMessage + for _, line := range s.export() { + if line.Table == "agent_configs" { + row = line.Row + } + } + s.Require().NotNil(row, "the app has an agent") + fields := map[string]any{} + s.Require().NoError(json.Unmarshal(row, &fields)) + id := "agent-" + s.utils.uuid() + fields["id"], fields["name"], fields["instructions"] = id, id, "" + empty := s.lineOf(fields) + filler := maxImportLine - 1 - len(empty) + fields["instructions"] = strings.Repeat("x", filler) + line := s.lineOf(fields) + s.Require().Len(line, maxImportLine-1) + + status, failure := s.serverClient.failure(http.MethodPost, "/v1/data/import?full=true", line) + + s.Require().Equal(http.StatusOK, status, failure[:min(len(failure), 200)]) + var stored int + s.Require().NoError(s.store.GlobalDB().QueryRowContext(context.Background(), + "SELECT length(instructions) FROM agent_configs WHERE id = ? AND customer_id = ?", id, s.customerID()).Scan(&stored)) + s.Equal(filler, stored) +} + +// lineOf is one line of an import carrying an agent config row. +func (s *DataMoveSuite) lineOf(fields map[string]any) string { + row, err := json.Marshal(fields) + s.Require().NoError(err) + encoded, err := json.Marshal(dataLine{Table: "agent_configs", Row: row}) + s.Require().NoError(err) + return string(encoded) +} + +// An export holds a connection of the router's pool until its client has read it all. +func (s *DataMoveSuite) TestASecondExportOfAnAppIsRefusedWhileOneIsRunning() { + s.skipOnARouterWithShards() + s.seedRowsTooBigToBuffer() + s.Require().Equal(http.StatusOK, s.stalledExport().StatusCode) + + status, failure := s.serverClient.failure(http.MethodGet, "/v1/data/export", nil) + + s.Require().Equal(http.StatusConflict, status) + s.Contains(failure, "already running") +} + +func (s *DataMoveSuite) TestOtherRequestsAreServedWhileExportsRun() { + s.skipOnARouterWithShards() + s.seedRowsTooBigToBuffer() + statuses := map[int]int{} + for range suiteConnections { + statuses[s.stalledExport().StatusCode]++ + } + + s.Equal(http.StatusCreated, s.anotherRequest()) + s.Equal(map[int]int{http.StatusOK: 1, http.StatusConflict: suiteConnections - 1}, statuses) +} + +func (s *DataMoveSuite) TestOtherRequestsAreServedWhileExportsOfManyAppsRun() { + s.skipOnARouterWithShards() + s.Require().Less(maxExports, suiteConnections, "the suite's pool holds more than the exports a router runs") + statuses := map[int]int{} + for range suiteConnections { + s.useApp(s.data.createApp()) + s.seedRowsTooBigToBuffer() + statuses[s.stalledExport().StatusCode]++ + } + + s.Equal(http.StatusCreated, s.anotherRequest()) + s.Equal(map[int]int{http.StatusOK: maxExports, http.StatusServiceUnavailable: suiteConnections - maxExports}, statuses) +} + +// The rows of a table an export ends in the middle of are not all read before it lets go. +func (s *DataMoveSuite) TestAnExportHungUpOnLetsGoAtOnce() { + s.skipOnARouterWithShards() + // 20,000 rows of 64 KiB: reading them all takes seconds, and a batch of them a moment. + _, err := s.store.GlobalDB().ExecContext(context.Background(), ` +INSERT INTO agent_configs (id, customer_id, name, instructions) +SELECT 'agent-' || gen_random_uuid(), ?, 'agent-' || gen_random_uuid(), repeat('x', 64 << 10) +FROM generate_series(1, 20000)`, s.customerID()) + s.Require().NoError(err) + export := s.stalledExport() + s.Require().Equal(http.StatusOK, export.StatusCode) + lines := bufio.NewReader(export.Body) + for range 3 { + _, err := lines.ReadBytes('\n') + s.Require().NoError(err) + } + + s.Require().NoError(export.Body.Close()) + + s.Eventually(func() bool { return len(s.router.exports) == 0 }, 2*time.Second, 10*time.Millisecond, + "the export hung up on still holds its place") +} + +func (s *DataMoveSuite) TestAnExportReadSlowlyEndsAtItsDeadline() { + s.skipOnARouterWithShards() + s.seedRowsTooBigToBuffer() + s.Equal(exportWait, s.router.exportWait, "the default bound") + s.router.exportWait = 2 * time.Second + s.T().Cleanup(func() { s.router.exportWait = exportWait }) + slow := s.stalledExport() + s.Require().Equal(http.StatusOK, slow.StatusCode) + go func() { + // 640 KB a second: the whole export would take most of a minute, and no line a minute. + chunk := make([]byte, 64<<10) + for { + if _, err := io.ReadFull(slow.Body, chunk); err != nil { + return + } + time.Sleep(100 * time.Millisecond) + } + }() + + s.Eventually(func() bool { return len(s.router.exports) == 0 }, letGoWithin, 50*time.Millisecond, + "the export read slowly is still running") +} + +func (s *DataMoveSuite) TestAnExportWhoseClientStopsReadingIsLetGo() { + s.skipOnARouterWithShards() + s.seedRowsTooBigToBuffer() + s.Equal(exportLineWait, s.router.exportLineWait, "the default bound") + s.router.exportLineWait = 500 * time.Millisecond + s.T().Cleanup(func() { s.router.exportLineWait = exportLineWait }) + s.Require().Equal(http.StatusOK, s.stalledExport().StatusCode) + + s.Eventually(func() bool { return len(s.router.exports) == 0 }, letGoWithin, 50*time.Millisecond, + "the export nobody reads is still running") +} + func (s *DataMoveSuite) TestSomethingThatIsNotAnExportIsRefused() { status, failure := s.serverClient.failure(http.MethodPost, "/v1/data/import", "not an export at all") @@ -626,6 +780,45 @@ func (s *DataMoveSuite) shardDSN() string { return dsn } +// seedRowsTooBigToBuffer gives the app 32 MiB of agent configs, more than the sockets between +// the router and a client hold, so an export whose client stops reading stops writing. +func (s *DataMoveSuite) seedRowsTooBigToBuffer() { + _, err := s.store.GlobalDB().ExecContext(context.Background(), ` +INSERT INTO agent_configs (id, customer_id, name, instructions) +SELECT 'agent-' || gen_random_uuid(), ?, 'agent-' || gen_random_uuid(), repeat('x', 1 << 20) +FROM generate_series(1, 32)`, s.customerID()) + s.Require().NoError(err) +} + +// stalledExport starts an export on a connection of its own and reads nothing past the headers. +func (s *DataMoveSuite) stalledExport() *http.Response { + request, err := http.NewRequest(http.MethodGet, s.serverClient.base()+"/v1/data/export", nil) + s.Require().NoError(err) + request.Header = s.serverClient.header.Clone() + transport := &http.Transport{} + response, err := (&http.Client{Transport: transport}).Do(request) + s.Require().NoError(err) + s.T().Cleanup(func() { + _ = response.Body.Close() + transport.CloseIdleConnections() + }) + return response +} + +// anotherRequest creates an agent config of the app, giving up after settleFor, and answers its +// status. +func (s *DataMoveSuite) anotherRequest() int { + request, err := http.NewRequestWithContext(s.T().Context(), http.MethodPost, s.serverClient.base()+"/v1/agents/configs", + strings.NewReader(`{"name":"agent-`+s.utils.uuid()+`","llm":"llm-flow"}`)) + s.Require().NoError(err) + request.Header = s.serverClient.header.Clone() + request.Header.Set("Content-Type", "application/json") + response, err := (&http.Client{Timeout: settleFor}).Do(request) + s.Require().NoError(err, "the request found no free connection") + s.Require().NoError(response.Body.Close()) + return response.StatusCode +} + // openWrite writes an agent config of a customer in a transaction the test ends. func (s *DataMoveSuite) openWrite(customerID string) openWrite { return s.openWriteAt(sql.LevelDefault, customerID) diff --git a/acceleration/internal/api/handwritten.go b/acceleration/internal/api/handwritten.go index 97cc50496b..6d84c36a97 100644 --- a/acceleration/internal/api/handwritten.go +++ b/acceleration/internal/api/handwritten.go @@ -937,6 +937,8 @@ func documentHandWritten(api huma.API) { "sample and a call recording lives in an object bucket rather than in this database; the " + "rows naming those objects are here, and copying the bucket is yours to do.\n" + "A router with shards cannot be the source of a move and answers 400 `not_configured`.\n" + + "An app runs one export at a time, and an export ends after an hour, or when one line " + + "has taken a minute to write: an export with no cursor line is one to run again.\n" + "Server-side only, and refused entirely when the router runs with " + "ROUTER_AUTH_MODE=noauth, where naming a customer is all it takes to be one.", Responses: map[string]*huma.Response{ @@ -944,7 +946,8 @@ func documentHandWritten(api huma.API) { "400": {Ref: "#/components/responses/BadRequest"}, "401": {Ref: "#/components/responses/Unauthorized"}, "403": {Ref: "#/components/responses/Forbidden"}, - "503": {Description: "This deployment has no database to export from, or cannot record changes; or a write that was open when the export started is still open after 30 seconds: try again.", Content: map[string]*huma.MediaType{"application/json": {Schema: registry.Schema(reflect.TypeFor[ErrorResponse](), true, "")}}}, + "409": {Description: "An export of this app is already running on this router: one runs at a time.", Content: map[string]*huma.MediaType{"application/json": {Schema: registry.Schema(reflect.TypeFor[ErrorResponse](), true, "")}}}, + "503": {Description: "This deployment has no database to export from, or cannot record changes; or this router is running as many exports as it takes at once; or a write that was open when the export started is still open after 30 seconds: try again.", Content: map[string]*huma.MediaType{"application/json": {Schema: registry.Schema(reflect.TypeFor[ErrorResponse](), true, "")}}}, }, }) document.AddOperation(&huma.Operation{ @@ -952,8 +955,8 @@ func documentHandWritten(api huma.API) { Method: http.MethodPost, Path: "/v1/data/import", Summary: "Write an export, or a batch of changes, into this deployment", - Description: "Takes what `exportData` produced, and the same lines with a `change` in place of a " + - "`row` for what `listDataChanges` returned. Every row is written under the calling app " + + Description: "Takes what `exportData` produced, one JSON object per line of at most 64 MiB, and the " + + "same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app " + "whatever the file says, so an export from one app cannot be imported into another's " + "rows, and rows belonging to a customer through a parent are only written where that " + "parent is the caller's.\n" + @@ -979,6 +982,7 @@ func documentHandWritten(api huma.API) { "401": {Ref: "#/components/responses/Unauthorized"}, "403": {Ref: "#/components/responses/Forbidden"}, "409": {Description: "The file carries an export's rows, the app already has data here and `full` is not true.", Content: map[string]*huma.MediaType{"application/json": {Schema: registry.Schema(reflect.TypeFor[ErrorResponse](), true, "")}}}, + "413": {Description: "A line of the file is over 64 MiB.", Content: map[string]*huma.MediaType{"application/json": {Schema: registry.Schema(reflect.TypeFor[ErrorResponse](), true, "")}}}, "503": {Description: "This deployment has no database to import into.", Content: map[string]*huma.MediaType{"application/json": {Schema: registry.Schema(reflect.TypeFor[ErrorResponse](), true, "")}}}, }, }) diff --git a/acceleration/internal/api/server.go b/acceleration/internal/api/server.go index fd653dd984..d64f76f5f1 100644 --- a/acceleration/internal/api/server.go +++ b/acceleration/internal/api/server.go @@ -389,9 +389,15 @@ type Server struct { authMode auth.Mode dataRetention time.Duration exportWritesWait time.Duration + exportLineWait time.Duration + exportWait time.Duration quota *quota.Limiter policies *policy.Enforcer connectors core.Registry + // exporting holds the customers with an export running on this router, one each, and + // exports a place for each export running on it, of maxExports. + exporting sync.Map + exports chan struct{} // connectorSecrets seals consent attempts; credentials stores what a consent got. Both // are nil when connectors are off. connectorSecrets *auth.Sealer @@ -589,6 +595,9 @@ func NewServer(options Options, with ...Option) (*Server, error) { authMode: authMode, dataRetention: retention, exportWritesWait: exportWritesWait, + exportLineWait: exportLineWait, + exportWait: exportWait, + exports: make(chan struct{}, maxExports), scheduledPoll: 2 * time.Second, scheduledPeerWait: 30 * time.Second, replyPoll: 100 * time.Millisecond, diff --git a/acceleration/internal/store/agent_config.go b/acceleration/internal/store/agent_config.go index 55821566cf..9acdf2d490 100644 --- a/acceleration/internal/store/agent_config.go +++ b/acceleration/internal/store/agent_config.go @@ -13,6 +13,7 @@ import ( "strings" "time" + "github.com/redis/rueidis/rueidisaside" "github.com/uptrace/bun" "github.com/GetStream/Vision-Agents/acceleration/internal/pricing" @@ -494,8 +495,8 @@ func (r *AgentConfigs) Get(ctx context.Context, customerID, id string) (AgentCon } // GetByName returns the config a customer holds under this name, and ErrNoAgentConfig when it -// holds none. That none is cached too: a session opened by name asks the same question on -// every conversation. +// holds none. That none is cached too, for missTTL: a session opened by name asks the same +// question on every conversation. func (r *AgentConfigs) GetByName(ctx context.Context, customerID, name string) (AgentConfig, error) { if customerID == "" || name == "" { return AgentConfig{}, stack.Wrap(errors.New("store: a customer and a config name are required")) @@ -503,6 +504,7 @@ func (r *AgentConfigs) GetByName(ctx context.Context, customerID, name string) ( answer, err := cached(ctx, r.store, agentConfigNameKey(customerID, name), func(ctx context.Context) (found[AgentConfig], error) { config, err := r.where(ctx, customerID, "name", name) if errors.Is(err, ErrNoAgentConfig) { + rueidisaside.OverrideCacheTTL(ctx, missTTL) return found[AgentConfig]{}, nil } return found[AgentConfig]{Value: config, Found: err == nil}, err diff --git a/acceleration/internal/store/agent_config_test.go b/acceleration/internal/store/agent_config_test.go index e0376b80cf..6e6d2452b5 100644 --- a/acceleration/internal/store/agent_config_test.go +++ b/acceleration/internal/store/agent_config_test.go @@ -204,6 +204,28 @@ func (s *StoreSuite) TestADeletedAgentConfigIsForgottenByIdAndName() { s.ErrorIs(err, ErrNoAgentConfig) } +// Every name asked for is a key of its own, and no write deletes one nobody creates. +func (s *StoreSuite) TestANameNoConfigHoldsIsCachedForAMinuteOnly() { + config := s.boundConfig("acme-app") + _, err := s.store.AgentConfigs.GetByName(s.ctx, "acme-app", config.Name) + s.Require().NoError(err) + missing := "nobody-" + newID() + _, err = s.store.AgentConfigs.GetByName(s.ctx, "acme-app", missing) + s.Require().ErrorIs(err, ErrNoAgentConfig) + + s.Positive(s.expiryOf(agentConfigNameKey("acme-app", missing)), "the miss is cached") + s.LessOrEqual(s.expiryOf(agentConfigNameKey("acme-app", missing)), time.Minute) + s.Greater(s.expiryOf(agentConfigNameKey("acme-app", config.Name)), 59*time.Minute, "a config found is still cached for the hour") +} + +// expiryOf is how long a key has left in Redis. +func (s *StoreSuite) expiryOf(key string) time.Duration { + redis := s.store.sharedRedis() + ttl, err := redis.Do(s.ctx, redis.B().Pttl().Key(key).Build()).AsInt64() + s.Require().NoError(err) + return time.Duration(ttl) * time.Millisecond +} + func (s *StoreSuite) TestAgentConfigQueryBudgets() { for range 20 { s.boundConfig("acme-app") diff --git a/acceleration/internal/store/datamove.go b/acceleration/internal/store/datamove.go index e9b1a2e881..1e7210ba71 100644 --- a/acceleration/internal/store/datamove.go +++ b/acceleration/internal/store/datamove.go @@ -617,28 +617,62 @@ func (s *Store) exportTable(ctx context.Context, tx bun.Tx, table dataTable, cus return err } query, args := table.selectRows(customerID, shape.secrets()) - rows, err := tx.QueryContext(ctx, query, args...) - if err != nil { + // Read through a cursor in the transaction's snapshot rather than as one query: closing a + // query's rows early reads every row left, so an export that ends partway would hold its + // transaction until the whole table had been read. A batch is all it reads instead. + if _, err := tx.ExecContext(ctx, "DECLARE export_rows NO SCROLL CURSOR FOR "+query, args...); err != nil { return fmt.Errorf("store: export %s: %w", table.name, err) } + for { + if err := ctx.Err(); err != nil { + return fmt.Errorf("store: export %s: %w", table.name, err) + } + fetched, err := s.exportBatch(ctx, tx, table.name, write) + if err != nil { + return err + } + if fetched < exportBatchRows { + break + } + } + if _, err := tx.ExecContext(ctx, "CLOSE export_rows"); err != nil { + return fmt.Errorf("store: export %s: %w", table.name, err) + } + return nil +} + +// exportBatchRows is how many rows an export reads from its cursor at a time, and so the most it +// reads past the row it stops at. A row can be a whole document's text of several MiB, which +// a hundred keep to a moment's reading, and most rows are well under a KiB. +const exportBatchRows = 100 + +// exportBatch writes the next exportBatchRows rows of the export_rows cursor and returns how many +// it read. +func (s *Store) exportBatch(ctx context.Context, tx bun.Tx, table string, write func(string, json.RawMessage) error) (int, error) { + rows, err := tx.QueryContext(ctx, fmt.Sprintf("FETCH %d FROM export_rows", exportBatchRows)) + if err != nil { + return 0, fmt.Errorf("store: export %s: %w", table, err) + } defer rows.Close() + fetched := 0 for rows.Next() { + fetched++ var row json.RawMessage if err := rows.Scan(&row); err != nil { - return fmt.Errorf("store: export %s: %w", table.name, err) + return 0, fmt.Errorf("store: export %s: %w", table, err) } - if row, err = s.exportPin(table.name, row); err != nil { - return err + if row, err = s.exportPin(table, row); err != nil { + return 0, err } - if err := write(table.name, row); err != nil { - return err + if err := write(table, row); err != nil { + return 0, err } } if err := rows.Err(); err != nil { - return fmt.Errorf("store: export %s: %w", table.name, err) + return 0, fmt.Errorf("store: export %s: %w", table, err) } - return nil + return fetched, nil } // selectRows reads one table's rows for one customer, without the columns that never diff --git a/acceleration/internal/store/redis.go b/acceleration/internal/store/redis.go index e09ea8594f..51430107df 100644 --- a/acceleration/internal/store/redis.go +++ b/acceleration/internal/store/redis.go @@ -29,6 +29,11 @@ const cacheTTL = time.Hour // stop authenticating within a minute rather than an hour. const keyCacheTTL = time.Minute +// missTTL is how long a lookup that found nothing is cached. No write deletes such a key unless +// it creates the row, so the expiry is what lets one go, and every name asked for once would +// otherwise be kept for cacheTTL. +const missTTL = time.Minute + // Redis says where a Redis server is. An empty Address is none. type Redis struct { // Address is a host:port, for example localhost:6379. diff --git a/acceleration/internal/store/router_config.go b/acceleration/internal/store/router_config.go index 4555549849..1ea183036a 100644 --- a/acceleration/internal/store/router_config.go +++ b/acceleration/internal/store/router_config.go @@ -7,6 +7,7 @@ import ( "fmt" "time" + "github.com/redis/rueidis/rueidisaside" "github.com/uptrace/bun" "github.com/GetStream/Vision-Agents/acceleration/internal/options" @@ -159,7 +160,7 @@ func (r *RouterConfigs) Get(ctx context.Context, customerID, id string) (RouterC // GetByName returns the config a customer holds under this name, which is how a caller that // names a config rather than an id reaches one, and ErrNoRouterConfig when it holds none. -// That none is cached too. +// That none is cached too, for missTTL. func (r *RouterConfigs) GetByName(ctx context.Context, customerID, name string) (RouterConfig, error) { if customerID == "" || name == "" { return RouterConfig{}, stack.Wrap(errors.New("store: a customer and a config name are required")) @@ -167,6 +168,7 @@ func (r *RouterConfigs) GetByName(ctx context.Context, customerID, name string) answer, err := cached(ctx, r.store, routerConfigNameKey(customerID, name), func(ctx context.Context) (found[RouterConfig], error) { config, err := r.where(ctx, customerID, "name", name) if errors.Is(err, ErrNoRouterConfig) { + rueidisaside.OverrideCacheTTL(ctx, missTTL) return found[RouterConfig]{}, nil } return found[RouterConfig]{Value: config, Found: err == nil}, err diff --git a/acceleration/internal/store/router_config_test.go b/acceleration/internal/store/router_config_test.go index 7e2e0e5532..0884722377 100644 --- a/acceleration/internal/store/router_config_test.go +++ b/acceleration/internal/store/router_config_test.go @@ -2,12 +2,26 @@ package store +import "time" + func (s *StoreSuite) routerConfig(customerID, name string) RouterConfig { config := RouterConfig{CustomerID: customerID, Name: name} s.Require().NoError(s.store.RouterConfigs.Insert(s.ctx, &config)) return config } +func (s *StoreSuite) TestANameNoRouterConfigHoldsIsCachedForAMinuteOnly() { + s.routerConfig("acme-app", "fast") + _, err := s.store.RouterConfigs.GetByName(s.ctx, "acme-app", "fast") + s.Require().NoError(err) + _, err = s.store.RouterConfigs.GetByName(s.ctx, "acme-app", "nobody") + s.Require().ErrorIs(err, ErrNoRouterConfig) + + s.Positive(s.expiryOf(routerConfigNameKey("acme-app", "nobody")), "the miss is cached") + s.LessOrEqual(s.expiryOf(routerConfigNameKey("acme-app", "nobody")), time.Minute) + s.Greater(s.expiryOf(routerConfigNameKey("acme-app", "fast")), 59*time.Minute, "a config found is still cached for the hour") +} + func (s *StoreSuite) TestARouterConfigIsOnlyItsOwnCustomers() { mine := s.routerConfig("acme-app", "fast") s.routerConfig("other-app", "fast") diff --git a/acceleration/internal/store/voice.go b/acceleration/internal/store/voice.go index 269dfb91b2..f8d7a0ef7e 100644 --- a/acceleration/internal/store/voice.go +++ b/acceleration/internal/store/voice.go @@ -7,6 +7,7 @@ import ( "fmt" "time" + "github.com/redis/rueidis/rueidisaside" "github.com/uptrace/bun" "github.com/uptrace/bun/dialect/pgdialect" @@ -157,7 +158,7 @@ func (r *Voices) Get(ctx context.Context, customerID, id string) (Voice, error) // GetByName returns the voice a customer calls this. It is what lets a session name a voice // the way a person would rather than by id. A name the customer has no voice by is cached as -// that too, since it is usually one of a provider's own. +// that too, for missTTL, since it is usually one of a provider's own. func (r *Voices) GetByName(ctx context.Context, customerID, name string) (Voice, error) { if customerID == "" || name == "" { return Voice{}, stack.Wrap(errors.New("store: a customer and a voice name are required")) @@ -165,6 +166,7 @@ func (r *Voices) GetByName(ctx context.Context, customerID, name string) (Voice, answer, err := cached(ctx, r.store, voiceNameKey(customerID, name), func(ctx context.Context) (found[Voice], error) { voice, err := r.where(ctx, customerID, "name", name) if errors.Is(err, ErrNoVoice) { + rueidisaside.OverrideCacheTTL(ctx, missTTL) return found[Voice]{}, nil } return found[Voice]{Value: voice, Found: err == nil}, err diff --git a/acceleration/internal/store/voice_test.go b/acceleration/internal/store/voice_test.go index 4bf0f06ae0..068c27b00e 100644 --- a/acceleration/internal/store/voice_test.go +++ b/acceleration/internal/store/voice_test.go @@ -4,6 +4,7 @@ package store import ( "errors" + "time" ) func (s *StoreSuite) TestAVoiceIsReadBackByIdAndByTheNameItWasGiven() { @@ -20,6 +21,18 @@ func (s *StoreSuite) TestAVoiceIsReadBackByIdAndByTheNameItWasGiven() { s.Equal(voice.ID, byName.ID) } +func (s *StoreSuite) TestANameNoVoiceHoldsIsCachedForAMinuteOnly() { + s.Require().NoError(s.store.Voices.Insert(s.ctx, &Voice{CustomerID: "acme", Name: "founder"})) + _, err := s.store.Voices.GetByName(s.ctx, "acme", "founder") + s.Require().NoError(err) + _, err = s.store.Voices.GetByName(s.ctx, "acme", "narrator") + s.Require().ErrorIs(err, ErrNoVoice) + + s.Positive(s.expiryOf(voiceNameKey("acme", "narrator")), "the miss is cached") + s.LessOrEqual(s.expiryOf(voiceNameKey("acme", "narrator")), time.Minute) + s.Greater(s.expiryOf(voiceNameKey("acme", "founder")), 59*time.Minute, "a voice found is still cached for the hour") +} + func (s *StoreSuite) TestOneCustomersVoiceIsNotAnothersToRead() { voice := Voice{CustomerID: "acme", Name: "founder"} s.Require().NoError(s.store.Voices.Insert(s.ctx, &voice)) diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/api/default/export_data.py b/plugins/stream/vision_agents/plugins/stream/_generated/api/default/export_data.py index 7c5f85d953..1c7f642211 100644 --- a/plugins/stream/vision_agents/plugins/stream/_generated/api/default/export_data.py +++ b/plugins/stream/vision_agents/plugins/stream/_generated/api/default/export_data.py @@ -46,6 +46,11 @@ def _parse_response( return response_403 + if response.status_code == 409: + response_409 = ErrorResponse.from_dict(response.json()) + + return response_409 + if response.status_code == 500: response_500 = ErrorResponse.from_dict(response.json()) @@ -90,6 +95,8 @@ def sync_detailed( an object bucket rather than in this database; the rows naming those objects are here, and copying the bucket is yours to do. A router with shards cannot be the source of a move and answers 400 `not_configured`. + An app runs one export at a time, and an export ends after an hour, or when one line has taken a + minute to write: an export with no cursor line is one to run again. Server-side only, and refused entirely when the router runs with ROUTER_AUTH_MODE=noauth, where naming a customer is all it takes to be one. @@ -127,6 +134,8 @@ def sync( an object bucket rather than in this database; the rows naming those objects are here, and copying the bucket is yours to do. A router with shards cannot be the source of a move and answers 400 `not_configured`. + An app runs one export at a time, and an export ends after an hour, or when one line has taken a + minute to write: an export with no cursor line is one to run again. Server-side only, and refused entirely when the router runs with ROUTER_AUTH_MODE=noauth, where naming a customer is all it takes to be one. @@ -160,6 +169,8 @@ async def asyncio_detailed( an object bucket rather than in this database; the rows naming those objects are here, and copying the bucket is yours to do. A router with shards cannot be the source of a move and answers 400 `not_configured`. + An app runs one export at a time, and an export ends after an hour, or when one line has taken a + minute to write: an export with no cursor line is one to run again. Server-side only, and refused entirely when the router runs with ROUTER_AUTH_MODE=noauth, where naming a customer is all it takes to be one. @@ -195,6 +206,8 @@ async def asyncio( an object bucket rather than in this database; the rows naming those objects are here, and copying the bucket is yours to do. A router with shards cannot be the source of a move and answers 400 `not_configured`. + An app runs one export at a time, and an export ends after an hour, or when one line has taken a + minute to write: an export with no cursor line is one to run again. Server-side only, and refused entirely when the router runs with ROUTER_AUTH_MODE=noauth, where naming a customer is all it takes to be one. diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/api/default/import_data.py b/plugins/stream/vision_agents/plugins/stream/_generated/api/default/import_data.py index 7c3b6c011e..5313ec7000 100644 --- a/plugins/stream/vision_agents/plugins/stream/_generated/api/default/import_data.py +++ b/plugins/stream/vision_agents/plugins/stream/_generated/api/default/import_data.py @@ -69,6 +69,11 @@ def _parse_response( return response_409 + if response.status_code == 413: + response_413 = ErrorResponse.from_dict(response.json()) + + return response_413 + if response.status_code == 500: response_500 = ErrorResponse.from_dict(response.json()) @@ -104,10 +109,11 @@ def sync_detailed( ) -> Response[DataImport | ErrorResponse]: """Write an export, or a batch of changes, into this deployment - Takes what `exportData` produced, and the same lines with a `change` in place of a `row` for what - `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an - export from one app cannot be imported into another's rows, and rows belonging to a customer through - a parent are only written where that parent is the caller's. + Takes what `exportData` produced, one JSON object per line of at most 64 MiB, and the same lines + with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under + the calling app whatever the file says, so an export from one app cannot be imported into another's + rows, and rows belonging to a customer through a parent are only written where that parent is the + caller's. An export's rows are written as the source had them, so an export is refused with 409 `conflict`, before any of its rows is written, for an app that already has a row here in a table of the shared database: it would undo what was done here since. `full=true` writes it over them anyway, and @@ -148,10 +154,11 @@ def sync( ) -> DataImport | ErrorResponse | None: """Write an export, or a batch of changes, into this deployment - Takes what `exportData` produced, and the same lines with a `change` in place of a `row` for what - `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an - export from one app cannot be imported into another's rows, and rows belonging to a customer through - a parent are only written where that parent is the caller's. + Takes what `exportData` produced, one JSON object per line of at most 64 MiB, and the same lines + with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under + the calling app whatever the file says, so an export from one app cannot be imported into another's + rows, and rows belonging to a customer through a parent are only written where that parent is the + caller's. An export's rows are written as the source had them, so an export is refused with 409 `conflict`, before any of its rows is written, for an app that already has a row here in a table of the shared database: it would undo what was done here since. `full=true` writes it over them anyway, and @@ -187,10 +194,11 @@ async def asyncio_detailed( ) -> Response[DataImport | ErrorResponse]: """Write an export, or a batch of changes, into this deployment - Takes what `exportData` produced, and the same lines with a `change` in place of a `row` for what - `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an - export from one app cannot be imported into another's rows, and rows belonging to a customer through - a parent are only written where that parent is the caller's. + Takes what `exportData` produced, one JSON object per line of at most 64 MiB, and the same lines + with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under + the calling app whatever the file says, so an export from one app cannot be imported into another's + rows, and rows belonging to a customer through a parent are only written where that parent is the + caller's. An export's rows are written as the source had them, so an export is refused with 409 `conflict`, before any of its rows is written, for an app that already has a row here in a table of the shared database: it would undo what was done here since. `full=true` writes it over them anyway, and @@ -229,10 +237,11 @@ async def asyncio( ) -> DataImport | ErrorResponse | None: """Write an export, or a batch of changes, into this deployment - Takes what `exportData` produced, and the same lines with a `change` in place of a `row` for what - `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an - export from one app cannot be imported into another's rows, and rows belonging to a customer through - a parent are only written where that parent is the caller's. + Takes what `exportData` produced, one JSON object per line of at most 64 MiB, and the same lines + with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under + the calling app whatever the file says, so an export from one app cannot be imported into another's + rows, and rows belonging to a customer through a parent are only written where that parent is the + caller's. An export's rows are written as the source had them, so an export is refused with 409 `conflict`, before any of its rows is written, for an app that already has a row here in a table of the shared database: it would undo what was done here since. `full=true` writes it over them anyway, and diff --git a/sdks/go/acceleration/generated.go b/sdks/go/acceleration/generated.go index 960562a03e..a4e000d826 100644 --- a/sdks/go/acceleration/generated.go +++ b/sdks/go/acceleration/generated.go @@ -15517,6 +15517,7 @@ type ClientInterface interface { // One line per row, `{"table": ..., "row": {...}}`, and a last line `{"cursor": ..., "customer": ..., "at": ...}`. The cursor comes last because it is also what says the export finished: a stream that broke halfway has no cursor line, so half a copy cannot be mistaken for a whole one. The rows are read at one moment rather than stitched together, and exporting starts recording changes so that `listDataChanges` carries on from exactly where this left off. // Only the calling app's rows are here, and credentials are not: an API key secret, an OAuth access token and an OAuth refresh token stay with the deployment that holds them, so an imported plugin connection has to be authorized again. The audio behind a voice sample and a call recording lives in an object bucket rather than in this database; the rows naming those objects are here, and copying the bucket is yours to do. // A router with shards cannot be the source of a move and answers 400 `not_configured`. + // An app runs one export at a time, and an export ends after an hour, or when one line has taken a minute to write: an export with no cursor line is one to run again. // Server-side only, and refused entirely when the router runs with ROUTER_AUTH_MODE=noauth, where naming a customer is all it takes to be one. // // Corresponds with GET /v1/data/export (the `ExportData` operationId). @@ -15524,7 +15525,7 @@ type ClientInterface interface { // ImportDataWithBody Write an export, or a batch of changes, into this deployment // - // Takes what `exportData` produced, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. + // Takes what `exportData` produced, one JSON object per line of at most 64 MiB, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. // An export's rows are written as the source had them, so an export is refused with 409 `conflict`, before any of its rows is written, for an app that already has a row here in a table of the shared database: it would undo what was done here since. `full=true` writes it over them anyway, and importing the same export twice that way leaves what importing it once would. Changes are applied whatever the app holds. An import that stopped partway is run again with `full=true`, since the app then holds its first rows. // Server-side only, and refused when the router runs with ROUTER_AUTH_MODE=noauth. // @@ -21224,6 +21225,7 @@ func (c *Client) ListDataChanges(ctx context.Context, params *ListDataChangesPar // One line per row, `{"table": ..., "row": {...}}`, and a last line `{"cursor": ..., "customer": ..., "at": ...}`. The cursor comes last because it is also what says the export finished: a stream that broke halfway has no cursor line, so half a copy cannot be mistaken for a whole one. The rows are read at one moment rather than stitched together, and exporting starts recording changes so that `listDataChanges` carries on from exactly where this left off. // Only the calling app's rows are here, and credentials are not: an API key secret, an OAuth access token and an OAuth refresh token stay with the deployment that holds them, so an imported plugin connection has to be authorized again. The audio behind a voice sample and a call recording lives in an object bucket rather than in this database; the rows naming those objects are here, and copying the bucket is yours to do. // A router with shards cannot be the source of a move and answers 400 `not_configured`. +// An app runs one export at a time, and an export ends after an hour, or when one line has taken a minute to write: an export with no cursor line is one to run again. // Server-side only, and refused entirely when the router runs with ROUTER_AUTH_MODE=noauth, where naming a customer is all it takes to be one. // // Corresponds with GET /v1/data/export (the `ExportData` operationId). @@ -21241,7 +21243,7 @@ func (c *Client) ExportData(ctx context.Context, reqEditors ...RequestEditorFn) // ImportDataWithBody Write an export, or a batch of changes, into this deployment // -// Takes what `exportData` produced, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. +// Takes what `exportData` produced, one JSON object per line of at most 64 MiB, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. // An export's rows are written as the source had them, so an export is refused with 409 `conflict`, before any of its rows is written, for an app that already has a row here in a table of the shared database: it would undo what was done here since. `full=true` writes it over them anyway, and importing the same export twice that way leaves what importing it once would. Changes are applied whatever the app holds. An import that stopped partway is run again with `full=true`, since the app then holds its first rows. // Server-side only, and refused when the router runs with ROUTER_AUTH_MODE=noauth. // @@ -38775,6 +38777,7 @@ type ClientWithResponsesInterface interface { // One line per row, `{"table": ..., "row": {...}}`, and a last line `{"cursor": ..., "customer": ..., "at": ...}`. The cursor comes last because it is also what says the export finished: a stream that broke halfway has no cursor line, so half a copy cannot be mistaken for a whole one. The rows are read at one moment rather than stitched together, and exporting starts recording changes so that `listDataChanges` carries on from exactly where this left off. // Only the calling app's rows are here, and credentials are not: an API key secret, an OAuth access token and an OAuth refresh token stay with the deployment that holds them, so an imported plugin connection has to be authorized again. The audio behind a voice sample and a call recording lives in an object bucket rather than in this database; the rows naming those objects are here, and copying the bucket is yours to do. // A router with shards cannot be the source of a move and answers 400 `not_configured`. + // An app runs one export at a time, and an export ends after an hour, or when one line has taken a minute to write: an export with no cursor line is one to run again. // Server-side only, and refused entirely when the router runs with ROUTER_AUTH_MODE=noauth, where naming a customer is all it takes to be one. // // Returns a wrapper object for the known response body format(s). @@ -38784,7 +38787,7 @@ type ClientWithResponsesInterface interface { // ImportDataWithBodyWithResponse Write an export, or a batch of changes, into this deployment // - // Takes what `exportData` produced, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. + // Takes what `exportData` produced, one JSON object per line of at most 64 MiB, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. // An export's rows are written as the source had them, so an export is refused with 409 `conflict`, before any of its rows is written, for an app that already has a row here in a table of the shared database: it would undo what was done here since. `full=true` writes it over them anyway, and importing the same export twice that way leaves what importing it once would. Changes are applied whatever the app holds. An import that stopped partway is run again with `full=true`, since the app then holds its first rows. // Server-side only, and refused when the router runs with ROUTER_AUTH_MODE=noauth. // @@ -58559,6 +58562,8 @@ type ExportDataResponse struct { JSON402 *PaymentRequired // JSON403 the response for an HTTP 403 `application/json` response JSON403 *Forbidden + // JSON409 the response for an HTTP 409 `application/json` response + JSON409 *ErrorResponse // JSON500 the response for an HTTP 500 `application/json` response JSON500 *InternalError // JSON503 the response for an HTTP 503 `application/json` response @@ -58589,6 +58594,11 @@ func (r ExportDataResponse) GetJSON403() *Forbidden { return r.JSON403 } +// GetJSON409 returns the response for an HTTP 409 `application/json` response +func (r ExportDataResponse) GetJSON409() *ErrorResponse { + return r.JSON409 +} + // GetJSON500 returns the response for an HTTP 500 `application/json` response func (r ExportDataResponse) GetJSON500() *InternalError { return r.JSON500 @@ -58657,6 +58667,8 @@ type ImportDataResponse struct { JSON403 *Forbidden // JSON409 the response for an HTTP 409 `application/json` response JSON409 *ErrorResponse + // JSON413 the response for an HTTP 413 `application/json` response + JSON413 *ErrorResponse // JSON500 the response for an HTTP 500 `application/json` response JSON500 *InternalError // JSON503 the response for an HTTP 503 `application/json` response @@ -58697,6 +58709,11 @@ func (r ImportDataResponse) GetJSON409() *ErrorResponse { return r.JSON409 } +// GetJSON413 returns the response for an HTTP 413 `application/json` response +func (r ImportDataResponse) GetJSON413() *ErrorResponse { + return r.JSON413 +} + // GetJSON500 returns the response for an HTTP 500 `application/json` response func (r ImportDataResponse) GetJSON500() *InternalError { return r.JSON500 @@ -71218,6 +71235,7 @@ func (c *ClientWithResponses) ListDataChangesWithResponse(ctx context.Context, p // One line per row, `{"table": ..., "row": {...}}`, and a last line `{"cursor": ..., "customer": ..., "at": ...}`. The cursor comes last because it is also what says the export finished: a stream that broke halfway has no cursor line, so half a copy cannot be mistaken for a whole one. The rows are read at one moment rather than stitched together, and exporting starts recording changes so that `listDataChanges` carries on from exactly where this left off. // Only the calling app's rows are here, and credentials are not: an API key secret, an OAuth access token and an OAuth refresh token stay with the deployment that holds them, so an imported plugin connection has to be authorized again. The audio behind a voice sample and a call recording lives in an object bucket rather than in this database; the rows naming those objects are here, and copying the bucket is yours to do. // A router with shards cannot be the source of a move and answers 400 `not_configured`. +// An app runs one export at a time, and an export ends after an hour, or when one line has taken a minute to write: an export with no cursor line is one to run again. // Server-side only, and refused entirely when the router runs with ROUTER_AUTH_MODE=noauth, where naming a customer is all it takes to be one. // // Returns a wrapper object for the known response body format(s). @@ -71233,7 +71251,7 @@ func (c *ClientWithResponses) ExportDataWithResponse(ctx context.Context, reqEdi // ImportDataWithBodyWithResponse Write an export, or a batch of changes, into this deployment // -// Takes what `exportData` produced, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. +// Takes what `exportData` produced, one JSON object per line of at most 64 MiB, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. // An export's rows are written as the source had them, so an export is refused with 409 `conflict`, before any of its rows is written, for an app that already has a row here in a table of the shared database: it would undo what was done here since. `full=true` writes it over them anyway, and importing the same export twice that way leaves what importing it once would. Changes are applied whatever the app holds. An import that stopped partway is run again with `full=true`, since the app then holds its first rows. // Server-side only, and refused when the router runs with ROUTER_AUTH_MODE=noauth. // @@ -94831,6 +94849,13 @@ func ParseExportDataResponse(rsp *http.Response) (*ExportDataResponse, error) { } response.JSON403 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON409 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -94957,6 +94982,13 @@ func ParseImportDataResponse(rsp *http.Response) (*ImportDataResponse, error) { } response.JSON409 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 413: + var dest ErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON413 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest InternalError if err := json.Unmarshal(bodyBytes, &dest); err != nil { diff --git a/sdks/js/src/generated/api.ts b/sdks/js/src/generated/api.ts index 1407d33fd3..0c8f58cec2 100644 --- a/sdks/js/src/generated/api.ts +++ b/sdks/js/src/generated/api.ts @@ -3197,6 +3197,7 @@ export type paths = { * @description One line per row, `{"table": ..., "row": {...}}`, and a last line `{"cursor": ..., "customer": ..., "at": ...}`. The cursor comes last because it is also what says the export finished: a stream that broke halfway has no cursor line, so half a copy cannot be mistaken for a whole one. The rows are read at one moment rather than stitched together, and exporting starts recording changes so that `listDataChanges` carries on from exactly where this left off. * Only the calling app's rows are here, and credentials are not: an API key secret, an OAuth access token and an OAuth refresh token stay with the deployment that holds them, so an imported plugin connection has to be authorized again. The audio behind a voice sample and a call recording lives in an object bucket rather than in this database; the rows naming those objects are here, and copying the bucket is yours to do. * A router with shards cannot be the source of a move and answers 400 `not_configured`. + * An app runs one export at a time, and an export ends after an hour, or when one line has taken a minute to write: an export with no cursor line is one to run again. * Server-side only, and refused entirely when the router runs with ROUTER_AUTH_MODE=noauth, where naming a customer is all it takes to be one. */ readonly get: operations["exportData"]; @@ -3219,7 +3220,7 @@ export type paths = { readonly put?: never; /** * Write an export, or a batch of changes, into this deployment - * @description Takes what `exportData` produced, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. + * @description Takes what `exportData` produced, one JSON object per line of at most 64 MiB, and the same lines with a `change` in place of a `row` for what `listDataChanges` returned. Every row is written under the calling app whatever the file says, so an export from one app cannot be imported into another's rows, and rows belonging to a customer through a parent are only written where that parent is the caller's. * An export's rows are written as the source had them, so an export is refused with 409 `conflict`, before any of its rows is written, for an app that already has a row here in a table of the shared database: it would undo what was done here since. `full=true` writes it over them anyway, and importing the same export twice that way leaves what importing it once would. Changes are applied whatever the app holds. An import that stopped partway is run again with `full=true`, since the app then holds its first rows. * Server-side only, and refused when the router runs with ROUTER_AUTH_MODE=noauth. */ @@ -19465,8 +19466,17 @@ export interface operations { readonly 401: components["responses"]["Unauthorized"]; readonly 402: components["responses"]["PaymentRequired"]; readonly 403: components["responses"]["Forbidden"]; + /** @description An export of this app is already running on this router: one runs at a time. */ + readonly 409: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["ErrorResponse"]; + }; + }; readonly 500: components["responses"]["InternalError"]; - /** @description This deployment has no database to export from, or cannot record changes; or a write that was open when the export started is still open after 30 seconds: try again. */ + /** @description This deployment has no database to export from, or cannot record changes; or this router is running as many exports as it takes at once; or a write that was open when the export started is still open after 30 seconds: try again. */ readonly 503: { headers: { readonly [name: string]: unknown; @@ -19519,6 +19529,15 @@ export interface operations { readonly "application/json": components["schemas"]["ErrorResponse"]; }; }; + /** @description A line of the file is over 64 MiB. */ + readonly 413: { + headers: { + readonly [name: string]: unknown; + }; + content: { + readonly "application/json": components["schemas"]["ErrorResponse"]; + }; + }; readonly 500: components["responses"]["InternalError"]; /** @description This deployment has no database to import into. */ readonly 503: {