Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,10 @@ Below are the existing sink names and their corresponding object names (as neede
- ``UserProfile`` - Listens for the ``post_save`` Django signal on the ``UserProfile``
model and stores the user profile data in ClickHouse. Object name: ``user_profile``
- ``CourseEnrollmentSink`` - Listen for the ``ENROLL_STATUS_CHANGE`` event and stores
the course enrollment data. Object name: ``course_enrollment``
the course enrollment data, identifying the learner only by their xAPI ``actor_id``.
Object name: ``course_enrollment``. Its ``username`` and ``user_id`` columns were removed
because they were written whatever the PII setting said
(`tutor-contrib-aspects#1403 <https://github.com/openedx/tutor-contrib-aspects/issues/1403>`_).
- ``CatalogPathwaySink`` - Listens for the ``post_save`` Django signal on the openedx-core
``CatalogPathway`` model. Object name: ``catalog_pathway``
- ``CatalogPathwayTombstoneSink`` - Listens for the ``post_delete`` Django signal on the
Expand All @@ -58,8 +61,9 @@ taxonomy's ``taxonomy_type`` as ``tags``. Their ``EVENT_SINK_CLICKHOUSE_MODEL_CO
``student_competency_status``, ``student_competency_course_status`` and ``competency_taxonomy``.

Apply the matching tutor-contrib-aspects ClickHouse migrations before upgrading to a version that
adds sink columns, such as ``taxonomy_type`` on ``taxonomy``. Sink inserts are positional CSV and
tolerate one bad row, so a single-row dump against the old schema is dropped without an error.
changes sink columns, such as ``taxonomy_type`` on ``taxonomy`` or the rebuilt ``course_enrollment``
table. Sink inserts are positional CSV and tolerate one bad row, so a single-row dump against the
old schema is dropped without an error.

Commands
========
Expand Down
19 changes: 16 additions & 3 deletions src/platform_plugin_aspects/sinks/base_sink.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,11 +239,24 @@ def serialize_item(self, item, many=False, initial=None):
Serialize the data to be sent to ClickHouse
"""
Serializer = self.get_serializer()
serializer = Serializer( # pylint: disable=not-callable
item, many=many, initial=initial
)
kwargs = {"many": many, "initial": initial}
context = self.get_serializer_context(item, many=many)
if context:
kwargs["context"] = context
serializer = Serializer(item, **kwargs) # pylint: disable=not-callable
return serializer.data

def get_serializer_context(
self, item, many=False
): # pylint: disable=unused-argument
"""
Return the serializer context, such as data prefetched for a whole batch.

Empty by default, and an empty context isn't passed, so serializers that take
no context keep working.
"""
return {}

def get_serializer(self):
"""
Return the serializer to be used for the insert
Expand Down
53 changes: 52 additions & 1 deletion src/platform_plugin_aspects/sinks/course_enrollment_sink.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
"""User profile sink"""
"""Course enrollment sink"""

from platform_plugin_aspects.sinks.base_sink import ModelBaseSink
from platform_plugin_aspects.sinks.external_id_sink import ExternalIdSink
from platform_plugin_aspects.sinks.serializers import CourseEnrollmentSerializer
from platform_plugin_aspects.utils import create_xapi_actor_ids, get_xapi_actor_ids


class CourseEnrollmentSink(ModelBaseSink): # pylint: disable=abstract-method
Expand All @@ -16,5 +18,54 @@ class CourseEnrollmentSink(ModelBaseSink): # pylint: disable=abstract-method
name = "Course Enrollment"
serializer_class = CourseEnrollmentSerializer

# time_last_dumped has a UTC offset, which DateTime64 only parses with "best_effort"
CLICKHOUSE_BULK_INSERT_PARAMS = {
**ModelBaseSink.CLICKHOUSE_BULK_INSERT_PARAMS,
"date_time_input_format": "best_effort",
}

def get_queryset(self, start_pk=None):
return super().get_queryset(start_pk).select_related("user")

def get_serializer_context(self, item, many=False):
"""
Load the batch's xAPI actor ids, creating the missing ones, in a few queries.

Without this, each enrollment would look up its learner's actor id, and each
learner without one would get it created alone, with its own ExternalIdSink
dump. That is the common case in a first backfill.
"""
if not many:
return {}
user_ids = {enrollment.user_id for enrollment in item}
actor_ids = get_xapi_actor_ids(user_ids)
missing = user_ids - actor_ids.keys()
if missing:
created = create_xapi_actor_ids(missing)
actor_ids.update(
{
external_id.user_id: str(external_id.external_user_id)
for external_id in created
}
)
self.dump_created_external_ids(created)
return {"xapi_actor_ids": actor_ids}

def dump_created_external_ids(self, external_ids):
"""
Send newly created ExternalIds to ClickHouse in one insert, if their sink is on.

Stands in for the per-row post_save dump that bulk_create skips. A failure is
logged and doesn't stop the enrollment dump, as a failed post_save task
wouldn't: dump_data_to_clickhouse --object external_id repairs it.
"""
if not external_ids or not ExternalIdSink.is_enabled():
return
try:
ExternalIdSink(self.connection_overrides, self.log).dump(
external_ids, many=True
)
except Exception: # pylint: disable=broad-exception-caught
self.log.exception(
f"Error dumping {len(external_ids)} new External IDs to ClickHouse"
)
26 changes: 22 additions & 4 deletions src/platform_plugin_aspects/sinks/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,10 +189,19 @@ def get_course_key(self, overview):


class CourseEnrollmentSerializer(BaseSinkSerializer, serializers.ModelSerializer):
"""Serializer for the Course Enrollment model."""
"""
Serializer for the Course Enrollment model.

Learners are identified only by their xAPI ``actor_id``, so the table holds no PII,
is written whatever ``ASPECTS_ENABLE_PII`` says, and joins the xAPI tables and the
other learner sinks. The ``username`` and ``user_id`` columns were removed as a
privacy fix: https://github.com/openedx/tutor-contrib-aspects/issues/1403

Sink inserts are positional CSV, so the field order is the ClickHouse column order.
"""

course_key = serializers.SerializerMethodField()
username = serializers.CharField(source="user.username")
actor_id = serializers.SerializerMethodField()

class Meta:
"""Meta class for the CourseEnrollmentSerializer"""
Expand All @@ -204,16 +213,25 @@ class Meta:
"created",
"is_active",
"mode",
"username",
"user_id",
"dump_id",
"time_last_dumped",
"actor_id",
]

