dev.restate.sdk.Util Maven / Gradle / Ivy
// 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.sdk;
import dev.restate.sdk.common.AbortedExecutionException;
import dev.restate.sdk.common.Output;
import dev.restate.sdk.common.Serde;
import dev.restate.sdk.common.function.ThrowingFunction;
import dev.restate.sdk.common.syscalls.Deferred;
import dev.restate.sdk.common.syscalls.Result;
import dev.restate.sdk.common.syscalls.SyscallCallback;
import dev.restate.sdk.common.syscalls.Syscalls;
import java.nio.ByteBuffer;
import java.util.Optional;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
class Util {
private Util() {}
static T blockOnResolve(Syscalls syscalls, Deferred deferred) {
if (!deferred.isCompleted()) {
Util.blockOnSyscall(cb -> syscalls.resolveDeferred(deferred, cb));
}
return Util.unwrapResult(deferred.toResult());
}
static T awaitCompletableFuture(CompletableFuture future) {
try {
return future.get();
} catch (InterruptedException | CancellationException e) {
AbortedExecutionException.sneakyThrow();
return null; // Previous statement throws an exception
} catch (ExecutionException e) {
throw (RuntimeException) e.getCause();
}
}
static T blockOnSyscall(Consumer> syscallExecutor) {
CompletableFuture fut = new CompletableFuture<>();
syscallExecutor.accept(SyscallCallback.completingFuture(fut));
return Util.awaitCompletableFuture(fut);
}
static T unwrapResult(Result res) {
if (res.isSuccess()) {
return res.getValue();
}
throw res.getFailure();
}
static Optional unwrapOptionalReadyResult(Result res) {
if (!res.isSuccess()) {
throw res.getFailure();
}
if (res.isEmpty()) {
return Optional.empty();
}
return Optional.of(res.getValue());
}
static Output unwrapOutputReadyResult(Result res) {
if (!res.isSuccess()) {
throw res.getFailure();
}
if (res.isEmpty()) {
return Output.notReady();
}
return Output.ready(res.getValue());
}
static R executeMappingException(Syscalls syscalls, ThrowingFunction fn, T t) {
try {
return fn.apply(t);
} catch (Throwable e) {
syscalls.fail(e);
AbortedExecutionException.sneakyThrow();
return null;
}
}
static ByteBuffer serializeWrappingException(Syscalls syscalls, Serde serde, T value) {
return executeMappingException(syscalls, serde::serializeToByteBuffer, value);
}
static T deserializeWrappingException(
Syscalls syscalls, Serde serde, ByteBuffer byteString) {
return executeMappingException(syscalls, serde::deserialize, byteString);
}
}