@nodestackapp/server 2.5.0 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (269) hide show
  1. package/README.md +42 -28
  2. package/dist/NodeStack.d.ts +5 -1
  3. package/dist/NodeStack.d.ts.map +1 -1
  4. package/dist/NodeStack.js +117 -18
  5. package/dist/NodeStack.js.map +1 -1
  6. package/dist/admin/AdminUIBundler.d.ts.map +1 -1
  7. package/dist/admin/AdminUIBundler.js +2 -0
  8. package/dist/admin/AdminUIBundler.js.map +1 -1
  9. package/dist/admin/ui/css/main.css +40 -3
  10. package/dist/admin/ui/css/webhooks.css +8 -0
  11. package/dist/admin/ui/index.html +21479 -17251
  12. package/dist/admin/ui/js/api-keys.js +1381 -0
  13. package/dist/admin/ui/js/api.js +8 -0
  14. package/dist/admin/ui/js/app.js +698 -641
  15. package/dist/admin/ui/js/apps.js +514 -489
  16. package/dist/admin/ui/js/collections.js +486 -484
  17. package/dist/admin/ui/js/command-palette.js +693 -673
  18. package/dist/admin/ui/js/cron.js +1706 -0
  19. package/dist/admin/ui/js/database.js +10 -0
  20. package/dist/admin/ui/js/flows-designer.js +1219 -1076
  21. package/dist/admin/ui/js/flows.js +947 -890
  22. package/dist/admin/ui/js/functions-tester.js +1 -1
  23. package/dist/admin/ui/js/functions-workbench.js +1162 -1101
  24. package/dist/admin/ui/js/functions.js +983 -979
  25. package/dist/admin/ui/js/rules.js +1080 -775
  26. package/dist/admin/ui/js/schema.js +346 -304
  27. package/dist/admin/ui/js/snapshots.js +338 -0
  28. package/dist/admin/ui/js/views.js +1 -1
  29. package/dist/apps/AppManager.d.ts +1 -1
  30. package/dist/apps/AppManager.d.ts.map +1 -1
  31. package/dist/apps/AppManager.js +11 -21
  32. package/dist/apps/AppManager.js.map +1 -1
  33. package/dist/apps/AppRegistry.d.ts +1 -0
  34. package/dist/apps/AppRegistry.d.ts.map +1 -1
  35. package/dist/apps/AppRegistry.js +78 -23
  36. package/dist/apps/AppRegistry.js.map +1 -1
  37. package/dist/apps/AppScope.d.ts +2 -1
  38. package/dist/apps/AppScope.d.ts.map +1 -1
  39. package/dist/apps/AppScope.js +27 -17
  40. package/dist/apps/AppScope.js.map +1 -1
  41. package/dist/auth/ApiKeyService.d.ts +63 -2
  42. package/dist/auth/ApiKeyService.d.ts.map +1 -1
  43. package/dist/auth/ApiKeyService.js +518 -8
  44. package/dist/auth/ApiKeyService.js.map +1 -1
  45. package/dist/auth/AuthService.d.ts +30 -1
  46. package/dist/auth/AuthService.d.ts.map +1 -1
  47. package/dist/auth/AuthService.js +468 -65
  48. package/dist/auth/AuthService.js.map +1 -1
  49. package/dist/auth/oauth/AppleProvider.d.ts +2 -0
  50. package/dist/auth/oauth/AppleProvider.d.ts.map +1 -1
  51. package/dist/auth/oauth/AppleProvider.js +40 -3
  52. package/dist/auth/oauth/AppleProvider.js.map +1 -1
  53. package/dist/auth/oauth/BaseOAuthProvider.d.ts +3 -2
  54. package/dist/auth/oauth/BaseOAuthProvider.d.ts.map +1 -1
  55. package/dist/auth/oauth/BaseOAuthProvider.js +29 -3
  56. package/dist/auth/oauth/BaseOAuthProvider.js.map +1 -1
  57. package/dist/auth/oauth/DiscordProvider.d.ts.map +1 -1
  58. package/dist/auth/oauth/DiscordProvider.js +4 -1
  59. package/dist/auth/oauth/DiscordProvider.js.map +1 -1
  60. package/dist/auth/oauth/GitHubProvider.d.ts.map +1 -1
  61. package/dist/auth/oauth/GitHubProvider.js +4 -1
  62. package/dist/auth/oauth/GitHubProvider.js.map +1 -1
  63. package/dist/auth/oauth/GoogleProvider.d.ts.map +1 -1
  64. package/dist/auth/oauth/GoogleProvider.js +4 -1
  65. package/dist/auth/oauth/GoogleProvider.js.map +1 -1
  66. package/dist/auth/oauth/MicrosoftProvider.d.ts.map +1 -1
  67. package/dist/auth/oauth/MicrosoftProvider.js +4 -1
  68. package/dist/auth/oauth/MicrosoftProvider.js.map +1 -1
  69. package/dist/auth/oauth/OAuthProviderRegistry.d.ts +6 -2
  70. package/dist/auth/oauth/OAuthProviderRegistry.d.ts.map +1 -1
  71. package/dist/auth/oauth/OAuthProviderRegistry.js +25 -10
  72. package/dist/auth/oauth/OAuthProviderRegistry.js.map +1 -1
  73. package/dist/auth/oauth/types.d.ts +4 -2
  74. package/dist/auth/oauth/types.d.ts.map +1 -1
  75. package/dist/cli/cli.d.ts.map +1 -1
  76. package/dist/cli/cli.js +228 -12
  77. package/dist/cli/cli.js.map +1 -1
  78. package/dist/core/config/ConfigService.d.ts.map +1 -1
  79. package/dist/core/config/ConfigService.js +5 -3
  80. package/dist/core/config/ConfigService.js.map +1 -1
  81. package/dist/core/config/EnvLoader.d.ts +14 -0
  82. package/dist/core/config/EnvLoader.d.ts.map +1 -1
  83. package/dist/core/config/EnvLoader.js +44 -0
  84. package/dist/core/config/EnvLoader.js.map +1 -1
  85. package/dist/core/container/Container.d.ts +14 -0
  86. package/dist/core/container/Container.d.ts.map +1 -1
  87. package/dist/core/container/Container.js +32 -0
  88. package/dist/core/container/Container.js.map +1 -1
  89. package/dist/core/container/Tokens.d.ts +2 -0
  90. package/dist/core/container/Tokens.d.ts.map +1 -1
  91. package/dist/core/container/Tokens.js +2 -0
  92. package/dist/core/container/Tokens.js.map +1 -1
  93. package/dist/core/errors/AppError.d.ts +7 -7
  94. package/dist/core/errors/AppError.d.ts.map +1 -1
  95. package/dist/core/errors/AppError.js +18 -14
  96. package/dist/core/errors/AppError.js.map +1 -1
  97. package/dist/core/events/EventBus.d.ts.map +1 -1
  98. package/dist/core/events/EventBus.js +36 -6
  99. package/dist/core/events/EventBus.js.map +1 -1
  100. package/dist/core/maintenance/MaintenanceGate.d.ts +47 -0
  101. package/dist/core/maintenance/MaintenanceGate.d.ts.map +1 -1
  102. package/dist/core/maintenance/MaintenanceGate.js +265 -7
  103. package/dist/core/maintenance/MaintenanceGate.js.map +1 -1
  104. package/dist/core/plugins/PluginManager.d.ts +20 -1
  105. package/dist/core/plugins/PluginManager.d.ts.map +1 -1
  106. package/dist/core/plugins/PluginManager.js +231 -146
  107. package/dist/core/plugins/PluginManager.js.map +1 -1
  108. package/dist/core/plugins/types.d.ts +48 -31
  109. package/dist/core/plugins/types.d.ts.map +1 -1
  110. package/dist/cron/CronParser.d.ts +83 -0
  111. package/dist/cron/CronParser.d.ts.map +1 -0
  112. package/dist/cron/CronParser.js +538 -0
  113. package/dist/cron/CronParser.js.map +1 -0
  114. package/dist/cron/CronService.d.ts +74 -0
  115. package/dist/cron/CronService.d.ts.map +1 -0
  116. package/dist/cron/CronService.js +1254 -0
  117. package/dist/cron/CronService.js.map +1 -0
  118. package/dist/cron/types.d.ts +98 -0
  119. package/dist/cron/types.d.ts.map +1 -0
  120. package/dist/cron/types.js +3 -0
  121. package/dist/cron/types.js.map +1 -0
  122. package/dist/database/DatabaseService.d.ts +4 -1
  123. package/dist/database/DatabaseService.d.ts.map +1 -1
  124. package/dist/database/DatabaseService.js +34 -9
  125. package/dist/database/DatabaseService.js.map +1 -1
  126. package/dist/database/config/DatabaseConfigService.d.ts +1 -0
  127. package/dist/database/config/DatabaseConfigService.d.ts.map +1 -1
  128. package/dist/database/config/DatabaseConfigService.js +4 -2
  129. package/dist/database/config/DatabaseConfigService.js.map +1 -1
  130. package/dist/database/drivers/DriverPackageLoader.d.ts +11 -0
  131. package/dist/database/drivers/DriverPackageLoader.d.ts.map +1 -0
  132. package/dist/database/drivers/DriverPackageLoader.js +112 -0
  133. package/dist/database/drivers/DriverPackageLoader.js.map +1 -0
  134. package/dist/database/drivers/DriverRegistry.d.ts +1 -0
  135. package/dist/database/drivers/DriverRegistry.d.ts.map +1 -1
  136. package/dist/database/drivers/DriverRegistry.js +29 -0
  137. package/dist/database/drivers/DriverRegistry.js.map +1 -1
  138. package/dist/database/drivers/IDatabaseDriver.d.ts +1 -0
  139. package/dist/database/drivers/IDatabaseDriver.d.ts.map +1 -1
  140. package/dist/database/drivers/MssqlDriver.d.ts.map +1 -1
  141. package/dist/database/drivers/MssqlDriver.js +10 -5
  142. package/dist/database/drivers/MssqlDriver.js.map +1 -1
  143. package/dist/database/drivers/NodeSqliteDriver.d.ts.map +1 -1
  144. package/dist/database/drivers/NodeSqliteDriver.js +15 -1
  145. package/dist/database/drivers/NodeSqliteDriver.js.map +1 -1
  146. package/dist/database/drivers/PostgresDriver.d.ts.map +1 -1
  147. package/dist/database/drivers/PostgresDriver.js +4 -5
  148. package/dist/database/drivers/PostgresDriver.js.map +1 -1
  149. package/dist/database/migration/DatabaseMigrationService.d.ts +1 -0
  150. package/dist/database/migration/DatabaseMigrationService.d.ts.map +1 -1
  151. package/dist/database/migration/DatabaseMigrationService.js +51 -0
  152. package/dist/database/migration/DatabaseMigrationService.js.map +1 -1
  153. package/dist/database/migrations/SystemMigrations.d.ts.map +1 -1
  154. package/dist/database/migrations/SystemMigrations.js +200 -5
  155. package/dist/database/migrations/SystemMigrations.js.map +1 -1
  156. package/dist/flows/FlowEngine.js.map +1 -1
  157. package/dist/flows/FlowService.d.ts +10 -1
  158. package/dist/flows/FlowService.d.ts.map +1 -1
  159. package/dist/flows/FlowService.js +227 -14
  160. package/dist/flows/FlowService.js.map +1 -1
  161. package/dist/flows/FlowValidator.d.ts +2 -1
  162. package/dist/flows/FlowValidator.d.ts.map +1 -1
  163. package/dist/flows/FlowValidator.js +89 -4
  164. package/dist/flows/FlowValidator.js.map +1 -1
  165. package/dist/flows/types.d.ts +20 -3
  166. package/dist/flows/types.d.ts.map +1 -1
  167. package/dist/functions/FunctionService.d.ts +10 -2
  168. package/dist/functions/FunctionService.d.ts.map +1 -1
  169. package/dist/functions/FunctionService.js +271 -37
  170. package/dist/functions/FunctionService.js.map +1 -1
  171. package/dist/functions/runtime/QuickJsWasmRuntime.d.ts.map +1 -1
  172. package/dist/functions/runtime/QuickJsWasmRuntime.js +189 -177
  173. package/dist/functions/runtime/QuickJsWasmRuntime.js.map +1 -1
  174. package/dist/functions/types.d.ts +31 -2
  175. package/dist/functions/types.d.ts.map +1 -1
  176. package/dist/http/HttpServer.d.ts +7 -1
  177. package/dist/http/HttpServer.d.ts.map +1 -1
  178. package/dist/http/HttpServer.js +187 -8
  179. package/dist/http/HttpServer.js.map +1 -1
  180. package/dist/http/controllers/ApiKeyController.d.ts +1 -0
  181. package/dist/http/controllers/ApiKeyController.d.ts.map +1 -1
  182. package/dist/http/controllers/ApiKeyController.js +47 -1
  183. package/dist/http/controllers/ApiKeyController.js.map +1 -1
  184. package/dist/http/controllers/AuthController.d.ts +12 -0
  185. package/dist/http/controllers/AuthController.d.ts.map +1 -1
  186. package/dist/http/controllers/AuthController.js +40 -2
  187. package/dist/http/controllers/AuthController.js.map +1 -1
  188. package/dist/http/controllers/CronController.d.ts +63 -0
  189. package/dist/http/controllers/CronController.d.ts.map +1 -0
  190. package/dist/http/controllers/CronController.js +92 -0
  191. package/dist/http/controllers/CronController.js.map +1 -0
  192. package/dist/http/controllers/DatabaseController.d.ts.map +1 -1
  193. package/dist/http/controllers/DatabaseController.js +53 -0
  194. package/dist/http/controllers/DatabaseController.js.map +1 -1
  195. package/dist/http/controllers/FlowController.d.ts.map +1 -1
  196. package/dist/http/controllers/FlowController.js +45 -4
  197. package/dist/http/controllers/FlowController.js.map +1 -1
  198. package/dist/http/controllers/FunctionController.d.ts.map +1 -1
  199. package/dist/http/controllers/FunctionController.js +16 -2
  200. package/dist/http/controllers/FunctionController.js.map +1 -1
  201. package/dist/http/controllers/HealthController.js +2 -2
  202. package/dist/http/middleware/AppResolutionMiddleware.d.ts +1 -1
  203. package/dist/http/middleware/AppResolutionMiddleware.d.ts.map +1 -1
  204. package/dist/http/middleware/AppResolutionMiddleware.js +2 -3
  205. package/dist/http/middleware/AppResolutionMiddleware.js.map +1 -1
  206. package/dist/http/middleware/AuthMiddleware.d.ts.map +1 -1
  207. package/dist/http/middleware/AuthMiddleware.js +6 -3
  208. package/dist/http/middleware/AuthMiddleware.js.map +1 -1
  209. package/dist/http/middleware/ChaosMiddleware.js +6 -6
  210. package/dist/http/middleware/ChaosMiddleware.js.map +1 -1
  211. package/dist/index.d.ts +2 -2
  212. package/dist/index.d.ts.map +1 -1
  213. package/dist/index.js +6 -2
  214. package/dist/index.js.map +1 -1
  215. package/dist/queue/QueueService.d.ts +9 -0
  216. package/dist/queue/QueueService.d.ts.map +1 -1
  217. package/dist/queue/QueueService.js +143 -60
  218. package/dist/queue/QueueService.js.map +1 -1
  219. package/dist/queue/drivers/SqliteQueueDriver.d.ts +3 -0
  220. package/dist/queue/drivers/SqliteQueueDriver.d.ts.map +1 -1
  221. package/dist/queue/drivers/SqliteQueueDriver.js +315 -255
  222. package/dist/queue/drivers/SqliteQueueDriver.js.map +1 -1
  223. package/dist/records/FtsService.d.ts +7 -3
  224. package/dist/records/FtsService.d.ts.map +1 -1
  225. package/dist/records/FtsService.js +69 -5
  226. package/dist/records/FtsService.js.map +1 -1
  227. package/dist/records/QueryFilterParser.d.ts.map +1 -1
  228. package/dist/records/QueryFilterParser.js +58 -20
  229. package/dist/records/QueryFilterParser.js.map +1 -1
  230. package/dist/records/RecordSanitizer.d.ts.map +1 -1
  231. package/dist/records/RecordSanitizer.js +32 -4
  232. package/dist/records/RecordSanitizer.js.map +1 -1
  233. package/dist/records/RecordService.d.ts +6 -0
  234. package/dist/records/RecordService.d.ts.map +1 -1
  235. package/dist/records/RecordService.js +95 -14
  236. package/dist/records/RecordService.js.map +1 -1
  237. package/dist/records/RecordValidator.d.ts +10 -0
  238. package/dist/records/RecordValidator.d.ts.map +1 -1
  239. package/dist/records/RecordValidator.js +110 -2
  240. package/dist/records/RecordValidator.js.map +1 -1
  241. package/dist/records/fts/IFtsDriver.d.ts +7 -6
  242. package/dist/records/fts/IFtsDriver.d.ts.map +1 -1
  243. package/dist/records/fts/MssqlFtsDriver.d.ts +5 -1
  244. package/dist/records/fts/MssqlFtsDriver.d.ts.map +1 -1
  245. package/dist/records/fts/MssqlFtsDriver.js +35 -3
  246. package/dist/records/fts/MssqlFtsDriver.js.map +1 -1
  247. package/dist/records/fts/PostgresFtsDriver.d.ts +9 -2
  248. package/dist/records/fts/PostgresFtsDriver.d.ts.map +1 -1
  249. package/dist/records/fts/PostgresFtsDriver.js +116 -11
  250. package/dist/records/fts/PostgresFtsDriver.js.map +1 -1
  251. package/dist/records/fts/SqliteFts5Driver.d.ts +7 -1
  252. package/dist/records/fts/SqliteFts5Driver.d.ts.map +1 -1
  253. package/dist/records/fts/SqliteFts5Driver.js +66 -6
  254. package/dist/records/fts/SqliteFts5Driver.js.map +1 -1
  255. package/dist/schema/OpenApiGenerator.d.ts.map +1 -1
  256. package/dist/schema/OpenApiGenerator.js +103 -3
  257. package/dist/schema/OpenApiGenerator.js.map +1 -1
  258. package/dist/schema/models/Field.d.ts +1 -0
  259. package/dist/schema/models/Field.d.ts.map +1 -1
  260. package/dist/snapshots/SnapshotService.d.ts.map +1 -1
  261. package/dist/snapshots/SnapshotService.js +21 -9
  262. package/dist/snapshots/SnapshotService.js.map +1 -1
  263. package/dist/snapshots/drivers/LogicalSnapshotDriver.d.ts.map +1 -1
  264. package/dist/snapshots/drivers/LogicalSnapshotDriver.js +2 -0
  265. package/dist/snapshots/drivers/LogicalSnapshotDriver.js.map +1 -1
  266. package/dist/templates/definitions/ecommerce.js +6 -6
  267. package/dist/templates/definitions/ecommerce.js.map +1 -1
  268. package/dist/webhooks/WebhookService.js +1 -1
  269. package/package.json +5 -3
