forked from roastedroot/proxy-wasm-java-host
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMockSharedHandler.java
More file actions
100 lines (87 loc) · 3.08 KB
/
MockSharedHandler.java
File metadata and controls
100 lines (87 loc) · 3.08 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
package io.roastedroot.proxywasm;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;
public class MockSharedHandler implements Handler {
private final HashMap<String, SharedData> sharedData = new HashMap<>();
@Override
public SharedData getSharedData(String key) throws WasmException {
return sharedData.get(key);
}
@Override
public WasmResult setSharedData(String key, byte[] value, int cas) {
SharedData prev = sharedData.get(key);
if (prev == null) {
if (cas == 0) {
sharedData.put(key, new SharedData(value, 0));
return WasmResult.OK;
} else {
return WasmResult.CAS_MISMATCH;
}
} else {
if (cas == 0 || prev.cas == cas) {
sharedData.put(key, new SharedData(value, prev.cas + 1));
return WasmResult.OK;
} else {
return WasmResult.CAS_MISMATCH;
}
}
}
public static class SharedQueue {
public final QueueName queueName;
public final LinkedList<byte[]> data = new LinkedList<>();
public final int id;
public SharedQueue(QueueName queueName, int id) {
this.queueName = queueName;
this.id = id;
}
}
private final AtomicInteger lastSharedQueueId = new AtomicInteger(0);
private final HashMap<Integer, SharedQueue> sharedQueues = new HashMap<>();
public SharedQueue getSharedQueue(int queueId) {
return sharedQueues.get(queueId);
}
@Override
public WasmResult enqueueSharedQueue(int queueId, byte[] value) {
SharedQueue queue = sharedQueues.get(queueId);
if (queue == null) {
return WasmResult.NOT_FOUND;
}
queue.data.add(value);
return WasmResult.OK;
}
@Override
public byte[] dequeueSharedQueue(int queueId) throws WasmException {
SharedQueue queue = sharedQueues.get(queueId);
if (queue == null) {
throw new WasmException(WasmResult.NOT_FOUND);
}
return queue.data.poll();
}
@Override
public int resolveSharedQueue(QueueName queueName) throws WasmException {
var existing =
sharedQueues.values().stream()
.filter(x -> x.queueName.equals(queueName))
.findFirst();
if (existing.isPresent()) {
return existing.get().id;
} else {
throw new WasmException(WasmResult.NOT_FOUND);
}
}
@Override
public int registerSharedQueue(QueueName queueName) throws WasmException {
var existing =
sharedQueues.values().stream()
.filter(x -> x.queueName.equals(queueName))
.findFirst();
if (existing.isPresent()) {
return existing.get().id;
} else {
int id = lastSharedQueueId.incrementAndGet();
sharedQueues.put(id, new SharedQueue(queueName, id));
return id;
}
}
}