def get_course_key(self, obj):
"""Return the course key as a string."""
return str(obj.course_id)

def get_actor_id(self, instance):
"""
Return the learner's xAPI actor id.

A bulk dump passes the batch's existing actor ids in the ``xapi_actor_ids``
context, so only learners without one yet need a query of their own.
"""
actor_id = self.context.get("xapi_actor_ids", {}).get(instance.user_id)
return actor_id or get_or_create_xapi_actor_id(instance.user)


class CatalogPathwaySerializer(BaseSinkSerializer, serializers.ModelSerializer):
"""Serializer for the CatalogPathway model."""
Expand Down
18 changes: 18 additions & 0 deletions src/platform_plugin_aspects/sinks/tests/test_base_sink.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,24 @@ def test_serialize_item(self):
self.child_sink.get_serializer.return_value.return_value.data,
)

def test_serialize_item_with_context(self):
"""
Test that a sink's serializer context is passed to the serializer.
"""
items = [Mock(id=1), Mock(id=2)]
self.child_sink.get_serializer = Mock()
self.child_sink.get_serializer_context = Mock(return_value={"prefetched": 1})

self.child_sink.serialize_item(items, many=True, initial=None)

self.child_sink.get_serializer_context.assert_called_once_with(items, many=True)
self.child_sink.get_serializer.return_value.assert_called_once_with(
items,
many=True,
initial=None,
context={"prefetched": 1},
)

