-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathapi.py
More file actions
2290 lines (1973 loc) · 90.5 KB
/
api.py
File metadata and controls
2290 lines (1973 loc) · 90.5 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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
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
769
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
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
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
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Publishing API (warning: UNSTABLE, in progress API)
Please look at the models.py file for more information about the kinds of data
are stored in this app.
"""
from __future__ import annotations
from contextlib import nullcontext
from dataclasses import dataclass
from datetime import datetime, timezone
from enum import Enum
from typing import ContextManager, Optional, TypeVar
from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db.models import F, Prefetch, Q, QuerySet
from django.db.transaction import atomic
from openedx_django_lib.fields import create_hash_digest
from .contextmanagers import DraftChangeLogContext
from .models import (
Container,
ContainerVersion,
Draft,
DraftChangeLog,
DraftChangeLogRecord,
DraftSideEffect,
EntityList,
EntityListRow,
LearningPackage,
PublishableContentModelRegistry,
PublishableEntity,
PublishableEntityMixin,
PublishableEntityVersion,
PublishableEntityVersionDependency,
PublishableEntityVersionMixin,
PublishLog,
PublishLogRecord,
PublishSideEffect,
)
from .models.publish_log import Published
# A few of the APIs in this file are generic and can be used for Containers in
# general, or e.g. Units (subclass of Container) in particular. These type
# variables are used to provide correct typing for those generic API methods.
ContainerModel = TypeVar('ContainerModel', bound=Container)
ContainerVersionModel = TypeVar('ContainerVersionModel', bound=ContainerVersion)
# The public API that will be re-exported by openedx_content.api
# is listed in the __all__ entries below. Internal helper functions that are
# private to this module should start with an underscore. If a function does not
# start with an underscore AND it is not in __all__, that function is considered
# to be callable only by other apps in the authoring package.
__all__ = [
"get_learning_package",
"get_learning_package_by_key",
"create_learning_package",
"update_learning_package",
"learning_package_exists",
"create_publishable_entity",
"create_publishable_entity_version",
"get_publishable_entity",
"get_publishable_entity_by_key",
"get_publishable_entities",
"get_last_publish",
"get_all_drafts",
"get_entities_with_unpublished_changes",
"get_entities_with_unpublished_deletes",
"publish_all_drafts",
"publish_from_drafts",
"get_draft_version",
"get_published_version",
"get_entity_draft_history",
"get_entity_publish_history",
"get_entity_publish_history_entries",
"get_entity_version_contributors",
"set_draft_version",
"soft_delete_draft",
"reset_drafts_to_published",
"register_publishable_models",
"filter_publishable_entities",
# 🛑 UNSTABLE: All APIs related to containers are unstable until we've figured
# out our approach to dynamic content (randomized, A/B tests, etc.)
"create_container",
"create_container_version",
"create_next_container_version",
"get_container",
"get_container_by_key",
"get_containers",
"get_collection_containers",
"ChildrenEntitiesAction",
"ContainerEntityListEntry",
"ContainerEntityRow",
"get_entities_in_container",
"contains_unpublished_changes",
"get_containers_with_entity",
"get_container_children_count",
"bulk_draft_changes_for",
"get_container_children_entities_keys",
]
def get_learning_package(learning_package_id: int, /) -> LearningPackage:
"""
Get LearningPackage by ID.
"""
return LearningPackage.objects.get(id=learning_package_id)
def get_learning_package_by_key(key: str) -> LearningPackage:
"""
Get LearningPackage by key.
Can throw a NotFoundError
"""
return LearningPackage.objects.get(key=key)
def create_learning_package(
key: str, title: str, description: str = "", created: datetime | None = None
) -> LearningPackage:
"""
Create a new LearningPackage.
The ``key`` must be unique.
Errors that can be raised:
* django.core.exceptions.ValidationError
"""
if not created:
created = datetime.now(tz=timezone.utc)
package = LearningPackage(
key=key,
title=title,
description=description,
created=created,
updated=created,
)
package.full_clean()
package.save()
return package
def update_learning_package(
learning_package_id: int,
/,
key: str | None = None,
title: str | None = None,
description: str | None = None,
updated: datetime | None = None,
) -> LearningPackage:
"""
Make an update to LearningPackage metadata.
Note that LearningPackage itself is not versioned (only stuff inside it is).
"""
lp = LearningPackage.objects.get(id=learning_package_id)
# If no changes were requested, there's nothing to update, so just return
# the LearningPackage as-is.
if all(field is None for field in [key, title, description, updated]):
return lp
if key is not None:
lp.key = key
if title is not None:
lp.title = title
if description is not None:
lp.description = description
# updated is a bit different–we auto-generate it if it's not explicitly
# passed in.
if updated is None:
updated = datetime.now(tz=timezone.utc)
lp.updated = updated
lp.save()
return lp
def learning_package_exists(key: str) -> bool:
"""
Check whether a LearningPackage with a particular key exists.
"""
return LearningPackage.objects.filter(key=key).exists()
def create_publishable_entity(
learning_package_id: int,
/,
key: str,
created: datetime,
# User ID who created this
created_by: int | None,
*,
can_stand_alone: bool = True,
) -> PublishableEntity:
"""
Create a PublishableEntity.
You'd typically want to call this right before creating your own content
model that points to it.
"""
return PublishableEntity.objects.create(
learning_package_id=learning_package_id,
key=key,
created=created,
created_by_id=created_by,
can_stand_alone=can_stand_alone,
)
def create_publishable_entity_version(
entity_id: int,
/,
version_num: int,
title: str,
created: datetime,
created_by: int | None,
*,
dependencies: list[int] | None = None, # PublishableEntity IDs
) -> PublishableEntityVersion:
"""
Create a PublishableEntityVersion.
You'd typically want to call this right before creating your own content
version model that points to it.
"""
with atomic(savepoint=False):
version = PublishableEntityVersion.objects.create(
entity_id=entity_id,
version_num=version_num,
title=title,
created=created,
created_by_id=created_by,
)
if dependencies:
set_version_dependencies(version.id, dependencies)
set_draft_version(
entity_id,
version.id,
set_at=created,
set_by=created_by,
)
return version
def set_version_dependencies(
version_id: int, # PublishableEntityVersion.id,
/,
dependencies: list[int] # List of PublishableEntity.id
) -> None:
"""
Set the dependencies of a publishable entity version.
In general, callers should not modify dependencies after creation (i.e. use
the optional param in create_publishable_entity_version() instead of using
this function). **This function is not atomic.** If you're doing backfills,
you must wrap calls to this function with a transaction.atomic() call.
The idea behind dependencies is that a PublishableEntity's Versions may
be declared to reference unpinned PublishableEntities. Changes to those
referenced PublishableEntities still affect the draft or published state of
the referent PublishableEntity, even if the referent entity's version is not
incremented.
For example, we only create a new UnitVersion when there are changes to the
metadata of the Unit itself. So this would happen when the name of the Unit
is changed, or if a child Component is added, removed, or reordered. No new
UnitVersion is created when a child Component of that Unit is modified or
published. Yet we still consider a Unit to be affected when one of its child
Components is modified or published. Therefore, we say that the child
Components are dependencies of the UnitVersion.
Dependencies vs. Container Rows/Children
Dependencies overlap with the concept of container child rows, but the two
are not exactly the same. For instance:
* Dependencies have no sense of ordering.
* If a row is declared to be pinned to a specific version of a child, then
it is NOT a dependency. For example, if U1.v1 is declared to have a pinned
reference to ComponentVersion C1.v1, then future changes to C1 do not
affect U1.v1 because U1.v1 will just ignore those new ComponentVersions.
Guidelines:
1. Only declare one level of dependencies, e.g. immediate parent-child
relationships. The publishing app will calculate transitive dependencies
like "all descendants" based on this. This is important for saving space,
because the DAG of trasitive dependency relationships can explode out to
tens of thousands of nodes per version.
2. Declare dependencies from the bottom-up when possible. In other words, if
you're building an entire Subsection, set the Component dependencies for
the Units before you set the Unit dependencies for the Subsection. This
code will still work if you build from the top-down, but we'll end up
doing many redundant re-calculations, since every change to a lower layer
will cause recalculation to the higher levels that depend on it.
3. Do not create circular dependencies.
"""
PublishableEntityVersionDependency.objects.bulk_create(
[
PublishableEntityVersionDependency(
referring_version_id=version_id,
referenced_entity_id=dep_entity_id,
)
for dep_entity_id in set(dependencies) # dependencies have no ordering
],
)
def get_publishable_entity(publishable_entity_id: int, /) -> PublishableEntity:
return PublishableEntity.objects.get(id=publishable_entity_id)
def get_publishable_entity_by_key(learning_package_id, /, key) -> PublishableEntity:
return PublishableEntity.objects.get(
learning_package_id=learning_package_id,
key=key,
)
def get_last_publish(learning_package_id: int, /) -> PublishLog | None:
return PublishLog.objects \
.filter(learning_package_id=learning_package_id) \
.order_by('-id') \
.first()
def get_all_drafts(learning_package_id: int, /) -> QuerySet[Draft]:
return Draft.objects.filter(
entity__learning_package_id=learning_package_id,
version__isnull=False,
)
def get_publishable_entities(learning_package_id: int, /) -> QuerySet[PublishableEntity]:
"""
Get all entities in a learning package.
"""
return (
PublishableEntity.objects
.filter(learning_package_id=learning_package_id)
.select_related(
"draft__version",
"published__version",
)
)
def get_entities_with_unpublished_changes(
learning_package_id: int,
/,
include_deleted_drafts: bool = False
) -> QuerySet[PublishableEntity]:
"""
Fetch entities that have unpublished changes.
By default, this excludes soft-deleted drafts but can be included using
include_deleted_drafts option.
"""
entities_qs = (
PublishableEntity.objects
.filter(learning_package_id=learning_package_id)
.exclude(draft__version=F('published__version'))
)
if include_deleted_drafts:
# This means that we should also return PublishableEntities where the draft
# has been soft-deleted, but that deletion has not been published yet. Just
# excluding records where the Draft and Published versions don't match won't
# be enough here, because that will return soft-deletes that have already
# been published (since NULL != NULL in SQL).
#
# So we explicitly exclude already-published soft-deletes:
return entities_qs.exclude(
Q(draft__version__isnull=True) & Q(published__version__isnull=True)
)
# Simple case: exclude all entities that have been soft-deleted.
return entities_qs.exclude(draft__version__isnull=True)
def get_entities_with_unpublished_deletes(learning_package_id: int, /) -> QuerySet[PublishableEntity]:
"""
Something will become "deleted" if it has a null Draft version but a
not-null Published version. (If both are null, it means it's already been
deleted in a previous publish, or it was never published.)
"""
return PublishableEntity.objects \
.filter(
learning_package_id=learning_package_id,
draft__version__isnull=True,
).exclude(published__version__isnull=True)
def publish_all_drafts(
learning_package_id: int,
/,
message="",
published_at: datetime | None = None,
published_by: int | None = None
) -> PublishLog:
"""
Publish everything that is a Draft and is not already published.
"""
draft_qset = (
Draft.objects
.filter(entity__learning_package_id=learning_package_id)
.with_unpublished_changes()
)
return publish_from_drafts(
learning_package_id, draft_qset, message, published_at, published_by
)
def _get_dependencies_with_unpublished_changes(
draft_qset: QuerySet[Draft]
) -> list[QuerySet[Draft]]:
"""
Return all dependencies to publish as a list of Draft QuerySets.
This should only return the Drafts that have actual changes, not pure side-
effects. The side-effect calculations will happen separately.
"""
# First we have to do a full crawl of *all* dependencies, regardless of
# whether they have unpublished changes or not. This is because we might
# have a dependency-of-a-dependency that has changed somewhere down the
# line. Example: The draft_qset includes a Subsection. Even if the Unit
# versions are still the same, there might be a changed Component that needs
# to be published.
all_dependency_drafts = []
dependency_drafts = Draft.objects.filter(
entity__affects__in=draft_qset.values_list("version_id", flat=True)
).distinct()
while dependency_drafts:
all_dependency_drafts.append(dependency_drafts)
dependency_drafts = Draft.objects.filter(
entity__affects__in=dependency_drafts.all().values_list("version_id", flat=True)
).distinct()
unpublished_dependency_drafts = [
dependency_drafts_qset.all().with_unpublished_changes()
for dependency_drafts_qset in all_dependency_drafts
]
return unpublished_dependency_drafts
def publish_from_drafts(
learning_package_id: int, # LearningPackage.id
/,
draft_qset: QuerySet[Draft],
message: str = "",
published_at: datetime | None = None,
published_by: int | None = None, # User.id
*,
publish_dependencies: bool = True,
) -> PublishLog:
"""
Publish the rows in the ``draft_model_qsets`` args passed in.
By default, this will also publish all dependencies (e.g. unpinned children)
of the Drafts that are passed in.
"""
if published_at is None:
published_at = datetime.now(tz=timezone.utc)
with atomic():
if publish_dependencies:
dependency_drafts_qsets = _get_dependencies_with_unpublished_changes(draft_qset)
else:
dependency_drafts_qsets = []
# One PublishLog for this entire publish operation.
publish_log = PublishLog(
learning_package_id=learning_package_id,
message=message,
published_at=published_at,
published_by_id=published_by,
)
publish_log.full_clean()
publish_log.save(force_insert=True)
# We're intentionally avoiding union() here because Django ORM unions
# introduce cumbersome restrictions (can only union once, can't
# select_related on it after, the extra rows must be exactly compatible
# in unioned qsets, etc.) Instead, we're going to have one queryset per
# dependency layer.
all_draft_qsets = [
draft_qset.select_related("entity__published__version"),
*dependency_drafts_qsets, # one QuerySet per layer of dependencies
]
published_draft_ids = set()
for qset in all_draft_qsets:
for draft in qset:
# Skip duplicates that we might get from expanding dependencies.
if draft.pk in published_draft_ids:
continue
try:
old_version = draft.entity.published.version
except ObjectDoesNotExist:
# This means there is no published version yet.
old_version = None
# Create a record describing publishing this particular
# Publishable (useful for auditing and reverting).
publish_log_record = PublishLogRecord(
publish_log=publish_log,
entity=draft.entity,
old_version=old_version,
new_version=draft.version,
)
publish_log_record.full_clean()
publish_log_record.save(force_insert=True)
# Update the lookup we use to fetch the published versions
Published.objects.update_or_create(
entity=draft.entity,
defaults={
"version": draft.version,
"publish_log_record": publish_log_record,
},
)
published_draft_ids.add(draft.pk)
_create_side_effects_for_change_log(publish_log)
return publish_log
def get_draft_version(publishable_entity_or_id: PublishableEntity | int, /) -> PublishableEntityVersion | None:
"""
Return current draft PublishableEntityVersion for this PublishableEntity.
This function will return None if there is no current draft.
"""
if isinstance(publishable_entity_or_id, PublishableEntity):
# Fetches the draft version for a given PublishableEntity.
# Gracefully handles cases where no draft is present.
draft: Optional[Draft] = getattr(publishable_entity_or_id, "draft", None)
if draft is None:
return None
return draft.version
try:
draft = Draft.objects.select_related("version").get(
entity_id=publishable_entity_or_id
)
except Draft.DoesNotExist:
# No draft was ever created.
return None
# draft.version could be None if it was set that way by set_draft_version.
# Setting the Draft.version to None is how we show that we've "deleted" the
# content in Studio.
return draft.version
def get_published_version(publishable_entity_or_id: PublishableEntity | int, /) -> PublishableEntityVersion | None:
"""
Return current published PublishableEntityVersion for this PublishableEntity.
This function will return None if there is no current published version.
"""
if isinstance(publishable_entity_or_id, PublishableEntity):
# Fetches the published version for a given PublishableEntity.
# Gracefully handles cases where no published version is present.
published: Optional[Published] = getattr(publishable_entity_or_id, "published", None)
if published is None:
return None
return published.version
try:
published = Published.objects.select_related("version").get(
entity_id=publishable_entity_or_id
)
except Published.DoesNotExist:
return None
# published.version could be None if something was published at one point,
# had its draft soft deleted, and then was published again.
return published.version
def get_entity_draft_history(
publishable_entity_or_id: PublishableEntity | int, /
) -> QuerySet[DraftChangeLogRecord]:
"""
Return DraftChangeLogRecords for a PublishableEntity since its last publication,
ordered from most recent to oldest.
Each record pre-fetches ``entity__component__component_type`` so callers can
access ``record.entity.component.component_type`` (namespace and name) without
extra queries. Note: accessing ``.component`` on a record whose entity backs a
Container rather than a Component will raise ``RelatedObjectDoesNotExist``.
Edge cases:
- Never published, no versions: returns an empty queryset.
- Never published, has versions: returns all DraftChangeLogRecords.
- No changes since the last publish: returns an empty queryset.
- Last publish was a soft-delete (Published.version=None): the Published row
still exists and its published_at timestamp is used as the lower bound, so
only draft changes made after that soft-delete publish are returned. If
there are no subsequent changes, the queryset is empty.
- Unpublished soft-delete (soft-delete in draft, not yet published): the
soft-delete DraftChangeLogRecord (new_version=None) is included because
it was made after the last real publish.
"""
if isinstance(publishable_entity_or_id, int):
entity_id = publishable_entity_or_id
else:
entity_id = publishable_entity_or_id.pk
qs = (
DraftChangeLogRecord.objects
.filter(entity_id=entity_id)
.select_related(
"draft_change_log__changed_by",
"entity__component__component_type",
"old_version",
"new_version",
)
.order_by("-draft_change_log__changed_at")
)
# Narrow to changes since the last publication (or last reset to published)
try:
published = Published.objects.select_related(
"publish_log_record__publish_log"
).get(entity_id=entity_id)
published_at = published.publish_log_record.publish_log.published_at
published_version_id = published.version_id
# If reset_drafts_to_published() was called after the last publish,
# there will be a DraftChangeLogRecord where new_version == published
# version. Use the most recent such record's timestamp as the lower
# bound so that discarded entries no longer appear in the draft history.
last_reset_at = (
DraftChangeLogRecord.objects
.filter(
entity_id=entity_id,
new_version_id=published_version_id,
draft_change_log__changed_at__gt=published_at,
)
.order_by("-draft_change_log__changed_at")
.values_list("draft_change_log__changed_at", flat=True)
.first()
)
lower_bound = last_reset_at if last_reset_at else published_at
qs = qs.filter(draft_change_log__changed_at__gt=lower_bound)
except Published.DoesNotExist:
pass
return qs
def get_entity_publish_history(
publishable_entity_or_id: PublishableEntity | int, /
) -> QuerySet[PublishLogRecord]:
"""
Return all PublishLogRecords for a PublishableEntity, ordered most recent first.
Each record represents one publish event for this entity. old_version,
new_version, and ``entity__component__component_type`` are pre-fetched so
callers can access ``record.entity.component.component_type`` (namespace and
name) without extra queries. Note: accessing ``.component`` on a record whose
entity backs a Container rather than a Component will raise
``RelatedObjectDoesNotExist``.
Edge cases:
- Never published: returns an empty queryset.
- Soft-delete published (new_version=None): the record is included with
old_version pointing to the last published version and new_version=None,
indicating the entity was removed from the published state.
- Multiple draft versions created between two publishes are compacted: each
PublishLogRecord captures only the version that was actually published,
not the intermediate draft versions.
"""
if isinstance(publishable_entity_or_id, int):
entity_id = publishable_entity_or_id
else:
entity_id = publishable_entity_or_id.pk
return (
PublishLogRecord.objects
.filter(entity_id=entity_id)
.select_related(
"publish_log__published_by",
"entity__component__component_type",
"old_version",
"new_version",
)
.order_by("-publish_log__published_at")
)
def get_entity_publish_history_entries(
publishable_entity_or_id: PublishableEntity | int,
/,
publish_log_uuid: str,
) -> QuerySet[DraftChangeLogRecord]:
"""
Return the DraftChangeLogRecords associated with a specific PublishLog.
Finds the PublishLogRecord for the given entity and publish_log_uuid, then
returns all DraftChangeLogRecords whose changed_at falls between the previous
publish for this entity (exclusive) and this publish (inclusive), ordered
most-recent-first.
Time bounds are used instead of version bounds because DraftChangeLogRecord
has no single version_num field (soft-delete records have new_version=None),
and using published_at timestamps cleanly handles all cases without extra
joins.
Each record pre-fetches ``entity__component__component_type`` so callers can
access ``record.entity.component.component_type`` (namespace and name) without
extra queries. Note: accessing ``.component`` on a record whose entity backs a
Container rather than a Component will raise ``RelatedObjectDoesNotExist``.
Edge cases:
- Each publish group is independent: only the DraftChangeLogRecords that
belong to the requested publish_log_uuid are returned; changes attributed
to other publish groups are excluded.
- Soft-delete publish (PublishLogRecord.new_version=None): the soft-delete
DraftChangeLogRecord (new_version=None) is included in the entries because
it falls within the time window of that publish group.
Raises PublishLogRecord.DoesNotExist if publish_log_uuid is not found for
this entity.
"""
if isinstance(publishable_entity_or_id, int):
entity_id = publishable_entity_or_id
else:
entity_id = publishable_entity_or_id.pk
# Fetch the PublishLogRecord for the requested PublishLog
pub_record = (
PublishLogRecord.objects
.filter(entity_id=entity_id, publish_log__uuid=publish_log_uuid)
.select_related("publish_log")
.get()
)
published_at = pub_record.publish_log.published_at
# Find the previous publish for this entity to use as the lower time bound
prev_pub_record = (
PublishLogRecord.objects
.filter(entity_id=entity_id, publish_log__published_at__lt=published_at)
.select_related("publish_log")
.order_by("-publish_log__published_at")
.first()
)
prev_published_at = prev_pub_record.publish_log.published_at if prev_pub_record else None
# All draft changes up to (and including) this publish's timestamp
draft_qs = (
DraftChangeLogRecord.objects
.filter(entity_id=entity_id, draft_change_log__changed_at__lte=published_at)
.select_related(
"draft_change_log__changed_by",
"entity__component__component_type",
"old_version",
"new_version",
)
.order_by("-draft_change_log__changed_at")
)
# Exclude changes that belong to an earlier PublishLog's window
if prev_published_at:
draft_qs = draft_qs.filter(draft_change_log__changed_at__gt=prev_published_at)
# Find the baseline: the version that was published in the previous publish group
# (None if this is the first publish for this entity).
baseline_version_id = prev_pub_record.new_version_id if prev_pub_record else None
# If reset_drafts_to_published() was called within this publish window, there
# will be a DraftChangeLogRecord where new_version == baseline. Use the most
# recent such record as the new lower bound so discarded entries are excluded.
reset_filter = {
"entity_id": entity_id,
"new_version_id": baseline_version_id,
"draft_change_log__changed_at__lte": published_at,
}
if prev_published_at:
reset_filter["draft_change_log__changed_at__gt"] = prev_published_at
last_reset_at = (
DraftChangeLogRecord.objects
.filter(**reset_filter)
.order_by("-draft_change_log__changed_at")
.values_list("draft_change_log__changed_at", flat=True)
.first()
)
if last_reset_at:
draft_qs = draft_qs.filter(draft_change_log__changed_at__gt=last_reset_at)
return draft_qs
def get_entity_version_contributors(
publishable_entity_or_id: PublishableEntity | int,
/,
old_version_num: int,
new_version_num: int | None,
) -> QuerySet:
"""
Return distinct User queryset of contributors (changed_by) for
DraftChangeLogRecords of a PublishableEntity after old_version_num.
If new_version_num is not None (normal publish), captures records where
new_version is between old_version_num (exclusive) and new_version_num (inclusive).
If new_version_num is None (soft delete published), captures both normal
edits after old_version_num AND the soft-delete record itself (identified
by new_version=None and old_version >= old_version_num). A soft-delete
record whose old_version falls before old_version_num is excluded.
Edge cases:
- If no DraftChangeLogRecords fall in the range, returns an empty queryset.
- Records with changed_by=None (system changes with no associated user) are
always excluded.
- A user who contributed multiple versions in the range appears only once
(results are deduplicated with DISTINCT).
"""
entity_id = publishable_entity_or_id if isinstance(publishable_entity_or_id, int) else publishable_entity_or_id.pk
if new_version_num is not None:
version_filter = Q(
new_version__version_num__gt=old_version_num,
new_version__version_num__lte=new_version_num,
)
else:
# Soft delete: include edits after old_version_num + the soft-delete record
version_filter = (
Q(new_version__version_num__gt=old_version_num) |
Q(new_version__isnull=True, old_version__version_num__gte=old_version_num)
)
contributor_ids = (
DraftChangeLogRecord.objects
.filter(entity_id=entity_id)
.filter(version_filter)
.exclude(draft_change_log__changed_by=None)
.values_list("draft_change_log__changed_by", flat=True)
.distinct()
)
return get_user_model().objects.filter(pk__in=contributor_ids)
def set_draft_version(
draft_or_id: Draft | int,
publishable_entity_version_pk: int | None,
/,
set_at: datetime | None = None,
set_by: int | None = None, # User.id
) -> None:
"""
Modify the Draft of a PublishableEntity to be a PublishableEntityVersion.
The ``draft`` argument can be either a Draft model object, or the primary
key of a Draft/PublishableEntity (Draft is defined so these will be the same
value).
This would most commonly be used to set the Draft to point to a newly
created PublishableEntityVersion that was created in Studio (because someone
edited some content). Setting a Draft's version to None is like deleting it
from Studio's editing point of view (see ``soft_delete_draft`` for more
details).
Calling this function attaches a new DraftChangeLogRecord and attaches it to
a DraftChangeLog.
This function will create DraftSideEffect entries and properly add any
containers that may have been affected by this draft update, UNLESS it is
called from within a bulk_draft_changes_for block. If it is called from
inside a bulk_draft_changes_for block, it will not add side-effects for
containers, as bulk_draft_changes_for will automatically do that when the
block exits.
"""
if set_at is None:
set_at = datetime.now(tz=timezone.utc)
with atomic(savepoint=False):
if isinstance(draft_or_id, Draft):
draft = draft_or_id
elif isinstance(draft_or_id, int):
draft, _created = Draft.objects.select_related("entity") \
.get_or_create(entity_id=draft_or_id)
else:
class_name = draft_or_id.__class__.__name__
raise TypeError(
f"draft_or_id must be a Draft or int, not ({class_name})"
)
# If the Draft is already pointing at this version, there's nothing to do.
old_version_id = draft.version_id
if old_version_id == publishable_entity_version_pk:
return
# The actual update of the Draft model is here. Everything after this
# block is bookkeeping in our DraftChangeLog.
draft.version_id = publishable_entity_version_pk
# Check to see if we're inside a context manager for an active
# DraftChangeLog (i.e. what happens if the caller is using the public
# bulk_draft_changes_for() API call), or if we have to make our own.
learning_package_id = draft.entity.learning_package_id
active_change_log = DraftChangeLogContext.get_active_draft_change_log(
learning_package_id
)
if active_change_log:
draft_log_record = _add_to_existing_draft_change_log(
active_change_log,
draft.entity_id,
old_version_id=old_version_id,
new_version_id=publishable_entity_version_pk,
)
if draft_log_record:
# Normal case: a DraftChangeLogRecord was created or updated.
draft.draft_log_record = draft_log_record
else:
# Edge case: this change cancelled out other changes, and the
# net effect is that the DraftChangeLogRecord shouldn't exist,
# i.e. the version at the start and end of the DraftChangeLog is
# the same. In that case, _add_to_existing_draft_change_log will
# delete the log record for this Draft state, and we have to
# look for the most recently created DraftLogRecord from another
# DraftChangeLog. This value may be None.
#
# NOTE: There may be some weird edge cases here around soft-
# deletions and modifications of the same Draft entry in nested
# bulk_draft_changes_for() calls. I haven't thought that through
# yet--it might be better to just throw an error rather than try
# to accommodate it.
draft.draft_log_record = (
DraftChangeLogRecord.objects
.filter(entity_id=draft.entity_id)
.order_by("-pk")
.first()
)
draft.save()
# We also *don't* create container side effects here because there
# may be many changes in this DraftChangeLog, some of which haven't
# been made yet. It wouldn't make sense to create a side effect that
# says, "this Unit changed because this Component in it changed" if
# we were changing that same Unit later on in the same
# DraftChangeLog, because that new Unit version might not even
# include that child Component. Also, calculating side-effects is
# expensive, and would result in a lot of wasted queries if we did
# it for every change will inside an active change log context.
#
# Therefore we'll let DraftChangeLogContext do that work when it
# exits its context.
else:
# This means there is no active DraftChangeLog, so we create our own
# and add our DraftChangeLogRecord to it. This has the very minor
# optimization that we don't have to check for an existing
# DraftChangeLogRecord, because we know it can't exist yet.
change_log = DraftChangeLog.objects.create(
learning_package_id=learning_package_id,
changed_at=set_at,
changed_by_id=set_by,
)
draft.draft_log_record = DraftChangeLogRecord.objects.create(
draft_change_log=change_log,
entity_id=draft.entity_id,
old_version_id=old_version_id,
new_version_id=publishable_entity_version_pk,
)
draft.save()
_create_side_effects_for_change_log(change_log)
def _add_to_existing_draft_change_log(
active_change_log: DraftChangeLog,
entity_id: int,
old_version_id: int | None,
new_version_id: int | None,
) -> DraftChangeLogRecord | None:
"""
Create, update, or delete a DraftChangeLogRecord for the active_change_log.
The an active_change_log may have many DraftChangeLogRecords already
associated with it. A DraftChangeLog can only have one DraftChangeLogRecord
per PublishableEntity, e.g. the same Component can't go from v1 to v2 and v2
to v3 in the same DraftChangeLog. The DraftChangeLogRecord is meant to
capture the before and after states of the Draft version for that entity,
so we always keep the first value for old_version, while updating to the
most recent value for new_version.
So for example, if we called this function with the same active_change_log
and the same entity_id but with versions: (None, v1), (v1, v2), (v2, v3);