@the-w1zard/singularity 1.0.11 → 1.0.13

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.
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ /**
3
+ *
4
+ *
5
+ import { setSauron, } from '../the-cloud/the-cloud/hook-system'
6
+
7
+ // #region ── LIVE SELF BINDING ────────────────────────────────────────────────
8
+ export function createLiveSelf(instanceId: string) {
9
+ const liveTarget: Record<string, any> = {};
10
+ const selfProxy = new Proxy(liveTarget, {
11
+ get(target, key: string) { return target[key]; },
12
+ set(target, key: string, value: any) {// reuse the existing Sauron store — same primitive `live`/`useLive` already build on
13
+ target[key] = value;
14
+ setSauron(`${instanceId}:${key}`, value);
15
+ return true;
16
+ }
17
+ });
18
+ return { selfProxy, liveTarget };
19
+ }
20
+ // #endregion
21
+
22
+ */
@@ -0,0 +1,532 @@
1
+ // QUEUE
2
+ // #region ══════════════════════════════════════════════════════════════════════════════════════════════════════
3
+ let queuedLength = 0;
4
+ export function useQueue(optionsOrConcurrent) {
5
+ const queueRef = atom(null);
6
+ const [results, setResults] = darkState([]);
7
+ const [errors, setErrors] = darkState([]);
8
+ const [state, setState] = darkState({
9
+ pending: 0,
10
+ active: 0,
11
+ size: 0,
12
+ isEmpty: true,
13
+ isRunning: false
14
+ });
15
+ const updateState = darkCallback(() => {
16
+ if (!queueRef.current)
17
+ return;
18
+ setState({
19
+ pending: queueRef.current.pending,
20
+ active: queueRef.current.active,
21
+ size: queueRef.current.size,
22
+ isEmpty: queueRef.current.isEmpty,
23
+ isRunning: queueRef.current.isRunning
24
+ });
25
+ }, []);
26
+ if (!queueRef.current) {
27
+ const opts = typeof optionsOrConcurrent === 'number'
28
+ ? { concurrent: optionsOrConcurrent }
29
+ : optionsOrConcurrent || {};
30
+ queueRef.current = queue({
31
+ ...opts,
32
+ onComplete: (result) => {
33
+ setResults((prev) => [...prev, result]);
34
+ if (opts.onComplete)
35
+ opts.onComplete(result);
36
+ updateState();
37
+ },
38
+ onError: (error, task) => {
39
+ setErrors((prev) => [...prev, error]);
40
+ if (opts.onError)
41
+ opts.onError(error, task);
42
+ updateState();
43
+ }
44
+ });
45
+ }
46
+ const add = darkCallback(async (task, options) => {
47
+ if (!queueRef.current)
48
+ throw new Error('Queue not initialized');
49
+ updateState();
50
+ const result = await queueRef.current(task, options);
51
+ updateState();
52
+ return result;
53
+ }, [updateState]);
54
+ const start = darkCallback(() => {
55
+ queueRef.current?.start();
56
+ updateState();
57
+ }, [updateState]);
58
+ const stop = darkCallback(() => {
59
+ queueRef.current?.stop();
60
+ updateState();
61
+ }, [updateState]);
62
+ const clear = darkCallback(() => {
63
+ queueRef.current?.clear();
64
+ setResults([]);
65
+ setErrors([]);
66
+ updateState();
67
+ }, [updateState]);
68
+ const flush = darkCallback(() => {
69
+ queueRef.current?.flush();
70
+ updateState();
71
+ }, [updateState]);
72
+ darkEffect(() => {
73
+ updateState();
74
+ }, [updateState]);
75
+ return {
76
+ add,
77
+ results,
78
+ errors,
79
+ pending: state.pending,
80
+ active: state.active,
81
+ size: state.size,
82
+ isEmpty: state.isEmpty,
83
+ isRunning: state.isRunning,
84
+ start,
85
+ stop,
86
+ clear,
87
+ flush
88
+ };
89
+ }
90
+ export class TIERED_QUEUE2 {
91
+ config;
92
+ tiers = new Map();
93
+ tierOrder = [];
94
+ tierResults = new Map();
95
+ constructor(config = {}) {
96
+ this.config = config;
97
+ }
98
+ REG(tier, options) {
99
+ if (!this.tiers.has(tier)) {
100
+ const tierQueue = queue({
101
+ concurrent: options?.concurrent ?? this.config.defaultConcurrent ?? 100,
102
+ retry: options?.retry ?? this.config.retry ?? 0,
103
+ timeout: options?.timeout ?? this.config.timeout ?? 30000,
104
+ priority: false,
105
+ onError: (error, task) => {
106
+ console.log(`✘[QUEUE-TIERED][FAILED][${tier}]:[${task.label}]:[${error}]`);
107
+ this.config.onTierError?.(tier, error);
108
+ },
109
+ onComplete: (result) => {
110
+ console.log(`✔[QUEUE-TIERED][COMPLETED][${tier}]`);
111
+ }
112
+ });
113
+ this.tiers.set(tier, tierQueue);
114
+ this.tierResults.set(tier, []);
115
+ this.tierOrder.push(tier);
116
+ this.tierOrder.sort((a, b) => a - b);
117
+ }
118
+ return this;
119
+ }
120
+ async ADD(tier, label, task) {
121
+ this.REG(tier);
122
+ const tierQueue = this.tiers.get(tier);
123
+ const taskKey = `T${tier}-${label}`;
124
+ try {
125
+ const result = await tierQueue(async () => {
126
+ const startTime = Date.now();
127
+ try {
128
+ const result = await task();
129
+ const duration = Date.now() - startTime;
130
+ console.log(`✔[QUEUE][DONE][T${tier}]:[${label}] ⏱️${duration}ms`);
131
+ return result;
132
+ }
133
+ catch (error) {
134
+ const duration = Date.now() - startTime;
135
+ console.log(`✘[QUEUE][FAIL][T${tier}]:[${label}] ⏱️${duration}ms Error: ${error}`);
136
+ throw error;
137
+ }
138
+ }, { label });
139
+ this.tierResults.get(tier).push(result);
140
+ return result;
141
+ }
142
+ catch (error) {
143
+ console.log(`✘[QUEUE-TIERED][FAILED][${tier}]:[${label}]:[${error}]`);
144
+ return undefined;
145
+ }
146
+ }
147
+ async ADD_BATCH(tier, tasks) {
148
+ const batchKey = `Batch-T${tier}`;
149
+ const startTime = Date.now();
150
+ const results = await Promise.allSettled(tasks.map(task => this.ADD(tier, task.label, task.task)));
151
+ const duration = Date.now() - startTime;
152
+ const successCount = results.filter(r => r.status === 'fulfilled').length;
153
+ const failCount = results.filter(r => r.status === 'rejected').length;
154
+ console.log(`✔✘[BATCH][DONE][T${tier}]: ✔${successCount} ✘${failCount} ⏱️${duration}ms`);
155
+ return results.map(result => {
156
+ if (result.status === 'fulfilled') {
157
+ return result.value;
158
+ }
159
+ console.error('Unexpected rejection:', result.reason);
160
+ return undefined;
161
+ });
162
+ }
163
+ /** Executes tiers in order — tasks WITHIN each tier run concurrently. Reactive via onIdle(), no polling. */
164
+ async execute() {
165
+ const results = new Map();
166
+ for (const tier of this.tierOrder) {
167
+ const tierQueue = this.tiers.get(tier);
168
+ if (tierQueue.isPausedState) {
169
+ tierQueue.start();
170
+ }
171
+ await tierQueue.onIdle();
172
+ const tierRes = this.tierResults.get(tier) ?? [];
173
+ this.config.onTierComplete?.(tier, []);
174
+ results.set(tier, tierRes);
175
+ }
176
+ return results;
177
+ }
178
+ getStatus() {
179
+ return this.tierOrder.map(tier => ({
180
+ tier,
181
+ pending: this.tiers.get(tier)?.pending ?? 0,
182
+ active: this.tiers.get(tier)?.active ?? 0
183
+ }));
184
+ }
185
+ clear() {
186
+ this.tiers.forEach(tierQueue => tierQueue.clear());
187
+ this.tierResults.forEach(arr => arr.length = 0);
188
+ }
189
+ }
190
+ export class Queue {
191
+ options;
192
+ tasks = [];
193
+ running = [];
194
+ isPaused = false;
195
+ idleListeners = new Set();
196
+ constructor(optionsOrConcurrent = 1) {
197
+ const opts = typeof optionsOrConcurrent === 'number' ? { concurrent: optionsOrConcurrent } : optionsOrConcurrent;
198
+ this.options = {
199
+ concurrent: opts.concurrent ?? 1,
200
+ retry: opts.retry ?? 0,
201
+ timeout: opts.timeout ?? 0,
202
+ priority: opts.priority ?? false,
203
+ onError: opts.onError ?? (() => { }),
204
+ onComplete: opts.onComplete ?? (() => { }),
205
+ onChange: opts.onChange ?? (() => { })
206
+ };
207
+ }
208
+ async run(taskOrTasks, taskOptions) {
209
+ if (Array.isArray(taskOrTasks)) {
210
+ return Promise.all(taskOrTasks.map(fn => this.add(fn, taskOptions)));
211
+ }
212
+ return this.add(taskOrTasks, taskOptions);
213
+ }
214
+ add(fn, taskOptions) {
215
+ return new Promise((resolve, reject) => {
216
+ let insertIndex = queuedLength;
217
+ let firstInsertedIndex = insertIndex;
218
+ const task = { fn, priority: taskOptions?.priority ?? 0, label: taskOptions?.label, resolve, reject };
219
+ if (this.options.priority) {
220
+ const insertIndex = this.tasks.findIndex(t => (t.priority ?? 0) < (task.priority ?? 0));
221
+ if (insertIndex === -1) {
222
+ this.tasks.push(task);
223
+ }
224
+ else {
225
+ this.tasks.splice(insertIndex, 0, task);
226
+ }
227
+ }
228
+ else {
229
+ this.tasks.push(task);
230
+ }
231
+ this.options.onChange();
232
+ this.process();
233
+ });
234
+ }
235
+ async process2() {
236
+ if (this.isPaused)
237
+ return;
238
+ if (this.running.length >= this.options.concurrent)
239
+ return;
240
+ if (this.tasks.length === 0)
241
+ return;
242
+ const task = this.tasks.shift();
243
+ this.running.push(task);
244
+ this.options.onChange();
245
+ try {
246
+ const result = await this.executeWithRetry(task.fn);
247
+ task.resolve(result);
248
+ this.options.onComplete(result);
249
+ }
250
+ catch (error) {
251
+ task.reject(error);
252
+ this.options.onError(error, task);
253
+ }
254
+ finally {
255
+ this.running = this.running.filter(t => t !== task);
256
+ this.options.onChange();
257
+ this.maybeFireIdle();
258
+ this.process();
259
+ }
260
+ }
261
+ process() {
262
+ if (this.isPaused)
263
+ return;
264
+ while (!this.isPaused &&
265
+ this.running.length < this.options.concurrent &&
266
+ this.tasks.length > 0) {
267
+ const task = this.tasks.shift();
268
+ this.running.push(task);
269
+ this.options.onChange();
270
+ void this.runTask(task);
271
+ }
272
+ }
273
+ async runTask(task) {
274
+ try {
275
+ const result = await this.executeWithRetry(task.fn);
276
+ task.resolve(result);
277
+ this.options.onComplete(result);
278
+ }
279
+ catch (error) {
280
+ task.reject(error);
281
+ this.options.onError(error, task);
282
+ }
283
+ finally {
284
+ this.running = this.running.filter((running) => running !== task);
285
+ this.options.onChange();
286
+ this.maybeFireIdle();
287
+ // Backfill the slot immediately.
288
+ this.process();
289
+ }
290
+ }
291
+ async executeWithRetry(fn, attempt = 0) {
292
+ try {
293
+ if (this.options.timeout > 0) {
294
+ return await this.withTimeout(fn(), this.options.timeout);
295
+ }
296
+ return await fn();
297
+ }
298
+ catch (error) {
299
+ if (attempt < this.options.retry) {
300
+ return this.executeWithRetry(fn, attempt + 1);
301
+ }
302
+ throw error;
303
+ }
304
+ }
305
+ withTimeout(promise, ms) {
306
+ return new Promise((resolve, reject) => {
307
+ let settled = false;
308
+ const timer = setTimeout(() => {
309
+ if (settled)
310
+ return;
311
+ settled = true;
312
+ reject(new Error('Timeout'));
313
+ }, ms);
314
+ promise.then((v) => { if (!settled) {
315
+ settled = true;
316
+ clearTimeout(timer);
317
+ resolve(v);
318
+ } }, (e) => { if (!settled) {
319
+ settled = true;
320
+ clearTimeout(timer);
321
+ reject(e);
322
+ } });
323
+ });
324
+ }
325
+ /** Resolves immediately if already idle, otherwise resolves the next time the queue fully empties. No polling. */
326
+ onIdle() {
327
+ if (this.tasks.length === 0 && this.running.length === 0 && !this.isPaused)
328
+ return Promise.resolve();
329
+ return new Promise((resolve) => { this.idleListeners.add(resolve); });
330
+ }
331
+ removeAt(index) {
332
+ if (index < 0 || index >= this.tasks.length)
333
+ return;
334
+ const [task] = this.tasks.splice(index, 1);
335
+ task.reject(new Error('Removed from queue'));
336
+ this.options.onChange();
337
+ }
338
+ moveUp(index) {
339
+ if (index <= 0 || index >= this.tasks.length)
340
+ return;
341
+ [this.tasks[index - 1], this.tasks[index]] = [this.tasks[index], this.tasks[index - 1]];
342
+ this.options.onChange();
343
+ }
344
+ moveDown(index) {
345
+ if (index < 0 || index >= this.tasks.length - 1)
346
+ return;
347
+ [this.tasks[index], this.tasks[index + 1]] = [this.tasks[index + 1], this.tasks[index]];
348
+ this.options.onChange();
349
+ }
350
+ moveToNext(index) {
351
+ if (index <= 0 || index >= this.tasks.length)
352
+ return;
353
+ const [task] = this.tasks.splice(index, 1);
354
+ this.tasks.unshift(task);
355
+ this.options.onChange();
356
+ }
357
+ moveToLast(index) {
358
+ if (index < 0 || index >= this.tasks.length - 1)
359
+ return;
360
+ const [task] = this.tasks.splice(index, 1);
361
+ this.tasks.push(task);
362
+ this.options.onChange();
363
+ }
364
+ start() { this.isPaused = false; this.maybeFireIdle(); this.process(); }
365
+ stop() { this.isPaused = true; }
366
+ maybeFireIdle() {
367
+ if (this.tasks.length === 0 && this.running.length === 0 && !this.isPaused) {
368
+ this.idleListeners.forEach(resolve => resolve());
369
+ this.idleListeners.clear();
370
+ }
371
+ }
372
+ clear() {
373
+ this.tasks = [];
374
+ this.options.onChange();
375
+ this.maybeFireIdle();
376
+ }
377
+ flush() {
378
+ const pending = [...this.tasks];
379
+ this.tasks = [];
380
+ pending.forEach(task => task.reject(new Error('Queue flushed')));
381
+ this.options.onChange();
382
+ this.maybeFireIdle();
383
+ }
384
+ peek() { return this.tasks[0]; }
385
+ peekAll() { return [...this.tasks]; }
386
+ getRunning() { return [...this.running]; }
387
+ get size() { return this.tasks.length; }
388
+ get isEmpty() { return this.tasks.length === 0; }
389
+ get isRunning() { return this.running.length > 0; }
390
+ get isPausedState() { return this.isPaused; }
391
+ get pending() { return this.tasks.length; }
392
+ get active() { return this.running.length; }
393
+ setOptions(newOptions) { this.options = { ...this.options, ...newOptions }; }
394
+ }
395
+ export function queue(options) {
396
+ const q = new Queue(options);
397
+ const runFn = (taskOrTasks, taskOptions) => {
398
+ return q.run(taskOrTasks, taskOptions);
399
+ };
400
+ runFn.start = () => q.start();
401
+ runFn.stop = () => q.stop();
402
+ runFn.clear = () => q.clear();
403
+ runFn.flush = () => q.flush();
404
+ runFn.onIdle = () => q.onIdle();
405
+ runFn.peek = () => q.peek();
406
+ runFn.peekAll = () => q.peekAll();
407
+ runFn.getRunning = () => q.getRunning();
408
+ runFn.removeAt = (i) => q.removeAt(i);
409
+ runFn.moveUp = (i) => q.moveUp(i);
410
+ runFn.moveDown = (i) => q.moveDown(i);
411
+ runFn.moveToNext = (i) => q.moveToNext(i);
412
+ runFn.moveToLast = (i) => q.moveToLast(i);
413
+ runFn.setOptions = (opts) => q.setOptions(opts);
414
+ Object.defineProperty(runFn, 'size', { get: () => q.size });
415
+ Object.defineProperty(runFn, 'isEmpty', { get: () => q.isEmpty });
416
+ Object.defineProperty(runFn, 'isRunning', { get: () => q.isRunning });
417
+ Object.defineProperty(runFn, 'isPausedState', { get: () => q.isPausedState });
418
+ Object.defineProperty(runFn, 'pending', { get: () => q.pending });
419
+ Object.defineProperty(runFn, 'active', { get: () => q.active });
420
+ return runFn;
421
+ }
422
+ export class TIERED_QUEUE {
423
+ config;
424
+ tiers = new Map();
425
+ tierOrder = [];
426
+ stagedTasks = new Map(); // Tasks waiting to be released for their priority batch. `ADD()` writes here. `execute()` drains it.
427
+ tierResults = new Map(); // Final successful values, grouped by tier.
428
+ constructor(config = {}) {
429
+ this.config = config;
430
+ }
431
+ // registerTier
432
+ REG(tier, options) {
433
+ if (!this.tiers.has(tier)) {
434
+ const tierQueue = queue({
435
+ concurrent: options?.concurrent ?? this.config.defaultConcurrent ?? 100,
436
+ retry: options?.retry ?? this.config.retry ?? 0,
437
+ timeout: options?.timeout ?? this.config.timeout ?? 30_000,
438
+ priority: false,
439
+ onError: (error, task) => { console.log(`✘[QUEUE-TIERED][FAILED][${tier}] [${task.label}]`); this.config.onTierError?.(tier, error); },
440
+ onComplete: () => { console.log(`✔[QUEUE-TIERED][COMPLETED][${tier}] `); },
441
+ }); // Important: A tier queue is dormant until `execute()` releases its batch.
442
+ tierQueue.stop();
443
+ this.tiers.set(tier, tierQueue);
444
+ this.stagedTasks.set(tier, []);
445
+ this.tierResults.set(tier, []);
446
+ this.tierOrder.push(tier);
447
+ this.tierOrder.sort((a, b) => a - b);
448
+ }
449
+ return this;
450
+ } // Registers a task in its priority batch. It intentionally does NOT run now. The returned promise resolves/rejects when `execute()` eventually reaches this task's batch.
451
+ // addToTier
452
+ ADD(tier, label, task, options) {
453
+ this.REG(tier, options);
454
+ return new Promise((resolve, reject) => {
455
+ this.stagedTasks.get(tier).push({ label, task, resolve, reject, });
456
+ });
457
+ } // Adds many tasks to one priority batch. All tasks in this call—and all previous tasks added at this same priority—run in the same concurrent batch when execute() reaches it.
458
+ // addBatchToTier
459
+ ADD_BATCH(tier, tasks, options) {
460
+ return Promise.all(tasks.map(({ label, task }) => this.ADD(tier, label, task, options)));
461
+ } // Runs priority batches in ascending numeric order:
462
+ // priority 0 → all concurrent tasks settle
463
+ // priority 1 → all concurrent tasks settle
464
+ // priority 2 → all concurrent tasks settle
465
+ async execute() {
466
+ const allResults = new Map();
467
+ for (const tier of this.tierOrder) {
468
+ const tierQueue = this.tiers.get(tier);
469
+ const staged = this.stagedTasks.get(tier) ?? [];
470
+ const tierResults = this.tierResults.get(tier);
471
+ if (staged.length === 0) {
472
+ allResults.set(tier, [...tierResults]);
473
+ continue;
474
+ }
475
+ console.log(`▶[QUEUE-TIERED][START][${tier}] ${staged.length} task(s)`);
476
+ const pending = staged.splice(0, staged.length); // Queue all members of the batch BEFORE start(). This guarantees every task in the batch is available together. `Queue.process()` then chooses how many can actually run at once, according to its `concurrent` setting.
477
+ const scheduled = pending.map((entry) => {
478
+ return tierQueue(async () => {
479
+ const startedAt = Date.now();
480
+ try {
481
+ const value = await entry.task();
482
+ const duration = Date.now() - startedAt;
483
+ tierResults.push(value);
484
+ entry.resolve(value);
485
+ console.log(`✔[QUEUE][DONE][T${tier}] [${entry.label}] ⏱️${duration}ms`);
486
+ return value;
487
+ }
488
+ catch (error) {
489
+ const duration = Date.now() - startedAt;
490
+ console.log(`✘[QUEUE][FAIL][T${tier}]:[${entry.label}] ⏱️${duration}ms Error: ${error} `);
491
+ entry.resolve(undefined); // Preserve your old return convention: failed ADD calls resolve undefined rather than reject. If you prefer normal Promise semantics, replace this line with `entry.reject(error)`.
492
+ throw error;
493
+ }
494
+ }, { label: entry.label });
495
+ });
496
+ tierQueue.start(); // Release this exact priority batch only after all members have been queued.
497
+ await Promise.allSettled(scheduled); // Do not use Promise.all here: one rejected task would cause the next priority batch to start early.
498
+ await tierQueue.onIdle(); // This is mostly redundant after `allSettled`, but retains the queue's own authoritative idle lifecycle.
499
+ this.config.onTierComplete?.(tier, [...tierResults]);
500
+ allResults.set(tier, [...tierResults]);
501
+ console.log(`✔[QUEUE-TIERED][BATCH-DONE][${tier}]: ${tierResults.length} successful result(s)`);
502
+ }
503
+ return allResults;
504
+ }
505
+ getStatus() {
506
+ return this.tierOrder.map((tier) => {
507
+ const tierQueue = this.tiers.get(tier);
508
+ return {
509
+ tier,
510
+ staged: this.stagedTasks.get(tier)?.length ?? 0,
511
+ pending: tierQueue.pending,
512
+ active: tierQueue.active,
513
+ completed: this.tierResults.get(tier)?.length ?? 0,
514
+ };
515
+ });
516
+ } // Cancels tasks that have not reached an active queue yet. Existing active tasks cannot generally be force-cancelled unless their `task()` implementation supports AbortSignal.
517
+ clear() {
518
+ for (const [tier, staged] of this.stagedTasks) {
519
+ for (const entry of staged) {
520
+ entry.reject(new Error(`Tier ${tier} cleared before execution`));
521
+ }
522
+ staged.length = 0;
523
+ }
524
+ for (const tierQueue of this.tiers.values()) {
525
+ tierQueue.clear();
526
+ }
527
+ for (const results of this.tierResults.values()) {
528
+ results.length = 0;
529
+ }
530
+ }
531
+ }
532
+ // #endregion
@@ -0,0 +1 @@
1
+ export {};