001/*
002 * Copyright 2022-2026 Revetware LLC.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.soklet;
018
019import org.jspecify.annotations.NonNull;
020
021import javax.annotation.concurrent.ThreadSafe;
022import java.util.Optional;
023
024/**
025 * Thread-safe cooperative cancelation signal for response producers and
026 * request handlers.
027 * <p>
028 * Producers and handlers should check this token between expensive or blocking
029 * operations and stop work when it becomes canceled. Soklet exposes it through
030 * {@link ResponseStream#getCancelationToken()} and through
031 * {@link McpInvocationFeatures#getCancelationToken()} for selected MCP
032 * application handlers. Soklet cancels the token when the associated response
033 * can no longer continue, such as when the client disconnects, forced shutdown
034 * begins after the graceful-drain budget, the request HTTP version cannot
035 * support streaming, or a response deadline or streaming timeout is reached.
036 * Graceful shutdown by itself does not cancel already-admitted finite MCP work;
037 * its unary or request-scoped progress response may finish within that budget.
038 * <p>
039 * MCP 2025-06-18 and 2025-11-25 distinguish an already-committed progress SSE
040 * response from a finite response. Losing that SSE connection detaches its
041 * writer without canceling application work solely for connection loss. The
042 * request deadline and forced shutdown can still cancel the retained work.
043 * Disconnects before SSE commitment continue to cancel the token. MCP
044 * 2026-07-28 progress retains its disconnect cancelation behavior.
045 * <p>
046 * The built-in MCP listener treats input EOF as response-channel loss, including
047 * both a normal TCP close and a deliberate client {@code shutdownOutput()}.
048 * Clients must keep their sending side open while awaiting a response.
049 * Modern work and finite/uncommitted legacy work are canceled; an already
050 * committed legacy POST SSE writer is detached as described above.
051 *
052 * <p>Normal completion does not mark the token canceled. Tokens
053 * release registered callbacks when the associated operation completes normally,
054 * and callbacks registered afterward are inert.
055 *
056 * @author <a href="https://www.revetkn.com">Mark Allen</a>
057 */
058@ThreadSafe
059public interface CancelationToken {
060        /**
061         * Is the associated operation canceled?
062         *
063         * @return {@code true} if canceled
064         */
065        @NonNull
066        Boolean isCanceled();
067
068        /**
069         * The cancelation reason, if cancelation has occurred.
070         *
071         * @return the cancelation reason, or {@link Optional#empty()} if not canceled
072         */
073        @NonNull
074        Optional<@NonNull StreamTerminationReason> getCancelationReason();
075
076        /**
077         * The underlying cancelation cause, if available.
078         *
079         * @return the underlying cause, or {@link Optional#empty()} if no cause is available
080         */
081        @NonNull
082        Optional<@NonNull Throwable> getCancelationCause();
083
084        /**
085         * Registers a callback that runs when the token is canceled.
086         * <p>
087         * Each registration is independent, including registrations of the same callback object. Closing the returned
088         * handle suppresses invocation if removal wins before callback claim; it does not wait for a claimed callback.
089         * If the token is already canceled, the callback may run before this method returns. If the associated operation
090         * already completed normally, the callback does not run and its reference is not retained.
091         * <p>
092         * Callback dispatch is selected by the runtime. HTTP streaming uses managed callback execution. MCP application
093         * requests and bounded policy work use a bounded callback executor, after handler interruption and terminal
094         * response offering or transport detachment. Their physical capacity remains charged until callback delivery
095         * exits. Other runtimes may defer delivery until their operation releases callbacks. Late delivery may run inline on the registering
096         * application thread. Keep callbacks fast and non-blocking. Each callback is invoked at most once; failures
097         * are isolated, and independent callbacks have no ordering guarantee.
098         *
099         * @param callback the callback to run on cancelation
100         * @return a handle that removes the callback when closed
101         */
102        @NonNull
103        CallbackRegistration onCancel(@NonNull Runnable callback);
104
105        /**
106         * Throws if the token has been canceled.
107         *
108         * @throws StreamingResponseCanceledException if canceled
109         */
110        default void throwIfCanceled() throws StreamingResponseCanceledException {
111                StreamTerminationReason reason = getCancelationReason().orElse(null);
112
113                if (reason != null)
114                        throw new StreamingResponseCanceledException(reason, getCancelationCause().orElse(null));
115        }
116}