Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .gitleaks.toml
Original file line number Diff line number Diff line change
@@ -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==''',
]
37 changes: 35 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 |

Expand All @@ -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,
Expand Down
5 changes: 5 additions & 0 deletions core/src/main/java/io/questdb/client/Completion.java
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ public interface Completion {
/**
* Blocks up to the given timeout. Returns {@code true} if the query
* completed, {@code false} on timeout.
* <p>
* 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
Expand Down
47 changes: 41 additions & 6 deletions core/src/main/java/io/questdb/client/Query.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -44,12 +46,13 @@
* creates one small lease handle per borrow (often scalar-replaced by the JIT
* when used with try-with-resources).
* <p>
* 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.
* <p>
* Thread safety: not thread-safe and single-flight -- one in-flight query per
* handle. To run queries concurrently, borrow one handle per concurrent query.
Expand Down Expand Up @@ -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.
* <p>
* A client whose connection failed is discarded. Any other client whose
* query has ended is returned to the pool at once.
* <p>
* 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
Expand Down Expand Up @@ -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.
* <p>
* 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.
* <p>
* 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);
}
18 changes: 15 additions & 3 deletions core/src/main/java/io/questdb/client/QueryException.java
Original file line number Diff line number Diff line change
Expand Up @@ -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)}
Expand All @@ -35,9 +36,12 @@
* <p>
* 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 {

Expand Down Expand Up @@ -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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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.
* <p>
* 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;
Expand All @@ -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;
}

Expand All @@ -68,6 +82,7 @@ public QueryEvent asEnd(long totalRows) {
this.buffer = null;
this.totalRows = totalRows;
this.details.clear();
this.requestId = ANY_REQUEST;
return this;
}

Expand All @@ -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;
}

Expand All @@ -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;
}

Expand All @@ -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(...)}
Expand All @@ -119,6 +156,7 @@ public void reset() {
this.opType = 0;
this.rowsAffected = 0;
this.totalRows = 0;
this.requestId = ANY_REQUEST;
this.details.clear();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@
* <strong>Exception contract:</strong> 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 {

Expand Down
Loading
Loading