semola 0.5.4 → 0.6.1

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.
Files changed (50) hide show
  1. package/README.md +35 -50
  2. package/dist/lib/api/index.cjs +1 -523
  3. package/dist/lib/api/index.d.cts +1 -271
  4. package/dist/lib/api/index.d.mts +80 -84
  5. package/dist/lib/api/index.mjs +1 -521
  6. package/dist/lib/cache/index.cjs +1 -74
  7. package/dist/lib/cache/index.d.cts +1 -48
  8. package/dist/lib/cache/index.d.mts +3 -24
  9. package/dist/lib/cache/index.mjs +1 -73
  10. package/dist/lib/cron/index.cjs +1 -735
  11. package/dist/lib/cron/index.d.cts +1 -146
  12. package/dist/lib/cron/index.d.mts +99 -36
  13. package/dist/lib/cron/index.mjs +1 -726
  14. package/dist/lib/errors/index.cjs +1 -30
  15. package/dist/lib/errors/index.d.cts +1 -2
  16. package/dist/lib/errors/index.d.mts +12 -1
  17. package/dist/lib/errors/index.mjs +1 -26
  18. package/dist/lib/i18n/index.cjs +1 -42
  19. package/dist/lib/i18n/index.d.cts +1 -28
  20. package/dist/lib/i18n/index.mjs +1 -41
  21. package/dist/lib/logging/index.cjs +1 -387
  22. package/dist/lib/logging/index.d.cts +1 -108
  23. package/dist/lib/logging/index.mjs +1 -374
  24. package/dist/lib/orm/index.cjs +1 -0
  25. package/dist/lib/orm/index.d.cts +1 -0
  26. package/dist/lib/orm/index.d.mts +404 -0
  27. package/dist/lib/orm/index.mjs +1 -0
  28. package/dist/lib/policy/index.cjs +1 -285
  29. package/dist/lib/policy/index.d.cts +1 -77
  30. package/dist/lib/policy/index.mjs +1 -265
  31. package/dist/lib/prompts/index.cjs +6 -769
  32. package/dist/lib/prompts/index.d.cts +1 -96
  33. package/dist/lib/prompts/index.d.mts +12 -33
  34. package/dist/lib/prompts/index.mjs +6 -763
  35. package/dist/lib/pubsub/index.cjs +1 -117
  36. package/dist/lib/pubsub/index.d.cts +1 -41
  37. package/dist/lib/pubsub/index.d.mts +3 -18
  38. package/dist/lib/pubsub/index.mjs +1 -116
  39. package/dist/lib/queue/index.cjs +1 -182
  40. package/dist/lib/queue/index.d.cts +1 -74
  41. package/dist/lib/queue/index.d.mts +11 -4
  42. package/dist/lib/queue/index.mjs +1 -181
  43. package/dist/lib/workflow/index.cjs +1 -534
  44. package/dist/lib/workflow/index.d.cts +1 -85
  45. package/dist/lib/workflow/index.d.mts +76 -11
  46. package/dist/lib/workflow/index.mjs +1 -533
  47. package/dist/rolldown-runtime-CMqjfN_6.cjs +1 -0
  48. package/package.json +17 -5
  49. package/dist/index-BhGNDjPq.d.mts +0 -13
  50. package/dist/index-DxSbeGP-.d.cts +0 -13
