Class Soklet

java.lang.Object
com.soklet.Soklet

@ThreadSafe public final class Soklet extends Object
Owns one ready-to-terminal Soklet lifecycle and its configured HTTP, SSE, and MCP transports. run(SokletConfig) returns after all configured transports reach readiness; each instance is one-shot. Every run registers a JVM shutdown hook by default. An embedding host can disable only that registration through SokletConfig.Builder.jvmShutdownHookEnabled(Boolean). Bounded application cleanup, terminal reporting, and process-registration release remain owned by the instance until finalization finishes, even when nobody waits.

SokletConfig config = SokletConfig.withHttpServer(HttpServer.fromPort(8080)).build();
Soklet soklet = Soklet.run(config);
ShutdownResult result = soklet.awaitShutdown();
To stop programmatically, call requestShutdown() and then await completion from an independent owning thread. An embedding host must finish Soklet shutdown before closing shared databases, telemetry, or logging. JVM hooks execute concurrently and do not establish resource ordering. With the automatic hook disabled, the host must prevent new runs once termination begins and request and synchronously await shutdown before its own shutdown hook returns. Any deregistration or delay belongs before that shutdown request; shared dependencies remain available until shutdown succeeds.

Required application cleanup belongs in bounded ShutdownCleanup, rather than post-wait code or observational lifecycle callbacks: during JVM shutdown the JVM need not let those callers finish. Cleanup is eligible only after complete core shutdown; a cleanup timeout does not forcibly stop its code. Running built-in listeners and the lifecycle owner retain JVM liveness until shutdown and finalization; custom transports own their listener-thread policy.

Soklet also offers an off-network Simulator through SokletSimulator, useful for integration testing.

Given a Resource Method...

public class HelloResource {
  @GET("/hello")
  public String hello(@QueryParameter String name) {
    return String.format("Hello, %s", name);
  }
}
...we might test it like this:
@Test
public void integrationTest() {
  // Instead of running on a real HTTP server that listens on a port,
  // a non-network Simulator is provided against which you can
  // issue requests and receive responses.
  SokletSimulator.run(SimulatorConfig.builder().httpServer().build(), simulator -> {
    // Construct a request
    Request request = Request.withPath(HttpMethod.GET, "/hello")
      .queryParameters(Map.of("name", List.of("Mark")))
      .build();

    // Perform the request and get a handle to the response
    HttpRequestResult result = simulator.performHttpRequest(request);
    MarshaledResponse marshaledResponse = result.getMarshaledResponse();

    // Verify status code
    Integer expectedCode = 200;
    Integer actualCode = marshaledResponse.getStatusCode();
    assertEquals(expectedCode, actualCode, "Bad status code");

    // Verify response body
    marshaledResponse.getBody().ifPresentOrElse(body -> {
      String expectedBody = "Hello, Mark";
      byte[] bytes = ((MarshaledResponseBody.Bytes) body).getBytes();
      String actualBody = new String(bytes, StandardCharsets.UTF_8);
      assertEquals(expectedBody, actualBody, "Bad response body");
    }, () -> {
      Assertions.fail("No response body");
    });
  });
}

The Simulator also supports Server-Sent Events.

Integration testing documentation is available at https://www.soklet.com/docs/testing.

