Skip to content
This repository was archived by the owner on May 5, 2025. It is now read-only.

Commit 98a9a16

Browse files
chore: some type updates (#473)
Some relevant decisions: * `timeout` passed to `TorngitBaseAdapter.__init__` is transformed into `httpx.Timeout` directly, (so that `self._timeout` can be directly an `httpx.Timeout` object instead a bunch of different options * `verify_ssl` receives the default value of `True`. That shouldn't break anyone except BB server. (but no one is using it, so as I said it shouldn't break anyone) * Better differentiation of aouth_consumer_token and token. They are actually different things.
1 parent de4b37b commit 98a9a16

File tree

5 files changed

+51
-50
lines changed

5 files changed

+51
-50
lines changed

shared/helpers/cache.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ def args_indexes_to_log(self) -> List[int]:
142142
return self.get("args_indexes_to_log", [])
143143

144144
@property
145-
def kwargs_keys_to_log(self) -> List[Any]:
145+
def kwargs_keys_to_log(self) -> List[str]:
146146
"""List of args from the function to be logged (if present)"""
147147
return self.get("kwargs_keys_to_log", [])
148148

shared/torngit/base.py

Lines changed: 37 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import re
22
from enum import Enum
3-
from typing import Dict, List, Optional, Tuple
43

54
import httpx
65

@@ -13,7 +12,6 @@
1312
OnRefreshCallback,
1413
Token,
1514
)
16-
from shared.typings.torngit import TorngitInstanceData
1715

1816
get_start_of_line = re.compile(r"@@ \-(\d+),?(\d*) \+(\d+),?(\d*).*").match
1917

@@ -28,66 +26,67 @@ class TokenType(Enum):
2826
pull = "pull"
2927

3028

31-
TokenTypeMapping = Dict[TokenType, Token]
29+
TokenTypeMapping = dict[TokenType, Token]
3230

3331

3432
class TorngitBaseAdapter(object):
3533
_repo_url: str | None = None
3634
_aws_key = None
37-
_oauth: OauthConsumerToken | None = None
38-
_on_token_refresh: OnRefreshCallback = None
35+
_oauth: OauthConsumerToken | None
36+
_on_token_refresh: OnRefreshCallback | None
3937
_token: Token | None = None
40-
verify_ssl = None
38+
verify_ssl: str | bool
39+
_timeout: httpx.Timeout
40+
valid_languages = set(language[0] for language in Repository.Languages.choices)
4141

42-
valid_languages = set(language.value for language in Repository.Languages)
42+
# These are set by the subclasses
43+
service_url: str | None = None
44+
service: str | None = None
45+
urls: dict[str, str] | None = None
4346

4447
def __init__(
4548
self,
4649
oauth_consumer_token: OauthConsumerToken | None = None,
47-
timeouts=None,
50+
timeout: httpx.Timeout | tuple[int, int] | None = None,
4851
token: Token | None = None,
4952
token_type_mapping: TokenTypeMapping | None = None,
50-
on_token_refresh: OnRefreshCallback = None,
51-
verify_ssl=None,
53+
on_token_refresh: OnRefreshCallback | None = None,
54+
verify_ssl: str | bool = True,
5255
**kwargs,
53-
):
54-
self._timeouts = timeouts or [10, 30]
56+
) -> None:
57+
if isinstance(timeout, tuple):
58+
self._timeout = httpx.Timeout(timeout[1], connect=timeout[0])
59+
else:
60+
self._timeout = timeout or httpx.Timeout(30, connect=10)
5561
self._token = token
5662
self._on_token_refresh = on_token_refresh
5763
self._token_type_mapping = token_type_mapping or {}
5864
self._oauth = oauth_consumer_token
59-
self.data: TorngitInstanceData = {
60-
"owner": {},
61-
"repo": {},
62-
"fallback_installations": None,
63-
"installation": None,
64-
"additional_data": {},
65-
}
6665
self.verify_ssl = verify_ssl
67-
self.data.update(kwargs)
66+
self.data = {
67+
"owner": kwargs.get("owner", {}),
68+
"repo": kwargs.get("repo", {}),
69+
"fallback_installations": kwargs.get("fallback_installations", None),
70+
"installation": kwargs.get("installation", None),
71+
"additional_data": kwargs.get("additional_data", {}),
72+
}
6873
# This has the side effect of initializing the torngit_cache
6974
# (if not yet initialized)
7075
torngit_cache.initialize()
7176

72-
def __repr__(self):
77+
def __repr__(self) -> str:
7378
return "<%s slug=%s ownerid=%s repoid=%s>" % (
7479
self.service,
7580
self.slug,
7681
self.data["owner"].get("ownerid"),
7782
self.data["repo"].get("repoid"),
7883
)
7984

