forked from dbos-inc/dbos-transact-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDBOS.java
More file actions
1272 lines (1162 loc) · 48 KB
/
Copy pathDBOS.java
File metadata and controls
1272 lines (1162 loc) · 48 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
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package dev.dbos.transact;
import dev.dbos.transact.config.DBOSConfig;
import dev.dbos.transact.context.DBOSContext;
import dev.dbos.transact.execution.DBOSExecutor;
import dev.dbos.transact.execution.DBOSLifecycleListener;
import dev.dbos.transact.execution.RegisteredWorkflow;
import dev.dbos.transact.execution.ThrowingRunnable;
import dev.dbos.transact.execution.ThrowingSupplier;
import dev.dbos.transact.internal.DBOSIntegration;
import dev.dbos.transact.internal.DBOSInvocationHandler;
import dev.dbos.transact.internal.QueueRegistry;
import dev.dbos.transact.internal.WorkflowRegistry;
import dev.dbos.transact.migrations.MigrationManager;
import dev.dbos.transact.workflow.Debouncer;
import dev.dbos.transact.workflow.ForkOptions;
import dev.dbos.transact.workflow.ListWorkflowsInput;
import dev.dbos.transact.workflow.Queue;
import dev.dbos.transact.workflow.QueueConflictResolution;
import dev.dbos.transact.workflow.QueueOptions;
import dev.dbos.transact.workflow.ScheduleStatus;
import dev.dbos.transact.workflow.SendMessage;
import dev.dbos.transact.workflow.SerializationStrategy;
import dev.dbos.transact.workflow.Step;
import dev.dbos.transact.workflow.StepInfo;
import dev.dbos.transact.workflow.StepOptions;
import dev.dbos.transact.workflow.VersionInfo;
import dev.dbos.transact.workflow.Workflow;
import dev.dbos.transact.workflow.WorkflowDelay;
import dev.dbos.transact.workflow.WorkflowHandle;
import dev.dbos.transact.workflow.WorkflowSchedule;
import dev.dbos.transact.workflow.WorkflowStatus;
import dev.dbos.transact.workflow.internal.InternalWorkflows;
import java.io.IOException;
import java.io.InputStream;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import org.jspecify.annotations.NonNull;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Facade for context-based access to DBOS. `DBOS` is responsible for: Lifecycle - configuring,
* launching, and shutting down DBOS Starting, enqueuing, and managing workflows Interacting with
* workflows - getting status, results, events, and messages Accessing the workflow context Etc.
*/
public class DBOS implements AutoCloseable {
private static final Logger logger = LoggerFactory.getLogger(DBOS.class);
private static final String DBOS_VERSION = loadVersionFromResources();
private final WorkflowRegistry workflowRegistry = new WorkflowRegistry();
private final QueueRegistry queueRegistry = new QueueRegistry();
private final Set<DBOSLifecycleListener> lifecycleRegistry = ConcurrentHashMap.newKeySet();
private final DBOSConfig config;
private final AtomicReference<DBOSExecutor> dbosExecutor = new AtomicReference<>();
private final DBOSIntegration integration;
private final RegisteredWorkflow debouncerWorkflow;
private AlertHandler alertHandler;
/**
* Construct a new DBOS instance with the provided configuration.
*
* @param config the DBOS configuration; must not be null
* @throws NullPointerException if config or required config fields are null
*/
public DBOS(@NonNull DBOSConfig config) {
Objects.requireNonNull(config, "DBOSConfig must not be null");
Objects.requireNonNull(config.appName(), "DBOSConfig.appName must not be null");
if (config.dataSource() == null) {
Objects.requireNonNull(config.databaseUrl(), "DBOSConfig.databaseUrl must not be null");
Objects.requireNonNull(config.dbUser(), "DBOSConfig.dbUser must not be null");
Objects.requireNonNull(config.dbPassword(), "DBOSConfig.dbPassword must not be null");
}
this.config = new DBOSConfig(config);
this.integration =
new DBOSIntegration(
this.config, this.workflowRegistry, dbosExecutor::get, this::registerLifecycleListener);
// Register the built-in debouncer service workflow directly (without a proxy) so callers can
// use Debouncer without having to declare and wire the service themselves.
var internalWorkflows = new InternalWorkflows(this, dbosExecutor::get);
workflowRegistry.registerInternalInstance(internalWorkflows);
this.debouncerWorkflow =
workflowRegistry.registerInternalWorkflow(
Constants.DEBOUNCER_WORKFLOW_NAME,
Constants.DEBOUNCER_CLASS_NAME,
internalWorkflows,
InternalWorkflows.debouncerWorkflowMethod());
}
/**
* Close this DBOS instance and shut down all associated resources. This method delegates to
* {@link #shutdown()}.
*/
@Override
public void close() {
shutdown();
}
private static @Nullable String loadVersionFromResources() {
final String PROPERTIES_FILE = "/dev/dbos/transact/app.properties";
final String VERSION_KEY = "app.version";
Properties props = new Properties();
try (InputStream input = DBOS.class.getResourceAsStream(PROPERTIES_FILE)) {
if (input == null) {
logger.warn("Could not find {} resource file", PROPERTIES_FILE);
return "<unknown (resource missing)>";
}
// Load the properties from the file
props.load(input);
// Retrieve the version property, defaulting to "unknown"
return props.getProperty(VERSION_KEY, "<unknown>");
} catch (IOException ex) {
logger.error("Error loading version properties", ex);
return "<unknown (IO Error)>";
}
}
/**
* Get the current DBOS version.
*
* @return the DBOS version string
*/
public static String version() {
return DBOS_VERSION;
}
/**
* Register a lifecycle listener that receives callbacks when DBOS is launched or shut down
*
* @param listener the lifecycle listener to register
*/
private void registerLifecycleListener(@NonNull DBOSLifecycleListener listener) {
if (dbosExecutor.get() != null) {
throw new IllegalStateException("Cannot register lifecycle listener after DBOS is launched");
}
lifecycleRegistry.add(listener);
}
/**
* Register a DBOS queue. This must be called on each queue prior to launch, so that recovery has
* the queue options available.
*
* @param queue `Queue` to register
*/
public void registerQueue(@NonNull Queue queue) {
if (dbosExecutor.get() != null) {
throw new IllegalStateException("Cannot build a queue after DBOS is launched");
}
queueRegistry.register(queue);
}
/**
* Register a set of DBOS queues. Each queue must be registered prior to launch, so that recovery
* has the queue options available.
*
* @param queues collection of `Queue` instances to register
*/
public void registerQueues(@NonNull Queue... queues) {
for (Queue queue : queues) {
registerQueue(queue);
}
}
/**
* Register a database-backed dynamic queue. Must be called after launch. Queue configuration can
* be updated at runtime via {@link #updateQueue(String, QueueOptions)}.
*
* <p>Uses {@link QueueConflictResolution#UPDATE_IF_LATEST_VERSION} by default: the existing
* configuration is overwritten only if this executor is running the latest application version.
*
* @param name Queue name
* @param options Initial configuration options
*/
public void registerQueue(@NonNull String name, @NonNull QueueOptions options) {
ensureLaunched("registerQueue")
.registerDynamicQueue(name, options, QueueConflictResolution.UPDATE_IF_LATEST_VERSION);
}
/**
* Register a database-backed dynamic queue. Must be called after launch. Queue configuration can
* be updated at runtime via {@link #updateQueue(String, QueueOptions)}.
*
* @param name Queue name
* @param options Initial configuration options
* @param onConflict How to handle an existing queue with the same name
*/
public void registerQueue(
@NonNull String name,
@NonNull QueueOptions options,
@NonNull QueueConflictResolution onConflict) {
ensureLaunched("registerQueue").registerDynamicQueue(name, options, onConflict);
}
/**
* Update the configuration of a database-backed dynamic queue. Must be called after launch. Only
* fields that are present in {@code options} are written; absent fields are left unchanged.
*
* @param name Queue name
* @param options Fields to update
*/
public void updateQueue(@NonNull String name, @NonNull QueueOptions options) {
ensureLaunched("updateQueue").updateDynamicQueue(name, options);
}
/**
* Retrieve a database-backed dynamic queue by name. Must be called after launch.
*
* @param name Queue name
* @return the queue if it exists in the database, or empty
*/
public @NonNull Optional<Queue> findQueue(@NonNull String name) {
return ensureLaunched("findQueue").findDynamicQueue(name);
}
/**
* Delete a database-backed dynamic queue. Must be called after launch.
*
* @param name Queue name
* @return true if the queue was deleted, false if it did not exist
*/
public boolean deleteQueue(@NonNull String name) {
return ensureLaunched("deleteQueue").deleteDynamicQueue(name);
}
/**
* List all database-backed dynamic queues. Must be called after launch.
*
* @return list of all queues currently registered in the database
*/
public @NonNull List<Queue> listQueues() {
return ensureLaunched("listQueues").listDynamicQueues();
}
/**
* Register all workflows and steps in the provided class instance
*
* @param <T> The interface type for the instance
* @param interfaceClass The interface class for the workflows
* @param target An implementation instance providing the workflow and step function code
* @return A proxy, with interface {@literal <T>}, that provides durability for the workflow
* functions
*/
public <T> @NonNull T registerProxy(@NonNull Class<T> interfaceClass, @NonNull T target) {
return registerProxy(interfaceClass, target, null);
}
/**
* Register all workflows and steps in the provided class instance
*
* @param <T> The interface type for the instance
* @param interfaceClass The interface class for the workflows
* @param target An implementation instance providing the workflow and step function code
* @param instanceName Name of the instance, allowing multiple instances of the same class to be
* registered
* @return A proxy, with interface {@literal <T>}, that provides durability for the workflow
* functions
*/
public <T> @NonNull T registerProxy(
@NonNull Class<T> interfaceClass, @NonNull T target, @Nullable String instanceName) {
if (dbosExecutor.get() != null) {
throw new IllegalStateException("Cannot register workflow after DBOS is launched");
}
Objects.requireNonNull(interfaceClass, "interfaceClass must not be null");
Objects.requireNonNull(target, "target must not be null");
if (!hasWorkflowsOrSteps(target)) {
throw new IllegalArgumentException("Target does not contain any @Workflow or @Step methods");
}
workflowRegistry.registerInstance(instanceName, target);
for (var method : target.getClass().getDeclaredMethods()) {
var wfTag = method.getAnnotation(Workflow.class);
if (wfTag != null) {
method.setAccessible(true); // In case it's not public
integration.registerWorkflow(wfTag, target, method, instanceName);
}
}
return DBOSInvocationHandler.createProxy(
interfaceClass, target, instanceName, dbosExecutor::get);
}
/**
* Check if the provided target object contains any methods annotated with @Workflow.
*
* @param target the object to check for workflow methods
* @return true if the target contains at least one @Workflow annotated method, false otherwise
* @throws NullPointerException if target is null
*/
static boolean hasWorkflowsOrSteps(@NonNull Object target) {
var methods =
Objects.requireNonNull(target, "target can not be null").getClass().getDeclaredMethods();
for (var method : methods) {
if (method.isAnnotationPresent(Workflow.class) || method.isAnnotationPresent(Step.class)) {
return true;
}
}
return false;
}
/**
* Registers an {@link AlertHandler} to handle alerts generated by DBOS. This method must be
* called before DBOS is launched; attempting to register an alert handler after launch will
* result in an {@link IllegalStateException}.
*
* @param handler the {@link AlertHandler} instance to register; must not be null
* @throws IllegalStateException if called after DBOS has been launched
*/
public void registerAlertHandler(AlertHandler handler) {
if (dbosExecutor.get() != null) {
throw new IllegalStateException("Cannot set alert handler after DBOS is launched");
}
this.alertHandler = handler;
}
// package private method for test purposes
@Nullable DBOSExecutor getDbosExecutor() {
return dbosExecutor.get();
}
/**
* Launch DBOS, and start recovery. All workflows, queues, and other objects should be registered
* before launch
*/
public void launch() {
logger.info("Launching DBOS v{}", DBOS.version());
if (dbosExecutor.get() == null) {
var executor = new DBOSExecutor(config);
if (dbosExecutor.compareAndSet(null, executor)) {
if (config.migrate()) {
MigrationManager.runMigrations(config);
}
executor.start(
this,
new HashSet<>(this.lifecycleRegistry),
workflowRegistry.getWorkflowSnapshot(),
workflowRegistry.getInstanceSnapshot(),
workflowRegistry.getInternalWorkflowSnapshot(),
workflowRegistry.getInternalInstanceSnapshot(),
queueRegistry.getSnapshot(),
alertHandler);
}
}
}
/**
* Shut down DBOS. This method should only be used in test environments, where DBOS is used
* multiple times in the same JVM.
*/
public void shutdown() {
var current = dbosExecutor.get();
if (current != null) {
current.close();
if (!dbosExecutor.compareAndSet(current, null)) {
logger.error("failed to set DBOS executor to null on shut down");
}
}
logger.info("DBOS shut down");
}
// helper for methods that can only be called after launch
private DBOSExecutor ensureLaunched(String caller) {
var exec = dbosExecutor.get();
if (exec == null) {
throw new IllegalStateException(
String.format("Cannot call %s before DBOS is launched", caller));
}
return exec;
}
/**
* Retrieve a queue definition
*
* @param queueName Name of the queue
* @return Optional containing the queue definition for given `queueName`, or empty if not found
*/
public @NonNull Optional<Queue> getQueue(@NonNull String queueName) {
return ensureLaunched("getQueue").findStaticQueue(queueName);
}
/**
* Durable sleep. Use this instead of Thread.sleep, especially in workflows. On restart or during
* recovery the original expected wakeup time is honoured as opposed to sleeping all over again.
*
* @param duration amount of time to sleep
*/
public void sleep(@NonNull Duration duration) {
if (!DBOSContext.inWorkflow() || DBOSContext.inStep()) {
try {
Thread.sleep(duration.toMillis());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} else {
ensureLaunched("sleep").sleep(duration);
}
}
/**
* Start or enqueue a workflow with a return value
*
* @param <T> Return type of the workflow
* @param <E> Type of checked exception thrown by the workflow, if any
* @param supplier A lambda that calls exactly one workflow function
* @param options Start workflow options
* @return A handle to the enqueued or running workflow
*/
public <T, E extends Exception> @NonNull WorkflowHandle<T, E> startWorkflow(
@NonNull ThrowingSupplier<T, E> supplier, @Nullable StartWorkflowOptions options) {
return ensureLaunched("startWorkflow").startWorkflow(supplier, options);
}
/**
* Start or enqueue a workflow with default options
*
* @param <T> Return type of the workflow
* @param <E> Type of checked exception thrown by the workflow, if any
* @param supplier A lambda that calls exactly one workflow function
* @return A handle to the enqueued or running workflow
*/
public <T, E extends Exception> @NonNull WorkflowHandle<T, E> startWorkflow(
@NonNull ThrowingSupplier<T, E> supplier) {
return startWorkflow(supplier, null);
}
/**
* Start or enqueue a workflow with no return value
*
* @param <E> Type of checked exception thrown by the workflow, if any
* @param runnable A lambda that calls exactly one workflow function
* @param options Start workflow options
* @return A handle to the enqueued or running workflow
*/
public <E extends Exception> @NonNull WorkflowHandle<Void, E> startWorkflow(
@NonNull ThrowingRunnable<E> runnable, @Nullable StartWorkflowOptions options) {
return startWorkflow(
() -> {
runnable.execute();
return null;
},
options);
}
/**
* Start or enqueue a workflow with no return value, using default options
*
* @param <E> Type of checked exception thrown by the workflow, if any
* @param runnable A lambda that calls exactly one workflow function
* @return A handle to the enqueued or running workflow
*/
public <E extends Exception> @NonNull WorkflowHandle<Void, E> startWorkflow(
@NonNull ThrowingRunnable<E> runnable) {
return startWorkflow(runnable, null);
}
/**
* Build a {@link Debouncer} that consolidates a series of calls on the same key into one
* execution of the targeted workflow using the most recent arguments.
*
* <p>The returned debouncer is immutable; configuration helpers like {@link
* Debouncer#withQueue(String)} and {@link Debouncer#withDebounceTimeout(java.time.Duration)}
* return new instances.
*
* @param <R> the return type of the debounced workflow (used only for type inference)
* @return a fresh debouncer bound to this DBOS instance
*/
public <R> @NonNull Debouncer<R> debouncer() {
return new Debouncer<>(this, ensureLaunched("debouncer"), debouncerWorkflow);
}
/**
* Returns the DBOS integration APIs for use by specialized integrations such as AOP aspects and
* event listeners.
*
* <p>The returned {@link DBOSIntegration} instance is <strong>not part of the primary public
* API</strong> and may change without notice. Application code should use the methods on this
* class directly instead.
*
* @return the {@link DBOSIntegration} accessor for this DBOS instance
*/
public @NonNull DBOSIntegration integration() {
return integration;
}
/**
* Get the result of a workflow, or rethrow the exception thrown by the workflow
*
* @param <T> Return type of the workflow
* @param <E> Checked exception type, if any, thrown by the workflow
* @param workflowId ID of the workflow to retrieve
* @return Return value of the workflow
* @throws E if the workflow threw an exception
*/
public <T, E extends Exception> T getResult(@NonNull String workflowId) throws E {
return ensureLaunched("getResult").<T, E>getResult(workflowId);
}
/**
* Get the status of a workflow
*
* @param workflowId ID of the workflow to query
* @return Current workflow status for the provided workflowId, or empty if no such workflow
* exists.
*/
public @NonNull Optional<WorkflowStatus> getWorkflowStatus(@NonNull String workflowId) {
return Optional.ofNullable(ensureLaunched("getWorkflowStatus").getWorkflowStatus(workflowId));
}
/**
* Send a message to a workflow
*
* @param destinationId recipient of the message
* @param message message to be sent
* @param topic topic to which the message is send
* @param idempotencyKey optional idempotency key for exactly-once send
*/
public void send(
@NonNull String destinationId,
@NonNull Object message,
@Nullable String topic,
@Nullable String idempotencyKey) {
send(destinationId, message, topic, idempotencyKey, null, false);
}
/**
* Send a message to a workflow
*
* @param destinationId recipient of the message
* @param message message to be sent
* @param topic topic to which the message is send
*/
public void send(@NonNull String destinationId, @NonNull Object message, @Nullable String topic) {
send(destinationId, message, topic, null, null, false);
}
/**
* Send a message to a workflow with serialization strategy
*
* @param destinationId recipient of the message
* @param message message to be sent
* @param topic topic to which the message is send
* @param idempotencyKey optional idempotency key for exactly-once send
* @param serialization serialization strategy to use (null for default)
*/
public void send(
@NonNull String destinationId,
@NonNull Object message,
@Nullable String topic,
@Nullable String idempotencyKey,
@Nullable SerializationStrategy serialization) {
send(destinationId, message, topic, idempotencyKey, serialization, false);
}
/**
* Send a message to a workflow with all options
*
* @param destinationId recipient of the message
* @param message message to be sent
* @param topic topic to which the message is sent
* @param idempotencyKey optional idempotency key for exactly-once send
* @param serialization serialization strategy to use (null for default)
* @param sendToForks if true, also deliver the message to any forked copies of the destination
* workflow
*/
public void send(
@NonNull String destinationId,
@NonNull Object message,
@Nullable String topic,
@Nullable String idempotencyKey,
@Nullable SerializationStrategy serialization,
boolean sendToForks) {
if (serialization == null) serialization = SerializationStrategy.DEFAULT;
ensureLaunched("send")
.send(destinationId, message, topic, idempotencyKey, serialization, sendToForks);
}
/**
* Send multiple messages to workflows using default options
*
* @param messages list of messages to send
*/
public void sendBulk(@NonNull List<SendMessage> messages) {
sendBulk(messages, false, null);
}
/**
* Send multiple messages to workflows
*
* @param messages list of messages to send
* @param sendToForks if true, also deliver each message to any forked copies of the destination
* workflow
*/
public void sendBulk(@NonNull List<SendMessage> messages, boolean sendToForks) {
sendBulk(messages, sendToForks, null);
}
/**
* Send multiple messages to workflows with full options
*
* @param messages list of messages to send
* @param sendToForks if true, also deliver each message to any forked copies of the destination
* workflow
* @param serialization serialization strategy to use (null for default)
*/
public void sendBulk(
@NonNull List<SendMessage> messages,
boolean sendToForks,
@Nullable SerializationStrategy serialization) {
if (serialization == null) serialization = SerializationStrategy.DEFAULT;
ensureLaunched("sendBulk").sendBulk(messages, sendToForks, serialization);
}
/**
* Get a message sent to a particular topic
*
* @param topic the topic whose message to get
* @param timeout duration after which the call times out
* @return the message if there is one or else null
*/
public @NonNull @SuppressWarnings("unchecked") <T> Optional<T> recv(
@Nullable String topic, @NonNull Duration timeout) {
return Optional.ofNullable((T) ensureLaunched("recv").recv(topic, timeout));
}
/**
* Call within a workflow to publish a key value pair. Uses the workflow's serialization format.
*
* @param key identifier for published data
* @param value data that is published
*/
public void setEvent(@NonNull String key, @NonNull Object value) {
setEvent(key, value, null);
}
/**
* Call within a workflow to publish a key value pair with a specific serialization strategy.
*
* @param key identifier for published data
* @param value data that is published
* @param serialization serialization strategy to use (null to use workflow's default)
*/
public void setEvent(
@NonNull String key, @NonNull Object value, @Nullable SerializationStrategy serialization) {
// If no explicit serialization specified, use the workflow context's serialization
if (serialization == null) {
serialization = serializationStrategy();
}
ensureLaunched("setEvent").setEvent(key, value, serialization);
}
/**
* Get the data published by a workflow
*
* @param workflowId id of the workflow who data is to be retrieved
* @param key identifies the data
* @param timeout time to wait for data before timing out
* @return Optional containing the published value if available, or empty if timeout occurs or no
* value found
*/
public @NonNull @SuppressWarnings("unchecked") <T> Optional<T> getEvent(
@NonNull String workflowId, @NonNull String key, @NonNull Duration timeout) {
logger.debug("Received getEvent for {} {}", workflowId, key);
return Optional.ofNullable((T) ensureLaunched("getEvent").getEvent(workflowId, key, timeout));
}
/**
* Run the provided function as a step; this variant is for functions with a return value
*
* @param <E> Checked exception thrown by the step, if any
* @param stepfunc function or lambda to run
* @param opts step name, and retry options for running the step
* @throws E
*/
public <T, E extends Exception> T runStep(
@NonNull ThrowingSupplier<T, E> stepfunc, @NonNull StepOptions opts) throws E {
return ensureLaunched("runStep").runStep(stepfunc, opts, null);
}
/**
* Run the provided function as a step; this variant is for functions with a return value
*
* @param <E> Checked exception thrown by the step, if any
* @param stepfunc function or lambda to run
* @param name name of the step, for tracing and to record in the system database
* @throws E
*/
public <T, E extends Exception> T runStep(
@NonNull ThrowingSupplier<T, E> stepfunc, @NonNull String name) throws E {
return runStep(stepfunc, new StepOptions(name));
}
/**
* Run the provided function as a step; this variant is for functions with no return value
*
* @param <E> Checked exception thrown by the step, if any
* @param stepfunc function or lambda to run
* @param opts step name, and retry options for running the step
* @throws E
*/
public <E extends Exception> void runStep(
@NonNull ThrowingRunnable<E> stepfunc, @NonNull StepOptions opts) throws E {
runStep(
() -> {
stepfunc.execute();
return null;
},
opts);
}
/**
* Run the provided function as a step; this variant is for functions with no return value
*
* @param <E> Checked exception thrown by the step, if any
* @param stepfunc function or lambda to run
* @param name Name of the step, for tracing and recording in the system database
* @throws E
*/
public <E extends Exception> void runStep(
@NonNull ThrowingRunnable<E> stepfunc, @NonNull String name) throws E {
runStep(stepfunc, new StepOptions(name));
}
/**
* Resume a workflow starting from the step after the last complete step. This method allows
* resuming workflows that were previously interrupted, failed, or canceled. The workflow will
* continue execution from where it left off, replaying any completed steps deterministically.
*
* @param <T> Return type of the workflow function
* @param <E> Type of checked exception thrown by the workflow function, if any
* @param workflowId ID of the workflow to resume; must not be null
* @param queueName optional queue name to enqueue the resumed workflow to; if null, the workflow
* will be resumed in the default execution context
* @return A handle to the resumed workflow
* @throws IllegalStateException if called before DBOS is launched
*/
@SuppressWarnings("unchecked")
public <T, E extends Exception> @NonNull WorkflowHandle<T, E> resumeWorkflow(
@NonNull String workflowId, @Nullable String queueName) {
var handles = resumeWorkflows(List.of(workflowId), queueName);
assert (handles.size() == 1);
return (WorkflowHandle<T, E>) handles.get(0);
}
/**
* Resume a workflow starting from the step after the last complete step using the default queue.
* This method is equivalent to calling {@code resumeWorkflow(workflowId, null)}. The workflow
* will continue execution from where it left off, replaying any completed steps
* deterministically.
*
* @param <T> Return type of the workflow function
* @param <E> Type of checked exception thrown by the workflow function, if any
* @param workflowId ID of the workflow to resume; must not be null
* @return A handle to the resumed workflow
* @throws IllegalStateException if called before DBOS is launched
*/
public <T, E extends Exception> @NonNull WorkflowHandle<T, E> resumeWorkflow(
@NonNull String workflowId) {
return resumeWorkflow(workflowId, null);
}
/**
* Resume multiple workflows starting from the step after the last complete step for each
* workflow. This method allows bulk resumption of workflows that were previously interrupted,
* failed, or canceled. Each workflow will continue execution from where it left off, replaying
* any completed steps deterministically.
*
* @param workflowIds a list of workflow IDs to resume; must not be null
* @param queueName optional queue name to enqueue the resumed workflows to; if null, the
* workflows will be resumed in the default execution context
* @return A list of handles to the resumed workflows
* @throws IllegalStateException if called before DBOS is launched
*/
public @NonNull List<WorkflowHandle<Object, Exception>> resumeWorkflows(
@NonNull List<String> workflowIds, @Nullable String queueName) {
return ensureLaunched("resumeWorkflow").resumeWorkflows(workflowIds, queueName);
}
/**
* Resume multiple workflows starting from the step after the last complete step for each workflow
* using the default queue. This method is equivalent to calling {@code
* resumeWorkflows(workflowIds, null)}. Each workflow will continue execution from where it left
* off, replaying any completed steps deterministically.
*
* @param workflowIds a list of workflow IDs to resume; must not be null
* @return A list of handles to the resumed workflows
* @throws IllegalStateException if called before DBOS is launched
*/
public @NonNull List<WorkflowHandle<Object, Exception>> resumeWorkflows(
@NonNull List<String> workflowIds) {
return resumeWorkflows(workflowIds, null);
}
/***
*
* Cancel the workflow. After this function is called, the next step (not the
* current one) will not execute
*
* @param workflowId ID of the workflow to cancel
* @throws IllegalStateException if called before DBOS is launched
*/
public void cancelWorkflow(@NonNull String workflowId) {
cancelWorkflows(List.of(workflowId));
}
/**
* Cancels multiple workflows. After this function is called, the next step (not the current one)
* of each specified workflow will not execute.
*
* @param workflowIds a list of workflow IDs to cancel; must not be null
* @throws IllegalStateException if called before DBOS is launched
*/
public void cancelWorkflows(@NonNull List<String> workflowIds) {
ensureLaunched("cancelWorkflow").cancelWorkflows(workflowIds);
}
/**
* Delete a workflow from the system. This permanently removes the workflow and its associated
* data from the database. Child workflows are preserved by default.
*
* @param workflowId ID of the workflow to delete; must not be null
* @throws IllegalStateException if called before DBOS is launched
*/
public void deleteWorkflow(@NonNull String workflowId) {
deleteWorkflows(List.of(workflowId), false);
}
/**
* Delete a workflow from the system. This permanently removes the workflow and its associated
* data from the database.
*
* @param workflowId ID of the workflow to delete; must not be null
* @param deleteChildren if true, also delete any child workflows; if false, preserve child
* workflows
* @throws IllegalStateException if called before DBOS is launched
*/
public void deleteWorkflow(@NonNull String workflowId, boolean deleteChildren) {
deleteWorkflows(List.of(workflowId), deleteChildren);
}
/**
* Delete multiple workflows from the system. This permanently removes the workflows and their
* associated data from the database. Child workflows are preserved by default.
*
* @param workflowIds a list of workflow IDs to delete; must not be null
* @throws IllegalStateException if called before DBOS is launched
*/
public void deleteWorkflows(@NonNull List<String> workflowIds) {
deleteWorkflows(workflowIds, false);
}
/**
* Delete multiple workflows from the system. This permanently removes the workflows and their
* associated data from the database.
*
* @param workflowIds a list of workflow IDs to delete; must not be null
* @param deleteChildren if true, also delete any child workflows; if false, preserve child
* workflows
* @throws IllegalStateException if called before DBOS is launched
*/
public void deleteWorkflows(@NonNull List<String> workflowIds, boolean deleteChildren) {
ensureLaunched("deleteWorkflows").deleteWorkflows(workflowIds, deleteChildren);
}
/**
* Fork the workflow. Re-execute with another Id from the step provided. Steps prior to the
* provided step are copied over
*
* @param <T> Return type of the workflow function
* @param <E> Checked exception thrown by the workflow function, if any
* @param workflowId Original workflow Id
* @param startStep Start execution from this step. Prior steps copied over
* @param options {@link ForkOptions} containing forkedWorkflowId, applicationVersion, timeout
* @return handle to the workflow
*/
public <T, E extends Exception> @NonNull WorkflowHandle<T, E> forkWorkflow(
@NonNull String workflowId, int startStep, @NonNull ForkOptions options) {
return ensureLaunched("forkWorkflow").forkWorkflow(workflowId, startStep, options);
}
/**
* Fork the workflow. Re-execute with another Id from the step provided. Steps prior to the
* provided step are copied over
*
* @param <T> Return type of the workflow function
* @param <E> Checked exception thrown by the workflow function, if any
* @param workflowId Original workflow Id
* @param startStep Start execution from this step. Prior steps copied over
* @return handle to the workflow
*/
public <T, E extends Exception> @NonNull WorkflowHandle<T, E> forkWorkflow(
@NonNull String workflowId, int startStep) {
return forkWorkflow(workflowId, startStep, new ForkOptions());
}
/**
* List all registered application versions, ordered by timestamp descending.
*
* @return list of {@link VersionInfo} records
*/
public @NonNull List<VersionInfo> listApplicationVersions() {
return ensureLaunched("listApplicationVersions").listApplicationVersions();
}
/**
* Get the most recently promoted application version.
*
* @return the latest {@link VersionInfo}
*/
public @NonNull VersionInfo getLatestApplicationVersion() {
return ensureLaunched("getLatestApplicationVersion").getLatestApplicationVersion();
}
/**
* Promote a version to be the latest application version.
*
* @param versionName the version to promote
*/
public void setLatestApplicationVersion(@NonNull String versionName) {
ensureLaunched("setLatestApplicationVersion").setLatestApplicationVersion(versionName);
}
/**
* Create a cron schedule that periodically invokes a workflow. The scheduleId is generated if
* null.
*
* @param schedule the schedule configuration
*/
public void createSchedule(@NonNull WorkflowSchedule schedule) {
ensureLaunched("createSchedule").createSchedule(schedule);
}
/**
* Get a schedule by name.
*
* @param name schedule name
* @return the schedule, or empty if not found
*/
public @NonNull Optional<WorkflowSchedule> getSchedule(@NonNull String name) {
return ensureLaunched("getSchedule").getSchedule(name);
}
/**
* List schedules with optional filters.
*
* @param status filter by status (e.g. "ACTIVE", "PAUSED"); null means no filter
* @param workflowName filter by workflow name; null means no filter
* @param namePrefix filter by schedule name prefix; null means no filter
* @return matching schedules
*/
public @NonNull List<WorkflowSchedule> listSchedules(
@Nullable List<ScheduleStatus> status,
@Nullable List<String> workflowName,
@Nullable List<String> namePrefix) {
return ensureLaunched("listSchedules").listSchedules(status, workflowName, namePrefix);
}
/**
* Delete a schedule by name. No-op if the schedule does not exist.
*
* @param name schedule name
*/
public void deleteSchedule(@NonNull String name) {
ensureLaunched("deleteSchedule").deleteSchedule(name);
}
/**
* Pause a schedule. A paused schedule does not fire.
*
* @param name schedule name
*/
public void pauseSchedule(@NonNull String name) {
ensureLaunched("pauseSchedule").pauseSchedule(name);
}