Receive the best robot token only once

This commit is contained in:
Mikhail f. Shiryaev 2023-04-28 16:01:53 +02:00
parent 309291a27c
commit 8c60b60916
No known key found for this signature in database
GPG Key ID: 4B02ED204C7D93F4

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python3
import logging
from dataclasses import dataclass
from typing import Optional
import boto3 # type: ignore
from github import Github
@ -20,7 +21,13 @@ def get_parameter_from_ssm(name, decrypt=True, client=None):
return client.get_parameter(Name=name, WithDecryption=decrypt)["Parameter"]["Value"]
ROBOT_TOKEN = None # type: Optional[Token]
def get_best_robot_token(token_prefix_env_name="github_robot_token_"):
global ROBOT_TOKEN
if ROBOT_TOKEN is not None:
return ROBOT_TOKEN.value
client = boto3.client("ssm", region_name="us-east-1")
parameters = client.describe_parameters(
ParameterFilters=[
@ -28,7 +35,6 @@ def get_best_robot_token(token_prefix_env_name="github_robot_token_"):
]
)["Parameters"]
assert parameters
token = None
for token_name in [p["Name"] for p in parameters]:
value = get_parameter_from_ssm(token_name, True, client)
@ -38,15 +44,17 @@ def get_best_robot_token(token_prefix_env_name="github_robot_token_"):
user = gh.get_user()
rest, _ = gh.rate_limiting
logging.info("Get token with %s remaining requests", rest)
if token is None:
token = Token(user, value, rest)
if ROBOT_TOKEN is None:
ROBOT_TOKEN = Token(user, value, rest)
continue
if token.rest < rest:
token.user, token.value, token.rest = user, value, rest
if ROBOT_TOKEN.rest < rest:
ROBOT_TOKEN.user, ROBOT_TOKEN.value, ROBOT_TOKEN.rest = user, value, rest
assert token
assert ROBOT_TOKEN
logging.info(
"User %s with %s remaining requests is used", token.user.login, token.rest
"User %s with %s remaining requests is used",
ROBOT_TOKEN.user.login,
ROBOT_TOKEN.rest,
)
return token.value
return ROBOT_TOKEN.value