model_data.py 35.5 KB
Newer Older
1
"""
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Classes to provide the LMS runtime data storage to XBlocks.

:class:`DjangoKeyValueStore`: An XBlock :class:`~KeyValueStore` which
    stores a subset of xblocks scopes as Django ORM objects. It wraps
    :class:`~FieldDataCache` to provide an XBlock-friendly interface.


:class:`FieldDataCache`: A object which provides a read-through prefetch cache
    of data to support XBlock fields within a limited set of scopes.

The remaining classes in this module provide read-through prefetch cache implementations
for specific scopes. The individual classes provide the knowledge of what are the essential
pieces of information for each scope, and thus how to cache, prefetch, and create new field data
entries.

UserStateCache: A cache for Scope.user_state
UserStateSummaryCache: A cache for Scope.user_state_summary
PreferencesCache: A cache for Scope.preferences
UserInfoCache: A cache for Scope.user_info
DjangoOrmFieldCache: A base-class for single-row-per-field caches.
22 23
"""

24
import json
25
from abc import abstractmethod, ABCMeta
26
from collections import defaultdict, namedtuple
27 28
from .models import (
    StudentModule,
Calen Pennington committed
29
    XModuleUserStateSummaryField,
30 31 32
    XModuleStudentPrefsField,
    XModuleStudentInfoField
)
33
import logging
34
from opaque_keys.edx.keys import CourseKey, UsageKey
35
from opaque_keys.edx.block_types import BlockTypeKeyV1
36
from opaque_keys.edx.asides import AsideUsageKeyV1, AsideUsageKeyV2
37
from contracts import contract, new_contract
38 39

from django.db import DatabaseError
40

Calen Pennington committed
41 42
from xblock.runtime import KeyValueStore
from xblock.exceptions import KeyValueMultiSaveError, InvalidScopeError
43
from xblock.fields import Scope, UserScope
44
from xmodule.modulestore.django import modulestore
45
from xblock.core import XBlockAside
46
from courseware.user_state_client import DjangoXBlockUserStateClient
47

48

49
log = logging.getLogger(__name__)
50 51 52


class InvalidWriteError(Exception):
53 54 55 56
    """
    Raised to indicate that writing to a particular key
    in the KeyValueStore is disabled
    """
57 58


59 60 61 62 63 64 65 66 67 68 69
def _all_usage_keys(descriptors, aside_types):
    """
    Return a set of all usage_ids for the `descriptors` and for
    as all asides in `aside_types` for those descriptors.
    """
    usage_ids = set()
    for descriptor in descriptors:
        usage_ids.add(descriptor.scope_ids.usage_id)

        for aside_type in aside_types:
            usage_ids.add(AsideUsageKeyV1(descriptor.scope_ids.usage_id, aside_type))
70
            usage_ids.add(AsideUsageKeyV2(descriptor.scope_ids.usage_id, aside_type))
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89

    return usage_ids


def _all_block_types(descriptors, aside_types):
    """
    Return a set of all block_types for the supplied `descriptors` and for
    the asides types in `aside_types` associated with those descriptors.
    """
    block_types = set()
    for descriptor in descriptors:
        block_types.add(BlockTypeKeyV1(descriptor.entry_point, descriptor.scope_ids.block_type))

    for aside_type in aside_types:
        block_types.add(BlockTypeKeyV1(XBlockAside.entry_point, aside_type))

    return block_types


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
class DjangoKeyValueStore(KeyValueStore):
    """
    This KeyValueStore will read and write data in the following scopes to django models
        Scope.user_state_summary
        Scope.user_state
        Scope.preferences
        Scope.user_info

    Access to any other scopes will raise an InvalidScopeError

    Data for Scope.user_state is stored as StudentModule objects via the django orm.

    Data for the other scopes is stored in individual objects that are named for the
    scope involved and have the field name as a key

    If the key isn't found in the expected table during a read or a delete, then a KeyError will be raised
    """

    _allowed_scopes = (
        Scope.user_state_summary,
        Scope.user_state,
        Scope.preferences,
        Scope.user_info,
    )

    def __init__(self, field_data_cache):
        self._field_data_cache = field_data_cache

    def get(self, key):
119
        self._raise_unless_scope_is_allowed(key)
120
        return self._field_data_cache.get(key)
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135

    def set(self, key, value):
        """
        Set a single value in the KeyValueStore
        """
        self.set_many({key: value})

    def set_many(self, kv_dict):
        """
        Provide a bulk save mechanism.

        `kv_dict`: A dictionary of dirty fields that maps
          xblock.KvsFieldData._key : value

        """
