datadouble-salesforce 0.0.3__py3-none-any.whl

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.
@@ -0,0 +1,151 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """The Salesforce engine adapter for Datadouble.
5
+
6
+ Spec settings::
7
+
8
+ sources:
9
+ app:
10
+ engine: salesforce
11
+ connection:
12
+ instance_url: {env: SHOP_SF_INSTANCE_URL} # by reference
13
+ access_token: {env: SHOP_SF_ACCESS_TOKEN}
14
+ api_version: "62.0" # the default
15
+ objects: [Account, Contact, "Acme__*"] # optional: only these objects
16
+
17
+ or, for the fake org (:mod:`datadouble_salesforce.fake`)::
18
+
19
+ connection:
20
+ fake: /path/to/org.sqlite
21
+
22
+ The adapter reads the org through its REST, Tooling and Bulk 2.0 APIs, and
23
+ builds its working copies, anonymization and images locally in SQLite: the
24
+ image is logical, each object's records as JSON lines.
25
+ """
26
+
27
+ import re
28
+ from collections.abc import Generator, Mapping
29
+ from contextlib import contextmanager
30
+ from pathlib import Path
31
+ from typing import Annotated
32
+
33
+ import httpx
34
+ from pydantic import BaseModel, ConfigDict, Field, JsonValue, StringConstraints
35
+
36
+ from datadouble.engine import EngineError, ServerPlan, SourceSession, Tooling, WorkingDatabases
37
+ from datadouble.names import EngineName
38
+ from datadouble.planner import Capabilities
39
+ from datadouble.runtime import identity
40
+ from datadouble.secrets import resolve_secret
41
+ from datadouble.settings import NoSettings, parse_settings
42
+ from datadouble.spec import ImageFormat, SecretRef
43
+ from datadouble_salesforce.fake import FakeOrg, FakeTransport
44
+ from datadouble_salesforce.org import DEFAULT_API_VERSION, RestOrg
45
+ from datadouble_salesforce.source import ENGINE, SalesforceSource
46
+ from datadouble_salesforce.working import SalesforceWorking
47
+
48
+ FAKE_URL = "https://fake.example.com"
49
+ """The instance URL requests to the fake org name."""
50
+ _TIMEOUT = httpx.Timeout(120.0, connect=15.0)
51
+
52
+
53
+ type HiddenField = Annotated[str, StringConstraints(pattern=r"^[A-Za-z0-9_]+\.[A-Za-z0-9_]+$")]
54
+ """A field as ``Object.Field``."""
55
+
56
+
57
+ class OrgConnection(BaseModel):
58
+ """The ``sources.<name>.connection`` settings for an org."""
59
+
60
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
61
+
62
+ instance_url: SecretRef
63
+ access_token: SecretRef
64
+ api_version: str = Field(default=DEFAULT_API_VERSION, pattern=re.compile(r"^\d+\.\d$"))
65
+ objects: tuple[str, ...] = ()
66
+ """Patterns (``*``, ``?``, ``[...]``) for the objects to read; all, when empty."""
67
+ hidden: tuple[HiddenField, ...] = ()
68
+ """Fields field-level security may hide from the user, which copies go without."""
69
+
70
+
71
+ class FakeConnection(BaseModel):
72
+ """The ``sources.<name>.connection`` settings for the fake org."""
73
+
74
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
75
+
76
+ fake: str
77
+ api_version: str = Field(default=DEFAULT_API_VERSION, pattern=re.compile(r"^\d+\.\d$"))
78
+ objects: tuple[str, ...] = ()
79
+ hidden: tuple[HiddenField, ...] = ()
80
+
81
+
82
+ class SalesforceEngine:
83
+ """Implements :class:`datadouble.engine.EngineAdapter` for Salesforce."""
84
+
85
+ @property
86
+ def name(self) -> EngineName:
87
+ """``salesforce``."""
88
+ return ENGINE
89
+
90
+ @property
91
+ def owner(self) -> str:
92
+ """Whoever runs Datadouble: copies are local files, served by no server."""
93
+ return identity()
94
+
95
+ def capabilities(self) -> Capabilities:
96
+ """Logical images only; no expressions, nested strategy or hooks."""
97
+ return Capabilities(
98
+ formats=(ImageFormat.LOGICAL,), expressions=False, nested=False, hooks=False
99
+ )
100
+
101
+ @contextmanager
102
+ def connect(self, connection: Mapping[str, JsonValue]) -> Generator[SourceSession]:
103
+ """Open the org, or the fake."""
104
+ settings: OrgConnection | FakeConnection
105
+ if "fake" in connection:
106
+ settings = parse_settings(FakeConnection, connection, "salesforce connection")
107
+ path = Path(settings.fake)
108
+ if not path.is_file():
109
+ message = f"the fake org {path} does not exist"
110
+ raise EngineError(message)
111
+ transport: httpx.BaseTransport = FakeTransport(FakeOrg(path))
112
+ url, token, poll = FAKE_URL, "fake", 0.0
113
+ else:
114
+ settings = parse_settings(OrgConnection, connection, "salesforce connection")
115
+ transport = httpx.HTTPTransport(retries=2)
116
+ url, token = (
117
+ resolve_secret(settings.instance_url),
118
+ resolve_secret(settings.access_token),
119
+ )
120
+ poll = 2.0
121
+ headers = {"Authorization": f"Bearer {token}", "Accept": "application/json"}
122
+ with httpx.Client(
123
+ base_url=url, headers=headers, transport=transport, timeout=_TIMEOUT
124
+ ) as client:
125
+ org = RestOrg(client, settings.api_version, poll_seconds=poll)
126
+ yield SalesforceSource(
127
+ org, settings.api_version, settings.objects, frozenset(settings.hidden)
128
+ )
129
+
130
+ def working(self, scratch: Path, tooling: Tooling, source_version: str) -> WorkingDatabases: # noqa: ARG002 - copies are SQLite at every API version
131
+ """SQLite copies under ``scratch``; no container image applies."""
132
+ parse_settings(NoSettings, tooling.server, "salesforce server")
133
+ if tooling.image is not None:
134
+ message = (
135
+ "Salesforce copies are local SQLite databases; sources.<name>.image does not apply"
136
+ )
137
+ raise EngineError(message)
138
+ return SalesforceWorking(scratch)
139
+
140
+ def server(self, image: Path, server_image: str | None) -> ServerPlan:
141
+ """A Salesforce image has no server to start."""
142
+ message = (
143
+ f"{image.name}: a Salesforce image has no server to start, in"
144
+ f" {server_image or 'any'} image; its copies are records for an org"
145
+ )
146
+ raise EngineError(message)
147
+
148
+
149
+ def engine() -> SalesforceEngine:
150
+ """The entry point named in ``datadouble.engines``."""
151
+ return SalesforceEngine()
@@ -0,0 +1,181 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Cassettes: recorded HTTP interactions with an org, scrubbed, and replayed.
5
+
6
+ :class:`RecordingTransport` passes each request on and keeps the request and
7
+ response. :func:`scrub` removes what must not be committed: credentials and
8
+ cookies (only the headers replay needs are kept), access tokens and session
9
+ IDs, the org's instance URL and other Salesforce hosts, which become
10
+ ``org.example.com``, and org IDs, which become ``00D000000000000AAA``.
11
+ :class:`ReplayTransport` answers requests from a cassette, matching method,
12
+ path, query and body, but not the host. Requests that repeat, such as a Bulk
13
+ API job's status, get their recorded responses in order, then the last one
14
+ again.
15
+ """
16
+
17
+ import re
18
+ from collections import deque
19
+ from collections.abc import Iterable
20
+ from pathlib import Path
21
+ from typing import Literal
22
+ from urllib.parse import urlsplit
23
+
24
+ import httpx
25
+ from pydantic import BaseModel, ConfigDict
26
+
27
+ EXAMPLE_HOST = "org.example.com"
28
+ EXAMPLE_ORG_ID = "00D000000000000AAA"
29
+ REDACTED = "REDACTED"
30
+ _KEPT_HEADERS = {"content-type", "sforce-locator"}
31
+ _SESSION_ID = re.compile(r"\b00D[A-Za-z0-9]{12,15}![A-Za-z0-9._\-]+")
32
+ _SECRET_FIELD = re.compile(
33
+ r'("(?:access_token|accessToken|refresh_token|refreshToken|id_token|sessionId|signature)"'
34
+ r'\s*:\s*)"[^"]*"'
35
+ )
36
+ _SALESFORCE_HOST = re.compile(
37
+ r"\b[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.(?:salesforce|force|visualforce|salesforce-sites"
38
+ r"|cloudforce|database)\.com\b"
39
+ )
40
+ # Alone, or URL-encoded in a query (%2700D...%27).
41
+ _ORG_ID = re.compile(
42
+ r"(?:(?<![A-Za-z0-9])|(?<=%[0-9A-Fa-f]{2}))00D[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?(?![A-Za-z0-9])"
43
+ )
44
+
45
+
46
+ class _Model(BaseModel):
47
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
48
+
49
+
50
+ class Interaction(_Model):
51
+ """One request and its response."""
52
+
53
+ method: str
54
+ url: str
55
+ """The path and query: replay ignores the host."""
56
+ body: str
57
+ status: int
58
+ headers: dict[str, str]
59
+ response: str
60
+
61
+
62
+ class Cassette(_Model):
63
+ """Interactions, in the order they happened."""
64
+
65
+ format: Literal[1] = 1
66
+ interactions: tuple[Interaction, ...]
67
+
68
+ def text(self) -> str:
69
+ """The cassette as indented JSON, as it is committed."""
70
+ return self.model_dump_json(indent=1) + "\n"
71
+
72
+ @classmethod
73
+ def read(cls, path: Path) -> "Cassette":
74
+ """Read a cassette."""
75
+ return cls.model_validate_json(path.read_bytes())
76
+
77
+
78
+ class CassetteError(httpx.TransportError):
79
+ """A request the cassette has no response for."""
80
+
81
+
82
+ def _target(request: httpx.Request) -> str:
83
+ parts = urlsplit(str(request.url))
84
+ return parts.path + (f"?{parts.query}" if parts.query else "")
85
+
86
+
87
+ class RecordingTransport(httpx.BaseTransport):
88
+ """Passes requests to another transport and records each interaction."""
89
+
90
+ def __init__(self, inner: httpx.BaseTransport) -> None:
91
+ """Record what ``inner`` answers."""
92
+ self.inner = inner
93
+ self.interactions: list[Interaction] = []
94
+
95
+ def handle_request(self, request: httpx.Request) -> httpx.Response:
96
+ """Pass the request on and keep it with its response."""
97
+ response = self.inner.handle_request(request)
98
+ content = response.read()
99
+ # The content is decoded now: its encoding and length no longer apply.
100
+ headers = {
101
+ k: v
102
+ for k, v in response.headers.items()
103
+ if k.lower() not in {"content-encoding", "content-length", "transfer-encoding"}
104
+ }
105
+ self.interactions.append(
106
+ Interaction(
107
+ method=request.method,
108
+ url=_target(request),
109
+ body=request.read().decode(),
110
+ status=response.status_code,
111
+ headers=headers,
112
+ response=content.decode(),
113
+ )
114
+ )
115
+ return httpx.Response(response.status_code, headers=headers, content=content)
116
+
117
+ def cassette(self) -> Cassette:
118
+ """What has been recorded so far, not yet scrubbed."""
119
+ return Cassette(interactions=tuple(self.interactions))
120
+
121
+
122
+ def _scrub_text(text: str, instance_url: str, secrets: Iterable[str]) -> str:
123
+ for secret in secrets:
124
+ if secret:
125
+ text = text.replace(secret, REDACTED)
126
+ text = _SESSION_ID.sub(REDACTED, text)
127
+ text = _SECRET_FIELD.sub(rf'\1"{REDACTED}"', text)
128
+ host = urlsplit(instance_url).hostname
129
+ if host:
130
+ text = text.replace(host, EXAMPLE_HOST)
131
+ text = _SALESFORCE_HOST.sub(EXAMPLE_HOST, text)
132
+ return _ORG_ID.sub(lambda m: EXAMPLE_ORG_ID[: len(m[0])], text)
133
+
134
+
135
+ def scrub(cassette: Cassette, instance_url: str, secrets: Iterable[str] = ()) -> Cassette:
136
+ """The cassette without credentials, session IDs, instance URLs or org IDs.
137
+
138
+ ``secrets`` are values to remove wherever they appear, such as the access
139
+ token the recording used.
140
+ """
141
+ known = tuple(secrets)
142
+
143
+ def clean(text: str) -> str:
144
+ return _scrub_text(text, instance_url, known)
145
+
146
+ return Cassette(
147
+ interactions=tuple(
148
+ Interaction(
149
+ method=i.method,
150
+ url=clean(i.url),
151
+ body=clean(i.body),
152
+ status=i.status,
153
+ headers={k: clean(v) for k, v in i.headers.items() if k.lower() in _KEPT_HEADERS},
154
+ response=clean(i.response),
155
+ )
156
+ for i in cassette.interactions
157
+ )
158
+ )
159
+
160
+
161
+ class ReplayTransport(httpx.BaseTransport):
162
+ """Answers requests from a cassette."""
163
+
164
+ def __init__(self, cassette: Cassette) -> None:
165
+ """Replay ``cassette``."""
166
+ self.recorded: dict[tuple[str, str, str], deque[Interaction]] = {}
167
+ for interaction in cassette.interactions:
168
+ key = (interaction.method, interaction.url, interaction.body)
169
+ self.recorded.setdefault(key, deque()).append(interaction)
170
+
171
+ def handle_request(self, request: httpx.Request) -> httpx.Response:
172
+ """The recorded response to a request like this one."""
173
+ key = (request.method, _target(request), request.read().decode())
174
+ found = self.recorded.get(key)
175
+ if not found:
176
+ message = f"the cassette has no response to {request.method} {key[1]}"
177
+ raise CassetteError(message)
178
+ interaction = found.popleft() if len(found) > 1 else found[0]
179
+ return httpx.Response(
180
+ interaction.status, headers=interaction.headers, content=interaction.response.encode()
181
+ )