-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathProjection.cs
More file actions
164 lines (136 loc) · 5.86 KB
/
Projection.cs
File metadata and controls
164 lines (136 loc) · 5.86 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
using System;
using System.Collections.Immutable;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Lokad.AzureEventStore.Projections;
using ExampleProject.Events;
using System.Collections.Generic;
using MessagePack;
using System.Text.RegularExpressions;
using Lokad.AzureEventStore;
namespace ExampleProject;
public sealed class Projection : IProjection<IEvent, State>
{
public State Initial(StateCreationContext stateCreationContext) => new(
ImmutableDictionary<string, int>.Empty,
ImmutableList<ImmutableList<int>>.Empty,
ImmutableList<State.Document>.Empty);
/// <summary> Update the state by applying an event. </summary>
public State Apply(uint sequence, IEvent e, State previous)
{
// In a real-life project, this would likely have been implemented using
// a visitor pattern (so that, when adding event types, the compiler can
// help us detect all cases where these new events need to be handled).
if (e is DocumentAdded d)
{
if (d.Id != previous.Documents.Count)
throw new InvalidDataException();
// Add the new document to the table of documents
var state = new State(
previous.Index,
previous.DocumentLists,
previous.Documents.Add(
new State.Document(d.Id, d.Path, d.Contents)));
// Index all words in the document
foreach (var word in WordsOf(d.Contents))
{
if (state.Index.TryGetValue(word, out var list))
{
// Word exists in the index: update the documents list.
state = new State(
state.Index,
state.DocumentLists.SetItem(
list,
state.DocumentLists[list].Add(d.Id)),
state.Documents);
}
else
{
// Word does not exist in the index: add to index, and
// create new documents list.
state = new State(
state.Index.Add(word, state.DocumentLists.Count),
state.DocumentLists.Add(
ImmutableList<int>.Empty.Add(d.Id)),
state.Documents);
}
}
return state;
}
if (e is DocumentRemoved r)
{
if (previous.Documents.Count <= r.Id || r.Id < 0)
throw new InvalidDataException();
if (previous.Documents[r.Id] == null)
throw new InvalidDataException();
var doc = previous.Documents[r.Id];
// Remove the document
var state = new State(
previous.Index,
previous.DocumentLists,
previous.Documents.SetItem(r.Id, null));
// Remove the document id from the document lists of all
// indexed words (leaving empty document lists is acceptable).
foreach (var word in WordsOf(doc.Contents))
{
var list = state.Index[word];
state = new State(
state.Index,
state.DocumentLists.SetItem(
list,
state.DocumentLists[list].Remove(r.Id)),
state.Documents);
}
return state;
}
throw new ArgumentOutOfRangeException(nameof(e), "Unknown event type " + e.GetType());
}
/// <summary> Cut a document into distinct words. </summary>
private static IEnumerable<string> WordsOf(string words)
{
var set = new HashSet<string>();
foreach (var w in new Regex("\\W").Split(words))
{
if (string.IsNullOrWhiteSpace(w)) continue;
set.Add(w.ToLowerInvariant());
}
return set;
}
/// <summary> Load the state from a stream. </summary>
public async Task<State> TryLoadAsync(Stream source, CancellationToken cancel)
{
var index = await MessagePackSerializer.DeserializeAsync<ImmutableDictionary<string, int>>(
source, State.MessagePackOptions);
var documentLists = await MessagePackSerializer.DeserializeAsync<ImmutableList<ImmutableList<int>>>(
source, State.MessagePackOptions);
var documents = await MessagePackSerializer.DeserializeAsync<ImmutableList<State.Document>>(
source, State.MessagePackOptions);
return new State(index, documentLists, documents);
}
/// <summary> Save the state to a stream. </summary>
public async Task<bool> TrySaveAsync(Stream destination, State state, CancellationToken cancel)
{
await MessagePackSerializer.SerializeAsync(destination, state.Index, State.MessagePackOptions);
await MessagePackSerializer.SerializeAsync(destination, state.DocumentLists, State.MessagePackOptions);
await MessagePackSerializer.SerializeAsync(destination, state.Documents, State.MessagePackOptions);
return true;
}
public Task<RestoredState<State>> TryRestoreAsync(StateCreationContext stateCreationContext, CancellationToken cancel = default)
{
return Task.FromResult<RestoredState<State>>(null);
}
public Task CommitAsync(State state, uint sequence, CancellationToken cancel = default)
{
return Task.CompletedTask;
}
public Task<State> UpkeepAsync(StateUpkeepContext stateUpkeepContext, State state, CancellationToken cancel = default)
{
return Task.FromResult(state);
}
/// <see cref="IProjection{TEvent}.FullName"/>
public string FullName => "State";
/// <see cref="IProjection{TEvent}.State"/>
Type IProjection<IEvent>.State => typeof(State);
public bool NeedsMemoryMappedFolder => false;
}