136 137
        for key in kv_dict:
            # Check key for validity
138
            self._raise_unless_scope_is_allowed(key)
139

140
        self._field_data_cache.set_many(kv_dict)
141 142

    def delete(self, key):
143
        self._raise_unless_scope_is_allowed(key)
144
        self._field_data_cache.delete(key)
145 146

    def has(self, key):
147 148 149 150 151
        self._raise_unless_scope_is_allowed(key)
        return self._field_data_cache.has(key)

    def _raise_unless_scope_is_allowed(self, key):
        """Raise an InvalidScopeError if key.scope is not in self._allowed_scopes."""
152
        if key.scope not in self._allowed_scopes:
153
            raise InvalidScopeError(key, self._allowed_scopes)
154 155


156 157 158
new_contract("DjangoKeyValueStore", DjangoKeyValueStore)
new_contract("DjangoKeyValueStore_Key", DjangoKeyValueStore.Key)

159

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
class DjangoOrmFieldCache(object):
    """
    Baseclass for Scope-specific field cache objects that are based on
    single-row-per-field Django ORM objects.
    """
    __metaclass__ = ABCMeta

    def __init__(self):
        self._cache = {}

    def cache_fields(self, fields, xblocks, aside_types):
        """
        Load all fields specified by ``fields`` for the supplied ``xblocks``
        and ``aside_types`` into this cache.

        Arguments:
            fields (list of str): Field names to cache.
            xblocks (list of :class:`XBlock`): XBlocks to cache fields for.
            aside_types (list of str): Aside types to cache fields for.
        """
        for field_object in self._read_objects(fields, xblocks, aside_types):
            self._cache[self._cache_key_for_field_object(field_object)] = field_object

183 184
    @contract(kvs_key=DjangoKeyValueStore.Key)
    def get(self, kvs_key):
185 186 187 188 189 190 191 192 193
        """
        Return the django model object specified by `kvs_key` from
        the cache.

        Arguments:
            kvs_key (`DjangoKeyValueStore.Key`): The field value to delete

        Returns: A django orm object from the cache
        """
194 195 196 197 198 199 200
        cache_key = self._cache_key_for_kvs_key(kvs_key)
        if cache_key not in self._cache:
            raise KeyError(kvs_key.field_name)

        field_object = self._cache[cache_key]

        return json.loads(field_object.value)
201

202 203
    @contract(kvs_key=DjangoKeyValueStore.Key)
    def set(self, kvs_key, value):
204
        """
205
        Set the specified `kvs_key` to the field value `value`.
206 207 208

        Arguments:
            kvs_key (`DjangoKeyValueStore.Key`): The field value to delete
209
            value: The field value to store
210
        """
211
        self.set_many({kvs_key: value})
212

213 214 215 216
    @contract(kv_dict="dict(DjangoKeyValueStore_Key: *)")
    def set_many(self, kv_dict):
        """
        Set the specified fields to the supplied values.
217

218 219 220 221
        Arguments:
            kv_dict (dict): A dictionary mapping :class:`~DjangoKeyValueStore.Key`
                objects to values to set.
        """
222
        saved_fields = []
223 224 225 226
        for kvs_key, value in sorted(kv_dict.items()):
            cache_key = self._cache_key_for_kvs_key(kvs_key)
            field_object = self._cache.get(cache_key)

227
            try:
228 229 230 231 232 233 234 235 236 237 238 239 240 241
                serialized_value = json.dumps(value)
                # It is safe to force an insert or an update, because
                # a) we should have retrieved the object as part of the
                #    prefetch step, so if it isn't in our cache, it doesn't exist yet.
                # b) no other code should be modifying these models out of band of
                #    this cache.
                if field_object is None:
                    field_object = self._create_object(kvs_key, serialized_value)
                    field_object.save(force_insert=True)
                    self._cache[cache_key] = field_object
                else:
                    field_object.value = serialized_value
                    field_object.save(force_update=True)

242 243 244
            except DatabaseError:
                log.exception("Saving field %r failed", kvs_key.field_name)
                raise KeyValueMultiSaveError(saved_fields)
245

246 247 248
            finally:
                saved_fields.append(kvs_key.field_name)