@patch("platform_plugin_aspects.sinks.base_sink.io")
@patch("platform_plugin_aspects.sinks.base_sink.requests")
@ddt.data(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
Test the course enrollment sink module.
"""

from unittest.mock import patch
from unittest.mock import Mock, patch
from uuid import UUID

from platform_plugin_aspects.sinks import CourseEnrollmentSink

Expand All @@ -18,3 +19,115 @@ def test_get_queryset(mock_get_queryset):

mock_get_queryset.assert_called_once_with(None)
mock_get_queryset.return_value.select_related.assert_called_once_with("user")


@patch("platform_plugin_aspects.sinks.course_enrollment_sink.ExternalIdSink")
@patch("platform_plugin_aspects.sinks.course_enrollment_sink.create_xapi_actor_ids")
@patch("platform_plugin_aspects.sinks.course_enrollment_sink.get_xapi_actor_ids")
def test_get_serializer_context_many(
mock_get_xapi_actor_ids, mock_create_xapi_actor_ids, mock_external_id_sink
):
"""
Test that a bulk dump loads the batch's actor ids in one call and creates none
when every learner has one.
"""
mock_get_xapi_actor_ids.return_value = {7: "actor-7", 8: "actor-8"}
sink = CourseEnrollmentSink(None, None)
enrollments = [Mock(user_id=7), Mock(user_id=8), Mock(user_id=7)]

context = sink.get_serializer_context(enrollments, many=True)

assert context == {"xapi_actor_ids": {7: "actor-7", 8: "actor-8"}}
mock_get_xapi_actor_ids.assert_called_once_with({7, 8})
mock_create_xapi_actor_ids.assert_not_called()
mock_external_id_sink.assert_not_called()


@patch("platform_plugin_aspects.sinks.course_enrollment_sink.ExternalIdSink")
@patch("platform_plugin_aspects.sinks.course_enrollment_sink.create_xapi_actor_ids")
@patch("platform_plugin_aspects.sinks.course_enrollment_sink.get_xapi_actor_ids")
def test_get_serializer_context_creates_missing(
mock_get_xapi_actor_ids, mock_create_xapi_actor_ids, mock_external_id_sink
):
"""
Test that learners without an actor id get one in a single bulk create, and that
the new ExternalIds are dumped together.
"""
mock_get_xapi_actor_ids.return_value = {7: "actor-7"}
created = [
Mock(user_id=8, external_user_id=UUID("29e5b22b-b457-49fa-9633-6c0123305d18"))
]
mock_create_xapi_actor_ids.return_value = created
mock_external_id_sink.is_enabled.return_value = True
sink = CourseEnrollmentSink({"url": "x"}, Mock())

context = sink.get_serializer_context([Mock(user_id=7), Mock(user_id=8)], many=True)

assert context == {
"xapi_actor_ids": {7: "actor-7", 8: "29e5b22b-b457-49fa-9633-6c0123305d18"}
}
mock_create_xapi_actor_ids.assert_called_once_with({8})
mock_external_id_sink.assert_called_once_with({"url": "x"}, sink.log)
mock_external_id_sink.return_value.dump.assert_called_once_with(created, many=True)


@patch("platform_plugin_aspects.sinks.course_enrollment_sink.ExternalIdSink")
def test_dump_created_external_ids_sink_disabled(mock_external_id_sink):
"""
Test that new ExternalIds aren't dumped when the external_id sink is off.
"""
mock_external_id_sink.is_enabled.return_value = False
sink = CourseEnrollmentSink(None, Mock())

sink.dump_created_external_ids([Mock()])

mock_external_id_sink.assert_not_called()


@patch("platform_plugin_aspects.sinks.course_enrollment_sink.ExternalIdSink")
def test_dump_created_external_ids_none_created(mock_external_id_sink):
"""
Test that nothing is dumped when no ExternalId was created.
"""
sink = CourseEnrollmentSink(None, Mock())

sink.dump_created_external_ids([])

mock_external_id_sink.assert_not_called()
mock_external_id_sink.is_enabled.assert_not_called()


@patch("platform_plugin_aspects.sinks.course_enrollment_sink.ExternalIdSink")
def test_dump_created_external_ids_failure_is_logged(mock_external_id_sink):
"""
Test that a failed ExternalId dump is logged and doesn't stop the enrollment dump.
"""
mock_external_id_sink.is_enabled.return_value = True
mock_external_id_sink.return_value.dump.side_effect = Exception("down")
log = Mock()
sink = CourseEnrollmentSink(None, log)

sink.dump_created_external_ids([Mock(), Mock()])

log.exception.assert_called_once()


@patch("platform_plugin_aspects.sinks.course_enrollment_sink.get_xapi_actor_ids")
def test_get_serializer_context_single(mock_get_xapi_actor_ids):
"""
Test that a single enrollment skips the prefetch.
"""
sink = CourseEnrollmentSink(None, None)

assert not sink.get_serializer_context(Mock(user_id=7), many=False)
mock_get_xapi_actor_ids.assert_not_called()


def test_bulk_insert_params():
"""
Test that inserts parse time_last_dumped's UTC offset into the DateTime64 column.
"""
assert (
CourseEnrollmentSink.CLICKHOUSE_BULK_INSERT_PARAMS["date_time_input_format"]
== "best_effort"
)
Loading
Loading