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
5 changes: 4 additions & 1 deletion acceleration/cmd/router/replicate.go
Original file line number Diff line number Diff line change
Expand Up @@ -345,8 +345,11 @@ func follow(ctx context.Context, source *deployment, pgStore *store.Store, reser
if err := pgStore.ApplyChanges(ctx, customerID, page.Changes); err != nil {
return err
}
logger.Info("caught up on changes", "changes", len(page.Changes), "cursor", page.Cursor)
}
// A page can move the cursor with no change on it: past changes the source leaves out.
if page.Cursor > cursor {
cursor = page.Cursor
logger.Info("caught up on changes", "changes", len(page.Changes), "cursor", cursor)
}
// Saved after every read rather than only one that brought changes: a read is what keeps
// the source recording the app's changes (carryOn).
Expand Down
18 changes: 18 additions & 0 deletions acceleration/cmd/router/replicate_repeat_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,24 @@ func (s *ReplicateRepeatSuite) TestARunThatBringsNoChangesStillSavesWhenItReadTh
s.WithinDuration(time.Now(), s.saved().ReadAt, time.Minute, "the read kept the source recording, so the next run is not refused")
}

// The source leaves an organization's policy under the app's id out of the changes, and the
// cursor it answers past it is where the next run starts.
func (s *ReplicateRepeatSuite) TestARunWhosePageCarriesNoChangeStillMovesItsCursor() {
s.recorded(1)
s.Require().NoError(s.once("acme", false))
_, err := s.source.GlobalDB().ExecContext(s.ctx,
"INSERT INTO policies (scope, scope_id, updated_at) VALUES ('organization', 'acme', now())")
s.Require().NoError(err)
var last int64
s.Require().NoError(s.source.GlobalDB().QueryRowContext(s.ctx,
"SELECT max(seq) FROM data_changes WHERE customer_id = 'acme'").Scan(&last))

s.Require().NoError(s.once("acme", false))

s.Require().NotNil(s.saved().Cursor)
s.Equal(last, *s.saved().Cursor)
}

