@cratis/pi 7.137.0 → 7.138.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.
Files changed (21) hide show
  1. package/package/corpus/harnesses/copilot/instructions/glossary.instructions.md +4 -0
  2. package/package/corpus/product-sync.json +1 -0
  3. package/package/corpus/rules/glossary.md +4 -0
  4. package/package/corpus/skills/cratis-arc-neo4j/LICENSE +2 -0
  5. package/package/corpus/skills/cratis-arc-neo4j/SKILL.md +166 -0
  6. package/package/corpus/skills/cratis-arc-neo4j/references/connection-resolution-and-single-mode.md +51 -0
  7. package/package/corpus/skills/cratis-chronicle-client-elixir/SKILL.md +12 -1
  8. package/package/corpus/skills/cratis-chronicle-client-elixir/references/graphs.md +123 -0
  9. package/package/corpus/skills/cratis-chronicle-projection/SKILL.md +18 -1
  10. package/package/corpus/skills/cratis-chronicle-projection/references/graph-projections.md +159 -0
  11. package/package/corpus/skills/cratis-screenplay-projections/SKILL.md +15 -2
  12. package/package/corpus/skills/cratis-screenplay-projections/references/graphs.md +150 -0
  13. package/package/corpus/skills/cratis-screenplay-specifications/SKILL.md +25 -23
  14. package/package/corpus/skills/cratis-screenplay-specifications/references/graph-steps.md +90 -0
  15. package/package/corpus/skills/cratis-screenplay-specifications/references/vocabulary.md +6 -0
  16. package/package/corpus/skills/cratis-screenplay-toolchain/references/screenplay-contract.json +7212 -1834
  17. package/package/corpus/skills/cratis-screenplay-toolchain/references/screenplay-contract.version +1 -1
  18. package/package/corpus/skills/cratis-stage-rendering-and-sandbox/SKILL.md +2 -0
  19. package/package/corpus/skills/cratis-stage-rendering-and-sandbox/references/graphs.md +52 -0
  20. package/package/profile-catalog.json +1 -0
  21. package/package.json +1 -1
@@ -41,6 +41,10 @@ One precise line per load-bearing term, so the same word means the same thing ev
41
41
  - **Observer** — Chronicle's umbrella for anything consuming an event sequence (projection, reducer, reactor); carries subscription / replay / **quarantine** state. Projection replay and catch-up each walk the sequence in one globally ordered job step; a new catch-up failure stops that step. Full replay is inactive and completion does not resume a quarantined observer (Chronicle v19.50.1, `Documentation/concepts/observers.mdx`, `Observation/Jobs/{CatchUpObserver,ReplayObserver}.cs` under `Source/Kernel/Core/`).
42
42
  - **Sink** — where a read model is persisted (MongoDB, EF Core).
43
43
  - **AutoMap** — Chronicle's on-by-default mapping of matching event→read-model property names; **never call `.AutoMap()`**.
44
+ - **Graph** — a named property graph that events build through a graph projection: nodes, edges and their properties. Derived state like a read model; nothing writes to it directly.
45
+ - **Node** — a graph element with a label, one unique key and primitive properties. The label is the type name.
46
+ - **Edge** — a directed, typed graph relationship from a source node to a target node, identified by type, source key and target key (plus an identifying property when several edges of one type may join the same pair).
47
+ - **Graph sink** — where a graph is persisted (Neo4j, or the in-memory graph); it applies the five idempotent graph operations, separate from the `ISink` of document read models.
44
48
  - **Query** — a `static` method on a `[ReadModel]`; returns derived state, **snapshot** (one-shot) or **observable** (live).
45
49
 
46
50
  ## Write side
@@ -78,6 +78,7 @@
78
78
  "cratis-arc-command-validation",
79
79
  "cratis-arc-ef-core-migration",
80
80
  "cratis-arc-hosting",
81
+ "cratis-arc-neo4j",
81
82
  "cratis-arc-observable-query-http",
82
83
  "cratis-arc-query-paging",
83
84
  "cratis-arc-react-page",
@@ -40,6 +40,10 @@ One precise line per load-bearing term, so the same word means the same thing ev
40
40
  - **Observer** — Chronicle's umbrella for anything consuming an event sequence (projection, reducer, reactor); carries subscription / replay / **quarantine** state. Projection replay and catch-up each walk the sequence in one globally ordered job step; a new catch-up failure stops that step. Full replay is inactive and completion does not resume a quarantined observer (Chronicle v19.50.1, `Documentation/concepts/observers.mdx`, `Observation/Jobs/{CatchUpObserver,ReplayObserver}.cs` under `Source/Kernel/Core/`).
41
41
  - **Sink** — where a read model is persisted (MongoDB, EF Core).