80-
def get_client(self, timeouts: List[int] = []) -> httpx.AsyncClient:
81-
if timeouts:
82-
timeout = httpx.Timeout(timeouts[1], connect=timeouts[0])
83-
else:
84-
timeout = httpx.Timeout(self._timeouts[1], connect=self._timeouts[0])
85+
def get_client(self, timeout: httpx.Timeout | None = None) -> httpx.AsyncClient:
86+
if timeout is None:
87+
timeout = self._timeout
8588
return httpx.AsyncClient(
86-
verify=(
87-
self.verify_ssl
88-
if not isinstance(self.verify_ssl, bool)
89-
else self.verify_ssl
90-
),
89+
verify=self.verify_ssl,
9190
timeout=timeout,
9291
)
9392

@@ -96,7 +95,7 @@ def get_token_by_type(self, token_type: TokenType):
9695
return self._token_type_mapping.get(token_type)
9796
return self.token
9897

99-
def get_token_by_type_if_none(self, token: Optional[str], token_type: TokenType):
98+
def get_token_by_type_if_none(self, token: str | None, token_type: TokenType):
10099
if token is not None:
101100
return token
102101
return self.get_token_by_type(token_type)
@@ -106,14 +105,15 @@ def _oauth_consumer_token(self) -> OauthConsumerToken:
106105
raise Exception("Oauth consumer token not present")
107106
return self._oauth
108107

109-
def _validate_language(self, language: str) -> str | None:
108+
def _validate_language(self, language: str | None) -> str | None:
110109
if language:
111110
language = language.lower()
111+
112112
if language in self.valid_languages:
113113
return language
114114
return None
115115

116-
def set_token(self, token: OauthConsumerToken) -> None:
116+
def set_token(self, token: Token) -> None:
117117
self._token = token
118118

119119
@property
@@ -329,7 +329,7 @@ async def edit_webhook(
329329

330330
# OTHERS
331331

332-
async def get_authenticated(self, token=None) -> Tuple[bool, bool]:
332+
async def get_authenticated(self, token=None) -> tuple[bool, bool]:
333333
"""Finds the user permissions about about whether the user on
334334
`self.data["user"]` can access the repo from `self.data["repo"]`
335335
Returns a `can_view` and a `can_edit` permission tuple
@@ -357,7 +357,7 @@ async def get_authenticated_user(self, **kwargs):
357357
async def get_branches(self, token=None):
358358
raise NotImplementedError()
359359

360-
async def get_branch(self, token=None):
360+
async def get_branch(self, branch_name: str, token=None):
361361
raise NotImplementedError()
362362

363363
async def get_compare(
@@ -426,7 +426,7 @@ async def list_top_level_files(self, ref, token=None):
426426
async def get_workflow_run(self, run_id, token=None):
427427
raise NotImplementedError()
428428

429-
async def get_best_effort_branches(self, commit_sha: str, token=None) -> List[str]:
429+
async def get_best_effort_branches(self, commit_sha: str, token=None) -> list[str]:
430430
"""
431431
Gets a 'best effort' list of branches this commit is in.
432432
If a branch is returned, this means this commit is in that branch. If not, it could still be

shared/torngit/cache/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ def is_initialized(self) -> bool:
4747
def is_enabled(self) -> bool:
4848
return self._enabled
4949

50-
def get_ttl(self, endpoint: CachedEndpoint) -> dict:
50+
def get_ttl(self, endpoint: CachedEndpoint) -> int:
5151
return self.ttls.get(endpoint, 120)
5252

5353

shared/typings/oauth_token_types.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
from typing import Awaitable, Callable, Optional, TypedDict
1+
from typing import Awaitable, Callable, NotRequired, TypedDict
22

33

44
class Token(TypedDict):
55
key: str
6+
refresh_token: NotRequired[str]
67
# This information is used to identify the token owner in the logs, if present
78
username: str | None
89
# This represents the entity it belongs to. Entities can have the form of
@@ -13,9 +14,9 @@ class Token(TypedDict):
1314
entity_name: str | None
1415

1516

16-
class OauthConsumerToken(Token):
17-
secret: Optional[str]
18-
refresh_token: Optional[str]
17+
class OauthConsumerToken(TypedDict):
18+
key: str # client_id
19+
secret: str
1920

2021

21-
OnRefreshCallback = Optional[Callable[[OauthConsumerToken], Awaitable[None]]]
22+
OnRefreshCallback = Callable[[Token], Awaitable[None]]

shared/typings/torngit.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Dict, List, NotRequired, Optional, TypedDict, Union
1+
from typing import Dict, List, NotRequired, Optional, TypedDict
22

33
from shared.reports.types import UploadType
44

@@ -38,8 +38,8 @@ class AdditionalData(TypedDict):
3838

3939

4040
class TorngitInstanceData(TypedDict):
41-
owner: Union[OwnerInfo, Dict]
42-
repo: Union[RepoInfo, Dict]
43-
fallback_installations: List[Optional[GithubInstallationInfo]] | None
44-
installation: Optional[GithubInstallationInfo]
45-
additional_data: Optional[AdditionalData]
41+
owner: OwnerInfo | Dict
42+
repo: RepoInfo | Dict
43+
fallback_installations: List[GithubInstallationInfo | None] | None
44+
installation: GithubInstallationInfo | None
45+
additional_data: AdditionalData | None

0 commit comments

Comments
 (0)