fix: address performance and security findings
- Add PostgreSQL-backed backend and frontend tests to CI - Harden Android API logging and disable app backups - Update the performance report with resolved findings
This commit is contained in:
1 parent
a84a36349b
commit
937f51b4fb
35 files changed
+2566
-332
No files matched your search
+191
-176
@@ -9,6 +9,10 @@ import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// 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
|
||||
|
||||
func syncMaxFutureSkew() int64 {
|
||||
value := envInt64("SYNC_MAX_FUTURE_SKEW_MS", 0)
|
||||
if value < 0 {
|
||||
@@ -91,16 +95,193 @@ func valueReferences(ctx context.Context, tx pgx.Tx, values []ItemValue) (map[st
|
||||
return fieldLists, existingItems, nil
|
||||
}
|
||||
|
||||
// changeEventType names a synced change for the notification feed: a tombstone
|
||||
// is "deleted", a first sync reports "created", and anything else "updated".
|
||||
func changeEventType(initialSync, deleted bool) string {
|
||||
if deleted {
|
||||
return "deleted"
|
||||
}
|
||||
if initialSync {
|
||||
return "created"
|
||||
}
|
||||
return "updated"
|
||||
}
|
||||
|
||||
// syncBatch holds what every row of one sync request shares.
|
||||
type syncBatch struct {
|
||||
now int64
|
||||
initialSync bool
|
||||
deviceID string
|
||||
}
|
||||
|
||||
func (b syncBatch) notify(ctx context.Context, tx pgx.Tx, eventType, entityType, entityID, listID string, createdAt int64) {
|
||||
ignoreNotificationError(enqueueNotificationInTx(ctx, tx, b.deviceID, eventType, entityType, entityID, listID, createdAt))
|
||||
}
|
||||
|
||||
// applyLists upserts the pushed lists. A write older than the stored row
|
||||
// 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 {
|
||||
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 !applied {
|
||||
continue
|
||||
}
|
||||
batch.notify(ctx, tx, changeEventType(batch.initialSync, list.IsDeleted), "list", list.ID, list.ID, updatedAt)
|
||||
|
||||
if list.IsDeleted {
|
||||
if err := cascadeDeleteList(ctx, tx, list.ID, updatedAt); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func applyFields(ctx context.Context, tx pgx.Tx, fields []Field, batch syncBatch) error {
|
||||
for _, field := range fields {
|
||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(field.CreatedAt), int64(field.UpdatedAt), batch.now)
|
||||
applied, err := upsertField(ctx, tx, field, createdAt, updatedAt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !applied {
|
||||
continue
|
||||
}
|
||||
batch.notify(ctx, tx, changeEventType(batch.initialSync, field.IsDeleted), "field", field.ID, field.ListID, updatedAt)
|
||||
|
||||
if field.IsDeleted {
|
||||
if _, err := cascadeDeleteField(ctx, tx, field.ID, field.ListID, updatedAt); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func applyItems(ctx context.Context, tx pgx.Tx, items []Item, batch syncBatch) error {
|
||||
for _, item := range items {
|
||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(item.CreatedAt), int64(item.UpdatedAt), batch.now)
|
||||
applied, err := upsertItem(ctx, tx, item, createdAt, updatedAt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !applied {
|
||||
continue
|
||||
}
|
||||
batch.notify(ctx, tx, changeEventType(batch.initialSync, item.IsDeleted), "item", item.ID, item.ListID, updatedAt)
|
||||
if item.IsDeleted {
|
||||
if err := cascadeDeleteItem(ctx, tx, item.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// applyValues upserts the pushed item values and returns the ones it could not
|
||||
// place. Items are read after applyItems has run, so a request's own item inserts
|
||||
// are visible.
|
||||
func applyValues(ctx context.Context, tx pgx.Tx, values []ItemValue, batch syncBatch) ([]OrphanValue, error) {
|
||||
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)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, value := range values {
|
||||
updatedAt := normalizeTimestamp(int64(value.UpdatedAt), batch.now, batch.now)
|
||||
listID, ok := fieldLists[value.FieldID]
|
||||
if !ok {
|
||||
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "missingField"})
|
||||
continue
|
||||
}
|
||||
|
||||
if !existingItems[value.ItemID] {
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $3, 0)
|
||||
ON CONFLICT (id) DO NOTHING
|
||||
`, value.ItemID, listID, updatedAt); err != nil {
|
||||
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "failedCreateStubItem"})
|
||||
continue
|
||||
}
|
||||
existingItems[value.ItemID] = true
|
||||
}
|
||||
applied, err := upsertValue(ctx, tx, value, updatedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !applied {
|
||||
continue
|
||||
}
|
||||
batch.notify(ctx, tx, "listContentUpdated", "value", value.ID, listID, updatedAt)
|
||||
}
|
||||
return orphans, nil
|
||||
}
|
||||
|
||||
// applySyncRequest writes everything a device pushed, parents before children.
|
||||
func applySyncRequest(ctx context.Context, tx pgx.Tx, request SyncRequest, batch syncBatch) ([]OrphanValue, error) {
|
||||
if err := applyLists(ctx, tx, request.Lists, batch); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := applyFields(ctx, tx, request.Fields, batch); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := applyItems(ctx, tx, request.Items, batch); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
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)
|
||||
if err != nil {
|
||||
return SyncResponse{}, err
|
||||
}
|
||||
fields, err := d.queryFields(ctx, true, since, "")
|
||||
if err != nil {
|
||||
return SyncResponse{}, err
|
||||
}
|
||||
items, err := d.queryItems(ctx, true, since, "")
|
||||
if 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
|
||||
}
|
||||
|
||||
func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
||||
// Bound the number of syncs in flight, so large bodies and transactions cannot
|
||||
// take every database connection at once.
|
||||
select {
|
||||
case s.syncSlots <- struct{}{}:
|
||||
defer func() { <-s.syncSlots }()
|
||||
case <-r.Context().Done():
|
||||
writeJSONError(w, http.StatusServiceUnavailable, "Sync busy")
|
||||
return
|
||||
}
|
||||
|
||||
var request SyncRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid sync request")
|
||||
if err := decodeJSONLimit(w, r, &request, syncBodyLimit); err != nil {
|
||||
writeDecodeError(w, err, "Invalid sync request")
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now().UnixMilli()
|
||||
lastSync := normalizeTimestamp(int64(request.LastSyncTimestamp), 0, now)
|
||||
deviceID := requestDeviceID(r, request.DeviceID)
|
||||
batch := syncBatch{now: now, initialSync: lastSync == 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 {
|
||||
@@ -108,154 +289,9 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
for _, list := range request.Lists {
|
||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(list.CreatedAt), int64(list.UpdatedAt), now)
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
INSERT INTO lists (id, name, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET name = EXCLUDED.name, updatedat = EXCLUDED.updatedat, isdeleted = EXCLUDED.isdeleted
|
||||
`, list.ID, list.Name, createdAt, updatedAt, boolInt(list.IsDeleted)); err != nil {
|
||||
return err
|
||||
}
|
||||
event := "updated"
|
||||
if lastSync == 0 {
|
||||
event = "created"
|
||||
}
|
||||
if list.IsDeleted {
|
||||
event = "deleted"
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, event, "list", list.ID, list.ID, updatedAt))
|
||||
|
||||
if list.IsDeleted {
|
||||
if _, err := tx.Exec(r.Context(), `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, list.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, list.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, list.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, field := range request.Fields {
|
||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(field.CreatedAt), int64(field.UpdatedAt), now)
|
||||
fieldType := field.FieldType
|
||||
if fieldType == "" {
|
||||
fieldType = "TEXT"
|
||||
}
|
||||
alignment := field.Alignment
|
||||
if alignment == "" {
|
||||
alignment = "start"
|
||||
}
|
||||
if _, 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)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET name = EXCLUDED.name,
|
||||
fieldtype = EXCLUDED.fieldtype,
|
||||
fieldoptions = EXCLUDED.fieldoptions,
|
||||
alignment = EXCLUDED.alignment,
|
||||
"order" = EXCLUDED."order",
|
||||
updatedat = EXCLUDED.updatedat,
|
||||
isdeleted = EXCLUDED.isdeleted
|
||||
`, field.ID, field.Name, fieldType, field.FieldOptions, alignment, field.ListID, field.Order, createdAt, updatedAt, boolInt(field.IsDeleted)); err != nil {
|
||||
return err
|
||||
}
|
||||
event := "updated"
|
||||
if lastSync == 0 {
|
||||
event = "created"
|
||||
}
|
||||
if field.IsDeleted {
|
||||
event = "deleted"
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, event, "field", field.ID, field.ListID, updatedAt))
|
||||
|
||||
if field.IsDeleted {
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE fieldid = $1`, field.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
var remaining int
|
||||
if err := tx.QueryRow(r.Context(), `SELECT count(*) FROM fields WHERE listid = $1 AND isdeleted = 0`, field.ListID).Scan(&remaining); err != nil {
|
||||
return err
|
||||
}
|
||||
if remaining == 0 {
|
||||
if _, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, field.ListID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, field.ListID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, item := range request.Items {
|
||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(item.CreatedAt), int64(item.UpdatedAt), now)
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET updatedat = EXCLUDED.updatedat, isdeleted = EXCLUDED.isdeleted
|
||||
`, item.ID, item.ListID, createdAt, updatedAt, boolInt(item.IsDeleted)); err != nil {
|
||||
return err
|
||||
}
|
||||
event := "updated"
|
||||
if lastSync == 0 {
|
||||
event = "created"
|
||||
}
|
||||
if item.IsDeleted {
|
||||
event = "deleted"
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, event, "item", item.ID, item.ListID, updatedAt))
|
||||
if item.IsDeleted {
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid = $1`, item.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve the fields and items the values refer to once per request, not once
|
||||
// per value. Items are read after the item loop above, so this request's own
|
||||
// item inserts are visible.
|
||||
fieldLists, existingItems, err := valueReferences(r.Context(), tx, request.ItemValues)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, value := range request.ItemValues {
|
||||
updatedAt := normalizeTimestamp(int64(value.UpdatedAt), now, now)
|
||||
listID, ok := fieldLists[value.FieldID]
|
||||
if !ok {
|
||||
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "missingField"})
|
||||
continue
|
||||
}
|
||||
|
||||
if !existingItems[value.ItemID] {
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $3, 0)
|
||||
ON CONFLICT (id) DO NOTHING
|
||||
`, value.ItemID, listID, updatedAt); err != nil {
|
||||
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "failedCreateStubItem"})
|
||||
continue
|
||||
}
|
||||
existingItems[value.ItemID] = true
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
INSERT INTO item_values (id, itemid, fieldid, value, updatedat)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET value = EXCLUDED.value, updatedat = EXCLUDED.updatedat
|
||||
`, value.ID, value.ItemID, value.FieldID, value.Value, updatedAt); err != nil {
|
||||
return err
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, "listContentUpdated", "value", value.ID, listID, updatedAt))
|
||||
}
|
||||
return nil
|
||||
var err error
|
||||
orphans, err = applySyncRequest(r.Context(), tx, request, batch)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Printf("[SYNC] Failed: %v\n", err)
|
||||
@@ -267,33 +303,12 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
||||
if lastSync != 0 {
|
||||
since = &lastSync
|
||||
}
|
||||
lists, err := s.db.queryLists(r.Context(), true, since)
|
||||
response, err := s.db.changesSince(r.Context(), since)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||
return
|
||||
}
|
||||
fields, err := s.db.queryFields(r.Context(), true, since, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||
return
|
||||
}
|
||||
items, err := s.db.queryItems(r.Context(), true, since, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||
return
|
||||
}
|
||||
values, err := s.db.queryValues(r.Context(), since, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, SyncResponse{
|
||||
Lists: lists,
|
||||
Fields: fields,
|
||||
Items: items,
|
||||
ItemValues: values,
|
||||
OrphanItemValues: orphans,
|
||||
ServerTimestamp: time.Now().UnixMilli(),
|
||||
})
|
||||
response.OrphanItemValues = orphans
|
||||
response.ServerTimestamp = time.Now().UnixMilli()
|
||||
writeJSON(w, http.StatusOK, response)
|
||||
}
|
||||
Reference in new issue
Block a user