42
42
  - **AutoMap** — Chronicle's on-by-default mapping of matching event→read-model property names; **never call `.AutoMap()`**.
43
+ - **Graph** — a named property graph that events build through a graph projection: nodes, edges and their properties. Derived state like a read model; nothing writes to it directly.
44
+ - **Node** — a graph element with a label, one unique key and primitive properties. The label is the type name.
45
+ - **Edge** — a directed, typed graph relationship from a source node to a target node, identified by type, source key and target key (plus an identifying property when several edges of one type may join the same pair).
46
+ - **Graph sink** — where a graph is persisted (Neo4j, or the in-memory graph); it applies the five idempotent graph operations, separate from the `ISink` of document read models.
43
47
  - **Query** — a `static` method on a `[ReadModel]`; returns derived state, **snapshot** (one-shot) or **observable** (live).
44
48
 
45
49
  ## Write side
@@ -0,0 +1,2 @@
1
+ Copyright (c) Cratis. All rights reserved.
2
+ Licensed under the MIT license. See LICENSE file in the project root for full license information.
@@ -0,0 +1,166 @@
1
+ ---
2
+ name: cratis-arc-neo4j
3
+ description: Use when an Arc C# query or command must read a Neo4j graph, inject the tenant-aware IGraphSession, run Cypher, or choose the graph database per tenant. Not for projecting events onto a graph or for MongoDB documents.
4
+ license: MIT
5
+ ---
6
+
7
+ <!-- Copyright (c) Cratis. All rights reserved. -->
8
+ <!-- Licensed under the MIT license. See LICENSE file in the project root for full license information. -->
9
+
10
+ # Read a Neo4j graph from Arc
11
+
12
+ `Cratis.Arc.Neo4j` gives a model-bound query, a command's `Provide()` method or any
13
+ scoped service a session on the Neo4j database of the current tenant. It reads the
14
+ graph; it does not build it. A graph is what events leave behind: a graph projection
15
+ (`cratis-chronicle-projection`, or `cratis-screenplay-projections` in a model) writes
16
+ nodes and relationships through Chronicle's Neo4j sink, and nothing writes to the
17
+ graph from a query. Arc does not need Chronicle or event sourcing to read a graph.
18
+
19
+ Requires `Cratis.Arc.Neo4j` 22.168.0 (`dotnet list package`); older Arc releases have
20
+ no graph session, so read the graph with the Neo4j driver directly.
21
+
22
+ - An accepted `.play` model under the model root covers the behavior, or the
23
+ repository is opted in (per `general.md` "Model first"): change the model first
24
+ with `cratis-screenplay-event-modeling`. The graph shape comes from the model's
25
+ `graph` declaration; this skill covers only the read side in code.
26
+
27
+ ## When a graph read fits
28
+
29
+ Use a graph query for traversals: who belongs to which group, nested groups,
30
+ paths, "everyone who reaches this node". Use a document read model
31
+ (`cratis-chronicle-read-model`, MongoDB or EF Core) for lookups by key, lists and
32
+ anything shaped like one row per entity. Do not read a graph for what one document
33
+ read already answers.
34
+
35
+ ## Set it up
36
+
37
+ ```bash
38
+ dotnet add package Cratis.Arc.Neo4j
39
+ ```
40
+
41
+ ```json
42
+ {
43
+ "Cratis": {
44
+ "Neo4j": {
45
+ "Server": "bolt://localhost:7687",
46
+ "EventStore": "Organization",
47
+ "UserName": "neo4j",
48
+ "PasswordSecret": "NEO4J_PASSWORD"
49
+ }
50
+ }
51
+ }
52
+ ```
53
+
54
+ `Server` and `EventStore` are required. `EventStore` is the event store whose graph
55
+ Chronicle's sink writes; it is the first part of the database name. `PasswordSecret`
56
+ names a configuration key (environment variable, user secrets, key vault), so the
57
+ password is never written in options. `Password` exists for local development only
58
+ and loses to `PasswordSecret`. Other options: `DatabasePrefix`, `DatabaseMode`,
59
+ `SingleDatabase`, `ConnectionResolution`.
60
+
61
+ ```csharp
62
+ builder.AddCratisArc(configureBuilder: arc => arc.WithNeo4j());
63
+ ```
64
+
65
+ Use `WithNeo4j()` on the Arc builder, or `AddCratisNeo4j()` on the service
66
+ collection for existing host code, never both. Starting the host does not connect;
67
+ the first query checks connectivity and permissions.
68
+
69
+ ## Query
70
+
71
+ ```csharp
72
+ [ReadModel]
73
+ public record GroupMember(PersonId PersonId, PersonName Name)
74
+ {
75
+ public static Task<IReadOnlyList<GroupMember>> MembersOf(GroupId groupId, IGraphSession graph) =>
76
+ graph.Query<GroupMember>(
77
+ "MATCH (p:Person)-[:MEMBER_OF]->(g:Group { groupId: $groupId }) RETURN p.personId AS personId, p.name AS name ORDER BY p.name",
78
+ new { groupId });
79
+ }
80
+ ```
81
+
82
+ - `Query<T>` maps every row; `QuerySingle<T>` maps the first row or gives `null`.
83
+ - Parameters are an object's public properties or a dictionary.
84
+ - One returned column maps to a primitive, concept or list of those. Several
85
+ columns match constructor parameters or settable properties by name, ignoring
86
+ case. `RETURN p` maps a node's properties.
87
+ - `Run` returns the driver's `IResultCursor` and `Session` exposes `IAsyncSession`
88
+ for transaction functions. Pass `graph.Parameters(new { ... })` so the converted
89
+ parameters, including `$namespace`, are used.
90
+ - Concepts bind as their inner value and are rebuilt from results. A `Guid` is
91
+ bound and read as its string, a `decimal` as `double`, an enum by name. This is
92
+ what the Chronicle sink stores, so a key written from an event is found by the
93
+ same parameter.
94
+
95
+ ## The session is a read session
96
+
97
+ The scoped `IGraphSession` opens with `AccessMode.Read`; the server refuses a query
98
+ that writes. Change the graph by appending events. For data no projection owns, open
99
+ a write session with `IGraphSessionFactory.Open(AccessMode.Write)` and dispose it.
100
+ `IGraphSession` is scoped: a singleton that captures it keeps the database of an
101
+ earlier scope.
102
+
103
+ ## Pick the tenant's database
104
+
105
+ `IGraphNamespaceResolver` maps the tenant to a namespace like the Chronicle
106
+ integration: a named tenant is the namespace of the same name, and `TenantId.NotSet`
107
+ and `TenantId.Default` are `Default`. The database is `[prefix-]eventStore[-namespace]`
108
+ and must equal what Chronicle's sink writes, so use the shipped algorithm
109
+ (`GraphDatabaseName.For(prefix, eventStore, namespace)`) rather than hand-building
110
+ names:
111
+
112
+ 1. Compose the name; the `Default` namespace (exact, case-sensitive), `null` or empty adds no segment.
113
+ 2. Lower-case it and replace every character outside `[a-z0-9-]` with `-`.
114
+ 3. Prefix `g-` when it does not start with a letter.
115
+ 4. When step 2 changed the lower-cased name, or the result is over 63 or under 3
116
+ characters, cut to 54 and append `-` and the first 8 lower-case hex of the SHA-256
117
+ of the unsanitized UTF-8 name.
118
+
119
+ | Event store | Namespace | Database |
120
+ | --- | --- | --- |
121
+ | `Orders` | `Default` | `orders` |
122
+ | `Orders` | `acme` or `Acme` | `orders-acme` |
123
+ | `Orders` | `Acme Corp` | `orders-acme-corp-` plus 8 hex of the hash |
124
+ | `1Orders` | `Default` | `g-1orders` |
125
+
126
+ Lower-casing alone adds no hash, so namespaces that differ only by case share a
127
+ database. Replace the naming only when you also change what writes the database:
128
+ `WithDatabaseNameResolver<T>()` and `WithNamespaceResolver<T>()` on the Neo4j builder.
129
+
130
+ Read references/connection-resolution-and-single-mode.md when tenants need their
131
+ own server, database or credentials, or when the host runs against Neo4j Community
132
+ Edition.
133
+
134
+ ## Test
135
+
136
+ `Cratis.Arc.Neo4j.Testing` replaces the session without a server:
137
+
138
+ ```csharp
139
+ var services = new ServiceCollection();
140
+ var graph = services.UseGraphSessionSubstitute();
141
+ graph.Returns("MATCH (p:Person)", new GroupMember(personId, new PersonName("Ada")));
142
+
143
+ var members = await GroupMember.MembersOf(groupId, graph);
144
+ ```
145
+
146
+ `Executions` lists the Cypher run with its converted parameters; assert on it to
147
+ prove a query was bound and filtered. `Run` and `Session` throw on the substitute,
148
+ so keep row mapping on `Query` and `QuerySingle`, and cover driver calls with an
149
+ integration test against Neo4j.
150
+
151
+ ## Pitfalls
152
+
153
+ - A query leaves out `_namespace` in `Single` database mode and reads across tenants.
154
+ - A resolved `Database` (template or endpoint) bypasses the naming algorithm, so
155
+ Arc reads a database nothing writes to unless the sink resolves the same one.
156
+ - A property starting with an underscore is the sink's own; never return it as data.
157
+ - A key keeps its type in the graph: `1` and `"1"` are different nodes.
158
+ - Reading the graph from a command to decide an invariant is advisory only; a
159
+ graph is eventually consistent with the event log.
160
+
161
+ ## Verify
162
+
163
+ Run the host with a query against a development graph: it returns the expected
164
+ rows, and with `DatabaseMode` `PerNamespace` another tenant's request returns none
165
+ of them. A specification using `UseGraphSessionSubstitute` passes, and `Executions`
166
+ shows the `$namespace` parameter. `dotnet build` finishes with zero warnings.
@@ -0,0 +1,51 @@
1
+ <!-- Copyright (c) Cratis. All rights reserved. -->
2
+ <!-- Licensed under the MIT license. See LICENSE file in the project root for full license information. -->
3
+
4
+ # Connection resolution and single-database mode
5
+
6
+ ## Single-database mode
7
+
8
+ `DatabaseMode` `Single` puts every namespace in `SingleDatabase` (`neo4j` by
9
+ default), the only user database on Neo4j Community Edition. Chronicle stamps the
10
+ namespace as `_namespace` on every node and relationship, and nothing else separates
11
+ tenants. Use it for development and tests, never production. Filter every pattern
12
+ with the `$namespace` parameter the session adds to each query:
13
+
14
+ ```cypher
15
+ MATCH (p:Person)-[:MEMBER_OF]->(g:Group)
16
+ WHERE p._namespace = $namespace AND g._namespace = $namespace
17
+ RETURN p.name AS name, g.name AS group
18
+ ```
19
+
20
+ In `PerNamespace` mode the parameter is still given and harmless, so one query can
21
+ carry the filter in both modes. `GraphParameters.Namespace` and
22
+ `GraphParameters.NamespaceProperty` name the parameter and the property.
23
+
24
+ ## Connection resolution
25
+
26
+ Resolution lets the platform choose server, database or credentials per tenant.
27
+ Arc resolves once per service scope, and the scoped `IGraphSession` and
28
+ `IGraphSessionFactory` share it. A resolved part applies as follows:
29
+
30
+ | Resolved part | Effect |
31
+ | --- | --- |
32
+ | `ConnectionString` | A Bolt URI that replaces `Server` |
33
+ | `Database` | Replaces the computed database name |
34
+ | `Identity.UserName` and `Identity.Password` | Basic authentication |
35
+ | `Identity.AccessToken` | Bearer token |
36
+
37
+ With no resolved identity the configured user and password apply. Drivers are shared
38
+ per server and resolution, never across credentials. When the server rejects a
39
+ credential or token, Arc drops the cached resolution and resolves again.
40
+
41
+ To resolve only the identity over HTTP and keep the shared server and naming:
42
+
43
+ ```csharp
44
+ builder.AddCratisArc(configureBuilder: arc => arc.WithNeo4j(
45
+ configureOptions: neo4j => neo4j.ConnectionResolution.Identity.UseHttp(new Uri("https://platform.example/connections"))));
46
+ ```
47
+
48
+ A template placing tenants by rule goes in the `ConnectionResolution` section with
49
+ `"Resolver": "Template"` and a `Template` holding a `Database` such as
50
+ `graph-{tenant}`. The default tenant then resolves to `graph-Default`, so point the
51
+ Chronicle sink at the same destination.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: cratis-chronicle-client-elixir
3
- description: Use when adding Chronicle to an Elixir OTP application, defining its event structs or handling client append outcomes. Not for JVM or Node.js clients; use the corresponding Chronicle client sibling.
3
+ description: Use when adding Chronicle to an Elixir OTP application, defining its event structs, declaring a graph with the node and edge DSL, or handling client append outcomes. Not for JVM or Node.js clients; use the corresponding Chronicle client sibling.
4
4
  license: MIT
