render-lab-tasks-render 0.1.0__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.
- render_lab_tasks_render/__init__.py +1 -0
- render_lab_tasks_render/_app.py +3 -0
- render_lab_tasks_render/await_deploy.py +18 -0
- render_lab_tasks_render/client.py +525 -0
- render_lab_tasks_render/create_private_service.py +20 -0
- render_lab_tasks_render/create_project.py +18 -0
- render_lab_tasks_render/delete_project.py +18 -0
- render_lab_tasks_render/delete_resource.py +18 -0
- render_lab_tasks_render/ensure_service.py +18 -0
- render_lab_tasks_render/get_deploy_diagnostics.py +20 -0
- render_lab_tasks_render/get_service.py +18 -0
- render_lab_tasks_render/provision_key_value.py +18 -0
- render_lab_tasks_render/provision_postgres.py +18 -0
- render_lab_tasks_render/provision_service.py +43 -0
- render_lab_tasks_render/py.typed +0 -0
- render_lab_tasks_render/resume_service.py +18 -0
- render_lab_tasks_render/retry.py +5 -0
- render_lab_tasks_render/scale_service.py +18 -0
- render_lab_tasks_render/suspend_service.py +18 -0
- render_lab_tasks_render/tasks.py +50 -0
- render_lab_tasks_render/trigger_deploy.py +18 -0
- render_lab_tasks_render/types.py +367 -0
- render_lab_tasks_render-0.1.0.dist-info/METADATA +54 -0
- render_lab_tasks_render-0.1.0.dist-info/RECORD +26 -0
- render_lab_tasks_render-0.1.0.dist-info/WHEEL +4 -0
- render_lab_tasks_render-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Import .tasks explicitly to register durable tasks."""
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from render import TaskContext
|
|
2
|
+
|
|
3
|
+
from ._app import app
|
|
4
|
+
from .client import Deps, dependencies
|
|
5
|
+
from .retry import AWAIT_DEPLOY_RETRY
|
|
6
|
+
from .types import AwaitDeployInput, AwaitDeployResult
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
async def await_deploy_impl(
|
|
10
|
+
ctx: TaskContext, input: AwaitDeployInput, *, deps: Deps | None = None
|
|
11
|
+
) -> AwaitDeployResult:
|
|
12
|
+
async with dependencies(deps) as resolved:
|
|
13
|
+
return await resolved.render.await_deploy(input)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.task(name="render.awaitDeploy", retry=AWAIT_DEPLOY_RETRY)
|
|
17
|
+
async def await_deploy(ctx: TaskContext, input: AwaitDeployInput) -> AwaitDeployResult:
|
|
18
|
+
return await await_deploy_impl(ctx, input)
|
|
@@ -0,0 +1,525 @@
|
|
|
1
|
+
"""Injected vendor interface and one-attempt async HTTP adapter."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
|
|
8
|
+
from contextlib import asynccontextmanager
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import Any, Protocol, cast
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
from render_lab_tasks_core.bounded import MAX_TEXT_BYTES, validate_byte_limit
|
|
14
|
+
from render_lab_tasks_core.http import (
|
|
15
|
+
ApiError,
|
|
16
|
+
HttpClient,
|
|
17
|
+
enc,
|
|
18
|
+
js_string,
|
|
19
|
+
nullish,
|
|
20
|
+
pick,
|
|
21
|
+
query,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
from . import types as t
|
|
25
|
+
|
|
26
|
+
DEPLOY_FAILED = {"build_failed", "update_failed", "pre_deploy_failed", "canceled", "deactivated"}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def gate(status: str, ready: str, failed: set[str], wait: str, failure: str) -> None:
|
|
30
|
+
if status != ready:
|
|
31
|
+
raise ValueError(failure if status in failed else wait)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def service_dto(raw: Any) -> t.ServiceDTO:
|
|
35
|
+
raw = raw or {}
|
|
36
|
+
details = raw.get("serviceDetails") or {}
|
|
37
|
+
return {
|
|
38
|
+
"id": raw.get("id", ""),
|
|
39
|
+
"name": raw.get("name", ""),
|
|
40
|
+
"type": raw.get("type", ""),
|
|
41
|
+
"runtime": nullish(details.get("env"), raw.get("runtime")),
|
|
42
|
+
"region": raw.get("region"),
|
|
43
|
+
"plan": nullish(details.get("plan"), raw.get("plan")),
|
|
44
|
+
"repositoryUrl": nullish(raw.get("repo"), raw.get("repositoryUrl")),
|
|
45
|
+
"branch": raw.get("branch"),
|
|
46
|
+
"createdAt": nullish(raw.get("createdAt"), raw.get("created_at", "")),
|
|
47
|
+
"updatedAt": nullish(raw.get("updatedAt"), raw.get("updated_at", "")),
|
|
48
|
+
"suspended": raw.get("suspended") == "suspended",
|
|
49
|
+
"url": nullish(details.get("url"), details.get("internalAddress")),
|
|
50
|
+
"dashboardUrl": raw.get("dashboardUrl"),
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def deploy_dto(service_id: str, raw: Any) -> t.DeployDTO:
|
|
55
|
+
raw = raw or {}
|
|
56
|
+
return {
|
|
57
|
+
"id": raw.get("id", ""),
|
|
58
|
+
"serviceId": service_id,
|
|
59
|
+
"status": raw.get("status", "created"),
|
|
60
|
+
"commitId": (raw.get("commit") or {}).get("id"),
|
|
61
|
+
"createdAt": nullish(raw.get("createdAt"), raw.get("created_at", "")),
|
|
62
|
+
"updatedAt": nullish(raw.get("updatedAt"), raw.get("updated_at", "")),
|
|
63
|
+
"finishedAt": nullish(raw.get("finishedAt"), raw.get("finished_at")),
|
|
64
|
+
"failureReason": nullish(raw.get("failureReason"), raw.get("failure_reason")),
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def subset_matches(actual: Any, desired: Mapping[str, Any]) -> bool:
|
|
69
|
+
if not isinstance(actual, dict):
|
|
70
|
+
return not desired
|
|
71
|
+
return all(
|
|
72
|
+
subset_matches(actual.get(k), v) if isinstance(v, dict) else k in actual and actual[k] == v
|
|
73
|
+
for k, v in desired.items()
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def service_details(input: Mapping[str, Any]) -> dict[str, Any]:
|
|
78
|
+
details: dict[str, Any] = {}
|
|
79
|
+
for key in ("plan", "buildCommand", "preDeployCommand"):
|
|
80
|
+
if input.get(key):
|
|
81
|
+
details[key] = input[key]
|
|
82
|
+
if input.get("runtime"):
|
|
83
|
+
details["env"] = input["runtime"]
|
|
84
|
+
if input.get("startCommand") and input.get("runtime") != "docker" and not input.get("image"):
|
|
85
|
+
details["startCommand"] = input["startCommand"]
|
|
86
|
+
if input["type"] == "web_service" and input.get("healthCheckPath"):
|
|
87
|
+
details["healthCheckPath"] = input["healthCheckPath"]
|
|
88
|
+
if input["type"] == "static_site":
|
|
89
|
+
details["publishPath"] = input["publishPath"]
|
|
90
|
+
if input.get("image"):
|
|
91
|
+
details["env"] = "image"
|
|
92
|
+
if input.get("runtime") == "docker":
|
|
93
|
+
docker = {
|
|
94
|
+
k: input[k]
|
|
95
|
+
for k in ("dockerfilePath", "dockerContext", "dockerCommand")
|
|
96
|
+
if input.get(k)
|
|
97
|
+
}
|
|
98
|
+
if docker:
|
|
99
|
+
details["envSpecificDetails"] = docker
|
|
100
|
+
if input.get("disk"):
|
|
101
|
+
details["disk"] = input["disk"]
|
|
102
|
+
return details
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class Port(Protocol):
|
|
106
|
+
async def get_deploy(self, service_id: str, deploy_id: str) -> t.DeployDTO: ...
|
|
107
|
+
async def await_deploy(self, input: t.AwaitDeployInput) -> t.AwaitDeployResult: ...
|
|
108
|
+
async def create_private_service(
|
|
109
|
+
self, input: t.CreatePrivateServiceInput
|
|
110
|
+
) -> t.CreatePrivateServiceResult: ...
|
|
111
|
+
async def create_project(self, input: t.CreateProjectInput) -> t.CreateProjectResult: ...
|
|
112
|
+
async def delete_project(self, input: t.DeleteProjectInput) -> t.DeleteProjectResult: ...
|
|
113
|
+
async def delete_resource(self, input: t.DeleteResourceInput) -> t.DeleteResourceResult: ...
|
|
114
|
+
async def ensure_service(self, input: t.ProvisionServiceInput) -> t.EnsureServiceResult: ...
|
|
115
|
+
async def get_deploy_diagnostics(
|
|
116
|
+
self, input: t.GetDeployDiagnosticsInput
|
|
117
|
+
) -> t.DeployDiagnosticsResult: ...
|
|
118
|
+
async def get_service(self, input: t.GetServiceInput) -> t.ServiceDTO: ...
|
|
119
|
+
async def provision_key_value(self, input: t.ProvisionKeyValueInput) -> t.KeyValueDTO: ...
|
|
120
|
+
async def provision_postgres(self, input: t.ProvisionPostgresInput) -> t.PostgresDTO: ...
|
|
121
|
+
async def resume_service(self, input: t.ResumeServiceInput) -> t.ResumeServiceResult: ...
|
|
122
|
+
async def scale_service(self, input: t.ScaleServiceInput) -> t.ScaleServiceResult: ...
|
|
123
|
+
async def suspend_service(self, input: t.SuspendServiceInput) -> t.SuspendServiceResult: ...
|
|
124
|
+
async def trigger_deploy(self, input: t.TriggerDeployInput) -> t.TriggerDeployResult: ...
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@dataclass(frozen=True)
|
|
128
|
+
class Deps:
|
|
129
|
+
render: Port
|
|
130
|
+
ensure_service: Callable[[t.ProvisionServiceInput], Awaitable[t.EnsureServiceResult]] | None = (
|
|
131
|
+
None
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class Client:
|
|
136
|
+
def __init__(self, http: httpx.AsyncClient, env: Mapping[str, str] | None = None) -> None:
|
|
137
|
+
self.env = os.environ if env is None else env
|
|
138
|
+
self.api = HttpClient(
|
|
139
|
+
http, "https://api.render.com/v1", auth=self._auth, label="Render API"
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
def _auth(self) -> dict[str, str]:
|
|
143
|
+
key = self.env.get("RENDER_API_KEY")
|
|
144
|
+
if not key:
|
|
145
|
+
raise ValueError(
|
|
146
|
+
"RENDER_API_KEY is required for the render.* control-plane tasks "
|
|
147
|
+
"(triggerDeploy, awaitDeploy, scaleService, suspend/resumeService, "
|
|
148
|
+
"provisionPostgres/KeyValue, createPrivateService, getService)."
|
|
149
|
+
)
|
|
150
|
+
return {"authorization": f"Bearer {key}"}
|
|
151
|
+
|
|
152
|
+
def _owner(self, input: Mapping[str, Any]) -> str:
|
|
153
|
+
owner = nullish(input.get("ownerId"), self.env.get("RENDER_OWNER_ID"))
|
|
154
|
+
if not owner:
|
|
155
|
+
raise ValueError(
|
|
156
|
+
"An ownerId is required to provision resources: "
|
|
157
|
+
"pass { ownerId } or set RENDER_OWNER_ID."
|
|
158
|
+
)
|
|
159
|
+
return str(owner)
|
|
160
|
+
|
|
161
|
+
async def _find(self, path: str, key: str, input: Mapping[str, Any]) -> Any:
|
|
162
|
+
params = {"name": input["name"], "limit": "20"}
|
|
163
|
+
if input.get("ownerId"):
|
|
164
|
+
params["ownerId"] = input["ownerId"]
|
|
165
|
+
items = await self.api.call(path + "?" + query(params))
|
|
166
|
+
return (
|
|
167
|
+
next((e.get(key, e) for e in items if e.get(key, e).get("name") == input["name"]), None)
|
|
168
|
+
if isinstance(items, list)
|
|
169
|
+
else None
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
async def _latest(self, service: str) -> str | None:
|
|
173
|
+
items = await self.api.call(f"/services/{enc(service)}/deploys?limit=1")
|
|
174
|
+
return (
|
|
175
|
+
items[0].get("deploy", items[0]).get("id")
|
|
176
|
+
if isinstance(items, list) and items
|
|
177
|
+
else None
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
def _source(self, input: Mapping[str, Any]) -> dict[str, Any]:
|
|
181
|
+
return (
|
|
182
|
+
{"image": {"ownerId": self._owner(input), "imagePath": input["image"]}}
|
|
183
|
+
if input.get("image")
|
|
184
|
+
else pick(input, "repo", "branch")
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
async def get_service(self, input: t.GetServiceInput) -> t.ServiceDTO:
|
|
188
|
+
return service_dto(await self.api.call(f"/services/{enc(input['serviceId'])}"))
|
|
189
|
+
|
|
190
|
+
async def get_deploy(self, service_id: str, deploy_id: str) -> t.DeployDTO:
|
|
191
|
+
return deploy_dto(
|
|
192
|
+
service_id, await self.api.call(f"/services/{enc(service_id)}/deploys/{enc(deploy_id)}")
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
async def trigger_deploy(self, input: t.TriggerDeployInput) -> t.TriggerDeployResult:
|
|
196
|
+
body = {}
|
|
197
|
+
if input.get("clearCache"):
|
|
198
|
+
body["clearCache"] = "clear"
|
|
199
|
+
if input.get("commitId"):
|
|
200
|
+
body["commitId"] = input["commitId"]
|
|
201
|
+
deploy = deploy_dto(
|
|
202
|
+
input["serviceId"],
|
|
203
|
+
await self.api.call(
|
|
204
|
+
f"/services/{enc(input['serviceId'])}/deploys", method="POST", body=body
|
|
205
|
+
),
|
|
206
|
+
)
|
|
207
|
+
return {
|
|
208
|
+
"serviceId": input["serviceId"],
|
|
209
|
+
"deployId": deploy["id"],
|
|
210
|
+
"status": deploy["status"],
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async def await_deploy(self, input: t.AwaitDeployInput) -> t.AwaitDeployResult:
|
|
214
|
+
status = (await self.get_deploy(input["serviceId"], input["deployId"]))["status"]
|
|
215
|
+
gate(
|
|
216
|
+
status,
|
|
217
|
+
"live",
|
|
218
|
+
DEPLOY_FAILED,
|
|
219
|
+
f"Deploy {input['deployId']} still in progress (created)",
|
|
220
|
+
f"Deploy {input['deployId']} failed (created)",
|
|
221
|
+
)
|
|
222
|
+
return {**input, "status": status, "live": True}
|
|
223
|
+
|
|
224
|
+
async def scale_service(self, input: t.ScaleServiceInput) -> t.ScaleServiceResult:
|
|
225
|
+
if "numInstances" not in input and "plan" not in input:
|
|
226
|
+
raise ValueError("render.scaleService requires at least one of { numInstances, plan }.")
|
|
227
|
+
if "numInstances" in input:
|
|
228
|
+
await self.api.call(
|
|
229
|
+
f"/services/{enc(input['serviceId'])}/scale",
|
|
230
|
+
method="POST",
|
|
231
|
+
body={"numInstances": input["numInstances"]},
|
|
232
|
+
)
|
|
233
|
+
if "plan" in input:
|
|
234
|
+
await self.api.call(
|
|
235
|
+
f"/services/{enc(input['serviceId'])}",
|
|
236
|
+
method="PATCH",
|
|
237
|
+
body={"serviceDetails": {"plan": input["plan"]}},
|
|
238
|
+
)
|
|
239
|
+
return {
|
|
240
|
+
"serviceId": input["serviceId"],
|
|
241
|
+
"numInstances": input.get("numInstances"),
|
|
242
|
+
"plan": input.get("plan"),
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async def suspend_service(self, input: t.SuspendServiceInput) -> t.SuspendServiceResult:
|
|
246
|
+
await self.api.call(f"/services/{enc(input['serviceId'])}/suspend", method="POST")
|
|
247
|
+
return {"serviceId": input["serviceId"], "suspended": True}
|
|
248
|
+
|
|
249
|
+
async def resume_service(self, input: t.ResumeServiceInput) -> t.ResumeServiceResult:
|
|
250
|
+
await self.api.call(f"/services/{enc(input['serviceId'])}/resume", method="POST")
|
|
251
|
+
return {"serviceId": input["serviceId"], "suspended": False}
|
|
252
|
+
|
|
253
|
+
async def _provision_data(
|
|
254
|
+
self, input: Mapping[str, Any], path: str, key: str, label: str
|
|
255
|
+
) -> Any:
|
|
256
|
+
raw = await self._find(path, key, input)
|
|
257
|
+
if raw is None:
|
|
258
|
+
body = {
|
|
259
|
+
**pick(
|
|
260
|
+
input,
|
|
261
|
+
"name",
|
|
262
|
+
"plan",
|
|
263
|
+
"region",
|
|
264
|
+
"databaseName",
|
|
265
|
+
"databaseUser",
|
|
266
|
+
"environmentId",
|
|
267
|
+
"maxmemoryPolicy",
|
|
268
|
+
),
|
|
269
|
+
"ownerId": self._owner(input),
|
|
270
|
+
}
|
|
271
|
+
if key == "postgres":
|
|
272
|
+
body["version"] = nullish(input.get("version"), "18")
|
|
273
|
+
raw = await self.api.call(path, method="POST", body=body)
|
|
274
|
+
dto = {
|
|
275
|
+
"id": raw.get("id", ""),
|
|
276
|
+
"name": raw.get("name", ""),
|
|
277
|
+
"status": raw.get("status", "unknown"),
|
|
278
|
+
"plan": raw.get("plan"),
|
|
279
|
+
"region": raw.get("region"),
|
|
280
|
+
}
|
|
281
|
+
gate(
|
|
282
|
+
dto["status"],
|
|
283
|
+
"available",
|
|
284
|
+
{"unavailable", "recovery_failed"},
|
|
285
|
+
f'{label} "{input["name"]}" still provisioning (undefined)',
|
|
286
|
+
f'{label} "{input["name"]}" provisioning failed (undefined)',
|
|
287
|
+
)
|
|
288
|
+
return dto
|
|
289
|
+
|
|
290
|
+
async def provision_postgres(self, input: t.ProvisionPostgresInput) -> t.PostgresDTO:
|
|
291
|
+
return cast(
|
|
292
|
+
t.PostgresDTO, await self._provision_data(input, "/postgres", "postgres", "Postgres")
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
async def provision_key_value(self, input: t.ProvisionKeyValueInput) -> t.KeyValueDTO:
|
|
296
|
+
return cast(
|
|
297
|
+
t.KeyValueDTO, await self._provision_data(input, "/key-value", "keyValue", "Key Value")
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
async def create_private_service(
|
|
301
|
+
self, input: t.CreatePrivateServiceInput
|
|
302
|
+
) -> t.CreatePrivateServiceResult:
|
|
303
|
+
if not input.get("repo") and not input.get("image"):
|
|
304
|
+
raise ValueError(
|
|
305
|
+
"render.createPrivateService requires a source: "
|
|
306
|
+
"pass { repo } (+ optional branch) or { image }."
|
|
307
|
+
)
|
|
308
|
+
existing = await self._find("/services", "service", input)
|
|
309
|
+
if existing is not None:
|
|
310
|
+
service = service_dto(existing)
|
|
311
|
+
deploy_id = await self._latest(service["id"])
|
|
312
|
+
else:
|
|
313
|
+
details: dict[str, Any] = pick(input, "plan")
|
|
314
|
+
if input.get("image"):
|
|
315
|
+
details["env"] = "image"
|
|
316
|
+
created = await self.api.call(
|
|
317
|
+
"/services",
|
|
318
|
+
method="POST",
|
|
319
|
+
body={
|
|
320
|
+
**pick(input, "name", "region", "envVars"),
|
|
321
|
+
"type": "private_service",
|
|
322
|
+
"ownerId": self._owner(input),
|
|
323
|
+
**self._source(input),
|
|
324
|
+
"serviceDetails": details,
|
|
325
|
+
},
|
|
326
|
+
)
|
|
327
|
+
service = service_dto(created.get("service", created))
|
|
328
|
+
deploy_id = nullish(created.get("deployId"), (created.get("deploy") or {}).get("id"))
|
|
329
|
+
status: t.DeployStatus = "created"
|
|
330
|
+
if deploy_id:
|
|
331
|
+
status = (await self.get_deploy(service["id"], deploy_id))["status"]
|
|
332
|
+
gate(
|
|
333
|
+
status,
|
|
334
|
+
"live",
|
|
335
|
+
DEPLOY_FAILED,
|
|
336
|
+
f'Private service "{input["name"]}" still deploying (created)',
|
|
337
|
+
f'Private service "{input["name"]}" deploy failed (created)',
|
|
338
|
+
)
|
|
339
|
+
return {
|
|
340
|
+
"serviceId": service["id"],
|
|
341
|
+
"name": input["name"],
|
|
342
|
+
"status": status,
|
|
343
|
+
"live": True,
|
|
344
|
+
"url": service["url"],
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
async def ensure_service(self, input: t.ProvisionServiceInput) -> t.EnsureServiceResult:
|
|
348
|
+
existing = await self._find("/services", "service", input)
|
|
349
|
+
desired = service_details(input)
|
|
350
|
+
if existing is not None:
|
|
351
|
+
service = service_dto(existing)
|
|
352
|
+
problems = []
|
|
353
|
+
if service["type"] != input["type"]:
|
|
354
|
+
problems.append(f"type is {service['type']}")
|
|
355
|
+
if (
|
|
356
|
+
input.get("runtime")
|
|
357
|
+
and service.get("runtime")
|
|
358
|
+
and service["runtime"] != input.get("runtime")
|
|
359
|
+
):
|
|
360
|
+
problems.append(f"runtime is {service['runtime']}")
|
|
361
|
+
if problems:
|
|
362
|
+
raise ValueError(
|
|
363
|
+
f"Existing service {input['name']} is incompatible: {', '.join(problems)}."
|
|
364
|
+
)
|
|
365
|
+
if not subset_matches(existing.get("serviceDetails"), desired):
|
|
366
|
+
await self.api.call(
|
|
367
|
+
f"/services/{enc(service['id'])}",
|
|
368
|
+
method="PATCH",
|
|
369
|
+
body={"serviceDetails": desired},
|
|
370
|
+
)
|
|
371
|
+
if "envVars" in input and input["envVars"] is not None:
|
|
372
|
+
await self.api.call(
|
|
373
|
+
f"/services/{enc(service['id'])}/env-vars",
|
|
374
|
+
method="PUT",
|
|
375
|
+
body=input["envVars"],
|
|
376
|
+
)
|
|
377
|
+
deploy = await self.api.call(
|
|
378
|
+
f"/services/{enc(service['id'])}/deploys", method="POST", body={}
|
|
379
|
+
)
|
|
380
|
+
deploy_id = nullish(deploy.get("id"), (deploy.get("deploy") or {}).get("id"))
|
|
381
|
+
else:
|
|
382
|
+
deploy_id = await self._latest(service["id"])
|
|
383
|
+
return {"service": service, "deployId": deploy_id, "created": False}
|
|
384
|
+
body = {
|
|
385
|
+
**pick(input, "type", "name", "rootDir", "region", "envVars", "environmentId"),
|
|
386
|
+
"ownerId": self._owner(input),
|
|
387
|
+
**self._source(input),
|
|
388
|
+
"serviceDetails": desired,
|
|
389
|
+
}
|
|
390
|
+
if "autoDeploy" in input:
|
|
391
|
+
body["autoDeploy"] = "yes" if input["autoDeploy"] else "no"
|
|
392
|
+
created = await self.api.call("/services", method="POST", body=body)
|
|
393
|
+
return {
|
|
394
|
+
"service": service_dto(created.get("service", created)),
|
|
395
|
+
"deployId": nullish(created.get("deployId"), (created.get("deploy") or {}).get("id")),
|
|
396
|
+
"created": True,
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
async def create_project(self, input: t.CreateProjectInput) -> t.CreateProjectResult:
|
|
400
|
+
owner = self._owner(input)
|
|
401
|
+
project = await self._find("/projects", "project", {**input, "ownerId": owner})
|
|
402
|
+
if project is None:
|
|
403
|
+
project = await self.api.call(
|
|
404
|
+
"/projects",
|
|
405
|
+
method="POST",
|
|
406
|
+
body={
|
|
407
|
+
"name": input["name"],
|
|
408
|
+
"ownerId": owner,
|
|
409
|
+
"environments": [{"name": nullish(input.get("environmentName"), "production")}],
|
|
410
|
+
},
|
|
411
|
+
)
|
|
412
|
+
envs = project.get("environmentIds") or project.get("environments") or []
|
|
413
|
+
environment = (
|
|
414
|
+
(envs[0].get("id") if isinstance(envs[0], dict) else envs[0]) if envs else None
|
|
415
|
+
)
|
|
416
|
+
if not environment:
|
|
417
|
+
raise ValueError(
|
|
418
|
+
f'Render project "{project.get("name", project.get("id", "?"))}" '
|
|
419
|
+
"has no environment to place resources in."
|
|
420
|
+
)
|
|
421
|
+
return {
|
|
422
|
+
"project": {"id": project.get("id", ""), "name": project.get("name", "")},
|
|
423
|
+
"environmentId": environment,
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
async def _delete(self, path: str) -> bool:
|
|
427
|
+
try:
|
|
428
|
+
await self.api.call(path, method="DELETE")
|
|
429
|
+
except ApiError as error:
|
|
430
|
+
if error.status == 404:
|
|
431
|
+
return True
|
|
432
|
+
raise
|
|
433
|
+
return False
|
|
434
|
+
|
|
435
|
+
async def delete_project(self, input: t.DeleteProjectInput) -> t.DeleteProjectResult:
|
|
436
|
+
missing = await self._delete(f"/projects/{enc(input['projectId'])}")
|
|
437
|
+
return {"projectId": input["projectId"], "deleted": True, "alreadyMissing": missing}
|
|
438
|
+
|
|
439
|
+
async def delete_resource(self, input: t.DeleteResourceInput) -> t.DeleteResourceResult:
|
|
440
|
+
paths = {
|
|
441
|
+
"service": "services",
|
|
442
|
+
"postgres": "postgres",
|
|
443
|
+
"keyValue": "key-value",
|
|
444
|
+
"disk": "disks",
|
|
445
|
+
}
|
|
446
|
+
missing = await self._delete(f"/{paths[input['kind']]}/{enc(input['id'])}")
|
|
447
|
+
return {
|
|
448
|
+
"kind": input["kind"],
|
|
449
|
+
"id": input["id"],
|
|
450
|
+
"deleted": True,
|
|
451
|
+
"alreadyMissing": missing,
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
async def get_deploy_diagnostics(
|
|
455
|
+
self, input: t.GetDeployDiagnosticsInput
|
|
456
|
+
) -> t.DeployDiagnosticsResult:
|
|
457
|
+
deploy = await self.get_deploy(input["serviceId"], input["deployId"])
|
|
458
|
+
max_lines = int(nullish(input.get("maxLines"), 200))
|
|
459
|
+
maximum = validate_byte_limit(nullish(input.get("maxBytes"), 128000), MAX_TEXT_BYTES)
|
|
460
|
+
params: dict[str, Any] = {"ownerId": input["ownerId"], "resource": input["serviceId"]}
|
|
461
|
+
if deploy.get("createdAt"):
|
|
462
|
+
params["startTime"] = deploy["createdAt"]
|
|
463
|
+
params["limit"] = max_lines
|
|
464
|
+
raw = await self.api.call("/logs?" + query(params))
|
|
465
|
+
entries = raw if isinstance(raw, list) else raw.get("logs", raw.get("results", []))
|
|
466
|
+
lines: list[t.LogLineDTO] = []
|
|
467
|
+
used = 0
|
|
468
|
+
truncated = len(entries) > max_lines
|
|
469
|
+
for entry in entries[:max_lines]:
|
|
470
|
+
if lines and used >= maximum:
|
|
471
|
+
truncated = True
|
|
472
|
+
break
|
|
473
|
+
message = re.sub(
|
|
474
|
+
r"\x1B\[[0-?]*[ -/]*[@-~]",
|
|
475
|
+
"",
|
|
476
|
+
js_string(nullish(entry.get("message"), entry.get("text", ""))),
|
|
477
|
+
)
|
|
478
|
+
budget = max(0, maximum - used - (1 if lines else 0))
|
|
479
|
+
clipped = message.encode()[:budget].decode("utf-8", errors="ignore")
|
|
480
|
+
truncated |= clipped != message
|
|
481
|
+
lines.append(
|
|
482
|
+
{
|
|
483
|
+
"timestamp": nullish(entry.get("timestamp"), entry.get("time", "")),
|
|
484
|
+
"resourceId": nullish(entry.get("resourceId"), entry.get("resource_id", "")),
|
|
485
|
+
"level": entry.get("level", ""),
|
|
486
|
+
"type": entry.get("type", ""),
|
|
487
|
+
"message": clipped,
|
|
488
|
+
}
|
|
489
|
+
)
|
|
490
|
+
used += len(clipped.encode()) + (1 if len(lines) > 1 else 0)
|
|
491
|
+
if truncated and used >= maximum:
|
|
492
|
+
break
|
|
493
|
+
return {
|
|
494
|
+
"deploy": {
|
|
495
|
+
"id": deploy["id"],
|
|
496
|
+
"serviceId": deploy["serviceId"],
|
|
497
|
+
"status": deploy["status"],
|
|
498
|
+
"commitId": deploy["commitId"],
|
|
499
|
+
"createdAt": deploy.get("createdAt", ""),
|
|
500
|
+
"updatedAt": deploy.get("updatedAt", ""),
|
|
501
|
+
"finishedAt": deploy.get("finishedAt"),
|
|
502
|
+
},
|
|
503
|
+
"logs": lines,
|
|
504
|
+
"failureReason": deploy.get("failureReason"),
|
|
505
|
+
"truncated": truncated,
|
|
506
|
+
"nextStartTime": None
|
|
507
|
+
if isinstance(raw, list)
|
|
508
|
+
else nullish(raw.get("nextStartTime"), raw.get("next_start_time")),
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
@asynccontextmanager
|
|
513
|
+
async def dependencies(deps: Deps | None) -> AsyncIterator[Deps]:
|
|
514
|
+
if deps is not None:
|
|
515
|
+
yield deps
|
|
516
|
+
else:
|
|
517
|
+
async with httpx.AsyncClient(
|
|
518
|
+
timeout=30, transport=httpx.AsyncHTTPTransport(retries=0)
|
|
519
|
+
) as http:
|
|
520
|
+
yield Deps(render=Client(http))
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
RenderPort = Port
|
|
524
|
+
RenderClient = Client
|
|
525
|
+
RenderDeps = Deps
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from render import TaskContext
|
|
2
|
+
|
|
3
|
+
from ._app import app
|
|
4
|
+
from .client import Deps, dependencies
|
|
5
|
+
from .retry import PROVISION_RETRY
|
|
6
|
+
from .types import CreatePrivateServiceInput, CreatePrivateServiceResult
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
async def create_private_service_impl(
|
|
10
|
+
ctx: TaskContext, input: CreatePrivateServiceInput, *, deps: Deps | None = None
|
|
11
|
+
) -> CreatePrivateServiceResult:
|
|
12
|
+
async with dependencies(deps) as resolved:
|
|
13
|
+
return await resolved.render.create_private_service(input)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.task(name="render.createPrivateService", retry=PROVISION_RETRY)
|
|
17
|
+
async def create_private_service(
|
|
18
|
+
ctx: TaskContext, input: CreatePrivateServiceInput
|
|
19
|
+
) -> CreatePrivateServiceResult:
|
|
20
|
+
return await create_private_service_impl(ctx, input)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from render import TaskContext
|
|
2
|
+
|
|
3
|
+
from ._app import app
|
|
4
|
+
from .client import Deps, dependencies
|
|
5
|
+
from .retry import RENDER_RETRY
|
|
6
|
+
from .types import CreateProjectInput, CreateProjectResult
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
async def create_project_impl(
|
|
10
|
+
ctx: TaskContext, input: CreateProjectInput, *, deps: Deps | None = None
|
|
11
|
+
) -> CreateProjectResult:
|
|
12
|
+
async with dependencies(deps) as resolved:
|
|
13
|
+
return await resolved.render.create_project(input)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.task(name="render.createProject", retry=RENDER_RETRY)
|
|
17
|
+
async def create_project(ctx: TaskContext, input: CreateProjectInput) -> CreateProjectResult:
|
|
18
|
+
return await create_project_impl(ctx, input)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from render import TaskContext
|
|
2
|
+
|
|
3
|
+
from ._app import app
|
|
4
|
+
from .client import Deps, dependencies
|
|
5
|
+
from .retry import RENDER_RETRY
|
|
6
|
+
from .types import DeleteProjectInput, DeleteProjectResult
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
async def delete_project_impl(
|
|
10
|
+
ctx: TaskContext, input: DeleteProjectInput, *, deps: Deps | None = None
|
|
11
|
+
) -> DeleteProjectResult:
|
|
12
|
+
async with dependencies(deps) as resolved:
|
|
13
|
+
return await resolved.render.delete_project(input)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.task(name="render.deleteProject", retry=RENDER_RETRY)
|
|
17
|
+
async def delete_project(ctx: TaskContext, input: DeleteProjectInput) -> DeleteProjectResult:
|
|
18
|
+
return await delete_project_impl(ctx, input)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from render import TaskContext
|
|
2
|
+
|
|
3
|
+
from ._app import app
|
|
4
|
+
from .client import Deps, dependencies
|
|
5
|
+
from .retry import RENDER_RETRY
|
|
6
|
+
from .types import DeleteResourceInput, DeleteResourceResult
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
async def delete_resource_impl(
|
|
10
|
+
ctx: TaskContext, input: DeleteResourceInput, *, deps: Deps | None = None
|
|
11
|
+
) -> DeleteResourceResult:
|
|
12
|
+
async with dependencies(deps) as resolved:
|
|
13
|
+
return await resolved.render.delete_resource(input)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.task(name="render.deleteResource", retry=RENDER_RETRY)
|
|
17
|
+
async def delete_resource(ctx: TaskContext, input: DeleteResourceInput) -> DeleteResourceResult:
|
|
18
|
+
return await delete_resource_impl(ctx, input)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from render import TaskContext
|
|
2
|
+
|
|
3
|
+
from ._app import app
|
|
4
|
+
from .client import Deps, dependencies
|
|
5
|
+
from .retry import RENDER_RETRY
|
|
6
|
+
from .types import EnsureServiceResult, ProvisionServiceInput
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
async def ensure_service_impl(
|
|
10
|
+
ctx: TaskContext, input: ProvisionServiceInput, *, deps: Deps | None = None
|
|
11
|
+
) -> EnsureServiceResult:
|
|
12
|
+
async with dependencies(deps) as resolved:
|
|
13
|
+
return await resolved.render.ensure_service(input)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.task(name="render.ensureService", retry=RENDER_RETRY)
|
|
17
|
+
async def ensure_service(ctx: TaskContext, input: ProvisionServiceInput) -> EnsureServiceResult:
|
|
18
|
+
return await ensure_service_impl(ctx, input)
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from render import TaskContext
|
|
2
|
+
|
|
3
|
+
from ._app import app
|
|
4
|
+
from .client import Deps, dependencies
|
|
5
|
+
from .retry import RENDER_RETRY
|
|
6
|
+
from .types import DeployDiagnosticsResult, GetDeployDiagnosticsInput
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
async def get_deploy_diagnostics_impl(
|
|
10
|
+
ctx: TaskContext, input: GetDeployDiagnosticsInput, *, deps: Deps | None = None
|
|
11
|
+
) -> DeployDiagnosticsResult:
|
|
12
|
+
async with dependencies(deps) as resolved:
|
|
13
|
+
return await resolved.render.get_deploy_diagnostics(input)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.task(name="render.getDeployDiagnostics", retry=RENDER_RETRY)
|
|
17
|
+
async def get_deploy_diagnostics(
|
|
18
|
+
ctx: TaskContext, input: GetDeployDiagnosticsInput
|
|
19
|
+
) -> DeployDiagnosticsResult:
|
|
20
|
+
return await get_deploy_diagnostics_impl(ctx, input)
|