entries.py 38.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#
# Copyright The NOMAD Authors.
#
# This file is part of NOMAD. See https://nomad-lab.eu for further info.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

19
20
from typing import Optional, Union, Dict, Iterator, Any, List, Set, IO, cast
from fastapi import APIRouter, Depends, Path, status, HTTPException, Request, Query as QueryParameter
21
22
23
24
25
from fastapi.responses import StreamingResponse
import os.path
import io
import json
import orjson
26
27
28
import magic
import gzip
import lzma
29
30
31
32
33
34

from nomad import search, files, config, utils
from nomad.utils import strip
from nomad.archive import (
    query_archive, ArchiveQueryError, compute_required_with_referenced,
    read_partial_archives_from_mongo, filter_archive)
35
36
37
38

from .auth import get_optional_user
from ..utils import create_streamed_zipfile, File, create_responses
from ..models import (
David Sikter's avatar
David Sikter committed
39
    EntryPagination, WithQuery, MetadataRequired, EntriesMetadataResponse, EntriesMetadata,
40
    EntryMetadataResponse, query_parameters, metadata_required_parameters, Files, Query,
David Sikter's avatar
David Sikter committed
41
    entry_pagination_parameters, files_parameters, User, Owner, HTTPExceptionModel, EntriesRaw,
42
43
    EntriesRawResponse, EntriesRawDownload, EntryRaw, EntryRawFile, EntryRawResponse,
    EntriesArchiveDownload, EntryArchiveResponse, EntriesArchive, EntriesArchiveResponse,
44
    ArchiveRequired, EntryArchiveRequest)
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66


router = APIRouter()
default_tag = 'entries'
metadata_tag = 'entries/metadata'
raw_tag = 'entries/raw'
archive_tag = 'entries/archive'

logger = utils.get_logger(__name__)


_bad_owner_response = status.HTTP_401_UNAUTHORIZED, {
    'model': HTTPExceptionModel,
    'description': strip('''
        Unauthorized. The given owner requires authorization,
        but no or bad authentication credentials are given.''')}

_bad_id_response = status.HTTP_404_NOT_FOUND, {
    'model': HTTPExceptionModel,
    'description': strip('''
        Entry not found. The given id does not match any entry.''')}

67
68
69
70
_bad_path_response = status.HTTP_404_NOT_FOUND, {
    'model': HTTPExceptionModel,
    'description': strip('File or directory not found.')}

71
72
73
74
75
76
77
_raw_download_response = 200, {
    'content': {'application/zip': {}},
    'description': strip('''
        A zip file with the requested raw files. The file is streamed.
        The content length is not known in advance.
    ''')}

78
79
80
81
82
83
84
85
_raw_download_file_response = 200, {
    'content': {'application/octet-stream': {}},
    'description': strip('''
        A byte stream with raw file contents. The content length is not known in advance.
        If the whole file is requested, the mime-type might be more specific, depending
        on the file contents.
    ''')}

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
_archive_download_response = 200, {
    'content': {'application/zip': {}},
    'description': strip('''
        A zip file with the requested archive files. The file is streamed.
        The content length is not known in advance.
    ''')}


_bad_archive_required_response = status.HTTP_400_BAD_REQUEST, {
    'model': HTTPExceptionModel,
    'description': strip('''
        The given required specification could not be understood.''')}


def perform_search(*args, **kwargs):
    try:
        return search.search(*args, **kwargs)
    except search.AuthenticationRequiredError as e:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(e))
    except search.ElasticSearchError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail='Elasticsearch could not process your query: %s' % str(e))


@router.post(
    '/query', tags=['entries/metadata'],
    summary='Search entries and retrieve their metadata',
    response_model=EntriesMetadataResponse,
    responses=create_responses(_bad_owner_response),
    response_model_exclude_unset=True,
    response_model_exclude_none=True)
async def post_entries_metadata_query(
119
        request: Request,
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
        data: EntriesMetadata,
        user: User = Depends(get_optional_user)):

    '''
    Executes a *query* and returns a *page* of the results with *required* result data
    as well as *statistics* and *aggregated* data.

    This is the basic search operation to retrieve metadata for entries that match
    certain search criteria (`query` and `owner`). All parameters (including `query`, `owner`)
    are optional. Look at the body schema or parameter documentation for more details.

    By default the *empty* search (that returns everything) is performed. Only a small
    page of the search results are returned at a time; use `pagination` in subsequent
    requests to retrive more data. Each entry has a lot of different *metadata*, use
    `required` to limit the data that is returned.

    The `statistics` and `aggregations` keys will further allow to return statistics
    and aggregated data over all search results.
    '''

