@brickkit/core 0.13.2 → 0.14.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.
@@ -84,6 +84,139 @@ declare const crudEventName: (resource: string, operation: CrudEventOperation) =
84
84
  declare const crudEventSource: (service: string, resource: string) => string;
85
85
  /** Whether `name` is the CRUD event of one of `resources`. */
86
86
  declare function isCrudEvent(name: string, resources: readonly string[]): boolean;
87
+ /** A parsed cron expression: the allowed values of each field. */
88
+ interface CronExpression {
89
+ readonly source: string;
90
+ readonly seconds: ReadonlySet<number>;
91
+ readonly minutes: ReadonlySet<number>;
92
+ readonly hours: ReadonlySet<number>;
93
+ readonly days: ReadonlySet<number>;
94
+ readonly months: ReadonlySet<number>;
95
+ /** 0 is Sunday. */
96
+ readonly weekdays: ReadonlySet<number>;
97
+ /** Both day fields are restricted: a day matches when either does. */
98
+ readonly eitherDay: boolean;
99
+ }
100
+ /** What a schedule's `run` receives: which run this is. */
101
+ interface ScheduleRun {
102
+ /** The schedule's name. */
103
+ schedule: string;
104
+ /**
105
+ * When this run was due, as an ISO timestamp: the cron time, the end of the
106
+ * interval, or the moment someone triggered it. Retries of a failed run keep it.
107
+ */
108
+ slot: string;
109
+ /** `manual` when started with `schedules.trigger(name)` or `brick schedules run`. */
110
+ trigger: "schedule" | "manual";
111
+ /** 1 on the first try, 2 on the first retry, and so on. */
112
+ attempt: number;
113
+ /** `<schedule>:<slot>`: the same on every retry, for idempotency keys. */
114
+ runKey: string;
115
+ }
116
+ /** What a schedule's workflow receives: the run, without `attempt` (a run starts one workflow however often it is tried). */
117
+ type ScheduleWorkflowRun = Omit<ScheduleRun, "attempt">;
118
+ /** A function marked `"use workflow"`, started once per run of the schedule it is given to. */
119
+ type ScheduleWorkflow = (run: ScheduleWorkflowRun) => Promise<unknown>;
120
+ type When = {
121
+ /**
122
+ * A cron expression: `"0 2 * * *"` is 02:00 every day. Five fields, or six
123
+ * with seconds first; `@daily` and the other macros work too.
124
+ */
125
+ cron: string;
126
+ /** The IANA time zone `cron` is read in, such as `"Europe/Berlin"`. Default `"UTC"`. */
127
+ timeZone?: string;
128
+ every?: never;
129
+ } | {
130
+ /**
131
+ * Run again this long after the last successful run finished: `"6h"`,
132
+ * `"15m"`, `"1h30m"`, or milliseconds. The first run is due as soon as a
133
+ * process starts the schedules.
134
+ */
135
+ every: string | number;
136
+ cron?: never;
137
+ timeZone?: never;
138
+ };
139
+ /** What `defineSchedule` takes. */
140
+ type ScheduleConfig = When & {
141
+ /** Unique among the app's schedules, and the key its state is stored under: renaming it starts it afresh. */
142
+ name: string;
143
+ /**
144
+ * A due time that passed while no process ran the schedules (or one more
145
+ * than a minute late): `"once"` (the default) runs it once, however many
146
+ * were missed; `"skip"` skips it and waits for the next.
147
+ */
148
+ catchUp?: "once" | "skip";
149
+ /** Tries per due time, the first included. Default 3. */
150
+ maxAttempts?: number;
151
+ /** The wait before the first retry, doubling on each retry after it; 0 retries at once. Default `"1m"`. */
152
+ backoff?: string | number;
153
+ /** A random delay of up to this much, added to every due time, so many processes or apps do not all start at once. */
154
+ jitter?: string | number;
155
+ /** `false` keeps the schedule from running on its own; `trigger` still runs it. Default `true`. */
156
+ enabled?: boolean;
157
+ } & ({
158
+ /** Runs in the process that claims the due time. Throwing retries it. */
159
+ run: (run: ScheduleRun) => void | Promise<void>;
160
+ workflow?: never;
161
+ } | {
162
+ /**
163
+ * A durable workflow started for each due time, on the app's
164
+ * `events.world`. The run counts as done once the workflow started; the
165
+ * workflow retries its own steps.
166
+ */
167
+ workflow: ScheduleWorkflow;
168
+ run?: never;
169
+ });
170
+ /** A schedule, made by `defineSchedule`. */
171
+ interface Schedule {
172
+ readonly name: string;
173
+ readonly cron?: CronExpression;
174
+ readonly timeZone?: string;
175
+ /** The interval, in milliseconds. */
176
+ readonly every?: number;
177
+ readonly catchUp: "once" | "skip";
178
+ readonly maxAttempts: number;
179
+ readonly backoffMs: number;
180
+ readonly jitterMs: number;
181
+ readonly enabled: boolean;
182
+ readonly run?: (run: ScheduleRun) => void | Promise<void>;
183
+ readonly workflow?: ScheduleWorkflow;
184
+ /** What decides the due times, as stored with them: a change makes the next one be worked out again. */
185
+ readonly spec: string;
186
+ }
187
+ /**
188
+ * Define a schedule: code that runs at set times, in one process among all
189
+ * those that run the app. Pass it to `brick({ events: { schedules } })`.
190
+ *
191
+ * It runs either on a `cron` expression, at fixed wall-clock times in a time
192
+ * zone, or `every` so long, counted from the end of the last successful run.
193
+ * State lives in the app's `scheduleTable()`, so a due time runs once however
194
+ * many processes there are, and a restart or deploy carries on where it
195
+ * stopped. A due time counts as done only once its run succeeds: a run that
196
+ * throws is retried with a growing delay, and one whose process died is taken
197
+ * over by another process. A run is never started while the last one is still
198
+ * running; due times that pass in the meantime are skipped.
199
+ *
200
+ * @param config - `name`, `cron` (and `timeZone`) or `every`, `run` or
201
+ * `workflow`, and optionally `catchUp`, `maxAttempts`, `backoff`, `jitter` and
202
+ * `enabled`.
203
+ * @returns The schedule.
204
+ * @throws When the name is empty or contains `:`, the cron expression or time
205
+ * zone is invalid, or the schedule has both or neither of `cron` and `every`,
206
+ * or of `run` and `workflow`.
207
+ * @example
208
+ * import { brick, defineSchedule } from "@brickkit/core";
209
+ *
210
+ * const backup = defineSchedule({
211
+ * name: "db-backup",
212
+ * cron: "0 *\/6 * * *",
213
+ * timeZone: "Europe/Berlin",
214
+ * run: () => backupDatabase(),
215
+ * });
216
+ *
217
+ * export default brick({ services, events: { schedules: [backup] } });
218
+ */
219
+ declare function defineSchedule(config: ScheduleConfig): Schedule;
87
220
  /**
88
221
  * An event, as it was recorded. It is the same for every listener of it.
89
222
  */