249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
    @contract(kvs_key=DjangoKeyValueStore.Key)
    def delete(self, kvs_key):
        """
        Delete the value specified by `kvs_key`.

        Arguments:
            kvs_key (`DjangoKeyValueStore.Key`): The field value to delete

        Raises: KeyError if key isn't found in the cache
        """

        cache_key = self._cache_key_for_kvs_key(kvs_key)
        field_object = self._cache.get(cache_key)
        if field_object is None:
            raise KeyError(kvs_key.field_name)

        field_object.delete()
        del self._cache[cache_key]

268 269 270 271 272 273 274 275 276 277 278 279
    @contract(kvs_key=DjangoKeyValueStore.Key, returns=bool)
    def has(self, kvs_key):
        """
        Return whether the specified `kvs_key` is set.

        Arguments:
            kvs_key (`DjangoKeyValueStore.Key`): The field value to delete

        Returns: bool
        """
        return self._cache_key_for_kvs_key(kvs_key) in self._cache

280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
    @contract(kvs_key=DjangoKeyValueStore.Key, returns="datetime|None")
    def last_modified(self, kvs_key):
        """
        Return when the supplied field was changed.

        Arguments:
            kvs_key (`DjangoKeyValueStore.Key`): The field value to delete

        Returns: datetime if there was a modified date, or None otherwise
        """
        field_object = self._cache.get(self._cache_key_for_kvs_key(kvs_key))

        if field_object is None:
            return None
        else:
            return field_object.modified

297 298 299 300
    def __len__(self):
        return len(self._cache)

    @abstractmethod
301
    def _create_object(self, kvs_key, value):
302 303 304 305 306 307 308
        """
        Create a new object to add to the cache (which should record
        the specified field ``value`` for the field identified by
        ``kvs_key``).

        Arguments:
            kvs_key (:class:`DjangoKeyValueStore.Key`): Which field to create an entry for
309
            value: What value to record in the field
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
        """
        raise NotImplementedError()

    @abstractmethod
    def _read_objects(self, fields, xblocks, aside_types):
        """
        Return an iterator for all objects stored in the underlying datastore
        for the ``fields`` on the ``xblocks`` and the ``aside_types`` associated
        with them.

        Arguments:
            fields (list of str): Field names to return values for
            xblocks (list of :class:`~XBlock`): XBlocks to load fields for
            aside_types (list of str): Asides to load field for (which annotate the supplied
                xblocks).
        """
        raise NotImplementedError()

    @abstractmethod
    def _cache_key_for_field_object(self, field_object):
        """
        Return the key used in this DjangoOrmFieldCache to store the specified field_object.

        Arguments:
            field_object: A Django model instance that stores the data for fields in this cache
        """
        raise NotImplementedError()

    @abstractmethod
    def _cache_key_for_kvs_key(self, key):
        """
        Return the key used in this DjangoOrmFieldCache for the specified KeyValueStore key.

        Arguments:
            key (:class:`~DjangoKeyValueStore.Key`): The key representing the cached field
        """
        raise NotImplementedError()


349
class UserStateCache(object):
350 351 352
    """
    Cache for Scope.user_state xblock field data.
    """
353
    def __init__(self, user, course_id):
354
        self._cache = defaultdict(dict)
355 356
        self.course_id = course_id
        self.user = user
357
        self._client = DjangoXBlockUserStateClient(self.user)
358

359
    def cache_fields(self, fields, xblocks, aside_types):  # pylint: disable=unused-argument
360
        """
361 362
        Load all fields specified by ``fields`` for the supplied ``xblocks``
        and ``aside_types`` into this cache.
363 364

        Arguments:
365 366 367
            fields (list of str): Field names to cache.
            xblocks (list of :class:`XBlock`): XBlocks to cache fields for.
            aside_types (list of str): Aside types to cache fields for.
368
        """
369 370
        block_field_state = self._client.get_many(
            self.user.username,
371 372
            _all_usage_keys(xblocks, aside_types),
        )
373 374
        for user_state in block_field_state:
            self._cache[user_state.block_key] = user_state.state
375

376 377
    @contract(kvs_key=DjangoKeyValueStore.Key)
    def set(self, kvs_key, value):
378
        """
379
        Set the specified `kvs_key` to the field value `value`.
380 381

        Arguments:
382 383
            kvs_key (`DjangoKeyValueStore.Key`): The field value to delete
            value: The field value to store
384
        """
385
        self.set_many({kvs_key: value})
386

387 388
    @contract(kvs_key=DjangoKeyValueStore.Key, returns="datetime|None")
    def last_modified(self, kvs_key):
