-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathviews.py
More file actions
251 lines (213 loc) · 8.48 KB
/
views.py
File metadata and controls
251 lines (213 loc) · 8.48 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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
from dataclasses import dataclass
from enum import Enum
from rest_framework.authentication import SessionAuthentication
from rest_framework.decorators import api_view, authentication_classes
from rest_framework.response import Response
from jobserver.api.authentication import get_backend_from_token
from jobserver.github import GitHubError, _get_github_api
from jobserver.models import User, Workspace
from .config import ORG_OUTPUT_CHECKING_REPOS
from .emails import (
send_request_approved_email,
send_request_rejected_email,
send_request_released_email,
send_request_returned_email,
)
from .issues import (
IssueStatusLabel,
close_output_checking_issue,
create_output_checking_issue,
update_output_checking_issue,
)
class NotificationError(Exception): ...
class EventType(Enum):
REQUEST_SUBMITTED = "request submitted"
REQUEST_WITHDRAWN = "request withdrawn"
REQUEST_APPROVED = "request approved"
REQUEST_RELEASED = "request released"
REQUEST_REJECTED = "request rejected"
REQUEST_RETURNED = "request returned"
REQUEST_RESUBMITTED = "request resubmitted"
REQUEST_PARTIALLY_REVIEWED = "request reviewed"
REQUEST_REVIEWED = "request reviewed"
def status_label(self):
"""The GitHub Issue label that should be added for this request"""
match self:
case EventType.REQUEST_SUBMITTED | EventType.REQUEST_RESUBMITTED:
return IssueStatusLabel.PENDING_REVIEW
case EventType.REQUEST_PARTIALLY_REVIEWED | EventType.REQUEST_REVIEWED:
return IssueStatusLabel.UNDER_REVIEW
case EventType.REQUEST_RETURNED:
return IssueStatusLabel.WITH_REQUESTER
case _:
return None
@dataclass(frozen=True)
class AirlockEvent:
event_type: EventType
workspace: Workspace
updates: list
release_request_id: str
request_author: User
user: User
org: str
repo: str
@classmethod
def from_payload(cls, data):
event_type = data.get("event_type").upper()
try:
event_type = EventType[event_type]
except KeyError:
raise NotificationError(f"Unknown event type '{event_type}'")
updates = data.get("updates") or []
request_author = User.objects.get(username=data.get("request_author"))
username = data.get("user")
if username == request_author.username:
user = request_author
else:
user = User.objects.get(username=username)
workspace = Workspace.objects.get(name=data.get("workspace"))
org = data.get("org")
repo = data.get("repo")
if org is None:
lookup = "default"
# We check to see whether any of the project's organisations do their own
# output checking. If a project has multiple organisations and more than
# one does its own output checking, we choose one arbitrarily but
# consistently. At time of writing (March 2025) this is a hypothetical
# situation.
for org in workspace.project.orgs.order_by("slug"):
if org.slug in ORG_OUTPUT_CHECKING_REPOS:
lookup = org.slug
org = ORG_OUTPUT_CHECKING_REPOS[lookup]["org"]
repo = ORG_OUTPUT_CHECKING_REPOS[lookup]["repo"]
workspace.project
return cls(
event_type=event_type,
updates=updates,
workspace=workspace,
release_request_id=data.get("request"),
request_author=request_author,
user=user,
org=org,
repo=repo,
)
def describe_event(self):
return self.event_type.value
def _update_dict_to_string(self, update_dict):
user = update_dict.get("user")
group = update_dict.get("group")
update = update_dict.get("update_type") or update_dict.get("update")
update_string = update
if group:
update_string = f"{update_string} (filegroup {group})"
if user:
update_string = f"{update_string} by user {user}"
return update_string
def describe_updates(self):
updates = [f"{self.describe_event()} by user {self.user.username}"]
for update_dict in self.updates:
updates.append(self._update_dict_to_string(update_dict))
return updates
def describe_updates_as_str(self):
updates = self.describe_updates()
str_updates = "\n".join([f"- {update}" for update in updates])
return str_updates
def create_issue(airlock_event: AirlockEvent, github_api=None):
github_api = github_api or _get_github_api()
try:
create_output_checking_issue(
airlock_event.workspace,
airlock_event.release_request_id,
airlock_event.request_author,
airlock_event.org,
airlock_event.repo,
github_api,
)
except GitHubError as e:
raise NotificationError(f"Error creating GitHub issue: {e}")
def close_issue(airlock_event: AirlockEvent, github_api=None):
github_api = github_api or _get_github_api()
reason = airlock_event.describe_event()
try:
close_output_checking_issue(
airlock_event.release_request_id,
airlock_event.user,
reason,
airlock_event.org,
airlock_event.repo,
github_api,
)
except GitHubError as e:
raise NotificationError(f"Error closing GitHub issue: {e}")
def update_issue(airlock_event: AirlockEvent, github_api=None, notify_slack=False):
github_api = github_api or _get_github_api()
updates = airlock_event.describe_updates_as_str()
try:
update_output_checking_issue(
airlock_event.release_request_id,
airlock_event.workspace.name,
updates,
airlock_event.org,
airlock_event.repo,
github_api,
notify_slack,
airlock_event.request_author,
label=airlock_event.event_type.status_label(),
)
except GitHubError as e:
raise NotificationError(f"Error creating GitHub issue comment: {e}")
def update_issue_and_slack(airlock_event, github_api=None):
update_issue(airlock_event, github_api, notify_slack=True)
def email_author(airlock_event: AirlockEvent):
match airlock_event.event_type:
case EventType.REQUEST_APPROVED:
send_request_approved_email(airlock_event)
case EventType.REQUEST_RELEASED:
send_request_released_email(airlock_event)
case EventType.REQUEST_REJECTED:
send_request_rejected_email(airlock_event)
case EventType.REQUEST_RETURNED:
send_request_returned_email(airlock_event)
case _: # pragma: no cover
assert False
EVENT_NOTIFICATIONS = {
EventType.REQUEST_SUBMITTED: [create_issue],
EventType.REQUEST_WITHDRAWN: [close_issue],
EventType.REQUEST_APPROVED: [email_author, update_issue_and_slack],
EventType.REQUEST_RELEASED: [email_author, close_issue],
EventType.REQUEST_REJECTED: [email_author, close_issue],
EventType.REQUEST_RETURNED: [email_author, update_issue_and_slack],
EventType.REQUEST_RESUBMITTED: [update_issue_and_slack],
EventType.REQUEST_PARTIALLY_REVIEWED: [update_issue_and_slack],
EventType.REQUEST_REVIEWED: [update_issue_and_slack],
}
@api_view(["POST"])
@authentication_classes([SessionAuthentication])
def airlock_event_view(request):
token = request.headers.get("Authorization")
# do token authentication
get_backend_from_token(token)
try:
airlock_event = AirlockEvent.from_payload(request.data)
except NotificationError as err:
errors = [str(err)]
else:
errors = handle_notifications(airlock_event)
if errors:
return Response({"status": "error", "message": "; ".join(errors)}, status=201)
return Response({"status": "ok"}, status=201)
def handle_notifications(airlock_event: AirlockEvent):
"""
Try each notify action in turn, catch any exceptions, and return
them as a list so that we can report them. This means that an
unexpected exception in one notification action won't prevent others
being tried, e.g. if we get a Github error updating an issue, we'll still
send a notification to slack.
"""
errors = []
for notify_fn in EVENT_NOTIFICATIONS[airlock_event.event_type]:
try:
notify_fn(airlock_event)
except Exception as err:
errors.append(str(err))
return errors