heroku_applink 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.
- heroku_applink-0.1.0/LICENSE +14 -0
- heroku_applink-0.1.0/PKG-INFO +19 -0
- heroku_applink-0.1.0/README.md +10 -0
- heroku_applink-0.1.0/heroku_applink/__init__.py +21 -0
- heroku_applink-0.1.0/heroku_applink/context.py +93 -0
- heroku_applink-0.1.0/heroku_applink/data_api/__init__.py +270 -0
- heroku_applink-0.1.0/heroku_applink/data_api/_requests.py +327 -0
- heroku_applink-0.1.0/heroku_applink/data_api/exceptions.py +62 -0
- heroku_applink-0.1.0/heroku_applink/data_api/record.py +65 -0
- heroku_applink-0.1.0/heroku_applink/data_api/reference_id.py +15 -0
- heroku_applink-0.1.0/heroku_applink/data_api/unit_of_work.py +135 -0
- heroku_applink-0.1.0/heroku_applink/middleware.py +45 -0
- heroku_applink-0.1.0/heroku_applink.egg-info/PKG-INFO +19 -0
- heroku_applink-0.1.0/heroku_applink.egg-info/SOURCES.txt +17 -0
- heroku_applink-0.1.0/heroku_applink.egg-info/dependency_links.txt +1 -0
- heroku_applink-0.1.0/heroku_applink.egg-info/requires.txt +2 -0
- heroku_applink-0.1.0/heroku_applink.egg-info/top_level.txt +1 -0
- heroku_applink-0.1.0/pyproject.toml +13 -0
- heroku_applink-0.1.0/setup.cfg +4 -0
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
BSD 3-Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025, Salesforce.com, Inc.
|
|
4
|
+
All rights reserved.
|
|
5
|
+
|
|
6
|
+
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
|
7
|
+
|
|
8
|
+
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
|
9
|
+
|
|
10
|
+
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
|
11
|
+
|
|
12
|
+
3. Neither the name of Salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
|
13
|
+
|
|
14
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Metadata-Version: 2.2
|
|
2
|
+
Name: heroku_applink
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Simple SDK for Heroku AppLink and Salesforce development
|
|
5
|
+
Requires-Python: >=3.10
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: aiohttp>=3.11.12
|
|
8
|
+
Requires-Dist: orjson>=3.10.15
|
|
9
|
+
|
|
10
|
+
# Python SDK for Heroku AppLink
|
|
11
|
+
|
|
12
|
+
This library provides basic functionality for building Python apps that use
|
|
13
|
+
Heroku AppLink to secure communication and credential sharing with a Salesforce
|
|
14
|
+
org.
|
|
15
|
+
|
|
16
|
+
Though the interaction with AppLink is simple and easy to hand code, using the
|
|
17
|
+
SDK will quickstart your project experience.
|
|
18
|
+
|
|
19
|
+
Use of this project with Salesforce is subject to the TERMS_OF_USE.md document.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# Python SDK for Heroku AppLink
|
|
2
|
+
|
|
3
|
+
This library provides basic functionality for building Python apps that use
|
|
4
|
+
Heroku AppLink to secure communication and credential sharing with a Salesforce
|
|
5
|
+
org.
|
|
6
|
+
|
|
7
|
+
Though the interaction with AppLink is simple and easy to hand code, using the
|
|
8
|
+
SDK will quickstart your project experience.
|
|
9
|
+
|
|
10
|
+
Use of this project with Salesforce is subject to the TERMS_OF_USE.md document.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
|
|
2
|
+
from .context import ClientContext, Org, User
|
|
3
|
+
from .data_api.record import QueriedRecord, Record, RecordQueryResult
|
|
4
|
+
from .data_api.reference_id import ReferenceId
|
|
5
|
+
from .data_api.unit_of_work import UnitOfWork
|
|
6
|
+
from .middleware import IntegrationWsgiMiddleware, IntegrationAsgiMiddleware, client_context
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"client_context",
|
|
10
|
+
"ClientContext",
|
|
11
|
+
"Org",
|
|
12
|
+
"QueriedRecord",
|
|
13
|
+
"Record",
|
|
14
|
+
"RecordQueryResult",
|
|
15
|
+
"ReferenceId",
|
|
16
|
+
"UnitOfWork",
|
|
17
|
+
"User",
|
|
18
|
+
"IntegrationWsgiMiddleware",
|
|
19
|
+
"IntegrationAsgiMiddleware",
|
|
20
|
+
]
|
|
21
|
+
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import base64
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
from .data_api import DataAPI
|
|
6
|
+
|
|
7
|
+
__all__ = ["User", "Org", "ClientContext"]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True, kw_only=True, slots=True)
|
|
11
|
+
class User:
|
|
12
|
+
"""
|
|
13
|
+
Information about the Salesforce user that made the request.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
id: str
|
|
17
|
+
"""
|
|
18
|
+
The user's ID.
|
|
19
|
+
|
|
20
|
+
For example: `005JS000000H123`
|
|
21
|
+
"""
|
|
22
|
+
username: str
|
|
23
|
+
"""
|
|
24
|
+
The username of the user.
|
|
25
|
+
|
|
26
|
+
For example: `user@example.tld`
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True, kw_only=True, slots=True)
|
|
31
|
+
class Org:
|
|
32
|
+
"""Information about the Salesforce org and the user that made the request."""
|
|
33
|
+
|
|
34
|
+
id: str
|
|
35
|
+
"""
|
|
36
|
+
The Salesforce org ID.
|
|
37
|
+
|
|
38
|
+
For example: `00DJS0000000123ABC`
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
domain_url: str
|
|
42
|
+
"""
|
|
43
|
+
The canonical URL of the Salesforce org.
|
|
44
|
+
|
|
45
|
+
This URL never changes. Use this URL when making API calls to your org.
|
|
46
|
+
|
|
47
|
+
For example: `https://example-domain-url.my.salesforce.com`
|
|
48
|
+
"""
|
|
49
|
+
user: User
|
|
50
|
+
"""The currently logged in user."""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True, kw_only=True, slots=True)
|
|
54
|
+
class ClientContext:
|
|
55
|
+
"""Information about the Salesforce org that made the request."""
|
|
56
|
+
|
|
57
|
+
org: Org
|
|
58
|
+
"""Information about the Salesforce org and the user that made the request."""
|
|
59
|
+
data_api: DataAPI
|
|
60
|
+
"""An initialized data API client instance for interacting with data in the org."""
|
|
61
|
+
request_id: str
|
|
62
|
+
"""Request ID from the Salesforce org."""
|
|
63
|
+
access_token: str
|
|
64
|
+
"""Valid access token for the current context org/user."""
|
|
65
|
+
api_version: str
|
|
66
|
+
"""API version of the Salesforce component that made the request."""
|
|
67
|
+
namespace: str
|
|
68
|
+
"""Namespace of the Salesforce component that made the request."""
|
|
69
|
+
|
|
70
|
+
@classmethod
|
|
71
|
+
def from_header(cls, header: str):
|
|
72
|
+
decoded = base64.b64decode(header)
|
|
73
|
+
data = json.loads(decoded)
|
|
74
|
+
|
|
75
|
+
return cls(
|
|
76
|
+
org=Org(
|
|
77
|
+
id=data["orgId"],
|
|
78
|
+
domain_url=data["orgDomainUrl"],
|
|
79
|
+
user=User(
|
|
80
|
+
id=data["userContext"]["userId"],
|
|
81
|
+
username=data["userContext"]["username"],
|
|
82
|
+
),
|
|
83
|
+
),
|
|
84
|
+
request_id=data["requestId"],
|
|
85
|
+
access_token=data["accessToken"],
|
|
86
|
+
api_version=data["apiVersion"],
|
|
87
|
+
namespace=data["namespace"],
|
|
88
|
+
data_api=DataAPI(
|
|
89
|
+
org_domain_url=data["orgDomainUrl"],
|
|
90
|
+
api_version=data["apiVersion"],
|
|
91
|
+
access_token=data["accessToken"],
|
|
92
|
+
),
|
|
93
|
+
)
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
from typing import Any, TypeVar
|
|
2
|
+
|
|
3
|
+
import aiohttp
|
|
4
|
+
import orjson
|
|
5
|
+
from aiohttp.payload import BytesPayload
|
|
6
|
+
|
|
7
|
+
from ._requests import (
|
|
8
|
+
CompositeGraphRestApiRequest,
|
|
9
|
+
CreateRecordRestApiRequest,
|
|
10
|
+
DeleteRecordRestApiRequest,
|
|
11
|
+
QueryNextRecordsRestApiRequest,
|
|
12
|
+
QueryRecordsRestApiRequest,
|
|
13
|
+
RestApiRequest,
|
|
14
|
+
UpdateRecordRestApiRequest,
|
|
15
|
+
)
|
|
16
|
+
from .exceptions import ClientError, UnexpectedRestApiResponsePayload
|
|
17
|
+
from .record import Record, RecordQueryResult
|
|
18
|
+
from .reference_id import ReferenceId
|
|
19
|
+
from .unit_of_work import UnitOfWork
|
|
20
|
+
|
|
21
|
+
__all__ = ["DataAPI"]
|
|
22
|
+
|
|
23
|
+
T = TypeVar("T")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class DataAPI:
|
|
27
|
+
"""
|
|
28
|
+
Data API client to interact with data in a Salesforce org.
|
|
29
|
+
|
|
30
|
+
We provide a preconfigured instance of this client at `context.org.data_api`
|
|
31
|
+
to make it easier for you to query, insert, and update records.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
*,
|
|
37
|
+
org_domain_url: str,
|
|
38
|
+
api_version: str,
|
|
39
|
+
access_token: str,
|
|
40
|
+
session: aiohttp.ClientSession | None = None,
|
|
41
|
+
) -> None:
|
|
42
|
+
self._api_version = api_version
|
|
43
|
+
self._org_domain_url = org_domain_url
|
|
44
|
+
self._shared_session = session
|
|
45
|
+
|
|
46
|
+
self.access_token = access_token
|
|
47
|
+
|
|
48
|
+
async def query(self, soql: str) -> RecordQueryResult:
|
|
49
|
+
"""
|
|
50
|
+
Query for records using the given SOQL string.
|
|
51
|
+
|
|
52
|
+
For example:
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
result = await context.org.data_api.query("SELECT Id, Name FROM Account")
|
|
56
|
+
|
|
57
|
+
for record in result.records:
|
|
58
|
+
# ...
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
If the returned `RecordQueryResult`'s `done` attribute is `False`, there are more
|
|
62
|
+
records to be returned. To retrieve these, use `DataAPI.query_more()`.
|
|
63
|
+
|
|
64
|
+
For more information, see the [Query REST API documentation](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_query.htm).
|
|
65
|
+
""" # noqa: E501 pylint: disable=line-too-long
|
|
66
|
+
return await self._execute(
|
|
67
|
+
QueryRecordsRestApiRequest(soql, self._download_file)
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
async def query_more(self, result: RecordQueryResult) -> RecordQueryResult:
|
|
71
|
+
"""
|
|
72
|
+
Query for more records, based on the given `RecordQueryResult`.
|
|
73
|
+
|
|
74
|
+
For example:
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
result = await context.org.data_api.query("SELECT Id, Name FROM Account")
|
|
78
|
+
|
|
79
|
+
if not result.done:
|
|
80
|
+
query_more_result = await context.org.data_api.query_more(result)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
For more information, see the [Query More Results REST API documentation](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_query_more_results.htm).
|
|
84
|
+
""" # noqa: E501 pylint: disable=line-too-long
|
|
85
|
+
if result.next_records_url is None:
|
|
86
|
+
return RecordQueryResult(
|
|
87
|
+
done=True,
|
|
88
|
+
total_size=result.total_size,
|
|
89
|
+
records=[],
|
|
90
|
+
next_records_url=None,
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
return await self._execute(
|
|
94
|
+
QueryNextRecordsRestApiRequest(result.next_records_url, self._download_file)
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
async def create(self, record: Record) -> str:
|
|
98
|
+
"""
|
|
99
|
+
Create a new record based on the given `Record` object.
|
|
100
|
+
|
|
101
|
+
Returns the ID of the new record.
|
|
102
|
+
|
|
103
|
+
For example:
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
record_id = await context.org.data_api.create(
|
|
107
|
+
Record(
|
|
108
|
+
type="Account",
|
|
109
|
+
fields={
|
|
110
|
+
"Name": "Example Account",
|
|
111
|
+
},
|
|
112
|
+
)
|
|
113
|
+
)
|
|
114
|
+
```
|
|
115
|
+
"""
|
|
116
|
+
return await self._execute(CreateRecordRestApiRequest(record))
|
|
117
|
+
|
|
118
|
+
async def update(self, record: Record) -> str:
|
|
119
|
+
"""
|
|
120
|
+
Update an existing record based on the given `Record` object.
|
|
121
|
+
|
|
122
|
+
The given `Record` must contain an `Id` field. Returns the ID of the record that was updated.
|
|
123
|
+
|
|
124
|
+
For example:
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
await context.org.data_api.update(
|
|
128
|
+
Record(
|
|
129
|
+
type="Account",
|
|
130
|
+
fields={
|
|
131
|
+
"Id": "001B000001Lp1FxIAJ",
|
|
132
|
+
"Name": "New Name",
|
|
133
|
+
},
|
|
134
|
+
)
|
|
135
|
+
)
|
|
136
|
+
```
|
|
137
|
+
"""
|
|
138
|
+
return await self._execute(UpdateRecordRestApiRequest(record))
|
|
139
|
+
|
|
140
|
+
async def delete(self, object_type: str, record_id: str) -> str:
|
|
141
|
+
"""
|
|
142
|
+
Delete an existing record of the given Salesforce object type and ID.
|
|
143
|
+
|
|
144
|
+
Returns the ID of the record that was deleted.
|
|
145
|
+
|
|
146
|
+
For example:
|
|
147
|
+
|
|
148
|
+
```python
|
|
149
|
+
await data_api.delete("Account", "001B000001Lp1FxIAJ")
|
|
150
|
+
```
|
|
151
|
+
"""
|
|
152
|
+
return await self._execute(DeleteRecordRestApiRequest(object_type, record_id))
|
|
153
|
+
|
|
154
|
+
async def commit_unit_of_work(
|
|
155
|
+
self, unit_of_work: UnitOfWork
|
|
156
|
+
) -> dict[ReferenceId, str]:
|
|
157
|
+
"""
|
|
158
|
+
Commit a `UnitOfWork`, which executes all operations registered with it.
|
|
159
|
+
|
|
160
|
+
If any of these operations fail, the whole unit is rolled back. To examine results for a
|
|
161
|
+
single operation, inspect the returned dict (which is keyed with `ReferenceId` objects
|
|
162
|
+
returned from the `register*` functions on `UnitOfWork`).
|
|
163
|
+
|
|
164
|
+
For example:
|
|
165
|
+
|
|
166
|
+
```python
|
|
167
|
+
# Create a unit of work, against which multiple operations can be registered.
|
|
168
|
+
unit_of_work = UnitOfWork()
|
|
169
|
+
|
|
170
|
+
first_reference_id = unit_of_work.register_create(
|
|
171
|
+
# ...
|
|
172
|
+
)
|
|
173
|
+
second_reference_id = unit_of_work.register_create(
|
|
174
|
+
# ...
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
# Commit the unit of work, executing all of the operations registered above.
|
|
178
|
+
result = await context.org.data_api.commit_unit_of_work(unit_of_work)
|
|
179
|
+
|
|
180
|
+
# The result of each operation.
|
|
181
|
+
first_record_id = result[first_create_reference_id]
|
|
182
|
+
second_record_id = result[second_create_reference_id]
|
|
183
|
+
```
|
|
184
|
+
"""
|
|
185
|
+
return await self._execute(
|
|
186
|
+
CompositeGraphRestApiRequest(
|
|
187
|
+
self._api_version,
|
|
188
|
+
unit_of_work._sub_requests, # pyright: ignore [reportPrivateUsage] pylint:disable=protected-access
|
|
189
|
+
)
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
async def _execute(self, rest_api_request: RestApiRequest[T]) -> T:
|
|
193
|
+
url: str = rest_api_request.url(self._org_domain_url, self._api_version)
|
|
194
|
+
method: str = rest_api_request.http_method()
|
|
195
|
+
body = rest_api_request.request_body()
|
|
196
|
+
|
|
197
|
+
session = self._shared_session or _create_session()
|
|
198
|
+
|
|
199
|
+
try:
|
|
200
|
+
response = await session.request(
|
|
201
|
+
method,
|
|
202
|
+
url,
|
|
203
|
+
headers=self._default_headers(),
|
|
204
|
+
data=None if body is None else _json_serialize(body),
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
# Using orjson for faster JSON deserialization over the stdlib.
|
|
208
|
+
# This is not implemented using the `loads` argument to `Response.json` since:
|
|
209
|
+
# - We don't want the content type validation, since some successful requests.py return 204
|
|
210
|
+
# (No Content) which will not have an `application/json`` content type header. However,
|
|
211
|
+
# these parse just fine as JSON helping to unify the interface to the REST request classes.
|
|
212
|
+
# - Orjson's performance/memory usage is better if it is passed bytes directly instead of `str`.
|
|
213
|
+
response_body = await response.read()
|
|
214
|
+
json_body = orjson.loads(response_body) if response_body else None
|
|
215
|
+
except aiohttp.ClientError as e:
|
|
216
|
+
# https://docs.aiohttp.org/en/stable/client_reference.html#client-exceptions
|
|
217
|
+
raise ClientError(
|
|
218
|
+
f"An error occurred while making the request: {e.__class__.__name__}: {e}"
|
|
219
|
+
) from e
|
|
220
|
+
except orjson.JSONDecodeError as e:
|
|
221
|
+
raise UnexpectedRestApiResponsePayload(
|
|
222
|
+
f"The server didn't respond with valid JSON: {e.__class__.__name__}: {e}"
|
|
223
|
+
) from e
|
|
224
|
+
finally:
|
|
225
|
+
if session != self._shared_session:
|
|
226
|
+
await session.close()
|
|
227
|
+
|
|
228
|
+
return await rest_api_request.process_response(response.status, json_body)
|
|
229
|
+
|
|
230
|
+
async def _download_file(self, url: str) -> bytes:
|
|
231
|
+
session = self._shared_session or _create_session()
|
|
232
|
+
|
|
233
|
+
try:
|
|
234
|
+
response = await session.request(
|
|
235
|
+
"GET", f"{self._org_domain_url}{url}", headers=self._default_headers()
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
return await response.read()
|
|
239
|
+
finally:
|
|
240
|
+
if session != self._shared_session:
|
|
241
|
+
await session.close()
|
|
242
|
+
|
|
243
|
+
def _default_headers(self) -> dict[str, str]:
|
|
244
|
+
return {
|
|
245
|
+
"Authorization": f"Bearer {self.access_token}",
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _create_session() -> aiohttp.ClientSession:
|
|
250
|
+
# Disable cookie storage using `DummyCookieJar`, given that we don't need cookie support.
|
|
251
|
+
return aiohttp.ClientSession(cookie_jar=aiohttp.DummyCookieJar())
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _json_serialize(data: Any) -> BytesPayload:
|
|
255
|
+
"""
|
|
256
|
+
JSON serialize the provided data to bytes.
|
|
257
|
+
|
|
258
|
+
This is a replacement for aiohttp's default JSON implementation that uses `orjson` instead
|
|
259
|
+
of the Python stdlib's `json` module, since `orjson` is faster:
|
|
260
|
+
https://github.com/ijl/orjson#performance
|
|
261
|
+
|
|
262
|
+
We can't just implement this by passing `json_serialize` to `ClientSession`, due to:
|
|
263
|
+
https://github.com/aio-libs/aiohttp/issues/4482
|
|
264
|
+
|
|
265
|
+
So instead this is based on `payload.JsonPayload`:
|
|
266
|
+
https://github.com/aio-libs/aiohttp/blob/v3.8.3/aiohttp/payload.py#L386-L403
|
|
267
|
+
"""
|
|
268
|
+
return BytesPayload(
|
|
269
|
+
orjson.dumps(data), encoding="utf-8", content_type="application/json"
|
|
270
|
+
)
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
from base64 import standard_b64encode
|
|
2
|
+
from typing import Any, Awaitable, Callable, Generic, Literal, TypeVar, cast
|
|
3
|
+
from urllib.parse import urlencode
|
|
4
|
+
|
|
5
|
+
"Context > Org > DataAPI"
|
|
6
|
+
|
|
7
|
+
from .exceptions import (
|
|
8
|
+
InnerSalesforceRestApiError,
|
|
9
|
+
MissingFieldError,
|
|
10
|
+
SalesforceRestApiError,
|
|
11
|
+
UnexpectedRestApiResponsePayload,
|
|
12
|
+
)
|
|
13
|
+
from .record import QueriedRecord, Record, RecordQueryResult
|
|
14
|
+
from .reference_id import ReferenceId
|
|
15
|
+
|
|
16
|
+
HttpMethod = Literal["GET", "POST", "PATCH", "DELETE"]
|
|
17
|
+
Json = dict[str, Any] | list[Any]
|
|
18
|
+
DownloadFileFunction = Callable[[str], Awaitable[bytes]]
|
|
19
|
+
|
|
20
|
+
T = TypeVar("T")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class RestApiRequest(Generic[T]):
|
|
24
|
+
def url(self, org_domain_url: str, api_version: str) -> str:
|
|
25
|
+
raise NotImplementedError # pragma: no cover
|
|
26
|
+
|
|
27
|
+
def http_method(self) -> HttpMethod:
|
|
28
|
+
raise NotImplementedError # pragma: no cover
|
|
29
|
+
|
|
30
|
+
def request_body(self) -> Json | None:
|
|
31
|
+
raise NotImplementedError # pragma: no cover
|
|
32
|
+
|
|
33
|
+
async def process_response(self, status_code: int, json_body: Json | None) -> T:
|
|
34
|
+
raise NotImplementedError # pragma: no cover
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class QueryRecordsRestApiRequest(RestApiRequest[RecordQueryResult]):
|
|
38
|
+
def __init__(self, soql: str, download_file_fn: DownloadFileFunction):
|
|
39
|
+
self._soql = soql
|
|
40
|
+
self._download_file_fn = download_file_fn
|
|
41
|
+
|
|
42
|
+
def url(self, org_domain_url: str, api_version: str) -> str:
|
|
43
|
+
return f"{org_domain_url}/services/data/v{api_version}/query?{urlencode({'q': self._soql})}"
|
|
44
|
+
|
|
45
|
+
def http_method(self) -> HttpMethod:
|
|
46
|
+
return "GET"
|
|
47
|
+
|
|
48
|
+
def request_body(self) -> Json | None:
|
|
49
|
+
return None
|
|
50
|
+
|
|
51
|
+
async def process_response(
|
|
52
|
+
self, status_code: int, json_body: Json | None
|
|
53
|
+
) -> RecordQueryResult:
|
|
54
|
+
return await _process_records_response(
|
|
55
|
+
status_code, json_body, self._download_file_fn
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class QueryNextRecordsRestApiRequest(RestApiRequest[RecordQueryResult]):
|
|
60
|
+
def __init__(self, next_records_path: str, download_file_fn: DownloadFileFunction):
|
|
61
|
+
self._next_records_path = next_records_path
|
|
62
|
+
self._download_file_fn = download_file_fn
|
|
63
|
+
|
|
64
|
+
def url(self, org_domain_url: str, api_version: str) -> str:
|
|
65
|
+
return f"{org_domain_url}{self._next_records_path}"
|
|
66
|
+
|
|
67
|
+
def http_method(self) -> HttpMethod:
|
|
68
|
+
return "GET"
|
|
69
|
+
|
|
70
|
+
def request_body(self) -> Json | None:
|
|
71
|
+
return None
|
|
72
|
+
|
|
73
|
+
async def process_response(
|
|
74
|
+
self, status_code: int, json_body: Json | None
|
|
75
|
+
) -> RecordQueryResult:
|
|
76
|
+
return await _process_records_response(
|
|
77
|
+
status_code, json_body, self._download_file_fn
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class CreateRecordRestApiRequest(RestApiRequest[str]):
|
|
82
|
+
def __init__(self, record: Record):
|
|
83
|
+
self._record = record
|
|
84
|
+
|
|
85
|
+
def url(self, org_domain_url: str, api_version: str) -> str:
|
|
86
|
+
return f"{org_domain_url}/services/data/v{api_version}/sobjects/{self._record.type}"
|
|
87
|
+
|
|
88
|
+
def http_method(self) -> HttpMethod:
|
|
89
|
+
return "POST"
|
|
90
|
+
|
|
91
|
+
def request_body(self) -> Json | None:
|
|
92
|
+
return _normalize_record_fields(self._record.fields)
|
|
93
|
+
|
|
94
|
+
async def process_response(self, status_code: int, json_body: Json | None) -> str:
|
|
95
|
+
if status_code != 201:
|
|
96
|
+
raise SalesforceRestApiError(api_errors=_parse_errors(json_body))
|
|
97
|
+
|
|
98
|
+
if isinstance(json_body, dict):
|
|
99
|
+
return str(json_body["id"])
|
|
100
|
+
|
|
101
|
+
raise UnexpectedRestApiResponsePayload(
|
|
102
|
+
"The create record API response payload doesn't match the expected structure."
|
|
103
|
+
) # pragma: no cover
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class UpdateRecordRestApiRequest(RestApiRequest[str]):
|
|
107
|
+
def __init__(self, record: Record):
|
|
108
|
+
if "Id" not in record.fields:
|
|
109
|
+
raise MissingFieldError(
|
|
110
|
+
"The 'Id' field is required, but isn't present in the given Record."
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
self._record = record
|
|
114
|
+
|
|
115
|
+
def url(self, org_domain_url: str, api_version: str) -> str:
|
|
116
|
+
return f"{org_domain_url}/services/data/v{api_version}/sobjects/{self._record.type}/{self._record.fields['Id']}"
|
|
117
|
+
|
|
118
|
+
def http_method(self) -> HttpMethod:
|
|
119
|
+
return "PATCH"
|
|
120
|
+
|
|
121
|
+
def request_body(self) -> Json | None:
|
|
122
|
+
return _normalize_record_fields(
|
|
123
|
+
{
|
|
124
|
+
key: self._record.fields[key]
|
|
125
|
+
for key in self._record.fields
|
|
126
|
+
if key != "Id"
|
|
127
|
+
}
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
async def process_response(self, status_code: int, json_body: Json | None) -> str:
|
|
131
|
+
if status_code != 204:
|
|
132
|
+
raise SalesforceRestApiError(
|
|
133
|
+
api_errors=_parse_errors(json_body)
|
|
134
|
+
) # pragma: no cover
|
|
135
|
+
|
|
136
|
+
return str(self._record.fields["Id"])
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class DeleteRecordRestApiRequest(RestApiRequest[str]):
|
|
140
|
+
def __init__(self, object_type: str, record_id: str):
|
|
141
|
+
self._object_type = object_type
|
|
142
|
+
self._record_id = record_id
|
|
143
|
+
|
|
144
|
+
def url(self, org_domain_url: str, api_version: str) -> str:
|
|
145
|
+
return f"{org_domain_url}/services/data/v{api_version}/sobjects/{self._object_type}/{self._record_id}"
|
|
146
|
+
|
|
147
|
+
def http_method(self) -> HttpMethod:
|
|
148
|
+
return "DELETE"
|
|
149
|
+
|
|
150
|
+
def request_body(self) -> Json | None:
|
|
151
|
+
return None
|
|
152
|
+
|
|
153
|
+
async def process_response(self, status_code: int, json_body: Json | None) -> str:
|
|
154
|
+
if status_code != 204:
|
|
155
|
+
raise SalesforceRestApiError(api_errors=_parse_errors(json_body))
|
|
156
|
+
|
|
157
|
+
return self._record_id
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class CompositeGraphRestApiRequest(RestApiRequest[dict[ReferenceId, str]]):
|
|
161
|
+
def __init__(
|
|
162
|
+
self,
|
|
163
|
+
api_version: str,
|
|
164
|
+
sub_requests: dict[ReferenceId, RestApiRequest[str]],
|
|
165
|
+
):
|
|
166
|
+
self._api_version = api_version
|
|
167
|
+
self._sub_requests = sub_requests
|
|
168
|
+
|
|
169
|
+
def url(self, org_domain_url: str, api_version: str) -> str:
|
|
170
|
+
return f"{org_domain_url}/services/data/v{api_version}/composite/graph"
|
|
171
|
+
|
|
172
|
+
def http_method(self) -> HttpMethod:
|
|
173
|
+
return "POST"
|
|
174
|
+
|
|
175
|
+
def request_body(self) -> Json | None:
|
|
176
|
+
json_sub_requests: list[dict[str, Any]] = []
|
|
177
|
+
|
|
178
|
+
for reference_id, sub_request in self._sub_requests.items():
|
|
179
|
+
json_sub_request: dict[str, Any] = {
|
|
180
|
+
# Sub-requests use relative URLs, hence the empty-string `org_domain_url`.
|
|
181
|
+
"url": sub_request.url("", self._api_version),
|
|
182
|
+
"method": sub_request.http_method(),
|
|
183
|
+
"referenceId": reference_id.id,
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
if sub_request.request_body():
|
|
187
|
+
json_sub_request["body"] = sub_request.request_body()
|
|
188
|
+
|
|
189
|
+
json_sub_requests.append(json_sub_request)
|
|
190
|
+
|
|
191
|
+
return {
|
|
192
|
+
"graphs": [{"graphId": "graph0", "compositeRequest": json_sub_requests}]
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async def process_response(
|
|
196
|
+
self, status_code: int, json_body: Json | None
|
|
197
|
+
) -> dict[ReferenceId, str]:
|
|
198
|
+
# This is the case when the composite request itself has errors. Errors of the sub-requests are handled
|
|
199
|
+
# separately.
|
|
200
|
+
if status_code != 200:
|
|
201
|
+
raise SalesforceRestApiError(
|
|
202
|
+
api_errors=_parse_errors(json_body)
|
|
203
|
+
) # pragma: no cover
|
|
204
|
+
|
|
205
|
+
if isinstance(json_body, dict):
|
|
206
|
+
composite_responses = json_body["graphs"][0]["graphResponse"][
|
|
207
|
+
"compositeResponse"
|
|
208
|
+
]
|
|
209
|
+
result: dict[ReferenceId, str] = {}
|
|
210
|
+
errors: list[InnerSalesforceRestApiError] = []
|
|
211
|
+
|
|
212
|
+
for composite_response in composite_responses:
|
|
213
|
+
reference_id = ReferenceId(id=composite_response["referenceId"])
|
|
214
|
+
sub_status_code = composite_response["httpStatusCode"]
|
|
215
|
+
body = composite_response.get("body")
|
|
216
|
+
|
|
217
|
+
try:
|
|
218
|
+
result[reference_id] = await self._sub_requests[
|
|
219
|
+
reference_id
|
|
220
|
+
].process_response(sub_status_code, body)
|
|
221
|
+
except SalesforceRestApiError as rest_api_error:
|
|
222
|
+
errors.extend(rest_api_error.api_errors)
|
|
223
|
+
|
|
224
|
+
if errors:
|
|
225
|
+
raise SalesforceRestApiError(api_errors=errors)
|
|
226
|
+
|
|
227
|
+
return result
|
|
228
|
+
|
|
229
|
+
raise UnexpectedRestApiResponsePayload(
|
|
230
|
+
"The composite graph API response payload doesn't match the expected structure."
|
|
231
|
+
) # pragma: no cover
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
async def _process_records_response(
|
|
235
|
+
status_code: int, json_body: Json | None, download_file_fn: DownloadFileFunction
|
|
236
|
+
) -> RecordQueryResult:
|
|
237
|
+
if status_code != 200:
|
|
238
|
+
raise SalesforceRestApiError(api_errors=_parse_errors(json_body))
|
|
239
|
+
|
|
240
|
+
if isinstance(json_body, dict):
|
|
241
|
+
return await _parse_record_query_result(json_body, download_file_fn)
|
|
242
|
+
|
|
243
|
+
raise UnexpectedRestApiResponsePayload(
|
|
244
|
+
"The API response payload doesn't match the expected structure."
|
|
245
|
+
) # pragma: no cover
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
async def _parse_record_query_result(
|
|
249
|
+
json_body: dict[str, Any], download_file_fn: DownloadFileFunction
|
|
250
|
+
) -> RecordQueryResult:
|
|
251
|
+
done: bool = json_body["done"]
|
|
252
|
+
total_size: int = json_body["totalSize"]
|
|
253
|
+
next_records_url: str | None = json_body.get("nextRecordsUrl")
|
|
254
|
+
|
|
255
|
+
records: list[QueriedRecord] = []
|
|
256
|
+
for record_json in json_body["records"]:
|
|
257
|
+
records.append(await _parse_queried_record(record_json, download_file_fn))
|
|
258
|
+
|
|
259
|
+
return RecordQueryResult(
|
|
260
|
+
done=done,
|
|
261
|
+
total_size=total_size,
|
|
262
|
+
records=records,
|
|
263
|
+
next_records_url=next_records_url,
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
async def _parse_queried_record(
|
|
268
|
+
record_json: dict[str, Any], download_file_fn: DownloadFileFunction
|
|
269
|
+
) -> QueriedRecord:
|
|
270
|
+
salesforce_object_type = record_json["attributes"]["type"]
|
|
271
|
+
|
|
272
|
+
fields: dict[str, bytes | QueriedRecord | Any] = {}
|
|
273
|
+
sub_query_results = {}
|
|
274
|
+
for key, value in record_json.items():
|
|
275
|
+
if key == "attributes":
|
|
276
|
+
continue
|
|
277
|
+
|
|
278
|
+
if isinstance(value, dict):
|
|
279
|
+
value = cast(dict[str, Any], value)
|
|
280
|
+
if "attributes" in value:
|
|
281
|
+
fields[key] = await _parse_queried_record(value, download_file_fn)
|
|
282
|
+
else:
|
|
283
|
+
sub_query_results[key] = await _parse_record_query_result(
|
|
284
|
+
value, download_file_fn
|
|
285
|
+
)
|
|
286
|
+
elif _is_binary_field(salesforce_object_type, key):
|
|
287
|
+
fields[key] = await download_file_fn(value)
|
|
288
|
+
else:
|
|
289
|
+
fields[key] = value
|
|
290
|
+
|
|
291
|
+
return QueriedRecord(
|
|
292
|
+
type=salesforce_object_type, fields=fields, sub_query_results=sub_query_results
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _is_binary_field(salesforce_object_type: str, field_name: str) -> bool:
|
|
297
|
+
return salesforce_object_type == "ContentVersion" and field_name == "VersionData"
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _normalize_record_fields(fields: dict[str, Any]) -> dict[str, Any]:
|
|
301
|
+
return {key: _normalize_field_value(value) for (key, value) in fields.items()}
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _normalize_field_value(value: Any) -> Any:
|
|
305
|
+
if isinstance(value, ReferenceId):
|
|
306
|
+
return f"@{{{value.id}.id}}"
|
|
307
|
+
|
|
308
|
+
if isinstance(value, (bytes, bytearray)):
|
|
309
|
+
return standard_b64encode(value).decode("ascii")
|
|
310
|
+
|
|
311
|
+
return value
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _parse_errors(json_errors: Json | None) -> list[InnerSalesforceRestApiError]:
|
|
315
|
+
if isinstance(json_errors, list):
|
|
316
|
+
return [
|
|
317
|
+
InnerSalesforceRestApiError(
|
|
318
|
+
message=json_error["message"],
|
|
319
|
+
error_code=json_error["errorCode"],
|
|
320
|
+
fields=json_error.get("fields", []),
|
|
321
|
+
)
|
|
322
|
+
for json_error in json_errors
|
|
323
|
+
]
|
|
324
|
+
|
|
325
|
+
raise UnexpectedRestApiResponsePayload(
|
|
326
|
+
"The API response payload doesn't match the expected structure."
|
|
327
|
+
) # pragma: no cover
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
|
|
3
|
+
# The order in `__all__` is the in which pdoc3 will display the classes in the docs.
|
|
4
|
+
__all__ = [
|
|
5
|
+
"DataApiError",
|
|
6
|
+
"SalesforceRestApiError",
|
|
7
|
+
"InnerSalesforceRestApiError",
|
|
8
|
+
"MissingFieldError",
|
|
9
|
+
"ClientError",
|
|
10
|
+
"UnexpectedRestApiResponsePayload",
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class DataApiError(Exception):
|
|
15
|
+
"""Base class for Data API exceptions."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True, kw_only=True, slots=True)
|
|
19
|
+
class SalesforceRestApiError(DataApiError):
|
|
20
|
+
"""Raised when the Salesforce REST API signalled error(s)."""
|
|
21
|
+
|
|
22
|
+
api_errors: list["InnerSalesforceRestApiError"]
|
|
23
|
+
"""A list of one or more errors returned from Salesforce REST API."""
|
|
24
|
+
|
|
25
|
+
def __str__(self) -> str:
|
|
26
|
+
errors_list = "\n---\n".join(str(error) for error in self.api_errors)
|
|
27
|
+
return (
|
|
28
|
+
f"Salesforce REST API reported the following error(s):\n---\n{errors_list}"
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True, kw_only=True, slots=True)
|
|
33
|
+
class InnerSalesforceRestApiError:
|
|
34
|
+
"""An error returned from the Salesforce REST API."""
|
|
35
|
+
|
|
36
|
+
message: str
|
|
37
|
+
"""The description of this error."""
|
|
38
|
+
error_code: str
|
|
39
|
+
"""The error code for this error."""
|
|
40
|
+
fields: list[str]
|
|
41
|
+
"""
|
|
42
|
+
The field names where the error occurred.
|
|
43
|
+
|
|
44
|
+
This will be empty for errors that aren't related to a specific field.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
def __str__(self) -> str:
|
|
48
|
+
# The error message includes the field names, so `self.fields` is intentionally not
|
|
49
|
+
# included, as the string representation is for human not programmatic consumption.
|
|
50
|
+
return f"{self.error_code} error:\n{self.message}"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class MissingFieldError(DataApiError):
|
|
54
|
+
"""Raised when the given `Record` must contain a field, but no such field was found."""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class ClientError(DataApiError):
|
|
58
|
+
"""Raised when the API request failed due to a connection error, timeout, or malformed HTTP response."""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class UnexpectedRestApiResponsePayload(DataApiError):
|
|
62
|
+
"""Raised when the Salesforce REST API returned an unexpected payload."""
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
from dataclasses import dataclass, field
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
__all__ = ["Record", "QueriedRecord", "RecordQueryResult"]
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass(frozen=True, kw_only=True, slots=True)
|
|
8
|
+
class Record:
|
|
9
|
+
"""
|
|
10
|
+
A Salesforce record.
|
|
11
|
+
|
|
12
|
+
A record describes a particular occurrence of a Salesforce object, such as a
|
|
13
|
+
specific account "Acme Company" from the Account standard object. A record is
|
|
14
|
+
analogous to a row in a database table.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
type: str
|
|
18
|
+
"""
|
|
19
|
+
The Salesforce Object type.
|
|
20
|
+
|
|
21
|
+
For example: `Account`
|
|
22
|
+
"""
|
|
23
|
+
fields: dict[str, Any]
|
|
24
|
+
"""The fields belonging to the record."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True, kw_only=True, slots=True)
|
|
28
|
+
class QueriedRecord(Record):
|
|
29
|
+
"""
|
|
30
|
+
A Salesforce record that's the result of a SOQL query.
|
|
31
|
+
|
|
32
|
+
Extends `Record` with potential sub query results that can only exist when
|
|
33
|
+
a record was queried from the data API.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
sub_query_results: dict[str, "RecordQueryResult"] = field(default_factory=dict)
|
|
37
|
+
"""Additional query results from sub queries."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True, kw_only=True, slots=True)
|
|
41
|
+
class RecordQueryResult:
|
|
42
|
+
"""The result of a record query."""
|
|
43
|
+
|
|
44
|
+
done: bool
|
|
45
|
+
"""
|
|
46
|
+
Indicates whether all record results have been returned.
|
|
47
|
+
|
|
48
|
+
If true, no additional records can be retrieved from the query result.
|
|
49
|
+
If false, one or more records remain to be retrieved.
|
|
50
|
+
"""
|
|
51
|
+
total_size: int
|
|
52
|
+
"""
|
|
53
|
+
The total number of records returned by the query.
|
|
54
|
+
|
|
55
|
+
This number isn't necessarily the same as the number of records found in `records`.
|
|
56
|
+
"""
|
|
57
|
+
records: list[QueriedRecord]
|
|
58
|
+
"""
|
|
59
|
+
The list of `Record`s in this query result.
|
|
60
|
+
|
|
61
|
+
Use `done` to determine whether there are additional records to be
|
|
62
|
+
queried with `queryMore`.
|
|
63
|
+
"""
|
|
64
|
+
next_records_url: str | None
|
|
65
|
+
"""The URL for the next set of records, if any."""
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
|
|
3
|
+
__all__ = ["ReferenceId"]
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass(frozen=True, kw_only=True, slots=True)
|
|
7
|
+
class ReferenceId:
|
|
8
|
+
"""
|
|
9
|
+
A reference ID for an operation inside a `UnitOfWork`.
|
|
10
|
+
|
|
11
|
+
Used to reference results of other operations inside the same unit of work.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
id: str
|
|
15
|
+
"""The internal identifier of this `ReferenceId`."""
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
from ._requests import (
|
|
2
|
+
CreateRecordRestApiRequest,
|
|
3
|
+
DeleteRecordRestApiRequest,
|
|
4
|
+
RestApiRequest,
|
|
5
|
+
UpdateRecordRestApiRequest,
|
|
6
|
+
)
|
|
7
|
+
from .record import Record
|
|
8
|
+
from .reference_id import ReferenceId
|
|
9
|
+
|
|
10
|
+
__all__ = ["UnitOfWork"]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class UnitOfWork:
|
|
14
|
+
"""
|
|
15
|
+
Represents a `UnitOfWork`.
|
|
16
|
+
|
|
17
|
+
A `UnitOfWork` encapsulates a set of one or more Salesforce operations that must be
|
|
18
|
+
performed as a single atomic operation. Single atomic operations reduce the number of
|
|
19
|
+
requests back to the org, and are more efficient when working with larger data volumes.
|
|
20
|
+
|
|
21
|
+
First, register the create, update, or delete operations that make up the `UnitOfWork`
|
|
22
|
+
using their corresponding methods, such as `register_create`. Then submit the `UnitOfWork`
|
|
23
|
+
with the `commit_unit_of_work` method of `DataAPI`.
|
|
24
|
+
|
|
25
|
+
For example:
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
# Create a unit of work, against which multiple operations can be registered.
|
|
29
|
+
unit_of_work = UnitOfWork()
|
|
30
|
+
|
|
31
|
+
# Register a new Account for creation
|
|
32
|
+
account_reference_id = unit_of_work.register_create(
|
|
33
|
+
Record(
|
|
34
|
+
type="Account",
|
|
35
|
+
fields={
|
|
36
|
+
"Name": "Example Account",
|
|
37
|
+
},
|
|
38
|
+
)
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
# Register a new Contact for creation, that references the account above.
|
|
42
|
+
unit_of_work.register_create(
|
|
43
|
+
Record(
|
|
44
|
+
type="Contact",
|
|
45
|
+
fields={
|
|
46
|
+
"FirstName": "Joe",
|
|
47
|
+
"LastName": "Smith",
|
|
48
|
+
"AccountId": account_reference_id,
|
|
49
|
+
},
|
|
50
|
+
)
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
# Commit the unit of work, executing all of the operations registered above.
|
|
54
|
+
result = await context.org.data_api.commit_unit_of_work(unit_of_work)
|
|
55
|
+
```
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
def __init__(self) -> None:
|
|
59
|
+
self._sub_requests: dict[ReferenceId, RestApiRequest[str]] = {}
|
|
60
|
+
self._next_reference_id = 0
|
|
61
|
+
|
|
62
|
+
def register_create(self, record: Record) -> ReferenceId:
|
|
63
|
+
"""
|
|
64
|
+
Register a record creation for the `UnitOfWork`.
|
|
65
|
+
|
|
66
|
+
Returns a `ReferenceId` that you can use to refer to the created record in subsequent operations in this
|
|
67
|
+
`UnitOfWork`.
|
|
68
|
+
|
|
69
|
+
For example:
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
unit_of_work = UnitOfWork()
|
|
73
|
+
|
|
74
|
+
reference_id = unit_of_work.register_create(
|
|
75
|
+
Record(
|
|
76
|
+
type="Account",
|
|
77
|
+
fields={
|
|
78
|
+
"Name": "Example Account",
|
|
79
|
+
},
|
|
80
|
+
)
|
|
81
|
+
)
|
|
82
|
+
```
|
|
83
|
+
"""
|
|
84
|
+
return self._register(CreateRecordRestApiRequest(record))
|
|
85
|
+
|
|
86
|
+
def register_update(self, record: Record) -> ReferenceId:
|
|
87
|
+
"""
|
|
88
|
+
Register a record update for the `UnitOfWork`.
|
|
89
|
+
|
|
90
|
+
The given `Record` must contain an `Id` field.
|
|
91
|
+
|
|
92
|
+
Returns a `ReferenceId` that you can use to refer to the updated record in subsequent operations in this
|
|
93
|
+
`UnitOfWork`.
|
|
94
|
+
|
|
95
|
+
For example:
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
unit_of_work = UnitOfWork()
|
|
99
|
+
|
|
100
|
+
reference_id = unit_of_work.register_update(
|
|
101
|
+
Record(
|
|
102
|
+
type="Account",
|
|
103
|
+
fields={
|
|
104
|
+
"Id": "001B000001Lp1FxIAJ",
|
|
105
|
+
"Name": "New Name",
|
|
106
|
+
},
|
|
107
|
+
)
|
|
108
|
+
)
|
|
109
|
+
```
|
|
110
|
+
"""
|
|
111
|
+
return self._register(UpdateRecordRestApiRequest(record))
|
|
112
|
+
|
|
113
|
+
def register_delete(self, object_type: str, record_id: str) -> ReferenceId:
|
|
114
|
+
"""
|
|
115
|
+
Register a deletion of an existing record of the given type and ID.
|
|
116
|
+
|
|
117
|
+
Returns a `ReferenceId` that you can use to refer to the deleted record in subsequent operations in this
|
|
118
|
+
`UnitOfWork`.
|
|
119
|
+
|
|
120
|
+
For example:
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
unit_of_work = UnitOfWork()
|
|
124
|
+
|
|
125
|
+
reference_id = unit_of_work.register_delete("Account", "001B000001Lp1FxIAJ")
|
|
126
|
+
```
|
|
127
|
+
"""
|
|
128
|
+
return self._register(DeleteRecordRestApiRequest(object_type, record_id))
|
|
129
|
+
|
|
130
|
+
def _register(self, request: RestApiRequest[str]) -> ReferenceId:
|
|
131
|
+
reference_id = ReferenceId(id="referenceId" + str(self._next_reference_id))
|
|
132
|
+
self._next_reference_id += 1
|
|
133
|
+
|
|
134
|
+
self._sub_requests[reference_id] = request
|
|
135
|
+
return reference_id
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import contextvars
|
|
2
|
+
from .context import ClientContext
|
|
3
|
+
|
|
4
|
+
client_context: contextvars.ContextVar = contextvars.ContextVar("client_context")
|
|
5
|
+
|
|
6
|
+
def from_request(request) -> ClientContext:
|
|
7
|
+
header = request.headers.get("x-client-context")
|
|
8
|
+
|
|
9
|
+
if not header:
|
|
10
|
+
raise ValueError("x-client-context not set")
|
|
11
|
+
|
|
12
|
+
return ClientContext.from_http(header)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class IntegrationWsgiMiddleware:
|
|
16
|
+
|
|
17
|
+
def __init__(self, get_response) -> None:
|
|
18
|
+
self.get_response = get_response
|
|
19
|
+
|
|
20
|
+
def __call__(self, request):
|
|
21
|
+
ctx = from_request(request)
|
|
22
|
+
client_context.set(ctx)
|
|
23
|
+
|
|
24
|
+
response = self.get_response(request)
|
|
25
|
+
return response
|
|
26
|
+
|
|
27
|
+
class IntegrationAsgiMiddleware:
|
|
28
|
+
def __init__(self, app):
|
|
29
|
+
self.app = app
|
|
30
|
+
|
|
31
|
+
async def __call__(self, scope, receive, send):
|
|
32
|
+
if scope["type"] != "http":
|
|
33
|
+
await self.app(scope, receive, send)
|
|
34
|
+
return
|
|
35
|
+
|
|
36
|
+
headers = dict(scope["headers"])
|
|
37
|
+
header = headers.get(b"x-client-context")
|
|
38
|
+
if not header:
|
|
39
|
+
raise ValueError("x-client-context not set")
|
|
40
|
+
|
|
41
|
+
ctx = ClientContext.from_header(header)
|
|
42
|
+
client_context.set(ctx)
|
|
43
|
+
scope["client-context"] = ctx
|
|
44
|
+
|
|
45
|
+
await self.app(scope, receive, send)
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Metadata-Version: 2.2
|
|
2
|
+
Name: heroku_applink
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Simple SDK for Heroku AppLink and Salesforce development
|
|
5
|
+
Requires-Python: >=3.10
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: aiohttp>=3.11.12
|
|
8
|
+
Requires-Dist: orjson>=3.10.15
|
|
9
|
+
|
|
10
|
+
# Python SDK for Heroku AppLink
|
|
11
|
+
|
|
12
|
+
This library provides basic functionality for building Python apps that use
|
|
13
|
+
Heroku AppLink to secure communication and credential sharing with a Salesforce
|
|
14
|
+
org.
|
|
15
|
+
|
|
16
|
+
Though the interaction with AppLink is simple and easy to hand code, using the
|
|
17
|
+
SDK will quickstart your project experience.
|
|
18
|
+
|
|
19
|
+
Use of this project with Salesforce is subject to the TERMS_OF_USE.md document.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
heroku_applink/__init__.py
|
|
5
|
+
heroku_applink/context.py
|
|
6
|
+
heroku_applink/middleware.py
|
|
7
|
+
heroku_applink.egg-info/PKG-INFO
|
|
8
|
+
heroku_applink.egg-info/SOURCES.txt
|
|
9
|
+
heroku_applink.egg-info/dependency_links.txt
|
|
10
|
+
heroku_applink.egg-info/requires.txt
|
|
11
|
+
heroku_applink.egg-info/top_level.txt
|
|
12
|
+
heroku_applink/data_api/__init__.py
|
|
13
|
+
heroku_applink/data_api/_requests.py
|
|
14
|
+
heroku_applink/data_api/exceptions.py
|
|
15
|
+
heroku_applink/data_api/record.py
|
|
16
|
+
heroku_applink/data_api/reference_id.py
|
|
17
|
+
heroku_applink/data_api/unit_of_work.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
heroku_applink
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "heroku_applink"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Simple SDK for Heroku AppLink and Salesforce development"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.10"
|
|
7
|
+
dependencies = [
|
|
8
|
+
"aiohttp>=3.11.12",
|
|
9
|
+
"orjson>=3.10.15",
|
|
10
|
+
]
|
|
11
|
+
[tool.setuptools]
|
|
12
|
+
packages = ["heroku_applink", "heroku_applink.data_api"]
|
|
13
|
+
license-files = []
|