mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 13:44:03 +00:00
Merge main and preserve CI scope gates with nightly fuzz policy
Signed-off-by: WenyXu <wenymedia@gmail.com>
This commit is contained in:
@@ -0,0 +1,170 @@
|
||||
# Integration CI admission gate
|
||||
|
||||
`integration.yml` filters its expensive jobs — fuzz, export/import E2E, and the
|
||||
sqlness KvBackend legs — by the diff. Fuzz additionally follows the event policy
|
||||
in [Heavy CI scheduling](../heavy-ci.md): PR opening or ready-for-review events,
|
||||
scheduled runs, and explicit manual profiles. A scope verdict cannot override
|
||||
that event policy.
|
||||
|
||||
The gate can only *skip* work, never add it, and it fails open: when the verdict
|
||||
is missing or uncertain, every gated job runs.
|
||||
|
||||
| File | Role |
|
||||
|---|---|
|
||||
| `ci_scope.py` | the classifier: reads the diff, writes `$GITHUB_OUTPUT` |
|
||||
| `scope-rules.toml` | the policy: which paths select which suite, as data |
|
||||
| `ci_scope_rules.py` | loads and validates the policy; `--check-paths` |
|
||||
| `tests/` | unit tests, and `fixtures/scope-cases.toml` golden cases |
|
||||
|
||||
Two words appear everywhere below. A **suite** is one matrix leg of a gated job,
|
||||
named `<gate>/<leg>`. A **gate** is one `$GITHUB_OUTPUT` key that switches a
|
||||
whole job.
|
||||
|
||||
## What is gated
|
||||
|
||||
Only `integration.yml`, and only these jobs:
|
||||
|
||||
| Gated job | Runs |
|
||||
|---|---|
|
||||
| `prepare-fuzz-targets` | the fuzz targets only |
|
||||
| `fuzztest` | standalone fuzz, 2 legs |
|
||||
| `unstable-fuzztest` | unstable standalone create-table fuzz, 1 leg |
|
||||
| `distributed-fuzztest` | distributed fuzz with remote WAL, 4 legs |
|
||||
| `distributed-fuzztest-with-chaos` | Chaos Mesh, 3 legs |
|
||||
| `build-greptime-ci` | the profile-CI binary only |
|
||||
| `export-import-v2-e2e` | CLI `COPY DATABASE` export/import against S3 |
|
||||
| `sqlness-kvbackend` | sqlness with PostgreSQL and MySQL as the metadata store |
|
||||
|
||||
The legs themselves are the `matrix` entries in `integration.yml`; the rules
|
||||
file repeats their ids so a verdict can name them.
|
||||
|
||||
Everything else always runs: `rust.yml`, `checks.yml`, `docs.yml`, the debug
|
||||
`build`, the required `sqlness` job (Basic, Remote WAL, Flat format), `compat`
|
||||
and `compat-updater-check`. None of the gated jobs is in the required-check
|
||||
matrix in `docs.yml`, so a skipped job can never block a merge.
|
||||
|
||||
Two choices follow from that rule. The two KvBackend legs sit in their own
|
||||
`sqlness-kvbackend` job because a job-level `if:` cannot read `matrix`, so
|
||||
gating them inside `sqlness` would skip required checks and make the pull
|
||||
request unmergeable. The multi-language SDK job stays ungated: it takes about
|
||||
three minutes, less than the cost of getting its verdict wrong.
|
||||
|
||||
## How a verdict is made
|
||||
|
||||
First match wins:
|
||||
|
||||
1. **Forced** — `merge_group`, `schedule`, `workflow_dispatch`, the `ci:full`
|
||||
label or `CI_SCOPE_FORCE_ALL`. All scope outputs allow execution; job event
|
||||
conditions and manual profile selection still apply.
|
||||
2. **Too large to judge** — more than 300 changed files. Everything runs.
|
||||
3. **Always-run file changed** — `Cargo.toml`, `Cargo.lock`, `tests-fuzz/**`,
|
||||
this directory, or anything else that changes what the suites build or how
|
||||
they start. Everything runs.
|
||||
4. **Uncovered change** — a path under `src/` that no suite claims. This is the
|
||||
net for a crate added, split or renamed after the rules were written.
|
||||
Everything runs.
|
||||
5. **Path rules** — the suites whose globs match the changed files, and only
|
||||
those.
|
||||
|
||||
The code is the source of truth for the details; its module docstring is worth
|
||||
reading before changing it.
|
||||
|
||||
## Why a check was skipped
|
||||
|
||||
The run page's summary pane answers this without opening a log: one row per
|
||||
suite, with its verdict, the rule that decided it, and up to three of the
|
||||
changed files that matched.
|
||||
|
||||
The step log of the `CI Scope` job has the same information in text form. It
|
||||
starts with `CI scope: mode=… full=…` (`grep '^CI scope'` finds it), then one
|
||||
line per suite — `run` or `skip`, source, reason — then `gates:` with the exact
|
||||
values the jobs read.
|
||||
|
||||
A degraded decision is never silent. A failed label or file lookup emits
|
||||
`::warning::` and widens the gate to every suite.
|
||||
|
||||
## Forcing a full run
|
||||
|
||||
Add the `ci:full` label to the pull request and click "Re-run all jobs". The
|
||||
label is read through the API at run time, not from the event payload, so one
|
||||
added after the first run still counts. `/ci` dispatch
|
||||
(`.github/scripts/ci-slash.py`), the `CI_SCOPE_FORCE_ALL` repository variable
|
||||
and every merge-queue run also run everything: the classifier returns a forced
|
||||
plan there, so a wrong skip is still exercised before the change lands. None of
|
||||
the gated jobs is a required check, so a failure in the queue does not block the
|
||||
merge by itself.
|
||||
|
||||
`CI_SCOPE_FORCE_ALL` is the switch to flip while debugging the rules themselves.
|
||||
|
||||
## Changing the rules
|
||||
|
||||
`scope-rules.toml` is data, not code: `ci_scope_rules.py` loads it with the
|
||||
standard library's `tomllib`. Two things are validated:
|
||||
|
||||
- the shape — an unknown or cyclic `@group` reference, a `gate` that disagrees
|
||||
with the suite id, a gate missing from `[gates]`, or an exemption without a
|
||||
`reason` all raise;
|
||||
- that every glob still points at something that exists, so a renamed or
|
||||
deleted crate fails the check instead of silently matching nothing.
|
||||
|
||||
Run both with `make check-ci-scope`, or the path half alone with
|
||||
`python3 .github/ci/ci_scope_rules.py --check-paths`. The same command runs in
|
||||
the `CI Scope Rules` job of `checks.yml`, on `ubuntu-slim` — the image the
|
||||
classifier itself uses, so a path that exists there also exists when the verdict
|
||||
is computed.
|
||||
|
||||
A malformed file fails the classify step, and because every step of that job is
|
||||
`continue-on-error`, every gated job runs instead.
|
||||
|
||||
`[[matching.exempt]]` lists paths outside the gate's remit: they select no suite
|
||||
and never widen the gate. Each one carries a `reason`, and the loader rejects an
|
||||
empty one — what CI never runs is the part a reader must be able to justify.
|
||||
|
||||
`tests/fixtures/scope-cases.toml` is test data, not configuration: a diff shape
|
||||
and the suites it must start. `ScopeCaseTests` replays each case through the
|
||||
classifier, so a rule edit that changes behaviour fails with the case name
|
||||
instead of silently rerouting CI. The cases carry no pull request numbers;
|
||||
`git log` has those.
|
||||
|
||||
## Adding a suite
|
||||
|
||||
1. Add a `[suites."<gate>/<leg>"]` table to `scope-rules.toml` with `gate`,
|
||||
`paths` (globs or `@group` references) and a one-line `description`. The id
|
||||
is `<gate>/<matrix leg id>`, and `gate` is that id with `-` replaced by `_`;
|
||||
the loader and `test_suite_metadata` both enforce it.
|
||||
2. Add the matching matrix leg to the job in `integration.yml`.
|
||||
3. Gate the job's `if:` with the matching output, and list `scope` in its
|
||||
`needs`. A new gate also needs a key in `derive_outputs` and in the `scope`
|
||||
job's `outputs`; `test_every_gate_routes_to_an_output` fails when that
|
||||
routing is missing.
|
||||
4. Add a case to `tests/fixtures/scope-cases.toml` and run
|
||||
`python3 .github/ci/tests/test_ci_scope.py`. `CrateCoverageTests` separately
|
||||
fails when a workspace crate matches no suite and is not excused in
|
||||
`UNMAPPED_CRATES`: the runtime net would run everything, but the rule table
|
||||
is what should be updated.
|
||||
|
||||
## Ground rules for the workflow
|
||||
|
||||
These six rules keep the gate failing open. Break one and either CI runs jobs it
|
||||
should have skipped, or a classifier failure takes CI down with it.
|
||||
|
||||
- **Read the output as `!= 'false'`.** An absent output means "run"; writing
|
||||
`== 'true'` inverts the failure direction.
|
||||
- **Start every gate with `!cancelled()`.** Without a status function the
|
||||
condition carries an implicit `success()` over `needs`, so a `scope` job that
|
||||
times out would skip the gates. Other dependencies are therefore required
|
||||
explicitly with `needs.<job>.result == 'success'`.
|
||||
- **Every fallible step of `scope` is `continue-on-error: true`.** GitHub skips
|
||||
the dependents of a *failed* job, so a classifier crash must leave the job
|
||||
green with no outputs rather than take CI down with it.
|
||||
- **Rules come from the base revision.** The `scope` job checks out
|
||||
`pull_request.base.sha` (or `merge_group.base_sha`), so a pull request cannot
|
||||
weaken its own gate. On the first pull request that introduces this directory
|
||||
the base has no `ci_scope.py`: the step fails, no outputs are written, and
|
||||
every gate runs.
|
||||
- **One gate per job, never per leg.** GitHub does not expose `matrix` to
|
||||
`jobs.<job_id>.if`. Per-suite verdicts stay visible in the log.
|
||||
- **Pass the run's `head`/`base` SHAs and let the classifier compare them with
|
||||
the pull request's live revisions.** A re-run keeps the original SHAs while
|
||||
GitHub serves the *current* file list; without the comparison the new diff
|
||||
would be judged against the old tree. With it, a mismatch runs everything.
|
||||
Executable
+623
@@ -0,0 +1,623 @@
|
||||
#!/usr/bin/env python3
|
||||
# Copyright 2023 Greptime Team
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Decide which integration CI suites must run for one pull request.
|
||||
|
||||
Pipeline, in priority order:
|
||||
|
||||
1. forced mode -- `merge_group`, `schedule`, `workflow_dispatch`,
|
||||
`CI_SCOPE_FORCE_ALL`, or the `ci:full` label. Every suite runs.
|
||||
2. always-run floor -- a changed file matches `ALWAYS_RUN`. Every suite runs.
|
||||
3. uncovered build change -- a path under `SRC_TREE` that no suite claims, so a
|
||||
crate added or renamed later still runs everything.
|
||||
4. static path matches -- glob match of the changed files against the suite
|
||||
catalog in `scope-rules.toml`. Paths under `EXEMPT_TREES` are outside the
|
||||
gate's remit and are dropped first: `@server` claims `src/query/**`, which
|
||||
would otherwise put a PromQL-only change through the whole fleet.
|
||||
|
||||
The verdict is deterministic: the same diff always produces the same plan, and
|
||||
a change that no rule explains falls through to "run everything".
|
||||
|
||||
The plan maps to `$GITHUB_OUTPUT` keys that the `integration.yml` gate jobs
|
||||
consume; `--dry-run` prints them as JSON.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from ci_scope_rules import (
|
||||
ALWAYS_RUN,
|
||||
EXEMPT_TREES,
|
||||
SRC_TREE,
|
||||
SUITES,
|
||||
suite_group,
|
||||
suite_paths,
|
||||
)
|
||||
|
||||
MAX_FILES = 300
|
||||
HTTP_TIMEOUT = 45
|
||||
FORCED_EVENTS = {"merge_group", "schedule", "workflow_dispatch"}
|
||||
# A diff with no code, config or workflow file never needs a suite.
|
||||
CODE_FILE = re.compile(
|
||||
r"\.(rs|toml|lock|sh|ya?ml)$|(^|/)Makefile$|(^|/)Cargo\.toml$|\.sql$"
|
||||
)
|
||||
FUZZ_GATES = ("fuzz_standalone", "fuzz_distributed", "fuzz_chaos")
|
||||
|
||||
|
||||
class ScopeError(Exception):
|
||||
"""A handled failure: the caller falls back instead of crashing."""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# HTTP seam (tests replace `_request`)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _request(method, url, headers, body=None, timeout=HTTP_TIMEOUT):
|
||||
request = urllib.request.Request(url, data=body, headers=headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
return response.status, response.read()
|
||||
except urllib.error.HTTPError as err:
|
||||
return err.code, err.read()
|
||||
except (urllib.error.URLError, TimeoutError, OSError) as err:
|
||||
raise ScopeError(f"{method} {url}: {err}") from err
|
||||
|
||||
|
||||
def _get(url, headers, timeout=HTTP_TIMEOUT):
|
||||
return _request("GET", url, headers, None, timeout)
|
||||
|
||||
|
||||
def _post(url, headers, body, timeout=HTTP_TIMEOUT):
|
||||
return _request("POST", url, headers, body, timeout)
|
||||
|
||||
|
||||
def get_json(url, headers, timeout=HTTP_TIMEOUT):
|
||||
"""GET returning (status, parsed json); transport failures raise `ScopeError`."""
|
||||
status, raw = _get(url, headers, timeout)
|
||||
try:
|
||||
payload = json.loads(raw.decode("utf-8", "replace")) if raw else None
|
||||
except json.JSONDecodeError:
|
||||
payload = None
|
||||
return status, payload
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Path matching
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def glob_to_regex(pattern):
|
||||
"""Translate a repo glob into an anchored regexp.
|
||||
|
||||
`**/` also matches zero directories, `**` spans `/`, `*` and `?` do not.
|
||||
"""
|
||||
out = ["^"]
|
||||
index = 0
|
||||
while index < len(pattern):
|
||||
char = pattern[index]
|
||||
if char == "*":
|
||||
end = index
|
||||
while end < len(pattern) and pattern[end] == "*":
|
||||
end += 1
|
||||
if end - index >= 2:
|
||||
if end < len(pattern) and pattern[end] == "/":
|
||||
out.append("(?:.*/)?")
|
||||
index = end + 1
|
||||
continue
|
||||
out.append(".*")
|
||||
else:
|
||||
out.append("[^/]*")
|
||||
index = end
|
||||
elif char == "?":
|
||||
out.append("[^/]")
|
||||
index += 1
|
||||
else:
|
||||
out.append(re.escape(char))
|
||||
index += 1
|
||||
out.append("$")
|
||||
return re.compile("".join(out))
|
||||
|
||||
|
||||
def compile_patterns(patterns):
|
||||
return [glob_to_regex(pattern) for pattern in patterns]
|
||||
|
||||
|
||||
def matches_any(filename, compiled):
|
||||
return any(regex.match(filename) for regex in compiled)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# GitHub API
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def github_api(method, path, token, payload=None):
|
||||
base = os.environ.get("GITHUB_API_URL", "https://api.github.com").rstrip("/")
|
||||
url = base + path
|
||||
headers = {
|
||||
"Accept": "application/vnd.github+json",
|
||||
"User-Agent": "greptimedb-ci-scope",
|
||||
}
|
||||
if token:
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
body = None
|
||||
if payload is not None:
|
||||
body = json.dumps(payload).encode()
|
||||
headers["Content-Type"] = "application/json"
|
||||
if method == "GET":
|
||||
return get_json(url, headers)
|
||||
status, raw = _request(method, url, headers, body, HTTP_TIMEOUT)
|
||||
try:
|
||||
parsed = json.loads(raw.decode("utf-8", "replace")) if raw else None
|
||||
except json.JSONDecodeError:
|
||||
parsed = None
|
||||
return status, parsed
|
||||
|
||||
|
||||
def fetch_changed_files(repo, number, token):
|
||||
"""Return (files, truncated). `truncated` means the PR has more than MAX_FILES."""
|
||||
files = []
|
||||
page = 1
|
||||
while True:
|
||||
status, payload = github_api(
|
||||
"GET", f"/repos/{repo}/pulls/{number}/files?per_page=100&page={page}", token
|
||||
)
|
||||
if status != 200 or not isinstance(payload, list):
|
||||
raise ScopeError(f"cannot list pull request files (HTTP {status})")
|
||||
for item in payload:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
patch = item.get("patch")
|
||||
files.append(
|
||||
{
|
||||
"filename": item.get("filename", ""),
|
||||
"previous_filename": item.get("previous_filename") or "",
|
||||
"status": item.get("status", "modified"),
|
||||
"additions": item.get("additions", 0),
|
||||
"deletions": item.get("deletions", 0),
|
||||
"patch": patch if isinstance(patch, str) else "",
|
||||
"patch_included": isinstance(patch, str) and bool(patch),
|
||||
}
|
||||
)
|
||||
if len(payload) < 100:
|
||||
return files, False
|
||||
if len(files) >= MAX_FILES:
|
||||
# Keep `per_page=100`: with `per_page=1`, page N is item N, so the
|
||||
# probe would answer "is there a file 4?" instead of "file 301?".
|
||||
status, extra = github_api(
|
||||
"GET",
|
||||
f"/repos/{repo}/pulls/{number}/files?per_page=100&page={page + 1}",
|
||||
token,
|
||||
)
|
||||
if status != 200 or not isinstance(extra, list):
|
||||
raise ScopeError(
|
||||
"cannot confirm the changed file list is complete "
|
||||
f"(HTTP {status})"
|
||||
)
|
||||
del files[MAX_FILES:]
|
||||
return files, bool(extra)
|
||||
page += 1
|
||||
|
||||
|
||||
def fetch_pull(repo, number, token):
|
||||
"""Return (labels, head sha, base sha) for one pull request."""
|
||||
status, payload = github_api("GET", f"/repos/{repo}/pulls/{number}", token)
|
||||
if status != 200 or not isinstance(payload, dict):
|
||||
raise ScopeError(f"cannot read pull request (HTTP {status})")
|
||||
labels = payload.get("labels") or []
|
||||
head = ((payload.get("head") or {}).get("sha") or "").strip()
|
||||
base = ((payload.get("base") or {}).get("sha") or "").strip()
|
||||
names = {label.get("name", "") for label in labels if isinstance(label, dict)}
|
||||
return names, head, base
|
||||
|
||||
|
||||
def revision_drift(args, head, base):
|
||||
"""Return a note when the tested revisions are no longer the live ones.
|
||||
|
||||
A re-run keeps the run's original SHAs while the file list served by GitHub
|
||||
is the pull request's current one. After a force-push the classifier would
|
||||
judge the new diff for the old tree, so a mismatch runs every suite instead.
|
||||
"""
|
||||
for supplied, live, name in (
|
||||
(args.head_sha, head, "head"),
|
||||
(args.base_sha, base, "base"),
|
||||
):
|
||||
if supplied and live and supplied.lower() != live.lower():
|
||||
return (
|
||||
f"pull request {name} moved from {supplied[:12]} to "
|
||||
f"{live[:12]} after this run started"
|
||||
)
|
||||
return ""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Decisions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def file_paths(item):
|
||||
"""Every path the change touched; a rename keeps the deleted side too."""
|
||||
names = [item["filename"]]
|
||||
previous = item.get("previous_filename")
|
||||
if previous and previous != item["filename"]:
|
||||
names.append(previous)
|
||||
return names
|
||||
|
||||
|
||||
def gated_paths(item):
|
||||
"""The paths of one changed file that the gate judges.
|
||||
|
||||
A path under `EXEMPT_TREES` is outside the remit: it selects no suite, and
|
||||
it is not a change that "no rule covers", so it cannot widen the gate.
|
||||
"""
|
||||
return [name for name in file_paths(item) if not name.startswith(EXEMPT_TREES)]
|
||||
|
||||
|
||||
def path_matches(files):
|
||||
"""Return (always_run_hits, {suite_id: [matching file paths]})."""
|
||||
always_compiled = compile_patterns(ALWAYS_RUN)
|
||||
suite_matchers = {
|
||||
suite_id: compile_patterns(suite_paths(suite))
|
||||
for suite_id, suite in SUITES.items()
|
||||
}
|
||||
always_hits = set()
|
||||
matches = {suite_id: set() for suite_id in SUITES}
|
||||
for item in files:
|
||||
for name in file_paths(item):
|
||||
if matches_any(name, always_compiled):
|
||||
always_hits.add(name)
|
||||
for name in gated_paths(item):
|
||||
for suite_id, compiled in suite_matchers.items():
|
||||
if matches_any(name, compiled):
|
||||
matches[suite_id].add(name)
|
||||
return sorted(always_hits), {
|
||||
suite_id: sorted(matched) for suite_id, matched in matches.items()
|
||||
}
|
||||
|
||||
|
||||
def uncovered_changes(files, matches):
|
||||
"""True when a change can reach code that no suite path claims.
|
||||
|
||||
This is the net for a crate that was added, split or renamed after the rules
|
||||
were written: without it such a change matches no suite and would skip every
|
||||
gated job. A single unmatched path is enough, even when other paths in the
|
||||
same diff match a suite.
|
||||
"""
|
||||
return first_uncovered(files, matches) is not None
|
||||
|
||||
|
||||
def first_uncovered(files, matches):
|
||||
"""The first changed path that no suite claims, or None.
|
||||
|
||||
Naming it is what makes the widening explainable in the log.
|
||||
"""
|
||||
matched = {name for names in matches.values() for name in names}
|
||||
return next(
|
||||
(
|
||||
name
|
||||
for item in files
|
||||
for name in gated_paths(item)
|
||||
if name.startswith(SRC_TREE) and name not in matched
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
def has_meaningful_changes(files):
|
||||
return any(CODE_FILE.search(item["filename"]) for item in files)
|
||||
|
||||
|
||||
def finalize(plan):
|
||||
"""`full` means every gated suite runs, whatever produced the decision."""
|
||||
plan["full"] = all(entry["run"] for entry in plan["suites"].values())
|
||||
return plan
|
||||
|
||||
|
||||
def all_suites(run, reason, source):
|
||||
return {
|
||||
suite_id: {"run": run, "source": source, "reason": reason}
|
||||
for suite_id in SUITES
|
||||
}
|
||||
|
||||
|
||||
def full_plan(plan, reason, source, mode="static"):
|
||||
"""Every suite runs; `finalize` derives `full` from the verdicts."""
|
||||
plan.update(mode=mode, suites=all_suites(True, reason, source))
|
||||
return finalize(plan)
|
||||
|
||||
|
||||
def forced_reason(args, labels):
|
||||
"""Return why every suite must run, or an empty string."""
|
||||
event = args.event or os.environ.get("GITHUB_EVENT_NAME") or "pull_request"
|
||||
if event in FORCED_EVENTS:
|
||||
return f"event={event}"
|
||||
if os.environ.get("CI_SCOPE_FORCE_ALL", "").strip().lower() in {
|
||||
"1",
|
||||
"true",
|
||||
"yes",
|
||||
"on",
|
||||
}:
|
||||
return "CI_SCOPE_FORCE_ALL"
|
||||
if "ci:full" in labels:
|
||||
return "label ci:full"
|
||||
return ""
|
||||
|
||||
|
||||
def build_plan(args, token):
|
||||
notes = []
|
||||
plan = {
|
||||
"mode": "static",
|
||||
"head_sha": args.head_sha or "",
|
||||
"base_sha": args.base_sha or "",
|
||||
"full": False,
|
||||
"suites": {},
|
||||
"matching": {},
|
||||
"notes": notes,
|
||||
}
|
||||
|
||||
# Events and variables that force a run need no GitHub call at all; the
|
||||
# `ci:full` label is the only reason to read the pull request early.
|
||||
forced = forced_reason(args, set())
|
||||
labels, head_live, base_live = set(), "", ""
|
||||
if args.pr and not forced:
|
||||
try:
|
||||
labels, head_live, base_live = fetch_pull(
|
||||
args.repo, args.pr, token
|
||||
)
|
||||
except ScopeError as err:
|
||||
# A failed lookup must widen the gate, never narrow it.
|
||||
notes.append(f"pull request lookup failed: {err}")
|
||||
return full_plan(plan, "pull request lookup failed", "always-run")
|
||||
forced = forced_reason(args, labels)
|
||||
|
||||
if forced:
|
||||
notes.append(f"forced: {forced}")
|
||||
return full_plan(plan, f"forced by {forced}", "forced", mode="forced")
|
||||
|
||||
if not args.pr:
|
||||
raise ScopeError("--pr is required unless the event forces every suite")
|
||||
|
||||
drift = revision_drift(args, head_live, base_live)
|
||||
if drift:
|
||||
notes.append(drift)
|
||||
return full_plan(plan, drift, "always-run")
|
||||
|
||||
files, truncated = fetch_changed_files(args.repo, args.pr, token)
|
||||
if truncated:
|
||||
notes.append(f"changed file list truncated at {MAX_FILES}")
|
||||
return full_plan(
|
||||
plan,
|
||||
f"pull request has more than {MAX_FILES} changed files",
|
||||
"always-run",
|
||||
)
|
||||
|
||||
always_hits, matches = path_matches(files)
|
||||
# Keep the evidence: the step summary explains a verdict by naming the files
|
||||
# that matched, which is what triage asks for first.
|
||||
plan["matching"] = {suite_id: sorted(names) for suite_id, names in matches.items()}
|
||||
if always_hits:
|
||||
notes.append(f"always-run: {', '.join(sorted(always_hits)[:5])}")
|
||||
return full_plan(
|
||||
plan,
|
||||
"always-run path: " + ", ".join(sorted(always_hits)[:3]),
|
||||
"always-run",
|
||||
)
|
||||
|
||||
first = first_uncovered(files, matches)
|
||||
if first is not None:
|
||||
notes.append(f"uncovered build change: {first}")
|
||||
return full_plan(plan, f"uncovered build change: {first}", "uncovered")
|
||||
|
||||
static_run = {suite_id: bool(matched) for suite_id, matched in matches.items()}
|
||||
|
||||
if not has_meaningful_changes(files) and not any(static_run.values()):
|
||||
plan.update(
|
||||
mode="static",
|
||||
full=False,
|
||||
suites={
|
||||
suite_id: {
|
||||
"run": False,
|
||||
"source": "static",
|
||||
"reason": "no code, config or workflow file changed",
|
||||
}
|
||||
for suite_id in SUITES
|
||||
},
|
||||
)
|
||||
notes.append("no meaningful changes: skip every suite")
|
||||
return finalize(plan)
|
||||
|
||||
plan.update(
|
||||
mode="static",
|
||||
suites={
|
||||
suite_id: {
|
||||
"run": static_run[suite_id],
|
||||
"source": "static",
|
||||
"reason": ("path rule: " + ", ".join(matches[suite_id][:3]))
|
||||
if matches[suite_id]
|
||||
else "no path rule matched",
|
||||
}
|
||||
for suite_id in SUITES
|
||||
},
|
||||
)
|
||||
return finalize(plan)
|
||||
|
||||
|
||||
def derive_outputs(plan):
|
||||
"""Flatten the plan into the `$GITHUB_OUTPUT` keys the workflow gates on.
|
||||
|
||||
|
||||
Every gate in `SUITES` must route to a key here, otherwise its suites are
|
||||
classified but never switch a job; `test_every_gate_routes_to_an_output`
|
||||
asks this function directly, so a new gate fails there until it is routed.
|
||||
|
||||
|
||||
Job-level `if:` cannot read the `matrix` context, so the workflow gates a
|
||||
whole fuzz gate instead of individual matrix legs; the per-suite verdicts
|
||||
stay visible in the step log.
|
||||
"""
|
||||
|
||||
def suites_of(gate):
|
||||
return [
|
||||
suite_id
|
||||
for suite_id, entry in plan["suites"].items()
|
||||
if entry["run"] and SUITES[suite_id]["gate"] == gate
|
||||
]
|
||||
|
||||
outputs = {}
|
||||
legs = {}
|
||||
for gate in FUZZ_GATES:
|
||||
running = suites_of(gate)
|
||||
legs[gate] = [suite_group(suite_id) for suite_id in running]
|
||||
legs[gate] = [leg for leg in legs[gate] if leg]
|
||||
outputs[gate] = "true" if running else "false"
|
||||
unstable = bool(suites_of("fuzz_unstable"))
|
||||
# Every gate outside the fuzz group switches exactly one job of its own.
|
||||
for gate in sorted({suite["gate"] for suite in SUITES.values()}):
|
||||
if gate not in FUZZ_GATES:
|
||||
outputs[gate] = "true" if suites_of(gate) else "false"
|
||||
outputs["any_fuzz"] = (
|
||||
"true"
|
||||
if unstable or any(outputs[gate] == "true" for gate in FUZZ_GATES)
|
||||
else "false"
|
||||
)
|
||||
distributed = outputs["fuzz_distributed"] == "true" or outputs["fuzz_chaos"] == "true"
|
||||
outputs["build_ci_needed"] = "true" if unstable or distributed else "false"
|
||||
return outputs, legs
|
||||
|
||||
|
||||
def render_log(plan):
|
||||
"""One line per suite plus the emitted gates, for the step log.
|
||||
|
||||
Triage starts in the run log, so the verdict has to be readable there
|
||||
without any other artifact.
|
||||
"""
|
||||
head = f"CI scope: mode={plan['mode']} full={'true' if plan['full'] else 'false'}"
|
||||
lines = [head]
|
||||
width = max((len(suite_id) for suite_id in plan["suites"]), default=0)
|
||||
for suite_id, entry in plan["suites"].items():
|
||||
lines.append(
|
||||
f" {'run ' if entry['run'] else 'skip'} {suite_id:<{width}} "
|
||||
f"{entry['source']:<12} {entry['reason']}"
|
||||
)
|
||||
outputs, _ = derive_outputs(plan)
|
||||
lines.append(
|
||||
" gates: " + " ".join(f"{key}={value}" for key, value in outputs.items())
|
||||
)
|
||||
for note in plan["notes"]:
|
||||
lines.append(f" note: {note}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
SUMMARY_MAX_FILES = 3
|
||||
|
||||
|
||||
def render_summary(plan):
|
||||
"""Markdown for the job summary: the matching evidence behind each verdict.
|
||||
|
||||
The step log answers "what ran"; this answers "why", which is the question
|
||||
when a pull request unexpectedly skips or starts a suite.
|
||||
"""
|
||||
lines = [
|
||||
f"### CI scope: mode={plan['mode']}, full={'true' if plan['full'] else 'false'}",
|
||||
"",
|
||||
"| suite | verdict | rule | matched files |",
|
||||
"| --- | --- | --- | --- |",
|
||||
]
|
||||
matching = plan.get("matching") or {}
|
||||
for suite_id, entry in plan["suites"].items():
|
||||
matched = matching.get(suite_id) or []
|
||||
shown = ", ".join(f"`{name}`" for name in matched[:SUMMARY_MAX_FILES])
|
||||
if len(matched) > SUMMARY_MAX_FILES:
|
||||
shown += f" +{len(matched) - SUMMARY_MAX_FILES} more"
|
||||
lines.append(
|
||||
f"| `{suite_id}` | {'run' if entry['run'] else 'skip'} | "
|
||||
f"{entry['source']} | {shown or '—'} |"
|
||||
)
|
||||
if plan["notes"]:
|
||||
lines += ["", "<details><summary>notes</summary>", ""]
|
||||
lines += [f"- {note}" for note in plan["notes"]]
|
||||
lines += ["", "</details>"]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def log_annotations(plan):
|
||||
"""Workflow-run annotations for every degraded decision.
|
||||
|
||||
A lookup failure widens the gate; it must be visible in the run list without
|
||||
opening the job log, otherwise it looks like a confident verdict.
|
||||
"""
|
||||
annotations = []
|
||||
for note in plan["notes"]:
|
||||
if note.startswith("pull request lookup failed"):
|
||||
suffix = "every suite runs"
|
||||
level = "warning"
|
||||
else:
|
||||
continue
|
||||
message = f"CI scope: {note}; {suffix}"[:300]
|
||||
annotations.append(f"::{level}::{message}")
|
||||
return annotations
|
||||
|
||||
|
||||
def emit(plan, args):
|
||||
outputs, _ = derive_outputs(plan)
|
||||
if args.dry_run:
|
||||
print(json.dumps(outputs, indent=2))
|
||||
elif args.github_output:
|
||||
with open(args.github_output, "a", encoding="utf-8") as handle:
|
||||
for key, value in outputs.items():
|
||||
handle.write(f"{key}={value}\n")
|
||||
if args.summary:
|
||||
with open(args.summary, "a", encoding="utf-8") as handle:
|
||||
handle.write(render_summary(plan) + "\n")
|
||||
|
||||
|
||||
def parse_args(argv):
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("--repo", default=os.environ.get("GITHUB_REPOSITORY", ""))
|
||||
parser.add_argument("--pr", type=int)
|
||||
parser.add_argument("--head-sha", default="")
|
||||
parser.add_argument("--base-sha", default="")
|
||||
parser.add_argument(
|
||||
"--event",
|
||||
choices=["pull_request", "merge_group", "schedule", "workflow_dispatch"],
|
||||
)
|
||||
parser.add_argument("--github-output")
|
||||
parser.add_argument(
|
||||
"--summary",
|
||||
help="append the markdown matching table to this file ($GITHUB_STEP_SUMMARY)",
|
||||
)
|
||||
parser.add_argument("--dry-run", action="store_true")
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
args = parse_args(argv)
|
||||
token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN") or ""
|
||||
plan = build_plan(args, token)
|
||||
for annotation in log_annotations(plan):
|
||||
print(annotation)
|
||||
print(render_log(plan))
|
||||
emit(plan, args)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+277
@@ -0,0 +1,277 @@
|
||||
#!/usr/bin/env python3
|
||||
# Copyright 2023 Greptime Team
|
||||
#
|
||||
# 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.
|
||||
|
||||
"""Policy for the integration CI admission gate.
|
||||
|
||||
The rules are data and live in `.github/ci/scope-rules.toml` so they can be
|
||||
reviewed and changed without touching the classifier. This module parses that
|
||||
file once at import, validates it, and exposes the names `ci_scope.py` uses.
|
||||
|
||||
A malformed file raises at import: the classifier job's steps are
|
||||
`continue-on-error`, so a broken rules file leaves the gate outputs empty and
|
||||
every gated job runs.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import pathlib
|
||||
import sys
|
||||
import tomllib
|
||||
|
||||
RULES_PATH = pathlib.Path(__file__).resolve().with_name("scope-rules.toml")
|
||||
# `.github/ci/scope-rules.toml`: parents[0] is `.github/ci`, parents[2] the repo.
|
||||
REPO_ROOT = RULES_PATH.parents[2]
|
||||
|
||||
|
||||
|
||||
class RulesError(ValueError):
|
||||
"""The rules file is missing, malformed or internally inconsistent."""
|
||||
|
||||
|
||||
def _require(table, key, where):
|
||||
if key not in table:
|
||||
raise RulesError(f"{where} is missing `{key}`")
|
||||
return table[key]
|
||||
|
||||
|
||||
def _strings(value, where):
|
||||
if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
|
||||
raise RulesError(f"{where} must be an array of strings")
|
||||
return list(value)
|
||||
|
||||
|
||||
def _trees(entries, where):
|
||||
"""Normalise `[[matching.*_tree]]` tables into bare path prefixes.
|
||||
|
||||
Each entry carries a `reason`: the exclusions decide what CI never runs, so
|
||||
the justification is part of the contract, not a comment.
|
||||
"""
|
||||
if not isinstance(entries, list):
|
||||
raise RulesError(f"{where} must be an array of tables")
|
||||
paths = []
|
||||
for index, entry in enumerate(entries):
|
||||
if not isinstance(entry, dict):
|
||||
raise RulesError(f"{where}[{index}] is not a table")
|
||||
path = _require(entry, "path", f"{where}[{index}]")
|
||||
if not isinstance(path, str) or not path:
|
||||
raise RulesError(f"{where}[{index}].path must be a non-empty string")
|
||||
reason = _require(entry, "reason", f"{where}[{index}]")
|
||||
if not isinstance(reason, str) or not reason.strip():
|
||||
raise RulesError(f"{where}[{index}].reason must explain the exclusion")
|
||||
paths.append(path)
|
||||
return paths
|
||||
|
||||
|
||||
def validate(data):
|
||||
"""Check the shape of a parsed rules document and return it normalised."""
|
||||
if not isinstance(data, dict):
|
||||
raise RulesError("rules document is not a table")
|
||||
matching = _require(data, "matching", "the rules file")
|
||||
gates_in = _require(data, "gates", "the rules file")
|
||||
groups_in = _require(data, "groups", "the rules file")
|
||||
suites_in = _require(data, "suites", "the rules file")
|
||||
|
||||
groups = {}
|
||||
for name, paths in groups_in.items():
|
||||
groups[name] = _strings(paths, f"groups.{name}")
|
||||
|
||||
def expand(entries, stack=()):
|
||||
out = []
|
||||
for entry in entries:
|
||||
if not entry.startswith("@"):
|
||||
out.append(entry)
|
||||
continue
|
||||
name = entry[1:]
|
||||
if name not in groups:
|
||||
raise RulesError(f"unknown path group `{entry}`")
|
||||
if name in stack:
|
||||
raise RulesError(f"path group cycle: {' -> '.join(stack + (name,))}")
|
||||
out.extend(expand(groups[name], stack + (name,)))
|
||||
return out
|
||||
|
||||
for name in groups:
|
||||
expand([f"@{name}"]) # every group must resolve on its own
|
||||
|
||||
suites = {}
|
||||
for suite_id, suite in suites_in.items():
|
||||
if not isinstance(suite, dict):
|
||||
raise RulesError(f"suites.{suite_id} is not a table")
|
||||
gate = _require(suite, "gate", f"suites.{suite_id}")
|
||||
paths = _strings(
|
||||
_require(suite, "paths", f"suites.{suite_id}"), f"suites.{suite_id}.paths"
|
||||
)
|
||||
description = _require(suite, "description", f"suites.{suite_id}")
|
||||
if not isinstance(description, str) or not description.strip():
|
||||
raise RulesError(f"suites.{suite_id}.description is empty")
|
||||
# `gate/leg` for a matrix job, or a bare gate for a single-leg job.
|
||||
prefix = suite_id.split("/", 1)[0].replace("-", "_")
|
||||
if prefix != gate:
|
||||
raise RulesError(
|
||||
f"suites.{suite_id}.gate is `{gate}`, expected `{prefix}`"
|
||||
)
|
||||
expand(paths)
|
||||
suites[suite_id] = {
|
||||
"gate": gate,
|
||||
"paths": paths,
|
||||
"description": description,
|
||||
}
|
||||
|
||||
gate_jobs = {}
|
||||
for gate, job in gates_in.items():
|
||||
if not isinstance(job, str) or not job:
|
||||
raise RulesError(f"gates.{gate} must name a job id")
|
||||
gate_jobs[gate] = job
|
||||
used = {suite["gate"] for suite in suites.values()}
|
||||
unknown = sorted(used - set(gate_jobs))
|
||||
if unknown:
|
||||
raise RulesError(f"suites use gates missing from [gates]: {', '.join(unknown)}")
|
||||
dead = sorted(set(gate_jobs) - used)
|
||||
if dead:
|
||||
raise RulesError(f"[gates] names gates no suite uses: {', '.join(dead)}")
|
||||
|
||||
return {
|
||||
"always_run": _strings(
|
||||
_require(matching, "always_run", "matching"), "matching.always_run"
|
||||
),
|
||||
"src_tree": _require(matching, "src_tree", "matching"),
|
||||
"exempt_trees": _trees(
|
||||
_require(matching, "exempt", "matching"), "matching.exempt"
|
||||
),
|
||||
"gates": gate_jobs,
|
||||
"groups": groups,
|
||||
"suites": suites,
|
||||
}
|
||||
|
||||
|
||||
def load(path=None):
|
||||
"""Parse and validate the rules file."""
|
||||
path = RULES_PATH if path is None else path
|
||||
try:
|
||||
raw = pathlib.Path(path).read_bytes()
|
||||
except OSError as err:
|
||||
raise RulesError(f"cannot read {path}: {err}") from err
|
||||
try:
|
||||
data = tomllib.loads(raw.decode("utf-8"))
|
||||
except (tomllib.TOMLDecodeError, UnicodeDecodeError) as err:
|
||||
raise RulesError(f"{path} is not valid TOML: {err}") from err
|
||||
return validate(data)
|
||||
|
||||
|
||||
_RULES = load()
|
||||
|
||||
ALWAYS_RUN = _RULES["always_run"]
|
||||
SRC_TREE = _RULES["src_tree"]
|
||||
EXEMPT_TREES = tuple(_RULES["exempt_trees"])
|
||||
GATE_JOBS = _RULES["gates"]
|
||||
PATH_GROUPS = _RULES["groups"]
|
||||
SUITES = _RULES["suites"]
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
"""Validate the rules file and print what it holds; non-zero on failure."""
|
||||
parser = argparse.ArgumentParser(description="Validate the CI scope rules.")
|
||||
parser.add_argument(
|
||||
"--check-paths",
|
||||
action="store_true",
|
||||
help="also fail when a pattern's literal prefix does not exist",
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
rules = load()
|
||||
except RulesError as err:
|
||||
print(f"scope rules invalid: {err}", file=sys.stderr)
|
||||
return 1
|
||||
if args.check_paths:
|
||||
missing = missing_paths(rules)
|
||||
for pattern, prefix in missing:
|
||||
print(f"missing path: {pattern} (nothing under {prefix})", file=sys.stderr)
|
||||
return 1 if missing else 0
|
||||
print(
|
||||
f"scope rules ok: {len(rules['suites'])} suites, "
|
||||
f"{len(rules['groups'])} path groups, "
|
||||
f"{len(rules['always_run'])} always-run entries"
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
def suite_group(suite_id):
|
||||
"""Return the matrix group id encoded in a suite id, or None."""
|
||||
_, _, group = suite_id.partition("/")
|
||||
return group or None
|
||||
|
||||
|
||||
def expand_paths(entries, groups=None):
|
||||
"""Expand `@group` references, including groups nested in other groups."""
|
||||
groups = PATH_GROUPS if groups is None else groups
|
||||
patterns = []
|
||||
for entry in entries:
|
||||
if entry.startswith("@"):
|
||||
patterns.extend(expand_paths(groups[entry[1:]], groups))
|
||||
else:
|
||||
patterns.append(entry)
|
||||
return patterns
|
||||
|
||||
|
||||
def suite_paths(suite):
|
||||
"""Expand `@group` references in one suite definition into globs."""
|
||||
return expand_paths(suite["paths"])
|
||||
|
||||
|
||||
def _literal_prefix(pattern):
|
||||
"""Return the longest leading path that the glob cannot vary.
|
||||
|
||||
Everything from the first `*`, `?` or `[` onwards is variable. When that
|
||||
wildcard sits inside a segment the incomplete segment is dropped, so
|
||||
`src/a/foo*.rs` yields `src/a/`; a wildcard in the very first segment (for
|
||||
example `*.md`) yields `""` because the whole path is variable.
|
||||
"""
|
||||
cuts = [pattern.find(ch) for ch in "*?[" if ch in pattern]
|
||||
if not cuts:
|
||||
return pattern
|
||||
prefix = pattern[: min(cuts)]
|
||||
if "/" not in prefix:
|
||||
return ""
|
||||
return prefix.rsplit("/", 1)[0] + "/"
|
||||
|
||||
|
||||
def _all_patterns(rules):
|
||||
"""Every glob the rules mention, with `@group` references expanded."""
|
||||
patterns = []
|
||||
for key in ("always_run", "exempt_trees"):
|
||||
patterns.extend(expand_paths(rules[key], rules["groups"]))
|
||||
for suite in rules["suites"].values():
|
||||
patterns.extend(expand_paths(suite["paths"], rules["groups"]))
|
||||
return patterns
|
||||
|
||||
|
||||
def missing_paths(rules=None, root=None):
|
||||
"""Return `(pattern, prefix)` for patterns whose literal prefix is absent.
|
||||
|
||||
A rule that names a directory nobody renamed would otherwise match nothing
|
||||
forever, silently narrowing the gate. A pattern with no fixed prefix is
|
||||
skipped: there is nothing on disk to check.
|
||||
"""
|
||||
rules = _RULES if rules is None else rules
|
||||
root = pathlib.Path(REPO_ROOT if root is None else root)
|
||||
missing = set()
|
||||
for pattern in _all_patterns(rules):
|
||||
prefix = _literal_prefix(pattern)
|
||||
if prefix and not (root / prefix).exists():
|
||||
missing.add((pattern, prefix))
|
||||
return sorted(missing)
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,285 @@
|
||||
# Rules for the integration CI admission gate.
|
||||
#
|
||||
# Data only: `ci_scope_rules.py` loads this file with the stdlib `tomllib`, and
|
||||
# `ci_scope.py` matches diffs against it. Edit this file, not the code, when a
|
||||
# suite's paths change.
|
||||
#
|
||||
# Conventions
|
||||
# -----------
|
||||
# - `**` crosses directories, `*` does not; a trailing `/**` covers everything
|
||||
# under a directory.
|
||||
# - `@name` inside `suites.*.paths` expands `[groups].name`, and groups may
|
||||
# reference other groups. Expansion is recursive.
|
||||
# - A suite id is `<gate>/<matrix group id>`; `gate` is the `$GITHUB_OUTPUT`
|
||||
# key that switches the job, and it must equal the id prefix with `-`
|
||||
# replaced by `_`.
|
||||
# - Everything here is a floor, never a filter: an unmatched `src/` path runs
|
||||
# every suite, and a malformed file fails the classifier job, whose steps are
|
||||
# `continue-on-error`, so the gated jobs run.
|
||||
|
||||
[matching]
|
||||
# A changed file matching one of these runs every suite.
|
||||
# Put here anything that changes what the suites build or how they start.
|
||||
always_run = [
|
||||
"Cargo.toml",
|
||||
"Cargo.lock",
|
||||
"rust-toolchain.toml",
|
||||
".cargo/**",
|
||||
"tests-fuzz/**",
|
||||
"tests-integration/**",
|
||||
"config/**",
|
||||
"docker/**",
|
||||
".github/ci/**",
|
||||
".github/workflows/integration.yml",
|
||||
".github/actions/**",
|
||||
# Both run through a composite action, so neither appears in the workflow:
|
||||
# `setup-kind` starts the cluster for the distributed and chaos jobs, and
|
||||
# `fuzz-test` seeds the corpus every fuzz job starts from.
|
||||
".github/scripts/kind-with-registry.sh",
|
||||
".github/scripts/prepare-fuzz-corpus.sh",
|
||||
".github/scripts/run-fuzz-targets.sh",
|
||||
".github/scripts/collect-fuzz-target-artifacts.sh",
|
||||
".github/scripts/wait-kafka-ready.sh",
|
||||
".github/scripts/pull-test-deps-images.sh",
|
||||
]
|
||||
|
||||
# A change under `src/` that no suite claims runs every suite: that is the net
|
||||
# for a crate added, split or renamed after these rules were written.
|
||||
src_tree = "src/"
|
||||
|
||||
# Paths outside the gate's remit. They select no suite, and they do not count as
|
||||
# "no rule covers this" either, so they never widen the gate. Each needs a
|
||||
# `reason`: what CI covers them instead.
|
||||
[[matching.exempt]]
|
||||
path = "src/promql/"
|
||||
reason = "PromQL crate: rust.yml and the promql sqlness cases own it; the fuzz suites speak SQL."
|
||||
|
||||
[[matching.exempt]]
|
||||
path = "src/query/src/promql/"
|
||||
reason = "PromQL module inside `src/query`, which `@server` claims as `src/query/**`."
|
||||
|
||||
[[matching.exempt]]
|
||||
path = "src/flow/"
|
||||
reason = "Flow engine: rust.yml and the flow sqlness cases own it; no fuzz suite loads it."
|
||||
|
||||
# Which job each gate switches. The keys are `$GITHUB_OUTPUT` names; the values
|
||||
# are job ids in `integration.yml`. The classifier cannot read YAML, so the
|
||||
# mapping is data here, and a test proves both directions line up.
|
||||
[gates]
|
||||
fuzz_standalone = "fuzztest"
|
||||
fuzz_unstable = "unstable-fuzztest"
|
||||
fuzz_distributed = "distributed-fuzztest"
|
||||
fuzz_chaos = "distributed-fuzztest-with-chaos"
|
||||
export_import_v2 = "export-import-v2-e2e"
|
||||
sqlness_kvbackend = "sqlness-kvbackend"
|
||||
|
||||
[groups]
|
||||
server = [
|
||||
"src/operator/**",
|
||||
"src/sql/**",
|
||||
"src/catalog/**",
|
||||
"src/datatypes/**",
|
||||
"src/table/**",
|
||||
"src/store-api/**",
|
||||
"src/session/**",
|
||||
"src/api/**",
|
||||
"src/servers/**",
|
||||
"src/frontend/**",
|
||||
# Also covers `src/query/src/promql/`, which is exempt (see
|
||||
# `[[matching.exempt]]`): a PromQL-only change must not run the fuzz fleet.
|
||||
"src/query/**",
|
||||
"src/partition/**",
|
||||
"src/index/**",
|
||||
"src/object-store/**",
|
||||
"src/cache/**",
|
||||
"src/puffin/**",
|
||||
"src/auth/**",
|
||||
"src/client/**",
|
||||
"src/log-query/**",
|
||||
"src/pipeline/**",
|
||||
"src/plugins/**",
|
||||
"src/cmd/**",
|
||||
"src/standalone/**",
|
||||
"src/datanode/**",
|
||||
"src/common/base/**",
|
||||
"src/common/batcher/**",
|
||||
"src/common/cache/**",
|
||||
"src/common/catalog/**",
|
||||
"src/common/config/**",
|
||||
"src/common/datasource/**",
|
||||
"src/common/decimal/**",
|
||||
"src/common/error/**",
|
||||
"src/common/event-recorder/**",
|
||||
"src/common/frontend/**",
|
||||
"src/common/function/**",
|
||||
"src/common/grpc/**",
|
||||
"src/common/grpc-expr/**",
|
||||
"src/common/greptimedb-telemetry/**",
|
||||
"src/common/macro/**",
|
||||
"src/common/mem-prof/**",
|
||||
"src/common/memory-manager/**",
|
||||
"src/common/options/**",
|
||||
"src/common/plugins/**",
|
||||
"src/common/pprof/**",
|
||||
"src/common/query/**",
|
||||
"src/common/recordbatch/**",
|
||||
"src/common/runtime/**",
|
||||
"src/common/session/**",
|
||||
"src/common/sql/**",
|
||||
"src/common/stat/**",
|
||||
"src/common/substrait/**",
|
||||
"src/common/telemetry/**",
|
||||
"src/common/test-util/**",
|
||||
"src/common/time/**",
|
||||
"src/common/version/**",
|
||||
"src/common/workload/**",
|
||||
]
|
||||
|
||||
# Storage engines and WAL.
|
||||
engine = [
|
||||
"src/mito2/**",
|
||||
"src/mito-codec/**",
|
||||
"src/metric-engine/**",
|
||||
"src/file-engine/**",
|
||||
"src/log-store/**",
|
||||
"src/common/wal/**",
|
||||
]
|
||||
|
||||
# DDL and procedure code standalone executes in-process: it builds a
|
||||
# `DdlManager` and runs `LocalProcedureExecutor` without any metasrv.
|
||||
meta-core = [
|
||||
"src/common/meta/**",
|
||||
"src/common/procedure/**",
|
||||
"src/common/procedure-test/**",
|
||||
]
|
||||
|
||||
# Everything that sits on the KV backend the two sqlness KvBackend legs
|
||||
# exercise: the backend implementations, the metadata service and the startup
|
||||
# wiring that picks a backend.
|
||||
kv-backend = [
|
||||
# The runner implements `--setup-pg`/`--setup-mysql`, which only these legs pass.
|
||||
"tests/runner/**",
|
||||
"src/common/meta/**",
|
||||
"src/meta-srv/**",
|
||||
"src/meta-client/**",
|
||||
"src/common/procedure/**",
|
||||
"src/cmd/**",
|
||||
"src/common/config/**",
|
||||
"src/common/options/**",
|
||||
]
|
||||
|
||||
# Adds the metasrv/meta-client crates on top of the in-process DDL code.
|
||||
meta = [
|
||||
"src/meta-srv/**",
|
||||
"src/meta-client/**",
|
||||
"@meta-core",
|
||||
]
|
||||
|
||||
[suites."fuzz-standalone/database-and-regular-table"]
|
||||
gate = "fuzz_standalone"
|
||||
paths = [
|
||||
"@server",
|
||||
"@engine",
|
||||
"@meta-core",
|
||||
]
|
||||
description = "Standalone-server black-box fuzz of CREATE DATABASE/TABLE, ALTER, INSERT over MySQL."
|
||||
|
||||
[suites."fuzz-standalone/logical-table"]
|
||||
gate = "fuzz_standalone"
|
||||
paths = [
|
||||
"@server",
|
||||
"@engine",
|
||||
"@meta-core",
|
||||
]
|
||||
description = "Standalone logical-table DDL/INSERT fuzz (mito2 logical tables)."
|
||||
|
||||
[suites."fuzz-unstable/standalone"]
|
||||
gate = "fuzz_unstable"
|
||||
paths = [
|
||||
"@server",
|
||||
"@engine",
|
||||
"@meta-core",
|
||||
]
|
||||
description = "Unstable standalone create-table fuzz (nix build feature)."
|
||||
|
||||
[suites."fuzz-distributed/database-and-regular-table"]
|
||||
gate = "fuzz_distributed"
|
||||
paths = [
|
||||
"@server",
|
||||
"@engine",
|
||||
"@meta",
|
||||
]
|
||||
description = "Distributed (frontend/datanode/metasrv, remote WAL) DDL/DML fuzz."
|
||||
|
||||
[suites."fuzz-distributed/logical-table"]
|
||||
gate = "fuzz_distributed"
|
||||
paths = [
|
||||
"@server",
|
||||
"@engine",
|
||||
"@meta",
|
||||
]
|
||||
description = "Distributed logical-table fuzz."
|
||||
|
||||
[suites."fuzz-distributed/repartition"]
|
||||
gate = "fuzz_distributed"
|
||||
paths = [
|
||||
"@server",
|
||||
"@engine",
|
||||
"@meta",
|
||||
]
|
||||
description = "Distributed repartition ALTER TABLE + GC fuzz."
|
||||
|
||||
[suites."fuzz-distributed/logical-pruning"]
|
||||
gate = "fuzz_distributed"
|
||||
paths = [
|
||||
"@engine",
|
||||
"@meta",
|
||||
]
|
||||
description = "Remote-WAL logical table pruning of stale manifests."
|
||||
|
||||
[suites."fuzz-chaos/migration"]
|
||||
gate = "fuzz_chaos"
|
||||
paths = [
|
||||
"@server",
|
||||
"@engine",
|
||||
"@meta",
|
||||
]
|
||||
description = "Region migration under Chaos Mesh, mito and metric engines."
|
||||
|
||||
[suites."fuzz-chaos/failover"]
|
||||
gate = "fuzz_chaos"
|
||||
paths = [
|
||||
"@server",
|
||||
"@engine",
|
||||
"@meta",
|
||||
]
|
||||
description = "Region failover under Chaos Mesh, mito and metric engines."
|
||||
|
||||
[suites."fuzz-chaos/repartition"]
|
||||
gate = "fuzz_chaos"
|
||||
paths = [
|
||||
"@server",
|
||||
"@engine",
|
||||
"@meta",
|
||||
]
|
||||
description = "Repartition + GC under Chaos Mesh."
|
||||
|
||||
[suites."export-import-v2"]
|
||||
gate = "export_import_v2"
|
||||
paths = [
|
||||
"src/cli/**",
|
||||
"@server",
|
||||
"@engine",
|
||||
"@meta-core",
|
||||
]
|
||||
description = "CLI COPY DATABASE export/import v2 end-to-end against S3."
|
||||
|
||||
[suites."sqlness-kvbackend/metasrv-postgres"]
|
||||
gate = "sqlness_kvbackend"
|
||||
paths = ["@kv-backend"]
|
||||
description = "Sqlness with PostgreSQL as the metadata KV backend."
|
||||
|
||||
[suites."sqlness-kvbackend/metasrv-mysql"]
|
||||
gate = "sqlness_kvbackend"
|
||||
paths = ["@kv-backend"]
|
||||
description = "Sqlness with MySQL as the metadata KV backend."
|
||||
@@ -0,0 +1,158 @@
|
||||
# Golden cases for the admission gate.
|
||||
#
|
||||
# `tests/test_ci_scope.py` replays every case through the real classifier,
|
||||
# so an edit to `scope-rules.toml` that changes behaviour fails with the case
|
||||
# name here. The cases encode intent, not implementation: each one says which
|
||||
# suites a kind of change must start.
|
||||
#
|
||||
# `suites` is a list of globs over suite ids; `["*"]` means every suite and
|
||||
# `[]` means none.
|
||||
|
||||
[[case]]
|
||||
name = "server crate: the whole fuzz fleet except the pruning suite"
|
||||
note = "A change to `src/api` reaches every suite that builds the server binary."
|
||||
paths = [
|
||||
"src/api/src/lib.rs",
|
||||
]
|
||||
suites = [
|
||||
"fuzz-standalone/database-and-regular-table",
|
||||
"fuzz-standalone/logical-table",
|
||||
"fuzz-unstable/standalone",
|
||||
"fuzz-distributed/database-and-regular-table",
|
||||
"fuzz-distributed/logical-table",
|
||||
"fuzz-distributed/repartition",
|
||||
"fuzz-chaos/migration",
|
||||
"fuzz-chaos/failover",
|
||||
"fuzz-chaos/repartition",
|
||||
"export-import-v2",
|
||||
]
|
||||
|
||||
[[case]]
|
||||
name = "storage engine: every fuzz suite, including remote-WAL pruning"
|
||||
note = "logical-pruning needs engine and DDL code, so an engine change starts it."
|
||||
paths = [
|
||||
"src/mito2/src/lib.rs",
|
||||
]
|
||||
suites = [
|
||||
"fuzz-standalone/*",
|
||||
"fuzz-unstable/*",
|
||||
"fuzz-distributed/*",
|
||||
"fuzz-chaos/*",
|
||||
"export-import-v2",
|
||||
]
|
||||
|
||||
[[case]]
|
||||
name = "in-process DDL code registers the procedures standalone executes"
|
||||
paths = [
|
||||
"src/common/meta/src/lib.rs",
|
||||
]
|
||||
suites = [
|
||||
"fuzz-standalone/*",
|
||||
"fuzz-unstable/*",
|
||||
"fuzz-distributed/*",
|
||||
"fuzz-chaos/*",
|
||||
"export-import-v2",
|
||||
"sqlness-kvbackend/*",
|
||||
]
|
||||
|
||||
[[case]]
|
||||
name = "metasrv only: distributed and chaos families"
|
||||
note = "Standalone builds a DdlManager in-process and never links a metasrv."
|
||||
paths = [
|
||||
"src/meta-srv/src/discovery/lease.rs",
|
||||
]
|
||||
suites = [
|
||||
"fuzz-distributed/database-and-regular-table",
|
||||
"fuzz-distributed/logical-table",
|
||||
"fuzz-distributed/repartition",
|
||||
"fuzz-distributed/logical-pruning",
|
||||
"fuzz-chaos/migration",
|
||||
"fuzz-chaos/failover",
|
||||
"fuzz-chaos/repartition",
|
||||
"sqlness-kvbackend/*",
|
||||
]
|
||||
|
||||
[[case]]
|
||||
name = "CLI only touches the export/import path"
|
||||
paths = [
|
||||
"src/cli/src/lib.rs",
|
||||
]
|
||||
suites = [
|
||||
"export-import-v2",
|
||||
]
|
||||
|
||||
[[case]]
|
||||
name = "PromQL crate: no suite"
|
||||
note = "rust.yml and the promql sqlness cases own it; the fuzz suites speak SQL."
|
||||
paths = [
|
||||
"src/promql/src/lib.rs",
|
||||
]
|
||||
suites = []
|
||||
|
||||
[[case]]
|
||||
name = "PromQL module inside the query crate is not fuzzable either"
|
||||
note = "`@server` claims `src/query/**`, so the module must be exempt."
|
||||
paths = [
|
||||
"src/query/src/promql/src/lib.rs",
|
||||
]
|
||||
suites = []
|
||||
|
||||
[[case]]
|
||||
name = "flow engine: no suite"
|
||||
paths = [
|
||||
"src/flow/src/lib.rs",
|
||||
]
|
||||
suites = []
|
||||
|
||||
[[case]]
|
||||
name = "mixed diff: the PromQL file subtracts nothing"
|
||||
note = "The engine change still starts every suite."
|
||||
paths = [
|
||||
"src/mito2/src/lib.rs",
|
||||
"src/promql/src/lib.rs",
|
||||
]
|
||||
suites = [
|
||||
"fuzz-standalone/*",
|
||||
"fuzz-unstable/*",
|
||||
"fuzz-distributed/*",
|
||||
"fuzz-chaos/*",
|
||||
"export-import-v2",
|
||||
]
|
||||
|
||||
[[case]]
|
||||
name = "crate added after the rules were written"
|
||||
note = "No suite claims it, so the gate widens instead of skipping everything."
|
||||
paths = [
|
||||
"src/brand-new/src/lib.rs",
|
||||
]
|
||||
suites = ["*"]
|
||||
|
||||
[[case]]
|
||||
name = "integration harness change"
|
||||
paths = [
|
||||
"tests-integration/tests/fuzz.rs",
|
||||
]
|
||||
suites = ["*"]
|
||||
|
||||
[[case]]
|
||||
name = "documentation only"
|
||||
paths = [
|
||||
"docs/readme.md",
|
||||
]
|
||||
suites = []
|
||||
|
||||
[[case]]
|
||||
name = "kind registry setup: every suite"
|
||||
note = "The distributed and chaos fuzz jobs start their cluster with this script."
|
||||
paths = [
|
||||
".github/scripts/kind-with-registry.sh",
|
||||
]
|
||||
suites = ["*"]
|
||||
|
||||
[[case]]
|
||||
name = "fuzz corpus seeding: every suite"
|
||||
note = "Every fuzz job seeds its corpus through the `fuzz-test` action first."
|
||||
paths = [
|
||||
".github/scripts/prepare-fuzz-corpus.sh",
|
||||
]
|
||||
suites = ["*"]
|
||||
Executable
+1018
File diff suppressed because it is too large
Load Diff
+3
-3
@@ -5,9 +5,9 @@ nextest and Windows SQLness run in the existing Nightly CI workflow, which also
|
||||
supports manual dispatch. Its existing schedule is Tuesday through Friday at
|
||||
07:00 Asia/Shanghai, not every day. No new Windows test job is added.
|
||||
|
||||
Integration CI runs all fuzz suites when a non-draft PR is opened or marked
|
||||
ready for review, and on its existing weekday schedule (23:00 Asia/Shanghai,
|
||||
Monday through Friday). Ordinary pushes and reopening do not run fuzz; core
|
||||
Integration CI admits fuzz when a non-draft PR is opened or marked ready for
|
||||
review, selecting suites with the existing diff-scope classifier. Its weekday
|
||||
schedule (23:00 Asia/Shanghai, Monday through Friday) runs all fuzz suites. Ordinary pushes and reopening do not run fuzz; core
|
||||
integration checks still run. Merge groups continue to skip fuzz.
|
||||
|
||||
Re-running an ordinary push-triggered Integration CI run does not enable fuzz.
|
||||
|
||||
@@ -6,15 +6,17 @@ const workflows = resolve(__dirname, '../workflows');
|
||||
const integration = readFileSync(resolve(workflows, 'integration.yml'), 'utf8');
|
||||
const suites = ['fuzztest', 'unstable-fuzztest', 'distributed-fuzztest', 'distributed-fuzztest-with-chaos'];
|
||||
const prerequisites = ['prepare-fuzz-targets', 'build-greptime-ci'];
|
||||
function enabled(job, { event = 'pull_request', action = 'synchronize', draft = false, attempt = 1, profile = 'none', repository = 'GreptimeTeam/greptimedb' } = {}) {
|
||||
function enabled(job, { event = 'pull_request', action = 'synchronize', draft = false, attempt = 1, profile = 'none', repository = 'GreptimeTeam/greptimedb', outputs = {}, results = {}, cancelled = false } = {}) {
|
||||
const expression = integration.match(new RegExp(`^ ${job}:\\n if: \\$\\{\\{ (.+) \\}\\}`, 'm'))[1];
|
||||
// These job guards use only operators whose semantics match JS for this fixture.
|
||||
return new Function('github', 'inputs', `return (${expression});`)(
|
||||
return new Function('github', 'inputs', 'needs', 'cancelled', `return (${expression});`)(
|
||||
{ repository, event_name: event, event: { action, pull_request: { draft } }, run_attempt: attempt },
|
||||
{ fuzz_profile: profile, ci_command: false }
|
||||
{ fuzz_profile: profile, ci_command: false },
|
||||
{ scope: { outputs }, ...Object.fromEntries(['build', ...prerequisites].map(name => [name, { result: results[name] || 'success' }])) },
|
||||
() => cancelled
|
||||
);
|
||||
}
|
||||
test('automatic full fuzz on ready PR admission and schedule, not every update', () => {
|
||||
test('fuzz event policy on ready PR admission and schedule, not every update', () => {
|
||||
for (const job of [...suites, ...prerequisites]) {
|
||||
for (const action of ['opened', 'ready_for_review']) assert.equal(enabled(job, { action }), true, job);
|
||||
for (const action of ['synchronize', 'reopened']) assert.equal(enabled(job, { action }), false, job);
|
||||
@@ -49,3 +51,24 @@ test('Windows compilation stays in Rust CI; test coverage remains in Nightly CI'
|
||||
assert.match(nightly, /cargo nextest run -F dashboard/);
|
||||
assert.match(nightly, /^ workflow_dispatch:/m);
|
||||
});
|
||||
|
||||
test('scope exclusions and dependency failures compose with the event policy', () => {
|
||||
const gates = {
|
||||
'prepare-fuzz-targets': 'any_fuzz', 'build-greptime-ci': 'build_ci_needed',
|
||||
fuzztest: 'fuzz_standalone', 'unstable-fuzztest': 'fuzz_unstable',
|
||||
'distributed-fuzztest': 'fuzz_distributed', 'distributed-fuzztest-with-chaos': 'fuzz_chaos'
|
||||
};
|
||||
for (const [job, gate] of Object.entries(gates)) {
|
||||
assert.equal(enabled(job, { action: 'opened', outputs: { [gate]: 'false' } }), false, job);
|
||||
assert.equal(enabled(job, { action: 'opened', outputs: {} }), true, job);
|
||||
assert.equal(enabled(job, { outputs: { [gate]: 'true' } }), false, job);
|
||||
assert.equal(enabled(job, { action: 'opened', cancelled: true }), false, job);
|
||||
}
|
||||
for (const job of suites) {
|
||||
for (const result of ['failure', 'skipped', 'cancelled']) {
|
||||
assert.equal(enabled(job, { action: 'opened', results: { 'prepare-fuzz-targets': result } }), false, job);
|
||||
const build = job === 'fuzztest' ? 'build' : 'build-greptime-ci';
|
||||
assert.equal(enabled(job, { action: 'opened', results: { [build]: result } }), false, job);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -136,7 +136,7 @@ class CiSlashTest(unittest.TestCase):
|
||||
|
||||
def test_fork_rerun_gates_cover_standard_jobs(self):
|
||||
import re
|
||||
for name, count in [("rust", 7), ("integration", 5), ("checks", 5), ("docs", 3)]:
|
||||
for name, count in [("rust", 7), ("integration", 7), ("checks", 6), ("docs", 3)]:
|
||||
workflow = (SCRIPT.parents[1] / "workflows" / (name + ".yml")).read_text()
|
||||
gates = re.findall(r"^ if:.*github.run_attempt > 1.*$", workflow, re.MULTILINE)
|
||||
self.assertEqual(len(gates), count, name)
|
||||
|
||||
@@ -92,6 +92,8 @@ jobs:
|
||||
run: .github/scripts/run-fuzz-targets-test.sh
|
||||
- name: Run CI comment-command tests
|
||||
run: python3 .github/scripts/tests/test_ci_slash.py
|
||||
- name: Run CI scope gate tests
|
||||
run: python3 .github/ci/tests/test_ci_scope.py
|
||||
- name: Run metric snapshot benchmark tests
|
||||
run: python3 -m unittest discover -s .github/scripts/tests -p 'test_metric_snapshot*.py'
|
||||
- name: Run query-regression Python tooling tests
|
||||
@@ -107,6 +109,23 @@ jobs:
|
||||
python3 tests/perf/test_agent_observability_summary.py
|
||||
python3 tests/perf/test_tracesbench_summary.py
|
||||
|
||||
scope-rules:
|
||||
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
|
||||
name: CI Scope Rules
|
||||
# Same runner image as the `scope` job in integration.yml: if the rules file
|
||||
# stops parsing there, the gate silently runs every job, so this check exists
|
||||
# to fail the pull request instead.
|
||||
runs-on: ubuntu-slim
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Show the interpreter
|
||||
run: python3 -VV
|
||||
- name: Validate .github/ci/scope-rules.toml
|
||||
run: python3 .github/ci/ci_scope_rules.py --check-paths
|
||||
|
||||
check:
|
||||
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
|
||||
name: Check
|
||||
|
||||
@@ -42,6 +42,57 @@ concurrency:
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
# Which jobs this gate skips, and why: .github/ci/README.md.
|
||||
scope:
|
||||
name: CI Scope
|
||||
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
|
||||
# ubuntu-slim ships python3, git and curl; this job only classifies.
|
||||
runs-on: ubuntu-slim
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: read
|
||||
# `/pulls/{n}` and `/pulls/{n}/files`. An explicit block sets every
|
||||
# unlisted permission to none, and a 403 here would silently widen every
|
||||
# gate instead of classifying.
|
||||
pull-requests: read
|
||||
outputs:
|
||||
any_fuzz: ${{ steps.classify.outputs.any_fuzz }}
|
||||
build_ci_needed: ${{ steps.classify.outputs.build_ci_needed }}
|
||||
fuzz_standalone: ${{ steps.classify.outputs.fuzz_standalone }}
|
||||
fuzz_distributed: ${{ steps.classify.outputs.fuzz_distributed }}
|
||||
fuzz_chaos: ${{ steps.classify.outputs.fuzz_chaos }}
|
||||
fuzz_unstable: ${{ steps.classify.outputs.fuzz_unstable }}
|
||||
export_import_v2: ${{ steps.classify.outputs.export_import_v2 }}
|
||||
sqlness_kvbackend: ${{ steps.classify.outputs.sqlness_kvbackend }}
|
||||
steps:
|
||||
# Rules come from the pull request base (the queue base on merge_group),
|
||||
# so a pull request cannot weaken its own gate. If this job or the Classify
|
||||
# step fails, the outputs stay empty and every gate below treats an absent
|
||||
# value as "run", which keeps CI fail-open.
|
||||
- uses: actions/checkout@v4
|
||||
# A checkout failure leaves the outputs empty, which every gate treats
|
||||
# as "run"; letting the step fail would skip the gates instead.
|
||||
continue-on-error: true
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || github.sha }}
|
||||
persist-credentials: false
|
||||
- name: Classify
|
||||
id: classify
|
||||
continue-on-error: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
CI_SCOPE_FORCE_ALL: ${{ vars.CI_SCOPE_FORCE_ALL || 'false' }}
|
||||
run: |
|
||||
args=(--repo "$GITHUB_REPOSITORY" --event "$GITHUB_EVENT_NAME"
|
||||
--github-output "$GITHUB_OUTPUT"
|
||||
--summary "$GITHUB_STEP_SUMMARY")
|
||||
if [[ "${GITHUB_EVENT_NAME}" == "pull_request" ]]; then
|
||||
args+=(--pr "${{ github.event.pull_request.number }}"
|
||||
--head-sha "${{ github.event.pull_request.head.sha }}"
|
||||
--base-sha "${{ github.event.pull_request.base.sha }}")
|
||||
fi
|
||||
python3 .github/ci/ci_scope.py "${args[@]}"
|
||||
|
||||
build:
|
||||
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
|
||||
name: Build GreptimeDB binaries
|
||||
@@ -116,28 +167,12 @@ jobs:
|
||||
- name: "Basic"
|
||||
opts: ""
|
||||
kafka: false
|
||||
postgres: false
|
||||
mysql: false
|
||||
- name: "Remote WAL"
|
||||
opts: "-w kafka -k 127.0.0.1:9092"
|
||||
kafka: true
|
||||
postgres: false
|
||||
mysql: false
|
||||
- name: "PostgreSQL KvBackend"
|
||||
opts: "--setup-pg postgresql://greptimedb:admin@127.0.0.1:5432/postgres"
|
||||
kafka: false
|
||||
postgres: true
|
||||
mysql: false
|
||||
- name: "MySQL KvBackend"
|
||||
opts: "--setup-mysql mysql://greptimedb:admin@127.0.0.1:3306/mysql"
|
||||
kafka: false
|
||||
postgres: false
|
||||
mysql: true
|
||||
- name: "Flat format"
|
||||
opts: "--enable-flat-format"
|
||||
kafka: false
|
||||
postgres: false
|
||||
mysql: false
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
@@ -149,16 +184,6 @@ jobs:
|
||||
working-directory: tests-integration/fixtures
|
||||
run: ../../.github/scripts/pull-test-deps-images.sh && docker compose up -d --wait kafka
|
||||
|
||||
- if: matrix.mode.postgres
|
||||
name: Setup PostgreSQL
|
||||
working-directory: tests-integration/fixtures
|
||||
run: ../../.github/scripts/pull-test-deps-images.sh && docker compose up -d --wait postgres
|
||||
|
||||
- if: matrix.mode.mysql
|
||||
name: Setup MySQL
|
||||
working-directory: tests-integration/fixtures
|
||||
run: ../../.github/scripts/pull-test-deps-images.sh && docker compose up -d --wait mysql
|
||||
|
||||
- name: Download pre-built binaries
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
@@ -183,10 +208,68 @@ jobs:
|
||||
/tmp/sqlness*
|
||||
retention-days: 3
|
||||
|
||||
sqlness-kvbackend:
|
||||
# The two foreign KV backends are the only sqlness legs that are not
|
||||
# required checks, so they are the only ones this gate may skip. They run
|
||||
# the same cases as the `Basic` leg, so the diff only matters when it can
|
||||
# reach the backend itself; the merge queue runs them regardless.
|
||||
if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) && needs.build.result == 'success' && needs.scope.outputs.sqlness_kvbackend != 'false' }}
|
||||
name: Sqlness Test (${{ matrix.mode.name }})
|
||||
needs: [scope, build]
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ ubuntu-latest ]
|
||||
mode:
|
||||
- name: "Metasrv on PostgreSQL"
|
||||
id: "metasrv-postgres"
|
||||
opts: "--setup-pg postgresql://greptimedb:admin@127.0.0.1:5432/postgres"
|
||||
postgres: true
|
||||
mysql: false
|
||||
- name: "Metasrv on MySQL"
|
||||
id: "metasrv-mysql"
|
||||
opts: "--setup-mysql mysql://greptimedb:admin@127.0.0.1:3306/mysql"
|
||||
postgres: false
|
||||
mysql: true
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- if: matrix.mode.postgres
|
||||
name: Setup PostgreSQL
|
||||
working-directory: tests-integration/fixtures
|
||||
run: ../../.github/scripts/pull-test-deps-images.sh && docker compose up -d --wait postgres
|
||||
|
||||
- if: matrix.mode.mysql
|
||||
name: Setup MySQL
|
||||
working-directory: tests-integration/fixtures
|
||||
run: ../../.github/scripts/pull-test-deps-images.sh && docker compose up -d --wait mysql
|
||||
|
||||
- name: Download pre-built binaries
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: bins
|
||||
path: .
|
||||
- name: Unzip binaries
|
||||
run: tar -xvf ./bins.tar.gz
|
||||
- name: Run sqlness
|
||||
run: RUST_BACKTRACE=1 ./bins/sqlness-runner bare ${{ matrix.mode.opts }} -c ./tests/cases --bins-dir ./bins --preserve-state
|
||||
- name: Upload sqlness logs
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: sqlness-logs-${{ matrix.mode.name }}
|
||||
path: |
|
||||
/tmp/sqlness*
|
||||
retention-days: 3
|
||||
|
||||
export-import-v2-e2e:
|
||||
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
|
||||
if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) && needs.build.result == 'success' && needs.scope.outputs.export_import_v2 != 'false' }}
|
||||
name: Export/Import V2 E2E Test
|
||||
needs: build
|
||||
needs: [scope, build]
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
@@ -321,8 +404,9 @@ jobs:
|
||||
# Fuzz runs on opening a ready PR, marking it ready, manual dispatch, and
|
||||
# the scheduled main run. Synchronize events keep the core integration tests.
|
||||
prepare-fuzz-targets:
|
||||
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile != 'none'))) }}
|
||||
if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile != 'none'))) && needs.scope.outputs.any_fuzz != 'false' }}
|
||||
name: Prepare Fuzz Targets
|
||||
needs: [scope]
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
@@ -435,9 +519,9 @@ jobs:
|
||||
if-no-files-found: error
|
||||
|
||||
fuzztest:
|
||||
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile == 'standalone' || inputs.fuzz_profile == 'all'))) }}
|
||||
if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile == 'standalone' || inputs.fuzz_profile == 'all'))) && needs.build.result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_standalone != 'false' }}
|
||||
name: Fuzz Test (Standalone, ${{ matrix.group.name }})
|
||||
needs: [build, prepare-fuzz-targets]
|
||||
needs: [build, prepare-fuzz-targets, scope]
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
@@ -516,9 +600,9 @@ jobs:
|
||||
artifact-name: fuzz-standalone-${{ matrix.group.id }}
|
||||
|
||||
unstable-fuzztest:
|
||||
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile == 'standalone' || inputs.fuzz_profile == 'all'))) }}
|
||||
if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile == 'standalone' || inputs.fuzz_profile == 'all'))) && needs['build-greptime-ci'].result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_unstable != 'false' }}
|
||||
name: Unstable Fuzz Test
|
||||
needs: [build-greptime-ci, prepare-fuzz-targets]
|
||||
needs: [build-greptime-ci, prepare-fuzz-targets, scope]
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
@@ -576,8 +660,9 @@ jobs:
|
||||
artifact-name: fuzz-unstable-standalone
|
||||
|
||||
build-greptime-ci:
|
||||
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile != 'none'))) }}
|
||||
if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile != 'none'))) && needs.scope.outputs.build_ci_needed != 'false' }}
|
||||
name: Build GreptimeDB binary (profile-CI)
|
||||
needs: [scope]
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
@@ -636,10 +721,10 @@ jobs:
|
||||
version: current
|
||||
|
||||
distributed-fuzztest:
|
||||
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile == 'distributed' || inputs.fuzz_profile == 'all'))) }}
|
||||
if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile == 'distributed' || inputs.fuzz_profile == 'all'))) && needs['build-greptime-ci'].result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_distributed != 'false' }}
|
||||
name: Fuzz Test (Distributed, ${{ matrix.mode.name }}, ${{ matrix.group.name }})
|
||||
runs-on: ubuntu-latest
|
||||
needs: [build-greptime-ci, prepare-fuzz-targets]
|
||||
needs: [build-greptime-ci, prepare-fuzz-targets, scope]
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
@@ -875,10 +960,10 @@ jobs:
|
||||
docker system prune -f
|
||||
|
||||
distributed-fuzztest-with-chaos:
|
||||
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile == 'chaos' || inputs.fuzz_profile == 'all'))) }}
|
||||
if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile == 'chaos' || inputs.fuzz_profile == 'all'))) && needs['build-greptime-ci'].result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_chaos != 'false' }}
|
||||
name: Fuzz Test with Chaos (Distributed, ${{ matrix.mode.name }}, ${{ matrix.group.name }})
|
||||
runs-on: ubuntu-latest
|
||||
needs: [build-greptime-ci, prepare-fuzz-targets]
|
||||
needs: [build-greptime-ci, prepare-fuzz-targets, scope]
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
|
||||
Generated
+45
-36
@@ -2340,6 +2340,16 @@ dependencies = [
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "common-cache"
|
||||
version = "1.4.0-alpha.0"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"moka",
|
||||
"prometheus 0.14.0",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "common-catalog"
|
||||
version = "1.4.0-alpha.0"
|
||||
@@ -2588,7 +2598,6 @@ dependencies = [
|
||||
"tokio-util",
|
||||
"tonic 0.14.2",
|
||||
"tower 0.5.2",
|
||||
"uuid",
|
||||
"vec1",
|
||||
]
|
||||
|
||||
@@ -3757,7 +3766,7 @@ checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8"
|
||||
[[package]]
|
||||
name = "datafusion"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"arrow-schema 59.2.0",
|
||||
@@ -3809,7 +3818,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-catalog"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"async-trait",
|
||||
@@ -3833,7 +3842,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-catalog-listing"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"async-trait",
|
||||
@@ -3856,7 +3865,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-common"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"arrow-ipc 59.2.0",
|
||||
@@ -3882,7 +3891,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-common-runtime"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"log",
|
||||
@@ -3892,7 +3901,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-datasource"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"async-compression",
|
||||
@@ -3928,7 +3937,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-datasource-arrow"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"arrow-ipc 59.2.0",
|
||||
@@ -3952,7 +3961,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-datasource-csv"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"async-trait",
|
||||
@@ -3975,7 +3984,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-datasource-json"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"async-trait",
|
||||
@@ -3998,7 +4007,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-datasource-parquet"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"arrow-schema 59.2.0",
|
||||
@@ -4030,12 +4039,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-doc"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
|
||||
[[package]]
|
||||
name = "datafusion-execution"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"arrow-buffer 59.2.0",
|
||||
@@ -4060,7 +4069,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-expr"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"arrow-schema 59.2.0",
|
||||
@@ -4084,7 +4093,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-expr-common"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"datafusion-common",
|
||||
@@ -4095,7 +4104,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-functions"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"arrow-buffer 59.2.0",
|
||||
@@ -4126,7 +4135,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-functions-aggregate"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"datafusion-common",
|
||||
@@ -4146,7 +4155,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-functions-aggregate-common"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"datafusion-common",
|
||||
@@ -4157,7 +4166,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-functions-nested"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"arrow-ord 59.2.0",
|
||||
@@ -4181,7 +4190,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-functions-table"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"async-trait",
|
||||
@@ -4196,7 +4205,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-functions-window"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"datafusion-common",
|
||||
@@ -4212,7 +4221,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-functions-window-common"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"datafusion-common",
|
||||
"datafusion-physical-expr-common",
|
||||
@@ -4221,7 +4230,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-macros"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"datafusion-doc",
|
||||
"quote",
|
||||
@@ -4231,7 +4240,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-optimizer"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"chrono",
|
||||
@@ -4279,7 +4288,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-physical-expr"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"arrow-schema 59.2.0",
|
||||
@@ -4302,7 +4311,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-physical-expr-adapter"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"datafusion-common",
|
||||
@@ -4316,7 +4325,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-physical-expr-common"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"chrono",
|
||||
@@ -4333,7 +4342,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-physical-optimizer"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"datafusion-common",
|
||||
@@ -4352,7 +4361,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-physical-plan"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"arrow-data 59.2.0",
|
||||
@@ -4389,7 +4398,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-proto"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"datafusion-catalog",
|
||||
@@ -4415,7 +4424,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-proto-common"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"datafusion-common",
|
||||
@@ -4425,7 +4434,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-proto-models"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"datafusion-common",
|
||||
"datafusion-proto-common",
|
||||
@@ -4435,7 +4444,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-pruning"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"datafusion-common",
|
||||
@@ -4450,7 +4459,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-session"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow-schema 59.2.0",
|
||||
"async-trait",
|
||||
@@ -4464,7 +4473,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-sql"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"bigdecimal 0.4.8",
|
||||
@@ -4483,7 +4492,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-substrait"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
dependencies = [
|
||||
"async-recursion",
|
||||
"async-trait",
|
||||
|
||||
+17
-16
@@ -9,6 +9,7 @@ members = [
|
||||
"src/cmd",
|
||||
"src/common/base",
|
||||
"src/common/batcher",
|
||||
"src/common/cache",
|
||||
"src/common/catalog",
|
||||
"src/common/config",
|
||||
"src/common/datasource",
|
||||
@@ -367,22 +368,22 @@ rev = "f743c3a5fe8c1f57363eac5866c356b7d91f9b39"
|
||||
|
||||
[patch.crates-io]
|
||||
substrait = { git = "https://github.com/GreptimeTeam/substrait-rs.git", rev = "91ec978b0649417ad3da8390e7a515baec723b1b" }
|
||||
datafusion = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
|
||||
datafusion-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
|
||||
datafusion-datasource = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
|
||||
datafusion-execution = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
|
||||
datafusion-expr = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
|
||||
datafusion-expr-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
|
||||
datafusion-functions = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
|
||||
datafusion-functions-aggregate-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
|
||||
datafusion-functions-window-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
|
||||
datafusion-optimizer = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
|
||||
datafusion-physical-expr = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
|
||||
datafusion-physical-expr-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
|
||||
datafusion-physical-plan = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
|
||||
datafusion-proto = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
|
||||
datafusion-sql = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
|
||||
datafusion-substrait = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
|
||||
datafusion = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
|
||||
datafusion-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
|
||||
datafusion-datasource = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
|
||||
datafusion-execution = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
|
||||
datafusion-expr = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
|
||||
datafusion-expr-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
|
||||
datafusion-functions = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
|
||||
datafusion-functions-aggregate-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
|
||||
datafusion-functions-window-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
|
||||
datafusion-optimizer = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
|
||||
datafusion-physical-expr = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
|
||||
datafusion-physical-expr-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
|
||||
datafusion-physical-plan = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
|
||||
datafusion-proto = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
|
||||
datafusion-sql = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
|
||||
datafusion-substrait = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
|
||||
datafusion-pg-catalog = { git = "https://github.com/datafusion-contrib/datafusion-postgres.git", rev = "3ae0a6cb30b1c5131687f4637247ff4f84ac11e4" }
|
||||
arrow-pg = { git = "https://github.com/datafusion-contrib/datafusion-postgres.git", rev = "3ae0a6cb30b1c5131687f4637247ff4f84ac11e4" }
|
||||
sqlparser = { git = "https://github.com/GreptimeTeam/sqlparser-rs.git", rev = "9e9019bb1c7040ed956f654e39378dd42ab17884" }
|
||||
|
||||
@@ -249,6 +249,10 @@ fmt-check: ## Check code format.
|
||||
check-enterprise-license: ## Check enterprise-gated files are listed in both license configs.
|
||||
python3 scripts/check-enterprise-license.py
|
||||
|
||||
.PHONY: check-ci-scope
|
||||
check-ci-scope: ## Check the CI scope rules still match existing paths.
|
||||
python3 .github/ci/ci_scope_rules.py --check-paths
|
||||
|
||||
.PHONY: start-etcd
|
||||
start-etcd: ## Start single node etcd for testing purpose.
|
||||
docker run --rm -d --network=host -p 2379-2380:2379-2380 ${ETCD_IMAGE}
|
||||
|
||||
@@ -15,11 +15,6 @@ headerPath = "licenses/enterprise-header.txt"
|
||||
# with the "# enterprise" block in `licenserc.toml`'s `excludes` — both are
|
||||
# enforced by `make check-enterprise-license`.
|
||||
includes = [
|
||||
"src/common/grpc/src/flow_write.rs",
|
||||
"src/frontend/src/instance/flow_write.rs",
|
||||
"src/datanode/src/region_server/flow_write.rs",
|
||||
"src/operator/src/insert/flow_write.rs",
|
||||
"src/flow/src/batching_mode/frontend_client/flow_write.rs",
|
||||
"src/common/meta/src/rpc/ddl/trigger.rs",
|
||||
"src/operator/src/expr_helper/trigger.rs",
|
||||
"src/sql/src/statements/alter/trigger.rs",
|
||||
|
||||
@@ -31,11 +31,6 @@ excludes = [
|
||||
# Keep this list in sync with that file's `includes`; enforced by
|
||||
# `make check-enterprise-license`.
|
||||
# enterprise:start
|
||||
"src/common/grpc/src/flow_write.rs",
|
||||
"src/frontend/src/instance/flow_write.rs",
|
||||
"src/datanode/src/region_server/flow_write.rs",
|
||||
"src/operator/src/insert/flow_write.rs",
|
||||
"src/flow/src/batching_mode/frontend_client/flow_write.rs",
|
||||
"src/common/meta/src/rpc/ddl/trigger.rs",
|
||||
"src/operator/src/expr_helper/trigger.rs",
|
||||
"src/sql/src/statements/alter/trigger.rs",
|
||||
|
||||
Vendored
+16
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "common-cache"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
moka = { workspace = true, features = ["future"] }
|
||||
prometheus.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
futures.workspace = true
|
||||
tokio = { workspace = true, features = ["macros", "rt", "sync"] }
|
||||
Vendored
+473
@@ -0,0 +1,473 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// 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.
|
||||
|
||||
use std::borrow::Borrow;
|
||||
use std::hash::Hash;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::metrics::{CacheMetrics, CacheSizeMetric, CacheSizeRegistration};
|
||||
|
||||
/// Reason for releasing an entry from the cache.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RemovalCause {
|
||||
/// The entry reached its expiration time.
|
||||
Expired,
|
||||
/// The entry was explicitly invalidated.
|
||||
Explicit,
|
||||
/// A new value replaced the entry.
|
||||
Replaced,
|
||||
/// The entry was removed to satisfy the capacity policy.
|
||||
Size,
|
||||
}
|
||||
|
||||
impl RemovalCause {
|
||||
/// Returns the established eviction metric label.
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Expired => "expired",
|
||||
Self::Explicit => "explicit",
|
||||
Self::Replaced => "replaced",
|
||||
Self::Size => "size",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<moka::notification::RemovalCause> for RemovalCause {
|
||||
fn from(value: moka::notification::RemovalCause) -> Self {
|
||||
match value {
|
||||
moka::notification::RemovalCause::Expired => Self::Expired,
|
||||
moka::notification::RemovalCause::Explicit => Self::Explicit,
|
||||
moka::notification::RemovalCause::Replaced => Self::Replaced,
|
||||
moka::notification::RemovalCause::Size => Self::Size,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A weighted memory cache with backend-provided asynchronous load deduplication.
|
||||
/// Values should be inexpensive to clone, such as `Arc<T>` or `Bytes`.
|
||||
/// Capacity is maintained asynchronously; insertion does not guarantee retention.
|
||||
#[derive(Clone)]
|
||||
pub struct Cache<K, V> {
|
||||
inner: moka::future::Cache<K, V>,
|
||||
capacity: u64,
|
||||
size_registration: Option<CacheSizeRegistration>,
|
||||
metrics: Option<Arc<CacheMetrics>>,
|
||||
}
|
||||
|
||||
impl<K, V> Cache<K, V>
|
||||
where
|
||||
K: Eq + Hash + Send + Sync + 'static,
|
||||
V: Clone + Send + Sync + 'static,
|
||||
{
|
||||
/// Creates a cache with the caller's weight and eviction accounting.
|
||||
pub fn new<W, L>(name: &str, capacity: u64, weigher: W, listener: L) -> Self
|
||||
where
|
||||
W: Fn(&K, &V) -> u32 + Send + Sync + 'static,
|
||||
L: Fn(Arc<K>, V, RemovalCause) + Send + Sync + 'static,
|
||||
{
|
||||
Self {
|
||||
inner: moka::future::Cache::builder()
|
||||
.name(name)
|
||||
.max_capacity(capacity)
|
||||
.support_invalidation_closures()
|
||||
.weigher(weigher)
|
||||
.eviction_listener(move |key, value, cause| listener(key, value, cause.into()))
|
||||
.build(),
|
||||
capacity,
|
||||
size_registration: None,
|
||||
metrics: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Attaches caller-bound metrics without changing existing hit/miss accounting.
|
||||
pub fn with_metrics(mut self, metrics: Arc<CacheMetrics>) -> Self {
|
||||
self.metrics = Some(metrics);
|
||||
self
|
||||
}
|
||||
|
||||
/// Samples this cache's retained weight when the caller collects byte metrics.
|
||||
pub fn with_size_metric(mut self, metric: CacheSizeMetric) -> Self {
|
||||
let cache = self.inner.clone();
|
||||
self.size_registration = Some(metric.register(move || cache.weighted_size()));
|
||||
self
|
||||
}
|
||||
|
||||
/// Gets a completed value without starting a load.
|
||||
pub fn get<'a, Q>(&'a self, key: &'a Q) -> impl Future<Output = Option<V>> + Send + 'a
|
||||
where
|
||||
K: Borrow<Q>,
|
||||
Q: Hash + Eq + Sync + ?Sized,
|
||||
{
|
||||
self.inner.get(key)
|
||||
}
|
||||
|
||||
/// Shares a successful load among concurrent callers with the same key and error type.
|
||||
/// Errors are shared with current waiters but are not retained as cached values.
|
||||
/// Cancelling the active loader lets a remaining caller execute its own loader.
|
||||
pub async fn try_get_with<Q, F, E>(&self, key: &Q, load: F) -> Result<V, Arc<E>>
|
||||
where
|
||||
K: Borrow<Q>,
|
||||
Q: ToOwned<Owned = K> + Hash + Eq + ?Sized,
|
||||
F: Future<Output = Result<V, E>>,
|
||||
E: Send + Sync + 'static,
|
||||
{
|
||||
let request = self
|
||||
.metrics
|
||||
.as_ref()
|
||||
.map(|metrics| metrics.requests.start());
|
||||
let result = self
|
||||
.inner
|
||||
.try_get_with_by_ref(key, async {
|
||||
// Only the backend-selected loader contributes physical load metrics.
|
||||
let operation = self.metrics.as_ref().map(|metrics| metrics.loads.start());
|
||||
let result = load.await;
|
||||
if let Some(operation) = operation {
|
||||
operation.finish(&result);
|
||||
}
|
||||
result
|
||||
})
|
||||
.await;
|
||||
if let Some(request) = request {
|
||||
request.finish(&result);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Submits a completed value to the cache's admission and eviction policy.
|
||||
pub async fn insert(&self, key: K, value: V) {
|
||||
self.inner.insert(key, value).await;
|
||||
}
|
||||
|
||||
/// Invalidates a completed entry. This does not cancel a concurrent loader.
|
||||
pub async fn invalidate<Q>(&self, key: &Q)
|
||||
where
|
||||
K: Borrow<Q>,
|
||||
Q: Hash + Eq + ?Sized,
|
||||
{
|
||||
self.inner.invalidate(key).await;
|
||||
}
|
||||
|
||||
/// Invalidates completed entries matching a predicate. Pending loaders are not fenced.
|
||||
/// Physical removal and eviction accounting run asynchronously.
|
||||
pub fn invalidate_if<F>(&self, predicate: F) -> std::io::Result<()>
|
||||
where
|
||||
F: Fn(&K, &V) -> bool + Send + Sync + 'static,
|
||||
{
|
||||
self.inner
|
||||
.invalidate_entries_if(predicate)
|
||||
.map(|_| ())
|
||||
.map_err(std::io::Error::other)
|
||||
}
|
||||
|
||||
/// Returns the configured weight capacity.
|
||||
pub fn capacity(&self) -> u64 {
|
||||
self.capacity
|
||||
}
|
||||
|
||||
/// Returns the approximate number of retained entries.
|
||||
pub fn entry_count(&self) -> u64 {
|
||||
self.inner.entry_count()
|
||||
}
|
||||
|
||||
/// Returns the approximate total retained weight.
|
||||
pub fn weighted_size(&self) -> u64 {
|
||||
self.inner.weighted_size()
|
||||
}
|
||||
|
||||
/// Applies pending admission, eviction, and accounting work.
|
||||
pub async fn run_pending_tasks(&self) {
|
||||
self.inner.run_pending_tasks().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use tokio::sync::Notify;
|
||||
|
||||
use super::*;
|
||||
|
||||
// This is also a compile-time contract for generic callers crossing async-trait boundaries.
|
||||
fn send_lookup<'a, K, V, Q>(
|
||||
cache: &'a Cache<K, V>,
|
||||
key: &'a Q,
|
||||
) -> impl Future<Output = Option<V>> + Send + 'a
|
||||
where
|
||||
K: Borrow<Q> + Eq + Hash + Send + Sync + 'static,
|
||||
V: Clone + Send + Sync + 'static,
|
||||
Q: Hash + Eq + Sync + ?Sized,
|
||||
{
|
||||
cache.get(key)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_borrowed_lookup_has_a_send_future() {
|
||||
let cache = cache(1024);
|
||||
cache
|
||||
.insert("key".to_string(), Arc::new("value".to_string()))
|
||||
.await;
|
||||
let future: futures::future::BoxFuture<'_, Option<Arc<String>>> =
|
||||
Box::pin(send_lookup(&cache, "key"));
|
||||
assert_eq!(future.await.as_deref().map(String::as_str), Some("value"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_predicate_invalidation_preserves_other_entries() {
|
||||
let cache = cache(1024);
|
||||
cache
|
||||
.insert("old".to_string(), Arc::new("a".to_string()))
|
||||
.await;
|
||||
cache
|
||||
.insert("keep".to_string(), Arc::new("b".to_string()))
|
||||
.await;
|
||||
cache.run_pending_tasks().await;
|
||||
cache.invalidate_if(|key, _| key == "old").unwrap();
|
||||
assert!(cache.get("old").await.is_none());
|
||||
assert_eq!(
|
||||
cache.get("keep").await.as_deref().map(String::as_str),
|
||||
Some("b")
|
||||
);
|
||||
}
|
||||
|
||||
fn cache(capacity: u64) -> Cache<String, Arc<String>> {
|
||||
Cache::new(
|
||||
"test",
|
||||
capacity,
|
||||
|_, value: &Arc<String>| value.len() as u32,
|
||||
|_, _, _| {},
|
||||
)
|
||||
}
|
||||
|
||||
fn operation_metrics(name: &str) -> crate::metrics::OperationMetrics {
|
||||
use prometheus::{Histogram, HistogramOpts, IntCounter, IntGauge};
|
||||
|
||||
crate::metrics::OperationMetrics {
|
||||
started: IntCounter::new(format!("{name}_started"), "test").unwrap(),
|
||||
succeeded: IntCounter::new(format!("{name}_succeeded"), "test").unwrap(),
|
||||
failed: IntCounter::new(format!("{name}_failed"), "test").unwrap(),
|
||||
cancelled: IntCounter::new(format!("{name}_cancelled"), "test").unwrap(),
|
||||
active: IntGauge::new(format!("{name}_active"), "test").unwrap(),
|
||||
elapsed: Histogram::with_opts(HistogramOpts::new(format!("{name}_seconds"), "test"))
|
||||
.unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
fn instrumented_cache() -> (Cache<String, Arc<String>>, Arc<CacheMetrics>) {
|
||||
let metrics = Arc::new(CacheMetrics {
|
||||
requests: operation_metrics("requests"),
|
||||
loads: operation_metrics("loads"),
|
||||
});
|
||||
(cache(1024).with_metrics(metrics.clone()), metrics)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_metrics_distinguish_requests_from_executed_loads() {
|
||||
let (cache, metrics) = instrumented_cache();
|
||||
// Merely constructing an async call does not start an operation.
|
||||
drop(cache.try_get_with("unused", async { Ok::<_, ()>(Arc::new(String::new())) }));
|
||||
assert_eq!(0, metrics.requests.started.get());
|
||||
let gate = Notify::new();
|
||||
let mut first = Box::pin(cache.try_get_with("key", async {
|
||||
gate.notified().await;
|
||||
Ok::<_, ()>(Arc::new("value".to_string()))
|
||||
}));
|
||||
let mut second = Box::pin(cache.try_get_with("key", async { Err::<Arc<String>, _>(()) }));
|
||||
assert!(futures::poll!(&mut first).is_pending());
|
||||
assert!(futures::poll!(&mut second).is_pending());
|
||||
assert_eq!(2, metrics.requests.active.get());
|
||||
assert_eq!(1, metrics.loads.active.get());
|
||||
gate.notify_waiters();
|
||||
let (first, second) = tokio::join!(first, second);
|
||||
assert!(Arc::ptr_eq(&first.unwrap(), &second.unwrap()));
|
||||
cache
|
||||
.try_get_with("key", async { Err::<Arc<String>, _>(()) })
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(3, metrics.requests.started.get());
|
||||
assert_eq!(3, metrics.requests.succeeded.get());
|
||||
assert_eq!(1, metrics.loads.started.get());
|
||||
assert_eq!(1, metrics.loads.succeeded.get());
|
||||
assert_eq!(0, metrics.requests.active.get());
|
||||
assert_eq!(0, metrics.loads.active.get());
|
||||
assert_eq!(3, metrics.requests.elapsed.get_sample_count());
|
||||
assert_eq!(1, metrics.loads.elapsed.get_sample_count());
|
||||
assert_eq!(0, metrics.requests.failed.get());
|
||||
assert_eq!(0, metrics.requests.cancelled.get());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_metrics_release_active_work_on_cancellation_and_error() {
|
||||
let (cache, metrics) = instrumented_cache();
|
||||
let mut producer =
|
||||
Box::pin(cache.try_get_with("key", std::future::pending::<Result<Arc<String>, ()>>()));
|
||||
let mut waiter =
|
||||
Box::pin(cache.try_get_with("key", std::future::pending::<Result<Arc<String>, ()>>()));
|
||||
assert!(futures::poll!(&mut producer).is_pending());
|
||||
assert!(futures::poll!(&mut waiter).is_pending());
|
||||
drop(waiter);
|
||||
assert_eq!(1, metrics.requests.cancelled.get());
|
||||
assert_eq!(0, metrics.loads.cancelled.get());
|
||||
drop(producer);
|
||||
assert_eq!(2, metrics.requests.cancelled.get());
|
||||
assert_eq!(1, metrics.loads.cancelled.get());
|
||||
let result = cache
|
||||
.try_get_with("key", async { Err::<Arc<String>, _>(()) })
|
||||
.await;
|
||||
assert!(result.is_err());
|
||||
assert_eq!(1, metrics.requests.failed.get());
|
||||
assert_eq!(1, metrics.loads.failed.get());
|
||||
assert_eq!(0, metrics.requests.active.get());
|
||||
assert_eq!(0, metrics.loads.active.get());
|
||||
assert_eq!(3, metrics.requests.elapsed.get_sample_count());
|
||||
assert_eq!(2, metrics.loads.elapsed.get_sample_count());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_instrumented_loading_future_is_send() {
|
||||
fn assert_send<T: Send>(value: T) -> T {
|
||||
value
|
||||
}
|
||||
|
||||
let (cache, _) = instrumented_cache();
|
||||
assert_send(
|
||||
cache.try_get_with("key", async { Ok::<_, ()>(Arc::new("value".to_string())) }),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_shares_load_and_bypasses_loader_on_hit() {
|
||||
let cache = cache(1024);
|
||||
let calls = AtomicUsize::new(0);
|
||||
let gate = Notify::new();
|
||||
let load = || async {
|
||||
calls.fetch_add(1, Ordering::Relaxed);
|
||||
gate.notified().await;
|
||||
Ok::<_, ()>(Arc::new("value".to_string()))
|
||||
};
|
||||
let mut first = Box::pin(cache.try_get_with("key", load()));
|
||||
let mut second = Box::pin(cache.try_get_with("key", load()));
|
||||
assert!(futures::poll!(&mut first).is_pending());
|
||||
assert!(futures::poll!(&mut second).is_pending());
|
||||
assert_eq!(1, calls.load(Ordering::Relaxed));
|
||||
gate.notify_waiters();
|
||||
let (first, second) = tokio::join!(first, second);
|
||||
let first = first.unwrap();
|
||||
assert!(Arc::ptr_eq(&first, &second.unwrap()));
|
||||
let hit = cache
|
||||
.try_get_with("key", async { Err::<Arc<String>, _>(()) })
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(Arc::ptr_eq(&first, &hit));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_remaining_waiter_loads_after_producer_cancellation() {
|
||||
let (cache, metrics) = instrumented_cache();
|
||||
let mut first =
|
||||
Box::pin(cache.try_get_with("key", std::future::pending::<Result<Arc<String>, ()>>()));
|
||||
assert!(futures::poll!(&mut first).is_pending());
|
||||
let mut second = Box::pin(
|
||||
cache.try_get_with("key", async { Ok::<_, ()>(Arc::new("retry".to_string())) }),
|
||||
);
|
||||
assert!(futures::poll!(&mut second).is_pending());
|
||||
drop(first);
|
||||
assert_eq!("retry", second.await.unwrap().as_str());
|
||||
assert_eq!(2, metrics.requests.started.get());
|
||||
assert_eq!(1, metrics.requests.cancelled.get());
|
||||
assert_eq!(1, metrics.requests.succeeded.get());
|
||||
assert_eq!(2, metrics.loads.started.get());
|
||||
assert_eq!(1, metrics.loads.cancelled.get());
|
||||
assert_eq!(1, metrics.loads.succeeded.get());
|
||||
assert_eq!(0, metrics.requests.active.get());
|
||||
assert_eq!(0, metrics.loads.active.get());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_errors_are_shared_but_not_cached() {
|
||||
let (cache, metrics) = instrumented_cache();
|
||||
let calls = AtomicUsize::new(0);
|
||||
let gate = Notify::new();
|
||||
let load = || async {
|
||||
calls.fetch_add(1, Ordering::Relaxed);
|
||||
gate.notified().await;
|
||||
Err::<Arc<String>, _>("read failed")
|
||||
};
|
||||
let mut first = Box::pin(cache.try_get_with("key", load()));
|
||||
let mut second = Box::pin(cache.try_get_with("key", load()));
|
||||
assert!(futures::poll!(&mut first).is_pending());
|
||||
assert!(futures::poll!(&mut second).is_pending());
|
||||
gate.notify_waiters();
|
||||
let (first, second) = tokio::join!(first, second);
|
||||
assert!(Arc::ptr_eq(&first.unwrap_err(), &second.unwrap_err()));
|
||||
assert_eq!(2, metrics.requests.failed.get());
|
||||
assert_eq!(1, metrics.loads.failed.get());
|
||||
assert_eq!(0, metrics.requests.active.get());
|
||||
assert_eq!(0, metrics.loads.active.get());
|
||||
assert_eq!(1, calls.load(Ordering::Relaxed));
|
||||
assert!(cache.get("key").await.is_none());
|
||||
assert_eq!(
|
||||
"retry",
|
||||
cache
|
||||
.try_get_with("key", async {
|
||||
Ok::<_, &'static str>(Arc::new("retry".to_string()))
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.as_str()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_sampled_size_sums_instances_and_preserves_manual_bytes() {
|
||||
use crate::metrics::CacheSizeMetrics;
|
||||
use prometheus::Opts;
|
||||
use prometheus::core::Collector;
|
||||
|
||||
let metrics =
|
||||
CacheSizeMetrics::new(Opts::new("test_cache_bytes", "test"), &["type"]).unwrap();
|
||||
let manual = metrics.with_label_values(&["shared"]);
|
||||
manual.set(3);
|
||||
let make_cache = || {
|
||||
Cache::new("sampled", 100, |_: &u64, _: &Arc<String>| 7, |_, _, _| {})
|
||||
.with_size_metric(metrics.bind(&["shared"]))
|
||||
};
|
||||
let a = make_cache();
|
||||
let b = make_cache();
|
||||
let sample = || {
|
||||
metrics.collect()[0].get_metric()[0]
|
||||
.get_gauge()
|
||||
.as_ref()
|
||||
.map_or(0.0, |gauge| gauge.value())
|
||||
};
|
||||
a.insert(1, Arc::new("one".into())).await;
|
||||
b.insert(2, Arc::new("two".into())).await;
|
||||
a.run_pending_tasks().await;
|
||||
b.run_pending_tasks().await;
|
||||
assert_eq!(17.0, sample());
|
||||
assert_eq!(3, manual.get());
|
||||
let consumer = a.get(&1).await.unwrap();
|
||||
a.invalidate(&1).await;
|
||||
a.run_pending_tasks().await;
|
||||
assert_eq!(10.0, sample());
|
||||
drop(consumer);
|
||||
let cloned = b.clone();
|
||||
drop(b);
|
||||
assert_eq!(10.0, sample());
|
||||
drop(cloned);
|
||||
assert_eq!(3.0, sample());
|
||||
}
|
||||
}
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// 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.
|
||||
|
||||
//! Shared memory cache primitives with native asynchronous load deduplication.
|
||||
|
||||
mod cache;
|
||||
|
||||
pub mod metrics;
|
||||
|
||||
pub use cache::{Cache, RemovalCause};
|
||||
Vendored
+194
@@ -0,0 +1,194 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// 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.
|
||||
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
use std::time::Instant;
|
||||
|
||||
use prometheus::core::{Collector, Desc};
|
||||
use prometheus::proto::{Gauge, MetricFamily};
|
||||
use prometheus::{Histogram, IntCounter, IntGauge, IntGaugeVec, Opts};
|
||||
|
||||
/// Caller-bound metrics for native cache loading. No collectors are registered here.
|
||||
/// Requests count only `try_get_with` calls, including its cache hits and callers sharing
|
||||
/// another request's load. Plain `get` calls are not counted. Loads count
|
||||
/// only loader futures actually polled by the backend; their difference is not a waiter count.
|
||||
#[derive(Clone)]
|
||||
pub struct CacheMetrics {
|
||||
pub requests: OperationMetrics,
|
||||
pub loads: OperationMetrics,
|
||||
}
|
||||
|
||||
/// Metrics for one operation, with labels bound once when constructing a cache.
|
||||
/// Completion counters are mutually exclusive. Dropping an unfinished future is cancellation.
|
||||
#[derive(Clone)]
|
||||
pub struct OperationMetrics {
|
||||
pub started: IntCounter,
|
||||
pub succeeded: IntCounter,
|
||||
pub failed: IntCounter,
|
||||
pub cancelled: IntCounter,
|
||||
pub active: IntGauge,
|
||||
/// Wall-clock lifetime, including suspended time, for every outcome.
|
||||
pub elapsed: Histogram,
|
||||
}
|
||||
|
||||
impl OperationMetrics {
|
||||
/// Starts tracking an operation and its elapsed time.
|
||||
pub(crate) fn start(&self) -> OperationGuard<'_> {
|
||||
self.started.inc();
|
||||
self.active.inc();
|
||||
OperationGuard {
|
||||
metrics: self,
|
||||
started: Instant::now(),
|
||||
completed: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Tracks an operation, recording cancellation if dropped before completion.
|
||||
pub(crate) struct OperationGuard<'a> {
|
||||
metrics: &'a OperationMetrics,
|
||||
started: Instant,
|
||||
completed: bool,
|
||||
}
|
||||
|
||||
impl OperationGuard<'_> {
|
||||
/// Records success or failure and completes the operation.
|
||||
pub(crate) fn finish<T, E>(mut self, result: &Result<T, E>) {
|
||||
if result.is_ok() {
|
||||
self.metrics.succeeded.inc();
|
||||
} else {
|
||||
self.metrics.failed.inc();
|
||||
}
|
||||
self.completed = true;
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for OperationGuard<'_> {
|
||||
fn drop(&mut self) {
|
||||
if !self.completed {
|
||||
self.metrics.cancelled.inc();
|
||||
}
|
||||
self.metrics.active.dec();
|
||||
self.metrics
|
||||
.elapsed
|
||||
.observe(self.started.elapsed().as_secs_f64());
|
||||
}
|
||||
}
|
||||
|
||||
/// Cache byte metrics combining manually maintained gauges and sampled cache weights.
|
||||
/// Sampling does not force backend maintenance or include pending loader values.
|
||||
#[derive(Clone)]
|
||||
pub struct CacheSizeMetrics {
|
||||
gauges: IntGaugeVec,
|
||||
sources: Arc<Mutex<Vec<CacheSizeSource>>>,
|
||||
}
|
||||
|
||||
/// A byte metric with labels bound for one or more cache instances.
|
||||
#[derive(Clone)]
|
||||
pub struct CacheSizeMetric {
|
||||
metrics: CacheSizeMetrics,
|
||||
gauge: IntGauge,
|
||||
}
|
||||
|
||||
/// Keeps a cache instance registered for size sampling while any owner remains.
|
||||
#[derive(Clone)]
|
||||
pub struct CacheSizeRegistration {
|
||||
_reader: Arc<dyn Fn() -> u64 + Send + Sync>,
|
||||
}
|
||||
|
||||
struct CacheSizeSource {
|
||||
gauge: IntGauge,
|
||||
read: Weak<dyn Fn() -> u64 + Send + Sync>,
|
||||
}
|
||||
|
||||
impl CacheSizeMetrics {
|
||||
/// Creates an unregistered collector. Register a clone with the caller's registry.
|
||||
pub fn new(opts: Opts, labels: &[&str]) -> prometheus::Result<Self> {
|
||||
Ok(Self {
|
||||
gauges: IntGaugeVec::new(opts, labels)?,
|
||||
sources: Arc::new(Mutex::new(Vec::new())),
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the backing gauges for callers retaining manual accounting.
|
||||
pub fn gauges(&self) -> &IntGaugeVec {
|
||||
&self.gauges
|
||||
}
|
||||
|
||||
/// Returns a manually maintained gauge for existing non-cache accounting.
|
||||
pub fn with_label_values(&self, labels: &[&str]) -> IntGauge {
|
||||
self.gauges.with_label_values(labels)
|
||||
}
|
||||
|
||||
/// Binds labels for sampled cache weights. Instances sharing labels are summed.
|
||||
pub fn bind(&self, labels: &[&str]) -> CacheSizeMetric {
|
||||
CacheSizeMetric {
|
||||
metrics: self.clone(),
|
||||
gauge: self.gauges.with_label_values(labels),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CacheSizeMetric {
|
||||
/// Registers a cache-level weight reader without retaining it in the collector.
|
||||
/// Keep the returned registration alongside the cache, including in its clones.
|
||||
pub fn register(
|
||||
&self,
|
||||
read: impl Fn() -> u64 + Send + Sync + 'static,
|
||||
) -> CacheSizeRegistration {
|
||||
let read: Arc<dyn Fn() -> u64 + Send + Sync> = Arc::new(read);
|
||||
self.metrics
|
||||
.sources
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.push(CacheSizeSource {
|
||||
gauge: self.gauge.clone(),
|
||||
read: Arc::downgrade(&read),
|
||||
});
|
||||
CacheSizeRegistration { _reader: read }
|
||||
}
|
||||
}
|
||||
|
||||
impl Collector for CacheSizeMetrics {
|
||||
fn desc(&self) -> Vec<&Desc> {
|
||||
self.gauges.desc()
|
||||
}
|
||||
|
||||
fn collect(&self) -> Vec<MetricFamily> {
|
||||
let mut families = self.gauges.collect();
|
||||
let mut sources = self.sources.lock().unwrap_or_else(|e| e.into_inner());
|
||||
sources.retain(|source| {
|
||||
let Some(read) = source.read.upgrade() else {
|
||||
return false;
|
||||
};
|
||||
let labels = source.gauge.collect();
|
||||
for family in &mut families {
|
||||
for metric in family.mut_metric() {
|
||||
if metric.get_label() == labels[0].get_metric()[0].get_label() {
|
||||
let bytes = metric
|
||||
.get_gauge()
|
||||
.as_ref()
|
||||
.map_or(0.0, |gauge| gauge.value())
|
||||
+ read() as f64;
|
||||
let mut gauge = Gauge::default();
|
||||
gauge.set_value(bytes);
|
||||
metric.set_gauge(gauge);
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
});
|
||||
families
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,6 @@ license.workspace = true
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
enterprise = []
|
||||
|
||||
[dependencies]
|
||||
api.workspace = true
|
||||
arrow-flight.workspace = true
|
||||
@@ -35,7 +32,6 @@ tokio.workspace = true
|
||||
tokio-util.workspace = true
|
||||
tonic.workspace = true
|
||||
tower.workspace = true
|
||||
uuid.workspace = true
|
||||
vec1 = "1.12"
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -1,477 +0,0 @@
|
||||
// Copyright 2023-2026 GrepTime Inc.
|
||||
//
|
||||
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
|
||||
// the GreptimeDB Enterprise License. You may not use this file except in
|
||||
// compliance with that license. A copy of the license is available at the root
|
||||
// of this repository in the file LICENSE-ENTERPRISE.
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, this software is
|
||||
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
// either express or implied.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use common_error::ext::{ErrorExt, StackError};
|
||||
use common_error::status_code::StatusCode;
|
||||
|
||||
use common_recordbatch::{RecordBatch, RecordBatches};
|
||||
use datatypes::arrow::array::{Array, StringArray};
|
||||
use datatypes::prelude::{ConcreteDataType, VectorRef};
|
||||
use datatypes::schema::{ColumnSchema, Schema};
|
||||
use datatypes::vectors::StringVector;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::watch;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub const COMMAND_KEY: &str = "flow_write_command";
|
||||
pub const CHILD_KEY: &str = "flow_write_child";
|
||||
|
||||
/// The control command carried by a Flow write request.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Command {
|
||||
Open { nonce: String },
|
||||
Write { capability: String },
|
||||
Close { capability: String },
|
||||
}
|
||||
|
||||
impl Command {
|
||||
/// Serializes this command as JSON.
|
||||
pub fn encode(&self) -> serde_json::Result<String> {
|
||||
serde_json::to_string(self)
|
||||
}
|
||||
|
||||
/// Parses a serialized command.
|
||||
pub fn decode(value: &str) -> serde_json::Result<Self> {
|
||||
serde_json::from_str(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// A safe terminal application error.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct TerminalError {
|
||||
pub code: u32,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for TerminalError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.message)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for TerminalError {}
|
||||
|
||||
impl StackError for TerminalError {
|
||||
fn debug_fmt(&self, layer: usize, buf: &mut Vec<String>) {
|
||||
buf.push(format!("{layer}: {self:?}"));
|
||||
}
|
||||
|
||||
fn next(&self) -> Option<&dyn StackError> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl ErrorExt for TerminalError {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
StatusCode::from_u32(self.code).unwrap_or(StatusCode::Internal)
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// A finite response for a tracked Flow write.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum Reply {
|
||||
Opened {
|
||||
capability: String,
|
||||
},
|
||||
Closed,
|
||||
Complete {
|
||||
rows: usize,
|
||||
cost: usize,
|
||||
metrics: Option<common_recordbatch::adapter::RecordBatchMetrics>,
|
||||
error: Option<TerminalError>,
|
||||
},
|
||||
}
|
||||
|
||||
fn envelope_schema() -> Arc<Schema> {
|
||||
Arc::new(Schema::new(vec![ColumnSchema::new(
|
||||
"envelope",
|
||||
ConcreteDataType::string_datatype(),
|
||||
false,
|
||||
)]))
|
||||
}
|
||||
|
||||
fn response_error(reason: impl Into<String>) -> common_recordbatch::error::Error {
|
||||
common_recordbatch::error::Error::CreateRecordBatches {
|
||||
reason: reason.into(),
|
||||
location: snafu::Location::new(file!(), line!(), column!()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes a reply in the finite one-string-column record-batch envelope.
|
||||
pub fn reply_batches(reply: &Reply) -> common_recordbatch::error::Result<RecordBatches> {
|
||||
let value = serde_json::to_string(reply).map_err(|e| response_error(e.to_string()))?;
|
||||
let batch = RecordBatch::new(
|
||||
envelope_schema(),
|
||||
vec![Arc::new(StringVector::from(vec![value])) as VectorRef],
|
||||
)?;
|
||||
RecordBatches::try_new(batch.schema.clone(), vec![batch])
|
||||
}
|
||||
|
||||
/// Decodes a reply from its finite one-string-column record-batch envelope.
|
||||
pub fn decode_reply(batches: &RecordBatches) -> common_recordbatch::error::Result<Reply> {
|
||||
let batch = batches
|
||||
.iter()
|
||||
.next()
|
||||
.ok_or_else(|| response_error("missing reply batch"))?;
|
||||
if batches.iter().count() != 1 || batch.num_columns() != 1 || batch.num_rows() != 1 {
|
||||
return Err(response_error("reply must be exactly one string value"));
|
||||
}
|
||||
let values = batch.columns()[0]
|
||||
.as_any()
|
||||
.downcast_ref::<StringArray>()
|
||||
.ok_or_else(|| response_error("reply value is not a string"))?;
|
||||
if values.is_null(0) {
|
||||
return Err(response_error("reply value is null"));
|
||||
}
|
||||
let value = values.value(0);
|
||||
serde_json::from_str(value).map_err(|e| response_error(e.to_string()))
|
||||
}
|
||||
|
||||
/// Errors that reject admission or indicate that an admitted writer was lost.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum RegistryError {
|
||||
UnknownCapability,
|
||||
Closing,
|
||||
WriterLost,
|
||||
PayloadMismatch,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for RegistryError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{self:?}")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for RegistryError {}
|
||||
|
||||
impl StackError for RegistryError {
|
||||
fn debug_fmt(&self, layer: usize, buf: &mut Vec<String>) {
|
||||
buf.push(format!("{layer}: {self:?}"));
|
||||
}
|
||||
|
||||
fn next(&self) -> Option<&dyn StackError> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl ErrorExt for RegistryError {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
StatusCode::InvalidArguments
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of atomically admitting or joining a payload.
|
||||
#[derive(Debug)]
|
||||
pub enum Admission<R> {
|
||||
Start(watch::Sender<Option<Arc<R>>>),
|
||||
Join(watch::Receiver<Option<Arc<R>>>),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Entry<P, R> {
|
||||
payload: Option<P>,
|
||||
sender: Option<watch::Sender<Option<Arc<R>>>>,
|
||||
receiver: watch::Receiver<Option<Arc<R>>>,
|
||||
closing: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct State<P, R> {
|
||||
openers: HashMap<String, String>,
|
||||
entries: HashMap<String, Entry<P, R>>,
|
||||
}
|
||||
|
||||
/// Receiver-issued capabilities for single-write admission and completion sharing.
|
||||
#[derive(Debug)]
|
||||
pub struct FlowWriteRegistry<P, R> {
|
||||
state: Mutex<State<P, R>>,
|
||||
}
|
||||
|
||||
impl<P, R> Default for FlowWriteRegistry<P, R> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
state: Mutex::new(State {
|
||||
openers: HashMap::new(),
|
||||
entries: HashMap::new(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: PartialEq, R: Send + Sync + 'static> FlowWriteRegistry<P, R> {
|
||||
/// Returns the active capability for this opener nonce, creating one if needed.
|
||||
pub fn open(&self, nonce: &str) -> Result<String, RegistryError> {
|
||||
let mut state = self
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(capability) = state.openers.get(nonce) {
|
||||
if state
|
||||
.entries
|
||||
.get(capability)
|
||||
.is_some_and(|entry| entry.closing)
|
||||
{
|
||||
return Err(RegistryError::Closing);
|
||||
}
|
||||
return Ok(capability.clone());
|
||||
}
|
||||
let capability = Uuid::new_v4().to_string();
|
||||
let (sender, receiver) = watch::channel(None);
|
||||
state.openers.insert(nonce.to_string(), capability.clone());
|
||||
state.entries.insert(
|
||||
capability.clone(),
|
||||
Entry {
|
||||
payload: None,
|
||||
sender: Some(sender),
|
||||
receiver,
|
||||
closing: false,
|
||||
},
|
||||
);
|
||||
Ok(capability)
|
||||
}
|
||||
|
||||
/// Atomically starts one payload or joins its identical in-flight completion.
|
||||
pub fn admit(&self, capability: &str, payload: P) -> Result<Admission<R>, RegistryError> {
|
||||
let mut state = self
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let entry = state
|
||||
.entries
|
||||
.get_mut(capability)
|
||||
.ok_or(RegistryError::UnknownCapability)?;
|
||||
if entry.closing {
|
||||
return Err(RegistryError::Closing);
|
||||
}
|
||||
match &entry.payload {
|
||||
Some(existing) if existing != &payload => Err(RegistryError::PayloadMismatch),
|
||||
Some(_) => Ok(Admission::Join(entry.receiver.clone())),
|
||||
None => {
|
||||
entry.payload = Some(payload);
|
||||
let sender = entry.sender.take().ok_or(RegistryError::Closing)?;
|
||||
Ok(Admission::Start(sender))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Closes admission, drains an admitted writer, then deletes the capability.
|
||||
pub async fn close(&self, capability: &str) -> Result<(), RegistryError> {
|
||||
let receiver = {
|
||||
let mut state = self
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let Some(entry) = state.entries.get_mut(capability) else {
|
||||
return Ok(());
|
||||
};
|
||||
entry.closing = true;
|
||||
if entry.payload.is_none() {
|
||||
state.entries.remove(capability);
|
||||
state.openers.retain(|_, value| value != capability);
|
||||
return Ok(());
|
||||
}
|
||||
entry.receiver.clone()
|
||||
};
|
||||
wait_completion(receiver).await?;
|
||||
let mut state = self
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
state.entries.remove(capability);
|
||||
state.openers.retain(|_, value| value != capability);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for an admitted writer's positive terminal completion.
|
||||
pub async fn wait_completion<R>(
|
||||
mut receiver: watch::Receiver<Option<Arc<R>>>,
|
||||
) -> Result<Arc<R>, RegistryError> {
|
||||
loop {
|
||||
if let Some(value) = receiver.borrow().clone() {
|
||||
return Ok(value);
|
||||
}
|
||||
if receiver.changed().await.is_err() {
|
||||
return Err(RegistryError::WriterLost);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Barrier;
|
||||
use std::thread;
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_admission_has_one_owner_and_same_payload_joins() {
|
||||
let registry = Arc::new(FlowWriteRegistry::<String, usize>::default());
|
||||
let cap = registry.open("nonce").unwrap();
|
||||
let barrier = Arc::new(Barrier::new(8));
|
||||
let mut workers = Vec::new();
|
||||
for _ in 0..8 {
|
||||
let registry = registry.clone();
|
||||
let cap = cap.clone();
|
||||
let barrier = barrier.clone();
|
||||
workers.push(thread::spawn(move || {
|
||||
barrier.wait();
|
||||
registry.admit(&cap, "payload".into()).unwrap()
|
||||
}));
|
||||
}
|
||||
let admissions: Vec<_> = workers.into_iter().map(|w| w.join().unwrap()).collect();
|
||||
assert_eq!(
|
||||
admissions
|
||||
.iter()
|
||||
.filter(|a| matches!(a, Admission::Start(_)))
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
let sender = admissions
|
||||
.into_iter()
|
||||
.find_map(|a| match a {
|
||||
Admission::Start(s) => Some(s),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
sender.send(Some(Arc::new(7))).unwrap();
|
||||
registry.close(&cap).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn close_drains_active_writer_and_deletes_old_capability() {
|
||||
let registry = Arc::new(FlowWriteRegistry::<String, usize>::default());
|
||||
let cap = registry.open("first").unwrap();
|
||||
let Admission::Start(sender) = registry.admit(&cap, "payload".into()).unwrap() else {
|
||||
panic!()
|
||||
};
|
||||
let close_registry = registry.clone();
|
||||
let close_cap = cap.clone();
|
||||
let close = tokio::spawn(async move { close_registry.close(&close_cap).await });
|
||||
tokio::task::yield_now().await;
|
||||
assert!(matches!(
|
||||
registry.admit(&cap, "payload".into()),
|
||||
Err(RegistryError::Closing)
|
||||
));
|
||||
assert!(!close.is_finished());
|
||||
sender.send(Some(Arc::new(9))).unwrap();
|
||||
close.await.unwrap().unwrap();
|
||||
assert!(matches!(
|
||||
registry.admit(&cap, "payload".into()),
|
||||
Err(RegistryError::UnknownCapability)
|
||||
));
|
||||
registry.close(&cap).await.unwrap();
|
||||
let new_cap = registry.open("first").unwrap();
|
||||
assert_ne!(cap, new_cap);
|
||||
assert!(matches!(
|
||||
registry.admit(&cap, "late".into()),
|
||||
Err(RegistryError::UnknownCapability)
|
||||
));
|
||||
assert!(matches!(
|
||||
registry.admit(&new_cap, "new".into()).unwrap(),
|
||||
Admission::Start(_)
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn writer_loss_is_not_completion() {
|
||||
let registry = FlowWriteRegistry::<String, usize>::default();
|
||||
let cap = registry.open("nonce").unwrap();
|
||||
let Admission::Start(sender) = registry.admit(&cap, "payload".into()).unwrap() else {
|
||||
panic!()
|
||||
};
|
||||
let Admission::Join(receiver) = registry.admit(&cap, "payload".into()).unwrap() else {
|
||||
panic!()
|
||||
};
|
||||
drop(sender);
|
||||
assert_eq!(
|
||||
wait_completion(receiver).await.unwrap_err(),
|
||||
RegistryError::WriterLost
|
||||
);
|
||||
assert_eq!(
|
||||
registry.close(&cap).await.unwrap_err(),
|
||||
RegistryError::WriterLost
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_and_reply_envelope_round_trip_and_malformed_envelopes() {
|
||||
let command = Command::Open { nonce: "n".into() };
|
||||
assert_eq!(
|
||||
Command::decode(&command.encode().unwrap()).unwrap(),
|
||||
command
|
||||
);
|
||||
let reply = Reply::Complete {
|
||||
rows: 2,
|
||||
cost: 3,
|
||||
metrics: Some(common_recordbatch::adapter::RecordBatchMetrics::default()),
|
||||
error: Some(TerminalError {
|
||||
code: 4,
|
||||
message: "terminal".into(),
|
||||
}),
|
||||
};
|
||||
let batches = reply_batches(&reply).unwrap();
|
||||
let decoded = decode_reply(&batches).unwrap();
|
||||
assert!(matches!(
|
||||
decoded,
|
||||
Reply::Complete {
|
||||
rows: 2,
|
||||
cost: 3,
|
||||
error: Some(_),
|
||||
..
|
||||
}
|
||||
));
|
||||
|
||||
let schema = envelope_schema();
|
||||
let two_rows = RecordBatch::new(
|
||||
schema.clone(),
|
||||
vec![Arc::new(StringVector::from(vec!["a", "b"])) as VectorRef],
|
||||
)
|
||||
.unwrap();
|
||||
assert!(
|
||||
decode_reply(&RecordBatches::try_new(schema.clone(), vec![two_rows]).unwrap()).is_err()
|
||||
);
|
||||
let int_schema = Arc::new(Schema::new(vec![ColumnSchema::new(
|
||||
"envelope",
|
||||
ConcreteDataType::int32_datatype(),
|
||||
false,
|
||||
)]));
|
||||
let non_string = RecordBatch::new(
|
||||
int_schema.clone(),
|
||||
vec![Arc::new(datatypes::vectors::Int32Vector::from(vec![Some(1)])) as VectorRef],
|
||||
)
|
||||
.unwrap();
|
||||
assert!(
|
||||
decode_reply(&RecordBatches::try_new(int_schema, vec![non_string]).unwrap()).is_err()
|
||||
);
|
||||
let invalid_json = RecordBatch::new(
|
||||
envelope_schema(),
|
||||
vec![Arc::new(StringVector::from(vec!["not json"])) as VectorRef],
|
||||
)
|
||||
.unwrap();
|
||||
assert!(
|
||||
decode_reply(
|
||||
&RecordBatches::try_new(invalid_json.schema.clone(), vec![invalid_json]).unwrap()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -15,8 +15,6 @@
|
||||
pub mod channel_manager;
|
||||
pub mod error;
|
||||
pub mod flight;
|
||||
#[cfg(feature = "enterprise")]
|
||||
pub mod flow_write;
|
||||
pub mod precision;
|
||||
pub mod reloadable_tls;
|
||||
pub mod select;
|
||||
|
||||
@@ -6,7 +6,7 @@ license.workspace = true
|
||||
|
||||
[features]
|
||||
testing = []
|
||||
enterprise = ["mito2/enterprise", "common-grpc/enterprise"]
|
||||
enterprise = ["mito2/enterprise"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -134,13 +134,18 @@ impl RegionAliveKeeper {
|
||||
}
|
||||
}
|
||||
|
||||
/// Renews the lease of regions to `deadline`.
|
||||
async fn renew_region_leases(&self, regions: &[GrantedRegion], deadline: Instant) {
|
||||
/// Renews the lease of regions to `deadline`, granted for a heartbeat sent at `sent_at`.
|
||||
async fn renew_region_leases(
|
||||
&self,
|
||||
regions: &[GrantedRegion],
|
||||
sent_at: Instant,
|
||||
deadline: Instant,
|
||||
) {
|
||||
for region in regions {
|
||||
let (role, region_id) = (region.role().into(), RegionId::from(region.region_id));
|
||||
if let Some(handle) = self.find_handle(region_id).await {
|
||||
handle
|
||||
.reset_deadline(role, deadline, region.extensions.clone())
|
||||
.reset_deadline(role, sent_at, deadline, region.extensions.clone())
|
||||
.await;
|
||||
} else {
|
||||
warn!(
|
||||
@@ -281,7 +286,7 @@ impl HeartbeatResponseHandler for RegionAliveKeeper {
|
||||
if let Some(mito) = self.region_server.mito_engine() {
|
||||
mito.renew_node_lease(deadline.into_std());
|
||||
}
|
||||
self.renew_region_leases(®ion_lease.regions, deadline)
|
||||
self.renew_region_leases(®ion_lease.regions, start_instant, deadline)
|
||||
.await;
|
||||
self.close_staled_regions(®ion_lease.closeable_region_ids)
|
||||
.await;
|
||||
@@ -296,8 +301,8 @@ enum CountdownCommand {
|
||||
/// 4 * `heartbeat_interval_millis`
|
||||
Start(u64),
|
||||
/// Reset countdown deadline to the given instance.
|
||||
/// (NextRole, Deadline, ExtensionInfo)
|
||||
Reset((RegionRole, Instant, HashMap<String, Vec<u8>>)),
|
||||
/// (NextRole, HeartbeatSentAt, Deadline, ExtensionInfo)
|
||||
Reset((RegionRole, Instant, Instant, HashMap<String, Vec<u8>>)),
|
||||
/// Returns the current deadline of the countdown task.
|
||||
#[cfg(test)]
|
||||
Deadline(oneshot::Sender<Instant>),
|
||||
@@ -377,12 +382,18 @@ impl CountdownTaskHandle {
|
||||
async fn reset_deadline(
|
||||
&self,
|
||||
role: RegionRole,
|
||||
sent_at: Instant,
|
||||
deadline: Instant,
|
||||
extension_info: HashMap<String, Vec<u8>>,
|
||||
) {
|
||||
if let Err(e) = self
|
||||
.tx
|
||||
.send(CountdownCommand::Reset((role, deadline, extension_info)))
|
||||
.send(CountdownCommand::Reset((
|
||||
role,
|
||||
sent_at,
|
||||
deadline,
|
||||
extension_info,
|
||||
)))
|
||||
.await
|
||||
{
|
||||
warn!(
|
||||
@@ -436,20 +447,25 @@ impl CountdownTask {
|
||||
started = true;
|
||||
}
|
||||
},
|
||||
Some(CountdownCommand::Reset((role, deadline, extension_info))) => {
|
||||
Some(CountdownCommand::Reset((role, sent_at, deadline, extension_info))) => {
|
||||
let prev_role_leader = self.region_server.is_region_leader(self.region_id).unwrap_or(false);
|
||||
if let Err(err) = self.region_server.set_region_role_with_lease(self.region_id, role, deadline.into_std()) {
|
||||
if err.status_code() == StatusCode::RegionNotFound {
|
||||
// Table metadata in metasrv is deleted after its regions are dropped.
|
||||
// The datanode may still receive lease renewal responses that depend on the metadata
|
||||
// during the short period before it is removed.
|
||||
warn!(err; "Failed to set region role to {role} for region {region_id}");
|
||||
} else {
|
||||
error!(err; "Failed to set region role to {role} for region {region_id}");
|
||||
let applied = match self.region_server.set_region_role_with_lease(self.region_id, role, sent_at.into_std(), deadline.into_std()) {
|
||||
Ok(applied) => applied,
|
||||
Err(err) => {
|
||||
if err.status_code() == StatusCode::RegionNotFound {
|
||||
// Table metadata in metasrv is deleted after its regions are dropped.
|
||||
// The datanode may still receive lease renewal responses that depend on the metadata
|
||||
// during the short period before it is removed.
|
||||
warn!(err; "Failed to set region role to {role} for region {region_id}");
|
||||
} else {
|
||||
error!(err; "Failed to set region role to {role} for region {region_id}");
|
||||
}
|
||||
false
|
||||
}
|
||||
};
|
||||
|
||||
// Finalize leadership: persist backfilled metadata.
|
||||
} else if !prev_role_leader && role == RegionRole::Leader
|
||||
// Finalize leadership if the grant was applied: persist backfilled metadata.
|
||||
if applied && !prev_role_leader && role == RegionRole::Leader
|
||||
&& let Err(err) = self
|
||||
.region_server
|
||||
.set_region_role_state_gracefully(self.region_id, SettableRegionRoleState::Leader)
|
||||
@@ -503,26 +519,42 @@ impl CountdownTask {
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
|
||||
use api::v1::Rows;
|
||||
use api::v1::meta::{HeartbeatResponse, RegionLease};
|
||||
use common_meta::heartbeat::mailbox::HeartbeatMailbox;
|
||||
use mito2::config::MitoConfig;
|
||||
use mito2::engine::MITO_ENGINE_NAME;
|
||||
use mito2::test_util::{CreateRequestBuilder, TestEnv, build_rows, rows_schema};
|
||||
use store_api::region_engine::RegionEngine;
|
||||
use store_api::region_engine::{
|
||||
RegionEngine, SetRegionRoleStateResponse, SetRegionRoleStateSuccess,
|
||||
};
|
||||
use store_api::region_request::{
|
||||
EnterStagingRequest, RegionPutRequest, StagingPartitionDirective,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
use crate::tests::mock_region_server;
|
||||
use crate::tests::{MockRegionEngine, mock_region_server};
|
||||
|
||||
/// Handles a heartbeat response that grants `regions` for a heartbeat sent now.
|
||||
async fn handle_lease_response(alive_keeper: &RegionAliveKeeper, regions: Vec<GrantedRegion>) {
|
||||
let sent_at = alive_keeper.epoch().elapsed();
|
||||
handle_lease_response_sent_at(alive_keeper, sent_at, regions).await;
|
||||
}
|
||||
|
||||
/// Handles a heartbeat response that grants `regions` for a heartbeat sent at `sent_at`
|
||||
/// after the epoch.
|
||||
async fn handle_lease_response_sent_at(
|
||||
alive_keeper: &RegionAliveKeeper,
|
||||
sent_at: Duration,
|
||||
regions: Vec<GrantedRegion>,
|
||||
) {
|
||||
let (tx, _rx) = mpsc::channel(1);
|
||||
let response = HeartbeatResponse {
|
||||
region_lease: Some(RegionLease {
|
||||
regions,
|
||||
duration_since_epoch: alive_keeper.epoch().elapsed().as_millis() as u64,
|
||||
duration_since_epoch: sent_at.as_millis() as u64,
|
||||
// The countdown of a granted region does not expire during the test.
|
||||
lease_seconds: 86400,
|
||||
closeable_region_ids: vec![],
|
||||
@@ -534,6 +566,38 @@ mod test {
|
||||
alive_keeper.handle(&mut ctx).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ignored_leader_grant_does_not_finalize_leadership() {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
let region_server = mock_region_server();
|
||||
let finalized = Arc::new(AtomicUsize::new(0));
|
||||
let (engine, _) = MockRegionEngine::with_custom_apply_fn(MITO_ENGINE_NAME, |engine| {
|
||||
// The engine ignores the grant, so the region stays a follower.
|
||||
engine.mock_role = Some(Some(RegionRole::Follower));
|
||||
let finalized = finalized.clone();
|
||||
engine.handle_set_readonly_gracefully_mock_fn = Some(Box::new(move |_| {
|
||||
finalized.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(SetRegionRoleStateResponse::success(
|
||||
SetRegionRoleStateSuccess::mito(0),
|
||||
))
|
||||
}));
|
||||
});
|
||||
let region_id = RegionId::new(1024, 1);
|
||||
region_server.register_test_region(region_id, engine);
|
||||
let alive_keeper =
|
||||
RegionAliveKeeper::new(region_server.clone(), None, Duration::from_millis(100));
|
||||
alive_keeper.register_region(region_id).await;
|
||||
let grant = GrantedRegion {
|
||||
region_id: region_id.as_u64(),
|
||||
role: api::v1::meta::RegionRole::Leader.into(),
|
||||
extensions: HashMap::new(),
|
||||
};
|
||||
handle_lease_response(&alive_keeper, vec![grant]).await;
|
||||
// The countdown task has handled the grant once it answers.
|
||||
alive_keeper.deadline(region_id).await.unwrap();
|
||||
assert_eq!(0, finalized.load(Ordering::Relaxed));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn lease_responses_let_regions_write() {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
@@ -583,10 +647,26 @@ mod test {
|
||||
role: api::v1::meta::RegionRole::Leader.into(),
|
||||
extensions: HashMap::new(),
|
||||
};
|
||||
handle_lease_response(&alive_keeper, vec![grant]).await;
|
||||
handle_lease_response(&alive_keeper, vec![grant.clone()]).await;
|
||||
// The countdown task has applied the grant once it answers.
|
||||
alive_keeper.deadline(region_id).await.unwrap();
|
||||
put(region_id).await.unwrap();
|
||||
|
||||
// A grant for a heartbeat sent before a downgrade does not make the region a leader again.
|
||||
let sent_before = alive_keeper.epoch().elapsed();
|
||||
region_server
|
||||
.set_region_role_state_gracefully(region_id, SettableRegionRoleState::Follower)
|
||||
.await
|
||||
.unwrap();
|
||||
handle_lease_response_sent_at(&alive_keeper, sent_before, vec![grant.clone()]).await;
|
||||
alive_keeper.deadline(region_id).await.unwrap();
|
||||
assert_eq!(region_server.is_region_leader(region_id), Some(false));
|
||||
|
||||
// Send times have millisecond precision, so the next heartbeat is sent after the downgrade.
|
||||
tokio::time::sleep(Duration::from_millis(2)).await;
|
||||
handle_lease_response(&alive_keeper, vec![grant]).await;
|
||||
alive_keeper.deadline(region_id).await.unwrap();
|
||||
put(region_id).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -641,6 +721,7 @@ mod test {
|
||||
role: api::v1::meta::RegionRole::Leader.into(),
|
||||
extensions: HashMap::new(),
|
||||
}],
|
||||
Instant::now(),
|
||||
Instant::now() + Duration::from_millis(200),
|
||||
)
|
||||
.await;
|
||||
@@ -694,6 +775,7 @@ mod test {
|
||||
countdown_handle
|
||||
.reset_deadline(
|
||||
RegionRole::Leader,
|
||||
Instant::now(),
|
||||
Instant::now() + Duration::from_millis(heartbeat_interval_millis * 5),
|
||||
HashMap::new(),
|
||||
)
|
||||
@@ -744,6 +826,7 @@ mod test {
|
||||
role: api::v1::meta::RegionRole::StagingLeader.into(),
|
||||
extensions: HashMap::new(),
|
||||
}],
|
||||
Instant::now(),
|
||||
Instant::now() + Duration::from_millis(3000),
|
||||
)
|
||||
.await;
|
||||
@@ -792,6 +875,7 @@ mod test {
|
||||
role: api::v1::meta::RegionRole::Leader.into(),
|
||||
extensions: HashMap::new(),
|
||||
}],
|
||||
Instant::now(),
|
||||
Instant::now() + Duration::from_millis(3000),
|
||||
)
|
||||
.await;
|
||||
@@ -834,6 +918,7 @@ mod test {
|
||||
role: api::v1::meta::RegionRole::StagingLeader.into(),
|
||||
extensions: HashMap::new(),
|
||||
}],
|
||||
Instant::now(),
|
||||
Instant::now() + Duration::from_millis(3000),
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -13,10 +13,6 @@
|
||||
// limitations under the License.
|
||||
|
||||
mod catalog;
|
||||
#[cfg(feature = "enterprise")]
|
||||
mod flow_write;
|
||||
#[cfg(feature = "enterprise")]
|
||||
use flow_write::TrackedPayload;
|
||||
mod registrations;
|
||||
mod remote_dyn_filter;
|
||||
|
||||
@@ -42,8 +38,6 @@ use async_trait::async_trait;
|
||||
use bytes::Bytes;
|
||||
use common_error::ext::{BoxedError, ErrorExt};
|
||||
use common_error::status_code::StatusCode;
|
||||
#[cfg(feature = "enterprise")]
|
||||
use common_grpc::flow_write::{COMMAND_KEY, FlowWriteRegistry, Reply};
|
||||
use common_meta::datanode::TopicStatsReporter;
|
||||
use common_query::OutputData;
|
||||
use common_query::request::QueryRequest;
|
||||
@@ -122,8 +116,6 @@ pub struct RegionServer {
|
||||
inner: Arc<RegionServerInner>,
|
||||
flight_compression: FlightCompression,
|
||||
suspend: Arc<AtomicBool>,
|
||||
#[cfg(feature = "enterprise")]
|
||||
flow_write_registry: Arc<FlowWriteRegistry<TrackedPayload, Reply>>,
|
||||
}
|
||||
|
||||
pub struct RegionStat {
|
||||
@@ -172,8 +164,6 @@ impl RegionServer {
|
||||
)),
|
||||
flight_compression,
|
||||
suspend: Arc::new(AtomicBool::new(false)),
|
||||
#[cfg(feature = "enterprise")]
|
||||
flow_write_registry: Arc::new(FlowWriteRegistry::default()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -471,20 +461,23 @@ impl RegionServer {
|
||||
.with_context(|_| HandleRegionRequestSnafu { region_id })
|
||||
}
|
||||
|
||||
/// Sets the role of a region from a lease the metasrv grants until `deadline`.
|
||||
/// Sets the role of a region from a lease the metasrv grants until `deadline`, in reply to a
|
||||
/// heartbeat sent at `sent_at`. Returns false if the engine ignores a Leader lease because the
|
||||
/// region was downgraded or (re)opened after `sent_at`.
|
||||
pub fn set_region_role_with_lease(
|
||||
&self,
|
||||
region_id: RegionId,
|
||||
role: RegionRole,
|
||||
sent_at: std::time::Instant,
|
||||
deadline: std::time::Instant,
|
||||
) -> Result<()> {
|
||||
) -> Result<bool> {
|
||||
let engine = self
|
||||
.inner
|
||||
.region_map
|
||||
.get(®ion_id)
|
||||
.with_context(|| RegionNotFoundSnafu { region_id })?;
|
||||
engine
|
||||
.set_region_role_with_lease(region_id, role, deadline)
|
||||
.set_region_role_with_lease(region_id, role, sent_at, deadline)
|
||||
.with_context(|_| HandleRegionRequestSnafu { region_id })
|
||||
}
|
||||
|
||||
@@ -1069,15 +1062,6 @@ impl RegionServerHandler for RegionServer {
|
||||
&self,
|
||||
request: RegionRequestV1,
|
||||
) -> ServerResult<RegionResponseV1> {
|
||||
#[cfg(feature = "enterprise")]
|
||||
if request
|
||||
.header
|
||||
.as_ref()
|
||||
.and_then(|header| header.query_context.as_ref())
|
||||
.is_some_and(|context| context.extensions.contains_key(COMMAND_KEY))
|
||||
{
|
||||
return self.handle_flow_write_request(request).await;
|
||||
}
|
||||
let accept_partial_result = request
|
||||
.header
|
||||
.as_ref()
|
||||
|
||||
@@ -1,969 +0,0 @@
|
||||
// Copyright 2023-2026 GrepTime Inc.
|
||||
//
|
||||
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
|
||||
// the GreptimeDB Enterprise License. You may not use this file except in
|
||||
// compliance with that license. A copy of the license is available at the root
|
||||
// of this repository in the file LICENSE-ENTERPRISE.
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, this software is
|
||||
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
// either express or implied.
|
||||
|
||||
//! Datanode receiver for tracked Flow writes.
|
||||
//!
|
||||
//! A single immutable operation per receiver-issued capability: the first
|
||||
//! admitted `Write` becomes the owner and executes the Inserts exactly once on
|
||||
//! the region engines; concurrent or retried identical writers join the
|
||||
//! owner's completion. Dropping a waiter (for example a lost RPC response)
|
||||
//! never cancels the engine work, and closing a capability rejects later
|
||||
//! writes with that capability. If the owner's outcome becomes unknown (a
|
||||
//! child ingest worker was lost), no positive terminal completion is
|
||||
//! published: waiters observe `WriterLost`; the capability admits no second
|
||||
//! owner, so no overlapping engine write can be produced.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use api::v1::region::RegionRequest as RegionRequestV1;
|
||||
use api::v1::region::region_request;
|
||||
use common_error::ext::ErrorExt;
|
||||
use common_grpc::flow_write::{Admission, COMMAND_KEY, Command, Reply, TerminalError};
|
||||
use common_runtime::runtime::RuntimeTrait;
|
||||
use common_telemetry::tracing_context::{FutureExt, TracingContext};
|
||||
use futures_util::future::join_all;
|
||||
use prost::Message;
|
||||
use servers::error::{InvalidQuerySnafu, Result as ServerResult};
|
||||
use snafu::OptionExt;
|
||||
|
||||
use crate::region_server::RegionServer;
|
||||
|
||||
/// Payload of a tracked write: encoded Inserts rows (exact bytes, so floats
|
||||
/// keep bit equality even for NaN), schemas compared by protobuf equality, and
|
||||
/// semantic header identity (dbname and command-free query context). Retrying
|
||||
/// with different business data or context is rejected instead of joining.
|
||||
pub(crate) type TrackedPayload = (
|
||||
Vec<u8>,
|
||||
Vec<Option<Vec<api::v1::ColumnSchema>>>,
|
||||
String,
|
||||
Option<api::v1::QueryContext>,
|
||||
);
|
||||
|
||||
fn tracked_payload(request: &RegionRequestV1) -> ServerResult<TrackedPayload> {
|
||||
let body = request.body.as_ref().context(InvalidQuerySnafu {
|
||||
reason: "Expecting non-empty region request body.",
|
||||
})?;
|
||||
if !matches!(body, region_request::Body::Inserts(_)) {
|
||||
return Err(servers::error::Error::InvalidQuery {
|
||||
reason: "Tracked Flow write supports Inserts requests only.".to_string(),
|
||||
location: snafu::Location::new(file!(), line!(), column!()),
|
||||
});
|
||||
}
|
||||
// Oneof is not `prost::Message`; the variant message itself is. Schema
|
||||
// options contain unordered maps, so compare schemas separately rather than
|
||||
// letting their wire ordering affect retries; retain encoded rows for NaN.
|
||||
let (bytes, schemas) = match body {
|
||||
region_request::Body::Inserts(inserts) => {
|
||||
let mut inserts = inserts.clone();
|
||||
let schemas = inserts
|
||||
.requests
|
||||
.iter_mut()
|
||||
.map(|request| {
|
||||
request
|
||||
.rows
|
||||
.as_mut()
|
||||
.map(|rows| std::mem::take(&mut rows.schema))
|
||||
})
|
||||
.collect();
|
||||
(inserts.encode_to_vec(), schemas)
|
||||
}
|
||||
_ => unreachable!("checked above"),
|
||||
};
|
||||
let header = request.header.as_ref();
|
||||
let mut query_context = header.and_then(|header| header.query_context.clone());
|
||||
if let Some(context) = query_context.as_mut() {
|
||||
// The command extension differs per control request, not per business.
|
||||
context.extensions.remove(COMMAND_KEY);
|
||||
}
|
||||
Ok((
|
||||
bytes,
|
||||
schemas,
|
||||
header
|
||||
.map(|header| header.dbname.clone())
|
||||
.unwrap_or_default(),
|
||||
query_context,
|
||||
))
|
||||
}
|
||||
|
||||
fn ensure_empty_control_body(request: &RegionRequestV1) -> ServerResult<()> {
|
||||
match request.body.as_ref() {
|
||||
Some(region_request::Body::Inserts(inserts)) if inserts.requests.is_empty() => Ok(()),
|
||||
_ => Err(servers::error::Error::InvalidQuery {
|
||||
reason: "Tracked Flow write control requests must carry an empty Inserts body."
|
||||
.to_string(),
|
||||
location: snafu::Location::new(file!(), line!(), column!()),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn registry_error(error: common_grpc::flow_write::RegistryError) -> servers::error::Error {
|
||||
servers::error::Error::UnexpectedResult {
|
||||
reason: format!("Tracked Flow write registry rejected request: {error:?}"),
|
||||
location: snafu::Location::new(file!(), line!(), column!()),
|
||||
}
|
||||
}
|
||||
|
||||
fn response(reply: Reply) -> ServerResult<api::v1::region::RegionResponse> {
|
||||
let encoded =
|
||||
serde_json::to_vec(&reply).map_err(|error| servers::error::Error::UnexpectedResult {
|
||||
reason: format!("Failed to encode tracked Flow write reply: {error}"),
|
||||
location: snafu::Location::new(file!(), line!(), column!()),
|
||||
})?;
|
||||
let mut extensions = std::collections::HashMap::new();
|
||||
extensions.insert(COMMAND_KEY.to_string(), encoded);
|
||||
Ok(api::v1::region::RegionResponse {
|
||||
header: Some(api::v1::ResponseHeader {
|
||||
status: Some(api::v1::Status {
|
||||
status_code: common_error::status_code::StatusCode::Success as _,
|
||||
..Default::default()
|
||||
}),
|
||||
}),
|
||||
affected_rows: 0,
|
||||
extensions,
|
||||
metadata: Vec::new(),
|
||||
failures: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
impl RegionServer {
|
||||
pub(crate) async fn handle_flow_write_request(
|
||||
&self,
|
||||
request: RegionRequestV1,
|
||||
) -> ServerResult<api::v1::region::RegionResponse> {
|
||||
let command = request
|
||||
.header
|
||||
.as_ref()
|
||||
.and_then(|header| header.query_context.as_ref())
|
||||
.and_then(|context| context.extensions.get(COMMAND_KEY))
|
||||
.and_then(|value| Command::decode(value).ok());
|
||||
let command = match command {
|
||||
Some(command) => command,
|
||||
None => {
|
||||
// The extension exists but is not a decodable command: reject
|
||||
// before any ordinary DML dispatch.
|
||||
return Err(InvalidQuerySnafu {
|
||||
reason: "Malformed tracked Flow write command.",
|
||||
}
|
||||
.build());
|
||||
}
|
||||
};
|
||||
|
||||
match command {
|
||||
Command::Open { nonce } => {
|
||||
ensure_empty_control_body(&request)?;
|
||||
let capability = self
|
||||
.flow_write_registry
|
||||
.open(&nonce)
|
||||
.map_err(registry_error)?;
|
||||
response(Reply::Opened { capability })
|
||||
}
|
||||
Command::Close { capability } => {
|
||||
ensure_empty_control_body(&request)?;
|
||||
self.flow_write_registry
|
||||
.close(&capability)
|
||||
.await
|
||||
.map_err(registry_error)?;
|
||||
response(Reply::Closed)
|
||||
}
|
||||
Command::Write { capability } => {
|
||||
let payload = tracked_payload(&request)?;
|
||||
let admission = self
|
||||
.flow_write_registry
|
||||
.admit(&capability, payload)
|
||||
.map_err(registry_error)?;
|
||||
let reply = match admission {
|
||||
Admission::Start(owner) => {
|
||||
// Subscribe before the owner sender moves into the
|
||||
// spawned task: this caller stays a plain waiter whose
|
||||
// drop cannot cancel the engine work.
|
||||
let receiver = owner.subscribe();
|
||||
let server = self.clone();
|
||||
let body = request.body;
|
||||
let header = request.header;
|
||||
self.inner.runtime.spawn(async move {
|
||||
let completion = server
|
||||
.run_tracked_write(header, body)
|
||||
.trace(TracingContext::from_current_span().attach(
|
||||
common_telemetry::tracing::info_span!(
|
||||
"RegionServer::tracked_flow_write"
|
||||
),
|
||||
))
|
||||
.await;
|
||||
match completion {
|
||||
Some(reply) => {
|
||||
let _ = owner.send(Some(Arc::new(reply)));
|
||||
}
|
||||
None => {
|
||||
// Unknown worker outcome: no positive terminal
|
||||
// result is published. Dropping the sender lets
|
||||
// waiters observe `WriterLost`.
|
||||
drop(owner);
|
||||
}
|
||||
}
|
||||
});
|
||||
common_grpc::flow_write::wait_completion(receiver)
|
||||
.await
|
||||
.map_err(registry_error)?
|
||||
}
|
||||
Admission::Join(waiter) => common_grpc::flow_write::wait_completion(waiter)
|
||||
.await
|
||||
.map_err(registry_error)?,
|
||||
};
|
||||
response((*reply).clone())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes one admitted tracked write. Returns `None` only when the
|
||||
/// outcome is unknown (a child worker was lost); malformed request bodies
|
||||
/// are terminal because no child was ever dispatched.
|
||||
async fn run_tracked_write(
|
||||
&self,
|
||||
header: Option<api::v1::region::RegionRequestHeader>,
|
||||
body: Option<region_request::Body>,
|
||||
) -> Option<Reply> {
|
||||
let requests =
|
||||
match body.map(store_api::region_request::RegionRequest::try_from_request_body) {
|
||||
Some(Ok(requests)) => requests,
|
||||
Some(Err(error)) => {
|
||||
return Some(Reply::Complete {
|
||||
rows: 0,
|
||||
cost: 0,
|
||||
metrics: None,
|
||||
error: Some(TerminalError {
|
||||
code: error.status_code() as u32,
|
||||
message: error.output_msg(),
|
||||
}),
|
||||
});
|
||||
}
|
||||
// `None` is unreachable here: the Write path already rejected an
|
||||
// empty body before admission. Treat it as unknown rather than
|
||||
// inventing a terminal result.
|
||||
None => return None,
|
||||
};
|
||||
let tracing = header
|
||||
.as_ref()
|
||||
.map(|header| TracingContext::from_w3c(&header.tracing_context))
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut unknown_worker = false;
|
||||
let mut first_error: Option<crate::error::Error> = None;
|
||||
let mut affected_rows = 0usize;
|
||||
|
||||
let tasks = requests.into_iter().map(|(region_id, request)| {
|
||||
let span = tracing.attach(common_telemetry::tracing::info_span!(
|
||||
"RegionServer::tracked_region_write",
|
||||
region_id = region_id.to_string()
|
||||
));
|
||||
async move { self.handle_request(region_id, request).trace(span).await }
|
||||
});
|
||||
// Drain every per-region child before any terminal decision. A lost
|
||||
// ingest worker (`RuntimeJoin`) is unknown and outranks any ordinary
|
||||
// application error observed during the same drain.
|
||||
for result in join_all(tasks).await {
|
||||
match result {
|
||||
Ok(response) => affected_rows += response.affected_rows,
|
||||
Err(crate::error::Error::RuntimeJoin { .. }) => {
|
||||
unknown_worker = true;
|
||||
}
|
||||
Err(error) if first_error.is_none() => first_error = Some(error),
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
if unknown_worker {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(match first_error {
|
||||
None => Reply::Complete {
|
||||
rows: affected_rows,
|
||||
cost: affected_rows,
|
||||
metrics: None,
|
||||
error: None,
|
||||
},
|
||||
Some(error) => Reply::Complete {
|
||||
rows: 0,
|
||||
cost: 0,
|
||||
metrics: None,
|
||||
error: Some(TerminalError {
|
||||
code: error.status_code() as u32,
|
||||
message: error.output_msg(),
|
||||
}),
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use api::region::RegionResponse;
|
||||
use api::v1::region::region_request::Body;
|
||||
use api::v1::region::{
|
||||
InsertRequest, InsertRequests, RegionRequest as Request, RegionRequestHeader,
|
||||
};
|
||||
use api::v1::{ColumnDataType, ColumnSchema, QueryContext, Row, Rows, SemanticType, Value};
|
||||
use common_grpc::flow_write::{self, Command, Reply};
|
||||
use servers::grpc::region_server::RegionServerHandler;
|
||||
use store_api::region_engine::{RegionEngine, RegionEngineRef};
|
||||
use store_api::storage::RegionId;
|
||||
use tokio::sync::Notify;
|
||||
use tokio::time::{Duration, timeout};
|
||||
|
||||
use super::*;
|
||||
use crate::tests::{MockRegionEngine, mock_region_server};
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct Gate {
|
||||
entered: Arc<AtomicUsize>,
|
||||
notified: Arc<Notify>,
|
||||
open: Arc<AtomicUsize>,
|
||||
fail: bool,
|
||||
}
|
||||
|
||||
impl Gate {
|
||||
async fn wait_entered(&self, count: usize) {
|
||||
timeout(Duration::from_secs(5), async {
|
||||
loop {
|
||||
let notified = self.notified.notified();
|
||||
tokio::pin!(notified);
|
||||
notified.as_mut().enable();
|
||||
if self.entered.load(Ordering::SeqCst) >= count {
|
||||
break;
|
||||
}
|
||||
notified.await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
fn release(&self) {
|
||||
self.open.store(1, Ordering::SeqCst);
|
||||
self.notified.notify_waiters();
|
||||
}
|
||||
async fn wait_open(&self) {
|
||||
loop {
|
||||
let notified = self.notified.notified();
|
||||
tokio::pin!(notified);
|
||||
notified.as_mut().enable();
|
||||
if self.open.load(Ordering::SeqCst) != 0 {
|
||||
break;
|
||||
}
|
||||
notified.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct GatedEngine {
|
||||
gate: Gate,
|
||||
inner: Arc<MockRegionEngine>,
|
||||
panic_id: Option<u64>,
|
||||
}
|
||||
#[async_trait::async_trait]
|
||||
impl RegionEngine for GatedEngine {
|
||||
fn name(&self) -> &str {
|
||||
self.inner.name()
|
||||
}
|
||||
async fn handle_request(
|
||||
&self,
|
||||
id: RegionId,
|
||||
_request: store_api::region_request::RegionRequest,
|
||||
) -> Result<RegionResponse, common_error::ext::BoxedError> {
|
||||
self.gate.entered.fetch_add(1, Ordering::SeqCst);
|
||||
self.gate.notified.notify_waiters();
|
||||
if self.panic_id == Some(id.as_u64()) {
|
||||
panic!("test ingest panic");
|
||||
}
|
||||
if self.gate.fail && id.as_u64() == 1 {
|
||||
return Err(common_error::ext::BoxedError::new(
|
||||
crate::error::RegionNotFoundSnafu { region_id: id }.build(),
|
||||
));
|
||||
}
|
||||
self.gate.wait_open().await;
|
||||
Ok(RegionResponse::new(1))
|
||||
}
|
||||
async fn handle_query(
|
||||
&self,
|
||||
id: RegionId,
|
||||
req: store_api::storage::ScanRequest,
|
||||
) -> Result<store_api::region_engine::RegionScannerRef, common_error::ext::BoxedError>
|
||||
{
|
||||
self.inner.handle_query(id, req).await
|
||||
}
|
||||
async fn get_committed_sequence(
|
||||
&self,
|
||||
id: RegionId,
|
||||
) -> Result<store_api::storage::SequenceNumber, common_error::ext::BoxedError> {
|
||||
self.inner.get_committed_sequence(id).await
|
||||
}
|
||||
async fn get_metadata(
|
||||
&self,
|
||||
id: RegionId,
|
||||
) -> Result<store_api::metadata::RegionMetadataRef, common_error::ext::BoxedError> {
|
||||
self.inner.get_metadata(id).await
|
||||
}
|
||||
fn region_statistic(
|
||||
&self,
|
||||
id: RegionId,
|
||||
) -> Option<store_api::region_engine::RegionStatistic> {
|
||||
self.inner.region_statistic(id)
|
||||
}
|
||||
async fn stop(&self) -> Result<(), common_error::ext::BoxedError> {
|
||||
self.inner.stop().await
|
||||
}
|
||||
fn set_region_role(
|
||||
&self,
|
||||
id: RegionId,
|
||||
role: store_api::region_engine::RegionRole,
|
||||
) -> Result<(), common_error::ext::BoxedError> {
|
||||
self.inner.set_region_role(id, role)
|
||||
}
|
||||
|
||||
fn set_region_role_with_lease(
|
||||
&self,
|
||||
id: RegionId,
|
||||
role: store_api::region_engine::RegionRole,
|
||||
deadline: std::time::Instant,
|
||||
) -> Result<(), common_error::ext::BoxedError> {
|
||||
self.inner.set_region_role_with_lease(id, role, deadline)
|
||||
}
|
||||
async fn sync_region(
|
||||
&self,
|
||||
id: RegionId,
|
||||
req: store_api::region_engine::SyncRegionFromRequest,
|
||||
) -> Result<store_api::region_engine::SyncRegionFromResponse, common_error::ext::BoxedError>
|
||||
{
|
||||
self.inner.sync_region(id, req).await
|
||||
}
|
||||
async fn remap_manifests(
|
||||
&self,
|
||||
req: store_api::region_engine::RemapManifestsRequest,
|
||||
) -> Result<store_api::region_engine::RemapManifestsResponse, common_error::ext::BoxedError>
|
||||
{
|
||||
self.inner.remap_manifests(req).await
|
||||
}
|
||||
async fn set_region_role_state_gracefully(
|
||||
&self,
|
||||
id: RegionId,
|
||||
state: store_api::region_engine::SettableRegionRoleState,
|
||||
) -> Result<
|
||||
store_api::region_engine::SetRegionRoleStateResponse,
|
||||
common_error::ext::BoxedError,
|
||||
> {
|
||||
self.inner.set_region_role_state_gracefully(id, state).await
|
||||
}
|
||||
fn role(&self, id: RegionId) -> Option<store_api::region_engine::RegionRole> {
|
||||
self.inner.role(id)
|
||||
}
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
fn body(ids: &[u64], nan: bool) -> Body {
|
||||
Body::Inserts(InsertRequests {
|
||||
requests: ids
|
||||
.iter()
|
||||
.map(|id| InsertRequest {
|
||||
region_id: *id,
|
||||
rows: Some(Rows {
|
||||
schema: vec![
|
||||
ColumnSchema {
|
||||
column_name: "ts".into(),
|
||||
datatype: ColumnDataType::TimestampMillisecond as i32,
|
||||
semantic_type: SemanticType::Timestamp as i32,
|
||||
datatype_extension: None,
|
||||
options: None,
|
||||
},
|
||||
ColumnSchema {
|
||||
column_name: "v".into(),
|
||||
datatype: ColumnDataType::Float64 as i32,
|
||||
semantic_type: SemanticType::Field as i32,
|
||||
datatype_extension: None,
|
||||
options: None,
|
||||
},
|
||||
],
|
||||
rows: vec![Row {
|
||||
values: vec![
|
||||
Value {
|
||||
value_data: Some(
|
||||
api::v1::value::ValueData::TimestampMillisecondValue(1),
|
||||
),
|
||||
},
|
||||
Value {
|
||||
value_data: Some(api::v1::value::ValueData::F64Value(if nan {
|
||||
f64::NAN
|
||||
} else {
|
||||
7.
|
||||
})),
|
||||
},
|
||||
],
|
||||
}],
|
||||
}),
|
||||
partition_expr_version: None,
|
||||
skip_wal: false,
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
}
|
||||
|
||||
fn request(cmd: Command, body: Option<Body>) -> Request {
|
||||
let mut extensions = HashMap::new();
|
||||
extensions.insert(flow_write::COMMAND_KEY.into(), cmd.encode().unwrap());
|
||||
Request {
|
||||
header: Some(RegionRequestHeader {
|
||||
dbname: "db".into(),
|
||||
tracing_context: Default::default(),
|
||||
query_context: Some(QueryContext {
|
||||
extensions,
|
||||
..Default::default()
|
||||
}),
|
||||
}),
|
||||
body,
|
||||
}
|
||||
}
|
||||
fn decode(resp: &api::v1::region::RegionResponse) -> Reply {
|
||||
assert_eq!(
|
||||
resp.header
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.status
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.status_code,
|
||||
common_error::status_code::StatusCode::Success as u32
|
||||
);
|
||||
serde_json::from_slice(resp.extensions.get(flow_write::COMMAND_KEY).unwrap()).unwrap()
|
||||
}
|
||||
async fn open(s: &RegionServer) -> String {
|
||||
match decode(
|
||||
&s.handle_region_request(request(
|
||||
Command::Open { nonce: "n".into() },
|
||||
Some(Body::Inserts(InsertRequests { requests: vec![] })),
|
||||
))
|
||||
.await
|
||||
.unwrap(),
|
||||
) {
|
||||
Reply::Opened { capability } => capability,
|
||||
x => panic!("{x:?}"),
|
||||
}
|
||||
}
|
||||
fn setup(gate: Gate, panic_id: Option<u64>, ids: &[u64]) -> RegionServer {
|
||||
let s = mock_region_server();
|
||||
let (inner, _) = MockRegionEngine::new("mock");
|
||||
let engine: RegionEngineRef = Arc::new(GatedEngine {
|
||||
gate,
|
||||
inner,
|
||||
panic_id,
|
||||
});
|
||||
for id in ids {
|
||||
s.inner.region_map.insert(
|
||||
RegionId::from_u64(*id),
|
||||
super::super::RegionEngineWithStatus::Ready(engine.clone()),
|
||||
);
|
||||
}
|
||||
s
|
||||
}
|
||||
fn write(cap: &str, ids: &[u64], nan: bool) -> Request {
|
||||
request(
|
||||
Command::Write {
|
||||
capability: cap.into(),
|
||||
},
|
||||
Some(body(ids, nan)),
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropped_rpc_retry_and_close_drain_exactly_once() {
|
||||
let gate = Gate::default();
|
||||
let s = setup(gate.clone(), None, &[1, 2]);
|
||||
let cap = open(&s).await;
|
||||
let w = write(&cap, &[1, 2], false);
|
||||
let first = tokio::spawn({
|
||||
let s = s.clone();
|
||||
let w = w.clone();
|
||||
async move { s.handle_region_request(w).await }
|
||||
});
|
||||
gate.wait_entered(2).await;
|
||||
first.abort();
|
||||
// Exercise the same actual registry admission used by retry, before release.
|
||||
let payload = tracked_payload(&w).unwrap();
|
||||
let Admission::Join(waiter) = s.flow_write_registry.admit(&cap, payload).unwrap() else {
|
||||
panic!("retry did not join")
|
||||
};
|
||||
let mut retry_waiter = tokio::spawn(common_grpc::flow_write::wait_completion(waiter));
|
||||
assert!(
|
||||
timeout(Duration::from_millis(20), &mut retry_waiter)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let mut closer = tokio::spawn({
|
||||
let s = s.clone();
|
||||
let cap = cap.clone();
|
||||
async move {
|
||||
s.handle_region_request(request(
|
||||
Command::Close { capability: cap },
|
||||
Some(Body::Inserts(InsertRequests { requests: vec![] })),
|
||||
))
|
||||
.await
|
||||
}
|
||||
});
|
||||
assert!(
|
||||
timeout(Duration::from_millis(20), &mut closer)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
gate.release();
|
||||
let joined = timeout(Duration::from_secs(5), &mut retry_waiter)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
*joined,
|
||||
Reply::Complete {
|
||||
rows: 2,
|
||||
error: None,
|
||||
..
|
||||
}
|
||||
));
|
||||
assert!(matches!(
|
||||
decode(
|
||||
&timeout(Duration::from_secs(5), &mut closer)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
),
|
||||
Reply::Closed
|
||||
));
|
||||
assert!(
|
||||
s.handle_region_request(write(&cap, &[1], false))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let cap2 = open(&s).await;
|
||||
gate.release();
|
||||
let r = s
|
||||
.handle_region_request(write(&cap2, &[1], false))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(matches!(decode(&r), Reply::Complete { rows: 1, .. }));
|
||||
assert!(
|
||||
s.handle_region_request(write(&cap, &[1], false))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(gate.entered.load(Ordering::SeqCst), 3);
|
||||
let close2 = request(
|
||||
Command::Close { capability: cap2 },
|
||||
Some(Body::Inserts(InsertRequests { requests: vec![] })),
|
||||
);
|
||||
assert!(matches!(
|
||||
decode(&s.handle_region_request(close2).await.unwrap()),
|
||||
Reply::Closed
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn application_error_waits_for_sibling_and_panic_overrides_it() {
|
||||
let gate = Gate {
|
||||
fail: true,
|
||||
..Default::default()
|
||||
};
|
||||
let s = setup(gate.clone(), None, &[1, 2]);
|
||||
let cap = open(&s).await;
|
||||
let task = tokio::spawn({
|
||||
let s = s.clone();
|
||||
async move { s.handle_region_request(write(&cap, &[1, 2], false)).await }
|
||||
});
|
||||
gate.wait_entered(2).await;
|
||||
// The ordinary error is immediate for region 1, but region 2 remains gated.
|
||||
assert!(!task.is_finished());
|
||||
gate.release();
|
||||
let r = timeout(Duration::from_secs(5), task)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(matches!(decode(&r), Reply::Complete { error: Some(_), .. }));
|
||||
|
||||
let gate = Gate {
|
||||
fail: true,
|
||||
..Default::default()
|
||||
};
|
||||
let s = setup(gate.clone(), Some(2), &[1, 2, 3]);
|
||||
let cap = open(&s).await;
|
||||
let task = tokio::spawn({
|
||||
let s = s.clone();
|
||||
let cap = cap.clone();
|
||||
async move {
|
||||
s.handle_region_request(write(&cap, &[1, 2, 3], false))
|
||||
.await
|
||||
}
|
||||
});
|
||||
gate.wait_entered(3).await;
|
||||
assert!(!task.is_finished());
|
||||
gate.release();
|
||||
assert!(
|
||||
timeout(Duration::from_secs(5), task)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
s.handle_region_request(write(&cap, &[1, 2, 3], false))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(gate.entered.load(Ordering::SeqCst), 3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn decoded_schema_option_maps_join_live_nan_write() {
|
||||
let gate = Gate::default();
|
||||
let s = setup(gate.clone(), None, &[1]);
|
||||
let cap = open(&s).await;
|
||||
let mut original = write(&cap, &[1], true);
|
||||
let Body::Inserts(inserts) = original.body.as_mut().unwrap() else {
|
||||
unreachable!()
|
||||
};
|
||||
inserts.requests[0].rows.as_mut().unwrap().schema[1].options =
|
||||
Some(api::v1::ColumnOptions {
|
||||
options: [
|
||||
("alpha".to_string(), "one".to_string()),
|
||||
("beta".to_string(), "two".to_string()),
|
||||
("gamma".to_string(), "three".to_string()),
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
});
|
||||
let encoded = original.encode_to_vec();
|
||||
let Body::Inserts(original_inserts) = original.body.as_ref().unwrap() else {
|
||||
unreachable!()
|
||||
};
|
||||
let original_rows = original_inserts.requests[0].rows.clone();
|
||||
let original_body_bytes = original_inserts.encode_to_vec();
|
||||
let mut retries = Vec::new();
|
||||
let mut found_different_wire_order = false;
|
||||
for _ in 0..128 {
|
||||
let decoded = Request::decode(encoded.as_slice()).unwrap();
|
||||
let Body::Inserts(decoded_inserts) = decoded.body.as_ref().unwrap() else {
|
||||
unreachable!()
|
||||
};
|
||||
assert_eq!(
|
||||
decoded_inserts.requests[0].rows.as_ref().unwrap().schema,
|
||||
original_rows.as_ref().unwrap().schema
|
||||
);
|
||||
assert_eq!(
|
||||
tracked_payload(&decoded).unwrap(),
|
||||
tracked_payload(&original).unwrap()
|
||||
);
|
||||
found_different_wire_order |= decoded_inserts.encode_to_vec() != original_body_bytes;
|
||||
retries.push(decoded);
|
||||
if found_different_wire_order && retries.len() >= 16 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(found_different_wire_order);
|
||||
|
||||
let owner = tokio::spawn({
|
||||
let s = s.clone();
|
||||
async move { s.handle_region_request(original).await }
|
||||
});
|
||||
gate.wait_entered(1).await;
|
||||
let retry_tasks: Vec<_> = retries
|
||||
.into_iter()
|
||||
.map(|retry| {
|
||||
let s = s.clone();
|
||||
tokio::spawn(async move { s.handle_region_request(retry).await })
|
||||
})
|
||||
.collect();
|
||||
tokio::task::yield_now().await;
|
||||
assert!(retry_tasks.iter().all(|retry| !retry.is_finished()));
|
||||
assert_eq!(gate.entered.load(Ordering::SeqCst), 1);
|
||||
gate.release();
|
||||
let owner_reply = decode(
|
||||
&timeout(Duration::from_secs(5), owner)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
);
|
||||
assert!(matches!(
|
||||
&owner_reply,
|
||||
Reply::Complete {
|
||||
rows: 1,
|
||||
error: None,
|
||||
..
|
||||
}
|
||||
));
|
||||
let owner_reply_json = serde_json::to_string(&owner_reply).unwrap();
|
||||
for retry in retry_tasks {
|
||||
let retry_reply = decode(
|
||||
&timeout(Duration::from_secs(5), retry)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
);
|
||||
assert!(matches!(
|
||||
&retry_reply,
|
||||
Reply::Complete {
|
||||
rows: 1,
|
||||
error: None,
|
||||
..
|
||||
}
|
||||
));
|
||||
assert_eq!(
|
||||
serde_json::to_string(&retry_reply).unwrap(),
|
||||
owner_reply_json
|
||||
);
|
||||
}
|
||||
assert_eq!(gate.entered.load(Ordering::SeqCst), 1);
|
||||
|
||||
let replay = Request::decode(encoded.as_slice()).unwrap();
|
||||
assert!(matches!(
|
||||
decode(&s.handle_region_request(replay.clone()).await.unwrap()),
|
||||
Reply::Complete { rows: 1, .. }
|
||||
));
|
||||
let mut changed_schema = replay.clone();
|
||||
let Body::Inserts(inserts) = changed_schema.body.as_mut().unwrap() else {
|
||||
unreachable!()
|
||||
};
|
||||
inserts.requests[0].rows.as_mut().unwrap().schema[1]
|
||||
.options
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.options
|
||||
.insert("gamma".into(), "changed".into());
|
||||
assert!(s.handle_region_request(changed_schema).await.is_err());
|
||||
let close = request(
|
||||
Command::Close {
|
||||
capability: cap.clone(),
|
||||
},
|
||||
Some(Body::Inserts(InsertRequests { requests: vec![] })),
|
||||
);
|
||||
assert!(matches!(
|
||||
decode(&s.handle_region_request(close).await.unwrap()),
|
||||
Reply::Closed
|
||||
));
|
||||
assert!(s.handle_region_request(replay).await.is_err());
|
||||
assert_eq!(gate.entered.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn payload_identity_nan_semantics_and_pre_admission_rejection() {
|
||||
let s = mock_region_server();
|
||||
let cap = open(&s).await;
|
||||
let a = write(&cap, &[1], true);
|
||||
let b = write(&cap, &[1], true);
|
||||
assert_eq!(tracked_payload(&a).unwrap(), tracked_payload(&b).unwrap());
|
||||
let owner = match s
|
||||
.flow_write_registry
|
||||
.admit(&cap, tracked_payload(&a).unwrap())
|
||||
.unwrap()
|
||||
{
|
||||
Admission::Start(owner) => owner,
|
||||
_ => panic!(),
|
||||
};
|
||||
let mut semantic_mismatch = b.clone();
|
||||
semantic_mismatch.header.as_mut().unwrap().dbname = "other_db".into();
|
||||
assert_eq!(
|
||||
s.flow_write_registry
|
||||
.admit(&cap, tracked_payload(&semantic_mismatch).unwrap())
|
||||
.unwrap_err(),
|
||||
flow_write::RegistryError::PayloadMismatch
|
||||
);
|
||||
semantic_mismatch = b.clone();
|
||||
semantic_mismatch
|
||||
.header
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.query_context
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.extensions
|
||||
.insert("flow_lane".into(), "changed".into());
|
||||
assert_eq!(
|
||||
s.flow_write_registry
|
||||
.admit(&cap, tracked_payload(&semantic_mismatch).unwrap())
|
||||
.unwrap_err(),
|
||||
flow_write::RegistryError::PayloadMismatch
|
||||
);
|
||||
let Admission::Join(waiter) = s
|
||||
.flow_write_registry
|
||||
.admit(&cap, tracked_payload(&b).unwrap())
|
||||
.unwrap()
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
let mut joined = tokio::spawn(common_grpc::flow_write::wait_completion(waiter));
|
||||
assert!(
|
||||
timeout(Duration::from_millis(20), &mut joined)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
owner
|
||||
.send(Some(Arc::new(Reply::Complete {
|
||||
rows: 1,
|
||||
cost: 1,
|
||||
metrics: None,
|
||||
error: None,
|
||||
})))
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
*timeout(Duration::from_secs(5), &mut joined)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
Reply::Complete { rows: 1, .. }
|
||||
));
|
||||
s.flow_write_registry.close(&cap).await.unwrap();
|
||||
assert_ne!(
|
||||
tracked_payload(&a).unwrap(),
|
||||
tracked_payload(&write(&cap, &[1], false)).unwrap()
|
||||
);
|
||||
assert!(
|
||||
s.handle_region_request(request(
|
||||
Command::Write {
|
||||
capability: cap.clone()
|
||||
},
|
||||
Some(Body::Deletes(Default::default()))
|
||||
))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let fresh = open(&s).await;
|
||||
let mut bad = request(
|
||||
Command::Write {
|
||||
capability: fresh.clone(),
|
||||
},
|
||||
Some(body(&[1], false)),
|
||||
);
|
||||
bad.header
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.query_context
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.extensions
|
||||
.insert(flow_write::COMMAND_KEY.into(), "not-json".into());
|
||||
assert!(s.handle_region_request(bad).await.is_err());
|
||||
s.flow_write_registry.close(&fresh).await.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -292,10 +292,12 @@ impl RegionEngine for MockRegionEngine {
|
||||
fn set_region_role_with_lease(
|
||||
&self,
|
||||
_region_id: RegionId,
|
||||
_role: RegionRole,
|
||||
role: RegionRole,
|
||||
_sent_at: std::time::Instant,
|
||||
_deadline: std::time::Instant,
|
||||
) -> Result<(), BoxedError> {
|
||||
Ok(())
|
||||
) -> Result<bool, BoxedError> {
|
||||
// A mocked role stays, so a grant of another role is not applied.
|
||||
Ok(self.mock_role.flatten().is_none_or(|mocked| mocked == role))
|
||||
}
|
||||
|
||||
async fn set_region_role_state_gracefully(
|
||||
|
||||
@@ -137,9 +137,10 @@ impl RegionEngine for FileRegionEngine {
|
||||
&self,
|
||||
region_id: RegionId,
|
||||
role: RegionRole,
|
||||
_sent_at: Instant,
|
||||
_deadline: Instant,
|
||||
) -> Result<(), BoxedError> {
|
||||
self.set_region_role(region_id, role)
|
||||
) -> Result<bool, BoxedError> {
|
||||
self.set_region_role(region_id, role).map(|_| true)
|
||||
}
|
||||
|
||||
async fn set_region_role_state_gracefully(
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[features]
|
||||
enterprise = ["common-grpc/enterprise", "session/enterprise"]
|
||||
enterprise = []
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -95,12 +95,8 @@ pub enum FrontendClient {
|
||||
control_channel_manager: ChannelManager,
|
||||
query: QueryOptions,
|
||||
batch_opts: BatchingModeOptions,
|
||||
#[cfg(feature = "enterprise")]
|
||||
tracked_writes: bool,
|
||||
},
|
||||
Standalone {
|
||||
#[cfg(feature = "enterprise")]
|
||||
tracked_writes: bool,
|
||||
/// for the sake of simplicity still use grpc even in standalone mode
|
||||
/// notice the client here should all be lazy, so that can wait after frontend is booted then make conn
|
||||
database_client: HandlerMutable,
|
||||
@@ -109,26 +105,6 @@ pub enum FrontendClient {
|
||||
}
|
||||
|
||||
impl FrontendClient {
|
||||
#[cfg(feature = "enterprise")]
|
||||
pub fn with_tracked_writes(&self) -> Self {
|
||||
let mut client = self.clone();
|
||||
match &mut client {
|
||||
Self::Distributed { tracked_writes, .. } | Self::Standalone { tracked_writes, .. } => {
|
||||
*tracked_writes = true;
|
||||
}
|
||||
}
|
||||
client
|
||||
}
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
fn tracked_writes_enabled(&self) -> bool {
|
||||
match self {
|
||||
Self::Distributed { tracked_writes, .. } | Self::Standalone { tracked_writes, .. } => {
|
||||
*tracked_writes
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new empty frontend client, with a `HandlerMutable` to set the grpc handler later
|
||||
pub fn from_empty_grpc_handler(query: QueryOptions) -> (Self, HandlerMutable) {
|
||||
let is_initialized = Arc::new(SetOnce::new());
|
||||
@@ -140,8 +116,6 @@ impl FrontendClient {
|
||||
Self::Standalone {
|
||||
database_client: handler.clone(),
|
||||
query,
|
||||
#[cfg(feature = "enterprise")]
|
||||
tracked_writes: false,
|
||||
},
|
||||
handler,
|
||||
)
|
||||
@@ -178,8 +152,6 @@ impl FrontendClient {
|
||||
control_channel_manager,
|
||||
query,
|
||||
batch_opts,
|
||||
#[cfg(feature = "enterprise")]
|
||||
tracked_writes: false,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -196,8 +168,6 @@ impl FrontendClient {
|
||||
Self::Standalone {
|
||||
database_client: handler,
|
||||
query,
|
||||
#[cfg(feature = "enterprise")]
|
||||
tracked_writes: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -235,39 +205,7 @@ impl DatabaseWithPeer {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
pub(crate) mod flow_write;
|
||||
|
||||
impl FrontendClient {
|
||||
/// Preflight tracked-write support by opening and closing a capability without writing.
|
||||
#[cfg(feature = "enterprise")]
|
||||
pub async fn check_tracked_writes(&self, catalog: &str, schema: &str) -> Result<(), Error> {
|
||||
if !self.tracked_writes_enabled() {
|
||||
return UnexpectedSnafu {
|
||||
reason: "Tracked writes are not enabled on this frontend client",
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
flow_write::check_tracked_writes(self, catalog, schema).await
|
||||
}
|
||||
|
||||
/// Execute a finite SQL write with receiver-issued completion tracking.
|
||||
#[cfg(feature = "enterprise")]
|
||||
pub async fn tracked_sql_write(
|
||||
&self,
|
||||
catalog: &str,
|
||||
schema: &str,
|
||||
sql: &str,
|
||||
) -> Result<OutputWithMetrics, Error> {
|
||||
if !self.tracked_writes_enabled() {
|
||||
return UnexpectedSnafu {
|
||||
reason: "Tracked writes are not enabled on this frontend client",
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
flow_write::tracked_sql_write(self, catalog, schema, sql).await
|
||||
}
|
||||
|
||||
/// scan for available frontend from metadata
|
||||
pub(crate) async fn scan_for_frontend(&self) -> Result<Vec<Peer>, Error> {
|
||||
let Self::Distributed { meta_client, .. } = self else {
|
||||
@@ -558,33 +496,6 @@ impl FrontendClient {
|
||||
peer_desc: &mut Option<PeerDesc>,
|
||||
) -> Result<OutputWithMetrics, Error> {
|
||||
let flow_extensions = build_flow_extensions(extensions)?;
|
||||
#[cfg(feature = "enterprise")]
|
||||
if self.tracked_writes_enabled() && is_tracked_insert_request(&request) {
|
||||
let effective_extensions: HashMap<String, String> = extensions
|
||||
.iter()
|
||||
.map(|(key, value)| ((*key).to_string(), (*value).to_string()))
|
||||
.collect();
|
||||
if effective_extensions.contains_key(common_grpc::flow_write::COMMAND_KEY) {
|
||||
return UnexpectedSnafu {
|
||||
reason: "Client-supplied tracked Flow command is forbidden",
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
let effective_extension_refs: Vec<(&str, &str)> = effective_extensions
|
||||
.iter()
|
||||
.map(|(key, value)| (key.as_str(), value.as_str()))
|
||||
.collect();
|
||||
return flow_write::tracked_query(
|
||||
self,
|
||||
catalog,
|
||||
schema,
|
||||
Some(request),
|
||||
&effective_extension_refs,
|
||||
snapshot_seqs,
|
||||
peer_desc,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
match self {
|
||||
FrontendClient::Distributed {
|
||||
query, batch_opts, ..
|
||||
@@ -835,15 +746,6 @@ impl FrontendClient {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
fn is_tracked_insert_request(request: &QueryRequest) -> bool {
|
||||
match request.query.as_ref() {
|
||||
Some(Query::InsertIntoPlan(_)) => true,
|
||||
Some(Query::Sql(sql)) => sql.trim_start().to_ascii_uppercase().starts_with("INSERT "),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn build_flow_extensions(extensions: &[(&str, &str)]) -> Result<FlowQueryExtensions, Error> {
|
||||
let flow_extensions = HashMap::from_iter(
|
||||
extensions
|
||||
|
||||
@@ -1,758 +0,0 @@
|
||||
// Copyright 2023-2026 GrepTime Inc.
|
||||
//
|
||||
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
|
||||
// the GreptimeDB Enterprise License. You may not use this file except in
|
||||
// compliance with that license. A copy of the license is available at the root
|
||||
// of this repository in the file LICENSE-ENTERPRISE.
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, this software is
|
||||
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
// either express or implied.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use api::v1::query_request::Query;
|
||||
use api::v1::{QueryRequest, greptime_request::Request};
|
||||
use client::OutputWithMetrics;
|
||||
use common_error::ext::{BoxedError, ErrorExt};
|
||||
use common_error::status_code::StatusCode;
|
||||
use common_grpc::flow_write::{self, COMMAND_KEY, Command, Reply, TerminalError};
|
||||
use common_query::{Output, OutputData, OutputMeta};
|
||||
use common_telemetry::warn;
|
||||
use session::context::{Channel, QueryContextBuilder, generate_remote_query_id};
|
||||
use snafu::OptionExt;
|
||||
use tokio::time::sleep;
|
||||
|
||||
use crate::Error;
|
||||
use crate::batching_mode::frontend_client::{DatabaseWithPeer, FrontendClient, PeerDesc};
|
||||
use crate::error::UnexpectedSnafu;
|
||||
|
||||
const RETRY_PACE: Duration = Duration::from_secs(1);
|
||||
|
||||
pub(crate) async fn tracked_sql_write(
|
||||
frontend: &FrontendClient,
|
||||
catalog: &str,
|
||||
schema: &str,
|
||||
sql: &str,
|
||||
) -> Result<OutputWithMetrics, Error> {
|
||||
tracked_query(
|
||||
frontend,
|
||||
catalog,
|
||||
schema,
|
||||
Some(QueryRequest {
|
||||
query: Some(Query::Sql(sql.to_string())),
|
||||
}),
|
||||
&[],
|
||||
&HashMap::new(),
|
||||
&mut None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn check_tracked_writes(
|
||||
frontend: &FrontendClient,
|
||||
catalog: &str,
|
||||
schema: &str,
|
||||
) -> Result<(), Error> {
|
||||
tracked_query(
|
||||
frontend,
|
||||
catalog,
|
||||
schema,
|
||||
None,
|
||||
&[],
|
||||
&HashMap::new(),
|
||||
&mut None,
|
||||
)
|
||||
.await
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
pub(crate) async fn tracked_query(
|
||||
frontend: &FrontendClient,
|
||||
catalog: &str,
|
||||
schema: &str,
|
||||
request: Option<QueryRequest>,
|
||||
extensions: &[(&str, &str)],
|
||||
snapshot_seqs: &HashMap<u64, u64>,
|
||||
peer_desc: &mut Option<PeerDesc>,
|
||||
) -> Result<OutputWithMetrics, Error> {
|
||||
let (selected, handler, parallelism, read_preference, timeout) = match frontend {
|
||||
FrontendClient::Distributed {
|
||||
query, batch_opts, ..
|
||||
} => (
|
||||
Some(
|
||||
frontend
|
||||
.get_random_active_frontend(catalog, schema)
|
||||
.await
|
||||
.map_err(prewrite_error)?,
|
||||
),
|
||||
None,
|
||||
query.parallelism.to_string(),
|
||||
Some(batch_opts.read_preference.as_ref().to_string()),
|
||||
batch_opts.experimental_flight_do_get_timeout,
|
||||
),
|
||||
FrontendClient::Standalone {
|
||||
database_client,
|
||||
query,
|
||||
..
|
||||
} => {
|
||||
let handler = database_client
|
||||
.handler
|
||||
.lock()
|
||||
.map_err(|e| {
|
||||
prewrite_reason(
|
||||
format!("Failed to lock database client: {e}"),
|
||||
StatusCode::Internal,
|
||||
)
|
||||
})?
|
||||
.as_ref()
|
||||
.context(UnexpectedSnafu {
|
||||
reason: "Standalone's frontend instance is not set",
|
||||
})
|
||||
.map_err(prewrite_error)?
|
||||
.upgrade()
|
||||
.context(UnexpectedSnafu {
|
||||
reason: "Failed to upgrade database client",
|
||||
})
|
||||
.map_err(prewrite_error)?;
|
||||
(
|
||||
None,
|
||||
Some(handler),
|
||||
query.parallelism.to_string(),
|
||||
None,
|
||||
RETRY_PACE,
|
||||
)
|
||||
}
|
||||
};
|
||||
*peer_desc = Some(match &selected {
|
||||
Some(DatabaseWithPeer { peer, .. }) => PeerDesc::Dist { peer: peer.clone() },
|
||||
None => PeerDesc::Standalone,
|
||||
});
|
||||
|
||||
let nonce = generate_remote_query_id();
|
||||
let mut command = Command::Open { nonce };
|
||||
let mut completion: Option<(
|
||||
usize,
|
||||
usize,
|
||||
Option<common_recordbatch::adapter::RecordBatchMetrics>,
|
||||
Option<TerminalError>,
|
||||
)> = None;
|
||||
|
||||
loop {
|
||||
let encoded = command.encode().map_err(|error| {
|
||||
UnexpectedSnafu {
|
||||
reason: format!("Failed to encode tracked Flow command: {error}"),
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
let mut operation_extensions: Vec<(String, String)> = extensions
|
||||
.iter()
|
||||
.filter(|(key, _)| *key != COMMAND_KEY)
|
||||
.map(|(key, value)| ((*key).to_string(), (*value).to_string()))
|
||||
.collect();
|
||||
operation_extensions.push((COMMAND_KEY.to_string(), encoded));
|
||||
let extension_refs: Vec<(&str, &str)> = operation_extensions
|
||||
.iter()
|
||||
.map(|(k, v)| (k.as_str(), v.as_str()))
|
||||
.collect();
|
||||
let phase_request = match &command {
|
||||
Command::Write { .. } => request
|
||||
.as_ref()
|
||||
.context(UnexpectedSnafu {
|
||||
reason: "Tracked Flow write command has no request",
|
||||
})?
|
||||
.clone(),
|
||||
Command::Open { .. } | Command::Close { .. } => QueryRequest {
|
||||
query: Some(Query::Sql(String::new())),
|
||||
},
|
||||
};
|
||||
let response = if let Some(DatabaseWithPeer { database, .. }) = &selected {
|
||||
let mut hints = vec![(
|
||||
query::datafusion::QUERY_PARALLELISM_HINT,
|
||||
parallelism.as_str(),
|
||||
)];
|
||||
if let Some(preference) = read_preference.as_deref() {
|
||||
hints.push((session::hints::READ_PREFERENCE_HINT, preference));
|
||||
}
|
||||
database
|
||||
.flight_request()
|
||||
.with_hints(&hints)
|
||||
.with_flow_extensions(&extension_refs)
|
||||
.with_snapshot_seqs(snapshot_seqs)
|
||||
.with_timeout(timeout)
|
||||
.query_with_terminal_metrics(phase_request)
|
||||
.await
|
||||
.map(|output| output.output)
|
||||
.map_err(|e| (e.status_code(), e.to_string()))
|
||||
} else {
|
||||
let mut ctx_extensions: HashMap<String, String> =
|
||||
operation_extensions.into_iter().collect();
|
||||
ctx_extensions.insert(
|
||||
query::datafusion::QUERY_PARALLELISM_HINT.to_string(),
|
||||
parallelism.clone(),
|
||||
);
|
||||
let ctx = QueryContextBuilder::default()
|
||||
.current_catalog(catalog.to_string())
|
||||
.current_schema(schema.to_string())
|
||||
.channel(Channel::Internal)
|
||||
.extensions(ctx_extensions)
|
||||
.snapshot_seqs(Arc::new(std::sync::RwLock::new(snapshot_seqs.clone())))
|
||||
.build();
|
||||
let handler = handler.as_ref().ok_or_else(|| {
|
||||
UnexpectedSnafu {
|
||||
reason: "Standalone handler was not pinned",
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
handler
|
||||
.do_query(Request::Query(phase_request), Arc::new(ctx))
|
||||
.await
|
||||
.map_err(|e| (e.status_code(), e.to_string()))
|
||||
};
|
||||
let reply = match response {
|
||||
Ok(output) => match decode_output(output).await {
|
||||
Ok(reply) => Some(reply),
|
||||
Err(e) if matches!(&command, Command::Open { .. }) => {
|
||||
return Err(prewrite_reason(
|
||||
format!("Frontend does not support tracked Flow writes: {e}"),
|
||||
StatusCode::Unsupported,
|
||||
));
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("Malformed tracked Flow {:?} reply: {}", command, e);
|
||||
None
|
||||
}
|
||||
},
|
||||
Err((code, msg)) => {
|
||||
// Only Open is pre-admission; definitive rejection there is safe to surface.
|
||||
if matches!(&command, Command::Open { .. }) && is_definitive_rejection(code) {
|
||||
return Err(prewrite_reason(
|
||||
format!("Frontend rejected tracked Flow open: {msg}"),
|
||||
code,
|
||||
));
|
||||
}
|
||||
warn!(
|
||||
"Tracked Flow {:?} transport failure (code={:?}): {}",
|
||||
command, code, msg
|
||||
);
|
||||
None
|
||||
}
|
||||
};
|
||||
match (command.clone(), reply) {
|
||||
(Command::Open { .. }, Some(Reply::Opened { capability: cap })) if !cap.is_empty() => {
|
||||
command = if request.is_some() {
|
||||
Command::Write { capability: cap }
|
||||
} else {
|
||||
Command::Close { capability: cap }
|
||||
};
|
||||
continue;
|
||||
}
|
||||
(Command::Open { .. }, Some(other)) => {
|
||||
return Err(prewrite_reason(
|
||||
format!("Invalid tracked Flow open reply: {other:?}"),
|
||||
StatusCode::InvalidArguments,
|
||||
));
|
||||
}
|
||||
(
|
||||
Command::Write { capability },
|
||||
Some(Reply::Complete {
|
||||
rows,
|
||||
cost,
|
||||
metrics,
|
||||
error,
|
||||
}),
|
||||
) => {
|
||||
completion = Some((rows, cost, metrics, error));
|
||||
command = Command::Close { capability };
|
||||
continue;
|
||||
}
|
||||
(Command::Write { .. }, Some(other)) => {
|
||||
warn!("Unexpected tracked Flow write reply: {other:?}")
|
||||
}
|
||||
(Command::Close { .. }, Some(Reply::Closed)) => {
|
||||
let Some((rows, cost, metrics, error)) = completion.take() else {
|
||||
if request.is_none() {
|
||||
return Ok(OutputWithMetrics::from_output(Output::new(
|
||||
OutputData::AffectedRows(0),
|
||||
OutputMeta::default(),
|
||||
)));
|
||||
}
|
||||
return UnexpectedSnafu {
|
||||
reason: "Close completed without positive write result",
|
||||
}
|
||||
.fail();
|
||||
};
|
||||
if let Some(error) = error {
|
||||
return Err(Error::External {
|
||||
source: BoxedError::new(error),
|
||||
location: snafu::Location::new(file!(), line!(), column!()),
|
||||
});
|
||||
}
|
||||
let output = OutputWithMetrics::from_output(Output::new(
|
||||
OutputData::AffectedRows(rows),
|
||||
OutputMeta {
|
||||
cost,
|
||||
..Default::default()
|
||||
},
|
||||
));
|
||||
output.metrics.update(metrics);
|
||||
return Ok(output);
|
||||
}
|
||||
(Command::Close { .. }, Some(other)) => {
|
||||
warn!("Unexpected tracked Flow close reply: {other:?}")
|
||||
}
|
||||
(_, None) => {}
|
||||
}
|
||||
sleep(RETRY_PACE).await;
|
||||
}
|
||||
}
|
||||
|
||||
fn prewrite_error(error: Error) -> Error {
|
||||
let status = error.status_code();
|
||||
prewrite_reason(error.to_string(), status)
|
||||
}
|
||||
|
||||
/// Returns true when a tracked Flow command error is a definitive, non-retryable
|
||||
/// rejection from the frontend rather than an ambiguous transport failure. These
|
||||
/// codes indicate the frontend itself refused the command (unsupported protocol,
|
||||
/// malformed/empty command, or wrong channel), so retrying the same pinned
|
||||
/// frontend can never succeed; the caller must fail fast instead of looping.
|
||||
fn is_definitive_rejection(code: StatusCode) -> bool {
|
||||
matches!(
|
||||
code,
|
||||
StatusCode::Unsupported | StatusCode::InvalidArguments | StatusCode::PermissionDenied
|
||||
)
|
||||
}
|
||||
|
||||
fn prewrite_reason(message: String, status: StatusCode) -> Error {
|
||||
Error::External {
|
||||
source: BoxedError::new(TerminalError {
|
||||
code: status as u32,
|
||||
message,
|
||||
}),
|
||||
location: snafu::Location::new(file!(), line!(), column!()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn decode_output(output: Output) -> Result<Reply, String> {
|
||||
let batches = match output.data {
|
||||
OutputData::RecordBatches(batches) => batches,
|
||||
OutputData::Stream(stream) => common_recordbatch::util::collect_batches(stream)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?,
|
||||
_ => return Err("tracked control request returned a non-record-batch result".to_string()),
|
||||
};
|
||||
flow_write::decode_reply(&batches).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use common_error::ext::{BoxedError, PlainError};
|
||||
use common_error::status_code::StatusCode;
|
||||
use session::context::QueryContextRef;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct LostReplyHandler {
|
||||
opens: AtomicUsize,
|
||||
writes: AtomicUsize,
|
||||
closes: AtomicUsize,
|
||||
executions: AtomicUsize,
|
||||
registry: common_grpc::flow_write::FlowWriteRegistry<String, Reply>,
|
||||
capabilities: std::sync::Mutex<HashMap<String, String>>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl super::super::GrpcQueryHandlerWithBoxedError for LostReplyHandler {
|
||||
async fn do_query(
|
||||
&self,
|
||||
request: Request,
|
||||
ctx: QueryContextRef,
|
||||
) -> Result<Output, BoxedError> {
|
||||
let encoded = ctx.extensions().get(COMMAND_KEY).cloned().ok_or_else(|| {
|
||||
BoxedError::new(PlainError::new(
|
||||
"missing command".into(),
|
||||
StatusCode::Unexpected,
|
||||
))
|
||||
})?;
|
||||
match Command::decode(&encoded).map_err(|error| {
|
||||
BoxedError::new(PlainError::new(
|
||||
error.to_string(),
|
||||
StatusCode::InvalidArguments,
|
||||
))
|
||||
})? {
|
||||
Command::Open { nonce } => {
|
||||
let call = self.opens.fetch_add(1, Ordering::SeqCst);
|
||||
let capability = self.registry.open(&nonce).unwrap();
|
||||
let previous = self
|
||||
.capabilities
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(nonce, capability.clone());
|
||||
if let Some(previous) = previous {
|
||||
assert_eq!(previous, capability);
|
||||
}
|
||||
if call == 0 {
|
||||
return Err(transport_error("lost Open reply"));
|
||||
}
|
||||
assert_empty_sql(&request);
|
||||
response(Reply::Opened { capability })
|
||||
}
|
||||
Command::Write { capability } => {
|
||||
let sql = request_sql(&request);
|
||||
let call = self.writes.fetch_add(1, Ordering::SeqCst);
|
||||
let admission = self.registry.admit(&capability, sql.clone()).unwrap();
|
||||
let result = match admission {
|
||||
common_grpc::flow_write::Admission::Start(sender) => {
|
||||
self.executions.fetch_add(1, Ordering::SeqCst);
|
||||
let reply = Reply::Complete {
|
||||
rows: 1,
|
||||
cost: 9,
|
||||
metrics: Some(common_recordbatch::adapter::RecordBatchMetrics {
|
||||
region_watermarks: vec![
|
||||
common_recordbatch::adapter::RegionWatermarkEntry {
|
||||
region_id: 41,
|
||||
watermark: Some(17),
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
}),
|
||||
error: None,
|
||||
};
|
||||
sender.send(Some(Arc::new(reply.clone()))).unwrap();
|
||||
reply
|
||||
}
|
||||
common_grpc::flow_write::Admission::Join(receiver) => {
|
||||
common_grpc::flow_write::wait_completion(receiver)
|
||||
.await
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
.clone()
|
||||
}
|
||||
};
|
||||
if call == 0 {
|
||||
return Err(transport_error("lost Write reply"));
|
||||
}
|
||||
response(result)
|
||||
}
|
||||
Command::Close { capability } => {
|
||||
let call = self.closes.fetch_add(1, Ordering::SeqCst);
|
||||
self.registry.close(&capability).await.unwrap();
|
||||
if call == 0 {
|
||||
return Err(transport_error("lost Close reply"));
|
||||
}
|
||||
response(Reply::Closed)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn request_sql(request: &Request) -> String {
|
||||
match request {
|
||||
Request::Query(query) => match query.query.as_ref() {
|
||||
Some(Query::Sql(sql)) => sql.clone(),
|
||||
other => panic!("expected SQL INSERT, got {other:?}"),
|
||||
},
|
||||
other => panic!("expected Query request, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_empty_sql(request: &Request) {
|
||||
assert!(
|
||||
matches!(request, Request::Query(QueryRequest { query: Some(Query::Sql(sql)) }) if sql.is_empty())
|
||||
);
|
||||
}
|
||||
|
||||
fn transport_error(message: &str) -> BoxedError {
|
||||
BoxedError::new(PlainError::new(
|
||||
message.to_string(),
|
||||
StatusCode::StorageUnavailable,
|
||||
))
|
||||
}
|
||||
|
||||
fn response(reply: Reply) -> Result<Output, BoxedError> {
|
||||
let batches = flow_write::reply_batches(&reply).map_err(BoxedError::new)?;
|
||||
Ok(Output::new_with_record_batches(batches))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn retries_same_open_write_and_close_capability_and_executes_once() {
|
||||
let handler = Arc::new(LostReplyHandler::default());
|
||||
let trait_handler: Arc<dyn super::super::GrpcQueryHandlerWithBoxedError> = handler.clone();
|
||||
let weak = Arc::downgrade(&trait_handler);
|
||||
let frontend =
|
||||
FrontendClient::from_grpc_handler(weak, query::options::QueryOptions::default())
|
||||
.with_tracked_writes();
|
||||
let output = frontend
|
||||
.tracked_sql_write("greptime", "public", "INSERT INTO t VALUES (7)")
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(matches!(output.output.data, OutputData::AffectedRows(1)));
|
||||
assert_eq!(output.output.meta.cost, 9);
|
||||
assert_eq!(
|
||||
output.metrics.region_watermark_map(),
|
||||
Some(HashMap::from([(41, 17)]))
|
||||
);
|
||||
assert_eq!(handler.opens.load(Ordering::SeqCst), 2);
|
||||
assert_eq!(handler.writes.load(Ordering::SeqCst), 2);
|
||||
assert_eq!(handler.closes.load(Ordering::SeqCst), 2);
|
||||
assert_eq!(handler.executions.load(Ordering::SeqCst), 1);
|
||||
let second = frontend
|
||||
.tracked_sql_write("greptime", "public", "INSERT INTO t VALUES (8)")
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(matches!(second.output.data, OutputData::AffectedRows(1)));
|
||||
assert_eq!(handler.executions.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
/// A legacy frontend that does not understand the tracked-write extension
|
||||
/// processes `Open` as an ordinary empty-SQL query and rejects it with
|
||||
/// `InvalidArguments`. That is a definitive application rejection, not an
|
||||
/// ambiguous transport failure: the client must fail fast instead of
|
||||
/// retrying the same pinned frontend forever.
|
||||
#[derive(Debug, Default)]
|
||||
struct LegacyRejectHandler {
|
||||
opens: AtomicUsize,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl super::super::GrpcQueryHandlerWithBoxedError for LegacyRejectHandler {
|
||||
async fn do_query(
|
||||
&self,
|
||||
_request: Request,
|
||||
_ctx: QueryContextRef,
|
||||
) -> Result<Output, BoxedError> {
|
||||
self.opens.fetch_add(1, Ordering::SeqCst);
|
||||
Err(BoxedError::new(PlainError::new(
|
||||
"empty statements".to_string(),
|
||||
StatusCode::InvalidArguments,
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PreflightHandler {
|
||||
opens: AtomicUsize,
|
||||
closes: AtomicUsize,
|
||||
reject_open: bool,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl super::super::GrpcQueryHandlerWithBoxedError for PreflightHandler {
|
||||
async fn do_query(
|
||||
&self,
|
||||
request: Request,
|
||||
ctx: QueryContextRef,
|
||||
) -> Result<Output, BoxedError> {
|
||||
let encoded = ctx.extensions().get(COMMAND_KEY).cloned().unwrap();
|
||||
assert_empty_sql(&request);
|
||||
match Command::decode(&encoded).unwrap() {
|
||||
Command::Open { .. } => {
|
||||
self.opens.fetch_add(1, Ordering::SeqCst);
|
||||
if self.reject_open {
|
||||
Err(BoxedError::new(PlainError::new(
|
||||
"preflight rejected".into(),
|
||||
StatusCode::PermissionDenied,
|
||||
)))
|
||||
} else {
|
||||
response(Reply::Opened {
|
||||
capability: "preflight-capability".into(),
|
||||
})
|
||||
}
|
||||
}
|
||||
Command::Close { capability } => {
|
||||
assert_eq!(capability, "preflight-capability");
|
||||
self.closes.fetch_add(1, Ordering::SeqCst);
|
||||
response(Reply::Closed)
|
||||
}
|
||||
Command::Write { .. } => panic!("preflight must not write"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preflight_opens_and_closes_without_writing() {
|
||||
let handler = Arc::new(PreflightHandler {
|
||||
opens: AtomicUsize::default(),
|
||||
closes: AtomicUsize::default(),
|
||||
reject_open: false,
|
||||
});
|
||||
let trait_handler: Arc<dyn super::super::GrpcQueryHandlerWithBoxedError> = handler.clone();
|
||||
let frontend = FrontendClient::from_grpc_handler(
|
||||
Arc::downgrade(&trait_handler),
|
||||
query::options::QueryOptions::default(),
|
||||
)
|
||||
.with_tracked_writes();
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(10),
|
||||
frontend.check_tracked_writes("greptime", "public"),
|
||||
)
|
||||
.await
|
||||
.expect("tracked-write preflight should finish within 10 seconds")
|
||||
.unwrap();
|
||||
assert_eq!(handler.opens.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(handler.closes.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preflight_preserves_definitive_open_error() {
|
||||
let handler = Arc::new(PreflightHandler {
|
||||
opens: AtomicUsize::default(),
|
||||
closes: AtomicUsize::default(),
|
||||
reject_open: true,
|
||||
});
|
||||
let trait_handler: Arc<dyn super::super::GrpcQueryHandlerWithBoxedError> = handler.clone();
|
||||
let frontend = FrontendClient::from_grpc_handler(
|
||||
Arc::downgrade(&trait_handler),
|
||||
query::options::QueryOptions::default(),
|
||||
)
|
||||
.with_tracked_writes();
|
||||
let error = tokio::time::timeout(
|
||||
Duration::from_secs(10),
|
||||
frontend.check_tracked_writes("greptime", "public"),
|
||||
)
|
||||
.await
|
||||
.expect("tracked-write preflight rejection should finish within 10 seconds")
|
||||
.unwrap_err();
|
||||
assert_eq!(error.status_code(), StatusCode::PermissionDenied);
|
||||
assert!(matches!(
|
||||
&error,
|
||||
Error::External { source, .. }
|
||||
if source.as_any().downcast_ref::<TerminalError>().is_some_and(|terminal| {
|
||||
terminal.code == StatusCode::PermissionDenied as u32
|
||||
&& terminal.message.contains("preflight rejected")
|
||||
})
|
||||
));
|
||||
assert_eq!(handler.opens.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(handler.closes.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct RejectionRetryHandler {
|
||||
status: StatusCode,
|
||||
opens: AtomicUsize,
|
||||
writes: AtomicUsize,
|
||||
closes: AtomicUsize,
|
||||
capability: std::sync::Mutex<Option<String>>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl super::super::GrpcQueryHandlerWithBoxedError for RejectionRetryHandler {
|
||||
async fn do_query(
|
||||
&self,
|
||||
request: Request,
|
||||
ctx: QueryContextRef,
|
||||
) -> Result<Output, BoxedError> {
|
||||
let encoded = ctx.extensions().get(COMMAND_KEY).cloned().unwrap();
|
||||
match Command::decode(&encoded).unwrap() {
|
||||
Command::Open { nonce } => {
|
||||
assert_empty_sql(&request);
|
||||
self.opens.fetch_add(1, Ordering::SeqCst);
|
||||
let mut capability = self.capability.lock().unwrap();
|
||||
let value = capability.get_or_insert_with(|| nonce);
|
||||
response(Reply::Opened {
|
||||
capability: value.clone(),
|
||||
})
|
||||
}
|
||||
Command::Write { capability } => {
|
||||
assert_eq!(request_sql(&request), "INSERT INTO t VALUES (11)");
|
||||
assert_eq!(self.capability.lock().unwrap().as_ref(), Some(&capability));
|
||||
if self.writes.fetch_add(1, Ordering::SeqCst) == 0 {
|
||||
Err(BoxedError::new(PlainError::new(
|
||||
"write rejection".into(),
|
||||
self.status,
|
||||
)))
|
||||
} else {
|
||||
response(Reply::Complete {
|
||||
rows: 2,
|
||||
cost: 0,
|
||||
metrics: None,
|
||||
error: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
Command::Close { capability } => {
|
||||
assert_empty_sql(&request);
|
||||
assert_eq!(self.capability.lock().unwrap().as_ref(), Some(&capability));
|
||||
if self.closes.fetch_add(1, Ordering::SeqCst) == 0 {
|
||||
Err(BoxedError::new(PlainError::new(
|
||||
"close rejection".into(),
|
||||
self.status,
|
||||
)))
|
||||
} else {
|
||||
response(Reply::Closed)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn post_admission_rejections_retry_same_capability_until_close() {
|
||||
for status in [
|
||||
StatusCode::Unsupported,
|
||||
StatusCode::InvalidArguments,
|
||||
StatusCode::PermissionDenied,
|
||||
] {
|
||||
let handler = Arc::new(RejectionRetryHandler {
|
||||
status,
|
||||
opens: AtomicUsize::default(),
|
||||
writes: AtomicUsize::default(),
|
||||
closes: AtomicUsize::default(),
|
||||
capability: std::sync::Mutex::new(None),
|
||||
});
|
||||
let trait_handler: Arc<dyn super::super::GrpcQueryHandlerWithBoxedError> =
|
||||
handler.clone();
|
||||
let frontend = FrontendClient::from_grpc_handler(
|
||||
Arc::downgrade(&trait_handler),
|
||||
query::options::QueryOptions::default(),
|
||||
)
|
||||
.with_tracked_writes();
|
||||
let output = tokio::time::timeout(
|
||||
Duration::from_secs(10),
|
||||
frontend.tracked_sql_write("greptime", "public", "INSERT INTO t VALUES (11)"),
|
||||
)
|
||||
.await
|
||||
.expect("post-admission retries should finish within 10 seconds")
|
||||
.unwrap();
|
||||
assert!(matches!(output.output.data, OutputData::AffectedRows(2)));
|
||||
assert_eq!(handler.opens.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(handler.writes.load(Ordering::SeqCst), 2);
|
||||
assert_eq!(handler.closes.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fails_fast_on_definitive_open_rejection() {
|
||||
let handler = Arc::new(LegacyRejectHandler::default());
|
||||
let trait_handler: Arc<dyn super::super::GrpcQueryHandlerWithBoxedError> = handler.clone();
|
||||
let weak = Arc::downgrade(&trait_handler);
|
||||
let frontend =
|
||||
FrontendClient::from_grpc_handler(weak, query::options::QueryOptions::default())
|
||||
.with_tracked_writes();
|
||||
let result = tokio::time::timeout(
|
||||
Duration::from_secs(10),
|
||||
frontend.tracked_sql_write("greptime", "public", "INSERT INTO t VALUES (7)"),
|
||||
)
|
||||
.await
|
||||
.expect("definitive Open rejection should finish within 10 seconds");
|
||||
let err = result.expect_err("definitive Open rejection must not be retried forever");
|
||||
assert_eq!(err.status_code(), StatusCode::InvalidArguments);
|
||||
// The durable-execution layer keys repair off a TerminalError inside
|
||||
// Error::External; pin that exact shape so a refactor cannot silently
|
||||
// downgrade the rejection to an unresolved (permanently stalled) error.
|
||||
assert!(
|
||||
matches!(&err, Error::External { source, .. } if source.as_any().is::<common_grpc::flow_write::TerminalError>()),
|
||||
"expected Error::External carrying TerminalError, got {err:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
handler.opens.load(Ordering::SeqCst),
|
||||
1,
|
||||
"Open must not be retried after a definitive rejection"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,6 @@ license.workspace = true
|
||||
[features]
|
||||
testing = []
|
||||
enterprise = [
|
||||
"common-grpc/enterprise",
|
||||
"session/enterprise",
|
||||
"common-meta/enterprise",
|
||||
"operator/enterprise",
|
||||
"sql/enterprise",
|
||||
|
||||
@@ -17,8 +17,6 @@ mod copy_in;
|
||||
mod dashboard;
|
||||
mod entity_graph;
|
||||
mod export_database;
|
||||
#[cfg(feature = "enterprise")]
|
||||
mod flow_write;
|
||||
mod grpc;
|
||||
mod import_packed;
|
||||
mod influxdb;
|
||||
@@ -136,13 +134,6 @@ pub struct Instance {
|
||||
trace_aux_limiter: Option<RequestLimiter>,
|
||||
otlp_resource_info: bool,
|
||||
suspend: Arc<AtomicBool>,
|
||||
#[cfg(feature = "enterprise")]
|
||||
flow_write_registry: Arc<
|
||||
common_grpc::flow_write::FlowWriteRegistry<
|
||||
flow_write::WritePayload,
|
||||
common_grpc::flow_write::Reply,
|
||||
>,
|
||||
>,
|
||||
}
|
||||
|
||||
impl Instance {
|
||||
@@ -332,17 +323,6 @@ impl Instance {
|
||||
timeout_recorder,
|
||||
);
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
let result = if query_ctx.channel() == Channel::Internal
|
||||
&& query_ctx.extension(common_grpc::flow_write::CHILD_KEY) == Some("1")
|
||||
{
|
||||
query_fut.await
|
||||
} else {
|
||||
CancellableFuture::new(query_fut, ticket.cancellation_handle.clone())
|
||||
.await
|
||||
.map_err(|_| error::CancelledSnafu.build())?
|
||||
};
|
||||
#[cfg(not(feature = "enterprise"))]
|
||||
let result = CancellableFuture::new(query_fut, ticket.cancellation_handle.clone())
|
||||
.await
|
||||
.map_err(|_| error::CancelledSnafu.build())?;
|
||||
@@ -913,17 +893,6 @@ impl Instance {
|
||||
|
||||
let query_fut = self.exec_plan_with_timeout(plan, query_ctx.clone(), timeout_recorder);
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
let result = if query_ctx.channel() == Channel::Internal
|
||||
&& query_ctx.extension(common_grpc::flow_write::CHILD_KEY) == Some("1")
|
||||
{
|
||||
query_fut.await
|
||||
} else {
|
||||
CancellableFuture::new(query_fut, ticket.cancellation_handle.clone())
|
||||
.await
|
||||
.map_err(|_| error::CancelledSnafu.build())?
|
||||
};
|
||||
#[cfg(not(feature = "enterprise"))]
|
||||
let result = CancellableFuture::new(query_fut, ticket.cancellation_handle.clone())
|
||||
.await
|
||||
.map_err(|_| error::CancelledSnafu.build())?;
|
||||
|
||||
@@ -438,8 +438,6 @@ impl FrontendBuilder {
|
||||
trace_aux_limiter,
|
||||
otlp_resource_info: self.options.otlp.experimental_enable_resource_info,
|
||||
suspend: Arc::new(AtomicBool::new(false)),
|
||||
#[cfg(feature = "enterprise")]
|
||||
flow_write_registry: Default::default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,227 +0,0 @@
|
||||
// Copyright 2023-2026 GrepTime Inc.
|
||||
//
|
||||
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
|
||||
// the GreptimeDB Enterprise License. You may not use this file except in
|
||||
// compliance with that license. A copy of the license is available at the root
|
||||
// of this repository in the file LICENSE-ENTERPRISE.
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, this software is
|
||||
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
// either express or implied.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use api::v1::{greptime_request::Request, query_request::Query};
|
||||
use common_error::ext::ErrorExt;
|
||||
use common_grpc::flow_write::{
|
||||
Admission, CHILD_KEY, COMMAND_KEY, Command, Reply, TerminalError, wait_completion,
|
||||
};
|
||||
use common_query::{Output, OutputData};
|
||||
use servers::error::{self as server_error, Error as ServerError};
|
||||
use servers::interceptor::GrpcQueryInterceptor;
|
||||
use servers::query_handler::grpc::GrpcQueryHandler;
|
||||
use session::context::QueryContextRef;
|
||||
|
||||
use crate::instance::Instance;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct WritePayload {
|
||||
request: Request,
|
||||
catalog: String,
|
||||
schema: String,
|
||||
snapshots: Vec<(u64, u64)>,
|
||||
sst_min_sequences: Vec<(u64, u64)>,
|
||||
extensions: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl WritePayload {
|
||||
fn new(request: &Request, ctx: &QueryContextRef) -> Result<Self, String> {
|
||||
if !is_finite_insert(request) {
|
||||
return Err("tracked flow writes require INSERT or InsertIntoPlan".to_string());
|
||||
}
|
||||
let mut snapshots: Vec<_> = ctx.snapshots().into_iter().collect();
|
||||
snapshots.sort_unstable();
|
||||
let mut sst_min_sequences: Vec<_> = ctx.sst_min_sequences().into_iter().collect();
|
||||
sst_min_sequences.sort_unstable();
|
||||
let mut extensions: Vec<_> = ctx
|
||||
.extensions()
|
||||
.into_iter()
|
||||
.filter(|(key, _)| {
|
||||
key != COMMAND_KEY
|
||||
&& key != CHILD_KEY
|
||||
&& key != session::context::REMOTE_QUERY_ID_EXTENSION_KEY
|
||||
})
|
||||
.collect();
|
||||
extensions.sort_unstable();
|
||||
Ok(Self {
|
||||
request: request.clone(),
|
||||
catalog: ctx.current_catalog().to_string(),
|
||||
schema: ctx.current_schema(),
|
||||
snapshots,
|
||||
sst_min_sequences,
|
||||
extensions,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn is_finite_insert(request: &Request) -> bool {
|
||||
match request {
|
||||
Request::Query(query) => match query.query.as_ref() {
|
||||
Some(Query::InsertIntoPlan(_)) => true,
|
||||
Some(Query::Sql(sql)) => sql.split_whitespace().next().is_some_and(|statement| {
|
||||
statement
|
||||
.trim_end_matches(';')
|
||||
.eq_ignore_ascii_case("INSERT")
|
||||
}),
|
||||
_ => false,
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
impl Instance {
|
||||
fn intercept_control(
|
||||
&self,
|
||||
request: &Request,
|
||||
ctx: &QueryContextRef,
|
||||
) -> server_error::Result<()> {
|
||||
let interceptor = self
|
||||
.plugins
|
||||
.get::<servers::interceptor::GrpcQueryInterceptorRef<crate::error::Error>>();
|
||||
interceptor
|
||||
.as_ref()
|
||||
.pre_execute(request, ctx.clone())
|
||||
.map_err(|error| ServerError::ExecuteQuery {
|
||||
source: common_error::ext::BoxedError::new(error),
|
||||
location: snafu::Location::new(file!(), line!(), column!()),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn handle_flow_write_request(
|
||||
&self,
|
||||
request: Request,
|
||||
ctx: QueryContextRef,
|
||||
encoded_command: String,
|
||||
) -> server_error::Result<Output> {
|
||||
let command = Command::decode(&encoded_command).map_err(|e| ServerError::InvalidQuery {
|
||||
reason: e.to_string(),
|
||||
location: snafu::Location::new(file!(), line!(), column!()),
|
||||
})?;
|
||||
let reply = match command {
|
||||
Command::Open { nonce } => {
|
||||
self.intercept_control(&request, &ctx)?;
|
||||
if !is_empty_control(&request) {
|
||||
return Err(ServerError::InvalidQuery {
|
||||
reason: "Open requires an empty SQL request".into(),
|
||||
location: snafu::Location::new(file!(), line!(), column!()),
|
||||
});
|
||||
}
|
||||
Reply::Opened {
|
||||
capability: self
|
||||
.flow_write_registry
|
||||
.open(&nonce)
|
||||
.map_err(registry_error)?,
|
||||
}
|
||||
}
|
||||
Command::Close { capability } => {
|
||||
self.intercept_control(&request, &ctx)?;
|
||||
if !is_empty_control(&request) {
|
||||
return Err(ServerError::InvalidQuery {
|
||||
reason: "Close requires an empty SQL request".into(),
|
||||
location: snafu::Location::new(file!(), line!(), column!()),
|
||||
});
|
||||
}
|
||||
self.flow_write_registry
|
||||
.close(&capability)
|
||||
.await
|
||||
.map_err(registry_error)?;
|
||||
Reply::Closed
|
||||
}
|
||||
Command::Write { capability } => {
|
||||
let payload = WritePayload::new(&request, &ctx).map_err(|reason| {
|
||||
ServerError::InvalidQuery {
|
||||
reason,
|
||||
location: snafu::Location::new(file!(), line!(), column!()),
|
||||
}
|
||||
})?;
|
||||
match self
|
||||
.flow_write_registry
|
||||
.admit(&capability, payload)
|
||||
.map_err(registry_error)?
|
||||
{
|
||||
Admission::Join(receiver) => {
|
||||
(*wait_completion(receiver).await.map_err(registry_error)?).clone()
|
||||
}
|
||||
Admission::Start(sender) => {
|
||||
let receiver = sender.subscribe();
|
||||
let instance = self.clone();
|
||||
let mut child_ctx = (*ctx).clone();
|
||||
child_ctx.remove_extension(COMMAND_KEY);
|
||||
child_ctx.set_extension(CHILD_KEY, "1");
|
||||
let child_ctx = Arc::new(child_ctx);
|
||||
common_runtime::spawn_global(async move {
|
||||
let terminal = match instance.do_query(request, child_ctx).await {
|
||||
Ok(output) => terminal_reply(output),
|
||||
Err(error) => Reply::Complete {
|
||||
rows: 0,
|
||||
cost: 0,
|
||||
metrics: None,
|
||||
error: Some(TerminalError {
|
||||
code: error.status_code() as u32,
|
||||
message: error.output_msg(),
|
||||
}),
|
||||
},
|
||||
};
|
||||
let _ = sender.send(Some(Arc::new(terminal)));
|
||||
});
|
||||
(*wait_completion(receiver).await.map_err(registry_error)?).clone()
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let batches = common_grpc::flow_write::reply_batches(&reply).map_err(|e| {
|
||||
ServerError::InvalidQuery {
|
||||
reason: e.to_string(),
|
||||
location: snafu::Location::new(file!(), line!(), column!()),
|
||||
}
|
||||
})?;
|
||||
Ok(Output::new_with_record_batches(batches))
|
||||
}
|
||||
}
|
||||
|
||||
fn is_empty_control(request: &Request) -> bool {
|
||||
matches!(request, Request::Query(query) if matches!(&query.query, Some(Query::Sql(sql)) if sql.trim().is_empty()))
|
||||
}
|
||||
|
||||
fn terminal_reply(output: Output) -> Reply {
|
||||
let (rows, cost) = output.extract_rows_and_cost();
|
||||
let metrics = output
|
||||
.meta
|
||||
.plan
|
||||
.clone()
|
||||
.and_then(query::metrics::terminal_recordbatch_metrics_from_plan);
|
||||
match output.data {
|
||||
OutputData::AffectedRows(_) => Reply::Complete {
|
||||
rows,
|
||||
cost,
|
||||
metrics,
|
||||
error: None,
|
||||
},
|
||||
_ => Reply::Complete {
|
||||
rows: 0,
|
||||
cost,
|
||||
metrics,
|
||||
error: Some(TerminalError {
|
||||
code: 1001,
|
||||
message: "tracked INSERT did not produce finite affected rows".into(),
|
||||
}),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn registry_error(error: common_grpc::flow_write::RegistryError) -> ServerError {
|
||||
ServerError::InvalidQuery {
|
||||
reason: format!("flow write capability rejected: {error:?}"),
|
||||
location: snafu::Location::new(file!(), line!(), column!()),
|
||||
}
|
||||
}
|
||||
@@ -66,20 +66,6 @@ impl GrpcQueryHandler for Instance {
|
||||
request: Request,
|
||||
ctx: QueryContextRef,
|
||||
) -> server_error::Result<Output> {
|
||||
#[cfg(feature = "enterprise")]
|
||||
if let Some(command) = ctx
|
||||
.extension(common_grpc::flow_write::COMMAND_KEY)
|
||||
.map(str::to_string)
|
||||
{
|
||||
if ctx.channel() != session::context::Channel::Internal {
|
||||
return Err(server_error::Error::InvalidQuery {
|
||||
reason: "flow write commands are only accepted on the internal channel".into(),
|
||||
location: snafu::Location::new(file!(), line!(), column!()),
|
||||
});
|
||||
}
|
||||
return self.handle_flow_write_request(request, ctx, command).await;
|
||||
}
|
||||
|
||||
let result: Result<Output> = async {
|
||||
let interceptor_ref = self.plugins.get::<GrpcQueryInterceptorRef<Error>>();
|
||||
let interceptor = interceptor_ref.as_ref();
|
||||
|
||||
@@ -429,6 +429,7 @@ where
|
||||
user_provider.clone(),
|
||||
Some(self.instance.process_manager().clone()),
|
||||
)
|
||||
.with_influxdb_handler(instance.clone())
|
||||
.with_batching_enabled(postgres_batching),
|
||||
) as Box<dyn Server>;
|
||||
|
||||
|
||||
@@ -630,13 +630,13 @@ impl Context {
|
||||
Ok(datanode_table_value)
|
||||
}
|
||||
|
||||
/// Notifies the RegionSupervisor to register failure detectors of failed region.
|
||||
/// Notifies the RegionSupervisor to register failure detectors of the given regions on the
|
||||
/// source peer.
|
||||
///
|
||||
/// The original failure detector was removed once the procedure was triggered.
|
||||
/// Now, we need to register the failure detector for the failed region again.
|
||||
pub async fn register_failure_detectors(&self) {
|
||||
pub async fn register_failure_detectors(&self, region_ids: &[RegionId]) {
|
||||
let datanode_id = self.persistent_ctx.from_peer.id;
|
||||
let region_ids = &self.persistent_ctx.region_ids;
|
||||
let detecting_regions = region_ids
|
||||
.iter()
|
||||
.map(|region_id| (datanode_id, *region_id))
|
||||
@@ -650,10 +650,10 @@ impl Context {
|
||||
);
|
||||
}
|
||||
|
||||
/// Notifies the RegionSupervisor to reset failure detectors of candidate regions.
|
||||
pub async fn reset_failure_detectors_for_candidate_regions(&self) {
|
||||
/// Notifies the RegionSupervisor to reset failure detectors of the given regions on the target
|
||||
/// peer.
|
||||
pub async fn reset_failure_detectors(&self, region_ids: &[RegionId]) {
|
||||
let datanode_id = self.persistent_ctx.to_peer.id;
|
||||
let region_ids = &self.persistent_ctx.region_ids;
|
||||
let detecting_regions = region_ids
|
||||
.iter()
|
||||
.map(|region_id| (datanode_id, *region_id))
|
||||
@@ -662,7 +662,7 @@ impl Context {
|
||||
.reset_failure_detectors(detecting_regions)
|
||||
.await;
|
||||
info!(
|
||||
"Reset failure detectors after migration success for datanode {}, regions {:?}",
|
||||
"Reset failure detectors of regions for datanode {}, regions {:?}",
|
||||
datanode_id, region_ids
|
||||
);
|
||||
}
|
||||
@@ -878,12 +878,29 @@ impl RegionMigrationProcedure {
|
||||
.with_label_values(&["rollback"])
|
||||
.start_timer();
|
||||
let ctx = &self.context;
|
||||
let to_peer_id = ctx.persistent_ctx.to_peer.id;
|
||||
let table_regions = ctx.persistent_ctx.table_regions();
|
||||
// Regions whose route was switched to the target before the procedure aborted.
|
||||
let mut switched_regions = Vec::new();
|
||||
for (table_id, regions) in table_regions {
|
||||
let table_lock = TableLock::Write(table_id).into();
|
||||
let _guard = procedure_ctx.provider.acquire_lock(&table_lock).await;
|
||||
let table_route = ctx.get_table_route_value(table_id).await?;
|
||||
let table_route = match ctx.get_table_route_value(table_id).await {
|
||||
Ok(table_route) => table_route,
|
||||
// The table has been dropped meanwhile.
|
||||
Err(error::Error::TableRouteNotFound { .. }) => continue,
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
let region_routes = table_route.region_routes().unwrap();
|
||||
switched_regions.extend(
|
||||
region_routes
|
||||
.iter()
|
||||
.filter(|route| regions.contains(&route.region.id))
|
||||
.filter(|route| {
|
||||
route.leader_peer.as_ref().map(|peer| peer.id) == Some(to_peer_id)
|
||||
})
|
||||
.map(|route| route.region.id),
|
||||
);
|
||||
let downgraded = region_routes
|
||||
.iter()
|
||||
.filter(|route| regions.contains(&route.region.id))
|
||||
@@ -912,7 +929,24 @@ impl RegionMigrationProcedure {
|
||||
self.context
|
||||
.deregister_failure_detectors_for_candidate_regions()
|
||||
.await;
|
||||
self.context.register_failure_detectors().await;
|
||||
// The switched regions are served by the target, so they are monitored there instead.
|
||||
let unswitched_regions = ctx
|
||||
.persistent_ctx
|
||||
.region_ids
|
||||
.iter()
|
||||
.filter(|region_id| !switched_regions.contains(region_id))
|
||||
.copied()
|
||||
.collect::<Vec<_>>();
|
||||
self.context
|
||||
.register_failure_detectors(&unswitched_regions)
|
||||
.await;
|
||||
// The target's next heartbeat would register these detectors again, but nothing would if
|
||||
// the target stopped before sending one.
|
||||
if !switched_regions.is_empty() {
|
||||
self.context
|
||||
.reset_failure_detectors(&switched_regions)
|
||||
.await;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1014,8 +1048,8 @@ mod tests {
|
||||
|
||||
use common_meta::distributed_time_constants::default_distributed_time_constants;
|
||||
use common_meta::instruction::Instruction;
|
||||
use common_meta::key::test_utils::new_test_table_info;
|
||||
use common_meta::rpc::router::{Region, RegionRoute};
|
||||
use common_meta::key::test_utils::{new_test_table_info, new_test_table_info_with_name};
|
||||
use common_meta::rpc::router::{LeaderState, Region, RegionRoute};
|
||||
|
||||
use super::*;
|
||||
use crate::handler::HeartbeatMailbox;
|
||||
@@ -1025,12 +1059,66 @@ mod tests {
|
||||
new_downgrade_region_reply, new_flush_region_reply_for_region, new_open_region_reply,
|
||||
new_upgrade_region_reply,
|
||||
};
|
||||
use crate::region::supervisor::{Event, RegionFailureDetectorControl};
|
||||
use crate::service::mailbox::Channel;
|
||||
|
||||
fn new_persistent_context() -> PersistentContext {
|
||||
test_util::new_persistent_context(1, 2, RegionId::new(1024, 1))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_rollback_registers_detectors_for_switched_regions() {
|
||||
let env = TestingEnv::new();
|
||||
// The route switch aborted after the table of `switched` was switched to the target and
|
||||
// before the table of `unswitched`, whose leader is still downgrading; the table of
|
||||
// `dropped` has been dropped.
|
||||
let switched = RegionId::new(1024, 1);
|
||||
let unswitched = RegionId::new(1025, 1);
|
||||
let dropped = RegionId::new(1026, 1);
|
||||
for (region_id, leader) in [(switched, 2), (unswitched, 1)] {
|
||||
let table_id = region_id.table_id();
|
||||
let table_info = new_test_table_info_with_name(table_id, &format!("table_{table_id}"));
|
||||
let region_routes = vec![RegionRoute {
|
||||
region: Region::new_test(region_id),
|
||||
leader_peer: Some(Peer::empty(leader)),
|
||||
leader_state: (region_id == unswitched).then_some(LeaderState::Downgrading),
|
||||
..Default::default()
|
||||
}];
|
||||
env.create_physical_table_metadata(table_info, region_routes)
|
||||
.await;
|
||||
}
|
||||
let mut persistent_ctx = new_persistent_context();
|
||||
persistent_ctx.region_ids = vec![switched, unswitched, dropped];
|
||||
let (tx, mut rx) = tokio::sync::mpsc::channel(8);
|
||||
let mut context_factory = env.context_factory();
|
||||
context_factory.region_failure_detector_controller =
|
||||
Arc::new(RegionFailureDetectorControl::new(tx));
|
||||
let mut procedure = RegionMigrationProcedure::new(persistent_ctx, context_factory, vec![]);
|
||||
|
||||
procedure
|
||||
.rollback_inner(&new_procedure_context())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// The target's detectors are replaced by the source's, except for `switched`, which stays
|
||||
// monitored on the target.
|
||||
let target = [switched, unswitched, dropped].map(|region_id| (2, region_id));
|
||||
let source = [unswitched, dropped].map(|region_id| (1, region_id));
|
||||
assert_matches!(rx.try_recv(), Ok(Event::DeregisterFailureDetectors(r)) if r == target);
|
||||
assert_matches!(rx.try_recv(), Ok(Event::RegisterFailureDetectors(r)) if r == source);
|
||||
assert_matches!(rx.try_recv(), Ok(Event::ResetFailureDetectors(r)) if r == [(2, switched)]);
|
||||
assert!(rx.try_recv().is_err());
|
||||
let table_route = env
|
||||
.table_metadata_manager()
|
||||
.table_route_manager()
|
||||
.table_route_storage()
|
||||
.get(unswitched.table_id())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(table_route.region_routes().unwrap()[0].leader_state, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lock_key() {
|
||||
let persistent_context = new_persistent_context();
|
||||
|
||||
+2
-1
@@ -64,7 +64,8 @@ impl UpdateMetadata {
|
||||
"Rolling back downgraded leader region table route success, table_id: {table_id}, regions: {regions:?}"
|
||||
);
|
||||
}
|
||||
ctx.register_failure_detectors().await;
|
||||
ctx.register_failure_detectors(&ctx.persistent_ctx.region_ids)
|
||||
.await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+2
-1
@@ -215,7 +215,8 @@ impl UpdateMetadata {
|
||||
}
|
||||
|
||||
ctx.deregister_failure_detectors().await;
|
||||
ctx.reset_failure_detectors_for_candidate_regions().await;
|
||||
ctx.reset_failure_detectors(&ctx.persistent_ctx.region_ids)
|
||||
.await;
|
||||
// Consumes the guard.
|
||||
ctx.volatile_ctx.opening_region_guards.clear();
|
||||
|
||||
|
||||
@@ -388,23 +388,27 @@ impl RegionEngine for MetricEngine {
|
||||
&self,
|
||||
region_id: RegionId,
|
||||
role: RegionRole,
|
||||
sent_at: Instant,
|
||||
deadline: Instant,
|
||||
) -> Result<(), BoxedError> {
|
||||
// ignore the region not found error
|
||||
) -> Result<bool, BoxedError> {
|
||||
// The metadata region goes first. If it ignores the grant, the data region, whose role the
|
||||
// engine reports, must not take it either. A region that is not found is ignored.
|
||||
for x in [
|
||||
utils::to_metadata_region_id(region_id),
|
||||
utils::to_data_region_id(region_id),
|
||||
] {
|
||||
if let Err(e) = self
|
||||
match self
|
||||
.inner
|
||||
.mito
|
||||
.set_region_role_with_lease(x, role, deadline)
|
||||
&& e.status_code() != StatusCode::RegionNotFound
|
||||
.set_region_role_with_lease(x, role, sent_at, deadline)
|
||||
{
|
||||
return Err(e);
|
||||
Ok(true) => {}
|
||||
Ok(false) => return Ok(false),
|
||||
Err(e) if e.status_code() != StatusCode::RegionNotFound => return Err(e),
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
async fn sync_region(
|
||||
@@ -887,6 +891,42 @@ mod test {
|
||||
assert!(!object_store.exists(&data_region_dir).await.unwrap());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_leader_grant_ignored_by_metadata_region_leaves_data_region() {
|
||||
let env = TestEnv::new().await;
|
||||
env.init_metric_region().await;
|
||||
let (engine, mito) = (env.metric(), env.mito());
|
||||
let physical_region_id = env.default_physical_region_id();
|
||||
let lease = std::time::Duration::from_secs(10);
|
||||
// The data region is downgraded before the heartbeat is sent, the metadata region after it.
|
||||
let downgrade = |region_id| {
|
||||
mito.set_region_role_state_gracefully(region_id, SettableRegionRoleState::Follower)
|
||||
};
|
||||
downgrade(utils::to_data_region_id(physical_region_id))
|
||||
.await
|
||||
.unwrap();
|
||||
let sent_at = Instant::now();
|
||||
downgrade(utils::to_metadata_region_id(physical_region_id))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let grant = |sent_at: Instant| {
|
||||
engine
|
||||
.set_region_role_with_lease(
|
||||
physical_region_id,
|
||||
RegionRole::Leader,
|
||||
sent_at,
|
||||
sent_at + lease,
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
assert!(!grant(sent_at));
|
||||
assert_eq!(engine.role(physical_region_id), Some(RegionRole::Follower));
|
||||
|
||||
assert!(grant(Instant::now()));
|
||||
assert_eq!(engine.role(physical_region_id), Some(RegionRole::Leader));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_role() {
|
||||
let env = TestEnv::new().await;
|
||||
|
||||
@@ -2379,7 +2379,7 @@ mod tests {
|
||||
let at = |n| start + n * Duration::from_secs(10);
|
||||
let grant = |n| {
|
||||
engine
|
||||
.set_region_role_with_lease(physical_region_id, RegionRole::Leader, at(n))
|
||||
.set_region_role_with_lease(physical_region_id, RegionRole::Leader, start, at(n))
|
||||
.unwrap()
|
||||
};
|
||||
let expire = |n| mito.freeze_lease_clock(at(n));
|
||||
|
||||
@@ -1605,15 +1605,21 @@ impl RegionEngine for MitoEngine {
|
||||
&self,
|
||||
region_id: RegionId,
|
||||
role: RegionRole,
|
||||
sent_at: Instant,
|
||||
deadline: Instant,
|
||||
) -> Result<(), BoxedError> {
|
||||
) -> Result<bool, BoxedError> {
|
||||
let region = self.inner.find_region(region_id).map_err(BoxedError::new)?;
|
||||
// Before the role, and even if the role leaves the region's state unchanged.
|
||||
if role.writable() {
|
||||
region.leader_deadline.extend(deadline);
|
||||
region.manifest_ctx.leader_deadline.extend(deadline);
|
||||
}
|
||||
if role == RegionRole::Leader {
|
||||
return Ok(region
|
||||
.manifest_ctx
|
||||
.promote_unless_downgrade_started_after(sent_at, region_id));
|
||||
}
|
||||
region.set_role(role);
|
||||
Ok(())
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
async fn set_region_role_state_gracefully(
|
||||
|
||||
@@ -13,8 +13,10 @@
|
||||
// limitations under the License.
|
||||
|
||||
//! Tests that a region acknowledges only writes whose WAL append completed within its leader
|
||||
//! lease.
|
||||
//! lease, and that Leader grants for heartbeats sent before a downgrade do not make it writable
|
||||
//! again.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -24,8 +26,11 @@ use common_error::ext::{BoxedError, ErrorExt};
|
||||
use common_recordbatch::RecordBatches;
|
||||
use rstest::rstest;
|
||||
use rstest_reuse::apply;
|
||||
use store_api::region_engine::{RegionEngine, RegionRole};
|
||||
use store_api::region_request::{RegionCatchupRequest, RegionPutRequest, RegionRequest};
|
||||
use store_api::region_engine::{RegionEngine, RegionRole, SettableRegionRoleState};
|
||||
use store_api::region_request::{
|
||||
EnterStagingRequest, RegionCatchupRequest, RegionPutRequest, RegionRequest,
|
||||
StagingPartitionDirective,
|
||||
};
|
||||
use store_api::storage::{RegionId, ScanRequest};
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
@@ -34,10 +39,11 @@ use crate::engine::MitoEngine;
|
||||
use crate::engine::basic_test::build_bulk_insert_request;
|
||||
use crate::engine::listener::WriteWalListener;
|
||||
use crate::error::Error;
|
||||
use crate::region::{RegionLeaderState, RegionRoleState};
|
||||
use crate::test_util::{
|
||||
CreateRequestBuilder, LogStoreFactory, TestEnv, build_rows, kafka_log_store_factory,
|
||||
multiple_log_store_factories, prepare_test_for_kafka_log_store, raft_engine_log_store_factory,
|
||||
rows_schema,
|
||||
reopen_region, rows_schema,
|
||||
};
|
||||
|
||||
const LEASE: Duration = Duration::from_secs(10);
|
||||
@@ -66,10 +72,18 @@ async fn create_region(
|
||||
|
||||
fn grant(engine: &MitoEngine, role: RegionRole, deadline: Instant) {
|
||||
engine
|
||||
.set_region_role_with_lease(REGION_ID, role, deadline)
|
||||
.set_region_role_with_lease(REGION_ID, role, Instant::now(), deadline)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Grants Leader for a heartbeat sent at `sent_at`, and returns whether the role was applied.
|
||||
fn grant_leader_at(engine: &MitoEngine, sent_at: Instant) -> bool {
|
||||
let deadline = Instant::now() + LEASE;
|
||||
engine
|
||||
.set_region_role_with_lease(REGION_ID, RegionRole::Leader, sent_at, deadline)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Returns a request that writes rows `start..start + 3`.
|
||||
fn put_request(schema: &[ColumnSchema], start: usize) -> RegionRequest {
|
||||
let rows = Rows {
|
||||
@@ -282,3 +296,91 @@ async fn test_upgraded_region_writes_before_leader_grant() {
|
||||
.unwrap();
|
||||
put(&engine, REGION_ID, &schema, 0).await.unwrap().unwrap();
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case::downgrading(SettableRegionRoleState::DowngradingLeader)]
|
||||
#[case::follower(SettableRegionRoleState::Follower)]
|
||||
#[tokio::test]
|
||||
async fn test_stale_leader_grant_after_downgrade(#[case] downgraded_to: SettableRegionRoleState) {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
let mut env = TestEnv::with_prefix("stale-leader-grant").await;
|
||||
let (_listener, engine, _schema) = create_region(&mut env, None).await;
|
||||
let sent_before = Instant::now() - Duration::from_millis(1);
|
||||
engine
|
||||
.set_region_role_state_gracefully(REGION_ID, downgraded_to)
|
||||
.await
|
||||
.unwrap();
|
||||
let downgraded = engine.get_region(REGION_ID).unwrap().state();
|
||||
// Another downgrade raises the gate again, though the role does not change.
|
||||
let sent_between = Instant::now();
|
||||
engine
|
||||
.set_region_role_state_gracefully(REGION_ID, downgraded_to)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Grants for heartbeats sent before either downgrade arrive late.
|
||||
assert!(!grant_leader_at(&engine, sent_before));
|
||||
assert!(!grant_leader_at(&engine, sent_between));
|
||||
assert_eq!(downgraded, engine.get_region(REGION_ID).unwrap().state());
|
||||
|
||||
assert!(grant_leader_at(&engine, Instant::now()));
|
||||
assert!(engine.get_region(REGION_ID).unwrap().is_writable());
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case::catchup(false)]
|
||||
#[case::close_and_open(true)]
|
||||
#[tokio::test]
|
||||
async fn test_reopened_region_ignores_earlier_grants(#[case] close: bool) {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
let mut env = TestEnv::with_prefix("reopened-region-grant").await;
|
||||
let (_listener, engine, schema) = create_region(&mut env, None).await;
|
||||
grant(&engine, RegionRole::Leader, Instant::now() + LEASE);
|
||||
// The memtable is not empty, so the catchup below reopens the region.
|
||||
put(&engine, REGION_ID, &schema, 0).await.unwrap().unwrap();
|
||||
let sent_before = Instant::now() - Duration::from_millis(1);
|
||||
let region = engine.get_region(REGION_ID).unwrap();
|
||||
if close {
|
||||
let table_dir = CreateRequestBuilder::new().build().table_dir;
|
||||
reopen_region(&engine, REGION_ID, table_dir, false, HashMap::new()).await;
|
||||
} else {
|
||||
engine
|
||||
.set_region_role_state_gracefully(REGION_ID, SettableRegionRoleState::Follower)
|
||||
.await
|
||||
.unwrap();
|
||||
let request = RegionRequest::Catchup(RegionCatchupRequest::default());
|
||||
engine.handle_request(REGION_ID, request).await.unwrap();
|
||||
}
|
||||
assert!(!Arc::ptr_eq(
|
||||
®ion,
|
||||
&engine.get_region(REGION_ID).unwrap()
|
||||
));
|
||||
|
||||
assert!(!grant_leader_at(&engine, sent_before));
|
||||
assert!(!engine.get_region(REGION_ID).unwrap().is_writable());
|
||||
|
||||
grant(&engine, RegionRole::Leader, Instant::now() + LEASE);
|
||||
assert!(engine.get_region(REGION_ID).unwrap().is_writable());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_leader_grant_exits_staging() {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
let mut env = TestEnv::with_prefix("staging-leader-grant").await;
|
||||
let (_listener, engine, _schema) = create_region(&mut env, None).await;
|
||||
let request = EnterStagingRequest {
|
||||
partition_directive: StagingPartitionDirective::RejectAllWrites,
|
||||
};
|
||||
engine
|
||||
.handle_request(REGION_ID, RegionRequest::EnterStaging(request))
|
||||
.await
|
||||
.unwrap();
|
||||
let state = || engine.get_region(REGION_ID).unwrap().state();
|
||||
assert_eq!(RegionRoleState::Leader(RegionLeaderState::Staging), state());
|
||||
|
||||
grant(&engine, RegionRole::Leader, Instant::now() + LEASE);
|
||||
assert_eq!(
|
||||
RegionRoleState::Leader(RegionLeaderState::Writable),
|
||||
state()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// 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.
|
||||
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
/// The instant lease deadlines count from, so that a deadline fits in an [AtomicU64].
|
||||
static LEASE_EPOCH: LazyLock<Instant> = LazyLock::new(Instant::now);
|
||||
|
||||
fn lease_nanos(instant: Instant) -> u64 {
|
||||
instant.saturating_duration_since(*LEASE_EPOCH).as_nanos() as u64
|
||||
}
|
||||
|
||||
/// A lease deadline in nanoseconds since [LEASE_EPOCH]. It only moves forward; 0 means none.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Deadline(AtomicU64);
|
||||
|
||||
impl Deadline {
|
||||
pub(crate) fn extend(&self, deadline: Instant) {
|
||||
self.0.fetch_max(lease_nanos(deadline), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub(crate) fn get(&self) -> u64 {
|
||||
self.0.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
/// Lease of this node: the latest deadline of the heartbeat responses that carry region leases.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct NodeLease {
|
||||
/// Whether writes need a lease. Only a datanode the metasrv controls sets it.
|
||||
enabled: AtomicBool,
|
||||
deadline: Deadline,
|
||||
/// The time of the lease checks while a test freezes it, in the unit of [Deadline]; 0 when
|
||||
/// it is not frozen.
|
||||
#[cfg(any(test, feature = "test"))]
|
||||
frozen_now: AtomicU64,
|
||||
}
|
||||
|
||||
impl NodeLease {
|
||||
pub(crate) fn enable(&self) {
|
||||
self.enabled.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub(crate) fn is_enabled(&self) -> bool {
|
||||
self.enabled.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub(crate) fn renew(&self, deadline: Instant) {
|
||||
self.deadline.extend(deadline);
|
||||
}
|
||||
|
||||
/// Returns the current time in the unit of [Deadline].
|
||||
pub(crate) fn now(&self) -> u64 {
|
||||
#[cfg(any(test, feature = "test"))]
|
||||
{
|
||||
let frozen_now = self.frozen_now.load(Ordering::Relaxed);
|
||||
if frozen_now != 0 {
|
||||
return frozen_now;
|
||||
}
|
||||
}
|
||||
lease_nanos(Instant::now())
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test"))]
|
||||
pub(crate) fn freeze_clock(&self, at: Instant) {
|
||||
self.frozen_now
|
||||
.store(lease_nanos(at).max(1), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Lets a region created or upgraded on this node write until the node's deadline. The
|
||||
/// metasrv granted that deadline before the creation or upgrade, so a later migration of the
|
||||
/// region waits past it. Later responses do not extend it; the region's Leader grants do.
|
||||
pub(crate) fn seed(&self, leader_deadline: &Deadline) {
|
||||
leader_deadline
|
||||
.0
|
||||
.fetch_max(self.deadline.get(), Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,7 @@ pub mod error;
|
||||
pub mod extension;
|
||||
pub mod flush;
|
||||
pub mod gc;
|
||||
mod lease;
|
||||
pub mod manifest;
|
||||
pub mod memtable;
|
||||
mod metrics;
|
||||
|
||||
+61
-80
@@ -23,8 +23,8 @@ pub(crate) mod version;
|
||||
use std::cell::OnceCell;
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, LazyLock, Mutex, RwLock};
|
||||
use std::sync::atomic::{AtomicI64, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
use std::time::Instant;
|
||||
|
||||
use common_base::hash::partition_expr_version;
|
||||
@@ -59,6 +59,7 @@ use crate::error::{
|
||||
FlushableRegionStateSnafu, InvalidPartitionExprSnafu, RegionNotFoundSnafu, RegionStateSnafu,
|
||||
RegionTruncatedSnafu, Result, UnexpectedSnafu, UpdateManifestSnafu,
|
||||
};
|
||||
use crate::lease::Deadline;
|
||||
use crate::manifest::action::{
|
||||
RegionChange, RegionManifest, RegionMetaAction, RegionMetaActionList,
|
||||
};
|
||||
@@ -186,8 +187,6 @@ pub struct MitoRegion {
|
||||
/// There are no WAL entries in range [flushed_entry_id, topic_latest_entry_id] for current region,
|
||||
/// which means these WAL entries maybe able to be pruned up to `topic_latest_entry_id`.
|
||||
pub(crate) topic_latest_entry_id: AtomicU64,
|
||||
/// Deadline of the region's latest Leader or StagingLeader lease from the metasrv.
|
||||
pub(crate) leader_deadline: Deadline,
|
||||
/// Region stats.
|
||||
pub(crate) region_stats: RegionStats,
|
||||
/// manifest stats
|
||||
@@ -224,80 +223,6 @@ impl RegionStats {
|
||||
|
||||
pub type MitoRegionRef = Arc<MitoRegion>;
|
||||
|
||||
/// The instant lease deadlines count from, so that a deadline fits in an [AtomicU64].
|
||||
static LEASE_EPOCH: LazyLock<Instant> = LazyLock::new(Instant::now);
|
||||
|
||||
fn lease_nanos(instant: Instant) -> u64 {
|
||||
instant.saturating_duration_since(*LEASE_EPOCH).as_nanos() as u64
|
||||
}
|
||||
|
||||
/// A lease deadline in nanoseconds since [LEASE_EPOCH]. It only moves forward; 0 means none.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Deadline(AtomicU64);
|
||||
|
||||
impl Deadline {
|
||||
pub(crate) fn extend(&self, deadline: Instant) {
|
||||
self.0.fetch_max(lease_nanos(deadline), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub(crate) fn get(&self) -> u64 {
|
||||
self.0.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
/// Lease of this node: the latest deadline of the heartbeat responses that carry region leases.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct NodeLease {
|
||||
/// Whether writes need a lease. Only a datanode the metasrv controls sets it.
|
||||
enabled: AtomicBool,
|
||||
deadline: Deadline,
|
||||
/// The time of the lease checks while a test freezes it, in the unit of [Deadline]; 0 when
|
||||
/// it is not frozen.
|
||||
#[cfg(any(test, feature = "test"))]
|
||||
frozen_now: AtomicU64,
|
||||
}
|
||||
|
||||
impl NodeLease {
|
||||
pub(crate) fn enable(&self) {
|
||||
self.enabled.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub(crate) fn is_enabled(&self) -> bool {
|
||||
self.enabled.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub(crate) fn renew(&self, deadline: Instant) {
|
||||
self.deadline.extend(deadline);
|
||||
}
|
||||
|
||||
/// Returns the current time in the unit of [Deadline].
|
||||
pub(crate) fn now(&self) -> u64 {
|
||||
#[cfg(any(test, feature = "test"))]
|
||||
{
|
||||
let frozen_now = self.frozen_now.load(Ordering::Relaxed);
|
||||
if frozen_now != 0 {
|
||||
return frozen_now;
|
||||
}
|
||||
}
|
||||
lease_nanos(Instant::now())
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test"))]
|
||||
pub(crate) fn freeze_clock(&self, at: Instant) {
|
||||
self.frozen_now
|
||||
.store(lease_nanos(at).max(1), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Lets a region created or upgraded on this node write until the node's deadline. The
|
||||
/// metasrv granted that deadline before the creation or upgrade, so a later migration of the
|
||||
/// region waits past it. Later responses do not extend it; the region's Leader grants do.
|
||||
pub(crate) fn seed(&self, leader_deadline: &Deadline) {
|
||||
leader_deadline
|
||||
.0
|
||||
.fetch_max(self.deadline.get(), Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct StagingPartitionInfo {
|
||||
pub(crate) partition_directive: StagingPartitionDirective,
|
||||
@@ -1290,6 +1215,17 @@ pub(crate) struct ManifestContext {
|
||||
/// The state of the region. The region checks the state before updating
|
||||
/// manifest.
|
||||
state: AtomicCell<RegionRoleState>,
|
||||
/// When the region last began a downgrade. A promotion issued before it does not apply. The
|
||||
/// lock covers comparing or raising it and the role change.
|
||||
///
|
||||
/// It starts at creation time, so promotions issued before the region was opened or reopened
|
||||
/// do not apply. A context that replaces this one is created after the worker loop closes or
|
||||
/// reopens the region, so after its last downgrade began.
|
||||
downgrade_started_at: Mutex<Instant>,
|
||||
/// Deadline of the region's latest Leader or StagingLeader lease from the metasrv, which is how
|
||||
/// long the Leader role stays valid. The engine extends it from those leases, and writes check
|
||||
/// it.
|
||||
pub(crate) leader_deadline: Deadline,
|
||||
/// Partition info of the region in staging mode.
|
||||
///
|
||||
/// During the staging mode, the region metadata in [`VersionControlRef`] is not updated,
|
||||
@@ -1308,6 +1244,8 @@ impl ManifestContext {
|
||||
ManifestContext {
|
||||
manifest_manager: tokio::sync::RwLock::new(manager),
|
||||
state: AtomicCell::new(state),
|
||||
downgrade_started_at: Mutex::new(Instant::now()),
|
||||
leader_deadline: Deadline::default(),
|
||||
staging_partition_info: Mutex::new(None),
|
||||
hook,
|
||||
}
|
||||
@@ -1666,6 +1604,33 @@ impl ManifestContext {
|
||||
self.update_and_fire(manager, action_list, is_staging).await
|
||||
}
|
||||
|
||||
/// Raises the downgrade start time to now, then marks the region downgrading.
|
||||
pub(crate) fn begin_downgrade(&self, region_id: RegionId) {
|
||||
let mut downgrade_started_at = self.downgrade_started_at.lock().unwrap();
|
||||
*downgrade_started_at = Instant::now();
|
||||
self.set_role(RegionRole::DowngradingLeader, region_id);
|
||||
}
|
||||
|
||||
/// Promotes the region to a writable leader unless a downgrade started after `issued_at`.
|
||||
/// Returns false if the promotion is ignored for that reason; otherwise the role changes as
|
||||
/// [`Self::set_role`] allows.
|
||||
pub(crate) fn promote_unless_downgrade_started_after(
|
||||
&self,
|
||||
issued_at: Instant,
|
||||
region_id: RegionId,
|
||||
) -> bool {
|
||||
// A writable leader needs no change; a staging leader is promoted below.
|
||||
if self.state.load() == RegionRoleState::Leader(RegionLeaderState::Writable) {
|
||||
return true;
|
||||
}
|
||||
let downgrade_started_at = self.downgrade_started_at.lock().unwrap();
|
||||
if issued_at < *downgrade_started_at {
|
||||
return false;
|
||||
}
|
||||
self.set_role(RegionRole::Leader, region_id);
|
||||
true
|
||||
}
|
||||
|
||||
/// Sets the [`RegionRole`].
|
||||
///
|
||||
/// ```text
|
||||
@@ -2341,7 +2306,6 @@ mod tests {
|
||||
last_schedule_compaction_millis: Default::default(),
|
||||
time_provider: Arc::new(StdTimeProvider),
|
||||
topic_latest_entry_id: Default::default(),
|
||||
leader_deadline: Default::default(),
|
||||
region_stats: RegionStats::new(),
|
||||
stats: ManifestStats::default(),
|
||||
}
|
||||
@@ -2457,6 +2421,24 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_promoting_writable_leader_takes_no_lock() {
|
||||
let env = SchedulerEnv::new().await;
|
||||
let region = Arc::new(build_test_region(&env).await);
|
||||
let _downgrade_started_at = region.manifest_ctx.downgrade_started_at.lock().unwrap();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let promoted = region.clone();
|
||||
std::thread::spawn(move || {
|
||||
let manifest_ctx = &promoted.manifest_ctx;
|
||||
let issued_at = std::time::Instant::now();
|
||||
tx.send(
|
||||
manifest_ctx.promote_unless_downgrade_started_after(issued_at, promoted.region_id),
|
||||
)
|
||||
.unwrap();
|
||||
});
|
||||
assert!(rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_compaction_update_manifest_allows_editing_state() {
|
||||
let env = SchedulerEnv::new().await;
|
||||
@@ -2945,7 +2927,6 @@ mod tests {
|
||||
last_schedule_compaction_millis: Default::default(),
|
||||
time_provider: Arc::new(StdTimeProvider),
|
||||
topic_latest_entry_id: Default::default(),
|
||||
leader_deadline: Default::default(),
|
||||
region_stats: RegionStats::new(),
|
||||
stats: ManifestStats::default(),
|
||||
};
|
||||
|
||||
@@ -459,7 +459,6 @@ impl RegionOpener {
|
||||
last_schedule_compaction_millis: AtomicI64::new(now),
|
||||
time_provider: self.time_provider.clone(),
|
||||
topic_latest_entry_id: AtomicU64::new(flushed_entry_id),
|
||||
leader_deadline: Default::default(),
|
||||
region_stats: RegionStats::new(),
|
||||
stats: self.stats,
|
||||
}))
|
||||
@@ -698,7 +697,6 @@ impl RegionOpener {
|
||||
last_schedule_compaction_millis: AtomicI64::new(now),
|
||||
time_provider: self.time_provider.clone(),
|
||||
topic_latest_entry_id: AtomicU64::new(topic_latest_entry_id),
|
||||
leader_deadline: Default::default(),
|
||||
region_stats: RegionStats::new(),
|
||||
stats: self.stats.clone(),
|
||||
};
|
||||
|
||||
@@ -52,7 +52,7 @@ use rand::{Rng, rng};
|
||||
use snafu::ResultExt;
|
||||
use store_api::logstore::LogStore;
|
||||
use store_api::region_engine::{
|
||||
RegionRole, SetRegionRoleStateResponse, SetRegionRoleStateSuccess, SettableRegionRoleState,
|
||||
SetRegionRoleStateResponse, SetRegionRoleStateSuccess, SettableRegionRoleState,
|
||||
};
|
||||
use store_api::storage::{FileId, RegionId};
|
||||
use tokio::sync::mpsc::{Receiver, Sender};
|
||||
@@ -67,12 +67,13 @@ use crate::config::MitoConfig;
|
||||
use crate::error::{self, CreateDirSnafu, JoinSnafu, Result, WorkerStoppedSnafu};
|
||||
use crate::flush::{FlushScheduler, WriteBufferManagerImpl, WriteBufferManagerRef};
|
||||
use crate::gc::{GcLimiter, GcLimiterRef};
|
||||
use crate::lease::NodeLease;
|
||||
use crate::memtable::MemtableBuilderProvider;
|
||||
use crate::metrics::{REGION_COUNT, REQUEST_WAIT_TIME, WRITE_STALLING};
|
||||
use crate::region::opener::PartitionExprFetcherRef;
|
||||
use crate::region::{
|
||||
CatchupRegions, CatchupRegionsRef, MitoRegionRef, NodeLease, OpeningRegions, OpeningRegionsRef,
|
||||
RegionMap, RegionMapRef,
|
||||
CatchupRegions, CatchupRegionsRef, MitoRegionRef, OpeningRegions, OpeningRegionsRef, RegionMap,
|
||||
RegionMapRef,
|
||||
};
|
||||
use crate::request::{
|
||||
BackgroundNotify, BulkInsertRequest, DdlRequest, OptionOutputTx, SenderBulkRequest,
|
||||
@@ -1516,8 +1517,9 @@ impl<S: LogStore> RegionWorkerLoop<S> {
|
||||
) {
|
||||
// Fence writes here: writes the worker handles later see
|
||||
// Downgrading, and earlier ones have finished. This only
|
||||
// changes a writable or staging leader.
|
||||
region.set_role(RegionRole::DowngradingLeader);
|
||||
// changes a writable or staging leader, but always fences
|
||||
// promotions issued before.
|
||||
region.manifest_ctx.begin_downgrade(region_id);
|
||||
}
|
||||
#[cfg(feature = "hdfs-object-store")]
|
||||
let sweep_older_than = self.config.gc.unknown_file_lingering_time;
|
||||
|
||||
@@ -87,7 +87,7 @@ impl<S: LogStore> RegionWorkerLoop<S> {
|
||||
if request.set_writable {
|
||||
// The region takes writes under the node lease until its next Leader
|
||||
// grant.
|
||||
node_lease.seed(®ion.leader_deadline);
|
||||
node_lease.seed(®ion.manifest_ctx.leader_deadline);
|
||||
region.set_role(RegionRole::Leader);
|
||||
// Finalize leadership: persist backfilled metadata.
|
||||
match region
|
||||
|
||||
@@ -107,7 +107,7 @@ impl<S: LogStore> RegionWorkerLoop<S> {
|
||||
}
|
||||
|
||||
// The region takes writes under the node lease until its first Leader grant.
|
||||
self.node_lease.seed(®ion.leader_deadline);
|
||||
self.node_lease.seed(®ion.manifest_ctx.leader_deadline);
|
||||
// Insert the MitoRegion into the RegionMap.
|
||||
self.register_region(region);
|
||||
if let Some(state) = &self.series_index_task_state {
|
||||
|
||||
@@ -340,7 +340,7 @@ impl<S> RegionWorkerLoop<S> {
|
||||
match region.state() {
|
||||
RegionRoleState::Leader(RegionLeaderState::Writable)
|
||||
| RegionRoleState::Leader(RegionLeaderState::Staging) => {
|
||||
let leader_deadline = region.leader_deadline.get();
|
||||
let leader_deadline = region.manifest_ctx.leader_deadline.get();
|
||||
if lease_now.is_some_and(|now| now >= leader_deadline) {
|
||||
sender_req
|
||||
.sender
|
||||
@@ -497,7 +497,7 @@ impl<S> RegionWorkerLoop<S> {
|
||||
match region.state() {
|
||||
RegionRoleState::Leader(RegionLeaderState::Writable)
|
||||
| RegionRoleState::Leader(RegionLeaderState::Staging) => {
|
||||
let leader_deadline = region.leader_deadline.get();
|
||||
let leader_deadline = region.manifest_ctx.leader_deadline.get();
|
||||
if lease_now.is_some_and(|now| now >= leader_deadline) {
|
||||
bulk_req
|
||||
.sender
|
||||
@@ -606,7 +606,7 @@ impl<S> RegionWorkerLoop<S> {
|
||||
for (region_id, region_ctx) in region_ctxs.iter_mut() {
|
||||
// A Leader grant may have extended the deadline during the append.
|
||||
let expired = region_ctx.lease.as_ref().is_some_and(|(region, deadline)| {
|
||||
now >= *deadline && now >= region.leader_deadline.get()
|
||||
now >= *deadline && now >= region.manifest_ctx.leader_deadline.get()
|
||||
});
|
||||
if !expired || region_ctx.is_failed() {
|
||||
continue;
|
||||
|
||||
@@ -7,7 +7,6 @@ license.workspace = true
|
||||
[features]
|
||||
testing = []
|
||||
enterprise = [
|
||||
"common-grpc/enterprise",
|
||||
"common-meta/enterprise",
|
||||
"sql/enterprise",
|
||||
"query/enterprise",
|
||||
|
||||
@@ -12,8 +12,6 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
mod flow_write;
|
||||
mod otlp;
|
||||
|
||||
pub use otlp::MetricInsertPreflight;
|
||||
@@ -857,47 +855,6 @@ impl Inserter {
|
||||
has_instant_rows,
|
||||
)?;
|
||||
|
||||
// Tracked Flow children use a same-capability write protocol. Keep the
|
||||
// ordinary dispatch path unchanged for every other request.
|
||||
#[cfg(feature = "enterprise")]
|
||||
if flow_write::is_child(ctx) {
|
||||
let dispatcher = self.write_dispatcher.clone();
|
||||
let request = request_factory.build_insert(normal_requests);
|
||||
let writes = dispatcher.prepare(vec![request]).await?;
|
||||
let tracked_tasks = writes.into_iter().map(|(peer, mut request)| {
|
||||
let mut query_context = crate::utils::to_meta_query_context(ctx.clone());
|
||||
query_context.extensions.insert(
|
||||
common_grpc::flow_write::CHILD_KEY.to_string(),
|
||||
"1".to_string(),
|
||||
);
|
||||
if let Some(header) = request.header.as_mut() {
|
||||
header.query_context = Some(query_context.into());
|
||||
}
|
||||
let node_manager = self.node_manager.clone();
|
||||
async move { flow_write::dispatch(&node_manager, &peer, request).await }
|
||||
});
|
||||
let results = future::join_all(tracked_tasks).await;
|
||||
let mut affected_rows = 0;
|
||||
let mut first_error = None;
|
||||
for result in results {
|
||||
match result {
|
||||
Ok(response) => affected_rows += response.affected_rows,
|
||||
Err(error) if first_error.is_none() => first_error = Some(error),
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
if let Some(error) = first_error {
|
||||
return Err(error);
|
||||
}
|
||||
crate::metrics::DIST_INGEST_ROW_COUNT
|
||||
.with_label_values(&[ctx.get_db_string().as_str()])
|
||||
.inc_by(affected_rows as u64);
|
||||
return Ok(Output::new(
|
||||
OutputData::AffectedRows(affected_rows),
|
||||
OutputMeta::new_with_cost(write_cost as _),
|
||||
));
|
||||
}
|
||||
|
||||
let dispatcher = self.write_dispatcher.clone();
|
||||
let request = request_factory.build_insert(normal_requests);
|
||||
let writes = dispatcher.prepare(vec![request]).await?;
|
||||
|
||||
@@ -1,391 +0,0 @@
|
||||
// Copyright 2023-2026 GrepTime Inc.
|
||||
//
|
||||
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
|
||||
// the GreptimeDB Enterprise License. You may not use this file except in
|
||||
// compliance with that license. A copy of the license is available at the root
|
||||
// of this repository in the file LICENSE-ENTERPRISE.
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, this software is
|
||||
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
// either express or implied.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use api::v1::region::RegionRequest;
|
||||
use common_error::ext::BoxedError;
|
||||
use common_grpc::flow_write::{self, Command, Reply};
|
||||
use common_meta::node_manager::{DatanodeRef, NodeManagerRef};
|
||||
use common_meta::peer::Peer;
|
||||
use session::context::generate_remote_query_id;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
|
||||
const RETRY_DELAY: Duration = Duration::from_secs(1);
|
||||
|
||||
fn error(message: impl Into<String>) -> Error {
|
||||
Error::Unexpected {
|
||||
violated: message.into(),
|
||||
location: snafu::Location::new(file!(), line!(), column!()),
|
||||
}
|
||||
}
|
||||
|
||||
fn command_request(
|
||||
request: &RegionRequest,
|
||||
command: &Command,
|
||||
control: bool,
|
||||
) -> Result<RegionRequest> {
|
||||
let mut request = request.clone();
|
||||
if control {
|
||||
request.body = Some(api::v1::region::region_request::Body::Inserts(
|
||||
Default::default(),
|
||||
));
|
||||
}
|
||||
let header = request.header.get_or_insert_with(Default::default);
|
||||
let query_context = header
|
||||
.query_context
|
||||
.get_or_insert_with(api::v1::QueryContext::default);
|
||||
query_context.extensions.insert(
|
||||
flow_write::COMMAND_KEY.to_string(),
|
||||
command.encode().map_err(|e| error(e.to_string()))?,
|
||||
);
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
fn reply(response: &api::region::RegionResponse) -> Option<Reply> {
|
||||
response
|
||||
.extensions
|
||||
.get(flow_write::COMMAND_KEY)
|
||||
.and_then(|value| std::str::from_utf8(value).ok())
|
||||
.and_then(|value| serde_json::from_str(value).ok())
|
||||
}
|
||||
|
||||
pub(crate) async fn dispatch(
|
||||
node_manager: &NodeManagerRef,
|
||||
peer: &Peer,
|
||||
request: RegionRequest,
|
||||
) -> Result<api::region::RegionResponse> {
|
||||
dispatch_datanode(node_manager.datanode(peer).await, request).await
|
||||
}
|
||||
|
||||
async fn dispatch_datanode(
|
||||
datanode: DatanodeRef,
|
||||
request: RegionRequest,
|
||||
) -> Result<api::region::RegionResponse> {
|
||||
let nonce = generate_remote_query_id();
|
||||
let open = command_request(&request, &Command::Open { nonce }, true)?;
|
||||
let capability = loop {
|
||||
match datanode.handle(open.clone()).await {
|
||||
Ok(response) => match reply(&response) {
|
||||
Some(Reply::Opened { capability }) if !capability.is_empty() => break capability,
|
||||
_ => return Err(error("Datanode does not support tracked Flow writes")),
|
||||
},
|
||||
Err(_) => tokio::time::sleep(RETRY_DELAY).await,
|
||||
}
|
||||
};
|
||||
|
||||
let write = command_request(
|
||||
&request,
|
||||
&Command::Write {
|
||||
capability: capability.clone(),
|
||||
},
|
||||
false,
|
||||
)?;
|
||||
let complete = loop {
|
||||
match datanode.handle(write.clone()).await {
|
||||
Ok(response) => match reply(&response) {
|
||||
Some(Reply::Complete {
|
||||
rows,
|
||||
cost: _,
|
||||
metrics: _,
|
||||
error,
|
||||
}) => break (response, rows, error),
|
||||
_ => tokio::time::sleep(RETRY_DELAY).await,
|
||||
},
|
||||
Err(_) => tokio::time::sleep(RETRY_DELAY).await,
|
||||
}
|
||||
};
|
||||
|
||||
let close = command_request(
|
||||
&request,
|
||||
&Command::Close {
|
||||
capability: capability.clone(),
|
||||
},
|
||||
true,
|
||||
)?;
|
||||
loop {
|
||||
match datanode.handle(close.clone()).await {
|
||||
Ok(response) if matches!(reply(&response), Some(Reply::Closed)) => break,
|
||||
_ => tokio::time::sleep(RETRY_DELAY).await,
|
||||
}
|
||||
}
|
||||
|
||||
let (mut response, rows, terminal_error) = complete;
|
||||
if let Some(terminal_error) = terminal_error {
|
||||
return Err(Error::External {
|
||||
source: BoxedError::new(terminal_error),
|
||||
location: snafu::location!(),
|
||||
});
|
||||
}
|
||||
response.affected_rows = rows as _;
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
pub(crate) fn is_child(ctx: &session::context::QueryContextRef) -> bool {
|
||||
ctx.channel() == common_base::protocol::Channel::Internal
|
||||
&& ctx.extension(flow_write::CHILD_KEY) == Some("1")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use api::region::RegionResponse;
|
||||
use api::v1::region::{RegionRequest, region_request::Body};
|
||||
use common_error::ext::BoxedError;
|
||||
use common_error::ext::ErrorExt;
|
||||
use common_grpc::flow_write::{self, Command, Reply};
|
||||
use common_meta::node_manager::{Datanode, DatanodeRef};
|
||||
use common_query::request::QueryRequest;
|
||||
use common_recordbatch::SendableRecordBatchStream;
|
||||
use futures_util::future::join_all;
|
||||
use tokio::sync::Notify;
|
||||
|
||||
use super::dispatch_datanode;
|
||||
|
||||
#[derive(Default)]
|
||||
struct MockDatanode {
|
||||
capabilities: Mutex<HashMap<String, String>>,
|
||||
business_write_attempts: AtomicUsize,
|
||||
write_commands: Mutex<Vec<String>>,
|
||||
requests: Mutex<Vec<RegionRequest>>,
|
||||
drop_open_reply: AtomicUsize,
|
||||
drop_write_reply: AtomicUsize,
|
||||
drop_close_reply: AtomicUsize,
|
||||
latch_write: bool,
|
||||
terminal_error: bool,
|
||||
write_started: Notify,
|
||||
release_write: Notify,
|
||||
close_started: Notify,
|
||||
}
|
||||
|
||||
impl MockDatanode {
|
||||
fn response(reply: Reply) -> RegionResponse {
|
||||
let mut response = RegionResponse::new(0);
|
||||
response.extensions.insert(
|
||||
flow_write::COMMAND_KEY.to_string(),
|
||||
serde_json::to_vec(&reply).unwrap(),
|
||||
);
|
||||
response
|
||||
}
|
||||
|
||||
fn command(request: &RegionRequest) -> Command {
|
||||
let serialized = request
|
||||
.header
|
||||
.as_ref()
|
||||
.and_then(|header| header.query_context.as_ref())
|
||||
.and_then(|context| context.extensions.get(flow_write::COMMAND_KEY))
|
||||
.unwrap();
|
||||
Command::decode(serialized).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Datanode for MockDatanode {
|
||||
async fn handle_request(
|
||||
&self,
|
||||
request: Arc<RegionRequest>,
|
||||
) -> common_meta::error::Result<RegionResponse> {
|
||||
self.requests.lock().unwrap().push(request.as_ref().clone());
|
||||
match Self::command(&request) {
|
||||
Command::Open { nonce } => {
|
||||
if !matches!(request.body, Some(Body::Inserts(ref inserts)) if inserts.requests.is_empty())
|
||||
{
|
||||
return Err(common_meta::error::Error::External {
|
||||
source: BoxedError::new(common_error::mock::MockError::new(
|
||||
common_error::status_code::StatusCode::InvalidArguments,
|
||||
)),
|
||||
location: snafu::location!(),
|
||||
});
|
||||
}
|
||||
let mut capabilities = self.capabilities.lock().unwrap();
|
||||
let capability = capabilities
|
||||
.entry(nonce)
|
||||
.or_insert_with(|| "cap-1".into())
|
||||
.clone();
|
||||
if self
|
||||
.drop_open_reply
|
||||
.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1))
|
||||
.is_ok()
|
||||
{
|
||||
return Err(common_meta::error::Error::External {
|
||||
source: BoxedError::new(common_error::mock::MockError::new(
|
||||
common_error::status_code::StatusCode::TableUnavailable,
|
||||
)),
|
||||
location: snafu::location!(),
|
||||
});
|
||||
}
|
||||
Ok(Self::response(Reply::Opened { capability }))
|
||||
}
|
||||
Command::Write { capability } => {
|
||||
self.write_commands.lock().unwrap().push(capability.clone());
|
||||
if matches!(request.body, Some(Body::Inserts(ref inserts)) if !inserts.requests.is_empty())
|
||||
&& self.business_write_attempts.fetch_add(1, Ordering::SeqCst) == 0
|
||||
&& self.latch_write
|
||||
{
|
||||
self.write_started.notify_one();
|
||||
self.release_write.notified().await;
|
||||
}
|
||||
if self
|
||||
.drop_write_reply
|
||||
.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1))
|
||||
.is_ok()
|
||||
{
|
||||
return Err(common_meta::error::Error::External {
|
||||
source: BoxedError::new(common_error::mock::MockError::new(
|
||||
common_error::status_code::StatusCode::TableUnavailable,
|
||||
)),
|
||||
location: snafu::location!(),
|
||||
});
|
||||
}
|
||||
Ok(Self::response(Reply::Complete {
|
||||
rows: 7,
|
||||
cost: 0,
|
||||
metrics: None,
|
||||
error: self.terminal_error.then(|| flow_write::TerminalError {
|
||||
code: common_error::status_code::StatusCode::TableNotFound as u32,
|
||||
message: "terminal child error".to_string(),
|
||||
}),
|
||||
}))
|
||||
}
|
||||
Command::Close { .. } => {
|
||||
self.close_started.notify_one();
|
||||
if self
|
||||
.drop_close_reply
|
||||
.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1))
|
||||
.is_ok()
|
||||
{
|
||||
return Err(common_meta::error::Error::External {
|
||||
source: BoxedError::new(common_error::mock::MockError::new(
|
||||
common_error::status_code::StatusCode::TableUnavailable,
|
||||
)),
|
||||
location: snafu::location!(),
|
||||
});
|
||||
}
|
||||
Ok(Self::response(Reply::Closed))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_query(
|
||||
&self,
|
||||
_: QueryRequest,
|
||||
) -> common_meta::error::Result<SendableRecordBatchStream> {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
|
||||
fn request() -> RegionRequest {
|
||||
RegionRequest {
|
||||
header: None,
|
||||
body: Some(Body::Inserts(api::v1::region::InsertRequests {
|
||||
requests: vec![Default::default()],
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn lost_control_and_write_replies_reuse_capability_and_exact_request() {
|
||||
let datanode = Arc::new(MockDatanode::default());
|
||||
datanode.drop_open_reply.store(1, Ordering::SeqCst);
|
||||
datanode.drop_write_reply.store(1, Ordering::SeqCst);
|
||||
datanode.drop_close_reply.store(1, Ordering::SeqCst);
|
||||
let response = dispatch_datanode(datanode.clone(), request())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.affected_rows, 7);
|
||||
assert_eq!(datanode.business_write_attempts.load(Ordering::SeqCst), 2);
|
||||
let writes = datanode.write_commands.lock().unwrap();
|
||||
assert_eq!(writes.len(), 2);
|
||||
assert!(writes.iter().all(|capability| capability == "cap-1"));
|
||||
let requests = datanode.requests.lock().unwrap();
|
||||
let writes: Vec<_> = requests
|
||||
.iter()
|
||||
.filter(|request| matches!(MockDatanode::command(request), Command::Write { .. }))
|
||||
.collect();
|
||||
assert_eq!(writes.len(), 2);
|
||||
assert_eq!(writes[0].body, writes[1].body);
|
||||
assert_eq!(writes[0].header, writes[1].header);
|
||||
assert_eq!(
|
||||
requests
|
||||
.iter()
|
||||
.filter(|request| matches!(
|
||||
MockDatanode::command(request),
|
||||
Command::Open { .. } | Command::Close { .. }
|
||||
))
|
||||
.count(),
|
||||
4
|
||||
);
|
||||
assert!(requests
|
||||
.iter()
|
||||
.filter(|request| matches!(MockDatanode::command(request), Command::Open { .. } | Command::Close { .. }))
|
||||
.all(|request| matches!(request.body, Some(Body::Inserts(ref inserts)) if inserts.requests.is_empty())));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unsupported_open_never_submits_business_request() {
|
||||
struct Unsupported;
|
||||
#[async_trait::async_trait]
|
||||
impl Datanode for Unsupported {
|
||||
async fn handle_request(
|
||||
&self,
|
||||
_: Arc<RegionRequest>,
|
||||
) -> common_meta::error::Result<RegionResponse> {
|
||||
Ok(RegionResponse::new(0))
|
||||
}
|
||||
async fn handle_query(
|
||||
&self,
|
||||
_: QueryRequest,
|
||||
) -> common_meta::error::Result<SendableRecordBatchStream> {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
let datanode: DatanodeRef = Arc::new(Unsupported);
|
||||
let error = dispatch_datanode(datanode, request()).await.unwrap_err();
|
||||
assert_eq!(
|
||||
error.status_code(),
|
||||
common_error::status_code::StatusCode::Unexpected
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn all_peer_writes_drain_before_terminal_error_returns() {
|
||||
let failing = Arc::new(MockDatanode {
|
||||
terminal_error: true,
|
||||
..Default::default()
|
||||
});
|
||||
let latched = Arc::new(MockDatanode {
|
||||
latch_write: true,
|
||||
..Default::default()
|
||||
});
|
||||
let first_datanode: DatanodeRef = failing.clone();
|
||||
let second_datanode: DatanodeRef = latched.clone();
|
||||
let aggregate = tokio::spawn(async move {
|
||||
join_all([
|
||||
dispatch_datanode(first_datanode, request()),
|
||||
dispatch_datanode(second_datanode, request()),
|
||||
])
|
||||
.await
|
||||
});
|
||||
latched.write_started.notified().await;
|
||||
failing.close_started.notified().await;
|
||||
assert!(!aggregate.is_finished());
|
||||
latched.release_write.notify_one();
|
||||
let results = aggregate.await.unwrap();
|
||||
assert_eq!(results.len(), 2);
|
||||
assert_eq!(failing.business_write_attempts.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(latched.business_write_attempts.load(Ordering::SeqCst), 1);
|
||||
assert!(results.into_iter().any(|result| result.is_err()));
|
||||
}
|
||||
}
|
||||
@@ -107,8 +107,9 @@ impl RegionEngine for MetaRegionEngine {
|
||||
&self,
|
||||
_region_id: RegionId,
|
||||
_role: RegionRole,
|
||||
_sent_at: std::time::Instant,
|
||||
_deadline: std::time::Instant,
|
||||
) -> Result<(), BoxedError> {
|
||||
) -> Result<bool, BoxedError> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ use common_grpc::precision::Precision;
|
||||
use common_telemetry::tracing;
|
||||
use session::context::{Channel, QueryContext, QueryContextRef};
|
||||
|
||||
use crate::error::{Result, TimePrecisionSnafu};
|
||||
use crate::error::Result;
|
||||
use crate::http::header::write_cost_header_map;
|
||||
use crate::influxdb::InfluxdbRequest;
|
||||
use crate::query_handler::InfluxdbLineProtocolHandlerRef;
|
||||
@@ -107,30 +107,13 @@ pub async fn influxdb_write(
|
||||
))
|
||||
}
|
||||
|
||||
fn parse_time_precision(value: &str) -> Result<Precision> {
|
||||
// Precision conversion needs to be compatible with influxdb v1 v2 api.
|
||||
// For details, see the Influxdb documents.
|
||||
// https://docs.influxdata.com/influxdb/v1.8/tools/api/#apiv2write-http-endpoint
|
||||
// https://docs.influxdata.com/influxdb/v1.8/tools/api/#write-http-endpoint
|
||||
match value {
|
||||
"n" | "ns" => Ok(Precision::Nanosecond),
|
||||
"u" | "us" => Ok(Precision::Microsecond),
|
||||
"ms" => Ok(Precision::Millisecond),
|
||||
"s" => Ok(Precision::Second),
|
||||
"m" => Ok(Precision::Minute),
|
||||
"h" => Ok(Precision::Hour),
|
||||
unknown => TimePrecisionSnafu {
|
||||
name: unknown.to_string(),
|
||||
}
|
||||
.fail(),
|
||||
}
|
||||
}
|
||||
pub(crate) use crate::influxdb::parse_time_precision;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use common_grpc::precision::Precision;
|
||||
|
||||
use crate::http::influxdb::parse_time_precision;
|
||||
use super::parse_time_precision;
|
||||
|
||||
#[test]
|
||||
fn test_parse_time_precision() {
|
||||
|
||||
@@ -20,7 +20,7 @@ use hyper::Request;
|
||||
use influxdb_line_protocol::{FieldValue, parse_lines};
|
||||
use snafu::ResultExt;
|
||||
|
||||
use crate::error::{Error, InfluxdbLineProtocolSnafu};
|
||||
use crate::error::{Error, InfluxdbLineProtocolSnafu, TimePrecisionSnafu};
|
||||
use crate::row_writer::{self, MultiTableData};
|
||||
|
||||
const INFLUXDB_API_PATH_NAME: &str = "influxdb";
|
||||
@@ -113,6 +113,27 @@ fn unwrap_or_default_precision(precision: Option<Precision>) -> Precision {
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses an InfluxDB time-precision name shared by the HTTP write
|
||||
/// endpoints (v1/v2) and the `precision` option of COPY FROM STDIN.
|
||||
pub(crate) fn parse_time_precision(value: &str) -> crate::error::Result<Precision> {
|
||||
// Precision conversion needs to be compatible with influxdb v1 v2 api.
|
||||
// For details, see the Influxdb documents.
|
||||
// https://docs.influxdata.com/influxdb/v1.8/tools/api/#apiv2write-http-endpoint
|
||||
// https://docs.influxdata.com/influxdb/v1.8/tools/api/#write-http-endpoint
|
||||
match value {
|
||||
"n" | "ns" => Ok(Precision::Nanosecond),
|
||||
"u" | "us" => Ok(Precision::Microsecond),
|
||||
"ms" => Ok(Precision::Millisecond),
|
||||
"s" => Ok(Precision::Second),
|
||||
"m" => Ok(Precision::Minute),
|
||||
"h" => Ok(Precision::Hour),
|
||||
unknown => TimePrecisionSnafu {
|
||||
name: unknown.to_string(),
|
||||
}
|
||||
.fail(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use api::v1::value::ValueData;
|
||||
|
||||
@@ -43,8 +43,8 @@ use session::context::Channel;
|
||||
|
||||
use self::auth_handler::{PgUserProviderSource, ZeroPidSecretKeyGenerator};
|
||||
use self::handler::DefaultQueryParser;
|
||||
use crate::query_handler::CopyInHandlerRef;
|
||||
use crate::query_handler::sql::ServerSqlQueryHandlerRef;
|
||||
use crate::query_handler::{CopyInHandlerRef, InfluxdbLineProtocolHandlerRef};
|
||||
|
||||
pub(crate) struct GreptimeDBStartupParameters {
|
||||
version: String,
|
||||
@@ -81,6 +81,11 @@ pub struct PostgresServerHandlerInner {
|
||||
query_handler: ServerSqlQueryHandlerRef,
|
||||
auth_source: Option<Arc<PgUserProviderSource>>,
|
||||
copy_in_handler: CopyInHandlerRef,
|
||||
/// Executes influxdb line-protocol batches flushed by a table-less
|
||||
/// COPY FROM STDIN — the same handler the HTTP write endpoints use.
|
||||
/// Absent on servers not wired for it; such connections reject the
|
||||
/// influxdb format when a copy starts.
|
||||
influxdb_handler: Option<InfluxdbLineProtocolHandlerRef>,
|
||||
force_tls: bool,
|
||||
auth_driver: AuthDriver<Arc<GreptimeDBStartupParameters>, UserInfoRef>,
|
||||
/// SCRAM selected; failures get the uniform metric label.
|
||||
@@ -99,6 +104,8 @@ pub struct PostgresServerHandlerInner {
|
||||
pub(crate) struct MakePostgresServerHandler {
|
||||
query_handler: ServerSqlQueryHandlerRef,
|
||||
copy_in_handler: CopyInHandlerRef,
|
||||
#[builder(default)]
|
||||
influxdb_handler: Option<InfluxdbLineProtocolHandlerRef>,
|
||||
user_provider: Option<UserProviderRef>,
|
||||
#[builder(default = "Arc::new(GreptimeDBStartupParameters::new())")]
|
||||
param_provider: Arc<GreptimeDBStartupParameters>,
|
||||
@@ -149,6 +156,7 @@ impl MakePostgresServerHandler {
|
||||
.clone()
|
||||
.map(|p| Arc::new(PgUserProviderSource::new(p))),
|
||||
copy_in_handler: self.copy_in_handler.clone(),
|
||||
influxdb_handler: self.influxdb_handler.clone(),
|
||||
force_tls: self.force_tls,
|
||||
auth_driver: AuthDriver::new(self.param_provider.clone())
|
||||
.with_pid_secret_key_generator(Arc::new(ZeroPidSecretKeyGenerator)),
|
||||
|
||||
@@ -12,58 +12,63 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! The COPY FROM STDIN codec framework.
|
||||
//! The COPY FROM STDIN formats.
|
||||
//!
|
||||
//! A *codec* binds one COPY data format to its implementation. Codecs are
|
||||
//! stateless strategies: they validate the options they accept at
|
||||
//! statement-parse time, describe which column types they can ingest, and
|
||||
//! create the stateful [`RecordParser`] per stream.
|
||||
//!
|
||||
//! Formats are not limited to PostgreSQL's own — GreptimeDB-specific
|
||||
//! formats (a line protocol, a JSON-lines dialect, ...) register exactly
|
||||
//! like `csv` does, and may define their own options through the open
|
||||
//! `WITH (...)` clause.
|
||||
//! [`CopyFormat`] is the closed, explicit set of supported formats — a
|
||||
//! small enum over the real implementations rather than a generic
|
||||
//! format framework. Each variant carries its validated options and
|
||||
//! its rules are stated where they apply: a variant's match arms in
|
||||
//! the copy lifecycle (see the parent module) decide whether a target
|
||||
//! table is required, how the `CopyData` bytes are consumed, and which
|
||||
//! existing ingestion pipeline completes the copy. Adding a format is
|
||||
//! a normal extension: a new variant plus its arms.
|
||||
//!
|
||||
//! # Parsing and conversion
|
||||
//!
|
||||
//! A [`RecordParser`] consumes raw `CopyData` bytes and emits complete,
|
||||
//! insertable rows: one [`ParsedRow`] per record, in the order of the
|
||||
//! targeted columns. Parsers validate record shape (field counts) and
|
||||
//! convert field values themselves — `csv` delegates both splitting and
|
||||
//! typed conversion to arrow-csv's incremental decoder (the engine
|
||||
//! behind `COPY ... FROM 'file.csv'`) and turns decoded batches into
|
||||
//! rows with the shared `api::helper::vectors_to_rows`. A future format
|
||||
//! that carries values as text (e.g. a line protocol) would reintroduce
|
||||
//! shared field-conversion helpers here; see the removed `text` codec in
|
||||
//! git history for the shape they had.
|
||||
//! Table-bound formats parse incrementally through a [`RecordParser`]:
|
||||
//! it consumes raw `CopyData` bytes and emits complete, insertable
|
||||
//! rows — one [`ParsedRow`] per record, in the order of the targeted
|
||||
//! columns. `csv` delegates splitting and typed conversion to
|
||||
//! arrow-csv's incremental decoder (the engine behind
|
||||
//! `COPY ... FROM 'file.csv'`) and turns decoded batches into rows
|
||||
//! with the shared `api::helper::vectors_to_rows`.
|
||||
//!
|
||||
//! Formats that delegate to an existing ingestion pipeline (the
|
||||
//! influxdb line protocol) do not parse here at all: the whole payload
|
||||
//! is buffered as one bounded request body and completed through that
|
||||
//! pipeline, so record boundaries and values stay with the pipeline's
|
||||
//! own parser.
|
||||
//!
|
||||
//! # Options
|
||||
//!
|
||||
//! The `WITH (...)` clause is open: every `KEY value` entry the client
|
||||
//! writes is collected into a [`CopyOptionSet`] (see `options`) regardless
|
||||
//! of whether any format understands it — the statement is parsed
|
||||
//! textually (see `parse`) precisely so options beyond sqlparser's COPY
|
||||
//! grammar can reach the codecs. A codec builder takes the options it
|
||||
//! understands (`take_string`, `take_single_byte`, `take_flag`, or raw
|
||||
//! `take_value` for codec-specific shapes) and rejects the rest with
|
||||
//! `reject_leftovers`, so a future format like
|
||||
//! `COPY t FROM STDIN WITH (FORMAT influxdb_line, precision 'ns')` only
|
||||
//! needs its own codec and registry entry.
|
||||
//!
|
||||
//! To add a format:
|
||||
//!
|
||||
//! 1. implement [`CopyInCodec`] for a config struct holding the format's
|
||||
//! validated options (see `csv::CsvCodec` for the example),
|
||||
//! 2. write a builder `fn(CopyOptionSet) -> PgWireResult<Arc<dyn
|
||||
//! CopyInCodec>>` that applies defaults and rejects options the format
|
||||
//! does not accept,
|
||||
//! 3. register the builder under every accepted `FORMAT` name (including
|
||||
//! aliases) in `REGISTERED_FORMATS` in the parent module.
|
||||
//! writes is collected into a [`CopyOptionSet`] (see `options`)
|
||||
//! regardless of whether any format understands it — the statement is
|
||||
//! parsed textually (see `parse`) precisely so options beyond
|
||||
//! sqlparser's COPY grammar can reach the formats. A format builder
|
||||
//! takes the options it understands (`take_string`,
|
||||
//! `take_single_byte`, `take_flag`, or raw `take_value` for
|
||||
//! format-specific shapes) and rejects the rest with
|
||||
//! `reject_leftovers`.
|
||||
|
||||
use datatypes::prelude::ConcreteDataType;
|
||||
use datatypes::schema::ColumnSchema;
|
||||
use pgwire::error::PgWireResult;
|
||||
|
||||
use crate::postgres::copy_in::csv::CsvCodec;
|
||||
use crate::postgres::copy_in::influxdb::InfluxdbOptions;
|
||||
|
||||
/// A resolved COPY FROM STDIN format with its validated options.
|
||||
#[derive(Debug, Clone)]
|
||||
pub(super) enum CopyFormat {
|
||||
/// Table-bound CSV: records are parsed incrementally against the
|
||||
/// targeted table's columns and inserted in batches.
|
||||
Csv(CsvCodec),
|
||||
/// Table-less influxdb line protocol: the whole payload is one
|
||||
/// bounded request body, completed through the line-protocol
|
||||
/// pipeline the HTTP write endpoints use (one COPY statement is one
|
||||
/// ingestion request; streaming ingest is not supported).
|
||||
Influxdb(InfluxdbOptions),
|
||||
}
|
||||
|
||||
/// A parsed, insertable row: one gRPC value per targeted column, in COPY
|
||||
/// field order. Every parser emits these directly, whatever mechanism it
|
||||
/// used to produce them.
|
||||
@@ -83,34 +88,3 @@ pub(super) trait RecordParser: Send {
|
||||
/// stream ended exactly at a record boundary.
|
||||
fn finish(&mut self) -> PgWireResult<Vec<ParsedRow>>;
|
||||
}
|
||||
|
||||
/// A COPY FROM STDIN data format implementation.
|
||||
///
|
||||
/// Implementations are shared per statement (hence `Send + Sync`) and must
|
||||
/// be stateless; per-stream state belongs to the [`RecordParser`] they
|
||||
/// create. Every method is tailored to the format: `check_column_type`
|
||||
/// declares the types the format can decode (csv is bounded by what
|
||||
/// arrow-csv supports).
|
||||
pub(super) trait CopyInCodec: Send + Sync + std::fmt::Debug {
|
||||
/// The canonical format name, used in error messages.
|
||||
fn name(&self) -> &'static str;
|
||||
/// The format code advertised in the `CopyInResponse` header: 0 when
|
||||
/// the client sends textual data (the default), 1 for binary.
|
||||
fn format_code(&self) -> i8 {
|
||||
0
|
||||
}
|
||||
/// Validates that a column of `data_type` can be ingested by this
|
||||
/// format.
|
||||
fn check_column_type(&self, data_type: &ConcreteDataType) -> PgWireResult<()>;
|
||||
/// Creates the stateful parser for one copy stream over the targeted
|
||||
/// columns (in COPY field order).
|
||||
///
|
||||
/// `timezone` is the session timezone (an IANA name or a UTC offset):
|
||||
/// formats that parse offset-free timestamp strings from text should
|
||||
/// interpret them in this zone, matching SQL INSERT.
|
||||
fn create_parser(
|
||||
&self,
|
||||
columns: &[ColumnSchema],
|
||||
timezone: &str,
|
||||
) -> PgWireResult<Box<dyn RecordParser + Send>>;
|
||||
}
|
||||
|
||||
@@ -40,12 +40,12 @@ use datatypes::schema::{ColumnSchema, Schema as GreptimeSchema};
|
||||
use datatypes::vectors::{BooleanVector, Helper, StringVector, Vector};
|
||||
use pgwire::error::{PgWireError, PgWireResult};
|
||||
|
||||
use crate::postgres::copy_in::codec::{CopyInCodec, ParsedRow, RecordParser};
|
||||
use crate::postgres::copy_in::codec::{CopyFormat, ParsedRow, RecordParser};
|
||||
use crate::postgres::copy_in::options::CopyOptionSet;
|
||||
use crate::postgres::copy_in::{COPY_IN_FLUSH_ROWS, bad_copy_data, invalid_text_repr, unsupported};
|
||||
|
||||
/// The validated `csv` format configuration.
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub(super) struct CsvCodec {
|
||||
delimiter: u8,
|
||||
quote: u8,
|
||||
@@ -54,7 +54,7 @@ pub(super) struct CsvCodec {
|
||||
}
|
||||
|
||||
/// Builds the CSV codec from the parsed options.
|
||||
pub(super) fn build_csv_codec(mut options: CopyOptionSet) -> PgWireResult<Arc<dyn CopyInCodec>> {
|
||||
pub(super) fn build_csv_codec(mut options: CopyOptionSet) -> PgWireResult<CopyFormat> {
|
||||
let delimiter = options.take_single_byte("DELIMITER")?.unwrap_or(b',');
|
||||
let quote = options.take_single_byte("QUOTE")?.unwrap_or(b'"');
|
||||
// In PostgreSQL the default escape character for CSV is the quote
|
||||
@@ -75,7 +75,7 @@ pub(super) fn build_csv_codec(mut options: CopyOptionSet) -> PgWireResult<Arc<dy
|
||||
if delimiter == quote {
|
||||
return Err(bad_copy_data("DELIMITER must not be equal to QUOTE"));
|
||||
}
|
||||
Ok(Arc::new(CsvCodec {
|
||||
Ok(CopyFormat::Csv(CsvCodec {
|
||||
delimiter,
|
||||
quote,
|
||||
escape,
|
||||
@@ -83,13 +83,9 @@ pub(super) fn build_csv_codec(mut options: CopyOptionSet) -> PgWireResult<Arc<dy
|
||||
}))
|
||||
}
|
||||
|
||||
impl CopyInCodec for CsvCodec {
|
||||
fn name(&self) -> &'static str {
|
||||
"csv"
|
||||
}
|
||||
|
||||
impl CsvCodec {
|
||||
/// The column types arrow-csv can decode against.
|
||||
fn check_column_type(&self, data_type: &ConcreteDataType) -> PgWireResult<()> {
|
||||
pub(super) fn check_column_type(&self, data_type: &ConcreteDataType) -> PgWireResult<()> {
|
||||
let supported = matches!(
|
||||
data_type,
|
||||
ConcreteDataType::Boolean(_)
|
||||
@@ -117,7 +113,7 @@ impl CopyInCodec for CsvCodec {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn create_parser(
|
||||
pub(super) fn create_parser(
|
||||
&self,
|
||||
columns: &[ColumnSchema],
|
||||
timezone: &str,
|
||||
@@ -292,9 +288,15 @@ mod tests {
|
||||
]
|
||||
}
|
||||
|
||||
fn build_codec(set: CopyOptionSet) -> CsvCodec {
|
||||
match build_csv_codec(set).unwrap() {
|
||||
CopyFormat::Csv(codec) => codec,
|
||||
other => panic!("expected csv format, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn parser() -> Box<dyn RecordParser + Send> {
|
||||
build_csv_codec(CopyOptionSet::default())
|
||||
.unwrap()
|
||||
build_codec(CopyOptionSet::default())
|
||||
.create_parser(&test_columns(), "UTC")
|
||||
.unwrap()
|
||||
}
|
||||
@@ -308,8 +310,7 @@ mod tests {
|
||||
|
||||
fn rows_with(mut set: CopyOptionSet) -> Box<dyn RecordParser + Send> {
|
||||
set.take_format().unwrap();
|
||||
build_csv_codec(set)
|
||||
.unwrap()
|
||||
build_codec(set)
|
||||
.create_parser(&test_columns(), "UTC")
|
||||
.unwrap()
|
||||
}
|
||||
@@ -329,8 +330,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_build_defaults() {
|
||||
let codec = build_csv_codec(CopyOptionSet::default()).unwrap();
|
||||
assert_eq!(codec.name(), "csv");
|
||||
let codec = build_codec(CopyOptionSet::default());
|
||||
assert!(matches!(codec, CsvCodec { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -368,7 +369,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_check_column_type() {
|
||||
let codec = build_csv_codec(CopyOptionSet::default()).unwrap();
|
||||
let codec = build_codec(CopyOptionSet::default());
|
||||
assert!(
|
||||
codec
|
||||
.check_column_type(&ConcreteDataType::json_datatype())
|
||||
@@ -524,8 +525,7 @@ mod tests {
|
||||
.into_bytes();
|
||||
|
||||
let check = |chunk: usize| {
|
||||
let mut parser = build_csv_codec(CopyOptionSet::default())
|
||||
.unwrap()
|
||||
let mut parser = build_codec(CopyOptionSet::default())
|
||||
.create_parser(&sweep_columns, "UTC")
|
||||
.unwrap();
|
||||
let mut ids: Vec<i32> = Vec::new();
|
||||
@@ -560,8 +560,7 @@ mod tests {
|
||||
check(chunk);
|
||||
let mut shifted = payload.clone();
|
||||
shifted.drain(..37);
|
||||
let mut parser = build_csv_codec(CopyOptionSet::default())
|
||||
.unwrap()
|
||||
let mut parser = build_codec(CopyOptionSet::default())
|
||||
.create_parser(&sweep_columns, "UTC")
|
||||
.unwrap();
|
||||
let mut count = 0usize;
|
||||
@@ -585,8 +584,7 @@ mod tests {
|
||||
false,
|
||||
),
|
||||
];
|
||||
let mut parser = build_csv_codec(CopyOptionSet::default())
|
||||
.unwrap()
|
||||
let mut parser = build_codec(CopyOptionSet::default())
|
||||
.create_parser(&columns, "UTC")
|
||||
.unwrap();
|
||||
let rows = feed_all(
|
||||
@@ -628,8 +626,7 @@ mod tests {
|
||||
false,
|
||||
),
|
||||
];
|
||||
let mut parser = build_csv_codec(CopyOptionSet::default())
|
||||
.unwrap()
|
||||
let mut parser = build_codec(CopyOptionSet::default())
|
||||
.create_parser(&columns, "UTC")
|
||||
.unwrap();
|
||||
parser.feed(b"maybe,2024-01-01 00:00:00\n").unwrap();
|
||||
@@ -656,8 +653,7 @@ mod tests {
|
||||
false,
|
||||
),
|
||||
];
|
||||
let mut parser = build_csv_codec(CopyOptionSet::default())
|
||||
.unwrap()
|
||||
let mut parser = build_codec(CopyOptionSet::default())
|
||||
.create_parser(&columns, "Asia/Shanghai")
|
||||
.unwrap();
|
||||
let rows = feed_all(
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// 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.
|
||||
|
||||
//! The `influxdb` line protocol format for COPY FROM STDIN.
|
||||
//!
|
||||
//! `COPY FROM STDIN WITH (FORMAT influxdb, precision 'ns')` ingests
|
||||
//! [InfluxDB line protocol](https://docs.influxdata.com/influxdb/v1.8/write_protocols/line_protocol_reference/)
|
||||
//! text. The format is table-less — each line names its own measurement
|
||||
//! — and does not parse here at all: the COPY layer buffers the whole
|
||||
//! payload (bounded by [`crate::postgres::copy_in::COPY_IN_MAX_PAYLOAD_BYTES`])
|
||||
//! and completes the copy by handing it to the frontend's line-protocol
|
||||
//! write pipeline as one body, exactly like the HTTP
|
||||
//! `/v1/influxdb/v1/write` endpoint receives one request body:
|
||||
//! conversion, permissions, interceptors, timestamp alignment, merge
|
||||
//! mode and inserts are the same path, and record boundaries (including
|
||||
//! newlines inside quoted field values and after escapes) are decided
|
||||
//! by the line-protocol parser alone — the COPY layer never splits
|
||||
//! records.
|
||||
//!
|
||||
//! One COPY statement is therefore one bounded ingestion request; a
|
||||
//! larger import is multiple COPY statements.
|
||||
//!
|
||||
//! The `precision` option carries the same values as the HTTP
|
||||
//! `precision` query parameter (`ns`, `us`, `ms`, `s`, ...), defaults to
|
||||
//! nanoseconds, and is resolved by the shared `parse_time_precision`.
|
||||
|
||||
use common_grpc::precision::Precision;
|
||||
use pgwire::error::PgWireResult;
|
||||
|
||||
use crate::postgres::copy_in::bad_copy_data;
|
||||
use crate::postgres::copy_in::codec::CopyFormat;
|
||||
use crate::postgres::copy_in::options::CopyOptionSet;
|
||||
|
||||
/// The format's validated options. A `None` precision carries the
|
||||
/// pipeline's default (nanoseconds), exactly like an HTTP write without
|
||||
/// a `precision` parameter.
|
||||
#[derive(Debug, Clone)]
|
||||
pub(super) struct InfluxdbOptions {
|
||||
pub(super) precision: Option<Precision>,
|
||||
}
|
||||
|
||||
pub(super) fn build_influxdb_codec(mut options: CopyOptionSet) -> PgWireResult<CopyFormat> {
|
||||
let precision = match options.take_string("precision")? {
|
||||
Some(value) => Some(
|
||||
crate::influxdb::parse_time_precision(&value)
|
||||
.map_err(|e| bad_copy_data(format!("invalid precision option: {e}")))?,
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
options.reject_leftovers("influxdb")?;
|
||||
Ok(CopyFormat::Influxdb(InfluxdbOptions { precision }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::postgres::copy_in::options::CopyOptionValue;
|
||||
|
||||
#[test]
|
||||
fn test_builder_options() {
|
||||
let format = build_influxdb_codec(CopyOptionSet::default()).unwrap();
|
||||
assert!(matches!(format, CopyFormat::Influxdb(_)));
|
||||
assert!(matches!(format, CopyFormat::Influxdb(_)));
|
||||
|
||||
let mut set = CopyOptionSet::default();
|
||||
set.insert("precision".into(), CopyOptionValue::String("ms".into()))
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
build_influxdb_codec(set).unwrap(),
|
||||
CopyFormat::Influxdb(InfluxdbOptions {
|
||||
precision: Some(Precision::Millisecond)
|
||||
})
|
||||
));
|
||||
|
||||
let mut set = CopyOptionSet::default();
|
||||
set.insert("precision".into(), CopyOptionValue::String("bogus".into()))
|
||||
.unwrap();
|
||||
assert!(build_influxdb_codec(set).is_err());
|
||||
|
||||
let mut set = CopyOptionSet::default();
|
||||
set.insert("unknown".into(), CopyOptionValue::Flag).unwrap();
|
||||
assert!(build_influxdb_codec(set).is_err());
|
||||
}
|
||||
}
|
||||
@@ -21,38 +21,42 @@
|
||||
//! the data stream incrementally and flushes it into the query handler as
|
||||
//! [`RowInsertRequests`] batches.
|
||||
//!
|
||||
//! # Format framework
|
||||
//! # Formats
|
||||
//!
|
||||
//! Each COPY data format is implemented as a [`codec::CopyInCodec`]: a
|
||||
//! stateless strategy that validates its options at statement-parse time,
|
||||
//! describes the column types it can ingest, and creates the stateful
|
||||
//! record parser for one stream. Formats register a builder under every
|
||||
//! accepted `FORMAT` name in [`REGISTERED_FORMATS`] — `csv` is the only
|
||||
//! implemented format today; PostgreSQL's `text`/`binary` and
|
||||
//! GreptimeDB-specific formats alike can be added the same way. See the
|
||||
//! `codec` module docs.
|
||||
//! The supported formats are the explicit [`codec::CopyFormat`] enum —
|
||||
//! `csv` (table-bound, incremental row parsing) and `influxdb`
|
||||
//! (table-less, one bounded whole-payload request). Each format states
|
||||
//! its own target rule and ingestion shape in the match arms of the
|
||||
//! copy lifecycle below; adding a format is a new variant plus its
|
||||
//! arms. Builders resolve a `FORMAT` name (and its aliases) through
|
||||
//! [`REGISTERED_FORMATS`]. See the `codec` module docs.
|
||||
|
||||
mod codec;
|
||||
mod csv;
|
||||
mod influxdb;
|
||||
mod options;
|
||||
mod parse;
|
||||
|
||||
use std::fmt::Debug;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::influxdb::InfluxdbRequest;
|
||||
use api::helper::ColumnDataTypeWrapper;
|
||||
use api::v1::column_def::options_from_column_schema;
|
||||
use api::v1::{
|
||||
Row as GrpcRow, RowInsertRequest, RowInsertRequests, Rows as GrpcRows, SemanticType,
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use codec::{CopyInCodec, RecordParser};
|
||||
use codec::{CopyFormat, RecordParser};
|
||||
use common_grpc::precision::Precision;
|
||||
use common_query::OutputData;
|
||||
use common_telemetry::{info, warn};
|
||||
use csv::CsvCodec;
|
||||
use datafusion::sql::sqlparser::ast::{CopyTarget, Statement as SqlParserStatement};
|
||||
use datatypes::data_type::DataType;
|
||||
use datatypes::schema::{ColumnSchema, SchemaRef};
|
||||
use futures::{Sink, SinkExt, stream};
|
||||
use influxdb::InfluxdbOptions;
|
||||
use pgwire::api::copy::CopyHandler;
|
||||
use pgwire::api::results::{CopyResponse, Response, Tag};
|
||||
use pgwire::api::{ClientInfo, PgWireConnectionState};
|
||||
@@ -80,38 +84,43 @@ use crate::postgres::utils::convert_err;
|
||||
/// the per-batch fixed costs negligible.
|
||||
pub(crate) const COPY_IN_FLUSH_ROWS: usize = 32768;
|
||||
|
||||
/// Builds a codec from the format-neutral option set.
|
||||
type CodecBuilder = fn(options::CopyOptionSet) -> PgWireResult<Arc<dyn CopyInCodec>>;
|
||||
/// Upper bound of an influxdb COPY FROM STDIN payload. One COPY
|
||||
/// statement is one bounded ingestion request (the whole payload is
|
||||
/// buffered like one HTTP write body); a larger import is multiple COPY
|
||||
/// statements. Streaming ingest may arrive later, with framing owned by
|
||||
/// the shared line-protocol parser rather than the COPY layer.
|
||||
pub(crate) const COPY_IN_MAX_PAYLOAD_BYTES: usize = 64 * 1024 * 1024;
|
||||
|
||||
/// Builds a format from the format-neutral option set.
|
||||
type FormatBuilder = fn(options::CopyOptionSet) -> PgWireResult<CopyFormat>;
|
||||
|
||||
/// The registered COPY FROM STDIN formats: accepted `FORMAT` name to
|
||||
/// builder. `csv` is the only implemented format; the others are
|
||||
/// registered so they report a clear "not supported yet" instead of an
|
||||
/// unknown-format error.
|
||||
const REGISTERED_FORMATS: &[(&str, CodecBuilder)] = &[
|
||||
const REGISTERED_FORMATS: &[(&str, FormatBuilder)] = &[
|
||||
("csv", csv::build_csv_codec),
|
||||
("influxdb", influxdb::build_influxdb_codec),
|
||||
("influxdb_line", influxdb::build_influxdb_codec),
|
||||
("text", build_unimplemented_text_codec),
|
||||
("txt", build_unimplemented_text_codec),
|
||||
("binary", build_unimplemented_binary_codec),
|
||||
];
|
||||
|
||||
fn build_unimplemented_text_codec(
|
||||
_options: options::CopyOptionSet,
|
||||
) -> PgWireResult<Arc<dyn CopyInCodec>> {
|
||||
fn build_unimplemented_text_codec(_options: options::CopyOptionSet) -> PgWireResult<CopyFormat> {
|
||||
Err(unsupported(
|
||||
"the text format is not supported yet; use WITH (FORMAT csv)",
|
||||
))
|
||||
}
|
||||
|
||||
fn build_unimplemented_binary_codec(
|
||||
_options: options::CopyOptionSet,
|
||||
) -> PgWireResult<Arc<dyn CopyInCodec>> {
|
||||
fn build_unimplemented_binary_codec(_options: options::CopyOptionSet) -> PgWireResult<CopyFormat> {
|
||||
Err(unsupported(
|
||||
"COPY FROM STDIN WITH (FORMAT binary) is not supported yet",
|
||||
))
|
||||
}
|
||||
|
||||
/// Resolves the format codec from the parsed options.
|
||||
fn resolve_codec(options: &mut options::CopyOptionSet) -> PgWireResult<Arc<dyn CopyInCodec>> {
|
||||
/// Resolves the format from the parsed options.
|
||||
fn resolve_format(options: &mut options::CopyOptionSet) -> PgWireResult<CopyFormat> {
|
||||
let name = options.take_format()?.ok_or_else(|| {
|
||||
unsupported(
|
||||
"COPY FROM STDIN requires an explicit format in this version; use WITH (FORMAT csv)",
|
||||
@@ -133,15 +142,15 @@ pub(crate) struct CopyFromStdin {
|
||||
table: Vec<String>,
|
||||
/// Requested column list; empty means all columns in table order.
|
||||
columns: Vec<String>,
|
||||
/// The resolved format codec, validated and ready to run.
|
||||
codec: Arc<dyn CopyInCodec>,
|
||||
/// The resolved format with its validated options.
|
||||
format: CopyFormat,
|
||||
}
|
||||
|
||||
fn copy_in_error(code: PgErrorCode, message: impl Into<String>) -> PgWireError {
|
||||
PgWireError::UserError(Box::new(code.to_err_info(message.into())))
|
||||
}
|
||||
|
||||
fn unsupported(message: impl Into<String>) -> PgWireError {
|
||||
pub(super) fn unsupported(message: impl Into<String>) -> PgWireError {
|
||||
copy_in_error(PgErrorCode::Ec0A000, message)
|
||||
}
|
||||
|
||||
@@ -174,11 +183,11 @@ pub(crate) fn copy_from_stdin_from_sql(sql: &str) -> PgWireResult<Option<CopyFro
|
||||
parse::CopyInScan::CopyIn(raw) => raw,
|
||||
};
|
||||
let mut option_set = raw.options;
|
||||
let codec = resolve_codec(&mut option_set)?;
|
||||
let format = resolve_format(&mut option_set)?;
|
||||
Ok(Some(CopyFromStdin {
|
||||
table: raw.table,
|
||||
columns: raw.columns,
|
||||
codec,
|
||||
format,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -221,26 +230,49 @@ fn resolve_table_name(
|
||||
}
|
||||
|
||||
/// Per-connection state of an in-progress COPY FROM STDIN.
|
||||
///
|
||||
/// The payload shape follows the codec: table-bound formats (csv) parse
|
||||
/// records into rows against the targeted table's columns; table-less
|
||||
/// formats (influxdb line protocol) split the stream into complete
|
||||
/// lines that each route to their own measurement, and flush through
|
||||
/// the handler's line-protocol pipeline — the same one the HTTP write
|
||||
/// endpoint uses.
|
||||
pub(crate) struct CopyInState {
|
||||
query_ctx: QueryContextRef,
|
||||
/// The gRPC column schemas of the targeted columns. Cloned into each
|
||||
/// flushed batch: `Rows.schema` is an owned `Vec` in the proto
|
||||
/// request, so one copy per request is inherent.
|
||||
grpc_schema: Vec<api::v1::ColumnSchema>,
|
||||
table_name: String,
|
||||
parser: Box<dyn RecordParser + Send>,
|
||||
payload: Payload,
|
||||
/// The resolved codec's name, for logging.
|
||||
codec_name: &'static str,
|
||||
/// The wire format code of the resolved codec.
|
||||
codec_format_code: i8,
|
||||
/// Parsed rows not yet flushed to the handler.
|
||||
rows: Vec<GrpcRow>,
|
||||
rows_written: u64,
|
||||
}
|
||||
|
||||
enum Payload {
|
||||
/// Table-bound rows: parsed against `grpc_schema` and flushed to
|
||||
/// `table_name` via `copy_in_insert`. The schema is cloned into each
|
||||
/// flushed batch: `Rows.schema` is an owned `Vec` in the proto
|
||||
/// request, so one copy per request is inherent.
|
||||
Table {
|
||||
grpc_schema: Vec<api::v1::ColumnSchema>,
|
||||
table_name: String,
|
||||
parser: Box<dyn RecordParser + Send>,
|
||||
/// Parsed rows not yet flushed to the handler.
|
||||
rows: Vec<GrpcRow>,
|
||||
},
|
||||
/// The whole buffered influxdb line-protocol payload with its
|
||||
/// request precision. One COPY statement is one bounded ingestion
|
||||
/// request, buffered until `CopyDone` — exactly like one HTTP write
|
||||
/// body — and record boundaries belong to the line-protocol parser,
|
||||
/// never to the COPY layer.
|
||||
Influxdb {
|
||||
data: Vec<u8>,
|
||||
precision: Option<Precision>,
|
||||
},
|
||||
}
|
||||
|
||||
impl CopyInState {
|
||||
fn new(
|
||||
codec: Arc<dyn CopyInCodec>,
|
||||
codec: &CsvCodec,
|
||||
columns: Vec<String>,
|
||||
table_info: Arc<TableInfo>,
|
||||
query_ctx: QueryContextRef,
|
||||
@@ -249,7 +281,7 @@ impl CopyInState {
|
||||
let schema = table_info.meta.schema.clone();
|
||||
let timestamp_index = schema.timestamp_index();
|
||||
|
||||
let columns = resolve_columns(codec.as_ref(), columns, &schema, &table_info)?;
|
||||
let columns = resolve_columns(codec, columns, &schema, &table_info)?;
|
||||
if let Some(ts_index) = timestamp_index {
|
||||
let ts_column = &schema.column_schemas()[ts_index];
|
||||
if !columns.iter().any(|column| column.name == ts_column.name) {
|
||||
@@ -268,58 +300,122 @@ impl CopyInState {
|
||||
|
||||
Ok(Self {
|
||||
query_ctx,
|
||||
grpc_schema,
|
||||
table_name,
|
||||
parser,
|
||||
codec_name: codec.name(),
|
||||
codec_format_code: codec.format_code(),
|
||||
rows: Vec::with_capacity(COPY_IN_FLUSH_ROWS),
|
||||
payload: Payload::Table {
|
||||
grpc_schema,
|
||||
table_name,
|
||||
parser,
|
||||
rows: Vec::with_capacity(COPY_IN_FLUSH_ROWS),
|
||||
},
|
||||
codec_name: "csv",
|
||||
codec_format_code: 0,
|
||||
rows_written: 0,
|
||||
})
|
||||
}
|
||||
|
||||
/// State for the influxdb format: the whole payload is buffered and
|
||||
/// completed once at `CopyDone` through the line-protocol pipeline.
|
||||
fn new_influxdb(options: &InfluxdbOptions, query_ctx: QueryContextRef) -> Self {
|
||||
Self {
|
||||
query_ctx,
|
||||
payload: Payload::Influxdb {
|
||||
data: Vec::new(),
|
||||
precision: options.precision,
|
||||
},
|
||||
codec_name: "influxdb",
|
||||
codec_format_code: 0,
|
||||
rows_written: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The wire format code advertised to the client.
|
||||
pub(crate) fn format_code(&self) -> i8 {
|
||||
self.codec_format_code
|
||||
}
|
||||
|
||||
/// Feeds a `CopyData` chunk into the parser and buffers parsed rows.
|
||||
/// Feeds a `CopyData` chunk into the parser and buffers parsed rows
|
||||
/// (csv) or payload bytes (influxdb).
|
||||
fn feed(&mut self, data: &[u8]) -> PgWireResult<()> {
|
||||
self.rows.extend(self.parser.feed(data)?);
|
||||
match &mut self.payload {
|
||||
Payload::Table { parser, rows, .. } => rows.extend(parser.feed(data)?),
|
||||
Payload::Influxdb { data: buffered, .. } => {
|
||||
if buffered.len() + data.len() > COPY_IN_MAX_PAYLOAD_BYTES {
|
||||
return Err(bad_copy_data(format!(
|
||||
"COPY FROM STDIN payload exceeds the {} limit; split the import into multiple COPY statements",
|
||||
COPY_IN_MAX_PAYLOAD_BYTES
|
||||
)));
|
||||
}
|
||||
buffered.extend_from_slice(data);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Parses the buffered tail at `CopyDone`; a final record without a
|
||||
/// trailing newline is accepted.
|
||||
fn finish(&mut self) -> PgWireResult<()> {
|
||||
self.rows.extend(self.parser.finish()?);
|
||||
match &mut self.payload {
|
||||
Payload::Table { parser, rows, .. } => rows.extend(parser.finish()?),
|
||||
// The whole payload is one request body; nothing to finalize.
|
||||
Payload::Influxdb { .. } => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn should_flush(&self) -> bool {
|
||||
self.rows.len() >= COPY_IN_FLUSH_ROWS
|
||||
match &self.payload {
|
||||
Payload::Table { rows, .. } => rows.len() >= COPY_IN_FLUSH_ROWS,
|
||||
// Completed once at CopyDone, not mid-stream.
|
||||
Payload::Influxdb { .. } => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes the buffered rows as an insert request, if any.
|
||||
fn take_requests(&mut self) -> Option<RowInsertRequests> {
|
||||
if self.rows.is_empty() {
|
||||
let Payload::Table {
|
||||
grpc_schema,
|
||||
table_name,
|
||||
rows,
|
||||
..
|
||||
} = &mut self.payload
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
if rows.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let rows = GrpcRows {
|
||||
schema: self.grpc_schema.clone(),
|
||||
rows: std::mem::take(&mut self.rows),
|
||||
schema: grpc_schema.clone(),
|
||||
rows: std::mem::take(rows),
|
||||
};
|
||||
Some(RowInsertRequests {
|
||||
inserts: vec![RowInsertRequest {
|
||||
table_name: self.table_name.clone(),
|
||||
table_name: table_name.clone(),
|
||||
rows: Some(rows),
|
||||
}],
|
||||
})
|
||||
}
|
||||
|
||||
/// Takes the buffered payload as one line-protocol request body, if
|
||||
/// any — the same bytes an HTTP write of the same records would
|
||||
/// carry.
|
||||
fn take_lines(&mut self) -> PgWireResult<Option<InfluxdbRequest>> {
|
||||
let Payload::Influxdb { data, precision } = &mut self.payload else {
|
||||
return Ok(None);
|
||||
};
|
||||
if data.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let lines = String::from_utf8(std::mem::take(data))
|
||||
.map_err(|e| bad_copy_data(format!("COPY FROM STDIN data is not valid UTF-8: {e}")))?;
|
||||
Ok(Some(InfluxdbRequest {
|
||||
precision: *precision,
|
||||
lines,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_columns(
|
||||
codec: &dyn CopyInCodec,
|
||||
codec: &CsvCodec,
|
||||
columns: Vec<String>,
|
||||
schema: &SchemaRef,
|
||||
table_info: &Arc<TableInfo>,
|
||||
@@ -411,27 +507,63 @@ impl PostgresServerHandlerInner {
|
||||
// pending-rows batcher like SQL INSERT when it is enabled for
|
||||
// this connection.
|
||||
let query_ctx = self.new_query_context();
|
||||
let (catalog, schema, table) = resolve_table_name(&query_ctx, &stmt.table)?;
|
||||
|
||||
let Some(table_info) = self
|
||||
.copy_in_handler
|
||||
.copy_in_table(&catalog, &schema, &table, query_ctx.clone())
|
||||
.await
|
||||
.map_err(convert_err)?
|
||||
else {
|
||||
return Err(copy_in_error(
|
||||
PgErrorCode::Ec42P01,
|
||||
format!("relation \"{}\" does not exist", stmt.table.join(".")),
|
||||
));
|
||||
// Each format states its own target rule and ingestion shape
|
||||
// explicitly.
|
||||
let state = match &stmt.format {
|
||||
// csv requires a target table: records are parsed against
|
||||
// its columns and inserted in batches.
|
||||
CopyFormat::Csv(codec) => {
|
||||
if stmt.table.is_empty() {
|
||||
return Err(unsupported(
|
||||
"format csv requires a table: COPY tbl [(cols)] FROM STDIN WITH (FORMAT csv)",
|
||||
));
|
||||
}
|
||||
let (catalog, schema, table) = resolve_table_name(&query_ctx, &stmt.table)?;
|
||||
|
||||
let Some(table_info) = self
|
||||
.copy_in_handler
|
||||
.copy_in_table(&catalog, &schema, &table, query_ctx.clone())
|
||||
.await
|
||||
.map_err(convert_err)?
|
||||
else {
|
||||
return Err(copy_in_error(
|
||||
PgErrorCode::Ec42P01,
|
||||
format!("relation \"{}\" does not exist", stmt.table.join(".")),
|
||||
));
|
||||
};
|
||||
|
||||
// The insert path resolves the bare table name against the
|
||||
// query context, so point the context at the resolved
|
||||
// catalog and schema when the COPY target is qualified.
|
||||
let query_ctx = adjust_query_context(query_ctx, &catalog, &schema);
|
||||
|
||||
CopyInState::new(codec, stmt.columns, table_info, query_ctx, table)?
|
||||
}
|
||||
// influxdb forbids a target table — each line names its own
|
||||
// measurement — and completes through the line-protocol
|
||||
// pipeline the HTTP write endpoints use; the server must be
|
||||
// wired for it.
|
||||
CopyFormat::Influxdb(options) => {
|
||||
if !stmt.table.is_empty() {
|
||||
return Err(unsupported(format!(
|
||||
"format influxdb routes each record to its own table; \"COPY {} FROM STDIN\" must not name one",
|
||||
stmt.table.join(".")
|
||||
)));
|
||||
}
|
||||
if self.influxdb_handler.is_none() {
|
||||
return Err(unsupported(
|
||||
"this server is not wired for the influxdb line protocol format",
|
||||
));
|
||||
}
|
||||
CopyInState::new_influxdb(options, query_ctx)
|
||||
}
|
||||
};
|
||||
let num_columns = match &state.payload {
|
||||
Payload::Table { grpc_schema, .. } => grpc_schema.len(),
|
||||
// No fixed column set: the format routes per record.
|
||||
Payload::Influxdb { .. } => 0,
|
||||
};
|
||||
|
||||
// The insert path resolves the bare table name against the query
|
||||
// context, so point the context at the resolved catalog and schema
|
||||
// when the COPY target is qualified.
|
||||
let query_ctx = adjust_query_context(query_ctx, &catalog, &schema);
|
||||
|
||||
let state = CopyInState::new(stmt.codec, stmt.columns, table_info, query_ctx, table)?;
|
||||
let num_columns = state.grpc_schema.len();
|
||||
let format_code = state.format_code();
|
||||
|
||||
*self.copy_in_state.lock().await = Some(state);
|
||||
@@ -443,13 +575,34 @@ impl PostgresServerHandlerInner {
|
||||
)))
|
||||
}
|
||||
|
||||
/// Flushes buffered rows of an in-progress copy. Returns the number of
|
||||
/// rows written by the flushed batch.
|
||||
/// Flushes the buffered payload of an in-progress copy. Returns the
|
||||
/// number of rows written by the flushed batch.
|
||||
async fn flush_copy_in(&self, state: &mut CopyInState) -> PgWireResult<u64> {
|
||||
let query_ctx = state.query_ctx.clone();
|
||||
// The buffered influxdb payload is completed through the
|
||||
// line-protocol pipeline — the same handler the HTTP write
|
||||
// endpoints use, so conversion, permissions, interceptors,
|
||||
// timestamp alignment and inserts are identical to an HTTP
|
||||
// write of the same bytes. The context stays this connection's
|
||||
// postgres context.
|
||||
if let Some(request) = state.take_lines()? {
|
||||
let Some(influxdb_handler) = &self.influxdb_handler else {
|
||||
return Err(unsupported(
|
||||
"this server is not wired for the influxdb line protocol format",
|
||||
));
|
||||
};
|
||||
let output = influxdb_handler
|
||||
.exec(request, query_ctx)
|
||||
.await
|
||||
.map_err(convert_err)?;
|
||||
return match output.data {
|
||||
OutputData::AffectedRows(rows) => Ok(rows as u64),
|
||||
OutputData::RecordBatches(_) | OutputData::Stream(_) => Ok(0),
|
||||
};
|
||||
}
|
||||
let Some(requests) = state.take_requests() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let query_ctx = state.query_ctx.clone();
|
||||
let output = self
|
||||
.copy_in_handler
|
||||
.copy_in_insert(requests, query_ctx)
|
||||
@@ -587,8 +740,8 @@ mod tests {
|
||||
.unwrap();
|
||||
assert_eq!(copy.table, vec!["t"]);
|
||||
assert!(copy.columns.is_empty());
|
||||
assert_eq!(copy.codec.name(), "csv");
|
||||
assert_eq!(copy.codec.format_code(), 0);
|
||||
assert!(matches!(copy.format, CopyFormat::Csv(_)));
|
||||
// Both formats are textual: format code 0.
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -599,7 +752,7 @@ mod tests {
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(copy.columns, vec!["a", "b"]);
|
||||
assert_eq!(copy.codec.name(), "csv");
|
||||
assert!(matches!(copy.format, CopyFormat::Csv(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -32,7 +32,7 @@ use pgwire::error::PgWireResult;
|
||||
use crate::postgres::copy_in::options::{CopyOptionSet, CopyOptionValue};
|
||||
use crate::postgres::copy_in::{bad_copy_data, copy_in_must_run_alone_error};
|
||||
|
||||
/// A scanned `COPY tbl [(cols)] FROM STDIN [WITH (...)]` statement.
|
||||
/// A scanned `COPY [tbl [(cols)]] FROM STDIN [WITH (...)]` statement.
|
||||
///
|
||||
/// Unquoted identifiers are folded to lowercase and quoted ones keep their
|
||||
/// case (`COPY Metrics` addresses the same table as `CREATE TABLE Metrics`,
|
||||
@@ -41,7 +41,9 @@ use crate::postgres::copy_in::{bad_copy_data, copy_in_must_run_alone_error};
|
||||
#[derive(Debug)]
|
||||
pub(super) struct RawCopyFromStdin {
|
||||
/// Table name parts, as written (`t`, `schema.t`,
|
||||
/// `catalog.schema.t`); quoted names keep their case.
|
||||
/// `catalog.schema.t`); quoted names keep their case. Empty for
|
||||
/// table-less formats whose records carry their own routing (e.g.
|
||||
/// the influxdb line protocol names its measurement per line).
|
||||
pub(super) table: Vec<String>,
|
||||
/// Requested column list; empty means all columns in table order.
|
||||
pub(super) columns: Vec<String>,
|
||||
@@ -89,13 +91,27 @@ pub(super) fn scan_copy_from_stdin(sql: &str) -> PgWireResult<CopyInScan> {
|
||||
return Ok(CopyInScan::NotCopyIn);
|
||||
}
|
||||
|
||||
let table = match parse_object_name(&mut cursor) {
|
||||
Some(table) => table,
|
||||
None => return Ok(CopyInScan::NotCopyIn),
|
||||
// Table-less statements (`COPY FROM STDIN WITH (FORMAT influxdb) ...`)
|
||||
// are table-format specific: the codec decides whether a missing
|
||||
// table is legal. An unquoted `FROM` cannot be a table name (SQL
|
||||
// would require quoting it), so peek instead of letting the
|
||||
// identifier parser swallow the keyword. A column list without a
|
||||
// table is not.
|
||||
let table = if cursor.peek_keyword("from") {
|
||||
Vec::new()
|
||||
} else {
|
||||
match parse_object_name(&mut cursor) {
|
||||
Some(table) => table,
|
||||
None => return Ok(CopyInScan::NotCopyIn),
|
||||
}
|
||||
};
|
||||
let columns = match parse_column_list(&mut cursor) {
|
||||
Some(columns) => columns,
|
||||
None => return Ok(CopyInScan::NotCopyIn),
|
||||
let columns = if table.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
match parse_column_list(&mut cursor) {
|
||||
Some(columns) => columns,
|
||||
None => return Ok(CopyInScan::NotCopyIn),
|
||||
}
|
||||
};
|
||||
|
||||
if !cursor.take_keyword("from") || !cursor.take_keyword("stdin") {
|
||||
@@ -151,16 +167,20 @@ impl<'a> Tokens<'a> {
|
||||
|
||||
/// Consumes the next token if it is the unquoted keyword `keyword`.
|
||||
fn take_keyword(&mut self, keyword: &str) -> bool {
|
||||
match self.peek() {
|
||||
Some(Token::Word(w))
|
||||
if w.quote_style.is_none() && w.value.eq_ignore_ascii_case(keyword) =>
|
||||
{
|
||||
self.pos += 1;
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
if self.peek_keyword(keyword) {
|
||||
self.pos += 1;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the next token is the unquoted keyword `keyword`, without
|
||||
/// consuming it.
|
||||
fn peek_keyword(&self, keyword: &str) -> bool {
|
||||
matches!(self.tokens.get(self.pos), Some(Token::Word(w))
|
||||
if w.quote_style.is_none() && w.value.eq_ignore_ascii_case(keyword))
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the identifier with the SQL parser's canonicalization: quoted
|
||||
@@ -275,6 +295,27 @@ mod tests {
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scan_tableless() {
|
||||
// Table-less statements: the codec decides whether a missing
|
||||
// table is legal (the influxdb line protocol names its
|
||||
// measurement per line).
|
||||
let raw = scan("COPY FROM STDIN WITH (FORMAT influxdb, precision 'ns')")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(raw.table.is_empty());
|
||||
assert!(raw.columns.is_empty());
|
||||
|
||||
let raw = scan("copy from stdin (format influxdb)").unwrap().unwrap();
|
||||
assert!(raw.table.is_empty());
|
||||
|
||||
// A column list without a table is not a copy-in statement.
|
||||
assert!(scan("COPY (a, b) FROM STDIN").unwrap().is_none());
|
||||
// COPY OUT and file COPY are unaffected.
|
||||
assert!(scan("COPY (SELECT 1) TO STDOUT").unwrap().is_none());
|
||||
assert!(scan("COPY t FROM '/tmp/x.csv'").unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scan_basic() {
|
||||
let raw = scan("COPY t FROM STDIN").unwrap().unwrap();
|
||||
|
||||
@@ -30,6 +30,7 @@ use tokio_rustls::TlsAcceptor;
|
||||
use crate::error::Result;
|
||||
use crate::postgres::{MakePostgresServerHandler, MakePostgresServerHandlerBuilder};
|
||||
use crate::query_handler::CopyInHandlerRef;
|
||||
use crate::query_handler::InfluxdbLineProtocolHandlerRef;
|
||||
use crate::query_handler::sql::ServerSqlQueryHandlerRef;
|
||||
use crate::server::{AbortableStream, BaseTcpServer, Server};
|
||||
use crate::tls::ReloadableTlsServerConfig;
|
||||
@@ -40,6 +41,7 @@ pub struct PostgresServer {
|
||||
tls_server_config: Arc<ReloadableTlsServerConfig>,
|
||||
keep_alive_secs: u64,
|
||||
batching_enabled: bool,
|
||||
influxdb_handler: Option<InfluxdbLineProtocolHandlerRef>,
|
||||
bind_addr: Option<SocketAddr>,
|
||||
process_manager: Option<ProcessManagerRef>,
|
||||
}
|
||||
@@ -77,6 +79,7 @@ impl PostgresServer {
|
||||
tls_server_config,
|
||||
keep_alive_secs,
|
||||
batching_enabled: false,
|
||||
influxdb_handler: None,
|
||||
bind_addr: None,
|
||||
process_manager,
|
||||
}
|
||||
@@ -88,12 +91,34 @@ impl PostgresServer {
|
||||
self
|
||||
}
|
||||
|
||||
/// Wires the influxdb line-protocol handler used by table-less
|
||||
/// `COPY FROM STDIN WITH (FORMAT influxdb)` flushes — the same
|
||||
/// handler the HTTP influxdb write endpoints use, so a flushed batch
|
||||
/// runs through the identical pipeline.
|
||||
pub fn with_influxdb_handler(mut self, handler: InfluxdbLineProtocolHandlerRef) -> Self {
|
||||
self.influxdb_handler = Some(handler);
|
||||
self
|
||||
}
|
||||
|
||||
fn accept(
|
||||
&self,
|
||||
io_runtime: Runtime,
|
||||
accepting_stream: AbortableStream,
|
||||
) -> impl Future<Output = ()> + use<> {
|
||||
let handler_maker = self.make_handler.clone();
|
||||
// Assemble the per-connection handler directly, including any
|
||||
// `with_*` wiring applied after construction (the influxdb
|
||||
// line-protocol handler). Constructing the struct — instead of
|
||||
// going through the builder — keeps this infallible: no
|
||||
// `.build().unwrap()` on the hot accept path.
|
||||
let make_handler = &self.make_handler;
|
||||
let handler_maker = Arc::new(MakePostgresServerHandler {
|
||||
query_handler: make_handler.query_handler.clone(),
|
||||
copy_in_handler: make_handler.copy_in_handler.clone(),
|
||||
influxdb_handler: self.influxdb_handler.clone(),
|
||||
user_provider: make_handler.user_provider.clone(),
|
||||
param_provider: make_handler.param_provider.clone(),
|
||||
force_tls: make_handler.force_tls,
|
||||
});
|
||||
let batching_enabled = self.batching_enabled;
|
||||
let tls_server_config = self.tls_server_config.clone();
|
||||
let process_manager = self.process_manager.clone();
|
||||
|
||||
@@ -4,9 +4,6 @@ version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[features]
|
||||
enterprise = []
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
|
||||
@@ -467,11 +467,6 @@ impl QueryContext {
|
||||
self.extensions.insert(key.into(), value.into());
|
||||
}
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
pub fn remove_extension(&mut self, key: &str) {
|
||||
self.extensions.remove(key);
|
||||
}
|
||||
|
||||
pub fn extension<S: AsRef<str>>(&self, key: S) -> Option<&str> {
|
||||
self.extensions.get(key.as_ref()).map(|v| v.as_str())
|
||||
}
|
||||
|
||||
@@ -1082,7 +1082,9 @@ pub trait RegionEngine: Send + Sync {
|
||||
/// take effect.
|
||||
fn set_region_role(&self, region_id: RegionId, role: RegionRole) -> Result<(), BoxedError>;
|
||||
|
||||
/// Sets [RegionRole] for a region from a lease the metasrv grants until `deadline`.
|
||||
/// Sets [RegionRole] for a region from a lease the metasrv grants until `deadline`, in reply
|
||||
/// to a heartbeat sent at `sent_at`. Returns false if the engine ignores a Leader lease because
|
||||
/// the region was downgraded or (re)opened after `sent_at`.
|
||||
///
|
||||
/// The region must not acknowledge a write whose WAL append completes at or after the
|
||||
/// deadline of its latest Leader or StagingLeader lease. Leases of other roles do not extend
|
||||
@@ -1091,8 +1093,9 @@ pub trait RegionEngine: Send + Sync {
|
||||
&self,
|
||||
region_id: RegionId,
|
||||
role: RegionRole,
|
||||
sent_at: Instant,
|
||||
deadline: Instant,
|
||||
) -> Result<(), BoxedError>;
|
||||
) -> Result<bool, BoxedError>;
|
||||
|
||||
/// Syncs the region manifest to the given manifest version.
|
||||
async fn sync_region(
|
||||
|
||||
@@ -1204,16 +1204,19 @@ pub async fn setup_pg_server_with_slow_query_threshold(
|
||||
.expect("Failed to load certificates and keys"),
|
||||
);
|
||||
|
||||
let mut pg_server = Box::new(PostgresServer::new(
|
||||
fe_instance_ref.clone(),
|
||||
fe_instance_ref.clone(),
|
||||
opts.tls.should_force_tls(),
|
||||
tls_server_config,
|
||||
0,
|
||||
runtime,
|
||||
None,
|
||||
None,
|
||||
));
|
||||
let mut pg_server = Box::new(
|
||||
PostgresServer::new(
|
||||
fe_instance_ref.clone(),
|
||||
fe_instance_ref.clone(),
|
||||
opts.tls.should_force_tls(),
|
||||
tls_server_config,
|
||||
0,
|
||||
runtime,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.with_influxdb_handler(fe_instance_ref.clone()),
|
||||
);
|
||||
|
||||
pg_server
|
||||
.start(fe_pg_addr.parse::<SocketAddr>().unwrap())
|
||||
@@ -1248,16 +1251,19 @@ pub async fn setup_pg_server_with_user_provider(
|
||||
.expect("Failed to load certificates and keys"),
|
||||
);
|
||||
|
||||
let mut pg_server = Box::new(PostgresServer::new(
|
||||
fe_instance_ref.clone(),
|
||||
fe_instance_ref.clone(),
|
||||
opts.tls.should_force_tls(),
|
||||
tls_server_config,
|
||||
0,
|
||||
runtime,
|
||||
user_provider,
|
||||
None,
|
||||
));
|
||||
let mut pg_server = Box::new(
|
||||
PostgresServer::new(
|
||||
fe_instance_ref.clone(),
|
||||
fe_instance_ref.clone(),
|
||||
opts.tls.should_force_tls(),
|
||||
tls_server_config,
|
||||
0,
|
||||
runtime,
|
||||
user_provider,
|
||||
None,
|
||||
)
|
||||
.with_influxdb_handler(fe_instance_ref.clone()),
|
||||
);
|
||||
|
||||
pg_server
|
||||
.start(fe_pg_addr.parse::<SocketAddr>().unwrap())
|
||||
@@ -1304,16 +1310,19 @@ pub async fn setup_pg_server_with_prom_native_histogram(
|
||||
.expect("Failed to load certificates and keys"),
|
||||
);
|
||||
|
||||
let mut pg_server = Box::new(PostgresServer::new(
|
||||
instance.fe_instance().clone(),
|
||||
instance.fe_instance().clone(),
|
||||
opts.tls.should_force_tls(),
|
||||
tls_server_config,
|
||||
0,
|
||||
runtime,
|
||||
None,
|
||||
None,
|
||||
));
|
||||
let mut pg_server = Box::new(
|
||||
PostgresServer::new(
|
||||
instance.fe_instance().clone(),
|
||||
instance.fe_instance().clone(),
|
||||
opts.tls.should_force_tls(),
|
||||
tls_server_config,
|
||||
0,
|
||||
runtime,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.with_influxdb_handler(instance.fe_instance().clone()),
|
||||
);
|
||||
|
||||
pg_server
|
||||
.start(fe_pg_addr.parse::<SocketAddr>().unwrap())
|
||||
|
||||
@@ -316,6 +316,7 @@ async fn test_postgres_copy_in_failed_copy_then_new_copy() {
|
||||
Err(e) => e,
|
||||
};
|
||||
assert!(err.as_db_error().is_some(), "{err}");
|
||||
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
|
||||
|
||||
// The connection is usable and a NEW copy succeeds on it.
|
||||
let rows = feed_copy_in(
|
||||
@@ -519,3 +520,302 @@ async fn test_postgres_copy_in_empty_field_is_null() {
|
||||
|
||||
server.shutdown().await.unwrap();
|
||||
}
|
||||
|
||||
/// `COPY FROM STDIN WITH (FORMAT influxdb)` ingests line protocol through
|
||||
/// the same pipeline as the HTTP influxdb write endpoint: lines route to
|
||||
/// their own measurements, tables are auto-created, and a batch behaves
|
||||
/// like an HTTP write of the same bytes.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn test_postgres_copy_in_influxdb_line_protocol() {
|
||||
init_default_ut_logging();
|
||||
let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_in_influxdb").await;
|
||||
let port = server.bind_addr().unwrap().port();
|
||||
let client = connect(port).await;
|
||||
|
||||
let payload = b"monitor,host=hosta cpu=66.6,memory=1024 1663840496100023100\n\
|
||||
monitor,host=hostb memory=1027 1663840496400340001\n\
|
||||
weather,location=us-midwest temperature=82 1663840496100023102\n";
|
||||
|
||||
// Feed byte-by-byte-ish: lines and UTF-8 may span CopyData chunks.
|
||||
let rows = feed_copy_in(
|
||||
&client,
|
||||
"COPY FROM STDIN WITH (FORMAT influxdb)",
|
||||
payload.chunks(7).map(Bytes::copy_from_slice).collect(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(rows, 3);
|
||||
|
||||
let messages = client
|
||||
.simple_query("SELECT host, cpu, memory FROM monitor ORDER BY host")
|
||||
.await
|
||||
.unwrap();
|
||||
let rows: Vec<(String, String, String)> = messages
|
||||
.iter()
|
||||
.filter_map(|m| {
|
||||
let tokio_postgres::SimpleQueryMessage::Row(row) = m else {
|
||||
return None;
|
||||
};
|
||||
Some((
|
||||
row.get(0).unwrap_or("").to_string(),
|
||||
row.get(1).unwrap_or("").to_string(),
|
||||
row.get(2).unwrap_or("").to_string(),
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
rows,
|
||||
vec![
|
||||
("hosta".into(), "66.6".into(), "1024.0".into()),
|
||||
("hostb".into(), "".into(), "1027.0".into()),
|
||||
]
|
||||
);
|
||||
|
||||
let messages = client
|
||||
.simple_query("SELECT temperature FROM weather")
|
||||
.await
|
||||
.unwrap();
|
||||
let temps: Vec<String> = messages
|
||||
.iter()
|
||||
.filter_map(|m| match m {
|
||||
tokio_postgres::SimpleQueryMessage::Row(row) => row.get(0).map(str::to_string),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(temps, vec!["82.0".to_string()]);
|
||||
|
||||
server.shutdown().await.unwrap();
|
||||
}
|
||||
|
||||
/// The `precision` option carries the HTTP endpoint's semantics:
|
||||
/// nanosecond timestamps by default, other units on request.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn test_postgres_copy_in_influxdb_precision() {
|
||||
init_default_ut_logging();
|
||||
let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_in_influxdb_prec").await;
|
||||
let port = server.bind_addr().unwrap().port();
|
||||
let client = connect(port).await;
|
||||
|
||||
let rows = feed_copy_in(
|
||||
&client,
|
||||
"COPY FROM STDIN WITH (FORMAT influxdb, precision 'ms')",
|
||||
vec![Bytes::from_static(b"prec,host=h v=1 1465839830100\n")],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(rows, 1);
|
||||
|
||||
let messages = client
|
||||
.simple_query("SELECT CAST(greptime_timestamp AS BIGINT) FROM prec")
|
||||
.await
|
||||
.unwrap();
|
||||
let ts: Vec<String> = messages
|
||||
.iter()
|
||||
.filter_map(|m| match m {
|
||||
tokio_postgres::SimpleQueryMessage::Row(row) => row.get(0).map(str::to_string),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
// 1465839830100 ms == 1465839830100000000 ns
|
||||
assert_eq!(ts.len(), 1);
|
||||
let ts_ns: i64 = ts[0].parse().unwrap();
|
||||
assert_eq!(ts_ns, 1465839830100000000);
|
||||
|
||||
server.shutdown().await.unwrap();
|
||||
}
|
||||
|
||||
/// Records with newlines INSIDE quoted field values are one line-protocol
|
||||
/// record: the parser owns record boundaries, so a CopyData chunk boundary
|
||||
/// inside the quoted string — the case a naive line splitter breaks on —
|
||||
/// must not split it.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn test_postgres_copy_in_influxdb_multiline_quoted_field() {
|
||||
init_default_ut_logging();
|
||||
let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_in_influxdb_ml").await;
|
||||
let port = server.bind_addr().unwrap().port();
|
||||
let client = connect(port).await;
|
||||
|
||||
// A record whose string field value contains a physical newline, and
|
||||
// one with a backslash right before the newline (the parser skips the
|
||||
// escaped newline; also not a record boundary).
|
||||
let payload: Vec<u8> = b"mlog,host=a line=\"first\nsecond\" 100\n\
|
||||
mlog,host=b line=\"tail\\\nmore\" 200\n"
|
||||
.to_vec();
|
||||
|
||||
// Split exactly on the internal newline of the first record: chunk 1
|
||||
// ends after `first`, chunk 2 starts with the newline.
|
||||
let split_at = payload.windows(6).position(|w| w == b"first\n").unwrap() + b"first".len();
|
||||
let (head, tail) = payload.split_at(split_at);
|
||||
let rows = feed_copy_in(
|
||||
&client,
|
||||
"COPY FROM STDIN WITH (FORMAT influxdb)",
|
||||
vec![Bytes::copy_from_slice(head), Bytes::copy_from_slice(tail)],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(rows, 2);
|
||||
|
||||
let messages = client
|
||||
.simple_query("SELECT line FROM mlog ORDER BY host")
|
||||
.await
|
||||
.unwrap();
|
||||
let lines: Vec<String> = messages
|
||||
.iter()
|
||||
.filter_map(|m| match m {
|
||||
tokio_postgres::SimpleQueryMessage::Row(row) => row.get(0).map(str::to_string),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
// The quoted values keep their physical newlines: `first`, newline,
|
||||
// `second`; and `tail`, backslash, newline, `more` (a backslash only
|
||||
// escapes `\` and `"` in line-protocol strings, so it stays literal
|
||||
// before the newline).
|
||||
assert_eq!(
|
||||
lines,
|
||||
vec!["first\nsecond".to_string(), "tail\\\nmore".to_string()]
|
||||
);
|
||||
|
||||
server.shutdown().await.unwrap();
|
||||
}
|
||||
|
||||
/// The payload is bounded by the HTTP write endpoints' own body limit.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn test_postgres_copy_in_influxdb_payload_limit() {
|
||||
init_default_ut_logging();
|
||||
let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_in_influxdb_cap").await;
|
||||
let port = server.bind_addr().unwrap().port();
|
||||
let client = connect(port).await;
|
||||
|
||||
// The HTTP write endpoints' default body limit (64 MiB) — kept in
|
||||
// sync with servers::http::DEFAULT_BODY_LIMIT.
|
||||
let limit = 64 * 1024 * 1024;
|
||||
// Several chunks over the limit, none containing a record boundary.
|
||||
let chunk = vec![b'x'; 1024 * 1024];
|
||||
let mut sent = 0usize;
|
||||
let mut sink = Box::pin(
|
||||
client
|
||||
.copy_in("COPY FROM STDIN WITH (FORMAT influxdb)")
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
while sent <= limit {
|
||||
sink.as_mut()
|
||||
.send(Bytes::from(chunk.clone()))
|
||||
.await
|
||||
.unwrap();
|
||||
sent += chunk.len();
|
||||
}
|
||||
// The cap fires mid-stream; the error surfaces when the copy
|
||||
// completes (the sink buffers sends locally).
|
||||
let error = sink
|
||||
.as_mut()
|
||||
.finish()
|
||||
.await
|
||||
.expect_err("expected the oversized payload to fail");
|
||||
assert!(
|
||||
error
|
||||
.as_db_error()
|
||||
.map(|d| d.message().contains("exceeds"))
|
||||
.unwrap_or(false),
|
||||
"unexpected error: {error}"
|
||||
);
|
||||
|
||||
// The connection stays usable.
|
||||
let messages = client.simple_query("SELECT 1").await.unwrap();
|
||||
assert!(!messages.is_empty());
|
||||
|
||||
server.shutdown().await.unwrap();
|
||||
}
|
||||
|
||||
/// The regression for the retired line-splitter's failure mode: with
|
||||
/// 32,767 ordinary records plus a multiline quoted record whose first
|
||||
/// physical line lands exactly on the old 32,768-line flush threshold —
|
||||
/// and a CopyData chunk boundary at the quoted value's internal newline —
|
||||
/// the whole payload must still ingest as one request.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn test_postgres_copy_in_influxdb_flush_threshold_multiline() {
|
||||
init_default_ut_logging();
|
||||
let (_guard, server) =
|
||||
setup_pg_server(StorageType::File, "pg_copy_in_influxdb_threshold").await;
|
||||
let port = server.bind_addr().unwrap().port();
|
||||
let client = connect(port).await;
|
||||
|
||||
// 32,767 ordinary records, then a record whose quoted value spans
|
||||
// three physical lines.
|
||||
let mut head = String::new();
|
||||
for i in 0..32_767 {
|
||||
head.push_str(&format!(
|
||||
"m,host=h{i} v={i} {}
|
||||
",
|
||||
1_000 + i
|
||||
));
|
||||
}
|
||||
head.push_str("mlog,host=z line=\"first\nsecond\nthird\" 99999");
|
||||
let tail = "
|
||||
"
|
||||
.to_string();
|
||||
|
||||
let rows = feed_copy_in(
|
||||
&client,
|
||||
"COPY FROM STDIN WITH (FORMAT influxdb)",
|
||||
vec![
|
||||
Bytes::from(head.into_bytes()),
|
||||
Bytes::from(tail.into_bytes()),
|
||||
],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(rows, 32_768);
|
||||
|
||||
let messages = client.simple_query("SELECT line FROM mlog").await.unwrap();
|
||||
let lines: Vec<String> = messages
|
||||
.iter()
|
||||
.filter_map(|m| match m {
|
||||
tokio_postgres::SimpleQueryMessage::Row(row) => row.get(0).map(str::to_string),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(lines, vec!["first\nsecond\nthird".to_string()]);
|
||||
|
||||
server.shutdown().await.unwrap();
|
||||
}
|
||||
|
||||
/// Invalid UTF-8 fails the copy with a clear error and the connection
|
||||
/// stays usable; a trailing record without a newline is still ingested.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn test_postgres_copy_in_influxdb_invalid_utf8_and_trailing_record() {
|
||||
init_default_ut_logging();
|
||||
let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_in_influxdb_utf8").await;
|
||||
let port = server.bind_addr().unwrap().port();
|
||||
let client = connect(port).await;
|
||||
|
||||
// Trailing record without a newline: accepted.
|
||||
let rows = feed_copy_in(
|
||||
&client,
|
||||
"COPY FROM STDIN WITH (FORMAT influxdb)",
|
||||
vec![Bytes::from_static(b"m2,host=a v=7 300")],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(rows, 1);
|
||||
|
||||
// Invalid UTF-8: the copy fails, the connection stays usable.
|
||||
let error = feed_copy_in(
|
||||
&client,
|
||||
"COPY FROM STDIN WITH (FORMAT influxdb)",
|
||||
vec![Bytes::from_static(b"m3 v=1 100\n\xff\xfe")],
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.as_db_error()
|
||||
.map(|d| d.message().contains("not valid UTF-8"))
|
||||
.unwrap_or(false),
|
||||
"unexpected error: {error}"
|
||||
);
|
||||
let messages = client.simple_query("SELECT 1").await.unwrap();
|
||||
assert!(!messages.is_empty());
|
||||
|
||||
server.shutdown().await.unwrap();
|
||||
}
|
||||
|
||||
@@ -97,6 +97,80 @@ ORDER BY k;
|
||||
| 1970-01-01T00:00:01 | 1.5 | 15 | 1 |
|
||||
+---------------------+-----+----+--------+
|
||||
|
||||
-- The same rows must also come back in descending order: a filter on a lossy
|
||||
-- cast must not turn `k` into a constant and drop the requested sort.
|
||||
SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k
|
||||
FROM partition_pruning_cast_partitioned
|
||||
WHERE CAST(k AS BIGINT) = 1
|
||||
ORDER BY k DESC;
|
||||
|
||||
+---------------------+-----+----+--------+
|
||||
| ts | k | v | cast_k |
|
||||
+---------------------+-----+----+--------+
|
||||
| 1970-01-01T00:00:01 | 1.5 | 15 | 1 |
|
||||
| 1970-01-01T00:00:01 | 1.0 | 10 | 1 |
|
||||
+---------------------+-----+----+--------+
|
||||
|
||||
SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k
|
||||
FROM partition_pruning_cast_control
|
||||
WHERE CAST(k AS BIGINT) = 1
|
||||
ORDER BY k DESC;
|
||||
|
||||
+---------------------+-----+----+--------+
|
||||
| ts | k | v | cast_k |
|
||||
+---------------------+-----+----+--------+
|
||||
| 1970-01-01T00:00:01 | 1.5 | 15 | 1 |
|
||||
| 1970-01-01T00:00:01 | 1.0 | 10 | 1 |
|
||||
+---------------------+-----+----+--------+
|
||||
|
||||
-- A table whose matching rows are stored in neither ascending nor descending
|
||||
-- order, so a dropped sort cannot accidentally satisfy the ASC assertion.
|
||||
CREATE TABLE partition_pruning_cast_unsorted (
|
||||
ts TIMESTAMP TIME INDEX,
|
||||
k FLOAT PRIMARY KEY,
|
||||
v BIGINT,
|
||||
);
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
INSERT INTO partition_pruning_cast_unsorted VALUES
|
||||
(1000, 1.5, 15),
|
||||
(1000, 2.5, 25),
|
||||
(1000, 1.0, 10),
|
||||
(1000, 1.25, 12);
|
||||
|
||||
Affected Rows: 4
|
||||
|
||||
SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k
|
||||
FROM partition_pruning_cast_unsorted
|
||||
WHERE CAST(k AS BIGINT) = 1
|
||||
ORDER BY k;
|
||||
|
||||
+---------------------+------+----+--------+
|
||||
| ts | k | v | cast_k |
|
||||
+---------------------+------+----+--------+
|
||||
| 1970-01-01T00:00:01 | 1.0 | 10 | 1 |
|
||||
| 1970-01-01T00:00:01 | 1.25 | 12 | 1 |
|
||||
| 1970-01-01T00:00:01 | 1.5 | 15 | 1 |
|
||||
+---------------------+------+----+--------+
|
||||
|
||||
SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k
|
||||
FROM partition_pruning_cast_unsorted
|
||||
WHERE CAST(k AS BIGINT) = 1
|
||||
ORDER BY k DESC;
|
||||
|
||||
+---------------------+------+----+--------+
|
||||
| ts | k | v | cast_k |
|
||||
+---------------------+------+----+--------+
|
||||
| 1970-01-01T00:00:01 | 1.5 | 15 | 1 |
|
||||
| 1970-01-01T00:00:01 | 1.25 | 12 | 1 |
|
||||
| 1970-01-01T00:00:01 | 1.0 | 10 | 1 |
|
||||
+---------------------+------+----+--------+
|
||||
|
||||
DROP TABLE partition_pruning_cast_unsorted;
|
||||
|
||||
Affected Rows: 0
|
||||
|
||||
-- SQLNESS REPLACE (-+) -
|
||||
-- SQLNESS REPLACE (\s\s+) _
|
||||
-- SQLNESS REPLACE (elapsed_compute.*) REDACTED
|
||||
|
||||
@@ -43,6 +43,42 @@ FROM partition_pruning_cast_control
|
||||
WHERE CAST(k AS BIGINT) = 1
|
||||
ORDER BY k;
|
||||
|
||||
-- The same rows must also come back in descending order: a filter on a lossy
|
||||
-- cast must not turn `k` into a constant and drop the requested sort.
|
||||
SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k
|
||||
FROM partition_pruning_cast_partitioned
|
||||
WHERE CAST(k AS BIGINT) = 1
|
||||
ORDER BY k DESC;
|
||||
SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k
|
||||
FROM partition_pruning_cast_control
|
||||
WHERE CAST(k AS BIGINT) = 1
|
||||
ORDER BY k DESC;
|
||||
|
||||
-- A table whose matching rows are stored in neither ascending nor descending
|
||||
-- order, so a dropped sort cannot accidentally satisfy the ASC assertion.
|
||||
CREATE TABLE partition_pruning_cast_unsorted (
|
||||
ts TIMESTAMP TIME INDEX,
|
||||
k FLOAT PRIMARY KEY,
|
||||
v BIGINT,
|
||||
);
|
||||
|
||||
INSERT INTO partition_pruning_cast_unsorted VALUES
|
||||
(1000, 1.5, 15),
|
||||
(1000, 2.5, 25),
|
||||
(1000, 1.0, 10),
|
||||
(1000, 1.25, 12);
|
||||
|
||||
SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k
|
||||
FROM partition_pruning_cast_unsorted
|
||||
WHERE CAST(k AS BIGINT) = 1
|
||||
ORDER BY k;
|
||||
SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k
|
||||
FROM partition_pruning_cast_unsorted
|
||||
WHERE CAST(k AS BIGINT) = 1
|
||||
ORDER BY k DESC;
|
||||
|
||||
DROP TABLE partition_pruning_cast_unsorted;
|
||||
|
||||
-- SQLNESS REPLACE (-+) -
|
||||
-- SQLNESS REPLACE (\s\s+) _
|
||||
-- SQLNESS REPLACE (elapsed_compute.*) REDACTED
|
||||
|
||||
Reference in New Issue
Block a user