feat(sync): paginate Android sync with change tokens
Lint / Lint (push) Successful in 1m8s
Tests / Go backend (push) Failing after 1m23s
Tests / Dashboard checks (push) Failing after 38s
Docker / Docker Build & Push (push) Failing after 6m29s

This commit is contained in:
Gabriel20xx committed 2026-10-20 15:27:53 +00:00
1 parent 0ff94f9b10
commit 97c237be80
76 files changed
+3401 -851

No files matched your search

+299 -14
View File
@@ -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
}