-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathcronjobs.py
More file actions
168 lines (145 loc) · 4.42 KB
/
cronjobs.py
File metadata and controls
168 lines (145 loc) · 4.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import datetime
import os
from threading import Thread
import click
import requests
from bs4 import BeautifulSoup
from github import Github
from github.GithubException import *
from gorse import Gorse
from sqlalchemy import create_engine, or_
from sqlalchemy.orm import sessionmaker
from utils import *
# Setup logger
logger = get_logger("cronjobs")
# Setup clients
github_client = Github(os.getenv("GITHUB_ACCESS_TOKEN"))
gorse_client = Gorse(os.getenv("GORSE_ADDRESS"), os.getenv("GORSE_API_KEY"))
# Setup sqlalchemy
engine = create_engine(os.getenv("SQLALCHEMY_DATABASE_URI"))
Session = sessionmaker()
Session.configure(bind=engine)
TRENDING_PAGES = [
"",
"python",
"java",
"javascript",
"c++",
"go",
"typescript",
"php",
"ruby",
"c",
"c#",
"nix",
"shell",
"scala",
"rust",
"kotlin",
"dart",
"swift",
"unknown",
]
def get_trending():
"""
Get trending repositories of C, C++, Go, Python, JS, Java, Rust, TS and unknown.
"""
full_names = []
for language_page in TRENDING_PAGES:
r = requests.get("https://github.com/trending/%s" % language_page)
if r.status_code != 200:
return full_names
soup = BeautifulSoup(r.text, "html.parser")
for article in soup.find_all("article"):
full_names.append(article.h2.a["href"][1:])
return full_names
def insert_trending():
"""
Insert trending repositories of C, C++, Go, Python, JS, Java, Rust, TS and unknown.
"""
logger.info("start pull trending repos")
trending_count = 0
trending_repos = get_trending()
for trending_repo in trending_repos:
try:
item = get_repo_info(github_client, trending_repo)
if item is not None:
gorse_client.insert_item(item)
trending_count += 1
except Exception as e:
logger.error(
"failed to insert trending repository",
extra={"tags": {"repo": trending_repo, "exception": str(e)}},
)
logger.info(
"insert trending repository succeed",
extra={"tags": {"num_repos": trending_count}},
)
def cleanup_expired_cache():
"""
Clean up expired KV cache entries.
"""
session = Session()
try:
expired_count = session.query(KvCache).filter(
KvCache.expire < datetime.datetime.utcnow()
).delete(synchronize_session=False)
session.commit()
logger.info(f"Cleaned up {expired_count} expired cache entries")
except Exception:
session.rollback()
raise
finally:
session.close()
def insert_trending_entry():
try:
insert_trending()
except Exception as e:
logger.exception("failed to insert trending repositories")
def update_users():
"""
Update user starred repositories.
"""
session = Session()
for user in session.query(User).filter(
or_(
User.pulled_at == None,
User.pulled_at < datetime.datetime.utcnow() - datetime.timedelta(days=1),
)
):
# print(user.login, user.token["access_token"], user.pulled_at)
try:
update_user(
gorse_client, user.token["access_token"], user.pulled_at)
user.pulled_at = datetime.datetime.now()
except BadCredentialsException as e:
session.delete(user)
logger.warning(
"invalid user token",
extra={"tags": {"login": user.login, "exception": str(e)}},
)
session.commit()
def insert_users_entry():
try:
update_users()
except:
logger.exception("failed to update user labels and feedback")
@click.command()
@click.option("--update-users", is_flag=True)
@click.option("--insert-trending", is_flag=True)
@click.option("--cleanup-cache", is_flag=True)
def main(update_users: bool, insert_trending: bool, cleanup_cache: bool):
threads = []
run_all = update_users is False and insert_trending is False and cleanup_cache is False
if run_all or insert_trending:
threads.append(Thread(target=insert_trending_entry))
if run_all or update_users:
threads.append(Thread(target=insert_users_entry))
if run_all or cleanup_cache:
threads.append(Thread(target=cleanup_expired_cache))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
if __name__ == "__main__":
main()