feat(sync): paginate Android sync with change tokens
This commit is contained in:
1 parent
0ff94f9b10
commit
97c237be80
76 files changed
+3401
-851
No files matched your search
+25
-15
@@ -87,9 +87,11 @@ accounts can exist, with `user`/`admin`/`superadmin` roles managed via `/api/aut
|
||||
AuthGuard integration has three states: `AUTHGUARD_URL` set (used immediately); unset with
|
||||
`AUTH_DISABLED` unset/false (the default -- "pending": auth stays fully enabled/gated, waiting
|
||||
for ProjectConfigurator's push, failing closed on auth calls until then); or `AUTH_DISABLED=true`
|
||||
(authentication fully off -- no login screen, nothing gated). Only set `AUTH_DISABLED=true` for
|
||||
local development or a deployment you are certain does not need access control. API tokens are
|
||||
unrelated to AuthGuard (see below), hashed at rest, and shown only when generated.
|
||||
(the browser-session gate is off). List access still requires membership. In this mode requests
|
||||
use placeholder identity 0, which has no list memberships, so the dashboard data is empty and
|
||||
sync API tokens for identity 0 are rejected. Use it only for local development of the auth shell,
|
||||
not for a working data deployment. API tokens are unrelated to AuthGuard (see below), hashed at
|
||||
rest, and shown only when generated.
|
||||
|
||||
### Data
|
||||
|
||||
@@ -106,6 +108,14 @@ unrelated to AuthGuard (see below), hashed at rest, and shown only when generate
|
||||
- `POST /api/sync`
|
||||
- `GET /api/notifications/poll?since=<timestamp-ms>`
|
||||
|
||||
The list, field, item and item-value collection GETs accept `limit` (default 200, maximum 500)
|
||||
and an opaque `cursor`. They return `{ "items": [...], "nextCursor": "...", "hasMore": true }`;
|
||||
continue with `nextCursor` while `hasMore` is true. The final page has an empty `nextCursor`.
|
||||
`POST /api/sync` requires `lastSyncToken` (use `0` for the first sync) and returns at most 500
|
||||
changes with `nextSyncToken` and `hasMore`. Clients must request each page until `hasMore` is
|
||||
false. Older sync clients without `lastSyncToken` receive HTTP 400 and must be updated with the
|
||||
server.
|
||||
|
||||
### Dashboard and health
|
||||
|
||||
- `GET /health` is public.
|
||||
@@ -135,9 +145,9 @@ unrelated to AuthGuard (see below), hashed at rest, and shown only when generate
|
||||
CollabTable authenticates against, default unset (pending). Leaving it unset does not disable
|
||||
authentication -- it leaves the service "pending" until ProjectConfigurator pushes a URL,
|
||||
failing closed on auth calls until then. Use `AUTH_DISABLED` to actually turn auth off.
|
||||
- `AUTH_DISABLED` — set `true` to disable authentication entirely (no login screen, nothing
|
||||
gated, every request treated as authenticated), default `false`. For local development or a
|
||||
standalone deployment with no AuthGuard integration at all.
|
||||
- `AUTH_DISABLED` — set `true` to disable browser-session gates, default `false`. List access is
|
||||
still membership-scoped; placeholder identity 0 has no memberships and its sync tokens are
|
||||
rejected. Use only for local auth-shell development, not a working data deployment.
|
||||
- `DB_INIT_RETRY_INTERVAL_MS` — startup retry delay, default `5000`
|
||||
- `DB_INIT_RETRY_MAX_ATTEMPTS` — maximum startup attempts, `0` retries forever
|
||||
- `SYNC_MAX_FUTURE_SKEW_MS` — allowed client timestamp skew, default `0`
|
||||
@@ -169,17 +179,17 @@ attribute. `Strict-Transport-Security` is not set here; set it at the TLS proxy.
|
||||
|
||||
## Access model
|
||||
|
||||
There is one shared data set. Lists, fields, items and values have no owner and no per-list
|
||||
roles: any valid sync token can read, change and delete all of them, and any signed-in dashboard
|
||||
user can see all of them. Tokens are per account only so that each can be regenerated on its own.
|
||||
Deleting an item, field or list removes its values for good, while the rows themselves are soft
|
||||
deleted. Per-list access would need a membership table checked in every handler; that has not
|
||||
been decided.
|
||||
List, field, item and value reads and writes are scoped to `list_memberships`. On migration,
|
||||
every current API-token user is granted access to every existing list because the old schema did
|
||||
not store owners. Lists created afterward are owned only by their creator. There is currently no
|
||||
API for owners to add or remove members, so a newly created list is private to its creator's
|
||||
account and devices. Deleting an item, field or list still removes its values permanently, while
|
||||
the parent rows remain soft-deleted.
|
||||
|
||||
When login is off (`AUTH_DISABLED=true`, or the login-required switch turned off in
|
||||
ProjectConfigurator), the dashboard data and user management need no session. Sync tokens are a
|
||||
separate matter: a caller without a session can only mint a token for the placeholder identity,
|
||||
and the sync API refuses that identity.
|
||||
ProjectConfigurator), browser-session gates are bypassed. Data remains membership-scoped; the
|
||||
placeholder identity 0 has no memberships, so `/web/data` contains no lists. A caller without a
|
||||
session can only mint a token for that placeholder identity, and the sync API refuses it.
|
||||
|
||||
## License
|
||||
|
||||
|
||||
+14
-1
@@ -146,11 +146,24 @@ func requireAPIToken(db *DB) func(http.Handler) http.Handler {
|
||||
writeJSONError(w, http.StatusUnauthorized, "Invalid API token")
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
ctx := context.WithValue(r.Context(), apiUserIDContextKey{}, userID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type apiUserIDContextKey struct{}
|
||||
|
||||
func requestUserID(r *http.Request) int64 {
|
||||
if userID, ok := r.Context().Value(apiUserIDContextKey{}).(int64); ok {
|
||||
return userID
|
||||
}
|
||||
if user := sharedauth.UserFromContext(r.Context()); user != nil {
|
||||
return user.ID
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func extractBearer(r *http.Request) string {
|
||||
header := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(header, "Bearer ") {
|
||||
|
||||
+317
-83
@@ -65,15 +65,17 @@ func (d *DB) getList(ctx context.Context, id string) (List, error) {
|
||||
return scanList(d.pool.QueryRow(ctx, `SELECT `+listColumns+` FROM lists WHERE id = $1`, id))
|
||||
}
|
||||
|
||||
func (d *DB) queryLists(ctx context.Context, includeDeleted bool, since *int64) ([]List, error) {
|
||||
conditions := make([]string, 0, 2)
|
||||
args := make([]any, 0, 1)
|
||||
func (d *DB) queryLists(ctx context.Context, userID int64, includeDeleted bool, since *int64) ([]List, error) {
|
||||
conditions := make([]string, 0, 3)
|
||||
args := make([]any, 0, 2)
|
||||
args = append(args, userID)
|
||||
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = lists.id AND m.user_id = $%d)", len(args)))
|
||||
if !includeDeleted {
|
||||
conditions = append(conditions, "isdeleted = 0")
|
||||
}
|
||||
if since != nil {
|
||||
conditions = append(conditions, "updatedat >= $1")
|
||||
args = append(args, *since)
|
||||
conditions = append(conditions, fmt.Sprintf("updatedat >= $%d", len(args)))
|
||||
}
|
||||
query := `SELECT ` + listColumns + ` FROM lists`
|
||||
if len(conditions) > 0 {
|
||||
@@ -98,9 +100,11 @@ func (d *DB) queryLists(ctx context.Context, includeDeleted bool, since *int64)
|
||||
return lists, rows.Err()
|
||||
}
|
||||
|
||||
func (d *DB) queryFields(ctx context.Context, includeDeleted bool, since *int64, listID string) ([]Field, error) {
|
||||
conditions := make([]string, 0, 3)
|
||||
args := make([]any, 0, 2)
|
||||
func (d *DB) queryFields(ctx context.Context, userID int64, includeDeleted bool, since *int64, listID string) ([]Field, error) {
|
||||
conditions := make([]string, 0, 4)
|
||||
args := make([]any, 0, 3)
|
||||
args = append(args, userID)
|
||||
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = fields.listid AND m.user_id = $%d)", len(args)))
|
||||
if !includeDeleted {
|
||||
conditions = append(conditions, "isdeleted = 0")
|
||||
}
|
||||
@@ -134,9 +138,11 @@ func (d *DB) queryFields(ctx context.Context, includeDeleted bool, since *int64,
|
||||
return fields, rows.Err()
|
||||
}
|
||||
|
||||
func (d *DB) queryItems(ctx context.Context, includeDeleted bool, since *int64, listID string) ([]Item, error) {
|
||||
conditions := make([]string, 0, 3)
|
||||
args := make([]any, 0, 2)
|
||||
func (d *DB) queryItems(ctx context.Context, userID int64, includeDeleted bool, since *int64, listID string) ([]Item, error) {
|
||||
conditions := make([]string, 0, 4)
|
||||
args := make([]any, 0, 3)
|
||||
args = append(args, userID)
|
||||
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = items.listid AND m.user_id = $%d)", len(args)))
|
||||
if !includeDeleted {
|
||||
conditions = append(conditions, "isdeleted = 0")
|
||||
}
|
||||
@@ -170,9 +176,11 @@ func (d *DB) queryItems(ctx context.Context, includeDeleted bool, since *int64,
|
||||
return items, rows.Err()
|
||||
}
|
||||
|
||||
func (d *DB) queryValues(ctx context.Context, since *int64, itemID string) ([]ItemValue, error) {
|
||||
conditions := make([]string, 0, 2)
|
||||
args := make([]any, 0, 2)
|
||||
func (d *DB) queryValues(ctx context.Context, userID int64, since *int64, itemID string) ([]ItemValue, error) {
|
||||
conditions := make([]string, 0, 3)
|
||||
args := make([]any, 0, 3)
|
||||
args = append(args, userID)
|
||||
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM items i JOIN list_memberships m ON m.listid = i.listid WHERE i.id = item_values.itemid AND m.user_id = $%d)", len(args)))
|
||||
if since != nil {
|
||||
args = append(args, *since)
|
||||
conditions = append(conditions, fmt.Sprintf("updatedat >= $%d", len(args)))
|
||||
@@ -353,7 +361,11 @@ type listMutation struct {
|
||||
|
||||
func (s *Server) handleListCollection(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet {
|
||||
lists, err := s.db.queryLists(r.Context(), false, nil)
|
||||
page, ok := requestPage(w, r, "lists")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
lists, err := s.db.queryListPage(r.Context(), requestUserID(r), false, page)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch lists")
|
||||
return
|
||||
@@ -371,15 +383,34 @@ func (s *Server) handleListCollection(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSONError(w, http.StatusBadRequest, "List id and name are required")
|
||||
return
|
||||
}
|
||||
_, err := s.db.pool.Exec(r.Context(), `
|
||||
INSERT INTO lists (id, name, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`, request.ID, request.Name, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := authorizeList(r.Context(), tx, requestUserID(r), request.ID, true); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.Exec(r.Context(), `
|
||||
INSERT INTO lists (id, name, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`, request.ID, request.Name, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := addListOwner(r.Context(), tx, requestUserID(r), request.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "created", "list", request.ID, request.ID, time.Now().UnixMilli()))
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, errListAccessDenied) {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
return
|
||||
}
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create list")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "created", "list", request.ID, request.ID, time.Now().UnixMilli()))
|
||||
list, err := s.db.getList(r.Context(), request.ID)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create list")
|
||||
@@ -392,6 +423,9 @@ func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
if !s.requireListMembership(w, r, id) {
|
||||
return
|
||||
}
|
||||
list, err := s.db.getList(r.Context(), id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
@@ -416,17 +450,34 @@ func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE lists SET name = $1, updatedat = $2 WHERE id = $3`, request.Name, updatedAt, id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update list")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
var list List
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||
return err
|
||||
}
|
||||
member, err := hasListMembership(r.Context(), tx, requestUserID(r), id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !member {
|
||||
return errListAccessDenied
|
||||
}
|
||||
result, err := tx.Exec(r.Context(), `UPDATE lists SET name = $1, updatedat = $2 WHERE id = $3`, request.Name, updatedAt, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "updated", "list", id, id, updatedAt))
|
||||
var scanErr error
|
||||
list, scanErr = scanList(tx.QueryRow(r.Context(), `SELECT `+listColumns+` FROM lists WHERE id = $1`, id))
|
||||
return scanErr
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "updated", "list", id, id, updatedAt))
|
||||
list, err := s.db.getList(r.Context(), id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update list")
|
||||
return
|
||||
@@ -435,6 +486,16 @@ func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) {
|
||||
case http.MethodDelete:
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||
return err
|
||||
}
|
||||
member, err := hasListMembership(r.Context(), tx, requestUserID(r), id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !member {
|
||||
return errListAccessDenied
|
||||
}
|
||||
result, err := tx.Exec(r.Context(), `UPDATE lists SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -448,7 +509,7 @@ func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) {
|
||||
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, ""), "deleted", "list", id, id, updatedAt))
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
return
|
||||
}
|
||||
@@ -466,7 +527,15 @@ type fieldMutation struct {
|
||||
}
|
||||
|
||||
func (s *Server) handleFieldsForList(w http.ResponseWriter, r *http.Request) {
|
||||
fields, err := s.db.queryFields(r.Context(), false, nil, r.PathValue("listId"))
|
||||
listID := r.PathValue("listId")
|
||||
if !s.requireListMembership(w, r, listID) {
|
||||
return
|
||||
}
|
||||
page, ok := requestPage(w, r, "fields")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
fields, err := s.db.queryFieldsPage(r.Context(), requestUserID(r), false, listID, page)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch fields")
|
||||
return
|
||||
@@ -485,16 +554,36 @@ func (s *Server) handleFieldCollection(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
request.FieldType, request.Alignment = fieldDefaults(request.FieldType, request.Alignment)
|
||||
_, err := s.db.pool.Exec(r.Context(), `
|
||||
INSERT INTO fields
|
||||
(id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
`, request.ID, request.Name, request.FieldType, request.FieldOptions, request.Alignment, request.ListID, request.Order, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||
return err
|
||||
}
|
||||
member, err := hasListMembership(r.Context(), tx, requestUserID(r), request.ListID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !member {
|
||||
return errListAccessDenied
|
||||
}
|
||||
_, err = tx.Exec(r.Context(), `
|
||||
INSERT INTO fields
|
||||
(id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
`, request.ID, request.Name, request.FieldType, request.FieldOptions, request.Alignment, request.ListID, request.Order, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "created", "field", request.ID, request.ListID, time.Now().UnixMilli()))
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, errListAccessDenied) {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
return
|
||||
}
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create field")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "created", "field", request.ID, request.ListID, time.Now().UnixMilli()))
|
||||
field, err := s.getField(r.Context(), request.ID)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create field")
|
||||
@@ -525,25 +614,49 @@ func (s *Server) handleFieldItem(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
request.FieldType, request.Alignment = fieldDefaults(request.FieldType, request.Alignment)
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
result, err := s.db.pool.Exec(r.Context(), `
|
||||
UPDATE fields
|
||||
SET name = $1, fieldtype = $2, fieldoptions = $3, alignment = $4, "order" = $5, updatedat = $6
|
||||
WHERE id = $7
|
||||
`, request.Name, request.FieldType, request.FieldOptions, request.Alignment, request.Order, updatedAt, id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update field")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
var field Field
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||
return err
|
||||
}
|
||||
var listID string
|
||||
if err := tx.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, id).Scan(&listID); err != nil {
|
||||
return err
|
||||
}
|
||||
member, err := hasListMembership(r.Context(), tx, requestUserID(r), listID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !member {
|
||||
return errListAccessDenied
|
||||
}
|
||||
result, err := tx.Exec(r.Context(), `
|
||||
UPDATE fields
|
||||
SET name = $1, fieldtype = $2, fieldoptions = $3, alignment = $4, "order" = $5, updatedat = $6
|
||||
WHERE id = $7
|
||||
`, request.Name, request.FieldType, request.FieldOptions, request.Alignment, request.Order, updatedAt, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
var scanErr error
|
||||
field, scanErr = scanField(tx.QueryRow(r.Context(), `SELECT `+fieldColumns+` FROM fields WHERE id = $1`, id))
|
||||
if scanErr != nil {
|
||||
return scanErr
|
||||
}
|
||||
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "updated", "field", id, field.ListID, updatedAt))
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||
writeJSONError(w, http.StatusNotFound, "Field not found")
|
||||
return
|
||||
}
|
||||
field, err := s.getField(r.Context(), id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update field")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "updated", "field", id, field.ListID, updatedAt))
|
||||
writeJSON(w, http.StatusOK, field)
|
||||
case http.MethodDelete:
|
||||
var request struct {
|
||||
@@ -554,11 +667,21 @@ func (s *Server) handleFieldItem(w http.ResponseWriter, r *http.Request) {
|
||||
var field Field
|
||||
cascade := false
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
field, err = scanField(tx.QueryRow(r.Context(), `SELECT `+fieldColumns+` FROM fields WHERE id = $1`, id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
member, err := hasListMembership(r.Context(), tx, requestUserID(r), field.ListID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !member {
|
||||
return errListAccessDenied
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -569,7 +692,7 @@ func (s *Server) handleFieldItem(w http.ResponseWriter, r *http.Request) {
|
||||
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "field", id, field.ListID, updatedAt))
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||
writeJSONError(w, http.StatusNotFound, "Field not found")
|
||||
return
|
||||
}
|
||||
@@ -594,7 +717,14 @@ func (s *Server) handleItemsForList(w http.ResponseWriter, r *http.Request) {
|
||||
listID = parts[1]
|
||||
}
|
||||
}
|
||||
items, err := s.db.queryItems(r.Context(), false, nil, listID)
|
||||
if !s.requireListMembership(w, r, listID) {
|
||||
return
|
||||
}
|
||||
page, ok := requestPage(w, r, "items")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
items, err := s.db.queryItemsPage(r.Context(), requestUserID(r), false, listID, page)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch items")
|
||||
return
|
||||
@@ -612,15 +742,35 @@ func (s *Server) handleItemCollection(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSONError(w, http.StatusBadRequest, "Item id and listId are required")
|
||||
return
|
||||
}
|
||||
_, err := s.db.pool.Exec(r.Context(), `
|
||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`, request.ID, request.ListID, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||
return err
|
||||
}
|
||||
member, err := hasListMembership(r.Context(), tx, requestUserID(r), request.ListID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !member {
|
||||
return errListAccessDenied
|
||||
}
|
||||
_, err = tx.Exec(r.Context(), `
|
||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`, request.ID, request.ListID, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "created", "item", request.ID, request.ListID, time.Now().UnixMilli()))
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, errListAccessDenied) {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
return
|
||||
}
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create item")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "created", "item", request.ID, request.ListID, time.Now().UnixMilli()))
|
||||
item, err := s.getItem(r.Context(), request.ID)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create item")
|
||||
@@ -641,7 +791,23 @@ func (s *Server) handleValuesForItem(w http.ResponseWriter, r *http.Request) {
|
||||
itemID = parts[0]
|
||||
}
|
||||
}
|
||||
values, err := s.db.queryValues(r.Context(), nil, itemID)
|
||||
var listID string
|
||||
if err := s.db.pool.QueryRow(r.Context(), `SELECT listid FROM items WHERE id = $1`, itemID).Scan(&listID); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeJSONError(w, http.StatusNotFound, "Item not found")
|
||||
} else {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch item values")
|
||||
}
|
||||
return
|
||||
}
|
||||
if !s.requireListMembership(w, r, listID) {
|
||||
return
|
||||
}
|
||||
page, ok := requestPage(w, r, "values")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
values, err := s.db.queryValuesPage(r.Context(), requestUserID(r), itemID, page)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch item values")
|
||||
return
|
||||
@@ -662,27 +828,57 @@ func (s *Server) handleItemValueCollection(w http.ResponseWriter, r *http.Reques
|
||||
writeJSONError(w, http.StatusBadRequest, "Value id, itemId, and fieldId are required")
|
||||
return
|
||||
}
|
||||
applied, err := upsertValue(r.Context(), s.db.pool, request.ItemValue, int64(request.UpdatedAt))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to save item value")
|
||||
return
|
||||
}
|
||||
// An older write than the stored value changes nothing, so it notifies no one.
|
||||
var listID string
|
||||
if applied {
|
||||
if err := s.db.pool.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, request.FieldID).Scan(&listID); err == nil {
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "listContentUpdated", "value", request.ID, listID, time.Now().UnixMilli()))
|
||||
}
|
||||
}
|
||||
var value ItemValue
|
||||
err = s.db.pool.QueryRow(r.Context(), `SELECT `+valueColumns+` FROM item_values WHERE id = $1`, request.ID).Scan(
|
||||
&value.ID,
|
||||
&value.ItemID,
|
||||
&value.FieldID,
|
||||
&value.Value,
|
||||
&value.UpdatedAt,
|
||||
)
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||
return err
|
||||
}
|
||||
var fieldListID, itemListID string
|
||||
if err := tx.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, request.FieldID).Scan(&fieldListID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.QueryRow(r.Context(), `SELECT listid FROM items WHERE id = $1`, request.ItemID).Scan(&itemListID); err != nil {
|
||||
return err
|
||||
}
|
||||
if fieldListID != itemListID {
|
||||
return errCellIdentityMismatch
|
||||
}
|
||||
member, err := hasListMembership(r.Context(), tx, requestUserID(r), fieldListID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !member {
|
||||
return errListAccessDenied
|
||||
}
|
||||
var storedItemID, storedFieldID string
|
||||
storedErr := tx.QueryRow(r.Context(), `SELECT itemid, fieldid FROM item_values WHERE id = $1`, request.ID).Scan(&storedItemID, &storedFieldID)
|
||||
if storedErr == nil && (storedItemID != request.ItemID || storedFieldID != request.FieldID) {
|
||||
return errCellIdentityMismatch
|
||||
}
|
||||
if storedErr != nil && !errors.Is(storedErr, pgx.ErrNoRows) {
|
||||
return storedErr
|
||||
}
|
||||
applied, err := upsertValue(r.Context(), tx, request.ItemValue, int64(request.UpdatedAt))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// An older write than the stored value changes nothing, so it notifies no one.
|
||||
if applied {
|
||||
var listID string
|
||||
if err := tx.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, request.FieldID).Scan(&listID); err != nil {
|
||||
return err
|
||||
}
|
||||
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "listContentUpdated", "value", request.ID, listID, time.Now().UnixMilli()))
|
||||
}
|
||||
var scanErr error
|
||||
value, scanErr = scanItemValue(tx.QueryRow(r.Context(), `SELECT `+valueColumns+` FROM item_values WHERE id = $1`, request.ID))
|
||||
return scanErr
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, errListAccessDenied) || errors.Is(err, errCellIdentityMismatch) || errors.Is(err, pgx.ErrNoRows) {
|
||||
writeJSONError(w, http.StatusNotFound, "Item value not found")
|
||||
return
|
||||
}
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to save item value")
|
||||
return
|
||||
}
|
||||
@@ -702,25 +898,63 @@ func (s *Server) handleItem(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
if r.Method == http.MethodPut {
|
||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE items SET updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update item")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
var item Item
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||
return err
|
||||
}
|
||||
var listID string
|
||||
if err := tx.QueryRow(r.Context(), `SELECT listid FROM items WHERE id = $1`, id).Scan(&listID); err != nil {
|
||||
return err
|
||||
}
|
||||
member, err := hasListMembership(r.Context(), tx, requestUserID(r), listID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !member {
|
||||
return errListAccessDenied
|
||||
}
|
||||
result, err := tx.Exec(r.Context(), `UPDATE items SET updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
var scanErr error
|
||||
item, scanErr = scanItem(tx.QueryRow(r.Context(), `SELECT `+itemColumns+` FROM items WHERE id = $1`, id))
|
||||
if scanErr != nil {
|
||||
return scanErr
|
||||
}
|
||||
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "updated", "item", id, item.ListID, updatedAt))
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||
writeJSONError(w, http.StatusNotFound, "Item not found")
|
||||
return
|
||||
}
|
||||
item, err := s.getItem(r.Context(), id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update item")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "updated", "item", id, item.ListID, updatedAt))
|
||||
writeJSON(w, http.StatusOK, item)
|
||||
return
|
||||
}
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||
return err
|
||||
}
|
||||
var listID string
|
||||
if err := tx.QueryRow(r.Context(), `SELECT listid FROM items WHERE id = $1`, id).Scan(&listID); err != nil {
|
||||
return err
|
||||
}
|
||||
member, err := hasListMembership(r.Context(), tx, requestUserID(r), listID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !member {
|
||||
return errListAccessDenied
|
||||
}
|
||||
result, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -738,7 +972,7 @@ func (s *Server) handleItem(w http.ResponseWriter, r *http.Request) {
|
||||
ignoreNotificationError(enqueueNotificationInTx(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "item", id, item.ListID, updatedAt))
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errListAccessDenied) {
|
||||
writeJSONError(w, http.StatusNotFound, "Item not found")
|
||||
return
|
||||
}
|
||||
|
||||
+108
-1
@@ -35,6 +35,11 @@ func (d *DB) withTx(ctx context.Context, fn func(pgx.Tx) error) error {
|
||||
return sharedpostgres.WithTx(ctx, d.pool, fn)
|
||||
}
|
||||
|
||||
func lockChangeClock(ctx context.Context, tx pgx.Tx) error {
|
||||
var token int64
|
||||
return tx.QueryRow(ctx, `SELECT token FROM collabtable_sync_clock WHERE id = 1 FOR UPDATE`).Scan(&token)
|
||||
}
|
||||
|
||||
// initSchema is idempotent so an existing CollabTable PostgreSQL database can
|
||||
// be used by the Go server without a separate migration step.
|
||||
func (d *DB) initSchema(ctx context.Context) error {
|
||||
@@ -44,7 +49,8 @@ func (d *DB) initSchema(ctx context.Context) error {
|
||||
name TEXT NOT NULL,
|
||||
createdat BIGINT NOT NULL,
|
||||
updatedat BIGINT NOT NULL,
|
||||
isdeleted INTEGER NOT NULL DEFAULT 0
|
||||
isdeleted INTEGER NOT NULL DEFAULT 0,
|
||||
change_token BIGINT NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS fields (
|
||||
@@ -58,6 +64,7 @@ func (d *DB) initSchema(ctx context.Context) error {
|
||||
createdat BIGINT NOT NULL,
|
||||
updatedat BIGINT NOT NULL,
|
||||
isdeleted INTEGER NOT NULL DEFAULT 0,
|
||||
change_token BIGINT NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (listid) REFERENCES lists(id)
|
||||
);
|
||||
|
||||
@@ -67,6 +74,7 @@ func (d *DB) initSchema(ctx context.Context) error {
|
||||
createdat BIGINT NOT NULL,
|
||||
updatedat BIGINT NOT NULL,
|
||||
isdeleted INTEGER NOT NULL DEFAULT 0,
|
||||
change_token BIGINT NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (listid) REFERENCES lists(id)
|
||||
);
|
||||
|
||||
@@ -76,6 +84,7 @@ func (d *DB) initSchema(ctx context.Context) error {
|
||||
fieldid TEXT NOT NULL,
|
||||
value TEXT,
|
||||
updatedat BIGINT NOT NULL,
|
||||
change_token BIGINT NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (itemid) REFERENCES items(id),
|
||||
FOREIGN KEY (fieldid) REFERENCES fields(id)
|
||||
);
|
||||
@@ -88,6 +97,54 @@ func (d *DB) initSchema(ctx context.Context) error {
|
||||
CREATE INDEX IF NOT EXISTS idx_fields_updatedat ON fields(updatedat);
|
||||
CREATE INDEX IF NOT EXISTS idx_items_updatedat ON items(updatedat);
|
||||
CREATE INDEX IF NOT EXISTS idx_item_values_updatedat ON item_values(updatedat);
|
||||
CREATE INDEX IF NOT EXISTS idx_lists_page ON lists(updatedat DESC, id ASC) WHERE isdeleted = 0;
|
||||
CREATE INDEX IF NOT EXISTS idx_fields_page ON fields(listid, "order" ASC, id ASC) WHERE isdeleted = 0;
|
||||
CREATE INDEX IF NOT EXISTS idx_items_page ON items(listid, updatedat DESC, id ASC) WHERE isdeleted = 0;
|
||||
CREATE INDEX IF NOT EXISTS idx_item_values_page ON item_values(itemid, updatedat ASC, id ASC);
|
||||
ALTER TABLE lists ADD COLUMN IF NOT EXISTS change_token BIGINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE fields ADD COLUMN IF NOT EXISTS change_token BIGINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE items ADD COLUMN IF NOT EXISTS change_token BIGINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE item_values ADD COLUMN IF NOT EXISTS change_token BIGINT NOT NULL DEFAULT 0;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS collabtable_sync_clock (
|
||||
id SMALLINT PRIMARY KEY DEFAULT 1 CHECK (id = 1),
|
||||
token BIGINT NOT NULL DEFAULT 0
|
||||
);
|
||||
INSERT INTO collabtable_sync_clock (id, token) VALUES (1, 0) ON CONFLICT (id) DO NOTHING;
|
||||
CREATE INDEX IF NOT EXISTS idx_lists_change_token ON lists(change_token);
|
||||
CREATE INDEX IF NOT EXISTS idx_fields_change_token ON fields(change_token);
|
||||
CREATE INDEX IF NOT EXISTS idx_items_change_token ON items(change_token);
|
||||
CREATE INDEX IF NOT EXISTS idx_item_values_change_token ON item_values(change_token);
|
||||
|
||||
CREATE OR REPLACE FUNCTION collabtable_assign_change_token()
|
||||
RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE next_token BIGINT;
|
||||
BEGIN
|
||||
UPDATE collabtable_sync_clock SET token = token + 1 WHERE id = 1 RETURNING token INTO next_token;
|
||||
IF next_token IS NULL THEN
|
||||
RAISE EXCEPTION 'sync clock row is missing';
|
||||
END IF;
|
||||
NEW.change_token := next_token;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'lists_change_token' AND tgrelid = 'lists'::regclass AND NOT tgisinternal) THEN
|
||||
EXECUTE 'CREATE TRIGGER lists_change_token BEFORE INSERT OR UPDATE ON lists FOR EACH ROW EXECUTE FUNCTION collabtable_assign_change_token()';
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'fields_change_token' AND tgrelid = 'fields'::regclass AND NOT tgisinternal) THEN
|
||||
EXECUTE 'CREATE TRIGGER fields_change_token BEFORE INSERT OR UPDATE ON fields FOR EACH ROW EXECUTE FUNCTION collabtable_assign_change_token()';
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'items_change_token' AND tgrelid = 'items'::regclass AND NOT tgisinternal) THEN
|
||||
EXECUTE 'CREATE TRIGGER items_change_token BEFORE INSERT OR UPDATE ON items FOR EACH ROW EXECUTE FUNCTION collabtable_assign_change_token()';
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'item_values_change_token' AND tgrelid = 'item_values'::regclass AND NOT tgisinternal) THEN
|
||||
EXECUTE 'CREATE TRIGGER item_values_change_token BEFORE INSERT OR UPDATE ON item_values FOR EACH ROW EXECUTE FUNCTION collabtable_assign_change_token()';
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS notifications (
|
||||
id TEXT PRIMARY KEY,
|
||||
@@ -190,14 +247,64 @@ func (d *DB) initSchema(ctx context.Context) error {
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS api_tokens_user_idx ON api_tokens(user_id);
|
||||
ALTER TABLE api_tokens DROP CONSTRAINT IF EXISTS api_tokens_user_id_fkey;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS list_memberships (
|
||||
listid TEXT NOT NULL REFERENCES lists(id) ON DELETE CASCADE,
|
||||
user_id BIGINT NOT NULL,
|
||||
is_owner BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (listid, user_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_list_memberships_user ON list_memberships(user_id, listid);
|
||||
`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("initialize schema: %w", err)
|
||||
}
|
||||
if err := d.backfillChangeTokens(ctx); err != nil {
|
||||
return fmt.Errorf("backfill change tokens: %w", err)
|
||||
}
|
||||
if err := d.backfillListMemberships(ctx); err != nil {
|
||||
return fmt.Errorf("backfill list memberships: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DB) backfillListMemberships(ctx context.Context) error {
|
||||
return d.withTx(ctx, func(tx pgx.Tx) error {
|
||||
if err := lockChangeClock(ctx, tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO list_memberships (listid, user_id, is_owner)
|
||||
SELECT lists.id, token_users.user_id, FALSE
|
||||
FROM lists
|
||||
CROSS JOIN (SELECT DISTINCT user_id FROM api_tokens WHERE user_id <> 0) AS token_users
|
||||
-- New lists already have their creator's membership, so they are not
|
||||
-- expanded to every token user on later starts.
|
||||
WHERE NOT EXISTS (SELECT 1 FROM list_memberships existing WHERE existing.listid = lists.id)
|
||||
ON CONFLICT (listid, user_id) DO NOTHING
|
||||
`); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (d *DB) backfillChangeTokens(ctx context.Context) error {
|
||||
return d.withTx(ctx, func(tx pgx.Tx) error {
|
||||
if err := lockChangeClock(ctx, tx); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, table := range []string{"lists", "fields", "items", "item_values"} {
|
||||
if _, err := tx.Exec(ctx, `UPDATE `+table+` SET change_token = change_token WHERE change_token = 0`); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (d *DB) pruneExpiredSessions(ctx context.Context) {
|
||||
ticker := time.NewTicker(time.Hour)
|
||||
defer ticker.Stop()
|
||||
|
||||
+299
-14
@@ -110,6 +110,10 @@ func newTestAPI(t *testing.T) *testAPI {
|
||||
}
|
||||
|
||||
func (a *testAPI) do(method, path, device string, body any) *httptest.ResponseRecorder {
|
||||
return a.doAs(method, path, device, testBearer, body)
|
||||
}
|
||||
|
||||
func (a *testAPI) doAs(method, path, device, token string, body any) *httptest.ResponseRecorder {
|
||||
a.t.Helper()
|
||||
var reader *bytes.Reader
|
||||
if body == nil {
|
||||
@@ -122,7 +126,7 @@ func (a *testAPI) do(method, path, device string, body any) *httptest.ResponseRe
|
||||
reader = bytes.NewReader(encoded)
|
||||
}
|
||||
request := httptest.NewRequest(method, path, reader)
|
||||
request.Header.Set("Authorization", "Bearer "+testBearer)
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
if device != "" {
|
||||
request.Header.Set("X-Device-Id", device)
|
||||
}
|
||||
@@ -140,6 +144,15 @@ func (a *testAPI) mustDo(method, path, device string, body any, wantStatus int)
|
||||
return recorder
|
||||
}
|
||||
|
||||
func (a *testAPI) mustDoAs(method, path, device, token string, body any, wantStatus int) *httptest.ResponseRecorder {
|
||||
a.t.Helper()
|
||||
recorder := a.doAs(method, path, device, token, body)
|
||||
if recorder.Code != wantStatus {
|
||||
a.t.Fatalf("%s %s status = %d, want %d; body %s", method, path, recorder.Code, wantStatus, recorder.Body.String())
|
||||
}
|
||||
return recorder
|
||||
}
|
||||
|
||||
func decodeBody[T any](t *testing.T, recorder *httptest.ResponseRecorder) T {
|
||||
t.Helper()
|
||||
var value T
|
||||
@@ -151,10 +164,25 @@ func decodeBody[T any](t *testing.T, recorder *httptest.ResponseRecorder) T {
|
||||
|
||||
func (a *testAPI) sync(device string, request SyncRequest) SyncResponse {
|
||||
a.t.Helper()
|
||||
if request.LastSyncToken == nil {
|
||||
initialToken := int64(0)
|
||||
request.LastSyncToken = &initialToken
|
||||
}
|
||||
request.DeviceID = device
|
||||
return decodeBody[SyncResponse](a.t, a.mustDo(http.MethodPost, "/api/sync", device, request, http.StatusOK))
|
||||
}
|
||||
|
||||
func (a *testAPI) currentSyncToken() int64 {
|
||||
a.t.Helper()
|
||||
var token int64
|
||||
if err := a.db.pool.QueryRow(context.Background(), `SELECT token FROM collabtable_sync_clock WHERE id = 1`).Scan(&token); err != nil {
|
||||
a.t.Fatalf("read sync token: %v", err)
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
func ptrInt64(value int64) *int64 { return &value }
|
||||
|
||||
func (a *testAPI) count(query string, args ...any) int {
|
||||
a.t.Helper()
|
||||
var n int
|
||||
@@ -219,9 +247,38 @@ func (a *testAPI) seedList(device, prefix string) {
|
||||
|
||||
func TestInitSchemaCanRunAgainstAnExistingDatabase(t *testing.T) {
|
||||
db := testDB(t)
|
||||
if _, err := db.pool.Exec(context.Background(), `INSERT INTO lists (id, name, createdat, updatedat) VALUES ('backfill', 'Backfill', $1, $1)`, t0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.pool.Exec(context.Background(), `ALTER TABLE lists DISABLE TRIGGER lists_change_token`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.pool.Exec(context.Background(), `UPDATE lists SET change_token = 0 WHERE id = 'backfill'`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.pool.Exec(context.Background(), `ALTER TABLE lists ENABLE TRIGGER lists_change_token`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.initSchema(context.Background()); err != nil {
|
||||
t.Fatalf("second initSchema() error = %v", err)
|
||||
}
|
||||
var firstToken int64
|
||||
if err := db.pool.QueryRow(context.Background(), `SELECT change_token FROM lists WHERE id = 'backfill'`).Scan(&firstToken); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if firstToken == 0 {
|
||||
t.Fatal("initSchema left an existing list without a change token")
|
||||
}
|
||||
if err := db.initSchema(context.Background()); err != nil {
|
||||
t.Fatalf("third initSchema() error = %v", err)
|
||||
}
|
||||
var secondToken int64
|
||||
if err := db.pool.QueryRow(context.Background(), `SELECT change_token FROM lists WHERE id = 'backfill'`).Scan(&secondToken); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if secondToken != firstToken {
|
||||
t.Fatalf("re-running initSchema changed backfilled token from %d to %d", firstToken, secondToken)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncRoundTripBetweenTwoDevices(t *testing.T) {
|
||||
@@ -240,21 +297,21 @@ func TestSyncRoundTripBetweenTwoDevices(t *testing.T) {
|
||||
t.Fatalf("orphanItemValues = %v, want none", full.OrphanItemValues)
|
||||
}
|
||||
|
||||
// The delta filter is "updated at or after the cursor".
|
||||
if got := api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0 + 11)}); len(got.Lists)+len(got.Fields)+len(got.Items)+len(got.ItemValues) != 0 {
|
||||
// The server returns a cursor from the same snapshot as its data page.
|
||||
if got := api.sync("tablet", SyncRequest{LastSyncToken: &full.NextSyncToken}); len(got.Lists)+len(got.Fields)+len(got.Items)+len(got.ItemValues) != 0 {
|
||||
t.Fatalf("sync after the last change returned %+v, want nothing", got)
|
||||
}
|
||||
if got := api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0 + 10)}); len(got.Lists) != 1 || len(got.ItemValues) != 2 {
|
||||
t.Fatalf("sync at the change time returned lists=%d values=%d, want 1 and 2", len(got.Lists), len(got.ItemValues))
|
||||
if got := api.sync("tablet", SyncRequest{LastSyncToken: ptrInt64(0)}); len(got.Lists) != 1 || len(got.ItemValues) != 2 {
|
||||
t.Fatalf("initial page returned lists=%d values=%d, want 1 and 2", len(got.Lists), len(got.ItemValues))
|
||||
}
|
||||
|
||||
// The REST reads see the same data.
|
||||
lists := decodeBody[[]List](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK))
|
||||
if len(lists) != 1 || lists[0].Name != "Groceries" {
|
||||
lists := decodeBody[PageResponse[List]](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK))
|
||||
if len(lists.Items) != 1 || lists.Items[0].Name != "Groceries" || lists.HasMore {
|
||||
t.Fatalf("GET /api/lists = %+v, want the pushed list", lists)
|
||||
}
|
||||
values := decodeBody[[]ItemValue](t, api.mustDo(http.MethodGet, "/api/items/g-item/values", "", nil, http.StatusOK))
|
||||
if len(values) != 2 {
|
||||
values := decodeBody[PageResponse[ItemValue]](t, api.mustDo(http.MethodGet, "/api/items/g-item/values", "", nil, http.StatusOK))
|
||||
if len(values.Items) != 2 || values.HasMore {
|
||||
t.Fatalf("GET item values = %+v, want 2", values)
|
||||
}
|
||||
|
||||
@@ -274,6 +331,232 @@ func TestSyncRoundTripBetweenTwoDevices(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCollectionEndpointsPageWithStableCursors(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
api.seedList("phone", "g")
|
||||
api.sync("phone", SyncRequest{
|
||||
Lists: []List{testList("a-list", "A", t0+10, false)},
|
||||
Items: []Item{testItem("a-item", "g-list", t0+10, false)},
|
||||
})
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
endpoint string
|
||||
decode func(*testing.T, *httptest.ResponseRecorder) (string, string, bool)
|
||||
}{
|
||||
{
|
||||
name: "lists",
|
||||
endpoint: "/api/lists",
|
||||
decode: func(t *testing.T, recorder *httptest.ResponseRecorder) (string, string, bool) {
|
||||
page := decodeBody[PageResponse[List]](t, recorder)
|
||||
if len(page.Items) != 1 {
|
||||
t.Fatalf("first list page has %d items, want 1", len(page.Items))
|
||||
}
|
||||
return page.Items[0].ID, page.NextCursor, page.HasMore
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "fields",
|
||||
endpoint: "/api/fields/list/g-list",
|
||||
decode: func(t *testing.T, recorder *httptest.ResponseRecorder) (string, string, bool) {
|
||||
page := decodeBody[PageResponse[Field]](t, recorder)
|
||||
if len(page.Items) != 1 {
|
||||
t.Fatalf("first field page has %d items, want 1", len(page.Items))
|
||||
}
|
||||
return page.Items[0].ID, page.NextCursor, page.HasMore
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "items",
|
||||
endpoint: "/api/items/list/g-list",
|
||||
decode: func(t *testing.T, recorder *httptest.ResponseRecorder) (string, string, bool) {
|
||||
page := decodeBody[PageResponse[Item]](t, recorder)
|
||||
if len(page.Items) != 1 {
|
||||
t.Fatalf("first item page has %d items, want 1", len(page.Items))
|
||||
}
|
||||
return page.Items[0].ID, page.NextCursor, page.HasMore
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "values",
|
||||
endpoint: "/api/items/g-item/values",
|
||||
decode: func(t *testing.T, recorder *httptest.ResponseRecorder) (string, string, bool) {
|
||||
page := decodeBody[PageResponse[ItemValue]](t, recorder)
|
||||
if len(page.Items) != 1 {
|
||||
t.Fatalf("first value page has %d items, want 1", len(page.Items))
|
||||
}
|
||||
return page.Items[0].ID, page.NextCursor, page.HasMore
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
firstPath := test.endpoint + "?limit=1"
|
||||
firstRecorder := api.mustDo(http.MethodGet, firstPath, "", nil, http.StatusOK)
|
||||
firstID, cursor, hasMore := test.decode(t, firstRecorder)
|
||||
if !hasMore || cursor == "" {
|
||||
t.Fatalf("first page hasMore=%v cursor=%q, want another page", hasMore, cursor)
|
||||
}
|
||||
secondPath := firstPath + "&cursor=" + url.QueryEscape(cursor)
|
||||
secondRecorder := api.mustDo(http.MethodGet, secondPath, "", nil, http.StatusOK)
|
||||
secondID, nextCursor, hasMore := test.decode(t, secondRecorder)
|
||||
if secondID == firstID {
|
||||
t.Fatalf("cursor repeated item %q", firstID)
|
||||
}
|
||||
if hasMore || nextCursor != "" {
|
||||
t.Fatalf("second page hasMore=%v cursor=%q, want final page", hasMore, nextCursor)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
api.mustDo(http.MethodGet, "/api/lists?limit=501", "", nil, http.StatusBadRequest)
|
||||
api.mustDo(http.MethodGet, "/api/lists?cursor=not-a-cursor", "", nil, http.StatusBadRequest)
|
||||
api.mustDo(http.MethodGet, "/api/lists?cursor="+url.QueryEscape(encodePageCursor(pageCursor{Kind: "items", Key: 1, ID: "x"})), "", nil, http.StatusBadRequest)
|
||||
}
|
||||
|
||||
func TestSyncUsesServerChangeTokenInsteadOfClientTimestamp(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
api.seedList("phone", "g")
|
||||
cursor := api.currentSyncToken()
|
||||
clientTimestamp := Timestamp(time.Now().UnixMilli())
|
||||
|
||||
response := api.sync("tablet", SyncRequest{
|
||||
LastSyncTimestamp: clientTimestamp,
|
||||
LastSyncToken: ptrInt64(cursor),
|
||||
Lists: []List{testList("g-list", "Edited offline", t0+20, false)},
|
||||
})
|
||||
if len(response.Lists) != 1 || response.Lists[0].Name != "Edited offline" {
|
||||
t.Fatalf("change with an old client timestamp = %+v, want the updated list", response.Lists)
|
||||
}
|
||||
if response.NextSyncToken <= cursor {
|
||||
t.Fatalf("next sync token = %d, want greater than previous cursor %d", response.NextSyncToken, cursor)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncBoundsAndPagesLargeInitialSync(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
api.mustDo(http.MethodPost, "/api/sync", "phone", map[string]any{}, http.StatusBadRequest)
|
||||
lists := make([]List, 501)
|
||||
for i := range lists {
|
||||
id := fmt.Sprintf("list-%03d", i)
|
||||
lists[i] = testList(id, id, t0+int64(i), false)
|
||||
}
|
||||
|
||||
first := api.sync("phone", SyncRequest{Lists: lists})
|
||||
if len(first.Lists) != syncPageSize || !first.HasMore {
|
||||
t.Fatalf("first page has lists=%d hasMore=%v, want %d and true", len(first.Lists), first.HasMore, syncPageSize)
|
||||
}
|
||||
if first.NextSyncToken <= 0 || first.NextSyncToken >= first.ServerChangeToken {
|
||||
t.Fatalf("first page tokens are next=%d server=%d, want next before server high-water mark", first.NextSyncToken, first.ServerChangeToken)
|
||||
}
|
||||
|
||||
second := api.sync("phone", SyncRequest{LastSyncToken: ptrInt64(first.NextSyncToken)})
|
||||
if len(second.Lists) != 1 || second.HasMore || second.NextSyncToken != second.ServerChangeToken {
|
||||
t.Fatalf("second page has lists=%d hasMore=%v next=%d server=%d, want 1, false, and caught up", len(second.Lists), second.HasMore, second.NextSyncToken, second.ServerChangeToken)
|
||||
}
|
||||
if second.Lists[0].ID == first.Lists[len(first.Lists)-1].ID {
|
||||
t.Fatalf("second page repeated list %q", second.Lists[0].ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPerListMembershipScopesDataAndSync(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
api.seedList("phone", "g")
|
||||
const secondUserID = int64(2)
|
||||
const secondToken = "second-user-device-token"
|
||||
if err := api.db.regenerateAPIToken(context.Background(), secondUserID, hashToken(secondToken)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
firstUserLists := decodeBody[PageResponse[List]](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK))
|
||||
if len(firstUserLists.Items) != 1 || firstUserLists.Items[0].ID != "g-list" {
|
||||
t.Fatalf("first user lists = %+v, want g-list", firstUserLists.Items)
|
||||
}
|
||||
secondUserLists := decodeBody[PageResponse[List]](t, api.mustDoAs(http.MethodGet, "/api/lists", "", secondToken, nil, http.StatusOK))
|
||||
if len(secondUserLists.Items) != 0 {
|
||||
t.Fatalf("second user lists = %+v, want no access to the first user's list", secondUserLists.Items)
|
||||
}
|
||||
api.mustDoAs(http.MethodGet, "/api/items/g-item/values", "", secondToken, nil, http.StatusNotFound)
|
||||
|
||||
foreignCursor := int64(0)
|
||||
foreignSync := decodeBody[SyncResponse](t, api.mustDoAs(http.MethodPost, "/api/sync", "", secondToken,
|
||||
SyncRequest{LastSyncToken: &foreignCursor}, http.StatusOK))
|
||||
if len(foreignSync.Lists)+len(foreignSync.Fields)+len(foreignSync.Items)+len(foreignSync.ItemValues) != 0 {
|
||||
t.Fatalf("second user's initial sync returned another list's data: %+v", foreignSync)
|
||||
}
|
||||
|
||||
api.mustDoAs(http.MethodPost, "/api/sync", "", secondToken, SyncRequest{
|
||||
LastSyncToken: ptrInt64(0),
|
||||
Lists: []List{testList("g-list", "Overwritten", t0+20, false)},
|
||||
}, http.StatusNotFound)
|
||||
var name string
|
||||
if err := api.db.pool.QueryRow(context.Background(), `SELECT name FROM lists WHERE id = 'g-list'`).Scan(&name); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if name != "Groceries" {
|
||||
t.Fatalf("unauthorized sync changed list name to %q", name)
|
||||
}
|
||||
|
||||
newListSync := decodeBody[SyncResponse](t, api.mustDoAs(http.MethodPost, "/api/sync", "", secondToken, SyncRequest{
|
||||
LastSyncToken: ptrInt64(0),
|
||||
Lists: []List{testList("second-list", "Private", t0+30, false)},
|
||||
}, http.StatusOK))
|
||||
if len(newListSync.Lists) != 1 || newListSync.Lists[0].ID != "second-list" {
|
||||
t.Fatalf("creator's sync response = %+v, want only second-list", newListSync.Lists)
|
||||
}
|
||||
if !hasMembership(t, api.db, secondUserID, "second-list") || hasMembership(t, api.db, testUserID, "second-list") {
|
||||
t.Fatal("new sync list was not private to its creator")
|
||||
}
|
||||
var creator bool
|
||||
if err := api.db.pool.QueryRow(context.Background(), `SELECT is_owner FROM list_memberships WHERE listid = 'second-list' AND user_id = $1`, secondUserID).Scan(&creator); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !creator {
|
||||
t.Fatal("new sync list did not mark its creator as owner")
|
||||
}
|
||||
api.mustDo(http.MethodGet, "/api/lists/second-list", "", nil, http.StatusNotFound)
|
||||
}
|
||||
|
||||
func TestMembershipBackfillPreservesCurrentAPITokenUsers(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
if _, err := api.db.pool.Exec(context.Background(), `INSERT INTO lists (id, name, createdat, updatedat) VALUES ('legacy-list', 'Legacy', $1, $1)`, t0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const secondUserID = int64(2)
|
||||
if err := api.db.regenerateAPIToken(context.Background(), secondUserID, hashToken("second-user-device-token")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := api.db.backfillListMemberships(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !hasMembership(t, api.db, testUserID, "legacy-list") || !hasMembership(t, api.db, secondUserID, "legacy-list") {
|
||||
t.Fatal("membership migration did not grant every current API-token user access to the legacy list")
|
||||
}
|
||||
if _, err := api.db.pool.Exec(context.Background(), `INSERT INTO lists (id, name, createdat, updatedat) VALUES ('new-list', 'New', $1, $1)`, t0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := api.db.withTx(context.Background(), func(tx pgx.Tx) error {
|
||||
return addListOwner(context.Background(), tx, secondUserID, "new-list")
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := api.db.backfillListMemberships(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if hasMembership(t, api.db, testUserID, "new-list") {
|
||||
t.Fatal("re-running membership backfill exposed a creator-owned list to another token user")
|
||||
}
|
||||
}
|
||||
|
||||
func hasMembership(t *testing.T, db *DB, userID int64, listID string) bool {
|
||||
t.Helper()
|
||||
member, err := hasListMembership(context.Background(), db.pool, userID, listID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return member
|
||||
}
|
||||
|
||||
func TestSyncLastWriterWinsByTimestamp(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
push := func(name string, updatedAt int64) {
|
||||
@@ -307,9 +590,10 @@ func TestSyncLastWriterWinsByTimestamp(t *testing.T) {
|
||||
func TestStaleDeleteDoesNotCascadeButNewerDeleteDoes(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
api.seedList("phone", "g")
|
||||
seedCursor := api.currentSyncToken()
|
||||
const kept = "list=0 fields=0/2 items=0/1 values=2"
|
||||
|
||||
api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0), Lists: []List{testList("g-list", "Groceries", t0+5, true)}})
|
||||
api.sync("tablet", SyncRequest{LastSyncToken: ptrInt64(seedCursor), Lists: []List{testList("g-list", "Groceries", t0+5, true)}})
|
||||
if got := api.cascadeState("g-list"); got != kept {
|
||||
t.Fatalf("state after a stale delete = %s, want %s", got, kept)
|
||||
}
|
||||
@@ -317,7 +601,7 @@ func TestStaleDeleteDoesNotCascadeButNewerDeleteDoes(t *testing.T) {
|
||||
t.Fatalf("a stale delete produced %d deleted notification(s)", got)
|
||||
}
|
||||
|
||||
api.sync("tablet", SyncRequest{LastSyncTimestamp: Timestamp(t0), Lists: []List{testList("g-list", "Groceries", t0+20, true)}})
|
||||
api.sync("tablet", SyncRequest{LastSyncToken: ptrInt64(seedCursor), Lists: []List{testList("g-list", "Groceries", t0+20, true)}})
|
||||
if got, want := api.cascadeState("g-list"), "list=1 fields=2/2 items=1/1 values=0"; got != want {
|
||||
t.Fatalf("state after a newer delete = %s, want %s (fields and items soft-deleted, values removed)", got, want)
|
||||
}
|
||||
@@ -326,11 +610,11 @@ func TestStaleDeleteDoesNotCascadeButNewerDeleteDoes(t *testing.T) {
|
||||
}
|
||||
|
||||
// The tombstone travels to other devices, but the REST list read hides it.
|
||||
delta := api.sync("phone", SyncRequest{LastSyncTimestamp: Timestamp(t0 + 15)})
|
||||
delta := api.sync("phone", SyncRequest{LastSyncToken: ptrInt64(seedCursor)})
|
||||
if len(delta.Lists) != 1 || !delta.Lists[0].IsDeleted {
|
||||
t.Fatalf("delta after the delete = %+v, want the tombstone", delta.Lists)
|
||||
}
|
||||
if lists := decodeBody[[]List](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK)); len(lists) != 0 {
|
||||
if lists := decodeBody[PageResponse[List]](t, api.mustDo(http.MethodGet, "/api/lists", "", nil, http.StatusOK)); len(lists.Items) != 0 {
|
||||
t.Fatalf("GET /api/lists = %+v, want the deleted list hidden", lists)
|
||||
}
|
||||
}
|
||||
@@ -466,13 +750,14 @@ func TestRESTValueWriteIgnoresAnOlderTimestamp(t *testing.T) {
|
||||
func TestWebDataSupportsConditionalRequests(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
api.seedList("phone", "g")
|
||||
server := &Server{db: api.db}
|
||||
get := func(etag string) *httptest.ResponseRecorder {
|
||||
request := httptest.NewRequest(http.MethodGet, "/web/data", nil)
|
||||
if etag != "" {
|
||||
request.Header.Set("If-None-Match", etag)
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
api.mux.ServeHTTP(recorder, request)
|
||||
server.writeWebData(recorder, request, testUserID)
|
||||
return recorder
|
||||
}
|
||||
|
||||
|
||||
+16
-6
@@ -86,6 +86,7 @@ type ItemValue struct {
|
||||
|
||||
type SyncRequest struct {
|
||||
LastSyncTimestamp Timestamp `json:"lastSyncTimestamp"`
|
||||
LastSyncToken *int64 `json:"lastSyncToken"`
|
||||
Lists []List `json:"lists"`
|
||||
Fields []Field `json:"fields"`
|
||||
Items []Item `json:"items"`
|
||||
@@ -94,12 +95,21 @@ type SyncRequest struct {
|
||||
}
|
||||
|
||||
type SyncResponse struct {
|
||||
Lists []List `json:"lists"`
|
||||
Fields []Field `json:"fields"`
|
||||
Items []Item `json:"items"`
|
||||
ItemValues []ItemValue `json:"itemValues"`
|
||||
OrphanItemValues []OrphanValue `json:"orphanItemValues"`
|
||||
ServerTimestamp int64 `json:"serverTimestamp"`
|
||||
Lists []List `json:"lists"`
|
||||
Fields []Field `json:"fields"`
|
||||
Items []Item `json:"items"`
|
||||
ItemValues []ItemValue `json:"itemValues"`
|
||||
OrphanItemValues []OrphanValue `json:"orphanItemValues"`
|
||||
ServerTimestamp int64 `json:"serverTimestamp"`
|
||||
ServerChangeToken int64 `json:"serverChangeToken"`
|
||||
NextSyncToken int64 `json:"nextSyncToken"`
|
||||
HasMore bool `json:"hasMore"`
|
||||
}
|
||||
|
||||
type PageResponse[T any] struct {
|
||||
Items []T `json:"items"`
|
||||
NextCursor string `json:"nextCursor"`
|
||||
HasMore bool `json:"hasMore"`
|
||||
}
|
||||
|
||||
type OrphanValue struct {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
var (
|
||||
errListAccessDenied = errors.New("list access denied")
|
||||
errCellIdentityMismatch = errors.New("item and field belong to different lists")
|
||||
)
|
||||
|
||||
type rowQueryer interface {
|
||||
QueryRow(context.Context, string, ...any) pgx.Row
|
||||
}
|
||||
|
||||
func hasListMembership(ctx context.Context, queryer rowQueryer, userID int64, listID string) (bool, error) {
|
||||
var member bool
|
||||
err := queryer.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM list_memberships WHERE listid = $1 AND user_id = $2)`, listID, userID).Scan(&member)
|
||||
return member, err
|
||||
}
|
||||
|
||||
func authorizeList(ctx context.Context, queryer rowQueryer, userID int64, listID string, allowCreate bool) (bool, error) {
|
||||
if userID <= 0 || listID == "" {
|
||||
return false, errListAccessDenied
|
||||
}
|
||||
member, err := hasListMembership(ctx, queryer, userID, listID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if member {
|
||||
return true, nil
|
||||
}
|
||||
var exists bool
|
||||
if err := queryer.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM lists WHERE id = $1)`, listID).Scan(&exists); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if exists || !allowCreate {
|
||||
return false, errListAccessDenied
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func addListOwner(ctx context.Context, tx pgx.Tx, userID int64, listID string) error {
|
||||
_, err := tx.Exec(ctx, `INSERT INTO list_memberships (listid, user_id, is_owner) VALUES ($1, $2, TRUE) ON CONFLICT (listid, user_id) DO NOTHING`, listID, userID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Server) requireListMembership(w http.ResponseWriter, r *http.Request, listID string) bool {
|
||||
member, err := hasListMembership(r.Context(), s.db.pool, requestUserID(r), listID)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to authorize list")
|
||||
return false
|
||||
}
|
||||
if !member {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultPageSize = 200
|
||||
maxPageSize = 500
|
||||
)
|
||||
|
||||
type pageCursor struct {
|
||||
Kind string `json:"kind"`
|
||||
Key int64 `json:"key"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
type pageRequest struct {
|
||||
Limit int
|
||||
Cursor *pageCursor
|
||||
}
|
||||
|
||||
func parsePageRequest(r *http.Request, kind string) (pageRequest, error) {
|
||||
page := pageRequest{Limit: defaultPageSize}
|
||||
if rawLimit := r.URL.Query().Get("limit"); rawLimit != "" {
|
||||
limit, err := strconv.Atoi(rawLimit)
|
||||
if err != nil || limit < 1 || limit > maxPageSize {
|
||||
return pageRequest{}, fmt.Errorf("limit must be between 1 and %d", maxPageSize)
|
||||
}
|
||||
page.Limit = limit
|
||||
}
|
||||
if rawCursor := r.URL.Query().Get("cursor"); rawCursor != "" {
|
||||
decoded, err := base64.RawURLEncoding.DecodeString(rawCursor)
|
||||
if err != nil {
|
||||
return pageRequest{}, errors.New("cursor is invalid")
|
||||
}
|
||||
var cursor pageCursor
|
||||
if err := json.Unmarshal(decoded, &cursor); err != nil || cursor.Kind != kind || cursor.ID == "" {
|
||||
return pageRequest{}, errors.New("cursor is invalid")
|
||||
}
|
||||
page.Cursor = &cursor
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func requestPage(w http.ResponseWriter, r *http.Request, kind string) (pageRequest, bool) {
|
||||
page, err := parsePageRequest(r, kind)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return pageRequest{}, false
|
||||
}
|
||||
return page, true
|
||||
}
|
||||
|
||||
func encodePageCursor(cursor pageCursor) string {
|
||||
encoded, _ := json.Marshal(cursor)
|
||||
return base64.RawURLEncoding.EncodeToString(encoded)
|
||||
}
|
||||
|
||||
func readPage[T any](rows pgx.Rows, request pageRequest, kind string, scan func(rowScanner) (T, error), key func(T) int64, id func(T) string) (PageResponse[T], error) {
|
||||
defer rows.Close()
|
||||
items := make([]T, 0, request.Limit+1)
|
||||
for rows.Next() {
|
||||
item, err := scan(rows)
|
||||
if err != nil {
|
||||
return PageResponse[T]{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return PageResponse[T]{}, err
|
||||
}
|
||||
hasMore := len(items) > request.Limit
|
||||
if hasMore {
|
||||
items = items[:request.Limit]
|
||||
}
|
||||
response := PageResponse[T]{Items: items, HasMore: hasMore}
|
||||
if hasMore {
|
||||
last := items[len(items)-1]
|
||||
response.NextCursor = encodePageCursor(pageCursor{Kind: kind, Key: key(last), ID: id(last)})
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func addPageCursor(conditions *[]string, args *[]any, column string, direction string, cursor *pageCursor) {
|
||||
if cursor == nil {
|
||||
return
|
||||
}
|
||||
*args = append(*args, cursor.Key)
|
||||
keyParam := len(*args)
|
||||
*args = append(*args, cursor.ID)
|
||||
idParam := len(*args)
|
||||
comparison := ">"
|
||||
if direction == "desc" {
|
||||
comparison = "<"
|
||||
}
|
||||
*conditions = append(*conditions, fmt.Sprintf("(%s %s $%d OR (%s = $%d AND id > $%d))", column, comparison, keyParam, column, keyParam, idParam))
|
||||
}
|
||||
|
||||
func (d *DB) queryListPage(ctx context.Context, userID int64, includeDeleted bool, request pageRequest) (PageResponse[List], error) {
|
||||
conditions := make([]string, 0, 3)
|
||||
args := make([]any, 0, 4)
|
||||
args = append(args, userID)
|
||||
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = lists.id AND m.user_id = $%d)", len(args)))
|
||||
if !includeDeleted {
|
||||
conditions = append(conditions, "isdeleted = 0")
|
||||
}
|
||||
addPageCursor(&conditions, &args, "updatedat", "desc", request.Cursor)
|
||||
args = append(args, request.Limit+1)
|
||||
query := `SELECT ` + listColumns + ` FROM lists`
|
||||
if len(conditions) > 0 {
|
||||
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||
}
|
||||
query += fmt.Sprintf(" ORDER BY updatedat DESC, id ASC LIMIT $%d", len(args))
|
||||
rows, err := d.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return PageResponse[List]{}, err
|
||||
}
|
||||
return readPage(rows, request, "lists", scanList, func(item List) int64 { return int64(item.UpdatedAt) }, func(item List) string { return item.ID })
|
||||
}
|
||||
|
||||
func (d *DB) queryFieldsPage(ctx context.Context, userID int64, includeDeleted bool, listID string, request pageRequest) (PageResponse[Field], error) {
|
||||
conditions := make([]string, 0, 4)
|
||||
args := make([]any, 0, 5)
|
||||
if !includeDeleted {
|
||||
conditions = append(conditions, "isdeleted = 0")
|
||||
}
|
||||
args = append(args, listID)
|
||||
conditions = append(conditions, fmt.Sprintf("listid = $%d", len(args)))
|
||||
args = append(args, userID)
|
||||
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = fields.listid AND m.user_id = $%d)", len(args)))
|
||||
addPageCursor(&conditions, &args, `"order"`, "asc", request.Cursor)
|
||||
args = append(args, request.Limit+1)
|
||||
query := `SELECT ` + fieldColumns + ` FROM fields WHERE ` + strings.Join(conditions, " AND ")
|
||||
query += fmt.Sprintf(` ORDER BY "order" ASC, id ASC LIMIT $%d`, len(args))
|
||||
rows, err := d.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return PageResponse[Field]{}, err
|
||||
}
|
||||
return readPage(rows, request, "fields", scanField, func(item Field) int64 { return int64(item.Order) }, func(item Field) string { return item.ID })
|
||||
}
|
||||
|
||||
func (d *DB) queryItemsPage(ctx context.Context, userID int64, includeDeleted bool, listID string, request pageRequest) (PageResponse[Item], error) {
|
||||
conditions := make([]string, 0, 4)
|
||||
args := make([]any, 0, 5)
|
||||
if !includeDeleted {
|
||||
conditions = append(conditions, "isdeleted = 0")
|
||||
}
|
||||
args = append(args, listID)
|
||||
conditions = append(conditions, fmt.Sprintf("listid = $%d", len(args)))
|
||||
args = append(args, userID)
|
||||
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = items.listid AND m.user_id = $%d)", len(args)))
|
||||
addPageCursor(&conditions, &args, "updatedat", "desc", request.Cursor)
|
||||
args = append(args, request.Limit+1)
|
||||
query := `SELECT ` + itemColumns + ` FROM items WHERE ` + strings.Join(conditions, " AND ")
|
||||
query += fmt.Sprintf(" ORDER BY updatedat DESC, id ASC LIMIT $%d", len(args))
|
||||
rows, err := d.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return PageResponse[Item]{}, err
|
||||
}
|
||||
return readPage(rows, request, "items", scanItem, func(item Item) int64 { return int64(item.UpdatedAt) }, func(item Item) string { return item.ID })
|
||||
}
|
||||
|
||||
func (d *DB) queryValuesPage(ctx context.Context, userID int64, itemID string, request pageRequest) (PageResponse[ItemValue], error) {
|
||||
conditions := make([]string, 0, 2)
|
||||
args := make([]any, 0, 4)
|
||||
args = append(args, itemID)
|
||||
conditions = append(conditions, fmt.Sprintf("itemid = $%d", len(args)))
|
||||
args = append(args, userID)
|
||||
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM items i JOIN list_memberships m ON m.listid = i.listid WHERE i.id = item_values.itemid AND m.user_id = $%d)", len(args)))
|
||||
addPageCursor(&conditions, &args, "updatedat", "asc", request.Cursor)
|
||||
args = append(args, request.Limit+1)
|
||||
query := `SELECT ` + valueColumns + ` FROM item_values WHERE ` + strings.Join(conditions, " AND ")
|
||||
query += fmt.Sprintf(" ORDER BY updatedat ASC, id ASC LIMIT $%d", len(args))
|
||||
rows, err := d.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return PageResponse[ItemValue]{}, err
|
||||
}
|
||||
return readPage(rows, request, "values", scanItemValue, func(item ItemValue) int64 { return int64(item.UpdatedAt) }, func(item ItemValue) string { return item.ID })
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParsePageRequest(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
query string
|
||||
wantLimit int
|
||||
wantCursor *pageCursor
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "defaults", wantLimit: defaultPageSize},
|
||||
{name: "custom limit", query: "limit=17", wantLimit: 17},
|
||||
{name: "maximum limit", query: "limit=500", wantLimit: 500},
|
||||
{name: "zero limit", query: "limit=0", wantErr: true},
|
||||
{name: "oversized limit", query: "limit=501", wantErr: true},
|
||||
{name: "invalid limit", query: "limit=large", wantErr: true},
|
||||
{
|
||||
name: "cursor",
|
||||
query: "cursor=" + encodePageCursor(pageCursor{Kind: "lists", Key: 123, ID: "list-1"}),
|
||||
wantLimit: defaultPageSize,
|
||||
wantCursor: &pageCursor{Kind: "lists", Key: 123, ID: "list-1"},
|
||||
},
|
||||
{name: "malformed cursor", query: "cursor=not-a-cursor", wantErr: true},
|
||||
{
|
||||
name: "cursor for another collection",
|
||||
query: "cursor=" + encodePageCursor(pageCursor{Kind: "items", Key: 123, ID: "item-1"}),
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
request := httptest.NewRequest("GET", "/api/lists?"+test.query, nil)
|
||||
got, err := parsePageRequest(request, "lists")
|
||||
if (err != nil) != test.wantErr {
|
||||
t.Fatalf("parsePageRequest() error = %v, wantErr %v", err, test.wantErr)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if got.Limit != test.wantLimit {
|
||||
t.Fatalf("limit = %d, want %d", got.Limit, test.wantLimit)
|
||||
}
|
||||
if test.wantCursor == nil {
|
||||
if got.Cursor != nil {
|
||||
t.Fatalf("cursor = %+v, want none", got.Cursor)
|
||||
}
|
||||
return
|
||||
}
|
||||
if got.Cursor == nil || *got.Cursor != *test.wantCursor {
|
||||
t.Fatalf("cursor = %+v, want %+v", got.Cursor, test.wantCursor)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+181
-32
@@ -2,8 +2,10 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
@@ -12,6 +14,7 @@ import (
|
||||
// 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
|
||||
const syncPageSize = 500
|
||||
|
||||
func syncMaxFutureSkew() int64 {
|
||||
value := envInt64("SYNC_MAX_FUTURE_SKEW_MS", 0)
|
||||
@@ -48,11 +51,11 @@ func normalizeEntityTimestamps(createdAt, updatedAt, now int64) (int64, int64) {
|
||||
|
||||
// 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) {
|
||||
func valueReferences(ctx context.Context, tx pgx.Tx, values []ItemValue) (map[string]string, map[string]string, error) {
|
||||
fieldLists := make(map[string]string)
|
||||
existingItems := make(map[string]bool)
|
||||
itemLists := make(map[string]string)
|
||||
if len(values) == 0 {
|
||||
return fieldLists, existingItems, nil
|
||||
return fieldLists, itemLists, nil
|
||||
}
|
||||
fieldIDs := make([]string, 0, len(values))
|
||||
itemIDs := make([]string, 0, len(values))
|
||||
@@ -77,22 +80,22 @@ func valueReferences(ctx context.Context, tx pgx.Tx, values []ItemValue) (map[st
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
itemRows, err := tx.Query(ctx, `SELECT id FROM items WHERE id = ANY($1)`, itemIDs)
|
||||
itemRows, err := tx.Query(ctx, `SELECT id, listid 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 {
|
||||
var itemID, listID string
|
||||
if err := itemRows.Scan(&itemID, &listID); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
existingItems[itemID] = true
|
||||
itemLists[itemID] = listID
|
||||
}
|
||||
if err := itemRows.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return fieldLists, existingItems, nil
|
||||
return fieldLists, itemLists, nil
|
||||
}
|
||||
|
||||
// changeEventType names a synced change for the notification feed: a tombstone
|
||||
@@ -110,6 +113,7 @@ func changeEventType(initialSync, deleted bool) string {
|
||||
// syncBatch holds what every row of one sync request shares.
|
||||
type syncBatch struct {
|
||||
now int64
|
||||
userID int64
|
||||
initialSync bool
|
||||
deviceID string
|
||||
}
|
||||
@@ -122,11 +126,20 @@ func (b syncBatch) notify(ctx context.Context, tx pgx.Tx, eventType, entityType,
|
||||
// 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 {
|
||||
member, err := authorizeList(ctx, tx, batch.userID, list.ID, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
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 !member {
|
||||
if err := addListOwner(ctx, tx, batch.userID, list.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if !applied {
|
||||
continue
|
||||
}
|
||||
@@ -141,8 +154,33 @@ func applyLists(ctx context.Context, tx pgx.Tx, lists []List, batch syncBatch) e
|
||||
return nil
|
||||
}
|
||||
|
||||
func ensureEntityList(ctx context.Context, tx pgx.Tx, table, id, listID string) error {
|
||||
var storedListID string
|
||||
err := tx.QueryRow(ctx, `SELECT listid FROM `+table+` WHERE id = $1`, id).Scan(&storedListID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if storedListID != listID {
|
||||
return errListAccessDenied
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func applyFields(ctx context.Context, tx pgx.Tx, fields []Field, batch syncBatch) error {
|
||||
for _, field := range fields {
|
||||
if err := ensureEntityList(ctx, tx, "fields", field.ID, field.ListID); err != nil {
|
||||
return err
|
||||
}
|
||||
member, err := hasListMembership(ctx, tx, batch.userID, field.ListID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !member {
|
||||
return errListAccessDenied
|
||||
}
|
||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(field.CreatedAt), int64(field.UpdatedAt), batch.now)
|
||||
applied, err := upsertField(ctx, tx, field, createdAt, updatedAt)
|
||||
if err != nil {
|
||||
@@ -164,6 +202,16 @@ func applyFields(ctx context.Context, tx pgx.Tx, fields []Field, batch syncBatch
|
||||
|
||||
func applyItems(ctx context.Context, tx pgx.Tx, items []Item, batch syncBatch) error {
|
||||
for _, item := range items {
|
||||
if err := ensureEntityList(ctx, tx, "items", item.ID, item.ListID); err != nil {
|
||||
return err
|
||||
}
|
||||
member, err := hasListMembership(ctx, tx, batch.userID, item.ListID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !member {
|
||||
return errListAccessDenied
|
||||
}
|
||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(item.CreatedAt), int64(item.UpdatedAt), batch.now)
|
||||
applied, err := upsertItem(ctx, tx, item, createdAt, updatedAt)
|
||||
if err != nil {
|
||||
@@ -189,7 +237,7 @@ func applyValues(ctx context.Context, tx pgx.Tx, values []ItemValue, batch syncB
|
||||
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)
|
||||
fieldLists, itemLists, err := valueReferences(ctx, tx, values)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -201,8 +249,16 @@ func applyValues(ctx context.Context, tx pgx.Tx, values []ItemValue, batch syncB
|
||||
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "missingField"})
|
||||
continue
|
||||
}
|
||||
member, err := hasListMembership(ctx, tx, batch.userID, listID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !member {
|
||||
return nil, errListAccessDenied
|
||||
}
|
||||
|
||||
if !existingItems[value.ItemID] {
|
||||
itemListID, itemExists := itemLists[value.ItemID]
|
||||
if !itemExists {
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $3, 0)
|
||||
@@ -211,7 +267,17 @@ func applyValues(ctx context.Context, tx pgx.Tx, values []ItemValue, batch syncB
|
||||
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "failedCreateStubItem"})
|
||||
continue
|
||||
}
|
||||
existingItems[value.ItemID] = true
|
||||
itemLists[value.ItemID] = listID
|
||||
} else if itemListID != listID {
|
||||
itemMember, err := hasListMembership(ctx, tx, batch.userID, itemListID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !itemMember {
|
||||
return nil, errListAccessDenied
|
||||
}
|
||||
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "itemFieldListMismatch"})
|
||||
continue
|
||||
}
|
||||
applied, err := upsertValue(ctx, tx, value, updatedAt)
|
||||
if err != nil {
|
||||
@@ -239,27 +305,104 @@ func applySyncRequest(ctx context.Context, tx pgx.Tx, request SyncRequest, batch
|
||||
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)
|
||||
type syncChange struct {
|
||||
token int64
|
||||
kind string
|
||||
value any
|
||||
}
|
||||
|
||||
type trailingTokenScanner struct {
|
||||
row rowScanner
|
||||
token int64
|
||||
}
|
||||
|
||||
func (s *trailingTokenScanner) Scan(dest ...any) error {
|
||||
return s.row.Scan(append(dest, &s.token)...)
|
||||
}
|
||||
|
||||
// changesSince returns a bounded page from one repeatable-read snapshot. Each
|
||||
// data write takes the clock row lock before touching a row, so a later commit
|
||||
// cannot publish a lower token than a cursor already returned to a device.
|
||||
func (d *DB) changesSince(ctx context.Context, userID int64, cursor int64) (SyncResponse, error) {
|
||||
tx, err := d.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
|
||||
if err != nil {
|
||||
return SyncResponse{}, err
|
||||
}
|
||||
fields, err := d.queryFields(ctx, true, since, "")
|
||||
if err != nil {
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
var serverToken int64
|
||||
if err := tx.QueryRow(ctx, `SELECT token FROM collabtable_sync_clock WHERE id = 1`).Scan(&serverToken); err != nil {
|
||||
return SyncResponse{}, err
|
||||
}
|
||||
items, err := d.queryItems(ctx, true, since, "")
|
||||
if err != nil {
|
||||
if cursor > serverToken {
|
||||
cursor = 0
|
||||
}
|
||||
|
||||
queries := []struct {
|
||||
kind string
|
||||
stmt string
|
||||
scan func(rowScanner) (any, error)
|
||||
}{
|
||||
{kind: "list", stmt: `SELECT lists.id, lists.name, lists.createdat, lists.updatedat, COALESCE(lists.isdeleted, 0), lists.change_token FROM lists JOIN list_memberships m ON m.listid = lists.id WHERE m.user_id = $1 AND lists.change_token > $2 ORDER BY lists.change_token LIMIT $3`, scan: func(row rowScanner) (any, error) { return scanList(row) }},
|
||||
{kind: "field", stmt: `SELECT fields.id, fields.name, fields.fieldtype, COALESCE(fields.fieldoptions, ''), COALESCE(fields.alignment, 'start'), fields.listid, fields."order", fields.createdat, fields.updatedat, COALESCE(fields.isdeleted, 0), fields.change_token FROM fields JOIN list_memberships m ON m.listid = fields.listid WHERE m.user_id = $1 AND fields.change_token > $2 ORDER BY fields.change_token LIMIT $3`, scan: func(row rowScanner) (any, error) { return scanField(row) }},
|
||||
{kind: "item", stmt: `SELECT items.id, items.listid, items.createdat, items.updatedat, COALESCE(items.isdeleted, 0), items.change_token FROM items JOIN list_memberships m ON m.listid = items.listid WHERE m.user_id = $1 AND items.change_token > $2 ORDER BY items.change_token LIMIT $3`, scan: func(row rowScanner) (any, error) { return scanItem(row) }},
|
||||
{kind: "value", stmt: `SELECT item_values.id, item_values.itemid, item_values.fieldid, COALESCE(item_values.value, ''), item_values.updatedat, item_values.change_token FROM item_values JOIN items i ON i.id = item_values.itemid JOIN list_memberships m ON m.listid = i.listid WHERE m.user_id = $1 AND item_values.change_token > $2 ORDER BY item_values.change_token LIMIT $3`, scan: func(row rowScanner) (any, error) { return scanItemValue(row) }},
|
||||
}
|
||||
changes := make([]syncChange, 0, syncPageSize*2)
|
||||
for _, query := range queries {
|
||||
rows, err := tx.Query(ctx, query.stmt, userID, cursor, syncPageSize+1)
|
||||
if err != nil {
|
||||
return SyncResponse{}, err
|
||||
}
|
||||
for rows.Next() {
|
||||
scanner := trailingTokenScanner{row: rows}
|
||||
value, err := query.scan(&scanner)
|
||||
if err != nil {
|
||||
rows.Close()
|
||||
return SyncResponse{}, err
|
||||
}
|
||||
changes = append(changes, syncChange{token: scanner.token, kind: query.kind, value: value})
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return SyncResponse{}, err
|
||||
}
|
||||
rows.Close()
|
||||
}
|
||||
sort.Slice(changes, func(i, j int) bool { return changes[i].token < changes[j].token })
|
||||
hasMore := len(changes) > syncPageSize
|
||||
if hasMore {
|
||||
changes = changes[:syncPageSize]
|
||||
}
|
||||
nextToken := serverToken
|
||||
if hasMore {
|
||||
nextToken = changes[len(changes)-1].token
|
||||
}
|
||||
response := SyncResponse{
|
||||
Lists: make([]List, 0),
|
||||
Fields: make([]Field, 0),
|
||||
Items: make([]Item, 0),
|
||||
ItemValues: make([]ItemValue, 0),
|
||||
ServerChangeToken: serverToken,
|
||||
NextSyncToken: nextToken,
|
||||
HasMore: hasMore,
|
||||
}
|
||||
for _, change := range changes {
|
||||
switch change.kind {
|
||||
case "list":
|
||||
response.Lists = append(response.Lists, change.value.(List))
|
||||
case "field":
|
||||
response.Fields = append(response.Fields, change.value.(Field))
|
||||
case "item":
|
||||
response.Items = append(response.Items, change.value.(Item))
|
||||
case "value":
|
||||
response.ItemValues = append(response.ItemValues, change.value.(ItemValue))
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); 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
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -278,10 +421,13 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
||||
writeDecodeError(w, err, "Invalid sync request")
|
||||
return
|
||||
}
|
||||
if request.LastSyncToken == nil || *request.LastSyncToken < 0 {
|
||||
writeJSONError(w, http.StatusBadRequest, "lastSyncToken is required; update the CollabTable client")
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now().UnixMilli()
|
||||
lastSync := normalizeTimestamp(int64(request.LastSyncTimestamp), 0, now)
|
||||
batch := syncBatch{now: now, initialSync: lastSync == 0, deviceID: requestDeviceID(r, request.DeviceID)}
|
||||
batch := syncBatch{now: now, userID: requestUserID(r), initialSync: *request.LastSyncToken == 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 {
|
||||
@@ -289,21 +435,24 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
if err := lockChangeClock(r.Context(), tx); err != nil {
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
orphans, err = applySyncRequest(r.Context(), tx, request, batch)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, errListAccessDenied) {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
return
|
||||
}
|
||||
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)
|
||||
response, err := s.db.changesSince(r.Context(), requestUserID(r), *request.LastSyncToken)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||
return
|
||||
|
||||
+14
-6
@@ -11,22 +11,26 @@ import (
|
||||
)
|
||||
|
||||
func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request) {
|
||||
lists, err := s.db.queryLists(r.Context(), false, nil)
|
||||
s.writeWebData(w, r, requestUserID(r))
|
||||
}
|
||||
|
||||
func (s *Server) writeWebData(w http.ResponseWriter, r *http.Request, userID int64) {
|
||||
lists, err := s.db.queryLists(r.Context(), userID, false, nil)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||
return
|
||||
}
|
||||
fields, err := s.db.queryFields(r.Context(), false, nil, "")
|
||||
fields, err := s.db.queryFields(r.Context(), userID, false, nil, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||
return
|
||||
}
|
||||
items, err := s.db.queryItems(r.Context(), false, nil, "")
|
||||
items, err := s.db.queryItems(r.Context(), userID, false, nil, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||
return
|
||||
}
|
||||
values, err := s.db.queryValues(r.Context(), nil, "")
|
||||
values, err := s.db.queryValues(r.Context(), userID, nil, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||
return
|
||||
@@ -134,10 +138,14 @@ func (s *Server) handleNotificationPoll(w http.ResponseWriter, r *http.Request)
|
||||
SELECT id, deviceidorigin, eventtype, entitytype, entityid, listid, createdat
|
||||
FROM notifications
|
||||
WHERE createdat > $1
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM list_memberships m
|
||||
WHERE m.listid = notifications.listid AND m.user_id = $2
|
||||
)
|
||||
`
|
||||
args := []any{since}
|
||||
args := []any{since, requestUserID(r)}
|
||||
if deviceID != "" {
|
||||
query += ` AND (deviceidorigin IS NULL OR deviceidorigin <> $2)`
|
||||
query += ` AND (deviceidorigin IS NULL OR deviceidorigin <> $3)`
|
||||
args = append(args, deviceID)
|
||||
}
|
||||
query += ` ORDER BY createdat ASC LIMIT 500`
|
||||
|
||||
Reference in new issue
Block a user