Skip to content

Commit e39586a

Browse files
committed
feat(trino): add support for http headers
1 parent 84e207e commit e39586a

9 files changed

Lines changed: 137 additions & 4 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1111
- `datacontract test`: test Excel workbooks (`format: xlsx`) (new `xlsx` extra) (#1717)
1212
- `datacontract edit --language` shows the editor in English, German, Swedish or French
1313
- `datacontract import avro` and `export avro` keep the `aliases` of fields and of the top-level record (#1744)
14+
- Trino connections support custom HTTP headers via `DATACONTRACT_TRINO_HTTP_HEADERS`
1415

1516
### Changed
1617
- The bundled Data Contract Editor (`datacontract edit`) is updated to 0.1.16

‎datacontract/config/settings.py‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@
22

33
from __future__ import annotations
44

5+
import json
56
import logging
67
import os
78
from pathlib import Path
89

9-
from pydantic import Field, SecretStr
10+
from pydantic import Field, SecretStr, TypeAdapter, field_validator
1011
from pydantic_settings import BaseSettings, SettingsConfigDict
1112

1213
logger = logging.getLogger(__name__)
@@ -334,6 +335,7 @@ class Config(BaseSettings):
334335
trino_username: str | None = None
335336
trino_password: SecretStr | None = None
336337
trino_jwt_token: SecretStr | None = None
338+
trino_http_headers: dict[str, str] | None = None
337339
# overrides for the contract's servers block
338340
trino_host: str | None = None
339341
trino_port: int | None = None
@@ -402,7 +404,9 @@ def from_yaml(cls, path: "str | Path") -> "Config":
402404
def walk(prefix: str, node: dict):
403405
for key, value in node.items():
404406
name = f"{prefix}_{key}" if prefix else str(key)
405-
if isinstance(value, dict):
407+
if name in cls.model_fields and isinstance(value, dict):
408+
flat[name] = {k: _interpolate_env(v, path) for k, v in value.items()}
409+
elif isinstance(value, dict):
406410
walk(name, value)
407411
else:
408412
flat[name] = _interpolate_env(value, path)
@@ -1040,6 +1044,14 @@ def get_trino_password(self, required: bool = False) -> str | None:
10401044
def get_trino_jwt_token(self, required: bool = False) -> str | None:
10411045
return self._str_option("trino_jwt_token", required)
10421046

1047+
@field_validator("trino_http_headers", mode="before")
1048+
@classmethod
1049+
def _parse_trino_http_headers(cls, value):
1050+
return TypeAdapter(dict[str, str]).validate_json(value) if isinstance(value, str) else value
1051+
1052+
def get_trino_http_headers(self) -> dict[str, str] | None:
1053+
return self._parse_trino_http_headers(self._raw_option("trino_http_headers"))
1054+
10431055
def get_trino_host(self, required: bool = False) -> str | None:
10441056
return self._str_option("trino_host", required)
10451057

@@ -1090,6 +1102,8 @@ def env_name(field_name: str, field) -> str:
10901102
def _as_env_value(value) -> str:
10911103
if isinstance(value, SecretStr):
10921104
return value.get_secret_value()
1105+
if isinstance(value, dict):
1106+
return json.dumps(value)
10931107
if isinstance(value, bool):
10941108
return "true" if value else "false"
10951109
return str(value)

‎datacontract/engines/ibis/connections/connect.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -860,6 +860,9 @@ def _connect_trino(ibis, server: Server, config: Config):
860860
database=config.get_trino_catalog() or server.catalog,
861861
schema=config.get_trino_schema() or server.schema_,
862862
)
863+
http_headers = config.get_trino_http_headers()
864+
if http_headers is not None:
865+
kwargs["http_headers"] = http_headers
863866

864867
if authentication == "basic":
865868
user = config.get_trino_username(required=True)

‎docs/docs/configuration.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -412,6 +412,7 @@ Every option, by its environment variable name and the matching `Config` field.
412412
| `DATACONTRACT_TRINO_USERNAME` | `trino_username` | string | |
413413
| `DATACONTRACT_TRINO_PASSWORD` | `trino_password` | string (secret) | |
414414
| `DATACONTRACT_TRINO_JWT_TOKEN` | `trino_jwt_token` | string (secret) | |
415+
| `DATACONTRACT_TRINO_HTTP_HEADERS` | `trino_http_headers` | string (json) | |
415416
| `DATACONTRACT_TRINO_HOST` | `trino_host` | string | Overrides `host` from the contract's `servers` block |
416417
| `DATACONTRACT_TRINO_PORT` | `trino_port` | integer | Overrides `port` from the contract's `servers` block |
417418
| `DATACONTRACT_TRINO_CATALOG` | `trino_catalog` | string | Overrides `catalog` from the contract's `servers` block |

‎docs/docs/reference/trino.md‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,38 @@ servers:
3232

3333
`host`, `port`, `catalog`, and `schema` come from the contract's `servers` block, and can be overridden with `DATACONTRACT_TRINO_HOST`, `DATACONTRACT_TRINO_PORT`, `DATACONTRACT_TRINO_CATALOG`, and `DATACONTRACT_TRINO_SCHEMA`.
3434

35+
## Custom HTTP headers
36+
37+
Set `DATACONTRACT_TRINO_HTTP_HEADERS` to a JSON object with string keys and string values:
38+
39+
```bash
40+
export DATACONTRACT_TRINO_HTTP_HEADERS='{"X-Trino-Client-Info":"datacontract-cli","X-Trino-Routing-Group":"analytics"}'
41+
```
42+
43+
Headers are passed to `trino.dbapi.connect(http_headers=...)` for both `datacontract test` and `datacontract import trino`.
44+
45+
In Python, pass a dictionary to `Config`:
46+
47+
```python
48+
config = Config(
49+
trino_http_headers={
50+
"X-Trino-Client-Info": "datacontract-cli",
51+
"X-Trino-Routing-Group": "analytics",
52+
},
53+
)
54+
```
55+
56+
In a [configuration file](../configuration.md), use a YAML mapping:
57+
58+
```yaml
59+
trino:
60+
http_headers:
61+
X-Trino-Client-Info: datacontract-cli
62+
X-Trino-Routing-Group: ${TRINO_ROUTING_GROUP:-analytics}
63+
```
64+
65+
`Config(...)` merges headers from the environment with the supplied dictionary; supplied values win for matching keys. A YAML configuration supplies its own mapping without merging environment headers. Header values are not masked.
66+
3567
## Data types
3668

3769
### Importing

‎tests/test_config.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,26 @@ def test_secrets_do_not_leak_into_repr():
6767
assert config.snowflake_password.get_secret_value() == "super-secret"
6868

6969

70+
def test_trino_http_headers_can_be_configured_by_env_name():
71+
config = Config.resolve({"DATACONTRACT_TRINO_HTTP_HEADERS": '{"X-Trino-Client-Info": "datacontract-cli"}'})
72+
73+
assert config.get_trino_http_headers() == {"X-Trino-Client-Info": "datacontract-cli"}
74+
75+
76+
def test_trino_http_headers_merge_env_with_explicit_config(monkeypatch):
77+
monkeypatch.setenv(
78+
"DATACONTRACT_TRINO_HTTP_HEADERS",
79+
'{"X-Trino-Client-Info": "datacontract-cli", "X-Trino-Routing-Group": "default"}',
80+
)
81+
config = Config(trino_http_headers={"X-Trino-Routing-Group": "analytics"})
82+
83+
assert config.get_trino_http_headers() == {
84+
"X-Trino-Client-Info": "datacontract-cli",
85+
"X-Trino-Routing-Group": "analytics",
86+
}
87+
assert Config.resolve(config.to_env_dict()).get_trino_http_headers() == config.get_trino_http_headers()
88+
89+
7090
def test_unknown_options_raise():
7191
with pytest.raises(ValueError, match="snowflake_pasword"):
7292
Config(snowflake_pasword="typo")

‎tests/test_config_file.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,34 @@ def test_from_yaml_maps_sections_to_fields(tmp_path):
5555
assert config.max_errors == 10
5656

5757

58+
def test_from_yaml_reads_trino_http_headers_as_a_mapping(tmp_path, monkeypatch):
59+
monkeypatch.setenv("TRINO_ROUTING_GROUP", "analytics")
60+
monkeypatch.setenv("DATACONTRACT_TRINO_HTTP_HEADERS", '{"X-Trino-Routing-Group": "default"}')
61+
path = _write_config(
62+
tmp_path,
63+
"""
64+
trino:
65+
http_headers:
66+
X-Trino-Client-Info: datacontract-cli
67+
X-Trino-Routing-Group: ${TRINO_ROUTING_GROUP}
68+
""",
69+
)
70+
71+
config = Config.from_yaml(path)
72+
73+
assert config.get_trino_http_headers() == {
74+
"X-Trino-Client-Info": "datacontract-cli",
75+
"X-Trino-Routing-Group": "analytics",
76+
}
77+
78+
79+
def test_from_yaml_empty_trino_http_headers_override_env(tmp_path, monkeypatch):
80+
monkeypatch.setenv("DATACONTRACT_TRINO_HTTP_HEADERS", '{"X-Trino-Routing-Group": "analytics"}')
81+
path = _write_config(tmp_path, "trino:\n http_headers: {}\n")
82+
83+
assert Config.from_yaml(path).get_trino_http_headers() == {}
84+
85+
5886
def test_from_yaml_interpolates_environment_references(tmp_path, monkeypatch):
5987
monkeypatch.setenv("SNOWFLAKE_PASSWORD", "pw-from-env")
6088
path = _write_config(tmp_path, "snowflake:\n password: ${SNOWFLAKE_PASSWORD}\n")

‎tests/test_connect_trino.py‎

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
"DATACONTRACT_TRINO_USERNAME",
1818
"DATACONTRACT_TRINO_PASSWORD",
1919
"DATACONTRACT_TRINO_JWT_TOKEN",
20+
"DATACONTRACT_TRINO_HTTP_HEADERS",
2021
"DATACONTRACT_TRINO_HOST",
2122
"DATACONTRACT_TRINO_PORT",
2223
"DATACONTRACT_TRINO_CATALOG",
@@ -49,8 +50,8 @@ def _server(**kwargs):
4950
return Server(**defaults)
5051

5152

52-
def _connect(server=None):
53-
return connect_ibis(Run.create_run(), data_contract=None, server=server or _server())
53+
def _connect(server=None, config=None):
54+
return connect_ibis(Run.create_run(), data_contract=None, server=server or _server(), config=config)
5455

5556

5657
def test_basic_auth_is_default(env, captured_connect):
@@ -140,3 +141,34 @@ def test_env_variables_override_the_contract_server_details(env, captured_connec
140141
assert captured_connect["port"] == 8443
141142
assert captured_connect["database"] == "env_catalog"
142143
assert captured_connect["schema"] == "env_schema"
144+
145+
146+
def test_http_headers_are_forwarded(env, captured_connect):
147+
env.setenv("DATACONTRACT_TRINO_USERNAME", "my_user")
148+
env.setenv(
149+
"DATACONTRACT_TRINO_HTTP_HEADERS",
150+
'{"X-Trino-Client-Info": "datacontract-cli", "X-Trino-Routing-Group": "analytics"}',
151+
)
152+
153+
_connect()
154+
155+
assert captured_connect["http_headers"] == {
156+
"X-Trino-Client-Info": "datacontract-cli",
157+
"X-Trino-Routing-Group": "analytics",
158+
}
159+
160+
161+
def test_http_headers_dictionary_is_forwarded(env, captured_connect):
162+
from datacontract import Config
163+
164+
config = Config(
165+
trino_username="my_user",
166+
trino_http_headers={"X-Trino-Client-Info": "datacontract-cli", "X-Trino-Routing-Group": "analytics"},
167+
)
168+
169+
_connect(config=config)
170+
171+
assert captured_connect["http_headers"] == {
172+
"X-Trino-Client-Info": "datacontract-cli",
173+
"X-Trino-Routing-Group": "analytics",
174+
}

‎update_config_options.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ def _type_label(annotation) -> str:
6161
text = str(annotation)
6262
if "SecretStr" in text:
6363
return "string (secret)"
64+
if "dict" in text:
65+
return "string (json)"
6466
if "int" in text:
6567
return "integer"
6668
if "bool" in text:

0 commit comments

Comments
 (0)