140
    return perform_search(
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
        owner=data.owner,
        query=data.query,
        pagination=data.pagination,
        required=data.required,
        statistics=data.statistics,
        aggregations=data.aggregations,
        user_id=user.user_id if user is not None else None)


@router.get(
    '', tags=[metadata_tag],
    summary='Search entries and retrieve their metadata',
    response_model=EntriesMetadataResponse,
    responses=create_responses(_bad_owner_response),
    response_model_exclude_unset=True,
    response_model_exclude_none=True)
async def get_entries_metadata(
158
        request: Request,
159
        with_query: WithQuery = Depends(query_parameters),
David Sikter's avatar
David Sikter committed
160
        pagination: EntryPagination = Depends(entry_pagination_parameters),
161
162
163
164
165
166
167
168
169
170
171
172
173
174
        required: MetadataRequired = Depends(metadata_required_parameters),
        user: User = Depends(get_optional_user)):
    '''
    Executes a *query* and returns a *page* of the results with *required* result data.
    This is a version of `/entries/query`. Queries work a little different, because
    we cannot put complex queries into URL parameters.

    In addition to the `q` parameter (see parameter documentation for details), you can use all NOMAD
    search quantities as parameters, e.g. `?atoms=H&atoms=O`. Those quantities can be
    used with additional operators attached to their names, e.g. `?n_atoms__gte=3` for
    all entries with more than 3 atoms. Operators are `all`, `any`, `none`, `gte`,
    `gt`, `lt`, `lte`.
    '''

175
    res = perform_search(
176
177
178
        owner=with_query.owner, query=with_query.query,
        pagination=pagination, required=required,
        user_id=user.user_id if user is not None else None)
179
180
    res.pagination.populate_urls(request)
    return res
181
182
183


def _do_exaustive_search(owner: Owner, query: Query, include: List[str], user: User) -> Iterator[Dict[str, Any]]:
184
    page_after_value = None
185
186
187
    while True:
        response = perform_search(
            owner=owner, query=query,
188
            pagination=EntryPagination(size=100, page_after_value=page_after_value, order_by='upload_id'),
189
190
191
            required=MetadataRequired(include=include),
            user_id=user.user_id if user is not None else None)

192
        page_after_value = response.pagination.next_page_after_value
193
194
195
196

        for result in response.data:
            yield result

197
        if page_after_value is None or len(response.data) == 0:
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
            break


class _Uploads():
    '''
    A helper class that caches subsequent access to upload files the same upload.
    '''
    def __init__(self):
        self._upload_files = None

    def get_upload_files(self, upload_id: str) -> files.UploadFiles:
        if self._upload_files is not None and self._upload_files.upload_id != upload_id:
            self._upload_files.close()

        if self._upload_files is None or self._upload_files.upload_id != upload_id:
            self._upload_files = files.UploadFiles.get(
                upload_id, is_authorized=lambda *args, **kwargs: True)

        return self._upload_files

    def close(self):
        if self._upload_files is not None:
            self._upload_files.close()


def _create_entry_raw(entry_metadata: Dict[str, Any], uploads: _Uploads):
    calc_id = entry_metadata['calc_id']
    upload_id = entry_metadata['upload_id']
    mainfile = entry_metadata['mainfile']

    upload_files = uploads.get_upload_files(upload_id)
    mainfile_dir = os.path.dirname(mainfile)

    files = []
    for file_name, file_size in upload_files.raw_file_list(directory=mainfile_dir):
        path = os.path.join(mainfile_dir, file_name)
        files.append(EntryRawFile(path=path, size=file_size))

    return EntryRaw(calc_id=calc_id, upload_id=upload_id, mainfile=mainfile, files=files)


