datadouble-elasticsearch 0.0.3__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- datadouble_elasticsearch-0.0.3/.gitignore +21 -0
- datadouble_elasticsearch-0.0.3/LICENSE +21 -0
- datadouble_elasticsearch-0.0.3/PKG-INFO +103 -0
- datadouble_elasticsearch-0.0.3/README.md +82 -0
- datadouble_elasticsearch-0.0.3/pyproject.toml +38 -0
- datadouble_elasticsearch-0.0.3/src/datadouble_elasticsearch/__init__.py +126 -0
- datadouble_elasticsearch-0.0.3/src/datadouble_elasticsearch/client.py +216 -0
- datadouble_elasticsearch-0.0.3/src/datadouble_elasticsearch/documents.py +150 -0
- datadouble_elasticsearch-0.0.3/src/datadouble_elasticsearch/indices.py +161 -0
- datadouble_elasticsearch-0.0.3/src/datadouble_elasticsearch/product.py +98 -0
- datadouble_elasticsearch-0.0.3/src/datadouble_elasticsearch/py.typed +0 -0
- datadouble_elasticsearch-0.0.3/src/datadouble_elasticsearch/search.py +206 -0
- datadouble_elasticsearch-0.0.3/src/datadouble_elasticsearch/server.py +186 -0
- datadouble_elasticsearch-0.0.3/src/datadouble_elasticsearch/source.py +373 -0
- datadouble_elasticsearch-0.0.3/src/datadouble_elasticsearch/working.py +462 -0
- datadouble_elasticsearch-0.0.3/tests/test_elasticsearch.py +509 -0
- datadouble_elasticsearch-0.0.3/tests/test_elasticsearch_conformance.py +209 -0
- datadouble_elasticsearch-0.0.3/tests/test_elasticsearch_units.py +337 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
__pycache__/
|
|
5
|
+
*.py[cod]
|
|
6
|
+
.venv/
|
|
7
|
+
.env
|
|
8
|
+
.coverage
|
|
9
|
+
.coverage.*
|
|
10
|
+
coverage.xml
|
|
11
|
+
.reports/
|
|
12
|
+
.pytest_cache/
|
|
13
|
+
.mypy_cache/
|
|
14
|
+
.ruff_cache/
|
|
15
|
+
dist/
|
|
16
|
+
site/
|
|
17
|
+
.cache/
|
|
18
|
+
|
|
19
|
+
# The default work directory of `datadouble run`.
|
|
20
|
+
.datadouble/
|
|
21
|
+
node_modules/
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026- Tight Line LLC
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: datadouble-elasticsearch
|
|
3
|
+
Version: 0.0.3
|
|
4
|
+
Summary: Elasticsearch engine adapter for Datadouble
|
|
5
|
+
Project-URL: Homepage, https://datadouble.tightlinesoftware.com/
|
|
6
|
+
Project-URL: Source, https://github.com/datadouble/datadouble
|
|
7
|
+
Author: Tight Line LLC
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
11
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
15
|
+
Classifier: Topic :: Database
|
|
16
|
+
Classifier: Typing :: Typed
|
|
17
|
+
Requires-Python: >=3.13
|
|
18
|
+
Requires-Dist: datadouble
|
|
19
|
+
Requires-Dist: elastic-transport>=9.4
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# datadouble-elasticsearch
|
|
23
|
+
|
|
24
|
+
The Elasticsearch engine adapter for [Datadouble](https://datadouble.tightlinesoftware.com/).
|
|
25
|
+
|
|
26
|
+
Each index is a table keyed by `_id`, and its columns are the field paths its
|
|
27
|
+
mapping declares: `address.city` for an object's field, `actors.actor_id` for
|
|
28
|
+
a field of nested documents. The extract reads through one point in time over
|
|
29
|
+
every index, so it sees them all as they were when it started. Working
|
|
30
|
+
databases are throwaway single-node clusters in the official Elasticsearch
|
|
31
|
+
image of the source's exact version, through the spec's container runtime. A
|
|
32
|
+
golden image is a snapshot repository (`physical`) or each index's mappings,
|
|
33
|
+
settings and documents as NDJSON (`logical`).
|
|
34
|
+
|
|
35
|
+
```yaml
|
|
36
|
+
sources:
|
|
37
|
+
app:
|
|
38
|
+
engine: elasticsearch
|
|
39
|
+
connection:
|
|
40
|
+
url: # http[s]://[user:password@]host[:port], by reference
|
|
41
|
+
env: SEARCH_URL
|
|
42
|
+
api_key: # optional; sent instead of the URL's credentials
|
|
43
|
+
env: SEARCH_KEY
|
|
44
|
+
indices: ["*", "-logs-*"] # index patterns; the default is every open index
|
|
45
|
+
subset:
|
|
46
|
+
seeds:
|
|
47
|
+
customers: '{"range": {"created": {"lte": ":as_of"}}}' # Query DSL; ":as_of" is the plan's anchor
|
|
48
|
+
virtual_fks:
|
|
49
|
+
rentals.customer_id -> customers: {} # a reference to a document's _id
|
|
50
|
+
payments.rental_id -> rentals.rental_id: {} # a reference to another field
|
|
51
|
+
unselected: none # indices nothing reaches, such as rentals here, are copied empty
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Elasticsearch declares no references, so every reference is virtual, and
|
|
55
|
+
subsets use the keys strategy. References must be `keyword`, numeric or `_id`
|
|
56
|
+
fields: no query matches a `text` field's value exactly.
|
|
57
|
+
|
|
58
|
+
An index whose mapping lets documents hold undeclared fields (`dynamic:
|
|
59
|
+
false` or `runtime`) also gets a column for each such field in its first
|
|
60
|
+
`sample` documents (1000 by default). The extract fails if a document it
|
|
61
|
+
copies holds a field the catalog does not list, so strict mode covers every
|
|
62
|
+
field that leaves the source. Indices that keep no `_source`, or only part of
|
|
63
|
+
it, cannot be copied, and data streams are not copied: leave them out of
|
|
64
|
+
`indices`. Indices whose names start with a dot belong to the server and are
|
|
65
|
+
never tables.
|
|
66
|
+
|
|
67
|
+
An index keeps its mappings, aliases and the settings that describe it
|
|
68
|
+
(shards, analysis, sorting, mode). Settings that tie it to the source
|
|
69
|
+
cluster are left out: allocation, lifecycle policies, ingest pipelines and
|
|
70
|
+
write blocks. Copies have no replicas.
|
|
71
|
+
|
|
72
|
+
Anonymization rewrites fields wherever a document holds them, in objects and
|
|
73
|
+
arrays alike. Expression rules are Painless scripts, run with
|
|
74
|
+
`_update_by_query` against each document (`ctx._source`) with
|
|
75
|
+
`params.column` naming the column; `where` is a Query DSL object. `_id` and
|
|
76
|
+
`_routing` are copied as they are, and no rule changes them: keep personal
|
|
77
|
+
data out of document IDs and routing values, or out of copies. Verify
|
|
78
|
+
assertions are `{"index": "...", "query": {...}}`, failing when they match
|
|
79
|
+
any document.
|
|
80
|
+
|
|
81
|
+
The source must be Elasticsearch 7.17 or later. Working nodes have a 512 MB
|
|
82
|
+
heap; set `sources.<name>.server.heap` (such as `2g`) for larger subsets.
|
|
83
|
+
|
|
84
|
+
## Plugins
|
|
85
|
+
|
|
86
|
+
Every plugin installed on the source's nodes (`GET _nodes/plugins`) is a
|
|
87
|
+
requirement at its version, such as `analysis-icu 9.5.5`. Reading them
|
|
88
|
+
needs the `monitor` cluster privilege, as well as read access to the
|
|
89
|
+
indices. Before reading the source, a build lists the working image's
|
|
90
|
+
plugins (`elasticsearch-plugin list`) and fails with `requirement_unmet` if
|
|
91
|
+
one is missing. The official image has none installed, so a source with
|
|
92
|
+
analysis or mapper plugins needs an image that adds them, built `FROM` the
|
|
93
|
+
official image of the source's version:
|
|
94
|
+
|
|
95
|
+
```dockerfile
|
|
96
|
+
FROM elasticsearch:9.5.5
|
|
97
|
+
RUN elasticsearch-plugin install --batch analysis-icu analysis-kuromoji
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Then name it in `sources.<name>.image`. A plugin the copies can go without, such
|
|
101
|
+
as a repository plugin, can be left out with `sources.<name>.omit`; an index whose
|
|
102
|
+
mapping uses an omitted plugin's analyzer or field type fails to load, so
|
|
103
|
+
exclude it too.
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# datadouble-elasticsearch
|
|
2
|
+
|
|
3
|
+
The Elasticsearch engine adapter for [Datadouble](https://datadouble.tightlinesoftware.com/).
|
|
4
|
+
|
|
5
|
+
Each index is a table keyed by `_id`, and its columns are the field paths its
|
|
6
|
+
mapping declares: `address.city` for an object's field, `actors.actor_id` for
|
|
7
|
+
a field of nested documents. The extract reads through one point in time over
|
|
8
|
+
every index, so it sees them all as they were when it started. Working
|
|
9
|
+
databases are throwaway single-node clusters in the official Elasticsearch
|
|
10
|
+
image of the source's exact version, through the spec's container runtime. A
|
|
11
|
+
golden image is a snapshot repository (`physical`) or each index's mappings,
|
|
12
|
+
settings and documents as NDJSON (`logical`).
|
|
13
|
+
|
|
14
|
+
```yaml
|
|
15
|
+
sources:
|
|
16
|
+
app:
|
|
17
|
+
engine: elasticsearch
|
|
18
|
+
connection:
|
|
19
|
+
url: # http[s]://[user:password@]host[:port], by reference
|
|
20
|
+
env: SEARCH_URL
|
|
21
|
+
api_key: # optional; sent instead of the URL's credentials
|
|
22
|
+
env: SEARCH_KEY
|
|
23
|
+
indices: ["*", "-logs-*"] # index patterns; the default is every open index
|
|
24
|
+
subset:
|
|
25
|
+
seeds:
|
|
26
|
+
customers: '{"range": {"created": {"lte": ":as_of"}}}' # Query DSL; ":as_of" is the plan's anchor
|
|
27
|
+
virtual_fks:
|
|
28
|
+
rentals.customer_id -> customers: {} # a reference to a document's _id
|
|
29
|
+
payments.rental_id -> rentals.rental_id: {} # a reference to another field
|
|
30
|
+
unselected: none # indices nothing reaches, such as rentals here, are copied empty
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Elasticsearch declares no references, so every reference is virtual, and
|
|
34
|
+
subsets use the keys strategy. References must be `keyword`, numeric or `_id`
|
|
35
|
+
fields: no query matches a `text` field's value exactly.
|
|
36
|
+
|
|
37
|
+
An index whose mapping lets documents hold undeclared fields (`dynamic:
|
|
38
|
+
false` or `runtime`) also gets a column for each such field in its first
|
|
39
|
+
`sample` documents (1000 by default). The extract fails if a document it
|
|
40
|
+
copies holds a field the catalog does not list, so strict mode covers every
|
|
41
|
+
field that leaves the source. Indices that keep no `_source`, or only part of
|
|
42
|
+
it, cannot be copied, and data streams are not copied: leave them out of
|
|
43
|
+
`indices`. Indices whose names start with a dot belong to the server and are
|
|
44
|
+
never tables.
|
|
45
|
+
|
|
46
|
+
An index keeps its mappings, aliases and the settings that describe it
|
|
47
|
+
(shards, analysis, sorting, mode). Settings that tie it to the source
|
|
48
|
+
cluster are left out: allocation, lifecycle policies, ingest pipelines and
|
|
49
|
+
write blocks. Copies have no replicas.
|
|
50
|
+
|
|
51
|
+
Anonymization rewrites fields wherever a document holds them, in objects and
|
|
52
|
+
arrays alike. Expression rules are Painless scripts, run with
|
|
53
|
+
`_update_by_query` against each document (`ctx._source`) with
|
|
54
|
+
`params.column` naming the column; `where` is a Query DSL object. `_id` and
|
|
55
|
+
`_routing` are copied as they are, and no rule changes them: keep personal
|
|
56
|
+
data out of document IDs and routing values, or out of copies. Verify
|
|
57
|
+
assertions are `{"index": "...", "query": {...}}`, failing when they match
|
|
58
|
+
any document.
|
|
59
|
+
|
|
60
|
+
The source must be Elasticsearch 7.17 or later. Working nodes have a 512 MB
|
|
61
|
+
heap; set `sources.<name>.server.heap` (such as `2g`) for larger subsets.
|
|
62
|
+
|
|
63
|
+
## Plugins
|
|
64
|
+
|
|
65
|
+
Every plugin installed on the source's nodes (`GET _nodes/plugins`) is a
|
|
66
|
+
requirement at its version, such as `analysis-icu 9.5.5`. Reading them
|
|
67
|
+
needs the `monitor` cluster privilege, as well as read access to the
|
|
68
|
+
indices. Before reading the source, a build lists the working image's
|
|
69
|
+
plugins (`elasticsearch-plugin list`) and fails with `requirement_unmet` if
|
|
70
|
+
one is missing. The official image has none installed, so a source with
|
|
71
|
+
analysis or mapper plugins needs an image that adds them, built `FROM` the
|
|
72
|
+
official image of the source's version:
|
|
73
|
+
|
|
74
|
+
```dockerfile
|
|
75
|
+
FROM elasticsearch:9.5.5
|
|
76
|
+
RUN elasticsearch-plugin install --batch analysis-icu analysis-kuromoji
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Then name it in `sources.<name>.image`. A plugin the copies can go without, such
|
|
80
|
+
as a repository plugin, can be left out with `sources.<name>.omit`; an index whose
|
|
81
|
+
mapping uses an omitted plugin's analyzer or field type fails to load, so
|
|
82
|
+
exclude it too.
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
[project]
|
|
5
|
+
name = "datadouble-elasticsearch"
|
|
6
|
+
# All packages share one version until 1.0 (decision 38); scripts/make_tag.py
|
|
7
|
+
# sets it at release time.
|
|
8
|
+
version = "0.0.3"
|
|
9
|
+
description = "Elasticsearch engine adapter for Datadouble"
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "Tight Line LLC" }]
|
|
14
|
+
requires-python = ">=3.13"
|
|
15
|
+
dependencies = ["datadouble", "elastic-transport>=9.4"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 2 - Pre-Alpha",
|
|
18
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
19
|
+
"Programming Language :: Python :: 3.13",
|
|
20
|
+
"Programming Language :: Python :: 3.14",
|
|
21
|
+
"Programming Language :: Python :: 3.15",
|
|
22
|
+
"Topic :: Database",
|
|
23
|
+
"Typing :: Typed",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://datadouble.tightlinesoftware.com/"
|
|
28
|
+
Source = "https://github.com/datadouble/datadouble"
|
|
29
|
+
|
|
30
|
+
[project.entry-points."datadouble.engines"]
|
|
31
|
+
elasticsearch = "datadouble_elasticsearch:engine"
|
|
32
|
+
|
|
33
|
+
[build-system]
|
|
34
|
+
requires = ["hatchling>=1.33.0"]
|
|
35
|
+
build-backend = "hatchling.build"
|
|
36
|
+
|
|
37
|
+
[tool.hatch.build.targets.wheel]
|
|
38
|
+
packages = ["src/datadouble_elasticsearch"]
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""The Elasticsearch engine adapter for Datadouble.
|
|
5
|
+
|
|
6
|
+
Spec settings::
|
|
7
|
+
|
|
8
|
+
sources:
|
|
9
|
+
app:
|
|
10
|
+
engine: elasticsearch
|
|
11
|
+
connection:
|
|
12
|
+
url: {env: SEARCH_URL} # http[s]://[user:password@]host[:port], by reference
|
|
13
|
+
api_key: {env: SEARCH_KEY} # optional; sent instead of the URL's credentials
|
|
14
|
+
indices: ["*", "-logs-*"] # index patterns; the default is every open index
|
|
15
|
+
sample: 1000 # documents sampled for fields mappings do not declare
|
|
16
|
+
server:
|
|
17
|
+
heap: 512m # the Java heap of working nodes
|
|
18
|
+
|
|
19
|
+
The source is Elasticsearch 7.17 or later. Extract reads over HTTP. Working
|
|
20
|
+
nodes and restores run in the official Elasticsearch image of the source's
|
|
21
|
+
exact version (``elasticsearch:<version>``), or in ``sources.<name>.image``, through
|
|
22
|
+
the spec's container runtime.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from collections.abc import Generator, Mapping
|
|
26
|
+
from contextlib import contextmanager
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
|
|
29
|
+
from pydantic import BaseModel, ConfigDict, Field, JsonValue
|
|
30
|
+
|
|
31
|
+
from datadouble.engine import ServerPlan, SourceSession, Tooling, WorkingDatabases
|
|
32
|
+
from datadouble.names import EngineName
|
|
33
|
+
from datadouble.planner import Capabilities
|
|
34
|
+
from datadouble.secrets import resolve_secret
|
|
35
|
+
from datadouble.settings import parse_settings
|
|
36
|
+
from datadouble.spec import ImageFormat, SecretRef
|
|
37
|
+
from datadouble_elasticsearch.client import Client
|
|
38
|
+
from datadouble_elasticsearch.product import ELASTICSEARCH, Product
|
|
39
|
+
from datadouble_elasticsearch.server import PORT, ServerSettings, Tools, ready_command
|
|
40
|
+
from datadouble_elasticsearch.source import ElasticSource, Layout, server_version
|
|
41
|
+
from datadouble_elasticsearch.working import DatabaseInfo, ElasticWorking, serve_command
|
|
42
|
+
|
|
43
|
+
MOUNT = "/var/lib/datadouble"
|
|
44
|
+
"""Where container servers mount a copy."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class ElasticConnection(BaseModel):
|
|
48
|
+
"""The ``sources.<name>.connection`` settings."""
|
|
49
|
+
|
|
50
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
51
|
+
|
|
52
|
+
url: SecretRef
|
|
53
|
+
api_key: SecretRef | None = None
|
|
54
|
+
indices: tuple[str, ...] = Field(default=("*",), min_length=1)
|
|
55
|
+
sample: int = Field(default=1000, ge=1)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class ElasticEngine:
|
|
59
|
+
"""Implements :class:`datadouble.engine.EngineAdapter` for Elasticsearch, or another product."""
|
|
60
|
+
|
|
61
|
+
def __init__(self, product: Product = ELASTICSEARCH) -> None:
|
|
62
|
+
"""Serve ``product``."""
|
|
63
|
+
self.product = product
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def name(self) -> EngineName:
|
|
67
|
+
"""The product's engine name, such as ``elasticsearch``."""
|
|
68
|
+
return self.product.engine
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def owner(self) -> str:
|
|
72
|
+
"""The user the product's official image serves as, such as ``1000:0``."""
|
|
73
|
+
return self.product.owner
|
|
74
|
+
|
|
75
|
+
def capabilities(self) -> Capabilities:
|
|
76
|
+
"""Both formats and Painless expressions; no nested strategy or hooks."""
|
|
77
|
+
return Capabilities(
|
|
78
|
+
formats=(ImageFormat.PHYSICAL, ImageFormat.LOGICAL),
|
|
79
|
+
expressions=True,
|
|
80
|
+
nested=False,
|
|
81
|
+
hooks=False,
|
|
82
|
+
# A snapshot from 8.15 cannot be restored on 8.12: each minor is a line.
|
|
83
|
+
version_line=2,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
@contextmanager
|
|
87
|
+
def connect(self, connection: Mapping[str, JsonValue]) -> Generator[SourceSession]:
|
|
88
|
+
"""Connect to the source."""
|
|
89
|
+
settings = parse_settings(ElasticConnection, connection, f"{self.name} connection")
|
|
90
|
+
api_key = resolve_secret(settings.api_key) if settings.api_key else None
|
|
91
|
+
client = Client.from_url(resolve_secret(settings.url), self.product, api_key)
|
|
92
|
+
try:
|
|
93
|
+
server_version(client)
|
|
94
|
+
yield ElasticSource(client, Layout(indices=settings.indices, sample=settings.sample))
|
|
95
|
+
finally:
|
|
96
|
+
client.close()
|
|
97
|
+
|
|
98
|
+
def working(self, scratch: Path, tooling: Tooling, source_version: str) -> WorkingDatabases:
|
|
99
|
+
"""Single-node clusters under ``scratch``, in the image for the source's version."""
|
|
100
|
+
settings = parse_settings(ServerSettings, tooling.server, f"{self.name} server")
|
|
101
|
+
image = tooling.image or self.product.image(source_version)
|
|
102
|
+
return ElasticWorking(Tools(self.product, tooling.runtime, image, settings.heap), scratch)
|
|
103
|
+
|
|
104
|
+
def server(self, image: Path, server_image: str | None) -> ServerPlan:
|
|
105
|
+
"""The product's official image of the image's version, on the copy.
|
|
106
|
+
|
|
107
|
+
The first start restores the image's snapshot into the copy; the
|
|
108
|
+
copy's password is the administrator's.
|
|
109
|
+
"""
|
|
110
|
+
info = DatabaseInfo.read(image)
|
|
111
|
+
command, marker = serve_command(self.product, MOUNT, ServerSettings().heap)
|
|
112
|
+
return ServerPlan(
|
|
113
|
+
image=server_image or self.product.image(info.server_version),
|
|
114
|
+
mount=MOUNT,
|
|
115
|
+
owner=self.owner,
|
|
116
|
+
command=("sh", "-c", command),
|
|
117
|
+
ready=ready_command(self.product, marker),
|
|
118
|
+
port=PORT,
|
|
119
|
+
database="",
|
|
120
|
+
user=self.product.user,
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def engine() -> ElasticEngine:
|
|
125
|
+
"""The entry point named in ``datadouble.engines``."""
|
|
126
|
+
return ElasticEngine()
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""Requests to the REST API, through elastic-transport.
|
|
5
|
+
|
|
6
|
+
The adapter talks to the REST API directly, with Elastic's own transport for
|
|
7
|
+
connections and retries, rather than through the official client: each major
|
|
8
|
+
version of that client talks only to servers of its own major version, and
|
|
9
|
+
the adapter reads sources of any version from 7.17 on.
|
|
10
|
+
|
|
11
|
+
Replies are parsed JSON, read with the helpers here. Errors name the
|
|
12
|
+
server's error type and HTTP status, never its reason: a reason can quote
|
|
13
|
+
the document that caused it.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import base64
|
|
17
|
+
from collections.abc import Mapping, Sequence
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from http import HTTPStatus
|
|
20
|
+
from typing import Final
|
|
21
|
+
from urllib.parse import quote, unquote, urlencode, urlsplit
|
|
22
|
+
|
|
23
|
+
from elastic_transport import NodeConfig, Transport, TransportError
|
|
24
|
+
from pydantic import JsonValue, TypeAdapter
|
|
25
|
+
|
|
26
|
+
from datadouble.engine import EngineError
|
|
27
|
+
from datadouble_elasticsearch.product import Product
|
|
28
|
+
|
|
29
|
+
type Document = dict[str, object]
|
|
30
|
+
type Params = Mapping[str, str | int | bool]
|
|
31
|
+
|
|
32
|
+
_SCHEMES: Final = {"http": 80, "https": 443}
|
|
33
|
+
_DOCUMENT: TypeAdapter[dict[str, object]] = TypeAdapter(dict[str, object])
|
|
34
|
+
_LIST: TypeAdapter[list[object]] = TypeAdapter(list[object])
|
|
35
|
+
_TIMEOUT = 120.0
|
|
36
|
+
"""Seconds a request may take, unless it waits for a long operation."""
|
|
37
|
+
LONG = 3600.0
|
|
38
|
+
"""Seconds for requests that wait for a snapshot, restore, update or bulk load to finish."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def as_document(value: object) -> Document | None:
|
|
42
|
+
"""``value`` as a JSON object, if it is one."""
|
|
43
|
+
# Parsed JSON's objects have text keys, so validating one cannot fail.
|
|
44
|
+
return _DOCUMENT.validate_python(value) if isinstance(value, Mapping) else None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def as_list(value: object) -> list[object] | None:
|
|
48
|
+
"""``value`` as a list, if it is one."""
|
|
49
|
+
return _LIST.validate_python(value) if isinstance(value, list) else None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def document(value: object, what: str) -> Document:
|
|
53
|
+
"""``value`` as a JSON object, or an error naming ``what``."""
|
|
54
|
+
found = as_document(value)
|
|
55
|
+
if found is None:
|
|
56
|
+
message = f"expected a JSON object for {what}"
|
|
57
|
+
raise EngineError(message)
|
|
58
|
+
return found
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def items(value: object, what: str) -> list[object]:
|
|
62
|
+
"""``value`` as a list, or an error naming ``what``."""
|
|
63
|
+
found = as_list(value)
|
|
64
|
+
if found is None:
|
|
65
|
+
message = f"expected a JSON array for {what}"
|
|
66
|
+
raise EngineError(message)
|
|
67
|
+
return found
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def text(value: object) -> str:
|
|
71
|
+
"""A scalar as text, as the server compares it: ``true``, ``42``, ``alice``."""
|
|
72
|
+
if isinstance(value, bool):
|
|
73
|
+
return "true" if value else "false"
|
|
74
|
+
return str(value)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _error_type(body: object) -> str:
|
|
78
|
+
"""The type of a reply's error, or of the cause of its first failure."""
|
|
79
|
+
reply = as_document(body) or {}
|
|
80
|
+
failures = as_list(reply.get("failures")) or [{}]
|
|
81
|
+
error = as_document(reply.get("error")) or as_document(
|
|
82
|
+
(as_document(failures[0]) or {}).get("cause")
|
|
83
|
+
)
|
|
84
|
+
kind = error.get("type") if error else None
|
|
85
|
+
return kind if isinstance(kind, str) else "error"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def path(*parts: str) -> str:
|
|
89
|
+
"""A request path, each part quoted: ``path("films", "_doc", "1")``."""
|
|
90
|
+
return "/" + "/".join(quote(part, safe=",*") for part in parts)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class Client:
|
|
94
|
+
"""A connection to one cluster of a product."""
|
|
95
|
+
|
|
96
|
+
def __init__(self, transport: Transport, headers: Mapping[str, str], product: Product) -> None:
|
|
97
|
+
"""Send requests through ``transport`` with ``headers``."""
|
|
98
|
+
self._transport = transport
|
|
99
|
+
self._headers = dict(headers)
|
|
100
|
+
self.product = product
|
|
101
|
+
|
|
102
|
+
@classmethod
|
|
103
|
+
def from_url(cls, url: str, product: Product, api_key: str | None = None) -> "Client":
|
|
104
|
+
"""A client for the cluster at an ``http://`` or ``https://`` URL.
|
|
105
|
+
|
|
106
|
+
Credentials in the URL are sent as basic authentication; an API key,
|
|
107
|
+
if given, is sent instead.
|
|
108
|
+
"""
|
|
109
|
+
parts = urlsplit(url)
|
|
110
|
+
if parts.scheme not in _SCHEMES or not parts.hostname:
|
|
111
|
+
message = (
|
|
112
|
+
f"the URL of the {product.name} source is http[s]://[user:password@]host[:port]"
|
|
113
|
+
)
|
|
114
|
+
raise EngineError(message)
|
|
115
|
+
headers: dict[str, str] = {}
|
|
116
|
+
if api_key:
|
|
117
|
+
headers["authorization"] = f"ApiKey {api_key}"
|
|
118
|
+
elif parts.username:
|
|
119
|
+
user, password = unquote(parts.username), unquote(parts.password or "")
|
|
120
|
+
headers["authorization"] = _basic(user, password)
|
|
121
|
+
node = NodeConfig(
|
|
122
|
+
parts.scheme,
|
|
123
|
+
parts.hostname,
|
|
124
|
+
parts.port or _SCHEMES[parts.scheme],
|
|
125
|
+
path_prefix=parts.path.rstrip("/"),
|
|
126
|
+
)
|
|
127
|
+
return cls(_transport(node), headers, product)
|
|
128
|
+
|
|
129
|
+
@classmethod
|
|
130
|
+
def at(cls, host: str, port: int, password: str, product: Product) -> "Client":
|
|
131
|
+
"""A client for a working node, as the product's administrator."""
|
|
132
|
+
return cls(
|
|
133
|
+
_transport(NodeConfig("http", host, port)),
|
|
134
|
+
{"authorization": _basic(product.user, password)},
|
|
135
|
+
product,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
def request(
|
|
139
|
+
self,
|
|
140
|
+
method: str,
|
|
141
|
+
target: str,
|
|
142
|
+
action: str,
|
|
143
|
+
*,
|
|
144
|
+
body: Mapping[str, JsonValue] | None = None,
|
|
145
|
+
params: Params | None = None,
|
|
146
|
+
) -> Document:
|
|
147
|
+
"""Send one request and return its JSON reply.
|
|
148
|
+
|
|
149
|
+
A request with ``wait_for_completion`` may wait for an hour.
|
|
150
|
+
"""
|
|
151
|
+
query = "?" + urlencode({k: text(v) for k, v in params.items()}) if params else ""
|
|
152
|
+
waits = bool(params and params.get("wait_for_completion"))
|
|
153
|
+
return self._send(
|
|
154
|
+
_Call(method, target + query, action, body, timeout=LONG if waits else _TIMEOUT)
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
def bulk(self, lines: Sequence[Mapping[str, JsonValue]], action: str) -> None:
|
|
158
|
+
"""Send a ``_bulk`` request; fail if any of its operations failed."""
|
|
159
|
+
if not lines:
|
|
160
|
+
return
|
|
161
|
+
reply = self._send(
|
|
162
|
+
_Call("POST", "/_bulk", action, list(lines), LONG, "application/x-ndjson")
|
|
163
|
+
)
|
|
164
|
+
if reply.get("errors") is not True:
|
|
165
|
+
return
|
|
166
|
+
outcomes = (
|
|
167
|
+
document(result, "a bulk result")
|
|
168
|
+
for item in items(reply.get("items"), "bulk results")
|
|
169
|
+
for result in document(item, "a bulk result").values()
|
|
170
|
+
)
|
|
171
|
+
none: Document = {}
|
|
172
|
+
failed = next((outcome for outcome in outcomes if "error" in outcome), none)
|
|
173
|
+
message = f"{action} failed: {_error_type(failed)} (HTTP {failed.get('status')})"
|
|
174
|
+
raise EngineError(message)
|
|
175
|
+
|
|
176
|
+
def _send(self, call: "_Call") -> Document:
|
|
177
|
+
headers = {**self._headers, "accept": "application/json", "content-type": call.content}
|
|
178
|
+
try:
|
|
179
|
+
response = self._transport.perform_request(
|
|
180
|
+
call.method,
|
|
181
|
+
call.target,
|
|
182
|
+
body=call.body,
|
|
183
|
+
headers=headers,
|
|
184
|
+
request_timeout=call.timeout,
|
|
185
|
+
)
|
|
186
|
+
except TransportError as error:
|
|
187
|
+
message = f"{call.action} failed: {type(error).__name__}"
|
|
188
|
+
raise EngineError(message) from None
|
|
189
|
+
status = response.meta.status
|
|
190
|
+
if not HTTPStatus(status).is_success:
|
|
191
|
+
message = f"{call.action} failed: {_error_type(response.body)} (HTTP {status})"
|
|
192
|
+
raise EngineError(message)
|
|
193
|
+
return as_document(response.body) or {}
|
|
194
|
+
|
|
195
|
+
def close(self) -> None:
|
|
196
|
+
"""Close the connections."""
|
|
197
|
+
self._transport.close()
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
@dataclass(frozen=True, slots=True)
|
|
201
|
+
class _Call:
|
|
202
|
+
method: str
|
|
203
|
+
target: str
|
|
204
|
+
action: str
|
|
205
|
+
body: object
|
|
206
|
+
timeout: float = _TIMEOUT
|
|
207
|
+
content: str = "application/json"
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _transport(node: NodeConfig) -> Transport:
|
|
211
|
+
# Overloaded nodes answer 429 or 503: retry those after a growing pause.
|
|
212
|
+
return Transport([node], retry_backoff_base=1, retry_backoff_cap=30)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _basic(user: str, password: str) -> str:
|
|
216
|
+
return "Basic " + base64.b64encode(f"{user}:{password}".encode()).decode()
|