forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExecOnlyOnce.cs
More file actions
69 lines (55 loc) · 2.03 KB
/
ExecOnlyOnce.cs
File metadata and controls
69 lines (55 loc) · 2.03 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
using System;
using ServiceStack.Common;
using ServiceStack.Common.Web;
using ServiceStack.Redis;
using ServiceStack.Text;
namespace ServiceStack.ServiceInterface.Validation
{
public class ExecOnceOnly : IDisposable
{
private const string Flag = "Y";
private readonly string hashKey;
private readonly string correlationId;
private readonly IRedisClient redis;
public ExecOnceOnly(IRedisClientsManager redisManager, Type forType, string correlationId)
: this(redisManager, "hash:nx:" + forType.Name, correlationId) { }
public ExecOnceOnly(IRedisClientsManager redisManager, Type forType, Guid? correlationId)
: this(redisManager, "hash:nx:" + forType.Name, (correlationId.HasValue ? correlationId.Value.ToString("N") : null)) { }
public ExecOnceOnly(IRedisClientsManager redisManager, string hashKey, string correlationId)
{
redisManager.ThrowIfNull("redisManager");
hashKey.ThrowIfNull("hashKey");
this.hashKey = hashKey;
this.correlationId = correlationId;
if (correlationId != null)
{
redis = redisManager.GetClient();
var exists = !redis.SetEntryInHashIfNotExists(hashKey, correlationId, Flag);
if (exists)
throw HttpError.Conflict("Request {0} has already been processed".Fmt(correlationId));
}
}
public bool Executed { get; private set; }
public void Commit()
{
this.Executed = true;
}
public void Rollback()
{
if (redis == null) return;
redis.RemoveEntryFromHash(hashKey, correlationId);
this.Executed = false;
}
public void Dispose()
{
if (correlationId != null && !Executed)
{
Rollback();
}
if (redis != null)
{
redis.Dispose(); //release back into the pool.
}
}
}
}