-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathClient.java
More file actions
867 lines (794 loc) · 30.4 KB
/
Client.java
File metadata and controls
867 lines (794 loc) · 30.4 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
// Copyright (c) 2023 - Restate Software, Inc., Restate GmbH
//
// This file is part of the Restate Java SDK,
// which is released under the MIT license.
//
// You can find a copy of the license in file LICENSE in the root
// directory of this repository or package, or at
// https://github.com/restatedev/sdk-java/blob/main/LICENSE
package dev.restate.client;
import dev.restate.common.Output;
import dev.restate.common.Request;
import dev.restate.common.Target;
import dev.restate.common.WorkflowRequest;
import dev.restate.common.reflections.MethodInfo;
import dev.restate.common.reflections.ProxySupport;
import dev.restate.common.reflections.ReflectionUtils;
import dev.restate.sdk.annotation.Service;
import dev.restate.sdk.annotation.VirtualObject;
import dev.restate.sdk.annotation.Workflow;
import dev.restate.serde.SerdeFactory;
import dev.restate.serde.TypeTag;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import org.jspecify.annotations.NonNull;
import org.jspecify.annotations.Nullable;
public interface Client {
/**
* Future version of {@link #call(Request)}
*
* @see #call(Request)
*/
<Req, Res> CompletableFuture<Response<Res>> callAsync(Request<Req, Res> request);
/** Call a service and wait for the response. */
default <Req, Res> Response<Res> call(Request<Req, Res> request) throws IngressException {
try {
return callAsync(request).join();
} catch (CompletionException e) {
if (e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
}
throw new RuntimeException(e.getCause());
}
}
/**
* Future version of {@link #send(Request)}
*
* @see #send(Request)
*/
default <Req, Res> CompletableFuture<SendResponse<Res>> sendAsync(Request<Req, Res> request) {
return sendAsync(request, null);
}
/** Send a request to a service without waiting for the response. */
default <Req, Res> SendResponse<Res> send(Request<Req, Res> request) throws IngressException {
return send(request, null);
}
/**
* Future version of {@link #send(Request, Duration)}
*
* @see #send(Request, Duration)
*/
<Req, Res> CompletableFuture<SendResponse<Res>> sendAsync(
Request<Req, Res> request, @Nullable Duration delay);
/**
* Send a request to a service without waiting for the response, optionally providing an execution
* delay to wait for.
*/
default <Req, Res> SendResponse<Res> send(Request<Req, Res> request, @Nullable Duration delay)
throws IngressException {
try {
return sendAsync(request, delay).join();
} catch (CompletionException e) {
if (e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
}
throw new RuntimeException(e.getCause());
}
}
/**
* Future version of {@link #submit(WorkflowRequest)}
*
* @see #submit(WorkflowRequest)
*/
default <Req, Res> CompletableFuture<SendResponse<Res>> submitAsync(
WorkflowRequest<Req, Res> request) {
return submitAsync(request, null);
}
/** Submit a workflow. */
default <Req, Res> SendResponse<Res> submit(WorkflowRequest<Req, Res> request)
throws IngressException {
return submit(request, null);
}
/**
* Future version of {@link #submit(WorkflowRequest, Duration)}
*
* @see #submit(WorkflowRequest, Duration)
*/
default <Req, Res> CompletableFuture<SendResponse<Res>> submitAsync(
WorkflowRequest<Req, Res> request, @Nullable Duration delay) {
return sendAsync(request, delay);
}
/** Submit a workflow, optionally providing an execution delay to wait for. */
default <Req, Res> SendResponse<Res> submit(
WorkflowRequest<Req, Res> request, @Nullable Duration delay) throws IngressException {
try {
return submitAsync(request, delay).join();
} catch (CompletionException e) {
if (e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
}
throw new RuntimeException(e.getCause());
}
}
/**
* Create a new {@link AwakeableHandle} for the provided identifier. You can use it to {@link
* AwakeableHandle#resolve(TypeTag, Object)} or {@link AwakeableHandle#reject(String)} an
* Awakeable from the ingress.
*/
AwakeableHandle awakeableHandle(String id);
/**
* This class represents a handle to an Awakeable. It can be used to complete awakeables from the
* ingress
*/
interface AwakeableHandle {
/** Same as {@link #resolve(TypeTag, Object)} but async with options. */
<T> CompletableFuture<Response<Void>> resolveAsync(
TypeTag<T> serde, @NonNull T payload, RequestOptions options);
/** Same as {@link #resolve(TypeTag, Object)} but async. */
default <T> CompletableFuture<Response<Void>> resolveAsync(
TypeTag<T> serde, @NonNull T payload) {
return resolveAsync(serde, payload, RequestOptions.DEFAULT);
}
/** Same as {@link #resolve(TypeTag, Object)} with options. */
default <T> Response<Void> resolve(
TypeTag<T> serde, @NonNull T payload, RequestOptions options) {
try {
return resolveAsync(serde, payload, options).join();
} catch (CompletionException e) {
if (e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
}
throw new RuntimeException(e.getCause());
}
}
/**
* Complete with success the Awakeable.
*
* @param clazz used to serialize the Awakeable result payload.
* @param payload the result payload. MUST NOT be null.
*/
default <T> Response<Void> resolve(Class<T> clazz, @NonNull T payload) {
return this.resolve(TypeTag.of(clazz), payload, RequestOptions.DEFAULT);
}
/** Same as {@link #resolve(Class, Object)} but async with options. */
default <T> CompletableFuture<Response<Void>> resolveAsync(
Class<T> clazz, @NonNull T payload, RequestOptions options) {
return this.resolveAsync(TypeTag.of(clazz), payload, options);
}
/** Same as {@link #resolve(TypeTag, Object)} but async. */
default <T> CompletableFuture<Response<Void>> resolveAsync(Class<T> clazz, @NonNull T payload) {
return resolveAsync(TypeTag.of(clazz), payload, RequestOptions.DEFAULT);
}
/** Same as {@link #resolve(TypeTag, Object)} with options. */
default <T> Response<Void> resolve(Class<T> clazz, @NonNull T payload, RequestOptions options) {
return resolve(TypeTag.of(clazz), payload, options);
}
/**
* Complete with success the Awakeable.
*
* @param serde used to serialize the Awakeable result payload.
* @param payload the result payload. MUST NOT be null.
*/
default <T> Response<Void> resolve(TypeTag<T> serde, @NonNull T payload) {
return this.resolve(serde, payload, RequestOptions.DEFAULT);
}
/** Same as {@link #reject(String)} but async with options. */
CompletableFuture<Response<Void>> rejectAsync(String reason, RequestOptions options);
/** Same as {@link #reject(String)} but async. */
default CompletableFuture<Response<Void>> rejectAsync(String reason) {
return rejectAsync(reason, RequestOptions.DEFAULT);
}
/** Same as {@link #reject(String)} with options. */
default Response<Void> reject(String reason, RequestOptions options) {
try {
return rejectAsync(reason, options).join();
} catch (CompletionException e) {
if (e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
}
throw new RuntimeException(e.getCause());
}
}
/**
* Complete with failure the Awakeable.
*
* @param reason the rejection reason. MUST NOT be null.
*/
default Response<Void> reject(String reason) {
return this.reject(reason, RequestOptions.DEFAULT);
}
}
/**
* Create a new {@link InvocationHandle} for the provided invocation identifier.
*
* @param invocationId the invocation identifier
* @param resTypeTag type tag used to deserialize the invocation result
* @return the invocation handle
*/
<Res> InvocationHandle<Res> invocationHandle(String invocationId, TypeTag<Res> resTypeTag);
/**
* Create a new {@link InvocationHandle} for the provided invocation identifier.
*
* @param invocationId the invocation identifier
* @param clazz used to deserialize the invocation result
* @return the invocation handle
*/
default <Res> InvocationHandle<Res> invocationHandle(String invocationId, Class<Res> clazz) {
return invocationHandle(invocationId, TypeTag.of(clazz));
}
interface InvocationHandle<Res> {
/**
* @return the invocation identifier
*/
String invocationId();
/**
* Future version of {@link #attach()}, with options.
*
* @see #attach()
*/
CompletableFuture<Response<Res>> attachAsync(RequestOptions options);
/**
* Future version of {@link #attach()}
*
* @see #attach()
*/
default CompletableFuture<Response<Res>> attachAsync() {
return attachAsync(RequestOptions.DEFAULT);
}
/**
* Like {@link #attach()}, with request options.
*
* @see #attach()
*/
default Response<Res> attach(RequestOptions options) throws IngressException {
try {
return attachAsync(options).join();
} catch (CompletionException e) {
if (e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
}
throw new RuntimeException(e.getCause());
}
}
/** Attach to a running invocation, waiting for its output. */
default Response<Res> attach() throws IngressException {
return attach(RequestOptions.DEFAULT);
}
/**
* Future version of {@link #getOutput()}, with options.
*
* @see #getOutput()
*/
CompletableFuture<Response<Output<Res>>> getOutputAsync(RequestOptions options);
/**
* Future version of {@link #getOutput()}
*
* @see #getOutput()
*/
default CompletableFuture<Response<Output<Res>>> getOutputAsync() {
return getOutputAsync(RequestOptions.DEFAULT);
}
/**
* Like {@link #getOutput()}, with request options.
*
* @see #getOutput()
*/
default Response<Output<Res>> getOutput(RequestOptions options) throws IngressException {
try {
return getOutputAsync(options).join();
} catch (CompletionException e) {
if (e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
}
throw new RuntimeException(e.getCause());
}
}
/** Get the output of an invocation. If running, {@link Output#isReady()} will be false. */
default Response<Output<Res>> getOutput() throws IngressException {
return getOutput(RequestOptions.DEFAULT);
}
}
/**
* Create a new {@link IdempotentInvocationHandle} for the provided target and idempotency key.
*
* @param target the target service/method
* @param idempotencyKey the idempotency key
* @param resTypeTag type tag used to deserialize the invocation result
* @return the idempotent invocation handle
*/
<Res> IdempotentInvocationHandle<Res> idempotentInvocationHandle(
Target target, String idempotencyKey, TypeTag<Res> resTypeTag);
/**
* Create a new {@link IdempotentInvocationHandle} for the provided target and idempotency key.
*
* @param target the target service/method
* @param idempotencyKey the idempotency key
* @param clazz used to deserialize the invocation result
* @return the idempotent invocation handle
*/
default <Res> IdempotentInvocationHandle<Res> idempotentInvocationHandle(
Target target, String idempotencyKey, Class<Res> clazz) {
return idempotentInvocationHandle(target, idempotencyKey, TypeTag.of(clazz));
}
interface IdempotentInvocationHandle<Res> {
/**
* Future version of {@link #attach()}, with options.
*
* @see #attach()
*/
CompletableFuture<Response<Res>> attachAsync(RequestOptions options);
/**
* Future version of {@link #attach()}
*
* @see #attach()
*/
default CompletableFuture<Response<Res>> attachAsync() {
return attachAsync(RequestOptions.DEFAULT);
}
/**
* Like {@link #attach()}, with request options.
*
* @see #attach()
*/
default Response<Res> attach(RequestOptions options) throws IngressException {
try {
return attachAsync(options).join();
} catch (CompletionException e) {
if (e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
}
throw new RuntimeException(e.getCause());
}
}
/** Attach to a running idempotent invocation, waiting for its output. */
default Response<Res> attach() throws IngressException {
return attach(RequestOptions.DEFAULT);
}
/**
* Future version of {@link #getOutput()}, with options.
*
* @see #getOutput()
*/
CompletableFuture<Response<Output<Res>>> getOutputAsync(RequestOptions options);
/**
* Future version of {@link #getOutput()}
*
* @see #getOutput()
*/
default CompletableFuture<Response<Output<Res>>> getOutputAsync() {
return getOutputAsync(RequestOptions.DEFAULT);
}
/**
* Like {@link #getOutput()}, with request options.
*
* @see #getOutput()
*/
default Response<Output<Res>> getOutput(RequestOptions options) throws IngressException {
try {
return getOutputAsync(options).join();
} catch (CompletionException e) {
if (e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
}
throw new RuntimeException(e.getCause());
}
}
/**
* Get the output of an idempotent invocation. If running, {@link Output#isReady()} will be
* false.
*/
default Response<Output<Res>> getOutput() throws IngressException {
return getOutput(RequestOptions.DEFAULT);
}
}
/**
* Create a new {@link WorkflowHandle} for the provided workflow name and identifier.
*
* @param workflowName the workflow name
* @param workflowId the workflow identifier
* @param resTypeTag type tag used to deserialize the invocation result
* @return the workflow handle
*/
<Res> WorkflowHandle<Res> workflowHandle(
String workflowName, String workflowId, TypeTag<Res> resTypeTag);
/**
* Create a new {@link WorkflowHandle} for the provided workflow name and identifier.
*
* @param workflowName the workflow name
* @param workflowId the workflow identifier
* @param clazz used to deserialize the workflow result
* @return the workflow handle
*/
default <Res> WorkflowHandle<Res> workflowHandle(
String workflowName, String workflowId, Class<Res> clazz) {
return workflowHandle(workflowName, workflowId, TypeTag.of(clazz));
}
interface WorkflowHandle<Res> {
/**
* Future version of {@link #attach()}, with options.
*
* @see #attach()
*/
CompletableFuture<Response<Res>> attachAsync(RequestOptions options);
/**
* Future version of {@link #attach()}
*
* @see #attach()
*/
default CompletableFuture<Response<Res>> attachAsync() {
return attachAsync(RequestOptions.DEFAULT);
}
/**
* Like {@link #attach()}, with request options.
*
* @see #attach()
*/
default Response<Res> attach(RequestOptions options) throws IngressException {
try {
return attachAsync(options).join();
} catch (CompletionException e) {
if (e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
}
throw new RuntimeException(e.getCause());
}
}
/** Attach to a running workflow, waiting for its output. */
default Response<Res> attach() throws IngressException {
return attach(RequestOptions.DEFAULT);
}
/**
* Future version of {@link #getOutput()}, with options.
*
* @see #getOutput()
*/
CompletableFuture<Response<Output<Res>>> getOutputAsync(RequestOptions options);
/**
* Future version of {@link #getOutput()}
*
* @see #getOutput()
*/
default CompletableFuture<Response<Output<Res>>> getOutputAsync() {
return getOutputAsync(RequestOptions.DEFAULT);
}
/**
* Like {@link #getOutput()}, with request options.
*
* @see #getOutput()
*/
default Response<Output<Res>> getOutput(RequestOptions options) throws IngressException {
try {
return getOutputAsync(options).join();
} catch (CompletionException e) {
if (e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
}
throw new RuntimeException(e.getCause());
}
}
/** Get the output of a workflow. If running, {@link Output#isReady()} will be false. */
default Response<Output<Res>> getOutput() throws IngressException {
return getOutput(RequestOptions.DEFAULT);
}
}
/**
* <b>EXPERIMENTAL API:</b> Scope client communication, to send requests to services, virtual
* objects and workflows within a scope. Requires Restate >= 1.7.
*
* <pre>{@code
* Client client = Client.connect("http://localhost:8080");
*
* var greeterProxy = client.scope("my-scope").service(Greeter.class);
* GreetingResponse output = greeterProxy.greet(new Greeting("Alice"));
* }</pre>
*
* @param scopeKey the scope key to prepend to all invocation targets
* @return a scoped client
*/
@org.jetbrains.annotations.ApiStatus.Experimental
default ScopedClient scope(String scopeKey) {
return new ScopedClient(this, scopeKey);
}
/**
* <b>EXPERIMENTAL API:</b> Simple API to invoke a Restate service from the ingress.
*
* <p>Create a proxy client that allows calling service methods directly and synchronously,
* returning just the output (not wrapped in {@link Response}). This is the recommended approach
* for straightforward request-response interactions.
*
* <pre>{@code
* Client client = Client.connect("http://localhost:8080");
*
* var greeterProxy = client.service(Greeter.class);
* GreetingResponse output = greeterProxy.greet(new Greeting("Alice"));
* }</pre>
*
* <p>For advanced use cases requiring asynchronous request handling, access to {@link Response}
* metadata, or invocation options (such as idempotency keys), use {@link #serviceHandle(Class)}
* instead.
*
* @param clazz the service class annotated with {@link Service}
* @return a proxy client to invoke the service
*/
@org.jetbrains.annotations.ApiStatus.Experimental
default <SVC> SVC service(Class<SVC> clazz) {
ReflectionUtils.mustHaveServiceAnnotation(clazz);
if (ReflectionUtils.isKotlinClass(clazz)) {
throw new IllegalArgumentException("Using Kotlin classes with Java's API is not supported");
}
var serviceName = ReflectionUtils.extractServiceName(clazz);
return ProxySupport.createProxy(
clazz,
invocation -> {
var methodInfo = MethodInfo.fromMethod(invocation.getMethod());
//noinspection unchecked
return this.call(
Request.of(
Target.virtualObject(serviceName, null, methodInfo.getHandlerName()),
(TypeTag<? super Object>) methodInfo.getInputType(),
(TypeTag<? super Object>) methodInfo.getOutputType(),
invocation.getArguments().length == 0 ? null : invocation.getArguments()[0]))
.response();
});
}
/**
* <b>EXPERIMENTAL API:</b> Advanced API to invoke a Restate service from the ingress with full
* control.
*
* <p>Create a handle that provides advanced invocation capabilities including:
*
* <ul>
* <li>Async request handling with {@link CompletableFuture}
* <li>Invocation options such as idempotency keys
* <li>Fire-and-forget requests via {@code send()}
* <li>Access to full {@link Response} metadata
* </ul>
*
* <pre>{@code
* Client client = Client.connect("http://localhost:8080");
*
* // Use call() with method reference and wait for the result
* Response<GreetingResponse> response = client.serviceHandle(Greeter.class)
* .call(Greeter::greet, new Greeting("Alice"));
*
* // Use send() for one-way invocation without waiting
* SendResponse<GreetingResponse> sendResponse = client.serviceHandle(Greeter.class)
* .send(Greeter::greet, new Greeting("Alice"));
* }</pre>
*
* <p>For simple synchronous request-response interactions, consider using {@link #service(Class)}
* instead.
*
* @param clazz the service class annotated with {@link Service}
* @return a handle to invoke the service with advanced options
*/
@org.jetbrains.annotations.ApiStatus.Experimental
default <SVC> ClientServiceHandle<SVC> serviceHandle(Class<SVC> clazz) {
ReflectionUtils.mustHaveServiceAnnotation(clazz);
if (ReflectionUtils.isKotlinClass(clazz)) {
throw new IllegalArgumentException("Using Kotlin classes with Java's API is not supported");
}
return new ClientServiceHandleImpl<>(this, clazz, null);
}
/**
* <b>EXPERIMENTAL API:</b> Simple API to invoke a Restate Virtual Object from the ingress.
*
* <p>Create a proxy client that allows calling virtual object methods directly and synchronously,
* returning just the output (not wrapped in {@link Response}). This is the recommended approach
* for straightforward request-response interactions.
*
* <pre>{@code
* Client client = Client.connect("http://localhost:8080");
*
* var counterProxy = client.virtualObject(Counter.class, "my-counter");
* int count = counterProxy.increment();
* }</pre>
*
* <p>For advanced use cases requiring asynchronous request handling, access to {@link Response}
* metadata, or invocation options (such as idempotency keys), use {@link
* #virtualObjectHandle(Class, String)} instead.
*
* @param clazz the virtual object class annotated with {@link VirtualObject}
* @param key the key identifying the specific virtual object instance
* @return a proxy client to invoke the virtual object
*/
@org.jetbrains.annotations.ApiStatus.Experimental
default <SVC> SVC virtualObject(Class<SVC> clazz, String key) {
ReflectionUtils.mustHaveVirtualObjectAnnotation(clazz);
if (ReflectionUtils.isKotlinClass(clazz)) {
throw new IllegalArgumentException("Using Kotlin classes with Java's API is not supported");
}
var serviceName = ReflectionUtils.extractServiceName(clazz);
return ProxySupport.createProxy(
clazz,
invocation -> {
var methodInfo = MethodInfo.fromMethod(invocation.getMethod());
//noinspection unchecked
return this.call(
Request.of(
Target.virtualObject(serviceName, key, methodInfo.getHandlerName()),
(TypeTag<? super Object>) methodInfo.getInputType(),
(TypeTag<? super Object>) methodInfo.getOutputType(),
invocation.getArguments().length == 0 ? null : invocation.getArguments()[0]))
.response();
});
}
/**
* <b>EXPERIMENTAL API:</b> Advanced API to invoke a Restate Virtual Object from the ingress with
* full control.
*
* <p>Create a handle that provides advanced invocation capabilities including:
*
* <ul>
* <li>Async request handling with {@link CompletableFuture}
* <li>Invocation options such as idempotency keys
* <li>Fire-and-forget requests via {@code send()}
* <li>Access to full {@link Response} metadata
* </ul>
*
* <pre>{@code
* Client client = Client.connect("http://localhost:8080");
*
* // Use call() with method reference and wait for the result
* Response<Integer> response = client.virtualObjectHandle(Counter.class, "my-counter")
* .call(Counter::increment);
*
* // Use send() for one-way invocation without waiting
* SendResponse<Integer> sendResponse = client.virtualObjectHandle(Counter.class, "my-counter")
* .send(Counter::increment);
* }</pre>
*
* <p>For simple synchronous request-response interactions, consider using {@link
* #virtualObject(Class, String)} instead.
*
* @param clazz the virtual object class annotated with {@link VirtualObject}
* @param key the key identifying the specific virtual object instance
* @return a handle to invoke the virtual object with advanced options
*/
@org.jetbrains.annotations.ApiStatus.Experimental
default <SVC> ClientServiceHandle<SVC> virtualObjectHandle(Class<SVC> clazz, String key) {
ReflectionUtils.mustHaveVirtualObjectAnnotation(clazz);
if (ReflectionUtils.isKotlinClass(clazz)) {
throw new IllegalArgumentException("Using Kotlin classes with Java's API is not supported");
}
return new ClientServiceHandleImpl<>(this, clazz, key);
}
/**
* <b>EXPERIMENTAL API:</b> Simple API to invoke a Restate Workflow from the ingress.
*
* <p>Create a proxy client that allows calling workflow methods directly and synchronously,
* returning just the output (not wrapped in {@link Response}). This is the recommended approach
* for straightforward request-response interactions.
*
* <pre>{@code
* Client client = Client.connect("http://localhost:8080");
*
* var workflowProxy = client.workflow(OrderWorkflow.class, "order-123");
* OrderResult result = workflowProxy.start(new OrderRequest(...));
* }</pre>
*
* <p>For advanced use cases requiring asynchronous request handling, access to {@link Response}
* metadata, or invocation options (such as idempotency keys), use {@link #workflowHandle(Class,
* String)} instead.
*
* @param clazz the workflow class annotated with {@link Workflow}
* @param key the key identifying the specific workflow instance
* @return a proxy client to invoke the workflow
*/
@org.jetbrains.annotations.ApiStatus.Experimental
default <SVC> SVC workflow(Class<SVC> clazz, String key) {
ReflectionUtils.mustHaveWorkflowAnnotation(clazz);
if (ReflectionUtils.isKotlinClass(clazz)) {
throw new IllegalArgumentException("Using Kotlin classes with Java's API is not supported");
}
var serviceName = ReflectionUtils.extractServiceName(clazz);
return ProxySupport.createProxy(
clazz,
invocation -> {
var methodInfo = MethodInfo.fromMethod(invocation.getMethod());
//noinspection unchecked
return this.call(
Request.of(
Target.virtualObject(serviceName, key, methodInfo.getHandlerName()),
(TypeTag<? super Object>) methodInfo.getInputType(),
(TypeTag<? super Object>) methodInfo.getOutputType(),
invocation.getArguments().length == 0 ? null : invocation.getArguments()[0]))
.response();
});
}
/**
* <b>EXPERIMENTAL API:</b> Advanced API to invoke a Restate Workflow from the ingress with full
* control.
*
* <p>Create a handle that provides advanced invocation capabilities including:
*
* <ul>
* <li>Async request handling with {@link CompletableFuture}
* <li>Invocation options such as idempotency keys
* <li>Fire-and-forget requests via {@code send()}
* <li>Access to full {@link Response} metadata
* </ul>
*
* <pre>{@code
* Client client = Client.connect("http://localhost:8080");
*
* // Use call() with method reference and wait for the result
* Response<OrderResult> response = client.workflowHandle(OrderWorkflow.class, "order-123")
* .call(OrderWorkflow::start, new OrderRequest(...));
*
* // Use send() for one-way invocation without waiting
* SendResponse<OrderResult> sendResponse = client.workflowHandle(OrderWorkflow.class, "order-123")
* .send(OrderWorkflow::start, new OrderRequest(...));
* }</pre>
*
* <p>For simple synchronous request-response interactions, consider using {@link #workflow(Class,
* String)} instead.
*
* @param clazz the workflow class annotated with {@link Workflow}
* @param key the key identifying the specific workflow instance
* @return a handle to invoke the workflow with advanced options
*/
@org.jetbrains.annotations.ApiStatus.Experimental
default <SVC> ClientServiceHandle<SVC> workflowHandle(Class<SVC> clazz, String key) {
ReflectionUtils.mustHaveWorkflowAnnotation(clazz);
if (ReflectionUtils.isKotlinClass(clazz)) {
throw new IllegalArgumentException("Using Kotlin classes with Java's API is not supported");
}
return new ClientServiceHandleImpl<>(this, clazz, key);
}
/**
* Create a default JDK client.
*
* @param baseUri uri to connect to.
*/
static Client connect(String baseUri) {
return connect(baseUri, null, null);
}
/**
* Create a default JDK client.
*
* @param baseUri uri to connect to
* @param options default options to use in all the requests.
*/
static Client connect(String baseUri, RequestOptions options) {
return connect(baseUri, null, options);
}
/**
* Create a default JDK client.
*
* @param baseUri uri to connect to
* @param serdeFactory Serde factory to use. If you're just wrapping this client in a
* code-generated client, you don't need to provide this parameter.
*/
static Client connect(String baseUri, SerdeFactory serdeFactory) {
return connect(baseUri, serdeFactory, RequestOptions.DEFAULT);
}
/**
* Create a default JDK client.
*
* @param baseUri uri to connect to
* @param serdeFactory Serde factory to use. If you're just wrapping this client in a
* code-generated client, you don't need to provide this parameter.
* @param options default options to use in all the requests.
*/
static Client connect(String baseUri, SerdeFactory serdeFactory, RequestOptions options) {
// We load through reflections to avoid CNF exceptions in JVMs
// where JDK's HttpClient is not available (see Android!)
try {
Class.forName("java.net.http.HttpClient");
} catch (ClassNotFoundException e) {
throw new IllegalStateException(
"Cannot load the JdkClient, because the java.net.http.HttpClient is not available on this JVM. Please use another client",
e);
}
try {
return (Client)
Class.forName("dev.restate.client.jdk.JdkClient")
.getMethod("of", String.class, SerdeFactory.class, RequestOptions.class)
.invoke(null, baseUri, serdeFactory, options);
} catch (Exception e) {
throw new IllegalStateException("Cannot instantiate the client", e);
}
}
}