@@ -206,7 +339,8 @@ interface EventsWorld {
206
339
  /**
207
340
  * Where the workflows of an app are built from. The CLI (`brick dev`,
208
341
  * `brick start`) writes the bundle to `<root>/.well-known/workflow/v1` before
209
- * events start, and events read it from there.
342
+ * events start, and events read it from there. A server compiled by
343
+ * `brick build` reads the bundle shipped beside it instead.
210
344
  */
211
345
  interface WorkflowsOptions {
212
346
  /** The project root: where the Workflow SDK is installed. Default: the working directory. */
@@ -242,13 +376,20 @@ interface EventsOptions {
242
376
  /** The listeners of the app. */
243
377
  listeners?: readonly EventListener[];
244
378
  /**
245
- * Whether this process delivers recorded events. `true` (the default) starts a
246
- * dispatcher with the default settings, an object tunes it, and `false` only
247
- * records events, for an app whose events are delivered by another process.
379
+ * The schedules of the app, from `defineSchedule`. Their state lives in the
380
+ * one `scheduleTable()` among the services' databases, and they run in the
381
+ * processes that deliver events, by the same `dispatch` settings.
382
+ */
383
+ schedules?: readonly Schedule[];
384
+ /**
385
+ * Whether this process delivers recorded events and runs schedules. `true`
386
+ * (the default) starts a dispatcher with the default settings, an object
387
+ * tunes it, and `false` only records events, for an app whose events are
388
+ * delivered by another process.
248
389
  */
249
390
  dispatch?: boolean | DispatchOptions;
250
391
  /**
251
- * The world that runs `workflow` listeners. Required when any listener has one.
392
+ * The world that runs `workflow` listeners and schedules. Required when any has one.
252
393
  * Brick starts it when the app's events start and closes it when they stop.
253
394
  */
254
395
  world?: EventsWorld;
@@ -1307,6 +1448,454 @@ declare function outboxTable(engine: "sqlite", options?: {
1307
1448
  declare function outboxTable(engine: "postgres", options?: {
1308
1449
  name?: string;
1309
1450
  }): PostgresOutboxTable;
1451
+ /** One finished run of a schedule, as the schedule table keeps it. */
1452
+ interface ScheduleRunRecord {
1453
+ /** The time the run was due, as an ISO timestamp. */
1454
+ slot: string;
1455
+ trigger: "schedule" | "manual";
1456
+ attempt: number;
1457
+ startedAt: string;
1458
+ finishedAt: string;
1459
+ /** `skipped`: a slot missed while no process ran, with `catchUp: "skip"`. */
1460
+ outcome: "succeeded" | "failed" | "skipped";
1461
+ error?: string;
1462
+ }
1463
+ declare function sqliteSchedules(name: string): import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
1464
+ name: string;
1465
+ schema: undefined;
1466
+ columns: {
1467
+ name: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1468
+ name: "name";
1469
+ tableName: string;
1470
+ dataType: "string";
1471
+ columnType: "SQLiteText";
1472
+ data: string;
1473
+ driverParam: string;
1474
+ notNull: true;
1475
+ hasDefault: false;
1476
+ isPrimaryKey: true;
1477
+ isAutoincrement: false;
1478
+ hasRuntimeDefault: false;
1479
+ enumValues: [string, ...string[]];
1480
+ baseColumn: never;
1481
+ identity: undefined;
1482
+ generated: undefined;
1483
+ }, {}, {
1484
+ length: number | undefined;
1485
+ }>;
1486
+ spec: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1487
+ name: "spec";
1488
+ tableName: string;
1489
+ dataType: "string";
1490
+ columnType: "SQLiteText";
1491
+ data: string;
1492
+ driverParam: string;
1493
+ notNull: true;
1494
+ hasDefault: false;
1495
+ isPrimaryKey: false;
1496
+ isAutoincrement: false;
1497
+ hasRuntimeDefault: false;
1498
+ enumValues: [string, ...string[]];
1499
+ baseColumn: never;
1500
+ identity: undefined;
1501
+ generated: undefined;
1502
+ }, {}, {
1503
+ length: number | undefined;
1504
+ }>;
1505
+ slot: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1506
+ name: string;
1507
+ tableName: string;
1508
+ dataType: "date";
1509
+ columnType: "SQLiteTimestamp";
1510
+ data: Date;
1511
+ driverParam: number;
1512
+ notNull: true;
1513
+ hasDefault: false;
1514
+ isPrimaryKey: false;
1515
+ isAutoincrement: false;
1516
+ hasRuntimeDefault: false;
1517
+ enumValues: undefined;
1518
+ baseColumn: never;
1519
+ identity: undefined;
1520
+ generated: undefined;
1521
+ }, {}, {}>;
1522
+ nextAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1523
+ name: string;
1524
+ tableName: string;
1525
+ dataType: "date";
1526
+ columnType: "SQLiteTimestamp";
1527
+ data: Date;
1528
+ driverParam: number;
1529
+ notNull: true;
1530
+ hasDefault: false;
1531
+ isPrimaryKey: false;
1532
+ isAutoincrement: false;
1533
+ hasRuntimeDefault: false;
1534
+ enumValues: undefined;
1535
+ baseColumn: never;
1536
+ identity: undefined;
1537
+ generated: undefined;
1538
+ }, {}, {}>;
1539
+ attempts: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1540
+ name: "attempts";
1541
+ tableName: string;
1542
+ dataType: "number";
1543
+ columnType: "SQLiteInteger";
1544
+ data: number;
1545
+ driverParam: number;
1546
+ notNull: true;
1547
+ hasDefault: true;
1548
+ isPrimaryKey: false;
1549
+ isAutoincrement: false;
1550
+ hasRuntimeDefault: false;
1551
+ enumValues: undefined;
1552
+ baseColumn: never;
1553
+ identity: undefined;
1554
+ generated: undefined;
1555
+ }, {}, {}>;
1556
+ trigger: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1557
+ name: "trigger";
1558
+ tableName: string;
1559
+ dataType: "string";
1560
+ columnType: "SQLiteText";
1561
+ data: "manual" | "schedule";
1562
+ driverParam: string;
1563
+ notNull: true;
1564
+ hasDefault: false;
1565
+ isPrimaryKey: false;
1566
+ isAutoincrement: false;
1567
+ hasRuntimeDefault: false;
1568
+ enumValues: [string, ...string[]];
1569
+ baseColumn: never;
1570
+ identity: undefined;
1571
+ generated: undefined;
1572
+ }, {}, {
1573
+ length: number | undefined;
1574
+ $type: "manual" | "schedule";
1575
+ }>;
1576
+ runId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1577
+ name: "run_id";
1578
+ tableName: string;
1579
+ dataType: "string";
1580
+ columnType: "SQLiteText";
1581
+ data: string;
1582
+ driverParam: string;
1583
+ notNull: false;
1584
+ hasDefault: false;
1585
+ isPrimaryKey: false;
1586
+ isAutoincrement: false;
1587
+ hasRuntimeDefault: false;
1588
+ enumValues: [string, ...string[]];
1589
+ baseColumn: never;
1590
+ identity: undefined;
1591
+ generated: undefined;
1592
+ }, {}, {
1593
+ length: number | undefined;
1594
+ }>;
1595
+ startedAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1596
+ name: string;
1597
+ tableName: string;
1598
+ dataType: "date";
1599
+ columnType: "SQLiteTimestamp";
1600
+ data: Date;
1601
+ driverParam: number;
1602
+ notNull: false;
1603
+ hasDefault: false;
1604
+ isPrimaryKey: false;
1605
+ isAutoincrement: false;
1606
+ hasRuntimeDefault: false;
1607
+ enumValues: undefined;
1608
+ baseColumn: never;
1609
+ identity: undefined;
1610
+ generated: undefined;
1611
+ }, {}, {}>;
1612
+ leaseUntil: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1613
+ name: string;
1614
+ tableName: string;
1615
+ dataType: "date";
1616
+ columnType: "SQLiteTimestamp";
1617
+ data: Date;
1618
+ driverParam: number;
1619
+ notNull: false;
1620
+ hasDefault: false;
1621
+ isPrimaryKey: false;
1622
+ isAutoincrement: false;
1623
+ hasRuntimeDefault: false;
1624
+ enumValues: undefined;
1625
+ baseColumn: never;
1626
+ identity: undefined;
1627
+ generated: undefined;
1628
+ }, {}, {}>;
1629
+ lastSuccessAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1630
+ name: string;
1631
+ tableName: string;
1632
+ dataType: "date";
1633
+ columnType: "SQLiteTimestamp";
1634
+ data: Date;
1635
+ driverParam: number;
1636
+ notNull: false;
1637
+ hasDefault: false;
1638
+ isPrimaryKey: false;
1639
+ isAutoincrement: false;
1640
+ hasRuntimeDefault: false;
1641
+ enumValues: undefined;
1642
+ baseColumn: never;
1643
+ identity: undefined;
1644
+ generated: undefined;
1645
+ }, {}, {}>;
1646
+ runs: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1647
+ name: "runs";
1648
+ tableName: string;
1649
+ dataType: "json";
1650
+ columnType: "SQLiteTextJson";
1651
+ data: ScheduleRunRecord[];
1652
+ driverParam: string;
1653
+ notNull: true;
1654
+ hasDefault: false;
1655
+ isPrimaryKey: false;
1656
+ isAutoincrement: false;
1657
+ hasRuntimeDefault: false;
1658
+ enumValues: undefined;
1659
+ baseColumn: never;
1660
+ identity: undefined;
1661
+ generated: undefined;
1662
+ }, {}, {
1663
+ $type: ScheduleRunRecord[];
1664
+ }>;
1665
+ };
1666
+ dialect: 'sqlite';
1667
+ }>;
1668
+ declare function postgresSchedules(name: string): import("drizzle-orm/pg-core").PgTableWithColumns<{
1669
+ name: string;
1670
+ schema: undefined;
1671
+ columns: {
1672
+ name: import("drizzle-orm/pg-core").PgColumn<{
1673
+ name: "name";
1674
+ tableName: string;
1675
+ dataType: "string";
1676
+ columnType: "PgText";
1677
+ data: string;
1678
+ driverParam: string;
1679
+ notNull: true;
1680
+ hasDefault: false;
1681
+ isPrimaryKey: true;
1682
+ isAutoincrement: false;
1683
+ hasRuntimeDefault: false;
1684
+ enumValues: [string, ...string[]];
1685
+ baseColumn: never;
1686
+ identity: undefined;
1687
+ generated: undefined;
1688
+ }, {}, {}>;
1689
+ spec: import("drizzle-orm/pg-core").PgColumn<{
1690
+ name: "spec";
1691
+ tableName: string;
1692
+ dataType: "string";
1693
+ columnType: "PgText";
1694
+ data: string;
1695
+ driverParam: string;
1696
+ notNull: true;
1697
+ hasDefault: false;
1698
+ isPrimaryKey: false;
1699
+ isAutoincrement: false;
1700
+ hasRuntimeDefault: false;
1701
+ enumValues: [string, ...string[]];
1702
+ baseColumn: never;
1703
+ identity: undefined;
1704
+ generated: undefined;
1705
+ }, {}, {}>;
1706
+ slot: import("drizzle-orm/pg-core").PgColumn<{
1707
+ name: string;
1708
+ tableName: string;
1709
+ dataType: "date";
1710
+ columnType: "PgTimestamp";
1711
+ data: Date;
1712
+ driverParam: string;
1713
+ notNull: true;
1714
+ hasDefault: false;
1715
+ isPrimaryKey: false;
1716
+ isAutoincrement: false;
1717
+ hasRuntimeDefault: false;
1718
+ enumValues: undefined;
1719
+ baseColumn: never;
1720
+ identity: undefined;
1721
+ generated: undefined;
1722
+ }, {}, {}>;
1723
+ nextAt: import("drizzle-orm/pg-core").PgColumn<{
1724
+ name: string;
1725
+ tableName: string;
1726
+ dataType: "date";
1727
+ columnType: "PgTimestamp";
1728
+ data: Date;
1729
+ driverParam: string;
1730
+ notNull: true;
1731
+ hasDefault: false;
1732
+ isPrimaryKey: false;
1733
+ isAutoincrement: false;
1734
+ hasRuntimeDefault: false;
1735
+ enumValues: undefined;
1736
+ baseColumn: never;
1737
+ identity: undefined;
1738
+ generated: undefined;
1739
+ }, {}, {}>;
1740
+ attempts: import("drizzle-orm/pg-core").PgColumn<{
1741
+ name: "attempts";
1742
+ tableName: string;
1743
+ dataType: "number";
1744
+ columnType: "PgInteger";
1745
+ data: number;
1746
+ driverParam: string | number;
1747
+ notNull: true;
1748
+ hasDefault: true;
1749
+ isPrimaryKey: false;
1750
+ isAutoincrement: false;
1751
+ hasRuntimeDefault: false;
1752
+ enumValues: undefined;
1753
+ baseColumn: never;
1754
+ identity: undefined;
1755
+ generated: undefined;
1756
+ }, {}, {}>;
1757
+ trigger: import("drizzle-orm/pg-core").PgColumn<{
1758
+ name: "trigger";
1759
+ tableName: string;
1760
+ dataType: "string";
1761
+ columnType: "PgText";
1762
+ data: "manual" | "schedule";
1763
+ driverParam: string;
1764
+ notNull: true;
1765
+ hasDefault: false;
1766
+ isPrimaryKey: false;
1767
+ isAutoincrement: false;
1768
+ hasRuntimeDefault: false;
1769
+ enumValues: [string, ...string[]];
1770
+ baseColumn: never;
1771
+ identity: undefined;
1772
+ generated: undefined;
1773
+ }, {}, {
1774
+ $type: "manual" | "schedule";
1775
+ }>;
1776
+ runId: import("drizzle-orm/pg-core").PgColumn<{
1777
+ name: "run_id";
1778
+ tableName: string;
1779
+ dataType: "string";
1780
+ columnType: "PgText";
1781
+ data: string;
1782
+ driverParam: string;
1783
+ notNull: false;
1784
+ hasDefault: false;
1785
+ isPrimaryKey: false;
1786
+ isAutoincrement: false;
1787
+ hasRuntimeDefault: false;
1788
+ enumValues: [string, ...string[]];
1789
+ baseColumn: never;
1790
+ identity: undefined;
1791
+ generated: undefined;
1792
+ }, {}, {}>;
1793
+ startedAt: import("drizzle-orm/pg-core").PgColumn<{
1794
+ name: string;
1795
+ tableName: string;
1796
+ dataType: "date";
1797
+ columnType: "PgTimestamp";
1798
+ data: Date;
1799
+ driverParam: string;
1800
+ notNull: false;
1801
+ hasDefault: false;
1802
+ isPrimaryKey: false;
1803
+ isAutoincrement: false;
1804
+ hasRuntimeDefault: false;
1805
+ enumValues: undefined;
1806
+ baseColumn: never;
1807
+ identity: undefined;
1808
+ generated: undefined;
1809
+ }, {}, {}>;
1810
+ leaseUntil: import("drizzle-orm/pg-core").PgColumn<{
1811
+ name: string;
1812
+ tableName: string;
1813
+ dataType: "date";
1814
+ columnType: "PgTimestamp";
1815
+ data: Date;
1816
+ driverParam: string;
1817
+ notNull: false;
1818
+ hasDefault: false;
1819
+ isPrimaryKey: false;
1820
+ isAutoincrement: false;
1821
+ hasRuntimeDefault: false;
1822
+ enumValues: undefined;
1823
+ baseColumn: never;
1824
+ identity: undefined;
1825
+ generated: undefined;
1826
+ }, {}, {}>;
1827
+ lastSuccessAt: import("drizzle-orm/pg-core").PgColumn<{
1828
+ name: string;
1829
+ tableName: string;
1830
+ dataType: "date";
1831
+ columnType: "PgTimestamp";
1832
+ data: Date;
1833
+ driverParam: string;
1834
+ notNull: false;
1835
+ hasDefault: false;
1836
+ isPrimaryKey: false;
1837
+ isAutoincrement: false;
1838
+ hasRuntimeDefault: false;
1839
+ enumValues: undefined;
1840
+ baseColumn: never;
1841
+ identity: undefined;
1842
+ generated: undefined;
1843
+ }, {}, {}>;
1844
+ runs: import("drizzle-orm/pg-core").PgColumn<{
1845
+ name: "runs";
1846
+ tableName: string;
1847
+ dataType: "json";
1848
+ columnType: "PgJsonb";
1849
+ data: ScheduleRunRecord[];
1850
+ driverParam: unknown;
1851
+ notNull: true;
1852
+ hasDefault: false;
1853
+ isPrimaryKey: false;
1854
+ isAutoincrement: false;
1855
+ hasRuntimeDefault: false;
1856
+ enumValues: undefined;
1857
+ baseColumn: never;
1858
+ identity: undefined;
1859
+ generated: undefined;
1860
+ }, {}, {
1861
+ $type: ScheduleRunRecord[];
1862
+ }>;
1863
+ };
1864
+ dialect: 'pg';
1865
+ }>;
1866
+ /** The schedule table of a SQLite database. */
1867
+ type SQLiteScheduleTable = ReturnType<typeof sqliteSchedules>;
1868
+ /** The schedule table of a Postgres database. */
1869
+ type PostgresScheduleTable = ReturnType<typeof postgresSchedules>;
1870
+ /** A schedule table, made by `scheduleTable`. */
1871
+ type ScheduleTable = SQLiteScheduleTable | PostgresScheduleTable;
1872
+ /**
1873
+ * The schedule table: one row per schedule, holding when it is next due, which
1874
+ * process is running it, and its last runs. Processes that share the table
1875
+ * share the schedules: each due time runs once among them, and a restart
1876
+ * picks up where the last process stopped.
1877
+ *
1878
+ * Brick does not create tables for you. Put it in the schema of one of the
1879
+ * app's databases, and your migration tool (such as drizzle-kit) creates it.
1880
+ *
1881
+ * @param engine - The database engine, `"sqlite"` or `"postgres"`.
1882
+ * @param options - `name` to call the table something other than `brick_schedules`.
1883
+ * @returns A Drizzle table.
1884
+ * @example
1885
+ * import { defineDatabase, outboxTable, scheduleTable } from "@brickkit/core";
1886
+ *
1887
+ * export const schedules = scheduleTable("postgres");
1888
+ * export const database = defineDatabase({
1889
+ * engine: "postgres",
1890
+ * tables: { users, schedules },
1891
+ * });
1892
+ */
1893
+ declare function scheduleTable(engine: "sqlite", options?: {
1894
+ name?: string;
1895
+ }): SQLiteScheduleTable;
1896
+ declare function scheduleTable(engine: "postgres", options?: {
1897
+ name?: string;
1898
+ }): PostgresScheduleTable;
1310
1899
  /**
1311
1900
  * What core's own modules use of a service, beyond the public `Service`. Every
1312
1901
  * service `defineService` makes is one.
@@ -1321,6 +1910,7 @@ interface ServicePort<TDb = any, TServiceContext extends Record<string, any> = R
1321
1910
  resolveContext(callCtx?: Partial<BaseContext<TDb> & TServiceContext>, pluginDeps?: Readonly<Record<string, unknown>>): Promise<BaseContext<TDb> & TServiceContext>;
1322
1911
  setRecorder(recorder: ServiceEvents | undefined): void;
1323
1912
  getOutbox(): OutboxTable | undefined;
1913
+ getScheduleTable(): ScheduleTable | undefined;
1324
1914
  /** @throws When the event is not in the catalog or its payload does not match. */