5
5
  ---
6
6
 
@@ -276,6 +276,17 @@ registered definitions.
276
276
 
277
277
  **Live updates arrive as messages, not as a stream.** `ReadModels.watch/2` and `subscribe/2` send `{:chronicle_read_model_changed, module, %Changeset{}}` and error messages to the calling process, which needs a `handle_info` for each. Read [references/read-models.md](references/read-models.md) when subscribing, filtering, observing collections, previewing or waiting for a projection.
278
278
 
279
+ #### Graph projections — `node` and `edge`
280
+
281
+ A graph is a module with `use Chronicle.Graphs.Graph, id: "Organization"`; its nodes
282
+ and edges are structs with `use Chronicle.Graphs.Node` and `use Chronicle.Graphs.Edge,
283
+ type: "MEMBER_OF"`. Inside the graph, `node Mod, key: :field do ... end` and
284
+ `edge Mod, source: A, target: B do ... end` hold `from/2` and `removed_with/2`
285
+ (`detach: true` on a node). Register it with `graphs: [Mod]` on `Chronicle.Client`.
286
+ Requires cratis_chronicle 3.20.0 (check `mix deps`). Read
287
+ [references/graphs.md](references/graphs.md) for the options, counters, edge identity,
288
+ compiler checks and sink choice. Pin `id:`; renaming it registers a different projection.
289
+
279
290
  ## Guarding decisions, testing and more
