Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions acceleration/api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -22066,19 +22067,25 @@ 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":
content:
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
Expand Down Expand Up @@ -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":
Expand Down
96 changes: 86 additions & 10 deletions acceleration/internal/api/datamove.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package api

import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"io"
"fmt"
"net/http"
"strconv"
"time"
Expand All @@ -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")
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Comment thread
thesyncim marked this conversation as resolved.
Resolved
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 {
Comment thread
thesyncim marked this conversation as resolved.
Resolved
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
}
Expand All @@ -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
}
Expand Down Expand Up @@ -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)
Comment thread
thesyncim marked this conversation as resolved.
Resolved
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()))
Comment thread
thesyncim marked this conversation as resolved.
Resolved
return
}
Expand Down Expand Up @@ -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})
Expand Down
Loading
Loading