@brickkit/core 0.13.3 → 0.15.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
  */
@@ -243,13 +376,20 @@ interface EventsOptions {
243
376
  /** The listeners of the app. */
244
377
  listeners?: readonly EventListener[];
245
378
  /**
246
- * Whether this process delivers recorded events. `true` (the default) starts a
247
- * dispatcher with the default settings, an object tunes it, and `false` only
248
- * 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.
249
389
  */
250
390
  dispatch?: boolean | DispatchOptions;
251
391
  /**
252
- * 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.
253
393
  * Brick starts it when the app's events start and closes it when they stop.
254
394
  */
255
395
  world?: EventsWorld;
@@ -1308,6 +1448,454 @@ declare function outboxTable(engine: "sqlite", options?: {
1308
1448
  declare function outboxTable(engine: "postgres", options?: {
1309
1449
  name?: string;
1310
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;
1311
1899
  /**
1312
1900
  * What core's own modules use of a service, beyond the public `Service`. Every
1313
1901
  * service `defineService` makes is one.
@@ -1322,6 +1910,7 @@ interface ServicePort<TDb = any, TServiceContext extends Record<string, any> = R
1322
1910
  resolveContext(callCtx?: Partial<BaseContext<TDb> & TServiceContext>, pluginDeps?: Readonly<Record<string, unknown>>): Promise<BaseContext<TDb> & TServiceContext>;
1323
1911
  setRecorder(recorder: ServiceEvents | undefined): void;
1324
1912
  getOutbox(): OutboxTable | undefined;
1913
+ getScheduleTable(): ScheduleTable | undefined;
1325
1914
  /** @throws When the event is not in the catalog or its payload does not match. */
1326
1915
  checkEvent(name: string, payload: unknown): void;
1327
1916
  /** Adds events to the catalog (a plugin's). */
@@ -1621,6 +2210,37 @@ interface WireError {
1621
2210
  }
1622
2211
  /** Event names starting with `$` are reserved for control messages. */
1623
2212
  declare const isControlEvent: (event: string) => boolean;
2213
+ /** The person `dashboard.auth.authorize` let in. */
2214
+ interface DashboardUser {
2215
+ id: string;
2216
+ name?: string;
2217
+ }
2218
+ /**
2219
+ * Who a request came from, when it reached the app through the dashboard's
2220
+ * `/app/*` proxy. `user` is missing when the dashboard let the request in
2221
+ * without one: by token, by `authorize` returning `true`, or with no `auth`.
2222
+ */
2223
+ interface DashboardIdentity {
2224
+ user?: DashboardUser;
2225
+ }
2226
+ /** The header the dashboard's `/app/*` proxy signs the identity into. */
2227
+ declare const DASHBOARD_IDENTITY_HEADER = "x-brick-dashboard";
2228
+ /** How `brick dev` hands the signing key to the app's process. */
2229
+ declare const DASHBOARD_KEY_ENV = "BRICK_DASHBOARD_KEY";
2230
+ /**
2231
+ * The key the dashboard signs identities with: random per process, or the one
2232
+ * `brick dev` or the Vite plugin handed the app.
2233
+ */
2234
+ declare function dashboardKey(): string;
2235
+ /** The header value for an identity: `<base64url(json)>.<hmac>`. */
2236
+ declare function signDashboardIdentity(identity: DashboardIdentity, now?: number): string;
2237
+ /**
2238
+ * The dashboard user a request came from, for an endpoint: the person
2239
+ * `dashboard.auth.authorize` let in, when the request arrived through the
2240
+ * dashboard's `/app/*` proxy. Undefined for any other request, and for one the
2241
+ * dashboard let in by token. Actions read it as `ctx.dashboard?.user`.
2242
+ */
2243
+ declare function dashboardUser(request: Request): DashboardUser | undefined;
1624
2244
  /** How many outbox rows are in each state. */
1625
2245
  type OutboxCounts = Record<OutboxStatus, number>;
1626
2246
  /**
@@ -1677,6 +2297,25 @@ declare class Dispatcher {
1677
2297
  private logError;
1678
2298
  private purgeDelivered;
1679
2299
  }
2300
+ /** A schedule as `schedules.list()` reports it. */
2301
+ interface ScheduleState {
2302
+ name: string;
2303
+ kind: "handler" | "workflow";
2304
+ cron?: string;
2305
+ timeZone?: string;
2306
+ /** The interval, in milliseconds. */
2307
+ every?: number;
2308
+ enabled: boolean;
2309
+ /** When it is next due (a retry included), as an ISO timestamp; `null` before a process first started the schedules. */
2310
+ nextRunAt: string | null;
2311
+ /** Whether a process is running it now. */
2312
+ running: boolean;
2313
+ /** Tries of the current due time so far. */
2314
+ attempts: number;
2315
+ lastSuccessAt: string | null;
2316
+ /** The last runs, newest first. */
2317
+ runs: ScheduleRunRecord[];
2318
+ }
1680
2319
  /**
1681
2320
  * Stop every events hub started in this process, by any copy of `@brickkit/core`,
1682
2321
  * and wait for their deliveries. A hub that fails to stop does not cut the wait
@@ -1696,6 +2335,30 @@ interface EventsDefinition {
1696
2335
  dispatch: boolean;
1697
2336
  /** Names of the services whose writes record events. */
1698
2337
  recorders: string[];
2338
+ /** The app's schedules; absent when it has none. */
2339
+ schedules?: {
2340
+ name: string;
2341
+ kind: "handler" | "workflow";
2342
+ cron?: string;
2343
+ timeZone?: string;
2344
+ every?: number;
2345
+ enabled: boolean;
2346
+ }[];
2347
+ }
2348
+ /** What `app.events.schedules` offers: see and trigger the app's schedules. */
2349
+ interface ScheduleControl {
2350
+ /** Every schedule, with when it is next due and its last runs. */
2351
+ list(): Promise<ScheduleState[]>;
2352
+ /**
2353
+ * Run a schedule now, once, in whichever process runs the schedules. It
2354
+ * works with `enabled: false` too.
2355
+ *
2356
+ * @returns `false` when the schedule is running now, so nothing was started.
2357
+ * @throws When no schedule has that name.
2358
+ */
2359
+ trigger(name: string): Promise<boolean>;
2360
+ /** Run what is due now, and wait for it. For tests and workers driven by hand. @returns How many runs started. */
2361
+ drain(): Promise<number>;
1699
2362
  }
1700
2363
  /** What the dispatcher runs for a delivery. */
1701
2364
  interface Deliverable {
@@ -1717,6 +2380,8 @@ declare class EventsHub {
1717
2380
  private readonly dispatchOptions;
1718
2381
  private readonly runtime;
1719
2382
  private readonly recorderNames;
2383
+ private readonly scheduleList;
2384
+ private scheduler;
1720
2385
  private started;
1721
2386
  private stopping;
1722
2387
  /**
@@ -1736,6 +2401,15 @@ declare class EventsHub {
1736
2401
  attach(services: readonly Service<any, any>[]): this;
1737
2402
  matching(name: string): EventListener[];
1738
2403
  describe(): EventsDefinition;
2404
+ /** The app's schedules, when it has any. Running them follows `start()` and `stop()`. */
2405
+ get schedules(): ScheduleControl | undefined;
2406
+ /**
2407
+ * Find the one schedule table among the services' databases.
2408
+ *
2409
+ * @throws When none holds one, or more than one does: a schedule must have
2410
+ * one place where its state lives.
2411
+ */
2412
+ private attachSchedules;
1739
2413
  /**
1740
2414
  * Where the workflow bundle is read from, the project it is built from, and
1741
2415
  * the world the workflows run on. Only set when a listener runs a workflow.
@@ -2026,6 +2700,11 @@ interface BaseContext<TDb = any> {
2026
2700
  tenantId?: string;
2027
2701
  services?: Record<string, any>;
2028
2702
  metadata?: Record<string, unknown>;
2703
+ /**
2704
+ * Set when the request came through the dashboard's `/app/*` proxy, signed
2705
+ * by the dashboard: `user` is who `dashboard.auth.authorize` let in.
2706
+ */
2707
+ dashboard?: DashboardIdentity;
2029
2708
  }
2030
2709
  /**
2031
2710
  * Default fallback service context for untyped or simple services.
@@ -2129,6 +2808,12 @@ interface BaseActionConfig<TInputSchema extends TSchema | undefined = undefined,
2129
2808
  tags?: string[];
2130
2809
  }
2131
2810
  interface ActionConfigWithAuthorize<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> extends BaseActionConfig<TInputSchema, TOutputSchema, TErrors> {
2811
+ /**
2812
+ * `true` refuses (401) any HTTP call that did not come through the
2813
+ * dashboard's `/app/*` proxy, so only the dashboard's pages can reach it.
2814
+ * `ctx.dashboard` is then set.
2815
+ */
2816
+ dashboard?: boolean;
2132
2817
  authorize: (params: {
2133
2818
  user?: TContext extends {
2134
2819
  user: infer U;
@@ -2143,6 +2828,12 @@ interface ActionConfigWithAuthorize<TInputSchema extends TSchema | undefined = u
2143
2828
  }) => Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any> | (TOutputSchema extends TSchema ? Static<TOutputSchema> : any);
2144
2829
  }
2145
2830
  interface ActionConfigWithoutAuthorize<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> extends BaseActionConfig<TInputSchema, TOutputSchema, TErrors> {
2831
+ /**
2832
+ * `true` refuses (401) any HTTP call that did not come through the
2833
+ * dashboard's `/app/*` proxy, so only the dashboard's pages can reach it.
2834
+ * `ctx.dashboard` is then set.
2835
+ */
2836
+ dashboard?: boolean;
2146
2837
  authorize?: undefined;
2147
2838
  execute: (params: {
2148
2839
  input: TInputSchema extends TSchema ? Static<TInputSchema> : any;
@@ -2504,5 +3195,5 @@ interface ProxyOptions {
2504
3195
  from?: string;
2505
3196
  context?: Partial<ActionContext>;
2506
3197
  }
2507
- 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 };
3198
+ export { BrickSocketError as $, CrudEventPayload as $n, text$1 as $t, Resource as A, PluginFactory as An, useDeps as Ar, WireError as At, ServiceSchema as B, SecretRef as Bn, PostgresDatabaseConfig as Bt, ErrorDetails as C, OutboxStatus as Cn, crudEventName as Cr, DashboardIdentity as Ct, NarrowAuthorizedContext as D, outboxTable as Dn, Port as Dr, signDashboardIdentity as Dt, Logger as E, SQLiteOutboxTable as En, DepsOf as Er, dashboardUser as Et, ResourceConfig as F, PluginManifest as Fn, PostgresDefinition as Ft, ToolConfigWithoutAuthorize as G, overrideSecret as Gn, blob as Gt, Tool as H, defineSecret as Hn, BrickSQLiteDatabase as Ht, ResourceIdentity as I, PluginServiceContext as In, SQLiteDefinition as It, ValidationErrorItem as J, PluginTableBuilders as Jn, index$1 as Jt, ToolOptions as K, resetSecrets as Kn, createSQLiteDatabase as Kt, ResourceTypeOptions as L, PluginSetupContext as Ln, defineDatabase as Lt, ResourceActionConfig as M, PluginInstallOptions as Mn, DatabaseDefinition as Mt, ResourceActionInput as N, PluginInstance as Nn, DatabaseHandle as Nt, PreparationContribution as O, PluginAppContext as On, Ports as Or, STANDARD_ERRORS as Ot, ResourceChild as P, PluginLifecycleContext as Pn, EnvInput as Pt, BrickSocketConnectOptions as Q, getHostHooks as Qn, sqliteTable$1 as Qt, Service as R, definePlugin as Rn, isDatabaseHandle as Rt, ErrorBuilder as S, scheduleTable as Sn, EventRefs as Sr, DASHBOARD_KEY_ENV as St, InferTableRow as T, PostgresOutboxTable as Tn, isCrudEvent as Tr, dashboardKey as Tt, ToolAnnotations as U, envSource as Un, BunSQLiteDatabase$1 as Ut, StandardErrorMap as V, SecretSource as Vn, createPostgresDatabase as Vt, ToolConfigWithAuthorize as W, listSecrets as Wn, SQLiteDatabaseConfig as Wt, BrickSocketClient as X, PluginHookArgs as Xn, primaryKey as Xt, BrickClientSocket as Y, HostHooks as Yn, integer$1 as Yt, BrickSocketConfig as Z, PluginHooks as Zn, real$1 as Zt, CommandDecision as _, ServicePort as _n, ScheduleWorkflowRun as _r, stopAllEvents as _t, ActionConfigWithoutAuthorize as a, PluginRouteMethod as an, EventWorkflow as ar, BrickSocketStatus as at, DefaultServiceContext as b, ScheduleRunRecord as bn, EventCatalog as br, OutboxCounts as bt, ActionExecutionError as c, PluginRoutes as cn, ListenerFailure as cr, SocketEmitArgs as ct, BaseActionConfig as d, ResourcePluginContext as dn, WorkflowEvent as dr, SocketPayloads as dt, uniqueIndex as en, DispatchOptions as er, BrickSocketHandle as et, BaseContext as f, ResourcePluginTypes as fn, WorkflowsOptions as fr, SocketReplay as ft, CommandConfig as g, ResourceActionInfo as gn, ScheduleWorkflow as gr, ScheduleControl as gt, CommandChildren as h, ActionAccessInfo as hn, ScheduleRun as hr, EventsHub as ht, ActionConfigWithAuthorize as i, PluginEndpointContext as in, EventRecorder as ir, BrickSocketSender as it, ResourceActionAccess as j, PluginInfo as jn, HttpMethod as jr, isControlEvent as jt, ProxyOptions as k, PluginContext as kn, port as kr, StandardErrorCode as kt, ActionSchema as l, ResourcePlugin as ln, RetryDecision as lr, SocketEmitOptions as lt, Command as m, ServicePluginContext as mn, ScheduleConfig as mr, EventsDefinition as mt, ActionAccessPolicy as n, InstalledPlugin as nn, EventEnvelope as nr, BrickSocketReconnectOptions as nt, ActionContext as o, PluginRouteRegistrar as on, EventsOptions as or, SocketBroker as ot, ChildChanges as p, ServicePlugin as pn, Schedule as pr, SocketSchemas as pt, ValidationError as q, resolveSecrets as qn, foreignKey as qt, ActionConfig as r, PLUGIN_KIND as rn, EventListener as rr, BrickSocketSchema as rt, ActionErrorDefinition as s, PluginRouteScope as sn, EventsWorld as sr, SocketBrokerMessage as st, Action as t, ContextOf as tn, EventDelivery as tr, BrickSocketHandlerError as tt, ArchitectureSchema as u, ResourcePluginAPI as un, ServiceEvents as ur, SocketEventArgs as ut, CommandErrors as v, PostgresScheduleTable as vn, defineSchedule as vr, ScheduleState as vt, InferTableInsert as w, OutboxTable as wn, crudEventSource as wr, DashboardUser as wt, DuplicateNameError as x, ScheduleTable as xn, EventRef as xr, DASHBOARD_IDENTITY_HEADER as xt, CommandRow as y, SQLiteScheduleTable as yn, CrudEventOperation as yr, Dispatcher as yt, ServiceOptions as z, SecretOptions as zn, PostgresDatabase as zt };
2508
3199
  //# sourceMappingURL=types.d.ts.map