280
291
 
281
292
  Read the reference that matches the task:
@@ -0,0 +1,123 @@
1
+ # Graph projections with the node and edge DSL
2
+
3
+ ## Contents
4
+
5
+ - Declaring a graph
6
+ - Options
7
+ - Counters and edge identity
8
+ - Compiler checks
9
+ - Registering and choosing the sink
10
+ - Not supported yet
11
+
12
+ ## Declaring a graph
13
+
14
+ ```elixir
15
+ defmodule MyApp.Graphs.Person do
16
+ use Chronicle.Graphs.Node
17
+ defstruct person_id: "", name: ""
18
+ end
19
+
20
+ defmodule MyApp.Graphs.Group do
21
+ use Chronicle.Graphs.Node
22
+ defstruct group_id: "", name: ""
23
+ end
24
+
25
+ defmodule MyApp.Graphs.MemberOf do
26
+ use Chronicle.Graphs.Edge, type: "MEMBER_OF"
27
+ defstruct since: ""
28
+ end
29
+
30
+ defmodule MyApp.Graphs.Organization do
31
+ use Chronicle.Graphs.Graph, id: "Organization"
32
+
33
+ node MyApp.Graphs.Person, key: :person_id do
34
+ from MyApp.Events.PersonRegistered, key: :person_id, set: [name: :name]
35
+ removed_with MyApp.Events.PersonRemoved, key: :person_id, detach: true
36
+ end
37
+
38
+ node MyApp.Graphs.Group, key: :group_id do
39
+ from MyApp.Events.GroupCreated, key: :group_id
40
+ end
41
+
42
+ edge MyApp.Graphs.MemberOf, source: MyApp.Graphs.Person, target: MyApp.Graphs.Group do
43
+ from MyApp.Events.MemberAdded,
44
+ source_key: :person_id,
45
+ target_key: :group_id,
46
+ set: [since: {:event_context, :occurred}]
47
+
48
+ removed_with MyApp.Events.MemberRemoved, source_key: :person_id, target_key: :group_id
49
+ end
50
+ end
51
+ ```
52
+
53
+ The struct fields are the properties, typed by their `defstruct` defaults; a property
54
+ is a primitive or a list of primitives. A node's label and an edge's type default to the
55
+ last segment of the module name (`label:` / `type:` choose another). Property names are
56
+ the `camelCase` of the field names, as in the .NET client, so both register the same definition.
57
+ `node/3` names the unique key field with `key:`; `edge/3` names its `source:` and
58
+ `target:` nodes, both declared with `node` in the same graph. The end nodes are not
59
+ properties of the edge.
60
+
61
+ ## Options
62
+
63
+ - `from/2`: a node takes `key:`, an edge `source_key:` and `target_key:` (event
64
+ properties; each defaults to the event source id). `update_only: true` on a node's
65
+ `from` changes the node only when it exists.
66
+ - `removed_with/2`: deletes the node or edge. A node accepts `detach: true` (deletes
67
+ its edges too; without it a node that still has edges cannot be deleted). An edge
68
+ cannot detach.
69
+ - Property options as for read models: `set:` (event property, `:event_source_id`,
70
+ `{:event_context, :occurred}`, `{:value, v}`), `add:`, `subtract:`, `increment:`,
71
+ `decrement:`, `count:`, `clear:`.
72
+
73
+ ## Counters and edge identity
74
+
75
+ ```elixir
76
+ node MyApp.Graphs.Team, key: :team_id do
77
+ from MyApp.Events.TeamFormed, key: :team_id
78
+ from MyApp.Events.TeamMemberJoined, key: :team_id, increment: :member_count
79
+ from MyApp.Events.TeamMemberLeft, key: :team_id, decrement: :member_count
80
+ end
81
+ ```
82
+
83
+ `identified_by:` on an edge names a struct field that distinguishes several edges of
84
+ one type between the same two nodes. Every `from` and `removed_with` of that edge
85
+ must then name the identity event property with `identity:` or have one of the same
86
+ name as the field. A sink that cannot hold several edges between one pair rejects it.
87
+
88
+ ```elixir
89
+ edge MyApp.Graphs.Visited,
90
+ source: MyApp.Graphs.Customer,
91
+ target: MyApp.Graphs.Shop,
92
+ identified_by: :visit_id do
93
+ from MyApp.Events.ShopVisited, source_key: :customer_id, target_key: :shop_id, count: :times
94
+ end
95
+ ```
96
+
97
+ ## Compiler checks
98
+
99
+ A graph that cannot work raises a `CompileError` naming the declaration line when an
100
+ edge names a source or target that is not a node of the graph; a node has no `key:` or
101
+ the key is not a struct field; an edge's `removed_with` asks to `detach`; a node or edge
102
+ struct has a nested struct or map property; an identified edge has an event with no
103
+ identity; or a mapped field, option or module is unknown.
104
+
105
+ ## Registering and choosing the sink
106
+
107
+ ```elixir
108
+ {Chronicle.Client,
109
+ connection_string: "chronicle://localhost:35000",
110
+ event_store: "my-store",
111
+ default_graph_sink_type_id: :in_memory_graph,
112
+ graphs: [MyApp.Graphs.Organization]}
113
+ ```
114
+
115
+ The client registers the graph as a read model stored by the graph sink and as the
116
+ projection that fills it, with `id:` as read model name and projection identifier.
117
+ `:default_graph_sink_type_id` defaults to `:neo4j`; use `:in_memory_graph` for development
118
+ and tests. `:default_sink_type_id` still chooses the sink of document read models only.
119
+
120
+ ## Not supported yet
121
+
122
+ The client does not read a graph (use the engine driver) and `Chronicle.Testing` has no
123
+ graph scenario, so test a graph by asserting the definition it registers.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: cratis-chronicle-projection
3
- description: Use when populating an existing Chronicle read model through event mappings, structured joins or lifecycle variants, or diagnosing projection startup failures. Not for new query surfaces or external side effects.
3
+ description: Use when populating an existing Chronicle read model through event mappings, structured joins or lifecycle variants, projecting events onto a graph with nodes and edges, or diagnosing projection startup failures. Not for new query surfaces or external side effects.
4
4
  license: MIT
