interaqt 1.1.2 → 1.2.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.
- package/agent/agentspace/knowledge/generator/api-reference.md +19 -21
- package/agent/agentspace/knowledge/generator/computation-implementation.md +6 -0
- package/agent/agentspace/knowledge/generator/integration-implementation-handler.md +2 -0
- package/agent/agentspace/knowledge/usage/04-reactive-computations.md +8 -0
- package/agent/agentspace/knowledge/usage/05-interactions.md +13 -0
- package/agent/agentspace/knowledge/usage/10-async-computations.md +13 -0
- package/agent/agentspace/knowledge/usage/13-testing.md +12 -2
- package/agent/agentspace/knowledge/usage/14-api-reference.md +10 -0
- package/agent/agentspace/knowledge/usage/18-api-exports-reference.md +6 -1
- package/agent/agentspace/knowledge/usage/20-postgresql-concurrency-migration.md +105 -0
- package/agent/agentspace/knowledge/usage/README.md +1 -0
- package/agent/skill/interaqt-patterns.md +41 -36
- package/agent/skill/interaqt-recipes.md +164 -108
- package/agent/skill/interaqt-reference.md +264 -75
- package/dist/core/Custom.d.ts +18 -0
- package/dist/core/Custom.d.ts.map +1 -1
- package/dist/core/EventSource.d.ts +17 -0
- package/dist/core/EventSource.d.ts.map +1 -1
- package/dist/drivers/PGLite.d.ts +2 -0
- package/dist/drivers/PGLite.d.ts.map +1 -1
- package/dist/drivers/PostgreSQL.d.ts +27 -5
- package/dist/drivers/PostgreSQL.d.ts.map +1 -1
- package/dist/drivers/SQLite.d.ts +2 -0
- package/dist/drivers/SQLite.d.ts.map +1 -1
- package/dist/index.js +3651 -3042
- package/dist/index.js.map +1 -1
- package/dist/runtime/ComputationSourceMap.d.ts.map +1 -1
- package/dist/runtime/Controller.d.ts +1 -0
- package/dist/runtime/Controller.d.ts.map +1 -1
- package/dist/runtime/MonoSystem.d.ts +2 -0
- package/dist/runtime/MonoSystem.d.ts.map +1 -1
- package/dist/runtime/Scheduler.d.ts +14 -1
- package/dist/runtime/Scheduler.d.ts.map +1 -1
- package/dist/runtime/System.d.ts +40 -6
- package/dist/runtime/System.d.ts.map +1 -1
- package/dist/runtime/computations/Any.d.ts.map +1 -1
- package/dist/runtime/computations/Average.d.ts +2 -2
- package/dist/runtime/computations/Average.d.ts.map +1 -1
- package/dist/runtime/computations/Computation.d.ts +17 -0
- package/dist/runtime/computations/Computation.d.ts.map +1 -1
- package/dist/runtime/computations/Count.d.ts +5 -1
- package/dist/runtime/computations/Count.d.ts.map +1 -1
- package/dist/runtime/computations/Every.d.ts +1 -2
- package/dist/runtime/computations/Every.d.ts.map +1 -1
- package/dist/runtime/computations/StateMachine.d.ts.map +1 -1
- package/dist/runtime/computations/Summation.d.ts +3 -1
- package/dist/runtime/computations/Summation.d.ts.map +1 -1
- package/dist/runtime/computations/Transform.d.ts.map +1 -1
- package/dist/runtime/computations/WeightedSummation.d.ts +3 -1
- package/dist/runtime/computations/WeightedSummation.d.ts.map +1 -1
- package/dist/runtime/index.d.ts +1 -0
- package/dist/runtime/index.d.ts.map +1 -1
- package/dist/runtime/transaction.d.ts +15 -0
- package/dist/runtime/transaction.d.ts.map +1 -0
- package/dist/storage/erstorage/EntityQueryHandle.d.ts +1 -0
- package/dist/storage/erstorage/EntityQueryHandle.d.ts.map +1 -1
- package/dist/storage/erstorage/QueryExecutor.d.ts +1 -1
- package/dist/storage/erstorage/QueryExecutor.d.ts.map +1 -1
- package/dist/storage/erstorage/RecordQueryAgent.d.ts +1 -0
- package/dist/storage/erstorage/RecordQueryAgent.d.ts.map +1 -1
- package/package.json +2 -1
|
@@ -553,7 +553,7 @@ EventSource.create<TArgs, TResult>(
|
|
|
553
553
|
```typescript
|
|
554
554
|
async function(this: Controller, args: TArgs): Promise<TResult>
|
|
555
555
|
```
|
|
556
|
-
- `config.afterDispatch` (function, optional): Hook called
|
|
556
|
+
- `config.afterDispatch` (function, optional): Hook called inside the retryable transaction attempt. Can return additional context, but must be retry-safe and must not perform irreversible external IO.
|
|
557
557
|
```typescript
|
|
558
558
|
async function(this: Controller, args: TArgs, result: { data?: TResult }): Promise<Record<string, unknown> | void>
|
|
559
559
|
```
|
|
@@ -664,7 +664,7 @@ const result = await controller.dispatch(webhookSource, {
|
|
|
664
664
|
2. `guard` runs before event processing; throw to reject the event
|
|
665
665
|
3. `mapEventData` converts dispatch args into the format stored in the entity
|
|
666
666
|
4. `resolve` returns data to the caller (useful for query-type events)
|
|
667
|
-
5. `afterDispatch` runs
|
|
667
|
+
5. `afterDispatch` runs inside the retryable transaction attempt and can return additional context
|
|
668
668
|
6. The Controller automatically registers the event source's entity if not already in the entities list
|
|
669
669
|
7. Interaction is a built-in EventSource type that provides pre-built `guard`, `mapEventData`, and `resolve` implementations
|
|
670
670
|
|
|
@@ -1631,6 +1631,13 @@ Custom.create(config: CustomConfig): CustomInstance
|
|
|
1631
1631
|
- For accessing dictionaries: use `type: 'global'` with `source: DictionaryInstance`
|
|
1632
1632
|
- `config.useLastValue` (boolean, optional): Whether to use last computed value in incremental computation
|
|
1633
1633
|
- `config.attributeQuery` (AttributeQueryData, optional): Attribute query configuration
|
|
1634
|
+
- `config.concurrency` (`'serializable' | 'atomic-safe'`, optional): Defaults to `'serializable'`. Serializable custom computations are retried in PostgreSQL `SERIALIZABLE` transactions. Use `'atomic-safe'` only when the callback is explicitly written with atomic state, idempotent patches, or other safe primitives.
|
|
1635
|
+
|
|
1636
|
+
**Retry safety**
|
|
1637
|
+
|
|
1638
|
+
Custom `compute`, `incrementalCompute`, `incrementalPatchCompute`, and `asyncReturn` callbacks may be replayed after transaction retry. Keep them deterministic and avoid irreversible external IO. Put post-commit external work in `recordMutationSideEffects`.
|
|
1639
|
+
|
|
1640
|
+
For async custom computations, `ComputationResult.async({ freshnessKey })` can override the default freshness stream. Property async freshness is scoped to the host record, global async freshness is scoped to the global result, and entity/relation async freshness defaults to the result target.
|
|
1634
1641
|
|
|
1635
1642
|
**Examples**
|
|
1636
1643
|
|
|
@@ -3376,7 +3383,7 @@ type DispatchResponse = {
|
|
|
3376
3383
|
2. Execute `guard` (if provided and `ignoreGuard` is false)
|
|
3377
3384
|
3. Map event data via `mapEventData` and create event record
|
|
3378
3385
|
4. Execute `resolve` (if provided) - returns data
|
|
3379
|
-
5. Execute `afterDispatch` (if provided) - returns context
|
|
3386
|
+
5. Execute `afterDispatch` (if provided) inside the retryable transaction attempt - returns context
|
|
3380
3387
|
6. Commit transaction
|
|
3381
3388
|
7. Run RecordMutationSideEffects
|
|
3382
3389
|
|
|
@@ -3465,9 +3472,10 @@ interface Storage {
|
|
|
3465
3472
|
map: any
|
|
3466
3473
|
|
|
3467
3474
|
// Transaction operations
|
|
3468
|
-
|
|
3469
|
-
|
|
3470
|
-
|
|
3475
|
+
runInTransaction: <T>(
|
|
3476
|
+
options: { name?: string; isolation?: 'READ COMMITTED' | 'SERIALIZABLE' },
|
|
3477
|
+
fn: () => Promise<T>
|
|
3478
|
+
) => Promise<T>
|
|
3471
3479
|
|
|
3472
3480
|
// Dictionary-specific API
|
|
3473
3481
|
dict: {
|
|
@@ -3506,22 +3514,12 @@ interface Storage {
|
|
|
3506
3514
|
|
|
3507
3515
|
#### Transaction Operations
|
|
3508
3516
|
|
|
3509
|
-
**
|
|
3510
|
-
|
|
3511
|
-
```typescript
|
|
3512
|
-
await storage.beginTransaction('updateOrder')
|
|
3513
|
-
```
|
|
3514
|
-
|
|
3515
|
-
**commitTransaction(transactionName?: string)**
|
|
3516
|
-
Commit a database transaction.
|
|
3517
|
+
**runInTransaction(options, fn)**
|
|
3518
|
+
Run a callback inside a database transaction. The callback form is the only supported transaction boundary because it keeps the transaction connection bound to the full async chain.
|
|
3517
3519
|
```typescript
|
|
3518
|
-
await storage.
|
|
3519
|
-
|
|
3520
|
-
|
|
3521
|
-
**rollbackTransaction(transactionName?: string)**
|
|
3522
|
-
Rollback a database transaction.
|
|
3523
|
-
```typescript
|
|
3524
|
-
await storage.rollbackTransaction('updateOrder')
|
|
3520
|
+
await storage.runInTransaction({ name: 'updateOrder' }, async () => {
|
|
3521
|
+
await storage.update('Order', match, data)
|
|
3522
|
+
})
|
|
3525
3523
|
```
|
|
3526
3524
|
|
|
3527
3525
|
#### Entity/Relation Operations
|
|
@@ -5,6 +5,12 @@ Computations are the reactive core of interaqt, connecting interactions to entit
|
|
|
5
5
|
|
|
6
6
|
## Types of Computations
|
|
7
7
|
|
|
8
|
+
## Retry Safety
|
|
9
|
+
|
|
10
|
+
Computation callbacks may be replayed under PostgreSQL transaction retry. Keep callbacks deterministic and database-focused. Do not perform irreversible external IO in `compute`, `incrementalCompute`, `incrementalPatchCompute`, Transform callbacks, StateMachine compute functions, or `asyncReturn`.
|
|
11
|
+
|
|
12
|
+
For custom computations, the default concurrency mode is `serializable`; use `concurrency: 'atomic-safe'` only when the callback is explicitly safe under concurrent `READ COMMITTED` execution.
|
|
13
|
+
|
|
8
14
|
### 1. Transform - Creates Entities/Relations
|
|
9
15
|
|
|
10
16
|
**ONLY use in Entity/Relation computation, NEVER in Property!**
|
|
@@ -206,6 +206,8 @@ async setup(controller: Controller) {
|
|
|
206
206
|
|
|
207
207
|
**Purpose**: Define side effects that synchronize reactive data changes to external systems.
|
|
208
208
|
|
|
209
|
+
`RecordMutationSideEffect` is the recommended place for irreversible external IO. Interaction callbacks, custom computation callbacks, `afterDispatch`, and `asyncReturn` may be replayed by PostgreSQL transaction retry; side effects run after the final successful commit.
|
|
210
|
+
|
|
209
211
|
**Use Cases**:
|
|
210
212
|
- Push data mutations to external APIs
|
|
211
213
|
- Publish messages to message queues
|
|
@@ -81,6 +81,14 @@ Reactive computation is a **declarative way of defining data**:
|
|
|
81
81
|
- **Incremental computation**: Framework uses efficient incremental algorithms to avoid unnecessary recomputation
|
|
82
82
|
- **Persistent**: Computation results are stored in the database for fast queries
|
|
83
83
|
|
|
84
|
+
### PostgreSQL Concurrency Guarantees
|
|
85
|
+
|
|
86
|
+
Built-in computations such as Count, Summation, Average, Every, Any, WeightedSummation, StateMachine, and data-based Transform use atomic state updates, row locks, or unique indexes on PostgreSQL. They are safe when multiple Node.js processes share one PostgreSQL database.
|
|
87
|
+
|
|
88
|
+
Custom computations are different because interaqt cannot inspect user callback logic. `Custom.create()` defaults to `concurrency: 'serializable'`, so the framework promotes the transaction to PostgreSQL `SERIALIZABLE` and retries on `40001` / `40P01`. Use `concurrency: 'atomic-safe'` only when the custom computation is explicitly written with atomic state, idempotent patches, or other safe primitives.
|
|
89
|
+
|
|
90
|
+
Because retry replays the transaction attempt, `guard`, `mapEventData`, `resolve`, computation callbacks, `afterDispatch`, and `asyncReturn` must be deterministic and retry-safe. Put irreversible external IO in `recordMutationSideEffects`, which runs after the final commit.
|
|
91
|
+
|
|
84
92
|
### Core Principle: Data Existence
|
|
85
93
|
|
|
86
94
|
In interaqt, all data has its "reason for existence":
|
|
@@ -21,6 +21,19 @@ const result = await controller.callInteraction('CreatePost', {
|
|
|
21
21
|
});
|
|
22
22
|
```
|
|
23
23
|
|
|
24
|
+
## Retry-Safe Interaction Callbacks
|
|
25
|
+
|
|
26
|
+
`Controller.dispatch()` runs interaction processing inside a retryable transaction. PostgreSQL SERIALIZABLE promotion or retryable SQLSTATE errors (`40001`, `40P01`) may replay the transaction attempt.
|
|
27
|
+
|
|
28
|
+
These interaction callbacks must be deterministic and retry-safe:
|
|
29
|
+
|
|
30
|
+
- `guard`
|
|
31
|
+
- `mapEventData`
|
|
32
|
+
- `resolve`
|
|
33
|
+
- `afterDispatch`
|
|
34
|
+
|
|
35
|
+
`afterDispatch` runs before commit inside the retryable transaction attempt. It can return response context or perform retry-safe database work, but it must not perform irreversible external IO. Put emails, webhooks, message publishing, payment calls, and other post-commit external effects in `recordMutationSideEffects`.
|
|
36
|
+
|
|
24
37
|
## Basic Concepts of Interactions
|
|
25
38
|
|
|
26
39
|
### What is an Interaction
|
|
@@ -205,6 +205,19 @@ const currentWeather = await system.storage.get('state', 'currentWeather');
|
|
|
205
205
|
console.log('Current weather:', currentWeather);
|
|
206
206
|
```
|
|
207
207
|
|
|
208
|
+
### Retry and Freshness Semantics
|
|
209
|
+
|
|
210
|
+
`handleAsyncReturn()` runs inside the same retryable transaction model as `Controller.dispatch()`. If PostgreSQL reports a retryable transaction error, or if the async result applies a custom/full-replace path that requires `SERIALIZABLE`, interaqt may replay the async return attempt.
|
|
211
|
+
|
|
212
|
+
Keep `asyncReturn` deterministic and database-focused. Do not send emails, call payment APIs, publish messages, or perform other irreversible external IO from `asyncReturn`; those effects can be duplicated by a retry. Put irreversible post-commit work in `recordMutationSideEffects`.
|
|
213
|
+
|
|
214
|
+
Async tasks also use a freshness key so stale results do not overwrite newer work:
|
|
215
|
+
|
|
216
|
+
- Property async computations default to a key scoped by computation and host record.
|
|
217
|
+
- Global async computations default to a key scoped by computation and global result.
|
|
218
|
+
- Entity and relation async computations default to the result target, which means each target has one global freshness stream.
|
|
219
|
+
- Pass an explicit `freshnessKey` to `ComputationResult.async({ freshnessKey })` when multiple independent async streams should be allowed for the same entity or relation target.
|
|
220
|
+
|
|
208
221
|
## Implementing Entity Async Computations
|
|
209
222
|
|
|
210
223
|
### Use Cases
|
|
@@ -13,10 +13,10 @@ Many LLMs generate incorrect API usage. Here's the correct way to use interaqt t
|
|
|
13
13
|
controller.run() // ❌ No such method
|
|
14
14
|
storage.findByProperty('Entity', 'prop') // ❌ No such method
|
|
15
15
|
controller.execute() // ❌ No such method
|
|
16
|
-
controller.dispatch() // ❌ No such method
|
|
17
16
|
|
|
18
17
|
// ✅ CORRECT: Use these APIs instead
|
|
19
|
-
controller.callInteraction('InteractionName', args) // ✅ Call
|
|
18
|
+
controller.callInteraction('InteractionName', args) // ✅ Call interaction by name
|
|
19
|
+
controller.dispatch(InteractionObject, args) // ✅ Dispatch an event source object
|
|
20
20
|
storage.findOne('Entity', MatchExp) // ✅ Find single record
|
|
21
21
|
storage.find('Entity', MatchExp) // ✅ Find multiple records
|
|
22
22
|
storage.create('Entity', data) // ✅ Create record
|
|
@@ -139,6 +139,16 @@ describe('Feature Tests', () => {
|
|
|
139
139
|
})
|
|
140
140
|
```
|
|
141
141
|
|
|
142
|
+
### PostgreSQL Concurrency Tests
|
|
143
|
+
|
|
144
|
+
For changes that affect runtime transactions, custom computations, async computations, PostgreSQL id generation, or reactive computation state, run the real PostgreSQL suite:
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
INTERAQT_POSTGRES_DATABASE=interaqt_test npm run test:postgres-concurrency
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
This script fails when the database environment variable is missing. Plain `npm test` may skip PostgreSQL-specific tests in local lightweight environments.
|
|
151
|
+
|
|
142
152
|
### Key API Methods
|
|
143
153
|
|
|
144
154
|
#### 1. Controller APIs
|
|
@@ -514,6 +514,16 @@ Transform.create(config: TransformConfig): KlassInstance<typeof Transform>
|
|
|
514
514
|
- `config.callback` (function, required): Transformation function that converts source data to target data
|
|
515
515
|
- `config.attributeQuery` (AttributeQueryData, required): Attribute query configuration
|
|
516
516
|
|
|
517
|
+
### Custom.create()
|
|
518
|
+
|
|
519
|
+
Create a custom computation when built-in computations are not expressive enough.
|
|
520
|
+
|
|
521
|
+
**Concurrency parameter**
|
|
522
|
+
- `config.concurrency` (optional): `'serializable' | 'atomic-safe'`, defaults to `'serializable'`.
|
|
523
|
+
- `'serializable'`: interaqt runs the custom computation in a retryable PostgreSQL `SERIALIZABLE` transaction.
|
|
524
|
+
- `'atomic-safe'`: you explicitly promise the custom computation only uses atomic state, idempotent patches, or other concurrency-safe primitives. Full recompute and entity/relation full replace paths still require SERIALIZABLE even for `atomic-safe` custom computations.
|
|
525
|
+
|
|
526
|
+
Custom callbacks may be replayed after retryable transaction failures. Do not perform irreversible external IO inside custom `compute`, `incrementalCompute`, `incrementalPatchCompute`, or `asyncReturn`; use `recordMutationSideEffects` for post-commit external work.
|
|
517
527
|
|
|
518
528
|
### StateMachine.create()
|
|
519
529
|
|
|
@@ -53,6 +53,9 @@ import {
|
|
|
53
53
|
// Storage and Query
|
|
54
54
|
Controller,
|
|
55
55
|
MonoSystem,
|
|
56
|
+
runWithTransactionRetry,
|
|
57
|
+
isRetryableTransactionError,
|
|
58
|
+
isRequireSerializableRetry,
|
|
56
59
|
|
|
57
60
|
// Dictionary (Global State)
|
|
58
61
|
Dictionary,
|
|
@@ -173,4 +176,6 @@ const controller = new Controller({
|
|
|
173
176
|
|
|
174
177
|
4. **Filtered Entities**: Created using `Entity.create()` with `baseEntity` and `filterCondition`, not a separate import.
|
|
175
178
|
|
|
176
|
-
5. **Database Drivers**: Choose one based on your needs - PGLiteDB for in-memory testing, PostgreSQLDB for production, etc.
|
|
179
|
+
5. **Database Drivers**: Choose one based on your needs - PGLiteDB for in-memory testing, PostgreSQLDB for production, etc.
|
|
180
|
+
|
|
181
|
+
6. **Transaction helpers**: `runWithTransactionRetry`, `isRetryableTransactionError`, and `isRequireSerializableRetry` are exported for advanced runtime integrations and tests. Most application code should use `Controller.dispatch()` or `system.storage.runInTransaction()` instead of calling retry helpers directly.
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# PostgreSQL Concurrency Migration
|
|
2
|
+
|
|
3
|
+
This note summarizes user-visible changes from the PostgreSQL reactive computation concurrency fix.
|
|
4
|
+
|
|
5
|
+
## What Changed
|
|
6
|
+
|
|
7
|
+
interaqt now uses PostgreSQL as the concurrency coordinator for multi-process deployments:
|
|
8
|
+
|
|
9
|
+
- Built-in computations use atomic state updates, row locks, unique indexes, or SERIALIZABLE retry where needed.
|
|
10
|
+
- PostgreSQL id generation uses native sequences instead of writing `_IDS_`.
|
|
11
|
+
- Custom computations default to retryable `SERIALIZABLE` execution.
|
|
12
|
+
- Async return handling runs in a retryable transaction and applies freshness checks.
|
|
13
|
+
|
|
14
|
+
## Callback Replay Rules
|
|
15
|
+
|
|
16
|
+
The following callbacks may be replayed after SERIALIZABLE promotion, `40001`, or `40P01`:
|
|
17
|
+
|
|
18
|
+
- `guard`
|
|
19
|
+
- `mapEventData`
|
|
20
|
+
- `resolve`
|
|
21
|
+
- computation callbacks
|
|
22
|
+
- `afterDispatch`
|
|
23
|
+
- `asyncReturn`
|
|
24
|
+
|
|
25
|
+
Keep these callbacks deterministic. Do not send emails, charge payments, call irreversible external APIs, publish messages, or write non-transactional resources from these callbacks.
|
|
26
|
+
|
|
27
|
+
Use `recordMutationSideEffects` for irreversible external IO. Side effects run after the final successful commit and are not replayed for failed attempts.
|
|
28
|
+
|
|
29
|
+
## Custom Computation Concurrency
|
|
30
|
+
|
|
31
|
+
`Custom.create()` now defaults to:
|
|
32
|
+
|
|
33
|
+
```typescript
|
|
34
|
+
Custom.create({
|
|
35
|
+
name: 'MyComputation',
|
|
36
|
+
concurrency: 'serializable',
|
|
37
|
+
// ...
|
|
38
|
+
})
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Use `concurrency: 'atomic-safe'` only when the custom computation is explicitly safe under concurrent PostgreSQL `READ COMMITTED` execution, for example because it only uses atomic state or idempotent patches.
|
|
42
|
+
|
|
43
|
+
Even with `atomic-safe`, full recompute and entity/relation full replace paths still require SERIALIZABLE.
|
|
44
|
+
|
|
45
|
+
## Async Return Freshness
|
|
46
|
+
|
|
47
|
+
`handleAsyncReturn()` locks the task row and checks whether the task is still current.
|
|
48
|
+
|
|
49
|
+
Default freshness streams:
|
|
50
|
+
|
|
51
|
+
- Property async computation: scoped to the host record.
|
|
52
|
+
- Global async computation: scoped to the global result.
|
|
53
|
+
- Entity/relation async computation: scoped to the result target.
|
|
54
|
+
|
|
55
|
+
Pass an explicit `freshnessKey` when one entity or relation target needs multiple independent async streams:
|
|
56
|
+
|
|
57
|
+
```typescript
|
|
58
|
+
return ComputationResult.async({
|
|
59
|
+
freshnessKey: `tenant:${tenantId}:job:${jobId}`,
|
|
60
|
+
// task args...
|
|
61
|
+
})
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Stale tasks are marked `skipped` and do not call `asyncReturn`.
|
|
65
|
+
|
|
66
|
+
## PostgreSQL ID Sequences
|
|
67
|
+
|
|
68
|
+
PostgreSQL ids are allocated with native sequences.
|
|
69
|
+
|
|
70
|
+
Migration behavior:
|
|
71
|
+
|
|
72
|
+
- New databases start at id `1`.
|
|
73
|
+
- Existing table max id is used to initialize the sequence.
|
|
74
|
+
- Existing `_IDS_` rows are read as legacy migration input when the table exists.
|
|
75
|
+
- Databases without `_IDS_` are supported.
|
|
76
|
+
- Shared physical tables use one sequence per physical table/id field.
|
|
77
|
+
|
|
78
|
+
Do not write `_IDS_` to control ids. `_IDS_` is legacy input only.
|
|
79
|
+
|
|
80
|
+
PostgreSQL sequence gaps are normal after rollback or failed transactions. Do not depend on contiguous ids.
|
|
81
|
+
|
|
82
|
+
## Transaction API
|
|
83
|
+
|
|
84
|
+
Use callback transactions:
|
|
85
|
+
|
|
86
|
+
```typescript
|
|
87
|
+
await system.storage.runInTransaction(
|
|
88
|
+
{ name: 'my-operation', isolation: 'SERIALIZABLE' },
|
|
89
|
+
async () => {
|
|
90
|
+
// transactional work
|
|
91
|
+
}
|
|
92
|
+
)
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Do not use old manual transaction APIs such as `beginTransaction`, `commitTransaction`, or `rollbackTransaction`.
|
|
96
|
+
|
|
97
|
+
## Testing PostgreSQL Concurrency
|
|
98
|
+
|
|
99
|
+
Run the real PostgreSQL concurrency suite with:
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
INTERAQT_POSTGRES_DATABASE=interaqt_test npm run test:postgres-concurrency
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
This script intentionally fails when `INTERAQT_POSTGRES_DATABASE` is missing, so PostgreSQL concurrency coverage cannot silently skip in CI.
|
|
@@ -142,6 +142,7 @@ Remember: **Stop thinking "how to do", start thinking "what is"**!
|
|
|
142
142
|
18. [Performance Optimization](./17-performance-optimization.md) - Performance tips
|
|
143
143
|
19. [API Exports Reference](./18-api-exports-reference.md) - Complete list of available imports
|
|
144
144
|
20. [Common Anti-Patterns](./19-common-anti-patterns.md) - Mistakes to avoid
|
|
145
|
+
21. [PostgreSQL Concurrency Migration](./20-postgresql-concurrency-migration.md) - Retry, async, and sequence migration notes
|
|
145
146
|
|
|
146
147
|
## 📞 Need Help?
|
|
147
148
|
|
|
@@ -15,12 +15,12 @@ const User = Entity.create({
|
|
|
15
15
|
Property.create({ name: 'name', type: 'string' }),
|
|
16
16
|
Property.create({ name: 'email', type: 'string' }),
|
|
17
17
|
Property.create({ name: 'age', type: 'number' }),
|
|
18
|
-
Property.create({ name: 'status', type: 'string', defaultValue: 'active' }),
|
|
18
|
+
Property.create({ name: 'status', type: 'string', defaultValue: () => 'active' }),
|
|
19
19
|
Property.create({ name: 'createdAt', type: 'string', defaultValue: () => new Date().toISOString() }),
|
|
20
20
|
Property.create({
|
|
21
21
|
name: 'fullName',
|
|
22
22
|
type: 'string',
|
|
23
|
-
|
|
23
|
+
computed: (record) => `${record.firstName} ${record.lastName}`
|
|
24
24
|
})
|
|
25
25
|
]
|
|
26
26
|
})
|
|
@@ -52,7 +52,7 @@ The Klass pattern uses `generateUUID()` internally. Manual IDs risk collisions a
|
|
|
52
52
|
### Checklist
|
|
53
53
|
- [ ] Entity name is PascalCase and singular (`User` not `users`)
|
|
54
54
|
- [ ] No manual UUID assignment
|
|
55
|
-
- [ ] Computed properties that depend only on the same record use `
|
|
55
|
+
- [ ] Computed properties that depend only on the same record use `computed`, NOT Transform
|
|
56
56
|
- [ ] Properties with reactive computations (Count, etc.) include `defaultValue`
|
|
57
57
|
|
|
58
58
|
---
|
|
@@ -148,7 +148,7 @@ Without `type`, the framework cannot determine cardinality. ALWAYS explicitly se
|
|
|
148
148
|
| Check ANY related record matches condition | `Any` |
|
|
149
149
|
| Derive new entities from events or other entities | `Transform` (on Entity `computation`) |
|
|
150
150
|
| Update a property value based on state transitions | `StateMachine` (on Property `computation`) |
|
|
151
|
-
| Simple computation from same-record fields | `
|
|
151
|
+
| Simple computation from same-record fields | `computed` (on Property) |
|
|
152
152
|
|
|
153
153
|
```typescript
|
|
154
154
|
import { Entity, Property, Relation, Count, WeightedSummation, Transform, InteractionEventEntity } from 'interaqt'
|
|
@@ -184,12 +184,12 @@ Property.create({
|
|
|
184
184
|
Property.create({
|
|
185
185
|
name: 'formattedPrice',
|
|
186
186
|
type: 'string',
|
|
187
|
-
|
|
187
|
+
computed: (record) => `$${record.price}`
|
|
188
188
|
})
|
|
189
189
|
```
|
|
190
190
|
|
|
191
191
|
### WHY
|
|
192
|
-
Transform creates new records in a computed entity collection. It CANNOT update a single property. Use `
|
|
192
|
+
Transform creates new records in a computed entity collection. It CANNOT update a single property. Use `computed` for same-entity property computations.
|
|
193
193
|
|
|
194
194
|
### WRONG: Transform for counting
|
|
195
195
|
```typescript
|
|
@@ -220,8 +220,8 @@ Count uses incremental algorithms. Transform loads all records into memory, whic
|
|
|
220
220
|
```typescript
|
|
221
221
|
// DON'T — Controller does NOT accept a computations parameter
|
|
222
222
|
const controller = new Controller({
|
|
223
|
-
system, entities, relations,
|
|
224
|
-
|
|
223
|
+
system, entities, relations,
|
|
224
|
+
eventSources: [myComputation], // eventSources is for Interactions, not computations
|
|
225
225
|
})
|
|
226
226
|
```
|
|
227
227
|
|
|
@@ -243,7 +243,7 @@ All computations are declared within the `computation` field of Entity, Relation
|
|
|
243
243
|
- [ ] Transform is on `Entity.computation` or `Relation.computation`, NEVER on `Property.computation`
|
|
244
244
|
- [ ] Count, WeightedSummation, Every, Any are on `Property.computation`
|
|
245
245
|
- [ ] StateMachine is on `Property.computation`
|
|
246
|
-
- [ ] `
|
|
246
|
+
- [ ] `computed` is used for same-record-only property derivations
|
|
247
247
|
- [ ] Properties with computation ALWAYS have `defaultValue`
|
|
248
248
|
- [ ] NEVER pass computations to Controller constructor
|
|
249
249
|
|
|
@@ -261,9 +261,9 @@ const CreatePost = Interaction.create({
|
|
|
261
261
|
action: Action.create({ name: 'createPost' }),
|
|
262
262
|
payload: Payload.create({
|
|
263
263
|
items: [
|
|
264
|
-
PayloadItem.create({ name: 'title', required: true }),
|
|
265
|
-
PayloadItem.create({ name: 'content', required: true }),
|
|
266
|
-
PayloadItem.create({ name: 'postId', base: Post, isRef: true })
|
|
264
|
+
PayloadItem.create({ name: 'title', type: 'string', required: true }),
|
|
265
|
+
PayloadItem.create({ name: 'content', type: 'string', required: true }),
|
|
266
|
+
PayloadItem.create({ name: 'postId', type: 'string', base: Post, isRef: true })
|
|
267
267
|
]
|
|
268
268
|
})
|
|
269
269
|
})
|
|
@@ -310,8 +310,7 @@ const controller = new Controller({
|
|
|
310
310
|
system,
|
|
311
311
|
entities: [User, Post],
|
|
312
312
|
relations: [UserPosts],
|
|
313
|
-
|
|
314
|
-
interactions: [CreatePost],
|
|
313
|
+
eventSources: [CreatePost],
|
|
315
314
|
dict: [],
|
|
316
315
|
recordMutationSideEffects: []
|
|
317
316
|
})
|
|
@@ -319,18 +318,18 @@ const controller = new Controller({
|
|
|
319
318
|
await controller.setup(true)
|
|
320
319
|
```
|
|
321
320
|
|
|
322
|
-
### WRONG: Calling
|
|
321
|
+
### WRONG: Calling dispatch before setup
|
|
323
322
|
```typescript
|
|
324
323
|
// DON'T — setup MUST come first
|
|
325
|
-
const controller = new Controller({ system, entities, relations,
|
|
326
|
-
await controller.
|
|
324
|
+
const controller = new Controller({ system, entities, relations, eventSources: [CreatePost], dict: [] })
|
|
325
|
+
await controller.dispatch(CreatePost, { user: { id: '1' }, payload: { title: 'Hi' } })
|
|
327
326
|
```
|
|
328
327
|
|
|
329
328
|
### CORRECT:
|
|
330
329
|
```typescript
|
|
331
|
-
const controller = new Controller({ system, entities, relations,
|
|
330
|
+
const controller = new Controller({ system, entities, relations, eventSources: [CreatePost], dict: [] })
|
|
332
331
|
await controller.setup(true)
|
|
333
|
-
await controller.
|
|
332
|
+
await controller.dispatch(CreatePost, { user: { id: '1' }, payload: { title: 'Hi' } })
|
|
334
333
|
```
|
|
335
334
|
|
|
336
335
|
### WHY
|
|
@@ -338,15 +337,15 @@ await controller.callInteraction('CreatePost', { user: { id: '1' }, payload: { t
|
|
|
338
337
|
|
|
339
338
|
### Checklist
|
|
340
339
|
- [ ] `system.conceptClass = KlassByName` is set before creating Controller
|
|
341
|
-
- [ ] `controller.setup(true)` is called BEFORE any `
|
|
340
|
+
- [ ] `controller.setup(true)` is called BEFORE any `dispatch`
|
|
342
341
|
- [ ] `dict` contains only Dictionary instances, not computations
|
|
343
342
|
|
|
344
343
|
---
|
|
345
344
|
|
|
346
|
-
## When
|
|
345
|
+
## When Dispatching Interactions
|
|
347
346
|
|
|
348
347
|
```typescript
|
|
349
|
-
const result = await controller.
|
|
348
|
+
const result = await controller.dispatch(CreatePost, {
|
|
350
349
|
user: { id: 'user-1', role: 'author' },
|
|
351
350
|
payload: {
|
|
352
351
|
title: 'My Post',
|
|
@@ -361,17 +360,17 @@ if (result.error) {
|
|
|
361
360
|
|
|
362
361
|
### WRONG: Using try-catch for error handling
|
|
363
362
|
```typescript
|
|
364
|
-
// DON'T — interaqt does NOT throw exceptions
|
|
363
|
+
// DON'T — interaqt does NOT throw exceptions by default
|
|
365
364
|
try {
|
|
366
|
-
await controller.
|
|
365
|
+
await controller.dispatch(CreatePost, { user: { id: '1' }, payload: {} })
|
|
367
366
|
} catch (e) {
|
|
368
|
-
// This code will NEVER execute
|
|
367
|
+
// This code will NEVER execute (unless forceThrowDispatchError is true)
|
|
369
368
|
}
|
|
370
369
|
```
|
|
371
370
|
|
|
372
371
|
### CORRECT:
|
|
373
372
|
```typescript
|
|
374
|
-
const result = await controller.
|
|
373
|
+
const result = await controller.dispatch(CreatePost, {
|
|
375
374
|
user: { id: '1' },
|
|
376
375
|
payload: {}
|
|
377
376
|
})
|
|
@@ -381,20 +380,26 @@ if (result.error) {
|
|
|
381
380
|
```
|
|
382
381
|
|
|
383
382
|
### WHY
|
|
384
|
-
The framework catches all errors internally and returns them via `result.error`. Exceptions are never thrown to callers.
|
|
383
|
+
The framework catches all errors internally and returns them via `result.error`. Exceptions are never thrown to callers (unless `forceThrowDispatchError: true` is set on Controller).
|
|
384
|
+
|
|
385
|
+
### WRONG: Passing a name string instead of instance
|
|
386
|
+
```typescript
|
|
387
|
+
// DON'T — first argument must be the event source instance, not a string
|
|
388
|
+
controller.dispatch('CreatePost', payload)
|
|
389
|
+
```
|
|
385
390
|
|
|
386
391
|
### WRONG: Using non-existent API methods
|
|
387
392
|
```typescript
|
|
388
393
|
// DON'T — these methods do NOT exist
|
|
389
|
-
controller.
|
|
394
|
+
controller.callInteraction('CreatePost', payload)
|
|
390
395
|
controller.run()
|
|
391
396
|
controller.execute()
|
|
392
397
|
```
|
|
393
398
|
|
|
394
399
|
### CORRECT:
|
|
395
400
|
```typescript
|
|
396
|
-
// The ONLY method to trigger interactions
|
|
397
|
-
await controller.
|
|
401
|
+
// The ONLY method to trigger interactions — first arg is the instance reference
|
|
402
|
+
await controller.dispatch(CreatePost, {
|
|
398
403
|
user: { id: 'user-1' },
|
|
399
404
|
payload: { title: 'Hi' }
|
|
400
405
|
})
|
|
@@ -403,7 +408,7 @@ await controller.callInteraction('CreatePost', {
|
|
|
403
408
|
### Checklist
|
|
404
409
|
- [ ] ALWAYS pass a `user` object with at least `id`
|
|
405
410
|
- [ ] ALWAYS check `result.error` — NEVER use try-catch
|
|
406
|
-
- [ ] Use `controller.
|
|
411
|
+
- [ ] Use `controller.dispatch(eventSourceInstance, args)` — first arg is the instance, NOT a name string
|
|
407
412
|
|
|
408
413
|
---
|
|
409
414
|
|
|
@@ -486,13 +491,13 @@ describe('Feature', () => {
|
|
|
486
491
|
system = new MonoSystem(new PGLiteDB())
|
|
487
492
|
system.conceptClass = KlassByName
|
|
488
493
|
controller = new Controller({
|
|
489
|
-
system, entities, relations,
|
|
494
|
+
system, entities, relations, eventSources, dict: [], recordMutationSideEffects: []
|
|
490
495
|
})
|
|
491
496
|
await controller.setup(true)
|
|
492
497
|
})
|
|
493
498
|
|
|
494
499
|
test('creates a post via interaction', async () => {
|
|
495
|
-
const result = await controller.
|
|
500
|
+
const result = await controller.dispatch(CreatePost, {
|
|
496
501
|
user: { id: 'user-1' },
|
|
497
502
|
payload: { title: 'Test', content: 'Hello' }
|
|
498
503
|
})
|
|
@@ -518,8 +523,8 @@ const post = await system.storage.create('Post', { title: 'Test', content: 'Hell
|
|
|
518
523
|
|
|
519
524
|
### CORRECT:
|
|
520
525
|
```typescript
|
|
521
|
-
// Use
|
|
522
|
-
const result = await controller.
|
|
526
|
+
// Use dispatch to test business logic
|
|
527
|
+
const result = await controller.dispatch(CreatePost, {
|
|
523
528
|
user: { id: 'user-1' },
|
|
524
529
|
payload: { title: 'Test', content: 'Hello' }
|
|
525
530
|
})
|
|
@@ -531,6 +536,6 @@ const result = await controller.callInteraction('CreatePost', {
|
|
|
531
536
|
### Checklist
|
|
532
537
|
- [ ] Use `PGLiteDB` for test databases
|
|
533
538
|
- [ ] Call `controller.setup(true)` in `beforeEach`
|
|
534
|
-
- [ ] Test business logic through `
|
|
539
|
+
- [ ] Test business logic through `controller.dispatch`, not direct storage
|
|
535
540
|
- [ ] Check `result.error` — NEVER use try-catch
|
|
536
541
|
- [ ] ALWAYS pass `attributeQuery` when asserting on query results
|