@lunora/scheduler 1.0.0-alpha.2 → 1.0.0-alpha.21
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.md +6 -0
- package/README.md +1 -0
- package/dist/index.d.mts +551 -385
- package/dist/index.d.ts +551 -385
- package/dist/index.mjs +1 -8
- package/dist/packem_shared/CRON_SCHEDULE_KINDS-DMu4DfhG.mjs +1 -0
- package/dist/packem_shared/SchedulerDO-CCP9LV5x.mjs +1 -0
- package/dist/packem_shared/assertValidCronExpression-B2lN8n3O.mjs +1 -0
- package/dist/packem_shared/createCronTrigger-C4iUW_zz.mjs +1 -0
- package/dist/packem_shared/createQueueConsumer-BnX7wkJO.mjs +1 -0
- package/dist/packem_shared/createScheduler-CsRAEtdb.mjs +1 -0
- package/dist/packem_shared/createSchedulerHost-C5XacwXv.mjs +1 -0
- package/dist/packem_shared/createWorkpool-DyVdhB6o.mjs +1 -0
- package/dist/packem_shared/do-client-BFps7NIj.mjs +1 -0
- package/dist/packem_shared/isWorkflowReference-CT3tdefh.mjs +1 -0
- package/package.json +5 -3
- package/dist/packem_shared/CRON_SCHEDULE_KINDS-BaLlXJiN.mjs +0 -123
- package/dist/packem_shared/SchedulerDO-BNzXNnS4.mjs +0 -678
- package/dist/packem_shared/assertValidCronExpression-BLfrDgmK.mjs +0 -20
- package/dist/packem_shared/createCronTrigger-Cq9IBcWQ.mjs +0 -27
- package/dist/packem_shared/createQueueConsumer-DWahNPfz.mjs +0 -59
- package/dist/packem_shared/createScheduler-CWMn70nv.mjs +0 -69
- package/dist/packem_shared/createWorkpool-CEnqCafM.mjs +0 -62
- package/dist/packem_shared/isWorkflowReference-C9mQkMXt.mjs +0 -3
- package/dist/packem_shared/jurisdiction-CR2zC3Et.mjs +0 -13
package/dist/index.mjs
CHANGED
|
@@ -1,8 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { default as createWorkpool } from './packem_shared/createWorkpool-CEnqCafM.mjs';
|
|
3
|
-
export { createCronTrigger } from './packem_shared/createCronTrigger-Cq9IBcWQ.mjs';
|
|
4
|
-
export { CRON_SCHEDULE_KINDS, compileCronSchedule, cronJobs } from './packem_shared/CRON_SCHEDULE_KINDS-BaLlXJiN.mjs';
|
|
5
|
-
export { createQueueConsumer, createQueueWorkpool, httpDispatcher } from './packem_shared/createQueueConsumer-DWahNPfz.mjs';
|
|
6
|
-
export { SchedulerDO } from './packem_shared/SchedulerDO-BNzXNnS4.mjs';
|
|
7
|
-
export { isWorkflowReference } from './packem_shared/isWorkflowReference-C9mQkMXt.mjs';
|
|
8
|
-
export { assertValidCronExpression, isValidCronExpression } from './packem_shared/assertValidCronExpression-BLfrDgmK.mjs';
|
|
1
|
+
import{default as o}from"./packem_shared/createScheduler-CsRAEtdb.mjs";import{default as a}from"./packem_shared/createWorkpool-DyVdhB6o.mjs";import{createCronTrigger as c}from"./packem_shared/createCronTrigger-C4iUW_zz.mjs";import{CRON_SCHEDULE_KINDS as f,compileCronSchedule as l,cronJobs as n}from"./packem_shared/CRON_SCHEDULE_KINDS-DMu4DfhG.mjs";import{createQueueConsumer as u,createQueueWorkpool as x,httpDispatcher as d}from"./packem_shared/createQueueConsumer-BnX7wkJO.mjs";import{SchedulerDO as C}from"./packem_shared/SchedulerDO-CCP9LV5x.mjs";import{createSchedulerHost as h}from"./packem_shared/createSchedulerHost-C5XacwXv.mjs";import{isWorkflowReference as E}from"./packem_shared/isWorkflowReference-CT3tdefh.mjs";import{assertValidCronExpression as k,isValidCronExpression as W,warnIfSecondsLeading as w}from"./packem_shared/assertValidCronExpression-B2lN8n3O.mjs";export{f as CRON_SCHEDULE_KINDS,C as SchedulerDO,k as assertValidCronExpression,l as compileCronSchedule,c as createCronTrigger,u as createQueueConsumer,x as createQueueWorkpool,o as createScheduler,h as createSchedulerHost,a as createWorkpool,n as cronJobs,d as httpDispatcher,W as isValidCronExpression,E as isWorkflowReference,w as warnIfSecondsLeading};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as a}from"@lunora/errors";import{isWorkflowReference as y}from"./isWorkflowReference-CT3tdefh.mjs";import{assertValidCronExpression as c}from"./assertValidCronExpression-B2lN8n3O.mjs";const f={friday:5,monday:1,saturday:6,sunday:0,thursday:4,tuesday:2,wednesday:3},w=24,h=" For a daily or longer schedule use crons.daily(name, { hourUTC, minuteUTC }, …), crons.weekly(name, { dayOfWeek, hourUTC, minuteUTC }, …) or crons.monthly(name, { day, hourUTC, minuteUTC }, …).",l=(e,o,r,s)=>{if(!Number.isInteger(e)||e<r||e>s)throw new a("INTERNAL",`@lunora/scheduler: cronJobs ${o} must be an integer in [${r.toFixed(0)}, ${s.toFixed(0)}], got ${String(e)}`);return e.toFixed(0)},m=(e,o,r)=>{const s=l(e,o,1,r-1);if(r%e!==0)throw new a("INTERNAL",`@lunora/scheduler: ${o} must evenly divide ${r.toFixed(0)} for a fixed "every ${e.toFixed(0)}" interval — cron "*/${e.toFixed(0)}" means "at values divisible by ${e.toFixed(0)}", which wraps unevenly; pick a divisor of ${r.toFixed(0)}`);return s},$=(e,o)=>{const r=["seconds","minutes","hours"].filter(i=>e[i]!==void 0);if(r.length!==1){const i=Object.entries(e).filter(([,t])=>t!==void 0).map(([t])=>t);throw new a("INTERNAL",`@lunora/scheduler: interval schedule must specify exactly one of { seconds, minutes, hours }, got { ${i.join(", ")} }.${h}`)}const s=r[0],n=e[s];if(s==="hours"&&n>=w)throw new a("INTERNAL",`@lunora/scheduler: interval.hours is capped at 23, got ${String(n)} — an interval repeats WITHIN a day rather than spanning one.${h}`);if(s==="seconds")throw new a("INTERNAL",`@lunora/scheduler: cron job${o?` "${o}"`:""} uses interval.seconds (${String(n)}) — Cloudflare Cron Triggers have a one-minute floor and cannot run sub-minute schedules; \`wrangler deploy\` would reject the resulting 6-field cron expression. Use ctx.scheduler.runAfter/runAt (optionally via a workpool for bounded concurrency) for sub-minute recurrence, or crons.interval(name, { minutes: 1 }, …) for the fastest cron-native cadence.`);return s==="minutes"?`*/${m(n,"interval.minutes",60)} * * * *`:`0 */${m(n,"interval.hours",24)} * * *`},T=e=>`${l(e.minuteUTC,"hourly.minuteUTC",0,59)} * * * *`,p=e=>{const o=l(e.minuteUTC,"daily.minuteUTC",0,59),r=l(e.hourUTC,"daily.hourUTC",0,23);return`${o} ${r} * * *`},C=e=>{const o=f[e.dayOfWeek];if(o===void 0)throw new a("INTERNAL",`@lunora/scheduler: weekly schedule has invalid dayOfWeek "${e.dayOfWeek}"`);const r=l(e.minuteUTC,"weekly.minuteUTC",0,59),s=l(e.hourUTC,"weekly.hourUTC",0,23);return`${r} ${s} * * ${o.toFixed(0)}`},v=e=>{const o=l(e.day,"monthly.day",1,31),r=l(e.minuteUTC,"monthly.minuteUTC",0,59),s=l(e.hourUTC,"monthly.hourUTC",0,23);return`${r} ${s} ${o} * *`},b=new Set(["daily","hourly","interval","monthly","weekly"]),d=(e,o,r)=>{switch(e){case"daily":return p(o);case"hourly":return T(o);case"interval":return $(o,r);case"monthly":return v(o);case"weekly":return C(o);default:throw new a("INTERNAL",`@lunora/scheduler: unknown cron schedule kind "${String(e)}"`)}},k=()=>{const e=[],o=new Set,r=(n,i,t,u)=>{if(typeof n!="string"||n.trim()==="")throw new a("INTERNAL","@lunora/scheduler: cron job name must be a non-empty string");if(o.has(n))throw new a("INTERNAL",`@lunora/scheduler: duplicate cron job name "${n}" — names must be unique within one cronJobs()`);if(y(t)){c(i,`cron expression for job "${n}"`),o.add(n),e.push({args:u??{},cron:i,name:n,workflow:typeof t.name=="string"?t.name:""});return}if(!t||typeof t.__lunoraRef!="string")throw new a("INTERNAL",`@lunora/scheduler: cron job "${n}" requires a function reference (e.g. internal.email.digest) or a workflow reference`);c(i,`cron expression for job "${n}"`),o.add(n),e.push({args:u??{},cron:i,functionPath:t.__lunoraRef,name:n})},s={cron(n,i,t,u){return r(n,i,t,u),s},daily(n,i,t,u){return r(n,d("daily",i),t,u),s},hourly(n,i,t,u){return r(n,d("hourly",i),t,u),s},interval(n,i,t,u){return r(n,d("interval",i,n),t,u),s},jobs:()=>[...e],monthly(n,i,t,u){return r(n,d("monthly",i),t,u),s},weekly(n,i,t,u){return r(n,d("weekly",i),t,u),s}};return s};export{b as CRON_SCHEDULE_KINDS,d as compileCronSchedule,k as cronJobs};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const f=(u,t=200,e)=>Response.json(u,{headers:{"content-type":"application/json",...e},status:t}),w="lunora-ping",b="lunora-pong";const p="retry:",g="dead:",m="pool:";const y=u=>String(u).padStart(15,"0"),v=()=>{const u=crypto.getRandomValues(new Uint8Array(12));let t="";for(const e of u)t+=String.fromCodePoint(e);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")};class r{static indexKey(t,e){return`t:${y(t)}:${e}`}static json(t,e=200){return f(t,e)}static error(t,e,s){return r.json({error:{code:e,message:s}},t)}static resolveRetry(t){const e=t.retry,s=typeof e?.maxAttempts=="number"&&Number.isInteger(e.maxAttempts)&&e.maxAttempts>0?e.maxAttempts:5,a=typeof e?.baseMs=="number"&&Number.isFinite(e.baseMs)&&e.baseMs>=0?e.baseMs:3e4,n=e?.backoff==="linear"?"linear":"exponential",i=typeof e?.maxMs=="number"&&Number.isFinite(e.maxMs)&&e.maxMs>=0?e.maxMs:void 0;return{backoff:n,baseMs:a,maxAttempts:s,maxMs:i}}static normalizeConcurrency(t,e){return typeof t=="number"&&Number.isInteger(t)&&t>0?t:e}static normalizeRetry(t){if(typeof t!="object"||t===null)return;const e=t,s={};return typeof e.maxAttempts=="number"&&Number.isInteger(e.maxAttempts)&&e.maxAttempts>0&&(s.maxAttempts=e.maxAttempts),typeof e.baseMs=="number"&&Number.isFinite(e.baseMs)&&e.baseMs>=0&&(s.baseMs=e.baseMs),(e.backoff==="exponential"||e.backoff==="linear")&&(s.backoff=e.backoff),typeof e.maxMs=="number"&&Number.isFinite(e.maxMs)&&e.maxMs>=0&&(s.maxMs=e.maxMs),Object.keys(s).length===0?void 0:s}static releaseSlot(t,e){if(t.inFlightIds===void 0)return{...t,inFlight:Math.max(0,t.inFlight-1)};const s=t.inFlightIds.filter(a=>a!==e);return{...t,inFlight:s.length,inFlightIds:s}}static releaseFirstSlot(t){if(t.inFlightIds===void 0)return{...t,inFlight:Math.max(0,t.inFlight-1)};const e=t.inFlightIds.slice(0,Math.max(0,t.inFlightIds.length-1));return{...t,inFlight:e.length,inFlightIds:e}}static resolveScheduleTarget(t){const e=typeof t?.functionPath=="string"&&t.functionPath.length>0?t.functionPath:void 0,s=typeof t?.workflow=="string"&&t.workflow.length>0?t.workflow:void 0;if(!(e===void 0&&s===void 0))return{functionPath:e,workflow:s}}state;env;constructor(t,e){this.state=t,this.env=e,this.armWebSocketKeepalive()}async fetch(t){const e=new URL(t.url);if(e.pathname==="/ws"&&t.headers.get("Upgrade")==="websocket")return this.handleWebSocketUpgrade();switch(`${t.method} ${e.pathname}`){case"GET /dead":return this.handleDeadList();case"GET /get":return this.handleGet(e);case"GET /list":return this.handleList();case"GET /pool":return this.handlePoolStatus(e);case"GET /status":return this.handleStatus();case"POST /cancel":return this.handleCancel(t);case"POST /complete":return this.handleComplete(t);case"POST /dead/cancel":return this.handleDeadCancel(t);case"POST /dead/retry":return this.handleDeadRetry(t);case"POST /schedule":return this.handleSchedule(t)}return f({error:{code:"NOT_FOUND"}},404)}async alarm(){const t=Date.now(),e=[],s=await this.state.storage.list({end:`t:${y(t)}:~`,limit:100,prefix:"t:"});for(const[a,n]of s.entries()){const i=Number.parseInt(a.slice(2,a.indexOf(":",2)),10);if(Number.isFinite(i)&&i<=t){const o=await this.state.storage.get(`id:${n}`);o?e.push(o):await this.state.storage.delete(a)}}try{for(const a of e)await this.drainRecordGuarded(a)}finally{await this.rescheduleAlarm()}e.length>0&&await this.broadcastChange()}async dispatch(t){const e=typeof this.env.LUNORA_ORIGIN_URL=="string"&&this.env.LUNORA_ORIGIN_URL.length>0?this.env.LUNORA_ORIGIN_URL:void 0;if(!e)return!1;const s=JSON.stringify({args:t.args,functionPath:t.functionPath,id:t.id,instanceName:t.instanceName,pool:t.pool,scheduledFor:t.scheduledFor,shardKey:t.shardKey,workflow:t.workflow});try{const a={"content-type":"application/json"},n=await this.signDispatch(s);return n!==void 0?a["x-lunora-scheduler-signature"]=n:typeof this.env.LUNORA_ADMIN_TOKEN=="string"&&this.env.LUNORA_ADMIN_TOKEN.length>0&&(a.authorization=`Bearer ${this.env.LUNORA_ADMIN_TOKEN}`),(await fetch(`${e}/_lunora/scheduler/dispatch`,{body:s,headers:a,method:"POST"})).ok}catch{return!1}}armWebSocketKeepalive(){const t=this.state.setWebSocketAutoResponse;typeof t!="function"||typeof WebSocketRequestResponsePair>"u"||t.call(this.state,new WebSocketRequestResponsePair(w,b))}async drainRecordGuarded(t){try{await this.state.storage.delete(r.indexKey(t.scheduledFor,t.id)),await this.drainRecord(t)}catch{try{await this.state.storage.put(r.indexKey(t.scheduledFor,t.id),t.id)}catch{}}}async drainRecord(t){if(!await this.reservePoolSlot(t))return!1;const e=await this.dispatch(t);if(!e&&t.pool!==void 0){const s=await this.loadPool(t.pool),a=r.releaseSlot(s,t.id);await this.savePool(t.pool,a)}if(e){try{await this.state.storage.delete([`id:${t.id}`,`${p}${t.id}`])}catch{}return!0}return await this.recordRetry(t),!1}async reservePoolSlot(t){if(t.pool===void 0)return!0;const e=await this.loadPool(t.pool);if(e.inFlight>=e.maxConcurrency)return await this.requeuePooled(t),!1;const s=e.inFlightIds??[];return s.includes(t.id)||s.push(t.id),e.inFlightIds=s,e.inFlight=s.length,await this.savePool(t.pool,e),!0}async handleWebSocketUpgrade(){if(this.state.acceptWebSocket===void 0)return r.error(501,"WS_UNSUPPORTED","WebSocket subscriptions are not supported in this runtime");const t=new WebSocketPair,e=t[0],s=t[1];this.state.acceptWebSocket(s);const a=await this.listRecords();return s.send(JSON.stringify({records:a.records,truncated:a.truncated,type:"jobs"})),new Response(null,{status:101,webSocket:e})}async broadcastChange(){const t=this.state.getWebSockets?.();if(t===void 0||t.length===0)return;const{records:e,truncated:s}=await this.listRecords(),a=JSON.stringify({records:e,truncated:s,type:"jobs"});for(const n of t)try{n.send(a)}catch{}}async listRecords(t=100){const e=[...(await this.state.storage.list({limit:t+1,prefix:"id:"})).values()],s=e.length>t;return{records:s?e.slice(0,t):e,truncated:s}}async countHeaders(t,e=100){let s;for(;;){const a=await this.state.storage.list(s===void 0?{limit:e,prefix:"id:"}:{limit:e,prefix:"id:",startAfter:s});if(a.size===0)break;for(const n of a.values())t(n);if(s=[...a.keys()].at(-1),a.size<e)break}}async signDispatch(t){const e=typeof this.env.LUNORA_SCHEDULER_SECRET=="string"?this.env.LUNORA_SCHEDULER_SECRET:void 0;if(!e||e.length===0)return;const s=new TextEncoder,a=await crypto.subtle.importKey("raw",s.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),n=await crypto.subtle.sign("HMAC",a,s.encode(t)),i=new Uint8Array(n);let o="";for(const d of i)o+=String.fromCodePoint(d);return btoa(o).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}async recordRetry(t){const e=(t.attempts??0)+1,{backoff:s,baseMs:a,maxAttempts:n,maxMs:i}=r.resolveRetry(t);if(e>n){await this.state.storage.put(`${g}${t.id}`,{...t,attempts:e}),await this.state.storage.delete([`${p}${t.id}`,`id:${t.id}`]),console.warn(`@lunora/scheduler: job "${t.id}" (${t.functionPath??t.workflow??"unknown"}) parked in dead-letter after ${String(e)} attempts`);return}const o=s==="linear"?a*e:a*2**(e-1),d=i===void 0?o:Math.min(o,i),c=Date.now()+d,l={...t,attempts:e,scheduledFor:c};await this.state.storage.put(`${p}${t.id}`,l),await this.state.storage.put(`id:${t.id}`,l),await this.state.storage.put(r.indexKey(c,t.id),t.id)}async loadPool(t,e){const s=await this.state.storage.get(`${m}${t}`);return s!==void 0?Array.isArray(s.inFlightIds)?{inFlight:s.inFlightIds.length,inFlightIds:[...s.inFlightIds],maxConcurrency:s.maxConcurrency}:{inFlight:Math.max(0,s.inFlight),maxConcurrency:s.maxConcurrency}:{inFlight:0,inFlightIds:[],maxConcurrency:r.normalizeConcurrency(e,1)}}async savePool(t,e){await this.state.storage.put(`${m}${t}`,e)}async requeuePooled(t){const e=Date.now()+1e3,s={...t,scheduledFor:e};await this.state.storage.put(`id:${t.id}`,s),await this.state.storage.put(r.indexKey(e,t.id),t.id)}async handleComplete(t){const e=await t.json().catch(()=>{}),s=typeof e?.pool=="string"&&e.pool.length>0?e.pool:void 0,a=typeof e?.id=="string"&&e.id.length>0?e.id:void 0;if(s===void 0)return r.error(400,"INVALID_INPUT","pool is required");const n=await this.loadPool(s),i=a===void 0?r.releaseFirstSlot(n):r.releaseSlot(n,a);return await this.savePool(s,i),await this.armAlarmIfEarlier(Date.now()),r.json({inFlight:i.inFlight})}async handlePoolStatus(t){const e=t.searchParams.get("name");if(e===null||e.length===0)return r.error(400,"INVALID_INPUT","name is required");const s=await this.loadPool(e);let a=0;return await this.countHeaders(n=>{n.pool===e&&(a+=1)}),r.json({inFlight:s.inFlight,maxConcurrency:s.maxConcurrency,queued:a})}async handleStatus(){const t=await this.state.storage.list({prefix:m}),e=new Map;await this.countHeaders(o=>{o.pool!==void 0&&e.set(o.pool,(e.get(o.pool)??0)+1)});const s=[];let a=0,n=0;for(const[o,d]of t.entries()){const c=o.slice(m.length),l=Math.max(0,d.inFlight),h=e.get(c)??0;s.push({inFlight:l,maxConcurrency:d.maxConcurrency,name:c,queued:h}),a+=h,n+=l}const i={backlog:a,inFlight:n,pools:s};return r.json(i)}async handleSchedule(t){const e=await t.json().catch(()=>{}),s=r.resolveScheduleTarget(e);if(!e||s===void 0)return r.error(400,"INVALID_INPUT","functionPath or workflow is required");const{functionPath:a,workflow:n}=s;if(typeof e.scheduledFor!="number"||!Number.isInteger(e.scheduledFor)||e.scheduledFor<=0||e.scheduledFor>999999999999999)return r.error(400,"INVALID_INPUT","scheduledFor must be a positive integer epoch-millisecond number no greater than 999999999999999");if(typeof this.env.LUNORA_ORIGIN_URL!="string"||this.env.LUNORA_ORIGIN_URL.length===0)return r.error(500,"ORIGIN_NOT_CONFIGURED","LUNORA_ORIGIN_URL env binding must be set on the SchedulerDO");const i=typeof e.pool=="string"&&e.pool.length>0?e.pool:void 0,o=typeof e.instanceName=="string"&&e.instanceName.length>0?e.instanceName:void 0,d=r.normalizeRetry(e.retry),c=v(),l={args:e.args??{},enqueuedAt:Date.now(),id:c,...a===void 0?{}:{functionPath:a},...o===void 0?{}:{instanceName:o},...i===void 0?{}:{pool:i},...d===void 0?{}:{retry:d},scheduledFor:e.scheduledFor,shardKey:e.shardKey,...n===void 0?{}:{workflow:n}};if(i!==void 0){const h=await this.loadPool(i,e.maxConcurrency);await this.savePool(i,{inFlight:h.inFlight,...h.inFlightIds===void 0?{}:{inFlightIds:h.inFlightIds},maxConcurrency:r.normalizeConcurrency(e.maxConcurrency,h.maxConcurrency)})}return await this.state.storage.put(`id:${c}`,l),await this.state.storage.put(r.indexKey(l.scheduledFor,c),c),await this.armAlarmIfEarlier(l.scheduledFor),await this.broadcastChange(),r.json({id:c,scheduledFor:l.scheduledFor})}async handleCancel(t){const e=await t.json().catch(()=>{});if(!e?.id)return r.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`id:${e.id}`);return s?(await this.removeRecord(s),await this.rescheduleAlarm(),await this.broadcastChange(),r.json({cancelled:!0})):r.json({cancelled:!1})}async handleList(){const{records:t,truncated:e}=await this.listRecords();return r.json({records:t,truncated:e})}async handleDeadList(){const t=await this.state.storage.list({prefix:g});return r.json({records:[...t.values()]})}async handleDeadRetry(t){const e=await t.json().catch(()=>{});if(typeof e?.id!="string"||e.id.length===0)return r.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`${g}${e.id}`);if(s===void 0)return r.json({retried:!1});const a=Date.now(),n={...s,attempts:0,scheduledFor:a};return await this.state.storage.put(`id:${s.id}`,n),await this.state.storage.put(r.indexKey(a,s.id),s.id),await this.state.storage.delete(`${g}${s.id}`),await this.armAlarmIfEarlier(a),await this.broadcastChange(),r.json({id:s.id,retried:!0,scheduledFor:a})}async handleDeadCancel(t){const e=await t.json().catch(()=>{});if(typeof e?.id!="string"||e.id.length===0)return r.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.delete(`${g}${e.id}`);return r.json({removed:!!s})}async handleGet(t){const e=t.searchParams.get("id");if(e===null||e.length===0)return r.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`id:${e}`);return r.json(s===void 0?{}:{record:s})}async removeRecord(t){await this.state.storage.delete([`id:${t.id}`,r.indexKey(t.scheduledFor,t.id),`${p}${t.id}`])}async armAlarmIfEarlier(t){const e=await this.state.storage.getAlarm();(e===null||t<e)&&await this.state.storage.setAlarm(t)}async rescheduleAlarm(){const t=(await this.state.storage.list({limit:1,prefix:"t:"})).entries().next();if(t.done){await this.state.storage.deleteAlarm();return}const[e]=t.value,s=Number.parseInt(e.slice(2,e.indexOf(":",2)),10);Number.isFinite(s)&&await this.state.storage.setAlarm(s)}}export{r as SchedulerDO};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as s}from"@lunora/errors";import{CronExpressionParser as o}from"cron-parser";const n=r=>{if(typeof r!="string"||r.trim()==="")return!1;try{return o.parse(r.trim()),!0}catch{return!1}},t=/\s+/u,i=(r,e)=>{r.trim().split(t).length===6&&console.warn(`@lunora/scheduler: ${e} "${r}" is a 6-field (seconds-leading) cron expression — Cloudflare Cron Triggers only support the standard 5-field form and will reject this at \`wrangler deploy\`. Drop the seconds field, or use ctx.scheduler.runAfter/runAt for sub-minute work.`)},d=(r,e="cron expression")=>{if(!n(r))throw new s("INTERNAL",`@lunora/scheduler: invalid ${e} "${r}" — expected a standard 5- or 6-field cron expression (e.g. "0 * * * *")`);i(r,e)};export{d as assertValidCronExpression,n as isValidCronExpression,i as warnIfSecondsLeading};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as s}from"@lunora/errors";import{assertValidCronExpression as n}from"./assertValidCronExpression-B2lN8n3O.mjs";const t=r=>{if(!r.schedule||!r.fn)throw new s("INTERNAL","@lunora/scheduler: createCronTrigger() requires `schedule` and `fn`");n(r.schedule);const e=JSON.stringify({triggers:{crons:[r.schedule]}},void 0,2);return{crons:[r.schedule],dispatcher:{args:r.args??{},functionPath:r.fn.__lunoraRef},wranglerJsonc:e}};export{t as createCronTrigger};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as o}from"@lunora/errors";const s=100,i=e=>{let a=e.length;for(;a>0&&e[a-1]==="/";)a-=1;return e.slice(0,a)},l=e=>{if(!e.queue)throw new o("INTERNAL","@lunora/scheduler: `queue` (a Cloudflare Queue binding) is required");return{enqueue:async(a,t,n={})=>{const r={args:t,functionPath:a.__lunoraRef,shardKey:n.shardKey},u=n.delaySeconds===void 0?void 0:{delaySeconds:n.delaySeconds};await e.queue.send(r,u)},enqueueBatch:async(a,t)=>{if(a.length>s)throw new o("INTERNAL",`@lunora/scheduler: enqueueBatch exceeds ${String(s)} (got ${String(a.length)}) — split across calls`);const n=a.map(r=>({body:{args:r.args,functionPath:r.ref.__lunoraRef,shardKey:r.shardKey}}));await e.queue.sendBatch(n,t)}}},c=e=>typeof e=="object"&&e!==null&&typeof e.functionPath=="string",d=e=>async a=>{await Promise.all(a.messages.map(async t=>{try{if(!c(t.body))throw new o("INTERNAL","@lunora/scheduler: queue message body is not a QueueJob (missing functionPath)");await e.dispatch(t.body),t.ack()}catch{t.retry()}}))},f=e=>{const a=e.fetchImpl??globalThis.fetch;if(typeof a!="function")throw new TypeError("@lunora/scheduler: no fetch implementation available — pass fetchImpl or run on a platform with global fetch");const t=`${i(e.originUrl)}/_lunora/scheduler/dispatch`;return async n=>{const r=await a(t,{body:JSON.stringify({args:n.args??{},functionPath:n.functionPath,shardKey:n.shardKey}),headers:{authorization:`Bearer ${e.adminToken}`,"content-type":"application/json"},method:"POST"});if(!r.ok)throw new o("INTERNAL",`@lunora/scheduler: queue dispatch failed (${r.status.toString()}): ${await r.text()}`)}};export{d as createQueueConsumer,l as createQueueWorkpool,f as httpDispatcher};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import{l as s,u as a}from"./do-client-BFps7NIj.mjs";import{isWorkflowReference as g}from"./isWorkflowReference-CT3tdefh.mjs";const y=n=>{if(!n.namespace)throw new i("INTERNAL","@lunora/scheduler: `namespace` (SchedulerDO binding) is required");if(!n.originUrl)throw new i("INTERNAL","@lunora/scheduler: `originUrl` is required so the DO can dispatch back to the Worker");const c=async(e,r,o,t={})=>{const l=e instanceof Date?e.getTime():e,d={args:o,originUrl:n.originUrl,pool:t.pool,retry:t.retry,scheduledFor:l,shardKey:t.shardKey};if(g(r)){if(typeof r.binding!="string"||r.binding.length===0)throw new i("INTERNAL","@lunora/scheduler: workflow/agent schedule target is missing its `binding` — pass the generated `workflows.<name>` / `agents.<name>` reference");return a(n,"/schedule",{...d,workflow:r.binding})}const u=typeof r=="string"?r:r.__lunoraRef;return a(n,"/schedule",{...d,functionPath:u})};return{cancel:async e=>a(n,"/cancel",{id:e}),dead:async()=>{const e=await s(n,"/dead");return Array.isArray(e.records)?e.records:[]},deadRetry:async e=>{const{retried:r}=await a(n,"/dead/retry",{id:e});return r===!0},get:async e=>(await s(n,`/get?id=${encodeURIComponent(e)}`)).record??null,list:async()=>{const e=await s(n,"/list");return Array.isArray(e.records)?e.records:[]},runAfter:async(e,r,o,t={})=>{if(!Number.isFinite(e)||e<0)throw new i("INTERNAL","@lunora/scheduler: `delayMs` must be a non-negative finite number");return c(Date.now()+e,r,o,t)},runAt:c}};export{y as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import i from"./createScheduler-CsRAEtdb.mjs";const o=a=>a?.at!==void 0?typeof a.at=="number"?a.at:a.at.getTime():Date.now()+(a?.delayMs??0),u=a=>{const t=i({instanceName:a.instanceName,jurisdiction:a.jurisdiction,namespace:a.namespace,originUrl:a.originUrl}),c=e=>({attempts:e.attempts??0,functionPath:e.functionPath??e.workflow??"",id:e.id,scheduledFor:e.scheduledFor});return{cancel:async e=>{const{cancelled:r}=await t.cancel(e);return r},deadLetter:{list:async()=>(await t.dead()).map(e=>c(e)),requeue:async e=>t.deadRetry(e)},list:async()=>(await t.list()).map(e=>c(e)),schedule:async(e,r,n)=>{const s=t.runAt;return s(o(n),e,r,{retry:n?.retry,shardKey:n?.shardKey})}}};export{u as createSchedulerHost};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as n}from"@lunora/errors";import{l as c,u as i}from"./do-client-BFps7NIj.mjs";const m=e=>{if(!e.namespace)throw new n("INTERNAL","@lunora/scheduler: `namespace` (SchedulerDO binding) is required");if(!e.originUrl)throw new n("INTERNAL","@lunora/scheduler: `originUrl` is required so the DO can dispatch back to the Worker");if(!Number.isInteger(e.maxConcurrency)||e.maxConcurrency<=0)throw new n("INTERNAL","@lunora/scheduler: `maxConcurrency` must be a positive integer");const r=typeof e.name=="string"&&e.name.length>0?e.name:"default";return{cancel:async a=>i(e,"/cancel",{id:a}),enqueue:async(a,u,o={})=>{const t=o.delayMs??0;if(!Number.isFinite(t)||t<0)throw new n("INTERNAL","@lunora/scheduler: `delayMs` must be a non-negative finite number");return i(e,"/schedule",{args:u,functionPath:a.__lunoraRef,instanceName:e.instanceName??"default",maxConcurrency:e.maxConcurrency,originUrl:e.originUrl,pool:r,retry:o.retry,scheduledFor:Date.now()+t,shardKey:o.shardKey})},name:r,status:async()=>c(e,`/pool?name=${encodeURIComponent(r)}`)}};export{m as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as o}from"@lunora/errors";const s=(e,t)=>{if(t===void 0)return e;if(typeof e.jurisdiction!="function")throw new TypeError(`@lunora/scheduler: Durable Object namespace does not support jurisdiction("${t}") — update @cloudflare/workers-types or remove the jurisdiction option`);return e.jurisdiction(t)},i=e=>{const t=s(e.namespace,e.jurisdiction);return t.get(t.idFromName(e.instanceName??"default"))},u=async(e,t,r)=>{const n=await i(e).fetch(`https://scheduler.internal${t}`,{body:JSON.stringify(r),headers:{"content-type":"application/json"},method:"POST"});if(!n.ok){const a=await n.text();throw new o("INTERNAL",`@lunora/scheduler: SchedulerDO ${t} failed (${String(n.status)}): ${a}`)}return await n.json()},d=async(e,t)=>{const r=await i(e).fetch(`https://scheduler.internal${t}`,{method:"GET"});if(!r.ok){const n=await r.text();throw new o("INTERNAL",`@lunora/scheduler: SchedulerDO ${t} failed (${String(r.status)}): ${n}`)}return await r.json()};export{d as l,u};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=o=>typeof o=="object"&&o!==null&&o.isLunoraWorkflow===!0;export{e as isWorkflowReference};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/scheduler",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.21",
|
|
4
4
|
"description": "Scheduling for Lunora: runAfter / runAt and Cron Triggers via SchedulerDO",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
"directory": "packages/scheduler"
|
|
26
26
|
},
|
|
27
27
|
"files": [
|
|
28
|
-
"dist",
|
|
28
|
+
"./dist",
|
|
29
29
|
"__assets__",
|
|
30
30
|
"README.md",
|
|
31
31
|
"LICENSE.md"
|
|
@@ -46,7 +46,9 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"
|
|
49
|
+
"@lunora/errors": "1.0.0-alpha.14",
|
|
50
|
+
"@lunora/platform": "1.0.0-alpha.6",
|
|
51
|
+
"cron-parser": "5.6.2"
|
|
50
52
|
},
|
|
51
53
|
"engines": {
|
|
52
54
|
"node": "^22.15.0 || >=24.11.0"
|
|
@@ -1,123 +0,0 @@
|
|
|
1
|
-
import { isWorkflowReference } from './isWorkflowReference-C9mQkMXt.mjs';
|
|
2
|
-
import { assertValidCronExpression } from './assertValidCronExpression-BLfrDgmK.mjs';
|
|
3
|
-
|
|
4
|
-
const WEEKDAY_INDEX = {
|
|
5
|
-
friday: 5,
|
|
6
|
-
monday: 1,
|
|
7
|
-
saturday: 6,
|
|
8
|
-
sunday: 0,
|
|
9
|
-
thursday: 4,
|
|
10
|
-
tuesday: 2,
|
|
11
|
-
wednesday: 3
|
|
12
|
-
};
|
|
13
|
-
const field = (value, label, min, max) => {
|
|
14
|
-
if (!Number.isInteger(value) || value < min || value > max) {
|
|
15
|
-
throw new Error(`@lunora/scheduler: cronJobs ${label} must be an integer in [${min.toFixed(0)}, ${max.toFixed(0)}], got ${String(value)}`);
|
|
16
|
-
}
|
|
17
|
-
return value.toFixed(0);
|
|
18
|
-
};
|
|
19
|
-
const compileInterval = (schedule) => {
|
|
20
|
-
const units = ["seconds", "minutes", "hours"].filter((unit2) => schedule[unit2] !== void 0);
|
|
21
|
-
if (units.length !== 1) {
|
|
22
|
-
throw new Error(`@lunora/scheduler: interval schedule must specify exactly one of { seconds, minutes, hours }`);
|
|
23
|
-
}
|
|
24
|
-
const unit = units[0];
|
|
25
|
-
const value = schedule[unit];
|
|
26
|
-
if (unit === "seconds") {
|
|
27
|
-
return `*/${field(value, "interval.seconds", 1, 59)} * * * * *`;
|
|
28
|
-
}
|
|
29
|
-
if (unit === "minutes") {
|
|
30
|
-
return `*/${field(value, "interval.minutes", 1, 59)} * * * *`;
|
|
31
|
-
}
|
|
32
|
-
return `0 */${field(value, "interval.hours", 1, 23)} * * *`;
|
|
33
|
-
};
|
|
34
|
-
const compileDaily = (schedule) => {
|
|
35
|
-
const minute = field(schedule.minuteUTC, "daily.minuteUTC", 0, 59);
|
|
36
|
-
const hour = field(schedule.hourUTC, "daily.hourUTC", 0, 23);
|
|
37
|
-
return `${minute} ${hour} * * *`;
|
|
38
|
-
};
|
|
39
|
-
const compileWeekly = (schedule) => {
|
|
40
|
-
const index = WEEKDAY_INDEX[schedule.dayOfWeek];
|
|
41
|
-
if (index === void 0) {
|
|
42
|
-
throw new Error(`@lunora/scheduler: weekly schedule has invalid dayOfWeek "${schedule.dayOfWeek}"`);
|
|
43
|
-
}
|
|
44
|
-
const minute = field(schedule.minuteUTC, "weekly.minuteUTC", 0, 59);
|
|
45
|
-
const hour = field(schedule.hourUTC, "weekly.hourUTC", 0, 23);
|
|
46
|
-
return `${minute} ${hour} * * ${index.toFixed(0)}`;
|
|
47
|
-
};
|
|
48
|
-
const compileMonthly = (schedule) => {
|
|
49
|
-
const day = field(schedule.day, "monthly.day", 1, 31);
|
|
50
|
-
const minute = field(schedule.minuteUTC, "monthly.minuteUTC", 0, 59);
|
|
51
|
-
const hour = field(schedule.hourUTC, "monthly.hourUTC", 0, 23);
|
|
52
|
-
return `${minute} ${hour} ${day} * *`;
|
|
53
|
-
};
|
|
54
|
-
const CRON_SCHEDULE_KINDS = /* @__PURE__ */ new Set(["daily", "interval", "monthly", "weekly"]);
|
|
55
|
-
const compileCronSchedule = (kind, schedule) => {
|
|
56
|
-
switch (kind) {
|
|
57
|
-
case "daily": {
|
|
58
|
-
return compileDaily(schedule);
|
|
59
|
-
}
|
|
60
|
-
case "interval": {
|
|
61
|
-
return compileInterval(schedule);
|
|
62
|
-
}
|
|
63
|
-
case "monthly": {
|
|
64
|
-
return compileMonthly(schedule);
|
|
65
|
-
}
|
|
66
|
-
case "weekly": {
|
|
67
|
-
return compileWeekly(schedule);
|
|
68
|
-
}
|
|
69
|
-
default: {
|
|
70
|
-
throw new Error(`@lunora/scheduler: unknown cron schedule kind "${String(kind)}"`);
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
};
|
|
74
|
-
const cronJobs = () => {
|
|
75
|
-
const jobs = [];
|
|
76
|
-
const seen = /* @__PURE__ */ new Set();
|
|
77
|
-
const register = (name, cron, target, args) => {
|
|
78
|
-
if (typeof name !== "string" || name.trim() === "") {
|
|
79
|
-
throw new Error(`@lunora/scheduler: cron job name must be a non-empty string`);
|
|
80
|
-
}
|
|
81
|
-
if (seen.has(name)) {
|
|
82
|
-
throw new Error(`@lunora/scheduler: duplicate cron job name "${name}" — names must be unique within one cronJobs()`);
|
|
83
|
-
}
|
|
84
|
-
if (isWorkflowReference(target)) {
|
|
85
|
-
assertValidCronExpression(cron, `cron expression for job "${name}"`);
|
|
86
|
-
seen.add(name);
|
|
87
|
-
jobs.push({ args: args ?? {}, cron, name, workflow: typeof target.name === "string" ? target.name : "" });
|
|
88
|
-
return;
|
|
89
|
-
}
|
|
90
|
-
if (!target || typeof target.__lunoraRef !== "string") {
|
|
91
|
-
throw new Error(`@lunora/scheduler: cron job "${name}" requires a function reference (e.g. internal.email.digest) or a workflow reference`);
|
|
92
|
-
}
|
|
93
|
-
assertValidCronExpression(cron, `cron expression for job "${name}"`);
|
|
94
|
-
seen.add(name);
|
|
95
|
-
jobs.push({ args: args ?? {}, cron, functionPath: target.__lunoraRef, name });
|
|
96
|
-
};
|
|
97
|
-
const builder = {
|
|
98
|
-
cron(name, cronExpr, function_, args) {
|
|
99
|
-
register(name, cronExpr, function_, args);
|
|
100
|
-
return builder;
|
|
101
|
-
},
|
|
102
|
-
daily(name, schedule, function_, args) {
|
|
103
|
-
register(name, compileCronSchedule("daily", schedule), function_, args);
|
|
104
|
-
return builder;
|
|
105
|
-
},
|
|
106
|
-
interval(name, schedule, function_, args) {
|
|
107
|
-
register(name, compileCronSchedule("interval", schedule), function_, args);
|
|
108
|
-
return builder;
|
|
109
|
-
},
|
|
110
|
-
jobs: () => [...jobs],
|
|
111
|
-
monthly(name, schedule, function_, args) {
|
|
112
|
-
register(name, compileCronSchedule("monthly", schedule), function_, args);
|
|
113
|
-
return builder;
|
|
114
|
-
},
|
|
115
|
-
weekly(name, schedule, function_, args) {
|
|
116
|
-
register(name, compileCronSchedule("weekly", schedule), function_, args);
|
|
117
|
-
return builder;
|
|
118
|
-
}
|
|
119
|
-
};
|
|
120
|
-
return builder;
|
|
121
|
-
};
|
|
122
|
-
|
|
123
|
-
export { CRON_SCHEDULE_KINDS, compileCronSchedule, cronJobs };
|