def _answer_entries_raw_request(
David Sikter's avatar
David Sikter committed
240
        owner: Owner, query: Query, pagination: EntryPagination, user: User):
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

    if owner == Owner.all_:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=strip('''
            The owner=all is not allowed for this operation as it will search for entries
            that you might now be allowed to access.
            '''))

    search_response = perform_search(
        owner=owner, query=query,
        pagination=pagination,
        required=MetadataRequired(include=['calc_id', 'upload_id', 'mainfile']),
        user_id=user.user_id if user is not None else None)

    uploads = _Uploads()
    try:
        response_data = [
            _create_entry_raw(entry_metadata, uploads)
            for entry_metadata in search_response.data]
    finally:
        uploads.close()

    return EntriesRawResponse(
        owner=search_response.owner,
        query=search_response.query,
        pagination=search_response.pagination,
        data=response_data)


def _answer_entries_raw_download_request(owner: Owner, query: Query, files: Files, user: User):
    if owner == Owner.all_:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=strip('''
            The owner=all is not allowed for this operation as it will search for entries
            that you might now be allowed to access.
            '''))

    response = perform_search(
        owner=owner, query=query,
278
        pagination=EntryPagination(page_size=0),
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
        required=MetadataRequired(include=[]),
        user_id=user.user_id if user is not None else None)

    if response.pagination.total > config.max_entry_download:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail='The limit of maximum number of entries in a single download (%d) has been exeeded (%d).' % (
                config.max_entry_download, response.pagination.total))

    uploads = _Uploads()
    files_params = Files() if files is None else files
    manifest = []
    search_includes = ['calc_id', 'upload_id', 'mainfile']
    streamed_paths: Set[str] = set()

    try:
        # a generator of File objects to create the streamed zip from
        def raw_file_generator():
            # go through all entries that match the query
            for entry_metadata in _do_exaustive_search(owner, query, include=search_includes, user=user):
                upload_id = entry_metadata['upload_id']
                mainfile = entry_metadata['mainfile']

                upload_files = uploads.get_upload_files(upload_id)
                mainfile_dir = os.path.dirname(mainfile)

                # go through all files that belong to this entry
                all_filtered = True
                files = upload_files.raw_file_list(directory=mainfile_dir)
                for file_name, file_size in files:
                    path = os.path.join(mainfile_dir, file_name)

                    # apply the filter
                    if files_params.re_pattern is not None and not files_params.re_pattern.search(path):
                        continue
                    all_filtered = False

                    # add upload_id to path used in streamed zip
                    streamed_path = os.path.join(upload_id, path)

                    # check if already streamed
                    if streamed_path in streamed_paths:
                        continue
                    streamed_paths.add(streamed_path)

                    # yield the file
                    with upload_files.raw_file(path, 'rb') as f:
                        yield File(path=streamed_path, f=f, size=file_size)

                if not all_filtered or len(files) == 0:
                    entry_metadata['mainfile'] = os.path.join(upload_id, mainfile)
                    manifest.append(entry_metadata)

            # add the manifest at the end
            manifest_content = json.dumps(manifest).encode()
            yield File(path='manifest.json', f=io.BytesIO(manifest_content), size=len(manifest_content))

        # create the streaming response with zip file contents
        content = create_streamed_zipfile(raw_file_generator(), compress=files_params.compress)
        return StreamingResponse(content, media_type='application/zip')
339
340
    except Exception as e:
        logger.error('exception while streaming download', exc_info=e)
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
    finally:
        uploads.close()


_entries_raw_query_docstring = strip('''
    Will perform a search and return a *page* of raw file metadata for entries fulfilling
    the query. This allows you to get a complete list of all rawfiles with their full
    path in their respective upload and their sizes. The first returned files for each
    entry, is their respective *mainfile*.

    Each entry on NOMAD represents a set of raw files. These are the input and output
    files (as well as additional auxiliary files) in their original form, i.e. as
    provided by the uploader. More specifically, an entry represents a code-run identified
    by a certain *mainfile*. This is usually the main output file of the code. All other
    files in the same directory are considered the entries *auxiliary* no matter their role
    or if they were actually parsed by NOMAD.

    This operation supports the usual `owner`, `query`, and `pagination` parameters.
    ''')


@router.post(
    '/raw/query',
    tags=[raw_tag],
    summary='Search entries and get their raw files metadata',
    description=_entries_raw_query_docstring,
    response_model=EntriesRawResponse,
    responses=create_responses(_bad_owner_response),
    response_model_exclude_unset=True,
    response_model_exclude_none=True)
