@lunora/scheduler 1.0.0-alpha.92 → 1.0.0-alpha.94

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/dist/index.d.mts CHANGED
@@ -927,6 +927,18 @@ declare class SchedulerDO {
927
927
  * instead — `alarm()` drops it as a dangling entry once the header is gone.
928
928
  */
929
929
  private readonly activeLeases;
930
+ /**
931
+ * Ids `/cancel` removed while this instance held their dispatch lease.
932
+ *
933
+ * The attempt is already in flight when such a cancel lands, and whatever it
934
+ * settles to must not write the job back: `recordRetry()` and
935
+ * `requeuePooled()` re-create the `id:` header and a `t:` entry, so a
936
+ * failed attempt would resurrect a job `/cancel` answered `{ cancelled: true }`
937
+ * for, and it would fire again. Both check this set synchronously right
938
+ * before their single write, so no `/cancel` can land between the check and
939
+ * the write. Cleared with the lease in `drainRecordGuarded()`.
940
+ */
941
+ private readonly cancelledLeases;
930
942
  constructor(state: SchedulerDOState, env: SchedulerEnv);
931
943
  fetch(request: Request): Promise<Response>;
932
944
  /** Called by the Workers runtime when the alarm previously set by `rescheduleAlarm()` fires. */
package/dist/index.d.ts CHANGED
@@ -927,6 +927,18 @@ declare class SchedulerDO {
927
927
  * instead — `alarm()` drops it as a dangling entry once the header is gone.
928
928
  */
929
929
  private readonly activeLeases;
930
+ /**
931
+ * Ids `/cancel` removed while this instance held their dispatch lease.
932
+ *
933
+ * The attempt is already in flight when such a cancel lands, and whatever it
934
+ * settles to must not write the job back: `recordRetry()` and
935
+ * `requeuePooled()` re-create the `id:` header and a `t:` entry, so a
936
+ * failed attempt would resurrect a job `/cancel` answered `{ cancelled: true }`
937
+ * for, and it would fire again. Both check this set synchronously right
938
+ * before their single write, so no `/cancel` can land between the check and
939
+ * the write. Cleared with the lease in `drainRecordGuarded()`.
940
+ */
941
+ private readonly cancelledLeases;
930
942
  constructor(state: SchedulerDOState, env: SchedulerEnv);
931
943
  fetch(request: Request): Promise<Response>;
932
944
  /** Called by the Workers runtime when the alarm previously set by `rescheduleAlarm()` fires. */
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{default as o}from"./packem_shared/createScheduler-BW6wVD57.mjs";import{default as a}from"./packem_shared/createWorkpool-CQs6z3Y0.mjs";import{createCronTrigger as f}from"./packem_shared/createCronTrigger-DSuDZtqj.mjs";import{CRON_SCHEDULE_KINDS as p,compileCronSchedule as c,cronJobs as d}from"./packem_shared/CRON_SCHEDULE_KINDS-xyFk800s.mjs";import{createQueueConsumer as m,createQueueWorkpool as n,httpDispatcher as x}from"./packem_shared/createQueueConsumer--7v7nhxZ.mjs";import{default as i}from"./packem_shared/resolveScheduleId-DgysKSrN.mjs";import{MAX_RETRY_ATTEMPTS as E,RETRY_BASE_DELAY_MS as C,SchedulerDO as _}from"./packem_shared/MAX_RETRY_ATTEMPTS-BFBSSPrs.mjs";import{createSchedulerHost as R}from"./packem_shared/createSchedulerHost-CO6BlgVY.mjs";import{isWorkflowReference as A}from"./packem_shared/isWorkflowReference-CT3tdefh.mjs";import{assertValidCronExpression as g,isValidCronExpression as k,warnIfSecondsLeading as L}from"./packem_shared/assertValidCronExpression-DnBtukpq.mjs";import{default as W}from"./packem_shared/assertScheduleDelay-BgA4K1WB.mjs";import{default as w}from"./packem_shared/assertScheduleInstant-BzESPqyw.mjs";export{p as CRON_SCHEDULE_KINDS,E as MAX_RETRY_ATTEMPTS,C as RETRY_BASE_DELAY_MS,_ as SchedulerDO,W as assertScheduleDelay,w as assertScheduleInstant,g as assertValidCronExpression,c as compileCronSchedule,f as createCronTrigger,m as createQueueConsumer,n as createQueueWorkpool,o as createScheduler,R as createSchedulerHost,a as createWorkpool,d as cronJobs,x as httpDispatcher,k as isValidCronExpression,A as isWorkflowReference,i as resolveScheduleId,L as warnIfSecondsLeading};
1
+ import{default as o}from"./packem_shared/createScheduler-BEOeea0Y.mjs";import{default as a}from"./packem_shared/createWorkpool-Bi5eQkLO.mjs";import{createCronTrigger as f}from"./packem_shared/createCronTrigger-DSuDZtqj.mjs";import{CRON_SCHEDULE_KINDS as p,compileCronSchedule as c,cronJobs as d}from"./packem_shared/CRON_SCHEDULE_KINDS-xyFk800s.mjs";import{createQueueConsumer as m,createQueueWorkpool as n,httpDispatcher as x}from"./packem_shared/createQueueConsumer-qxMgxXfE.mjs";import{default as i}from"./packem_shared/resolveScheduleId-DuLCFI_l.mjs";import{MAX_RETRY_ATTEMPTS as E,RETRY_BASE_DELAY_MS as C,SchedulerDO as _}from"./packem_shared/MAX_RETRY_ATTEMPTS-Q3JXDtb1.mjs";import{createSchedulerHost as R}from"./packem_shared/createSchedulerHost-yXQn-hdf.mjs";import{isWorkflowReference as A}from"./packem_shared/isWorkflowReference-CT3tdefh.mjs";import{assertValidCronExpression as g,isValidCronExpression as k,warnIfSecondsLeading as L}from"./packem_shared/assertValidCronExpression-DnBtukpq.mjs";import{default as W}from"./packem_shared/assertScheduleDelay-Cz5e-UVl.mjs";import{default as w}from"./packem_shared/assertScheduleInstant-CMN9XCFm.mjs";export{p as CRON_SCHEDULE_KINDS,E as MAX_RETRY_ATTEMPTS,C as RETRY_BASE_DELAY_MS,_ as SchedulerDO,W as assertScheduleDelay,w as assertScheduleInstant,g as assertValidCronExpression,c as compileCronSchedule,f as createCronTrigger,m as createQueueConsumer,n as createQueueWorkpool,o as createScheduler,R as createSchedulerHost,a as createWorkpool,d as cronJobs,x as httpDispatcher,k as isValidCronExpression,A as isWorkflowReference,i as resolveScheduleId,L as warnIfSecondsLeading};
@@ -0,0 +1 @@
1
+ import{a as N}from"./base64-junLSktH.mjs";import R from"./resolveScheduleId-DuLCFI_l.mjs";const E="DISPATCH_IN_PROGRESS",x="x-lunora-dispatch-declined",P=(u,t=200,e)=>{const s=new Headers({"content-type":"application/json"});for(const[a,i]of Object.entries({}))s.set(a,i);return Response.json(u,{headers:s,status:t})},F="lunora-ping",L="lunora-pong",c="id:",m="retry:",g="dead:",y="pool:",w=100,$=5,b=3e4,k=1e3,T=6,C=9e5,M=999999999999999,U=15,A=u=>String(u).padStart(U,"0"),v=u=>Number.isInteger(u)&&u>0&&u<=M;class n{static indexKey(t,e){return`t:${A(t)}:${e}`}static json(t,e=200){return P(t,e)}static error(t,e,s){return n.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:$,a=typeof e?.baseMs=="number"&&Number.isFinite(e.baseMs)&&e.baseMs>=0?e.baseMs:b,i=e?.backoff==="linear"?"linear":"exponential",o=typeof e?.maxMs=="number"&&Number.isFinite(e.maxMs)&&e.maxMs>=0?e.maxMs:void 0;return{backoff:i,baseMs:a,maxAttempts:s,maxMs:o}}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;reindexed=!1;poolLock=Promise.resolve();activeLeases=new Map;cancelledLeases=new Set;constructor(t,e){this.state=t,this.env=e,this.armWebSocketKeepalive()}async fetch(t){await this.reindexOrphanedRecords();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(e);case"GET /get":return this.handleGet(e);case"GET /list":return this.handleList(e);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 P({error:{code:"NOT_FOUND"}},404)}async alarm(){await this.reindexOrphanedRecords();const t=Date.now(),e=[],s=new Set,a=await this.state.storage.list({end:`t:${A(t)}:~`,limit:100,prefix:"t:"});for(const[i,o]of a.entries()){const r=Number.parseInt(i.slice(2,i.indexOf(":",2)),10);if(Number.isFinite(r)&&r<=t){const d=await this.state.storage.get(`${c}${o}`);d&&s.has(o)?await this.state.storage.delete(i):d?(s.add(o),e.push({claimKey:i,record:d})):await this.state.storage.delete(i)}}try{await this.drainDue(e)}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"},i=await this.signDispatch(s);i!==void 0?a["x-lunora-scheduler-signature"]=i:typeof this.env.LUNORA_ADMIN_TOKEN=="string"&&this.env.LUNORA_ADMIN_TOKEN.length>0&&(a.authorization=`Bearer ${this.env.LUNORA_ADMIN_TOKEN}`);const o=await fetch(`${e}/_lunora/scheduler/dispatch`,{body:s,headers:a,method:"POST"});return o.status===409&&o.headers.get(x)==="1"&&await o.json().then(d=>d?.error?.code===E,()=>!1)?"in-progress":o.ok}catch{return!1}}armWebSocketKeepalive(){const t=this.state.setWebSocketAutoResponse;typeof t!="function"||typeof WebSocketRequestResponsePair>"u"||t.call(this.state,new WebSocketRequestResponsePair(F,L))}async drainDue(t){const e=[...t],s=[],a=Math.min(T,e.length);for(let i=0;i<a;i+=1)s.push((async()=>{for(let o=e.shift();o!==void 0;o=e.shift())await this.drainRecordGuarded(o.record,o.claimKey)})());await Promise.all(s)}async withPoolLock(t){const e=this.poolLock.then(t,t);return this.poolLock=e.then(()=>{},()=>{}),e}async drainRecordGuarded(t,e){const s=n.indexKey(Date.now()+C,t.id);try{const a=await this.state.storage.get(`${c}${t.id}`);if(a===void 0){await this.state.storage.delete(e);return}if(JSON.stringify(a)!==JSON.stringify(t))return;await this.state.storage.delete(e),await this.state.storage.put(s,t.id),this.activeLeases.set(t.id,s),await this.drainRecord(t)}catch{try{if(this.cancelledLeases.has(t.id)){await this.state.storage.delete(s);return}if(await this.state.storage.get(`${g}${t.id}`)!==void 0){await this.state.storage.delete(s),await this.state.storage.delete([`${m}${t.id}`,`${c}${t.id}`]);return}await this.state.storage.put(e,t.id),await this.state.storage.delete(s)}catch{}return}finally{this.activeLeases.delete(t.id),this.cancelledLeases.delete(t.id)}try{await this.state.storage.delete(s)}catch{}}async drainRecord(t){if(!await this.reservePoolSlot(t))return!1;const s=await this.dispatch(t),a=s===!0,i=t.pool;if(!a&&i!==void 0&&await this.withPoolLock(async()=>{const o=await this.loadPool(i);await this.savePool(i,n.releaseSlot(o,t.id))}),this.cancelledLeases.has(t.id))return a;if(a){try{await this.state.storage.delete([`${c}${t.id}`,`${m}${t.id}`])}catch{}return!0}return await this.recordRetry(t,s==="in-progress"),!1}async reservePoolSlot(t){const e=t.pool;if(e===void 0)return!0;const s=await this.withPoolLock(async()=>{const a=await this.loadPool(e);if(a.inFlight>=a.maxConcurrency)return!1;const i=a.inFlightIds??[];return i.includes(t.id)||i.push(t.id),a.inFlightIds=i,a.inFlight=i.length,await this.savePool(e,a),!0});return s||await this.requeuePooled(t),s}async handleWebSocketUpgrade(){if(this.state.acceptWebSocket===void 0)return n.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.listPage(c,w);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.listPage(c,w),a=JSON.stringify({records:e,truncated:s,type:"jobs"});for(const i of t)try{i.send(a)}catch{}}async listPage(t,e,s){const a=await this.state.storage.list({limit:e+1,prefix:t,...s===void 0?{}:{startAfter:s}}),i=[...a.keys()],o=[...a.values()],r=o.length>e;return r?{cursor:i[e-1],records:o.slice(0,e),truncated:r}:{records:o,truncated:r}}async forEachPage(t,e,s=w){let a;for(;;){const i=await this.state.storage.list(a===void 0?{limit:s,prefix:t}:{limit:s,prefix:t,startAfter:a});if(i.size===0)break;for(const[r,d]of i.entries())e(d,r);if(a=[...i.keys()].at(-1),i.size<s)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"]),i=await crypto.subtle.sign("HMAC",a,s.encode(t));return N(new Uint8Array(i))}async recordRetry(t,e=!1){if(this.cancelledLeases.has(t.id))return;const s=(t.attempts??0)+(e?0:1),a=(t.attempts??0)+1,{backoff:i,baseMs:o,maxAttempts:r,maxMs:d}=n.resolveRetry(t),h=i==="linear"?o*a:o*2**(a-1),l=d===void 0?h:Math.min(h,d),f=e?Math.max(l,b):l,p=Math.round(Date.now()+f);if(s>r){await this.parkDead(t,s,`after ${String(s)} attempts`);return}if(!v(p)){await this.parkDead(t,s,`at attempt ${String(s)}: the retry backoff exceeded the largest schedulable time`);return}const I={...t,attempts:s,scheduledFor:p};await this.state.storage.put({[`${c}${t.id}`]:I,[`${m}${t.id}`]:I,[n.indexKey(p,t.id)]:t.id})}async parkDead(t,e,s){await this.state.storage.put(`${g}${t.id}`,{...t,attempts:e}),await this.state.storage.delete([`${m}${t.id}`,`${c}${t.id}`]),console.warn(`@lunora/scheduler: job "${t.id}" (${t.functionPath??t.workflow??"unknown"}) parked in dead-letter ${s}`)}async loadPool(t,e){const s=await this.state.storage.get(`${y}${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:n.normalizeConcurrency(e,1)}}async savePool(t,e){await this.state.storage.put(`${y}${t}`,e)}async requeuePooled(t){if(this.cancelledLeases.has(t.id))return;const e=Date.now()+k,s={...t,scheduledFor:e};await this.state.storage.put({[`${c}${t.id}`]:s,[n.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 n.error(400,"INVALID_INPUT","pool is required");const i=await this.withPoolLock(async()=>{const o=await this.loadPool(s),r=a===void 0?n.releaseFirstSlot(o):n.releaseSlot(o,a);return await this.savePool(s,r),r});return await this.armAlarmIfEarlier(Date.now()),n.json({inFlight:i.inFlight})}async handlePoolStatus(t){const e=t.searchParams.get("name");if(e===null||e.length===0)return n.error(400,"INVALID_INPUT","name is required");const s=await this.loadPool(e);let a=0;return await this.forEachPage(c,i=>{i.pool===e&&(a+=1)}),n.json({inFlight:s.inFlight,maxConcurrency:s.maxConcurrency,queued:a})}async handleStatus(){const t=new Map;await this.forEachPage(c,o=>{o.pool!==void 0&&t.set(o.pool,(t.get(o.pool)??0)+1)});const e=[];let s=0,a=0;await this.forEachPage(y,(o,r)=>{const d=r.slice(y.length),h=Math.max(0,o.inFlight),l=t.get(d)??0;e.push({inFlight:h,maxConcurrency:o.maxConcurrency,name:d,queued:l}),s+=l,a+=h});const i={backlog:s,inFlight:a,pools:e};return n.json(i)}async persistPoolCap(t,e){const s=await this.loadPool(t,e);await this.savePool(t,{inFlight:s.inFlight,...s.inFlightIds===void 0?{}:{inFlightIds:s.inFlightIds},maxConcurrency:n.normalizeConcurrency(e,s.maxConcurrency)})}async idConflict(t){if(await this.state.storage.get(`${c}${t}`)!==void 0)return n.error(409,"DUPLICATE_SCHEDULE_ID",`a job with id "${t}" is already scheduled — cancel it first, or schedule under a different id`);if(await this.state.storage.get(`${g}${t}`)!==void 0)return n.error(409,"DUPLICATE_SCHEDULE_ID",`id "${t}" is held by a dead-letter record — retry or cancel it (POST /dead/retry, POST /dead/cancel) first, or schedule under a different id`)}async resolveId(t){let e;try{e=R(t)}catch(s){return n.error(400,"INVALID_SCHEDULE_ID",s instanceof Error?s.message:"invalid `id`")}return t===void 0?e:await this.idConflict(e)??e}async handleSchedule(t){const e=await t.json().catch(()=>{}),s=n.resolveScheduleTarget(e);if(!e||s===void 0)return n.error(400,"INVALID_INPUT","functionPath or workflow is required");const{functionPath:a,workflow:i}=s;if(typeof e.scheduledFor!="number"||!v(e.scheduledFor))return n.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 n.error(500,"ORIGIN_NOT_CONFIGURED","LUNORA_ORIGIN_URL env binding must be set on the SchedulerDO");const o=typeof e.pool=="string"&&e.pool.length>0?e.pool:void 0,r=typeof e.instanceName=="string"&&e.instanceName.length>0?e.instanceName:void 0,d=n.normalizeRetry(e.retry),h=await this.resolveId(e.id);if(h instanceof Response)return h;const l=h,f={args:e.args??{},enqueuedAt:Date.now(),id:l,...a===void 0?{}:{functionPath:a},...r===void 0?{}:{instanceName:r},...o===void 0?{}:{pool:o},...d===void 0?{}:{retry:d},scheduledFor:e.scheduledFor,shardKey:e.shardKey,...i===void 0?{}:{workflow:i}};return o!==void 0&&await this.persistPoolCap(o,e.maxConcurrency),await this.state.storage.put(`${c}${l}`,f),await this.state.storage.put(n.indexKey(f.scheduledFor,l),l),await this.armAlarmIfEarlier(f.scheduledFor),await this.broadcastChange(),n.json({id:l,scheduledFor:f.scheduledFor})}async handleCancel(t){const e=await t.json().catch(()=>{});if(!e?.id)return n.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`${c}${e.id}`);return s?(await this.removeRecord(s),await this.rescheduleAlarm(),await this.broadcastChange(),n.json({cancelled:!0})):n.json({cancelled:!1})}async handleList(t){const{cursor:e,records:s,truncated:a}=await this.listPage(c,w,t.searchParams.get("cursor")??void 0);return n.json({cursor:e,records:s,truncated:a})}async handleDeadList(t){const{cursor:e,records:s,truncated:a}=await this.listPage(g,w,t.searchParams.get("cursor")??void 0);return n.json({cursor:e,records:s,truncated:a})}async handleDeadRetry(t){const e=await t.json().catch(()=>{});if(typeof e?.id!="string"||e.id.length===0)return n.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`${g}${e.id}`);if(s===void 0)return n.json({retried:!1});const a=Date.now(),i={...s,attempts:0,scheduledFor:a};return await this.state.storage.put(`${c}${s.id}`,i),await this.state.storage.put(n.indexKey(a,s.id),s.id),await this.state.storage.delete(`${g}${s.id}`),await this.armAlarmIfEarlier(a),await this.broadcastChange(),n.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 n.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.delete(`${g}${e.id}`);return n.json({removed:!!s})}async handleGet(t){const e=t.searchParams.get("id");if(e===null||e.length===0)return n.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`${c}${e}`);return n.json(s===void 0?{}:{record:s})}async removeRecord(t){const e=[`${c}${t.id}`,n.indexKey(t.scheduledFor,t.id),`${m}${t.id}`],s=this.activeLeases.get(t.id);s!==void 0&&(e.push(s),this.cancelledLeases.add(t.id)),await this.state.storage.delete(e)}async armAlarmIfEarlier(t){const e=await this.state.storage.getAlarm();(e===null||t<e)&&await this.state.storage.setAlarm(t)}async reindexOrphanedRecords(){if(this.reindexed)return;this.reindexed=!0;const t=new Set;await this.forEachPage("t:",s=>{t.add(s)});const e=[];await this.forEachPage(c,s=>{!t.has(s.id)&&v(s.scheduledFor)&&e.push(s)});for(const s of e)await this.state.storage.put(n.indexKey(s.scheduledFor,s.id),s.id),await this.armAlarmIfEarlier(s.scheduledFor);if(await this.state.storage.getAlarm()===null){const s=await this.earliestPendingTime();s!==void 0&&Number.isFinite(s)&&await this.state.storage.setAlarm(s)}}async earliestPendingTime(){const e=(await this.state.storage.list({limit:1,prefix:"t:"})).entries().next();if(e.done)return;const[s]=e.value;return Number.parseInt(s.slice(2,s.indexOf(":",2)),10)}async rescheduleAlarm(){const t=await this.earliestPendingTime();if(t===void 0){await this.state.storage.deleteAlarm();return}Number.isFinite(t)&&await this.state.storage.setAlarm(t)}}export{C as DISPATCH_LEASE_MS,T as MAX_CONCURRENT_DISPATCHES,$ as MAX_RETRY_ATTEMPTS,M as MAX_SCHEDULED_FOR_MS,b as RETRY_BASE_DELAY_MS,n as SchedulerDO};
@@ -0,0 +1 @@
1
+ import{LunoraError as r}from"@lunora/errors";import{MAX_SCHEDULED_FOR_MS as i}from"./MAX_RETRY_ATTEMPTS-Q3JXDtb1.mjs";const s=(t,e,n="delayMs")=>{if(!Number.isFinite(t)||t<0)throw new r("INVALID_INPUT",`${e}: \`${n}\` must be a non-negative finite number`);if(Date.now()+t>i)throw new r("INVALID_INPUT",`${e}: \`${n}\` is later than the latest schedulable instant (${String(i)} ms)`)};export{s as default};
@@ -1 +1 @@
1
- import r from"./assertScheduleDelay-BgA4K1WB.mjs";const l=(t,s,a)=>{const e=t-s;r(Number.isFinite(e)&&e<0?0:e,a,"date")};export{l as default};
1
+ import r from"./assertScheduleDelay-Cz5e-UVl.mjs";const l=(t,s,a)=>{const e=t-s;r(Number.isFinite(e)&&e<0?0:e,a,"date")};export{l as default};
@@ -1 +1 @@
1
- const h=t=>{let r="";for(let a=0;a<t.length;a+=32768)r+=String.fromCharCode(...t.subarray(a,a+32768));return btoa(r)},l=t=>{const r=atob(t),n=new Uint8Array(r.length);for(let a=0;a<r.length;a+=1)n[a]=r.codePointAt(a)??0;return n},c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",i=t=>{let r="",n=0;const a=t.length-2;for(;n<a;n+=3){const o=t[n]<<16|t[n+1]<<8|t[n+2];r+=c.charAt(o>>18&63)+c.charAt(o>>12&63)+c.charAt(o>>6&63)+c.charAt(o&63)}const e=t.length-n;if(e===1){const o=t[n]<<16;r+=c.charAt(o>>18&63)+c.charAt(o>>12&63)}else if(e===2){const o=t[n]<<16|t[n+1]<<8;r+=c.charAt(o>>18&63)+c.charAt(o>>12&63)+c.charAt(o>>6&63)}return r};export{h as a,l as f,i as t};
1
+ const h=t=>{let r="";for(let a=0;a<t.length;a+=32768)r+=String.fromCharCode(...t.subarray(a,a+32768));return btoa(r)},l=t=>{const r=atob(t),n=new Uint8Array(r.length);for(let a=0;a<r.length;a+=1)n[a]=r.codePointAt(a)??0;return n},c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",i=t=>{let r="",n=0;const a=t.length-2;for(;n<a;n+=3){const o=t[n]<<16|t[n+1]<<8|t[n+2];r+=c.charAt(o>>18&63)+c.charAt(o>>12&63)+c.charAt(o>>6&63)+c.charAt(o&63)}const e=t.length-n;if(e===1){const o=t[n]<<16;r+=c.charAt(o>>18&63)+c.charAt(o>>12&63)}else if(e===2){const o=t[n]<<16|t[n+1]<<8;r+=c.charAt(o>>18&63)+c.charAt(o>>12&63)+c.charAt(o>>6&63)}return r};export{i as a,l as f,h as t};
@@ -1,4 +1,4 @@
1
- import{LunoraError as d,isLunoraError as k}from"@lunora/errors";import{a as B}from"./wire-codec-TIVAE0Ds.mjs";const Q=9e5,F="DISPATCH_IN_PROGRESS",H="x-lunora-dispatch-declined",W=(e,t,a)=>{if(t===void 0)return{dispose:()=>{},signal:e};const o=new AbortController,r=setTimeout(()=>{o.abort(a())},t);return{dispose:()=>{clearTimeout(r)},signal:o.signal}},G=e=>{let t="";for(let a=0;a<e.length;a+=32768)t+=String.fromCharCode(...e.subarray(a,a+32768));return btoa(t)},V=e=>{const t=atob(e),a=new Uint8Array(t.length);for(let o=0;o<t.length;o+=1)a[o]=t.codePointAt(o)??0;return a},h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",q=e=>{let t="",a=0;const o=e.length-2;for(;a<o;a+=3){const n=e[a]<<16|e[a+1]<<8|e[a+2];t+=h.charAt(n>>18&63)+h.charAt(n>>12&63)+h.charAt(n>>6&63)+h.charAt(n&63)}const r=e.length-a;if(r===1){const n=e[a]<<16;t+=h.charAt(n>>18&63)+h.charAt(n>>12&63)}else if(r===2){const n=e[a]<<16|e[a+1]<<8;t+=h.charAt(n>>18&63)+h.charAt(n>>12&63)+h.charAt(n>>6&63)}return t};new TextDecoder;const U=new TextEncoder,N="=",X=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},z=e=>q(U.encode(JSON.stringify(e))),Y=e=>!e.startsWith(N)&&X(e)?e:`${N}${q(U.encode(e))}`,Z="$lunora.wire$",R=64,v=1024,$="__proto__",I={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},O={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},l=(e,t=0)=>{if(t>R)throw new RangeError(`wire-codec: value nesting exceeds the ${R}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===Z)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>l(r,t+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>v||!/^-?\d+$/.test(r))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${v} digits)`);return BigInt(r)}case"date":{const r=l(e[2],t+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[l(n[0],t+1),l(n[1],t+1)]}))}case"set":return new Set(e[2].map(r=>l(r,t+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],n=e[3];if(typeof r!="string"||typeof n!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(O,r)?O[r]:void 0)??Error,c=new s(n);c.name!==r&&Object.defineProperty(c,"name",{configurable:!0,value:r,writable:!0});const i=l(e[4],t+1);if(i===null||typeof i!="object"||Array.isArray(i))throw new TypeError("wire-codec: malformed error — props must be an object");for(const u of Object.keys(i))u===$?Object.defineProperty(c,u,{configurable:!0,enumerable:!0,value:i[u],writable:!0}):c[u]=i[u];return e.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:l(e[5],t+1),writable:!0}),c}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const n=V(r);if(G(n)!==r)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=e[3]??"Uint8Array";if(s==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;const c=Object.hasOwn(I,s)?I[s]:void 0;return c?new c(n.slice().buffer):n}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>l(r,t+1))}return e.map(r=>l(r,t+1))}const a=e,o={};for(const r of Object.keys(a)){const n=l(a[r],t+1);r===$?Object.defineProperty(o,r,{configurable:!0,enumerable:!0,value:n,writable:!0}):o[r]=n}return o},ee="/_lunora/scheduler/dispatch",te=3e4,re=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},L=Symbol("lunoraDispatchFailure"),P=Symbol("lunoraDispatchDecline"),ne=Symbol("lunoraDispatchMessageId"),x=(e,t)=>(t!==void 0&&Object.defineProperty(e,ne,{value:t}),e),ae=(e,t)=>(Object.defineProperty(e,L,{value:!0}),x(e,t)),oe=(e,t,a,o)=>{const{status:r}=t;try{const n=JSON.parse(a)?.error;if(typeof n=="object"&&n!==null&&typeof n.code=="string"){const{code:s,data:c,message:i}=n,u=ae(new d(s,typeof i=="string"?i:void 0,{data:c,status:r}),o);return t.headers.get(H)==="1"&&Object.defineProperty(u,P,{value:!0}),u}}catch{}return x(new d("INTERNAL",`${e}: function dispatch failed (${String(r)}): ${a}`,{status:r}),o)},se=e=>k(e)&&e[L]===!0,ce=e=>se(e)&&e[P]===!0,_=Q/1e3,ie=3,ue=async(e,t)=>{const a=t.maxRetries??ie,o=typeof e.attempts=="number"&&e.attempts>a;let r="";if(o&&t.requeue!==void 0)try{return await t.requeue(_),e.ack(),"requeued"}catch(n){r=` Re-enqueueing a delayed copy failed (${n instanceof Error?n.message:String(n)}).`}return e.retry({delaySeconds:_}),o&&console.error(`${t.where}: message ${e.id} was declined (${F}) on its last delivery (attempt ${String(e.attempts)} of ${String(a+1)}) — its earlier delivery is still running the call.${r} It is retried anyway, but its retries are exhausted, so it will be dead-lettered if the queue has a deadLetterQueue and dropped if not. Raise max_retries so a slow call cannot exhaust it.`),"retried"},le=(e,t,a)=>new d("INTERNAL",`${e}: function dispatch to "${t}" timed out after ${String(a)}ms`,{status:503}),de=e=>{const{label:t}=e,a=globalThis.fetch,o=e.fetchImpl??(typeof a=="function"?a.bind(globalThis):void 0);return async(r,n,s={})=>{if(typeof o!="function")throw new TypeError(`${t}: no fetch implementation available — pass fetchImpl or run on a platform with global fetch`);const c=()=>n??{},i=e.env.LUNORA_ORIGIN_URL;if(typeof i!="string"||i.length===0)throw new d("INTERNAL",`${t}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const u=e.env.LUNORA_ADMIN_TOKEN;if(typeof u!="string"||u.length===0)throw new d("INTERNAL",`${t}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const w=`${re(i)}${ee}`,m={authorization:`Bearer ${u}`,"content-type":"application/json"};e.traceparent!==void 0&&e.traceparent.length>0&&(m.traceparent=e.traceparent),e.identity?.userId!==void 0&&(m["x-lunora-userid"]=Y(e.identity.userId)),e.identity?.claims!==void 0&&(m["x-lunora-identity"]=z(e.identity.claims));const b=s.timeoutMs??te,E=W(void 0,b,()=>new DOMException(`dispatch timed out after ${String(b)}ms`,"TimeoutError")),A=y=>{throw y instanceof Error&&y.name==="TimeoutError"?le(t,r.__lunoraRef,b):y};let f;try{try{f=await o(w,{body:JSON.stringify({args:c(),functionPath:r.__lunoraRef,id:s.dedupId,shardKey:s.shardKey}),headers:m,method:"POST",signal:E.signal})}catch(g){return A(g)}if(!f.ok){let g;try{g=await f.text()}catch(J){return A(J)}throw oe(t,f,g,s.messageId)}let y;try{y=await f.text()}catch(g){return A(g)}if(y.length===0)return;let p;try{p=JSON.parse(y)}catch{throw new d("INTERNAL",`${t}: function dispatch returned a non-JSON body (${String(f.status)}): ${y}`,{status:f.status})}if(p===null||typeof p!="object"||Array.isArray(p)||!("result"in p))throw new d("INTERNAL",`${t}: function dispatch returned a JSON body that is not a { result } envelope (${String(f.status)}): ${y}`,{status:f.status});return l(p.result)}finally{E.dispose()}}},fe="lunora.requeue.v1",M=new TextEncoder,j=async(e,t)=>crypto.subtle.importKey("raw",M.encode(e),{hash:"SHA-256",name:"HMAC"},!1,[t]),D=(e,t,a)=>M.encode(`${fe}
1
+ import{LunoraError as d,isLunoraError as k}from"@lunora/errors";import{a as B}from"./wire-codec-DtqZBjRy.mjs";const Q=9e5,F="DISPATCH_IN_PROGRESS",H="x-lunora-dispatch-declined",W=(e,t,a)=>{if(t===void 0)return{dispose:()=>{},signal:e};const o=new AbortController,r=setTimeout(()=>{o.abort(a())},t);return{dispose:()=>{clearTimeout(r)},signal:o.signal}},G=e=>{let t="";for(let a=0;a<e.length;a+=32768)t+=String.fromCharCode(...e.subarray(a,a+32768));return btoa(t)},V=e=>{const t=atob(e),a=new Uint8Array(t.length);for(let o=0;o<t.length;o+=1)a[o]=t.codePointAt(o)??0;return a},h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",q=e=>{let t="",a=0;const o=e.length-2;for(;a<o;a+=3){const n=e[a]<<16|e[a+1]<<8|e[a+2];t+=h.charAt(n>>18&63)+h.charAt(n>>12&63)+h.charAt(n>>6&63)+h.charAt(n&63)}const r=e.length-a;if(r===1){const n=e[a]<<16;t+=h.charAt(n>>18&63)+h.charAt(n>>12&63)}else if(r===2){const n=e[a]<<16|e[a+1]<<8;t+=h.charAt(n>>18&63)+h.charAt(n>>12&63)+h.charAt(n>>6&63)}return t};new TextDecoder;const U=new TextEncoder,N="=",X=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},z=e=>q(U.encode(JSON.stringify(e))),Y=e=>!e.startsWith(N)&&X(e)?e:`${N}${q(U.encode(e))}`,Z="$lunora.wire$",R=64,v=1024,$="__proto__",I={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},O={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},l=(e,t=0)=>{if(t>R)throw new RangeError(`wire-codec: value nesting exceeds the ${R}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===Z)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>l(r,t+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>v||!/^-?\d+$/.test(r))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${v} digits)`);return BigInt(r)}case"date":{const r=l(e[2],t+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[l(n[0],t+1),l(n[1],t+1)]}))}case"set":return new Set(e[2].map(r=>l(r,t+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],n=e[3];if(typeof r!="string"||typeof n!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(O,r)?O[r]:void 0)??Error,c=new s(n);c.name!==r&&Object.defineProperty(c,"name",{configurable:!0,value:r,writable:!0});const i=l(e[4],t+1);if(i===null||typeof i!="object"||Array.isArray(i))throw new TypeError("wire-codec: malformed error — props must be an object");for(const u of Object.keys(i))u===$?Object.defineProperty(c,u,{configurable:!0,enumerable:!0,value:i[u],writable:!0}):c[u]=i[u];return e.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:l(e[5],t+1),writable:!0}),c}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const n=V(r);if(G(n)!==r)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=e[3]??"Uint8Array";if(s==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;const c=Object.hasOwn(I,s)?I[s]:void 0;return c?new c(n.slice().buffer):n}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>l(r,t+1))}return e.map(r=>l(r,t+1))}const a=e,o={};for(const r of Object.keys(a)){const n=l(a[r],t+1);r===$?Object.defineProperty(o,r,{configurable:!0,enumerable:!0,value:n,writable:!0}):o[r]=n}return o},ee="/_lunora/scheduler/dispatch",te=3e4,re=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},L=Symbol("lunoraDispatchFailure"),P=Symbol("lunoraDispatchDecline"),ne=Symbol("lunoraDispatchMessageId"),x=(e,t)=>(t!==void 0&&Object.defineProperty(e,ne,{value:t}),e),ae=(e,t)=>(Object.defineProperty(e,L,{value:!0}),x(e,t)),oe=(e,t,a,o)=>{const{status:r}=t;try{const n=JSON.parse(a)?.error;if(typeof n=="object"&&n!==null&&typeof n.code=="string"){const{code:s,data:c,message:i}=n,u=ae(new d(s,typeof i=="string"?i:void 0,{data:c,status:r}),o);return t.headers.get(H)==="1"&&Object.defineProperty(u,P,{value:!0}),u}}catch{}return x(new d("INTERNAL",`${e}: function dispatch failed (${String(r)}): ${a}`,{status:r}),o)},se=e=>k(e)&&e[L]===!0,ce=e=>se(e)&&e[P]===!0,_=Q/1e3,ie=3,ue=async(e,t)=>{const a=t.maxRetries??ie,o=typeof e.attempts=="number"&&e.attempts>a;let r="";if(o&&t.requeue!==void 0)try{return await t.requeue(_),e.ack(),"requeued"}catch(n){r=` Re-enqueueing a delayed copy failed (${n instanceof Error?n.message:String(n)}).`}return e.retry({delaySeconds:_}),o&&console.error(`${t.where}: message ${e.id} was declined (${F}) on its last delivery (attempt ${String(e.attempts)} of ${String(a+1)}) — its earlier delivery is still running the call.${r} It is retried anyway, but its retries are exhausted, so it will be dead-lettered if the queue has a deadLetterQueue and dropped if not. Raise max_retries so a slow call cannot exhaust it.`),"retried"},le=(e,t,a)=>new d("INTERNAL",`${e}: function dispatch to "${t}" timed out after ${String(a)}ms`,{status:503}),de=e=>{const{label:t}=e,a=globalThis.fetch,o=e.fetchImpl??(typeof a=="function"?a.bind(globalThis):void 0);return async(r,n,s={})=>{if(typeof o!="function")throw new TypeError(`${t}: no fetch implementation available — pass fetchImpl or run on a platform with global fetch`);const c=()=>n??{},i=e.env.LUNORA_ORIGIN_URL;if(typeof i!="string"||i.length===0)throw new d("INTERNAL",`${t}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const u=e.env.LUNORA_ADMIN_TOKEN;if(typeof u!="string"||u.length===0)throw new d("INTERNAL",`${t}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const w=`${re(i)}${ee}`,m={authorization:`Bearer ${u}`,"content-type":"application/json"};e.traceparent!==void 0&&e.traceparent.length>0&&(m.traceparent=e.traceparent),e.identity?.userId!==void 0&&(m["x-lunora-userid"]=Y(e.identity.userId)),e.identity?.claims!==void 0&&(m["x-lunora-identity"]=z(e.identity.claims));const b=s.timeoutMs??te,E=W(void 0,b,()=>new DOMException(`dispatch timed out after ${String(b)}ms`,"TimeoutError")),A=y=>{throw y instanceof Error&&y.name==="TimeoutError"?le(t,r.__lunoraRef,b):y};let f;try{try{f=await o(w,{body:JSON.stringify({args:c(),functionPath:r.__lunoraRef,id:s.dedupId,shardKey:s.shardKey}),headers:m,method:"POST",signal:E.signal})}catch(g){return A(g)}if(!f.ok){let g;try{g=await f.text()}catch(J){return A(J)}throw oe(t,f,g,s.messageId)}let y;try{y=await f.text()}catch(g){return A(g)}if(y.length===0)return;let p;try{p=JSON.parse(y)}catch{throw new d("INTERNAL",`${t}: function dispatch returned a non-JSON body (${String(f.status)}): ${y}`,{status:f.status})}if(p===null||typeof p!="object"||Array.isArray(p)||!("result"in p))throw new d("INTERNAL",`${t}: function dispatch returned a JSON body that is not a { result } envelope (${String(f.status)}): ${y}`,{status:f.status});return l(p.result)}finally{E.dispose()}}},fe="lunora.requeue.v1",M=new TextEncoder,j=async(e,t)=>crypto.subtle.importKey("raw",M.encode(e),{hash:"SHA-256",name:"HMAC"},!1,[t]),D=(e,t,a)=>M.encode(`${fe}
2
2
  ${e}
3
3
  ${t}
4
4
  ${a}`),ye=e=>[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join(""),he=/^[\da-f]{64}$/u,pe=async(e,t,a,o)=>ye(await crypto.subtle.sign("HMAC",await j(e,"sign"),D(t,a,o))),ge=async(e,t,a,o,r)=>{if(typeof r!="string"||!he.test(r))return!1;const n=Uint8Array.from({length:r.length/2},(s,c)=>Number.parseInt(r.slice(c*2,c*2+2),16));return crypto.subtle.verify("HMAC",await j(e,"verify"),n,D(t,a,o))},S=100,me=3e5,T=e=>e===void 0?void 0:B(e),Ne=e=>{if(!e.queue)throw new d("INTERNAL","@lunora/scheduler: `queue` (a Cloudflare Queue binding) is required");return{enqueue:async(o,r,n={})=>{const s={args:T(r),functionPath:o.__lunoraRef,shardKey:n.shardKey},c=n.delaySeconds===void 0?void 0:{delaySeconds:n.delaySeconds};await e.queue.send(s,c)},enqueueBatch:async(o,r)=>{if(o.length>S)throw new d("VALIDATION_ERROR",`@lunora/scheduler: enqueueBatch exceeds ${String(S)} (got ${String(o.length)}) — split across calls`);const n=o.map(s=>({body:{args:T(s.args),functionPath:s.ref.__lunoraRef,shardKey:s.shardKey}}));await e.queue.sendBatch(n,r)}}},we=e=>typeof e=="object"&&e!==null&&typeof e.functionPath=="string",K="scheduler",C=e=>JSON.stringify({args:e.args,functionPath:e.functionPath,shardKey:e.shardKey}),be=async(e,t,a)=>{const{requeuedFrom:o,requeueMac:r,...n}=e;return typeof o=="string"&&a!==void 0&&await ge(a,K,o,C(n),r).catch(()=>!1)?{id:o,job:n,requeued:!0}:{id:t,job:n,requeued:!1}},Re=e=>async t=>{await Promise.all(t.messages.map(async a=>{let o;try{if(!we(a.body))throw new d("INTERNAL","@lunora/scheduler: queue message body is not a QueueJob (missing functionPath)");o=await be(a.body,a.id,e.requeue?.secret),await e.dispatch(o.job,o.id),a.ack()}catch(r){if(ce(r)&&o!==void 0){const{requeue:n}=e,{id:s,job:c,requeued:i}=o;await ue(a,{maxRetries:e.maxRetries,requeue:n===void 0||i?void 0:async u=>{const w=await pe(n.secret,K,s,C(c));await n.queue.send({...c,requeuedFrom:s,requeueMac:w},{delaySeconds:u})},where:`@lunora/scheduler: queue "${t.queue}"`});return}a.retry()}}))},ve=e=>{const t=de({env:{LUNORA_ADMIN_TOKEN:e.adminToken,LUNORA_ORIGIN_URL:e.originUrl},fetchImpl:e.fetchImpl,label:"@lunora/scheduler"}),a=e.timeoutMs??me;return async(o,r)=>{await t({__lunoraRef:o.functionPath},o.args,{dedupId:r,messageId:r,shardKey:o.shardKey,timeoutMs:a})}};export{Re as createQueueConsumer,Ne as createQueueWorkpool,ve as httpDispatcher};
@@ -0,0 +1 @@
1
+ import{LunoraError as g}from"@lunora/errors";import{e as w,d as A}from"./wire-codec-DtqZBjRy.mjs";import{a as p,c as d,g as f}from"./do-client-XQayNStI.mjs";import{isWorkflowReference as y}from"./isWorkflowReference-CT3tdefh.mjs";import R from"./assertScheduleDelay-Cz5e-UVl.mjs";import b from"./assertScheduleInstant-CMN9XCFm.mjs";const v=async e=>{const o=[];let a;for(;;){const c=await e(a);if(o.push(...Array.isArray(c.records)?c.records:[]),c.truncated!==!0||typeof c.cursor!="string"||c.cursor.length===0)return o;if(c.cursor===a)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");a=c.cursor}},x=e=>typeof e=="string"?e:(y(e)?e.binding:e.__lunoraRef)??"<unknown>",h=e=>({...e,args:A(e.args)}),K=e=>{p(e);const o=async(n,r,s,t={})=>{const l=Math.ceil(n instanceof Date?n.getTime():n);b(l,Date.now(),"ctx.scheduler.runAt");const i={args:w("ctx.scheduler.runAt",x(r),s),id:t.id,instanceName:e.instanceName??"default",maxConcurrency:t.pool===void 0?void 0:t.maxConcurrency,pool:t.pool,retry:t.retry,scheduledFor:l,shardKey:t.shardKey};if(y(r)){if(typeof r.binding!="string"||r.binding.length===0)throw new g("INTERNAL","@lunora/scheduler: workflow/agent schedule target is missing its `binding` — pass the generated `workflows.<name>` / `agents.<name>` reference");return(await d(e,"/schedule",{...i,workflow:r.binding})).id}const m=typeof r=="string"?r:r.__lunoraRef;return(await d(e,"/schedule",{...i,functionPath:m})).id},a=async(n,r,s,t={})=>(R(n,"ctx.scheduler.runAfter"),o(Date.now()+n,r,s,t)),c=async n=>d(e,"/cancel",{id:n}),u=async n=>(await v(async s=>f(e,s===void 0?n:`${n}?cursor=${encodeURIComponent(s)}`))).map(s=>h(s));return{cancel:c,dead:async()=>u("/dead"),deadRetry:async n=>{const{retried:r}=await d(e,"/dead/retry",{id:n});return r===!0},get:async n=>{const r=await f(e,`/get?id=${encodeURIComponent(n)}`);return r.record===void 0?null:h(r.record)},list:async()=>u("/list"),runAfter:a,runAt:o}};export{K as default};
@@ -1 +1 @@
1
- import u from"./createScheduler-BW6wVD57.mjs";const i=t=>t?.at!==void 0?typeof t.at=="number"?t.at:t.at.getTime():Date.now()+(t?.delayMs??0),m=t=>{const r=u({instanceName:t.instanceName,jurisdiction:t.jurisdiction,namespace:t.namespace}),n=e=>({attempts:e.attempts??0,functionPath:e.functionPath??e.workflow??"",id:e.id,scheduledFor:e.scheduledFor});return{cancel:async e=>{const{cancelled:a}=await r.cancel(e);return a},deadLetter:{list:async()=>(await r.dead()).map(a=>n(a)),requeue:async e=>r.deadRetry(e)},list:async()=>(await r.list()).map(a=>n(a)),schedule:async(e,a,c)=>{const d=r.runAt,s=i(c);return{id:await d(s,e,a,{retry:c?.retry,shardKey:c?.shardKey}),scheduledFor:s}}}};export{m as createSchedulerHost};
1
+ import u from"./createScheduler-BEOeea0Y.mjs";const i=t=>t?.at!==void 0?typeof t.at=="number"?t.at:t.at.getTime():Date.now()+(t?.delayMs??0),m=t=>{const r=u({instanceName:t.instanceName,jurisdiction:t.jurisdiction,namespace:t.namespace}),n=e=>({attempts:e.attempts??0,functionPath:e.functionPath??e.workflow??"",id:e.id,scheduledFor:e.scheduledFor});return{cancel:async e=>{const{cancelled:a}=await r.cancel(e);return a},deadLetter:{list:async()=>(await r.dead()).map(a=>n(a)),requeue:async e=>r.deadRetry(e)},list:async()=>(await r.list()).map(a=>n(a)),schedule:async(e,a,c)=>{const d=r.runAt,s=i(c);return{id:await d(s,e,a,{retry:c?.retry,shardKey:c?.shardKey}),scheduledFor:s}}}};export{m as createSchedulerHost};
@@ -0,0 +1 @@
1
+ import{LunoraError as l}from"@lunora/errors";import{e as s}from"./wire-codec-DtqZBjRy.mjs";import{a as o,g as m,c as u}from"./do-client-XQayNStI.mjs";import y from"./assertScheduleDelay-Cz5e-UVl.mjs";const N=e=>{if(o(e),!Number.isInteger(e.maxConcurrency)||e.maxConcurrency<=0)throw new l("INTERNAL","@lunora/scheduler: `maxConcurrency` must be a positive integer");const a=typeof e.name=="string"&&e.name.length>0?e.name:"default";return{cancel:async r=>u(e,"/cancel",{id:r}),enqueue:async(r,t,n={})=>{const c=n.delayMs??0;return y(c,"workpool.enqueue"),u(e,"/schedule",{args:s("workpool.enqueue",r.__lunoraRef,t),functionPath:r.__lunoraRef,instanceName:e.instanceName??"default",maxConcurrency:e.maxConcurrency,pool:a,retry:n.retry,scheduledFor:Math.ceil(Date.now()+c),shardKey:n.shardKey})},name:a,status:async()=>m(e,`/pool?name=${encodeURIComponent(a)}`)}};export{N as default};
@@ -1 +1 @@
1
- import{LunoraError as o}from"@lunora/errors";import{t as r}from"./base64-BFBvYeZM.mjs";const a=/^\w[\w-]{0,63}$/u,n=/^-/u,i=t=>{if(t===void 0)return r(crypto.getRandomValues(new Uint8Array(12))).replace(n,"_");if(typeof t!="string"||!a.test(t))throw new o("INVALID_SCHEDULE_ID","@lunora/scheduler: `id` must be 1-64 characters of [A-Za-z0-9_-] and must not start with `-`; omit it to have one minted",{status:400});return t};export{i as default};
1
+ import{LunoraError as o}from"@lunora/errors";import{a as r}from"./base64-junLSktH.mjs";const a=/^\w[\w-]{0,63}$/u,n=/^-/u,i=t=>{if(t===void 0)return r(crypto.getRandomValues(new Uint8Array(12))).replace(n,"_");if(typeof t!="string"||!a.test(t))throw new o("INVALID_SCHEDULE_ID","@lunora/scheduler: `id` must be 1-64 characters of [A-Za-z0-9_-] and must not start with `-`; omit it to have one minted",{status:400});return t};export{i as default};
@@ -1 +1 @@
1
- import{a as d,f as E}from"./base64-BFBvYeZM.mjs";const o="$lunora.wire$",w=64,p=1024,g="__proto__",l={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},A={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},O=e=>{if(e===null||typeof e!="object")return!1;const n=Object.getPrototypeOf(e);return n===null||n===Object.prototype},u=(e,n=0)=>{if(n>w)throw new RangeError(`wire-codec: value nesting exceeds the ${w}-level limit`);if(e===void 0)return[o,"undefined"];if(e===null)return null;const b=typeof e;if(b==="bigint")return[o,"bigint",e.toString()];if(b==="number"){const r=e;return Number.isNaN(r)?[o,"nan"]:r===1/0?[o,"inf"]:r===-1/0?[o,"-inf"]:r}if(b!=="object")return e;if(e instanceof Date)return[o,"date",u(e.getTime(),n+1)];if(e instanceof Error){const r=e,t={};for(const i of Object.keys(r)){if(r[i]===void 0)continue;const y=u(r[i],n+1);i===g?Object.defineProperty(t,i,{configurable:!0,enumerable:!0,value:y,writable:!0}):t[i]=y}const s=[o,"error",String(r.name),String(r.message),t];return r.cause!==void 0&&s.push(u(r.cause,n+1)),s}if(e instanceof URL)return[o,"url",e.href];if(e instanceof Map)return[o,"map",[...e.entries()].map(([r,t])=>[u(r,n+1),u(t,n+1)])];if(e instanceof Set)return[o,"set",[...e].map(r=>u(r,n+1))];if(e instanceof ArrayBuffer)return[o,"bytes",d(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,t=r.constructor.name,s=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return t==="Uint8Array"?[o,"bytes",d(s)]:[o,"bytes",d(s),t]}if(Array.isArray(e)){const r=e.map(t=>u(t,n+1));return r.length>0&&r[0]===o?[o,"arr",r]:r}if(!O(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const c=e,a={};for(const r of Object.keys(c)){const t=c[r];if(t===void 0)continue;const s=u(t,n+1);r===g?Object.defineProperty(a,r,{configurable:!0,enumerable:!0,value:s,writable:!0}):a[r]=s}return a},f=(e,n=0)=>{if(n>w)throw new RangeError(`wire-codec: value nesting exceeds the ${w}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===o)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>f(r,n+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>p||!/^-?\d+$/.test(r))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${p} digits)`);return BigInt(r)}case"date":{const r=f(e[2],n+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(t=>{if(!Array.isArray(t)||t.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[f(t[0],n+1),f(t[1],n+1)]}))}case"set":return new Set(e[2].map(r=>f(r,n+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],t=e[3];if(typeof r!="string"||typeof t!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(A,r)?A[r]:void 0)??Error,i=new s(t);i.name!==r&&Object.defineProperty(i,"name",{configurable:!0,value:r,writable:!0});const y=f(e[4],n+1);if(y===null||typeof y!="object"||Array.isArray(y))throw new TypeError("wire-codec: malformed error — props must be an object");for(const m of Object.keys(y))m===g?Object.defineProperty(i,m,{configurable:!0,enumerable:!0,value:y[m],writable:!0}):i[m]=y[m];return e.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:f(e[5],n+1),writable:!0}),i}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const t=E(r);if(d(t)!==r)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=e[3]??"Uint8Array";if(s==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const i=Object.hasOwn(l,s)?l[s]:void 0;return i?new i(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>f(r,n+1))}return e.map(a=>f(a,n+1))}const b=e,c={};for(const a of Object.keys(b)){const r=f(b[a],n+1);a===g?Object.defineProperty(c,a,{configurable:!0,enumerable:!0,value:r,writable:!0}):c[a]=r}return c},T=(e,n,b)=>{try{return u(b)}catch(c){throw new TypeError(`${e}: cannot encode args for '${n}' — ${c instanceof Error?c.message:String(c)}`,c instanceof Error?{cause:c}:void 0)}};export{u as a,f as d,T as e};
1
+ import{t as d,f as E}from"./base64-junLSktH.mjs";const o="$lunora.wire$",w=64,p=1024,g="__proto__",l={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},A={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},O=e=>{if(e===null||typeof e!="object")return!1;const n=Object.getPrototypeOf(e);return n===null||n===Object.prototype},u=(e,n=0)=>{if(n>w)throw new RangeError(`wire-codec: value nesting exceeds the ${w}-level limit`);if(e===void 0)return[o,"undefined"];if(e===null)return null;const b=typeof e;if(b==="bigint")return[o,"bigint",e.toString()];if(b==="number"){const r=e;return Number.isNaN(r)?[o,"nan"]:r===1/0?[o,"inf"]:r===-1/0?[o,"-inf"]:r}if(b!=="object")return e;if(e instanceof Date)return[o,"date",u(e.getTime(),n+1)];if(e instanceof Error){const r=e,t={};for(const i of Object.keys(r)){if(r[i]===void 0)continue;const y=u(r[i],n+1);i===g?Object.defineProperty(t,i,{configurable:!0,enumerable:!0,value:y,writable:!0}):t[i]=y}const s=[o,"error",String(r.name),String(r.message),t];return r.cause!==void 0&&s.push(u(r.cause,n+1)),s}if(e instanceof URL)return[o,"url",e.href];if(e instanceof Map)return[o,"map",[...e.entries()].map(([r,t])=>[u(r,n+1),u(t,n+1)])];if(e instanceof Set)return[o,"set",[...e].map(r=>u(r,n+1))];if(e instanceof ArrayBuffer)return[o,"bytes",d(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,t=r.constructor.name,s=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return t==="Uint8Array"?[o,"bytes",d(s)]:[o,"bytes",d(s),t]}if(Array.isArray(e)){const r=e.map(t=>u(t,n+1));return r.length>0&&r[0]===o?[o,"arr",r]:r}if(!O(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const c=e,a={};for(const r of Object.keys(c)){const t=c[r];if(t===void 0)continue;const s=u(t,n+1);r===g?Object.defineProperty(a,r,{configurable:!0,enumerable:!0,value:s,writable:!0}):a[r]=s}return a},f=(e,n=0)=>{if(n>w)throw new RangeError(`wire-codec: value nesting exceeds the ${w}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===o)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>f(r,n+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>p||!/^-?\d+$/.test(r))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${p} digits)`);return BigInt(r)}case"date":{const r=f(e[2],n+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(t=>{if(!Array.isArray(t)||t.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[f(t[0],n+1),f(t[1],n+1)]}))}case"set":return new Set(e[2].map(r=>f(r,n+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],t=e[3];if(typeof r!="string"||typeof t!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(A,r)?A[r]:void 0)??Error,i=new s(t);i.name!==r&&Object.defineProperty(i,"name",{configurable:!0,value:r,writable:!0});const y=f(e[4],n+1);if(y===null||typeof y!="object"||Array.isArray(y))throw new TypeError("wire-codec: malformed error — props must be an object");for(const m of Object.keys(y))m===g?Object.defineProperty(i,m,{configurable:!0,enumerable:!0,value:y[m],writable:!0}):i[m]=y[m];return e.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:f(e[5],n+1),writable:!0}),i}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const t=E(r);if(d(t)!==r)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=e[3]??"Uint8Array";if(s==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const i=Object.hasOwn(l,s)?l[s]:void 0;return i?new i(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>f(r,n+1))}return e.map(a=>f(a,n+1))}const b=e,c={};for(const a of Object.keys(b)){const r=f(b[a],n+1);a===g?Object.defineProperty(c,a,{configurable:!0,enumerable:!0,value:r,writable:!0}):c[a]=r}return c},T=(e,n,b)=>{try{return u(b)}catch(c){throw new TypeError(`${e}: cannot encode args for '${n}' — ${c instanceof Error?c.message:String(c)}`,c instanceof Error?{cause:c}:void 0)}};export{u as a,f as d,T as e};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/scheduler",
3
- "version": "1.0.0-alpha.92",
3
+ "version": "1.0.0-alpha.94",
4
4
  "description": "Scheduling for Lunora: runAfter / runAt and Cron Triggers via SchedulerDO",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,7 +46,7 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/errors": "1.0.0-alpha.45",
49
+ "@lunora/errors": "1.0.0-alpha.46",
50
50
  "@lunora/platform": "1.0.0-alpha.41",
51
51
  "cron-parser": "5.10.0"
52
52
  },
@@ -1 +0,0 @@
1
- import{t as R}from"./base64-BFBvYeZM.mjs";import N from"./resolveScheduleId-DgysKSrN.mjs";const E="DISPATCH_IN_PROGRESS",x="x-lunora-dispatch-declined",P=(u,t=200,e)=>{const s=new Headers({"content-type":"application/json"});for(const[a,i]of Object.entries({}))s.set(a,i);return Response.json(u,{headers:s,status:t})},F="lunora-ping",$="lunora-pong",c="id:",m="retry:",g="dead:",y="pool:",w=100,L=5,b=3e4,k=1e3,T=6,C=9e5,M=999999999999999,U=15,A=u=>String(u).padStart(U,"0"),v=u=>Number.isInteger(u)&&u>0&&u<=M;class n{static indexKey(t,e){return`t:${A(t)}:${e}`}static json(t,e=200){return P(t,e)}static error(t,e,s){return n.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:L,a=typeof e?.baseMs=="number"&&Number.isFinite(e.baseMs)&&e.baseMs>=0?e.baseMs:b,i=e?.backoff==="linear"?"linear":"exponential",o=typeof e?.maxMs=="number"&&Number.isFinite(e.maxMs)&&e.maxMs>=0?e.maxMs:void 0;return{backoff:i,baseMs:a,maxAttempts:s,maxMs:o}}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;reindexed=!1;poolLock=Promise.resolve();activeLeases=new Map;constructor(t,e){this.state=t,this.env=e,this.armWebSocketKeepalive()}async fetch(t){await this.reindexOrphanedRecords();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(e);case"GET /get":return this.handleGet(e);case"GET /list":return this.handleList(e);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 P({error:{code:"NOT_FOUND"}},404)}async alarm(){await this.reindexOrphanedRecords();const t=Date.now(),e=[],s=new Set,a=await this.state.storage.list({end:`t:${A(t)}:~`,limit:100,prefix:"t:"});for(const[i,o]of a.entries()){const r=Number.parseInt(i.slice(2,i.indexOf(":",2)),10);if(Number.isFinite(r)&&r<=t){const d=await this.state.storage.get(`${c}${o}`);d&&s.has(o)?await this.state.storage.delete(i):d?(s.add(o),e.push({claimKey:i,record:d})):await this.state.storage.delete(i)}}try{await this.drainDue(e)}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"},i=await this.signDispatch(s);i!==void 0?a["x-lunora-scheduler-signature"]=i:typeof this.env.LUNORA_ADMIN_TOKEN=="string"&&this.env.LUNORA_ADMIN_TOKEN.length>0&&(a.authorization=`Bearer ${this.env.LUNORA_ADMIN_TOKEN}`);const o=await fetch(`${e}/_lunora/scheduler/dispatch`,{body:s,headers:a,method:"POST"});return o.status===409&&o.headers.get(x)==="1"&&await o.json().then(d=>d?.error?.code===E,()=>!1)?"in-progress":o.ok}catch{return!1}}armWebSocketKeepalive(){const t=this.state.setWebSocketAutoResponse;typeof t!="function"||typeof WebSocketRequestResponsePair>"u"||t.call(this.state,new WebSocketRequestResponsePair(F,$))}async drainDue(t){const e=[...t],s=[],a=Math.min(T,e.length);for(let i=0;i<a;i+=1)s.push((async()=>{for(let o=e.shift();o!==void 0;o=e.shift())await this.drainRecordGuarded(o.record,o.claimKey)})());await Promise.all(s)}async withPoolLock(t){const e=this.poolLock.then(t,t);return this.poolLock=e.then(()=>{},()=>{}),e}async drainRecordGuarded(t,e){const s=n.indexKey(Date.now()+C,t.id);try{await this.state.storage.delete(e),await this.state.storage.put(s,t.id),this.activeLeases.set(t.id,s),await this.drainRecord(t)}catch{try{if(await this.state.storage.get(`${g}${t.id}`)!==void 0){await this.state.storage.delete(s),await this.state.storage.delete([`${m}${t.id}`,`${c}${t.id}`]);return}await this.state.storage.put(e,t.id),await this.state.storage.delete(s)}catch{}return}finally{this.activeLeases.delete(t.id)}try{await this.state.storage.delete(s)}catch{}}async drainRecord(t){if(!await this.reservePoolSlot(t))return!1;const s=await this.dispatch(t),a=s===!0,i=t.pool;if(!a&&i!==void 0&&await this.withPoolLock(async()=>{const o=await this.loadPool(i);await this.savePool(i,n.releaseSlot(o,t.id))}),a){try{await this.state.storage.delete([`${c}${t.id}`,`${m}${t.id}`])}catch{}return!0}return await this.recordRetry(t,s==="in-progress"),!1}async reservePoolSlot(t){const e=t.pool;if(e===void 0)return!0;const s=await this.withPoolLock(async()=>{const a=await this.loadPool(e);if(a.inFlight>=a.maxConcurrency)return!1;const i=a.inFlightIds??[];return i.includes(t.id)||i.push(t.id),a.inFlightIds=i,a.inFlight=i.length,await this.savePool(e,a),!0});return s||await this.requeuePooled(t),s}async handleWebSocketUpgrade(){if(this.state.acceptWebSocket===void 0)return n.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.listPage(c,w);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.listPage(c,w),a=JSON.stringify({records:e,truncated:s,type:"jobs"});for(const i of t)try{i.send(a)}catch{}}async listPage(t,e,s){const a=await this.state.storage.list({limit:e+1,prefix:t,...s===void 0?{}:{startAfter:s}}),i=[...a.keys()],o=[...a.values()],r=o.length>e;return r?{cursor:i[e-1],records:o.slice(0,e),truncated:r}:{records:o,truncated:r}}async forEachPage(t,e,s=w){let a;for(;;){const i=await this.state.storage.list(a===void 0?{limit:s,prefix:t}:{limit:s,prefix:t,startAfter:a});if(i.size===0)break;for(const[r,d]of i.entries())e(d,r);if(a=[...i.keys()].at(-1),i.size<s)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"]),i=await crypto.subtle.sign("HMAC",a,s.encode(t));return R(new Uint8Array(i))}async recordRetry(t,e=!1){const s=(t.attempts??0)+(e?0:1),a=(t.attempts??0)+1,{backoff:i,baseMs:o,maxAttempts:r,maxMs:d}=n.resolveRetry(t),h=i==="linear"?o*a:o*2**(a-1),l=d===void 0?h:Math.min(h,d),f=e?Math.max(l,b):l,p=Math.round(Date.now()+f);if(s>r){await this.parkDead(t,s,`after ${String(s)} attempts`);return}if(!v(p)){await this.parkDead(t,s,`at attempt ${String(s)}: the retry backoff exceeded the largest schedulable time`);return}const I={...t,attempts:s,scheduledFor:p};await this.state.storage.put(`${m}${t.id}`,I),await this.state.storage.put(`${c}${t.id}`,I),await this.state.storage.put(n.indexKey(p,t.id),t.id)}async parkDead(t,e,s){await this.state.storage.put(`${g}${t.id}`,{...t,attempts:e}),await this.state.storage.delete([`${m}${t.id}`,`${c}${t.id}`]),console.warn(`@lunora/scheduler: job "${t.id}" (${t.functionPath??t.workflow??"unknown"}) parked in dead-letter ${s}`)}async loadPool(t,e){const s=await this.state.storage.get(`${y}${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:n.normalizeConcurrency(e,1)}}async savePool(t,e){await this.state.storage.put(`${y}${t}`,e)}async requeuePooled(t){const e=Date.now()+k,s={...t,scheduledFor:e};await this.state.storage.put(`${c}${t.id}`,s),await this.state.storage.put(n.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 n.error(400,"INVALID_INPUT","pool is required");const i=await this.withPoolLock(async()=>{const o=await this.loadPool(s),r=a===void 0?n.releaseFirstSlot(o):n.releaseSlot(o,a);return await this.savePool(s,r),r});return await this.armAlarmIfEarlier(Date.now()),n.json({inFlight:i.inFlight})}async handlePoolStatus(t){const e=t.searchParams.get("name");if(e===null||e.length===0)return n.error(400,"INVALID_INPUT","name is required");const s=await this.loadPool(e);let a=0;return await this.forEachPage(c,i=>{i.pool===e&&(a+=1)}),n.json({inFlight:s.inFlight,maxConcurrency:s.maxConcurrency,queued:a})}async handleStatus(){const t=new Map;await this.forEachPage(c,o=>{o.pool!==void 0&&t.set(o.pool,(t.get(o.pool)??0)+1)});const e=[];let s=0,a=0;await this.forEachPage(y,(o,r)=>{const d=r.slice(y.length),h=Math.max(0,o.inFlight),l=t.get(d)??0;e.push({inFlight:h,maxConcurrency:o.maxConcurrency,name:d,queued:l}),s+=l,a+=h});const i={backlog:s,inFlight:a,pools:e};return n.json(i)}async persistPoolCap(t,e){const s=await this.loadPool(t,e);await this.savePool(t,{inFlight:s.inFlight,...s.inFlightIds===void 0?{}:{inFlightIds:s.inFlightIds},maxConcurrency:n.normalizeConcurrency(e,s.maxConcurrency)})}async idConflict(t){if(await this.state.storage.get(`${c}${t}`)!==void 0)return n.error(409,"DUPLICATE_SCHEDULE_ID",`a job with id "${t}" is already scheduled — cancel it first, or schedule under a different id`);if(await this.state.storage.get(`${g}${t}`)!==void 0)return n.error(409,"DUPLICATE_SCHEDULE_ID",`id "${t}" is held by a dead-letter record — retry or cancel it (POST /dead/retry, POST /dead/cancel) first, or schedule under a different id`)}async resolveId(t){let e;try{e=N(t)}catch(s){return n.error(400,"INVALID_SCHEDULE_ID",s instanceof Error?s.message:"invalid `id`")}return t===void 0?e:await this.idConflict(e)??e}async handleSchedule(t){const e=await t.json().catch(()=>{}),s=n.resolveScheduleTarget(e);if(!e||s===void 0)return n.error(400,"INVALID_INPUT","functionPath or workflow is required");const{functionPath:a,workflow:i}=s;if(typeof e.scheduledFor!="number"||!v(e.scheduledFor))return n.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 n.error(500,"ORIGIN_NOT_CONFIGURED","LUNORA_ORIGIN_URL env binding must be set on the SchedulerDO");const o=typeof e.pool=="string"&&e.pool.length>0?e.pool:void 0,r=typeof e.instanceName=="string"&&e.instanceName.length>0?e.instanceName:void 0,d=n.normalizeRetry(e.retry),h=await this.resolveId(e.id);if(h instanceof Response)return h;const l=h,f={args:e.args??{},enqueuedAt:Date.now(),id:l,...a===void 0?{}:{functionPath:a},...r===void 0?{}:{instanceName:r},...o===void 0?{}:{pool:o},...d===void 0?{}:{retry:d},scheduledFor:e.scheduledFor,shardKey:e.shardKey,...i===void 0?{}:{workflow:i}};return o!==void 0&&await this.persistPoolCap(o,e.maxConcurrency),await this.state.storage.put(`${c}${l}`,f),await this.state.storage.put(n.indexKey(f.scheduledFor,l),l),await this.armAlarmIfEarlier(f.scheduledFor),await this.broadcastChange(),n.json({id:l,scheduledFor:f.scheduledFor})}async handleCancel(t){const e=await t.json().catch(()=>{});if(!e?.id)return n.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`${c}${e.id}`);return s?(await this.removeRecord(s),await this.rescheduleAlarm(),await this.broadcastChange(),n.json({cancelled:!0})):n.json({cancelled:!1})}async handleList(t){const{cursor:e,records:s,truncated:a}=await this.listPage(c,w,t.searchParams.get("cursor")??void 0);return n.json({cursor:e,records:s,truncated:a})}async handleDeadList(t){const{cursor:e,records:s,truncated:a}=await this.listPage(g,w,t.searchParams.get("cursor")??void 0);return n.json({cursor:e,records:s,truncated:a})}async handleDeadRetry(t){const e=await t.json().catch(()=>{});if(typeof e?.id!="string"||e.id.length===0)return n.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`${g}${e.id}`);if(s===void 0)return n.json({retried:!1});const a=Date.now(),i={...s,attempts:0,scheduledFor:a};return await this.state.storage.put(`${c}${s.id}`,i),await this.state.storage.put(n.indexKey(a,s.id),s.id),await this.state.storage.delete(`${g}${s.id}`),await this.armAlarmIfEarlier(a),await this.broadcastChange(),n.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 n.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.delete(`${g}${e.id}`);return n.json({removed:!!s})}async handleGet(t){const e=t.searchParams.get("id");if(e===null||e.length===0)return n.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`${c}${e}`);return n.json(s===void 0?{}:{record:s})}async removeRecord(t){const e=[`${c}${t.id}`,n.indexKey(t.scheduledFor,t.id),`${m}${t.id}`],s=this.activeLeases.get(t.id);s!==void 0&&e.push(s),await this.state.storage.delete(e)}async armAlarmIfEarlier(t){const e=await this.state.storage.getAlarm();(e===null||t<e)&&await this.state.storage.setAlarm(t)}async reindexOrphanedRecords(){if(this.reindexed)return;this.reindexed=!0;const t=new Set;await this.forEachPage("t:",s=>{t.add(s)});const e=[];await this.forEachPage(c,s=>{!t.has(s.id)&&v(s.scheduledFor)&&e.push(s)});for(const s of e)await this.state.storage.put(n.indexKey(s.scheduledFor,s.id),s.id),await this.armAlarmIfEarlier(s.scheduledFor);if(await this.state.storage.getAlarm()===null){const s=await this.earliestPendingTime();s!==void 0&&Number.isFinite(s)&&await this.state.storage.setAlarm(s)}}async earliestPendingTime(){const e=(await this.state.storage.list({limit:1,prefix:"t:"})).entries().next();if(e.done)return;const[s]=e.value;return Number.parseInt(s.slice(2,s.indexOf(":",2)),10)}async rescheduleAlarm(){const t=await this.earliestPendingTime();if(t===void 0){await this.state.storage.deleteAlarm();return}Number.isFinite(t)&&await this.state.storage.setAlarm(t)}}export{C as DISPATCH_LEASE_MS,T as MAX_CONCURRENT_DISPATCHES,L as MAX_RETRY_ATTEMPTS,b as RETRY_BASE_DELAY_MS,n as SchedulerDO};
@@ -1 +0,0 @@
1
- import{LunoraError as n}from"@lunora/errors";const o=(e,r,t="delayMs")=>{if(!Number.isFinite(e)||e<0)throw new n("INVALID_INPUT",`${r}: \`${t}\` must be a non-negative finite number`)};export{o as default};
@@ -1 +0,0 @@
1
- import{LunoraError as g}from"@lunora/errors";import{e as w,d as A}from"./wire-codec-TIVAE0Ds.mjs";import{a as p,c as d,g as f}from"./do-client-XQayNStI.mjs";import{isWorkflowReference as y}from"./isWorkflowReference-CT3tdefh.mjs";import R from"./assertScheduleDelay-BgA4K1WB.mjs";import b from"./assertScheduleInstant-BzESPqyw.mjs";const v=async e=>{const o=[];let a;for(;;){const c=await e(a);if(o.push(...Array.isArray(c.records)?c.records:[]),c.truncated!==!0||typeof c.cursor!="string"||c.cursor.length===0)return o;if(c.cursor===a)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");a=c.cursor}},x=e=>typeof e=="string"?e:(y(e)?e.binding:e.__lunoraRef)??"<unknown>",h=e=>({...e,args:A(e.args)}),K=e=>{p(e);const o=async(n,r,s,t={})=>{const l=n instanceof Date?n.getTime():n;b(l,Date.now(),"ctx.scheduler.runAt");const i={args:w("ctx.scheduler.runAt",x(r),s),id:t.id,instanceName:e.instanceName??"default",maxConcurrency:t.pool===void 0?void 0:t.maxConcurrency,pool:t.pool,retry:t.retry,scheduledFor:l,shardKey:t.shardKey};if(y(r)){if(typeof r.binding!="string"||r.binding.length===0)throw new g("INTERNAL","@lunora/scheduler: workflow/agent schedule target is missing its `binding` — pass the generated `workflows.<name>` / `agents.<name>` reference");return(await d(e,"/schedule",{...i,workflow:r.binding})).id}const m=typeof r=="string"?r:r.__lunoraRef;return(await d(e,"/schedule",{...i,functionPath:m})).id},a=async(n,r,s,t={})=>(R(n,"ctx.scheduler.runAfter"),o(Date.now()+n,r,s,t)),c=async n=>d(e,"/cancel",{id:n}),u=async n=>(await v(async s=>f(e,s===void 0?n:`${n}?cursor=${encodeURIComponent(s)}`))).map(s=>h(s));return{cancel:c,dead:async()=>u("/dead"),deadRetry:async n=>{const{retried:r}=await d(e,"/dead/retry",{id:n});return r===!0},get:async n=>{const r=await f(e,`/get?id=${encodeURIComponent(n)}`);return r.record===void 0?null:h(r.record)},list:async()=>u("/list"),runAfter:a,runAt:o}};export{K as default};
@@ -1 +0,0 @@
1
- import{LunoraError as s}from"@lunora/errors";import{e as l}from"./wire-codec-TIVAE0Ds.mjs";import{a as o,g as m,c as u}from"./do-client-XQayNStI.mjs";import y from"./assertScheduleDelay-BgA4K1WB.mjs";const N=e=>{if(o(e),!Number.isInteger(e.maxConcurrency)||e.maxConcurrency<=0)throw new s("INTERNAL","@lunora/scheduler: `maxConcurrency` must be a positive integer");const a=typeof e.name=="string"&&e.name.length>0?e.name:"default";return{cancel:async r=>u(e,"/cancel",{id:r}),enqueue:async(r,t,n={})=>{const c=n.delayMs??0;return y(c,"workpool.enqueue"),u(e,"/schedule",{args:l("workpool.enqueue",r.__lunoraRef,t),functionPath:r.__lunoraRef,instanceName:e.instanceName??"default",maxConcurrency:e.maxConcurrency,pool:a,retry:n.retry,scheduledFor:Date.now()+c,shardKey:n.shardKey})},name:a,status:async()=>m(e,`/pool?name=${encodeURIComponent(a)}`)}};export{N as default};