semblance-databricks 0.1.0__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.
Files changed (47) hide show
  1. semblance_databricks-0.1.0/LICENSE.md +21 -0
  2. semblance_databricks-0.1.0/PKG-INFO +126 -0
  3. semblance_databricks-0.1.0/README.md +93 -0
  4. semblance_databricks-0.1.0/pyproject.toml +58 -0
  5. semblance_databricks-0.1.0/setup.cfg +4 -0
  6. semblance_databricks-0.1.0/src/semblance_databricks/__init__.py +19 -0
  7. semblance_databricks-0.1.0/src/semblance_databricks/app.py +104 -0
  8. semblance_databricks-0.1.0/src/semblance_databricks/auth.py +145 -0
  9. semblance_databricks-0.1.0/src/semblance_databricks/cli.py +112 -0
  10. semblance_databricks-0.1.0/src/semblance_databricks/compatibility.py +30 -0
  11. semblance_databricks-0.1.0/src/semblance_databricks/compatibility.yaml +269 -0
  12. semblance_databricks-0.1.0/src/semblance_databricks/config.py +52 -0
  13. semblance_databricks-0.1.0/src/semblance_databricks/errors.py +72 -0
  14. semblance_databricks-0.1.0/src/semblance_databricks/fixtures/__init__.py +5 -0
  15. semblance_databricks-0.1.0/src/semblance_databricks/fixtures/defaults/__init__.py +0 -0
  16. semblance_databricks-0.1.0/src/semblance_databricks/fixtures/defaults/acme.yaml +47 -0
  17. semblance_databricks-0.1.0/src/semblance_databricks/fixtures/loaders.py +196 -0
  18. semblance_databricks-0.1.0/src/semblance_databricks/http.py +34 -0
  19. semblance_databricks-0.1.0/src/semblance_databricks/ids.py +88 -0
  20. semblance_databricks-0.1.0/src/semblance_databricks/models/__init__.py +1 -0
  21. semblance_databricks-0.1.0/src/semblance_databricks/pagination.py +48 -0
  22. semblance_databricks-0.1.0/src/semblance_databricks/py.typed +0 -0
  23. semblance_databricks-0.1.0/src/semblance_databricks/registry.py +29 -0
  24. semblance_databricks-0.1.0/src/semblance_databricks/services/__init__.py +1 -0
  25. semblance_databricks-0.1.0/src/semblance_databricks/services/clusters/__init__.py +3 -0
  26. semblance_databricks-0.1.0/src/semblance_databricks/services/clusters/routes.py +191 -0
  27. semblance_databricks-0.1.0/src/semblance_databricks/services/dbfs/__init__.py +3 -0
  28. semblance_databricks-0.1.0/src/semblance_databricks/services/dbfs/routes.py +126 -0
  29. semblance_databricks-0.1.0/src/semblance_databricks/services/dbsql/__init__.py +3 -0
  30. semblance_databricks-0.1.0/src/semblance_databricks/services/dbsql/routes.py +163 -0
  31. semblance_databricks-0.1.0/src/semblance_databricks/services/deps.py +37 -0
  32. semblance_databricks-0.1.0/src/semblance_databricks/services/jobs/__init__.py +3 -0
  33. semblance_databricks-0.1.0/src/semblance_databricks/services/jobs/routes.py +168 -0
  34. semblance_databricks-0.1.0/src/semblance_databricks/services/permissions/__init__.py +5 -0
  35. semblance_databricks-0.1.0/src/semblance_databricks/services/permissions/routes.py +50 -0
  36. semblance_databricks-0.1.0/src/semblance_databricks/services/secrets/__init__.py +3 -0
  37. semblance_databricks-0.1.0/src/semblance_databricks/services/secrets/routes.py +53 -0
  38. semblance_databricks-0.1.0/src/semblance_databricks/services/workspace/__init__.py +3 -0
  39. semblance_databricks-0.1.0/src/semblance_databricks/services/workspace/routes.py +39 -0
  40. semblance_databricks-0.1.0/src/semblance_databricks/state.py +253 -0
  41. semblance_databricks-0.1.0/src/semblance_databricks/testing.py +66 -0
  42. semblance_databricks-0.1.0/src/semblance_databricks.egg-info/PKG-INFO +126 -0
  43. semblance_databricks-0.1.0/src/semblance_databricks.egg-info/SOURCES.txt +45 -0
  44. semblance_databricks-0.1.0/src/semblance_databricks.egg-info/dependency_links.txt +1 -0
  45. semblance_databricks-0.1.0/src/semblance_databricks.egg-info/entry_points.txt +2 -0
  46. semblance_databricks-0.1.0/src/semblance_databricks.egg-info/requires.txt +13 -0
  47. semblance_databricks-0.1.0/src/semblance_databricks.egg-info/top_level.txt +1 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Semblance Contributors
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,126 @@
1
+ Metadata-Version: 2.4
2
+ Name: semblance-databricks
3
+ Version: 0.1.0
4
+ Summary: Unofficial local HTTP simulation of selected Databricks workspace REST operations
5
+ Author: Semblance Contributors
6
+ License-Expression: MIT
7
+ Project-URL: Documentation, https://semblance.readthedocs.io/en/latest/guides/databricks/
8
+ Project-URL: Repository, https://github.com/eddiethedean/semblance
9
+ Project-URL: Changelog, https://github.com/eddiethedean/semblance/blob/main/packages/semblance-databricks/CHANGELOG.md
10
+ Keywords: databricks,mock,simulation,testing,fastapi
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Software Development :: Testing
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE.md
21
+ Requires-Dist: semblance<0.8,>=0.7.0
22
+ Requires-Dist: pydantic>=2.0.0
23
+ Requires-Dist: pyyaml>=6.0
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
26
+ Requires-Dist: httpx>=0.25.0; extra == "dev"
27
+ Requires-Dist: ruff>=0.16.0; extra == "dev"
28
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
29
+ Requires-Dist: types-PyYAML>=6.0.0; extra == "dev"
30
+ Provides-Extra: sdk
31
+ Requires-Dist: databricks-sdk==0.57.0; extra == "sdk"
32
+ Dynamic: license-file
33
+
34
+ # semblance-databricks
35
+
36
+ **Unofficial** local HTTP simulation of selected [Databricks workspace REST](https://docs.databricks.com/api/workspace/) operations (clusters, jobs, warehouses, secrets metadata, DBFS stubs, permissions, SQL statements).
37
+
38
+ This package is **not affiliated with, endorsed by, or equivalent to Databricks**. It does not run Spark, jobs, or SQL engines. It is a test double for client development and CI.
39
+
40
+ Verified against public workspace REST documentation dated **2026-08-19**. See `compatibility.yaml` (also served at `/.well-known/semblance-databricks-compat.json`).
41
+
42
+ Requires `semblance` 0.7.x.
43
+
44
+ ## Install
45
+
46
+ ```bash
47
+ pip install semblance-databricks
48
+ ```
49
+
50
+ From a clone of this repository:
51
+
52
+ ```bash
53
+ pip install -e ".[dev]"
54
+ pip install -e "packages/semblance-databricks[dev]"
55
+ ```
56
+
57
+ Optional official SDK extra (not installed in default CI):
58
+
59
+ ```bash
60
+ pip install "semblance-databricks[sdk]"
61
+ pytest packages/semblance-databricks/tests -m sdk
62
+ ```
63
+
64
+ Pinned SDK: `databricks-sdk==0.57.0`. Untested SDK versions are not implied compatible.
65
+
66
+ ## Quick start (HTTP)
67
+
68
+ ```python
69
+ from semblance_databricks import DatabricksMock, DatabricksMockConfig
70
+ from semblance_databricks.testing import databricks_test_client
71
+
72
+ dbx = DatabricksMock(DatabricksMockConfig(seed=42, auth="optional"))
73
+ dbx.load_bundled_fixture()
74
+ client = databricks_test_client(dbx)
75
+
76
+ r = client.get("/api/2.1/clusters/list?page_size=2")
77
+ assert r.status_code == 200
78
+ ```
79
+
80
+ CLI:
81
+
82
+ ```bash
83
+ semblance-databricks fixture init --output databricks.yaml
84
+ semblance-databricks validate databricks.yaml
85
+ semblance-databricks operations
86
+ semblance-databricks serve --fixture databricks.yaml --port 8766
87
+ # or: semblance-databricks serve # bundled acme fixture
88
+ ```
89
+
90
+ Environment variables for local clients (not Databricks credentials): `SEMBLANCE_DATABRICKS_HOST`, `SEMBLANCE_DATABRICKS_TOKEN`.
91
+
92
+ ## Auth modes
93
+
94
+ - `disabled` — ignore `Authorization`
95
+ - `optional` (default) — missing token is OK; malformed `Bearer` values return 401
96
+ - `strict` — token must be in `DatabricksMockConfig.tokens`
97
+
98
+ Authentication errors never echo the token. This is not an OAuth server.
99
+
100
+ ## Fixtures
101
+
102
+ YAML/JSON version 1. Extra fields are rejected. Fixtures are **data only**. Secret **values** are never returned on REST (list and put only; there is no get-key).
103
+
104
+ `load_bundled_fixture()` loads the shipped `acme` workspace. Use `load_fixture(path)` for your own files. Advance cluster/run state with `dbx.tick()`.
105
+
106
+ ## Pagination
107
+
108
+ List endpoints use `page_size` or `limit` plus `page_token` / `next_page_token`. Tokens are opaque and checksummed. Tampering returns 400 `INVALID_PARAMETER_VALUE`.
109
+
110
+ ## Known unsupported (0.1.0)
111
+
112
+ - Unity Catalog, Model Serving, DLT / Spark Declarative Pipelines
113
+ - Jobs API 2.0 as primary (optional 2.1 aliases are representative)
114
+ - Real Spark/SQL execution (statements use fixture or allow-listed callbacks)
115
+
116
+ Unknown paths return Databricks-style 404. Known stubs such as `clusters/permanent-delete` and `dbfs/add-block` return 501 only when `auth=strict`.
117
+
118
+ ## Security
119
+
120
+ - Do not put production secrets in fixtures or tokens used with this mock
121
+ - Tokens are compared in-process and never written to error bodies
122
+ - Query/SQL/run-output behavior must be allow-listed Python, never YAML eval
123
+
124
+ ## License
125
+
126
+ MIT. Databricks is a trademark of its respective owners.
@@ -0,0 +1,93 @@
1
+ # semblance-databricks
2
+
3
+ **Unofficial** local HTTP simulation of selected [Databricks workspace REST](https://docs.databricks.com/api/workspace/) operations (clusters, jobs, warehouses, secrets metadata, DBFS stubs, permissions, SQL statements).
4
+
5
+ This package is **not affiliated with, endorsed by, or equivalent to Databricks**. It does not run Spark, jobs, or SQL engines. It is a test double for client development and CI.
6
+
7
+ Verified against public workspace REST documentation dated **2026-08-19**. See `compatibility.yaml` (also served at `/.well-known/semblance-databricks-compat.json`).
8
+
9
+ Requires `semblance` 0.7.x.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ pip install semblance-databricks
15
+ ```
16
+
17
+ From a clone of this repository:
18
+
19
+ ```bash
20
+ pip install -e ".[dev]"
21
+ pip install -e "packages/semblance-databricks[dev]"
22
+ ```
23
+
24
+ Optional official SDK extra (not installed in default CI):
25
+
26
+ ```bash
27
+ pip install "semblance-databricks[sdk]"
28
+ pytest packages/semblance-databricks/tests -m sdk
29
+ ```
30
+
31
+ Pinned SDK: `databricks-sdk==0.57.0`. Untested SDK versions are not implied compatible.
32
+
33
+ ## Quick start (HTTP)
34
+
35
+ ```python
36
+ from semblance_databricks import DatabricksMock, DatabricksMockConfig
37
+ from semblance_databricks.testing import databricks_test_client
38
+
39
+ dbx = DatabricksMock(DatabricksMockConfig(seed=42, auth="optional"))
40
+ dbx.load_bundled_fixture()
41
+ client = databricks_test_client(dbx)
42
+
43
+ r = client.get("/api/2.1/clusters/list?page_size=2")
44
+ assert r.status_code == 200
45
+ ```
46
+
47
+ CLI:
48
+
49
+ ```bash
50
+ semblance-databricks fixture init --output databricks.yaml
51
+ semblance-databricks validate databricks.yaml
52
+ semblance-databricks operations
53
+ semblance-databricks serve --fixture databricks.yaml --port 8766
54
+ # or: semblance-databricks serve # bundled acme fixture
55
+ ```
56
+
57
+ Environment variables for local clients (not Databricks credentials): `SEMBLANCE_DATABRICKS_HOST`, `SEMBLANCE_DATABRICKS_TOKEN`.
58
+
59
+ ## Auth modes
60
+
61
+ - `disabled` — ignore `Authorization`
62
+ - `optional` (default) — missing token is OK; malformed `Bearer` values return 401
63
+ - `strict` — token must be in `DatabricksMockConfig.tokens`
64
+
65
+ Authentication errors never echo the token. This is not an OAuth server.
66
+
67
+ ## Fixtures
68
+
69
+ YAML/JSON version 1. Extra fields are rejected. Fixtures are **data only**. Secret **values** are never returned on REST (list and put only; there is no get-key).
70
+
71
+ `load_bundled_fixture()` loads the shipped `acme` workspace. Use `load_fixture(path)` for your own files. Advance cluster/run state with `dbx.tick()`.
72
+
73
+ ## Pagination
74
+
75
+ List endpoints use `page_size` or `limit` plus `page_token` / `next_page_token`. Tokens are opaque and checksummed. Tampering returns 400 `INVALID_PARAMETER_VALUE`.
76
+
77
+ ## Known unsupported (0.1.0)
78
+
79
+ - Unity Catalog, Model Serving, DLT / Spark Declarative Pipelines
80
+ - Jobs API 2.0 as primary (optional 2.1 aliases are representative)
81
+ - Real Spark/SQL execution (statements use fixture or allow-listed callbacks)
82
+
83
+ Unknown paths return Databricks-style 404. Known stubs such as `clusters/permanent-delete` and `dbfs/add-block` return 501 only when `auth=strict`.
84
+
85
+ ## Security
86
+
87
+ - Do not put production secrets in fixtures or tokens used with this mock
88
+ - Tokens are compared in-process and never written to error bodies
89
+ - Query/SQL/run-output behavior must be allow-listed Python, never YAML eval
90
+
91
+ ## License
92
+
93
+ MIT. Databricks is a trademark of its respective owners.
@@ -0,0 +1,58 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "semblance-databricks"
7
+ version = "0.1.0"
8
+ description = "Unofficial local HTTP simulation of selected Databricks workspace REST operations"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE.md"]
13
+ authors = [{name = "Semblance Contributors"}]
14
+ keywords = ["databricks", "mock", "simulation", "testing", "fastapi"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.10",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Topic :: Software Development :: Testing",
23
+ ]
24
+ dependencies = [
25
+ "semblance>=0.7.0,<0.8",
26
+ "pydantic>=2.0.0",
27
+ "pyyaml>=6.0",
28
+ ]
29
+
30
+ [project.optional-dependencies]
31
+ dev = [
32
+ "pytest>=7.0.0",
33
+ "httpx>=0.25.0",
34
+ "ruff>=0.16.0",
35
+ "mypy>=1.0.0",
36
+ "types-PyYAML>=6.0.0",
37
+ ]
38
+ sdk = [
39
+ "databricks-sdk==0.57.0",
40
+ ]
41
+
42
+ [project.scripts]
43
+ semblance-databricks = "semblance_databricks.cli:main"
44
+
45
+ [project.urls]
46
+ Documentation = "https://semblance.readthedocs.io/en/latest/guides/databricks/"
47
+ Repository = "https://github.com/eddiethedean/semblance"
48
+ Changelog = "https://github.com/eddiethedean/semblance/blob/main/packages/semblance-databricks/CHANGELOG.md"
49
+
50
+ [tool.setuptools.packages.find]
51
+ where = ["src"]
52
+
53
+ [tool.setuptools.package-data]
54
+ semblance_databricks = [
55
+ "py.typed",
56
+ "compatibility.yaml",
57
+ "fixtures/defaults/*.yaml",
58
+ ]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,19 @@
1
+ """
2
+ Unofficial local simulation of selected Databricks workspace REST operations.
3
+
4
+ Not affiliated with, endorsed by, or equivalent to Databricks.
5
+ """
6
+
7
+ from semblance_databricks.app import DatabricksMock
8
+ from semblance_databricks.config import DatabricksMockConfig, TokenGrant
9
+ from semblance_databricks.fixtures.loaders import load_bundled_fixture
10
+ from semblance_databricks.testing import DatabricksMockContext, databricks_test_client
11
+
12
+ __all__ = [
13
+ "DatabricksMock",
14
+ "DatabricksMockConfig",
15
+ "DatabricksMockContext",
16
+ "TokenGrant",
17
+ "databricks_test_client",
18
+ "load_bundled_fixture",
19
+ ]
@@ -0,0 +1,104 @@
1
+ """DatabricksMock factory and ASGI construction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import random
6
+ from collections.abc import Callable
7
+ from importlib.metadata import PackageNotFoundError
8
+ from importlib.metadata import version as pkg_version
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from fastapi import FastAPI
13
+
14
+ from semblance_databricks.auth import DatabricksMiddleware
15
+ from semblance_databricks.compatibility import manifest_json
16
+ from semblance_databricks.config import DatabricksMockConfig
17
+ from semblance_databricks.errors import register_exception_handlers
18
+ from semblance_databricks.fixtures.loaders import (
19
+ apply_fixture,
20
+ bundled_acme_path,
21
+ load_fixture_file,
22
+ )
23
+ from semblance_databricks.ids import PageTokenCodec, token_secret
24
+ from semblance_databricks.services.clusters import create_clusters_router
25
+ from semblance_databricks.services.dbfs import create_dbfs_router
26
+ from semblance_databricks.services.dbsql import create_dbsql_router
27
+ from semblance_databricks.services.jobs import create_jobs_router
28
+ from semblance_databricks.services.permissions import create_permissions_router
29
+ from semblance_databricks.services.secrets import create_secrets_router
30
+ from semblance_databricks.services.workspace import create_workspace_router
31
+ from semblance_databricks.state import DatabricksState
32
+
33
+ _BUNDLED_FIXTURES = {"acme": bundled_acme_path}
34
+
35
+
36
+ def _distribution_version() -> str:
37
+ try:
38
+ return pkg_version("semblance-databricks")
39
+ except PackageNotFoundError:
40
+ return "0.1.0"
41
+
42
+
43
+ class DatabricksMock:
44
+ """Fixture-backed local simulation of selected Databricks REST operations."""
45
+
46
+ def __init__(self, config: DatabricksMockConfig | None = None) -> None:
47
+ self.config = config or DatabricksMockConfig()
48
+ self.state = DatabricksState(seed=self.config.seed)
49
+ self.page_token_codec = PageTokenCodec(token_secret(self.config.seed))
50
+ self._rng = random.Random(self.config.seed)
51
+
52
+ def load_fixture(self, path: str | Path) -> DatabricksMock:
53
+ self.state.clear()
54
+ doc = load_fixture_file(path)
55
+ apply_fixture(doc, self.state)
56
+ return self
57
+
58
+ def load_bundled_fixture(self, name: str = "acme") -> DatabricksMock:
59
+ """Load a fixture shipped with the package (currently ``acme``)."""
60
+ loader = _BUNDLED_FIXTURES.get(name)
61
+ if loader is None:
62
+ known = ", ".join(sorted(_BUNDLED_FIXTURES))
63
+ raise ValueError(
64
+ f"unknown bundled fixture {name!r}; expected one of: {known}"
65
+ )
66
+ return self.load_fixture(loader())
67
+
68
+ def tick(self) -> None:
69
+ """Advance virtual-clock cluster and run state machines."""
70
+ self.state.tick()
71
+
72
+ def register_statement(self, key: str, fn: Callable[..., Any]) -> None:
73
+ """Register an allow-listed callback keyed by SQL text or warehouse id."""
74
+ self.state.statement_callbacks[key] = fn
75
+
76
+ def as_fastapi(self) -> FastAPI:
77
+ app = FastAPI(
78
+ title="semblance-databricks",
79
+ description=(
80
+ "Unofficial local simulation of selected Databricks workspace "
81
+ "REST operations. Not affiliated with Databricks."
82
+ ),
83
+ version=_distribution_version(),
84
+ )
85
+ app.state.databricks_mock = self
86
+ register_exception_handlers(app)
87
+ app.add_middleware(
88
+ DatabricksMiddleware,
89
+ config=self.config,
90
+ rng=self._rng,
91
+ )
92
+ app.include_router(create_clusters_router())
93
+ app.include_router(create_jobs_router())
94
+ app.include_router(create_workspace_router())
95
+ app.include_router(create_dbsql_router())
96
+ app.include_router(create_secrets_router())
97
+ app.include_router(create_dbfs_router())
98
+ app.include_router(create_permissions_router())
99
+
100
+ @app.get("/.well-known/semblance-databricks-compat.json")
101
+ def compatibility() -> dict[str, Any]:
102
+ return manifest_json()
103
+
104
+ return app
@@ -0,0 +1,145 @@
1
+ """Auth, request-id, latency, error injection, and rate-limit middleware."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import random
7
+ import time
8
+ from collections import defaultdict
9
+ from collections.abc import Callable
10
+ from threading import Lock
11
+ from typing import Any
12
+
13
+ from starlette.middleware.base import BaseHTTPMiddleware
14
+ from starlette.requests import Request
15
+ from starlette.responses import JSONResponse, Response
16
+
17
+ from semblance_databricks.config import DatabricksMockConfig
18
+ from semblance_databricks.errors import databricks_error_body
19
+
20
+ REQUEST_ID_HEADER = "x-databricks-request-id"
21
+ ORG_ID_HEADER = "x-databricks-org-id"
22
+
23
+
24
+ class _SlidingWindow:
25
+ def __init__(self) -> None:
26
+ self._timestamps: dict[tuple[str, str], list[float]] = defaultdict(list)
27
+ self._lock = Lock()
28
+
29
+ def allow(self, path: str, method: str, limit: float) -> bool:
30
+ if limit <= 0:
31
+ return True
32
+ now = time.monotonic()
33
+ key = (path, method)
34
+ with self._lock:
35
+ ts_list = self._timestamps[key]
36
+ ts_list[:] = [t for t in ts_list if now - t < 1.0]
37
+ if len(ts_list) >= limit:
38
+ return False
39
+ ts_list.append(now)
40
+ return True
41
+
42
+
43
+ def _bearer_token(header: str | None) -> str | None:
44
+ if header is None or header == "":
45
+ return None
46
+ parts = header.split(None, 1)
47
+ if len(parts) != 2 or parts[0].lower() != "bearer":
48
+ raise ValueError("malformed")
49
+ token = parts[1].strip()
50
+ if not token:
51
+ raise ValueError("empty")
52
+ return token
53
+
54
+
55
+ class DatabricksMiddleware(BaseHTTPMiddleware):
56
+ def __init__(
57
+ self,
58
+ app: Any,
59
+ config: DatabricksMockConfig,
60
+ rng: random.Random,
61
+ ) -> None:
62
+ super().__init__(app)
63
+ self._config = config
64
+ self._rng = rng
65
+ self._limiter = _SlidingWindow()
66
+ self._req_n = 0
67
+
68
+ async def dispatch(
69
+ self, request: Request, call_next: Callable[[Request], Any]
70
+ ) -> Response:
71
+ incoming = request.headers.get(REQUEST_ID_HEADER)
72
+ self._req_n += 1
73
+ request_id = incoming if incoming else f"req-{self._config.seed}-{self._req_n}"
74
+ request.state.request_id = request_id
75
+
76
+ if self._config.rate_limit is not None:
77
+ if not self._limiter.allow(
78
+ request.url.path, request.method, self._config.rate_limit
79
+ ):
80
+ response = JSONResponse(
81
+ status_code=429,
82
+ content=databricks_error_body(
83
+ "REQUEST_LIMIT_EXCEEDED", "Rate limit exceeded"
84
+ ),
85
+ )
86
+ self._stamp(response, request_id)
87
+ return response
88
+
89
+ auth_error = self._check_auth(request)
90
+ if auth_error is not None:
91
+ self._stamp(auth_error, request_id)
92
+ return auth_error
93
+
94
+ if self._config.latency_ms or self._config.jitter_ms:
95
+ delay = self._config.latency_ms / 1000.0
96
+ if self._config.jitter_ms:
97
+ delay += self._rng.uniform(0, self._config.jitter_ms) / 1000.0
98
+ if delay > 0:
99
+ await asyncio.sleep(delay)
100
+
101
+ if self._config.error_rate > 0 and self._rng.random() < self._config.error_rate:
102
+ codes = self._config.error_codes or [500]
103
+ status = self._rng.choice(codes)
104
+ response = JSONResponse(
105
+ status_code=status,
106
+ content=databricks_error_body("INTERNAL_ERROR", "Injected error"),
107
+ )
108
+ self._stamp(response, request_id)
109
+ return response
110
+
111
+ response = await call_next(request)
112
+ self._stamp(response, request_id)
113
+ return response # type: ignore[no-any-return]
114
+
115
+ def _stamp(self, response: Response, request_id: str) -> None:
116
+ response.headers[REQUEST_ID_HEADER] = request_id
117
+ if self._config.org_id:
118
+ response.headers[ORG_ID_HEADER] = self._config.org_id
119
+
120
+ def _check_auth(self, request: Request) -> JSONResponse | None:
121
+ mode = self._config.auth
122
+ if mode == "disabled":
123
+ return None
124
+ header = request.headers.get("authorization")
125
+ try:
126
+ token = _bearer_token(header)
127
+ except ValueError:
128
+ return JSONResponse(
129
+ status_code=401,
130
+ content=databricks_error_body("UNAUTHENTICATED", "Invalid credentials"),
131
+ )
132
+ if mode == "optional":
133
+ return None
134
+ if token is None:
135
+ return JSONResponse(
136
+ status_code=401,
137
+ content=databricks_error_body("UNAUTHENTICATED", "Missing credentials"),
138
+ )
139
+ allowed = {g.token for g in self._config.tokens}
140
+ if token not in allowed:
141
+ return JSONResponse(
142
+ status_code=401,
143
+ content=databricks_error_body("UNAUTHENTICATED", "Invalid credentials"),
144
+ )
145
+ return None
@@ -0,0 +1,112 @@
1
+ """CLI: serve, validate, fixture init, operations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import os
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from semblance_databricks.app import DatabricksMock
11
+ from semblance_databricks.config import DatabricksMockConfig
12
+ from semblance_databricks.fixtures.loaders import bundled_acme_path, load_fixture_file
13
+ from semblance_databricks.registry import registered_operations
14
+
15
+
16
+ def cmd_serve(args: argparse.Namespace) -> None:
17
+ seed = (
18
+ args.seed
19
+ if args.seed is not None
20
+ else int(os.environ.get("SEMBLANCE_DATABRICKS_SEED", "42"))
21
+ )
22
+ host = os.environ.get("SEMBLANCE_DATABRICKS_HOST", args.host)
23
+ config = DatabricksMockConfig(seed=seed, auth=args.auth)
24
+ mock = DatabricksMock(config)
25
+ mock.load_fixture(args.fixture or bundled_acme_path())
26
+ app = mock.as_fastapi()
27
+ try:
28
+ import uvicorn
29
+ except ImportError as exc:
30
+ raise SystemExit(
31
+ "uvicorn not found. Install semblance (pulls uvicorn)."
32
+ ) from exc
33
+ uvicorn.run(app, host=host, port=args.port)
34
+
35
+
36
+ def cmd_validate(args: argparse.Namespace) -> None:
37
+ try:
38
+ load_fixture_file(args.fixture)
39
+ except Exception as exc:
40
+ raise SystemExit(f"Invalid fixture: {exc}") from exc
41
+ print("OK")
42
+
43
+
44
+ def cmd_fixture_init(args: argparse.Namespace) -> None:
45
+ dest = Path(args.output)
46
+ if dest.exists() and not args.force:
47
+ raise SystemExit(f"{dest} already exists (use --force to overwrite)")
48
+ dest.write_text(bundled_acme_path().read_text(encoding="utf-8"), encoding="utf-8")
49
+ print(f"Wrote {dest}")
50
+
51
+
52
+ def cmd_operations(_args: argparse.Namespace) -> None:
53
+ rows = registered_operations()
54
+ width = max((len(op.operation_id) for op in rows), default=8)
55
+ print(f"{'operation':<{width}} {'level':<16} method path")
56
+ for op in rows:
57
+ print(
58
+ f"{op.operation_id:<{width}} {op.support_level:<16} "
59
+ f"{op.method:<6} {op.path}"
60
+ )
61
+
62
+
63
+ def build_parser() -> argparse.ArgumentParser:
64
+ parser = argparse.ArgumentParser(
65
+ prog="semblance-databricks",
66
+ description=(
67
+ "Unofficial local Databricks workspace REST mock. "
68
+ "Not affiliated with Databricks."
69
+ ),
70
+ )
71
+ sub = parser.add_subparsers(dest="command", required=True)
72
+
73
+ serve = sub.add_parser("serve", help="Run a local mock server")
74
+ serve.add_argument(
75
+ "--fixture",
76
+ default=None,
77
+ help="YAML or JSON fixture path (default: bundled acme example)",
78
+ )
79
+ serve.add_argument("--host", default="127.0.0.1")
80
+ serve.add_argument("--port", type=int, default=8766)
81
+ serve.add_argument("--seed", type=int, default=None)
82
+ serve.add_argument(
83
+ "--auth",
84
+ default="optional",
85
+ choices=["disabled", "optional", "strict"],
86
+ )
87
+ serve.set_defaults(func=cmd_serve)
88
+
89
+ validate = sub.add_parser("validate", help="Validate a fixture without serving")
90
+ validate.add_argument("fixture")
91
+ validate.set_defaults(func=cmd_validate)
92
+
93
+ init = sub.add_parser("fixture", help="Fixture helpers")
94
+ init_sub = init.add_subparsers(dest="fixture_command", required=True)
95
+ init_cmd = init_sub.add_parser("init", help="Write the bundled example fixture")
96
+ init_cmd.add_argument("--output", required=True)
97
+ init_cmd.add_argument("--force", action="store_true")
98
+ init_cmd.set_defaults(func=cmd_fixture_init)
99
+
100
+ ops = sub.add_parser("operations", help="Print the compatibility table")
101
+ ops.set_defaults(func=cmd_operations)
102
+ return parser
103
+
104
+
105
+ def main(argv: list[str] | None = None) -> None:
106
+ parser = build_parser()
107
+ args = parser.parse_args(argv)
108
+ args.func(args)
109
+
110
+
111
+ if __name__ == "__main__":
112
+ main(sys.argv[1:])