371
372
async def post_entries_raw_query(
        request: Request, data: EntriesRaw, user: User = Depends(get_optional_user)):
373

374
    return _answer_entries_raw_request(
375
376
377
378
379
380
381
382
383
384
385
386
387
        owner=data.owner, query=data.query, pagination=data.pagination, user=user)


@router.get(
    '/raw',
    tags=[raw_tag],
    summary='Search entries and get raw their raw files metadata',
    description=_entries_raw_query_docstring,
    response_model=EntriesRawResponse,
    response_model_exclude_unset=True,
    response_model_exclude_none=True,
    responses=create_responses(_bad_owner_response))
async def get_entries_raw(
388
        request: Request,
389
        with_query: WithQuery = Depends(query_parameters),
David Sikter's avatar
David Sikter committed
390
        pagination: EntryPagination = Depends(entry_pagination_parameters),
391
392
        user: User = Depends(get_optional_user)):

393
    res = _answer_entries_raw_request(
394
        owner=with_query.owner, query=with_query.query, pagination=pagination, user=user)
395
396
    res.pagination.populate_urls(request)
    return res
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


_entries_raw_download_query_docstring = strip('''
    This operation will perform a search and stream a .zip file with raw input and output
    files of the found entries.

    Each entry on NOMAD represents a set of raw files. These are the input and output
    files (as well as additional auxiliary files) in their original form, i.e. as
    provided by the uploader. More specifically, an entry represents a code-run identified
    by a certain *mainfile*. This is usually the main output file of the code. All other
    files in the same directory are considered the entries *auxiliary* no matter their role
    or if they were actually parsed by NOMAD.

    After performing a search (that uses the same parameters as in all search operations),
    NOMAD will iterate through all results and create a .zip-file with all the entries'
    main and auxiliary files. The files will be organized in the same directory structure
    that they were uploaded in. The respective upload root directories are further prefixed
    with the `upload_id` of the respective uploads. The .zip-file will further contain
    a `manifest.json` with `upload_id`, `calc_id`, and `mainfile` of each entry.
    ''')


@router.post(
    '/raw/download/query',
    tags=[raw_tag],
    summary='Search entries and download their raw files',
    description=_entries_raw_download_query_docstring,
    response_class=StreamingResponse,
    responses=create_responses(_raw_download_response, _bad_owner_response))
async def post_entries_raw_download_query(
        data: EntriesRawDownload, user: User = Depends(get_optional_user)):

    return _answer_entries_raw_download_request(
        owner=data.owner, query=data.query, files=data.files, user=user)


@router.get(
    '/raw/download',
    tags=[raw_tag],
    summary='Search entries and download their raw files',
    description=_entries_raw_download_query_docstring,
    response_class=StreamingResponse,
    responses=create_responses(_raw_download_response, _bad_owner_response))
async def get_entries_raw_download(
        with_query: WithQuery = Depends(query_parameters),
        files: Files = Depends(files_parameters),
        user: User = Depends(get_optional_user)):

    return _answer_entries_raw_download_request(
        owner=with_query.owner, query=with_query.query, files=files, user=user)


def _read_archive(entry_metadata, uploads, required):
    calc_id = entry_metadata['calc_id']
    upload_id = entry_metadata['upload_id']
    upload_files = uploads.get_upload_files(upload_id)

    try:
        with upload_files.read_archive(calc_id) as archive:
            return {
                'calc_id': calc_id,
458
                'upload_id': upload_id,
459
460
461
462
463
464
465
466
                'parser_name': entry_metadata['parser_name'],
                'archive': query_archive(archive, {calc_id: required})[calc_id]
            }
    except ArchiveQueryError as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))


