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,181 +1 @@
1
- import { err, mightThrow, mightThrowSync, ok } from "../errors/index.mjs";
2
- //#region src/lib/queue/index.ts
3
- const toMinimalJob = (jobState) => ({
4
- id: jobState.id,
5
- data: jobState.data,
6
- attempts: jobState.attempts,
7
- maxRetries: jobState.maxRetries,
8
- createdAt: jobState.createdAt
9
- });
10
- const DEFAULT_RETRIES = 3;
11
- const DEFAULT_TIMEOUT = 3e4;
12
- const DEFAULT_CONCURRENCY = 1;
13
- const DEFAULT_POLL_INTERVAL = 100;
14
- const MAX_BACKOFF_DELAY = 6e4;
15
- const BASE_BACKOFF_DELAY = 1e3;
16
- const BACKOFF_MULTIPLIER = 2;
17
- const SHUTDOWN_POLL_INTERVAL = 10;
18
- var Queue = class {
19
- options;
20
- running = true;
21
- activeWorkers = 0;
22
- retries;
23
- timeout;
24
- concurrency;
25
- pollInterval;
26
- constructor(options) {
27
- this.options = options;
28
- this.retries = options.retries ?? DEFAULT_RETRIES;
29
- this.timeout = options.timeout ?? DEFAULT_TIMEOUT;
30
- this.concurrency = options.concurrency ?? DEFAULT_CONCURRENCY;
31
- this.pollInterval = options.pollInterval ?? DEFAULT_POLL_INTERVAL;
32
- this.startWorkers();
33
- }
34
- async enqueue(data) {
35
- const job = {
36
- id: crypto.randomUUID(),
37
- data,
38
- attempts: 0,
39
- maxRetries: this.retries,
40
- createdAt: Date.now()
41
- };
42
- const [serializeError, serialized] = this.serializeJob(job);
43
- if (serializeError || !serialized) return err("QueueError", "Unable to serialize job data");
44
- const [enqueueError] = await this.enqueueJobData(serialized);
45
- if (enqueueError) return err("QueueError", "Unable to enqueue job");
46
- return ok(job.id);
47
- }
48
- async stop() {
49
- this.running = false;
50
- while (this.activeWorkers > 0) await new Promise((resolve) => setTimeout(resolve, SHUTDOWN_POLL_INTERVAL));
51
- }
52
- waitForPollInterval() {
53
- return new Promise((resolve) => setTimeout(resolve, this.pollInterval));
54
- }
55
- serializeJob(job) {
56
- return mightThrowSync(() => JSON.stringify(job));
57
- }
58
- async enqueueJobData(serialized) {
59
- const queueKey = `queue:${this.options.name}:jobs`;
60
- return mightThrow(this.options.redis.lpush(queueKey, serialized));
61
- }
62
- async moveToDeadLetterQueue(jobData, parseError) {
63
- const deadLetterKey = `queue:${this.options.name}:dead-letter`;
64
- const deadLetterEntry = JSON.stringify({
65
- jobData,
66
- parseError: this.formatErrorMessage(parseError),
67
- timestamp: Date.now()
68
- });
69
- return mightThrow(this.options.redis.lpush(deadLetterKey, deadLetterEntry));
70
- }
71
- formatErrorMessage(error) {
72
- return error instanceof Error ? error.message : String(error);
73
- }
74
- startWorkers() {
75
- for (let i = 0; i < this.concurrency; i++) this.processJobs();
76
- }
77
- async processJobs() {
78
- while (this.running) {
79
- const queueKey = `queue:${this.options.name}:jobs`;
80
- const [popError, jobData] = await mightThrow(this.options.redis.rpop(queueKey));
81
- if (popError) {
82
- await this.waitForPollInterval();
83
- continue;
84
- }
85
- if (!jobData) {
86
- await this.waitForPollInterval();
87
- continue;
88
- }
89
- const [parseError, job] = mightThrowSync(() => JSON.parse(jobData));
90
- if (parseError || !job) {
91
- await this.callOnErrorForParseFailure(jobData, parseError);
92
- await this.moveToDeadLetterQueue(jobData, parseError);
93
- await this.waitForPollInterval();
94
- continue;
95
- }
96
- if (!this.running) {
97
- const [stringifyError, serialized] = this.serializeJob(job);
98
- if (!stringifyError && serialized) await mightThrow(this.options.redis.lpush(queueKey, serialized));
99
- break;
100
- }
101
- this.activeWorkers++;
102
- await mightThrow(this.handleJob(job));
103
- this.activeWorkers--;
104
- }
105
- }
106
- async handleJob(job) {
107
- const controller = new AbortController();
108
- const handlerPromise = Promise.resolve().then(() => this.options.handler(job.data, controller.signal));
109
- let timerId;
110
- const timeoutPromise = new Promise((_, reject) => {
111
- timerId = setTimeout(() => {
112
- reject(/* @__PURE__ */ new Error(`Job timeout after ${this.timeout}ms`));
113
- }, this.timeout);
114
- });
115
- const [handlerError] = await mightThrow(Promise.race([handlerPromise.then(() => void 0), timeoutPromise]));
116
- if (timerId) clearTimeout(timerId);
117
- if (handlerError && !controller.signal.aborted) controller.abort();
118
- if (!handlerError) {
119
- if (this.options.onSuccess) await mightThrow(Promise.resolve(this.options.onSuccess(toMinimalJob(job))));
120
- return;
121
- }
122
- job.attempts++;
123
- const errorMsg = this.formatErrorMessage(handlerError);
124
- job.error = errorMsg;
125
- if (!job.errorHistory) job.errorHistory = [];
126
- job.errorHistory.push({
127
- attempt: job.attempts,
128
- error: errorMsg,
129
- timestamp: Date.now()
130
- });
131
- if (job.attempts <= job.maxRetries) {
132
- if (this.options.onRetry) {
133
- const delay = Math.min(BASE_BACKOFF_DELAY * BACKOFF_MULTIPLIER ** (job.attempts - 1), MAX_BACKOFF_DELAY);
134
- await mightThrow(Promise.resolve(this.options.onRetry({
135
- job: toMinimalJob(job),
136
- error: errorMsg,
137
- nextRetryDelayMs: delay,
138
- retriesRemaining: job.maxRetries - job.attempts,
139
- backoffMultiplier: BACKOFF_MULTIPLIER
140
- })));
141
- }
142
- await this.retryJob(job);
143
- } else await this.callOnError(job);
144
- }
145
- async callOnError(job) {
146
- if (!this.options.onError) return;
147
- await mightThrow(Promise.resolve(this.options.onError({
148
- job: toMinimalJob(job),
149
- lastError: job.error ?? "",
150
- totalDurationMs: Date.now() - job.createdAt,
151
- totalAttempts: job.attempts,
152
- errorHistory: job.errorHistory ?? []
153
- })));
154
- }
155
- async callOnErrorForParseFailure(jobData, parseError) {
156
- if (!this.options.onParseError) return;
157
- await mightThrow(Promise.resolve(this.options.onParseError({
158
- rawJobData: jobData,
159
- parseError: this.formatErrorMessage(parseError),
160
- timestamp: Date.now()
161
- })));
162
- }
163
- async retryJob(job) {
164
- const delay = Math.min(BASE_BACKOFF_DELAY * BACKOFF_MULTIPLIER ** (job.attempts - 1), MAX_BACKOFF_DELAY);
165
- await new Promise((resolve) => setTimeout(resolve, delay));
166
- const [stringifyError, serialized] = this.serializeJob(job);
167
- if (stringifyError || !serialized) {
168
- job.error = `Failed to serialize job for retry: ${this.formatErrorMessage(stringifyError)}`;
169
- await this.callOnError(job);
170
- return;
171
- }
172
- const queueKey = `queue:${this.options.name}:jobs`;
173
- const [pushError] = await mightThrow(this.options.redis.lpush(queueKey, serialized));
174
- if (pushError) {
175
- job.error = `Failed to re-enqueue job for retry: ${this.formatErrorMessage(pushError)}`;
176
- await this.callOnError(job);
177
- }
178
- }
179
- };
180
- //#endregion
181
- export { Queue };
1
+ import{mightThrow as e,mightThrowSync as t}from"../errors/index.mjs";import n from"node:assert";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.ok(Number.isFinite(this.retryBaseDelay)&&this.retryBaseDelay>0,`Invalid retryBackoff.baseDelay: must be a positive finite number`),n.ok(Number.isFinite(this.retryMultiplier)&&this.retryMultiplier>0,`Invalid retryBackoff.multiplier: must be a positive finite number`),n.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(()=>JSON.stringify(e))}async enqueueJobData(t){let n=`queue:${this.options.name}:jobs`;return e(this.options.redis.lpush(n,t))}async moveToDeadLetterQueue(t,n){let r=`queue:${this.options.name}:dead-letter`,i=JSON.stringify({jobData:t,parseError:this.formatErrorMessage(n),timestamp:Date.now()});return e(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 n=`queue:${this.options.name}:jobs`,[r,i]=await e(this.options.redis.rpop(n));if(r){await this.waitForPollInterval();continue}if(!i){await this.waitForPollInterval();continue}let[a,o]=t(()=>JSON.parse(i));if(a||!o){await this.callOnErrorForParseFailure(i,a),await this.moveToDeadLetterQueue(i,a),await this.waitForPollInterval();continue}if(!this.running){let[t,r]=this.serializeJob(o);!t&&r&&await e(this.options.redis.lpush(n,r));break}this.activeWorkers++,await e(this.handleJob(o)),this.activeWorkers--}}async handleJob(t){let n=new AbortController,r=Promise.resolve().then(()=>this.options.handler(t.data,n.signal)),i,o=new Promise((e,t)=>{i=setTimeout(()=>{t(Error(`Job timeout after ${this.timeout}ms`))},this.timeout)}),[s]=await e(Promise.race([r.then(()=>void 0),o]));if(i&&clearTimeout(i),s&&!n.signal.aborted&&n.abort(),!s){this.options.onSuccess&&await e(Promise.resolve(this.options.onSuccess(a(t))));return}t.attempts++;let c=this.formatErrorMessage(s);if(t.error=c,t.errorHistory||=[],t.errorHistory.push({attempt:t.attempts,error:c,timestamp:Date.now()}),t.attempts<=t.maxRetries){if(this.options.onRetry){let n=this.computeBackoffDelay(t.attempts);await e(Promise.resolve(this.options.onRetry({job:a(t),error:c,nextRetryDelayMs:n,retriesRemaining:t.maxRetries-t.attempts,backoffMultiplier:this.retryMultiplier})))}await this.retryJob(t)}else await this.callOnError(t)}async callOnError(t){this.options.onError&&await e(Promise.resolve(this.options.onError({job:a(t),lastError:t.error??``,totalDurationMs:Date.now()-t.createdAt,totalAttempts:t.attempts,errorHistory:t.errorHistory??[]})))}async callOnErrorForParseFailure(t,n){this.options.onParseError&&await e(Promise.resolve(this.options.onParseError({rawJobData:t,parseError:this.formatErrorMessage(n),timestamp:Date.now()})))}async retryJob(t){let n=this.computeBackoffDelay(t.attempts);await new Promise(e=>setTimeout(e,n));let[r,i]=this.serializeJob(t);if(r||!i){t.error=`Failed to serialize job for retry: ${this.formatErrorMessage(r)}`,await this.callOnError(t);return}let a=`queue:${this.options.name}:jobs`,[o]=await e(this.options.redis.lpush(a,i));o&&(t.error=`Failed to re-enqueue job for retry: ${this.formatErrorMessage(o)}`,await this.callOnError(t))}};export{o as Queue};