@@ -1,117 +1 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_lib_errors_index = require("../errors/index.cjs");
3
- //#region src/lib/pubsub/index.ts
4
- var PubSub = class {
5
- options;
6
- isSubscribed = false;
7
- nextHandlerId = 0;
8
- handlers = /* @__PURE__ */ new Map();
9
- unsubscribeInFlight = null;
10
- subscribeInFlight = null;
11
- constructor(options) {
12
- this.options = options;
13
- }
14
- async onMessage(message, channel) {
15
- const [parseError, parsed] = require_lib_errors_index.mightThrowSync(() => JSON.parse(message));
16
- if (parseError) return;
17
- if (!parsed) return;
18
- const handlers = Array.from(this.handlers.values());
19
- for (const handler of handlers) await require_lib_errors_index.mightThrow(Promise.resolve().then(() => handler(parsed, channel)));
20
- }
21
- async unsubscribeHandler(handlerId) {
22
- const inFlightUnsubscribe = this.unsubscribeInFlight;
23
- if (inFlightUnsubscribe) await inFlightUnsubscribe;
24
- const handler = this.handlers.get(handlerId);
25
- if (!handler) return require_lib_errors_index.err("UnsubscribeError", "Not subscribed");
26
- this.handlers.delete(handlerId);
27
- if (this.handlers.size > 0) return require_lib_errors_index.ok(true);
28
- this.isSubscribed = false;
29
- this.unsubscribeInFlight = require_lib_errors_index.mightThrow(this.options.subscriber.unsubscribe(this.options.channel));
30
- const unsubscribeInFlight = this.unsubscribeInFlight;
31
- if (!unsubscribeInFlight) {
32
- this.handlers.set(handlerId, handler);
33
- this.isSubscribed = true;
34
- return require_lib_errors_index.err("UnsubscribeError", `Unable to unsubscribe from ${this.options.channel}`);
35
- }
36
- const [unsubscribeError] = await unsubscribeInFlight;
37
- if (unsubscribeError) {
38
- this.handlers.set(handlerId, handler);
39
- this.isSubscribed = true;
40
- this.unsubscribeInFlight = null;
41
- return require_lib_errors_index.err("UnsubscribeError", `Unable to unsubscribe from ${this.options.channel}`);
42
- }
43
- this.unsubscribeInFlight = null;
44
- return require_lib_errors_index.ok(true);
45
- }
46
- async publish(message) {
47
- const [stringifyError, stringified] = require_lib_errors_index.mightThrowSync(() => JSON.stringify(message));
48
- if (stringifyError || !stringified) return require_lib_errors_index.err("SerializationError", "Unable to serialize message");
49
- const [publishError, count] = await require_lib_errors_index.mightThrow(this.options.publisher.publish(this.options.channel, stringified));
50
- if (publishError) return require_lib_errors_index.err("PublishError", `Unable to publish to ${this.options.channel}`);
51
- return require_lib_errors_index.ok(count);
52
- }
53
- async subscribe(handler) {
54
- const inFlightUnsubscribe = this.unsubscribeInFlight;
55
- if (inFlightUnsubscribe) await inFlightUnsubscribe;
56
- const handlerId = this.nextHandlerId;
57
- this.nextHandlerId += 1;
58
- this.handlers.set(handlerId, handler);
59
- if (this.isActive()) return require_lib_errors_index.ok(() => this.unsubscribeHandler(handlerId));
60
- const inFlightSubscribe = this.subscribeInFlight;
61
- if (inFlightSubscribe) {
62
- const [inFlightError] = await inFlightSubscribe;
63
- if (inFlightError || !this.isSubscribed) {
64
- this.handlers.delete(handlerId);
65
- return require_lib_errors_index.err("SubscribeError", `Unable to subscribe to ${this.options.channel}`);
66
- }
67
- return require_lib_errors_index.ok(() => this.unsubscribeHandler(handlerId));
68
- }
69
- this.subscribeInFlight = require_lib_errors_index.mightThrow(this.options.subscriber.subscribe(this.options.channel, async (message, channel) => this.onMessage(message, channel)));
70
- const subscribeInFlight = this.subscribeInFlight;
71
- if (!subscribeInFlight) {
72
- this.handlers.delete(handlerId);
73
- return require_lib_errors_index.err("SubscribeError", `Unable to subscribe to ${this.options.channel}`);
74
- }
75
- const [subscribeError, count] = await subscribeInFlight;
76
- this.subscribeInFlight = null;
77
- if (subscribeError) {
78
- this.handlers.delete(handlerId);
79
- return require_lib_errors_index.err("SubscribeError", `Unable to subscribe to ${this.options.channel}`);
80
- }
81
- if (!count) {
82
- this.handlers.delete(handlerId);
83
- return require_lib_errors_index.err("SubscribeError", `Unable to subscribe to ${this.options.channel}`);
84
- }
85
- this.isSubscribed = true;
86
- return require_lib_errors_index.ok(() => this.unsubscribeHandler(handlerId));
87
- }
88
- async unsubscribe() {
89
- const inFlightUnsubscribe = this.unsubscribeInFlight;
90
- if (inFlightUnsubscribe) await inFlightUnsubscribe;
91
- if (!this.isActive()) return require_lib_errors_index.err("UnsubscribeError", "Not subscribed");
92
- const handlers = new Map(this.handlers);
93
- this.handlers.clear();
94
- this.isSubscribed = false;
95
- this.unsubscribeInFlight = require_lib_errors_index.mightThrow(this.options.subscriber.unsubscribe(this.options.channel));
96
- const unsubscribeInFlight = this.unsubscribeInFlight;
97
- if (!unsubscribeInFlight) {
98
- this.handlers = handlers;
99
- this.isSubscribed = true;
100
- return require_lib_errors_index.err("UnsubscribeError", `Unable to unsubscribe from ${this.options.channel}`);
101
- }
102
- const [unsubscribeError] = await unsubscribeInFlight;
103
- if (unsubscribeError) {
104
- this.handlers = handlers;
105
- this.isSubscribed = true;
106
- this.unsubscribeInFlight = null;
107
- return require_lib_errors_index.err("UnsubscribeError", `Unable to unsubscribe from ${this.options.channel}`);
108
- }
109
- this.unsubscribeInFlight = null;
110
- return require_lib_errors_index.ok(true);
111
- }
112
- isActive() {
113
- return this.handlers.size > 0 && this.isSubscribed;
114
- }
115
- };
116
- //#endregion
117
- exports.PubSub = PubSub;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../errors/index.cjs");var t=class extends Error{constructor(e){super(e),this.name=`UnsubscribeError`}},n=class extends Error{constructor(e){super(e),this.name=`SerializationError`}},r=class extends Error{constructor(e){super(e),this.name=`PublishError`}},i=class extends Error{constructor(e){super(e),this.name=`SubscribeError`}},a=class{options;isSubscribed=!1;nextHandlerId=0;handlers=new Map;unsubscribeInFlight=null;subscribeInFlight=null;constructor(e){this.options=e}async onMessage(t,n){let[r,i]=e.mightThrowSync(()=>JSON.parse(t));if(r||!i)return;let a=Array.from(this.handlers.values());for(let t of a)await e.mightThrow(Promise.resolve().then(()=>t(i,n)))}async unsubscribeHandler(n){let r=this.unsubscribeInFlight;r&&await r;let i=this.handlers.get(n);if(!i)throw new t(`Not subscribed`);if(this.handlers.delete(n),this.handlers.size>0)return;this.isSubscribed=!1,this.unsubscribeInFlight=e.mightThrow(this.options.subscriber.unsubscribe(this.options.channel));let a=this.unsubscribeInFlight;if(!a)throw this.handlers.set(n,i),this.isSubscribed=!0,new t(`Unable to unsubscribe from ${this.options.channel}`);let[o]=await a;if(o)throw this.handlers.set(n,i),this.isSubscribed=!0,this.unsubscribeInFlight=null,new t(`Unable to unsubscribe from ${this.options.channel}`);this.unsubscribeInFlight=null}async publish(t){let[i,a]=e.mightThrowSync(()=>JSON.stringify(t));if(i||!a)throw new n(`Unable to serialize message`);let[o,s]=await e.mightThrow(this.options.publisher.publish(this.options.channel,a));if(o)throw new r(`Unable to publish to ${this.options.channel}`);return s}async subscribe(t){let n=this.unsubscribeInFlight;n&&await n;let r=this.nextHandlerId;if(this.nextHandlerId+=1,this.handlers.set(r,t),this.isActive())return()=>this.unsubscribeHandler(r);let a=this.subscribeInFlight;if(a){let[e]=await a;if(e||!this.isSubscribed)throw this.handlers.delete(r),new i(`Unable to subscribe to ${this.options.channel}`);return()=>this.unsubscribeHandler(r)}this.subscribeInFlight=e.mightThrow(this.options.subscriber.subscribe(this.options.channel,async(e,t)=>this.onMessage(e,t)));let o=this.subscribeInFlight;if(!o)throw this.handlers.delete(r),new i(`Unable to subscribe to ${this.options.channel}`);let[s,c]=await o;if(this.subscribeInFlight=null,s||!c)throw this.handlers.delete(r),new i(`Unable to subscribe to ${this.options.channel}`);return this.isSubscribed=!0,()=>this.unsubscribeHandler(r)}async unsubscribe(){let n=this.unsubscribeInFlight;if(n&&await n,!this.isActive())throw new t(`Not subscribed`);let r=new Map(this.handlers);this.handlers.clear(),this.isSubscribed=!1,this.unsubscribeInFlight=e.mightThrow(this.options.subscriber.unsubscribe(this.options.channel));let i=this.unsubscribeInFlight;if(!i)throw this.handlers=r,this.isSubscribed=!0,new t(`Unable to unsubscribe from ${this.options.channel}`);let[a]=await i;if(a)throw this.handlers=r,this.isSubscribed=!0,this.unsubscribeInFlight=null,new t(`Unable to unsubscribe from ${this.options.channel}`);this.unsubscribeInFlight=null}isActive(){return this.handlers.size>0&&this.isSubscribed}};exports.PubSub=a;
@@ -1,41 +1 @@
1
- //#region src/lib/pubsub/types.d.ts
2
- type PubSubOptions = {
3
- subscriber: Bun.RedisClient;
4
- publisher: Bun.RedisClient;
5
- channel: string;
6
- };
7
- type MessageHandler<T> = (message: T, channel: string) => void | Promise<void>;
8
- //#endregion
9
- //#region src/lib/pubsub/index.d.ts
10
- declare class PubSub<T extends Record<string, unknown>> {
11
- private options;
12
- private isSubscribed;
13
- private nextHandlerId;
14
- private handlers;
15
- private unsubscribeInFlight;
16
- private subscribeInFlight;
17
- constructor(options: PubSubOptions);
18
- private onMessage;
19
- private unsubscribeHandler;
20
- publish(message: T): Promise<readonly [{
21
- readonly type: "SerializationError";
22
- readonly message: string;
23
- }, null] | readonly [{
24
- readonly type: "PublishError";
25
- readonly message: string;
26
- }, null] | readonly [null, number]>;
27
- subscribe(handler: MessageHandler<T>): Promise<readonly [null, () => Promise<readonly [{
28
- readonly type: "UnsubscribeError";
29
- readonly message: string;
30
- }, null] | readonly [null, boolean]>] | readonly [{
31
- readonly type: "SubscribeError";
32
- readonly message: string;
33
- }, null]>;
34
- unsubscribe(): Promise<readonly [{
35
- readonly type: "UnsubscribeError";
36
- readonly message: string;
37
- }, null] | readonly [null, boolean]>;
38
- isActive(): boolean;
39
- }
40
- //#endregion
41
- export { PubSub };
1
+ export type * from './index.d.mts'
@@ -17,24 +17,9 @@ declare class PubSub<T extends Record<string, unknown>> {
17
17
  constructor(options: PubSubOptions);
18
18
  private onMessage;
19
19
  private unsubscribeHandler;
20
- publish(message: T): Promise<readonly [{
21
- readonly type: "SerializationError";
22
- readonly message: string;
23
- }, null] | readonly [{
24
- readonly type: "PublishError";
25
- readonly message: string;
26
- }, null] | readonly [null, number]>;
27
- subscribe(handler: MessageHandler<T>): Promise<readonly [null, () => Promise<readonly [{
28
- readonly type: "UnsubscribeError";
29
- readonly message: string;
30
- }, null] | readonly [null, boolean]>] | readonly [{
31
- readonly type: "SubscribeError";
32
- readonly message: string;
33
- }, null]>;
34
- unsubscribe(): Promise<readonly [{
35
- readonly type: "UnsubscribeError";
36
- readonly message: string;
37
- }, null] | readonly [null, boolean]>;
20
+ publish(message: T): Promise<number>;
21
+ subscribe(handler: MessageHandler<T>): Promise<() => Promise<void>>;
22
+ unsubscribe(): Promise<void>;
38
23
  isActive(): boolean;
39
24
  }