389
        """
390
        Return when the supplied field was changed.
391 392

        Arguments:
393 394 395
            kvs_key (`DjangoKeyValueStore.Key`): The key representing the cached field

        Returns: datetime if there was a modified date, or None otherwise
396
        """
397 398 399 400 401 402 403 404
        try:
            return self._client.get(
                self.user.username,
                kvs_key.block_scope_id,
                fields=[kvs_key.field_name],
            ).updated
        except self._client.DoesNotExist:
            return None
405

406 407 408 409 410 411 412 413 414
    @contract(kv_dict="dict(DjangoKeyValueStore_Key: *)")
    def set_many(self, kv_dict):
        """
        Set the specified fields to the supplied values.

        Arguments:
            kv_dict (dict): A dictionary mapping :class:`~DjangoKeyValueStore.Key`
                objects to values to set.
        """
415
        pending_updates = defaultdict(dict)
416 417 418
        for kvs_key, value in kv_dict.items():
            cache_key = self._cache_key_for_kvs_key(kvs_key)

419
            pending_updates[cache_key][kvs_key.field_name] = value
420

421 422 423 424 425 426
        try:
            self._client.set_many(
                self.user.username,
                pending_updates
            )
        except DatabaseError:
427
            log.exception("Saving user state failed for %s", self.user.username)
428 429 430
            raise KeyValueMultiSaveError([])
        finally:
            self._cache.update(pending_updates)
431

432
    @contract(kvs_key=DjangoKeyValueStore.Key)
433 434 435 436 437 438 439 440 441 442 443 444 445 446
    def get(self, kvs_key):
        """
        Return the django model object specified by `kvs_key` from
        the cache.

        Arguments:
            kvs_key (`DjangoKeyValueStore.Key`): The field value to delete

        Returns: A django orm object from the cache
        """
        cache_key = self._cache_key_for_kvs_key(kvs_key)
        if cache_key not in self._cache:
            raise KeyError(kvs_key.field_name)

447
        return self._cache[cache_key][kvs_key.field_name]
448 449

    @contract(kvs_key=DjangoKeyValueStore.Key)
450 451 452 453 454 455 456 457 458
    def delete(self, kvs_key):
        """
        Delete the value specified by `kvs_key`.

        Arguments:
            kvs_key (`DjangoKeyValueStore.Key`): The field value to delete

        Raises: KeyError if key isn't found in the cache
        """
459 460 461
        cache_key = self._cache_key_for_kvs_key(kvs_key)
        if cache_key not in self._cache:
            raise KeyError(kvs_key.field_name)
462

463 464 465
        field_state = self._cache[cache_key]

        if kvs_key.field_name not in field_state:
466 467
            raise KeyError(kvs_key.field_name)

468 469
        self._client.delete(self.user.username, cache_key, fields=[kvs_key.field_name])
        del field_state[kvs_key.field_name]
470

471 472 473 474 475 476 477 478 479 480
    @contract(kvs_key=DjangoKeyValueStore.Key, returns=bool)
    def has(self, kvs_key):
        """
        Return whether the specified `kvs_key` is set.

        Arguments:
            kvs_key (`DjangoKeyValueStore.Key`): The field value to delete

        Returns: bool
        """
481
        cache_key = self._cache_key_for_kvs_key(kvs_key)
482

483 484 485 486
        return (
            cache_key in self._cache and
            kvs_key.field_name in self._cache[cache_key]
        )
487

488 489 490 491 492 493 494 495 496 497 498 499
    def __len__(self):
        return len(self._cache)

    def _cache_key_for_kvs_key(self, key):
        """
        Return the key used in this DjangoOrmFieldCache for the specified KeyValueStore key.

        Arguments:
            key (:class:`~DjangoKeyValueStore.Key`): The key representing the cached field
        """
        return key.block_scope_id

500

501
class UserStateSummaryCache(DjangoOrmFieldCache):
502 503 504
    """
    Cache for Scope.user_state_summary xblock field data.
    """
505
    def __init__(self, course_id):
506
        super(UserStateSummaryCache, self).__init__()
507 508
        self.course_id = course_id

509
    def _create_object(self, kvs_key, value):
510 511 512 513 514 515 516
        """
        Create a new object to add to the cache (which should record
        the specified field ``value`` for the field identified by
        ``kvs_key``).

        Arguments:
            kvs_key (:class:`DjangoKeyValueStore.Key`): Which field to create an entry for
517
            value: The value to assign to the new field object
518
        """
