-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathDBOSClient.java
More file actions
1242 lines (1143 loc) · 43.8 KB
/
DBOSClient.java
File metadata and controls
1242 lines (1143 loc) · 43.8 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 static dev.dbos.transact.internal.Validation.nullableIsEmpty;
import static dev.dbos.transact.internal.Validation.nullableIsNotPositive;
import dev.dbos.transact.database.Result;
import dev.dbos.transact.database.StreamIterator;
import dev.dbos.transact.database.SystemDatabase;
import dev.dbos.transact.execution.DBOSExecutor;
import dev.dbos.transact.execution.ExecutionOptions;
import dev.dbos.transact.json.DBOSSerializer;
import dev.dbos.transact.json.PortableWorkflowException;
import dev.dbos.transact.json.SerializationUtil;
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.StepInfo;
import dev.dbos.transact.workflow.Timeout;
import dev.dbos.transact.workflow.VersionInfo;
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 java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import javax.sql.DataSource;
import org.jspecify.annotations.NonNull;
import org.jspecify.annotations.Nullable;
/**
* DBOSClient allows external programs to interact with DBOS apps via direct system database access.
* Example interactions: Start/enqueue a workflow, and get the result Get events and send messages
* to the workflow Manage workflows - list, fork, cancel, etc.
*/
public class DBOSClient implements AutoCloseable {
private class WorkflowHandleClient<T, E extends Exception> implements WorkflowHandle<T, E> {
private @NonNull String workflowId;
public WorkflowHandleClient(@NonNull String workflowId) {
this.workflowId = workflowId;
}
@Override
public @NonNull String workflowId() {
return workflowId;
}
@Override
public T getResult() throws E {
var result = systemDatabase.<T>awaitWorkflowResult(workflowId);
return Result.<T, E>process(result);
}
@Override
public @Nullable WorkflowStatus getStatus() {
return systemDatabase.getWorkflowStatus(workflowId);
}
}
private final @NonNull SystemDatabase systemDatabase;
private final @Nullable DBOSSerializer serializer;
/**
* Construct a DBOSClient, by providing system database access credentials
*
* @param url System database JDBC URL
* @param user System database user
* @param password System database credential / password
*/
public DBOSClient(@NonNull String url, @NonNull String user, @NonNull String password) {
this(url, user, password, null, null, true);
}
/**
* Construct a DBOSClient, by providing system database access credentials
*
* @param url System database JDBC URL
* @param user System database user
* @param password System database credential / password
* @param schema Database schema for DBOS tables
*/
public DBOSClient(
@NonNull String url,
@NonNull String user,
@NonNull String password,
@Nullable String schema) {
this(url, user, password, schema, null, true);
}
/**
* Construct a DBOSClient, by providing system database access credentials
*
* @param url System database JDBC URL
* @param user System database user
* @param password System database credential / password
* @param schema Database schema for DBOS tables
* @param serializer Custom serializer for serialization/deserialization
*/
public DBOSClient(
@NonNull String url,
@NonNull String user,
@NonNull String password,
@Nullable String schema,
@Nullable DBOSSerializer serializer) {
this(url, user, password, schema, serializer, true);
}
/**
* Construct a DBOSClient, by providing system database access credentials
*
* @param url System database JDBC URL
* @param user System database user
* @param password System database credential / password
* @param schema Database schema for DBOS tables
* @param serializer Custom serializer for serialization/deserialization
* @param useListenNotify if true, use PostgreSQL LISTEN/NOTIFY for real-time event notifications
*/
public DBOSClient(
@NonNull String url,
@NonNull String user,
@NonNull String password,
@Nullable String schema,
@Nullable DBOSSerializer serializer,
boolean useListenNotify) {
this.serializer = serializer;
systemDatabase = new SystemDatabase(url, user, password, schema, serializer, useListenNotify);
}
/**
* Construct a DBOSClient, by providing a configured data source
*
* @param dataSource System database data source
*/
public DBOSClient(@NonNull DataSource dataSource) {
this(dataSource, null, null);
}
/**
* Construct a DBOSClient, by providing a configured data source
*
* @param dataSource System database data source
* @param schema Database schema for DBOS tables
*/
public DBOSClient(@NonNull DataSource dataSource, @Nullable String schema) {
this(dataSource, schema, null);
}
/**
* Construct a DBOSClient, by providing a configured data source
*
* @param dataSource System database data source
* @param schema Database schema for DBOS tables
* @param serializer Custom serializer for serialization/deserialization
*/
public DBOSClient(
@NonNull DataSource dataSource,
@Nullable String schema,
@Nullable DBOSSerializer serializer) {
this.serializer = serializer;
systemDatabase = new SystemDatabase(dataSource, schema, serializer);
}
/**
* Close this DBOSClient and release any underlying database resources. This method closes the
* system database connection.
*/
@Override
public void close() {
systemDatabase.close();
}
/**
* Options for enqueuing a workflow instance for execution.
*
* <p>This record encapsulates all configuration required to enqueue a workflow, including:
*
* <ul>
* <li>Workflow name and (optionally) class and instance name
* <li>Target queue and queue-related options (priority, partitioning, deduplication, delay)
* <li>Workflow idempotency and versioning
* <li>Timeout and deadline management
* <li>Serialization strategy for workflow arguments
* </ul>
*
* <p>Required fields: {@code workflowName}, {@code queueName}. All other fields are optional and
* can be set using the provided {@code with} methods.
*
* @param workflowName The name of the workflow function to enqueue. Required.
* @param className The Java class containing the workflow function. Optional.
* @param instanceName The instance name for object-based workflows. Optional.
* @param queueName The name of the queue to enqueue the workflow to. Required.
* @param workflowId The idempotency key for the workflow instance. Optional; if not set, a random
* UUID will be generated.
* @param appVersion The application version to target for execution. Optional.
* @param timeout The maximum duration the workflow may run before being canceled. Optional.
* @param deadline The absolute time by which the workflow must start or complete. Optional.
* @param deduplicationId An optional ID to prevent duplicate enqueued workflows. Optional.
* @param priority The priority to assign if the queue supports prioritization. Optional.
* @param queuePartitionKey The partition key for distributing workflows across queue partitions.
* Optional.
* @param delay The delay before the workflow starts executing. Optional.
* @param serialization The serialization strategy for workflow arguments. Optional.
*/
public record EnqueueOptions(
@NonNull String workflowName,
@Nullable String className,
@Nullable String instanceName,
@NonNull String queueName,
@Nullable String workflowId,
@Nullable String appVersion,
@Nullable Duration timeout,
@Nullable Instant deadline,
@Nullable String deduplicationId,
@Nullable Integer priority,
@Nullable String queuePartitionKey,
@Nullable Duration delay,
@Nullable SerializationStrategy serialization) {
public EnqueueOptions {
if (nullableIsEmpty(workflowName)) {
throw new IllegalArgumentException("workflowName must not be empty");
}
if (nullableIsEmpty(className)) {
throw new IllegalArgumentException("className must not be empty");
}
if (nullableIsEmpty(instanceName)) {
throw new IllegalArgumentException("instanceName must not be empty");
}
if (nullableIsEmpty(queueName)) {
throw new IllegalArgumentException("queueName must not be empty");
}
if (nullableIsEmpty(workflowId)) {
throw new IllegalArgumentException("workflowId must not be empty");
}
if (nullableIsEmpty(appVersion)) {
throw new IllegalArgumentException("appVersion must not be empty");
}
if (nullableIsNotPositive(timeout)) {
throw new IllegalArgumentException("timeout must be positive, non-zero duration");
}
if (nullableIsEmpty(deduplicationId)) {
throw new IllegalArgumentException("deduplicationId must not be empty");
}
if (nullableIsEmpty(queuePartitionKey)) {
throw new IllegalArgumentException("queuePartitionKey must not be empty");
}
if (nullableIsNotPositive(delay)) {
throw new IllegalArgumentException("delay must be positive, non-zero duration");
}
}
/** Construct `EnqueueOptions` with a minimum set of required options */
public EnqueueOptions(@NonNull String workflowName, @NonNull String queueName) {
this(
workflowName,
null,
null,
queueName,
null,
null,
null,
null,
null,
null,
null,
null,
null);
}
public EnqueueOptions(
@NonNull String workflowName, @Nullable String className, @NonNull String queueName) {
this(
workflowName,
className,
null,
queueName,
null,
null,
null,
null,
null,
null,
null,
null,
null);
}
/**
* Specify the Java classname for the class containing the workflow to enqueue
*
* @param className Class containing the workflow to enqueue
* @return New `EnqueueOptions` with the class name set
*/
public @NonNull EnqueueOptions withClassName(@Nullable String className) {
return new EnqueueOptions(
this.workflowName,
className,
this.instanceName,
this.queueName,
this.workflowId,
this.appVersion,
this.timeout,
this.deadline,
this.deduplicationId,
this.priority,
this.queuePartitionKey,
this.delay,
this.serialization);
}
/**
* Specify the workflow ID for the workflow to be enqueued. This is an idempotency key for
* running the workflow.
*
* @param workflowId Workflow idempotency ID to use
* @return New `EnqueueOptions` with the workflow ID set
*/
public @NonNull EnqueueOptions withWorkflowId(@Nullable String workflowId) {
return new EnqueueOptions(
this.workflowName,
this.className,
this.instanceName,
this.queueName,
workflowId,
this.appVersion,
this.timeout,
this.deadline,
this.deduplicationId,
this.priority,
this.queuePartitionKey,
this.delay,
this.serialization);
}
/**
* Specify the app version for the workflow to be enqueued. The workflow will be executed by an
* executor with this app version. If not specified, the current app version will be used.
*
* @param appVersion Application version to use for executing the workflow
* @return New `EnqueueOptions` with the app version set
*/
public @NonNull EnqueueOptions withAppVersion(@Nullable String appVersion) {
return new EnqueueOptions(
this.workflowName,
this.className,
this.instanceName,
this.queueName,
this.workflowId,
appVersion,
this.timeout,
this.deadline,
this.deduplicationId,
this.priority,
this.queuePartitionKey,
this.delay,
this.serialization);
}
/**
* Specify a timeout for the workflow to be enqueued. Timeout begins once the workflow is
* running; if it exceeds this it will be canceled.
*
* @param timeout Duration of time, from start, before the workflow is canceled.
* @return New `EnqueueOptions` with the timeout set
*/
public @NonNull EnqueueOptions withTimeout(@Nullable Duration timeout) {
return new EnqueueOptions(
this.workflowName,
this.className,
this.instanceName,
this.queueName,
this.workflowId,
this.appVersion,
timeout,
this.deadline,
this.deduplicationId,
this.priority,
this.queuePartitionKey,
this.delay,
this.serialization);
}
/**
* Specify a deadline for the workflow. This is an absolute time, regardless of when the
* workflow starts.
*
* @param deadline Instant after which the workflow will be canceled.
* @return New `EnqueueOptions` with the deadline set
*/
public @NonNull EnqueueOptions withDeadline(@Nullable Instant deadline) {
return new EnqueueOptions(
this.workflowName,
this.className,
this.instanceName,
this.queueName,
this.workflowId,
this.appVersion,
this.timeout,
deadline,
this.deduplicationId,
this.priority,
this.queuePartitionKey,
this.delay,
this.serialization);
}
/**
* Specify a queue deduplication ID for the workflow to be enqueued. Queue requests with the
* same deduplication ID will be rejected.
*
* @param deduplicationId Queue deduplication ID
* @return New `EnqueueOptions` with the deduplication ID set
*/
public @NonNull EnqueueOptions withDeduplicationId(@Nullable String deduplicationId) {
return new EnqueueOptions(
this.workflowName,
this.className,
this.instanceName,
this.queueName,
this.workflowId,
this.appVersion,
this.timeout,
this.deadline,
deduplicationId,
this.priority,
this.queuePartitionKey,
this.delay,
this.serialization);
}
/**
* Specify an object instance name to execute the workflow. If workflow objects are named, this
* must be specified to direct processing to the correct instance.
*
* @param instName Instance name registered within `DBOS.registerWorkflows`
* @return New `EnqueueOptions` with the target instance name set
*/
public @NonNull EnqueueOptions withInstanceName(@Nullable String instName) {
return new EnqueueOptions(
this.workflowName,
this.className,
instName,
this.queueName,
this.workflowId,
this.appVersion,
this.timeout,
this.deadline,
this.deduplicationId,
this.priority,
this.queuePartitionKey,
this.delay,
this.serialization);
}
/**
* Specify priority. Priority must be enabled on the queue for this to be effective.
*
* @param priority Queue priority; if `null`, priority '0' will be used.
* @return New `EnqueueOptions` with the priority set
*/
public @NonNull EnqueueOptions withPriority(@Nullable Integer priority) {
return new EnqueueOptions(
this.workflowName,
this.className,
this.instanceName,
this.queueName,
this.workflowId,
this.appVersion,
this.timeout,
this.deadline,
this.deduplicationId,
priority,
this.queuePartitionKey,
this.delay,
this.serialization);
}
/**
* Creates a new EnqueueOptions instance with the specified queue partition key. The partition
* key is used to determine which partition of the queue the workflow should be enqueued to,
* allowing for better load distribution and ordering guarantees.
*
* @param partitionKey the partition key to use for queue partitioning, can be null
* @return a new EnqueueOptions instance with the specified partition key
*/
public @NonNull EnqueueOptions withQueuePartitionKey(@Nullable String partitionKey) {
return new EnqueueOptions(
this.workflowName,
this.className,
this.instanceName,
this.queueName,
this.workflowId,
this.appVersion,
this.timeout,
this.deadline,
this.deduplicationId,
this.priority,
partitionKey,
this.delay,
this.serialization);
}
/**
* Specify a delay before the workflow starts executing. The workflow will remain in the queue
* until the delay has elapsed.
*
* @param delay Duration to wait before the workflow begins execution.
* @return New `EnqueueOptions` with the delay set
*/
public @NonNull EnqueueOptions withDelay(@Nullable Duration delay) {
return new EnqueueOptions(
this.workflowName,
this.className,
this.instanceName,
this.queueName,
this.workflowId,
this.appVersion,
this.timeout,
this.deadline,
this.deduplicationId,
this.priority,
this.queuePartitionKey,
delay,
this.serialization);
}
/**
* Specify the serialization strategy for the workflow arguments.
*
* @param serialization The serialization strategy ({@link SerializationStrategy#PORTABLE} for
* cross-language compatibility, {@link SerializationStrategy#NATIVE} for Java-specific, or
* {@link SerializationStrategy#DEFAULT} for the default behavior)
* @return New `EnqueueOptions` with the serialization strategy set
*/
public @NonNull EnqueueOptions withSerialization(
@Nullable SerializationStrategy serialization) {
return new EnqueueOptions(
this.workflowName,
this.className,
this.instanceName,
this.queueName,
this.workflowId,
this.appVersion,
this.timeout,
this.deadline,
this.deduplicationId,
this.priority,
this.queuePartitionKey,
this.delay,
serialization);
}
}
/**
* Enqueue a workflow with explicit serialization format and support for both positional and named
* arguments.
*
* @param <T> Return type of workflow function
* @param <E> Exception thrown by workflow function
* @param options {@link EnqueueOptions} for configuring the workflow enqueue
* @param positionalArgs Positional arguments to pass to the workflow function
* @param namedArgs Named arguments to pass to the workflow function (e.g., for Python kwargs)
* @param serializationFormat Serialization format string to use (null for default)
* @return WorkflowHandle for retrieving workflow ID, status, and results
*/
public <T, E extends Exception> @NonNull WorkflowHandle<T, E> enqueueWorkflow(
@NonNull EnqueueOptions options,
@Nullable Object[] positionalArgs,
@Nullable Map<String, Object> namedArgs,
@Nullable String serializationFormat) {
Objects.requireNonNull(options, "options must not be null");
Objects.requireNonNull(options.workflowName, "EnqueueOptions workflowName must not be null");
Objects.requireNonNull(options.queueName, "EnqueueOptions queueName must not be null");
if (options.timeout != null && options.deadline != null) {
throw new IllegalArgumentException("Can't set timeout and deadline EnqueueOptions");
}
var workflowId =
Objects.requireNonNullElseGet(options.workflowId(), () -> UUID.randomUUID().toString());
DBOSExecutor.enqueueWorkflow(
options.workflowName(),
options.className(),
options.instanceName(),
null,
positionalArgs,
namedArgs,
new ExecutionOptions(
workflowId,
Timeout.of(options.timeout()),
options.deadline,
options.queueName(),
options.deduplicationId,
options.priority,
options.queuePartitionKey,
options.delay,
options.appVersion,
false,
false,
serializationFormat),
null,
null,
null,
null,
systemDatabase,
this.serializer);
return new WorkflowHandleClient<>(workflowId);
}
/**
* Enqueue a workflow.
*
* @param <T> Return type of workflow function
* @param <E> Exception thrown by workflow function
* @param options `DBOSClient.EnqueueOptions` for enqueuing the workflow
* @param args Arguments to pass to the workflow function
* @return WorkflowHandle for retrieving workflow ID, status, and results
*/
public <T, E extends Exception> @NonNull WorkflowHandle<T, E> enqueueWorkflow(
@NonNull EnqueueOptions options, @Nullable Object[] args) {
var serializationFormat =
options.serialization() != null ? options.serialization().formatName() : null;
return enqueueWorkflow(options, args, null, serializationFormat);
}
/**
* Enqueue a workflow using portable JSON serialization. This method is intended for
* cross-language workflow initiation where the workflow function definition may not be available
* in Java.
*
* @param <T> Return type of workflow function
* @param options `DBOSClient.EnqueueOptions` for enqueuing the workflow
* @param positionalArgs Positional arguments to pass to the workflow function
* @param namedArgs Optional named arguments (for workflows that support them, e.g., Python
* kwargs)
* @return WorkflowHandle for retrieving workflow ID, status, and results
*/
public <T> @NonNull WorkflowHandle<T, PortableWorkflowException> enqueuePortableWorkflow(
@NonNull EnqueueOptions options,
@Nullable Object[] positionalArgs,
@Nullable Map<String, Object> namedArgs) {
return enqueueWorkflow(options, positionalArgs, namedArgs, SerializationUtil.PORTABLE);
}
/** Options for sending a message. */
public record SendOptions(@Nullable SerializationStrategy serialization, boolean sendToForks) {
/**
* Create SendOptions with default serialization strategy. Uses the system's default
* serialization format for message encoding.
*
* @return SendOptions configured with default serialization
*/
public static SendOptions defaults() {
return new SendOptions(SerializationStrategy.DEFAULT, false);
}
/**
* Create SendOptions with portable JSON serialization strategy. Uses portable JSON format
* suitable for cross-language workflow communication.
*
* @return SendOptions configured with portable JSON serialization
*/
public static SendOptions portable() {
return new SendOptions(SerializationStrategy.PORTABLE, false);
}
/**
* Create a new SendOptions with the sendToForks flag set.
*
* @param v if true, deliver the message to any forked copies of the destination workflow
* @return new SendOptions with the sendToForks flag updated
*/
public SendOptions withSendToForks(boolean v) {
return new SendOptions(serialization, v);
}
}
/**
* Send a message to a workflow
*
* @param destinationId workflowId of the workflow to receive the message
* @param message Message contents
* @param topic Topic for the message
* @param idempotencyKey If specified, use the value to ensure exactly-once send semantics
*/
public void send(
@NonNull String destinationId,
@NonNull Object message,
@NonNull String topic,
@Nullable String idempotencyKey) {
send(destinationId, message, topic, idempotencyKey, null);
}
/**
* Send a message to a workflow with serialization options
*
* @param destinationId workflowId of the workflow to receive the message
* @param message Message contents
* @param topic Topic for the message
* @param idempotencyKey If specified, use the value to ensure exactly-once send semantics
* @param options Optional send options including serialization type
*/
public void send(
@NonNull String destinationId,
@NonNull Object message,
@NonNull String topic,
@Nullable String idempotencyKey,
@Nullable SendOptions options) {
String serializationFormat =
(options != null && options.serialization() != null)
? options.serialization().formatName()
: null;
boolean sendToForks = options != null && options.sendToForks();
systemDatabase.sendBulk(
List.of(new SendMessage(destinationId, message, topic, idempotencyKey)),
null,
-1,
"DBOS.send",
sendToForks,
serializationFormat);
}
/**
* Send multiple messages to workflows using default options
*
* @param messages list of messages to send
*/
public void sendBulk(@NonNull List<SendMessage> messages) {
sendBulk(messages, null);
}
/**
* Send multiple messages to workflows with serialization options
*
* @param messages list of messages to send
* @param options optional send options including serialization type and fork delivery; null for
* defaults
*/
public void sendBulk(@NonNull List<SendMessage> messages, @Nullable SendOptions options) {
String serializationFormat =
(options != null && options.serialization() != null)
? options.serialization().formatName()
: null;
boolean sendToForks = options != null && options.sendToForks();
systemDatabase.sendBulk(messages, null, -1, "DBOS.sendBulk", sendToForks, serializationFormat);
}
/**
* Get event from a workflow
*
* @param targetId ID of the workflow setting the event
* @param key Key for the event
* @param timeout Maximum time duration to wait before timing out
* @return Optional containing the workflow event value if available, or empty if timeout occurs
* or no event found
*/
public @NonNull Optional<Object> getEvent(
@NonNull String targetId, @NonNull String key, @NonNull Duration timeout) {
return Optional.ofNullable(systemDatabase.getEvent(targetId, key, timeout, null));
}
/**
* Read values from a stream as an iterator. This function reads values from a stream identified
* by the workflow_id and key, returning an iterator that yields each value in order until the
* stream is closed or the workflow terminates.
*
* @param workflowId The workflow instance ID that owns the stream
* @param key The stream key / name within the workflow
* @return Iterator that yields each value in the stream
*/
public @NonNull Iterator<Object> readStream(@NonNull String workflowId, @NonNull String key) {
return new StreamIterator(workflowId, key, systemDatabase);
}
/**
* Create a handle for a workflow. This call does not ensure that the workflow exists; use the
* returned handle's `getStatus()`.
*
* @param <T> Type of the workflow's return value
* @param <E> Type of any checked exception thrown by the workflow
* @param workflowId ID of the workflow to retrieve
* @return A `WorkflowHandle` for the specified worflow ID
*/
public <T, E extends Exception> @NonNull WorkflowHandle<T, E> retrieveWorkflow(
@NonNull String workflowId) {
return new WorkflowHandleClient<>(workflowId);
}
/**
* Cancel a worflow
*
* @param workflowId ID of the workflow to cancel
*/
public void cancelWorkflow(@NonNull String workflowId) {
systemDatabase.cancelWorkflows(List.of(workflowId));
}
/**
* Cancel 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
*/
public void cancelWorkflows(@NonNull List<String> workflowIds) {
systemDatabase.cancelWorkflows(workflowIds);
}
/**
* 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> Type of the workflow's return value
* @param <E> Type of any checked exception thrown by the workflow
* @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 WorkflowHandle for the resumed workflow
*/
public <T, E extends Exception> @NonNull WorkflowHandle<T, E> resumeWorkflow(
@NonNull String workflowId, @Nullable String queueName) {
systemDatabase.resumeWorkflows(List.of(workflowId), queueName);
return retrieveWorkflow(workflowId);
}
/**
* 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> Type of the workflow's return value
* @param <E> Type of any checked exception thrown by the workflow
* @param workflowId ID of the workflow to resume; must not be null
* @return WorkflowHandle for the resumed workflow
*/
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
* 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
*/
public @NonNull List<WorkflowHandle<Object, Exception>> resumeWorkflows(
@NonNull List<String> workflowIds) {
return resumeWorkflows(workflowIds, 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
*/
public @NonNull List<WorkflowHandle<Object, Exception>> resumeWorkflows(
@NonNull List<String> workflowIds, @Nullable String queueName) {
systemDatabase.resumeWorkflows(workflowIds, queueName);
return workflowIds.stream().map(this::retrieveWorkflow).toList();
}
/**
* 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
*/
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
*/
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
*/
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
*/
public void deleteWorkflows(@NonNull List<String> workflowIds, boolean deleteChildren) {
systemDatabase.deleteWorkflows(workflowIds, deleteChildren);
}
/**
* Fork a workflow, providing a handle to the new workflow
*
* @param <T> Type of the workflow's return value
* @param <E> Type of any checked exception thrown by the workflow
* @param originalWorkflowId ID of the workflow to fork
* @param startStep Step number for starting the new fork of the workflow; if zero start from the
* beginning
* @param options Options for forking;
* @return `WorkflowHandle` for the new workflow
*/
public <T, E extends Exception> @NonNull WorkflowHandle<T, E> forkWorkflow(
@NonNull String originalWorkflowId, int startStep, @NonNull ForkOptions options) {
var forkedWorkflowId = systemDatabase.forkWorkflow(originalWorkflowId, startStep, options);
return retrieveWorkflow(forkedWorkflowId);
}
/**
* Get the status of a workflow
*
* @param workflowId ID of the workflow to query for status
* @return WorkflowStatus of the workflow, or empty if the workflow does not exist
*/
public @NonNull Optional<WorkflowStatus> getWorkflowStatus(@NonNull String workflowId) {
return Optional.ofNullable(systemDatabase.getWorkflowStatus(workflowId));
}
/**
* List workflows matching the supplied input filter criteria
*
* @param input Filter criteria to use for listing workflows. Pass null to list all workflows.
* @return list of workflows matching the `ListWorkflowsInput` criteria
*/
public @NonNull List<WorkflowStatus> listWorkflows(@Nullable ListWorkflowsInput input) {
return systemDatabase.listWorkflows(input);
}
/**
* List the steps executed by a workflow
*
* @param workflowId ID of the workflow to list
* @return List of steps executed by the workflow
*/
public @NonNull List<StepInfo> listWorkflowSteps(@NonNull String workflowId) {
return listWorkflowSteps(workflowId, null, null);
}
/**
* List the steps executed by a workflow with optional pagination
*
* @param workflowId ID of the workflow to list
* @param limit Maximum number of steps to return
* @param offset Number of steps to skip before returning
* @return List of steps executed by the workflow
*/