-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathStorage.cs
97 lines (83 loc) · 2.87 KB
/
Storage.cs
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
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Orleans;
using Orleans.Runtime;
using Orleans.Storage;
namespace ProcessManager
{
class Storage : IGrainStorage
{
public static string Init() => Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "orleankka_durable_fsm_example")).FullName;
readonly Type type;
readonly string folder;
readonly ILogger logger;
internal Storage(IServiceProvider services, Type type, string folder)
{
this.type = type;
this.folder = folder;
logger = services.GetRequiredService<ILoggerFactory>().CreateLogger($"{type.Name}Storage");
}
internal Storage(ILogger logger, Type type, string folder)
{
this.type = type;
this.folder = folder;
this.logger = logger;
}
public async Task ReadStateAsync<T>(string grainType, GrainId id, IGrainState<T> grainState)
{
var blob = GetBlob(id);
if (!File.Exists(blob))
return;
try
{
var json = await File.ReadAllTextAsync(blob, Encoding.UTF8);
grainState.State = (T)JsonConvert.DeserializeObject(json, type);
}
catch (FileNotFoundException)
{
logger.LogWarning($"File {blob} disappear between checking it exists and reading");
}
}
public async Task WriteStateAsync<T>(string grainType, GrainId id, IGrainState<T> grainState)
{
var state = grainState.State;
var blob = GetBlob(id);
var json = JsonConvert.SerializeObject(state);
try
{
await File.WriteAllTextAsync(blob, json);
}
catch (IOException ex)
{
var message = $"File {blob} might have been changed by other write";
logger.LogError(ex, message);
throw new InconsistentStateException(message);
}
}
public Task ClearStateAsync<T>(string grainType, GrainId id, IGrainState<T> grainState)
{
var blob = GetBlob(id);
try
{
File.Delete(blob);
grainState.State = (T)((object)new CopierState());
}
catch (IOException ex)
{
var message = $"File {blob} might have been changed by other write";
logger.LogError(ex, message);
throw new InconsistentStateException(message);
}
return Task.CompletedTask;
}
string GetBlob(GrainId id)
{
return Path.Combine(folder, $"{id}.blob");
}
}
}