519
        return XModuleUserStateSummaryField(
520
            field_name=kvs_key.field_name,
521 522
            usage_id=kvs_key.block_scope_id,
            value=value,
523 524
        )

525 526 527 528 529 530 531
    def _read_objects(self, fields, xblocks, aside_types):
        """
        Return an iterator for all objects stored in the underlying datastore
        for the ``fields`` on the ``xblocks`` and the ``aside_types`` associated
        with them.

        Arguments:
532
            fields (list of :class:`~Field`): Fields to return values for
533 534 535 536
            xblocks (list of :class:`~XBlock`): XBlocks to load fields for
            aside_types (list of str): Asides to load field for (which annotate the supplied
                xblocks).
        """
537
        return XModuleUserStateSummaryField.objects.chunked_filter(
538
            'usage_id__in',
539
            _all_usage_keys(xblocks, aside_types),
540 541
            field_name__in=set(field.name for field in fields),
        )
542

543 544 545
    def _cache_key_for_field_object(self, field_object):
        """
        Return the key used in this DjangoOrmFieldCache to store the specified field_object.
546

547 548 549 550
        Arguments:
            field_object: A Django model instance that stores the data for fields in this cache
        """
        return (field_object.usage_id.map_into_course(self.course_id), field_object.field_name)
551

552 553 554 555 556 557 558 559 560
    def _cache_key_for_kvs_key(self, key):
        """
        Return the key used in this DjangoOrmFieldCache for the specified KeyValueStore key.

        Arguments:
            key (:class:`~DjangoKeyValueStore.Key`): The key representing the cached field
        """
        return (key.block_scope_id, key.field_name)

561

562
class PreferencesCache(DjangoOrmFieldCache):
563 564 565
    """
    Cache for Scope.preferences xblock field data.
    """
566
    def __init__(self, user):
567
        super(PreferencesCache, self).__init__()
568 569
        self.user = user

570
    def _create_object(self, kvs_key, value):
571 572 573 574 575 576 577
        """
        Create a new object to add to the cache (which should record
        the specified field ``value`` for the field identified by
        ``kvs_key``).

        Arguments:
            kvs_key (:class:`DjangoKeyValueStore.Key`): Which field to create an entry for
578
            value: The value to assign to the new field object
579
        """
580
        return XModuleStudentPrefsField(
581 582 583
            field_name=kvs_key.field_name,
            module_type=BlockTypeKeyV1(kvs_key.block_family, kvs_key.block_scope_id),
            student_id=kvs_key.user_id,
584
            value=value,
585 586
        )

587 588 589 590 591 592 593 594 595 596 597 598
    def _read_objects(self, fields, xblocks, aside_types):
        """
        Return an iterator for all objects stored in the underlying datastore
        for the ``fields`` on the ``xblocks`` and the ``aside_types`` associated
        with them.

        Arguments:
            fields (list of str): Field names to return values for
            xblocks (list of :class:`~XBlock`): XBlocks to load fields for
            aside_types (list of str): Asides to load field for (which annotate the supplied
                xblocks).
        """
599
        return XModuleStudentPrefsField.objects.chunked_filter(
600
            'module_type__in',
601
            _all_block_types(xblocks, aside_types),
602
            student=self.user.pk,
603 604
            field_name__in=set(field.name for field in fields),
        )
605

606 607 608
    def _cache_key_for_field_object(self, field_object):
        """
        Return the key used in this DjangoOrmFieldCache to store the specified field_object.
609

610 611 612 613
        Arguments:
            field_object: A Django model instance that stores the data for fields in this cache
        """
        return (field_object.module_type, field_object.field_name)
614

615 616 617 618 619 620 621 622 623
    def _cache_key_for_kvs_key(self, key):
        """
        Return the key used in this DjangoOrmFieldCache for the specified KeyValueStore key.

        Arguments:
            key (:class:`~DjangoKeyValueStore.Key`): The key representing the cached field
        """
        return (BlockTypeKeyV1(key.block_family, key.block_scope_id), key.field_name)

624

625
class UserInfoCache(DjangoOrmFieldCache):
626 627 628
    """
    Cache for Scope.user_info xblock field data
    """
629
    def __init__(self, user):
630
        super(UserInfoCache, self).__init__()
631 632
        self.user = user

633
    def _create_object(self, kvs_key, value):
