@eltjs/eca 0.0.0-stage → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 ezzabuzaid
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,201 @@
1
- # Temporary Holding Version
1
+ # @eltjs/eca
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A user wants to know when the data in a warehouse starts to match a condition. For example: "when my card purchases in the first 10 days of a month pass 200 JOD, tell me". An agent writes the condition as code with SQL in it. A condition reads the warehouse at two positions, before and after, and it gives what became true between them. The host keeps one cursor for each rule, gives it to each evaluation, and saves the cursor that it gets back with the matches. eca keeps nothing. The model is Event–Condition–Action (ECA), from active databases: a new position of the warehouse is the event, and the host does the action.
4
+
5
+ The words in these documents have one meaning each. See the glossary in [CONTEXT.md](./CONTEXT.md).
6
+
7
+ ## Use it
8
+
9
+ The host makes one `Eca` with its warehouse and a clock. It starts each new rule, and then evaluates its rules when it wants:
10
+
11
+ ```ts
12
+ import { Eca } from '@eltjs/eca';
13
+
14
+ const eca = new Eca<DatabaseSync, { month: string; spent: number }>({
15
+ warehouse,
16
+ clock: globalThis,
17
+ });
18
+ const spend = { condition: new EarlyMonthSpend() };
19
+ cursors.set(spend, await eca.start());
20
+
21
+ for await (const outcome of eca.evaluate(
22
+ [...cursors].map(([rule, cursor]) => ({ rule, cursor })),
23
+ )) {
24
+ if ('expired' in outcome) continue; // the host decides; see below
25
+ await transaction(async (tx) => {
26
+ for (const { month, spent } of outcome.matches)
27
+ await outbox(
28
+ tx,
29
+ `You spent ${spent} JOD in the first 10 days of ${month}.`,
30
+ );
31
+ await saveCursor(tx, outcome.rule, outcome.cursor);
32
+ });
33
+ }
34
+ ```
35
+
36
+ - A rule is the host's own object with a `condition`. Each outcome carries it back as `outcome.rule`, with the host's own type, so a rule can hold what the host needs, such as the name its cursor is saved under.
37
+ - `start()` gives the cursor of a new rule: the newest position of the warehouse, now. The rule matches only what becomes true after it.
38
+ - `evaluate(rules)` gives one outcome for each rule, in order. The host saves its matches and its cursor in one transaction of its own, so a stop between them loses no match and repeats none.
39
+ - The two type parameters are the handle of the warehouse and the data of a match. Give a union when the rules have different data.
40
+ - The host decides when to evaluate: after each pass, on a timer, or when a user asks. See [ADR 0001](./docs/adr/0001-the-host-decides-when-a-rule-is-evaluated.md).
41
+
42
+ ## Give eca the warehouse
43
+
44
+ eca does not open the warehouse, and it does not know what holds it. The host gives a `Warehouse` with two methods:
45
+
46
+ - `stable(after)` gives the positions after a position, in ascending order, or `{ expired }`. A position names a commit where no pass is half done.
47
+ - `read(position?)` gives a reading of the warehouse as of a position, or as of its newest one: `{ sql, position, at }`, which eca disposes, or `{ expired }`.
48
+
49
+ elt's SQLite and Postgres destinations give both. The adapter is two lines:
50
+
51
+ ```ts
52
+ import type { DatabaseSync } from 'node:sqlite';
53
+
54
+ import type { Warehouse } from '@eltjs/eca';
55
+
56
+ const warehouse: Warehouse<DatabaseSync> = {
57
+ stable: async (after) => destination.positions(after),
58
+ read: async (position) => destination.reading(position),
59
+ };
60
+ ```
61
+
62
+ A Postgres destination gives a `postgres.Sql` reading, whose reader views read the database as of the position. See [ADR 0005](./docs/adr/0005-eca-reads-the-warehouse-through-a-port.md).
63
+
64
+ ## Write a condition
65
+
66
+ A condition has one method: `evaluate(before, after)`. Each argument is a reading: `sql`, the handle of the warehouse as of a position, and `at`, the time that the reading stands for. It resolves to what matches in `after` that did not match in `before`:
67
+
68
+ ```ts
69
+ import type { DatabaseSync } from 'node:sqlite';
70
+
71
+ import type { Condition, Reading } from '@eltjs/eca';
72
+
73
+ // The months whose card purchases of Arab Bank in days 1 to 10 pass 200 JOD,
74
+ // on the clock of the user, by the time of the SMS, in fils.
75
+ function overLimit(sql: DatabaseSync): Map<string, number> {
76
+ const fils = new Map<string, number>();
77
+ for (const { text, date } of sql
78
+ .prepare(`SELECT text, date FROM messages WHERE handle = 'Arab Bank'`)
79
+ .all()) {
80
+ if (typeof text !== 'string' || typeof date !== 'string') continue;
81
+ const amount =
82
+ /تم قيد حركة شراء من حسابكم .* بمبلغ JOD (\d+)\.(\d{3}) /u.exec(text);
83
+ if (amount === null) continue;
84
+ const day = Temporal.Instant.from(date).toZonedDateTimeISO('Asia/Amman');
85
+ if (day.day > 10) continue;
86
+ const month = day.toPlainDate().toPlainYearMonth().toString();
87
+ fils.set(
88
+ month,
89
+ (fils.get(month) ?? 0) + Number(`${amount[1]}${amount[2]}`),
90
+ );
91
+ }
92
+ return new Map([...fils].filter(([, spent]) => spent > 200_000));
93
+ }
94
+
95
+ class EarlyMonthSpend implements Condition<
96
+ DatabaseSync,
97
+ { month: string; spent: number }
98
+ > {
99
+ async evaluate(before: Reading<DatabaseSync>, after: Reading<DatabaseSync>) {
100
+ const was = overLimit(before.sql);
101
+ return [...overLimit(after.sql)]
102
+ .filter(([month]) => !was.has(month))
103
+ .map(([month, spent]) => ({ month, spent: spent / 1000 }));
104
+ }
105
+ }
106
+ ```
107
+
108
+ - The pattern is "true after, and not true before". What to compare is the condition's own choice: here a month, or an id, a day, or one text.
109
+ - The condition parses its own data. SQL reads the rows, and the code reads the text. See [ADR 0004](./docs/adr/0004-each-condition-parses-its-own-data.md).
110
+ - A condition on time reads `before.at` and `after.at`: a deadline that passes is one with `before.at < due <= after.at`. Each evaluation starts at the `at` where the last one ended, so it matches once.
111
+ - Judge a window by the time in the data, not by the time of the evaluation. A commit can be late.
112
+
113
+ ## The walk
114
+
115
+ `evaluate` walks each rule from its cursor over each position after it. In each step, one thing moves between `before` and `after`:
116
+
117
+ 1. Time moves up to the commit of the next position, with the data as it was.
118
+ 2. The data moves to the next position, at that time.
119
+ 3. After the last position, time moves up to now.
120
+
121
+ Thus:
122
+
123
+ - A key that stops matching and matches again between two evaluations matches again. A rule that the host evaluates once a day hears of each crossing of the day.
124
+ - A deadline that passes while a task is open matches, also when a later position closed the task, because it is read with the data of that time.
125
+ - A step in which nothing moves is skipped. With no new position, the walk is one step: time, from the cursor up to now.
126
+ - At most two readings are open at once.
127
+
128
+ See [ADR 0010](./docs/adr/0010-eca-is-a-stateless-reader-over-warehouse-positions.md).
129
+
130
+ ## Outcomes
131
+
132
+ | Outcome | When | The cursor |
133
+ | ---------------------------------- | ------------------------------------------------------ | --------------------------- |
134
+ | `{ rule, matches, cursor }` | The walk ended | At the newest position, now |
135
+ | `{ rule, matches, error, cursor }` | The condition threw at a step | After the last good step |
136
+ | `{ rule, expired }` | The warehouse can no longer read the cursor's position | None |
137
+
138
+ - A failure keeps the matches of the steps before it. The next evaluation goes on from the last good step, so a failure that passes, such as a lock, loses nothing. The other rules of the call still run. See [ADR 0008](./docs/adr/0008-a-failing-condition-is-yielded-with-the-matches-before-it.md).
139
+ - A position expires when it is older than the retention of the warehouse, or when a fresh run made the warehouse again. The reason says which. The host decides what to do: start the rule again with `start()`, or tell the user. eca never skips it silently.
140
+ - A cursor that eca did not make is a `TypeError`. A warehouse with no position yet makes `start()` throw: load it first.
141
+
142
+ ## Remove, pause and resume a rule
143
+
144
+ eca keeps nothing, so these need no API:
145
+
146
+ - **Remove** a rule: stop giving its cursor, and delete it.
147
+ - **Pause** a rule: keep its cursor, and do not give it.
148
+ - **Resume** a rule: give its cursor again. The walk covers each position that it missed, within the retention of the warehouse.
149
+
150
+ ## What eca does not do
151
+
152
+ - No store. The host saves the cursor of each rule, with its matches.
153
+ - No schedule. The host evaluates when it wants; a condition on time matches when the host evaluates after the time passed.
154
+ - No news of a match whose data changed, or of a match that stopped, unless the condition asks for it. "True after and not before" is the condition's own choice.
155
+ - No routing. Each evaluation evaluates the rules that the host gives. A condition can read the whole warehouse.
156
+
157
+ ## The same concepts in other systems
158
+
159
+ | This package | Other systems |
160
+ | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
161
+ | Rule: event, condition, action | ECA rules of active databases (HiPAC, 1988); Home Assistant automations: trigger, condition, action |
162
+ | Position, `stable(after)` | SQL Server change tracking: `CHANGE_TRACKING_CURRENT_VERSION`, `CHANGETABLE(… @since)`; Kafka's last stable offset |
163
+ | Reading as of a position | SQL:2011 system-versioned tables, `FOR SYSTEM_TIME AS OF` |
164
+ | Expired position | `CHANGE_TRACKING_MIN_VALID_VERSION`; a Kafka offset older than the log's retention |
165
+ | Cursor that the host saves | A Kafka consumer's committed offset, saved with its output in one transaction |
166
+ | Matches and cursor in one transaction | The transactional outbox |
167
+ | Warehouse port and the host's adapter | Ports and adapters; the `Dialect` of Kysely |
168
+
169
+ ## Documentation
170
+
171
+ - [ADR 0001: The host decides when a rule is evaluated](./docs/adr/0001-the-host-decides-when-a-rule-is-evaluated.md)
172
+ - [ADR 0002: A new rule starts from a baseline](./docs/adr/0002-a-new-rule-starts-from-a-baseline.md) (superseded)
173
+ - [ADR 0003: The host acts on each outcome](./docs/adr/0003-the-host-acts-on-each-outcome.md)
174
+ - [ADR 0004: Each condition parses its own data](./docs/adr/0004-each-condition-parses-its-own-data.md)
175
+ - [ADR 0005: eca reads the warehouse through a port](./docs/adr/0005-eca-reads-the-warehouse-through-a-port.md)
176
+ - [ADR 0006: eca keeps no state across restarts](./docs/adr/0006-eca-keeps-no-state-across-restarts.md) (superseded)
177
+ - [ADR 0007: eca yields only new matches](./docs/adr/0007-eca-yields-only-new-matches.md) (superseded)
178
+ - [ADR 0008: A failing condition is yielded with the matches before it](./docs/adr/0008-a-failing-condition-is-yielded-with-the-matches-before-it.md)
179
+ - [ADR 0009: A host gives a rule back its keys](./docs/adr/0009-a-host-gives-a-rule-back-its-keys.md) (superseded)
180
+ - [ADR 0010: eca is a stateless reader over warehouse positions](./docs/adr/0010-eca-is-a-stateless-reader-over-warehouse-positions.md)
181
+
182
+ ## Development
183
+
184
+ Run the commands from the workspace root.
185
+
186
+ ```sh
187
+ npx nx run eca:test # builds, then runs the tests
188
+ npx nx run eca:typecheck # formats, lints, then type checks
189
+ npx nx run eca:build # compiles src/ to dist/
190
+ ```
191
+
192
+ The tests run a real elt `Pipeline` into a real SQLite destination, and read it through the destination's positions and readings.
193
+
194
+ ```
195
+ src/
196
+ eca.ts Eca: start, evaluate, and the walk
197
+ rule.ts Rule, Condition, Outcome
198
+ warehouse.ts the Warehouse port and Reading
199
+ index.ts the public exports
200
+ eca.test.ts the tests
201
+ ```
package/dist/eca.d.ts ADDED
@@ -0,0 +1,45 @@
1
+ import type { Outcome, Rule } from './rule.ts';
2
+ import type { Warehouse } from './warehouse.ts';
3
+ /**
4
+ * The time of an evaluation. A host gives `globalThis`; a test can give a
5
+ * clock it moves.
6
+ */
7
+ export type Clock = {
8
+ readonly Temporal: {
9
+ readonly Now: {
10
+ instant(): Temporal.Instant;
11
+ };
12
+ };
13
+ };
14
+ /**
15
+ * Evaluates rules over the warehouse. It keeps nothing: each rule's cursor is
16
+ * the host's, which gives it to each evaluation and saves the one it gets
17
+ * back. A rule the host does not give is not evaluated, so a host removes,
18
+ * pauses and resumes a rule by what it keeps.
19
+ */
20
+ export declare class Eca<Sql, Data> {
21
+ #private;
22
+ constructor({ warehouse, clock, }: {
23
+ readonly warehouse: Warehouse<Sql>;
24
+ readonly clock: Clock;
25
+ });
26
+ /**
27
+ * The cursor of a new rule: the newest position, now. The rule matches only
28
+ * what becomes true after it. A warehouse with no position yet throws: load
29
+ * it first.
30
+ */
31
+ start(): Promise<string>;
32
+ /**
33
+ * One outcome for each rule, in order. Each rule walks from its cursor over
34
+ * each position after it, and in each step its condition evaluates two
35
+ * readings in which one thing moved: time, with the data as it was, up to
36
+ * the commit of the next position; then the data, at that time; and last,
37
+ * time up to now. So a key that stops matching and matches again between
38
+ * two evaluations matches again, and a time that passes is read with the
39
+ * data current then. Every rule of one call ends at the same time.
40
+ */
41
+ evaluate<R extends Rule<Sql, Data>>(rules: Iterable<{
42
+ readonly rule: R;
43
+ readonly cursor: string;
44
+ }>): AsyncGenerator<Outcome<Sql, Data, R>>;
45
+ }
package/dist/eca.js ADDED
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Evaluates rules over the warehouse. It keeps nothing: each rule's cursor is
3
+ * the host's, which gives it to each evaluation and saves the one it gets
4
+ * back. A rule the host does not give is not evaluated, so a host removes,
5
+ * pauses and resumes a rule by what it keeps.
6
+ */
7
+ export class Eca {
8
+ #warehouse;
9
+ #clock;
10
+ constructor({ warehouse, clock, }) {
11
+ this.#warehouse = warehouse;
12
+ this.#clock = clock;
13
+ }
14
+ /**
15
+ * The cursor of a new rule: the newest position, now. The rule matches only
16
+ * what becomes true after it. A warehouse with no position yet throws: load
17
+ * it first.
18
+ */
19
+ async start() {
20
+ const reading = await this.#warehouse.read();
21
+ if ('expired' in reading)
22
+ throw new Error(reading.expired);
23
+ await using _reading = reading;
24
+ return encode({
25
+ position: reading.position,
26
+ at: this.#clock.Temporal.Now.instant(),
27
+ });
28
+ }
29
+ /**
30
+ * One outcome for each rule, in order. Each rule walks from its cursor over
31
+ * each position after it, and in each step its condition evaluates two
32
+ * readings in which one thing moved: time, with the data as it was, up to
33
+ * the commit of the next position; then the data, at that time; and last,
34
+ * time up to now. So a key that stops matching and matches again between
35
+ * two evaluations matches again, and a time that passes is read with the
36
+ * data current then. Every rule of one call ends at the same time.
37
+ */
38
+ async *evaluate(rules) {
39
+ const now = this.#clock.Temporal.Now.instant();
40
+ for (const { rule, cursor } of rules)
41
+ yield await this.#walk(rule, decode(cursor), now);
42
+ }
43
+ // At most two readings are open: a step's before and its after. The before
44
+ // closes once its step has evaluated, so a long pause holds no more.
45
+ async #walk(rule, from, now) {
46
+ const positions = await this.#warehouse.stable(from.position);
47
+ if ('expired' in positions)
48
+ return { rule, expired: positions.expired };
49
+ const opened = await this.#warehouse.read(from.position);
50
+ if ('expired' in opened)
51
+ return { rule, expired: opened.expired };
52
+ let held = opened;
53
+ let before = { sql: opened.sql, ...from };
54
+ const matches = [];
55
+ // Evaluates one step, or gives the outcome of its failure: the cursor
56
+ // stays after the last step that evaluated.
57
+ const step = async (after) => {
58
+ try {
59
+ matches.push(...(await rule.condition.evaluate(before, after)));
60
+ }
61
+ catch (error) {
62
+ return { rule, matches, error, cursor: encode(before) };
63
+ }
64
+ before = after;
65
+ return undefined;
66
+ };
67
+ // A step in which time does not move changes nothing.
68
+ const until = (at) => Temporal.Instant.compare(at, before.at) > 0
69
+ ? step({ ...before, at })
70
+ : undefined;
71
+ try {
72
+ for (const position of positions) {
73
+ const reading = await this.#warehouse.read(position);
74
+ if ('expired' in reading)
75
+ return { rule, expired: reading.expired };
76
+ try {
77
+ const at = latest(reading.at, before.at, now);
78
+ const failed = (await until(at)) ??
79
+ (await step({ sql: reading.sql, position, at }));
80
+ if (failed !== undefined)
81
+ return failed;
82
+ }
83
+ finally {
84
+ await dispose(held);
85
+ held = reading;
86
+ }
87
+ }
88
+ return (await until(now)) ?? { rule, matches, cursor: encode(before) };
89
+ }
90
+ finally {
91
+ await dispose(held);
92
+ }
93
+ }
94
+ }
95
+ async function dispose(resource) {
96
+ if (Symbol.asyncDispose in resource)
97
+ await resource[Symbol.asyncDispose]();
98
+ else
99
+ resource[Symbol.dispose]();
100
+ }
101
+ // The commit time of a position, kept within the walk: never before the step
102
+ // it follows, as a position can become stable after an evaluation that came
103
+ // later than its commit, and never past the evaluation's time.
104
+ function latest(at, floor, ceiling) {
105
+ if (Temporal.Instant.compare(at, floor) < 0)
106
+ return floor;
107
+ if (Temporal.Instant.compare(at, ceiling) > 0)
108
+ return ceiling;
109
+ return at;
110
+ }
111
+ function encode({ position, at }) {
112
+ return JSON.stringify({ position, at: at.toString() });
113
+ }
114
+ function decode(cursor) {
115
+ let parsed;
116
+ try {
117
+ parsed = JSON.parse(cursor);
118
+ }
119
+ catch {
120
+ parsed = undefined;
121
+ }
122
+ const position = Reflect.get(Object(parsed), 'position');
123
+ const at = Reflect.get(Object(parsed), 'at');
124
+ if (typeof position !== 'string' || typeof at !== 'string')
125
+ throw new TypeError(`${cursor} is not a cursor that eca made`);
126
+ return { position, at: Temporal.Instant.from(at) };
127
+ }
@@ -0,0 +1,3 @@
1
+ export { type Clock, Eca } from './eca.ts';
2
+ export type { Condition, Outcome, Rule } from './rule.ts';
3
+ export type { Reading, Warehouse } from './warehouse.ts';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { Eca } from './eca.js';
package/dist/rule.d.ts ADDED
@@ -0,0 +1,41 @@
1
+ import type { Reading } from './warehouse.ts';
2
+ /**
3
+ * What became true between two readings of the warehouse: the agent writes it
4
+ * as code, with SQL in it, and it gives what matches in `after` that did not
5
+ * in `before`. `before.at` and `after.at` bound the time it covers, so a
6
+ * condition on time, such as a deadline that passes, matches once.
7
+ */
8
+ export interface Condition<Sql, Data> {
9
+ evaluate(before: Reading<Sql>, after: Reading<Sql>): Promise<readonly Data[]>;
10
+ }
11
+ /**
12
+ * The host's own object: an outcome carries it back, with the host's own type,
13
+ * so the host knows which rule it is about.
14
+ */
15
+ export type Rule<Sql, Data> = {
16
+ readonly condition: Condition<Sql, Data>;
17
+ };
18
+ /**
19
+ * What one evaluation of a rule gives. The host saves the matches and the new
20
+ * cursor together, in one transaction of its own, and gives that cursor back
21
+ * at the next evaluation.
22
+ * - The walk ended: each match of each step, and the cursor at the newest
23
+ * position.
24
+ * - The condition threw at a step: the matches of the steps before it, the
25
+ * error, and the cursor after the last good step.
26
+ * - The cursor names a position that the warehouse can no longer read, such
27
+ * as one older than its retention or of a warehouse made again.
28
+ */
29
+ export type Outcome<Sql, Data, R extends Rule<Sql, Data> = Rule<Sql, Data>> = {
30
+ readonly rule: R;
31
+ readonly matches: readonly Data[];
32
+ readonly cursor: string;
33
+ } | {
34
+ readonly rule: R;
35
+ readonly matches: readonly Data[];
36
+ readonly error: unknown;
37
+ readonly cursor: string;
38
+ } | {
39
+ readonly rule: R;
40
+ readonly expired: string;
41
+ };
package/dist/rule.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The warehouse as of one position: `sql` reads it as it was there, and
3
+ * `at` is the time that the reading stands for.
4
+ */
5
+ export type Reading<Sql> = {
6
+ readonly sql: Sql;
7
+ readonly position: string;
8
+ readonly at: Temporal.Instant;
9
+ };
10
+ /**
11
+ * What eca needs of the warehouse that its rules read, such as elt's SQLite
12
+ * or Postgres destination. The host gives it, so eca never learns where the
13
+ * data lives. A position names a commit where no pass is half done; one that
14
+ * the warehouse can no longer read gives `{ expired }`.
15
+ */
16
+ export interface Warehouse<Sql> {
17
+ stable(after: string): Promise<readonly string[] | {
18
+ readonly expired: string;
19
+ }>;
20
+ read(position?: string): Promise<(Reading<Sql> & (AsyncDisposable | Disposable)) | {
21
+ readonly expired: string;
22
+ }>;
23
+ }
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@eltjs/eca",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.2",
4
+ "description": "Event-condition-action rules over a warehouse that elt loads: a condition reads the warehouse at two positions, and the host saves each rule's cursor with what became true between them.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/ezzabuzaid/elt",
9
+ "directory": "packages/eca"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/ezzabuzaid/elt/issues"
13
+ },
14
+ "homepage": "https://github.com/ezzabuzaid/elt/tree/main/packages/eca#readme",
15
+ "keywords": [
16
+ "elt",
17
+ "eca",
18
+ "event-condition-action",
19
+ "rules",
20
+ "alerts",
21
+ "warehouse"
22
+ ],
23
+ "type": "module",
24
+ "sideEffects": false,
25
+ "exports": {
26
+ "./package.json": "./package.json",
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "default": "./dist/index.js"
30
+ }
31
+ },
32
+ "files": [
33
+ "dist",
34
+ "!dist/spec/**",
35
+ "!**/*.tsbuildinfo",
36
+ "!**/*.test.*"
37
+ ],
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "engines": {
42
+ "node": ">=26"
43
+ },
44
+ "devDependencies": {
45
+ "@eltjs/elt": "^0.3.2",
46
+ "@eltjs/elt-sqlite": "^0.3.2",
47
+ "@zukhruf/sqlite-open": "^0.8.10",
48
+ "@zukhruf/testing": "^0.8.10"
49
+ }
50
+ }