Repository navigation
Expand file tree
/
Copy pathRedisObjectStorage.ts
More file actions
173 lines (139 loc) · 4.84 KB
/
Copy pathRedisObjectStorage.ts
File metadata and controls
173 lines (139 loc) · 4.84 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
import type { Redis } from 'ioredis';
import type { IContainer } from 'node-cqrs';
import type { IObjectStorage, Identifier } from '../interfaces/index.ts';
import { assertDefined, assertFunction, assertString } from '../utils/assert.ts';
import { AbstractRedisAccessor } from './AbstractRedisAccessor.ts';
/**
* Lua script for atomic version-checked update.
*
* KEYS[1] = record key
* ARGV[1] = expected version (as string)
* ARGV[2] = new envelope JSON to store
*
* Returns:
* 1 = success (updated)
* 0 = version mismatch (retry)
* -1 = key does not exist
*/
const SCRIPT_UPDATE_IF_VERSION = `
local current = redis.call("GET", KEYS[1])
if not current then return -1 end
local envelope = cjson.decode(current)
if tostring(envelope["v"]) ~= ARGV[1] then return 0 end
redis.call("SET", KEYS[1], ARGV[2])
return 1
`;
type RecordEnvelope<TRecord> = { d: TRecord; v: number };
/**
* Redis-backed implementation of IObjectStorage.
*
* Each record is stored as a JSON string at key `{tableName}:{id}` with the shape
* `{ "d": <data>, "v": <version> }`. The version field enables optimistic
* concurrency control: `update` and `updateEnforcingNew` re-read the record after
* the user callback runs and atomically commit only when the version still matches.
* On mismatch the operation retries up to `maxRetries` times.
*/
export class RedisObjectStorage<TRecord> extends AbstractRedisAccessor implements IObjectStorage<TRecord> {
#tableName: string;
#maxRetries: number;
constructor(o: Partial<Pick<IContainer, 'viewModelRedis' | 'viewModelRedisFactory'>> & {
tableName: string;
maxRetries?: number;
}) {
super(o);
assertString(o.tableName, 'o.tableName');
this.#tableName = o.tableName;
this.#maxRetries = o.maxRetries ?? 100;
}
// eslint-disable-next-line class-methods-use-this
protected initialize(_redis: Redis): void {
// No Redis-level setup required for object storage
}
#key(id: Identifier): string {
return `${this.#tableName}:${String(id)}`;
}
async get(id: Identifier): Promise<TRecord | undefined> {
assertDefined(id, 'id');
await this.assertConnection();
const raw = await this.redis!.get(this.#key(id));
if (!raw)
return undefined;
const envelope: RecordEnvelope<TRecord> = JSON.parse(raw);
return envelope.d;
}
async create(id: Identifier, data: TRecord): Promise<void> {
assertDefined(id, 'id');
await this.assertConnection();
const envelope: RecordEnvelope<TRecord> = { d: data, v: 1 };
const result = await this.redis!.set(this.#key(id), JSON.stringify(envelope), 'NX');
if (!result)
throw new Error(`Record '${id}' could not be created`);
}
async update(id: Identifier, update: (r: TRecord) => TRecord): Promise<void> {
assertDefined(id, 'id');
assertFunction(update, 'update');
await this.assertConnection();
for (let attempt = 0; attempt <= this.#maxRetries; attempt++) {
const raw = await this.redis!.get(this.#key(id));
if (!raw)
throw new Error(`Record '${id}' does not exist`);
const envelope: RecordEnvelope<TRecord> = JSON.parse(raw);
const updated: RecordEnvelope<TRecord> = {
d: update(envelope.d),
v: envelope.v + 1
};
const result = await this.redis!.eval(
SCRIPT_UPDATE_IF_VERSION,
1,
this.#key(id),
String(envelope.v),
JSON.stringify(updated)
) as number;
if (result === 1)
return;
if (result === -1)
throw new Error(`Record '${id}' does not exist`);
// result === 0: version mismatch — retry
}
throw new Error(`Record '${id}' could not be updated after ${this.#maxRetries} retries`);
}
async updateEnforcingNew(id: Identifier, update: (r?: TRecord) => TRecord): Promise<void> {
assertDefined(id, 'id');
assertFunction(update, 'update');
await this.assertConnection();
for (let attempt = 0; attempt <= this.#maxRetries; attempt++) {
const raw = await this.redis!.get(this.#key(id));
if (raw) {
const envelope: RecordEnvelope<TRecord> = JSON.parse(raw);
const updated: RecordEnvelope<TRecord> = {
d: update(envelope.d),
v: envelope.v + 1
};
const result = await this.redis!.eval(
SCRIPT_UPDATE_IF_VERSION,
1,
this.#key(id),
String(envelope.v),
JSON.stringify(updated)
) as number;
if (result === 1)
return;
// result === 0 or -1: concurrent modification — retry
}
else {
const envelope: RecordEnvelope<TRecord> = { d: update(undefined), v: 1 };
const result = await this.redis!.set(this.#key(id), JSON.stringify(envelope), 'NX');
if (result)
return;
// Another process created the key between our GET and SET — retry
}
}
throw new Error(`Record '${id}' could not be upserted after ${this.#maxRetries} retries`);
}
async delete(id: Identifier): Promise<boolean> {
assertDefined(id, 'id');
await this.assertConnection();
const count = await this.redis!.del(this.#key(id));
return count === 1;
}
}