634 635 636 637 638 639 640
        """
        Create a new object to add to the cache (which should record
        the specified field ``value`` for the field identified by
        ``kvs_key``).

        Arguments:
            kvs_key (:class:`DjangoKeyValueStore.Key`): Which field to create an entry for
641
            value: The value to assign to the new field object
642
        """
643
        return XModuleStudentInfoField(
644 645
            field_name=kvs_key.field_name,
            student_id=kvs_key.user_id,
646
            value=value,
647 648
        )

649 650 651 652 653 654 655 656 657 658 659 660
    def _read_objects(self, fields, xblocks, aside_types):
        """
        Return an iterator for all objects stored in the underlying datastore
        for the ``fields`` on the ``xblocks`` and the ``aside_types`` associated
        with them.

        Arguments:
            fields (list of str): Field names to return values for
            xblocks (list of :class:`~XBlock`): XBlocks to load fields for
            aside_types (list of str): Asides to load field for (which annotate the supplied
                xblocks).
        """
661
        return XModuleStudentInfoField.objects.filter(
662
            student=self.user.pk,
663 664
            field_name__in=set(field.name for field in fields),
        )
665

666 667 668
    def _cache_key_for_field_object(self, field_object):
        """
        Return the key used in this DjangoOrmFieldCache to store the specified field_object.
669

670 671 672 673
        Arguments:
            field_object: A Django model instance that stores the data for fields in this cache
        """
        return field_object.field_name
674

675 676 677 678 679 680 681 682
    def _cache_key_for_kvs_key(self, key):
        """
        Return the key used in this DjangoOrmFieldCache for the specified KeyValueStore key.

        Arguments:
            key (:class:`~DjangoKeyValueStore.Key`): The key representing the cached field
        """
        return key.field_name
683

684

Calen Pennington committed
685
class FieldDataCache(object):
686 687
    """
    A cache of django model objects needed to supply the data
688
    for a module and its descendants
689
    """
690
    def __init__(self, descriptors, course_id, user, select_for_update=False, asides=None):
691
        """
692 693 694 695 696 697
        Find any courseware.models objects that are needed by any descriptor
        in descriptors. Attempts to minimize the number of queries to the database.
        Note: Only modules that have store_state = True or have shared
        state will have a StudentModule.

        Arguments
698
        descriptors: A list of XModuleDescriptors.
699 700
        course_id: The id of the current course
        user: The user for which to cache data
701
        select_for_update: Ignored
702
        asides: The list of aside types to load, or None to prefetch no asides.
703
        """
704 705 706 707 708
        if asides is None:
            self.asides = []
        else:
            self.asides = asides

709
        assert isinstance(course_id, CourseKey)
710 711 712
        self.course_id = course_id
        self.user = user

713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
        self.cache = {
            Scope.user_state: UserStateCache(
                self.user,
                self.course_id,
            ),
            Scope.user_info: UserInfoCache(
                self.user,
            ),
            Scope.preferences: PreferencesCache(
                self.user,
            ),
            Scope.user_state_summary: UserStateSummaryCache(
                self.course_id,
            ),
        }
728
        self.scorable_locations = set()
729 730 731 732 733 734 735
        self.add_descriptors_to_cache(descriptors)

    def add_descriptors_to_cache(self, descriptors):
        """
        Add all `descriptors` to this FieldDataCache.
        """
        if self.user.is_authenticated():
736
            self.scorable_locations.update(desc.location for desc in descriptors if desc.has_score)
737
            for scope, fields in self._fields_to_cache(descriptors).items():
738 739 740
                if scope not in self.cache:
                    continue

741
                self.cache[scope].cache_fields(fields, descriptors, self.asides)
742

743
    def add_descriptor_descendents(self, descriptor, depth=None, descriptor_filter=lambda descriptor: True):
744
        """
745
        Add all descendants of `descriptor` to this FieldDataCache.
746 747 748

        Arguments:
            descriptor: An XModuleDescriptor
749 750 751
            depth is the number of levels of descendant modules to load StudentModules for, in addition to
                the supplied descriptor. If depth is None, load all descendant StudentModules
            descriptor_filter is a function that accepts a descriptor and return whether the field data
752
                should be cached
753 754 755
        """

        def get_child_descriptors(descriptor, depth, descriptor_filter):
756 757 758 759 760 761 762 763 764
            """
            Return a list of all child descriptors down to the specified depth
            that match the descriptor filter. Includes `descriptor`

            descriptor: The parent to search inside
            depth: The number of levels to descend, or None for infinite depth
            descriptor_filter(descriptor): A function that returns True
                if descriptor should be included in the results
            """
