Skip to content

Commit 91a9c94

Browse files
committed
docs: enhance README of projection packages
1 parent 1cef260 commit 91a9c94

File tree

5 files changed

+153
-176
lines changed

5 files changed

+153
-176
lines changed

demo/README.md

-27
This file was deleted.

demo/projection-typeorm.js

-131
This file was deleted.

packages/projection-typeorm/README.md

+42-6
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,48 @@
11
# Cardano JS SDK | projection-typeorm
22

3-
Project Chain Sync events into PostgreSQL via TypeORM.
3+
This package is a library of utilities for projecting `ProjectionEvent`s into PostgreSQL database via [TypeORM](https://github.com/typeorm/typeorm).
44

5-
## Adding new projections
5+
If you're interested in generic projection types and utilities, see [projection](../projection) package.
66

7-
1. Create a new mapper that maps the block into something that you want to project (see [withStakeKeys](../projection/src/operators/Mappers/certificates/withStakeKeys.ts) as an example).
8-
2. Create a new granular TypeORM store (see [storeStakeKeys](./src/operators/storeStakeKeys.ts)) as an example.
7+
If you're interested in projector application as run by Lace, see [setup](../cardano-services/src/Projection) and [README](../cardano-services/README.md) in `cardano-services` package.
8+
9+
## TypeormStabilityWindowBuffer
10+
11+
Writes the block data into [block_data](./src/entity/BlockData.entity.ts) table and implements [StabilityWindowBuffer](../projection/README.md#stabilitywindowbuffer) interface that is required by [Bootstrap.fromCardanoNode](../projection/README.md#bootstrapfromcardanonode)
12+
13+
### TypeormStabilityWindowBuffer.storeBlockData
14+
15+
This method is intended to be called as part of PostgreSQL transaction that writes all other data from the event. It is important to keep StabilityWindowBuffer consistent with projection state.
16+
17+
## createTypeormTipTracker
18+
19+
Queries and emits local tip (latest block header) from [block](./src/entity/Block.entity.ts) table. Returns:
20+
- an operator that should be applied after processing the block
21+
- an `Observable<TipOrOrgin>` that is required by [Bootstrap.fromCardanoNode](../projection/README.md#bootstrapfromcardanonode)
22+
23+
## withTypeormTransaction
24+
25+
Adds TypeORM context (query runner) to each event and starts a PostgreSQL transaction. Subsequent operators can utilize this context to perform database operations (see [Store Operators](#store-operators)).
926

10-
### Demo
27+
## typeormTransactionCommit
1128

12-
See [demo/projection-typeorm.js](../../demo/)
29+
Commits PostgreSQL transaction started by [withTypeormTransaction](#withtypeormtransaction) and removes TypeORM context from the event object.
30+
31+
## createObservableConnection
32+
33+
Utility to initialize TypeORM data source.
34+
Returns an Observable that can be used as a dependency for
35+
[withTypeormTransaction](#withtypeormtransaction), [TypeormStabilityWindowBuffer](#typeormstabilitywindowbuffer) and [createTypeormTipTracker](#createtypeormtiptracker).
36+
37+
## Store Operators
38+
39+
[Each store operator](./src/operators) takes in an `Observable<WithTypeormContext & T>`, where `T` depends on what the specific operator needs. Usually it depends on one or more of the [Mappers](../projection/README.md#mappers).
40+
41+
Most store operators will just write some data into the database and emit the same event object (unchanged). However, they can also add additional context to the events (see [storeAssets](./src/operators/storeAssets.ts) which adds new total supplies for each minted asset).
42+
43+
---
44+
45+
### Adding New Store Operators
46+
47+
1. (optional) Create a new mapper that maps the block into something that you want to project (see [withStakeKeys](../projection/src/operators/Mappers/certificates/withStakeKeys.ts) as an example).
48+
2. Create a new granular TypeORM store (see [storeStakeKeys](./src/operators/storeStakeKeys.ts)) as an example.

packages/projection/README.md

+96-11
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,105 @@
11
# Cardano JS SDK | projection
22

3-
Chain Sync event projection utilities.
3+
This package is a library of generic projection types and utilities.
44

5-
## Summary
5+
> [!TIP]
6+
> [Guide to Projections and Read Models in Event-Driven Architecture](https://event-driven.io/en/projections_and_read_models_in_event_driven_architecture/)
67
7-
Projection is based on [RxJS](https://rxjs.dev/), where source observable of Chain Sync events is processed with various [operators](./src/operators/).
8+
If you're interested in projecting into PostgreSQL database, see [projection-typeorm](../projection-typeorm) package.
89

9-
There are no restrictions what an operator can do - you can utilize the full power of RxJS which makes it very flexible.
10+
If you're interested in projector application as run by Lace, see [setup](../cardano-services/src/Projection) and [README](../cardano-services/README.md) in `cardano-services` package.
1011

11-
All operators implemented in this package are extending the source event object with extra properties, e.g.
12+
## Prerequisites
1213

13-
```ts
14-
Bootstrap.fromCardanoNode({ buffer, cardanoNode, logger }).pipe(
15-
Mappers.withStakeKeys(),
16-
tap(({ stakeKeys }) => console.log('stakeKeys', stakeKeys)),
17-
Mappers.withStakePools(),
18-
tap(({ stakePools }) => console.log('stakePools', stakePools))
14+
In order to understand how `cardano-js-sdk` projections work, you'll first need basic understanding of:
15+
16+
- [Observables](https://github.com/tc39/proposal-observable) (we're using [RxJS](https://rxjs.dev/) implementation)
17+
- Chain Sync mini protocol (well explained in [Ogmios docs](https://ogmios.dev/mini-protocols/local-chain-sync/))
18+
19+
## Types
20+
21+
### ProjectionEvent\<ExtraProps>
22+
23+
All projections start by obtaining a source/producer<sup>1</sup>, which is an `Observable<ProjectionEvent<{}>>`. These events are very similar to Chain Sync events, but there are some important differences:
24+
25+
1. Block format is compatible with types from `@cardano-sdk/core` package.
26+
2. Events include some additional properties: `{eraSumaries, genesisParameters, epochNo, crossEpochBoundary}`.
27+
3. `RollBackward` events include block data (instead of just specifying the rollback point), and are emitted once for **each** rolled back block.
28+
29+
#### ExtraProps (Generic Parameter)
30+
31+
Source observable can be piped through a series of RxJS operators, which may add some properties to the event. In a nutshell, `ProjectionEvent<T> = ProjectionEvent<{}> & T`. For more detail see [Mappers](#mappers).
32+
33+
### StabilityWindowBuffer
34+
35+
Since `ProjectionEvent{eventType=RollBackward}` includes block data, we must store some number (at least `k`, which is the "security parameter") of latest blocks so that if a fork/rollback happens, we can call `StabilityWindowBuffer.getBlock(hash)` in order to build a valid `ProjectionEvent`.
36+
37+
### ObservableCardanoNode
38+
39+
This is our interface to Chain Sync and Local State Query protocols of Cardano node. The only implementation available in `cardano-js-sdk` is `OgmiosObservableCardanoNode`.
40+
41+
## Utilities
42+
43+
### Bootstrap.fromCardanoNode
44+
45+
Creates a projection source (`Observable<ProjectionEvent>`) from:
46+
47+
- [ObservableCardanoNode](#observablecardanonode)
48+
- [StabilityWindowBuffer](#stabilitywindowbuffer)
49+
- `Observable<TipOrOrigin>` that emits block header of last processed event (local tip). This is used to find intersection point.
50+
51+
```mermaid
52+
---
53+
title: Bootstrap Algorithm
54+
---
55+
flowchart LR
56+
subscribe[Subscribe] --> find-intersect{Find node\nintersection\nwith local tip}
57+
find-intersect --> |Found| start[Start ChainSync\nfrom intersection]
58+
start --> get-event{Get event\nfrom node,\ncheck type}
59+
get-event --> |RollBackward| get-block[Get block from StabilityWindowBuffer]
60+
get-event --> |RollForward| hydrate
61+
start --> hydrate[Hydrate event\nwith additional\npropertes]
62+
hydrate --> emit[Emit\nProjectionEvent]
63+
find-intersect --> |Not Found| get-block[Get block from\nStabilityWindowBuffer]
64+
get-block --> rollback[Create\nRollBackward\nevent]
65+
rollback --> hydrate
66+
rollback --> wait[Wait for\nlocal tip change]
67+
wait --> is-rollback-point{Is rollback point?}
68+
is-rollback-point --> |No| get-block
69+
is-rollback-point --> |Yes| started-sync{Already started\nChain Sync?}
70+
started-sync --> |Yes| get-event
71+
started-sync --> |No| find-intersect
72+
```
73+
74+
### Mappers
75+
76+
Projections are typically
77+
78+
1. Interpreting the block (e.g. extracting some relevant properties from all transactions). `Mappers` is a namespace that contains a collection of RxJS operators that process the ProjectionEvent (block) and emit a new event object that has some additional properties.
79+
2. Doing something with it (e.g. store into the database).
80+
81+
Here's an example:
82+
83+
```typescript
84+
// source$: Observable<ProjectionEvent<{}>>
85+
source$.pipe(
86+
// policyId is a parameter that should be provided
87+
// by handle issuer, e.g. ADA Handle
88+
Mappers.withHandles({ policyId }),
89+
// type WithHandles = { handles: HandleOwnership; }
90+
// Event type can also be inferred (no need for explicit type declaration)
91+
tap((event: ProjectionEvent<WithHandles>) => {
92+
console.log('Handles found by withHandles operator', event.handles);
93+
})
1994
);
2095
```
96+
97+
### Other Utils
98+
99+
#### InMemoryStabilityWindowBuffer
100+
101+
If your application doesn't need persistence, you can use in-memory implementation of [StabilityWindowBuffer](#stabilitywindowbuffer), which can also be used as local tip tracker for Bootstrap (provides `Observable<TipOrOrigin>`).
102+
103+
---
104+
105+
_<sup>1</sup>Currently our projection source observable is not a pure 'Producer', as events have a `requestNext` method that is used to control the source. This is subject to change in the future._

packages/projection/src/types.ts

+15-1
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,20 @@ export type WithEpochBoundary = { crossEpochBoundary: boolean };
5555

5656
export type BootstrapExtraProps = WithNetworkInfo & WithEpochNo & WithEpochBoundary;
5757

58+
/**
59+
* All projections start by obtaining a source/producer, which is an `Observable<ProjectionEvent<{}>>`.
60+
* These events are very similar to Chain Sync events, but there are some important differences:
61+
*
62+
* 1. Block format is compatible with types from `@cardano-sdk/core` package.
63+
* 2. Events include some additional properties: `{eraSumaries, genesisParameters, epochNo, crossEpochBoundary}`.
64+
* 3. `RollBackward` events include block data (instead of just specifying the rollback point),
65+
* and are emitted once for **each** rolled back block.
66+
*
67+
* #### ExtraProps (Generic Parameter)
68+
*
69+
* Source observable can be piped through a series of RxJS operators, which may add some properties to the event.
70+
* In an nutshell, `type ProjectionEvent<T> = ProjectionEvent<{}> & T`.
71+
*/
5872
export type ProjectionEvent<ExtraProps = {}> = UnifiedExtChainSyncEvent<BootstrapExtraProps & ExtraProps>;
5973

6074
export type ProjectionOperator<ExtraPropsIn, ExtraPropsOut = {}> = UnifiedExtChainSyncOperator<
@@ -63,7 +77,7 @@ export type ProjectionOperator<ExtraPropsIn, ExtraPropsOut = {}> = UnifiedExtCha
6377
>;
6478

6579
/**
66-
* Keeps track of blocks within stability window (computed as numSlots=3k/f).
80+
* Keeps track of blocks within stability window (computed as numSlots=3k/f, or k blocks).
6781
*
6882
* With current mainnet protocol parameters (Dec 2022),
6983
* it can be up to 2160 ("securityParam"/"k") blocks,

0 commit comments

Comments
 (0)