1325
1915
  checkEvent(name: string, payload: unknown): void;
1326
1916
  /** Adds events to the catalog (a plugin's). */
@@ -1676,6 +2266,25 @@ declare class Dispatcher {
1676
2266
  private logError;
1677
2267
  private purgeDelivered;
1678
2268
  }
2269
+ /** A schedule as `schedules.list()` reports it. */
2270
+ interface ScheduleState {
2271
+ name: string;
2272
+ kind: "handler" | "workflow";
2273
+ cron?: string;
2274
+ timeZone?: string;
2275
+ /** The interval, in milliseconds. */
2276
+ every?: number;
2277
+ enabled: boolean;
2278
+ /** When it is next due (a retry included), as an ISO timestamp; `null` before a process first started the schedules. */
2279
+ nextRunAt: string | null;
2280
+ /** Whether a process is running it now. */
2281
+ running: boolean;
2282
+ /** Tries of the current due time so far. */
2283
+ attempts: number;
2284
+ lastSuccessAt: string | null;
2285
+ /** The last runs, newest first. */
2286
+ runs: ScheduleRunRecord[];
2287
+ }
1679
2288
  /**
1680
2289
  * Stop every events hub started in this process, by any copy of `@brickkit/core`,
1681
2290
  * and wait for their deliveries. A hub that fails to stop does not cut the wait
@@ -1695,6 +2304,30 @@ interface EventsDefinition {
1695
2304
  dispatch: boolean;
1696
2305
  /** Names of the services whose writes record events. */
