diff --git a/.gitleaks.toml b/.gitleaks.toml new file mode 100644 index 000000000..cd2a3f3c9 --- /dev/null +++ b/.gitleaks.toml @@ -0,0 +1,16 @@ +# Gitleaks configuration, picked up from the repository root by the Gitleaks workflow. +# +# Keep every default rule and only add narrow exceptions for known false positives. + +[extend] +useDefault = true + +[allowlist] +description = "Known false positives" +regexTarget = "secret" +regexes = [ + # The example Sec-WebSocket-Key value from RFC 6455 section 1.3, base64 of + # "the sample nonce". Tests send it in hand-written WebSocket upgrade requests. + # It is a public handshake nonce, not a credential. + '''dGhlIHNhbXBsZSBub25jZQ==''', +] diff --git a/README.md b/README.md index 311c985d6..09d4a2676 100644 --- a/README.md +++ b/README.md @@ -219,8 +219,34 @@ try (Query q = db.borrowQuery()) { ### Cancel or Time Out a Query -`submit()` returns a `Completion`. `await(timeout, unit)` returns `false` if the query is still in flight; `cancel()` -stops it. +Give a query a timeout with `timeout(...)`, or every query a default with `query_timeout_ms` in the configuration +string. It overrides the server's default query timeout (`query.timeout`) for that query: the client sends it with the +query, and the server stops the query when it can. `await()` then throws a `QueryException` whose `isTimeout()` is +`true`, and the pooled connection stays open for the next query. + +```java +import io.questdb.client.QueryException; + +try (Query q = db.borrowQuery()) { + q.sql("SELECT * FROM big_table ORDER BY ts") + .handler(handler) + .timeout(5, TimeUnit.SECONDS); + try { + q.submit().await(); + } catch (QueryException e) { + if (!e.isTimeout()) { + throw e; + } + // the server stopped the query after 5 seconds + } +} +``` + +The client keeps no deadline of its own: it waits for the server's answer however long it takes. Some statements +cannot be stopped and run to completion. A server that does not support per-query timeouts applies its own default. + +`submit()` returns a `Completion`. `await(timeout, unit)` only bounds the wait: it returns `false` while the query keeps +running. `cancel()` stops the query. ```java import io.questdb.client.Completion; @@ -713,6 +739,7 @@ schema::key1=value1;key2=value2; | `query_pool_min` | `1` | Minimum query connections kept warm (`0` under `lazy_connect`) | | `query_pool_max` | `4` | Maximum query connections | | `acquire_timeout_ms` | `5000` | How long `borrowSender()`/`borrowQuery()` waits for a free slot | +| `query_close_timeout_ms` | `5000` | How long `Query.close()` waits for a running query | | `idle_timeout_ms` | `60000` | How long a pooled connection may stay idle before it is reaped | | `max_lifetime_ms` | `1800000` | Maximum lifetime of a pooled connection before it is recycled | @@ -727,6 +754,12 @@ Applied by the query pool to select and fail over between the nodes in the `addr | `zone` | | Prefer same-zone endpoints for `target=any`/`replica` (opaque, case-insensitive) | | `client_id` | | Opaque client identifier surfaced server-side for observability | +### Query keys + +| Key | Default | Description | +| ------------------ | ------- | ------------------------------------------------------------------------------------------ | +| `query_timeout_ms` | `0` | Default per-query server timeout in milliseconds (`0` = server default); override per query with `timeout()` | + The ingest side also accepts store-and-forward and reconnection tuning keys (`auto_flush_*`, `initial_connect_retry`, `reconnect_*`, `request_durable_ack`, `sf_*`, `max_frame_rejections`, `poison_min_escalation_window_millis`, …). `sf_max_total_bytes` caps the unacknowledged data all pooled senders buffer together — 128 MiB of memory by default, diff --git a/core/src/main/java/io/questdb/client/Completion.java b/core/src/main/java/io/questdb/client/Completion.java index 615799e07..7ddd5edd1 100644 --- a/core/src/main/java/io/questdb/client/Completion.java +++ b/core/src/main/java/io/questdb/client/Completion.java @@ -63,6 +63,11 @@ public interface Completion { /** * Blocks up to the given timeout. Returns {@code true} if the query * completed, {@code false} on timeout. + *
+ * This bounds only how long the caller waits: on {@code false} the query + * keeps running. To have the server stop queries that run too long, set a + * query timeout ({@link Query#timeout(long, TimeUnit)} or + * {@code query_timeout_ms}). * * @throws QueryException if the server reported an error or * {@link #cancel()} won the race diff --git a/core/src/main/java/io/questdb/client/Query.java b/core/src/main/java/io/questdb/client/Query.java index 216cbe278..c31d0d71d 100644 --- a/core/src/main/java/io/questdb/client/Query.java +++ b/core/src/main/java/io/questdb/client/Query.java @@ -28,8 +28,10 @@ import io.questdb.client.cutlass.qwp.client.QwpColumnBatchHandler; import io.questdb.client.cutlass.qwp.client.QwpQueryOptions; import io.questdb.client.cutlass.qwp.client.QwpServerInfo; +import io.questdb.client.cutlass.qwp.protocol.QwpConstants; import java.io.Closeable; +import java.util.concurrent.TimeUnit; /** * A query handle leased from the {@link QuestDB} pool via @@ -44,12 +46,13 @@ * creates one small lease handle per borrow (often scalar-replaced by the JIT * when used with try-with-resources). *
- * Lifecycle: configure with {@link #sql}, optional {@link #binds} and - * {@link #options}, and {@link #handler}, then call {@link #submit()} to obtain - * a {@link Completion} and {@code await()} it before the next {@link #submit()}. - * The query reads its SQL text, binds and handler while it runs, so do not - * change them before {@code await()} returns. It takes its options when it is - * submitted, so {@link #options} may set up the next query in the meantime. + * Lifecycle: configure with {@link #sql}, optional {@link #binds}, + * {@link #timeout} and {@link #options}, and {@link #handler}, then call + * {@link #submit()} to obtain a {@link Completion} and {@code await()} it before + * the next {@link #submit()}. The query reads its SQL text, binds and handler + * while it runs, so do not change them before {@code await()} returns. It takes + * its timeout and options when it is submitted, so {@link #timeout} and + * {@link #options} may set up the next query in the meantime. *
* Thread safety: not thread-safe and single-flight -- one in-flight query per * handle. To run queries concurrently, borrow one handle per concurrent query. @@ -84,6 +87,9 @@ public interface Query extends Closeable { * therefore never blocks the caller unbounded, even when the server is slow * to honor the cancel. *
+ * A client whose connection failed is discarded. Any other client whose + * query has ended is returned to the pool at once. + *
* Must NOT be called from a result handler: handlers run on the worker * thread, so {@code close()} would block waiting for a terminal event that * only that thread can deliver. Calling it there throws @@ -148,4 +154,33 @@ public interface Query extends Closeable { * before the first successful bind */ QwpServerInfo serverInfo(); + + /** + * Sets the query timeout for subsequent {@link #submit()} calls on this + * handle, overriding the {@code query_timeout_ms} default from the + * connection string. It stays in effect until changed, and every borrow + * starts from the configured default. + *
+ * The timeout overrides the server's default query timeout + * ({@code query.timeout}) for this query; the client sends it with the query + * and keeps no deadline of its own. The server stops the query when it can: + * the handler's {@code onError} then receives + * {@link QwpConstants#STATUS_QUERY_TIMEOUT}, {@link Completion#await()} + * throws a {@link QueryException} whose {@link QueryException#isTimeout()} + * is {@code true}, and the pooled connection serves the next query. Some + * statements cannot be stopped and run to completion. A server that does + * not support per-query timeouts applies its own default. + *
+ * To bound how long the caller waits, use + * {@link Completion#await(long, TimeUnit)}, and {@link Completion#cancel()} + * to stop the query from the client side. + * + * @param timeout the timeout, {@code 0} to send none so the server's default + * applies; a positive value below one millisecond counts as + * one millisecond + * @param unit the unit of {@code timeout} + * @return this handle + * @throws IllegalArgumentException when {@code timeout} is negative + */ + Query timeout(long timeout, TimeUnit unit); } diff --git a/core/src/main/java/io/questdb/client/QueryException.java b/core/src/main/java/io/questdb/client/QueryException.java index 4fbff9928..d584d955e 100644 --- a/core/src/main/java/io/questdb/client/QueryException.java +++ b/core/src/main/java/io/questdb/client/QueryException.java @@ -26,6 +26,7 @@ import io.questdb.client.cutlass.qwp.client.QwpEgressMsgKind; import io.questdb.client.cutlass.qwp.client.QwpQueryOptions; +import io.questdb.client.cutlass.qwp.protocol.QwpConstants; /** * Thrown from {@link Completion#await()} / {@link Completion#await(long, java.util.concurrent.TimeUnit)} @@ -35,9 +36,12 @@ *
* The original wire-level status byte is exposed via {@link #getStatus()} so * callers can distinguish cancellation from schema errors etc. without - * string-matching the message. When the query asked for the error position - * with {@link QwpQueryOptions#errorPosition(boolean)}, {@link #getPosition()} - * points at the offending character of the SQL text. + * string-matching the message. A query that ran past its timeout (see + * {@link Query#timeout(long, java.util.concurrent.TimeUnit)}) reports + * {@link QwpConstants#STATUS_QUERY_TIMEOUT}; {@link #isTimeout()} tests for it. + * When the query asked for the error position with + * {@link QwpQueryOptions#errorPosition(boolean)}, {@link #getPosition()} points + * at the offending character of the SQL text. */ public class QueryException extends RuntimeException { @@ -79,4 +83,12 @@ public int getPosition() { public byte getStatus() { return status; } + + /** + * Returns {@code true} when the server stopped the query because it ran + * past its timeout. The connection that ran it stays usable. + */ + public boolean isTimeout() { + return status == QwpConstants.STATUS_QUERY_TIMEOUT; + } } diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QueryEvent.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QueryEvent.java index 75b617354..2c99ea46d 100644 --- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QueryEvent.java +++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QueryEvent.java @@ -29,9 +29,21 @@ * One event per {@code RESULT_BATCH} / {@code RESULT_END} / {@code QUERY_ERROR} * received from the server, plus a synthetic error event if the connection drops * mid-query. + *
+ * The I/O thread stamps the events of a query with that query's id
+ * ({@link #requestId}), so {@code execute()} can tell its own events from the
+ * leftovers of an earlier query that its {@code execute()} stopped waiting for.
+ * Connection-level events -- the connection failed, the I/O thread stopped, the
+ * client closed -- carry {@link #ANY_REQUEST} and reach whichever query waits.
*/
public class QueryEvent {
+ /**
+ * {@link #requestId} of an event that belongs to no query in particular, such
+ * as a connection failure. Whichever query waits for events must see it.
+ */
+ public static final long ANY_REQUEST = -1L;
+
public static final int KIND_BATCH = 0;
public static final int KIND_END = 1;
public static final int KIND_ERROR = 2;
@@ -54,12 +66,14 @@ public class QueryEvent {
public byte errorStatus; // valid for KIND_ERROR
public int kind;
public short opType; // valid for KIND_EXEC_DONE (matches CompiledQuery.SELECT/INSERT/etc.)
+ public long requestId = ANY_REQUEST; // query the event belongs to; see forRequest()
public long rowsAffected; // valid for KIND_EXEC_DONE
public long totalRows; // valid for KIND_END
public QueryEvent asBatch(QwpBatchBuffer buffer) {
this.kind = KIND_BATCH;
this.buffer = buffer;
+ this.requestId = ANY_REQUEST;
return this;
}
@@ -68,6 +82,7 @@ public QueryEvent asEnd(long totalRows) {
this.buffer = null;
this.totalRows = totalRows;
this.details.clear();
+ this.requestId = ANY_REQUEST;
return this;
}
@@ -81,6 +96,7 @@ public QueryEvent asError(byte status, String message, int position) {
this.errorStatus = status;
this.errorMessage = message;
this.errorPosition = position;
+ this.requestId = ANY_REQUEST;
return this;
}
@@ -90,6 +106,7 @@ public QueryEvent asExecDone(short opType, long rowsAffected) {
this.opType = opType;
this.rowsAffected = rowsAffected;
this.details.clear();
+ this.requestId = ANY_REQUEST;
return this;
}
@@ -99,9 +116,29 @@ public QueryEvent asTransportError(byte status, String message) {
this.errorStatus = status;
this.errorMessage = message;
this.errorPosition = QwpEgressMsgKind.NO_ERROR_POSITION;
+ this.requestId = ANY_REQUEST;
+ return this;
+ }
+
+ /**
+ * Ties the event to the query with id {@code requestId}. Call it after the
+ * {@code asX()} builder, which leaves the event at {@link #ANY_REQUEST}.
+ */
+ public QueryEvent forRequest(long requestId) {
+ this.requestId = requestId;
return this;
}
+ /**
+ * Returns {@code true} when the event belongs to a query other than
+ * {@code requestId}: a leftover of an earlier query that its
+ * {@code execute()} stopped waiting for. An {@link #ANY_REQUEST} event
+ * belongs to every query.
+ */
+ public boolean isForOtherRequest(long requestId) {
+ return this.requestId != ANY_REQUEST && this.requestId != requestId;
+ }
+
/**
* Clears object references and resets primitive fields so a pooled event is
* safe to reuse across queries. The I/O thread calls the {@code asX(...)}
@@ -119,6 +156,7 @@ public void reset() {
this.opType = 0;
this.rowsAffected = 0;
this.totalRows = 0;
+ this.requestId = ANY_REQUEST;
this.details.clear();
}
diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpColumnBatchHandler.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpColumnBatchHandler.java
index ce809df61..c63bb421e 100644
--- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpColumnBatchHandler.java
+++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpColumnBatchHandler.java
@@ -47,7 +47,9 @@
* Exception contract: if any callback method throws, the
* exception propagates out of the {@link QwpQueryClient#execute} call on the
* caller's thread and no further callbacks fire for that query. The connection
- * remains usable for subsequent queries.
+ * remains usable for subsequent queries: when {@link #onBatch} throws while the
+ * query is still running, {@code execute} cancels the query, and the next query
+ * skips whatever the cancelled one still sends.
*/
public interface QwpColumnBatchHandler {
diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpEgressIoThread.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpEgressIoThread.java
index 7fd63f923..87efdb29c 100644
--- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpEgressIoThread.java
+++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpEgressIoThread.java
@@ -90,8 +90,9 @@ public class QwpEgressIoThread implements Runnable, WebSocketFrameHandler {
// reads the fields synchronously in {@link #sendQueryRequest} and does not
// retain a reference past that call. Reuse avoids a per-submit allocation
// -- one in-flight query per client makes this safe: the worker that
- // mutates pendingRequest is blocked on the events queue until the I/O
- // thread has finished consuming the previous instance.
+ // mutates pendingRequest does not return from execute() before the I/O
+ // thread has encoded the previous instance, or it was withdrawn
+ // (withdrawRequest).
private final QueryRequest pendingRequest = new QueryRequest();
// Single-slot request queue (Phase-1 allows one in-flight query).
private final BlockingQueue
* {@code queryFlags} are the bits the request carries, which the server
- * must advertise; zero sends no {@code query_flags} trailer. {@code skipRows}
- * goes on the wire only with {@link QwpEgressMsgKind#QUERY_FLAG_SKIP_ROWS}
- * and {@code maxRows} only with {@link QwpEgressMsgKind#QUERY_FLAG_MAX_ROWS};
- * both must be non-negative.
+ * must advertise; zero sends no {@code query_flags} trailer. {@code timeoutMs}
+ * goes on the wire only with {@link QwpEgressMsgKind#QUERY_FLAG_TIMEOUT},
+ * {@code skipRows} only with {@link QwpEgressMsgKind#QUERY_FLAG_SKIP_ROWS} and
+ * {@code maxRows} only with {@link QwpEgressMsgKind#QUERY_FLAG_MAX_ROWS}; all
+ * must be non-negative.
*/
public void submitQuery(
CharSequence sql,
@@ -475,6 +496,7 @@ public void submitQuery(
long bindPayloadPtr,
long bindPayloadLen,
long queryFlags,
+ long timeoutMs,
long skipRows,
long maxRows
) throws InterruptedException {
@@ -485,6 +507,7 @@ public void submitQuery(
pendingRequest.bindPayloadPtr = bindPayloadPtr;
pendingRequest.bindPayloadLen = bindPayloadLen;
pendingRequest.queryFlags = queryFlags;
+ pendingRequest.timeoutMs = timeoutMs;
pendingRequest.skipRows = skipRows;
pendingRequest.maxRows = maxRows;
requests.put(pendingRequest);
@@ -497,6 +520,29 @@ public QueryEvent takeEvent() throws InterruptedException {
return events.take();
}
+ /**
+ * Pops the next event, waiting at most until the absolute
+ * {@link System#nanoTime()} {@code deadlineNanos}. Returns {@code null} when
+ * the deadline passes with no event available. Called by the user thread
+ * while it stops an I/O thread it gave up on, releasing what that thread
+ * still publishes.
+ */
+ public QueryEvent takeEvent(long deadlineNanos) throws InterruptedException {
+ return events.take(deadlineNanos);
+ }
+
+ /**
+ * Takes back the request {@code requestId} that {@link #submitQuery} queued,
+ * provided this thread has not picked it up yet. Returns {@code true} when it
+ * was still queued: it is never sent, and the caller may reuse its SQL text
+ * and bind payload at once. Returns {@code false} when this thread has it;
+ * it reads them until {@link #isRequestEncoded} holds. Removal and pick-up
+ * are atomic with respect to each other.
+ */
+ public boolean withdrawRequest(long requestId) {
+ return pendingRequest.requestId == requestId && requests.remove(pendingRequest);
+ }
+
/**
* Reads the statistics block of {@link QwpEgressMsgKind#QUERY_FLAG_STATS}:
* {@code compile_ns, execute_ns, count_ns, client_wait_ns} as varints and
@@ -531,7 +577,7 @@ private QueryEvent borrowEvent() {
private void decodeAndEmitError(long payload, int payloadLen) {
QueryEvent ev = decodeError(payload, payloadLen, currentQueryFlags);
- events.offer(ev);
+ events.offer(ev.forRequest(currentRequestId));
}
/**
@@ -543,7 +589,7 @@ private void decodeAndEmitError(long payload, int payloadLen) {
*/
private void decodeAndEmitExecDone(long payload, int payloadLen) {
try {
- events.offer(decodeExecDone(borrowEvent(), payload, payloadLen, currentQueryFlags));
+ events.offer(decodeExecDone(borrowEvent(), payload, payloadLen, currentQueryFlags).forRequest(currentRequestId));
} catch (QwpDecodeException e) {
emitTerminalTransportError(e.getMessage());
}
@@ -558,7 +604,7 @@ private void decodeAndEmitExecDone(long payload, int payloadLen) {
*/
private void decodeAndEmitResultEnd(long payload, int payloadLen) {
try {
- events.offer(decodeResultEnd(borrowEvent(), payload, payloadLen, currentQueryFlags));
+ events.offer(decodeResultEnd(borrowEvent(), payload, payloadLen, currentQueryFlags).forRequest(currentRequestId));
} catch (QwpDecodeException e) {
emitTerminalTransportError(e.getMessage());
}
@@ -569,10 +615,22 @@ private void decodeAndEmitResultEnd(long payload, int payloadLen) {
* thread at every loop boundary so a cancel set by a user thread reaches
* the server regardless of whether the I/O thread was waiting on a frame
* or on a free buffer.
+ *
+ * Only a cancel of the query being served goes out. One for a later query
+ * stays pending: the user thread can queue that query, and cancel it, while
+ * this thread still works through an earlier query whose {@code execute()}
+ * stopped waiting for it. Sent now, the CANCEL would reach the server before
+ * the query does, and the server drops a cancel of a query it does not know.
+ * One for an earlier query, which has already ended, is dropped. Request ids
+ * only grow, so comparing them tells the three apart.
*/
private void drainPendingCancel() {
- long id = pendingCancelRequestId.getAndSet(-1L);
- if (id >= 0L) {
+ long id = pendingCancelRequestId.get();
+ if (id < 0L || id > currentRequestId) {
+ return;
+ }
+ // The CAS keeps a cancel the user thread set meanwhile, which is newer.
+ if (pendingCancelRequestId.compareAndSet(id, -1L) && id == currentRequestId) {
sendCancel(id);
}
}
@@ -671,7 +729,7 @@ private void handleResultBatch(long payloadPtr, int payloadLen) {
currentQueryDone = true;
return;
}
- events.offer(borrowEvent().asBatch(buf));
+ events.offer(borrowEvent().asBatch(buf).forRequest(currentRequestId));
// Park on the release latch. Returning sooner would let receiveFrame
// compact the WebSocket recv buffer, overwriting the bytes that the
// user-visible column pointers still reference. User thread's
@@ -762,9 +820,14 @@ private void sendQueryRequest(QueryRequest req) {
}
// Optional query_flags trailer; omitted when zero so a baseline frame
// stays byte-identical and the server defaults the flags to 0. The
- // row-window values follow the flags in ascending order of their bits.
+ // timeout and row-window values follow the flags in ascending order of
+ // their bits.
if (req.queryFlags != 0) {
sendScratch.putVarint(req.queryFlags);
+ // Flag-gated fields follow the flags in flag-bit order.
+ if ((req.queryFlags & QwpEgressMsgKind.QUERY_FLAG_TIMEOUT) != 0) {
+ sendScratch.putVarint(req.timeoutMs);
+ }
if ((req.queryFlags & QwpEgressMsgKind.QUERY_FLAG_SKIP_ROWS) != 0) {
sendScratch.putVarint(req.skipRows);
}
@@ -772,6 +835,8 @@ private void sendQueryRequest(QueryRequest req) {
sendScratch.putVarint(req.maxRows);
}
}
+ // The request no longer references the caller's SQL text or bind scratch.
+ encodedRequestId = req.requestId;
wsClient.sendBinary(sendScratch.getBufferPtr(), sendScratch.getPosition());
sendScratch.reset();
}
@@ -821,9 +886,10 @@ public interface TerminalFailureListener {
/**
* Mutable request holder reused across submits. Safe to reuse because at
* most one query is in flight per client: the worker thread mutates fields
- * and offers the instance into {@link #requests}, then blocks on the events
- * queue until the I/O thread has fully consumed the previous instance and
- * delivered a terminal event.
+ * and offers the instance into {@link #requests}, and does not return from
+ * {@code execute()} before this thread has encoded the instance (see
+ * {@link #isRequestEncoded}) or the worker withdrew it
+ * ({@link #withdrawRequest}).
*/
private static final class QueryRequest {
int bindCount;
@@ -835,6 +901,7 @@ private static final class QueryRequest {
long requestId;
long skipRows;
CharSequence sql;
+ long timeoutMs;
}
/**
diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpEgressMsgKind.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpEgressMsgKind.java
index 571e1d633..7eb00b08c 100644
--- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpEgressMsgKind.java
+++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpEgressMsgKind.java
@@ -56,11 +56,16 @@ public final class QwpEgressMsgKind {
*/
public static final int CAP_QUERY_FLAGS = 0x00000002;
/**
- * {@code SERVER_INFO.capabilities} bit reserved for per-query timeouts, which
- * this client does not send. Released clients (c-questdb-client 7.2.0 and
- * later, and the Python client built on it) read the bit as "the server
- * honours {@link #QUERY_FLAG_TIMEOUT}", so no other capability may take it.
- * Mirrors the server-side constant
+ * {@code SERVER_INFO.capabilities} bit: the server enforces a per-query
+ * timeout carried on {@code QUERY_REQUEST}. When set (together with
+ * {@link #CAP_QUERY_FLAGS}), a client that wants a timeout sets
+ * {@link #QUERY_FLAG_TIMEOUT} and appends {@code timeout_ms:varint} after the
+ * {@code query_flags} trailer; the server then ends an over-budget query with
+ * a {@code QUERY_ERROR} carrying
+ * {@link io.questdb.client.cutlass.qwp.protocol.QwpConstants#STATUS_QUERY_TIMEOUT},
+ * leaving the connection open. Released clients (c-questdb-client 7.2.0 and
+ * later, and the Python client built on it) read the bit the same way, so no
+ * other capability may take it. Mirrors the server-side constant
* {@code io.questdb.cutlass.qwp.codec.QwpEgressMsgKind#CAP_QUERY_TIMEOUT}.
*/
public static final int CAP_QUERY_TIMEOUT = 0x00000008;
@@ -127,7 +132,8 @@ public final class QwpEgressMsgKind {
* {@code QUERY_REQUEST.query_flags} bit: leave out the first
* {@code skip_rows} rows of the result set. The request carries
* {@code skip_rows:varint} after {@code query_flags}, behind the fields of
- * the lower flag bits, of which this client sends none. Statements that do
+ * the lower flag bits: after {@code timeout_ms} when
+ * {@link #QUERY_FLAG_TIMEOUT} is set too. Statements that do
* not produce rows ignore it. Sent only when the server advertised
* {@link #CAP_QUERY_DETAILS}.
*/
@@ -143,14 +149,13 @@ public final class QwpEgressMsgKind {
*/
public static final int QUERY_FLAG_STATS = 0x08;
/**
- * {@code QUERY_REQUEST.query_flags} bit reserved for per-query timeouts, which
- * this client does not send. Released clients (c-questdb-client 7.2.0 and
- * later, and the Python client built on it) send it, followed by a
- * {@code timeout_ms:varint}, to a server that advertises
- * {@link #CAP_QUERY_TIMEOUT}, so no other flag may take this bit. A flag that
- * carries a field appends it after {@code query_flags} in ascending order of
- * the flag bits, so {@code timeout_ms} goes ahead of {@code skip_rows} and
- * {@code max_rows}. Mirrors the server-side constant
+ * {@code QUERY_REQUEST.query_flags} bit: a {@code timeout_ms:varint} field
+ * follows the {@code query_flags} varint. A flag that carries a field appends
+ * it after {@code query_flags} in ascending order of the flag bits, so
+ * {@code timeout_ms} goes ahead of {@code skip_rows} and {@code max_rows}.
+ * The server runs the query under that timeout instead of its default
+ * {@code query.timeout}. Sent only when the server advertised
+ * {@link #CAP_QUERY_TIMEOUT}. Mirrors the server-side constant
* {@code io.questdb.cutlass.qwp.codec.QwpEgressMsgKind#QUERY_FLAG_TIMEOUT}.
*/
public static final int QUERY_FLAG_TIMEOUT = 0x02;
diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpQueryClient.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpQueryClient.java
index 20caf9a23..34b71e46a 100644
--- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpQueryClient.java
+++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpQueryClient.java
@@ -48,8 +48,10 @@
import java.util.Base64;
import java.util.List;
import java.util.Random;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.locks.LockSupport;
/**
* QWP egress (query results) client.
@@ -92,11 +94,21 @@
* query {@code QUERY_ERROR} responses are NOT terminal -- the connection
* remains usable for the next query.
*
+ * Query timeout: {@code query_timeout_ms=} (or {@link #withQueryTimeout} /
+ * the {@code timeoutMs} argument of {@link #execute}) overrides the server's
+ * default query timeout ({@code query.timeout}) for each query. The client
+ * only sends it; the server stops the query when it can and reports
+ * {@link QwpConstants#STATUS_QUERY_TIMEOUT}, and the connection stays open for
+ * the next query. The client keeps no deadline of its own: it waits for the
+ * server's answer however long that takes. A server that does not advertise
+ * {@link QwpEgressMsgKind#CAP_QUERY_TIMEOUT} never receives the timeout and
+ * applies its own default.
+ *
* Status byte convention on {@link QwpColumnBatchHandler#onError}: server-
* emitted {@code QUERY_ERROR} frames surface with the server's status code
* ({@link WebSocketResponse#STATUS_PARSE_ERROR}, {@code STATUS_INTERNAL_ERROR},
* {@link QwpConstants#STATUS_CANCELLED}, {@link QwpConstants#STATUS_LIMIT_EXCEEDED},
- * etc.). Failures detected client-side (closed client, bind encoding error,
+ * {@link QwpConstants#STATUS_QUERY_TIMEOUT}, etc.). Failures detected client-side (closed client, bind encoding error,
* truncated / unknown frame, decoder out of sync, I/O thread interrupt) all
* surface with {@link WebSocketResponse#STATUS_INTERNAL_ERROR} and the
* specific cause in the message.
@@ -169,6 +181,9 @@ public class QwpQueryClient implements QuietCloseable {
| QwpEgressMsgKind.QUERY_FLAG_COUNT_ROWS
| QwpEgressMsgKind.QUERY_FLAG_SKIP_ROWS
| QwpEgressMsgKind.QUERY_FLAG_MAX_ROWS;
+ // How often an interrupted execute() checks whether the I/O thread has
+ // encoded its request (see retractRequest).
+ private static final long REQUEST_ENCODED_POLL_NANOS = TimeUnit.MICROSECONDS.toNanos(100);
// query_flags bits of the row window, which change what the server streams
private static final int ROW_WINDOW_QUERY_FLAGS = QwpEgressMsgKind.QUERY_FLAG_SKIP_ROWS
| QwpEgressMsgKind.QUERY_FLAG_MAX_ROWS;
@@ -299,6 +314,11 @@ public class QwpQueryClient implements QuietCloseable {
// re-clamp) so a misconfigured server is observable from user code.
private int negotiatedZstdLevel;
private long nextRequestId = 1;
+ // Default per-query timeout, in milliseconds, applied by the execute()
+ // overloads that take no explicit timeout. 0 (the default) sends none, so the
+ // server's own query.timeout applies. Set via query_timeout_ms or
+ // withQueryTimeout(); read once per execute().
+ private volatile long queryTimeoutMs;
// Cancel intent latched between {@link #cancel} and the point where
// {@link #executeOnce} assigns {@link #currentRequestId}. Without this
// latch, a cancel arriving in the dispatch window (after the user thread's
@@ -375,6 +395,10 @@ private QwpQueryClient(String host, int port) {
* {@link #execute}, reconnect to another endpoint and re-submit the query.
* The user handler sees {@link QwpColumnBatchHandler#onFailoverReset} before
* replayed batches begin arriving (batch_seq restarts at 0 on the new node).
+ *
+ * The timeout overrides the server's default query timeout
+ * ({@code query.timeout}) for this query. When the server advertises
+ * {@link QwpEgressMsgKind#CAP_QUERY_TIMEOUT}, the timeout travels with the
+ * query, and every failover replay sends it again. The server stops the
+ * query when it can and ends it with a {@code QUERY_ERROR} carrying
+ * {@link QwpConstants#STATUS_QUERY_TIMEOUT}; the connection stays open for
+ * the next query. Some statements cannot be stopped and run to completion.
+ * An older server never receives the timeout and applies its own default.
+ *
+ * The client does not enforce the timeout: this call waits for the server's
+ * answer however long it takes. Use {@link #cancel()} to stop a query from
+ * the client side.
+ *
+ * @param timeoutMs query timeout in milliseconds; {@code 0} sends none, so
+ * the server's default applies
+ * @throws IllegalArgumentException when {@code timeoutMs} is negative
+ */
+ public void execute(
+ CharSequence sql,
+ QwpBindSetter binds,
+ QwpColumnBatchHandler handler,
+ boolean resetSymbolDict,
+ long timeoutMs
+ ) {
+ executeExclusive(sql, binds, handler, resetSymbolDict ? QwpEgressMsgKind.QUERY_FLAG_RESET_DICT : 0, 0, Long.MAX_VALUE, timeoutMs);
}
/**
@@ -839,10 +899,30 @@ public void execute(CharSequence sql, QwpBindSetter binds, QwpColumnBatchHandler
* new server again.
*/
public void execute(CharSequence sql, QwpBindSetter binds, QwpColumnBatchHandler handler, QwpQueryOptions options) {
+ execute(sql, binds, handler, options, queryTimeoutMs);
+ }
+
+ /**
+ * As {@link #execute(CharSequence, QwpBindSetter, QwpColumnBatchHandler, QwpQueryOptions)},
+ * with an explicit query timeout that overrides the client default. See
+ * {@link #execute(CharSequence, QwpBindSetter, QwpColumnBatchHandler, boolean, long)}
+ * for how the timeout works.
+ *
+ * @param timeoutMs query timeout in milliseconds; {@code 0} sends none, so
+ * the server's default applies
+ * @throws IllegalArgumentException when {@code timeoutMs} is negative
+ */
+ public void execute(
+ CharSequence sql,
+ QwpBindSetter binds,
+ QwpColumnBatchHandler handler,
+ QwpQueryOptions options,
+ long timeoutMs
+ ) {
if (options == null) {
- executeExclusive(sql, binds, handler, 0, 0, Long.MAX_VALUE);
+ executeExclusive(sql, binds, handler, 0, 0, Long.MAX_VALUE, timeoutMs);
} else {
- executeExclusive(sql, binds, handler, options.toQueryFlags(), options.getSkipRows(), options.getMaxRows());
+ executeExclusive(sql, binds, handler, options.toQueryFlags(), options.getSkipRows(), options.getMaxRows(), timeoutMs);
}
}
@@ -887,6 +967,7 @@ public java.util.Map
+ * Runs on the executing thread, the sole consumer of the event queue, and
+ * keeps releasing every batch the I/O thread still publishes while it winds
+ * down: the I/O thread waits uninterruptibly for each published batch to be
+ * released, and would otherwise outlive the joins in {@link #close()} and
+ * {@link #cleanupFailedConnect()}.
+ */
+ private void abandonConnection(QwpEgressIoThread io, String failureMessage) {
+ GenerationListener listener = currentGenerationListener;
+ if (listener != null) {
+ listener.onTerminalFailure(WebSocketResponse.STATUS_INTERNAL_ERROR, failureMessage);
+ }
+ io.shutdown();
+ Thread handle = ioThreadHandle;
+ if (handle == null) {
+ return;
+ }
+ handle.interrupt();
+ final long stopDeadlineNanos = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(shutdownJoinMs);
+ boolean interrupted = false;
+ while (handle.isAlive() && !isPast(stopDeadlineNanos)) {
+ long pollDeadlineNanos = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(10);
+ if (pollDeadlineNanos - stopDeadlineNanos > 0) {
+ pollDeadlineNanos = stopDeadlineNanos;
+ }
+ QueryEvent ev;
+ try {
+ ev = io.takeEvent(pollDeadlineNanos);
+ } catch (InterruptedException e) {
+ // Finish stopping the I/O thread first; the flag is restored below.
+ interrupted = true;
+ continue;
+ }
+ if (ev != null) {
+ discardEvent(io, ev);
+ }
+ }
+ if (interrupted) {
+ Thread.currentThread().interrupt();
+ }
+ }
+
private static TokenProviderSpec validateConfigAndResolveTokenProvider(ConfigView view, boolean tls) {
view.getHostPorts("addr", DEFAULT_WS_PORT, (h, p) -> {
});
@@ -1480,6 +1671,7 @@ private static TokenProviderSpec validateConfigAndResolveTokenProvider(ConfigVie
long backoffMax = view.getLong("failover_backoff_max_ms", -1);
view.getLong("failover_max_duration_ms", -1);
view.getLong("initial_credit", -1);
+ view.getLong("query_timeout_ms", -1);
view.getLong("auth_timeout_ms", -1);
// getInt: connect_timeout feeds an int API, so validation must also
// reject values that fit a long but not an int.
@@ -1801,8 +1993,12 @@ private void executeExclusive(
QwpColumnBatchHandler handler,
long queryFlags,
long skipRows,
- long maxRows
+ long maxRows,
+ long timeoutMs
) {
+ if (timeoutMs < 0) {
+ throw new IllegalArgumentException("timeoutMs must be >= 0");
+ }
if (!executing.compareAndSet(false, true)) {
throw new IllegalStateException(
"QwpQueryClient.execute called while another execute is in flight; one query at a time per client");
@@ -1814,7 +2010,7 @@ private void executeExclusive(
// is intentionally NOT cleared inside executeOnce().
pendingCancel = false;
try {
- executeImpl(sql, binds, handler, queryFlags, skipRows, maxRows);
+ executeImpl(sql, binds, handler, queryFlags, skipRows, maxRows, timeoutMs);
} finally {
executing.set(false);
}
@@ -1826,7 +2022,8 @@ private void executeImpl(
QwpColumnBatchHandler handler,
long queryFlags,
long skipRows,
- long maxRows
+ long maxRows,
+ long timeoutMs
) {
if (closedFlag.get() || isShutdownRequested) {
throw new IllegalStateException("QwpQueryClient is closed");
@@ -1868,7 +2065,14 @@ private void executeImpl(
}
attempt++;
FailoverProbeHandler probe = new FailoverProbeHandler(handler);
- executeOnce(sql, binds, probe, queryFlags, skipRows, maxRows);
+ executeOnce(sql, binds, probe, queryFlags, skipRows, maxRows, timeoutMs);
+ // An interrupted attempt can end without a failover after giving up on a stuck I/O thread.
+ if (probe.transportFailureIntercepted || hasTerminalFailure()) {
+ healthTracker.connectionLost();
+ if (!failoverEnabled || failoverMaxAttempts <= 1) {
+ healthTracker.failed();
+ }
+ }
if (!probe.transportFailureIntercepted) {
return;
}
@@ -1882,19 +2086,10 @@ private void executeImpl(
}
if (!failoverEnabled) {
// With failover off the transport failure stays latched: every later execute() reports it.
- healthTracker.connectionLost();
- healthTracker.failed();
deliverClientError(handler, probe.interceptedRequestId, probe.interceptedStatus, probe.interceptedMessage);
return;
}
if (attempt >= failoverMaxAttempts || System.nanoTime() - failoverDeadlineNanos >= 0) {
- // The connection is dead: its generation latched the transport failure, so no later query runs on
- // it. Record the loss, as the exits below do. With a single attempt per execute(), every later
- // execute() ends here on that same latch and never reconnects: terminal, as with failover off.
- healthTracker.connectionLost();
- if (failoverMaxAttempts <= 1) {
- healthTracker.failed();
- }
int failovers = Math.max(0, attempt - 1);
deliverClientError(handler, probe.interceptedRequestId, probe.interceptedStatus,
"transport failure after " + attempt + " execute attempt"
@@ -1910,7 +2105,6 @@ private void executeImpl(
}
cleanupFailedConnect();
connected = false;
- healthTracker.connectionLost();
// Every exit from here on - an exhausted deadline, an interrupted backoff, a failed reconnect - leaves
// the client disconnected; the next execute() reconnects rather than throw "not connected".
isReconnectOnNextExecute = true;
@@ -2003,6 +2197,19 @@ private void executeImpl(
* Inner loop for a single query attempt. Driven by {@link #execute}; wraps
* the user's handler in a {@link FailoverProbeHandler} so that the outer
* loop can intercept transport failures before they reach the user.
+ *
+ * A timeout ({@code timeoutMs > 0}) only goes on the wire, to a server that
+ * advertises {@link QwpEgressMsgKind#CAP_QUERY_TIMEOUT}. The attempt keeps
+ * no deadline of its own and waits for the query's last frame.
+ *
+ * An attempt that ends before its query's last frame -- the handler threw
+ * from {@code onBatch}, or the thread was interrupted -- leaves the query
+ * running on the connection, and cancels it. The I/O thread still works
+ * through it before it sends the next query, so the next attempt skips the
+ * leftover events: each event carries the id of its query (see
+ * {@link QueryEvent#requestId}). An interrupt that comes before the I/O
+ * thread has encoded the request takes the request back, or waits for the
+ * encoding, before the caller hears about it (see {@link #retractRequest}).
*/
private void executeOnce(
CharSequence sql,
@@ -2010,7 +2217,8 @@ private void executeOnce(
FailoverProbeHandler probe,
long queryFlags,
long skipRows,
- long maxRows
+ long maxRows,
+ long timeoutMs
) {
// Cache the I/O thread reference at entry: close() may null the field while
// we are inside this loop, so reading the field per-iteration would NPE
@@ -2034,7 +2242,13 @@ private void executeOnce(
// could clear it, and then no flag goes out.
final QwpServerInfo info = serverInfo;
final int capabilities = info != null ? info.getCapabilities() : 0;
- final long wireQueryFlags = resolveQueryFlags(queryFlags, capabilities);
+ // A server without CAP_QUERY_TIMEOUT never sees the timeout and applies
+ // its own default (see resolveQueryFlags).
+ final long requestedQueryFlags = timeoutMs > 0
+ ? queryFlags | QwpEgressMsgKind.QUERY_FLAG_TIMEOUT
+ : queryFlags & ~QwpEgressMsgKind.QUERY_FLAG_TIMEOUT;
+ final long wireQueryFlags = resolveQueryFlags(requestedQueryFlags, capabilities);
+ final long wireTimeoutMs = (wireQueryFlags & QwpEgressMsgKind.QUERY_FLAG_TIMEOUT) != 0 ? timeoutMs : 0L;
if ((wireQueryFlags & ROW_WINDOW_QUERY_FLAGS) != (queryFlags & ROW_WINDOW_QUERY_FLAGS)) {
// A server that does not know the row window would stream every
// row of the result set. Like a bind error, this is deterministic
@@ -2073,12 +2287,28 @@ private void executeOnce(
if (pendingCancel) {
io.requestCancel(requestId);
}
+ boolean submitted = false;
+ // Set once the attempt has taken its query's last event, or given up on
+ // the connection: the query no longer runs on it.
+ boolean settled = false;
try {
io.submitQuery(sql, requestId, initialCreditBytes, bindValues.count(), bindValues.bufferPtr(), bindValues.bufferLen(),
- wireQueryFlags, skipRows, maxRows);
+ wireQueryFlags, wireTimeoutMs, skipRows, maxRows);
+ submitted = true;
boolean isBatchSkipped = false;
while (true) {
QueryEvent ev = io.takeEvent();
+ if (ev.isForOtherRequest(requestId)) {
+ // A leftover of an earlier query whose attempt ended before that
+ // query did. Not this query's; skip it.
+ discardEvent(io, ev);
+ continue;
+ }
+ if (ev.kind != QueryEvent.KIND_BATCH) {
+ // Every other event ends the query on the connection, and the
+ // attempt returns once the switch below handles it.
+ settled = true;
+ }
try {
switch (ev.kind) {
case QueryEvent.KIND_BATCH:
@@ -2107,6 +2337,7 @@ private void executeOnce(
probe.onExecDone(requestId, ev.opType, ev.rowsAffected, ev.details);
return;
case QueryEvent.KIND_ERROR:
+ // Includes the server's own STATUS_QUERY_TIMEOUT report.
probe.onError(requestId, ev.errorStatus, ev.errorMessage, ev.errorPosition);
return;
case QueryEvent.KIND_TRANSPORT_ERROR:
@@ -2128,9 +2359,20 @@ private void executeOnce(
}
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
+ // Before the caller hears about the interrupt: the I/O thread must be
+ // done with the request (see retractRequest).
+ if (submitted && !io.isRequestEncoded(requestId) && retractRequest(io, requestId)) {
+ settled = true;
+ }
// Interrupt on the user thread is not a transport failure; surface directly.
probe.deliverFinal(requestId, "interrupted while waiting for server response");
} finally {
+ if (submitted && !settled) {
+ // The attempt ends while its query still runs: the handler threw,
+ // or the thread was interrupted. Cancel the query, so the leftovers
+ // the next attempt skips stop coming.
+ io.requestCancel(requestId);
+ }
currentRequestId = -1L;
}
}
@@ -2359,6 +2601,54 @@ private String resolveAuthorizationHeader() {
return authorizationHeader;
}
+ /**
+ * Makes sure the I/O thread no longer reads the request {@code requestId},
+ * which an interrupted {@code execute()} stops waiting for before the I/O
+ * thread has encoded it. Until then the I/O thread reads the caller's SQL
+ * text, which the caller may change once it learns about the interrupt, and
+ * this client's request holder and bind buffer, which the next query reuses.
+ *
+ * A request the I/O thread has not picked up yet is withdrawn: it is never
+ * sent. One it has picked up is awaited -- encoding is CPU work, done
+ * microseconds after the pick-up -- without regard to interrupts. An I/O
+ * thread that is still not done after {@link #shutdownJoinMs} is stuck, and
+ * the connection is given up.
+ *
+ * @return {@code true} when the query does not run on the connection: it was
+ * withdrawn, or the connection was given up
+ */
+ private boolean retractRequest(QwpEgressIoThread io, long requestId) {
+ if (io.withdrawRequest(requestId)) {
+ return true;
+ }
+ final Thread handle = ioThreadHandle;
+ // parkNanos() returns at once while the interrupt flag is set, so clear it
+ // for the wait, and restore it after.
+ boolean interrupted = Thread.interrupted();
+ try {
+ final long deadlineNanos = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(shutdownJoinMs);
+ while (!io.isRequestEncoded(requestId)) {
+ if (handle == null || !handle.isAlive()) {
+ // A stopped I/O thread reads nothing more.
+ return true;
+ }
+ if (isPast(deadlineNanos)) {
+ LOG.warn("QwpQueryClient I/O thread did not finish sending an interrupted query within {}ms; "
+ + "closing the connection", shutdownJoinMs);
+ abandonConnection(io, "I/O thread stopped responding");
+ return true;
+ }
+ LockSupport.parkNanos(REQUEST_ENCODED_POLL_NANOS);
+ interrupted |= Thread.interrupted();
+ }
+ return false;
+ } finally {
+ if (interrupted) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
+
private void runUpgradeWithTimeout(Endpoint ep, String authHeader) {
// Connect first, OUTSIDE the upgrade try. A connect-phase failure --
// including a connect_timeout overage flagged via flagAsTimeout() -- must
@@ -2531,6 +2821,7 @@ void markTransportFailure(long requestId, byte status, String message) {
interceptedStatus = status;
interceptedMessage = message;
}
+
}
/**
diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpSpscQueue.java b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpSpscQueue.java
index c5c292d32..f8fb6c3a7 100644
--- a/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpSpscQueue.java
+++ b/core/src/main/java/io/questdb/client/cutlass/qwp/client/QwpSpscQueue.java
@@ -146,4 +146,47 @@ public T take() throws InterruptedException {
consumerThread = null;
}
}
+
+ /**
+ * Spin-then-park take bounded by an absolute {@link System#nanoTime()}
+ * deadline. Returns the next value, or {@code null} once the deadline has
+ * passed with the ring still empty. A deadline already in the past
+ * degenerates to a single {@link #poll()}: a value that is already
+ * available is still returned. Allocation-free, like {@link #take()}.
+ *
+ * @throws InterruptedException when the consumer thread was interrupted
+ * while waiting
+ */
+ public T take(long deadlineNanos) throws InterruptedException {
+ T value = poll();
+ if (value != null) {
+ return value;
+ }
+ if (deadlineNanos - System.nanoTime() <= 0) {
+ return null;
+ }
+ for (int i = 0; i < SPIN_ITERATIONS; i++) {
+ Compat.onSpinWait();
+ if ((value = poll()) != null) {
+ return value;
+ }
+ }
+ // Same publish-then-re-poll handshake as take(); see the comment there.
+ consumerThread = Thread.currentThread();
+ try {
+ while ((value = poll()) == null) {
+ if (Thread.interrupted()) {
+ throw new InterruptedException();
+ }
+ final long remainingNanos = deadlineNanos - System.nanoTime();
+ if (remainingNanos <= 0) {
+ return null;
+ }
+ LockSupport.parkNanos(remainingNanos);
+ }
+ return value;
+ } finally {
+ consumerThread = null;
+ }
+ }
}
diff --git a/core/src/main/java/io/questdb/client/cutlass/qwp/protocol/QwpConstants.java b/core/src/main/java/io/questdb/client/cutlass/qwp/protocol/QwpConstants.java
index 0fa7a6455..8c0794148 100644
--- a/core/src/main/java/io/questdb/client/cutlass/qwp/protocol/QwpConstants.java
+++ b/core/src/main/java/io/questdb/client/cutlass/qwp/protocol/QwpConstants.java
@@ -121,6 +121,15 @@ public final class QwpConstants {
* the ingress {@code STATUS_*} namespace (0x00-0x09).
*/
public static final byte STATUS_LIMIT_EXCEEDED = 0x0B;
+ /**
+ * Status byte on a {@code QUERY_ERROR} frame: the query ran past its
+ * per-query timeout. Sent by a server that enforces the timeout carried on
+ * {@code QUERY_REQUEST} (see {@code QwpEgressMsgKind#CAP_QUERY_TIMEOUT}).
+ * The connection stays usable for the next query. Egress extension of the
+ * ingress {@code STATUS_*} namespace; the next free value after
+ * {@code STATUS_DICTIONARY_GAP} (0x0D).
+ */
+ public static final byte STATUS_QUERY_TIMEOUT = 0x0E;
/**
* Column type: BINARY (length-prefixed opaque bytes).
* Wire format: identical to VARCHAR — (N+1) x uint32 offsets + concatenated bytes.
diff --git a/core/src/main/java/io/questdb/client/impl/ConfigSchema.java b/core/src/main/java/io/questdb/client/impl/ConfigSchema.java
index 79830ece0..1f692eb86 100644
--- a/core/src/main/java/io/questdb/client/impl/ConfigSchema.java
+++ b/core/src/main/java/io/questdb/client/impl/ConfigSchema.java
@@ -115,6 +115,7 @@ public final class ConfigSchema {
longRange("failover_max_duration_ms", Side.EGRESS, 0, OPEN_MAX, false, false); // >= 0
intRange("max_batch_rows", Side.EGRESS, 1, 1_048_576, false, false); // [1, 1048576]
longRange("initial_credit", Side.EGRESS, 0, OPEN_MAX, false, false); // >= 0
+ longRange("query_timeout_ms", Side.EGRESS, 0, OPEN_MAX, false, false); // >= 0; 0 = no timeout
intRange("buffer_pool_size", Side.EGRESS, 1, OPEN_MAX, false, false); // >= 1
enumKey("compression", Side.EGRESS, "zstd", "raw", "auto");
intRange("compression_level", Side.EGRESS, 1, 22, false, false); // [1, 22]
diff --git a/core/src/main/java/io/questdb/client/impl/QueryImpl.java b/core/src/main/java/io/questdb/client/impl/QueryImpl.java
index 54b8c12af..fb6b27e0f 100644
--- a/core/src/main/java/io/questdb/client/impl/QueryImpl.java
+++ b/core/src/main/java/io/questdb/client/impl/QueryImpl.java
@@ -84,10 +84,26 @@ final class QueryImpl {
private final QueryWorker worker;
private final QwpBindSetter wireBinds = this::applyBinds;
private final WrappingHandler wrappingHandler = new WrappingHandler();
+ // Set when this lease cancels its current submission; cleared by submit().
+ // applyBinds() re-applies it from inside execute(), so a cancel issued while
+ // the submission still waits for the worker is not lost. See requestCancel().
+ private volatile boolean cancelRequested;
private volatile boolean done = true;
private volatile String resultMessage;
private volatile int resultPosition = QwpEgressMsgKind.NO_ERROR_POSITION;
private volatile byte resultStatus;
+ // Counts submit() calls. Written under doneLock; volatile so runOn() can read
+ // it without the lock. Lets runOn() tell its own submission from a later one,
+ // see signalUnexpected(long, Throwable).
+ private volatile long submissionSeq;
+ // Stamped by submit() for the worker thread: the timeout the query sends to
+ // the server (0 = none, the server's default applies). Published by
+ // worker.dispatch().
+ private long submitTimeoutMillis;
+ // Query timeout set on this handle, in milliseconds: -1 = the pooled client's
+ // default (query_timeout_ms), 0 = none. Kept across submits like the other
+ // builder state; abandon() and resetForBorrow() restore -1.
+ private long timeoutMillis = -1;
private volatile Throwable unexpectedError;
private QwpBindSetter userBinds;
private QwpColumnBatchHandler userHandler;
@@ -106,6 +122,7 @@ void abandon(long gen) {
userHandler = null;
options.clear();
sqlBuffer.clear();
+ timeoutMillis = -1;
}
void await(long gen) throws InterruptedException {
@@ -189,6 +206,12 @@ void close(long gen) {
return;
}
}
+ // A connection that failed -- the server closed it, or the client gave
+ // up on a stuck I/O thread -- must not go back to the pool.
+ if (worker.client().hasTerminalFailure()) {
+ worker.discardFromPool(gen);
+ return;
+ }
worker.releaseToPool(gen);
}
@@ -232,6 +255,29 @@ void setSql(long gen, CharSequence sql) {
sqlBuffer.put(sql);
}
+ /**
+ * Records that the current submission was cancelled. Called by
+ * {@link QueryWorker#cancelInFlight()} under the pool lock, after the lease
+ * generation was validated, so a stale handle cannot mark a later borrower's
+ * query. Needed because {@code execute()} starts by clearing the client's
+ * cancel latch: a cancel that lands while the submission still waits for the
+ * worker -- for instance while the worker thread is still returning from the
+ * previous query's {@code runOn()} -- would otherwise be dropped.
+ */
+ void requestCancel() {
+ cancelRequested = true;
+ }
+
+ void setTimeout(long gen, long timeout, TimeUnit unit) {
+ checkLive(gen);
+ if (timeout < 0) {
+ throw new IllegalArgumentException("timeout must be >= 0");
+ }
+ long millis = unit.toMillis(timeout);
+ // A positive timeout below one millisecond must not round down to "none".
+ this.timeoutMillis = millis == 0 && timeout > 0 ? 1 : millis;
+ }
+
void submit(long gen) {
checkLive(gen);
if (sqlBuffer.length() == 0) {
@@ -243,11 +289,14 @@ void submit(long gen) {
if (!done) {
throw new IllegalStateException("a previous submit() is still in flight; await the Completion first");
}
+ submitTimeoutMillis = timeoutMillis >= 0 ? timeoutMillis : worker.client().getQueryTimeoutMs();
+ cancelRequested = false;
// Reset terminal state under the lock so a stale signal from a prior
// run can't be observed by the upcoming await().
doneLock.lock();
try {
done = false;
+ submissionSeq++;
resultStatus = 0;
resultMessage = null;
resultPosition = QwpEgressMsgKind.NO_ERROR_POSITION;
@@ -259,7 +308,19 @@ void submit(long gen) {
worker.dispatch(this);
}
+ private static String describe(Throwable t) {
+ String message = t.getMessage();
+ return message != null ? message : t.getClass().getSimpleName();
+ }
+
private void applyBinds(QwpBindValues binds) {
+ // Runs inside execute() after it cleared the client's cancel latch for
+ // this query, and before the request is sent: set the latch again if the
+ // lease cancelled the submission meanwhile, so the query goes out with
+ // its CANCEL right behind it.
+ if (cancelRequested) {
+ worker.client().cancel();
+ }
QwpBindSetter setter = userBinds;
if (setter != null) {
setter.apply(binds);
@@ -337,6 +398,29 @@ private void signalDone(byte status, String message, int position, Throwable une
}
}
+ /**
+ * Signals an error that escaped the run of {@code submission}, unless a later
+ * {@link #submit} has taken that submission's place. A run can end with an
+ * exception after it signalled its outcome: when a terminal handler callback
+ * throws, {@link WrappingHandler} signals the outcome before the exception
+ * leaves {@code execute()}, and the caller, already released, may have
+ * submitted again meanwhile. That exception must not become the newer submission's outcome.
+ * The check and the signal share {@code doneLock}, which {@code submit()}
+ * takes to start a submission.
+ */
+ private void signalUnexpected(long submission, Throwable t) {
+ // getMessage() may be user code: run it before taking the lock submit() needs.
+ final String message = describe(t);
+ doneLock.lock();
+ try {
+ if (submission == submissionSeq) {
+ signalDone((byte) 0, message, t);
+ }
+ } finally {
+ doneLock.unlock();
+ }
+ }
+
private void throwIfFailed() {
Throwable unexpected = unexpectedError;
if (unexpected != null) {
@@ -352,14 +436,18 @@ private void throwIfFailed() {
* {@link QueryWorker#lease()} when {@link QuestDBImpl#borrowQuery()} hands a
* freshly stamped {@link QueryLease} out, so each borrow starts from the
* documented "reset to empty" contract on {@link io.questdb.client.Query}.
- * The leased worker is idle at this point (just acquired from the pool), so
- * the reset is unconditional.
+ * The reset is unconditional: the worker was just acquired from the pool, so
+ * its previous job, if any, is past its terminal callback and can no longer
+ * change this state -- even while the worker thread is still returning from
+ * that job's {@code runOn()}.
*/
void resetForBorrow() {
userBinds = null;
userHandler = null;
options.clear();
sqlBuffer.clear();
+ timeoutMillis = -1;
+ cancelRequested = false;
resultStatus = 0;
resultMessage = null;
resultPosition = QwpEgressMsgKind.NO_ERROR_POSITION;
@@ -368,15 +456,22 @@ void resetForBorrow() {
}
void runOn(QwpQueryClient client) {
+ // The submission this run executes. No later submit() can happen before
+ // the run signals this one's outcome, so the value is stable until then.
+ final long submission = submissionSeq;
// Pass the StringSink directly as a CharSequence -- the wire encoder
// reads chars and writes UTF-8 bytes straight into the send buffer.
// The query reads sqlBuffer, the binds and the handler while it runs;
// the Query contract tells the caller not to change them before
- // await() returns, but nothing enforces it. The options come from
- // submittedOptions instead, which submit() filled: execute() reads them
- // once, when it starts, and options() may change the handle's options
- // for the next query meanwhile.
- client.execute(sqlBuffer, wireBinds, wrappingHandler, submittedOptions);
+ // await() returns, but nothing enforces it. The options come from submittedOptions
+ // instead, which submit() filled: execute() reads them once, when it
+ // starts, and options() may change the handle's options for the next
+ // query meanwhile.
+ try {
+ client.execute(sqlBuffer, wireBinds, wrappingHandler, submittedOptions, submitTimeoutMillis);
+ } catch (Throwable t) {
+ signalUnexpected(submission, t);
+ }
}
/**
@@ -384,7 +479,7 @@ void runOn(QwpQueryClient client) {
* exception escaping {@code execute()} before any handler callback).
*/
void signalUnexpected(Throwable t) {
- signalDone((byte) 0, t.getMessage() != null ? t.getMessage() : t.getClass().getSimpleName(), t);
+ signalDone((byte) 0, describe(t), t);
}
private final class WrappingHandler implements QwpColumnBatchHandler {
diff --git a/core/src/main/java/io/questdb/client/impl/QueryLease.java b/core/src/main/java/io/questdb/client/impl/QueryLease.java
index 398596c40..d0ece91bc 100644
--- a/core/src/main/java/io/questdb/client/impl/QueryLease.java
+++ b/core/src/main/java/io/questdb/client/impl/QueryLease.java
@@ -120,4 +120,10 @@ public Completion submit() {
public QwpServerInfo serverInfo() {
return impl.serverInfo(generation);
}
+
+ @Override
+ public Query timeout(long timeout, TimeUnit unit) {
+ impl.setTimeout(generation, timeout, unit);
+ return this;
+ }
}
diff --git a/core/src/main/java/io/questdb/client/impl/QueryWorker.java b/core/src/main/java/io/questdb/client/impl/QueryWorker.java
index 4a8608f67..80162ed81 100644
--- a/core/src/main/java/io/questdb/client/impl/QueryWorker.java
+++ b/core/src/main/java/io/questdb/client/impl/QueryWorker.java
@@ -153,6 +153,10 @@ void markIdleAt(long nowMillis) {
* generation first. Lease code must use {@link #cancelInFlight(long)}.
*/
void cancelInFlight() {
+ // Remembered on the lease too: a submission still waiting for this worker
+ // (its thread still returning from the previous job) has not reached the
+ // client yet.
+ query.requestCancel();
try {
client.cancel();
} catch (RuntimeException ignored) {
diff --git a/core/src/test/java/io/questdb/client/test/QueryTimeoutFacadeTest.java b/core/src/test/java/io/questdb/client/test/QueryTimeoutFacadeTest.java
new file mode 100644
index 000000000..cbd7cabad
--- /dev/null
+++ b/core/src/test/java/io/questdb/client/test/QueryTimeoutFacadeTest.java
@@ -0,0 +1,576 @@
+/*+*****************************************************************************
+ * ___ _ ____ ____
+ * / _ \ _ _ ___ ___| |_| _ \| __ )
+ * | | | | | | |/ _ \/ __| __| | | | _ \
+ * | |_| | |_| | __/\__ \ |_| |_| | |_) |
+ * \__\_\\__,_|\___||___/\__|____/|____/
+ *
+ * Copyright (c) 2014-2019 Appsicle
+ * Copyright (c) 2019-2026 QuestDB
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************************/
+
+
+package io.questdb.client.test;
+
+import io.questdb.client.Completion;
+import io.questdb.client.Query;
+import io.questdb.client.QueryException;
+import io.questdb.client.QuestDB;
+import io.questdb.client.cutlass.qwp.client.QwpColumnBatch;
+import io.questdb.client.cutlass.qwp.client.QwpColumnBatchHandler;
+import io.questdb.client.cutlass.qwp.client.QwpEgressMsgKind;
+import io.questdb.client.cutlass.qwp.protocol.QwpConstants;
+import io.questdb.client.impl.QuestDBImpl;
+import io.questdb.client.test.cutlass.qwp.client.QwpEgressFrames;
+import io.questdb.client.test.cutlass.qwp.websocket.TestWebSocketServer;
+import io.questdb.client.test.tools.TestUtils;
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * {@link Query#timeout} through the {@link QuestDB} facade: the timeout goes to
+ * the server as an override of its default, and the client keeps no deadline of
+ * its own. A query the server stops is reported as a {@link QueryException}
+ * whose {@link QueryException#isTimeout()} holds, however late the server
+ * reports it, while the pooled, authenticated connection stays open and serves
+ * the following queries. A worker whose connection failed is replaced rather
+ * than reused, while one whose query has ended goes back to the pool at once --
+ * even when close() has no budget or the caller's interrupt flag is set. A
+ * handler that throws -- on the timeout, or mid-result -- fails only its own
+ * submission.
+ */
+public class QueryTimeoutFacadeTest {
+
+ @Test(timeout = 30_000)
+ public void testAbandonRestoresTheDefaultTimeout() throws Exception {
+ TestUtils.assertMemoryLeak(() -> {
+ Script script = new Script();
+ script.onQuery = (s, c, id, n) -> s.send(c, QwpEgressFrames.resultEnd(id, 0, 0).toFrame());
+ try (TestWebSocketServer server = startServer(script, QwpEgressMsgKind.CAP_QUERY_FLAGS | QwpEgressMsgKind.CAP_QUERY_TIMEOUT);
+ QuestDB db = QuestDB.connect(config(server) + "query_timeout_ms=100;")) {
+ try (Query q = db.borrowQuery()) {
+ q.sql("SELECT a()").handler(new NoopHandler()).timeout(7, TimeUnit.MILLISECONDS);
+ q.abandon();
+ q.sql("SELECT b()").handler(new NoopHandler()).submit().await();
+ Assert.assertEquals("abandon() must drop the handle's timeout", 100L, (long) script.timeouts.take());
+ }
+ } finally {
+ script.close();
+ }
+ });
+ }
+
+ @Test(timeout = 30_000)
+ public void testAwaitWaitsForTheServerPastTheTimeout() throws Exception {
+ TestUtils.assertMemoryLeak(() -> {
+ final long timeoutMs = 100;
+ final long replyDelayMs = 1_500;
+ Script script = new Script();
+ script.onQuery = (s, c, id, n) -> {
+ if (n == 1) {
+ s.sendLater(c, replyDelayMs, QwpEgressFrames.queryError(id, QwpConstants.STATUS_QUERY_TIMEOUT,
+ "timeout, query aborted").toFrame());
+ } else {
+ s.send(c, QwpEgressFrames.execDone(id, 0, 0).toFrame());
+ }
+ };
+ // failover=off and a short close budget: a client that gave up on the
+ // slow query would fail every later query on this connection.
+ try (TestWebSocketServer server = startServer(script, QwpEgressMsgKind.CAP_QUERY_FLAGS | QwpEgressMsgKind.CAP_QUERY_TIMEOUT);
+ QuestDB db = QuestDB.connect(config(server) + "query_close_timeout_ms=200;failover=off;")) {
+ try (Query q = db.borrowQuery()) {
+ q.sql("SELECT slow()").handler(new NoopHandler()).timeout(timeoutMs, TimeUnit.MILLISECONDS);
+ long start = System.nanoTime();
+ QueryException e = assertTimesOut(q);
+ long awaitMs = elapsedMs(start);
+ Assert.assertEquals("timeout, query aborted", e.getMessage());
+ Assert.assertTrue("await() must wait for the server's report, returned after " + awaitMs + "ms",
+ awaitMs >= replyDelayMs);
+ }
+ try (Query q = db.borrowQuery()) {
+ q.sql("INSERT INTO t VALUES (1)").handler(new NoopHandler());
+ assertOwnOutcome(q);
+ }
+ Assert.assertEquals("a slow query must not cost the connection", 1, server.handshakeCount());
+ } finally {
+ script.close();
+ }
+ });
+ }
+
+ @Test(timeout = 30_000)
+ public void testCancelOfASubmissionWaitingForTheWorkerIsNotLost() throws Exception {
+ TestUtils.assertMemoryLeak(() -> {
+ Script script = new Script();
+ script.onQuery = (s, c, id, n) -> {
+ if (n == 1) {
+ s.send(c, QwpEgressFrames.resultEnd(id, 0, 0).toFrame());
+ }
+ // n == 2: held; only a CANCEL ends it
+ };
+ script.onCancel = (s, c, id) -> s.send(c,
+ QwpEgressFrames.queryError(id, QwpConstants.STATUS_CANCELLED, "cancelled by client").toFrame());
+ try (TestWebSocketServer server = startServer(script, QwpEgressMsgKind.CAP_QUERY_FLAGS | QwpEgressMsgKind.CAP_QUERY_TIMEOUT);
+ QuestDB db = QuestDB.connect(config(server));
+ Query q = db.borrowQuery()) {
+ // Park the worker thread once, after the first query, so the second
+ // submission waits for it and is cancelled before execute() starts.
+ CountDownLatch release = new CountDownLatch(1);
+ AtomicBoolean isParkPending = new AtomicBoolean(true);
+ ((QuestDBImpl) db).getQueryPoolForTesting().setBusyWorkerHookForTesting(() -> {
+ if (isParkPending.compareAndSet(true, false)) {
+ try {
+ release.await();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ });
+ q.sql("SELECT s FROM t").handler(new NoopHandler());
+ Completion waiting;
+ try {
+ q.submit().await();
+ waiting = q.submit();
+ waiting.cancel();
+ } finally {
+ release.countDown();
+ }
+ try {
+ Assert.assertTrue("the cancelled query must end", waiting.await(10, TimeUnit.SECONDS));
+ Assert.fail("the cancelled query must not complete");
+ } catch (QueryException e) {
+ Assert.assertEquals("the cancel must reach the query: " + e.getMessage(),
+ QwpConstants.STATUS_CANCELLED, e.getStatus());
+ }
+ } finally {
+ script.close();
+ }
+ });
+ }
+
+ @Test(timeout = 30_000)
+ public void testCloseWithoutBudgetKeepsTheConnectionOfCompletedQueries() throws Exception {
+ assertCloseKeepsTheConnectionOfCompletedQueries("query_close_timeout_ms=0;", false);
+ }
+
+ @Test(timeout = 30_000)
+ public void testConfiguredDefaultAppliesAndHandleCanOverrideIt() throws Exception {
+ TestUtils.assertMemoryLeak(() -> {
+ Script script = new Script();
+ script.onQuery = (s, c, id, n) -> s.send(c, QwpEgressFrames.resultEnd(id, 0, 0).toFrame());
+ try (TestWebSocketServer server = startServer(script, QwpEgressMsgKind.CAP_QUERY_FLAGS | QwpEgressMsgKind.CAP_QUERY_TIMEOUT);
+ QuestDB db = QuestDB.connect(config(server) + "query_timeout_ms=100;")) {
+ try (Query q = db.borrowQuery()) {
+ q.sql("SELECT 1").handler(new NoopHandler());
+ q.submit().await();
+ Assert.assertEquals("the configured default must go on the wire", 100L, (long) script.timeouts.take());
+
+ q.timeout(250, TimeUnit.MILLISECONDS).submit().await();
+ Assert.assertEquals("the handle's timeout must override the default", 250L, (long) script.timeouts.take());
+
+ q.timeout(1, TimeUnit.MICROSECONDS).submit().await();
+ Assert.assertEquals("a positive timeout below 1ms must not become none", 1L, (long) script.timeouts.take());
+
+ q.timeout(0, TimeUnit.MILLISECONDS).submit().await();
+ Assert.assertEquals("timeout 0 must send none, so the server's default applies",
+ -1L, (long) script.timeouts.take());
+ }
+ // A fresh borrow starts from the configured default again.
+ try (Query q = db.borrowQuery()) {
+ q.sql("SELECT 1").handler(new NoopHandler()).submit().await();
+ Assert.assertEquals(100L, (long) script.timeouts.take());
+ }
+ Assert.assertEquals("all queries must share one connection", 1, server.handshakeCount());
+ } finally {
+ script.close();
+ }
+ });
+ }
+
+ @Test(timeout = 30_000)
+ public void testInterruptedCloseKeepsTheConnectionOfCompletedQueries() throws Exception {
+ assertCloseKeepsTheConnectionOfCompletedQueries("", true);
+ }
+
+ @Test(timeout = 30_000)
+ public void testThrowingBatchHandlerFailsOnlyItsOwnSubmission() throws Exception {
+ TestUtils.assertMemoryLeak(() -> {
+ Script script = new Script();
+ script.onQuery = (s, c, id, n) -> {
+ if (n == 1) {
+ s.send(c, QwpEgressFrames.resultBatchOfLongs(id, 0, 1));
+ // The rest of the result arrives after the handler has thrown.
+ s.sendLater(c, 300, QwpEgressFrames.resultBatchOfLongs(id, 1, 2));
+ s.sendLater(c, 300, QwpEgressFrames.resultEnd(id, 1, 2).toFrame());
+ } else {
+ s.send(c, QwpEgressFrames.execDone(id, 0, 0).toFrame());
+ }
+ };
+ try (TestWebSocketServer server = startServer(script, QwpEgressMsgKind.CAP_QUERY_FLAGS | QwpEgressMsgKind.CAP_QUERY_TIMEOUT);
+ QuestDB db = QuestDB.connect(config(server));
+ Query q = db.borrowQuery()) {
+ final IllegalStateException failure = new IllegalStateException("handler failed");
+ q.sql("SELECT s FROM t").handler(new QwpColumnBatchHandler() {
+ @Override
+ public void onBatch(QwpColumnBatch batch) {
+ throw failure;
+ }
+
+ @Override
+ public void onEnd(long totalRows) {
+ }
+
+ @Override
+ public void onError(byte status, String message) {
+ }
+ });
+ try {
+ q.submit().await();
+ Assert.fail("the submission whose handler threw must fail");
+ } catch (QueryException e) {
+ Assert.assertSame("the handler's exception must be its own submission's outcome",
+ failure, e.getCause());
+ }
+
+ RecordingHandler next = new RecordingHandler();
+ q.sql("INSERT INTO t VALUES (1)").handler(next);
+ assertOwnOutcome(q);
+ Assert.assertTrue("the next submission must get its own reply", next.execDone);
+ Assert.assertEquals("the abandoned query's rows must not reach the next submission",
+ 0, next.batches.get());
+ Assert.assertEquals("the connection must be reused", 1, server.handshakeCount());
+ } finally {
+ script.close();
+ }
+ });
+ }
+
+ @Test(timeout = 30_000)
+ public void testThrowingHandlerLeavesTheNextSubmissionIntact() throws Exception {
+ TestUtils.assertMemoryLeak(() -> {
+ Script script = new Script();
+ script.onQuery = (s, c, id, n) -> {
+ if (n == 1) {
+ s.sendLater(c, 150, QwpEgressFrames.queryError(id, QwpConstants.STATUS_QUERY_TIMEOUT,
+ "timeout, query aborted").toFrame());
+ } else {
+ s.send(c, QwpEgressFrames.execDone(id, 0, 0).toFrame());
+ }
+ };
+ try (TestWebSocketServer server = startServer(script, QwpEgressMsgKind.CAP_QUERY_FLAGS | QwpEgressMsgKind.CAP_QUERY_TIMEOUT);
+ QuestDB db = QuestDB.connect(config(server))) {
+ try (Query q = db.borrowQuery()) {
+ q.sql("SELECT slow()").handler(new QwpColumnBatchHandler() {
+ @Override
+ public void onBatch(QwpColumnBatch batch) {
+ }
+
+ @Override
+ public void onEnd(long totalRows) {
+ }
+
+ @Override
+ public void onError(byte status, String message) {
+ throw new IllegalStateException("handler failed: " + message);
+ }
+ }).timeout(100, TimeUnit.MILLISECONDS);
+ // onError releases the caller before its exception leaves the
+ // worker's execute(), so the next submission can race that exception.
+ assertTimesOut(q);
+
+ q.sql("INSERT INTO t VALUES (1)").handler(new NoopHandler()).timeout(0, TimeUnit.MILLISECONDS);
+ assertOwnOutcome(q);
+ }
+ try (Query q = db.borrowQuery()) {
+ q.sql("INSERT INTO t VALUES (2)").handler(new NoopHandler());
+ assertOwnOutcome(q);
+ }
+ Assert.assertEquals("the connection must be reused", 1, server.handshakeCount());
+ } finally {
+ script.close();
+ }
+ });
+ }
+
+ @Test(timeout = 30_000)
+ public void testTimedOutQueryKeepsThePooledConnection() throws Exception {
+ TestUtils.assertMemoryLeak(() -> {
+ Script script = new Script();
+ script.onQuery = (s, c, id, n) -> {
+ if (n == 1) {
+ s.sendLater(c, 150, QwpEgressFrames.queryError(id, QwpConstants.STATUS_QUERY_TIMEOUT,
+ "timeout, query aborted [runtime=150ms, timeout=100ms]").toFrame());
+ } else {
+ s.send(c, QwpEgressFrames.execDone(id, 0, 0).toFrame());
+ }
+ };
+ try (TestWebSocketServer server = startServer(script, QwpEgressMsgKind.CAP_QUERY_FLAGS | QwpEgressMsgKind.CAP_QUERY_TIMEOUT);
+ QuestDB db = QuestDB.connect(config(server))) {
+ try (Query q = db.borrowQuery()) {
+ q.sql("SELECT slow()").handler(new NoopHandler()).timeout(100, TimeUnit.MILLISECONDS);
+ QueryException e = assertTimesOut(q);
+ Assert.assertTrue("the server's report must reach the caller: " + e.getMessage(),
+ e.getMessage().startsWith("timeout, query aborted"));
+
+ // The same handle, and so the same connection, runs the next query.
+ q.sql("INSERT INTO t VALUES (1)").submit().await();
+ }
+ try (Query q = db.borrowQuery()) {
+ q.sql("INSERT INTO t VALUES (2)").handler(new NoopHandler()).submit().await();
+ }
+ Assert.assertEquals("the authenticated connection must be kept across the timeout",
+ 1, server.handshakeCount());
+ } finally {
+ script.close();
+ }
+ });
+ }
+
+ @Test(timeout = 30_000)
+ public void testWorkerWhoseConnectionFailedIsReplaced() throws Exception {
+ TestUtils.assertMemoryLeak(() -> {
+ Script script = new Script();
+ script.onQuery = (s, c, id, n) -> {
+ if (n == 1) {
+ s.closeConnection(c);
+ } else {
+ s.send(c, QwpEgressFrames.execDone(id, 0, 0).toFrame());
+ }
+ };
+ // failover=off: the client cannot replace the connection by itself, so
+ // the next query succeeds only if the pool discarded the worker.
+ try (TestWebSocketServer server = startServer(script, QwpEgressMsgKind.CAP_QUERY_FLAGS | QwpEgressMsgKind.CAP_QUERY_TIMEOUT);
+ QuestDB db = QuestDB.connect(config(server) + "failover=off;")) {
+ try (Query q = db.borrowQuery()) {
+ q.sql("SELECT slow()").handler(new NoopHandler()).timeout(100, TimeUnit.MILLISECONDS);
+ try {
+ q.submit().await();
+ Assert.fail("the query must fail with its connection");
+ } catch (QueryException e) {
+ Assert.assertFalse("a failed connection is not a timeout: " + e.getMessage(), e.isTimeout());
+ }
+ }
+ try (Query q = db.borrowQuery()) {
+ q.sql("INSERT INTO t VALUES (1)").handler(new NoopHandler());
+ assertOwnOutcome(q);
+ }
+ Assert.assertEquals("the failed connection must be replaced by a new one", 2, server.handshakeCount());
+ } finally {
+ script.close();
+ }
+ });
+ }
+
+ /**
+ * The terminal callback releases the caller while the worker thread is
+ * still returning from the job, so close() regularly lands in that
+ * window. close() must return the worker there without waiting for the
+ * thread: with no budget, or with the caller's interrupt flag set, a wait
+ * would give up at once and discard a healthy worker, and each discard
+ * would show as one more connection. Hitting the window is a matter of
+ * timing, hence the 2,000 cycles.
+ */
+ private static void assertCloseKeepsTheConnectionOfCompletedQueries(
+ String extraConfig,
+ boolean interruptBeforeClose
+ ) throws Exception {
+ TestUtils.assertMemoryLeak(() -> {
+ Script script = new Script();
+ script.onQuery = (s, c, id, n) -> s.send(c, QwpEgressFrames.resultEnd(id, 0, 0).toFrame());
+ try (TestWebSocketServer server = startServer(script, QwpEgressMsgKind.CAP_QUERY_FLAGS | QwpEgressMsgKind.CAP_QUERY_TIMEOUT);
+ QuestDB db = QuestDB.connect(config(server) + extraConfig)) {
+ NoopHandler handler = new NoopHandler();
+ for (int i = 0; i < 2_000; i++) {
+ try (Query q = db.borrowQuery()) {
+ q.sql("SELECT 1").handler(handler).submit().await();
+ if (interruptBeforeClose) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ if (interruptBeforeClose) {
+ Assert.assertTrue("close() must preserve the caller's interrupt flag", Thread.interrupted());
+ }
+ }
+ Assert.assertEquals("closing a handle whose query has ended must keep its connection",
+ 1, server.handshakeCount());
+ } finally {
+ script.close();
+ }
+ });
+ }
+
+ private static void assertOwnOutcome(Query q) throws InterruptedException {
+ try {
+ q.submit().await();
+ } catch (QueryException e) {
+ Assert.fail("the submission must get its own outcome, got status=" + e.getStatus()
+ + ", message=" + e.getMessage() + ", cause=" + e.getCause());
+ }
+ }
+
+ private static QueryException assertTimesOut(Query q) throws InterruptedException {
+ try {
+ q.submit().await();
+ } catch (QueryException e) {
+ Assert.assertTrue("expected a query timeout, got status=" + e.getStatus() + ": " + e.getMessage(),
+ e.isTimeout());
+ return e;
+ }
+ Assert.fail("the query must time out");
+ return null;
+ }
+
+ private static String config(TestWebSocketServer server) {
+ return "ws::addr=localhost:" + server.getPort()
+ + ";auth_timeout_ms=2000;sender_pool_min=0;query_pool_min=1;query_pool_max=1;";
+ }
+
+ private static long elapsedMs(long startNanos) {
+ return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
+ }
+
+ private static TestWebSocketServer startServer(Script script, int capabilities) throws Exception {
+ TestWebSocketServer server = new TestWebSocketServer(script);
+ server.setSendServerInfo(true);
+ server.setCapabilities(capabilities);
+ server.start();
+ Assert.assertTrue(server.awaitStart(5, TimeUnit.SECONDS));
+ return server;
+ }
+
+ @FunctionalInterface
+ private interface OnCancel {
+ void run(Script script, TestWebSocketServer.ClientHandler client, long requestId);
+ }
+
+ @FunctionalInterface
+ private interface OnQuery {
+ void run(Script script, TestWebSocketServer.ClientHandler client, long requestId, int queryNumber);
+ }
+
+ private static final class NoopHandler implements QwpColumnBatchHandler {
+ @Override
+ public void onBatch(QwpColumnBatch batch) {
+ }
+
+ @Override
+ public void onEnd(long totalRows) {
+ }
+
+ @Override
+ public void onError(byte status, String message) {
+ }
+ }
+
+ private static final class RecordingHandler implements QwpColumnBatchHandler {
+ final AtomicInteger batches = new AtomicInteger();
+ volatile boolean execDone;
+
+ @Override
+ public void onBatch(QwpColumnBatch batch) {
+ batches.incrementAndGet();
+ }
+
+ @Override
+ public void onEnd(long totalRows) {
+ }
+
+ @Override
+ public void onError(byte status, String message) {
+ }
+
+ @Override
+ public void onExecDone(short opType, long rowsAffected) {
+ execDone = true;
+ }
+ }
+
+ /**
+ * Scripted egress server. Records the {@code timeout_ms} of every
+ * {@code QUERY_REQUEST} and answers queries and cancels as each test scripts.
+ */
+ private static final class Script implements TestWebSocketServer.WebSocketServerHandler, AutoCloseable {
+ // timeout_ms of each QUERY_REQUEST, in order; -1 when the request carries none.
+ final LinkedBlockingQueue
+ * The server-side enforcement (breaker timeout, status mapping) is covered
+ * against a live server in the questdb repository.
+ */
+public class QwpQueryClientQueryTimeoutTest {
+
+ private static final int CAPS_FLAGS_ONLY = QwpEgressMsgKind.CAP_QUERY_FLAGS;
+ private static final int CAPS_WITH_TIMEOUT = QwpEgressMsgKind.CAP_QUERY_FLAGS | QwpEgressMsgKind.CAP_QUERY_TIMEOUT;
+
+ @Test(timeout = 30_000)
+ public void testBatchesSentPastTheTimeoutReachTheHandler() throws Exception {
+ TestUtils.assertMemoryLeak(() -> {
+ ScriptedServer script = new ScriptedServer();
+ script.onQuery = (s, c, frame, n) -> {
+ long id = requestIdOf(frame);
+ if (n == 1) {
+ send(c, QwpEgressFrames.resultBatchOfLongs(id, 0, 1));
+ s.sendLater(c, 400,
+ QwpEgressFrames.resultBatchOfLongs(id, 1, 2),
+ QwpEgressFrames.resultBatchOfLongs(id, 2, 3),
+ QwpEgressFrames.queryError(id, QwpConstants.STATUS_QUERY_TIMEOUT,
+ "timeout, query aborted").toFrame());
+ } else {
+ send(c, QwpEgressFrames.resultBatchOfLongs(id, 0, 1));
+ send(c, QwpEgressFrames.resultEnd(id, 0, 1).toFrame());
+ }
+ };
+ try (TestWebSocketServer server = startServer(script, CAPS_WITH_TIMEOUT);
+ QwpQueryClient client = connect(server, "")) {
+ RecordingHandler h = new RecordingHandler();
+ client.execute("SELECT s FROM t", null, h, false, 150);
+ Assert.assertEquals("the client withholds no batch the server sends, however late",
+ 3, h.batches.get());
+ h.assertTimedOut();
+ Assert.assertEquals("timeout, query aborted", h.errorMessage);
+ Assert.assertTrue("the client must leave the timeout to the server", script.cancels.isEmpty());
+
+ RecordingHandler next = new RecordingHandler();
+ client.execute("SELECT s FROM t", null, next, false, 0);
+ Assert.assertTrue("the next query must complete on the same connection", next.ended);
+ Assert.assertEquals(1, next.batches.get());
+ Assert.assertEquals("the connection must be reused, not replaced", 1, server.handshakeCount());
+ } finally {
+ script.close();
+ }
+ });
+ }
+
+ @Test(timeout = 30_000)
+ public void testCancelOfAQueryQueuedBehindLeftoversIsNotLost() throws Exception {
+ TestUtils.assertMemoryLeak(() -> {
+ final Set
+ * Every frame the handler wrote before the drop must reach the client, followed by an orderly end of stream.
+ * The condition that breaks this is ordinary: the client still has frames in flight. They sit unread in the
+ * server's receive queue when the handler drops, and closing a socket with unread input aborts the connection
+ * with an RST, which also discards whatever the kernel has not transmitted yet -- the frames the handler wrote
+ * a moment earlier. The client then sees "connection reset" instead of the acks, so "ack N frames, then drop"
+ * quietly becomes "drop", and anything that depends on those acks (a drainer's progress-based escalation
+ * budget, for one) fails at random.
+ *
+ * The test forces both halves of that race rather than waiting for the scheduler to produce them: the trailing
+ * client frame is larger than one server read, so its tail is still unread when the handler acts, and the
+ * filler ahead of the ack is larger than the client's receive window, so the ack is still queued on the server
+ * at the moment of the drop.
+ */
+public class TestWebSocketServerHandlerDropTest {
+
+ private static final byte[] ACK = "ack-written-before-drop".getBytes(StandardCharsets.US_ASCII);
+ // Applied before connect(), so it caps the window the client advertises.
+ private static final int CLIENT_RECEIVE_BUFFER_BYTES = 4096;
+ // Several times the client's receive window: most of it, and the ack queued behind it, has not left the
+ // server when the handler drops.
+ private static final int FILLER_BYTES = 32 * 1024;
+ // Several times the server's 8 KiB socket read, so the frame that triggers the drop is dispatched while the
+ // tail of this one is still unread in the server's receive queue.
+ private static final int TRAILING_FRAME_BYTES = 32 * 1024;
+
+ @Test
+ public void testFramesWrittenBeforeHandlerDropReachClientAheadOfEndOfStream() throws Exception {
+ TestUtils.assertMemoryLeak(() -> {
+ final byte[] filler = new byte[FILLER_BYTES];
+ Arrays.fill(filler, (byte) 'f');
+ TestWebSocketServer.WebSocketServerHandler handler = new TestWebSocketServer.WebSocketServerHandler() {
+ private boolean dropped;
+
+ @Override
+ public synchronized void onBinaryMessage(TestWebSocketServer.ClientHandler client, byte[] data) {
+ if (dropped) {
+ return;
+ }
+ dropped = true;
+ try {
+ client.sendBinary(filler);
+ client.sendBinary(ACK);
+ } catch (IOException e) {
+ throw new AssertionError("server could not queue its frames", e);
+ }
+ client.close(); // the scripted mid-stream wire drop
+ }
+ };
+ try (TestWebSocketServer server = new TestWebSocketServer(handler)) {
+ server.start();
+ assertTrue(server.awaitStart(5, TimeUnit.SECONDS));
+ try (Socket socket = new Socket()) {
+ socket.setReceiveBufferSize(CLIENT_RECEIVE_BUFFER_BYTES);
+ socket.setSoTimeout(10_000);
+ socket.connect(new InetSocketAddress(InetAddress.getLoopbackAddress(), server.getPort()), 5_000);
+ OutputStream out = socket.getOutputStream();
+ DataInputStream in = new DataInputStream(socket.getInputStream());
+ upgrade(out, in);
+
+ // A single write, so both frames are on the wire before the server reads anything.
+ ByteArrayOutputStream frames = new ByteArrayOutputStream();
+ writeMaskedBinaryFrame(frames, new byte[]{1});
+ writeMaskedBinaryFrame(frames, new byte[TRAILING_FRAME_BYTES]);
+ out.write(frames.toByteArray());
+ out.flush();
+
+ int framesReceived = 0;
+ try {
+ assertFrame(in, filler, "filler");
+ framesReceived++;
+ assertFrame(in, ACK, "ack");
+ framesReceived++;
+ assertEquals("the drop must end the stream right after the frames written before it",
+ -1, in.read());
+ } catch (IOException e) {
+ fail("the handler's drop lost frames it had written before dropping [framesReceived="
+ + framesReceived + " of 2]: " + e);
+ }
+ }
+ }
+ });
+ }
+
+ private static void assertFrame(DataInputStream in, byte[] expectedPayload, String what) throws IOException {
+ assertEquals(what + ": FIN + BINARY", 0x80 | WebSocketOpcode.BINARY, in.readUnsignedByte());
+ int lengthByte = in.readUnsignedByte();
+ assertEquals(what + ": server frames are unmasked", 0, lengthByte & 0x80);
+ int length = lengthByte & 0x7F;
+ if (length == 126) {
+ length = in.readUnsignedShort();
+ } else if (length == 127) {
+ long longLength = in.readLong();
+ assertTrue(what + ": implausible frame length " + longLength, longLength <= Integer.MAX_VALUE);
+ length = (int) longLength;
+ }
+ assertEquals(what + ": payload length", expectedPayload.length, length);
+ byte[] payload = new byte[length];
+ in.readFully(payload);
+ assertArrayEquals(what + ": payload", expectedPayload, payload);
+ }
+
+ private static void upgrade(OutputStream out, DataInputStream in) throws IOException {
+ String request = "GET /write/v4 HTTP/1.1\r\n"
+ + "Host: localhost\r\n"
+ + "Upgrade: websocket\r\n"
+ + "Connection: Upgrade\r\n"
+ + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
+ + "Sec-WebSocket-Version: 13\r\n"
+ + "\r\n";
+ out.write(request.getBytes(StandardCharsets.US_ASCII));
+ out.flush();
+ StringBuilder response = new StringBuilder();
+ while (response.indexOf("\r\n\r\n") < 0) {
+ int b = in.read();
+ if (b < 0) {
+ fail("server closed the connection during the upgrade [response=" + response + ']');
+ }
+ response.append((char) b);
+ }
+ assertTrue("upgrade rejected: " + response, response.toString().startsWith("HTTP/1.1 101"));
+ }
+
+ private static void writeMaskedBinaryFrame(ByteArrayOutputStream out, byte[] payload) {
+ int length = payload.length;
+ out.write(0x80 | WebSocketOpcode.BINARY);
+ if (length <= 125) {
+ out.write(0x80 | length);
+ } else if (length <= 0xFFFF) {
+ out.write(0x80 | 126);
+ out.write(length >>> 8);
+ out.write(length & 0xFF);
+ } else {
+ throw new IllegalArgumentException("frame too large for this helper: " + length);
+ }
+ // Client frames must be masked; an all-zero key leaves the payload bytes unchanged.
+ out.write(0);
+ out.write(0);
+ out.write(0);
+ out.write(0);
+ out.write(payload, 0, length);
+ }
+}
diff --git a/core/src/test/java/io/questdb/client/test/impl/QueryImplResetTest.java b/core/src/test/java/io/questdb/client/test/impl/QueryImplResetTest.java
index bedbba92f..5ce9841d9 100644
--- a/core/src/test/java/io/questdb/client/test/impl/QueryImplResetTest.java
+++ b/core/src/test/java/io/questdb/client/test/impl/QueryImplResetTest.java
@@ -71,10 +71,12 @@ public void testResetForBorrowClearsBuilderState() throws Exception {
Field bindsF = queryImplClass.getDeclaredField("userBinds");
Field sqlBufF = queryImplClass.getDeclaredField("sqlBuffer");
Field doneF = queryImplClass.getDeclaredField("done");
+ Field timeoutF = queryImplClass.getDeclaredField("timeoutMillis");
handlerF.setAccessible(true);
bindsF.setAccessible(true);
sqlBufF.setAccessible(true);
doneF.setAccessible(true);
+ timeoutF.setAccessible(true);
// Seed builder state as a prior borrow would have left it.
handlerF.set(q, new NoopHandler());
@@ -82,6 +84,7 @@ public void testResetForBorrowClearsBuilderState() throws Exception {
// no-op
});
((StringSink) sqlBufF.get(q)).put("SELECT 1");
+ timeoutF.setLong(q, 0L); // a prior borrow disabled the timeout
doneF.setBoolean(q, false);
Method reset = queryImplClass.getDeclaredMethod("resetForBorrow");
@@ -97,6 +100,8 @@ public void testResetForBorrowClearsBuilderState() throws Exception {
0, sqlBuffer.length());
Assert.assertTrue("done must be true so the handle starts idle, not in flight",
doneF.getBoolean(q));
+ Assert.assertEquals("the query timeout must fall back to the configured default (-1)",
+ -1L, timeoutF.getLong(q));
});
}
diff --git a/core/src/test/java/io/questdb/client/test/impl/QwpQueryClientConfigHonoredTest.java b/core/src/test/java/io/questdb/client/test/impl/QwpQueryClientConfigHonoredTest.java
index 3e02f327e..dad288477 100644
--- a/core/src/test/java/io/questdb/client/test/impl/QwpQueryClientConfigHonoredTest.java
+++ b/core/src/test/java/io/questdb/client/test/impl/QwpQueryClientConfigHonoredTest.java
@@ -63,6 +63,7 @@ public void testEveryEgressKeyIsHonored() throws Exception {
assertHonored("failover_max_duration_ms=56000", "failover_max_duration_ms", 56000L);
assertHonored("max_batch_rows=512", "max_batch_rows", 512);
assertHonored("initial_credit=65536", "initial_credit", 65536L);
+ assertHonored("query_timeout_ms=1500", "query_timeout_ms", 1500L);
assertHonored("buffer_pool_size=3", "buffer_pool_size", 3);
assertHonored("compression=zstd", "compression", "zstd");
assertHonored("compression_level=9", "compression_level", 9);
diff --git a/examples/src/main/java/com/example/query/QueryCancellationExample.java b/examples/src/main/java/com/example/query/QueryCancellationExample.java
index b9def4bb9..57bda2880 100644
--- a/examples/src/main/java/com/example/query/QueryCancellationExample.java
+++ b/examples/src/main/java/com/example/query/QueryCancellationExample.java
@@ -19,6 +19,9 @@
* blocking {@link Completion#await()} throws {@link QueryException} carrying
* that status. If the query finished before the cancel landed, {@code await()}
* returns normally -- {@code cancel()} is a no-op on an already-terminal query.
+ *
+ * To stop queries that run too long without driving the cancel yourself, give
+ * them a timeout instead; see {@link QueryTimeoutExample}.
*/
public class QueryCancellationExample {
diff --git a/examples/src/main/java/com/example/query/QueryTimeoutExample.java b/examples/src/main/java/com/example/query/QueryTimeoutExample.java
new file mode 100644
index 000000000..cc2d3fae3
--- /dev/null
+++ b/examples/src/main/java/com/example/query/QueryTimeoutExample.java
@@ -0,0 +1,68 @@
+package com.example.query;
+
+import io.questdb.client.Query;
+import io.questdb.client.QueryException;
+import io.questdb.client.QuestDB;
+import io.questdb.client.cutlass.qwp.client.QwpColumnBatch;
+import io.questdb.client.cutlass.qwp.client.QwpColumnBatchHandler;
+
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Giving a query a timeout.
+ *
+ * {@link Query#timeout(long, TimeUnit)} overrides the server's default query
+ * timeout ({@code query.timeout}) for one query; {@code query_timeout_ms} in the
+ * connection string sets a default for every query. The client sends the
+ * timeout with the query and keeps no deadline of its own. The server stops
+ * the query when it can, and {@code await()} throws a {@link QueryException}
+ * whose {@link QueryException#isTimeout()} is {@code true}. The pooled
+ * connection stays open, so the same handle goes on to run the next query on
+ * it. Some statements cannot be stopped and run to completion. A server that
+ * does not support per-query timeouts applies its own default.
+ *
+ * Compare {@link QueryCancellationExample}: {@code await(timeout)} only bounds
+ * how long the caller waits, the query keeps running until cancelled.
+ */
+public class QueryTimeoutExample {
+
+ public static void main(String[] args) throws InterruptedException {
+ // query_timeout_ms: default timeout for every query of this handle's pool.
+ try (QuestDB db = QuestDB.connect("ws::addr=localhost:9000;query_timeout_ms=30000;");
+ Query q = db.borrowQuery()) {
+
+ q.sql("SELECT * FROM trades ORDER BY price")
+ .handler(new PrintingHandler())
+ // Tighter than the default, for this handle only.
+ .timeout(5, TimeUnit.SECONDS);
+ try {
+ q.submit().await();
+ System.out.println("finished within the timeout");
+ } catch (QueryException e) {
+ if (!e.isTimeout()) {
+ throw e;
+ }
+ System.out.println("timed out: " + e.getMessage());
+ }
+
+ // The connection survived the timeout; run the next query on it.
+ q.sql("SELECT count() FROM trades").timeout(0, TimeUnit.SECONDS).submit().await();
+ }
+ }
+
+ private static final class PrintingHandler implements QwpColumnBatchHandler {
+ @Override
+ public void onBatch(QwpColumnBatch batch) {
+ // Process rows... kept minimal here.
+ }
+
+ @Override
+ public void onEnd(long totalRows) {
+ System.out.println("done: " + totalRows + " rows");
+ }
+
+ @Override
+ public void onError(byte status, String message) {
+ }
+ }
+}