@jcbuisson/express-x-drizzle 3.1.6 → 3.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CLAUDE.md CHANGED
@@ -24,6 +24,6 @@ The library exports one function: `drizzleOfflinePlugin(app, db, metadata, model
24
24
 
25
25
  1. **Per-model services** — For each table in `models`, registers an `express-x` service named after the table. Each service exposes: `findUnique`, `findMany`, `createWithMeta`, `updateWithMeta`, `deleteWithMeta`. All mutation methods write to both the model table and the `metadata` table inside a transaction, keeping timestamps in sync.
26
26
 
27
- 2. **`sync` service** — Implements an offline-first reconciliation algorithm. The client sends its local metadata dictionary (`{ uid → { created_at, updated_at, deleted_at } }`) plus a `cutoffDate`. The server computes set intersections between client UIDs and database UIDs, then determines add/update/delete operations for both sides. A `Mutex` (from `express-x`) serializes concurrent sync calls globally. The return value tells the client which records to add, update, or delete locally, and which UIDs the client should push to the database with full data.
27
+ 2. **`sync` service** — Implements an offline-first reconciliation algorithm. The client sends its local metadata dictionary (`{ uid → { created_at, updated_at, deleted_at } }`). The server computes set intersections between client UIDs and database UIDs, then determines add/update/delete operations for both sides. An overlap-aware lock serializes sync calls whose `where` scopes can touch the same records. The return value tells the client which records to add, update, or delete locally, and which UIDs the client should push to the database with full data.
28
28
 
29
29
  **Key invariant:** The sync algorithm compares `updated_at` (falling back to `created_at`) timestamps to decide which side wins a conflict — the most recently updated side wins. Records marked `deleted_at` on the client trigger a soft-delete propagation to the database.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jcbuisson/express-x-drizzle",
3
- "version": "3.1.6",
3
+ "version": "3.1.12",
4
4
  "description": "Drizzle ORM plugins for express-x framework",
5
5
  "main": "src/drizzle-plugins.mjs",
6
6
  "type": "module",
@@ -1,21 +1,10 @@
1
1
  import { and, eq, gt, gte, lt, lte, isNull, getTableName } from "drizzle-orm";
2
2
 
3
- import { Mutex, truncateString, computeSyncResult } from '@jcbuisson/express-x'
3
+ import { truncateString, computeSyncResult } from '@jcbuisson/express-x'
4
4
 
5
5
 
6
6
  ////////////////////////// UTILITIES //////////////////////////
7
7
 
8
- function stringifyWithSortedKeys(obj) {
9
- return JSON.stringify(obj, (_, value) => {
10
- if (value && typeof value === 'object' && !Array.isArray(value) && Object.prototype.toString.call(value) === '[object Object]') {
11
- const sorted = {}
12
- Object.keys(value).sort().forEach(k => { sorted[k] = value[k] })
13
- return sorted
14
- }
15
- return value
16
- })
17
- }
18
-
19
8
  function whereToDrizzleFilters(table, where) {
20
9
  const conditions = Object.entries(where)
21
10
  .filter(([_, value]) => value !== undefined)
@@ -35,8 +24,98 @@ function whereToDrizzleFilters(table, where) {
35
24
  return conditions.length ? and(...conditions) : undefined;
36
25
  }
37
26
 
27
+ function isPlainObject(value) {
28
+ return value && typeof value === 'object' && !Array.isArray(value) && Object.prototype.toString.call(value) === '[object Object]'
29
+ }
30
+
31
+ function hasRangeOperator(value) {
32
+ return isPlainObject(value) && ['gte', 'gt', 'lte', 'lt'].some(key => key in value)
33
+ }
34
+
35
+ function valueWithinRange(value, range) {
36
+ if (value === null || value === undefined) return false
37
+ if ('gte' in range && value < range.gte) return false
38
+ if ('gt' in range && value <= range.gt) return false
39
+ if ('lte' in range && value > range.lte) return false
40
+ if ('lt' in range && value >= range.lt) return false
41
+ return true
42
+ }
43
+
44
+ function rangesOverlap(a, b) {
45
+ const lower = [
46
+ 'gte' in a && { value: a.gte, inclusive: true },
47
+ 'gt' in a && { value: a.gt, inclusive: false },
48
+ 'gte' in b && { value: b.gte, inclusive: true },
49
+ 'gt' in b && { value: b.gt, inclusive: false },
50
+ ].filter(Boolean).sort((x, y) => x.value === y.value ? Number(x.inclusive) - Number(y.inclusive) : x.value > y.value ? -1 : 1)[0]
51
+
52
+ const upper = [
53
+ 'lte' in a && { value: a.lte, inclusive: true },
54
+ 'lt' in a && { value: a.lt, inclusive: false },
55
+ 'lte' in b && { value: b.lte, inclusive: true },
56
+ 'lt' in b && { value: b.lt, inclusive: false },
57
+ ].filter(Boolean).sort((x, y) => x.value === y.value ? Number(x.inclusive) - Number(y.inclusive) : x.value < y.value ? -1 : 1)[0]
58
+
59
+ if (!lower || !upper) return true
60
+ if (lower.value < upper.value) return true
61
+ if (lower.value > upper.value) return false
62
+ return lower.inclusive && upper.inclusive
63
+ }
64
+
65
+ function constraintsOverlap(a, b) {
66
+ if (a === undefined || b === undefined) return true
67
+ if (a === null || b === null) return a === null && b === null
68
+
69
+ const aRange = hasRangeOperator(a)
70
+ const bRange = hasRangeOperator(b)
71
+
72
+ if (aRange && bRange) return rangesOverlap(a, b)
73
+ if (aRange) return valueWithinRange(b, a)
74
+ if (bRange) return valueWithinRange(a, b)
75
+ if (isPlainObject(a) || isPlainObject(b)) return true
76
+ return a === b
77
+ }
78
+
79
+ function whereScopesOverlap(a = {}, b = {}) {
80
+ const sharedKeys = Object.keys(a).filter(key => key in b)
81
+ for (const key of sharedKeys) {
82
+ if (!constraintsOverlap(a[key], b[key])) return false
83
+ }
84
+ return true
85
+ }
86
+
87
+ class OverlapLock {
88
+ constructor() {
89
+ this.active = []
90
+ this.queue = []
91
+ }
92
+
93
+ acquire(where) {
94
+ return new Promise(resolve => {
95
+ const entry = { where, resolve }
96
+ this.queue.push(entry)
97
+ this.pump()
98
+ })
99
+ }
38
100
 
39
- // DOIT FAIRE UN ROLLBACK EN CAS D'ERREUR SERVEUR (EX: ERREUR SÉMANTIQUE TYPE PB CLÉ ÉTRANGÈRE OU AUTRE)
101
+ pump() {
102
+ for (let i = 0; i < this.queue.length; i++) {
103
+ const entry = this.queue[i]
104
+ if (this.active.some(active => whereScopesOverlap(active.where, entry.where))) continue
105
+ this.queue.splice(i, 1)
106
+ i -= 1
107
+ this.active.push(entry)
108
+ entry.resolve(() => {
109
+ this.active = this.active.filter(active => active !== entry)
110
+ this.pump()
111
+ })
112
+ }
113
+ }
114
+
115
+ get idle() {
116
+ return this.active.length === 0 && this.queue.length === 0
117
+ }
118
+ }
40
119
 
41
120
 
42
121
  ////////////////////////// DRIZZLE OFFLINE PLUGIN //////////////////////////
@@ -109,22 +188,20 @@ export function drizzleOfflinePlugin(app, db, metadata, models) {
109
188
  })
110
189
  }
111
190
 
112
- const syncMutexes = new Map()
191
+ const syncLocks = new Map()
113
192
 
114
193
  // add a synchronization service
115
194
  app.createService('sync', {
116
195
 
117
- // CUTOFFDATE INUTILE ?
118
- go: async (modelName, where, cutoffDate, clientMetadataDict) => {
196
+ go: async (modelName, where, clientMetadataDict) => {
119
197
 
120
- // get or create a mutex specific to modelName + where
121
- const mutexKey = `${modelName}:${stringifyWithSortedKeys(where)}`
122
- if (!syncMutexes.has(mutexKey)) syncMutexes.set(mutexKey, new Mutex())
123
- // acquire it: no other sync operation from another client on this model+where can occur in parallel
124
- await syncMutexes.get(mutexKey).acquire()
198
+ // overlap-aware lock so independent scopes can still run in parallel, but overlapping where predicates do not
199
+ if (!syncLocks.has(modelName)) syncLocks.set(modelName, new OverlapLock())
200
+ const syncLock = syncLocks.get(modelName)
201
+ const releaseSyncLock = await syncLock.acquire(where)
125
202
 
126
203
  try {
127
- console.log('>>>>> SYNC', modelName, where, cutoffDate)
204
+ console.log('>>>>> SYNC', modelName, where)
128
205
  const databaseService = app.service(modelName)
129
206
 
130
207
  // STEP1: get existing database `where` values and build a dictionary
@@ -166,10 +243,8 @@ export function drizzleOfflinePlugin(app, db, metadata, models) {
166
243
  console.log('*** err sync', err)
167
244
  throw err
168
245
  } finally {
169
- const mutex = syncMutexes.get(mutexKey)
170
- mutex.release()
171
- // Remove idle mutexes so the Map stays bounded for dynamic where clauses.
172
- if (mutex.queue.length === 0) syncMutexes.delete(mutexKey)
246
+ releaseSyncLock()
247
+ if (syncLock.idle) syncLocks.delete(modelName)
173
248
  }
174
249
  },
175
250
  })