1697
2306
  recorders: string[];
2307
+ /** The app's schedules; absent when it has none. */
2308
+ schedules?: {
2309
+ name: string;
2310
+ kind: "handler" | "workflow";
2311
+ cron?: string;
2312
+ timeZone?: string;
2313
+ every?: number;
2314
+ enabled: boolean;
2315
+ }[];
2316
+ }
2317
+ /** What `app.events.schedules` offers: see and trigger the app's schedules. */
2318
+ interface ScheduleControl {
2319
+ /** Every schedule, with when it is next due and its last runs. */
2320
+ list(): Promise<ScheduleState[]>;
2321
+ /**
2322
+ * Run a schedule now, once, in whichever process runs the schedules. It
2323
+ * works with `enabled: false` too.
2324
+ *
2325
+ * @returns `false` when the schedule is running now, so nothing was started.
2326
+ * @throws When no schedule has that name.
2327
+ */
2328
+ trigger(name: string): Promise<boolean>;
2329
+ /** Run what is due now, and wait for it. For tests and workers driven by hand. @returns How many runs started. */
2330
+ drain(): Promise<number>;
1698
2331
  }
1699
2332
  /** What the dispatcher runs for a delivery. */
1700
2333
  interface Deliverable {
@@ -1716,6 +2349,8 @@ declare class EventsHub {
1716
2349
  private readonly dispatchOptions;
1717
2350
  private readonly runtime;
1718
2351
  private readonly recorderNames;
2352
+ private readonly scheduleList;
2353
+ private scheduler;
1719
2354
  private started;
1720
2355
  private stopping;
1721
2356
  /**
@@ -1735,16 +2370,27 @@ declare class EventsHub {
1735
2370
  attach(services: readonly Service<any, any>[]): this;
1736
2371
  matching(name: string): EventListener[];
1737
2372
  describe(): EventsDefinition;
2373
+ /** The app's schedules, when it has any. Running them follows `start()` and `stop()`. */
2374
+ get schedules(): ScheduleControl | undefined;
2375
+ /**
2376
+ * Find the one schedule table among the services' databases.
2377
+ *
2378
+ * @throws When none holds one, or more than one does: a schedule must have
2379
+ * one place where its state lives.
2380
+ */
2381
+ private attachSchedules;
1738
2382
  /**
1739
2383
  * Where the workflow bundle is read from, the project it is built from, and
1740
2384
  * the world the workflows run on. Only set when a listener runs a workflow.
1741
2385
  * The CLI builds the bundle there before events start, and shows the world's
1742
- * runs in the dev dashboard.
2386
+ * runs in the dev dashboard. `shipped`: a compiled server reads the bundle
2387
+ * `brick build` shipped beside it, so there is nothing to build.
1743
2388
  */
1744
2389
  get workflows(): {
1745
2390
  root: string;
1746
2391
  dir: string;
1747
2392
  world: EventsWorld;
2393
+ shipped: boolean;
1748
2394
  } | undefined;
1749
2395
  /**
1750
2396
  * Resume the workflow that waits on a webhook. The server mounts this on the
@@ -2501,5 +3147,5 @@ interface ProxyOptions {
2501
3147
  from?: string;
2502
3148
  context?: Partial<ActionContext>;
2503
3149
  }
2504
- export { BrickSocketError as $, CrudEventOperation as $n, PluginRoutes as $t, Resource as A, listSecrets as An, PostgresDatabase as At, ServiceSchema as B, DispatchOptions as Bn, integer$1 as Bt, ErrorDetails as C, PluginSetupContext as Cn, DatabaseDefinition as Ct, NarrowAuthorizedContext as D, SecretSource as Dn, SQLiteDefinition as Dt, Logger as E, SecretRef as En, PostgresDefinition as Et, ResourceConfig as F, HostHooks as Fn, SQLiteDatabaseConfig as Ft, ToolConfigWithoutAuthorize as G, EventWorkflow as Gn, uniqueIndex as Gt, Tool as H, EventEnvelope as Hn, real$1 as Ht, ResourceIdentity as I, PluginHookArgs as In, blob as It, ValidationErrorItem as J, ListenerFailure as Jn, PLUGIN_KIND as Jt, ToolOptions as K, EventsOptions as Kn, ContextOf as Kt, ResourceTypeOptions as L, PluginHooks as Ln, createSQLiteDatabase as Lt, ResourceActionConfig as M, resetSecrets as Mn, createPostgresDatabase as Mt, ResourceActionInput as N, resolveSecrets as Nn, BrickSQLiteDatabase as Nt, PreparationContribution as O, defineSecret as On, defineDatabase as Ot, ResourceChild as P, PluginTableBuilders as Pn, BunSQLiteDatabase$1 as Pt, BrickSocketConnectOptions as Q, WorkflowsOptions as Qn, PluginRouteScope as Qt, Service as R, getHostHooks as Rn, foreignKey as Rt, ErrorBuilder as S, PluginServiceContext as Sn, isControlEvent as St, InferTableRow as T, SecretOptions as Tn, EnvInput as Tt, ToolAnnotations as U, EventListener as Un, sqliteTable$1 as Ut, StandardErrorMap as V, EventDelivery as Vn, primaryKey as Vt, ToolConfigWithAuthorize as W, EventRecorder as Wn, text$1 as Wt, BrickSocketClient as X, ServiceEvents as Xn, PluginRouteMethod as Xt, BrickClientSocket as Y, RetryDecision as Yn, PluginEndpointContext as Yt, BrickSocketConfig as Z, WorkflowEvent as Zn, PluginRouteRegistrar as Zt, CommandDecision as _, PluginInfo as _n, Dispatcher as _t, ActionConfigWithoutAuthorize as a, ServicePluginContext as an, isCrudEvent as ar, BrickSocketStatus as at, DefaultServiceContext as b, PluginLifecycleContext as bn, StandardErrorCode as bt, ActionExecutionError as c, ServicePort as cn, Ports as cr, SocketEmitArgs as ct, BaseActionConfig as d, PostgresOutboxTable as dn, HttpMethod as dr, SocketPayloads as dt, ResourcePlugin as en, EventCatalog as er, BrickSocketHandle as et, BaseContext as f, SQLiteOutboxTable as fn, SocketReplay as ft, CommandConfig as g, PluginFactory as gn, stopAllEvents as gt, CommandChildren as h, PluginContext as hn, EventsHub as ht, ActionConfigWithAuthorize as i, ServicePlugin as in, crudEventSource as ir, BrickSocketSender as it, ResourceActionAccess as j, overrideSecret as jn, PostgresDatabaseConfig as jt, ProxyOptions as k, envSource as kn, isDatabaseHandle as kt, ActionSchema as l, OutboxStatus as ln, port as lr, SocketEmitOptions as lt, Command as m, PluginAppContext as mn, EventsDefinition as mt, ActionAccessPolicy as n, ResourcePluginContext as nn, EventRefs as nr, BrickSocketReconnectOptions as nt, ActionContext as o, ActionAccessInfo as on, DepsOf as or, SocketBroker as ot, ChildChanges as p, outboxTable as pn, SocketSchemas as pt, ValidationError as q, EventsWorld as qn, InstalledPlugin as qt, ActionConfig as r, ResourcePluginTypes as rn, crudEventName as rr, BrickSocketSchema as rt, ActionErrorDefinition as s, ResourceActionInfo as sn, Port as sr, SocketBrokerMessage as st, Action as t, ResourcePluginAPI as tn, EventRef as tr, BrickSocketHandlerError as tt, ArchitectureSchema as u, OutboxTable as un, useDeps as ur, SocketEventArgs as ut, CommandErrors as v, PluginInstallOptions as vn, OutboxCounts as vt, InferTableInsert as w, definePlugin as wn, DatabaseHandle as wt, DuplicateNameError as x, PluginManifest as xn, WireError as xt, CommandRow as y, PluginInstance as yn, STANDARD_ERRORS as yt, ServiceOptions as z, CrudEventPayload as zn, index$1 as zt };
3150
+ export { BrickSocketError as $, EventsOptions as $n, PluginRouteRegistrar as $t, Resource as A, PluginSetupContext as An, defineDatabase as At, ServiceSchema as B, resolveSecrets as Bn, foreignKey as Bt, ErrorDetails as C, PluginFactory as Cn, useDeps as Cr, WireError as Ct, NarrowAuthorizedContext as D, PluginLifecycleContext as Dn, EnvInput as Dt, Logger as E, PluginInstance as En, DatabaseHandle as Et, ResourceConfig as F, defineSecret as Fn, BrickSQLiteDatabase as Ft, ToolConfigWithoutAuthorize as G, getHostHooks as Gn, sqliteTable$1 as Gt, Tool as H, HostHooks as Hn, integer$1 as Ht, ResourceIdentity as I, envSource as In, BunSQLiteDatabase$1 as It, ValidationErrorItem as J, EventDelivery as Jn, ContextOf as Jt, ToolOptions as K, CrudEventPayload as Kn, text$1 as Kt, ResourceTypeOptions as L, listSecrets as Ln, SQLiteDatabaseConfig as Lt, ResourceActionConfig as M, SecretOptions as Mn, PostgresDatabase as Mt, ResourceActionInput as N, SecretRef as Nn, PostgresDatabaseConfig as Nt, PreparationContribution as O, PluginManifest as On, PostgresDefinition as Ot, ResourceChild as P, SecretSource as Pn, createPostgresDatabase as Pt, BrickSocketConnectOptions as Q, EventWorkflow as Qn, PluginRouteMethod as Qt, Service as R, overrideSecret as Rn, blob as Rt, ErrorBuilder as S, PluginContext as Sn, port as Sr, StandardErrorCode as St, InferTableRow as T, PluginInstallOptions as Tn, DatabaseDefinition as Tt, ToolAnnotations as U, PluginHookArgs as Un, primaryKey as Ut, StandardErrorMap as V, PluginTableBuilders as Vn, index$1 as Vt, ToolConfigWithAuthorize as W, PluginHooks as Wn, real$1 as Wt, BrickSocketClient as X, EventListener as Xn, PLUGIN_KIND as Xt, BrickClientSocket as Y, EventEnvelope as Yn, InstalledPlugin as Yt, BrickSocketConfig as Z, EventRecorder as Zn, PluginEndpointContext as Zt, CommandDecision as _, OutboxTable as _n, crudEventSource as _r, stopAllEvents as _t, ActionConfigWithoutAuthorize as a, ResourcePluginTypes as an, WorkflowsOptions as ar, BrickSocketStatus as at, DefaultServiceContext as b, outboxTable as bn, Port as br, OutboxCounts as bt, ActionExecutionError as c, ActionAccessInfo as cn, ScheduleRun as cr, SocketEmitArgs as ct, BaseActionConfig as d, PostgresScheduleTable as dn, defineSchedule as dr, SocketPayloads as dt, PluginRouteScope as en, EventsWorld as er, BrickSocketHandle as et, BaseContext as f, SQLiteScheduleTable as fn, CrudEventOperation as fr, SocketReplay as ft, CommandConfig as g, OutboxStatus as gn, crudEventName as gr, ScheduleControl as gt, CommandChildren as h, scheduleTable as hn, EventRefs as hr, EventsHub as ht, ActionConfigWithAuthorize as i, ResourcePluginContext as in, WorkflowEvent as ir, BrickSocketSender as it, ResourceActionAccess as j, definePlugin as jn, isDatabaseHandle as jt, ProxyOptions as k, PluginServiceContext as kn, SQLiteDefinition as kt, ActionSchema as l, ResourceActionInfo as ln, ScheduleWorkflow as lr, SocketEmitOptions as lt, Command as m, ScheduleTable as mn, EventRef as mr, EventsDefinition as mt, ActionAccessPolicy as n, ResourcePlugin as nn, RetryDecision as nr, BrickSocketReconnectOptions as nt, ActionContext as o, ServicePlugin as on, Schedule as or, SocketBroker as ot, ChildChanges as p, ScheduleRunRecord as pn, EventCatalog as pr, SocketSchemas as pt, ValidationError as q, DispatchOptions as qn, uniqueIndex as qt, ActionConfig as r, ResourcePluginAPI as rn, ServiceEvents as rr, BrickSocketSchema as rt, ActionErrorDefinition as s, ServicePluginContext as sn, ScheduleConfig as sr, SocketBrokerMessage as st, Action as t, PluginRoutes as tn, ListenerFailure as tr, BrickSocketHandlerError as tt, ArchitectureSchema as u, ServicePort as un, ScheduleWorkflowRun as ur, SocketEventArgs as ut, CommandErrors as v, PostgresOutboxTable as vn, isCrudEvent as vr, ScheduleState as vt, InferTableInsert as w, PluginInfo as wn, HttpMethod as wr, isControlEvent as wt, DuplicateNameError as x, PluginAppContext as xn, Ports as xr, STANDARD_ERRORS as xt, CommandRow as y, SQLiteOutboxTable as yn, DepsOf as yr, Dispatcher as yt, ServiceOptions as z, resetSecrets as zn, createSQLiteDatabase as zt };
2505
3151
  //# sourceMappingURL=types.d.ts.map