40
25
  //#endregion
@@ -1,116 +1 @@
1
- import { err, mightThrow, mightThrowSync, ok } from "../errors/index.mjs";
2
- //#region src/lib/pubsub/index.ts
3
- var PubSub = class {
4
- options;
5
- isSubscribed = false;
6
- nextHandlerId = 0;
7
- handlers = /* @__PURE__ */ new Map();
8
- unsubscribeInFlight = null;
9
- subscribeInFlight = null;
10
- constructor(options) {
11
- this.options = options;
12
- }
13
- async onMessage(message, channel) {
14
- const [parseError, parsed] = mightThrowSync(() => JSON.parse(message));
15
- if (parseError) return;
16
- if (!parsed) return;
17
- const handlers = Array.from(this.handlers.values());
18
- for (const handler of handlers) await mightThrow(Promise.resolve().then(() => handler(parsed, channel)));
19
- }
20
- async unsubscribeHandler(handlerId) {
21
- const inFlightUnsubscribe = this.unsubscribeInFlight;
22
- if (inFlightUnsubscribe) await inFlightUnsubscribe;
23
- const handler = this.handlers.get(handlerId);
24
- if (!handler) return err("UnsubscribeError", "Not subscribed");
25
- this.handlers.delete(handlerId);
26
- if (this.handlers.size > 0) return ok(true);
27
- this.isSubscribed = false;
28
- this.unsubscribeInFlight = mightThrow(this.options.subscriber.unsubscribe(this.options.channel));
29
- const unsubscribeInFlight = this.unsubscribeInFlight;
30
- if (!unsubscribeInFlight) {
31
- this.handlers.set(handlerId, handler);
32
- this.isSubscribed = true;
33
- return err("UnsubscribeError", `Unable to unsubscribe from ${this.options.channel}`);
34
- }
35
- const [unsubscribeError] = await unsubscribeInFlight;
36
- if (unsubscribeError) {
37
- this.handlers.set(handlerId, handler);
38
- this.isSubscribed = true;
39
- this.unsubscribeInFlight = null;
40
- return err("UnsubscribeError", `Unable to unsubscribe from ${this.options.channel}`);
41
- }
42
- this.unsubscribeInFlight = null;
43
- return ok(true);
44
- }
45
- async publish(message) {
46
- const [stringifyError, stringified] = mightThrowSync(() => JSON.stringify(message));
47
- if (stringifyError || !stringified) return err("SerializationError", "Unable to serialize message");
48
- const [publishError, count] = await mightThrow(this.options.publisher.publish(this.options.channel, stringified));
49
- if (publishError) return err("PublishError", `Unable to publish to ${this.options.channel}`);
50
- return ok(count);
51
- }
52
- async subscribe(handler) {
53
- const inFlightUnsubscribe = this.unsubscribeInFlight;
54
- if (inFlightUnsubscribe) await inFlightUnsubscribe;
55
- const handlerId = this.nextHandlerId;
56
- this.nextHandlerId += 1;
57
- this.handlers.set(handlerId, handler);
58
- if (this.isActive()) return ok(() => this.unsubscribeHandler(handlerId));
59
- const inFlightSubscribe = this.subscribeInFlight;
60
- if (inFlightSubscribe) {
61
- const [inFlightError] = await inFlightSubscribe;
62
- if (inFlightError || !this.isSubscribed) {
63
- this.handlers.delete(handlerId);
64
- return err("SubscribeError", `Unable to subscribe to ${this.options.channel}`);
65
- }
66
- return ok(() => this.unsubscribeHandler(handlerId));
67
- }
68
- this.subscribeInFlight = mightThrow(this.options.subscriber.subscribe(this.options.channel, async (message, channel) => this.onMessage(message, channel)));
69
- const subscribeInFlight = this.subscribeInFlight;
70
- if (!subscribeInFlight) {
71
- this.handlers.delete(handlerId);
72
- return err("SubscribeError", `Unable to subscribe to ${this.options.channel}`);
73
- }
74
- const [subscribeError, count] = await subscribeInFlight;
75
- this.subscribeInFlight = null;
76
- if (subscribeError) {
77
- this.handlers.delete(handlerId);
78
- return err("SubscribeError", `Unable to subscribe to ${this.options.channel}`);
79
- }
80
- if (!count) {
81
- this.handlers.delete(handlerId);
82
- return err("SubscribeError", `Unable to subscribe to ${this.options.channel}`);
83
- }
84
- this.isSubscribed = true;
85
- return ok(() => this.unsubscribeHandler(handlerId));
86
- }
87
- async unsubscribe() {
88
- const inFlightUnsubscribe = this.unsubscribeInFlight;
89
- if (inFlightUnsubscribe) await inFlightUnsubscribe;
90
- if (!this.isActive()) return err("UnsubscribeError", "Not subscribed");
91
- const handlers = new Map(this.handlers);
92
- this.handlers.clear();
93
- this.isSubscribed = false;
94
- this.unsubscribeInFlight = mightThrow(this.options.subscriber.unsubscribe(this.options.channel));
95
- const unsubscribeInFlight = this.unsubscribeInFlight;
96
- if (!unsubscribeInFlight) {
97
- this.handlers = handlers;
98
- this.isSubscribed = true;
99
- return err("UnsubscribeError", `Unable to unsubscribe from ${this.options.channel}`);
100
- }
101
- const [unsubscribeError] = await unsubscribeInFlight;
102
- if (unsubscribeError) {
103
- this.handlers = handlers;
104
- this.isSubscribed = true;
105
- this.unsubscribeInFlight = null;
106
- return err("UnsubscribeError", `Unable to unsubscribe from ${this.options.channel}`);
107
- }
108
- this.unsubscribeInFlight = null;
109
- return ok(true);
110
- }
111
- isActive() {
112
- return this.handlers.size > 0 && this.isSubscribed;
113
- }
114
- };
115
- //#endregion
116
- export { PubSub };
1
+ import{mightThrow as e,mightThrowSync as t}from"../errors/index.mjs";var n=class extends Error{constructor(e){super(e),this.name=`UnsubscribeError`}},r=class extends Error{constructor(e){super(e),this.name=`SerializationError`}},i=class extends Error{constructor(e){super(e),this.name=`PublishError`}},a=class extends Error{constructor(e){super(e),this.name=`SubscribeError`}},o=class{options;isSubscribed=!1;nextHandlerId=0;handlers=new Map;unsubscribeInFlight=null;subscribeInFlight=null;constructor(e){this.options=e}async onMessage(n,r){let[i,a]=t(()=>JSON.parse(n));if(i||!a)return;let o=Array.from(this.handlers.values());for(let t of o)await e(Promise.resolve().then(()=>t(a,r)))}async unsubscribeHandler(t){let r=this.unsubscribeInFlight;r&&await r;let i=this.handlers.get(t);if(!i)throw new n(`Not subscribed`);if(this.handlers.delete(t),this.handlers.size>0)return;this.isSubscribed=!1,this.unsubscribeInFlight=e(this.options.subscriber.unsubscribe(this.options.channel));let a=this.unsubscribeInFlight;if(!a)throw this.handlers.set(t,i),this.isSubscribed=!0,new n(`Unable to unsubscribe from ${this.options.channel}`);let[o]=await a;if(o)throw this.handlers.set(t,i),this.isSubscribed=!0,this.unsubscribeInFlight=null,new n(`Unable to unsubscribe from ${this.options.channel}`);this.unsubscribeInFlight=null}async publish(n){let[a,o]=t(()=>JSON.stringify(n));if(a||!o)throw new r(`Unable to serialize message`);let[s,c]=await e(this.options.publisher.publish(this.options.channel,o));if(s)throw new i(`Unable to publish to ${this.options.channel}`);return c}async subscribe(t){let n=this.unsubscribeInFlight;n&&await n;let r=this.nextHandlerId;if(this.nextHandlerId+=1,this.handlers.set(r,t),this.isActive())return()=>this.unsubscribeHandler(r);let i=this.subscribeInFlight;if(i){let[e]=await i;if(e||!this.isSubscribed)throw this.handlers.delete(r),new a(`Unable to subscribe to ${this.options.channel}`);return()=>this.unsubscribeHandler(r)}this.subscribeInFlight=e(this.options.subscriber.subscribe(this.options.channel,async(e,t)=>this.onMessage(e,t)));let o=this.subscribeInFlight;if(!o)throw this.handlers.delete(r),new a(`Unable to subscribe to ${this.options.channel}`);let[s,c]=await o;if(this.subscribeInFlight=null,s||!c)throw this.handlers.delete(r),new a(`Unable to subscribe to ${this.options.channel}`);return this.isSubscribed=!0,()=>this.unsubscribeHandler(r)}async unsubscribe(){let t=this.unsubscribeInFlight;if(t&&await t,!this.isActive())throw new n(`Not subscribed`);let r=new Map(this.handlers);this.handlers.clear(),this.isSubscribed=!1,this.unsubscribeInFlight=e(this.options.subscriber.unsubscribe(this.options.channel));let i=this.unsubscribeInFlight;if(!i)throw this.handlers=r,this.isSubscribed=!0,new n(`Unable to unsubscribe from ${this.options.channel}`);let[a]=await i;if(a)throw this.handlers=r,this.isSubscribed=!0,this.unsubscribeInFlight=null,new n(`Unable to unsubscribe from ${this.options.channel}`);this.unsubscribeInFlight=null}isActive(){return this.handlers.size>0&&this.isSubscribed}};export{o as PubSub};
@@ -1,182 +1 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_lib_errors_index = require("../errors/index.cjs");
3
- //#region src/lib/queue/index.ts
4
- const toMinimalJob = (jobState) => ({
5
- id: jobState.id,
6
- data: jobState.data,
7
- attempts: jobState.attempts,
8
- maxRetries: jobState.maxRetries,
9
- createdAt: jobState.createdAt
10
- });
11
- const DEFAULT_RETRIES = 3;
12
- const DEFAULT_TIMEOUT = 3e4;
13
- const DEFAULT_CONCURRENCY = 1;
14
- const DEFAULT_POLL_INTERVAL = 100;
15
- const MAX_BACKOFF_DELAY = 6e4;
16
- const BASE_BACKOFF_DELAY = 1e3;
17
- const BACKOFF_MULTIPLIER = 2;
18
- const SHUTDOWN_POLL_INTERVAL = 10;
19
- var Queue = class {
20
- options;
21
- running = true;
22
- activeWorkers = 0;
23
- retries;
24
- timeout;
25
- concurrency;
26
- pollInterval;
27
- constructor(options) {
28
- this.options = options;
29
- this.retries = options.retries ?? DEFAULT_RETRIES;
30
- this.timeout = options.timeout ?? DEFAULT_TIMEOUT;
31
- this.concurrency = options.concurrency ?? DEFAULT_CONCURRENCY;
32
- this.pollInterval = options.pollInterval ?? DEFAULT_POLL_INTERVAL;
33
- this.startWorkers();
34
- }
35
- async enqueue(data) {
36
- const job = {
37
- id: crypto.randomUUID(),
38
- data,
39
- attempts: 0,
40
- maxRetries: this.retries,
41
- createdAt: Date.now()
42
- };
43
- const [serializeError, serialized] = this.serializeJob(job);
44
- if (serializeError || !serialized) return require_lib_errors_index.err("QueueError", "Unable to serialize job data");
45
- const [enqueueError] = await this.enqueueJobData(serialized);
46
- if (enqueueError) return require_lib_errors_index.err("QueueError", "Unable to enqueue job");
47
- return require_lib_errors_index.ok(job.id);
48
- }
49
- async stop() {
50
- this.running = false;
51
- while (this.activeWorkers > 0) await new Promise((resolve) => setTimeout(resolve, SHUTDOWN_POLL_INTERVAL));
52
- }
53
- waitForPollInterval() {
54
- return new Promise((resolve) => setTimeout(resolve, this.pollInterval));
55
- }
56
- serializeJob(job) {
57
- return require_lib_errors_index.mightThrowSync(() => JSON.stringify(job));
58
- }
59
- async enqueueJobData(serialized) {
60
- const queueKey = `queue:${this.options.name}:jobs`;
61
- return require_lib_errors_index.mightThrow(this.options.redis.lpush(queueKey, serialized));
62
- }
63
- async moveToDeadLetterQueue(jobData, parseError) {
64
- const deadLetterKey = `queue:${this.options.name}:dead-letter`;
65
- const deadLetterEntry = JSON.stringify({
66
- jobData,
67
- parseError: this.formatErrorMessage(parseError),
68
- timestamp: Date.now()
69
- });
70
- return require_lib_errors_index.mightThrow(this.options.redis.lpush(deadLetterKey, deadLetterEntry));
71
- }
72
- formatErrorMessage(error) {
73
- return error instanceof Error ? error.message : String(error);
74
- }
75
- startWorkers() {
76
- for (let i = 0; i < this.concurrency; i++) this.processJobs();
77
- }
78
- async processJobs() {
79
- while (this.running) {
80
- const queueKey = `queue:${this.options.name}:jobs`;
81
- const [popError, jobData] = await require_lib_errors_index.mightThrow(this.options.redis.rpop(queueKey));
82
- if (popError) {
83
- await this.waitForPollInterval();
84
- continue;
85
- }
86
- if (!jobData) {
87
- await this.waitForPollInterval();
88
- continue;
89
- }
90
- const [parseError, job] = require_lib_errors_index.mightThrowSync(() => JSON.parse(jobData));
91
- if (parseError || !job) {
92
- await this.callOnErrorForParseFailure(jobData, parseError);
93
- await this.moveToDeadLetterQueue(jobData, parseError);
94
- await this.waitForPollInterval();
95
- continue;
96
- }
97
- if (!this.running) {
98
- const [stringifyError, serialized] = this.serializeJob(job);
99
- if (!stringifyError && serialized) await require_lib_errors_index.mightThrow(this.options.redis.lpush(queueKey, serialized));
100
- break;
101
- }
102
- this.activeWorkers++;
103
- await require_lib_errors_index.mightThrow(this.handleJob(job));
104
- this.activeWorkers--;
105
- }
106
- }
107
- async handleJob(job) {
108
- const controller = new AbortController();
109
- const handlerPromise = Promise.resolve().then(() => this.options.handler(job.data, controller.signal));
110
- let timerId;
111
- const timeoutPromise = new Promise((_, reject) => {
112
- timerId = setTimeout(() => {
113
- reject(/* @__PURE__ */ new Error(`Job timeout after ${this.timeout}ms`));
114
- }, this.timeout);
115
- });
116
- const [handlerError] = await require_lib_errors_index.mightThrow(Promise.race([handlerPromise.then(() => void 0), timeoutPromise]));
117
- if (timerId) clearTimeout(timerId);
118
- if (handlerError && !controller.signal.aborted) controller.abort();
119
- if (!handlerError) {
120
- if (this.options.onSuccess) await require_lib_errors_index.mightThrow(Promise.resolve(this.options.onSuccess(toMinimalJob(job))));
121
- return;
122
- }
123
- job.attempts++;
124
- const errorMsg = this.formatErrorMessage(handlerError);
125
- job.error = errorMsg;
126
- if (!job.errorHistory) job.errorHistory = [];
127
- job.errorHistory.push({
128
- attempt: job.attempts,
129
- error: errorMsg,
130
- timestamp: Date.now()
131
- });
132
- if (job.attempts <= job.maxRetries) {
133
- if (this.options.onRetry) {
134
- const delay = Math.min(BASE_BACKOFF_DELAY * BACKOFF_MULTIPLIER ** (job.attempts - 1), MAX_BACKOFF_DELAY);
135
- await require_lib_errors_index.mightThrow(Promise.resolve(this.options.onRetry({
136
- job: toMinimalJob(job),
137
- error: errorMsg,
138
- nextRetryDelayMs: delay,
139
- retriesRemaining: job.maxRetries - job.attempts,
140
- backoffMultiplier: BACKOFF_MULTIPLIER
141
- })));
142
- }
143
- await this.retryJob(job);
144
- } else await this.callOnError(job);
145
- }
146
- async callOnError(job) {
147
- if (!this.options.onError) return;
148
- await require_lib_errors_index.mightThrow(Promise.resolve(this.options.onError({
149
- job: toMinimalJob(job),
150
- lastError: job.error ?? "",
151
- totalDurationMs: Date.now() - job.createdAt,
152
- totalAttempts: job.attempts,
153
- errorHistory: job.errorHistory ?? []
154
- })));
155
- }
156
- async callOnErrorForParseFailure(jobData, parseError) {
157
- if (!this.options.onParseError) return;
158
- await require_lib_errors_index.mightThrow(Promise.resolve(this.options.onParseError({
159
- rawJobData: jobData,
160
- parseError: this.formatErrorMessage(parseError),
161
- timestamp: Date.now()
162
- })));
163
- }
164
- async retryJob(job) {
165
- const delay = Math.min(BASE_BACKOFF_DELAY * BACKOFF_MULTIPLIER ** (job.attempts - 1), MAX_BACKOFF_DELAY);
166
- await new Promise((resolve) => setTimeout(resolve, delay));
167
- const [stringifyError, serialized] = this.serializeJob(job);
168
- if (stringifyError || !serialized) {
169
- job.error = `Failed to serialize job for retry: ${this.formatErrorMessage(stringifyError)}`;
170
- await this.callOnError(job);
171
- return;
172
- }
173
- const queueKey = `queue:${this.options.name}:jobs`;
174
- const [pushError] = await require_lib_errors_index.mightThrow(this.options.redis.lpush(queueKey, serialized));
175
- if (pushError) {
176
- job.error = `Failed to re-enqueue job for retry: ${this.formatErrorMessage(pushError)}`;
177
- await this.callOnError(job);
178
- }
179
- }
180
- };
181
- //#endregion
182
- exports.Queue = Queue;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../../rolldown-runtime-CMqjfN_6.cjs"),t=require("../errors/index.cjs");let n=require("node:assert");n=e.t(n,1);var r=class extends Error{constructor(e){super(e),this.name=`SerializationError`}},i=class extends Error{constructor(e){super(e),this.name=`EnqueueError`}};const a=e=>({id:e.id,data:e.data,attempts:e.attempts,maxRetries:e.maxRetries,createdAt:e.createdAt});var o=class{options;running=!0;activeWorkers=0;retries;timeout;concurrency;pollInterval;retryBaseDelay;retryMultiplier;retryMaxDelay;constructor(e){this.options=e,this.retries=e.retries??3,this.timeout=e.timeout??3e4,this.concurrency=e.concurrency??1,this.pollInterval=e.pollInterval??100,this.retryBaseDelay=e.retryBackoff?.baseDelay??1e3,this.retryMultiplier=e.retryBackoff?.multiplier??2,this.retryMaxDelay=e.retryBackoff?.maxDelay??6e4,n.default.ok(Number.isFinite(this.retryBaseDelay)&&this.retryBaseDelay>0,`Invalid retryBackoff.baseDelay: must be a positive finite number`),n.default.ok(Number.isFinite(this.retryMultiplier)&&this.retryMultiplier>0,`Invalid retryBackoff.multiplier: must be a positive finite number`),n.default.ok(Number.isFinite(this.retryMaxDelay)&&this.retryMaxDelay>0,`Invalid retryBackoff.maxDelay: must be a positive finite number`),this.startWorkers()}computeBackoffDelay(e){return Math.min(this.retryBaseDelay*this.retryMultiplier**(e-1),this.retryMaxDelay)}async enqueue(e){let t={id:crypto.randomUUID(),data:e,attempts:0,maxRetries:this.retries,createdAt:Date.now()},[n,a]=this.serializeJob(t);if(n||!a)throw new r(`Unable to serialize job data`);let[o]=await this.enqueueJobData(a);if(o)throw new i(`Unable to enqueue job`);return t.id}async stop(){for(this.running=!1;this.activeWorkers>0;)await new Promise(e=>setTimeout(e,10))}waitForPollInterval(){return new Promise(e=>setTimeout(e,this.pollInterval))}serializeJob(e){return t.mightThrowSync(()=>JSON.stringify(e))}async enqueueJobData(e){let n=`queue:${this.options.name}:jobs`;return t.mightThrow(this.options.redis.lpush(n,e))}async moveToDeadLetterQueue(e,n){let r=`queue:${this.options.name}:dead-letter`,i=JSON.stringify({jobData:e,parseError:this.formatErrorMessage(n),timestamp:Date.now()});return t.mightThrow(this.options.redis.lpush(r,i))}formatErrorMessage(e){return e?e.message:`Unknown error`}startWorkers(){for(let e=0;e<this.concurrency;e++)this.processJobs()}async processJobs(){for(;this.running;){let e=`queue:${this.options.name}:jobs`,[n,r]=await t.mightThrow(this.options.redis.rpop(e));if(n){await this.waitForPollInterval();continue}if(!r){await this.waitForPollInterval();continue}let[i,a]=t.mightThrowSync(()=>JSON.parse(r));if(i||!a){await this.callOnErrorForParseFailure(r,i),await this.moveToDeadLetterQueue(r,i),await this.waitForPollInterval();continue}if(!this.running){let[n,r]=this.serializeJob(a);!n&&r&&await t.mightThrow(this.options.redis.lpush(e,r));break}this.activeWorkers++,await t.mightThrow(this.handleJob(a)),this.activeWorkers--}}async handleJob(e){let n=new AbortController,r=Promise.resolve().then(()=>this.options.handler(e.data,n.signal)),i,o=new Promise((e,t)=>{i=setTimeout(()=>{t(Error(`Job timeout after ${this.timeout}ms`))},this.timeout)}),[s]=await t.mightThrow(Promise.race([r.then(()=>void 0),o]));if(i&&clearTimeout(i),s&&!n.signal.aborted&&n.abort(),!s){this.options.onSuccess&&await t.mightThrow(Promise.resolve(this.options.onSuccess(a(e))));return}e.attempts++;let c=this.formatErrorMessage(s);if(e.error=c,e.errorHistory||=[],e.errorHistory.push({attempt:e.attempts,error:c,timestamp:Date.now()}),e.attempts<=e.maxRetries){if(this.options.onRetry){let n=this.computeBackoffDelay(e.attempts);await t.mightThrow(Promise.resolve(this.options.onRetry({job:a(e),error:c,nextRetryDelayMs:n,retriesRemaining:e.maxRetries-e.attempts,backoffMultiplier:this.retryMultiplier})))}await this.retryJob(e)}else await this.callOnError(e)}async callOnError(e){this.options.onError&&await t.mightThrow(Promise.resolve(this.options.onError({job:a(e),lastError:e.error??``,totalDurationMs:Date.now()-e.createdAt,totalAttempts:e.attempts,errorHistory:e.errorHistory??[]})))}async callOnErrorForParseFailure(e,n){this.options.onParseError&&await t.mightThrow(Promise.resolve(this.options.onParseError({rawJobData:e,parseError:this.formatErrorMessage(n),timestamp:Date.now()})))}async retryJob(e){let n=this.computeBackoffDelay(e.attempts);await new Promise(e=>setTimeout(e,n));let[r,i]=this.serializeJob(e);if(r||!i){e.error=`Failed to serialize job for retry: ${this.formatErrorMessage(r)}`,await this.callOnError(e);return}let a=`queue:${this.options.name}:jobs`,[o]=await t.mightThrow(this.options.redis.lpush(a,i));o&&(e.error=`Failed to re-enqueue job for retry: ${this.formatErrorMessage(o)}`,await this.callOnError(e))}};exports.Queue=o;
@@ -1,74 +1 @@
1
- //#region src/lib/queue/types.d.ts
2
- type Job<T> = {
3
- id: string;
4
- data: T;
5
- attempts: number;
6
- maxRetries: number;
7
- createdAt: number;
8
- };
9
- type RetryContext<T> = {
10
- job: Job<T>;
11
- error: string;
12
- nextRetryDelayMs: number;
13
- retriesRemaining: number;
14
- backoffMultiplier: number;
15
- };
16
- type ErrorContext<T> = {
17
- job: Job<T>;
18
- lastError: string;
19
- totalDurationMs: number;
20
- totalAttempts: number;
21
- errorHistory: Array<{
22
- attempt: number;
23
- error: string;
24
- timestamp: number;
25
- }>;
26
- };
27
- type ParseErrorContext = {
28
- rawJobData: string;
29
- parseError: string;
30
- timestamp: number;
31
- };
32
- type QueueOptions<T> = {
33
- name: string;
34
- redis: Bun.RedisClient;
35
- handler: (data: T, signal?: AbortSignal) => void | Promise<void>;
36
- onSuccess?: (job: Job<T>) => void | Promise<void>;
37
- onRetry?: (context: RetryContext<T>) => void | Promise<void>;
38
- onError?: (context: ErrorContext<T>) => void | Promise<void>;
39
- onParseError?: (context: ParseErrorContext) => void | Promise<void>;
40
- retries?: number;
41
- timeout?: number;
42
- concurrency?: number;
43
- pollInterval?: number;
44
- };
45
- //#endregion
46
- //#region src/lib/queue/index.d.ts
47
- declare class Queue<T> {
48
- private options;
49
- private running;
50
- private activeWorkers;
51
- private retries;
52
- private timeout;
53
- private concurrency;
54
- private pollInterval;
55
- constructor(options: QueueOptions<T>);
56
- enqueue(data: T): Promise<readonly [null, string] | readonly [{
57
- readonly type: "QueueError";
58
- readonly message: string;
59
- }, null]>;
60
- stop(): Promise<void>;
61
- private waitForPollInterval;
62
- private serializeJob;
63
- private enqueueJobData;
64
- private moveToDeadLetterQueue;
65
- private formatErrorMessage;
66
- private startWorkers;
67
- private processJobs;
68
- private handleJob;
69
- private callOnError;
70
- private callOnErrorForParseFailure;
71
- private retryJob;
72
- }
73
- //#endregion
74
- export { Queue };
1
+ export type * from './index.d.mts'
@@ -29,6 +29,11 @@ type ParseErrorContext = {
29
29
  parseError: string;
30
30
  timestamp: number;
31
31
  };
