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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
| public class KVStateMachine implements StateMachine {
private static final Logger logger = Logger.getLogger(KVStateMachine.class.getName());
// 存储引擎
private final ConcurrentMap<String, VersionedValue> store = new ConcurrentHashMap<>();
private final AtomicLong globalVersion = new AtomicLong(0);
private final ReadWriteLock lock = new ReentrantReadWriteLock();
// 索引
private final ConcurrentSkipListMap<String, Set<String>> prefixIndex = new ConcurrentSkipListMap<>();
// 统计信息
private final AtomicLong totalKeys = new AtomicLong(0);
private final AtomicLong totalOperations = new AtomicLong(0);
// 版本化的值
public static class VersionedValue {
public final byte[] value;
public final long version;
public final Instant timestamp;
public final boolean deleted;
public VersionedValue(byte[] value, long version, boolean deleted) {
this.value = value != null ? value.clone() : null;
this.version = version;
this.timestamp = Instant.now();
this.deleted = deleted;
}
public VersionedValue(byte[] value, long version) {
this(value, version, false);
}
}
// 快照数据
public static class Snapshot {
public final Map<String, VersionedValue> data;
public final long version;
public final Instant timestamp;
public Snapshot(Map<String, VersionedValue> data, long version) {
this.data = new HashMap<>(data);
this.version = version;
this.timestamp = Instant.now();
}
}
public KVStateMachine() {
logger.info("Initialized KV state machine");
}
@Override
public void apply(LogEntry entry) {
try {
totalOperations.incrementAndGet();
Command command = deserializeCommand(entry.data);
Result result = executeCommand(command);
// 通知应用结果
if (entry.callback != null) {
entry.callback.onCommandApplied(command.id, result);
}
} catch (Exception e) {
logger.severe("Failed to apply log entry: " + e.getMessage());
}
}
// 执行命令
private Result executeCommand(Command command) {
lock.writeLock().lock();
try {
switch (command.type) {
case PUT:
return executePut(command.key, command.value);
case DELETE:
return executeDelete(command.key);
case BATCH:
return executeBatch(command.batch);
default:
return Result.error("Unsupported write operation: " + command.type);
}
} finally {
lock.writeLock().unlock();
}
}
// 执行PUT操作
private Result executePut(String key, byte[] value) {
long version = globalVersion.incrementAndGet();
VersionedValue oldValue = store.get(key);
if (oldValue == null || oldValue.deleted) {
totalKeys.incrementAndGet();
}
VersionedValue newValue = new VersionedValue(value, version);
store.put(key, newValue);
// 更新前缀索引
updatePrefixIndex(key, true);
logger.fine(String.format("PUT key=%s, version=%d", key, version));
return Result.success(null, version);
}
// 执行DELETE操作
private Result executeDelete(String key) {
VersionedValue oldValue = store.get(key);
if (oldValue == null || oldValue.deleted) {
return Result.error("Key not found");
}
long version = globalVersion.incrementAndGet();
VersionedValue deletedValue = new VersionedValue(null, version, true);
store.put(key, deletedValue);
totalKeys.decrementAndGet();
// 更新前缀索引
updatePrefixIndex(key, false);
logger.fine(String.format("DELETE key=%s, version=%d", key, version));
return Result.success(null, version);
}
// 执行批量操作
private Result executeBatch(Map<String, byte[]> batch) {
long batchVersion = globalVersion.get();
for (Map.Entry<String, byte[]> entry : batch.entrySet()) {
String key = entry.getKey();
byte[] value = entry.getValue();
if (value != null) {
// PUT操作
long version = globalVersion.incrementAndGet();
VersionedValue oldValue = store.get(key);
if (oldValue == null || oldValue.deleted) {
totalKeys.incrementAndGet();
}
VersionedValue newValue = new VersionedValue(value, version);
store.put(key, newValue);
updatePrefixIndex(key, true);
} else {
// DELETE操作
VersionedValue oldValue = store.get(key);
if (oldValue != null && !oldValue.deleted) {
long version = globalVersion.incrementAndGet();
VersionedValue deletedValue = new VersionedValue(null, version, true);
store.put(key, deletedValue);
totalKeys.decrementAndGet();
updatePrefixIndex(key, false);
}
}
}
logger.fine(String.format("BATCH operation completed, %d entries", batch.size()));
return Result.success(null, globalVersion.get());
}
// GET操作(读取)
public byte[] get(String key) {
lock.readLock().lock();
try {
VersionedValue value = store.get(key);
if (value != null && !value.deleted) {
return value.value.clone();
}
return null;
} finally {
lock.readLock().unlock();
}
}
// 获取版本号
public long getVersion(String key) {
lock.readLock().lock();
try {
VersionedValue value = store.get(key);
return value != null ? value.version : 0;
} finally {
lock.readLock().unlock();
}
}
// SCAN操作
public Map<String, byte[]> scan(String prefix, int limit) {
lock.readLock().lock();
try {
Map<String, byte[]> results = new LinkedHashMap<>();
int count = 0;
// 使用前缀索引优化查找
Set<String> candidateKeys = prefixIndex.get(prefix);
if (candidateKeys != null) {
for (String key : candidateKeys) {
if (count >= limit) break;
VersionedValue value = store.get(key);
if (value != null && !value.deleted) {
results.put(key, value.value.clone());
count++;
}
}
} else {
// 回退到全扫描
for (Map.Entry<String, VersionedValue> entry : store.entrySet()) {
if (count >= limit) break;
String key = entry.getKey();
if (key.startsWith(prefix)) {
VersionedValue value = entry.getValue();
if (!value.deleted) {
results.put(key, value.value.clone());
count++;
}
}
}
}
return results;
} finally {
lock.readLock().unlock();
}
}
// 更新前缀索引
private void updatePrefixIndex(String key, boolean add) {
// 为简化实现,只索引前2个字符的前缀
if (key.length() >= 2) {
String prefix = key.substring(0, 2);
prefixIndex.computeIfAbsent(prefix, k -> ConcurrentHashMap.newKeySet());
if (add) {
prefixIndex.get(prefix).add(key);
} else {
Set<String> keys = prefixIndex.get(prefix);
if (keys != null) {
keys.remove(key);
if (keys.isEmpty()) {
prefixIndex.remove(prefix);
}
}
}
}
}
@Override
public byte[] createSnapshot() {
lock.readLock().lock();
try {
Snapshot snapshot = new Snapshot(store, globalVersion.get());
return serializeSnapshot(snapshot);
} finally {
lock.readLock().unlock();
}
}
@Override
public void restoreSnapshot(byte[] snapshotData) {
lock.writeLock().lock();
try {
Snapshot snapshot = deserializeSnapshot(snapshotData);
store.clear();
prefixIndex.clear();
store.putAll(snapshot.data);
globalVersion.set(snapshot.version);
// 重建索引
long keyCount = 0;
for (Map.Entry<String, VersionedValue> entry : store.entrySet()) {
if (!entry.getValue().deleted) {
updatePrefixIndex(entry.getKey(), true);
keyCount++;
}
}
totalKeys.set(keyCount);
logger.info(String.format("Restored snapshot: %d keys, version=%d",
keyCount, snapshot.version));
} catch (Exception e) {
logger.severe("Failed to restore snapshot: " + e.getMessage());
throw new RuntimeException(e);
} finally {
lock.writeLock().unlock();
}
}
// 健康检查
public boolean isHealthy() {
return store != null && globalVersion.get() >= 0;
}
// 获取统计信息
public Map<String, Object> getStatistics() {
lock.readLock().lock();
try {
Map<String, Object> stats = new HashMap<>();
stats.put("totalKeys", totalKeys.get());
stats.put("totalOperations", totalOperations.get());
stats.put("currentVersion", globalVersion.get());
stats.put("storeSize", store.size());
stats.put("indexSize", prefixIndex.size());
return stats;
} finally {
lock.readLock().unlock();
}
}
// 序列化和反序列化方法
private byte[] serializeSnapshot(Snapshot snapshot) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeLong(snapshot.version);
oos.writeInt(snapshot.data.size());
for (Map.Entry<String, VersionedValue> entry : snapshot.data.entrySet()) {
oos.writeUTF(entry.getKey());
VersionedValue value = entry.getValue();
oos.writeLong(value.version);
oos.writeBoolean(value.deleted);
if (!value.deleted && value.value != null) {
oos.writeInt(value.value.length);
oos.write(value.value);
} else {
oos.writeInt(0);
}
}
oos.close();
return baos.toByteArray();
} catch (Exception e) {
throw new RuntimeException("Failed to serialize snapshot", e);
}
}
private Snapshot deserializeSnapshot(byte[] data) {
try {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
ObjectInputStream ois = new ObjectInputStream(bais);
long version = ois.readLong();
int size = ois.readInt();
Map<String, VersionedValue> storeData = new HashMap<>();
for (int i = 0; i < size; i++) {
String key = ois.readUTF();
long valueVersion = ois.readLong();
boolean deleted = ois.readBoolean();
int valueLength = ois.readInt();
byte[] value = null;
if (valueLength > 0) {
value = new byte[valueLength];
ois.readFully(value);
}
storeData.put(key, new VersionedValue(value, valueVersion, deleted));
}
ois.close();
return new Snapshot(storeData, version);
} catch (Exception e) {
throw new RuntimeException("Failed to deserialize snapshot", e);
}
}
private Command deserializeCommand(byte[] data) throws Exception {
ByteBuffer buffer = ByteBuffer.wrap(data);
// 读取命令ID
int idLength = buffer.getInt();
byte[] idBytes = new byte[idLength];
buffer.get(idBytes);
String id = new String(idBytes);
// 读取操作类型
OperationType type = OperationType.values()[buffer.getInt()];
switch (type) {
case PUT:
int keyLength = buffer.getInt();
byte[] keyBytes = new byte[keyLength];
buffer.get(keyBytes);
String key = new String(keyBytes);
int valueLength = buffer.getInt();
byte[] value = new byte[valueLength];
buffer.get(value);
return new Command(id, type, key, value);
case DELETE:
keyLength = buffer.getInt();
keyBytes = new byte[keyLength];
buffer.get(keyBytes);
key = new String(keyBytes);
return new Command(id, type, key, null);
case BATCH:
int batchSize = buffer.getInt();
Map<String, byte[]> batch = new HashMap<>();
for (int i = 0; i < batchSize; i++) {
keyLength = buffer.getInt();
keyBytes = new byte[keyLength];
buffer.get(keyBytes);
key = new String(keyBytes);
valueLength = buffer.getInt();
if (valueLength > 0) {
value = new byte[valueLength];
buffer.get(value);
batch.put(key, value);
} else {
batch.put(key, null); // 表示删除
}
}
return new Command(id, batch);
default:
throw new IllegalArgumentException("Unsupported operation type: " + type);
}
}
}
|