forked from ietf-tools/datatracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathviews_rpc.py
More file actions
578 lines (519 loc) · 21.1 KB
/
views_rpc.py
File metadata and controls
578 lines (519 loc) · 21.1 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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
# Copyright The IETF Trust 2023-2026, All Rights Reserved
import os
import shutil
from pathlib import Path
from tempfile import TemporaryDirectory
from django.conf import settings
from django.db import IntegrityError
from drf_spectacular.utils import OpenApiParameter
from rest_framework import mixins, parsers, serializers, viewsets, status
from rest_framework.decorators import action
from rest_framework.exceptions import APIException
from rest_framework.views import APIView
from rest_framework.response import Response
from django.db.models import CharField as ModelCharField, OuterRef, Subquery, Q
from django.db.models.functions import Coalesce
from django.http import Http404
from drf_spectacular.utils import extend_schema_view, extend_schema
from rest_framework import generics
from rest_framework.fields import CharField as DrfCharField
from rest_framework.filters import SearchFilter
from rest_framework.pagination import LimitOffsetPagination
from ietf.api.serializers_rpc import (
PersonSerializer,
FullDraftSerializer,
DraftSerializer,
SubmittedToQueueSerializer,
OriginalStreamSerializer,
ReferenceSerializer,
EmailPersonSerializer,
RfcWithAuthorsSerializer,
DraftWithAuthorsSerializer,
NotificationAckSerializer,
RfcPubSerializer,
RfcFileSerializer,
EditableRfcSerializer,
)
from ietf.doc.models import Document, DocHistory, RfcAuthor, DocEvent
from ietf.doc.serializers import RfcAuthorSerializer
from ietf.doc.storage_utils import remove_from_storage, store_file, exists_in_storage
from ietf.doc.tasks import (
signal_update_rfc_metadata_task,
rebuild_reference_relations_task,
trigger_red_precomputer_task,
update_rfc_searchindex_task,
)
from ietf.person.models import Email, Person
from ietf.sync.rfcindex import mark_rfcindex_as_dirty
class Conflict(APIException):
status_code = status.HTTP_409_CONFLICT
default_detail = "Conflict."
default_code = "conflict"
@extend_schema_view(
retrieve=extend_schema(
operation_id="get_person_by_id",
summary="Find person by ID",
description="Returns a single person",
parameters=[
OpenApiParameter(
name="person_id",
type=int,
location="path",
description="Person ID identifying this person.",
),
],
),
)
class PersonViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
queryset = Person.objects.all()
serializer_class = PersonSerializer
api_key_endpoint = "ietf.api.views_rpc"
lookup_url_kwarg = "person_id"
@extend_schema(
operation_id="get_persons",
summary="Get a batch of persons",
description="Returns a list of persons matching requested ids. Omits any that are missing.",
request=list[int],
responses=PersonSerializer(many=True),
)
@action(detail=False, methods=["post"])
def batch(self, request):
"""Get a batch of rpc person names"""
pks = request.data
return Response(
self.get_serializer(Person.objects.filter(pk__in=pks), many=True).data
)
@extend_schema(
operation_id="persons_by_email",
summary="Get a batch of persons by email addresses",
description=(
"Returns a list of persons matching requested ids. "
"Omits any that are missing."
),
request=list[str],
responses=EmailPersonSerializer(many=True),
)
@action(detail=False, methods=["post"], serializer_class=EmailPersonSerializer)
def batch_by_email(self, request):
emails = Email.objects.filter(address__in=request.data, person__isnull=False)
serializer = self.get_serializer(emails, many=True)
return Response(serializer.data)
class SubjectPersonView(APIView):
api_key_endpoint = "ietf.api.views_rpc"
@extend_schema(
operation_id="get_subject_person_by_id",
summary="Find person for OIDC subject by ID",
description="Returns a single person",
responses=PersonSerializer,
parameters=[
OpenApiParameter(
name="subject_id",
type=str,
description="subject ID of person to return",
location="path",
),
],
)
def get(self, request, subject_id: str):
try:
user_id = int(subject_id)
except ValueError:
raise serializers.ValidationError(
{"subject_id": "This field must be an integer value."}
)
person = Person.objects.filter(user__pk=user_id).first()
if person:
return Response(PersonSerializer(person).data)
raise Http404
class RpcLimitOffsetPagination(LimitOffsetPagination):
default_limit = 10
max_limit = 100
class SingleTermSearchFilter(SearchFilter):
"""SearchFilter backend that does not split terms
The default SearchFilter treats comma or whitespace-separated terms as individual
search terms. This backend instead searches for the exact term.
"""
def get_search_terms(self, request):
value = request.query_params.get(self.search_param, "")
field = DrfCharField(trim_whitespace=False, allow_blank=True)
cleaned_value = field.run_validation(value)
return [cleaned_value]
@extend_schema_view(
get=extend_schema(
operation_id="search_person",
description="Get a list of persons, matching by partial name or email",
),
)
class RpcPersonSearch(generics.ListAPIView):
# n.b. the OpenAPI schema for this can be generated by running
# ietf/manage.py spectacular --file spectacular.yaml
# and extracting / touching up the rpc_person_search_list operation
api_key_endpoint = "ietf.api.views_rpc"
queryset = Person.objects.all()
serializer_class = PersonSerializer
pagination_class = RpcLimitOffsetPagination
# Searchable on all name-like fields or email addresses
filter_backends = [SingleTermSearchFilter]
search_fields = ["name", "plain", "email__address"]
@extend_schema_view(
retrieve=extend_schema(
operation_id="get_draft_by_id",
summary="Get a draft",
description="Returns the draft for the requested ID",
parameters=[
OpenApiParameter(
name="doc_id",
type=int,
location="path",
description="Doc ID identifying this draft.",
),
],
),
submitted_to_rpc=extend_schema(
operation_id="submitted_to_rpc",
summary="List documents ready to enter the RFC Editor Queue",
description="List documents ready to enter the RFC Editor Queue",
responses=SubmittedToQueueSerializer(many=True),
),
)
class DraftViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
queryset = Document.objects.filter(type_id="draft")
serializer_class = FullDraftSerializer
api_key_endpoint = "ietf.api.views_rpc"
lookup_url_kwarg = "doc_id"
@action(detail=False, serializer_class=SubmittedToQueueSerializer)
def submitted_to_rpc(self, request):
"""Return documents in datatracker that have been submitted to the RPC but are not yet in the queue
Those queries overreturn - there may be things, particularly not from the IETF stream that are already in the queue.
"""
ietf_docs = Q(states__type_id="draft-iesg", states__slug__in=["ann"])
irtf_iab_ise_editorial_docs = Q(
states__type_id__in=[
"draft-stream-iab",
"draft-stream-irtf",
"draft-stream-ise",
"draft-stream-editorial",
],
states__slug__in=["rfc-edit"],
)
docs = (
self.get_queryset()
.filter(type_id="draft")
.filter(ietf_docs | irtf_iab_ise_editorial_docs)
)
serializer = self.get_serializer(docs, many=True)
return Response(serializer.data)
@extend_schema(
operation_id="get_draft_references",
summary="Get normative references to I-Ds",
description=(
"Returns the id and name of each normatively "
"referenced Internet-Draft for the given docId"
),
parameters=[
OpenApiParameter(
name="doc_id",
type=int,
location="path",
description="Doc ID identifying this draft.",
),
],
responses=ReferenceSerializer(many=True),
)
@action(detail=True, serializer_class=ReferenceSerializer)
def references(self, request, doc_id=None):
doc = self.get_object()
serializer = self.get_serializer(
[
reference
for reference in doc.related_that_doc("refnorm")
if reference.type_id == "draft"
],
many=True,
)
return Response(serializer.data)
@extend_schema(
operation_id="get_draft_authors",
summary="Gather authors of the drafts with the given names",
description="returns a list mapping draft names to objects describing authors",
request=list[str],
responses=DraftWithAuthorsSerializer(many=True),
)
@action(detail=False, methods=["post"], serializer_class=DraftWithAuthorsSerializer)
def bulk_authors(self, request):
drafts = self.get_queryset().filter(name__in=request.data)
serializer = self.get_serializer(drafts, many=True)
return Response(serializer.data)
@extend_schema_view(
rfc_original_stream=extend_schema(
operation_id="get_rfc_original_streams",
summary="Get the streams RFCs were originally published into",
description="returns a list of dicts associating an RFC with its originally published stream",
responses=OriginalStreamSerializer(many=True),
)
)
class RfcViewSet(mixins.UpdateModelMixin, viewsets.GenericViewSet):
queryset = Document.objects.filter(type_id="rfc")
api_key_endpoint = "ietf.api.views_rpc"
lookup_field = "rfc_number"
serializer_class = EditableRfcSerializer
def perform_update(self, serializer):
DocEvent.objects.create(
doc=serializer.instance,
rev=serializer.instance.rev,
by=Person.objects.get(name="(System)"),
type="sync_from_rfc_editor",
desc="Metadata update from RFC Editor",
)
super().perform_update(serializer)
@action(detail=False, serializer_class=OriginalStreamSerializer)
def rfc_original_stream(self, request):
rfcs = self.get_queryset().annotate(
orig_stream_id=Coalesce(
Subquery(
DocHistory.objects.filter(doc=OuterRef("pk"))
.exclude(stream__isnull=True)
.order_by("time")
.values_list("stream_id", flat=True)[:1]
),
"stream_id",
output_field=ModelCharField(),
),
)
serializer = self.get_serializer(rfcs, many=True)
return Response(serializer.data)
@extend_schema(
operation_id="get_rfc_authors",
summary="Gather authors of the RFCs with the given numbers",
description="returns a list mapping rfc numbers to objects describing authors",
request=list[int],
responses=RfcWithAuthorsSerializer(many=True),
)
@action(detail=False, methods=["post"], serializer_class=RfcWithAuthorsSerializer)
def bulk_authors(self, request):
rfcs = self.get_queryset().filter(rfc_number__in=request.data)
serializer = self.get_serializer(rfcs, many=True)
return Response(serializer.data)
class DraftsByNamesView(APIView):
api_key_endpoint = "ietf.api.views_rpc"
@extend_schema(
operation_id="get_drafts_by_names",
summary="Get a batch of drafts by draft names",
description="returns a list of drafts with matching names",
request=list[str],
responses=DraftSerializer(many=True),
)
def post(self, request):
names = request.data
docs = Document.objects.filter(type_id="draft", name__in=names)
return Response(DraftSerializer(docs, many=True).data)
class RfcAuthorViewSet(viewsets.ReadOnlyModelViewSet):
"""ViewSet for RfcAuthor model
Router needs to provide rfc_number as a kwarg
"""
api_key_endpoint = "ietf.api.views_rpc"
queryset = RfcAuthor.objects.all()
serializer_class = RfcAuthorSerializer
lookup_url_kwarg = "author_id"
rfc_number_param = "rfc_number"
def get_queryset(self):
return (
super()
.get_queryset()
.filter(
document__type_id="rfc",
document__rfc_number=self.kwargs[self.rfc_number_param],
)
)
class DestinationHelperMixin:
def fs_destination(self, filename: str | Path) -> Path:
"""Destination for an uploaded RFC file in the filesystem
Strips any path components in filename and returns an absolute Path.
"""
rfc_path = Path(settings.RFC_PATH)
filename = Path(filename) # could potentially have directory components
extension = "".join(filename.suffixes)
if extension == ".notprepped.xml":
return rfc_path / "prerelease" / filename.name
return rfc_path / filename.name
def blob_destination(self, filename: str | Path) -> str:
"""Destination name for an uploaded RFC file in the blob store
Strips any path components in filename and returns an absolute Path.
"""
filename = Path(filename) # could potentially have directory components
extension = "".join(filename.suffixes)
if extension == ".notprepped.xml":
file_type = "notprepped"
elif extension[0] == ".":
file_type = extension[1:]
else:
raise serializers.ValidationError(
f"Extension does not begin with '.'!? ({filename})",
)
return f"{file_type}/{filename.name}"
class RfcPubNotificationView(DestinationHelperMixin, APIView):
api_key_endpoint = "ietf.api.views_rpc"
@extend_schema(
operation_id="notify_rfc_published",
summary="Notify datatracker of RFC publication",
request=RfcPubSerializer,
responses=NotificationAckSerializer,
)
def post(self, request):
serializer = RfcPubSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
# Check blobstore & filesystem for conflicts
rfc_number = serializer.validated_data["rfc_number"]
dest_stem = f"rfc{rfc_number}"
blob_kind = "rfc"
possible_rfc_files = [
self.fs_destination(dest_stem + ext)
for ext in RfcFileSerializer.allowed_extensions
]
possible_rfc_blobs = [
self.blob_destination(dest_stem + ext)
for ext in RfcFileSerializer.allowed_extensions
]
for possible_existing_file in possible_rfc_files:
if possible_existing_file.exists():
raise Conflict(
"File(s) already exist for this RFC",
code="files-exist",
)
for possible_existing_blob in possible_rfc_blobs:
if exists_in_storage(kind=blob_kind, name=possible_existing_blob):
raise Conflict(
"Blob(s) already exist for this RFC",
code="blobs-exist",
)
# Create RFC
try:
rfc = serializer.save()
except IntegrityError as err:
if Document.objects.filter(
rfc_number=serializer.validated_data["rfc_number"]
):
raise serializers.ValidationError(
"RFC with that number already exists",
code="rfc-number-in-use",
)
raise serializers.ValidationError(
f"Unable to publish: {err}",
code="unknown-integrity-error",
)
rfc_number_list = [rfc.rfc_number]
rfc_number_list.extend(
[d.rfc_number for d in rfc.related_that_doc(("updates", "obs"))]
)
rfc_number_list = sorted(set(rfc_number_list))
signal_update_rfc_metadata_task.delay(rfc_number_list=rfc_number_list)
return Response(NotificationAckSerializer().data)
class RfcPubFilesView(DestinationHelperMixin, APIView):
api_key_endpoint = "ietf.api.views_rpc"
parser_classes = [parsers.MultiPartParser]
@extend_schema(
operation_id="upload_rfc_files",
summary="Upload files for a published RFC",
request=RfcFileSerializer,
responses=NotificationAckSerializer,
)
def post(self, request):
serializer = RfcFileSerializer(
# many=True,
data=request.data,
)
serializer.is_valid(raise_exception=True)
rfc = serializer.validated_data["rfc"]
uploaded_files = serializer.validated_data["contents"] # list[UploadedFile]
replace = serializer.validated_data["replace"]
dest_stem = f"rfc{rfc.rfc_number}"
mtime = serializer.validated_data["mtime"]
mtimestamp = mtime.timestamp()
blob_kind = "rfc"
# List of files that might exist for an RFC
possible_rfc_files = [
self.fs_destination(dest_stem + ext)
for ext in serializer.allowed_extensions
]
possible_rfc_blobs = [
self.blob_destination(dest_stem + ext)
for ext in serializer.allowed_extensions
]
if not replace:
# this is the default: refuse to overwrite anything if not replacing
for possible_existing_file in possible_rfc_files:
if possible_existing_file.exists():
raise Conflict(
"File(s) already exist for this RFC",
code="files-exist",
)
for possible_existing_blob in possible_rfc_blobs:
if exists_in_storage(kind=blob_kind, name=possible_existing_blob):
raise Conflict(
"Blob(s) already exist for this RFC",
code="blobs-exist",
)
with TemporaryDirectory() as tempdir:
# Save files in a temporary directory. Use the uploaded filename
# extensions to identify files, but ignore the stems and generate our own.
files_to_move = [] # list[Path]
tmpfile_stem = Path(tempdir) / dest_stem
for upfile in uploaded_files:
uploaded_filename = Path(upfile.name) # name supplied by request
uploaded_ext = "".join(uploaded_filename.suffixes)
tempfile_path = tmpfile_stem.with_suffix(uploaded_ext)
with tempfile_path.open("wb") as dest:
for chunk in upfile.chunks():
dest.write(chunk)
os.utime(tempfile_path, (mtimestamp, mtimestamp))
files_to_move.append(tempfile_path)
# copy files to final location, removing any existing ones first if the
# remove flag was set
if replace:
for possible_existing_file in possible_rfc_files:
possible_existing_file.unlink(missing_ok=True)
for possible_existing_blob in possible_rfc_blobs:
remove_from_storage(
blob_kind, possible_existing_blob, warn_if_missing=False
)
for ftm in files_to_move:
with ftm.open("rb") as f:
store_file(
kind=blob_kind,
name=self.blob_destination(ftm),
file=f,
doc_name=rfc.name,
doc_rev=rfc.rev, # expect blank, but match whatever it is
mtime=mtime,
)
destination = self.fs_destination(ftm)
if (
settings.SERVER_MODE != "production"
and not destination.parent.exists()
):
destination.parent.mkdir()
shutil.move(ftm, destination)
# Trigger red precomputer
needs_updating = [rfc.rfc_number]
for rel in rfc.relateddocument_set.filter(
relationship_id__in=["obs", "updates"]
):
needs_updating.append(rel.target.rfc_number)
trigger_red_precomputer_task.delay(rfc_number_list=sorted(needs_updating))
# Trigger search index update
update_rfc_searchindex_task.delay(rfc.rfc_number)
# Trigger reference relation srebuild
rebuild_reference_relations_task.delay(doc_names=[rfc.name])
return Response(NotificationAckSerializer().data)
class RfcIndexView(APIView):
api_key_endpoint = "ietf.api.views_rpc"
@extend_schema(
operation_id="refresh_rfc_index",
summary="Refresh rfc-index files",
description="Requests creation of various index files.",
responses={202: None},
request=None,
)
def post(self, request):
mark_rfcindex_as_dirty()
return Response(status=202)