Author:
Mark Allen
  • Method Details

    • run

      public static @NonNull Soklet run(@NonNull SokletConfig sokletConfig)
      Starts one lifecycle, returning only after every configured transport has reached readiness. By default owns a JVM shutdown hook until full finalization; SokletConfig.Builder.jvmShutdownHookEnabled(Boolean) may disable only that automatic registration. Programmatic shutdown, cleanup, and lifecycle owner liveness remain unchanged. The host then owns signal-driven shutdown and must request and synchronously await it before its own hook returns. Startup failure or cancellation throws synchronously after attempted teardown; interruption before readiness requests cancellation and the caller's interrupt status is restored. Cancellation competes atomically with readiness. If readiness wins, the ready handle is returned with the interrupt status restored, and that startup interruption does not request shutdown of the running lifecycle.
      Parameters:
      sokletConfig - configuration with unclaimed transport identities
      Returns:
      the ready lifecycle handle
      Throws:
      TransportOwnershipException - if a configured transport is already claimed
      SokletStartupException - if readiness is not reached
    • run

      public static @NonNull Soklet run(@NonNull SokletConfig sokletConfig, @NonNull ShutdownCleanup cleanup)
      Starts a lifecycle with bounded application cleanup eligible after complete core shutdown. All arguments are validated before transports are claimed. When enabled, the JVM hook joins bounded core shutdown, cleanup, and reporting. Both await methods additionally observe process-registration release.
      Parameters:
      sokletConfig - configuration with unclaimed transport identities
      cleanup - bounded synchronous application cleanup
      Returns:
      the ready lifecycle handle
      Throws:
      TransportOwnershipException - if a configured transport is already claimed
      SokletStartupException - if readiness is not reached
    • run

      public static <E extends @NonNull Throwable> @NonNull ShutdownResult run(@NonNull SokletConfig sokletConfig, @NonNull Soklet.RunAction<@NonNull E> action) throws E
      Starts Soklet, invokes the action after readiness, and requests shutdown when the action returns or throws. Joins full finalization before returning the immutable terminal result or propagating a failure. The action runs once on the calling thread; startup failure prevents its invocation. All arguments are validated before transports are claimed. The configuration's SokletConfig.isJvmShutdownHookEnabled() option applies to scoped execution as well; disabling the automatic hook does not disable teardown when the action returns or throws.

      A callback failure remains the exact primary exception or Error. A concurrent finalization failure is suppressed on it using ordinary Java suppression semantics, after finalization has finished. Without a callback failure, finalization uses the same failure classification as awaitShutdown(). A complete forced shutdown can return normally.

      Finalization does not abandon shutdown when the caller is interrupted. An interrupt flag left set by the action is temporarily cleared for the join, and it and interruptions received while joining are restored before returning or throwing. An InterruptedException thrown by the action is propagated as that action's original failure.

      The action has no imposed timeout. An external shutdown does not terminate it; the scoped invocation still needs the action to return or throw.

      Type Parameters:
      E - throwable type selected by the action
      Parameters:
      sokletConfig - configuration with unclaimed transport identities
      action - work defining the scope's lifetime
      Returns:
      the immutable successful terminal result; it may be ignored
      Throws:
      E - if the action fails, after attempted shutdown and full finalization
      SokletStartupException - if startup does not reach readiness
      SokletLifecycleException - if finalization fails without an action failure
    • run

      public static <E extends @NonNull Throwable> @NonNull ShutdownResult run(@NonNull SokletConfig sokletConfig, @NonNull ShutdownCleanup cleanup, @NonNull Soklet.RunAction<@NonNull E> action) throws E
      Runs one action-defined scope with bounded application cleanup. Shares the execution, error, and interruption semantics of run(SokletConfig, RunAction). Cleanup is eligible only after complete core shutdown, including when the action failed; incomplete core shutdown skips cleanup. All arguments are validated before transport claims.
      Type Parameters:
      E - throwable type selected by the action
      Parameters:
      sokletConfig - configuration with unclaimed transport identities
      cleanup - bounded synchronous application cleanup
      action - work defining the scope's lifetime
      Returns:
      the immutable successful terminal result; it may be ignored
      Throws:
      E - if the action fails, after attempted shutdown and full finalization
      SokletStartupException - if startup does not reach readiness
      SokletLifecycleException - if finalization fails without an action failure
    • requestShutdown

      public void requestShutdown()
      Requests shutdown promptly without waiting. Repeated requests are safe. Handlers and callbacks may request shutdown but must return without waiting for work whose termination depends on their own return.
    • awaitShutdown

      @CanIgnoreReturnValue public @NonNull ShutdownResult awaitShutdown() throws InterruptedException
      Waits for full shutdown, bounded application cleanup, terminal reporting, and process-registration release, without requesting shutdown. This wait and awaitShutdownAsync() expose the same immutable result or underlying lifecycle failure; the asynchronous stage wraps failures in CompletionException.
      Returns:
      the exact immutable terminal result
      Throws:
      InterruptedException - if this wait is interrupted; the lifecycle continues
      SokletLifecycleException - if the lifecycle or eligible cleanup fails
      IllegalStateException - if tracked lifecycle work attempts to join itself
    • awaitShutdownAsync

      Observes the same full terminal outcome as awaitShutdown() without blocking or requesting shutdown. Returns one cached read-only stage; no waiting thread is created by this method. Lifecycle failures complete it exceptionally, with the underlying lifecycle failure wrapped in CompletionException. Mutating a future derived from it cannot alter the lifecycle. Callbacks must not join this stage from work that shutdown must drain. The daemon completion handoff does not keep the JVM alive, including during normal programmatic shutdown after main returns. A host composing asynchronous cleanup must retain process liveness until its dependent stages finish. Put required standalone application cleanup in ShutdownCleanup.
      Returns:
      cached full-finalization completion stage