32
+ type QueueRetryBackoff = {
33
+ baseDelay?: number;
34
+ multiplier?: number;
35
+ maxDelay?: number;
36
+ };
32
37
  type QueueOptions<T> = {
33
38
  name: string;
34
39
  redis: Bun.RedisClient;
@@ -38,6 +43,7 @@ type QueueOptions<T> = {
38
43
  onError?: (context: ErrorContext<T>) => void | Promise<void>;
39
44
  onParseError?: (context: ParseErrorContext) => void | Promise<void>;
40
45
  retries?: number;
46
+ retryBackoff?: QueueRetryBackoff;
41
47
  timeout?: number;
42
48
  concurrency?: number;
43
49
  pollInterval?: number;
@@ -52,11 +58,12 @@ declare class Queue<T> {
52
58
  private timeout;
53
59
  private concurrency;
54
60
  private pollInterval;
61
+ private retryBaseDelay;
62
+ private retryMultiplier;
63
+ private retryMaxDelay;
55
64
  constructor(options: QueueOptions<T>);
56
- enqueue(data: T): Promise<readonly [null, string] | readonly [{
57
- readonly type: "QueueError";
58
- readonly message: string;
59
- }, null]>;
65
+ private computeBackoffDelay;
66
+ enqueue(data: T): Promise<string>;
60
67
  stop(): Promise<void>;
61
68
  private waitForPollInterval;
62
69
  private serializeJob;