def _answer_entries_archive_request(
David Sikter's avatar
David Sikter committed
467
        owner: Owner, query: Query, pagination: EntryPagination, required: ArchiveRequired,
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
        user: User):

    if owner == Owner.all_:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=strip('''
            The owner=all is not allowed for this operation as it will search for entries
            that you might now be allowed to access.
            '''))

    if required is None:
        required = '*'

    try:
        required_with_references = compute_required_with_referenced(required)
    except KeyError as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=(
            'The required specification contains an unknown quantity or section: %s' % str(e)))

    search_response = perform_search(
        owner=owner, query=query,
        pagination=pagination,
        required=MetadataRequired(include=['calc_id', 'upload_id', 'parser_name']),
        user_id=user.user_id if user is not None else None)

    if required_with_references is not None:
        # We can produce all the required archive data from the partial archives stored
        # in mongodb.
        entry_ids = [entry['calc_id'] for entry in search_response.data]
        partial_archives = cast(dict, read_partial_archives_from_mongo(entry_ids, as_dict=True))

    uploads = _Uploads()
    response_data = {}
    for entry_metadata in search_response.data:
        calc_id, upload_id = entry_metadata['calc_id'], entry_metadata['upload_id']

        archive_data = None
        if required_with_references is not None:
            try:
                partial_archive = partial_archives[calc_id]
                archive_data = filter_archive(required, partial_archive, transform=lambda e: e)
            except KeyError:
                # the partial archive might not exist, e.g. due to processing problems
                pass
            except ArchiveQueryError as e:
                detail = 'The required specification could not be understood: %s' % str(e)
                raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=detail)

        if archive_data is None:
            try:
                archive_data = _read_archive(entry_metadata, uploads, required)['archive']
            except KeyError as e:
                logger.error('missing archive', exc_info=e, calc_id=calc_id)
                continue

        response_data[calc_id] = {
            'calc_id': calc_id,
            'upload_id': upload_id,
            'parser_name': entry_metadata['parser_name'],
            'archive': archive_data}

    uploads.close()

    return EntriesArchiveResponse(
        owner=search_response.owner,
        query=search_response.query,
        pagination=search_response.pagination,
533
        required=required,
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
        data=list(response_data.values()))


_entries_archive_docstring = strip('''
    This operation will perform a search with the given `query` and `owner` and return
    the a *page* of `required` archive data. Look at the body schema or parameter documentation
    for more details. The **GET** version of this operation will only allow to provide
    the full archives.
    ''')


@router.post(
    '/archive/query',
    tags=[archive_tag],
    summary='Search entries and access their archives',
    description=_entries_archive_docstring,
    response_model=EntriesArchiveResponse,
    response_model_exclude_unset=True,
    response_model_exclude_none=True,
    responses=create_responses(_bad_owner_response, _bad_archive_required_response))
async def post_entries_archive_query(
555
        request: Request, data: EntriesArchive, user: User = Depends(get_optional_user)):
556

557
    return _answer_entries_archive_request(
558
559
560
561
562
563
564
565
566
567
568
569
570
571
        owner=data.owner, query=data.query, pagination=data.pagination,
        required=data.required, user=user)


@router.get(
    '/archive',
    tags=[archive_tag],
    summary='Search entries and access their archives',
    description=_entries_archive_docstring,
    response_model=EntriesArchiveResponse,
    response_model_exclude_unset=True,
    response_model_exclude_none=True,
    responses=create_responses(_bad_owner_response, _bad_archive_required_response))
async def get_entries_archive_query(
572
        request: Request,
573
        with_query: WithQuery = Depends(query_parameters),
David Sikter's avatar
David Sikter committed
574
        pagination: EntryPagination = Depends(entry_pagination_parameters),
575
576
        user: User = Depends(get_optional_user)):

577
    res = _answer_entries_archive_request(
578
579
        owner=with_query.owner, query=with_query.query, pagination=pagination,
        required=None, user=user)
580
581
    res.pagination.populate_urls(request)
    return res
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596


