✨ Add batch push endpoint for synced collections
POST /api/sync/push applies up to 500 client changes of a signed-in user in one transaction. Every change is answered with ok, stale, forbidden or readonly, so the client can reconcile its local state with the server state. closed_days and closed_weeks are answered as readonly because only the server computes them. The last remaining settings row of a user cannot be deleted either; such a change is answered as stale, which clients already treat as "server wins".
This commit is contained in:
@@ -5,6 +5,7 @@ go 1.27
|
|||||||
require (
|
require (
|
||||||
github.com/go-chi/chi/v5 v5.3.2
|
github.com/go-chi/chi/v5 v5.3.2
|
||||||
github.com/google/uuid v1.6.0
|
github.com/google/uuid v1.6.0
|
||||||
|
github.com/pocketbase/dbx v1.12.0
|
||||||
github.com/pocketbase/pocketbase v0.40.6
|
github.com/pocketbase/pocketbase v0.40.6
|
||||||
github.com/spf13/cobra v1.10.2
|
github.com/spf13/cobra v1.10.2
|
||||||
modernc.org/sqlite v1.60.1
|
modernc.org/sqlite v1.60.1
|
||||||
@@ -25,7 +26,6 @@ require (
|
|||||||
github.com/mattn/go-colorable v0.1.16 // indirect
|
github.com/mattn/go-colorable v0.1.16 // indirect
|
||||||
github.com/mattn/go-isatty v0.0.24 // indirect
|
github.com/mattn/go-isatty v0.0.24 // indirect
|
||||||
github.com/ncruces/go-strftime v1.1.0 // indirect
|
github.com/ncruces/go-strftime v1.1.0 // indirect
|
||||||
github.com/pocketbase/dbx v1.12.0 // indirect
|
|
||||||
github.com/pocketbase/ozzo-validation/v4 v4.3.0 // indirect
|
github.com/pocketbase/ozzo-validation/v4 v4.3.0 // indirect
|
||||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||||
github.com/spf13/cast v1.10.0 // indirect
|
github.com/spf13/cast v1.10.0 // indirect
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package syncapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/pocketbase/pocketbase/core"
|
||||||
|
"github.com/wotra/wotra/internal/collections"
|
||||||
|
)
|
||||||
|
|
||||||
|
func RegisterHooks(app core.App) {
|
||||||
|
app.OnRecordCreateRequest(collections.Synced...).BindFunc(func(e *core.RecordRequestEvent) error {
|
||||||
|
if e.Auth != nil && !e.HasSuperuserAuth() {
|
||||||
|
e.Record.Set("owner", e.Auth.Id)
|
||||||
|
}
|
||||||
|
e.Record.Set("rev", 1)
|
||||||
|
return e.Next()
|
||||||
|
})
|
||||||
|
app.OnRecordUpdateRequest(collections.Synced...).BindFunc(func(e *core.RecordRequestEvent) error {
|
||||||
|
orig := e.Record.Original()
|
||||||
|
e.Record.Set("owner", orig.GetString("owner"))
|
||||||
|
e.Record.Set("rev", orig.GetInt("rev")+1)
|
||||||
|
return e.Next()
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
package syncapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"regexp"
|
||||||
|
"slices"
|
||||||
|
|
||||||
|
"github.com/pocketbase/dbx"
|
||||||
|
"github.com/pocketbase/pocketbase/apis"
|
||||||
|
"github.com/pocketbase/pocketbase/core"
|
||||||
|
|
||||||
|
"github.com/wotra/wotra/internal/collections"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
MaxChanges = 500
|
||||||
|
MaxBodyBytes = 32 << 20
|
||||||
|
)
|
||||||
|
|
||||||
|
// Status codes reported back per change.
|
||||||
|
const (
|
||||||
|
statusOK = "ok"
|
||||||
|
statusStale = "stale"
|
||||||
|
statusForbidden = "forbidden"
|
||||||
|
statusReadOnly = "readonly"
|
||||||
|
)
|
||||||
|
|
||||||
|
var idPattern = regexp.MustCompile(`^[a-z0-9]{15}$`)
|
||||||
|
|
||||||
|
type Change struct {
|
||||||
|
Collection string `json:"collection"`
|
||||||
|
Id string `json:"id"`
|
||||||
|
Data map[string]any `json:"data"`
|
||||||
|
ClientUpdatedAt int64 `json:"client_updated_at"`
|
||||||
|
Deleted bool `json:"deleted"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PushRequest struct {
|
||||||
|
Changes []Change `json:"changes"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Result struct {
|
||||||
|
Id string `json:"id"`
|
||||||
|
Collection string `json:"collection"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Record *core.Record `json:"record,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func Register(app core.App) {
|
||||||
|
RegisterHooks(app)
|
||||||
|
app.OnServe().BindFunc(func(se *core.ServeEvent) error {
|
||||||
|
se.Router.POST("/api/sync/push", handlePush).
|
||||||
|
Bind(apis.RequireAuth("users"), apis.BodyLimit(MaxBodyBytes))
|
||||||
|
return se.Next()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func validate(req *PushRequest) error {
|
||||||
|
if len(req.Changes) > MaxChanges {
|
||||||
|
return fmt.Errorf("too many changes (max %d)", MaxChanges)
|
||||||
|
}
|
||||||
|
for i, c := range req.Changes {
|
||||||
|
if !collections.IsSynced(c.Collection) {
|
||||||
|
return fmt.Errorf("changes[%d]: invalid collection %q", i, c.Collection)
|
||||||
|
}
|
||||||
|
if !idPattern.MatchString(c.Id) {
|
||||||
|
return fmt.Errorf("changes[%d]: invalid id", i)
|
||||||
|
}
|
||||||
|
if c.ClientUpdatedAt < 0 {
|
||||||
|
return fmt.Errorf("changes[%d]: invalid client_updated_at", i)
|
||||||
|
}
|
||||||
|
for field := range c.Data {
|
||||||
|
if !slices.Contains(collections.DataFields[c.Collection], field) {
|
||||||
|
return fmt.Errorf("changes[%d]: unknown field %q", i, field)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func handlePush(e *core.RequestEvent) error {
|
||||||
|
var req PushRequest
|
||||||
|
if err := e.BindBody(&req); err != nil {
|
||||||
|
return e.BadRequestError("Invalid request body.", err)
|
||||||
|
}
|
||||||
|
if err := validate(&req); err != nil {
|
||||||
|
return e.BadRequestError(err.Error(), nil)
|
||||||
|
}
|
||||||
|
authId := e.Auth.Id
|
||||||
|
results := make([]Result, 0, len(req.Changes))
|
||||||
|
err := e.App.RunInTransaction(func(tx core.App) error {
|
||||||
|
for _, c := range req.Changes {
|
||||||
|
res, err := apply(tx, authId, c)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
results = append(results, res)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return e.BadRequestError("Failed to apply changes.", err)
|
||||||
|
}
|
||||||
|
return e.JSON(http.StatusOK, map[string]any{"results": results})
|
||||||
|
}
|
||||||
|
|
||||||
|
func apply(tx core.App, authId string, c Change) (Result, error) {
|
||||||
|
res := Result{Id: c.Id, Collection: c.Collection}
|
||||||
|
if collections.IsReadOnly(c.Collection) {
|
||||||
|
res.Status = statusReadOnly
|
||||||
|
return res, nil
|
||||||
|
}
|
||||||
|
existing, err := tx.FindRecordById(c.Collection, c.Id)
|
||||||
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
if existing == nil {
|
||||||
|
col, err := tx.FindCachedCollectionByNameOrId(c.Collection)
|
||||||
|
if err != nil {
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
r := core.NewRecord(col)
|
||||||
|
r.Id = c.Id
|
||||||
|
r.Set("owner", authId)
|
||||||
|
setData(r, c)
|
||||||
|
r.Set("client_updated_at", c.ClientUpdatedAt)
|
||||||
|
r.Set("deleted", c.Deleted)
|
||||||
|
r.Set("rev", 1)
|
||||||
|
if err := tx.Save(r); err != nil {
|
||||||
|
return res, fmt.Errorf("%s/%s: %w", c.Collection, c.Id, err)
|
||||||
|
}
|
||||||
|
res.Status = statusOK
|
||||||
|
res.Record = r
|
||||||
|
return res, nil
|
||||||
|
}
|
||||||
|
if existing.GetString("owner") != authId {
|
||||||
|
res.Status = statusForbidden
|
||||||
|
return res, nil
|
||||||
|
}
|
||||||
|
if c.ClientUpdatedAt < existing.GetInt64("client_updated_at") {
|
||||||
|
res.Status = statusStale
|
||||||
|
res.Record = existing
|
||||||
|
return res, nil
|
||||||
|
}
|
||||||
|
if c.Deleted && !existing.GetBool("deleted") && c.Collection == "settings_history" {
|
||||||
|
keep, err := isLastLiveSettings(tx, authId, c.Id)
|
||||||
|
if err != nil {
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
if keep {
|
||||||
|
res.Status = statusStale
|
||||||
|
res.Record = existing
|
||||||
|
return res, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setData(existing, c)
|
||||||
|
existing.Set("client_updated_at", c.ClientUpdatedAt)
|
||||||
|
existing.Set("deleted", c.Deleted)
|
||||||
|
existing.Set("rev", existing.GetInt("rev")+1)
|
||||||
|
if err := tx.Save(existing); err != nil {
|
||||||
|
return res, fmt.Errorf("%s/%s: %w", c.Collection, c.Id, err)
|
||||||
|
}
|
||||||
|
res.Status = statusOK
|
||||||
|
res.Record = existing
|
||||||
|
return res, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// setData copies the client-writable fields of the change onto the record.
|
||||||
|
// Fields missing from the change data are reset to their zero value.
|
||||||
|
func setData(r *core.Record, c Change) {
|
||||||
|
for _, field := range collections.DataFields[c.Collection] {
|
||||||
|
r.Set(field, c.Data[field])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// isLastLiveSettings reports whether id is the only non-deleted settings row of the owner.
|
||||||
|
func isLastLiveSettings(tx core.App, ownerId, id string) (bool, error) {
|
||||||
|
_, err := tx.FindFirstRecordByFilter("settings_history",
|
||||||
|
"owner = {:owner} && id != {:id} && deleted = false",
|
||||||
|
dbx.Params{"owner": ownerId, "id": id},
|
||||||
|
)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user