Class AbstractAlpacaStream
- All Implemented Interfaces:
AutoCloseable
- Direct Known Subclasses:
AbstractMarketDataStream,AlpacaTradingStream
Manages the OkHttp WebSocket connection lifecycle, automatic reconnection with jittered exponential backoff, and a thread-safe close flag. Subclasses implement the protocol specifics via template methods.
Thread safety: close() is safe to call from any thread. All template methods
are invoked on OkHttp's internal I/O thread.
-
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedAbstractAlpacaStream(okhttp3.OkHttpClient httpClient) protectedAbstractAlpacaStream(okhttp3.OkHttpClient httpClient, AlpacaStreamReconnectPolicy reconnectPolicy) protectedAbstractAlpacaStream(okhttp3.OkHttpClient httpClient, AlpacaStreamReconnectPolicy reconnectPolicy, Executor callbackExecutor) protectedAbstractAlpacaStream(okhttp3.OkHttpClient httpClient, AlpacaStreamReconnectPolicy reconnectPolicy, Executor callbackExecutor, String streamName) protectedAbstractAlpacaStream(okhttp3.OkHttpClient httpClient, AlpacaStreamReconnectPolicy reconnectPolicy, Executor callbackExecutor, ScheduledExecutorService scheduler) -
Method Summary
Modifier and TypeMethodDescriptionfinal CompletableFuture<Boolean>Returns a future that completes when the stream's first authentication attempt succeeds or fails.Returns a future that completes with the stream's first authentication outcome.protected abstract okhttp3.RequestBuilds the WebSocket upgrade request (URL + any auth headers).final voidclose()Closes the stream permanently.protected final voidcloseTerminal(String reason) Closes the stream permanently after a terminal protocol failure such as failed auth.protected final voidcloseTerminal(String reason, AlpacaStreamAuthResult result) Closes the stream permanently and completes authentication with the supplied terminal result.protected final voidcompleteAuthentication(boolean authenticated) Marks the first authentication attempt as completed.protected final voidMarks the first authentication attempt as completed with diagnostic details.final voidconnect()Opens the WebSocket connection.protected voidhandleBytes(okhttp3.WebSocket ws, okio.ByteString bytes) Called for each binary frame received from the server.protected abstract voidhandleClose(int code, String reason, boolean willReconnect) Called when the connection closes, either cleanly or due to an error.protected abstract voidhandleOpen(okhttp3.WebSocket ws) Called when the WebSocket connection is open.protected abstract voidhandleText(okhttp3.WebSocket ws, String text) Called for each text frame received from the server.protected final voidinvokeCallback(String callbackName, Runnable callback) Runs user-supplied listener code without allowing callback failures to interrupt protocol state transitions such as authentication, re-subscription, or reconnect.final booleanisClosed()Returnstrueifclose()has been called.protected final booleanReturnstrueif the current connection is a reconnect (i.e.protected voidCalled after a reconnect attempt succeeds and the stream is fully re-authenticated (and re-subscribed, if applicable).protected voidnotifyReconnecting(int attempt) Called just before a reconnect attempt is initiated.protected final voidrequireOpenForCommand(String commandName) Throws if a user command attempts to mutate a terminal stream.protected final voidResets the reconnect attempt counter after a successful connection.protected final booleanSends a text frame on the current connection.final booleanwaitForAuthentication(Duration timeout) Blocks until the stream authenticates, authentication fails, or the timeout elapses.final AlpacaStreamAuthResultwaitForAuthenticationResult(Duration timeout) Blocks until the stream authenticates, authentication fails, or the timeout elapses.
-
Constructor Details
-
AbstractAlpacaStream
protected AbstractAlpacaStream(okhttp3.OkHttpClient httpClient) -
AbstractAlpacaStream
protected AbstractAlpacaStream(okhttp3.OkHttpClient httpClient, AlpacaStreamReconnectPolicy reconnectPolicy) -
AbstractAlpacaStream
protected AbstractAlpacaStream(okhttp3.OkHttpClient httpClient, AlpacaStreamReconnectPolicy reconnectPolicy, Executor callbackExecutor) -
AbstractAlpacaStream
protected AbstractAlpacaStream(okhttp3.OkHttpClient httpClient, AlpacaStreamReconnectPolicy reconnectPolicy, Executor callbackExecutor, String streamName) -
AbstractAlpacaStream
protected AbstractAlpacaStream(okhttp3.OkHttpClient httpClient, AlpacaStreamReconnectPolicy reconnectPolicy, Executor callbackExecutor, ScheduledExecutorService scheduler)
-
-
Method Details
-
buildRequest
protected abstract okhttp3.Request buildRequest()Builds the WebSocket upgrade request (URL + any auth headers). -
handleOpen
protected abstract void handleOpen(okhttp3.WebSocket ws) Called when the WebSocket connection is open. -
handleText
Called for each text frame received from the server. -
handleBytes
protected void handleBytes(okhttp3.WebSocket ws, okio.ByteString bytes) Called for each binary frame received from the server.Most streams use text frames only. The paper trading endpoint sends binary
trade_updatesframes; the default implementation decodes them as UTF-8 and delegates tohandleText(okhttp3.WebSocket, java.lang.String). -
handleClose
Called when the connection closes, either cleanly or due to an error.- Parameters:
code- WebSocket close code, or-1for transport failuresreason- human-readable close reason
-
connect
public final void connect()Opens the WebSocket connection. Safe to call once; subsequent calls are ignored if the stream is already open or has been closed. -
send
Sends a text frame on the current connection.- Returns:
trueif the message was enqueued successfully
-
close
public final void close()Closes the stream permanently. No reconnect will be attempted after this call. Idempotent — safe to call multiple times.- Specified by:
closein interfaceAutoCloseable
-
isClosed
public final boolean isClosed()Returnstrueifclose()has been called. -
requireOpenForCommand
Throws if a user command attempts to mutate a terminal stream. -
authenticationFuture
Returns a future that completes when the stream's first authentication attempt succeeds or fails. A clean close before authentication completes the future withfalse. PreferauthenticationResultFuture()when callers need the failure status or server error. -
authenticationResultFuture
Returns a future that completes with the stream's first authentication outcome.The future completes with server rejection details, terminal close reasons, or success. It is not completed by a caller-side timeout from
waitForAuthenticationResult(Duration). -
waitForAuthentication
Blocks until the stream authenticates, authentication fails, or the timeout elapses.- Parameters:
timeout- maximum time to wait- Returns:
truewhen authentication succeeded;falseon timeout, failure, interruption, or close before authentication
-
waitForAuthenticationResult
Blocks until the stream authenticates, authentication fails, or the timeout elapses.A timeout returns
AlpacaStreamAuthResult.Status.TIMEOUTwithout completingauthenticationResultFuture(), allowing other callers to continue waiting for the actual stream outcome.- Parameters:
timeout- maximum time to wait- Returns:
- typed authentication outcome
-
completeAuthentication
protected final void completeAuthentication(boolean authenticated) Marks the first authentication attempt as completed. -
completeAuthentication
Marks the first authentication attempt as completed with diagnostic details. -
closeTerminal
Closes the stream permanently after a terminal protocol failure such as failed auth. -
closeTerminal
Closes the stream permanently and completes authentication with the supplied terminal result. -
invokeCallback
Runs user-supplied listener code without allowing callback failures to interrupt protocol state transitions such as authentication, re-subscription, or reconnect. -
resetReconnectAttempts
protected final void resetReconnectAttempts()Resets the reconnect attempt counter after a successful connection. -
isReconnecting
protected final boolean isReconnecting()Returnstrueif the current connection is a reconnect (i.e. a previous connection was made and then lost). Check this before callingresetReconnectAttempts(). -
notifyReconnecting
protected void notifyReconnecting(int attempt) Called just before a reconnect attempt is initiated.- Parameters:
attempt- 1-based attempt counter
-
notifyReconnected
protected void notifyReconnected()Called after a reconnect attempt succeeds and the stream is fully re-authenticated (and re-subscribed, if applicable). Default implementation is a no-op.
-