def _answer_entries_archive_download_request(
        owner: Owner, query: Query, files: Files, user: User):

    if owner == Owner.all_:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=strip('''
            The owner=all is not allowed for this operation as it will search for entries
            that you might now be allowed to access.
            '''))

    files_params = Files() if files is None else files

    response = perform_search(
        owner=owner, query=query,
597
        pagination=EntryPagination(page_size=0),
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
        required=MetadataRequired(include=[]),
        user_id=user.user_id if user is not None else None)

    if response.pagination.total > config.max_entry_download:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=(
                'The limit of maximum number of entries in a single download (%d) has been '
                'exeeded (%d).' % (config.max_entry_download, response.pagination.total)))

    uploads = _Uploads()
    manifest = []
    search_includes = ['calc_id', 'upload_id', 'parser_name']

    # a generator of File objects to create the streamed zip from
    def file_generator():
        # go through all entries that match the query
        for entry_metadata in _do_exaustive_search(owner, query, include=search_includes, user=user):
            path = os.path.join(entry_metadata['upload_id'], '%s.json' % entry_metadata['calc_id'])
            try:
                archive_data = _read_archive(entry_metadata, uploads, '*')

                f = io.BytesIO(orjson.dumps(
                    archive_data, option=orjson.OPT_INDENT_2 | orjson.OPT_NON_STR_KEYS))

                yield File(path=path, f=f, size=f.getbuffer().nbytes)
            except KeyError as e:
                logger.error('missing archive', calc_id=entry_metadata['calc_id'], exc_info=e)

            entry_metadata['path'] = path
            manifest.append(entry_metadata)

        # add the manifest at the end
        manifest_content = json.dumps(manifest).encode()
        yield File(path='manifest.json', f=io.BytesIO(manifest_content), size=len(manifest_content))

    try:
        # create the streaming response with zip file contents
        content = create_streamed_zipfile(file_generator(), compress=files_params.compress)
        return StreamingResponse(content, media_type='application/zip')
    finally:
        uploads.close()


_entries_archive_download_docstring = strip('''
    This operation will perform a search with the given `query` and `owner` and stream
    a .zip-file with the full archive contents for all matching entries. This is not
    paginated. Look at the body schema or parameter documentation for more details.
    ''')


@router.post(
    '/archive/download/query',
    tags=[archive_tag],
    summary='Search entries and download their archives',
    description=_entries_archive_download_docstring,
    response_class=StreamingResponse,
    responses=create_responses(
        _archive_download_response, _bad_owner_response, _bad_archive_required_response))
async def post_entries_archive_download_query(
        data: EntriesArchiveDownload, user: User = Depends(get_optional_user)):

    return _answer_entries_archive_download_request(
        owner=data.owner, query=data.query, files=data.files, user=user)


@router.get(
    '/archive/download',
    tags=[archive_tag],
    summary='Search entries and download their archives',
    description=_entries_archive_download_docstring,
    response_class=StreamingResponse,
    responses=create_responses(
        _archive_download_response, _bad_owner_response, _bad_archive_required_response))
async def get_entries_archive_download(
        with_query: WithQuery = Depends(query_parameters),
        files: Files = Depends(files_parameters),
        user: User = Depends(get_optional_user)):

    return _answer_entries_archive_download_request(
        owner=with_query.owner, query=with_query.query, files=files, user=user)


@router.get(
    '/{entry_id}', tags=[metadata_tag],
    summary='Get the metadata of an entry by its id',
    response_model=EntryMetadataResponse,
    responses=create_responses(_bad_id_response),
    response_model_exclude_unset=True,
    response_model_exclude_none=True)
async def get_entry_metadata(
        entry_id: str = Path(..., description='The unique entry id of the entry to retrieve metadata from.'),
        required: MetadataRequired = Depends(metadata_required_parameters),
        user: User = Depends(get_optional_user)):
    '''
    Retrives the entry metadata for the given id.
    '''

    query = {'calc_id': entry_id}
    response = perform_search(owner=Owner.all_, query=query, required=required, user_id=user.user_id if user is not None else None)

    if response.pagination.total == 0:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail='The entry with the given id does not exist or is not visible to you.')

    return {
        'entry_id': entry_id,
        'required': required,
        'data': response.data[0]
    }


@router.get(
    '/{entry_id}/raw',
    tags=[raw_tag],
    summary='Get the raw files metadata for an entry by its id',
    response_model=EntryRawResponse,
    responses=create_responses(_bad_id_response),
    response_model_exclude_unset=True,
    response_model_exclude_none=True)