765 766 767 768 769 770 771 772
            if descriptor_filter(descriptor):
                descriptors = [descriptor]
            else:
                descriptors = []

            if depth is None or depth > 0:
                new_depth = depth - 1 if depth is not None else depth

773
                for child in descriptor.get_children() + descriptor.get_required_module_descriptors():
774 775 776 777
                    descriptors.extend(get_child_descriptors(child, new_depth, descriptor_filter))

            return descriptors

778
        with modulestore().bulk_operations(descriptor.location.course_key):
779
            descriptors = get_child_descriptors(descriptor, depth, descriptor_filter)
780

781 782 783 784 785 786 787 788 789 790
        self.add_descriptors_to_cache(descriptors)

    @classmethod
    def cache_for_descriptor_descendents(cls, course_id, user, descriptor, depth=None,
                                         descriptor_filter=lambda descriptor: True,
                                         select_for_update=False, asides=None):
        """
        course_id: the course in the context of which we want StudentModules.
        user: the django user for whom to load modules.
        descriptor: An XModuleDescriptor
791 792 793
        depth is the number of levels of descendant modules to load StudentModules for, in addition to
            the supplied descriptor. If depth is None, load all descendant StudentModules
        descriptor_filter is a function that accepts a descriptor and return whether the field data
794
            should be cached
795
        select_for_update: Ignored
796 797 798 799
        """
        cache = FieldDataCache([], course_id, user, select_for_update, asides=asides)
        cache.add_descriptor_descendents(descriptor, depth, descriptor_filter)
        return cache
800

801
    def _fields_to_cache(self, descriptors):
802 803 804 805
        """
        Returns a map of scopes to fields in that scope that should be cached
        """
        scope_map = defaultdict(set)
806
        for descriptor in descriptors:
Calen Pennington committed
807
            for field in descriptor.fields.values():
808 809 810
                scope_map[field.scope].add(field)
        return scope_map

811 812
    @contract(key=DjangoKeyValueStore.Key)
    def get(self, key):
813
        """
814 815 816 817 818 819 820
        Load the field value specified by `key`.

        Arguments:
            key (`DjangoKeyValueStore.Key`): The field value to load

        Returns: The found value
        Raises: KeyError if key isn't found in the cache
821
        """
822 823 824 825 826 827 828 829 830

        if key.scope.user == UserScope.ONE and not self.user.is_anonymous():
            # If we're getting user data, we expect that the key matches the
            # user we were constructed for.
            assert key.user_id == self.user.id

        if key.scope not in self.cache:
            raise KeyError(key.field_name)

831
        return self.cache[key.scope].get(key)
832

833 834 835 836 837 838 839 840 841 842
    @contract(kv_dict="dict(DjangoKeyValueStore_Key: *)")
    def set_many(self, kv_dict):
        """
        Set all of the fields specified by the keys of `kv_dict` to the values
        in that dict.

        Arguments:
            kv_dict (dict): dict mapping from `DjangoKeyValueStore.Key`s to field values
        Raises: DatabaseError if any fields fail to save
        """
843

844
        saved_fields = []
845 846
        by_scope = defaultdict(dict)
        for key, value in kv_dict.iteritems():
847 848 849 850 851 852 853 854 855

            if key.scope.user == UserScope.ONE and not self.user.is_anonymous():
                # If we're getting user data, we expect that the key matches the
                # user we were constructed for.
                assert key.user_id == self.user.id

            if key.scope not in self.cache:
                continue

856 857 858
            by_scope[key.scope][key] = value

        for scope, set_many_data in by_scope.iteritems():
859
            try:
860 861
                self.cache[scope].set_many(set_many_data)
                # If save is successful on these fields, add it to
862
                # the list of successful saves
863 864 865 866
                saved_fields.extend(key.field_name for key in set_many_data)
            except KeyValueMultiSaveError as exc:
                log.exception('Error saving fields %r', [key.field_name for key in set_many_data])
                raise KeyValueMultiSaveError(saved_fields + exc.saved_field_names)
867

868 869 870 871 872 873 874 875 876 877
    @contract(key=DjangoKeyValueStore.Key)
    def delete(self, key):
        """
        Delete the value specified by `key`.

        Arguments:
            key (`DjangoKeyValueStore.Key`): The field value to delete

        Raises: KeyError if key isn't found in the cache
        """
