registry.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. import type { CronEventBusPort } from './host-ports.js';
  2. import {
  3. logger,
  4. backgroundCtx,
  5. getMetricsReporter,
  6. AppError,
  7. getCronStore,
  8. type CronHostUtils,
  9. } from './host-utils.js';
  10. import type { CronExecutor, ExecuteResult } from './executor.js';
  11. import type { CronConfig, CronTaskState, CronConfigUpdate, SessionConfig } from './types.js';
  12. /** Bounded origin of a cron config mutation. Keep this low-cardinality. */
  13. export type CronMutationSource = 'ui' | 'agent_tool' | 'http_api' | 'system';
  14. /** Bounded origin of a cron trigger attempt. */
  15. export type CronTriggerSource = 'schedule' | 'ui' | 'agent_tool' | 'http_api' | 'system';
  16. /** Semantic delivery target. Never put the concrete session id into metrics labels. */
  17. export type CronDeliveryTarget = 'new' | 'root' | 'me' | 'session_id';
  18. export interface CronMutationMetricsContext {
  19. mutationSource?: CronMutationSource;
  20. deliveryTarget?: CronDeliveryTarget;
  21. }
  22. export interface CronTriggerMetricsContext {
  23. triggerSource?: CronTriggerSource;
  24. deliveryTarget?: CronDeliveryTarget;
  25. }
  26. export interface CronRegistryOptions {
  27. /**
  28. * Unreference Croner timers so short-lived embedded hosts can finish after
  29. * serving a one-shot request. Long-lived daemon hosts keep the default false.
  30. */
  31. unrefTimers?: boolean;
  32. scheduler: CronSchedulerPort;
  33. cronHost?: CronHostUtils;
  34. }
  35. export interface CronRegistryStartOptions {
  36. /**
  37. * Whether tasks restored from disk may execute immediately. A quarantined
  38. * clone still registers tasks for inspection and later user mutations.
  39. */
  40. restoredTaskExecution?: 'enabled' | 'quarantined';
  41. }
  42. export interface CronJobPort {
  43. nextRun(): Date | null;
  44. stop(): void;
  45. }
  46. export interface CronSchedulerPort {
  47. createJob(
  48. config: CronConfig,
  49. options: { unref?: boolean | undefined },
  50. onTick: () => void,
  51. ): CronJobPort;
  52. assertSchedulable(config: CronConfig): void;
  53. }
  54. export class CronRegistry {
  55. private readonly tasks: Map<string, { state: CronTaskState; job: CronJobPort }> = new Map();
  56. private globalEnabled = true;
  57. private eventBus: CronEventBusPort | null = null;
  58. constructor(
  59. executor: CronExecutor,
  60. eventBus: CronEventBusPort | undefined,
  61. options: CronRegistryOptions,
  62. );
  63. constructor(
  64. private readonly executor: CronExecutor,
  65. eventBus?: CronEventBusPort,
  66. private readonly options: Partial<CronRegistryOptions> = {},
  67. ) {
  68. this.eventBus = eventBus ?? null;
  69. }
  70. private get scheduler(): CronSchedulerPort {
  71. const scheduler = this.options.scheduler;
  72. if (!scheduler) {
  73. throw new AppError(
  74. '[@mavis/cron] CronRegistry requires a host-provided CronSchedulerPort. ' +
  75. 'Runtime hosts must inject a scheduler instead of relying on agent-core timers.',
  76. 'CRON_SCHEDULER_MISSING',
  77. 500,
  78. );
  79. }
  80. return scheduler;
  81. }
  82. private get cronStore() {
  83. return this.options.cronHost?.cronStore ?? getCronStore();
  84. }
  85. /** Scan disk, register all cron jobs. Called once at startup. */
  86. async start(startOptions: CronRegistryStartOptions = {}): Promise<void> {
  87. this.assertSchedulerConfigured();
  88. const cronStore = this.cronStore;
  89. const configs = await cronStore.listAll();
  90. for (const { agentName, cronName, config, cronId } of configs) {
  91. const key = this.taskKey(agentName, cronName);
  92. const state: CronTaskState = {
  93. agentName,
  94. cronName,
  95. config,
  96. ...(cronId ? { cronId } : {}),
  97. enabled: startOptions.restoredTaskExecution !== 'quarantined' && !config.disabled,
  98. lastRun: null,
  99. lastResult: null,
  100. lastError: null,
  101. nextRun: null,
  102. status: 'idle',
  103. };
  104. try {
  105. const job = this.createJob(config, state);
  106. state.nextRun = job.nextRun()?.getTime() ?? null;
  107. this.tasks.set(key, { state, job });
  108. logger.info(
  109. { agentName, cronName, schedule: config.schedule, nextRun: state.nextRun },
  110. '[cron] Task registered',
  111. );
  112. } catch (err) {
  113. logger.error(
  114. { agentName, cronName, schedule: config.schedule, err: (err as Error).message },
  115. '[cron] Failed to register task — invalid schedule?',
  116. );
  117. }
  118. }
  119. logger.info(backgroundCtx(), `[cron] Registry started, count=${this.tasks.size}`);
  120. getMetricsReporter().incr('cron_engine_started_total');
  121. // Fire-and-forget: at startup, sweep every cron's persisted session
  122. // history to apply retention policy that was previously dependent on
  123. // an in-memory map and therefore lost across daemon restarts.
  124. const sweepCtx = backgroundCtx();
  125. logger.info(sweepCtx, '[cron] Startup session retention sweep — begin');
  126. void this.executor
  127. .cleanupAllCronSessions()
  128. .then(() => {
  129. logger.info(sweepCtx, '[cron] Startup session retention sweep — done');
  130. })
  131. .catch((err: unknown) => {
  132. logger.warn(
  133. sweepCtx,
  134. `[cron] Startup session retention sweep failed (non-fatal), err=${(err as Error).message}`,
  135. );
  136. });
  137. // Fire-and-forget: delete sessions whose purpose matches a cron task
  138. // that no longer exists (orphans from older deletion logic that didn't
  139. // sweep the session store by purpose).
  140. //
  141. // Build aliveKeys from `configs` (config files present on disk) rather
  142. // than `this.tasks` (jobs that successfully constructed). A cron whose
  143. // schedule/timezone temporarily fails Croner validation must NOT have its
  144. // session history wiped — the config file is still present, the user
  145. // hasn't deleted the task, only registration failed.
  146. const aliveKeys = new Set(
  147. configs.map(({ agentName, cronName }) => this.taskKey(agentName, cronName)),
  148. );
  149. void this.executor
  150. .cleanupOrphanCronSessions(aliveKeys)
  151. .then(() => {
  152. logger.debug(backgroundCtx(), '[cron] Orphan cron session cleanup — done');
  153. })
  154. .catch((err: unknown) => {
  155. logger.warn(
  156. backgroundCtx(),
  157. `[cron] Orphan cron session cleanup failed (non-fatal), err=${(err as Error).message}`,
  158. );
  159. });
  160. }
  161. /** Stop all cron jobs. */
  162. stop(): void {
  163. for (const [key, { job }] of this.tasks) {
  164. job.stop();
  165. logger.debug(backgroundCtx(), `[cron] Job stopped, key=${key}`);
  166. }
  167. this.tasks.clear();
  168. logger.info(backgroundCtx(), '[cron] Registry stopped');
  169. }
  170. /** List all tasks for a given agent. */
  171. listTasks(agentName: string): CronTaskState[] {
  172. const result: CronTaskState[] = [];
  173. for (const { state, job } of this.tasks.values()) {
  174. if (state.agentName === agentName) {
  175. state.nextRun = job.nextRun()?.getTime() ?? null;
  176. result.push(state);
  177. }
  178. }
  179. return result;
  180. }
  181. /** Get a specific task by agent name and cron name. */
  182. getTask(agentName: string, cronName: string): CronTaskState | undefined {
  183. const entry = this.tasks.get(this.taskKey(agentName, cronName));
  184. if (entry) {
  185. entry.state.nextRun = entry.job.nextRun()?.getTime() ?? null;
  186. }
  187. return entry?.state;
  188. }
  189. /** Trigger a task immediately (manual trigger via API). */
  190. async triggerTask(
  191. agentName: string,
  192. cronName: string,
  193. context: CronTriggerMetricsContext = {},
  194. ): Promise<ExecuteResult> {
  195. const entry = this.tasks.get(this.taskKey(agentName, cronName));
  196. if (!entry) {
  197. throw new AppError(
  198. `Cron task '${cronName}' not found for agent '${agentName}'`,
  199. 'CRON_TASK_NOT_FOUND',
  200. 404,
  201. );
  202. }
  203. const result = await this.executeAndRecordTrigger(entry.state, {
  204. triggerSource: context.triggerSource ?? 'http_api',
  205. deliveryTarget: context.deliveryTarget,
  206. force: true,
  207. });
  208. if (entry.state.config.scheduleType === 'once') {
  209. await this.completeOnceAfterExecution(agentName, cronName, result);
  210. }
  211. return result;
  212. }
  213. /**
  214. * Update cron task configuration — persists to config.yaml and updates in-memory state.
  215. * If schedule or timezone changed, recreates the Cron job (new job created before old one stopped).
  216. */
  217. async updateConfig(
  218. agentName: string,
  219. cronName: string,
  220. update: CronConfigUpdate,
  221. context: CronMutationMetricsContext = {},
  222. ): Promise<CronTaskState | undefined> {
  223. const cronStore = this.cronStore;
  224. const key = this.taskKey(agentName, cronName);
  225. const entry = this.tasks.get(key);
  226. if (!entry) return undefined;
  227. const oldConfig = entry.state.config;
  228. const needsRecreate = update.schedule !== undefined || update.timezone !== undefined;
  229. if (needsRecreate) {
  230. this.assertCronConfigSchedulable(applyCronScheduleUpdate(oldConfig, update));
  231. }
  232. const newConfig = await cronStore.update(agentName, cronName, update);
  233. if (needsRecreate) {
  234. // Create new job first — if this throws (invalid schedule), old job remains running
  235. const newJob = this.createJob(newConfig, entry.state);
  236. // Success — stop old job and replace
  237. entry.job.stop();
  238. entry.job = newJob;
  239. entry.state.nextRun = newJob.nextRun()?.getTime() ?? null;
  240. }
  241. // Update in-memory state
  242. entry.state.config = newConfig;
  243. entry.state.enabled = !newConfig.disabled;
  244. this.eventBus?.emit('cron.updated', 'cron-registry', { agentName, cronName });
  245. getMetricsReporter().incr(
  246. 'cron_task_updated_total',
  247. cronMutationMetricLabels(entry.state, context),
  248. );
  249. return entry.state;
  250. }
  251. async createTask(
  252. agentName: string,
  253. cronName: string,
  254. config: CronConfig,
  255. context: CronMutationMetricsContext = {},
  256. ): Promise<CronTaskState> {
  257. const cronStore = this.cronStore;
  258. const key = this.taskKey(agentName, cronName);
  259. if (this.tasks.has(key)) {
  260. throw new AppError(
  261. `Cron task already registered: ${agentName}/${cronName}`,
  262. 'CRON_TASK_EXISTS',
  263. 409,
  264. );
  265. }
  266. this.assertCronConfigSchedulable(config);
  267. await cronStore.create(agentName, cronName, config);
  268. // Surface the store-minted cron_id (archon_biz cron contract parity).
  269. // `create` returns only the config, so resolve the id via a best-effort
  270. // read-back; failure is non-fatal and simply leaves cronId undefined
  271. // (engine keying is unchanged either way).
  272. const cronId = await this.resolveCreatedCronId(agentName, cronName);
  273. const state: CronTaskState = {
  274. agentName,
  275. cronName,
  276. config,
  277. ...(cronId ? { cronId } : {}),
  278. enabled: !config.disabled,
  279. lastRun: null,
  280. lastResult: null,
  281. lastError: null,
  282. nextRun: null,
  283. status: 'idle',
  284. };
  285. const job = this.createJob(config, state);
  286. state.nextRun = job.nextRun()?.getTime() ?? null;
  287. this.tasks.set(key, { state, job });
  288. logger.info(
  289. { agentName, cronName, schedule: config.schedule, nextRun: state.nextRun },
  290. '[cron] Task created',
  291. );
  292. this.eventBus?.emit('cron.created', 'cron-registry', { agentName, cronName });
  293. getMetricsReporter().incr('cron_task_created_total', cronMutationMetricLabels(state, context));
  294. return state;
  295. }
  296. /** Delete a cron task — stops the job and removes from disk. */
  297. async deleteTask(
  298. agentName: string,
  299. cronName: string,
  300. context: CronMutationMetricsContext = {},
  301. ): Promise<boolean> {
  302. const cronStore = this.cronStore;
  303. const key = this.taskKey(agentName, cronName);
  304. const entry = this.tasks.get(key);
  305. if (!entry) return false;
  306. entry.job.stop();
  307. this.tasks.delete(key);
  308. const cancelledQueued = this.executor.cancelQueuedCron?.(agentName, cronName) ?? 0;
  309. if (cancelledQueued > 0) {
  310. logger.info(
  311. backgroundCtx(),
  312. `[cron] Cancelled queued messages for deleted task, agentName=${agentName}, cronName=${cronName}, count=${cancelledQueued}`,
  313. );
  314. }
  315. // Archive cron-created sessions before removing history
  316. try {
  317. await this.executor.cleanupSessionsOnDelete(agentName, cronName);
  318. } catch (err) {
  319. logger.warn(
  320. backgroundCtx(),
  321. `[cron] Session cleanup on delete failed (non-fatal), agentName=${agentName}, cronName=${cronName}, err=${(err as Error).message}`,
  322. );
  323. }
  324. // Delegate file deletion to the store
  325. await cronStore.delete(agentName, cronName);
  326. logger.info(
  327. backgroundCtx(),
  328. `[cron] Task deleted, agentName=${agentName}, cronName=${cronName}`,
  329. );
  330. this.eventBus?.emit('cron.deleted', 'cron-registry', { agentName, cronName });
  331. getMetricsReporter().incr(
  332. 'cron_task_deleted_total',
  333. cronMutationMetricLabels(entry.state, context),
  334. );
  335. return true;
  336. }
  337. /** Get session run history for a cron task (oldest-first). */
  338. async getSessionHistory(
  339. agentName: string,
  340. cronName: string,
  341. ): ReturnType<ReturnType<typeof getCronStore>['getSessionHistory']> {
  342. const cronStore = this.cronStore;
  343. return cronStore.getSessionHistory(agentName, cronName);
  344. }
  345. /** List all tasks across all agents. */
  346. listAllTasks(): CronTaskState[] {
  347. const result: CronTaskState[] = [];
  348. for (const { state, job } of this.tasks.values()) {
  349. state.nextRun = job.nextRun()?.getTime() ?? null;
  350. result.push(state);
  351. }
  352. return result;
  353. }
  354. /** Set global enabled flag. */
  355. setGlobalEnabled(enabled: boolean): void {
  356. this.globalEnabled = enabled;
  357. logger.info(backgroundCtx(), `[cron] Global enabled flag changed, enabled=${enabled}`);
  358. }
  359. /** Get global enabled flag. */
  360. isGlobalEnabled(): boolean {
  361. return this.globalEnabled;
  362. }
  363. // ── Harness registration ──
  364. /**
  365. * Register cron tasks from a harness's crons directory.
  366. */
  367. async registerHarnessCrons(harnessName: string, agentNameList: string[]): Promise<string[]> {
  368. this.assertSchedulerConfigured();
  369. const cronStore = this.cronStore;
  370. const registered: string[] = [];
  371. for (const agentName of agentNameList) {
  372. const configs = await cronStore.listByAgent(agentName);
  373. for (const { cronName, config, cronId } of configs) {
  374. try {
  375. // Register or update in-memory timer
  376. const key = this.taskKey(agentName, cronName);
  377. if (this.tasks.has(key)) {
  378. // Task already loaded — re-sync config and possibly recreate timer
  379. const existing = this.tasks.get(key)!;
  380. const oldConfig = existing.state.config;
  381. const needsRecreate =
  382. oldConfig.schedule !== config.schedule || oldConfig.timezone !== config.timezone;
  383. if (needsRecreate) {
  384. const newJob = this.createJob(config, existing.state);
  385. existing.job.stop();
  386. existing.job = newJob;
  387. existing.state.nextRun = newJob.nextRun()?.getTime() ?? null;
  388. }
  389. existing.state.config = config;
  390. existing.state.enabled = !config.disabled;
  391. this.eventBus?.emit('cron.updated', 'cron-registry', { agentName, cronName });
  392. } else {
  393. // New task — create in-memory timer
  394. const state: CronTaskState = {
  395. agentName,
  396. cronName,
  397. config,
  398. ...(cronId ? { cronId } : {}),
  399. enabled: !config.disabled,
  400. lastRun: null,
  401. lastResult: null,
  402. lastError: null,
  403. nextRun: null,
  404. status: 'idle',
  405. };
  406. const job = this.createJob(config, state);
  407. state.nextRun = job.nextRun()?.getTime() ?? null;
  408. this.tasks.set(key, { state, job });
  409. logger.info(
  410. { agentName, cronName, schedule: config.schedule, nextRun: state.nextRun },
  411. '[cron] Task created',
  412. );
  413. this.eventBus?.emit('cron.created', 'cron-registry', { agentName, cronName });
  414. }
  415. registered.push(cronName);
  416. } catch (err) {
  417. logger.error(
  418. { harnessName, cronName, err: (err as Error).message },
  419. '[cron] Failed to register harness cron timer',
  420. );
  421. }
  422. }
  423. }
  424. if (registered.length > 0) {
  425. logger.info(
  426. backgroundCtx(),
  427. `[cron] Harness crons registered, harnessName=${harnessName}, count=${registered.length}`,
  428. );
  429. }
  430. return registered;
  431. }
  432. /**
  433. * Remove all cron tasks registered by a specific harness.
  434. * Delegates symlink cleanup to CronStore, then stops in-memory timers.
  435. */
  436. async unregisterHarnessCrons(harnessName: string): Promise<string[]> {
  437. // 1. Stop in-memory timers for matching tasks
  438. const exactPrefix = `${harnessName}:`;
  439. const reinPrefix = `${harnessName}--`;
  440. const toRemove: Array<{ agentName: string; cronName: string }> = [];
  441. for (const [key, { state }] of this.tasks) {
  442. if (key.startsWith(exactPrefix) || key.startsWith(reinPrefix)) {
  443. toRemove.push({ agentName: state.agentName, cronName: state.cronName });
  444. }
  445. }
  446. const removed: string[] = [];
  447. for (const { agentName, cronName } of toRemove) {
  448. const key = this.taskKey(agentName, cronName);
  449. const entry = this.tasks.get(key);
  450. if (entry) {
  451. entry.job.stop();
  452. this.tasks.delete(key);
  453. this.eventBus?.emit('cron.deleted', 'cron-registry', { agentName, cronName });
  454. removed.push(cronName);
  455. }
  456. }
  457. if (removed.length > 0) {
  458. logger.info(
  459. backgroundCtx(),
  460. `[cron] Harness crons unregistered, harnessName=${harnessName}, count=${removed.length}`,
  461. );
  462. }
  463. return removed;
  464. }
  465. // ── Private ──
  466. private createJob(config: CronConfig, state: CronTaskState): CronJobPort {
  467. const { agentName, cronName } = state;
  468. return this.scheduler.createJob(config, { unref: this.options.unrefTimers }, () => {
  469. if (!this.globalEnabled) return;
  470. this.executeAndRecordTrigger(state, { triggerSource: 'schedule' })
  471. .then((result) => {
  472. if (state.config.scheduleType === 'once') {
  473. void this.completeOnceAfterExecution(agentName, cronName, result).catch(
  474. (err: unknown) => {
  475. logger.error(
  476. { agentName, cronName, err: (err as Error).message },
  477. '[cron] Failed to complete once task',
  478. );
  479. },
  480. );
  481. }
  482. })
  483. .catch((err: unknown) => {
  484. logger.error(
  485. { agentName, cronName, err: (err as Error).message },
  486. '[cron] Unhandled execution error',
  487. );
  488. });
  489. });
  490. }
  491. private async executeAndRecordTrigger(
  492. state: CronTaskState,
  493. context: CronTriggerMetricsContext & { force?: boolean },
  494. ): Promise<ExecuteResult> {
  495. const triggerSource = context.triggerSource ?? 'schedule';
  496. const result = await this.executor.execute(state, { force: context.force });
  497. getMetricsReporter().incr('cron_task_triggered_total', {
  498. trigger_source: triggerSource,
  499. trigger_outcome: cronTriggerOutcome(result),
  500. ...cronTaskMetricLabels(state, context.deliveryTarget),
  501. });
  502. return result;
  503. }
  504. private async completeOnceAfterExecution(
  505. agentName: string,
  506. cronName: string,
  507. result: ExecuteResult,
  508. ): Promise<void> {
  509. if (result.executed) {
  510. await this.completeOnceTask(agentName, cronName);
  511. return;
  512. }
  513. if (result.reason !== 'enqueued' || !result.queuedSend) return;
  514. void result.queuedSend.then((drainResult) => {
  515. if (drainResult !== 'sent') return;
  516. return this.completeOnceTask(agentName, cronName).catch((err: unknown) => {
  517. logger.error(
  518. { agentName, cronName, err: (err as Error).message },
  519. '[cron] Failed to complete once task after queued send',
  520. );
  521. });
  522. });
  523. }
  524. private async completeOnceTask(agentName: string, cronName: string): Promise<void> {
  525. const key = this.taskKey(agentName, cronName);
  526. const entry = this.tasks.get(key);
  527. if (!entry || entry.state.config.scheduleType !== 'once') return;
  528. if (entry.state.config.deleteAfterRun === false) return;
  529. entry.job.stop();
  530. this.tasks.delete(key);
  531. await this.cronStore.delete(agentName, cronName);
  532. getMetricsReporter().incr(
  533. 'cron_task_deleted_total',
  534. cronMutationMetricLabels(entry.state, { mutationSource: 'system' }),
  535. );
  536. logger.info(
  537. backgroundCtx(),
  538. `[cron] Once task completed and deleted, agentName=${agentName}, cronName=${cronName}`,
  539. );
  540. this.eventBus?.emit('cron.deleted', 'cron-registry', { agentName, cronName });
  541. }
  542. private assertCronConfigSchedulable(config: CronConfig): void {
  543. try {
  544. this.scheduler.assertSchedulable(config);
  545. } catch (err) {
  546. if (err instanceof AppError) throw err;
  547. throw new AppError(err instanceof Error ? err.message : String(err), 'VALIDATION_ERROR', 400);
  548. }
  549. }
  550. private assertSchedulerConfigured(): void {
  551. void this.scheduler;
  552. }
  553. private taskKey(agentName: string, cronName: string): string {
  554. return `${agentName}:${cronName}`;
  555. }
  556. /**
  557. * Best-effort resolution of a freshly created cron's stable cron_id.
  558. * `CronStorePort.create` returns only the config, so we read the id back
  559. * from `listByAgent` (the only required port method that carries cronId).
  560. * Any failure is swallowed — cronId is purely additive metadata and the
  561. * engine never keys on it.
  562. */
  563. private async resolveCreatedCronId(
  564. agentName: string,
  565. cronName: string,
  566. ): Promise<string | undefined> {
  567. try {
  568. const list = await this.cronStore.listByAgent(agentName);
  569. return list.find((entry) => entry.cronName === cronName)?.cronId;
  570. } catch {
  571. return undefined;
  572. }
  573. }
  574. }
  575. function cronMutationMetricLabels(
  576. state: CronTaskState,
  577. context: CronMutationMetricsContext,
  578. ): Record<string, string> {
  579. return {
  580. mutation_source: context.mutationSource ?? 'http_api',
  581. ...cronTaskMetricLabels(state, context.deliveryTarget),
  582. };
  583. }
  584. function cronTaskMetricLabels(
  585. state: CronTaskState,
  586. deliveryTarget?: CronDeliveryTarget,
  587. ): Record<string, string> {
  588. return {
  589. owner_agent: state.agentName,
  590. schedule_type: state.config.scheduleType ?? 'cron',
  591. delivery_target: deliveryTarget ?? deliveryTargetForSession(state.config.session),
  592. };
  593. }
  594. function deliveryTargetForSession(session: SessionConfig): CronDeliveryTarget {
  595. if (session.mode === 'new') return 'new';
  596. if (session.mode === 'root') return 'root';
  597. return 'session_id';
  598. }
  599. function cronTriggerOutcome(result: ExecuteResult): string {
  600. if (result.executed) return 'executed';
  601. if (result.reason === 'enqueued') return 'enqueued';
  602. if (result.reason === 'error') return 'error';
  603. return 'skipped';
  604. }
  605. function applyCronScheduleUpdate(config: CronConfig, update: CronConfigUpdate): CronConfig {
  606. return {
  607. ...config,
  608. ...(update.schedule !== undefined ? { schedule: update.schedule } : {}),
  609. ...(update.timezone !== undefined
  610. ? update.timezone === null
  611. ? { timezone: undefined }
  612. : { timezone: update.timezone }
  613. : {}),
  614. };
  615. }