@mark1russell7/collections 0.0.0-bootstrap.0 → 0.1.0
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/LICENSE +21 -0
- package/README.md +77 -1
- package/build/dag/index.d.ts +144 -0
- package/build/dag/index.d.ts.map +1 -0
- package/build/dag/index.js +294 -0
- package/build/dag/index.js.map +1 -0
- package/build/graph/index.d.ts +20 -0
- package/build/graph/index.d.ts.map +1 -0
- package/build/graph/index.js +48 -0
- package/build/graph/index.js.map +1 -0
- package/build/index.d.ts +4952 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +7811 -0
- package/build/index.js.map +1 -0
- package/build/testing/index.d.ts +25 -0
- package/build/testing/index.d.ts.map +1 -0
- package/build/testing/index.js +72 -0
- package/build/testing/index.js.map +1 -0
- package/package.json +71 -4
- package/src/async/async-queue.ts +481 -0
- package/src/async/channels.ts +450 -0
- package/src/async/settled.ts +41 -0
- package/src/behaviors/bounded.ts +485 -0
- package/src/behaviors/composite.ts +99 -0
- package/src/behaviors/evented.ts +464 -0
- package/src/behaviors/lru.ts +449 -0
- package/src/behaviors/readonly.ts +236 -0
- package/src/behaviors/safe.ts +358 -0
- package/src/behaviors/synchronized.ts +316 -0
- package/src/behaviors/ttl.ts +464 -0
- package/src/core/effects.ts +327 -0
- package/src/core/events.ts +363 -0
- package/src/core/middleware.ts +413 -0
- package/src/core/policies.ts +316 -0
- package/src/core/traits.ts +164 -0
- package/src/dag/builder.ts +124 -0
- package/src/dag/executor.ts +190 -0
- package/src/dag/index.ts +14 -0
- package/src/dag/traversal.ts +129 -0
- package/src/dag/types.ts +87 -0
- package/src/fx/collectors.ts +500 -0
- package/src/fx/iter.ts +536 -0
- package/src/graph/hub-order.ts +53 -0
- package/src/graph/index.ts +5 -0
- package/src/impl/array-deque.ts +463 -0
- package/src/impl/array-list.ts +490 -0
- package/src/impl/hash-map.ts +623 -0
- package/src/impl/hash-set.ts +342 -0
- package/src/impl/linked-hash-map.ts +572 -0
- package/src/impl/linked-list.ts +610 -0
- package/src/impl/priority-queue.ts +448 -0
- package/src/impl/summary-tree.ts +594 -0
- package/src/impl/tree-map.ts +913 -0
- package/src/impl/tree-set.ts +469 -0
- package/src/index.ts +237 -0
- package/src/interfaces/collection.ts +141 -0
- package/src/interfaces/list.ts +281 -0
- package/src/interfaces/map.ts +405 -0
- package/src/interfaces/queue.ts +353 -0
- package/src/interfaces/set.ts +158 -0
- package/src/order/index.ts +6 -0
- package/src/order/rank.ts +271 -0
- package/src/storage/listeners.ts +72 -0
- package/src/testing/check.ts +81 -0
- package/src/testing/index.ts +7 -0
- package/src/utils/defaults.ts +345 -0
- package/src/utils/factories.ts +357 -0
- package/src/utils/helpers.ts +248 -0
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Safe behavior - Gives Option/Result-based error handling.
|
|
3
|
+
*
|
|
4
|
+
* This module wraps collection operations that throw errors to instead return
|
|
5
|
+
* Option<T> or Result<T, E>, enabling functional error handling.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* const list = compose(
|
|
9
|
+
* safeList()
|
|
10
|
+
* )(arrayList<number>())
|
|
11
|
+
*
|
|
12
|
+
* const value = list.safe.get(10) // Option<number> instead of throwing
|
|
13
|
+
* if (isSome(value)) {
|
|
14
|
+
* console.log(value.value)
|
|
15
|
+
* }
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import type { Middleware } from "../core/middleware.js";
|
|
19
|
+
import type { List } from "../interfaces/list.js";
|
|
20
|
+
import type { Queue, Deque } from "../interfaces/queue.js";
|
|
21
|
+
import type { MapLike } from "../interfaces/map.js";
|
|
22
|
+
import { type Option, type Result } from "../core/effects.js";
|
|
23
|
+
import { None, Some, tryCatch } from "../core/effects.js";
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Safe operations for List.
|
|
27
|
+
*/
|
|
28
|
+
export interface SafeListOperations<T> {
|
|
29
|
+
/**
|
|
30
|
+
* Get element at index, giving Option.
|
|
31
|
+
*/
|
|
32
|
+
get(index: number): Option<T>;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Set element at index, giving Result with old value or error.
|
|
36
|
+
*/
|
|
37
|
+
set(index: number, element: T): Result<T, string>;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Remove element at index, giving Result with removed value or error.
|
|
41
|
+
*/
|
|
42
|
+
removeAt(index: number): Result<T, string>;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Get first element as Option.
|
|
46
|
+
*/
|
|
47
|
+
first(): Option<T>;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Get last element as Option.
|
|
51
|
+
*/
|
|
52
|
+
last(): Option<T>;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Pop element, giving Option.
|
|
56
|
+
*/
|
|
57
|
+
pop(): Option<T>;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Shift element, giving Option.
|
|
61
|
+
*/
|
|
62
|
+
shift(): Option<T>;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Safe operations for Queue.
|
|
67
|
+
*/
|
|
68
|
+
export interface SafeQueueOperations<T> {
|
|
69
|
+
/**
|
|
70
|
+
* Peek at head element as Option.
|
|
71
|
+
*/
|
|
72
|
+
peek(): Option<T>;
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Poll element as Option.
|
|
76
|
+
*/
|
|
77
|
+
poll(): Option<T>;
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Dequeue element as Option.
|
|
81
|
+
*/
|
|
82
|
+
dequeue(): Option<T>;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Safe operations for Deque.
|
|
87
|
+
*/
|
|
88
|
+
export interface SafeDequeOperations<T> extends SafeQueueOperations<T> {
|
|
89
|
+
/**
|
|
90
|
+
* Peek at first element as Option.
|
|
91
|
+
*/
|
|
92
|
+
peekFirst(): Option<T>;
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Peek at last element as Option.
|
|
96
|
+
*/
|
|
97
|
+
peekLast(): Option<T>;
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Poll first element as Option.
|
|
101
|
+
*/
|
|
102
|
+
pollFirst(): Option<T>;
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Poll last element as Option.
|
|
106
|
+
*/
|
|
107
|
+
pollLast(): Option<T>;
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Pop element as Option.
|
|
111
|
+
*/
|
|
112
|
+
pop(): Option<T>;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Safe operations for Map.
|
|
117
|
+
*/
|
|
118
|
+
export interface SafeMapOperations<K, V> {
|
|
119
|
+
/**
|
|
120
|
+
* Get value for key as Option.
|
|
121
|
+
*/
|
|
122
|
+
get(key: K): Option<V>;
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Set value for key, giving Result with old value or success.
|
|
126
|
+
*/
|
|
127
|
+
set(key: K, value: V): Result<V | undefined, string>;
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Delete key, giving Result with deleted value or error.
|
|
131
|
+
*/
|
|
132
|
+
delete(key: K): Result<V | undefined, string>;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* This function makes a safe List middleware.
|
|
137
|
+
*
|
|
138
|
+
* This function exposes a `safe` property with Option/Result-based operations.
|
|
139
|
+
*/
|
|
140
|
+
export function safeList<T>(): Middleware<
|
|
141
|
+
List<T>,
|
|
142
|
+
List<T> & { safe: SafeListOperations<T> }
|
|
143
|
+
> {
|
|
144
|
+
return (next: List<T>): List<T> & { safe: SafeListOperations<T> } => {
|
|
145
|
+
const safe: SafeListOperations<T> = {
|
|
146
|
+
get(index: number): Option<T> {
|
|
147
|
+
return tryCatch(
|
|
148
|
+
() => next.get(index),
|
|
149
|
+
() => "Index out of bounds"
|
|
150
|
+
).match<Option<T>>({
|
|
151
|
+
Ok: (value) => Some(value),
|
|
152
|
+
Err: () => None,
|
|
153
|
+
}) as Option<T>;
|
|
154
|
+
},
|
|
155
|
+
|
|
156
|
+
set(index: number, element: T): Result<T, string> {
|
|
157
|
+
return tryCatch(
|
|
158
|
+
() => next.set(index, element),
|
|
159
|
+
(error) => String(error)
|
|
160
|
+
);
|
|
161
|
+
},
|
|
162
|
+
|
|
163
|
+
removeAt(index: number): Result<T, string> {
|
|
164
|
+
return tryCatch(
|
|
165
|
+
() => next.removeAt(index),
|
|
166
|
+
(error) => String(error)
|
|
167
|
+
);
|
|
168
|
+
},
|
|
169
|
+
|
|
170
|
+
first(): Option<T> {
|
|
171
|
+
return next.isEmpty ? None : Some(next.first());
|
|
172
|
+
},
|
|
173
|
+
|
|
174
|
+
last(): Option<T> {
|
|
175
|
+
return next.isEmpty ? None : Some(next.last());
|
|
176
|
+
},
|
|
177
|
+
|
|
178
|
+
pop(): Option<T> {
|
|
179
|
+
if (next.isEmpty) return None;
|
|
180
|
+
return tryCatch(
|
|
181
|
+
() => next.pop(),
|
|
182
|
+
() => "List is empty"
|
|
183
|
+
).match<Option<T>>({
|
|
184
|
+
Ok: (value) => Some(value),
|
|
185
|
+
Err: () => None,
|
|
186
|
+
}) as Option<T>;
|
|
187
|
+
},
|
|
188
|
+
|
|
189
|
+
shift(): Option<T> {
|
|
190
|
+
if (next.isEmpty) return None;
|
|
191
|
+
return tryCatch(
|
|
192
|
+
() => next.shift(),
|
|
193
|
+
() => "List is empty"
|
|
194
|
+
).match<Option<T>>({
|
|
195
|
+
Ok: (value) => Some(value),
|
|
196
|
+
Err: () => None,
|
|
197
|
+
}) as Option<T>;
|
|
198
|
+
},
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
// Extend next with safe property
|
|
202
|
+
return Object.assign(next, { safe });
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* This function makes a safe Queue middleware.
|
|
208
|
+
*/
|
|
209
|
+
export function safeQueue<T>(): Middleware<
|
|
210
|
+
Queue<T>,
|
|
211
|
+
Queue<T> & { safe: SafeQueueOperations<T> }
|
|
212
|
+
> {
|
|
213
|
+
return (next: Queue<T>): Queue<T> & { safe: SafeQueueOperations<T> } => {
|
|
214
|
+
const safe: SafeQueueOperations<T> = {
|
|
215
|
+
peek(): Option<T> {
|
|
216
|
+
if (next.isEmpty) return None;
|
|
217
|
+
return tryCatch(
|
|
218
|
+
() => next.peek(),
|
|
219
|
+
() => "Queue is empty"
|
|
220
|
+
).match<Option<T>>({
|
|
221
|
+
Ok: (value) => Some(value),
|
|
222
|
+
Err: () => None,
|
|
223
|
+
}) as Option<T>;
|
|
224
|
+
},
|
|
225
|
+
|
|
226
|
+
poll(): Option<T> {
|
|
227
|
+
if (next.isEmpty) return None;
|
|
228
|
+
return tryCatch(
|
|
229
|
+
() => next.poll(),
|
|
230
|
+
() => "Queue is empty"
|
|
231
|
+
).match<Option<T>>({
|
|
232
|
+
Ok: (value) => Some(value),
|
|
233
|
+
Err: () => None,
|
|
234
|
+
}) as Option<T>;
|
|
235
|
+
},
|
|
236
|
+
|
|
237
|
+
dequeue(): Option<T> {
|
|
238
|
+
if (next.isEmpty) return None;
|
|
239
|
+
return tryCatch(
|
|
240
|
+
() => next.dequeue(),
|
|
241
|
+
() => "Queue is empty"
|
|
242
|
+
).match<Option<T>>({
|
|
243
|
+
Ok: (value) => Some(value),
|
|
244
|
+
Err: () => None,
|
|
245
|
+
}) as Option<T>;
|
|
246
|
+
},
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
return Object.assign(next, { safe });
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* This function makes a safe Deque middleware.
|
|
255
|
+
*/
|
|
256
|
+
export function safeDeque<T>(): Middleware<
|
|
257
|
+
Deque<T>,
|
|
258
|
+
Deque<T> & { safe: SafeDequeOperations<T> }
|
|
259
|
+
> {
|
|
260
|
+
return (next: Deque<T>): Deque<T> & { safe: SafeDequeOperations<T> } => {
|
|
261
|
+
const safe: SafeDequeOperations<T> = {
|
|
262
|
+
peek(): Option<T> {
|
|
263
|
+
return next.isEmpty ? None : Some(next.peekFirst());
|
|
264
|
+
},
|
|
265
|
+
|
|
266
|
+
poll(): Option<T> {
|
|
267
|
+
// One poll: before, the test and the result each called pollFirst(), so poll() removed
|
|
268
|
+
// two elements and returned the second (BUGS-2026-07 L12)
|
|
269
|
+
if (next.isEmpty) return None;
|
|
270
|
+
return Some(next.pollFirst() as T);
|
|
271
|
+
},
|
|
272
|
+
|
|
273
|
+
dequeue(): Option<T> {
|
|
274
|
+
if (next.isEmpty) return None;
|
|
275
|
+
return tryCatch(
|
|
276
|
+
() => next.dequeue(),
|
|
277
|
+
() => "Deque is empty"
|
|
278
|
+
).match<Option<T>>({
|
|
279
|
+
Ok: (value) => Some(value),
|
|
280
|
+
Err: () => None,
|
|
281
|
+
}) as Option<T>;
|
|
282
|
+
},
|
|
283
|
+
|
|
284
|
+
peekFirst(): Option<T> {
|
|
285
|
+
return next.isEmpty ? None : Some(next.peekFirst());
|
|
286
|
+
},
|
|
287
|
+
|
|
288
|
+
peekLast(): Option<T> {
|
|
289
|
+
return next.isEmpty ? None : Some(next.peekLast());
|
|
290
|
+
},
|
|
291
|
+
|
|
292
|
+
pollFirst(): Option<T> {
|
|
293
|
+
const result = next.pollFirst();
|
|
294
|
+
return result !== undefined ? Some(result) : None;
|
|
295
|
+
},
|
|
296
|
+
|
|
297
|
+
pollLast(): Option<T> {
|
|
298
|
+
const result = next.pollLast();
|
|
299
|
+
return result !== undefined ? Some(result) : None;
|
|
300
|
+
},
|
|
301
|
+
|
|
302
|
+
pop(): Option<T> {
|
|
303
|
+
if (next.isEmpty) return None;
|
|
304
|
+
return tryCatch(
|
|
305
|
+
() => next.pop(),
|
|
306
|
+
() => "Deque is empty"
|
|
307
|
+
).match<Option<T>>({
|
|
308
|
+
Ok: (value) => Some(value),
|
|
309
|
+
Err: () => None,
|
|
310
|
+
}) as Option<T>;
|
|
311
|
+
},
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
return Object.assign(next, { safe });
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* This function makes a safe Map middleware.
|
|
320
|
+
*/
|
|
321
|
+
export function safeMap<K, V>(): Middleware<
|
|
322
|
+
MapLike<K, V>,
|
|
323
|
+
MapLike<K, V> & { safe: SafeMapOperations<K, V> }
|
|
324
|
+
> {
|
|
325
|
+
return (
|
|
326
|
+
next: MapLike<K, V>
|
|
327
|
+
): MapLike<K, V> & { safe: SafeMapOperations<K, V> } => {
|
|
328
|
+
const safe: SafeMapOperations<K, V> = {
|
|
329
|
+
get(key: K): Option<V> {
|
|
330
|
+
return next.has(key) ? Some(next.get(key)) : None;
|
|
331
|
+
},
|
|
332
|
+
|
|
333
|
+
set(key: K, value: V): Result<V | undefined, string> {
|
|
334
|
+
return tryCatch(
|
|
335
|
+
() => next.set(key, value),
|
|
336
|
+
(error) => String(error)
|
|
337
|
+
);
|
|
338
|
+
},
|
|
339
|
+
|
|
340
|
+
delete(key: K): Result<V | undefined, string> {
|
|
341
|
+
return tryCatch(
|
|
342
|
+
() => next.delete(key),
|
|
343
|
+
(error) => String(error)
|
|
344
|
+
);
|
|
345
|
+
},
|
|
346
|
+
};
|
|
347
|
+
|
|
348
|
+
return Object.assign(next, { safe });
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Generic safe middleware that works with any collection.
|
|
354
|
+
*/
|
|
355
|
+
export function safe<C extends object>(): Middleware<C> {
|
|
356
|
+
// Return as-is for now; specialized versions handle specific types
|
|
357
|
+
return (next: C): C => next;
|
|
358
|
+
}
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Synchronized behavior - Gives thread-safe access with mutex locking.
|
|
3
|
+
*
|
|
4
|
+
* This module wraps collections to serialize all operations using a mutex, making sure that
|
|
5
|
+
* thread-safe access in concurrent environments. Mirrors Java's
|
|
6
|
+
* Collections.synchronizedList() and related methods.
|
|
7
|
+
*
|
|
8
|
+
* Note: JavaScript is single-threaded, but async operations can interleave.
|
|
9
|
+
* This middleware makes sure that atomic operations across async boundaries.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* const list = compose(
|
|
13
|
+
* synchronized()
|
|
14
|
+
* )(arrayList<number>())
|
|
15
|
+
*
|
|
16
|
+
* // All operations are now serialized
|
|
17
|
+
* await Promise.all([
|
|
18
|
+
* list.add(1),
|
|
19
|
+
* list.add(2),
|
|
20
|
+
* list.add(3)
|
|
21
|
+
* ])
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import type { Middleware } from "../core/middleware.js";
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Simple mutex implementation for JavaScript async operations.
|
|
28
|
+
*
|
|
29
|
+
* This middleware makes sure that only one operation starts at a time, even if
|
|
30
|
+
* multiple async operations are started concurrently.
|
|
31
|
+
*/
|
|
32
|
+
/** True for an `async` function or method. */
|
|
33
|
+
function isAsyncFunction(value: unknown): boolean {
|
|
34
|
+
return typeof value === "function" && (value as { [Symbol.toStringTag]?: string })[Symbol.toStringTag] === "AsyncFunction";
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
class Mutex {
|
|
38
|
+
private queue: Promise<void> = Promise.resolve();
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* This method acquires the lock and starts the function.
|
|
42
|
+
* Other operations wait until this completes.
|
|
43
|
+
*/
|
|
44
|
+
async lock<T>(fn: () => T | Promise<T>): Promise<T> {
|
|
45
|
+
const run = this.queue.then(() => fn());
|
|
46
|
+
this.queue = run.then(
|
|
47
|
+
() => undefined,
|
|
48
|
+
() => undefined
|
|
49
|
+
);
|
|
50
|
+
return run;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Synchronous version that starts immediately.
|
|
55
|
+
* Still queues to prevent interleaving with async operations.
|
|
56
|
+
*/
|
|
57
|
+
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* This function makes a synchronized middleware that locks all method calls.
|
|
62
|
+
*
|
|
63
|
+
* Every method call on the collection is wrapped with a mutex,
|
|
64
|
+
* making sure that atomic execution even in concurrent async scenarios.
|
|
65
|
+
*
|
|
66
|
+
* @example
|
|
67
|
+
* const syncList = compose(
|
|
68
|
+
* synchronized()
|
|
69
|
+
* )(arrayList<number>())
|
|
70
|
+
*
|
|
71
|
+
* // These additions are guaranteed to execute in order
|
|
72
|
+
* await Promise.all([
|
|
73
|
+
* syncList.add(1),
|
|
74
|
+
* syncList.add(2),
|
|
75
|
+
* syncList.add(3)
|
|
76
|
+
* ])
|
|
77
|
+
*/
|
|
78
|
+
export function synchronized<C extends object>(): Middleware<C> {
|
|
79
|
+
return (next: C): C => {
|
|
80
|
+
const mutex = new Mutex();
|
|
81
|
+
|
|
82
|
+
return new Proxy(next, {
|
|
83
|
+
get(target, prop, receiver) {
|
|
84
|
+
const value = Reflect.get(target, prop, receiver);
|
|
85
|
+
|
|
86
|
+
// Don't wrap non-functions
|
|
87
|
+
if (typeof value !== "function") {
|
|
88
|
+
return value;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// An async method runs inside the lock: it starts after the earlier async calls end.
|
|
92
|
+
// (Before, every method ran first and took the lock after, so nothing was excluded:
|
|
93
|
+
// BUGS-2026-07 L11.) A plain method runs at once: JavaScript does not interrupt it.
|
|
94
|
+
// When a plain method returns a promise anyway, the lock waits for that promise.
|
|
95
|
+
if (isAsyncFunction(value)) {
|
|
96
|
+
return function (this: unknown, ...args: unknown[]) {
|
|
97
|
+
return mutex.lock(() => (value as Function).apply(target, args));
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
return function (this: unknown, ...args: unknown[]) {
|
|
101
|
+
const result = (value as Function).apply(target, args);
|
|
102
|
+
if (result instanceof Promise) {
|
|
103
|
+
return mutex.lock(() => result);
|
|
104
|
+
}
|
|
105
|
+
return result;
|
|
106
|
+
};
|
|
107
|
+
},
|
|
108
|
+
}) as C;
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Alias for Java compatibility: synchronizedList
|
|
114
|
+
*/
|
|
115
|
+
export const synchronizedList : typeof synchronized = synchronized;
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Alias for Java compatibility: synchronizedMap
|
|
119
|
+
*/
|
|
120
|
+
export const synchronizedMap : typeof synchronized = synchronized;
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Alias for Java compatibility: synchronizedCollection
|
|
124
|
+
*/
|
|
125
|
+
export const synchronizedCollection : typeof synchronized = synchronized;
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Alias for Java compatibility: synchronizedSet
|
|
129
|
+
*/
|
|
130
|
+
export const synchronizedSet : typeof synchronized = synchronized;
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Advanced synchronized middleware with reentrant locking.
|
|
134
|
+
*
|
|
135
|
+
* With this function, the same "thread" (async context) can acquire the lock multiple times.
|
|
136
|
+
* Useful for methods that call other synchronized methods internally.
|
|
137
|
+
*
|
|
138
|
+
* Note: JavaScript has no true thread IDs. This function uses async context
|
|
139
|
+
* tracking if available. If not, the behavior is non-reentrant.
|
|
140
|
+
*/
|
|
141
|
+
export function reentrantSynchronized<C extends object>(): Middleware<C> {
|
|
142
|
+
return (next: C): C => {
|
|
143
|
+
const mutex = new Mutex();
|
|
144
|
+
let lockHolder: symbol | null = null;
|
|
145
|
+
let lockCount = 0;
|
|
146
|
+
|
|
147
|
+
return new Proxy(next, {
|
|
148
|
+
get(target, prop, receiver) {
|
|
149
|
+
const value = Reflect.get(target, prop, receiver);
|
|
150
|
+
|
|
151
|
+
if (typeof value !== "function") {
|
|
152
|
+
return value;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
return async function (this: any, ...args: any[]) {
|
|
156
|
+
// Generate a unique ID for this call context
|
|
157
|
+
const callerId = Symbol("caller");
|
|
158
|
+
|
|
159
|
+
// If we already hold the lock, execute directly (reentrant)
|
|
160
|
+
if (lockHolder === callerId) {
|
|
161
|
+
lockCount++;
|
|
162
|
+
try {
|
|
163
|
+
const result = (value as Function).apply(target, args);
|
|
164
|
+
return result instanceof Promise ? await result : result;
|
|
165
|
+
} finally {
|
|
166
|
+
lockCount--;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// Otherwise, acquire the lock
|
|
171
|
+
return mutex.lock(async () => {
|
|
172
|
+
lockHolder = callerId;
|
|
173
|
+
lockCount = 1;
|
|
174
|
+
try {
|
|
175
|
+
const result = (value as Function).apply(target, args);
|
|
176
|
+
return result instanceof Promise ? await result : result;
|
|
177
|
+
} finally {
|
|
178
|
+
lockCount--;
|
|
179
|
+
if (lockCount === 0) {
|
|
180
|
+
lockHolder = null;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
};
|
|
185
|
+
},
|
|
186
|
+
}) as C;
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Read-write lock implementation for collections.
|
|
192
|
+
*
|
|
193
|
+
* With this function, multiple concurrent readers can read, but a writer is exclusive.
|
|
194
|
+
* More efficient than full synchronization for read-heavy workloads.
|
|
195
|
+
*
|
|
196
|
+
* @example
|
|
197
|
+
* const list = compose(
|
|
198
|
+
* readWriteLock()
|
|
199
|
+
* )(arrayList<number>())
|
|
200
|
+
*
|
|
201
|
+
* // Multiple reads can happen concurrently
|
|
202
|
+
* await Promise.all([
|
|
203
|
+
* list.get(0),
|
|
204
|
+
* list.get(1),
|
|
205
|
+
* list.get(2)
|
|
206
|
+
* ])
|
|
207
|
+
*/
|
|
208
|
+
export function readWriteLock<C extends object>(): Middleware<C> {
|
|
209
|
+
return (next: C): C => {
|
|
210
|
+
let readers = 0;
|
|
211
|
+
let writer = false;
|
|
212
|
+
let waitingReaders: (() => void)[] = [];
|
|
213
|
+
let waitingWriters: (() => void)[] = [];
|
|
214
|
+
|
|
215
|
+
// Hand-off rule: the releaser counts the waiters it wakes (readers += n, or writer = true),
|
|
216
|
+
// so a woken waiter does not count itself again. (Before, releaseWrite set readers = n and
|
|
217
|
+
// each woken reader added 1, so the count never came back to 0 and writers waited forever:
|
|
218
|
+
// BUGS-2026-07 L11.)
|
|
219
|
+
const acquireRead = async (): Promise<void> => {
|
|
220
|
+
if (writer || waitingWriters.length > 0) {
|
|
221
|
+
await new Promise<void>((resolve) => waitingReaders.push(resolve));
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
readers++;
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
const releaseRead = (): void => {
|
|
228
|
+
readers--;
|
|
229
|
+
if (readers === 0 && waitingWriters.length > 0) {
|
|
230
|
+
writer = true;
|
|
231
|
+
const next = waitingWriters.shift()!;
|
|
232
|
+
next();
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
const acquireWrite = async (): Promise<void> => {
|
|
237
|
+
if (writer || readers > 0) {
|
|
238
|
+
await new Promise<void>((resolve) => waitingWriters.push(resolve));
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
writer = true;
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
const releaseWrite = (): void => {
|
|
245
|
+
writer = false;
|
|
246
|
+
if (waitingWriters.length > 0) {
|
|
247
|
+
writer = true;
|
|
248
|
+
const next = waitingWriters.shift()!;
|
|
249
|
+
next();
|
|
250
|
+
} else if (waitingReaders.length > 0) {
|
|
251
|
+
const allReaders = waitingReaders.splice(0);
|
|
252
|
+
readers += allReaders.length;
|
|
253
|
+
allReaders.forEach((resolve) => resolve());
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
// Methods that only read (don't mutate)
|
|
258
|
+
const READ_METHODS = new Set([
|
|
259
|
+
"get",
|
|
260
|
+
"has",
|
|
261
|
+
"contains",
|
|
262
|
+
"containsAll",
|
|
263
|
+
"containsValue",
|
|
264
|
+
"indexOf",
|
|
265
|
+
"lastIndexOf",
|
|
266
|
+
"peek",
|
|
267
|
+
"peekFirst",
|
|
268
|
+
"peekLast",
|
|
269
|
+
"first",
|
|
270
|
+
"last",
|
|
271
|
+
"isEmpty",
|
|
272
|
+
"size",
|
|
273
|
+
"toArray",
|
|
274
|
+
"keys",
|
|
275
|
+
"values",
|
|
276
|
+
"entries",
|
|
277
|
+
"forEach",
|
|
278
|
+
"getOrDefault",
|
|
279
|
+
"getOrUndefined",
|
|
280
|
+
]);
|
|
281
|
+
|
|
282
|
+
return new Proxy(next, {
|
|
283
|
+
get(target, prop, receiver) {
|
|
284
|
+
const value = Reflect.get(target, prop, receiver);
|
|
285
|
+
|
|
286
|
+
if (typeof value !== "function") {
|
|
287
|
+
return value;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const isReadMethod = typeof prop === "string" && READ_METHODS.has(prop);
|
|
291
|
+
|
|
292
|
+
return async function (this: any, ...args: any[]) {
|
|
293
|
+
if (isReadMethod) {
|
|
294
|
+
// Acquire read lock
|
|
295
|
+
await acquireRead();
|
|
296
|
+
try {
|
|
297
|
+
const result = (value as Function).apply(target, args);
|
|
298
|
+
return result instanceof Promise ? await result : result;
|
|
299
|
+
} finally {
|
|
300
|
+
releaseRead();
|
|
301
|
+
}
|
|
302
|
+
} else {
|
|
303
|
+
// Acquire write lock
|
|
304
|
+
await acquireWrite();
|
|
305
|
+
try {
|
|
306
|
+
const result = (value as Function).apply(target, args);
|
|
307
|
+
return result instanceof Promise ? await result : result;
|
|
308
|
+
} finally {
|
|
309
|
+
releaseWrite();
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
};
|
|
313
|
+
},
|
|
314
|
+
}) as C;
|
|
315
|
+
};
|
|
316
|
+
}
|