878 879 880 881 882 883 884 885 886

        if key.scope.user == UserScope.ONE and not self.user.is_anonymous():
            # If we're getting user data, we expect that the key matches the
            # user we were constructed for.
            assert key.user_id == self.user.id

        if key.scope not in self.cache:
            raise KeyError(key.field_name)

887
        self.cache[key.scope].delete(key)
888

889 890 891 892 893 894 895 896 897 898
    @contract(key=DjangoKeyValueStore.Key, returns=bool)
    def has(self, key):
        """
        Return whether the specified `key` is set.

        Arguments:
            key (`DjangoKeyValueStore.Key`): The field value to delete

        Returns: bool
        """
899 900 901 902 903 904 905 906 907

        if key.scope.user == UserScope.ONE and not self.user.is_anonymous():
            # If we're getting user data, we expect that the key matches the
            # user we were constructed for.
            assert key.user_id == self.user.id

        if key.scope not in self.cache:
            return False

908
        return self.cache[key.scope].has(key)
909

910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
    @contract(key=DjangoKeyValueStore.Key, returns="datetime|None")
    def last_modified(self, key):
        """
        Return when the supplied field was changed.

        Arguments:
            key (`DjangoKeyValueStore.Key`): The field value to delete

        Returns: datetime if there was a modified date, or None otherwise
        """
        if key.scope.user == UserScope.ONE and not self.user.is_anonymous():
            # If we're getting user data, we expect that the key matches the
            # user we were constructed for.
            assert key.user_id == self.user.id

        if key.scope not in self.cache:
            return None

        return self.cache[key.scope].last_modified(key)
929 930 931

    def __len__(self):
        return sum(len(cache) for cache in self.cache.values())
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


class ScoresClient(object):
    """
    Basic client interface for retrieving Score information.

    Eventually, this should read and write scores, but at the moment it only
    handles the read side of things.
    """
    Score = namedtuple('Score', 'correct total')

    def __init__(self, course_key, user_id):
        self.course_key = course_key
        self.user_id = user_id
        self._locations_to_scores = {}
        self._has_fetched = False

    def __contains__(self, location):
        """Return True if we have a score for this location."""
        return location in self._locations_to_scores

    def fetch_scores(self, locations):
        """Grab score information."""
        scores_qset = StudentModule.objects.filter(
            student_id=self.user_id,
            course_id=self.course_key,
            module_state_key__in=set(locations),
        )
        # Locations in StudentModule don't necessarily have course key info
        # attached to them (since old mongo identifiers don't include runs).
        # So we have to add that info back in before we put it into our lookup.
        self._locations_to_scores.update({
            UsageKey.from_string(location).map_into_course(self.course_key): self.Score(correct, total)
            for location, correct, total
            in scores_qset.values_list('module_state_key', 'grade', 'max_grade')
        })
        self._has_fetched = True

    def get(self, location):
        """
        Get the score for a given location, if it exists.

        If we don't have a score for that location, return `None`. Note that as
        convention, you should be passing in a location with full course run
        information.
        """
        if not self._has_fetched:
            raise ValueError(
                "Tried to fetch location {} from ScoresClient before fetch_scores() has run."
                .format(location)
            )
983
        return self._locations_to_scores.get(location.replace(version=None, branch=None))
984 985

    @classmethod
986 987 988 989
    def create_for_locations(cls, course_id, user_id, scorable_locations):
        """Create a ScoresClient with pre-fetched data for the given locations."""
        client = cls(course_id, user_id)
        client.fetch_scores(scorable_locations)
990
        return client
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010


# @contract(user_id=int, usage_key=UsageKey, score="number|None", max_score="number|None")
def set_score(user_id, usage_key, score, max_score):
    """
    Set the score and max_score for the specified user and xblock usage.
    """
    student_module, created = StudentModule.objects.get_or_create(
        student_id=user_id,
        module_state_key=usage_key,
        course_id=usage_key.course_key,
        defaults={
            'grade': score,
            'max_grade': max_score,
        }
    )
    if not created:
        student_module.grade = score
        student_module.max_grade = max_score
        student_module.save()
1011
    return student_module.modified
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027


def get_score(user_id, usage_key):
    """
    Get the score and max_score for the specified user and xblock usage.
    Returns None if not found.
    """
    try:
        student_module = StudentModule.objects.get(
            student_id=user_id,
            module_state_key=usage_key,
            course_id=usage_key.course_key,
        )
    except StudentModule.DoesNotExist:
        return None
    else:
1028
        return student_module