forked from kurrent-io/KurrentDB
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamMetadata.cs
More file actions
412 lines (380 loc) · 16.3 KB
/
StreamMetadata.cs
File metadata and controls
412 lines (380 loc) · 16.3 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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using EventStore.ClientAPI.Common;
using EventStore.ClientAPI.Common.Utils;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace EventStore.ClientAPI
{
/// <summary>
/// A class representing stream metadata with strongly typed properties
/// for system values and a dictionary-like interface for custom values.
/// </summary>
public class StreamMetadata
{
/// <summary>
/// The maximum number of events allowed in the stream.
/// </summary>
public readonly int? MaxCount;
/// <summary>
/// The maximum age of events allowed in the stream.
/// </summary>
public readonly TimeSpan? MaxAge;
/// <summary>
/// The event number from which previous events can be scavenged.
/// This is used to implement soft-deletion of streams.
/// </summary>
public readonly int? TruncateBefore;
/// <summary>
/// The amount of time for which the stream head is cachable.
/// </summary>
public readonly TimeSpan? CacheControl;
/// <summary>
/// The access control list for the stream.
/// </summary>
public readonly StreamAcl Acl;
/// <summary>
/// An enumerable of the keys in the user-provided metadata.
/// </summary>
public IEnumerable<string> CustomKeys { get { return _customMetadata.Keys; } }
/// <summary>
/// An enumerable of key-value pairs of keys to JSON text for user-provider metadata.
/// </summary>
public IEnumerable<KeyValuePair<string, string>> CustomMetadataAsRawJsons
{
get { return _customMetadata.Select(x => new KeyValuePair<string, string>(x.Key, x.Value.ToString())); }
}
private readonly IDictionary<string, JToken> _customMetadata;
internal StreamMetadata(int? maxCount, TimeSpan? maxAge, int? truncateBefore, TimeSpan? cacheControl,
StreamAcl acl, IDictionary<string, JToken> customMetadata = null)
{
if (maxCount <= 0)
throw new ArgumentOutOfRangeException("maxCount", string.Format("{0} should be positive value.", SystemMetadata.MaxCount));
if (maxAge <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException("maxAge", string.Format("{0} should be positive time span.", SystemMetadata.MaxAge));
if (truncateBefore < 0)
throw new ArgumentOutOfRangeException("truncateBefore", string.Format("{0} should be non negative value.", SystemMetadata.TruncateBefore));
if (cacheControl <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException("cacheControl", string.Format("{0} should be positive time span.", SystemMetadata.CacheControl));
MaxCount = maxCount;
MaxAge = maxAge;
TruncateBefore = truncateBefore;
CacheControl = cacheControl;
Acl = acl;
_customMetadata = customMetadata ?? Empty.CustomStreamMetadata;
}
/// <summary>
/// Creates a <see cref="StreamMetadata" /> with the specified parameters.
/// </summary>
/// <param name="maxCount">The maximum number of events allowed in the stream.</param>
/// <param name="maxAge">The maximum age of events allowed in the stream.</param>
/// <param name="truncateBefore">The event number from which previous events can be scavenged.</param>
/// <param name="cacheControl">The amount of time for which the stream head is cachable.</param>
/// <param name="acl">The access control list for the stream.</param>
/// <returns></returns>
public static StreamMetadata Create(int? maxCount = null, TimeSpan? maxAge = null, int? truncateBefore = null, TimeSpan? cacheControl = null, StreamAcl acl = null)
{
return new StreamMetadata(maxCount, maxAge, truncateBefore, cacheControl, acl);
}
/// <summary>
/// Builds a <see cref="StreamMetadata"/> from a <see cref="StreamMetadataBuilder" />.
/// </summary>
/// <returns>An instance of <see cref="StreamMetadata"/>.</returns>
public static StreamMetadataBuilder Build()
{
return new StreamMetadataBuilder();
}
/// <summary>
/// Get a value of type T for the given key from the custom metadata.
/// This method will throw an <see cref="ArgumentException"/> if the
/// key is not found.
/// </summary>
/// <typeparam name="T">The type of the value.</typeparam>
/// <param name="key">A key.</param>
/// <returns>Value of type T for the key.</returns>
public T GetValue<T>(string key)
{
T res;
if (!TryGetValue(key, out res))
throw new ArgumentException(string.Format("Key '{0}' not found in custom metadata.", key));
return res;
}
/// <summary>
/// Tries to get a value of type T for the given key from the custom
/// metadata, and if it exists returns true from the method and gives
/// the value as an out parameter.
/// </summary>
/// <param name="key">A key.</param>
/// <param name="value">Output variable for the value of type T for the key.</param>
/// <typeparam name="T">The type of the value.</typeparam>
/// <returns>True if the key exists, false otherwise.</returns>
public bool TryGetValue<T>(string key, out T value)
{
Ensure.NotNull(key, "key");
JToken token;
if (!_customMetadata.TryGetValue(key, out token))
{
value = default(T);
return false;
}
value = token.Value<T>();
return true;
}
/// <summary>
/// Gets a string containing raw JSON value for the given key.
/// </summary>
/// <param name="key">A key.</param>
/// <returns>String containing raw JSON value for the key.</returns>
/// <exception cref="ArgumentException">If the key does not exist.</exception>
public string GetValueAsRawJsonString(string key)
{
string res;
if (!TryGetValueAsRawJsonString(key, out res))
throw new ArgumentException(string.Format("No key '{0}' found in custom metadata.", key));
return res;
}
/// <summary>
/// Tries to get a string containing raw JSON value for the given key.
/// </summary>
/// <param name="key">A key.</param>
/// <param name="value">Output variable for the value for the key.</param>
/// <returns>True if the key exists, false otherwise.</returns>
public bool TryGetValueAsRawJsonString(string key, out string value)
{
Ensure.NotNull(key, "key");
JToken token;
if (!_customMetadata.TryGetValue(key, out token))
{
value = default(string);
return false;
}
value = token.ToString(Formatting.None);
return true;
}
/// <summary>
/// Returns a byte array representing the stream metadata
/// as JSON encoded as UTF8 with no byte order mark.
/// </summary>
/// <returns>Byte array representing the stream metadata.</returns>
public byte[] AsJsonBytes()
{
using (var memoryStream = new MemoryStream())
{
using (var jsonWriter = new JsonTextWriter(new StreamWriter(memoryStream, Helper.UTF8NoBom)))
{
WriteAsJson(jsonWriter);
}
return memoryStream.ToArray();
}
}
/// <summary>
/// Returns a JSON string representing the stream metadata.
/// </summary>
/// <returns>A string representing the stream metadata.</returns>
public string AsJsonString()
{
using (var stringWriter = new StringWriter())
{
using (var jsonWriter = new JsonTextWriter(stringWriter))
{
WriteAsJson(jsonWriter);
}
return stringWriter.ToString();
}
}
private void WriteAsJson(JsonTextWriter jsonWriter)
{
jsonWriter.WriteStartObject();
if (MaxCount.HasValue)
{
jsonWriter.WritePropertyName(SystemMetadata.MaxCount);
jsonWriter.WriteValue(MaxCount.Value);
}
if (MaxAge.HasValue)
{
jsonWriter.WritePropertyName(SystemMetadata.MaxAge);
jsonWriter.WriteValue((long) MaxAge.Value.TotalSeconds);
}
if (TruncateBefore.HasValue)
{
jsonWriter.WritePropertyName(SystemMetadata.TruncateBefore);
jsonWriter.WriteValue(TruncateBefore.Value);
}
if (CacheControl.HasValue)
{
jsonWriter.WritePropertyName(SystemMetadata.CacheControl);
jsonWriter.WriteValue((long) CacheControl.Value.TotalSeconds);
}
if (Acl != null)
{
jsonWriter.WritePropertyName(SystemMetadata.Acl);
WriteAcl(jsonWriter, Acl);
}
foreach (var customMetadata in _customMetadata)
{
jsonWriter.WritePropertyName(customMetadata.Key);
customMetadata.Value.WriteTo(jsonWriter);
}
jsonWriter.WriteEndObject();
}
internal static void WriteAcl(JsonTextWriter jsonWriter, StreamAcl acl)
{
jsonWriter.WriteStartObject();
WriteAclRoles(jsonWriter, SystemMetadata.AclRead, acl.ReadRoles);
WriteAclRoles(jsonWriter, SystemMetadata.AclWrite, acl.WriteRoles);
WriteAclRoles(jsonWriter, SystemMetadata.AclDelete, acl.DeleteRoles);
WriteAclRoles(jsonWriter, SystemMetadata.AclMetaRead, acl.MetaReadRoles);
WriteAclRoles(jsonWriter, SystemMetadata.AclMetaWrite, acl.MetaWriteRoles);
jsonWriter.WriteEndObject();
}
private static void WriteAclRoles(JsonTextWriter jsonWriter, string propertyName, string[] roles)
{
if (roles == null)
return;
jsonWriter.WritePropertyName(propertyName);
if (roles.Length == 1)
{
jsonWriter.WriteValue(roles[0]);
}
else
{
jsonWriter.WriteStartArray();
Array.ForEach(roles, jsonWriter.WriteValue);
jsonWriter.WriteEndArray();
}
}
/// <summary>
/// Builds a <see cref="StreamMetadata" /> object from a byte array
/// containing stream metadata.
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public static StreamMetadata FromJsonBytes(byte[] json)
{
using (var reader = new JsonTextReader(new StreamReader(new MemoryStream(json))))
{
Check(reader.Read(), reader);
Check(JsonToken.StartObject, reader);
int? maxCount = null;
TimeSpan? maxAge = null;
int? truncateBefore = null;
TimeSpan? cacheControl = null;
StreamAcl acl = null;
Dictionary<string, JToken> customMetadata = null;
while (true)
{
Check(reader.Read(), reader);
if (reader.TokenType == JsonToken.EndObject)
break;
Check(JsonToken.PropertyName, reader);
var name = (string) reader.Value;
switch (name)
{
case SystemMetadata.MaxCount:
{
Check(reader.Read(), reader);
Check(JsonToken.Integer, reader);
maxCount = (int)(long)reader.Value;
break;
}
case SystemMetadata.MaxAge:
{
Check(reader.Read(), reader);
Check(JsonToken.Integer, reader);
maxAge = TimeSpan.FromSeconds((long)reader.Value);
break;
}
case SystemMetadata.TruncateBefore:
{
Check(reader.Read(), reader);
Check(JsonToken.Integer, reader);
truncateBefore = (int)(long)reader.Value;
break;
}
case SystemMetadata.CacheControl:
{
Check(reader.Read(), reader);
Check(JsonToken.Integer, reader);
cacheControl = TimeSpan.FromSeconds((long)reader.Value);
break;
}
case SystemMetadata.Acl:
{
acl = ReadAcl(reader);
break;
}
default:
{
if (customMetadata == null)
customMetadata = new Dictionary<string, JToken>();
Check(reader.Read(), reader);
var jToken = JToken.ReadFrom(reader);
customMetadata.Add(name, jToken);
break;
}
}
}
return new StreamMetadata(maxCount, maxAge, truncateBefore, cacheControl, acl, customMetadata);
}
}
internal static StreamAcl ReadAcl(JsonTextReader reader)
{
Check(reader.Read(), reader);
Check(JsonToken.StartObject, reader);
string[] read = null;
string[] write = null;
string[] delete = null;
string[] metaRead = null;
string[] metaWrite = null;
while (true)
{
Check(reader.Read(), reader);
if (reader.TokenType == JsonToken.EndObject)
break;
Check(JsonToken.PropertyName, reader);
var name = (string)reader.Value;
switch (name)
{
case SystemMetadata.AclRead: read = ReadRoles(reader); break;
case SystemMetadata.AclWrite: write = ReadRoles(reader); break;
case SystemMetadata.AclDelete: delete = ReadRoles(reader); break;
case SystemMetadata.AclMetaRead: metaRead = ReadRoles(reader); break;
case SystemMetadata.AclMetaWrite: metaWrite = ReadRoles(reader); break;
}
}
return new StreamAcl(read, write, delete, metaRead, metaWrite);
}
private static string[] ReadRoles(JsonTextReader reader)
{
Check(reader.Read(), reader);
if (reader.TokenType == JsonToken.String)
return new[] { (string)reader.Value };
if (reader.TokenType == JsonToken.StartArray)
{
var roles = new List<string>();
while (true)
{
Check(reader.Read(), reader);
if (reader.TokenType == JsonToken.EndArray)
break;
Check(JsonToken.String, reader);
roles.Add((string)reader.Value);
}
return roles.ToArray();
}
throw new Exception("Invalid JSON");
}
private static void Check(JsonToken type, JsonTextReader reader)
{
if (reader.TokenType != type)
throw new Exception("Invalid JSON");
}
private static void Check(bool read, JsonTextReader reader)
{
if (!read)
throw new Exception("Invalid JSON");
}
}
}