async def get_entry_raw(
        entry_id: str = Path(..., description='The unique entry id of the entry to retrieve raw data from.'),
        files: Files = Depends(files_parameters),
        user: User = Depends(get_optional_user)):
    '''
    Returns the file metadata for all input and output files (including auxiliary files)
    of the given `entry_id`. The first file will be the *mainfile*.
    '''
    query = dict(calc_id=entry_id)
    response = perform_search(
        owner=Owner.visible, query=query,
        required=MetadataRequired(include=['calc_id', 'upload_id', 'mainfile']),
        user_id=user.user_id if user is not None else None)

    if response.pagination.total == 0:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail='The entry with the given id does not exist or is not visible to you.')

    uploads = _Uploads()
    try:
        return EntryRawResponse(entry_id=entry_id, data=_create_entry_raw(response.data[0], uploads))
    finally:
        uploads.close()


@router.get(
    '/{entry_id}/raw/download',
    tags=[raw_tag],
    summary='Get the raw data of an entry by its id',
    response_class=StreamingResponse,
    responses=create_responses(_bad_id_response, _raw_download_response))
async def get_entry_raw_download(
        entry_id: str = Path(..., description='The unique entry id of the entry to retrieve raw data from.'),
        files: Files = Depends(files_parameters),
        user: User = Depends(get_optional_user)):
    '''
    Streams a .zip file with the raw files from the requested entry.
    '''
    query = dict(calc_id=entry_id)
    response = perform_search(
        owner=Owner.visible, query=query,
        required=MetadataRequired(include=['calc_id']),
        user_id=user.user_id if user is not None else None)

    if response.pagination.total == 0:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail='The entry with the given id does not exist or is not visible to you.')

769
    return _answer_entries_raw_download_request(owner=Owner.public, query=query, files=files, user=user)
770
771


772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
class FileContentIterator:
    '''
    An iterator implementation that provides the contents of an underlying file, based on
    offset and length.

    Arguments:
        f: the file-like
        offset: the offset
        length: the amount of bytes
    '''
    def __init__(self, f, offset, length):
        self.f = f
        self.offset = offset
        self.read_bytes = 0
        self.f.seek(self.offset)
        self.length = length

    def __iter__(self):
        self.f.seek(self.offset)
        self.read_bytes = 0

    def __next__(self):
        remaining = self.length - self.read_bytes
        if remaining > 0:
            content = self.f.read(remaining)
            content_length = len(content)
            self.read_bytes += content_length
            if content_length == 0:
                self.length = self.read_bytes
            return content
        else:
            raise StopIteration


@router.get(
    '/{entry_id}/raw/download/{path}',
    tags=[raw_tag],
    summary='Get the raw data of an entry by its id',
    response_class=StreamingResponse,
    responses=create_responses(_bad_id_response, _bad_path_response, _raw_download_file_response))
async def get_entry_raw_download_file(
        entry_id: str = Path(..., description='The unique entry id of the entry to retrieve raw data from.'),
        path: str = Path(..., description='A relative path to a file based on the directory of the entry\'s mainfile.'),
        offset: Optional[int] = QueryParameter(
            0, ge=0, description=strip('''
                Integer offset that marks the start of the contents to retrieve. Default
                is the start of the file.''')),
        length: Optional[int] = QueryParameter(
            -1, ge=0, description=strip('''
                The amounts of contents in bytes to stream. By default, the remainder of
                the file is streamed.''')),
        decompress: Optional[bool] = QueryParameter(
            False, description=strip('''
                Attempt to decompress the contents, if the file is .gz or .xz.''')),
        user: User = Depends(get_optional_user)):
    '''
    Streams the contents of an individual file from the requested entry.
    '''
    query = dict(calc_id=entry_id)
    response = perform_search(
        owner=Owner.visible, query=query,
        required=MetadataRequired(include=['calc_id', 'upload_id', 'mainfile']),
        user_id=user.user_id if user is not None else None)

    if response.pagination.total == 0:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail='The entry with the given id does not exist or is not visible to you.')

    entry_metadata = response.data[0]
    upload_id, mainfile = entry_metadata['upload_id'], entry_metadata['mainfile']
    # The user is allowed to access all files, because the entry is in the "visible" scope
    upload_files = files.UploadFiles.get(upload_id, is_authorized=lambda *args, **kwargs: True)

    entry_path = os.path.dirname(mainfile)
    path = os.path.join(entry_path, path)

    raw_file: Any = None
    try:
        raw_file = upload_files.raw_file(path, 'br')

        if decompress:
            if path.endswith('.gz'):
                raw_file = gzip.GzipFile(filename=path[:3], mode='rb', fileobj=raw_file)

            if path.endswith('.xz'):
                raw_file = lzma.open(filename=raw_file, mode='rb')

        # We only provide a specific mime-type, if the whole file is requested. Otherwise,
        # it is unlikely that the provided contents will match the overall file mime-type.
        mime_type = 'application/octet-stream'
        if offset == 0 and length < 0:
            buffer = raw_file.read(2048)
            raw_file.seek(0)
            mime_type = magic.from_buffer(buffer, mime=True)

        raw_file_content: Union[FileContentIterator, IO] = None
        if length > 0:
            raw_file_content = FileContentIterator(raw_file, offset, length)
        else:
            raw_file.seek(offset)
            raw_file_content = raw_file

        return StreamingResponse(raw_file_content, media_type=mime_type)

    except KeyError:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail='The requested file does not exist.')