@@ -0,0 +1,1254 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CronService = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const CronParser_1 = require("./CronParser");
6
+ const AppError_1 = require("../core/errors/AppError");
7
+ class CronService {
8
+ db;
9
+ config;
10
+ eventBus;
11
+ functionService;
12
+ flowService;
13
+ snapshotService;
14
+ isDisposed = false;
15
+ isStarted = false;
16
+ tablesEnsured = false;
17
+ loopTimer = null;
18
+ isTicking = false;
19
+ activeRenewals = new Map();
20
+ instanceId = (0, crypto_1.randomUUID)();
21
+ startPromise = null;
22
+ ensureTablesPromise = null;
23
+ constructor(db, options = {}) {
24
+ this.db = db;
25
+ this.config = options.config;
26
+ this.eventBus = options.eventBus;
27
+ this.functionService = options.functionService;
28
+ this.flowService = options.flowService;
29
+ this.snapshotService = options.snapshotService;
30
+ }
31
+ setFunctionService(svc) {
32
+ this.functionService = svc;
33
+ }
34
+ setFlowService(svc) {
35
+ this.flowService = svc;
36
+ }
37
+ setSnapshotService(svc) {
38
+ this.snapshotService = svc;
39
+ }
40
+ onDriverSwitched(newDb) {
41
+ this.db = newDb;
42
+ this.tablesEnsured = false;
43
+ if (this.isDbAvailable()) {
44
+ void this.ensureTables().then(() => {
45
+ if (this.isDbAvailable()) {
46
+ this.cleanStaleLeases().catch(() => { });
47
+ this.scheduleNextWake();
48
+ this.isStarted = true;
49
+ }
50
+ }).catch(() => { });
51
+ }
52
+ }
53
+ isDbAvailable() {
54
+ if (this.isDisposed)
55
+ return false;
56
+ if (this.db) {
57
+ if (this.db.isDatabaseLocked?.() || (this.db.isOpen && !this.db.isOpen())) {
58
+ return false;
59
+ }
60
+ }
61
+ return true;
62
+ }
63
+ isRunning() {
64
+ return this.isStarted && !this.isDisposed;
65
+ }
66
+ // ==========================================
67
+ // Lifecycle
68
+ // ==========================================
69
+ async start() {
70
+ if (this.isStarted && !this.isDisposed) {
71
+ return;
72
+ }
73
+ if (this.startPromise) {
74
+ return this.startPromise;
75
+ }
76
+ this.isDisposed = false;
77
+ this.startPromise = (async () => {
78
+ try {
79
+ if (!this.isDbAvailable()) {
80
+ // If database driver is closed, attempt initialization if db exists
81
+ if (this.db && !this.db.isOpen()) {
82
+ try {
83
+ await this.db.init();
84
+ }
85
+ catch {
86
+ // DB driver may still be pending initialization via scope.ensureInitialized()
87
+ }
88
+ }
89
+ }
90
+ if (this.isDbAvailable()) {
91
+ await this.ensureTables();
92
+ await this.cleanStaleLeases();
93
+ this.scheduleNextWake();
94
+ this.isStarted = true;
95
+ }
96
+ }
97
+ catch (err) {
98
+ // Table initialization or schedule query failure
99
+ }
100
+ finally {
101
+ this.startPromise = null;
102
+ }
103
+ })();
104
+ return this.startPromise;
105
+ }
106
+ async dispose() {
107
+ this.isDisposed = true;
108
+ this.isStarted = false;
109
+ this.tablesEnsured = false;
110
+ if (this.loopTimer) {
111
+ clearTimeout(this.loopTimer);
112
+ this.loopTimer = null;
113
+ }
114
+ for (const [key, timer] of this.activeRenewals.entries()) {
115
+ clearInterval(timer);
116
+ }
117
+ this.activeRenewals.clear();
118
+ this.startPromise = null;
119
+ this.ensureTablesPromise = null;
120
+ }
121
+ async resetAfterRestore() {
122
+ if (this.loopTimer) {
123
+ clearTimeout(this.loopTimer);
124
+ this.loopTimer = null;
125
+ }
126
+ for (const [key, timer] of this.activeRenewals.entries()) {
127
+ clearInterval(timer);
128
+ }
129
+ this.activeRenewals.clear();
130
+ this.tablesEnsured = false;
131
+ if (this.isDbAvailable()) {
132
+ await this.ensureTables();
133
+ await this.cleanStaleLeases();
134
+ this.scheduleNextWake();
135
+ this.isStarted = true;
136
+ }
137
+ }
138
+ getNextOccurrence(expr, tz, after) {
139
+ try {
140
+ const res = CronParser_1.CronParser.getNextRun(expr, tz, after);
141
+ return res?.date || null;
142
+ }
143
+ catch {
144
+ return null;
145
+ }
146
+ }
147
+ async ensureTables() {
148
+ if (this.tablesEnsured || !this.isDbAvailable())
149
+ return;
150
+ if (this.ensureTablesPromise) {
151
+ return this.ensureTablesPromise;
152
+ }
153
+ this.ensureTablesPromise = (async () => {
154
+ try {
155
+ if (!this.isDbAvailable())
156
+ return;
157
+ const dialect = this.db.dialect;
158
+ const pk = dialect.name === 'sqlite' ? 'TEXT' : 'VARCHAR(255)';
159
+ const txt = dialect.textType();
160
+ const num = dialect.name === 'sqlite' ? 'INTEGER' : 'INT';
161
+ const date = dialect.timestampType();
162
+ const idx = dialect.name === 'sqlite' ? 'TEXT' : 'VARCHAR(100)';
163
+ const ddlSchedules = dialect.createTableIfNotExists('_cron_schedules', `
164
+ id ${pk} PRIMARY KEY,
165
+ name ${txt} NOT NULL,
166
+ targetType ${idx} NOT NULL,
167
+ targetId ${idx} NOT NULL,
168
+ cronExpression ${txt} NOT NULL,
169
+ timezone ${txt} NOT NULL DEFAULT 'UTC',
170
+ missedRunPolicy ${txt} NOT NULL DEFAULT 'skip',
171
+ payload ${txt},
172
+ isSystemBound ${num} NOT NULL DEFAULT 0,
173
+ enabled ${num} NOT NULL DEFAULT 1,
174
+ nextRunAt ${date},
175
+ lastRunAt ${date},
176
+ lastStatus ${txt},
177
+ lastError ${txt},
178
+ leaseOwner ${txt},
179
+ leaseExpiresAt ${date},
180
+ claimToken ${txt},
181
+ maxRetries ${num} NOT NULL DEFAULT 0,
182
+ autoPauseAfterFailures ${num} NOT NULL DEFAULT 0,
183
+ consecutiveFailures ${num} NOT NULL DEFAULT 0,
184
+ expiresAt ${date},
185
+ keepLast ${num},
186
+ created ${date} NOT NULL,
187
+ updated ${date} NOT NULL
188
+ `);
189
+ const ddlRuns = dialect.createTableIfNotExists('_cron_runs', `
190
+ id ${pk} PRIMARY KEY,
191
+ scheduleId ${idx} NOT NULL,
192
+ scheduleName ${txt} NOT NULL,
193
+ targetType ${txt} NOT NULL,
194
+ targetId ${txt} NOT NULL,
195
+ scheduledAt ${date} NOT NULL,
196
+ startedAt ${date} NOT NULL,
197
+ finishedAt ${date},
198
+ durationMs ${num} NOT NULL DEFAULT 0,
199
+ status ${idx} NOT NULL,
200
+ isCatchUp ${num} NOT NULL DEFAULT 0,
201
+ attempt ${num} NOT NULL DEFAULT 1,
202
+ executionRefId ${txt},
203
+ output ${txt},
204
+ error ${txt}
205
+ `);
206
+ await this.db.exec(ddlSchedules);
207
+ await this.db.exec(ddlRuns);
208
+ await this.db.exec(dialect.createIndexIfNotExists('idx_cron_due', '_cron_schedules', 'enabled, nextRunAt'));
209
+ await this.db.exec(dialect.createIndexIfNotExists('idx_cron_target', '_cron_schedules', 'targetType, targetId'));
210
+ await this.db.exec(dialect.createIndexIfNotExists('idx_cron_lease', '_cron_schedules', 'leaseExpiresAt'));
211
+ await this.db.exec(dialect.createIndexIfNotExists('idx_cron_runs_sched', '_cron_runs', 'scheduleId, startedAt DESC'));
212
+ await this.db.exec(dialect.createIndexIfNotExists('idx_cron_runs_status', '_cron_runs', 'status, startedAt DESC'));
213
+ // Migration for existing tables
214
+ const tryAddColumn = async (table, colDef) => {
215
+ try {
216
+ await this.db.exec(`ALTER TABLE ${table} ADD COLUMN ${colDef}`);
217
+ }
218
+ catch { }
219
+ };
220
+ await tryAddColumn('_cron_schedules', `maxRetries ${num} NOT NULL DEFAULT 0`);
221
+ await tryAddColumn('_cron_schedules', `autoPauseAfterFailures ${num} NOT NULL DEFAULT 0`);
222
+ await tryAddColumn('_cron_schedules', `consecutiveFailures ${num} NOT NULL DEFAULT 0`);
223
+ await tryAddColumn('_cron_schedules', `expiresAt ${date}`);
224
+ await tryAddColumn('_cron_schedules', `keepLast ${num}`);
225
+ await tryAddColumn('_cron_runs', `attempt ${num} NOT NULL DEFAULT 1`);
226
+ this.tablesEnsured = true;
227
+ }
228
+ catch (err) {
229
+ // Table initialization or migration error
230
+ }
231
+ finally {
232
+ this.ensureTablesPromise = null;
233
+ }
234
+ })();
235
+ return this.ensureTablesPromise;
236
+ }
237
+ async cleanStaleLeases() {
238
+ if (!this.isDbAvailable())
239
+ return;
240
+ try {
241
+ const nowIso = new Date().toISOString();
242
+ await this.db.run(`UPDATE _cron_schedules
243
+ SET leaseOwner = NULL, leaseExpiresAt = NULL, claimToken = NULL
244
+ WHERE leaseExpiresAt IS NOT NULL AND leaseExpiresAt <= ?`, nowIso);
245
+ }
246
+ catch { }
247
+ }
248
+ // ==========================================
249
+ // Schedule Management (CRUD)
250
+ // ==========================================
251
+ async createSchedule(dto, actor) {
252
+ if (!this.tablesEnsured && this.isDbAvailable()) {
253
+ await this.ensureTables();
254
+ }
255
+ if (!dto.name || !dto.name.trim()) {
256
+ throw new AppError_1.ValidationError('Schedule name is required');
257
+ }
258
+ if (!dto.targetType || !['function', 'flow', 'snapshot'].includes(dto.targetType)) {
259
+ throw new AppError_1.ValidationError("Valid targetType ('function', 'flow', 'snapshot') is required");
260
+ }
261
+ if (!dto.targetId || !dto.targetId.trim()) {
262
+ throw new AppError_1.ValidationError('targetId is required');
263
+ }
264
+ if (dto.targetType === 'snapshot') {
265
+ if (this.snapshotService && !this.snapshotService.isSupported()) {
266
+ throw new AppError_1.AppError('Scheduled snapshots are only supported on SQLite databases', 400);
267
+ }
268
+ }
269
+ const tz = dto.timezone?.trim() || 'UTC';
270
+ const validation = CronParser_1.CronParser.validate(dto.cronExpression, tz);
271
+ if (!validation.valid) {
272
+ throw new AppError_1.ValidationError(validation.error || 'Invalid cron expression');
273
+ }
274
+ const missedPolicy = dto.missedRunPolicy || (dto.targetType === 'snapshot' ? 'catch_up_once' : 'skip');
275
+ if (!['skip', 'catch_up_once', 'catch_up_all'].includes(missedPolicy)) {
276
+ throw new AppError_1.ValidationError(`Invalid missedRunPolicy '${missedPolicy}'`);
277
+ }
278
+ const maxRetries = dto.maxRetries !== undefined ? Number(dto.maxRetries) : 0;
279
+ if (isNaN(maxRetries) || !Number.isInteger(maxRetries) || maxRetries < 0 || maxRetries > 5) {
280
+ throw new AppError_1.ValidationError('maxRetries must be an integer between 0 and 5');
281
+ }
282
+ const autoPauseAfterFailures = dto.autoPauseAfterFailures !== undefined ? Number(dto.autoPauseAfterFailures) : 0;
283
+ if (isNaN(autoPauseAfterFailures) || !Number.isInteger(autoPauseAfterFailures) || autoPauseAfterFailures < 0 || autoPauseAfterFailures > 50) {
284
+ throw new AppError_1.ValidationError('autoPauseAfterFailures must be an integer between 0 and 50');
285
+ }
286
+ const now = new Date();
287
+ const nowIso = now.toISOString();
288
+ let expiresAt = null;
289
+ if (dto.expiresAt !== undefined && dto.expiresAt !== null && String(dto.expiresAt).trim() !== '') {
290
+ const expDate = new Date(dto.expiresAt);
291
+ if (isNaN(expDate.getTime())) {
292
+ throw new AppError_1.ValidationError('expiresAt must be a valid ISO 8601 date string');
293
+ }
294
+ if (expDate.getTime() <= now.getTime()) {
295
+ throw new AppError_1.ValidationError('expiresAt must be a future date');
296
+ }
297
+ expiresAt = expDate.toISOString();
298
+ }
299
+ let keepLast = null;
300
+ if (dto.keepLast !== undefined && dto.keepLast !== null && String(dto.keepLast).trim() !== '') {
301
+ keepLast = Number(dto.keepLast);
302
+ if (isNaN(keepLast) || !Number.isInteger(keepLast) || keepLast < 1 || keepLast > 1000) {
303
+ throw new AppError_1.ValidationError('keepLast must be a positive integer between 1 and 1000');
304
+ }
305
+ if (dto.targetType !== 'snapshot') {
306
+ throw new AppError_1.ValidationError('keepLast retention is only applicable to snapshot schedules');
307
+ }
308
+ }
309
+ const id = dto.id || (0, crypto_1.randomUUID)();
310
+ const enabled = dto.enabled !== false;
311
+ const isSystemBound = dto.isSystemBound ? 1 : 0;
312
+ let nextRunAt = null;
313
+ if (enabled) {
314
+ const nextDate = this.getNextOccurrence(dto.cronExpression, tz, now);
315
+ if (expiresAt && (!nextDate || nextDate.getTime() > new Date(expiresAt).getTime())) {
316
+ nextRunAt = expiresAt;
317
+ }
318
+ else {
319
+ nextRunAt = nextDate ? nextDate.toISOString() : null;
320
+ }
321
+ }
322
+ let payloadStr = null;
323
+ if (dto.payload !== undefined && dto.payload !== null) {
324
+ payloadStr = typeof dto.payload === 'string' ? dto.payload : JSON.stringify(dto.payload);
325
+ }
326
+ await this.db.run(`INSERT INTO _cron_schedules (
327
+ id, name, targetType, targetId, cronExpression, timezone, missedRunPolicy,
328
+ payload, isSystemBound, enabled, nextRunAt, lastRunAt, lastStatus, lastError,
329
+ leaseOwner, leaseExpiresAt, claimToken, maxRetries, autoPauseAfterFailures,
330
+ consecutiveFailures, expiresAt, keepLast, created, updated
331
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, NULL, NULL, NULL, ?, ?, 0, ?, ?, ?, ?)`, id, dto.name.trim(), dto.targetType, dto.targetId.trim(), dto.cronExpression.trim(), tz, missedPolicy, payloadStr, isSystemBound, enabled ? 1 : 0, nextRunAt, maxRetries, autoPauseAfterFailures, expiresAt, keepLast, nowIso, nowIso);
332
+ this.scheduleNextWake();
333
+ const created = await this.getSchedule(id);
334
+ if (!created) {
335
+ throw new AppError_1.AppError('Failed to create schedule', 500);
336
+ }
337
+ return created;
338
+ }
339
+ async getSchedule(id) {
340
+ if (!this.tablesEnsured && this.isDbAvailable()) {
341
+ await this.ensureTables();
342
+ }
343
+ const row = await this.db.get('SELECT * FROM _cron_schedules WHERE id = ?', id);
344
+ return row ? this.mapRowToSchedule(row) : null;
345
+ }
346
+ async getAllSchedules(filter) {
347
+ if (!this.tablesEnsured && this.isDbAvailable()) {
348
+ await this.ensureTables();
349
+ }
350
+ let sql = 'SELECT * FROM _cron_schedules WHERE 1=1';
351
+ const params = [];
352
+ if (filter?.targetType) {
353
+ sql += ' AND targetType = ?';
354
+ params.push(filter.targetType);
355
+ }
356
+ if (filter?.enabled !== undefined) {
357
+ sql += ' AND enabled = ?';
358
+ params.push(filter.enabled ? 1 : 0);
359
+ }
360
+ if (filter?.targetId) {
361
+ sql += ' AND targetId = ?';
362
+ params.push(filter.targetId);
363
+ }
364
+ sql += ' ORDER BY created DESC';
365
+ const rows = await this.db.all(sql, ...params);
366
+ return (rows || []).map((r) => this.mapRowToSchedule(r));
367
+ }
368
+ async updateSchedule(id, dto, actor) {
369
+ const existing = await this.getSchedule(id);
370
+ if (!existing) {
371
+ throw new AppError_1.NotFoundError(`Schedule '${id}' not found`);
372
+ }
373
+ const name = dto.name !== undefined ? dto.name.trim() : existing.name;
374
+ if (!name) {
375
+ throw new AppError_1.ValidationError('Schedule name cannot be empty');
376
+ }
377
+ if (dto.targetType !== undefined) {
378
+ if (!dto.targetType || !['function', 'flow', 'snapshot'].includes(dto.targetType)) {
379
+ throw new AppError_1.ValidationError("Valid targetType ('function', 'flow', 'snapshot') is required");
380
+ }
381
+ }
382
+ const targetType = dto.targetType || existing.targetType;
383
+ if (dto.targetId !== undefined) {
384
+ if (!dto.targetId || !dto.targetId.trim()) {
385
+ throw new AppError_1.ValidationError('targetId is required and cannot be empty');
386
+ }
387
+ }
388
+ const targetId = dto.targetId !== undefined ? dto.targetId.trim() : existing.targetId;
389
+ const enabled = dto.enabled !== undefined ? dto.enabled : existing.enabled;
390
+ if (targetType === 'snapshot') {
391
+ if (this.snapshotService && !this.snapshotService.isSupported() && enabled) {
392
+ const providerName = this.db.dialect.name === 'sqlite' ? 'SQLite' : (this.db.dialect.name === 'postgres' ? 'PostgreSQL' : 'SQL Server');
393
+ throw new AppError_1.AppError(`Scheduled snapshots are exclusive to embedded SQLite applications and cannot be enabled on ${providerName}`, 400);
394
+ }
395
+ }
396
+ const tz = dto.timezone !== undefined ? dto.timezone.trim() : existing.timezone;
397
+ const cronExpr = dto.cronExpression !== undefined ? dto.cronExpression.trim() : existing.cronExpression;
398
+ const validation = CronParser_1.CronParser.validate(cronExpr, tz);
399
+ if (!validation.valid) {
400
+ throw new AppError_1.ValidationError(validation.error || 'Invalid cron expression');
401
+ }
402
+ if (dto.missedRunPolicy !== undefined) {
403
+ if (!['skip', 'catch_up_once', 'catch_up_all'].includes(dto.missedRunPolicy)) {
404
+ throw new AppError_1.ValidationError(`Invalid missedRunPolicy '${dto.missedRunPolicy}'`);
405
+ }
406
+ }
407
+ const missedPolicy = dto.missedRunPolicy || existing.missedRunPolicy;
408
+ let maxRetries = existing.maxRetries || 0;
409
+ if (dto.maxRetries !== undefined) {
410
+ maxRetries = Number(dto.maxRetries);
411
+ if (isNaN(maxRetries) || !Number.isInteger(maxRetries) || maxRetries < 0 || maxRetries > 5) {
412
+ throw new AppError_1.ValidationError('maxRetries must be an integer between 0 and 5');
413
+ }
414
+ }
415
+ let autoPauseAfterFailures = existing.autoPauseAfterFailures || 0;
416
+ if (dto.autoPauseAfterFailures !== undefined) {
417
+ autoPauseAfterFailures = Number(dto.autoPauseAfterFailures);
418
+ if (isNaN(autoPauseAfterFailures) || !Number.isInteger(autoPauseAfterFailures) || autoPauseAfterFailures < 0 || autoPauseAfterFailures > 50) {
419
+ throw new AppError_1.ValidationError('autoPauseAfterFailures must be an integer between 0 and 50');
420
+ }
421
+ }
422
+ const now = new Date();
423
+ const nowIso = now.toISOString();
424
+ let expiresAt = existing.expiresAt;
425
+ if (dto.expiresAt !== undefined) {
426
+ if (dto.expiresAt === null || String(dto.expiresAt).trim() === '') {
427
+ expiresAt = null;
428
+ }
429
+ else {
430
+ const expDate = new Date(dto.expiresAt);
431
+ if (isNaN(expDate.getTime())) {
432
+ throw new AppError_1.ValidationError('expiresAt must be a valid ISO 8601 date string');
433
+ }
434
+ if (expDate.getTime() <= now.getTime()) {
435
+ throw new AppError_1.ValidationError('expiresAt must be a future date');
436
+ }
437
+ expiresAt = expDate.toISOString();
438
+ }
439
+ }
440
+ let keepLast = existing.keepLast;
441
+ if (dto.keepLast !== undefined) {
442
+ if (dto.keepLast === null || String(dto.keepLast).trim() === '') {
443
+ keepLast = null;
444
+ }
445
+ else {
446
+ keepLast = Number(dto.keepLast);
447
+ if (isNaN(keepLast) || !Number.isInteger(keepLast) || keepLast < 1 || keepLast > 1000) {
448
+ throw new AppError_1.ValidationError('keepLast must be a positive integer between 1 and 1000');
449
+ }
450
+ if (targetType !== 'snapshot') {
451
+ throw new AppError_1.ValidationError('keepLast retention is only applicable to snapshot schedules');
452
+ }
453
+ }
454
+ }
455
+ let consecutiveFailures = existing.consecutiveFailures || 0;
456
+ if (dto.enabled === true && !existing.enabled) {
457
+ consecutiveFailures = 0;
458
+ }
459
+ let payloadStr = null;
460
+ if (dto.payload !== undefined) {
461
+ payloadStr = dto.payload !== null ? (typeof dto.payload === 'string' ? dto.payload : JSON.stringify(dto.payload)) : null;
462
+ }
463
+ else if (existing.payload !== undefined && existing.payload !== null) {
464
+ payloadStr = typeof existing.payload === 'string' ? existing.payload : JSON.stringify(existing.payload);
465
+ }
466
+ let nextRunAt = existing.nextRunAt;
467
+ if (enabled && (dto.cronExpression !== undefined || dto.timezone !== undefined || !existing.enabled || dto.expiresAt !== undefined)) {
468
+ const nextDate = this.getNextOccurrence(cronExpr, tz, now);
469
+ if (expiresAt && (!nextDate || nextDate.getTime() > new Date(expiresAt).getTime())) {
470
+ nextRunAt = expiresAt;
471
+ }
472
+ else {
473
+ nextRunAt = nextDate ? nextDate.toISOString() : null;
474
+ }
475
+ }
476
+ else if (!enabled) {
477
+ nextRunAt = null;
478
+ }
479
+ await this.db.run(`UPDATE _cron_schedules SET
480
+ name = ?, targetType = ?, targetId = ?, cronExpression = ?, timezone = ?,
481
+ missedRunPolicy = ?, payload = ?, enabled = ?, nextRunAt = ?,
482
+ maxRetries = ?, autoPauseAfterFailures = ?, consecutiveFailures = ?,
483
+ expiresAt = ?, keepLast = ?, updated = ?,
484
+ leaseOwner = CASE WHEN ? = 0 THEN NULL ELSE leaseOwner END,
485
+ leaseExpiresAt = CASE WHEN ? = 0 THEN NULL ELSE leaseExpiresAt END,
486
+ claimToken = CASE WHEN ? = 0 THEN NULL ELSE claimToken END
487
+ WHERE id = ?`, name, targetType, targetId, cronExpr, tz, missedPolicy, payloadStr, enabled ? 1 : 0, nextRunAt, maxRetries, autoPauseAfterFailures, consecutiveFailures, expiresAt, keepLast, nowIso, enabled ? 1 : 0, enabled ? 1 : 0, enabled ? 1 : 0, id);
488
+ // Bidirectional sync for system-bound inline schedules:
489
+ if (existing.isSystemBound) {
490
+ try {
491
+ if (targetType === 'function') {
492
+ const fnCronExpr = enabled ? cronExpr : null;
493
+ await this.db.run(`UPDATE _functions SET
494
+ cronSchedule = ?, cronTimezone = ?, cronMissedPolicy = ?, cronPayload = ?, updated = ?
495
+ WHERE id = ?`, fnCronExpr, tz, missedPolicy, payloadStr, nowIso, targetId);
496
+ }
497
+ else if (targetType === 'flow') {
498
+ const flowCronExpr = enabled ? cronExpr : null;
499
+ const flowTriggerType = enabled ? 'cron' : 'manual';
500
+ await this.db.run(`UPDATE _flows SET
501
+ triggerType = ?, cronSchedule = ?, cronTimezone = ?, cronMissedPolicy = ?, cronInput = ?, updated = ?
502
+ WHERE id = ?`, flowTriggerType, flowCronExpr, tz, missedPolicy, payloadStr, nowIso, targetId);
503
+ }
504
+ }
505
+ catch (syncErr) {
506
+ console.warn(`[CronService] Failed to sync bound schedule '${id}' to ${targetType}:`, syncErr);
507
+ }
508
+ }
509
+ this.scheduleNextWake();
510
+ const updated = await this.getSchedule(id);
511
+ return updated;
512
+ }
513
+ deleteSchedule(id, actor) {
514
+ const row = this.db.get('SELECT * FROM _cron_schedules WHERE id = ?', id);
515
+ if (row instanceof Promise) {
516
+ return row.then((r) => {
517
+ if (!r)
518
+ return false;
519
+ return this.finishDeleteSchedule(id, r);
520
+ });
521
+ }
522
+ if (!row) {
523
+ return false;
524
+ }
525
+ return this.finishDeleteSchedule(id, row);
526
+ }
527
+ finishDeleteSchedule(id, existing) {
528
+ const promises = [];
529
+ // If deleting a system-bound schedule, clear cron on the parent function / flow
530
+ if (existing && (existing.isSystemBound || id.startsWith('inline_fn_') || id.startsWith('inline_flow_'))) {
531
+ const nowIso = new Date().toISOString();
532
+ if (existing.targetType === 'function') {
533
+ const pFn = this.db.run('UPDATE _functions SET cronSchedule = NULL, updated = ? WHERE id = ?', nowIso, existing.targetId);
534
+ if (pFn instanceof Promise)
535
+ promises.push(pFn);
536
+ }
537
+ else if (existing.targetType === 'flow') {
538
+ const pFlow = this.db.run("UPDATE _flows SET triggerType = 'manual', cronSchedule = NULL, updated = ? WHERE id = ?", nowIso, existing.targetId);
539
+ if (pFlow instanceof Promise)
540
+ promises.push(pFlow);
541
+ }
542
+ }
543
+ const del1 = this.db.run('DELETE FROM _cron_runs WHERE scheduleId = ?', id);
544
+ const del2 = this.db.run('DELETE FROM _cron_schedules WHERE id = ?', id);
545
+ this.scheduleNextWake();
546
+ if (del1 instanceof Promise)
547
+ promises.push(del1);
548
+ if (del2 instanceof Promise)
549
+ promises.push(del2);
550
+ if (promises.length > 0) {
551
+ return Promise.all(promises).then((results) => {
552
+ const last = results[results.length - 1];
553
+ return Number(last?.changes || 0) > 0;
554
+ });
555
+ }
556
+ return Number(del2?.changes || 0) > 0;
557
+ }
558
+ // ==========================================
559
+ // Target Synchronization (Inline 1:1 bindings)
560
+ // ==========================================
561
+ syncFunctionSchedule(fn) {
562
+ const scheduleId = `inline_fn_${fn.id}`;
563
+ const row = this.db.get('SELECT * FROM _cron_schedules WHERE id = ?', scheduleId);
564
+ if (row instanceof Promise) {
565
+ return row.then((r) => this.finishSyncFunctionSchedule(fn, scheduleId, r ? this.mapRowToSchedule(r) : null));
566
+ }
567
+ return this.finishSyncFunctionSchedule(fn, scheduleId, row ? this.mapRowToSchedule(row) : null);
568
+ }
569
+ finishSyncFunctionSchedule(fn, scheduleId, existing) {
570
+ if (fn.cronSchedule && fn.cronSchedule.trim() && fn.enabled) {
571
+ const tz = fn.cronTimezone?.trim() || 'UTC';
572
+ const validation = CronParser_1.CronParser.validate(fn.cronSchedule.trim(), tz);
573
+ if (!validation.valid) {
574
+ throw new AppError_1.ValidationError(validation.error || 'Invalid cron expression');
575
+ }
576
+ const missedPolicy = fn.cronMissedPolicy || 'skip';
577
+ if (!['skip', 'catch_up_once', 'catch_up_all'].includes(missedPolicy)) {
578
+ throw new AppError_1.ValidationError(`Invalid missedRunPolicy '${missedPolicy}'`);
579
+ }
580
+ const now = new Date();
581
+ const nextDate = this.getNextOccurrence(fn.cronSchedule.trim(), tz, now);
582
+ const nextRunAt = nextDate ? nextDate.toISOString() : null;
583
+ let payloadStr = null;
584
+ if (fn.cronPayload !== undefined && fn.cronPayload !== null) {
585
+ payloadStr = typeof fn.cronPayload === 'string' ? fn.cronPayload : JSON.stringify(fn.cronPayload);
586
+ }
587
+ const nowIso = now.toISOString();
588
+ let runRes;
589
+ if (existing) {
590
+ runRes = this.db.run(`UPDATE _cron_schedules SET
591
+ name = ?, cronExpression = ?, timezone = ?, missedRunPolicy = ?,
592
+ payload = ?, enabled = 1, nextRunAt = ?, updated = ?
593
+ WHERE id = ?`, `Function: ${fn.name}`, fn.cronSchedule.trim(), tz, missedPolicy, payloadStr, nextRunAt, nowIso, scheduleId);
594
+ }
595
+ else {
596
+ runRes = this.db.run(`INSERT INTO _cron_schedules (
597
+ id, name, targetType, targetId, cronExpression, timezone, missedRunPolicy,
598
+ payload, isSystemBound, enabled, nextRunAt, lastRunAt, lastStatus, lastError,
599
+ leaseOwner, leaseExpiresAt, claimToken, created, updated
600
+ ) VALUES (?, ?, 'function', ?, ?, ?, ?, ?, 1, 1, ?, NULL, NULL, NULL, NULL, NULL, NULL, ?, ?)`, scheduleId, `Function: ${fn.name}`, fn.id, fn.cronSchedule.trim(), tz, missedPolicy, payloadStr, nextRunAt, nowIso, nowIso);
601
+ }
602
+ this.scheduleNextWake();
603
+ if (runRes instanceof Promise) {
604
+ return runRes.then(() => { });
605
+ }
606
+ return;
607
+ }
608
+ else {
609
+ if (existing) {
610
+ return this.deleteSchedule(scheduleId);
611
+ }
612
+ }
613
+ }
614
+ syncFlowSchedule(flow) {
615
+ const scheduleId = `inline_flow_${flow.id}`;
616
+ const row = this.db.get('SELECT * FROM _cron_schedules WHERE id = ?', scheduleId);
617
+ if (row instanceof Promise) {
618
+ return row.then((r) => this.finishSyncFlowSchedule(flow, scheduleId, r ? this.mapRowToSchedule(r) : null));
619
+ }
620
+ return this.finishSyncFlowSchedule(flow, scheduleId, row ? this.mapRowToSchedule(row) : null);
621
+ }
622
+ finishSyncFlowSchedule(flow, scheduleId, existing) {
623
+ if (flow.triggerType === 'cron' && flow.cronSchedule && flow.cronSchedule.trim() && flow.enabled) {
624
+ const tz = flow.cronTimezone?.trim() || 'UTC';
625
+ const validation = CronParser_1.CronParser.validate(flow.cronSchedule.trim(), tz);
626
+ if (!validation.valid) {
627
+ throw new AppError_1.ValidationError(validation.error || 'Invalid cron expression');
628
+ }
629
+ const missedPolicy = flow.cronMissedPolicy || 'skip';
630
+ if (!['skip', 'catch_up_once', 'catch_up_all'].includes(missedPolicy)) {
631
+ throw new AppError_1.ValidationError(`Invalid missedRunPolicy '${missedPolicy}'`);
632
+ }
633
+ const now = new Date();
634
+ const nextDate = this.getNextOccurrence(flow.cronSchedule.trim(), tz, now);
635
+ const nextRunAt = nextDate ? nextDate.toISOString() : null;
636
+ let payloadStr = null;
637
+ if (flow.cronInput !== undefined && flow.cronInput !== null) {
638
+ payloadStr = typeof flow.cronInput === 'string' ? flow.cronInput : JSON.stringify(flow.cronInput);
639
+ }
640
+ const nowIso = now.toISOString();
641
+ let runRes;
642
+ if (existing) {
643
+ runRes = this.db.run(`UPDATE _cron_schedules SET
644
+ name = ?, cronExpression = ?, timezone = ?, missedRunPolicy = ?,
645
+ payload = ?, enabled = 1, nextRunAt = ?, updated = ?
646
+ WHERE id = ?`, `Flow: ${flow.name}`, flow.cronSchedule.trim(), tz, missedPolicy, payloadStr, nextRunAt, nowIso, scheduleId);
647
+ }
648
+ else {
649
+ runRes = this.db.run(`INSERT INTO _cron_schedules (
650
+ id, name, targetType, targetId, cronExpression, timezone, missedRunPolicy,
651
+ payload, isSystemBound, enabled, nextRunAt, lastRunAt, lastStatus, lastError,
652
+ leaseOwner, leaseExpiresAt, claimToken, created, updated
653
+ ) VALUES (?, ?, 'flow', ?, ?, ?, ?, ?, 1, 1, ?, NULL, NULL, NULL, NULL, NULL, NULL, ?, ?)`, scheduleId, `Flow: ${flow.name}`, flow.id, flow.cronSchedule.trim(), tz, missedPolicy, payloadStr, nextRunAt, nowIso, nowIso);
654
+ }
655
+ this.scheduleNextWake();
656
+ if (runRes instanceof Promise) {
657
+ return runRes.then(() => { });
658
+ }
659
+ return;
660
+ }
661
+ else {
662
+ if (existing) {
663
+ return this.deleteSchedule(scheduleId);
664
+ }
665
+ }
666
+ }
667
+ removeTargetSchedules(targetType, targetId) {
668
+ const rows = this.db.all('SELECT id FROM _cron_schedules WHERE targetType = ? AND targetId = ?', targetType, targetId);
669
+ if (rows instanceof Promise) {
670
+ return rows.then(async (rList) => {
671
+ for (const s of rList || []) {
672
+ await this.deleteSchedule(s.id);
673
+ }
674
+ });
675
+ }
676
+ for (const s of rows || []) {
677
+ const d = this.deleteSchedule(s.id);
678
+ if (d instanceof Promise)
679
+ void d.catch(() => { });
680
+ }
681
+ }
682
+ // ==========================================
683
+ // Immediate Trigger & Run History
684
+ // ==========================================
685
+ async triggerSchedule(id, actor) {
686
+ const schedule = await this.getSchedule(id);
687
+ if (!schedule) {
688
+ throw new AppError_1.NotFoundError(`Schedule '${id}' not found`);
689
+ }
690
+ const runId = (0, crypto_1.randomUUID)();
691
+ const scheduledAt = new Date();
692
+ return await this.executeTarget(schedule, scheduledAt, false, runId, true);
693
+ }
694
+ async getRuns(options = {}) {
695
+ if (!this.tablesEnsured && this.isDbAvailable()) {
696
+ await this.ensureTables();
697
+ }
698
+ const page = Math.max(1, options.page || 1);
699
+ const perPage = Math.max(1, Math.min(options.perPage || 30, 100));
700
+ const offset = (page - 1) * perPage;
701
+ let whereSql = 'WHERE 1=1';
702
+ const params = [];
703
+ if (options.scheduleId) {
704
+ whereSql += ' AND scheduleId = ?';
705
+ params.push(options.scheduleId);
706
+ }
707
+ if (options.targetType) {
708
+ whereSql += ' AND targetType = ?';
709
+ params.push(options.targetType);
710
+ }
711
+ if (options.status) {
712
+ whereSql += ' AND status = ?';
713
+ params.push(options.status);
714
+ }
715
+ const countRow = await this.db.get(`SELECT COUNT(*) as total FROM _cron_runs ${whereSql}`, ...params);
716
+ const total = Number(countRow?.total || 0);
717
+ const querySql = `SELECT * FROM _cron_runs ${whereSql} ORDER BY startedAt DESC LIMIT ? OFFSET ?`;
718
+ const rows = await this.db.all(querySql, ...params, perPage, offset);
719
+ const items = (rows || []).map((r) => this.mapRowToRun(r));
720
+ return { items, total, page, perPage };
721
+ }
722
+ async clearRuns(scheduleId) {
723
+ let res;
724
+ if (scheduleId) {
725
+ res = await this.db.run('DELETE FROM _cron_runs WHERE scheduleId = ?', scheduleId);
726
+ }
727
+ else {
728
+ res = await this.db.run('DELETE FROM _cron_runs');
729
+ }
730
+ return Number(res?.changes || 0);
731
+ }
732
+ async getStats() {
733
+ if (!this.tablesEnsured && this.isDbAvailable()) {
734
+ await this.ensureTables();
735
+ }
736
+ const totalSchedulesRow = await this.db.get('SELECT COUNT(*) as cnt FROM _cron_schedules');
737
+ const activeSchedulesRow = await this.db.get('SELECT COUNT(*) as cnt FROM _cron_schedules WHERE enabled = 1');
738
+ const totalRunsRow = await this.db.get('SELECT COUNT(*) as cnt FROM _cron_runs');
739
+ const successRunsRow = await this.db.get("SELECT COUNT(*) as cnt FROM _cron_runs WHERE status = 'succeeded'");
740
+ const failedRunsRow = await this.db.get("SELECT COUNT(*) as cnt FROM _cron_runs WHERE status = 'failed'");
741
+ const skippedRunsRow = await this.db.get("SELECT COUNT(*) as cnt FROM _cron_runs WHERE status = 'skipped'");
742
+ const fnSchedulesRow = await this.db.get("SELECT COUNT(*) as cnt FROM _cron_schedules WHERE targetType = 'function'");
743
+ const flowSchedulesRow = await this.db.get("SELECT COUNT(*) as cnt FROM _cron_schedules WHERE targetType = 'flow'");
744
+ const snapSchedulesRow = await this.db.get("SELECT COUNT(*) as cnt FROM _cron_schedules WHERE targetType = 'snapshot'");
745
+ return {
746
+ totalSchedules: Number(totalSchedulesRow?.cnt || 0),
747
+ activeSchedules: Number(activeSchedulesRow?.cnt || 0),
748
+ totalRuns: Number(totalRunsRow?.cnt || 0),
749
+ successfulRuns: Number(successRunsRow?.cnt || 0),
750
+ failedRuns: Number(failedRunsRow?.cnt || 0),
751
+ skippedRuns: Number(skippedRunsRow?.cnt || 0),
752
+ byTarget: {
753
+ function: Number(fnSchedulesRow?.cnt || 0),
754
+ flow: Number(flowSchedulesRow?.cnt || 0),
755
+ snapshot: Number(snapSchedulesRow?.cnt || 0),
756
+ },
757
+ };
758
+ }
759
+ preview(cronExpression, timezone = 'UTC', count = 5) {
760
+ return CronParser_1.CronParser.preview(cronExpression, timezone, count);
761
+ }
762
+ // ==========================================
763
+ // Scheduler Engine Loop & Leases
764
+ // ==========================================
765
+ scheduleNextWake() {
766
+ if (this.isDisposed || !this.isDbAvailable())
767
+ return;
768
+ if (this.loopTimer) {
769
+ clearTimeout(this.loopTimer);
770
+ this.loopTimer = null;
771
+ }
772
+ void (async () => {
773
+ try {
774
+ const row = await this.db.get('SELECT nextRunAt FROM _cron_schedules WHERE enabled = 1 AND nextRunAt IS NOT NULL ORDER BY nextRunAt ASC LIMIT 1');
775
+ let delayMs = 15_000;
776
+ if (row && row.nextRunAt) {
777
+ const nextTime = new Date(row.nextRunAt).getTime();
778
+ const now = Date.now();
779
+ delayMs = Math.min(Math.max(50, nextTime - now), 15_000);
780
+ }
781
+ if (!this.isDisposed) {
782
+ this.loopTimer = setTimeout(() => {
783
+ void this.tick();
784
+ }, delayMs);
785
+ }
786
+ }
787
+ catch {
788
+ if (!this.isDisposed) {
789
+ this.loopTimer = setTimeout(() => {
790
+ void this.tick();
791
+ }, 15_000);
792
+ }
793
+ }
794
+ })();
795
+ }
796
+ async tick() {
797
+ if (this.isTicking || this.isDisposed || !this.isDbAvailable())
798
+ return;
799
+ this.isTicking = true;
800
+ try {
801
+ const now = new Date();
802
+ const nowIso = now.toISOString();
803
+ // 1. Reclaim any expired leases
804
+ await this.cleanStaleLeases();
805
+ // 2. Select due schedules (with a safety batch cap of 50)
806
+ const dueSchedules = await this.db.all('SELECT * FROM _cron_schedules WHERE enabled = 1 AND nextRunAt IS NOT NULL AND nextRunAt <= ? ORDER BY nextRunAt ASC LIMIT 50', nowIso);
807
+ const claimed = [];
808
+ for (const row of dueSchedules || []) {
809
+ if (this.isDisposed)
810
+ break;
811
+ const schedule = this.mapRowToSchedule(row);
812
+ // Check if schedule has already expired
813
+ if (schedule.expiresAt && new Date(schedule.expiresAt).getTime() <= now.getTime()) {
814
+ await this.db.run(`UPDATE _cron_schedules
815
+ SET enabled = 0, nextRunAt = NULL, lastError = 'Schedule expired',
816
+ leaseOwner = NULL, leaseExpiresAt = NULL, claimToken = NULL
817
+ WHERE id = ?`, schedule.id);
818
+ if (this.eventBus) {
819
+ try {
820
+ this.eventBus.emit('cron:expired', { scheduleId: schedule.id, scheduleName: schedule.name });
821
+ }
822
+ catch { }
823
+ }
824
+ continue;
825
+ }
826
+ const claimToken = (0, crypto_1.randomUUID)();
827
+ const leaseExpiry = new Date(Date.now() + 60_000).toISOString();
828
+ // Atomic CAS lease acquisition
829
+ const leaseRes = await this.db.run(`UPDATE _cron_schedules
830
+ SET leaseOwner = ?, leaseExpiresAt = ?, claimToken = ?
831
+ WHERE id = ? AND nextRunAt = ? AND (leaseExpiresAt IS NULL OR leaseExpiresAt <= ?)`, this.instanceId, leaseExpiry, claimToken, schedule.id, schedule.nextRunAt, nowIso);
832
+ const acquired = Number(leaseRes?.changes || 0) > 0;
833
+ if (!acquired) {
834
+ continue; // Another instance claimed this schedule or nextRunAt changed
835
+ }
836
+ claimed.push({ schedule, claimToken });
837
+ }
838
+ // 3. Dispatch claimed schedules concurrently up to MAX_CONCURRENT (10 workers)
839
+ const MAX_CONCURRENT = 10;
840
+ let cursor = 0;
841
+ const worker = async () => {
842
+ while (cursor < claimed.length && !this.isDisposed) {
843
+ const item = claimed[cursor++];
844
+ if (!item)
845
+ break;
846
+ try {
847
+ await this.processDueSchedule(item.schedule, now, item.claimToken);
848
+ }
849
+ catch (err) {
850
+ // Guarded inside processDueSchedule
851
+ }
852
+ }
853
+ };
854
+ const workerCount = Math.min(MAX_CONCURRENT, claimed.length);
855
+ if (workerCount > 0) {
856
+ await Promise.all(Array.from({ length: workerCount }, () => worker()));
857
+ }
858
+ }
859
+ catch (err) {
860
+ // Loop tick error
861
+ }
862
+ finally {
863
+ this.isTicking = false;
864
+ this.scheduleNextWake();
865
+ }
866
+ }
867
+ async advanceNextRun(schedule, claimToken, afterTime, lastRunAtIso, lastStatus, lastError) {
868
+ const current = await this.getSchedule(schedule.id);
869
+ if (!current || !current.enabled) {
870
+ // Auto-paused by circuit breaker, deleted, or disabled by administrator during execution
871
+ await this.db.run(`UPDATE _cron_schedules
872
+ SET nextRunAt = NULL, leaseOwner = NULL, leaseExpiresAt = NULL, claimToken = NULL
873
+ WHERE id = ? AND (claimToken = ? OR claimToken IS NULL)`, schedule.id, claimToken);
874
+ return;
875
+ }
876
+ // Compute next future occurrence using fresh cronExpression and timezone
877
+ const baseTime = Math.max(Date.now(), afterTime);
878
+ const nextOccurrence = this.getNextOccurrence(current.cronExpression, current.timezone, new Date(baseTime + 1000));
879
+ let isExpired = false;
880
+ let nextRunAt = null;
881
+ if (nextOccurrence) {
882
+ if (current.expiresAt && nextOccurrence.getTime() > new Date(current.expiresAt).getTime()) {
883
+ isExpired = true;
884
+ }
885
+ else {
886
+ nextRunAt = nextOccurrence.toISOString();
887
+ }
888
+ }
889
+ else if (current.expiresAt) {
890
+ isExpired = true;
891
+ }
892
+ if (isExpired) {
893
+ await this.db.run(`UPDATE _cron_schedules
894
+ SET enabled = 0, nextRunAt = NULL, lastError = 'Schedule expired',
895
+ leaseOwner = NULL, leaseExpiresAt = NULL, claimToken = NULL
896
+ WHERE id = ? AND claimToken = ?`, schedule.id, claimToken);
897
+ if (this.eventBus) {
898
+ try {
899
+ this.eventBus.emit('cron:expired', { scheduleId: current.id, scheduleName: current.name });
900
+ }
901
+ catch { }
902
+ }
903
+ return;
904
+ }
905
+ if (lastRunAtIso && lastStatus) {
906
+ await this.db.run(`UPDATE _cron_schedules
907
+ SET lastRunAt = ?, lastStatus = ?, lastError = ?,
908
+ nextRunAt = ?, leaseOwner = NULL, leaseExpiresAt = NULL, claimToken = NULL
909
+ WHERE id = ? AND claimToken = ?`, lastRunAtIso, lastStatus, lastError || null, nextRunAt, schedule.id, claimToken);
910
+ }
911
+ else {
912
+ await this.db.run(`UPDATE _cron_schedules
913
+ SET nextRunAt = ?, leaseOwner = NULL, leaseExpiresAt = NULL, claimToken = NULL
914
+ WHERE id = ? AND claimToken = ?`, nextRunAt, schedule.id, claimToken);
915
+ }
916
+ }
917
+ async processDueSchedule(schedule, now, claimToken) {
918
+ const scheduledTime = schedule.nextRunAt ? new Date(schedule.nextRunAt).getTime() : now.getTime();
919
+ try {
920
+ const diffMs = now.getTime() - scheduledTime;
921
+ const nowIso = now.toISOString();
922
+ // Check 60-second misfire window
923
+ if (diffMs > 60_000) {
924
+ if (schedule.missedRunPolicy === 'skip') {
925
+ // Record skipped run log
926
+ const runId = (0, crypto_1.randomUUID)();
927
+ await this.db.run(`INSERT INTO _cron_runs (
928
+ id, scheduleId, scheduleName, targetType, targetId, scheduledAt, startedAt,
929
+ finishedAt, durationMs, status, isCatchUp, attempt, executionRefId, output, error
930
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'skipped', 0, 1, NULL, NULL, ?)`, runId, schedule.id, schedule.name, schedule.targetType, schedule.targetId, schedule.nextRunAt || nowIso, nowIso, nowIso, 'Missed schedule window (>60s) - skipped per policy');
931
+ // Advance to next future occurrence after now
932
+ await this.advanceNextRun(schedule, claimToken, now.getTime(), nowIso, 'skipped', 'Skipped missed window');
933
+ return;
934
+ }
935
+ if (schedule.missedRunPolicy === 'catch_up_once') {
936
+ // Run once with catch-up flag
937
+ await this.executeTarget(schedule, new Date(scheduledTime), true, claimToken, false);
938
+ // Advance nextRunAt to next future occurrence after scheduled time
939
+ await this.advanceNextRun(schedule, claimToken, scheduledTime);
940
+ return;
941
+ }
942
+ if (schedule.missedRunPolicy === 'catch_up_all') {
943
+ // Sequentially catch up missed slots capped at 10 runs
944
+ const catchUpSlots = [new Date(scheduledTime)];
945
+ let cursor = new Date(scheduledTime + 1000);
946
+ while (catchUpSlots.length < 10) {
947
+ const next = this.getNextOccurrence(schedule.cronExpression, schedule.timezone, cursor);
948
+ if (!next || next.getTime() > now.getTime())
949
+ break;
950
+ catchUpSlots.push(next);
951
+ cursor = new Date(next.getTime() + 1000);
952
+ }
953
+ for (const slot of catchUpSlots) {
954
+ await this.executeTarget(schedule, slot, true, claimToken, false);
955
+ }
956
+ // Advance nextRunAt to next future occurrence after last caught up slot
957
+ const lastSlotTime = catchUpSlots[catchUpSlots.length - 1].getTime();
958
+ await this.advanceNextRun(schedule, claimToken, lastSlotTime);
959
+ return;
960
+ }
961
+ }
962
+ // Normal on-time execution (diffMs <= 60_000)
963
+ await this.executeTarget(schedule, new Date(scheduledTime), false, claimToken, false);
964
+ // Advance nextRunAt using fresh schedule state
965
+ await this.advanceNextRun(schedule, claimToken, scheduledTime);
966
+ }
967
+ catch (err) {
968
+ // Emergency lease release and error logging if an unexpected failure occurs
969
+ try {
970
+ await this.advanceNextRun(schedule, claimToken, scheduledTime, undefined, 'failed', err?.message || 'Unexpected execution failure');
971
+ }
972
+ catch { }
973
+ }
974
+ }
975
+ async executeTarget(schedule, scheduledAt, isCatchUp, claimToken, isManual = false) {
976
+ const runId = (0, crypto_1.randomUUID)();
977
+ const startedAt = new Date();
978
+ const startedAtIso = startedAt.toISOString();
979
+ const scheduledAtIso = scheduledAt.toISOString();
980
+ // Insert 'running' run record
981
+ await this.db.run(`INSERT INTO _cron_runs (
982
+ id, scheduleId, scheduleName, targetType, targetId, scheduledAt, startedAt,
983
+ finishedAt, durationMs, status, isCatchUp, attempt, executionRefId, output, error
984
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, NULL, 0, 'running', ?, 1, NULL, NULL, NULL)`, runId, schedule.id, schedule.name, schedule.targetType, schedule.targetId, scheduledAtIso, startedAtIso, isCatchUp ? 1 : 0);
985
+ // Active lease renewal ticker (every 15s)
986
+ const renewalTimer = setInterval(() => {
987
+ if (this.isDisposed) {
988
+ clearInterval(renewalTimer);
989
+ return;
990
+ }
991
+ const newExpiry = new Date(Date.now() + 60_000).toISOString();
992
+ void this.db.run('UPDATE _cron_schedules SET leaseExpiresAt = ? WHERE id = ? AND claimToken = ?', newExpiry, schedule.id, claimToken);
993
+ }, 15_000);
994
+ this.activeRenewals.set(runId, renewalTimer);
995
+ let status = 'succeeded';
996
+ let output = null;
997
+ let error = null;
998
+ let executionRefId = null;
999
+ const maxRetries = Math.max(0, Math.min(schedule.maxRetries || 0, 5));
1000
+ const totalAttempts = 1 + maxRetries;
1001
+ let attemptNumber = 1;
1002
+ for (let attempt = 1; attempt <= totalAttempts; attempt++) {
1003
+ attemptNumber = attempt;
1004
+ status = 'succeeded';
1005
+ error = null;
1006
+ output = null;
1007
+ executionRefId = null;
1008
+ try {
1009
+ if (schedule.targetType === 'function') {
1010
+ if (!this.functionService) {
1011
+ throw new Error('FunctionService not available');
1012
+ }
1013
+ const cronCtx = {
1014
+ scheduleId: schedule.id,
1015
+ scheduleName: schedule.name,
1016
+ cronExpression: schedule.cronExpression,
1017
+ timezone: schedule.timezone,
1018
+ scheduledAt: scheduledAtIso,
1019
+ triggeredAt: startedAtIso,
1020
+ isCatchUp,
1021
+ };
1022
+ const fnResult = await this.functionService.executeScheduledFunction(schedule.targetId, cronCtx, schedule.payload);
1023
+ if (fnResult.status !== 'success' || fnResult.statusCode >= 400) {
1024
+ status = 'failed';
1025
+ error = fnResult.error || `Function returned status ${fnResult.statusCode}`;
1026
+ }
1027
+ output = fnResult.body !== undefined ? JSON.stringify(fnResult.body) : null;
1028
+ }
1029
+ else if (schedule.targetType === 'flow') {
1030
+ if (!this.flowService) {
1031
+ throw new Error('FlowService not available');
1032
+ }
1033
+ const flowResult = await this.flowService.executeFlow(schedule.targetId, schedule.payload || {}, { id: `cron:${schedule.id}`, isAdmin: true }, { wait: true, trusted: true });
1034
+ executionRefId = flowResult?.id || null;
1035
+ if (flowResult && flowResult.status !== 'succeeded') {
1036
+ status = 'failed';
1037
+ error = flowResult.error || `Flow execution ended with status '${flowResult.status}'`;
1038
+ }
1039
+ output = flowResult?.output !== undefined ? JSON.stringify(flowResult.output) : null;
1040
+ }
1041
+ else if (schedule.targetType === 'snapshot') {
1042
+ if (!this.snapshotService) {
1043
+ throw new Error('SnapshotService not available');
1044
+ }
1045
+ if (!this.snapshotService.isSupported()) {
1046
+ const providerName = this.db.dialect.name === 'sqlite' ? 'SQLite' : (this.db.dialect.name === 'postgres' ? 'PostgreSQL' : 'SQL Server');
1047
+ const errorMsg = `Scheduled snapshots are exclusive to embedded SQLite applications and are paused on ${providerName}.`;
1048
+ await this.db.run('UPDATE _cron_schedules SET enabled = 0, lastStatus = ?, lastError = ? WHERE id = ?', 'failed', errorMsg, schedule.id);
1049
+ throw new AppError_1.AppError(errorMsg, 400);
1050
+ }
1051
+ const cleanSchedId = schedule.id.toLowerCase().replace(/[^a-z0-9_-]/g, '-');
1052
+ const cleanNameSlug = schedule.name.toLowerCase().replace(/[^a-z0-9_-]/g, '-');
1053
+ const cleanName = `cron-${cleanSchedId}-${cleanNameSlug}-${Date.now()}`;
1054
+ const snap = await this.snapshotService.createSnapshot({
1055
+ name: cleanName,
1056
+ description: `Automated scheduled snapshot for '${schedule.name}' (${schedule.id})`,
1057
+ evictOldest: true,
1058
+ });
1059
+ executionRefId = snap.id;
1060
+ output = JSON.stringify({ snapshotId: snap.id, name: snap.name, size: snap.size });
1061
+ // Rolling Snapshot Retention: keepLast (scoped to immutable schedule ID)
1062
+ if (schedule.keepLast && schedule.keepLast > 0) {
1063
+ try {
1064
+ const prefix = `cron-${cleanSchedId}-`;
1065
+ const allSnaps = await this.snapshotService.listSnapshots();
1066
+ const matchingSnaps = (allSnaps || [])
1067
+ .filter((s) => s.name && s.name.startsWith(prefix))
1068
+ .sort((a, b) => new Date(b.created || b.createdAt || 0).getTime() - new Date(a.created || a.createdAt || 0).getTime());
1069
+ if (matchingSnaps.length > schedule.keepLast) {
1070
+ const toPrune = matchingSnaps.slice(schedule.keepLast);
1071
+ for (const oldSnap of toPrune) {
1072
+ try {
1073
+ await this.snapshotService.deleteSnapshot(oldSnap.id);
1074
+ }
1075
+ catch { }
1076
+ }
1077
+ }
1078
+ }
1079
+ catch (pruneErr) {
1080
+ console.warn(`[CronService] Failed to prune snapshot retention for '${schedule.id}':`, pruneErr);
1081
+ }
1082
+ }
1083
+ }
1084
+ else {
1085
+ status = 'failed';
1086
+ error = `Unsupported targetType '${schedule.targetType}'`;
1087
+ }
1088
+ }
1089
+ catch (err) {
1090
+ status = 'failed';
1091
+ error = err?.message || String(err);
1092
+ }
1093
+ if (status === 'succeeded') {
1094
+ break;
1095
+ }
1096
+ // If we failed and have retries remaining, wait with backoff
1097
+ if (attempt < totalAttempts && !this.isDisposed) {
1098
+ const backoffMs = Math.min(300 * Math.pow(2, attempt - 1), 3000);
1099
+ await new Promise((r) => setTimeout(r, backoffMs));
1100
+ }
1101
+ }
1102
+ try {
1103
+ clearInterval(renewalTimer);
1104
+ this.activeRenewals.delete(runId);
1105
+ }
1106
+ catch { }
1107
+ const finishedAt = new Date();
1108
+ const finishedAtIso = finishedAt.toISOString();
1109
+ const durationMs = Math.max(0, finishedAt.getTime() - startedAt.getTime());
1110
+ // Update run record
1111
+ await this.db.run(`UPDATE _cron_runs
1112
+ SET finishedAt = ?, durationMs = ?, status = ?, isCatchUp = ?, attempt = ?, executionRefId = ?, output = ?, error = ?
1113
+ WHERE id = ?`, finishedAtIso, durationMs, status, isCatchUp ? 1 : 0, attemptNumber, executionRefId, output, error, runId);
1114
+ // 1. Re-read latest schedule state from DB to avoid overwriting administrator updates
1115
+ const currentSchedule = await this.getSchedule(schedule.id);
1116
+ if (currentSchedule) {
1117
+ let consecutiveFailures = currentSchedule.consecutiveFailures || 0;
1118
+ let scheduleEnabled = currentSchedule.enabled;
1119
+ let scheduleError = error;
1120
+ if (status === 'succeeded') {
1121
+ consecutiveFailures = 0;
1122
+ }
1123
+ else {
1124
+ consecutiveFailures += 1;
1125
+ const pauseThreshold = currentSchedule.autoPauseAfterFailures || 0;
1126
+ if (pauseThreshold > 0 && consecutiveFailures >= pauseThreshold) {
1127
+ scheduleEnabled = false;
1128
+ scheduleError = `Auto-paused: reached ${pauseThreshold} consecutive failures (${error || 'Unknown error'})`;
1129
+ if (this.eventBus) {
1130
+ try {
1131
+ this.eventBus.emit('cron:autopause', {
1132
+ scheduleId: currentSchedule.id,
1133
+ scheduleName: currentSchedule.name,
1134
+ consecutiveFailures,
1135
+ error: scheduleError,
1136
+ });
1137
+ }
1138
+ catch { }
1139
+ }
1140
+ }
1141
+ }
1142
+ // 2. Guard schedule completion update with active claimToken (or direct id for manual trigger)
1143
+ if (isManual) {
1144
+ await this.db.run(`UPDATE _cron_schedules
1145
+ SET lastRunAt = ?, lastStatus = ?, lastError = ?, consecutiveFailures = ?, enabled = ?
1146
+ WHERE id = ?`, startedAtIso, status, scheduleError, consecutiveFailures, scheduleEnabled ? 1 : 0, currentSchedule.id);
1147
+ }
1148
+ else {
1149
+ await this.db.run(`UPDATE _cron_schedules
1150
+ SET lastRunAt = ?, lastStatus = ?, lastError = ?, consecutiveFailures = ?, enabled = ?
1151
+ WHERE id = ? AND claimToken = ?`, startedAtIso, status, scheduleError, consecutiveFailures, scheduleEnabled ? 1 : 0, currentSchedule.id, claimToken);
1152
+ }
1153
+ }
1154
+ // Prune run history (keep last 100 runs per schedule)
1155
+ try {
1156
+ const cutRow = await this.db.get('SELECT startedAt FROM _cron_runs WHERE scheduleId = ? ORDER BY startedAt DESC LIMIT 1 OFFSET 100', schedule.id);
1157
+ if (cutRow && cutRow.startedAt) {
1158
+ await this.db.run('DELETE FROM _cron_runs WHERE scheduleId = ? AND startedAt < ?', schedule.id, cutRow.startedAt);
1159
+ }
1160
+ }
1161
+ catch { }
1162
+ const runLog = {
1163
+ id: runId,
1164
+ scheduleId: schedule.id,
1165
+ scheduleName: schedule.name,
1166
+ targetType: schedule.targetType,
1167
+ targetId: schedule.targetId,
1168
+ scheduledAt: scheduledAtIso,
1169
+ startedAt: startedAtIso,
1170
+ finishedAt: finishedAtIso,
1171
+ durationMs,
1172
+ status,
1173
+ isCatchUp,
1174
+ attempt: attemptNumber,
1175
+ executionRefId,
1176
+ output,
1177
+ error,
1178
+ };
1179
+ if (this.eventBus) {
1180
+ try {
1181
+ this.eventBus.emit('cron:run', runLog);
1182
+ }
1183
+ catch { }
1184
+ }
1185
+ return runLog;
1186
+ }
1187
+ // ==========================================
1188
+ // Row Mappers
1189
+ // ==========================================
1190
+ mapRowToSchedule(row) {
1191
+ let payload = undefined;
1192
+ if (row.payload !== null && row.payload !== undefined) {
1193
+ if (typeof row.payload === 'string') {
1194
+ try {
1195
+ payload = JSON.parse(row.payload);
1196
+ }
1197
+ catch {
1198
+ payload = row.payload;
1199
+ }
1200
+ }
1201
+ else {
1202
+ payload = row.payload;
1203
+ }
1204
+ }
1205
+ return {
1206
+ id: String(row.id),
1207
+ name: String(row.name),
1208
+ targetType: row.targetType,
1209
+ targetId: String(row.targetId),
1210
+ cronExpression: String(row.cronExpression),
1211
+ humanDescription: CronParser_1.CronParser.humanize(String(row.cronExpression)),
1212
+ timezone: String(row.timezone || 'UTC'),
1213
+ missedRunPolicy: (row.missedRunPolicy || 'skip'),
1214
+ payload,
1215
+ isSystemBound: Boolean(row.isSystemBound),
1216
+ enabled: Boolean(row.enabled),
1217
+ nextRunAt: row.nextRunAt ? String(row.nextRunAt) : null,
1218
+ lastRunAt: row.lastRunAt ? String(row.lastRunAt) : null,
1219
+ lastStatus: row.lastStatus ? row.lastStatus : null,
1220
+ lastError: row.lastError ? String(row.lastError) : null,
1221
+ leaseOwner: row.leaseOwner ? String(row.leaseOwner) : null,
1222
+ leaseExpiresAt: row.leaseExpiresAt ? String(row.leaseExpiresAt) : null,
1223
+ claimToken: row.claimToken ? String(row.claimToken) : null,
1224
+ maxRetries: Number(row.maxRetries || 0),
1225
+ autoPauseAfterFailures: Number(row.autoPauseAfterFailures || 0),
1226
+ consecutiveFailures: Number(row.consecutiveFailures || 0),
1227
+ expiresAt: row.expiresAt ? String(row.expiresAt) : null,
1228
+ keepLast: row.keepLast !== null && row.keepLast !== undefined ? Number(row.keepLast) : null,
1229
+ created: String(row.created),
1230
+ updated: String(row.updated),
1231
+ };
1232
+ }
1233
+ mapRowToRun(row) {
1234
+ return {
1235
+ id: String(row.id),
1236
+ scheduleId: String(row.scheduleId),
1237
+ scheduleName: String(row.scheduleName),
1238
+ targetType: row.targetType,
1239
+ targetId: String(row.targetId),
1240
+ scheduledAt: String(row.scheduledAt),
1241
+ startedAt: String(row.startedAt),
1242
+ finishedAt: row.finishedAt ? String(row.finishedAt) : null,
1243
+ durationMs: Number(row.durationMs || 0),
1244
+ status: row.status,
1245
+ isCatchUp: Boolean(row.isCatchUp),
1246
+ attempt: Number(row.attempt || 1),
1247
+ executionRefId: row.executionRefId ? String(row.executionRefId) : null,
1248
+ output: row.output ? String(row.output) : null,
1249
+ error: row.error ? String(row.error) : null,
1250
+ };
1251
+ }
1252
+ }
1253
+ exports.CronService = CronService;
1254
+ //# sourceMappingURL=CronService.js.map