/
RedisHelper.java
341 lines (332 loc) · 15.8 KB
/
RedisHelper.java
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
package com.denizenscript.denizencore.utilities;
import com.denizenscript.denizencore.DenizenCore;
import com.denizenscript.denizencore.exceptions.InvalidArgumentsRuntimeException;
import com.denizenscript.denizencore.objects.ArgumentHelper;
import com.denizenscript.denizencore.objects.ObjectTag;
import com.denizenscript.denizencore.objects.core.ElementTag;
import com.denizenscript.denizencore.objects.core.ListTag;
import com.denizenscript.denizencore.objects.core.SecretTag;
import com.denizenscript.denizencore.scripts.ScriptEntry;
import com.denizenscript.denizencore.scripts.commands.AbstractCommand;
import com.denizenscript.denizencore.utilities.debugging.Debug;
import com.denizenscript.denizencore.utilities.scheduling.AsyncSchedulable;
import com.denizenscript.denizencore.utilities.scheduling.OneTimeSchedulable;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;
import redis.clients.jedis.util.SafeEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
public class RedisHelper {
public static Map<String, Jedis> connections = new HashMap<>();
public static Map<String, JedisPubSub> subscriptions = new HashMap<>();
public static AtomicBoolean isEnabled = new AtomicBoolean(true);
public static void onDisable() {
isEnabled.set(false);
for (Map.Entry<String, JedisPubSub> entry : subscriptions.entrySet()) {
try {
entry.getValue().punsubscribe();
}
catch (Exception e) {
Debug.echoError(e);
}
}
subscriptions.clear();
for (Map.Entry<String, Jedis> entry : connections.entrySet()) {
try {
entry.getValue().close();
}
catch (Exception e) {
Debug.echoError(e);
}
}
connections.clear();
}
public static ObjectTag processResponse(Object response) {
if (response instanceof List) {
ListTag list = new ListTag();
for (Object o : (List) response) {
ObjectTag resp = processResponse(o);
if (resp == null) {
resp = new ElementTag("null");
}
list.addObject(resp);
}
return list;
}
else if (response instanceof byte[]) {
return new ElementTag(new String((byte[]) response));
}
else if (response instanceof Long) {
return new ElementTag((long) response);
}
else {
return null;
}
}
public static void runChecked(Runnable r, ScriptEntry scriptEntry) {
DenizenCore.schedule(new AsyncSchedulable(new OneTimeSchedulable(() -> {
try {
r.run();
}
catch (Throwable ex) {
if (isEnabled.get() || CoreConfiguration.debugVerbose) { // Ignore errors when server is shutting down
DenizenCore.schedule(new OneTimeSchedulable(() -> {
Debug.echoError(ex);
scriptEntry.setFinished(true);
}, 0));
}
}
}, 0)));
}
public static void executeCommand(ScriptEntry scriptEntry) {
isEnabled.set(true);
ElementTag port = scriptEntry.argForPrefixAsElement("port", "6379");
if (!port.isInt()) {
throw new InvalidArgumentsRuntimeException("Port must be an integer number.");
}
ElementTag id = scriptEntry.requiredArgForPrefixAsElement("id");
ElementTag message = scriptEntry.argForPrefixAsElement("message", null);
ListTag args = scriptEntry.argForPrefix("args", ListTag.class, true);
boolean ssl = scriptEntry.argAsBoolean("ssl");
ObjectTag auth = scriptEntry.argForPrefix("auth", ObjectTag.class, true);
ElementTag action = scriptEntry.getElement("action");
ElementTag host = scriptEntry.getElement("host");
ListTag channels = scriptEntry.getObjectTag("channels");
ElementTag channel = scriptEntry.getElement("channel");
ElementTag command = scriptEntry.getElement("command");
String redisID = id.asLowerString();
if (scriptEntry.dbCallShouldDebug()) {
Debug.report(scriptEntry, "redis", id, action, host, auth, port, AbstractCommand.db("ssl", ssl), channels, channel, message, command, args);
}
if (!action.asString().equalsIgnoreCase("connect") &&
(!action.asString().equalsIgnoreCase("command") || !scriptEntry.shouldWaitFor())) {
scriptEntry.setFinished(true);
}
try {
if (action.asString().equalsIgnoreCase("connect")) {
if (host == null) {
Debug.echoError(scriptEntry, "Must specify a valid redis host!");
scriptEntry.setFinished(true);
return;
}
if (connections.containsKey(redisID)) {
Debug.echoError(scriptEntry, "Already connected to a server with ID '" + redisID + "'!");
scriptEntry.setFinished(true);
return;
}
runChecked(() -> {
Jedis con = null;
if (CoreConfiguration.debugVerbose) {
Debug.echoDebug(scriptEntry, "Connecting to " + host + " on port " + port);
}
try {
con = new Jedis(host.asString(), port.asInt(), ssl);
if (auth != null) {
String[] redisArgs = new String[] { auth.shouldBeType(SecretTag.class) ? auth.asType(SecretTag.class, scriptEntry.context).getValue() : auth.toString() };
if (redisArgs[0] == null) {
throw new Exception("Invalid SecretTag input for AUTH.");
}
con.sendCommand(() -> SafeEncoder.encode("AUTH"), redisArgs);
}
}
catch (final Exception e) {
DenizenCore.schedule(new OneTimeSchedulable(() -> {
Debug.echoError(scriptEntry, "Redis Exception: " + e.getMessage());
scriptEntry.setFinished(true);
if (CoreConfiguration.debugVerbose) {
Debug.echoError(scriptEntry, e);
}
}, 0));
}
if (CoreConfiguration.debugVerbose) {
Debug.echoDebug(scriptEntry, "Connection did not error");
}
final Jedis conn = con;
if (con != null) {
DenizenCore.schedule(new OneTimeSchedulable(() -> {
connections.put(redisID, conn);
Debug.echoDebug(scriptEntry, "Successfully connected to " + host + " on port " + port);
scriptEntry.setFinished(true);
}, 0));
}
else {
DenizenCore.schedule(new OneTimeSchedulable(() -> {
scriptEntry.setFinished(true);
if (CoreConfiguration.debugVerbose) {
Debug.echoDebug(scriptEntry, "Connecting errored!");
}
}, 0));
}
}, scriptEntry);
}
else if (action.asString().equalsIgnoreCase("disconnect")) {
scriptEntry.setFinished(true);
if (!connections.containsKey(redisID)) {
Debug.echoError(scriptEntry, "Not connected to redis server with ID '" + redisID + "'!");
return;
}
Jedis con = connections.remove(redisID);
JedisPubSub pubSub = subscriptions.remove(redisID);
if (pubSub != null) {
try {
// TODO: Make this work better?
pubSub.punsubscribe();
}
catch (Exception e) {
Debug.echoError(e);
}
}
try {
con.close();
}
catch (Exception e) {
Debug.echoError(e);
}
Debug.echoDebug(scriptEntry, "Disconnected from '" + redisID + "'.");
}
else if (action.asString().equalsIgnoreCase("subscribe")) {
Jedis con = connections.get(redisID);
if (con == null) {
Debug.echoError(scriptEntry, "Not connected to redis server with ID '" + redisID + "'!");
scriptEntry.setFinished(true);
return;
}
if (subscriptions.containsKey(redisID)) {
Debug.echoError(scriptEntry, "Already subscribed to a channel on redis server with ID '" + redisID + "'!");
scriptEntry.setFinished(true);
return;
}
JedisPubSub jedisPubSub = new DenizenJedisPubSub(redisID);
subscriptions.put(redisID, jedisPubSub);
String[] channelArr = new String[channels.size()];
for (int i = 0; i < channels.size(); i++) {
channelArr[i] = CoreUtilities.toLowerCase(channels.get(i));
}
runChecked(() -> { con.psubscribe(jedisPubSub, channelArr); scriptEntry.setFinished(true); }, scriptEntry);
}
else if (action.asString().equalsIgnoreCase("unsubscribe")) {
scriptEntry.setFinished(true);
if (!connections.containsKey(redisID)) {
Debug.echoError(scriptEntry, "Not connected to redis server with ID '" + redisID + "'!");
return;
}
if (!subscriptions.containsKey(redisID)) {
Debug.echoError(scriptEntry, "Not subscribed to redis server with ID '" + redisID + "'!");
return;
}
JedisPubSub pubSub = subscriptions.remove(redisID);
try {
pubSub.punsubscribe();
}
catch (Exception e) {
Debug.echoError(e);
}
}
else if (action.asString().equalsIgnoreCase("publish")) {
if (message == null) {
Debug.echoError(scriptEntry, "Must specify a valid message to publish!");
scriptEntry.setFinished(true);
return;
}
final Jedis con = connections.get(redisID);
if (con == null) {
Debug.echoError(scriptEntry, "Not connected to redis server with ID '" + redisID + "'!");
scriptEntry.setFinished(true);
return;
}
if (subscriptions.containsKey(redisID)) {
Debug.echoError(scriptEntry, "Cannot publish messages while subscribed to redis server with ID '" + redisID + "'!");
scriptEntry.setFinished(true);
return;
}
Debug.echoDebug(scriptEntry, "Publishing message '" + message.asString() + "' to channel '" + channel.asString() + "'");
Runnable doQuery = () -> {
try {
ElementTag result = new ElementTag(con.publish(channel.asLowerString(), message.asString()));
scriptEntry.addObject("result", result);
scriptEntry.setFinished(true);
}
catch (final Exception ex) {
DenizenCore.schedule(new OneTimeSchedulable(() -> {
Debug.echoError(scriptEntry, "Redis Exception: " + ex.getMessage());
scriptEntry.setFinished(true);
if (CoreConfiguration.debugVerbose) {
Debug.echoError(scriptEntry, ex);
}
}, 0));
}
};
if (scriptEntry.shouldWaitFor()) {
runChecked(doQuery, scriptEntry);
}
else {
doQuery.run();
}
}
else if (action.asString().equalsIgnoreCase("command")) {
if (command == null) {
Debug.echoError(scriptEntry, "Must specify a valid redis command!");
scriptEntry.setFinished(true);
return;
}
final Jedis con = connections.get(redisID);
if (con == null) {
Debug.echoError(scriptEntry, "Not connected to redis server with ID '" + redisID + "'!");
scriptEntry.setFinished(true);
return;
}
if (subscriptions.containsKey(redisID)) {
Debug.echoError(scriptEntry, "Cannot run commands while subscribed to redis server with ID '" + redisID + "'!");
scriptEntry.setFinished(true);
return;
}
Debug.echoDebug(scriptEntry, "Running command " + command.asString());
Runnable doQuery = () -> {
try {
String redisCommand;
String[] redisArgs;
if (args == null) {
String[] splitCommand = ArgumentHelper.buildArgs(command.asString());
redisCommand = splitCommand[0];
redisArgs = Arrays.copyOfRange(splitCommand, 1, splitCommand.length);
}
else {
redisCommand = command.asString();
redisArgs = args.toArray(new String[0]);
}
ObjectTag result = processResponse(con.sendCommand(() -> SafeEncoder.encode(redisCommand), redisArgs));
scriptEntry.addObject("result", result);
scriptEntry.setFinished(true);
}
catch (final Exception ex) {
DenizenCore.schedule(new OneTimeSchedulable(() -> {
Debug.echoError(scriptEntry, "Redis Exception: " + ex.getMessage());
scriptEntry.setFinished(true);
if (CoreConfiguration.debugVerbose) {
Debug.echoError(scriptEntry, ex);
}
}, 0));
}
};
if (scriptEntry.shouldWaitFor()) {
runChecked(doQuery, scriptEntry);
}
else {
doQuery.run();
}
}
else {
Debug.echoError(scriptEntry, "Unknown action '" + action.asString() + "'");
}
}
catch (Exception ex) {
Debug.echoError(scriptEntry, "Redis Exception: " + ex.getMessage());
if (CoreConfiguration.debugVerbose) {
Debug.echoError(scriptEntry, ex);
}
}
}
}