🐛 Reject invalid changes instead of failing the whole sync batch
Every whitelisted field was written, so a tombstone or a partial change without the required fields failed the validation and rolled back the whole batch with 400, which a client would retry forever. Only the keys present in the change are set now, a change is validated on its own and answered as invalid with the message, and a tombstone for an unknown row is answered ok without writing anything.
This commit is contained in:
@@ -2,6 +2,7 @@ package syncapi_test
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
@@ -10,6 +11,7 @@ import (
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
_ "time/tzdata"
|
||||
|
||||
_ "github.com/wotra/wotra/internal/migrations"
|
||||
"github.com/wotra/wotra/internal/syncapi"
|
||||
@@ -26,8 +28,14 @@ const (
|
||||
entryData = `"data":{"start_time":1000,"end_time":2000,"auto_stopped":false,"note":"%s","day_key":"2026-01-05"}`
|
||||
settingsData = `"data":{"effective_from":"2026-01-01","hours_per_week":40,"workdays_mask":31,"timezone":"Europe/Berlin"}`
|
||||
closedDay = `{"collection":"closed_days","id":"` + recB + `","data":{"day_key":"2026-01-05","worked_ms":1000,"kind":"work","closed_at":1},"client_updated_at":5,"deleted":false}`
|
||||
closedWeek = `{"collection":"closed_weeks","id":"` + recB + `","data":{"week_key":"2026-W02","expected_ms":1,"worked_ms":2,"delta_ms":1,"closed_at":3},"client_updated_at":5,"deleted":false}`
|
||||
)
|
||||
|
||||
// change builds a change with the given data.
|
||||
func change(collection, id, data string, updatedAt int64, deleted bool) string {
|
||||
return fmt.Sprintf(`{"collection":%q,"id":%q,"data":{%s},"client_updated_at":%d,"deleted":%t}`, collection, id, data, updatedAt, deleted)
|
||||
}
|
||||
|
||||
type env struct {
|
||||
app *tests.TestApp
|
||||
tokenA string
|
||||
@@ -94,6 +102,12 @@ func body(changes ...string) *strings.Reader {
|
||||
return strings.NewReader(`{"changes":[` + strings.Join(changes, ",") + `]}`)
|
||||
}
|
||||
|
||||
// jsonString returns s as a quoted JSON string.
|
||||
func jsonString(s string) string {
|
||||
b, _ := json.Marshal(s)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func checkRecord(collection, id string, want map[string]any) func(testing.TB, *tests.TestApp, *http.Response) {
|
||||
return func(t testing.TB, app *tests.TestApp, _ *http.Response) {
|
||||
r, err := app.FindRecordById(collection, id)
|
||||
@@ -174,6 +188,64 @@ func TestPush(t *testing.T) {
|
||||
content: []string{`"status":"readonly"`, `"collection":"closed_days"`},
|
||||
after: checkNoRecord("closed_days", recB),
|
||||
},
|
||||
{
|
||||
name: "closed_weeks change is readonly",
|
||||
auth: func(e *env) string { return e.tokenA },
|
||||
body: closedWeek,
|
||||
status: 200,
|
||||
content: []string{`"status":"readonly"`, `"collection":"closed_weeks"`},
|
||||
after: checkNoRecord("closed_weeks", recB),
|
||||
},
|
||||
{
|
||||
name: "tombstone for an unknown id",
|
||||
auth: func(e *env) string { return e.tokenA },
|
||||
body: change("entries", recB, "", 5, true),
|
||||
status: 200,
|
||||
content: []string{`"status":"ok"`, `"id":"` + recB + `"`},
|
||||
after: checkNoRecord("entries", recB),
|
||||
},
|
||||
{
|
||||
name: "tombstone for an unknown id with data",
|
||||
auth: func(e *env) string { return e.tokenA },
|
||||
body: entry(recB, "gone", 5, true),
|
||||
status: 200,
|
||||
content: []string{`"status":"ok"`, `"id":"` + recB + `"`},
|
||||
after: checkNoRecord("entries", recB),
|
||||
},
|
||||
{
|
||||
name: "tombstone for an existing id keeps the other fields",
|
||||
auth: func(e *env) string { return e.tokenA },
|
||||
body: change("entries", recA, "", 2000, true),
|
||||
status: 200,
|
||||
content: []string{`"status":"ok"`, `"rev":2`, `"deleted":true`, `"note":"orig"`},
|
||||
after: checkRecord("entries", recA, map[string]any{"deleted": true, "rev": 2, "note": "orig", "start_time": 1000, "day_key": "2026-01-05"}),
|
||||
},
|
||||
{
|
||||
name: "partial update leaves the other fields alone",
|
||||
auth: func(e *env) string { return e.tokenA },
|
||||
body: change("entries", recA, `"note":"upd"`, 2000, false),
|
||||
status: 200,
|
||||
content: []string{`"status":"ok"`, `"rev":2`, `"note":"upd"`},
|
||||
after: checkRecord("entries", recA, map[string]any{
|
||||
"note": "upd", "start_time": 1000, "end_time": 2000, "auto_stopped": false, "day_key": "2026-01-05", "deleted": false, "rev": 2,
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "new record without a required field is invalid",
|
||||
auth: func(e *env) string { return e.tokenA },
|
||||
body: change("entries", recB, `"note":"no times"`, 5, false),
|
||||
status: 200,
|
||||
content: []string{`"status":"invalid"`, `"error":"day_key: cannot be blank"`},
|
||||
after: checkNoRecord("entries", recB),
|
||||
},
|
||||
{
|
||||
name: "day_key that is not a real date is invalid",
|
||||
auth: func(e *env) string { return e.tokenA },
|
||||
body: change("entries", recB, `"start_time":1000,"end_time":2000,"auto_stopped":false,"note":"new","day_key":"2026-02-30"`, 5, false),
|
||||
status: 200,
|
||||
content: []string{`"status":"invalid"`, `"error":"day_key \"2026-02-30\" is not a calendar date"`},
|
||||
after: checkNoRecord("entries", recB),
|
||||
},
|
||||
{
|
||||
name: "unknown data field",
|
||||
auth: func(e *env) string { return e.tokenA },
|
||||
@@ -249,26 +321,162 @@ func TestPushCreatedRecordIsOwnedByCaller(t *testing.T) {
|
||||
}).Test(t)
|
||||
}
|
||||
|
||||
func TestPushBatchIsAtomic(t *testing.T) {
|
||||
func TestPushInvalidChangeDoesNotFailTheBatch(t *testing.T) {
|
||||
e := setup(t)
|
||||
// The second change fails validation (malformed day_key), so the first one must be rolled back too.
|
||||
// The second change fails the validation, so it is reported as invalid while
|
||||
// the first one of the same batch is applied.
|
||||
batch := body(entry(recB, "new", 5, false), `{"collection":"entries","id":"`+recA+`","data":{"start_time":1000,"end_time":2000,"note":"upd","day_key":"2026-1-5"},"client_updated_at":2000,"deleted":false}`)
|
||||
(&tests.ApiScenario{
|
||||
Name: "a failing change rolls back the whole batch",
|
||||
Method: http.MethodPost,
|
||||
URL: "/api/sync/push",
|
||||
Body: batch,
|
||||
Headers: map[string]string{"Authorization": e.tokenA},
|
||||
ExpectedStatus: 400,
|
||||
ExpectedContent: []string{`"Failed to apply changes.`},
|
||||
TestAppFactory: func(testing.TB) *tests.TestApp { return e.app },
|
||||
Name: "an invalid change is rejected without failing the batch",
|
||||
Method: http.MethodPost,
|
||||
URL: "/api/sync/push",
|
||||
Body: batch,
|
||||
Headers: map[string]string{"Authorization": e.tokenA},
|
||||
ExpectedStatus: 200,
|
||||
ExpectedContent: []string{
|
||||
`"id":"` + recB + `","collection":"entries","status":"ok"`,
|
||||
`"id":"` + recA + `","collection":"entries","status":"invalid","error":"day_key: Invalid value format"}`,
|
||||
},
|
||||
TestAppFactory: func(testing.TB) *tests.TestApp { return e.app },
|
||||
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
|
||||
checkNoRecord("entries", recB)(t, app, res)
|
||||
checkRecord("entries", recA, map[string]any{"note": "orig", "rev": 1})(t, app, res)
|
||||
checkRecord("entries", recB, map[string]any{"note": "new", "rev": 1})(t, app, res)
|
||||
checkRecord("entries", recA, map[string]any{"note": "orig", "rev": 1, "day_key": "2026-01-05"})(t, app, res)
|
||||
},
|
||||
}).Test(t)
|
||||
}
|
||||
|
||||
func TestPushRejectsInvalidChanges(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
collection string
|
||||
data string
|
||||
status string
|
||||
errMsg string
|
||||
}{
|
||||
{
|
||||
name: "running entry", collection: "entries",
|
||||
data: `"start_time":1000,"end_time":0,"auto_stopped":false,"note":"","day_key":"2026-01-05"`, status: "ok",
|
||||
},
|
||||
{
|
||||
name: "end before start", collection: "entries",
|
||||
data: `"start_time":2000,"end_time":1000,"auto_stopped":false,"note":"","day_key":"2026-01-05"`,
|
||||
status: "invalid", errMsg: "end_time must be 0 or not before start_time",
|
||||
},
|
||||
{
|
||||
name: "negative start", collection: "entries",
|
||||
data: `"start_time":-1,"end_time":0,"auto_stopped":false,"note":"","day_key":"2026-01-05"`,
|
||||
status: "invalid", errMsg: "start_time: Must be greater or equal than 0",
|
||||
},
|
||||
{
|
||||
name: "unknown timezone", collection: "settings_history",
|
||||
data: `"effective_from":"2026-01-01","hours_per_week":40,"workdays_mask":31,"timezone":"Mars/Olympus"`,
|
||||
status: "invalid", errMsg: `timezone "Mars/Olympus" is not a known IANA time zone`,
|
||||
},
|
||||
{
|
||||
name: "effective_from not a date", collection: "settings_history",
|
||||
data: `"effective_from":"2026-02-30","hours_per_week":40,"workdays_mask":31,"timezone":"UTC"`,
|
||||
status: "invalid", errMsg: `effective_from "2026-02-30" is not a calendar date`,
|
||||
},
|
||||
{
|
||||
name: "no workday", collection: "settings_history",
|
||||
data: `"effective_from":"2026-01-01","hours_per_week":40,"workdays_mask":0,"timezone":"UTC"`,
|
||||
status: "invalid", errMsg: "workdays_mask must be between 1 and 127",
|
||||
},
|
||||
{
|
||||
name: "zero adjustment", collection: "balance_adjustments",
|
||||
data: `"delta_ms":0,"note":"","effective_at":1`,
|
||||
status: "invalid", errMsg: "delta_ms must not be 0",
|
||||
},
|
||||
{
|
||||
name: "correction", collection: "balance_adjustments",
|
||||
data: `"delta_ms":-3600000,"note":"","effective_at":1`, status: "ok",
|
||||
},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
e := setup(t)
|
||||
content := []string{`"status":"` + c.status + `"`}
|
||||
if c.errMsg != "" {
|
||||
content = append(content, `"error":`+jsonString(c.errMsg))
|
||||
}
|
||||
after := checkNoRecord(c.collection, recB)
|
||||
if c.status == "ok" {
|
||||
after = checkRecord(c.collection, recB, map[string]any{"rev": 1})
|
||||
}
|
||||
(&tests.ApiScenario{
|
||||
Name: c.name,
|
||||
Method: http.MethodPost,
|
||||
URL: "/api/sync/push",
|
||||
Body: body(change(c.collection, recB, c.data, 5, false)),
|
||||
Headers: map[string]string{"Authorization": e.tokenA},
|
||||
ExpectedStatus: 200,
|
||||
ExpectedContent: content,
|
||||
TestAppFactory: func(testing.TB) *tests.TestApp { return e.app },
|
||||
AfterTestFunc: after,
|
||||
}).Test(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPushResurrectsDeletedRecord(t *testing.T) {
|
||||
e := setup(t)
|
||||
gone, err := e.app.FindRecordById("entries", recA)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gone.Set("deleted", true)
|
||||
if err := e.app.Save(gone); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
(&tests.ApiScenario{
|
||||
Name: "a soft deleted record is revived",
|
||||
Method: http.MethodPost,
|
||||
URL: "/api/sync/push",
|
||||
Body: body(entry(recA, "back", 2000, false)),
|
||||
Headers: map[string]string{"Authorization": e.tokenA},
|
||||
ExpectedStatus: 200,
|
||||
ExpectedContent: []string{`"status":"ok"`, `"rev":2`, `"deleted":false`, `"note":"back"`},
|
||||
TestAppFactory: func(testing.TB) *tests.TestApp { return e.app },
|
||||
AfterTestFunc: checkRecord("entries", recA, map[string]any{"deleted": false, "rev": 2, "note": "back"}),
|
||||
}).Test(t)
|
||||
}
|
||||
|
||||
func TestPushEqualClientUpdatedAtApplies(t *testing.T) {
|
||||
e := setup(t)
|
||||
// The seeded row has client_updated_at 1000, so the change is not stale.
|
||||
(&tests.ApiScenario{
|
||||
Name: "a change with the client_updated_at of the server row is applied",
|
||||
Method: http.MethodPost,
|
||||
URL: "/api/sync/push",
|
||||
Body: body(entry(recA, "same", 1000, false)),
|
||||
Headers: map[string]string{"Authorization": e.tokenA},
|
||||
ExpectedStatus: 200,
|
||||
ExpectedContent: []string{`"status":"ok"`, `"rev":2`, `"note":"same"`},
|
||||
NotExpectedContent: []string{`"status":"stale"`},
|
||||
TestAppFactory: func(testing.TB) *tests.TestApp { return e.app },
|
||||
AfterTestFunc: checkRecord("entries", recA, map[string]any{"note": "same", "rev": 2}),
|
||||
}).Test(t)
|
||||
}
|
||||
|
||||
func TestPushTooManyChanges(t *testing.T) {
|
||||
e := setup(t)
|
||||
changes := make([]string, syncapi.MaxChanges+1)
|
||||
for i := range changes {
|
||||
changes[i] = entry(recB, "new", 5, false)
|
||||
}
|
||||
(&tests.ApiScenario{
|
||||
Name: "more than MaxChanges changes",
|
||||
Method: http.MethodPost,
|
||||
URL: "/api/sync/push",
|
||||
Body: body(changes...),
|
||||
Headers: map[string]string{"Authorization": e.tokenA},
|
||||
ExpectedStatus: 400,
|
||||
ExpectedContent: []string{"Too many changes (max " + fmt.Sprint(syncapi.MaxChanges) + ")"},
|
||||
TestAppFactory: func(testing.TB) *tests.TestApp { return e.app },
|
||||
AfterTestFunc: checkNoRecord("entries", recB),
|
||||
}).Test(t)
|
||||
}
|
||||
func TestPushSettingsDelete(t *testing.T) {
|
||||
seedSettings := func(e *env, ids ...string) {
|
||||
for _, id := range ids {
|
||||
|
||||
Reference in New Issue
Block a user