883
884
885
886
887
888
889
def _answer_entry_archive_request(entry_id: str, required: ArchiveRequired, user: User):
    try:
        required_with_references = compute_required_with_referenced(required)
    except KeyError as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=(
            'The required specification contains an unknown quantity or section: %s' % str(e)))

890
891
892
893
894
895
896
897
898
899
900
    query = dict(calc_id=entry_id)
    response = perform_search(
        owner=Owner.visible, query=query,
        required=MetadataRequired(include=['calc_id', 'upload_id', 'parser_name']),
        user_id=user.user_id if user is not None else None)

    if response.pagination.total == 0:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail='The entry with the given id does not exist or is not visible to you.')

901
902
903
904
905
906
907
    entry_metadata = response.data[0]

    if required_with_references is not None:
        # We can produce all the required archive data from the partial archives stored
        # in mongodb.
        partial_archives = cast(dict, read_partial_archives_from_mongo([entry_id], as_dict=True))

908
909
    uploads = _Uploads()
    try:
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
        archive_data = None
        if required_with_references is not None:
            try:
                partial_archive = partial_archives[entry_id]
                archive_data = filter_archive(required, partial_archive, transform=lambda e: e)
            except KeyError:
                # the partial archive might not exist, e.g. due to processing problems
                pass
            except ArchiveQueryError as e:
                detail = 'The required specification could not be understood: %s' % str(e)
                raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=detail)

        if archive_data is None:
            try:
                archive_data = _read_archive(entry_metadata, uploads, required=required)['archive']
            except KeyError:
                raise HTTPException(
                    status_code=status.HTTP_404_NOT_FOUND,
                    detail='The entry with the given id does exist, but it has no archive.')
929
930
931

        return {
            'entry_id': entry_id,
932
933
934
935
936
937
938
            'required': required,
            'data': {
                'calc_id': entry_id,
                'upload_id': entry_metadata['upload_id'],
                'parser_name': entry_metadata['parser_name'],
                'archive': archive_data
            }}
939
940
    finally:
        uploads.close()
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976


@router.get(
    '/{entry_id}/archive',
    tags=[archive_tag],
    summary='Get the archive for an entry by its id',
    response_model=EntryArchiveResponse,
    response_model_exclude_unset=True,
    response_model_exclude_none=True,
    responses=create_responses(_bad_id_response))
async def get_entry_archive(
        entry_id: str = Path(..., description='The unique entry id of the entry to retrieve raw data from.'),
        user: User = Depends(get_optional_user)):
    '''
    Returns the full archive for the given `entry_id`.
    '''
    return _answer_entry_archive_request(entry_id=entry_id, required='*', user=user)


@router.post(
    '/{entry_id}/archive/query',
    tags=[archive_tag],
    summary='Get the archive for an entry by its id',
    response_model=EntryArchiveResponse,
    response_model_exclude_unset=True,
    response_model_exclude_none=True,
    responses=create_responses(_bad_id_response, _bad_archive_required_response))
async def post_entry_archive_query(
        data: EntryArchiveRequest, user: User = Depends(get_optional_user),
        entry_id: str = Path(..., description='The unique entry id of the entry to retrieve raw data from.')):

    '''
    Returns a partial archive for the given `entry_id` based on the `required` specified
    in the body.
    '''
    return _answer_entry_archive_request(entry_id=entry_id, required=data.required, user=user)