func (s *ReplicateRepeatSuite) TestAnOrganizationsPolicyUnderTheAppsIDIsNotTheAppsData() {
// The export carries only app policies, so an organization's under the same id is not a copy.
_, err := s.target.GlobalDB().ExecContext(s.ctx,
Expand Down
145 changes: 136 additions & 9 deletions acceleration/internal/store/datamove.go
Original file line number Diff line number Diff line change
Expand Up @@ -721,7 +721,12 @@ func (t dataTable) selectRows(customerID string, secrets []string) (string, []an
// is what lets a move be resumed after it was interrupted.
func (s *Store) ImportRow(ctx context.Context, customerID, table string, row json.RawMessage) error {
spec, _ := dataTableByName(table)
return s.importRow(ctx, s.sideOf(spec), customerID, table, row)
var stale []string
if err := s.importRow(ctx, s.sideOf(spec), customerID, table, row, &stale); err != nil {
return err
}
s.forget(ctx, stale...)
return nil
}

// sideOf is the database a table's rows are written to here: this shard's or the shared one.
Expand All @@ -738,7 +743,9 @@ func (s *Store) sideOf(table dataTable) *bun.DB {
var lineColumns = []string{"stream_trunk_id", "stream_route_id", "stream_app_pk", "stream_call_id", "stream_call_type",
"attached_at", "config_id"}

func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table string, row json.RawMessage) error {
// importRow writes one row of an export or of a change (ImportRow). It adds to stale the cached
// values the row was and is read through, for the caller to forget once the write has committed.
func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table string, row json.RawMessage, stale *[]string) error {
if slices.Contains(retiredTables, table) {
return nil
}
Expand Down Expand Up @@ -925,10 +932,22 @@ func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table str
"%sINSERT INTO %s (%s) SELECT %s FROM %sjsonb_populate_record(NULL::%s, %s) AS r%s ON CONFLICT %s %s",
locked, spec.name, quoted, selected, through, spec.name, subject, where, spec.conflictTarget(shape), conflict)

// A row renamed, or a skill moved to another config, is cached under what it was too.
var was []byte
if cachedByID(table) {
Comment thread
thesyncim marked this conversation as resolved.
Resolved
err := db.QueryRowContext(ctx, fmt.Sprintf("SELECT to_jsonb(h) FROM %s AS h WHERE h.id::text = ?::jsonb ->> 'id' AND h.customer_id = ?",
spec.name), string(row), customerID).Scan(&was)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return fmt.Errorf("store: import %s: %w", table, err)
}
}

result, err := db.ExecContext(ctx, query, args...)
if err != nil {
return fmt.Errorf("store: import %s: %w", table, err)
}
*stale = append(*stale, cachedKeys(customerID, table, was)...)
*stale = append(*stale, cachedKeys(customerID, table, row)...)
written, err := result.RowsAffected()
if err != nil {
return stack.Wrap(fmt.Errorf("store: import %s: %w", table, err))
Expand Down Expand Up @@ -967,6 +986,48 @@ func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table str
// ErrAnotherCustomersRow refuses an imported row whose key a row of another customer holds here.
var ErrAnotherCustomersRow = errors.New("a row with this key belongs to another customer here")

// cachedByID is whether a moved table's rows are cached by their id and something else they
// hold, which a write can change.
func cachedByID(table string) bool {
return slices.Contains([]string{"agent_configs", "router_configs", "skills", "voices"}, table)
}

// cachedKeys are the cached values a row of a moved table, as row reads under customerID, is read
// through: what the table's own writes forget (AgentConfigs.Update and its siblings). An app's
// policy is cached by its app alone, so any row of it names the same values.
func cachedKeys(customerID, table string, row []byte) []string {
if table == "policies" {
return policyKeys(ScopeApp, customerID)
}
if !cachedByID(table) || len(row) == 0 {
return nil
}
// The columns are text, which jsonb_populate_record also fills from a number, so a value is
// read as the text it is written as. A row that is not a JSON object was refused before it
// was written.
var fields map[string]any
decoder := json.NewDecoder(bytes.NewReader(row))
decoder.UseNumber()
if decoder.Decode(&fields) != nil {
return nil
}
text := func(column string) string {
if value, found := fields[column]; found && value != nil {
return fmt.Sprint(value)
}
return ""
}
switch table {
case "agent_configs":
return []string{agentConfigKey(customerID, text("id")), agentConfigNameKey(customerID, text("name"))}
case "router_configs":
return []string{routerConfigKey(customerID, text("id")), routerConfigNameKey(customerID, text("name"))}
case "voices":
return []string{voiceKey(customerID, text("id")), voiceNameKey(customerID, text("name"))}
}
return []string{skillsKey(customerID, text("config_id"))}
}

// validated is a model that refuses a row the API would not store.
type validated interface{ Validate() error }

Expand Down Expand Up @@ -1734,10 +1795,13 @@ func (s *Store) Changes(ctx context.Context, customerID string, after int64, lim
return nil, 0, ErrChangesExpired
}

// A policy is recorded under its scope id whatever its scope, so an organization's sharing the
// customer's id is left out, as an export leaves it out. It is left out before the limit, so a
// page is as full as the customer's own changes make it.
rows, err := tx.QueryContext(ctx, `
SELECT seq, table_name, op, key, payload, at
FROM data_changes
WHERE customer_id = ? AND seq > ? AND seq <= ?
WHERE customer_id = ? AND seq > ? AND seq <= ? AND (table_name <> 'policies' OR key ->> 'scope' = 'app')
Comment thread
thesyncim marked this conversation as resolved.
Resolved
ORDER BY seq
LIMIT ?`, customerID, after, mark, limit)
if err != nil {
Expand Down Expand Up @@ -1765,6 +1829,15 @@ LIMIT ?`, customerID, after, mark, limit)
if err := rows.Err(); err != nil {
return nil, 0, fmt.Errorf("store: changes: %w", err)
}
// A page that is not full holds every change of theirs up to the mark, so the cursor moves past
// the ones left out too: one left ahead of it would be pruned in time and expire the cursor.
if len(changes) < limit {
if err := tx.QueryRowContext(ctx,
"SELECT COALESCE(MAX(seq), ?) FROM data_changes WHERE customer_id = ? AND seq > ? AND seq <= ?",
Comment thread
thesyncim marked this conversation as resolved.
Resolved
cursor, customerID, cursor, mark).Scan(&cursor); err != nil {
return nil, 0, fmt.Errorf("store: changes: %w", err)
}
}
return changes, cursor, nil
}

Expand Down Expand Up @@ -1796,26 +1869,49 @@ func (s *Store) applyChanges(ctx context.Context, db *bun.DB, customerID string,
if len(changes) == 0 {
return nil
}
return db.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error {
var stale []string
err := db.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error {
for _, change := range changes {
if !appPolicy(change) {
continue
}
switch change.Op {
case ChangeDelete:
if err := s.deleteRow(ctx, tx, customerID, change); err != nil {
if err := s.deleteRow(ctx, tx, customerID, change, &stale); err != nil {
return err
}
default:
if err := s.importRow(ctx, tx, customerID, change.Table, change.Payload); err != nil {
if err := s.importRow(ctx, tx, customerID, change.Table, change.Payload, &stale); err != nil {
return err
}
}
}
return nil
})
if err != nil {
return err
}
s.forget(ctx, stale...)
return nil
}

// appPolicy is false for a change to a policy of another scope than an app's. The trigger records
// a policy under its scope id whatever its scope, so an organization's that shares an id with the
// app is recorded under the app, and replaying it would write it over the app's (identity).
func appPolicy(change DataChange) bool {
if change.Table != "policies" {
return true
}
var key struct {
Scope string `json:"scope"`
}
return json.Unmarshal(change.Key, &key) == nil && key.Scope == string(ScopeApp)
}

// deleteRow removes what a delete change names, scoped to the customer replaying it so a
// change carrying somebody else's key cannot reach their row.
func (s *Store) deleteRow(ctx context.Context, db bun.IDB, customerID string, change DataChange) error {
// change carrying somebody else's key cannot reach their row. It adds to stale the cached values
// the row was read through.
func (s *Store) deleteRow(ctx context.Context, db bun.IDB, customerID string, change DataChange, stale *[]string) error {
if slices.Contains(retiredTables, change.Table) {
return nil
}
Expand Down Expand Up @@ -1845,6 +1941,11 @@ func (s *Store) deleteRow(ctx context.Context, db bun.IDB, customerID string, ch
args = append(args, string(change.Key))
} else {
for _, column := range shape.keys {
// The customer in the key is the source's, which a move under another id does not
// keep: the customer's own condition below is what scopes the delete.
if column == spec.customer {
continue
}
conditions = append(conditions, fmt.Sprintf("t.%s::text = (?::jsonb ->> '%s')", column, column))
args = append(args, string(change.Key))
}
Expand All @@ -1865,7 +1966,33 @@ func (s *Store) deleteRow(ctx context.Context, db bun.IDB, customerID string, ch
args = append(args, customerID)

query := fmt.Sprintf("DELETE FROM %s AS t WHERE %s", spec.name, strings.Join(conditions, " AND "))
if _, err := db.ExecContext(ctx, query, args...); err != nil {
if !cachedByID(change.Table) {
result, err := db.ExecContext(ctx, query, args...)
if err != nil {
return fmt.Errorf("store: delete %s: %w", change.Table, err)
}
deleted, err := result.RowsAffected()
if err != nil {
return fmt.Errorf("store: delete %s: %w", change.Table, err)
}
if deleted > 0 {
*stale = append(*stale, cachedKeys(customerID, change.Table, nil)...)
}
return nil
}
rows, err := db.QueryContext(ctx, query+" RETURNING to_jsonb(t)", args...)
if err != nil {
return fmt.Errorf("store: delete %s: %w", change.Table, err)
}
defer rows.Close()
for rows.Next() {
var row []byte
if err := rows.Scan(&row); err != nil {
return fmt.Errorf("store: delete %s: %w", change.Table, err)
}
*stale = append(*stale, cachedKeys(customerID, change.Table, row)...)
}
if err := rows.Err(); err != nil {
return fmt.Errorf("store: delete %s: %w", change.Table, err)
}
return nil
Expand Down
Loading
Loading