@lunora/scheduler 1.0.0-alpha.169 → 1.0.0-alpha.170
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 +201 -104
- package/README.md +3 -3
- package/dist/index.d.mts +8 -6
- package/dist/index.d.ts +8 -6
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/MAX_RETRY_ATTEMPTS-Ds3leY0P.mjs +2 -0
- package/dist/packem_shared/{assertScheduleDelay-DjHvFHi8.mjs → assertScheduleDelay-D9Na2wPU.mjs} +1 -1
- package/dist/packem_shared/{assertScheduleInstant-B9o9aZYo.mjs → assertScheduleInstant-KIOgxgOT.mjs} +1 -1
- package/dist/packem_shared/{createScheduler-Bb4jsZgk.mjs → createScheduler-BUMMD_lz.mjs} +1 -1
- package/dist/packem_shared/{createSchedulerHost-Bdr87Prl.mjs → createSchedulerHost-e5kSr3H-.mjs} +1 -1
- package/dist/packem_shared/{createWorkpool-DOK6tfVx.mjs → createWorkpool-BEdQoG83.mjs} +1 -1
- package/package.json +2 -2
- package/dist/packem_shared/MAX_RETRY_ATTEMPTS-BlAZz_Qd.mjs +0 -1
package/LICENSE.md
CHANGED
|
@@ -1,108 +1,205 @@
|
|
|
1
|
-
# Functional Source License, Version 1.1, Apache 2.0 Future License
|
|
2
1
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
106
203
|
|
|
107
204
|
<!-- DEPENDENCIES -->
|
|
108
205
|
<!-- /DEPENDENCIES -->
|
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
<div align="center">
|
|
16
16
|
|
|
17
17
|
[![typescript-image][typescript-badge]][typescript-url]
|
|
18
|
-
[![
|
|
18
|
+
[![Apache-2.0 licence][license-badge]][license]
|
|
19
19
|
[![npm version][npm-version-badge]][npm-version]
|
|
20
20
|
[![npm downloads][npm-downloads-badge]][npm-downloads]
|
|
21
21
|
[![PRs Welcome][prs-welcome-badge]][prs-welcome]
|
|
@@ -134,11 +134,11 @@ This is an open source project and will always remain free to use. If you think
|
|
|
134
134
|
|
|
135
135
|
## License
|
|
136
136
|
|
|
137
|
-
The Lunora scheduler package is open-sourced software licensed under the [
|
|
137
|
+
The Lunora scheduler package is open-sourced software licensed under the [Apache-2.0][license].
|
|
138
138
|
|
|
139
139
|
<!-- badges -->
|
|
140
140
|
|
|
141
|
-
[license-badge]: https://img.shields.io/badge/license-
|
|
141
|
+
[license-badge]: https://img.shields.io/badge/license-Apache--2.0-blue.svg?style=for-the-badge
|
|
142
142
|
[license]: https://github.com/anolilab/lunora/blob/alpha/LICENSE.md
|
|
143
143
|
[npm-version-badge]: https://img.shields.io/npm/v/@lunora/scheduler?style=for-the-badge
|
|
144
144
|
[npm-version]: https://www.npmjs.com/package/@lunora/scheduler
|
package/dist/index.d.mts
CHANGED
|
@@ -888,8 +888,10 @@ interface SchedulerEnv {
|
|
|
888
888
|
*/
|
|
889
889
|
LUNORA_ORIGIN_URL?: string;
|
|
890
890
|
/**
|
|
891
|
-
* Shared secret used to HMAC-sign
|
|
892
|
-
*
|
|
891
|
+
* Shared secret used to HMAC-sign each dispatch so the runtime receiver can
|
|
892
|
+
* authenticate the call (header `x-lunora-scheduler-signature`). The signature
|
|
893
|
+
* covers the body, the send time (`x-lunora-scheduler-timestamp`) and the
|
|
894
|
+
* forwarded identity headers, via the shared `schedulerDispatchCanonical`. Without
|
|
893
895
|
* it the dispatch is sent unsigned (optionally bearer-authenticated via
|
|
894
896
|
* {@link SchedulerEnv.LUNORA_ADMIN_TOKEN}).
|
|
895
897
|
*/
|
|
@@ -1285,10 +1287,10 @@ declare class SchedulerDO {
|
|
|
1285
1287
|
*/
|
|
1286
1288
|
private forEachPage;
|
|
1287
1289
|
/**
|
|
1288
|
-
* HMAC-SHA-256 sign
|
|
1289
|
-
*
|
|
1290
|
-
*
|
|
1291
|
-
*
|
|
1290
|
+
* HMAC-SHA-256 sign a dispatch with `env.LUNORA_SCHEDULER_SECRET`, returning a
|
|
1291
|
+
* base64url signature, or `undefined` when no secret is configured. The signed
|
|
1292
|
+
* string is the shared `schedulerDispatchCanonical`, which the receiver rebuilds
|
|
1293
|
+
* from the body, the timestamp and the forwarded identity headers.
|
|
1292
1294
|
*/
|
|
1293
1295
|
private signDispatch;
|
|
1294
1296
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -888,8 +888,10 @@ interface SchedulerEnv {
|
|
|
888
888
|
*/
|
|
889
889
|
LUNORA_ORIGIN_URL?: string;
|
|
890
890
|
/**
|
|
891
|
-
* Shared secret used to HMAC-sign
|
|
892
|
-
*
|
|
891
|
+
* Shared secret used to HMAC-sign each dispatch so the runtime receiver can
|
|
892
|
+
* authenticate the call (header `x-lunora-scheduler-signature`). The signature
|
|
893
|
+
* covers the body, the send time (`x-lunora-scheduler-timestamp`) and the
|
|
894
|
+
* forwarded identity headers, via the shared `schedulerDispatchCanonical`. Without
|
|
893
895
|
* it the dispatch is sent unsigned (optionally bearer-authenticated via
|
|
894
896
|
* {@link SchedulerEnv.LUNORA_ADMIN_TOKEN}).
|
|
895
897
|
*/
|
|
@@ -1285,10 +1287,10 @@ declare class SchedulerDO {
|
|
|
1285
1287
|
*/
|
|
1286
1288
|
private forEachPage;
|
|
1287
1289
|
/**
|
|
1288
|
-
* HMAC-SHA-256 sign
|
|
1289
|
-
*
|
|
1290
|
-
*
|
|
1291
|
-
*
|
|
1290
|
+
* HMAC-SHA-256 sign a dispatch with `env.LUNORA_SCHEDULER_SECRET`, returning a
|
|
1291
|
+
* base64url signature, or `undefined` when no secret is configured. The signed
|
|
1292
|
+
* string is the shared `schedulerDispatchCanonical`, which the receiver rebuilds
|
|
1293
|
+
* from the body, the timestamp and the forwarded identity headers.
|
|
1292
1294
|
*/
|
|
1293
1295
|
private signDispatch;
|
|
1294
1296
|
/**
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{default as o}from"./packem_shared/createScheduler-
|
|
1
|
+
import{default as o}from"./packem_shared/createScheduler-BUMMD_lz.mjs";import{default as a}from"./packem_shared/createWorkpool-BEdQoG83.mjs";import{createCronTrigger as f}from"./packem_shared/createCronTrigger-cg32QNgj.mjs";import{CRON_SCHEDULE_KINDS as p,compileCronSchedule as c,cronJobs as d}from"./packem_shared/CRON_SCHEDULE_KINDS-AS5GtmnL.mjs";import{createQueueConsumer as m,createQueueWorkpool as n,httpDispatcher as x}from"./packem_shared/createQueueConsumer-CYwmsmvq.mjs";import{r as E}from"./packem_shared/resolve-schedule-id-B2ghxgFm.mjs";import{MAX_RETRY_ATTEMPTS as h,RETRY_BASE_DELAY_MS as T,SchedulerDO as _,TERMINAL_RETENTION_MS as R}from"./packem_shared/MAX_RETRY_ATTEMPTS-Ds3leY0P.mjs";import{createSchedulerHost as D}from"./packem_shared/createSchedulerHost-e5kSr3H-.mjs";import{isWorkflowReference as A}from"./packem_shared/isWorkflowReference-CT3tdefh.mjs";import{assertValidCronExpression as N,isValidCronExpression as L,warnIfSecondsLeading as g}from"./packem_shared/assertValidCronExpression-fiNfNiWf.mjs";import{default as O}from"./packem_shared/assertScheduleDelay-D9Na2wPU.mjs";import{default as Y}from"./packem_shared/assertScheduleInstant-KIOgxgOT.mjs";export{p as CRON_SCHEDULE_KINDS,h as MAX_RETRY_ATTEMPTS,T as RETRY_BASE_DELAY_MS,_ as SchedulerDO,R as TERMINAL_RETENTION_MS,O as assertScheduleDelay,Y as assertScheduleInstant,N as assertValidCronExpression,c as compileCronSchedule,f as createCronTrigger,m as createQueueConsumer,n as createQueueWorkpool,o as createScheduler,D as createSchedulerHost,a as createWorkpool,d as cronJobs,x as httpDispatcher,L as isValidCronExpression,A as isWorkflowReference,E as resolveScheduleId,g as warnIfSecondsLeading};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as z,r as C}from"./resolve-schedule-id-B2ghxgFm.mjs";const B="DISPATCH_IN_PROGRESS",Q="x-lunora-dispatch-declined",K=(d,t=200,e)=>{const s=new Headers({"content-type":"application/json"});for(const[a,n]of Object.entries({}))s.set(a,n);return Response.json(d,{headers:s,status:t})},D=(d,t)=>{if(d.size<t)return;const e=d.keys().next().value;e!==void 0&&d.delete(e)},J=(d,t,e,s)=>{const a=d.get(t);if(a!==void 0)return a;D(d,s);const n=e().catch(r=>{throw d.get(t)===n&&d.delete(t),r});return d.set(t,n),n},Z=new TextEncoder,O=64,tt=new Map,et=async d=>J(tt,d,async()=>crypto.subtle.importKey("raw",Z.encode(d),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),O),st=new TextEncoder,at=Array.from({length:32},(d,t)=>t);new RegExp(`[${at.map(d=>String.fromCodePoint(d)).join("")}]`,"u");const it=async(d,t)=>{const e=await et(d),s=await crypto.subtle.sign("HMAC",e,st.encode(t));return z(new Uint8Array(s))},nt="x-lunora-scheduler-signature",rt="x-lunora-scheduler-timestamp",ot=d=>["v1",String(d.timestamp),d.userId??"",d.identity??"",d.body].join(`
|
|
2
|
+
`),ct=(d,t)=>it(d,ot(t)),dt="lunora-ping",lt="lunora-pong",u="id:",I="retry:",f="dead:",R="pool:",P="pq:",p="done:",L="dt:",A="repair:",S="inst:",$="cl:",E="cr:",F=50,y=128,_=d=>typeof d=="string"&&d.length>0?d:void 0,m=d=>Array.from({length:d.length},(t,e)=>d.charCodeAt(e).toString(16).padStart(4,"0")).join(""),ht=d=>{let t="";for(let e=0;e<d.length;e+=4)t+=String.fromCharCode(Number.parseInt(d.slice(e,e+4),16));return t},G=d=>`${P}${m(d)}:`,N="meta:clean",k="meta:paused",v=100,ut=10,gt=5,H=3e4,W=1e3,X=18e5,ft=1e3,wt=6,V=9e5,q=6048e5,Y=64,pt=4,j=999999999999999,mt=15,T=d=>String(d).padStart(mt,"0"),M=d=>Number.isInteger(d)&&d>0&&d<=j;class i{static indexKey(t,e){return`t:${T(t)}:${e}`}static terminalIndexKey(t,e){return`${L}${T(j-t)}:${e}`}static cronRunKey(t){return`${E}${m(t.name)}:${T(j-t.endedAt)}:${t.runId}`}static leaseIsLive(t,e){return(t.renewedAt??t.startedAt)>e-V}static cronName(t){const e=t?.name;return typeof e=="string"&&e.length>0&&e.length<=256?e:void 0}static poolQueueKey(t){return t.pool===void 0?void 0:`${G(t.pool)}${t.id}`}static pendingRows(t){const e=i.poolQueueKey(t);return{[`${u}${t.id}`]:t,...e===void 0?{}:{[e]:t.id}}}static pendingKeys(t){return Object.keys(i.pendingRows(t))}static json(t,e=200){return K(t,e)}static error(t,e,s){return i.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:gt,a=typeof e?.baseMs=="number"&&Number.isFinite(e.baseMs)&&e.baseMs>=0?e.baseMs:H,n=e?.backoff==="linear"?"linear":"exponential",r=typeof e?.maxMs=="number"&&Number.isFinite(e.maxMs)&&e.maxMs>=0?e.maxMs:void 0,c=e?.forever===!0;return c?{backoff:n,baseMs:Math.max(W,a),forever:c,maxAttempts:s,maxMs:Math.min(X,Math.max(W,r??X))}:{backoff:n,baseMs:a,forever:c,maxAttempts:s,maxMs:r}}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),e.forever===!0&&(s.forever=!0),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;recovery;recovered=!1;dirty=!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 /cron/runs":return this.handleCronRuns();case"GET /dead":return this.handleDeadList(e);case"GET /get":return this.handleGet(e);case"GET /history":return this.handleHistory(e);case"GET /instances":return this.handleListInstances();case"GET /list":return this.handleList(e);case"GET /pause":return i.json(await this.pauseState());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 /cron/begin":return this.handleCronBegin(t);case"POST /cron/end":return this.handleCronEnd(t);case"POST /cron/renew":return this.handleCronRenew(t);case"POST /dead/cancel":return this.handleDeadCancel(t);case"POST /dead/retry":return this.handleDeadRetry(t);case"POST /instances/register":return this.handleRegisterInstance(t);case"POST /pause":return this.handleSetPause(t);case"POST /schedule":return this.handleSchedule(t)}return K({error:{code:"NOT_FOUND"}},404)}async alarm(){if(await this.reindexOrphanedRecords(),(await this.pauseState()).paused){await this.state.storage.deleteAlarm();return}const e=Date.now(),s=[],a=new Set,n=await this.state.storage.list({end:`t:${T(e)}:~`,limit:100,prefix:"t:"}),r=[];for(const[l,h]of n.entries()){const w=Number.parseInt(l.slice(2,l.indexOf(":",2)),10);Number.isFinite(w)&&w<=e&&r.push({indexKey:l,recordId:h})}const c=await Promise.all(r.map(l=>this.state.storage.get(`${u}${l.recordId}`)));for(const[l,{indexKey:h,recordId:w}]of r.entries()){const g=c[l];g&&a.has(w)?await this.state.storage.delete(h):g?(a.add(w),s.push({claimKey:h,record:g})):await this.state.storage.delete(h)}let o=!1;try{s.length>0&&(await this.state.storage.delete(N),o=!0),await this.drainDue(s)}finally{await this.rescheduleAlarm(),o&&this.recovered&&!this.dirty&&await this.state.storage.put(N,!0)}await this.sweepTerminal().catch(()=>{}),s.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.firstDueAt??t.scheduledFor,shardKey:t.shardKey,workflow:t.workflow});try{const a={"content-type":"application/json"},n=Date.now(),r=await this.signDispatch(s,n);r!==void 0?(a[nt]=r,a[rt]=String(n)):typeof this.env.LUNORA_ADMIN_TOKEN=="string"&&this.env.LUNORA_ADMIN_TOKEN.length>0&&(a.authorization=`Bearer ${this.env.LUNORA_ADMIN_TOKEN}`);const c=await fetch(`${e}/_lunora/scheduler/dispatch`,{body:s,headers:a,method:"POST"});return c.status===409&&c.headers.get(Q)==="1"&&await c.json().then(l=>l?.error?.code===B,()=>!1)?"in-progress":c.ok}catch{return!1}}armWebSocketKeepalive(){const t=this.state.setWebSocketAutoResponse;typeof t!="function"||typeof WebSocketRequestResponsePair>"u"||t.call(this.state,new WebSocketRequestResponsePair(dt,lt))}async drainDue(t){const e=[...t],s=[],a=Math.min(wt,e.length);for(let n=0;n<a;n+=1)s.push((async()=>{for(let r=e.shift();r!==void 0;r=e.shift())await this.drainRecordGuarded(r.record,r.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=i.indexKey(Date.now()+V,t.id);try{const a=await this.state.storage.get(`${u}${t.id}`);if(a===void 0){await this.state.storage.delete(e);return}if(JSON.stringify(a)!==JSON.stringify(t)||await this.isPaused())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(`${f}${t.id}`)!==void 0){await this.state.storage.delete(s),await this.state.storage.delete([`${I}${t.id}`,...i.pendingKeys(t)]);return}await this.state.storage.put(e,t.id),await this.state.storage.delete(s)}catch{this.dirty=!0}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,n=t.pool;if(!a&&n!==void 0&&await this.withPoolLock(async()=>{const r=await this.loadPool(n);await this.savePool(n,i.releaseSlot(r,t.id))}),this.cancelledLeases.has(t.id))return a&&await this.correctCanceledToSucceeded(t).catch(()=>{}),a;if(a){const r=Date.now();try{await this.writeTerminal(t,"succeeded",r)}catch{this.dirty=!0,await this.state.storage.put(`${A}${t.id}`,{...t,completedAt:r,state:"succeeded"}).catch(()=>{})}try{await this.state.storage.delete([...i.pendingKeys(t),`${I}${t.id}`])}catch{this.dirty=!0}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 n=a.inFlightIds??[];return n.includes(t.id)||n.push(t.id),a.inFlightIds=n,a.inFlight=n.length,await this.savePool(e,a),!0});return s||await this.requeuePooled(t),s}async handleWebSocketUpgrade(){if(this.state.acceptWebSocket===void 0)return i.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(u,v);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(u,v),a=JSON.stringify({records:e,truncated:s,type:"jobs"});for(const n of t)try{n.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}}),n=[...a.keys()],r=[...a.values()],c=r.length>e;return c?{cursor:n[e-1],records:r.slice(0,e),truncated:c}:{records:r,truncated:c}}async forEachPage(t,e,s=v){let a;for(;;){const n=await this.state.storage.list(a===void 0?{limit:s,prefix:t}:{limit:s,prefix:t,startAfter:a});if(n.size===0)break;for(const[c,o]of n.entries())e(o,c);if(a=[...n.keys()].at(-1),n.size<s)break}}async signDispatch(t,e){const s=typeof this.env.LUNORA_SCHEDULER_SECRET=="string"?this.env.LUNORA_SCHEDULER_SECRET:void 0;if(!(!s||s.length===0))return ct(s,{body:t,timestamp:e})}async recordRetry(t,e=!1){if(this.cancelledLeases.has(t.id))return;const{backoff:s,baseMs:a,forever:n,maxAttempts:r,maxMs:c}=i.resolveRetry(t),o=t.attempts??0,l=Math.min(Number.MAX_SAFE_INTEGER,o+(e?0:1)),h=Math.min(Number.MAX_SAFE_INTEGER,o+1),w=s==="linear"?a*h:a*2**(h-1),g=c===void 0?w:Math.min(w,c),x=e?Math.max(g,H):g,b=Math.round(Date.now()+x);if(!n&&l>r){await this.parkDead(t,l,`after ${String(l)} attempts`);return}if(n&&!e&&l===r+1&&console.warn(`@lunora/scheduler: job "${t.id}" (${t.functionPath??t.workflow??"unknown"}) has failed ${String(l)} attempts and keeps retrying (retry.forever)`),!M(b)){await this.parkDead(t,l,`at attempt ${String(l)}: the retry backoff exceeded the largest schedulable time`);return}const U={...t,attempts:l,firstDueAt:void 0,scheduledFor:b};await this.state.storage.put({...i.pendingRows(U),[`${I}${t.id}`]:U,[i.indexKey(b,t.id)]:t.id})}async parkDead(t,e,s){const a=Date.now();await this.state.storage.put({[`${f}${t.id}`]:{...t,attempts:e,completedAt:a,error:`dead-lettered ${s}`},[i.terminalIndexKey(a,t.id)]:t.id}),await this.state.storage.delete([`${I}${t.id}`,...i.pendingKeys(t)]),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(`${R}${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:i.normalizeConcurrency(e,1)}}async savePool(t,e){await this.state.storage.put(`${R}${t}`,e)}async requeuePooled(t){if(this.cancelledLeases.has(t.id))return;const e=Date.now()+ft,s={...t,firstDueAt:t.firstDueAt??t.scheduledFor,scheduledFor:e};await this.state.storage.put({...i.pendingRows(s),[i.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 i.error(400,"INVALID_INPUT","pool is required");const n=await this.withPoolLock(async()=>{const r=await this.loadPool(s),c=a===void 0?i.releaseFirstSlot(r):i.releaseSlot(r,a);return await this.savePool(s,c),c});return await this.armAlarmIfEarlier(Date.now()),i.json({inFlight:n.inFlight})}async handlePoolStatus(t){const e=t.searchParams.get("name");if(e===null||e.length===0)return i.error(400,"INVALID_INPUT","name is required");const s=await this.loadPool(e);let a=0;return await this.forEachPage(G(e),()=>{a+=1}),i.json({inFlight:s.inFlight,maxConcurrency:s.maxConcurrency,queued:a})}async handleStatus(){const t=new Map;await this.forEachPage(P,(r,c)=>{const o=ht(c.slice(P.length,c.indexOf(":",P.length)));t.set(o,(t.get(o)??0)+1)});const e=[];let s=0,a=0;await this.forEachPage(R,(r,c)=>{const o=c.slice(R.length),l=Math.max(0,r.inFlight),h=t.get(o)??0;e.push({inFlight:l,maxConcurrency:r.maxConcurrency,name:o,queued:h}),s+=h,a+=l});const n={backlog:s,inFlight:a,pools:e};return i.json(n)}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:i.normalizeConcurrency(e,s.maxConcurrency)})}async idConflict(t){if(await this.state.storage.get(`${u}${t}`)!==void 0)return i.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(`${f}${t}`)!==void 0)return i.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=C(t)}catch(s){return i.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=i.resolveScheduleTarget(e);if(!e||s===void 0)return i.error(400,"INVALID_INPUT","functionPath or workflow is required");const{functionPath:a,workflow:n}=s;if(typeof e.scheduledFor!="number"||!M(e.scheduledFor))return i.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 i.error(500,"ORIGIN_NOT_CONFIGURED","LUNORA_ORIGIN_URL env binding must be set on the SchedulerDO");const r=_(e.pool),c=_(e.instanceName),o=i.normalizeRetry(e.retry),l=await this.resolveId(e.id);if(l instanceof Response)return l;const h=l;r!==void 0&&await this.persistPoolCap(r,e.maxConcurrency);const w=e.id===void 0?void 0:this.state.storage.delete([`${p}${h}`,`${A}${h}`]),g={args:e.args??{},enqueuedAt:Date.now(),id:h,...a===void 0?{}:{functionPath:a},...c===void 0?{}:{instanceName:c},...r===void 0?{}:{pool:r},...o===void 0?{}:{retry:o},scheduledFor:e.scheduledFor,shardKey:e.shardKey,...n===void 0?{}:{workflow:n}},x=this.state.storage.put({...i.pendingRows(g),[i.indexKey(g.scheduledFor,h)]:h});return await Promise.all([w,x]),await this.armAlarmIfEarlier(g.scheduledFor),await this.broadcastChange(),i.json({id:h,scheduledFor:g.scheduledFor})}async handleCancel(t){const e=await t.json().catch(()=>{});if(!e?.id)return i.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`${u}${e.id}`);return s?await this.state.storage.get(`${p}${e.id}`)!==void 0?(await this.removeRecord(s),await this.rescheduleAlarm(),i.json({cancelled:!1})):(await this.removeRecord(s),await this.writeTerminal(s,"canceled").catch(()=>{}),await this.sweepTerminal().catch(()=>{}),await this.rescheduleAlarm(),await this.broadcastChange(),i.json({cancelled:!0})):i.json({cancelled:!1})}async handleList(t){const{cursor:e,records:s,truncated:a}=await this.listPage(u,v,t.searchParams.get("cursor")??void 0);return i.json({cursor:e,records:s,truncated:a})}async handleDeadList(t){const{cursor:e,records:s,truncated:a}=await this.listPage(f,v,t.searchParams.get("cursor")??void 0);return i.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 i.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`${f}${e.id}`);if(s===void 0)return i.json({retried:!1});const a=Date.now(),n={...s,attempts:0,firstDueAt:void 0,scheduledFor:a};delete n.error,delete n.completedAt,await this.state.storage.delete(`${p}${s.id}`);const r=this.state.storage.put({...i.pendingRows(n),[i.indexKey(a,s.id)]:s.id}),c=this.state.storage.delete(s.completedAt===void 0?[`${f}${s.id}`]:[`${f}${s.id}`,i.terminalIndexKey(s.completedAt,s.id)]);return await Promise.all([r,c]),await this.armAlarmIfEarlier(a),await this.broadcastChange(),i.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 i.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`${f}${e.id}`);return s===void 0?i.json({removed:!1}):(await this.writeTerminal(s,"failed",s.completedAt),await this.state.storage.delete(`${f}${e.id}`),await this.sweepTerminal().catch(()=>{}),i.json({removed:!0}))}async handleGet(t){const e=t.searchParams.get("id");if(e===null||e.length===0)return i.error(400,"INVALID_INPUT","id is required");const s=await this.readTerminal(e);if(s!==void 0)return i.json({record:s});const a=await this.state.storage.get(`${u}${e}`);if(a!==void 0){const r={...a,state:this.activeLeases.has(e)?"running":"pending"};return i.json({record:r})}const n=await this.state.storage.get(`${f}${e}`);return i.json(n===void 0?{}:{record:{...n,state:"failed"}})}async handleHistory(t){let e=t.searchParams.get("cursor")??void 0;const s=[];for(let a=0;a<ut;a+=1){const r=[...(await this.state.storage.list({limit:v+1,prefix:L,...e===void 0?{}:{startAfter:e}})).entries()],c=r.slice(0,v),o=await Promise.all(c.map(async([l,h])=>this.readTerminal(h,l)));if(s.push(...o.filter(l=>l!==void 0)),e=c.at(-1)?.[0],r.length<=v)return i.json({records:s,truncated:!1});if(s.length>0)break}return i.json({cursor:e,records:s,truncated:!0})}async readTerminal(t,e){const s=await this.state.storage.get(`${p}${t}`)??await this.readParked(t);if(!(s===void 0||s.completedAt<=Date.now()-q)&&!(e!==void 0&&i.terminalIndexKey(s.completedAt,t)!==e))return s}async readParked(t){const e=await this.state.storage.get(`${f}${t}`);return e?.completedAt===void 0?void 0:{...e,completedAt:e.completedAt,state:"failed"}}async correctCanceledToSucceeded(t){const e=await this.state.storage.get(`${p}${t.id}`);e?.state!=="canceled"||await this.state.storage.get(`${u}${t.id}`)!==void 0||JSON.stringify(e)===JSON.stringify({...t,completedAt:e.completedAt,state:e.state})&&await Promise.all([this.state.storage.delete(i.terminalIndexKey(e.completedAt,t.id)),this.writeTerminal(t,"succeeded")])}async writeTerminal(t,e,s=Date.now()){const a={...t,completedAt:s,state:e};await this.state.storage.put({[`${p}${t.id}`]:a,[i.terminalIndexKey(s,t.id)]:t.id})}async sweepTerminal(){for(let t=0;t<pt;t+=1)if(await this.sweepTerminalBatch()<Y)return}async sweepTerminalBatch(){const t=i.terminalIndexKey(Date.now()-q+1,"~"),e=await this.state.storage.list({limit:Y,prefix:L,startAfter:t});if(e.size===0)return 0;const s=await Promise.all([...e.entries()].map(async([a,n])=>{const r=await this.state.storage.get(`${p}${n}`);return r!==void 0&&i.terminalIndexKey(r.completedAt,n)===a?[a,`${p}${n}`]:[a]}));return await this.state.storage.delete(s.flat()),e.size}async pauseState(){return await this.state.storage.get(k)??{paused:!1}}async isPaused(){return(await this.pauseState()).paused}async handleRegisterInstance(t){const e=i.cronName(await t.json().catch(()=>{}));return e===void 0?i.error(400,"INVALID_INPUT","name is required"):(await this.state.storage.put(`${S}${m(e)}`,e),i.json(await this.pauseState()))}async handleListInstances(){const t=[];return await this.forEachPage(S,e=>{t.push(e)}),i.json({instances:t})}async handleSetPause(t){const e=await t.json().catch(()=>{});if(typeof e?.paused!="boolean")return i.error(400,"INVALID_INPUT","paused (boolean) is required");if(!e.paused){const n=await this.earliestPendingTime();return n!==void 0&&Number.isFinite(n)&&await this.state.storage.setAlarm(n),await this.state.storage.delete(k),i.json({paused:!1})}const a={paused:!0,pausedAt:(await this.pauseState()).pausedAt??Date.now(),...typeof e.reason=="string"&&e.reason.length>0?{reason:e.reason.slice(0,500)}:{}};return await this.state.storage.put(k,a),await this.state.storage.deleteAlarm(),i.json(a)}async handleCronBegin(t){const e=i.cronName(await t.json().catch(()=>{}));if(e===void 0)return i.error(400,"INVALID_INPUT","name is required");const s=`${$}${m(e)}`,a=Date.now();if((await this.pauseState()).paused)return await this.recordCronSkip(e,"paused",a).catch(()=>{}),i.json({acquired:!1,reason:"paused"});const r=await this.state.storage.get(s);if(r!==void 0&&i.leaseIsLive(r,a))return await this.state.storage.put(s,{...r,skipped:r.skipped+1}).catch(()=>{}),await this.recordCronSkip(e,"in-flight",a).catch(()=>{}),i.json({acquired:!1,reason:"in-flight",runningSince:r.startedAt});r!==void 0&&await this.recordLostCronRun(r,a);const c=C(void 0);return await this.state.storage.put(s,{name:e,runId:c,skipped:0,startedAt:a}),i.json({acquired:!0,runId:c})}async handleCronRenew(t){const e=await t.json().catch(()=>{}),s=i.cronName(e);if(s===void 0||typeof e?.runId!="string")return i.error(400,"INVALID_INPUT","name and runId are required");const a=`${$}${m(s)}`,n=await this.state.storage.get(a),r=Date.now();return n?.runId!==e.runId||!i.leaseIsLive(n,r)?i.json({renewed:!1}):(await this.state.storage.put(a,{...n,renewedAt:r}),i.json({renewed:!0}))}async handleCronEnd(t){const e=await t.json().catch(()=>{}),s=i.cronName(e);if(s===void 0||typeof e?.runId!="string"||e.status!=="succeeded"&&e.status!=="failed")return i.error(400,"INVALID_INPUT","name, runId and status (succeeded | failed) are required");const a=`${$}${m(s)}`,n=await this.state.storage.get(a);if(n?.runId!==e.runId)return i.json({recorded:!1});const r=Date.now();return await this.recordCronRun({durationMs:r-n.startedAt,endedAt:r,...e.status==="failed"&&typeof e.error=="string"?{error:e.error.slice(0,2e3)}:{},name:s,runId:n.runId,skipped:n.skipped,startedAt:n.startedAt,status:e.status}),await this.state.storage.delete(a),i.json({recorded:!0})}async handleCronRuns(){const t=[],e=[],s=[],a=Date.now();await this.forEachPage($,(n,r)=>{i.leaseIsLive(n,a)?t.push(n):e.push([r,n])});for(const[n,r]of e)await this.recordLostCronRun(r,a),await this.state.storage.delete(n);return await this.forEachPage(E,n=>{s.push(n)}),i.json({inFlight:t,runs:s})}async recordLostCronRun(t,e){[...(await this.state.storage.list({limit:F+y,prefix:`${E}${m(t.name)}:`})).keys()].some(a=>a.endsWith(`:${t.runId}`))||await this.recordCronRun({durationMs:e-t.startedAt,endedAt:e,error:"the run never reported completion; its lease expired",name:t.name,runId:t.runId,skipped:t.skipped,startedAt:t.startedAt,status:"failed"})}async recordCronSkip(t,e,s){const a=`${E}${m(t)}:`,n=await this.state.storage.list({limit:1,prefix:a}),[r]=n.entries();if(r?.[1].status==="skipped"&&r[1].reason===e){const[c,o]=r,l={...o,endedAt:s,skipped:o.skipped+1};await this.recordCronRun(l,i.cronRunKey(l)===c?void 0:c);return}await this.recordCronRun({durationMs:0,endedAt:s,name:t,reason:e,runId:C(void 0),skipped:1,startedAt:s,status:"skipped"})}async recordCronRun(t,e){const s=`${E}${m(t.name)}:`,a=this.state.storage.put(i.cronRunKey(t),t);await Promise.all([a,e===void 0?void 0:this.state.storage.delete(e)]);const r=[...(await this.state.storage.list({limit:F+y+1,prefix:s})).keys()].filter(c=>c!==e).slice(F);for(let c=0;c<r.length;c+=y)await this.state.storage.delete(r.slice(c,c+y))}async removeRecord(t){const e=[...i.pendingKeys(t),i.indexKey(t.scheduledFor,t.id),`${I}${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.recovery!==void 0)return this.recovery;const t=this.recoverStore();return this.recovery=t,t.catch(()=>{this.recovery=void 0}),t}async recoverStore(){if(await this.state.storage.get(N)===void 0&&(await this.reindexWalk(),await this.state.storage.put(N,!0)),await this.state.storage.getAlarm()===null){const t=await this.earliestPendingTime();t!==void 0&&Number.isFinite(t)&&await this.state.storage.setAlarm(t)}this.recovered=!0}async restoreOutcome(t){const e=await this.state.storage.get(`${u}${t.id}`);if(e!==void 0&&e.enqueuedAt!==t.enqueuedAt){await this.state.storage.delete(`${A}${t.id}`);return}await this.state.storage.get(`${p}${t.id}`)===void 0&&await this.writeTerminal(t,"succeeded",t.completedAt),await this.state.storage.delete([`${A}${t.id}`,...i.pendingKeys(t),`${I}${t.id}`])}async reindexWalk(){const t=new Set,e=new Set;await this.forEachPage("t:",o=>{t.add(o)}),await this.forEachPage(P,(o,l)=>{e.add(l)});const s=new Map;await this.forEachPage(A,o=>{s.set(o.id,o)});const a=new Set,n=[],r=[];await this.forEachPage(u,o=>{!t.has(o.id)&&M(o.scheduledFor)&&n.push(o);const l=i.poolQueueKey(o);l!==void 0&&(a.add(l),e.has(l)||r.push([l,o.id]))});const c=[...e].filter(o=>!a.has(o));for(let o=0;o<c.length;o+=y)await this.state.storage.delete(c.slice(o,o+y));for(let o=0;o<r.length;o+=y)await this.state.storage.put(Object.fromEntries(r.slice(o,o+y)));for(const o of s.values())await this.restoreOutcome(o);for(const o of n)await this.state.storage.put(i.indexKey(o.scheduledFor,o.id),o.id),await this.armAlarmIfEarlier(o.scheduledFor)}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(){if(await this.isPaused()){await this.state.storage.deleteAlarm();return}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{V as DISPATCH_LEASE_MS,wt as MAX_CONCURRENT_DISPATCHES,gt as MAX_RETRY_ATTEMPTS,j as MAX_SCHEDULED_FOR_MS,H as RETRY_BASE_DELAY_MS,i as SchedulerDO,q as TERMINAL_RETENTION_MS};
|
package/dist/packem_shared/{assertScheduleDelay-DjHvFHi8.mjs → assertScheduleDelay-D9Na2wPU.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as r}from"@lunora/errors";import{MAX_SCHEDULED_FOR_MS as i}from"./MAX_RETRY_ATTEMPTS-
|
|
1
|
+
import{LunoraError as r}from"@lunora/errors";import{MAX_SCHEDULED_FOR_MS as i}from"./MAX_RETRY_ATTEMPTS-Ds3leY0P.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};
|
package/dist/packem_shared/{assertScheduleInstant-B9o9aZYo.mjs → assertScheduleInstant-KIOgxgOT.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import r from"./assertScheduleDelay-
|
|
1
|
+
import r from"./assertScheduleDelay-D9Na2wPU.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
|
-
import{LunoraError as w}from"@lunora/errors";import{encodeArgsOrThrow as g,decodeWire as A}from"@lunora/wire";import{a as p,c as d,g as f}from"./do-client-DnJqrsmj.mjs";import{isWorkflowReference as h}from"./isWorkflowReference-CT3tdefh.mjs";import N from"./assertScheduleDelay-
|
|
1
|
+
import{LunoraError as w}from"@lunora/errors";import{encodeArgsOrThrow as g,decodeWire as A}from"@lunora/wire";import{a as p,c as d,g as f}from"./do-client-DnJqrsmj.mjs";import{isWorkflowReference as h}from"./isWorkflowReference-CT3tdefh.mjs";import N from"./assertScheduleDelay-D9Na2wPU.mjs";import R from"./assertScheduleInstant-KIOgxgOT.mjs";const v=async e=>{const a=[];let o;for(;;){const c=await e(o);if(a.push(...Array.isArray(c.records)?c.records:[]),c.truncated!==!0||typeof c.cursor!="string"||c.cursor.length===0)return a;if(c.cursor===o)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");o=c.cursor}},x=e=>typeof e=="string"?e:(h(e)?e.className:e.__lunoraRef)??"<unknown>",m=e=>({...e,args:A(e.args)}),K=e=>{p(e);const a=async(s,r,n,t={})=>{const u=Math.ceil(s instanceof Date?s.getTime():s);R(u,Date.now(),"ctx.scheduler.runAt");const i={args:g("ctx.scheduler.runAt",x(r),n),id:t.id,instanceName:e.instanceName??"default",maxConcurrency:t.pool===void 0?void 0:t.maxConcurrency,pool:t.pool,retry:t.retry,scheduledFor:u,shardKey:t.shardKey};if(h(r)){if(typeof r.className!="string"||r.className.length===0)throw new w("INTERNAL","@lunora/scheduler: workflow/agent schedule target is missing its `className` — pass the generated `workflows.<name>` / `agents.<name>` reference");return(await d(e,"/schedule",{...i,workflow:r.className})).id}const y=typeof r=="string"?r:r.__lunoraRef;return(await d(e,"/schedule",{...i,functionPath:y})).id},o=async(s,r,n,t={})=>(N(s,"ctx.scheduler.runAfter"),a(Date.now()+s,r,n,t)),c=async s=>d(e,"/cancel",{id:s}),l=async s=>(await v(async n=>f(e,n===void 0?s:`${s}?cursor=${encodeURIComponent(n)}`))).map(n=>m(n));return{cancel:c,dead:async()=>l("/dead"),deadRetry:async s=>{const{retried:r}=await d(e,"/dead/retry",{id:s});return r===!0},get:async s=>{const r=await f(e,`/get?id=${encodeURIComponent(s)}`);return r.record===void 0?null:m(r.record)},list:async()=>l("/list"),runAfter:o,runAt:a}};export{K as default};
|
package/dist/packem_shared/{createSchedulerHost-Bdr87Prl.mjs → createSchedulerHost-e5kSr3H-.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import u from"./createScheduler-
|
|
1
|
+
import u from"./createScheduler-BUMMD_lz.mjs";const l=a=>a?.at!==void 0?typeof a.at=="number"?a.at:a.at.getTime():Date.now()+(a?.delayMs??0),m=a=>{const r=u({instanceName:a.instanceName,jurisdiction:a.jurisdiction,namespace:a.namespace}),c=e=>({attempts:e.attempts??0,functionPath:e.functionPath??e.workflow??"",id:e.id,scheduledFor:e.scheduledFor});return{cancel:async e=>{const{cancelled:t}=await r.cancel(e);return t},deadLetter:{list:async()=>(await r.dead()).map(t=>c(t)),requeue:async e=>r.deadRetry(e)},get:async e=>{const t=await r.get(e);return t===null?null:{...c(t),state:t.state,...t.completedAt===void 0?{}:{completedAt:t.completedAt}}},list:async()=>(await r.list()).map(t=>c(t)),schedule:async(e,t,n)=>{const d=r.runAt,s=l(n);return{id:await d(s,e,t,{retry:n?.retry,shardKey:n?.shardKey}),scheduledFor:s}}}};export{m as createSchedulerHost};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as l}from"@lunora/errors";import{encodeArgsOrThrow as o}from"@lunora/wire";import{a as s,g as m,c as u}from"./do-client-DnJqrsmj.mjs";import y from"./assertScheduleDelay-
|
|
1
|
+
import{LunoraError as l}from"@lunora/errors";import{encodeArgsOrThrow as o}from"@lunora/wire";import{a as s,g as m,c as u}from"./do-client-DnJqrsmj.mjs";import y from"./assertScheduleDelay-D9Na2wPU.mjs";const N=e=>{if(s(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:o("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};
|
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.170",
|
|
4
4
|
"description": "Scheduling for Lunora: runAfter / runAt and Cron Triggers via SchedulerDO",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
],
|
|
15
15
|
"homepage": "https://lunora.sh",
|
|
16
16
|
"bugs": "https://github.com/anolilab/lunora/issues",
|
|
17
|
-
"license": "
|
|
17
|
+
"license": "Apache-2.0",
|
|
18
18
|
"author": {
|
|
19
19
|
"name": "Daniel Bannert",
|
|
20
20
|
"email": "d.bannert@anolilab.de"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as z,r as L}from"./resolve-schedule-id-B2ghxgFm.mjs";const B="DISPATCH_IN_PROGRESS",Q="x-lunora-dispatch-declined",J=(d,t)=>{if(d.size<t)return;const e=d.keys().next().value;e!==void 0&&d.delete(e)},D=(d,t,e,s)=>{const a=d.get(t);if(a!==void 0)return a;J(d,s);const n=e().catch(r=>{throw d.get(t)===n&&d.delete(t),r});return d.set(t,n),n},Z=new TextEncoder,O=64,tt=new Map,et=async d=>D(tt,d,async()=>crypto.subtle.importKey("raw",Z.encode(d),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),O),st=new TextEncoder,at=Array.from({length:32},(d,t)=>t);new RegExp(`[${at.map(d=>String.fromCodePoint(d)).join("")}]`,"u");const it=async(d,t)=>{const e=await et(d),s=await crypto.subtle.sign("HMAC",e,st.encode(t));return z(new Uint8Array(s))},U=(d,t=200,e)=>{const s=new Headers({"content-type":"application/json"});for(const[a,n]of Object.entries({}))s.set(a,n);return Response.json(d,{headers:s,status:t})},nt="lunora-ping",rt="lunora-pong",u="id:",I="retry:",f="dead:",R="pool:",E="pq:",p="done:",C="dt:",A="repair:",S="inst:",$="cl:",P="cr:",F=50,y=128,_=d=>typeof d=="string"&&d.length>0?d:void 0,m=d=>Array.from({length:d.length},(t,e)=>d.charCodeAt(e).toString(16).padStart(4,"0")).join(""),ot=d=>{let t="";for(let e=0;e<d.length;e+=4)t+=String.fromCharCode(Number.parseInt(d.slice(e,e+4),16));return t},G=d=>`${E}${m(d)}:`,N="meta:clean",k="meta:paused",v=100,ct=10,dt=5,H=3e4,W=1e3,X=18e5,lt=1e3,ht=6,V=9e5,q=6048e5,Y=64,ut=4,j=999999999999999,gt=15,T=d=>String(d).padStart(gt,"0"),M=d=>Number.isInteger(d)&&d>0&&d<=j;class i{static indexKey(t,e){return`t:${T(t)}:${e}`}static terminalIndexKey(t,e){return`${C}${T(j-t)}:${e}`}static cronRunKey(t){return`${P}${m(t.name)}:${T(j-t.endedAt)}:${t.runId}`}static leaseIsLive(t,e){return(t.renewedAt??t.startedAt)>e-V}static cronName(t){const e=t?.name;return typeof e=="string"&&e.length>0&&e.length<=256?e:void 0}static poolQueueKey(t){return t.pool===void 0?void 0:`${G(t.pool)}${t.id}`}static pendingRows(t){const e=i.poolQueueKey(t);return{[`${u}${t.id}`]:t,...e===void 0?{}:{[e]:t.id}}}static pendingKeys(t){return Object.keys(i.pendingRows(t))}static json(t,e=200){return U(t,e)}static error(t,e,s){return i.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:dt,a=typeof e?.baseMs=="number"&&Number.isFinite(e.baseMs)&&e.baseMs>=0?e.baseMs:H,n=e?.backoff==="linear"?"linear":"exponential",r=typeof e?.maxMs=="number"&&Number.isFinite(e.maxMs)&&e.maxMs>=0?e.maxMs:void 0,c=e?.forever===!0;return c?{backoff:n,baseMs:Math.max(W,a),forever:c,maxAttempts:s,maxMs:Math.min(X,Math.max(W,r??X))}:{backoff:n,baseMs:a,forever:c,maxAttempts:s,maxMs:r}}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),e.forever===!0&&(s.forever=!0),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;recovery;recovered=!1;dirty=!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 /cron/runs":return this.handleCronRuns();case"GET /dead":return this.handleDeadList(e);case"GET /get":return this.handleGet(e);case"GET /history":return this.handleHistory(e);case"GET /instances":return this.handleListInstances();case"GET /list":return this.handleList(e);case"GET /pause":return i.json(await this.pauseState());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 /cron/begin":return this.handleCronBegin(t);case"POST /cron/end":return this.handleCronEnd(t);case"POST /cron/renew":return this.handleCronRenew(t);case"POST /dead/cancel":return this.handleDeadCancel(t);case"POST /dead/retry":return this.handleDeadRetry(t);case"POST /instances/register":return this.handleRegisterInstance(t);case"POST /pause":return this.handleSetPause(t);case"POST /schedule":return this.handleSchedule(t)}return U({error:{code:"NOT_FOUND"}},404)}async alarm(){if(await this.reindexOrphanedRecords(),(await this.pauseState()).paused){await this.state.storage.deleteAlarm();return}const e=Date.now(),s=[],a=new Set,n=await this.state.storage.list({end:`t:${T(e)}:~`,limit:100,prefix:"t:"}),r=[];for(const[l,h]of n.entries()){const w=Number.parseInt(l.slice(2,l.indexOf(":",2)),10);Number.isFinite(w)&&w<=e&&r.push({indexKey:l,recordId:h})}const c=await Promise.all(r.map(l=>this.state.storage.get(`${u}${l.recordId}`)));for(const[l,{indexKey:h,recordId:w}]of r.entries()){const g=c[l];g&&a.has(w)?await this.state.storage.delete(h):g?(a.add(w),s.push({claimKey:h,record:g})):await this.state.storage.delete(h)}let o=!1;try{s.length>0&&(await this.state.storage.delete(N),o=!0),await this.drainDue(s)}finally{await this.rescheduleAlarm(),o&&this.recovered&&!this.dirty&&await this.state.storage.put(N,!0)}await this.sweepTerminal().catch(()=>{}),s.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.firstDueAt??t.scheduledFor,shardKey:t.shardKey,workflow:t.workflow});try{const a={"content-type":"application/json"},n=await this.signDispatch(s);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}`);const r=await fetch(`${e}/_lunora/scheduler/dispatch`,{body:s,headers:a,method:"POST"});return r.status===409&&r.headers.get(Q)==="1"&&await r.json().then(o=>o?.error?.code===B,()=>!1)?"in-progress":r.ok}catch{return!1}}armWebSocketKeepalive(){const t=this.state.setWebSocketAutoResponse;typeof t!="function"||typeof WebSocketRequestResponsePair>"u"||t.call(this.state,new WebSocketRequestResponsePair(nt,rt))}async drainDue(t){const e=[...t],s=[],a=Math.min(ht,e.length);for(let n=0;n<a;n+=1)s.push((async()=>{for(let r=e.shift();r!==void 0;r=e.shift())await this.drainRecordGuarded(r.record,r.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=i.indexKey(Date.now()+V,t.id);try{const a=await this.state.storage.get(`${u}${t.id}`);if(a===void 0){await this.state.storage.delete(e);return}if(JSON.stringify(a)!==JSON.stringify(t)||await this.isPaused())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(`${f}${t.id}`)!==void 0){await this.state.storage.delete(s),await this.state.storage.delete([`${I}${t.id}`,...i.pendingKeys(t)]);return}await this.state.storage.put(e,t.id),await this.state.storage.delete(s)}catch{this.dirty=!0}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,n=t.pool;if(!a&&n!==void 0&&await this.withPoolLock(async()=>{const r=await this.loadPool(n);await this.savePool(n,i.releaseSlot(r,t.id))}),this.cancelledLeases.has(t.id))return a&&await this.correctCanceledToSucceeded(t).catch(()=>{}),a;if(a){const r=Date.now();try{await this.writeTerminal(t,"succeeded",r)}catch{this.dirty=!0,await this.state.storage.put(`${A}${t.id}`,{...t,completedAt:r,state:"succeeded"}).catch(()=>{})}try{await this.state.storage.delete([...i.pendingKeys(t),`${I}${t.id}`])}catch{this.dirty=!0}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 n=a.inFlightIds??[];return n.includes(t.id)||n.push(t.id),a.inFlightIds=n,a.inFlight=n.length,await this.savePool(e,a),!0});return s||await this.requeuePooled(t),s}async handleWebSocketUpgrade(){if(this.state.acceptWebSocket===void 0)return i.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(u,v);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(u,v),a=JSON.stringify({records:e,truncated:s,type:"jobs"});for(const n of t)try{n.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}}),n=[...a.keys()],r=[...a.values()],c=r.length>e;return c?{cursor:n[e-1],records:r.slice(0,e),truncated:c}:{records:r,truncated:c}}async forEachPage(t,e,s=v){let a;for(;;){const n=await this.state.storage.list(a===void 0?{limit:s,prefix:t}:{limit:s,prefix:t,startAfter:a});if(n.size===0)break;for(const[c,o]of n.entries())e(o,c);if(a=[...n.keys()].at(-1),n.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 it(e,t)}async recordRetry(t,e=!1){if(this.cancelledLeases.has(t.id))return;const{backoff:s,baseMs:a,forever:n,maxAttempts:r,maxMs:c}=i.resolveRetry(t),o=t.attempts??0,l=Math.min(Number.MAX_SAFE_INTEGER,o+(e?0:1)),h=Math.min(Number.MAX_SAFE_INTEGER,o+1),w=s==="linear"?a*h:a*2**(h-1),g=c===void 0?w:Math.min(w,c),x=e?Math.max(g,H):g,b=Math.round(Date.now()+x);if(!n&&l>r){await this.parkDead(t,l,`after ${String(l)} attempts`);return}if(n&&!e&&l===r+1&&console.warn(`@lunora/scheduler: job "${t.id}" (${t.functionPath??t.workflow??"unknown"}) has failed ${String(l)} attempts and keeps retrying (retry.forever)`),!M(b)){await this.parkDead(t,l,`at attempt ${String(l)}: the retry backoff exceeded the largest schedulable time`);return}const K={...t,attempts:l,firstDueAt:void 0,scheduledFor:b};await this.state.storage.put({...i.pendingRows(K),[`${I}${t.id}`]:K,[i.indexKey(b,t.id)]:t.id})}async parkDead(t,e,s){const a=Date.now();await this.state.storage.put({[`${f}${t.id}`]:{...t,attempts:e,completedAt:a,error:`dead-lettered ${s}`},[i.terminalIndexKey(a,t.id)]:t.id}),await this.state.storage.delete([`${I}${t.id}`,...i.pendingKeys(t)]),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(`${R}${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:i.normalizeConcurrency(e,1)}}async savePool(t,e){await this.state.storage.put(`${R}${t}`,e)}async requeuePooled(t){if(this.cancelledLeases.has(t.id))return;const e=Date.now()+lt,s={...t,firstDueAt:t.firstDueAt??t.scheduledFor,scheduledFor:e};await this.state.storage.put({...i.pendingRows(s),[i.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 i.error(400,"INVALID_INPUT","pool is required");const n=await this.withPoolLock(async()=>{const r=await this.loadPool(s),c=a===void 0?i.releaseFirstSlot(r):i.releaseSlot(r,a);return await this.savePool(s,c),c});return await this.armAlarmIfEarlier(Date.now()),i.json({inFlight:n.inFlight})}async handlePoolStatus(t){const e=t.searchParams.get("name");if(e===null||e.length===0)return i.error(400,"INVALID_INPUT","name is required");const s=await this.loadPool(e);let a=0;return await this.forEachPage(G(e),()=>{a+=1}),i.json({inFlight:s.inFlight,maxConcurrency:s.maxConcurrency,queued:a})}async handleStatus(){const t=new Map;await this.forEachPage(E,(r,c)=>{const o=ot(c.slice(E.length,c.indexOf(":",E.length)));t.set(o,(t.get(o)??0)+1)});const e=[];let s=0,a=0;await this.forEachPage(R,(r,c)=>{const o=c.slice(R.length),l=Math.max(0,r.inFlight),h=t.get(o)??0;e.push({inFlight:l,maxConcurrency:r.maxConcurrency,name:o,queued:h}),s+=h,a+=l});const n={backlog:s,inFlight:a,pools:e};return i.json(n)}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:i.normalizeConcurrency(e,s.maxConcurrency)})}async idConflict(t){if(await this.state.storage.get(`${u}${t}`)!==void 0)return i.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(`${f}${t}`)!==void 0)return i.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=L(t)}catch(s){return i.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=i.resolveScheduleTarget(e);if(!e||s===void 0)return i.error(400,"INVALID_INPUT","functionPath or workflow is required");const{functionPath:a,workflow:n}=s;if(typeof e.scheduledFor!="number"||!M(e.scheduledFor))return i.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 i.error(500,"ORIGIN_NOT_CONFIGURED","LUNORA_ORIGIN_URL env binding must be set on the SchedulerDO");const r=_(e.pool),c=_(e.instanceName),o=i.normalizeRetry(e.retry),l=await this.resolveId(e.id);if(l instanceof Response)return l;const h=l;r!==void 0&&await this.persistPoolCap(r,e.maxConcurrency);const w=e.id===void 0?void 0:this.state.storage.delete([`${p}${h}`,`${A}${h}`]),g={args:e.args??{},enqueuedAt:Date.now(),id:h,...a===void 0?{}:{functionPath:a},...c===void 0?{}:{instanceName:c},...r===void 0?{}:{pool:r},...o===void 0?{}:{retry:o},scheduledFor:e.scheduledFor,shardKey:e.shardKey,...n===void 0?{}:{workflow:n}},x=this.state.storage.put({...i.pendingRows(g),[i.indexKey(g.scheduledFor,h)]:h});return await Promise.all([w,x]),await this.armAlarmIfEarlier(g.scheduledFor),await this.broadcastChange(),i.json({id:h,scheduledFor:g.scheduledFor})}async handleCancel(t){const e=await t.json().catch(()=>{});if(!e?.id)return i.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`${u}${e.id}`);return s?await this.state.storage.get(`${p}${e.id}`)!==void 0?(await this.removeRecord(s),await this.rescheduleAlarm(),i.json({cancelled:!1})):(await this.removeRecord(s),await this.writeTerminal(s,"canceled").catch(()=>{}),await this.sweepTerminal().catch(()=>{}),await this.rescheduleAlarm(),await this.broadcastChange(),i.json({cancelled:!0})):i.json({cancelled:!1})}async handleList(t){const{cursor:e,records:s,truncated:a}=await this.listPage(u,v,t.searchParams.get("cursor")??void 0);return i.json({cursor:e,records:s,truncated:a})}async handleDeadList(t){const{cursor:e,records:s,truncated:a}=await this.listPage(f,v,t.searchParams.get("cursor")??void 0);return i.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 i.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`${f}${e.id}`);if(s===void 0)return i.json({retried:!1});const a=Date.now(),n={...s,attempts:0,firstDueAt:void 0,scheduledFor:a};delete n.error,delete n.completedAt,await this.state.storage.delete(`${p}${s.id}`);const r=this.state.storage.put({...i.pendingRows(n),[i.indexKey(a,s.id)]:s.id}),c=this.state.storage.delete(s.completedAt===void 0?[`${f}${s.id}`]:[`${f}${s.id}`,i.terminalIndexKey(s.completedAt,s.id)]);return await Promise.all([r,c]),await this.armAlarmIfEarlier(a),await this.broadcastChange(),i.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 i.error(400,"INVALID_INPUT","id is required");const s=await this.state.storage.get(`${f}${e.id}`);return s===void 0?i.json({removed:!1}):(await this.writeTerminal(s,"failed",s.completedAt),await this.state.storage.delete(`${f}${e.id}`),await this.sweepTerminal().catch(()=>{}),i.json({removed:!0}))}async handleGet(t){const e=t.searchParams.get("id");if(e===null||e.length===0)return i.error(400,"INVALID_INPUT","id is required");const s=await this.readTerminal(e);if(s!==void 0)return i.json({record:s});const a=await this.state.storage.get(`${u}${e}`);if(a!==void 0){const r={...a,state:this.activeLeases.has(e)?"running":"pending"};return i.json({record:r})}const n=await this.state.storage.get(`${f}${e}`);return i.json(n===void 0?{}:{record:{...n,state:"failed"}})}async handleHistory(t){let e=t.searchParams.get("cursor")??void 0;const s=[];for(let a=0;a<ct;a+=1){const r=[...(await this.state.storage.list({limit:v+1,prefix:C,...e===void 0?{}:{startAfter:e}})).entries()],c=r.slice(0,v),o=await Promise.all(c.map(async([l,h])=>this.readTerminal(h,l)));if(s.push(...o.filter(l=>l!==void 0)),e=c.at(-1)?.[0],r.length<=v)return i.json({records:s,truncated:!1});if(s.length>0)break}return i.json({cursor:e,records:s,truncated:!0})}async readTerminal(t,e){const s=await this.state.storage.get(`${p}${t}`)??await this.readParked(t);if(!(s===void 0||s.completedAt<=Date.now()-q)&&!(e!==void 0&&i.terminalIndexKey(s.completedAt,t)!==e))return s}async readParked(t){const e=await this.state.storage.get(`${f}${t}`);return e?.completedAt===void 0?void 0:{...e,completedAt:e.completedAt,state:"failed"}}async correctCanceledToSucceeded(t){const e=await this.state.storage.get(`${p}${t.id}`);e?.state!=="canceled"||await this.state.storage.get(`${u}${t.id}`)!==void 0||JSON.stringify(e)===JSON.stringify({...t,completedAt:e.completedAt,state:e.state})&&await Promise.all([this.state.storage.delete(i.terminalIndexKey(e.completedAt,t.id)),this.writeTerminal(t,"succeeded")])}async writeTerminal(t,e,s=Date.now()){const a={...t,completedAt:s,state:e};await this.state.storage.put({[`${p}${t.id}`]:a,[i.terminalIndexKey(s,t.id)]:t.id})}async sweepTerminal(){for(let t=0;t<ut;t+=1)if(await this.sweepTerminalBatch()<Y)return}async sweepTerminalBatch(){const t=i.terminalIndexKey(Date.now()-q+1,"~"),e=await this.state.storage.list({limit:Y,prefix:C,startAfter:t});if(e.size===0)return 0;const s=await Promise.all([...e.entries()].map(async([a,n])=>{const r=await this.state.storage.get(`${p}${n}`);return r!==void 0&&i.terminalIndexKey(r.completedAt,n)===a?[a,`${p}${n}`]:[a]}));return await this.state.storage.delete(s.flat()),e.size}async pauseState(){return await this.state.storage.get(k)??{paused:!1}}async isPaused(){return(await this.pauseState()).paused}async handleRegisterInstance(t){const e=i.cronName(await t.json().catch(()=>{}));return e===void 0?i.error(400,"INVALID_INPUT","name is required"):(await this.state.storage.put(`${S}${m(e)}`,e),i.json(await this.pauseState()))}async handleListInstances(){const t=[];return await this.forEachPage(S,e=>{t.push(e)}),i.json({instances:t})}async handleSetPause(t){const e=await t.json().catch(()=>{});if(typeof e?.paused!="boolean")return i.error(400,"INVALID_INPUT","paused (boolean) is required");if(!e.paused){const n=await this.earliestPendingTime();return n!==void 0&&Number.isFinite(n)&&await this.state.storage.setAlarm(n),await this.state.storage.delete(k),i.json({paused:!1})}const a={paused:!0,pausedAt:(await this.pauseState()).pausedAt??Date.now(),...typeof e.reason=="string"&&e.reason.length>0?{reason:e.reason.slice(0,500)}:{}};return await this.state.storage.put(k,a),await this.state.storage.deleteAlarm(),i.json(a)}async handleCronBegin(t){const e=i.cronName(await t.json().catch(()=>{}));if(e===void 0)return i.error(400,"INVALID_INPUT","name is required");const s=`${$}${m(e)}`,a=Date.now();if((await this.pauseState()).paused)return await this.recordCronSkip(e,"paused",a).catch(()=>{}),i.json({acquired:!1,reason:"paused"});const r=await this.state.storage.get(s);if(r!==void 0&&i.leaseIsLive(r,a))return await this.state.storage.put(s,{...r,skipped:r.skipped+1}).catch(()=>{}),await this.recordCronSkip(e,"in-flight",a).catch(()=>{}),i.json({acquired:!1,reason:"in-flight",runningSince:r.startedAt});r!==void 0&&await this.recordLostCronRun(r,a);const c=L(void 0);return await this.state.storage.put(s,{name:e,runId:c,skipped:0,startedAt:a}),i.json({acquired:!0,runId:c})}async handleCronRenew(t){const e=await t.json().catch(()=>{}),s=i.cronName(e);if(s===void 0||typeof e?.runId!="string")return i.error(400,"INVALID_INPUT","name and runId are required");const a=`${$}${m(s)}`,n=await this.state.storage.get(a),r=Date.now();return n?.runId!==e.runId||!i.leaseIsLive(n,r)?i.json({renewed:!1}):(await this.state.storage.put(a,{...n,renewedAt:r}),i.json({renewed:!0}))}async handleCronEnd(t){const e=await t.json().catch(()=>{}),s=i.cronName(e);if(s===void 0||typeof e?.runId!="string"||e.status!=="succeeded"&&e.status!=="failed")return i.error(400,"INVALID_INPUT","name, runId and status (succeeded | failed) are required");const a=`${$}${m(s)}`,n=await this.state.storage.get(a);if(n?.runId!==e.runId)return i.json({recorded:!1});const r=Date.now();return await this.recordCronRun({durationMs:r-n.startedAt,endedAt:r,...e.status==="failed"&&typeof e.error=="string"?{error:e.error.slice(0,2e3)}:{},name:s,runId:n.runId,skipped:n.skipped,startedAt:n.startedAt,status:e.status}),await this.state.storage.delete(a),i.json({recorded:!0})}async handleCronRuns(){const t=[],e=[],s=[],a=Date.now();await this.forEachPage($,(n,r)=>{i.leaseIsLive(n,a)?t.push(n):e.push([r,n])});for(const[n,r]of e)await this.recordLostCronRun(r,a),await this.state.storage.delete(n);return await this.forEachPage(P,n=>{s.push(n)}),i.json({inFlight:t,runs:s})}async recordLostCronRun(t,e){[...(await this.state.storage.list({limit:F+y,prefix:`${P}${m(t.name)}:`})).keys()].some(a=>a.endsWith(`:${t.runId}`))||await this.recordCronRun({durationMs:e-t.startedAt,endedAt:e,error:"the run never reported completion; its lease expired",name:t.name,runId:t.runId,skipped:t.skipped,startedAt:t.startedAt,status:"failed"})}async recordCronSkip(t,e,s){const a=`${P}${m(t)}:`,n=await this.state.storage.list({limit:1,prefix:a}),[r]=n.entries();if(r?.[1].status==="skipped"&&r[1].reason===e){const[c,o]=r,l={...o,endedAt:s,skipped:o.skipped+1};await this.recordCronRun(l,i.cronRunKey(l)===c?void 0:c);return}await this.recordCronRun({durationMs:0,endedAt:s,name:t,reason:e,runId:L(void 0),skipped:1,startedAt:s,status:"skipped"})}async recordCronRun(t,e){const s=`${P}${m(t.name)}:`,a=this.state.storage.put(i.cronRunKey(t),t);await Promise.all([a,e===void 0?void 0:this.state.storage.delete(e)]);const r=[...(await this.state.storage.list({limit:F+y+1,prefix:s})).keys()].filter(c=>c!==e).slice(F);for(let c=0;c<r.length;c+=y)await this.state.storage.delete(r.slice(c,c+y))}async removeRecord(t){const e=[...i.pendingKeys(t),i.indexKey(t.scheduledFor,t.id),`${I}${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.recovery!==void 0)return this.recovery;const t=this.recoverStore();return this.recovery=t,t.catch(()=>{this.recovery=void 0}),t}async recoverStore(){if(await this.state.storage.get(N)===void 0&&(await this.reindexWalk(),await this.state.storage.put(N,!0)),await this.state.storage.getAlarm()===null){const t=await this.earliestPendingTime();t!==void 0&&Number.isFinite(t)&&await this.state.storage.setAlarm(t)}this.recovered=!0}async restoreOutcome(t){const e=await this.state.storage.get(`${u}${t.id}`);if(e!==void 0&&e.enqueuedAt!==t.enqueuedAt){await this.state.storage.delete(`${A}${t.id}`);return}await this.state.storage.get(`${p}${t.id}`)===void 0&&await this.writeTerminal(t,"succeeded",t.completedAt),await this.state.storage.delete([`${A}${t.id}`,...i.pendingKeys(t),`${I}${t.id}`])}async reindexWalk(){const t=new Set,e=new Set;await this.forEachPage("t:",o=>{t.add(o)}),await this.forEachPage(E,(o,l)=>{e.add(l)});const s=new Map;await this.forEachPage(A,o=>{s.set(o.id,o)});const a=new Set,n=[],r=[];await this.forEachPage(u,o=>{!t.has(o.id)&&M(o.scheduledFor)&&n.push(o);const l=i.poolQueueKey(o);l!==void 0&&(a.add(l),e.has(l)||r.push([l,o.id]))});const c=[...e].filter(o=>!a.has(o));for(let o=0;o<c.length;o+=y)await this.state.storage.delete(c.slice(o,o+y));for(let o=0;o<r.length;o+=y)await this.state.storage.put(Object.fromEntries(r.slice(o,o+y)));for(const o of s.values())await this.restoreOutcome(o);for(const o of n)await this.state.storage.put(i.indexKey(o.scheduledFor,o.id),o.id),await this.armAlarmIfEarlier(o.scheduledFor)}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(){if(await this.isPaused()){await this.state.storage.deleteAlarm();return}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{V as DISPATCH_LEASE_MS,ht as MAX_CONCURRENT_DISPATCHES,dt as MAX_RETRY_ATTEMPTS,j as MAX_SCHEDULED_FOR_MS,H as RETRY_BASE_DELAY_MS,i as SchedulerDO,q as TERMINAL_RETENTION_MS};
|