✨ 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:
@@ -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