Repository navigation
Implement CREATE HANDLER: SQL-defined HTTP handlers - #106231
Conversation
Add the ability to create and manage custom HTTP handlers from SQL, without editing the server configuration file, as requested in #100000. New SQL statements: - `CREATE [IF NOT EXISTS] HANDLER name [PROTOCOL p] URL [PREFIX|REGEXP] '/x' [METHODS (GET, POST)] [TYPE query] AS <query>` - `ALTER HANDLER name ...` (partial update of any subset of clauses) - `DROP [IF EXISTS] HANDLER name` Handlers are matched after configuration-defined handlers, in the lexicographical order of their names. The URL is matched without the `?` query string and `#` fragment. Exact/prefix URLs are checked for ambiguity at create/alter time. The query is parsed but not analyzed at creation, can be parameterized (URL params, form variables, headers, and named regexp capture groups), and an `INSERT` handler reads its data from the HTTP body. Handlers are persisted in a local or Keeper storage, mirroring named collections, configured via the `query_rules_storage` config section, and kept in sync across replicas. Access control: `CREATE HANDLER`, `ALTER HANDLER` and `DROP HANDLER` grants. Introspection: - new `currentHandler` and `currentRequestURL` functions - new `http_handler_name` and `http_request_url` columns in `system.query_log` - new `system.handlers` table The query-parameter substitution visitor preserves the placeholders in a handler's query (its parameterizable interface), like parameterized views. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [18857c1] Summary: ✅
AI ReviewSummaryThis PR adds SQL-defined HTTP handlers ( Findings
Tests
Final VerdictChanges requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 1066/1426 (74.75%) · Uncovered code |
Expand the stateless tests to cover every statement of the spec: - parser/registry (04303): mandatory URL, syntactic validation at create time, parentheses around the query, arbitrary queries (SHOW), FORMAT belonging to the query, all four HTTP methods, overlapping regexp handlers (no ambiguity), ALTER into ambiguity, and the existing exact/prefix/regexp/type/ambiguity cases. - HTTP (04304): currentHandler branching, custom HTTP response headers via the query SETTINGS, HTTP headers used as usual (X-ClickHouse-Database), lexicographic matching order, authentication via request credentials, invoking needs no grant, query grants checked during invocation, SQL SECURITY DEFINER view access, and separate CREATE/ALTER/DROP HANDLER grants. Add an integration test (test_create_handler) for behaviors that need special server setups: local-storage persistence across restart, configuration-defined handler priority over SQL-defined handlers, composable PROTOCOL scoping, ON CLUSTER, and Keeper-storage replication across nodes. Fix: the Keeper-backed handler storage was missing the `Coordination::setCurrentComponent` guards that every ZooKeeper operation requires, which made Keeper-stored handlers fail at startup with a LOGICAL_ERROR. Found by the new integration test. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
CI style fixes: - Remove the unused `LOGICAL_ERROR` error code from SQLDefinedHandlerFromAST.cpp. - 04304: target `SYSTEM FLUSH LOGS query_log`, add a `current_database = currentDatabase()` condition and a retry loop around the query_log check. Review feedback: - Do not persist sensitive request parameters: `system.query_log.http_request_url` now stores the request path only (query string and fragment stripped). `currentRequestURL()` still returns the full URL at runtime. - Keeper storage: ALTER only changes a child's data, which a children-list watch does not observe, so other replicas could serve stale definitions. Bump a version on the root node on every create/drop/alter and watch the root node's data, so all changes propagate. - Keeper storage: ALTER now uses `set` instead of create-or-update, so a delayed ALTER cannot resurrect a handler that was concurrently dropped; `ZNONODE` maps to HANDLER_DOESNT_EXIST. - Keep the idempotent contract under replicated storage: `CREATE HANDLER IF NOT EXISTS` swallows a concurrent `HANDLER_ALREADY_EXISTS`, and `DROP HANDLER [IF EXISTS]` uses `removeIfExists`. - Docs: narrow the documented parameter sources to what is implemented (URL query parameters and named URL REGEXP captures; standard ClickHouse HTTP headers), add the missing system-table frontmatter, and document the path-only query_log column. Tests: - Integration: verify ALTER HANDLER propagates across Keeper-backed replicas. - 04304: assert the query_log URL is the path only (query string not persisted). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
After merging master, the test numbers 04303 and 04304 collided with newly added tests. Renumber to 04305 (`04305_create_handler_basic`) and 04306 (`04306_create_handler_http`). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
In `SQLDefinedHandlersFactory::updateFromSQL`, the old handler was erased from `loaded_handlers` before persisting, and restored only when `checkAmbiguity` threw. If `store` threw instead (for example Keeper returns an error or loses the connection, or the local metadata write fails), `loaded_handlers` was left missing the entry while it still exists in storage, corrupting the local registry for subsequent `ALTER HANDLER` / `DROP HANDLER` calls. Move `store` inside the recovery scope so the old handler is restored on any failure of the check or the write. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Picked this up via Merged
Renumbered tests to avoid collisions introduced by Fixed bot review thread ( Verified on a fresh debug build (built clean from the merged branch): Deferred to you — three remaining bot threads are design decisions on this new feature, not mechanical fixes:
Left these for your call rather than guessing at the intended semantics. |
|
The failures of They were introduced by #104690 ("Add #104690 was merged in violation of the ClickHouse team rules: its own CI already showed these two tests failing (10 times between May 12 and June 1) before it was merged. Please update your branch to pick up the revert; the tests should pass again. |
The Keeper child mutation (`create`/`set`/`remove`) and the root-version bump that notifies replicas were issued as two separate requests. A connection loss between them could commit the handler change while leaving the watched root version unchanged, so other replicas would keep serving a stale set of handlers until an unrelated change bumped the version. Issue both in a single `multi` transaction via `bumpVersionRequest`, so the watched root version always advances together with the change (or not at all). This also makes the `IF EXISTS` drop a clean atomic no-op: if the node is absent, the whole transaction is rejected and nothing changes. Addresses review feedback on SQLDefinedHandlersMetadataStorage.
With Keeper-backed handler storage, handlers are synchronized across replicas automatically, so an `ON CLUSTER` clause is redundant: fanning out a non-`IF NOT EXISTS` `CREATE HANDLER` makes the second host fail with `HANDLER_ALREADY_EXISTS`, diverging from the unreplicated behavior. Add the `ignore_on_cluster_for_replicated_handler_queries` setting (mirroring `ignore_on_cluster_for_replicated_named_collections_queries`) and a `SQLDefinedHandlersFactory::isReplicated` query, and teach `removeOnClusterClauseIfNeeded` to strip `ON CLUSTER` from `CREATE`, `ALTER` and `DROP HANDLER` when the setting is enabled and the storage is replicated. Also fix the `DROP HANDLER` syntax in the docs: the parser consumes `IF EXISTS` after `HANDLER` (`DROP HANDLER [IF EXISTS] name`), matching `DROP NAMED COLLECTION`, so the previously documented `DROP [IF EXISTS] HANDLER name` failed to parse. Document the new setting and add an integration test. Addresses review feedback on InterpreterCreateHandlerQuery and the docs.
Handlers are a global, server-wide namespace, and 04305 uses fixed handler
names. The flaky check runs several copies of the same test concurrently
(`--test-runs N --jobs M`), so a `DROP HANDLER IF EXISTS` in one copy removes a
handler another copy is about to drop, surfacing as
Code: 1009. Cannot drop handler `h04305_b`, because it doesn't exist. (HANDLER_DOESNT_EXIST)
and, once `--max-failures` aborts the run, a hung in-flight HTTP request in the
sibling 04306 test reported as "Server died". Tag the test `no-parallel`, the
same way named collection tests (also a global namespace) are tagged.
CI report: #106231
|
Continued work on this PR: merged latest Fixed the "Server died" flaky-check failure. The flaky check runs each new test ~50× with Review threads addressed (resolved):
Left open as design decisions (replied inline, not resolved):
Unrelated CI failure: CI report: #106231 |
…y` parameter There is a single, non-rewindable HTTP request body. Binding `_request_body` drains it in `PredefinedQueryHandler::customizeContext` before `HTTPHandler::processQuery` builds the query's input pipeline, so a handler whose query also takes the body as its own input data (a plain `INSERT`, or an `INSERT ... SELECT` reading from `input`) would find the stream at EOF and silently insert nothing. Reject such a handler at `CREATE`/`ALTER` time with `BAD_ARGUMENTS` instead of creating one that discards every upload.
|
🕵 Status 2026-08-13:
All 27 handler stateless tests pass locally on the new head (two excluded as scratch-env-only: |
alexey-milovidov
left a comment
There was a problem hiding this comment.
The implementation is pretty straightforward and pedantic. Very good.
Treat additions and modifications under `docs/en` as unpublished documentation, while allowing cleanup deletions. Related: ClickHouse#106231
Register `CREATE HANDLER` in `StatementFactory`, keep the full reference body in the parser registration, and mark the Mintlify page as generated through `system.documentation`. Related: ClickHouse#115609 Related: ClickHouse#106231
|
The fix for the On 2026-07-31 I said I would rather not open one, because the private artifact was unreachable and the message phrase had zero CIDB hits, so I could not see the failure. That changed: it surfaced publicly in The keeper-backend rollback inconsistency I flagged in that same comment is a different shape and is not what #117793 addresses. |
Implements #100000: create and manage custom HTTP handlers from SQL, without editing the server configuration file.
New SQL statements:
CREATE HANDLER [IF NOT EXISTS] name [PROTOCOL p] URL [PREFIX|REGEXP] '/x' [METHODS (GET, POST)] [TYPE query] AS <query>ALTER HANDLER name ...— partial update of any subset of clausesDROP [IF EXISTS] HANDLER nameHandlers are matched after configuration-defined handlers, in the lexicographical order of their names. The URL is matched without the
?query string and#fragment; exact/prefix URLs are checked for ambiguity at create/alter time. The query is parsed (not analyzed) at creation, can be parameterized (URL params, form variables, headers, and named regexp capture groups), and anINSERThandler reads its data from the HTTP body.Handlers are persisted in a local or Keeper storage, mirroring named collections, configured via the
query_rules_storageconfig section, and kept in sync across replicas.Access control adds
CREATE HANDLER,ALTER HANDLERandDROP HANDLERgrants. Introspection adds thecurrentHandlerandcurrentRequestURLfunctions, thehttp_handler_nameandhttp_request_urlcolumns insystem.query_log, and thesystem.handlerstable.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added
CREATE HANDLER,ALTER HANDLERandDROP HANDLERstatements to define custom HTTP handlers from SQL, persisted in a local or Keeper storage. Added thecurrentHandlerandcurrentRequestURLfunctions, thesystem.handlerstable, and thehttp_handler_name/http_request_urlcolumns insystem.query_log.Documentation entry for user-facing changes
🤖 Generated with Claude Code