5
5
  ---
6
6
 
@@ -263,6 +263,23 @@ or a reactor rather than annotating the projection.
263
263
  Their two optional arguments are in **opposite order**: `[FromAll(contextProperty,
264
264
  property)]` and `[FromEvery(property, contextProperty)]`. Name them.
265
265
 
266
+ ## Graph projections — nodes and edges
267
+
268
+ A graph projection turns events into idempotent operations on a property graph
269
+ instead of folding them into a document. It uses the same observer, event routing,
270
+ key and property expressions, replay and failed-partition handling. Requires
271
+ Chronicle 19.129.0 (check the installed `Cratis.Chronicle` package version).
272
+
273
+ Choose a graph when the questions are traversals (membership, nesting, paths) and a
274
+ document read model when they are lookups by key. Design it by reading the graph
275
+ backwards: write each question as a path, make hops edge types and stops node labels,
276
+ then name the event that creates and removes each. Mark types with `[Node]` and
277
+ `[Edge("TYPE")]` (an edge's `[Source<T>]` and `[Target<T>]` members hold the end keys),
278
+ or declare the same definition with `IGraphProjection`. A type is never both a graph
279
+ element and a read model (CHR0068). Read
280
+ [references/graph-projections.md](references/graph-projections.md) for the attributes,
281
+ fluent builder, operation model, replay and idempotency, and the sinks.
282
+
266
283
  ## Definition changes replay
267
284
 
268
285
  Read [references/definition-changes.md](references/definition-changes.md) when a changed mapping, key, filter, join or child must replay, or when a corrected mapping does not repair existing counters and joins (replay rebuilds them; deploying alone does not).
@@ -0,0 +1,159 @@
1
+ # Graph projections
2
+
3
+ ## Contents
4
+
5
+ - Model-bound
6
+ - Fluent
7
+ - Counters and edge identity
8
+ - The operations
9
+ - Redelivery and replay
10
+ - Sinks
11
+ - Testing and analyzers
12
+
13
+ A **node** has a label (the type name), a unique key and properties. A property is a
14
+ primitive or an array of primitives; an object property is an error, so model the
15
+ object as a node and connect it with an edge. An **edge** has a type, a source node,
16
+ a target node and properties. By default it is identified by type, source and target.
17
+ Name the graph with `[Graph("Organization")]` on the types or the assembly; without
18
+ it the graph is named after the assembly's root namespace.
19
+
20
+ ## Model-bound
21
+
22
+ `[Key]` marks a node's unique key. `[Source<>]` and `[Target<>]` on an edge mark the
23
+ members holding the end keys; they are not properties of the edge. The node key is
24
+ the event source id unless `[FromEvent<>]` names an event property.
25
+
26
+ ```csharp
27
+ [Graph("Organization")]
28
+ [Node]
29
+ [FromEvent<PersonRegistered>]
30
+ [RemovedWith<PersonRemoved>(detach: true)]
31
+ public record Person([Key] Guid PersonId, string Name);
32
+
33
+ [Graph("Organization")]
34
+ [Node]
35
+ [FromEvent<GroupCreated>]
36
+ public record Group([Key] Guid GroupId, string Name);
37
+
38
+ [Graph("Organization")]
39
+ [Edge("MEMBER_OF")]
40
+ [EdgeFrom<MemberAdded>(sourceKey: nameof(MemberAdded.PersonId), targetKey: nameof(MemberAdded.GroupId))]
41
+ [EdgeRemovedWith<MemberRemoved>(sourceKey: nameof(MemberRemoved.PersonId), targetKey: nameof(MemberRemoved.GroupId))]
42
+ public record MemberOf(
43
+ [Source<Person>] Guid PersonId,
44
+ [Target<Group>] Guid GroupId,
45
+ [SetFromContext<MemberAdded>(nameof(EventContext.Occurred))] DateTimeOffset Since);
46
+ ```
47
+
48
+ Properties map by name from an event property of the same name, or with the
49
+ attributes of read-model projections: `[SetFrom<>]`, `[SetFromContext<>]`,
50
+ `[Increment<>]`, `[Decrement<>]`, `[Count<>]`, `[AddFrom<>]`, `[SubtractFrom<>]`.
51
+
52
+ ## Fluent
53
+
54
+ `IGraphProjection` builds exactly the same definition as the attributes:
55
+
56
+ ```csharp
57
+ [Graph("Organization")]
58
+ public class OrganizationGraph : IGraphProjection
59
+ {
60
+ public void Define(IGraphProjectionBuilder builder) => builder
61
+ .Node<Person>(n => n
62
+ .IdentifiedBy(p => p.PersonId)
63
+ .From<PersonRegistered>()
64
+ .RemovedWith<PersonRemoved>(b => b.Detach()))
65
+ .Node<Group>(n => n
66
+ .IdentifiedBy(g => g.GroupId)
67
+ .From<GroupCreated>())
68
+ .Edge<MemberOf, Person, Group>(e => e
69
+ .From<MemberAdded>(b => b
70
+ .UsingSourceKey(x => x.PersonId)
71
+ .UsingTargetKey(x => x.GroupId)
72
+ .Set(m => m.Since).ToEventContextProperty(c => c.Occurred))
73
+ .RemovedWith<MemberRemoved>(b => b
74
+ .UsingSourceKey(x => x.PersonId)
75
+ .UsingTargetKey(x => x.GroupId)));
76
+ }
77
+ ```
78
+
79
+ Chronicle also compiles the projection declaration language form (`graph Organization` with
80
+ `node` and `edge` declarations, then `projection X => graph Organization`), which is the text
81
+ `cratis-screenplay-projections` produces for a model.
82
+
83
+ ## Counters and edge identity
84
+
85
+ Counters work on node and edge properties:
86
+ `[Increment<MemberAdded>] [Decrement<MemberRemoved>] int MemberCount`.
87
+
88
+ Give an edge a `[Key]` member to allow several edges of one type between the same
89
+ two nodes. Every mapping of that edge must then say which event property holds the
90
+ identity (`identity:` argument or `UsingIdentity`). A sink that cannot hold several
91
+ edges between one pair rejects such an edge type.
92
+
93
+ ```csharp
94
+ [Edge("VISITED")]
95
+ [EdgeFrom<PlaceVisited>(
96
+ sourceKey: nameof(PlaceVisited.PersonId),
97
+ targetKey: nameof(PlaceVisited.PlaceId),
98
+ identity: nameof(PlaceVisited.VisitId))]
99
+ public record Visited(
100
+ [Source<Person>] Guid PersonId,
101
+ [Target<Place>] Guid PlaceId,
102
+ [Key] Guid VisitId,
103
+ [Count<PlaceVisited>] int Times);
104
+ ```
105
+
106
+ ## The operations
107
+
108
+ Each event yields a `GraphChangeset` of five idempotent operations: `UpsertNode`,
109
+ `SetProperties` (nothing is created), `DeleteNode` (with `detach` the attached edges
110
+ go too; without it a node that still has edges cannot be deleted), `UpsertEdge` and
111
+ `DeleteEdge` (the end nodes stay).
112
+
113
+ - An edge operation creates a bare end node when it does not exist; a node mapping
114
+ completes it later.
115
+ - A projection owns the edges and node properties it maps and never deletes a node it did not declare.
116
+ - Counters carry absolute values: the engine reads the current value from the sink
117
+ and the operation carries the result.
118
+
119
+ ## Redelivery and replay
120
+
121
+ Every node and edge stores a **watermark**, the sequence number of the event that last
122
+ wrote it. A write at or below the watermark is skipped, so redelivered and out-of-order
123
+ events do not apply twice. Replay is **mark and sweep**: a replay starts a new
124
+ generation for the projection, elements it has not rewritten read as absent (counters
125
+ rebuild from zero), and at the end elements it did not write are deleted. Elements
126
+ other projections wrote, and nodes only edges created, are never swept.
127
+
128
+ ## Sinks
129
+
130
+ A graph is stored by a graph sink, set per client with `DefaultGraphSinkTypeId`
131
+ (default `Neo4j`; `WellKnownSinkTypes.InMemoryGraph` keeps it in the kernel's memory).
132
+ The Neo4j sink uses one database per event store and namespace, with a single-database
133
+ mode for development; Cratis Arc reads those databases with `cratis-arc-neo4j`.
134
+
135
+ ```csharp
136
+ services.Configure<ChronicleOptions>(options =>
137
+ {
138
+ options.DefaultGraphSinkTypeId = WellKnownSinkTypes.InMemoryGraph;
139
+ });
140
+ ```
141
+
142
+ ## Testing and analyzers
143
+
144
+ `GraphScenario` runs a graph projection against the in-memory graph sink:
145
+
146
+ ```csharp
147
+ using var scenario = new GraphScenario();
148
+
149
+ await scenario.Append(personId, new PersonRegistered(personId, "Ada"));
150
+ await scenario.Append(personId, new MemberAdded(personId, groupId));
151
+
152
+ var person = await scenario.Node<Person>(personId);
153
+ var membership = await scenario.Edge<MemberOf>(personId, groupId);
154
+ var memberships = await scenario.Edges<MemberOf>();
155
+ ```
156
+
157
+ - CHR0066: a node or an edge has an object property.
158
+ - CHR0067: a node does not have exactly one key, or an edge has more than one.
159
+ - CHR0068: a type is both a node or an edge and a read model.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: cratis-screenplay-projections
3
- description: Use when declaring Screenplay event-to-state mappings or diagnosing a .play projection's keys, joins, children or lifecycle variants. Not for hand-written C# Chronicle projections or read-model query contracts.
3
+ description: Use when declaring Screenplay event-to-state mappings, a graph projection onto nodes and edges, or diagnosing a .play projection's keys, joins, children or lifecycle variants. Not for hand-written C# Chronicle projections or read-model query contracts.
4
4
  license: MIT
5
5
  ---
6
6
 
@@ -238,6 +238,18 @@ coexist.
238
238
 
239
239
  Each `variant` is its own read model created only by its `enters on` events, and mutual exclusion works through the event source identity: keep the event source equal to the entity identifier or the issue stays in both variants. Read [references/variants.md](references/variants.md) when modeling an entity with exclusive lifecycle shapes or fixing `PLAY0382`–`PLAY0385`.
240
240
 
241
+ ## Graph targets — `projection X => graph G`
242
+
243
+ A `graph` declares node labels (one `key` each) and edge types; `projection X => graph G`
244
+ builds it with `node` and `edge` blocks. Nothing writes to a graph except events.
245
+ Requires Screenplay 5.7.0 (`screenplay --version`).
246
+
247
+ Choose a graph for traversals (membership, nesting, paths) and a document read model
248
+ for lookups by key. Design by **reading the graph backwards**: write each question
249
+ as a path, make every hop an edge type and every stop a node label, then name the
250
+ event that creates and the one that removes each. Read
251
+ [references/graphs.md](references/graphs.md) for syntax, operations and `PLAY0862`–`PLAY0877`.
252
+
241
253
  ## When PDL is not enough — the reducer
242
254
 
243
255
  Excerpt: the events and the `AccountBalance` read model are declared elsewhere.
@@ -332,6 +344,7 @@ method: `cratis-screenplay-modeling-lifecycle` and `cratis-screenplay-slice-desi
332
344
 
333
345
  - Deciding which read models exist at all: `cratis-screenplay-event-modeling`.
334
346
  - Read-model shape, queries and screens: `cratis-screenplay-read-surface`.
335
- - Specifying projection behavior: `cratis-screenplay-specifications`.
347
+ - Specifying projection behavior, including `given graph` and `then graph`: `cratis-screenplay-specifications`.
348
+ - Reading a graph from Arc code: `cratis-arc-neo4j`.
336
349
  - Hand-written C# Chronicle projections: `cratis-chronicle-projection`.
337
350
  - Hand-written C# Chronicle reducers: `cratis-chronicle-reducer`.