Files
CollabTable/backend/sync.go
T

314 lines
9.4 KiB
Go
Raw Normal View History

package main
import (
2026-10-19 07:48:07 +00:00
"context"
"fmt"
"net/http"
"time"
"github.com/jackc/pgx/v5"
)
// maxConcurrentSyncs caps sync requests in flight. It stays below the pool size
// (DATABASE_MAX_CONNS defaults to 20), so syncs cannot hold every connection.
const maxConcurrentSyncs = 4
func syncMaxFutureSkew() int64 {
value := envInt64("SYNC_MAX_FUTURE_SKEW_MS", 0)
if value < 0 {
return 0
}
return value
}
func normalizeTimestamp(raw, fallback, now int64) int64 {
if raw <= 0 {
return fallback
}
ts := raw
if ts < 1_000_000_000_000 {
ts *= 1000
}
maxAllowed := now + syncMaxFutureSkew()
if ts > maxAllowed {
return maxAllowed
}
return ts
}
func normalizeEntityTimestamps(createdAt, updatedAt, now int64) (int64, int64) {
created := normalizeTimestamp(createdAt, now, now)
updated := normalizeTimestamp(updatedAt, created, now)
if updated < created {
updated = created
}
return created, updated
}
2026-10-19 07:48:07 +00:00
// valueReferences returns the list ID of each field and the existence of each
// item that the values refer to, using one statement per table.
func valueReferences(ctx context.Context, tx pgx.Tx, values []ItemValue) (map[string]string, map[string]bool, error) {
fieldLists := make(map[string]string)
existingItems := make(map[string]bool)
if len(values) == 0 {
return fieldLists, existingItems, nil
}
fieldIDs := make([]string, 0, len(values))
itemIDs := make([]string, 0, len(values))
for _, value := range values {
fieldIDs = append(fieldIDs, value.FieldID)
itemIDs = append(itemIDs, value.ItemID)
}
fieldRows, err := tx.Query(ctx, `SELECT id, listid FROM fields WHERE id = ANY($1)`, fieldIDs)
if err != nil {
return nil, nil, err
}
defer fieldRows.Close()
for fieldRows.Next() {
var fieldID, listID string
if err := fieldRows.Scan(&fieldID, &listID); err != nil {
return nil, nil, err
}
fieldLists[fieldID] = listID
}
if err := fieldRows.Err(); err != nil {
return nil, nil, err
}
itemRows, err := tx.Query(ctx, `SELECT id FROM items WHERE id = ANY($1)`, itemIDs)
if err != nil {
return nil, nil, err
}
defer itemRows.Close()
for itemRows.Next() {
var itemID string
if err := itemRows.Scan(&itemID); err != nil {
return nil, nil, err
}
existingItems[itemID] = true
}
if err := itemRows.Err(); err != nil {
return nil, nil, err
}
return fieldLists, existingItems, nil
}
// changeEventType names a synced change for the notification feed: a tombstone
// is "deleted", a first sync reports "created", and anything else "updated".
func changeEventType(initialSync, deleted bool) string {
if deleted {
return "deleted"
}
if initialSync {
return "created"
}
return "updated"
}
// syncBatch holds what every row of one sync request shares.
type syncBatch struct {
now int64
initialSync bool
deviceID string
}
func (b syncBatch) notify(ctx context.Context, tx pgx.Tx, eventType, entityType, entityID, listID string, createdAt int64) {
ignoreNotificationError(enqueueNotificationInTx(ctx, tx, b.deviceID, eventType, entityType, entityID, listID, createdAt))
}
// applyLists upserts the pushed lists. A write older than the stored row
// changes nothing, so it triggers no cascade or notification.
func applyLists(ctx context.Context, tx pgx.Tx, lists []List, batch syncBatch) error {
for _, list := range lists {
createdAt, updatedAt := normalizeEntityTimestamps(int64(list.CreatedAt), int64(list.UpdatedAt), batch.now)
applied, err := upsertList(ctx, tx, list, createdAt, updatedAt)
if err != nil {
return err
}
if !applied {
continue
}
batch.notify(ctx, tx, changeEventType(batch.initialSync, list.IsDeleted), "list", list.ID, list.ID, updatedAt)
if list.IsDeleted {
if err := cascadeDeleteList(ctx, tx, list.ID, updatedAt); err != nil {
return err
}
}
}
return nil
}
func applyFields(ctx context.Context, tx pgx.Tx, fields []Field, batch syncBatch) error {
for _, field := range fields {
createdAt, updatedAt := normalizeEntityTimestamps(int64(field.CreatedAt), int64(field.UpdatedAt), batch.now)
applied, err := upsertField(ctx, tx, field, createdAt, updatedAt)
if err != nil {
return err
}
if !applied {
continue
}
batch.notify(ctx, tx, changeEventType(batch.initialSync, field.IsDeleted), "field", field.ID, field.ListID, updatedAt)
if field.IsDeleted {
if _, err := cascadeDeleteField(ctx, tx, field.ID, field.ListID, updatedAt); err != nil {
return err
}
}
}
return nil
}
func applyItems(ctx context.Context, tx pgx.Tx, items []Item, batch syncBatch) error {
for _, item := range items {
createdAt, updatedAt := normalizeEntityTimestamps(int64(item.CreatedAt), int64(item.UpdatedAt), batch.now)
applied, err := upsertItem(ctx, tx, item, createdAt, updatedAt)
if err != nil {
return err
}
if !applied {
continue
}
batch.notify(ctx, tx, changeEventType(batch.initialSync, item.IsDeleted), "item", item.ID, item.ListID, updatedAt)
if item.IsDeleted {
if err := cascadeDeleteItem(ctx, tx, item.ID); err != nil {
return err
}
}
}
return nil
}
// applyValues upserts the pushed item values and returns the ones it could not
// place. Items are read after applyItems has run, so a request's own item inserts
// are visible.
func applyValues(ctx context.Context, tx pgx.Tx, values []ItemValue, batch syncBatch) ([]OrphanValue, error) {
orphans := make([]OrphanValue, 0)
// Resolve the fields and items the values refer to once per request, not once
// per value.
fieldLists, existingItems, err := valueReferences(ctx, tx, values)
if err != nil {
return nil, err
}
for _, value := range values {
updatedAt := normalizeTimestamp(int64(value.UpdatedAt), batch.now, batch.now)
listID, ok := fieldLists[value.FieldID]
if !ok {
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "missingField"})
continue
}
if !existingItems[value.ItemID] {
if _, err := tx.Exec(ctx, `
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
VALUES ($1, $2, $3, $3, 0)
ON CONFLICT (id) DO NOTHING
`, value.ItemID, listID, updatedAt); err != nil {
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "failedCreateStubItem"})
continue
}
existingItems[value.ItemID] = true
}
applied, err := upsertValue(ctx, tx, value, updatedAt)
if err != nil {
return nil, err
}
if !applied {
continue
}
batch.notify(ctx, tx, "listContentUpdated", "value", value.ID, listID, updatedAt)
}
return orphans, nil
}
// applySyncRequest writes everything a device pushed, parents before children.
func applySyncRequest(ctx context.Context, tx pgx.Tx, request SyncRequest, batch syncBatch) ([]OrphanValue, error) {
if err := applyLists(ctx, tx, request.Lists, batch); err != nil {
return nil, err
}
if err := applyFields(ctx, tx, request.Fields, batch); err != nil {
return nil, err
}
if err := applyItems(ctx, tx, request.Items, batch); err != nil {
return nil, err
}
return applyValues(ctx, tx, request.ItemValues, batch)
}
// changesSince reads what a device has to pull: everything when since is nil,
// otherwise the rows updated at or after it. The caller adds the orphan list and
// the server timestamp.
func (d *DB) changesSince(ctx context.Context, since *int64) (SyncResponse, error) {
lists, err := d.queryLists(ctx, true, since)
if err != nil {
return SyncResponse{}, err
}
fields, err := d.queryFields(ctx, true, since, "")
if err != nil {
return SyncResponse{}, err
}
items, err := d.queryItems(ctx, true, since, "")
if err != nil {
return SyncResponse{}, err
}
values, err := d.queryValues(ctx, since, "")
if err != nil {
return SyncResponse{}, err
}
return SyncResponse{Lists: lists, Fields: fields, Items: items, ItemValues: values}, nil
}
func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
// Bound the number of syncs in flight, so large bodies and transactions cannot
// take every database connection at once.
select {
case s.syncSlots <- struct{}{}:
defer func() { <-s.syncSlots }()
case <-r.Context().Done():
writeJSONError(w, http.StatusServiceUnavailable, "Sync busy")
return
}
var request SyncRequest
if err := decodeJSONLimit(w, r, &request, syncBodyLimit); err != nil {
writeDecodeError(w, err, "Invalid sync request")
return
}
now := time.Now().UnixMilli()
lastSync := normalizeTimestamp(int64(request.LastSyncTimestamp), 0, now)
batch := syncBatch{now: now, initialSync: lastSync == 0, deviceID: requestDeviceID(r, request.DeviceID)}
orphans := make([]OrphanValue, 0)
incoming := len(request.Lists) + len(request.Fields) + len(request.Items) + len(request.ItemValues)
if incoming > 0 {
fmt.Printf("[SYNC] Received lists=%d fields=%d items=%d values=%d\n", len(request.Lists), len(request.Fields), len(request.Items), len(request.ItemValues))
}
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
var err error
orphans, err = applySyncRequest(r.Context(), tx, request, batch)
return err
})
if err != nil {
fmt.Printf("[SYNC] Failed: %v\n", err)
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
return
}
var since *int64
if lastSync != 0 {
since = &lastSync
}
response, err := s.db.changesSince(r.Context(), since)
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
return
}
response.OrphanItemValues = orphans
response.ServerTimestamp = time.Now().UnixMilli()
writeJSON(w, http.StatusOK, response)
}