-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
RunLaterCommand.java
389 lines (356 loc) · 15.8 KB
/
RunLaterCommand.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
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
package com.denizenscript.denizencore.scripts.commands.queue;
import com.denizenscript.denizencore.DenizenCore;
import com.denizenscript.denizencore.exceptions.InvalidArgumentsException;
import com.denizenscript.denizencore.objects.Argument;
import com.denizenscript.denizencore.objects.ObjectTag;
import com.denizenscript.denizencore.objects.core.*;
import com.denizenscript.denizencore.scripts.ScriptEntry;
import com.denizenscript.denizencore.scripts.ScriptEntryData;
import com.denizenscript.denizencore.scripts.commands.AbstractCommand;
import com.denizenscript.denizencore.scripts.queues.ScriptQueue;
import com.denizenscript.denizencore.utilities.CoreUtilities;
import com.denizenscript.denizencore.utilities.ScriptUtilities;
import com.denizenscript.denizencore.utilities.YamlConfiguration;
import com.denizenscript.denizencore.utilities.debugging.Debug;
import com.denizenscript.denizencore.utilities.scheduling.AsyncSchedulable;
import com.denizenscript.denizencore.utilities.scheduling.OneTimeSchedulable;
import com.denizenscript.denizencore.utilities.text.StringHolder;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
public class RunLaterCommand extends AbstractCommand {
public RunLaterCommand() {
setName("runlater");
setSyntax("runlater [<script>] (path:<name>) [delay:<duration>] (def:<element>|.../defmap:<map>/def.<name>:<value>)");
setRequiredArguments(2, -1);
}
// <--[command]
// @Name RunLater
// @Syntax runlater [<script>] (path:<name>) [delay:<duration>] (def:<element>|.../defmap:<map>/def.<name>:<value>)
// @Required 2
// @Maximum -1
// @Short Causes a task to run sometime in the future, even if the server restarts.
// @Group queue
//
// @Description
// Causes a task to run sometime in the future, even if the server restarts.
//
// Script, path, and definition inputs work the exact same as with <@link command run>.
//
// This command will store intended script runs to a file, so that even if the server restarts, they will still run.
// Script runs are guaranteed to happen after the time is up - if the server is turned off at the scheduled time, they will run at next startup.
// The guarantee can be broken if the server crashes or other errors occur.
//
// The delay input is a DurationTag instance, that is relative to system time (not server delta time).
//
// Definitions and queue object links will be preserved, so long as they remain valid at time of execution.
// Objects that are lost before the delay is up (such as a linked NPC that is removed) may cause errors.
//
// Implementation note: the system that tracks when scripts should be ran is a fair bit more optimized than 'wait' commands or the 'run' command with a delay,
// specifically for the case of very large delays (hours or more) - in the short term, 'wait' or 'run' with a delay will be better.
//
// @Tags
// None
//
// @Usage
// Use to run a task script named 'example' 3 days later.
// - runlater example delay:3d
//
// -->
@Override
public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException {
MapTag defMap = new MapTag();
for (Argument arg : scriptEntry) {
if (arg.matchesPrefix("def")) {
scriptEntry.addObject("definitions", arg.asType(ListTag.class));
}
else if (arg.matchesPrefix("defmap")
&& arg.matchesArgumentType(MapTag.class)) {
defMap.map.putAll(arg.asType(MapTag.class).map);
}
else if (arg.matchesPrefix("delay")
&& arg.matchesArgumentType(DurationTag.class)) {
scriptEntry.addObject("delay", arg.asType(DurationTag.class));
}
else if (arg.hasPrefix()
&& arg.getPrefix().getRawValue().startsWith("def.")) {
defMap.putObject(arg.getPrefix().getRawValue().substring("def.".length()), arg.object);
}
else if (!scriptEntry.hasObject("script")
&& arg.matchesArgumentType(ScriptTag.class)
&& arg.limitToOnlyPrefix("script")) {
scriptEntry.addObject("script", arg.asType(ScriptTag.class));
}
else if (!scriptEntry.hasObject("path")
&& arg.matchesPrefix("path", "p")) {
scriptEntry.addObject("path", arg.asElement());
}
else if (!scriptEntry.hasObject("script") && !scriptEntry.hasObject("path")
&& !arg.hasPrefix() && arg.asElement().asString().contains(".")) {
String path = arg.asElement().asString();
int dotIndex = path.indexOf('.');
ScriptTag script = new ScriptTag(path.substring(0, dotIndex));
if (!script.isValid()) {
arg.reportUnhandled();
}
else {
scriptEntry.addObject("script", script);
scriptEntry.addObject("path", new ElementTag(path.substring(dotIndex + 1)));
}
}
else {
arg.reportUnhandled();
}
}
if (!scriptEntry.hasObject("script")) {
throw new InvalidArgumentsException("Must define a SCRIPT to be run.");
}
if (!scriptEntry.hasObject("delay")) {
throw new InvalidArgumentsException("Must specify a DELAY.");
}
if (!defMap.map.isEmpty()) {
scriptEntry.addObject("def_map", defMap);
}
}
@Override
public void execute(ScriptEntry scriptEntry) {
ElementTag pathElement = scriptEntry.getElement("path");
ScriptTag script = scriptEntry.getObjectTag("script");
DurationTag delay = scriptEntry.getObjectTag("delay");
MapTag defMap = scriptEntry.getObjectTag("def_map");
String path = pathElement != null ? pathElement.asString() : null;
if (script == null) {
Debug.echoError(scriptEntry.getResidingQueue(), "Script RunLater failed (invalid script name)!");
return;
}
if (path != null && (!script.getContainer().contains(path) || !script.getContainer().getContents().isList(path))) {
Debug.echoError(scriptEntry.getResidingQueue(), "Script RunLater failed (invalid path)!");
return;
}
ListTag definitions = scriptEntry.getObjectTag("definitions");
if (scriptEntry.dbCallShouldDebug()) {
Debug.report(scriptEntry, getName(), script, pathElement, delay, defMap, definitions);
}
FutureRunData runData = new FutureRunData();
runData.definitionList = definitions;
runData.defMap = defMap;
runData.scriptName = script.getName();
runData.path = path;
runData.entryData = scriptEntry.entryData.clone();
runData.executeAt = System.currentTimeMillis() + delay.getMillis();
addNewRunnable(runData);
}
public static class FutureRunData {
public ScriptEntryData entryData;
public String scriptName;
public String path;
public ListTag definitionList;
public MapTag defMap;
public long executeAt;
public YamlConfiguration savedData;
public void load(YamlConfiguration config) {
scriptName = config.getString("script_name");
path = config.getString("path", null);
definitionList = config.contains("definition_list") ? ListTag.valueOf(config.getString("definition_list"), CoreUtilities.errorButNoDebugContext) : null;
defMap = config.contains("definitions") ? MapTag.valueOf(config.getString("definitions"), CoreUtilities.errorButNoDebugContext) : null;
entryData = DenizenCore.getImplementation().getEmptyScriptEntryData().clone();
entryData.load(config.getConfigurationSection("entry_data"));
}
public YamlConfiguration save() {
if (savedData != null) {
return savedData;
}
YamlConfiguration out = new YamlConfiguration();
out.set("execute_at", String.valueOf(executeAt));
out.set("script_name", scriptName);
if (path != null) {
out.set("path", path);
}
if (definitionList != null) {
out.set("definition_list", definitionList.savable());
}
if (defMap != null) {
out.set("definitions", defMap.savable());
}
out.set("entry_data", entryData.save());
return out;
}
public void run() {
try {
if (savedData != null) {
load(savedData);
savedData = null;
}
ScriptTag script = ScriptTag.valueOf(scriptName, entryData.getTagContext());
if (script == null) {
Debug.echoError("Script RunLater failed (invalid script name)!");
return;
}
if (path != null && (!script.getContainer().contains(path) || !script.getContainer().getContents().isList(path))) {
Debug.echoError("Script RunLater failed (invalid path)!");
return;
}
Consumer<ScriptQueue> configure = (queue) -> {
if (defMap != null) {
for (Map.Entry<StringHolder, ObjectTag> val : defMap.map.entrySet()) {
queue.addDefinition(val.getKey().str, val.getValue());
}
}
};
ScriptQueue result = ScriptUtilities.createAndStartQueue(script.getContainer(), path, entryData, null, configure, null, null, definitionList, script.getContainer());
if (result == null) {
Debug.echoError("RunLater: script run failed!");
return;
}
}
catch (Throwable ex) {
Debug.echoError("Error in RunLater...");
Debug.echoError(ex);
}
}
}
public static void addNewRunnable(FutureRunData runData) {
hasChanged = true;
long timeNow = System.currentTimeMillis();
if (runData.executeAt < timeNow + MS_PER_MINUTE * 2) {
nextMinuteFutureRuns.add(runData);
}
else if (runData.executeAt < timeNow + MS_PER_HOUR * 2) {
nextHourFutureRuns.add(runData);
}
else {
farFutureRuns.add(runData);
}
}
public static List<FutureRunData> nextMinuteFutureRuns = new ArrayList<>();
public static List<FutureRunData> nextHourFutureRuns = new ArrayList<>();
public static List<FutureRunData> farFutureRuns = new ArrayList<>();
public static long timeMinuteReorg = 0, timeHourReorg = 0, timeLastSave = 0;
public static final long MS_PER_MINUTE = 60 * 1000, MS_PER_HOUR = 60 * MS_PER_MINUTE;
public static boolean hasAny() {
return !nextMinuteFutureRuns.isEmpty() || !nextHourFutureRuns.isEmpty() || !farFutureRuns.isEmpty();
}
public static String persistFilePath;
public static boolean isSaving = false;
public static boolean hasChanged = false;
public static void init(String path) {
nextMinuteFutureRuns.clear();
nextHourFutureRuns.clear();
farFutureRuns.clear();
persistFilePath = path;
String stored = CoreUtilities.journallingLoadFile(path);
if (stored != null) {
load(YamlConfiguration.load(stored));
}
timeLastSave = System.currentTimeMillis();
}
public static void saveToFile(boolean async) {
if (!hasChanged) {
return;
}
hasChanged = false;
final YamlConfiguration toSave = saveAll();
isSaving = true;
Runnable doSave = () -> {
try {
if (toSave == null) {
File fileObj = new File(persistFilePath);
if (fileObj.exists()) {
fileObj.delete();
}
fileObj = new File(persistFilePath + "~2");
if (fileObj.exists()) {
fileObj.delete();
}
return;
}
CoreUtilities.journallingFileSave(persistFilePath, toSave.saveToString(false));
}
catch (Throwable ex) {
Debug.echoError(ex);
}
finally {
isSaving = false;
}
};
if (async) {
DenizenCore.schedule(new AsyncSchedulable(new OneTimeSchedulable(doSave, 0)));
}
else {
doSave.run();
}
}
public static void tickFutureRuns() {
if (!hasAny()) {
if (hasChanged) {
saveToFile(true);
}
return;
}
long timeNow = System.currentTimeMillis();
for (int i = 0; i < nextMinuteFutureRuns.size(); i++) {
FutureRunData data = nextMinuteFutureRuns.get(i);
if (data.executeAt < timeNow) {
nextMinuteFutureRuns.remove(i--);
hasChanged = true;
data.run();
}
}
if (timeNow > timeMinuteReorg + MS_PER_MINUTE) {
timeMinuteReorg = timeNow;
if (timeNow > timeHourReorg + MS_PER_HOUR) {
timeHourReorg = timeNow;
for (int i = 0; i < farFutureRuns.size(); i++) {
FutureRunData data = farFutureRuns.get(i);
if (data.executeAt < timeNow + (2 * MS_PER_HOUR)) {
nextHourFutureRuns.add(data);
farFutureRuns.remove(i--);
}
}
}
for (int i = 0; i < nextHourFutureRuns.size(); i++) {
FutureRunData data = nextHourFutureRuns.get(i);
if (data.executeAt < timeNow + (2 * MS_PER_MINUTE)) {
nextMinuteFutureRuns.add(data);
nextHourFutureRuns.remove(i--);
}
}
if (timeNow > timeLastSave + (30 * MS_PER_MINUTE)) {
timeLastSave = timeNow;
saveToFile(true);
}
}
}
public static YamlConfiguration saveAll() {
if (!hasAny()) {
return null;
}
YamlConfiguration out = new YamlConfiguration();
int id = 0;
for (FutureRunData runData : nextMinuteFutureRuns) {
out.set("minute_" + (id++), runData.save());
}
for (FutureRunData runData : nextHourFutureRuns) {
out.set("hour_" + (id++), runData.save());
}
for (FutureRunData runData : farFutureRuns) {
out.set("future_" + (id++), runData.save());
}
return out;
}
public static void load(YamlConfiguration config) {
if (config == null) {
Debug.echoError("RunLater load failed due to an invalid YAML file!");
return;
}
for (StringHolder key : config.getKeys(false)) {
YamlConfiguration subConfig = config.getConfigurationSection(key.str);
FutureRunData runData = new FutureRunData();
runData.savedData = subConfig;
runData.executeAt = Long.parseLong(subConfig.getString("execute_at"));
addNewRunnable(runData);
}
}
}