render-lab-tasks-github 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.
@@ -0,0 +1,11 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.py[cod]
4
+ .pytest_cache/
5
+ .mypy_cache/
6
+ .ruff_cache/
7
+ dist/
8
+ *.egg-info/
9
+ .env
10
+ .env.*
11
+ !.env.example
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Render Lab
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,78 @@
1
+ Metadata-Version: 2.5
2
+ Name: render-lab-tasks-github
3
+ Version: 0.1.0
4
+ Summary: GitHub issue tasks for Render Workflows
5
+ Project-URL: Repository, https://github.com/render-lab/render-tasks-python
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.12
9
+ Requires-Dist: httpx<0.29,>=0.28
10
+ Requires-Dist: render==1.0.1
11
+ Description-Content-Type: text/markdown
12
+
13
+ # render-lab-tasks-github
14
+
15
+ GitHub issue tasks for Render Workflows. Initial subset: `github.listNewIssues`
16
+ and `github.applyLabels`. Other TypeScript GitHub tasks have not yet been ported.
17
+
18
+ This distribution is not yet on PyPI. From this repository:
19
+
20
+ ```sh
21
+ uv pip install ./packages/tasks-github
22
+ ```
23
+
24
+ ```python
25
+ from render import TaskContext, Workflows
26
+ from render_lab_tasks_github.tasks import app as github_app, list_new_issues
27
+
28
+ app = Workflows.from_workflows(github_app)
29
+
30
+
31
+ @app.task(name="example.readIssues")
32
+ async def read_issues(ctx: TaskContext):
33
+ return await ctx.run(list_new_issues, {"repo": "render-oss/sdk", "limit": 5})
34
+ ```
35
+
36
+ Call `app.start()` from the workflow entry point. Raw `list_new_issues_impl` and
37
+ `apply_labels_impl` are also exported from `.tasks`; inject `GitHubDeps` with a
38
+ `GitHubPort` fake to test or wrap under your own task name. Do not call a wrapped
39
+ task directly. Use `await ctx.run(task, input)`.
40
+
41
+ ## Contract
42
+
43
+ `list_new_issues` takes `repo` (`owner/name`), optional `sinceISO`, and optional
44
+ nonnegative integer `limit` (default 50; explicit null also selects 50, matching
45
+ TypeScript). Returns plain issue dictionaries with
46
+ `number`, `title`, `body`, `url`, `labels`, `createdAt`, and nullable `author`.
47
+ Lists open issues newest-created first, skips pull requests, and follows pages
48
+ until the requested issue count or the end. `sinceISO` filters by GitHub's
49
+ updated-since behavior, matching the TS adapter. Zero limit performs no request.
50
+
51
+ `apply_labels` takes `repo`, `issueNumber`, and `labels`. Returns `issueNumber`
52
+ and the requested `labels`. An empty label list makes no HTTP request. This task
53
+ writes when called; dry-run decisions belong to the workflow caller.
54
+
55
+ ## Environment
56
+
57
+ | Variable | Required | Purpose |
58
+ | --- | --- | --- |
59
+ | GITHUB_TOKEN | For writes/private repos; optional for public reads | GitHub token with permissions for the requested repository/operation |
60
+
61
+ Credentials are read during calls, never at import. GitHub responses determine
62
+ permission failures. HTTPX uses a 30-second timeout and no automatic retries.
63
+ Render retries failed tasks up to three times with a 1000 ms base delay and 2x
64
+ backoff. Pagination may make multiple requests within an attempt; writes may be
65
+ retried and callers must account for vendor idempotency.
66
+
67
+ ## Render SDK 1.0.1 result limitation
68
+
69
+ The raw implementation always returns a list. The pinned SDK unwraps a singleton
70
+ list after a durable child run, so consumers should normalize the result:
71
+
72
+ ```python
73
+ issues = await ctx.run(list_new_issues, {"repo": "owner/repo", "limit": 5})
74
+ if isinstance(issues, dict):
75
+ issues = [issues]
76
+ ```
77
+
78
+ Both examples include this workaround. See [ADR-0005](../../docs/adr/0005-sdk-singleton-list-results.md).
@@ -0,0 +1,66 @@
1
+ # render-lab-tasks-github
2
+
3
+ GitHub issue tasks for Render Workflows. Initial subset: `github.listNewIssues`
4
+ and `github.applyLabels`. Other TypeScript GitHub tasks have not yet been ported.
5
+
6
+ This distribution is not yet on PyPI. From this repository:
7
+
8
+ ```sh
9
+ uv pip install ./packages/tasks-github
10
+ ```
11
+
12
+ ```python
13
+ from render import TaskContext, Workflows
14
+ from render_lab_tasks_github.tasks import app as github_app, list_new_issues
15
+
16
+ app = Workflows.from_workflows(github_app)
17
+
18
+
19
+ @app.task(name="example.readIssues")
20
+ async def read_issues(ctx: TaskContext):
21
+ return await ctx.run(list_new_issues, {"repo": "render-oss/sdk", "limit": 5})
22
+ ```
23
+
24
+ Call `app.start()` from the workflow entry point. Raw `list_new_issues_impl` and
25
+ `apply_labels_impl` are also exported from `.tasks`; inject `GitHubDeps` with a
26
+ `GitHubPort` fake to test or wrap under your own task name. Do not call a wrapped
27
+ task directly. Use `await ctx.run(task, input)`.
28
+
29
+ ## Contract
30
+
31
+ `list_new_issues` takes `repo` (`owner/name`), optional `sinceISO`, and optional
32
+ nonnegative integer `limit` (default 50; explicit null also selects 50, matching
33
+ TypeScript). Returns plain issue dictionaries with
34
+ `number`, `title`, `body`, `url`, `labels`, `createdAt`, and nullable `author`.
35
+ Lists open issues newest-created first, skips pull requests, and follows pages
36
+ until the requested issue count or the end. `sinceISO` filters by GitHub's
37
+ updated-since behavior, matching the TS adapter. Zero limit performs no request.
38
+
39
+ `apply_labels` takes `repo`, `issueNumber`, and `labels`. Returns `issueNumber`
40
+ and the requested `labels`. An empty label list makes no HTTP request. This task
41
+ writes when called; dry-run decisions belong to the workflow caller.
42
+
43
+ ## Environment
44
+
45
+ | Variable | Required | Purpose |
46
+ | --- | --- | --- |
47
+ | GITHUB_TOKEN | For writes/private repos; optional for public reads | GitHub token with permissions for the requested repository/operation |
48
+
49
+ Credentials are read during calls, never at import. GitHub responses determine
50
+ permission failures. HTTPX uses a 30-second timeout and no automatic retries.
51
+ Render retries failed tasks up to three times with a 1000 ms base delay and 2x
52
+ backoff. Pagination may make multiple requests within an attempt; writes may be
53
+ retried and callers must account for vendor idempotency.
54
+
55
+ ## Render SDK 1.0.1 result limitation
56
+
57
+ The raw implementation always returns a list. The pinned SDK unwraps a singleton
58
+ list after a durable child run, so consumers should normalize the result:
59
+
60
+ ```python
61
+ issues = await ctx.run(list_new_issues, {"repo": "owner/repo", "limit": 5})
62
+ if isinstance(issues, dict):
63
+ issues = [issues]
64
+ ```
65
+
66
+ Both examples include this workaround. See [ADR-0005](../../docs/adr/0005-sdk-singleton-list-results.md).
@@ -0,0 +1,19 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27,<2"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "render-lab-tasks-github"
7
+ version = "0.1.0"
8
+ description = "GitHub issue tasks for Render Workflows"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.12"
13
+ dependencies = ["render==1.0.1", "httpx>=0.28,<0.29"]
14
+
15
+ [project.urls]
16
+ Repository = "https://github.com/render-lab/render-tasks-python"
17
+
18
+ [tool.hatch.build.targets.wheel]
19
+ packages = ["src/render_lab_tasks_github"]
@@ -0,0 +1 @@
1
+ """GitHub task pack. Import .tasks explicitly to register task definitions."""
@@ -0,0 +1,3 @@
1
+ from render import Workflows
2
+
3
+ app = Workflows()
@@ -0,0 +1,21 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import GitHubDeps, github_dependencies, parse_repo
5
+ from .retry import GITHUB_RETRY
6
+ from .types import ApplyLabelsInput, ApplyLabelsResult
7
+
8
+
9
+ async def apply_labels_impl(
10
+ ctx: TaskContext, input: ApplyLabelsInput, *, deps: GitHubDeps | None = None
11
+ ) -> ApplyLabelsResult:
12
+ """Add labels. The caller decides whether a workflow is a dry run."""
13
+ owner, repo = parse_repo(input["repo"])
14
+ async with github_dependencies(deps) as resolved:
15
+ await resolved.github.add_labels(owner, repo, input["issueNumber"], input["labels"])
16
+ return {"issueNumber": input["issueNumber"], "labels": list(input["labels"])}
17
+
18
+
19
+ @app.task(name="github.applyLabels", retry=GITHUB_RETRY)
20
+ async def apply_labels(ctx: TaskContext, input: ApplyLabelsInput) -> ApplyLabelsResult:
21
+ return await apply_labels_impl(ctx, input)
@@ -0,0 +1,118 @@
1
+ """The injected GitHub interface and its async REST adapter."""
2
+
3
+ import os
4
+ import re
5
+ from collections.abc import AsyncIterator, Mapping
6
+ from contextlib import asynccontextmanager
7
+ from dataclasses import dataclass
8
+ from typing import Any, Protocol
9
+ from urllib.parse import quote
10
+
11
+ import httpx
12
+
13
+ from .types import IssueDTO
14
+
15
+
16
+ class GitHubPort(Protocol):
17
+ async def list_issues(
18
+ self, owner: str, repo: str, since_iso: str | None, limit: int
19
+ ) -> list[IssueDTO]: ...
20
+
21
+ async def add_labels(
22
+ self, owner: str, repo: str, issue_number: int, labels: list[str]
23
+ ) -> None: ...
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class GitHubDeps:
28
+ github: GitHubPort
29
+
30
+
31
+ def parse_repo(repo: str) -> tuple[str, str]:
32
+ match = re.fullmatch(r"([^/\s]+)/([^/\s]+)", repo.strip())
33
+ if match is None:
34
+ raise ValueError(f'Invalid repo "{repo}". Expected "owner/name".')
35
+ return match[1], match[2]
36
+
37
+
38
+ def to_issue_dto(raw: dict[str, Any]) -> IssueDTO:
39
+ labels = [label if isinstance(label, str) else label.get("name") for label in raw["labels"]]
40
+ return {
41
+ "number": raw["number"],
42
+ "title": raw["title"],
43
+ "body": raw.get("body") or "",
44
+ "url": raw["html_url"],
45
+ "labels": [label for label in labels if label],
46
+ "createdAt": raw["created_at"],
47
+ "author": (raw.get("user") or {}).get("login"),
48
+ }
49
+
50
+
51
+ class GitHubClient:
52
+ """Caller owns the injected HTTP client; construction reads no credentials."""
53
+
54
+ def __init__(self, http: httpx.AsyncClient, env: Mapping[str, str] | None = None) -> None:
55
+ self.http = http
56
+ self.env = os.environ if env is None else env
57
+
58
+ def _headers(self) -> dict[str, str]:
59
+ headers = {"Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28"}
60
+ if token := self.env.get("GITHUB_TOKEN"):
61
+ headers["Authorization"] = f"Bearer {token}"
62
+ return headers
63
+
64
+ def _issues_url(self, owner: str, repo: str) -> str:
65
+ return f"https://api.github.com/repos/{quote(owner, safe='')}/{quote(repo, safe='')}/issues"
66
+
67
+ async def list_issues(
68
+ self, owner: str, repo: str, since_iso: str | None, limit: int
69
+ ) -> list[IssueDTO]:
70
+ issues: list[IssueDTO] = []
71
+ page = 1
72
+ while len(issues) < limit:
73
+ params: dict[str, str | int] = {
74
+ "state": "open",
75
+ "sort": "created",
76
+ "direction": "desc",
77
+ "per_page": 100,
78
+ "page": page,
79
+ }
80
+ if since_iso:
81
+ params["since"] = since_iso
82
+ response = await self.http.get(
83
+ self._issues_url(owner, repo), params=params, headers=self._headers()
84
+ )
85
+ response.raise_for_status()
86
+ for raw in response.json():
87
+ if raw.get("pull_request") is not None:
88
+ continue
89
+ issues.append(to_issue_dto(raw))
90
+ if len(issues) == limit:
91
+ return issues
92
+ if "next" not in response.links:
93
+ break
94
+ # Keep pagination on the configured GitHub endpoint; never forward
95
+ # credentials to an arbitrary URL in a response header.
96
+ page += 1
97
+ return issues
98
+
99
+ async def add_labels(self, owner: str, repo: str, issue_number: int, labels: list[str]) -> None:
100
+ if not labels:
101
+ return
102
+ response = await self.http.post(
103
+ f"{self._issues_url(owner, repo)}/{issue_number}/labels",
104
+ json={"labels": labels},
105
+ headers=self._headers(),
106
+ )
107
+ response.raise_for_status()
108
+
109
+
110
+ @asynccontextmanager
111
+ async def github_dependencies(deps: GitHubDeps | None) -> AsyncIterator[GitHubDeps]:
112
+ if deps is not None:
113
+ yield deps
114
+ else:
115
+ async with httpx.AsyncClient(
116
+ timeout=30, transport=httpx.AsyncHTTPTransport(retries=0)
117
+ ) as http:
118
+ yield GitHubDeps(github=GitHubClient(http))
@@ -0,0 +1,27 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import GitHubDeps, github_dependencies, parse_repo
5
+ from .retry import GITHUB_RETRY
6
+ from .types import IssueDTO, ListNewIssuesInput
7
+
8
+
9
+ async def list_new_issues_impl(
10
+ ctx: TaskContext, input: ListNewIssuesInput, *, deps: GitHubDeps | None = None
11
+ ) -> list[IssueDTO]:
12
+ """List open issues newest first, filtering PRs before applying the limit."""
13
+ owner, repo = parse_repo(input["repo"])
14
+ limit = input.get("limit")
15
+ if limit is None:
16
+ limit = 50
17
+ if isinstance(limit, bool) or not isinstance(limit, int) or limit < 0:
18
+ raise ValueError("limit must be a nonnegative integer")
19
+ if limit == 0:
20
+ return []
21
+ async with github_dependencies(deps) as resolved:
22
+ return await resolved.github.list_issues(owner, repo, input.get("sinceISO"), limit)
23
+
24
+
25
+ @app.task(name="github.listNewIssues", retry=GITHUB_RETRY)
26
+ async def list_new_issues(ctx: TaskContext, input: ListNewIssuesInput) -> list[IssueDTO]:
27
+ return await list_new_issues_impl(ctx, input)
@@ -0,0 +1,3 @@
1
+ from render import Retry
2
+
3
+ GITHUB_RETRY = Retry(max_retries=3, wait_duration_ms=1000, backoff_scaling=2)
@@ -0,0 +1,7 @@
1
+ """Explicit task registration and public task exports."""
2
+
3
+ from ._app import app
4
+ from .apply_labels import apply_labels, apply_labels_impl
5
+ from .list_new_issues import list_new_issues, list_new_issues_impl
6
+
7
+ __all__ = ["app", "apply_labels", "apply_labels_impl", "list_new_issues", "list_new_issues_impl"]
@@ -0,0 +1,28 @@
1
+ from typing import NotRequired, TypedDict
2
+
3
+
4
+ class IssueDTO(TypedDict):
5
+ number: int
6
+ title: str
7
+ body: str
8
+ url: str
9
+ labels: list[str]
10
+ createdAt: str
11
+ author: str | None
12
+
13
+
14
+ class ListNewIssuesInput(TypedDict):
15
+ repo: str
16
+ sinceISO: NotRequired[str]
17
+ limit: NotRequired[int | None]
18
+
19
+
20
+ class ApplyLabelsInput(TypedDict):
21
+ repo: str
22
+ issueNumber: int
23
+ labels: list[str]
24
+
25
+
26
+ class ApplyLabelsResult(TypedDict):
27
+ issueNumber: int
28
+ labels: list[str]
@@ -0,0 +1,135 @@
1
+ import json
2
+ from unittest.mock import AsyncMock
3
+
4
+ import httpx
5
+ import pytest
6
+ from render_lab_tasks_github.client import GitHubClient, GitHubDeps, parse_repo
7
+ from render_lab_tasks_github.tasks import apply_labels_impl, list_new_issues_impl
8
+
9
+
10
+ def issue(number, **overrides):
11
+ return {
12
+ "number": number,
13
+ "title": f"Issue {number}",
14
+ "body": None,
15
+ "html_url": f"https://github.com/o/r/issues/{number}",
16
+ "labels": ["bug", {"name": "triage"}, {"name": None}],
17
+ "created_at": "2026-09-01T00:00:00Z",
18
+ "user": None,
19
+ **overrides,
20
+ }
21
+
22
+
23
+ async def test_pagination_filters_prs_before_limit_and_maps_json(ctx):
24
+ requests = []
25
+
26
+ def handler(request):
27
+ requests.append(request)
28
+ assert request.url.params["since"] == "2026-09-01T00:00:00Z"
29
+ assert request.url.params["per_page"] == "100"
30
+ assert request.url.params["sort"] == "created"
31
+ assert "authorization" not in request.headers
32
+ if request.url.params["page"] == "1":
33
+ return httpx.Response(
34
+ 200,
35
+ json=[issue(4, pull_request={}), issue(3)],
36
+ headers={"Link": '<https://api.github.com/repos/o/r/issues?page=2>; rel="next"'},
37
+ )
38
+ return httpx.Response(200, json=[issue(2), issue(1)])
39
+
40
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
41
+ result = await list_new_issues_impl(
42
+ ctx,
43
+ {"repo": " o/r ", "sinceISO": "2026-09-01T00:00:00Z", "limit": 2},
44
+ deps=GitHubDeps(GitHubClient(http, env={})),
45
+ )
46
+ assert [value["number"] for value in result] == [3, 2]
47
+ assert result[0] == {
48
+ "number": 3,
49
+ "title": "Issue 3",
50
+ "body": "",
51
+ "url": "https://github.com/o/r/issues/3",
52
+ "labels": ["bug", "triage"],
53
+ "createdAt": "2026-09-01T00:00:00Z",
54
+ "author": None,
55
+ }
56
+ assert json.loads(json.dumps(result)) == result
57
+ assert len(requests) == 2
58
+
59
+
60
+ async def test_more_than_one_hundred_issues(ctx):
61
+ def handler(request):
62
+ if request.url.params["page"] == "1":
63
+ return httpx.Response(
64
+ 200,
65
+ json=[issue(n) for n in range(150, 50, -1)],
66
+ headers={"Link": '<https://api.github.com/repos/o/r/issues?page=2>; rel="next"'},
67
+ )
68
+ return httpx.Response(200, json=[issue(n) for n in range(50, 0, -1)])
69
+
70
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
71
+ result = await list_new_issues_impl(
72
+ ctx, {"repo": "o/r", "limit": 120}, deps=GitHubDeps(GitHubClient(http))
73
+ )
74
+ assert len(result) == 120
75
+ assert result[-1]["number"] == 31
76
+
77
+
78
+ @pytest.mark.parametrize("options", [{}, {"limit": None}])
79
+ async def test_default_limit_and_injected_port(ctx, options):
80
+ port = AsyncMock()
81
+ port.list_issues.return_value = []
82
+ assert await list_new_issues_impl(ctx, {"repo": "o/r", **options}, deps=GitHubDeps(port)) == []
83
+ port.list_issues.assert_awaited_once_with("o", "r", None, 50)
84
+
85
+
86
+ @pytest.mark.parametrize("repo", ["invalid", "a/b/c", "a b/c", "a/", " /b"])
87
+ def test_invalid_repo(repo):
88
+ with pytest.raises(ValueError, match="owner/name"):
89
+ parse_repo(repo)
90
+
91
+
92
+ @pytest.mark.parametrize("limit", [-1, True, 1.5])
93
+ async def test_invalid_limit_fails_before_network(ctx, limit):
94
+ with pytest.raises(ValueError, match="nonnegative integer"):
95
+ await list_new_issues_impl(ctx, {"repo": "o/r", "limit": limit})
96
+
97
+
98
+ async def test_zero_limit_needs_no_http(ctx):
99
+ assert await list_new_issues_impl(ctx, {"repo": "o/r", "limit": 0}) == []
100
+
101
+
102
+ async def test_labels_lazy_auth_and_empty_noop(ctx):
103
+ env = {}
104
+ requests = []
105
+
106
+ def handler(request):
107
+ requests.append(request)
108
+ assert request.headers["authorization"] == "Bearer fixture-token"
109
+ assert request.url.path == "/repos/o/r/issues/7/labels"
110
+ assert json.loads(request.content) == {"labels": ["bug"]}
111
+ return httpx.Response(200, json=[])
112
+
113
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
114
+ deps = GitHubDeps(GitHubClient(http, env))
115
+ env["GITHUB_TOKEN"] = "fixture-token"
116
+ result = await apply_labels_impl(
117
+ ctx, {"repo": "o/r", "issueNumber": 7, "labels": ["bug"]}, deps=deps
118
+ )
119
+ await apply_labels_impl(ctx, {"repo": "o/r", "issueNumber": 7, "labels": []}, deps=deps)
120
+ assert result == {"issueNumber": 7, "labels": ["bug"]}
121
+ assert len(requests) == 1
122
+
123
+
124
+ @pytest.mark.parametrize("status", [401, 403, 429, 500])
125
+ async def test_http_failure_is_one_attempt(ctx, status):
126
+ requests = []
127
+
128
+ def handler(request):
129
+ requests.append(request)
130
+ return httpx.Response(status, json={"message": "fixture failure"})
131
+
132
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
133
+ with pytest.raises(httpx.HTTPStatusError):
134
+ await list_new_issues_impl(ctx, {"repo": "o/r"}, deps=GitHubDeps(GitHubClient(http)))
135
+ assert len(requests) == 1