This repository was archived by the owner on Apr 5, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathCommandHandler.fs
More file actions
68 lines (59 loc) · 2.58 KB
/
CommandHandler.fs
File metadata and controls
68 lines (59 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
module FsUno.Domain.CommandHandlers
open Deck
open Game
// This version use F# agents (MailboxProcessor) to keep
// aggregates in memory.
// The dispatcher agent maintains a map of existing agents/aggregates,
// and forward commands to it.
// The agent loads aggregate state when receiving its first command,
// then simply maintain state and save new events to the store.
// This is usually ok for aggregates with a small number of events
module Game =
type Agent<'T> = MailboxProcessor<'T>
let create readStream appendToStream =
// this is the "repository"
let streamId (GameId gameId) = sprintf "Game-%O" gameId
let load gameId =
let rec fold state version =
async {
let! events, lastEvent, nextEvent =
readStream (streamId gameId) version 500
let state = List.fold State.apply state events
match nextEvent with
| None -> return lastEvent, state
| Some n -> return! fold state n }
fold State.initial 0
let save gameId expectedVersion events =
appendToStream (streamId gameId) expectedVersion events
let start gameId =
Agent.Start
<| fun inbox ->
let rec loop version state =
async {
let! command = inbox.Receive()
let events = handle command state
do! save gameId version events
let newState = List.fold State.apply state events
return! loop (version + List.length events) newState }
async {
let! version, state = load gameId
return! loop version state }
let forward (agent: Agent<_>) command = agent.Post command
let dispatcher =
Agent.Start
<| fun inbox ->
let rec loop aggregates =
async {
let! command = inbox.Receive()
let id = gameId command
match Map.tryFind id aggregates with
| Some aggregate ->
forward aggregate command
return! loop aggregates
| None ->
let aggregate = start id
forward aggregate command
return! loop (Map.add id aggregate aggregates) }
loop Map.empty
fun command ->
dispatcher.Post command