-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathversion.py
More file actions
271 lines (230 loc) · 9.31 KB
/
version.py
File metadata and controls
271 lines (230 loc) · 9.31 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
from __future__ import annotations
import datetime
import logging
from typing import TypedDict
from dandischema.conf import get_instance_config
from dandischema.models import AccessType
from django.conf import settings
from django.contrib.postgres.indexes import HashIndex
from django.core.validators import RegexValidator
from django.db import models
from django.db.models.query_utils import Q
from django_extensions.db.models import TimeStampedModel
from dandiapi.api.asset_paths import get_root_paths
from dandiapi.api.models.metadata import PublishableMetadataMixin
from .dandiset import Dandiset
logger = logging.getLogger(__name__)
class VersionAssetValidationError(TypedDict):
field: str
message: str
path: str
class Version(PublishableMetadataMixin, TimeStampedModel):
VERSION_REGEX = r'(0\.\d{6}\.\d{4})|draft'
class Status(models.TextChoices):
PENDING = 'Pending'
VALIDATING = 'Validating'
VALID = 'Valid'
INVALID = 'Invalid'
PUBLISHING = 'Publishing'
PUBLISHED = 'Published'
dandiset = models.ForeignKey(Dandiset, related_name='versions', on_delete=models.CASCADE)
name = models.CharField(max_length=300)
metadata = models.JSONField(blank=True, default=dict)
version = models.CharField(
max_length=13,
validators=[RegexValidator(f'^{VERSION_REGEX}$')],
)
doi = models.CharField(max_length=64, null=True, default=None, blank=True) # noqa: DJ001
"""Track the validation status of this version, without considering assets"""
status = models.CharField(
max_length=10,
default=Status.PENDING,
choices=Status.choices,
)
validation_errors = models.JSONField(default=list, blank=True, null=True)
class Meta:
ordering = ['version']
unique_together = ['dandiset', 'version']
constraints = [
models.CheckConstraint(
name='version_metadata_has_schema_version',
condition=Q(metadata__schemaVersion__isnull=False),
)
]
indexes = [
HashIndex(fields=['metadata']),
HashIndex(fields=['name']),
]
@property
def asset_count(self):
return get_root_paths(self).aggregate(nfiles=models.Sum('aggregate_files'))['nfiles'] or 0
@property
def size(self):
return (
get_root_paths(self).aggregate(total_size=models.Sum('aggregate_size'))['total_size']
or 0
)
@property
def active_uploads(self):
return self.dandiset.uploads.count() if self.version == 'draft' else 0
@property
def publishable(self) -> bool:
if self.status != Version.Status.VALID:
return False
# Import here to avoid dependency cycle
from .asset import Asset
# Return False if any asset is not VALID
return not self.assets.exclude(status=Asset.Status.VALID).exists()
@property
def asset_validation_errors(self) -> list[VersionAssetValidationError]:
# Import here to avoid dependency cycle
from .asset import Asset
# We want to display "Pending" assets in the validation errors list,
# despite them not being stored explicitly as errors in the database.
# Grab a random sample of 50 pending or currently validating assets
# and place them first in the list.
pending_assets: models.QuerySet[Asset] = (
self.assets.filter(status__in=[Asset.Status.PENDING, Asset.Status.VALIDATING])
.annotate(
field=models.Value(''),
message=models.Value('asset is currently being validated, please wait.'),
)
.values('field', 'message', 'path')[:50]
)
# Next, get all INVALID assets. Each of these should have one or more
# validation errors stored in the database.
# For performance reasons, we truncate the list of INVALID assets such
# that we only display errors for the 50 assets with the most errors.
invalid_assets: models.QuerySet[Asset] = (
self.assets.filter(status=Asset.Status.INVALID)
.alias(
validation_error_count=models.Func(
'validation_errors',
function='jsonb_array_length',
output_field=models.IntegerField(),
)
)
.order_by('-validation_error_count')
.values('path', 'validation_errors')
)[:50]
return list(pending_assets) + [
{
'field': error['field'],
'message': error['message'],
'path': asset['path'],
}
for asset in invalid_assets
for error in asset['validation_errors']
]
@staticmethod
def datetime_to_version(time: datetime.datetime) -> str:
return time.strftime('0.%y%m%d.%H%M')
@classmethod
def next_published_version(cls, dandiset: Dandiset) -> str:
time = datetime.datetime.now(datetime.UTC)
# increment time until there are no collisions
while True:
version = cls.datetime_to_version(time)
collision = dandiset.versions.filter(version=version).exists()
if not collision:
break
time += datetime.timedelta(minutes=1)
return version
@classmethod
def citation(cls, metadata):
year = datetime.datetime.now(datetime.UTC).year
name = metadata['name'].rstrip('.')
url = f'https://doi.org/{metadata["doi"]}' if 'doi' in metadata else metadata['url']
version = metadata['version']
# If we can't find any contributors, use this citation format
citation = f'{name} ({year}). (Version {version}) [Data set]. DANDI Archive. {url}'
if 'contributor' in metadata and isinstance(metadata['contributor'], list):
cl = '; '.join(
[val['name'] for val in metadata['contributor'] if val.get('includeInCitation')]
)
if cl:
citation = (
f'{cl} ({year}) {name} (Version {version}) [Data set]. DANDI Archive. {url}'
)
return citation
@classmethod
def strip_metadata(cls, metadata):
"""Strip away computed fields from a metadata dict."""
computed_fields = [
'name',
'identifier',
'version',
'id',
'url',
'assetsSummary',
'citation',
'doi',
'dateCreated',
'datePublished',
'publishedBy',
'manifestLocation',
]
stripped = {key: metadata[key] for key in metadata if key not in computed_fields}
# Strip the status and schemaKey fields, as modifying them is not supported
if (
'access' in stripped
and isinstance(stripped['access'], list)
and len(stripped['access'])
and isinstance(stripped['access'][0], dict)
):
stripped['access'][0].pop('schemaKey', None)
stripped['access'][0].pop('status', None)
return stripped
def _populate_access_metadata(self):
default_access = [{}]
access = self.metadata.get('access', default_access)
# Ensure access is a non-empty list
if not (isinstance(access, list) and access):
access = default_access
# Ensure that every item in access is a dict
access = [x for x in access if isinstance(x, dict)] or default_access
# Set first access item
access[0] = {
**access[0],
'schemaKey': 'AccessRequirements',
'status': AccessType.EmbargoedAccess.value
if self.dandiset.embargoed
else AccessType.OpenAccess.value,
}
return access
def _populate_metadata(self):
from dandiapi.api.manifests import manifest_location
schema_config = get_instance_config()
metadata = {
**self.metadata,
'@context': (
'https://raw.githubusercontent.com/dandi/schema/master/releases/'
f'{self.metadata["schemaVersion"]}/context.json'
),
'manifestLocation': manifest_location(self),
'name': self.name,
'identifier': (f'{schema_config.instance_name}:{self.dandiset.identifier}'),
'version': self.version,
'id': (f'{schema_config.instance_name}:{self.dandiset.identifier}/{self.version}'),
'repository': settings.DANDI_WEB_APP_URL,
'url': (
f'{settings.DANDI_WEB_APP_URL}/dandiset/{self.dandiset.identifier}/{self.version}'
),
'dateCreated': self.dandiset.created.isoformat(),
'access': self._populate_access_metadata(),
}
if 'assetsSummary' not in metadata:
metadata['assetsSummary'] = {
'schemaKey': 'AssetsSummary',
'numberOfBytes': 0,
'numberOfFiles': 0,
}
if self.doi:
metadata['doi'] = self.doi
metadata['citation'] = self.citation(metadata)
return metadata
def save(self, *args, **kwargs):
self.metadata = self._populate_metadata()
super().save(*args, **kwargs)
def __str__(self) -> str:
return f'{self.dandiset.identifier}/{self.version}'