model_data.py 35 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 36
from opaque_keys.edx.block_types import BlockTypeKeyV1
from opaque_keys.edx.asides import AsideUsageKeyV1
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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
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))

    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


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
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):
118
        self._raise_unless_scope_is_allowed(key)
119
        return self._field_data_cache.get(key)
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134

    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

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

139
        self._field_data_cache.set_many(kv_dict)
140 141

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

    def has(self, key):
146 147 148 149 150
        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."""
151
        if key.scope not in self._allowed_scopes:
152
            raise InvalidScopeError(key, self._allowed_scopes)
153 154


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

158

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
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

182 183
    @contract(kvs_key=DjangoKeyValueStore.Key)
    def get(self, kvs_key):
184 185 186 187 188 189 190 191 192
        """
        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
        """
193 194 195 196 197 198 199
        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)
200

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

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

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

217 218 219 220
        Arguments:
            kv_dict (dict): A dictionary mapping :class:`~DjangoKeyValueStore.Key`
                objects to values to set.
        """
221
        saved_fields = []
222 223 224 225
        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)

226
            try:
227 228 229 230 231 232 233 234 235 236 237 238 239 240
                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)

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

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

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
    @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]

267 268 269 270 271 272 273 274 275 276 277 278
    @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

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
    @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

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

    @abstractmethod
300
    def _create_object(self, kvs_key, value):
301 302 303 304 305 306 307
        """
        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
308
            value: What value to record in the field
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
        """
        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()


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

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

        Arguments:
364 365 366
            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.
367
        """
368 369
        block_field_state = self._client.get_many(
            self.user.username,
370 371
            _all_usage_keys(xblocks, aside_types),
        )
372 373
        for user_state in block_field_state:
            self._cache[user_state.block_key] = user_state.state
374

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

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

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

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

        Returns: datetime if there was a modified date, or None otherwise
395
        """
396 397 398 399 400 401 402 403
        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
404

405 406 407 408 409 410 411 412 413
    @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.
        """
414
        pending_updates = defaultdict(dict)
415 416 417
        for kvs_key, value in kv_dict.items():
            cache_key = self._cache_key_for_kvs_key(kvs_key)

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

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

431
    @contract(kvs_key=DjangoKeyValueStore.Key)
432 433 434 435 436 437 438 439 440 441 442 443 444 445
    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)

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

    @contract(kvs_key=DjangoKeyValueStore.Key)
449 450 451 452 453 454 455 456 457
    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
        """
458 459 460
        cache_key = self._cache_key_for_kvs_key(kvs_key)
        if cache_key not in self._cache:
            raise KeyError(kvs_key.field_name)
461

462 463 464
        field_state = self._cache[cache_key]

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

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

470 471 472 473 474 475 476 477 478 479
    @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
        """
480
        cache_key = self._cache_key_for_kvs_key(kvs_key)
481

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

487 488 489 490 491 492 493 494 495 496 497 498
    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

499

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

508
    def _create_object(self, kvs_key, value):
509 510 511 512 513 514 515
        """
        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
516
            value: The value to assign to the new field object
517
        """
518
        return XModuleUserStateSummaryField(
519
            field_name=kvs_key.field_name,
520 521
            usage_id=kvs_key.block_scope_id,
            value=value,
522 523
        )

524 525 526 527 528 529 530
    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:
531
            fields (list of :class:`~Field`): Fields to return values for
532 533 534 535
            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).
        """
536
        return XModuleUserStateSummaryField.objects.chunked_filter(
537
            'usage_id__in',
538
            _all_usage_keys(xblocks, aside_types),
539 540
            field_name__in=set(field.name for field in fields),
        )
541

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

546 547 548 549
        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)
550

551 552 553 554 555 556 557 558 559
    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)

560

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

569
    def _create_object(self, kvs_key, value):
570 571 572 573 574 575 576
        """
        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
577
            value: The value to assign to the new field object
578
        """
579
        return XModuleStudentPrefsField(
580 581 582
            field_name=kvs_key.field_name,
            module_type=BlockTypeKeyV1(kvs_key.block_family, kvs_key.block_scope_id),
            student_id=kvs_key.user_id,
583
            value=value,
584 585
        )

586 587 588 589 590 591 592 593 594 595 596 597
    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).
        """
598
        return XModuleStudentPrefsField.objects.chunked_filter(
599
            'module_type__in',
600
            _all_block_types(xblocks, aside_types),
601
            student=self.user.pk,
602 603
            field_name__in=set(field.name for field in fields),
        )
604

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

609 610 611 612
        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)
613

614 615 616 617 618 619 620 621 622
    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)

623

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

632
    def _create_object(self, kvs_key, value):
633 634 635 636 637 638 639
        """
        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
640
            value: The value to assign to the new field object
641
        """
642
        return XModuleStudentInfoField(
643 644
            field_name=kvs_key.field_name,
            student_id=kvs_key.user_id,
645
            value=value,
646 647
        )

648 649 650 651 652 653 654 655 656 657 658 659
    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).
        """
660
        return XModuleStudentInfoField.objects.filter(
661
            student=self.user.pk,
662 663
            field_name__in=set(field.name for field in fields),
        )
664

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

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

674 675 676 677 678 679 680 681
    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
682

683

Calen Pennington committed
684
class FieldDataCache(object):
685 686
    """
    A cache of django model objects needed to supply the data
687
    for a module and its descendants
688
    """
689
    def __init__(self, descriptors, course_id, user, select_for_update=False, asides=None):
690
        """
691 692 693 694 695 696
        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
697
        descriptors: A list of XModuleDescriptors.
698 699
        course_id: The id of the current course
        user: The user for which to cache data
700
        select_for_update: Ignored
701
        asides: The list of aside types to load, or None to prefetch no asides.
702
        """
703 704 705 706 707
        if asides is None:
            self.asides = []
        else:
            self.asides = asides

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

712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
        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,
            ),
        }
727
        self.scorable_locations = set()
728 729 730 731 732 733 734
        self.add_descriptors_to_cache(descriptors)

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

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

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

        Arguments:
            descriptor: An XModuleDescriptor
748 749 750
            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
751
                should be cached
752 753 754
        """

        def get_child_descriptors(descriptor, depth, descriptor_filter):
755 756 757 758 759 760 761 762 763
            """
            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
            """
764 765 766 767 768 769 770 771
            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

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

            return descriptors

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

780 781 782 783 784 785 786 787 788 789
        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
790 791 792
        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
793
            should be cached
794
        select_for_update: Ignored
795 796 797 798
        """
        cache = FieldDataCache([], course_id, user, select_for_update, asides=asides)
        cache.add_descriptor_descendents(descriptor, depth, descriptor_filter)
        return cache
799

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

810 811
    @contract(key=DjangoKeyValueStore.Key)
    def get(self, key):
812
        """
813 814 815 816 817 818 819
        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
820
        """
821 822 823 824 825 826 827 828 829

        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)

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

832 833 834 835 836 837 838 839 840 841
    @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
        """
842

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

            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

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

        for scope, set_many_data in by_scope.iteritems():
858
            try:
859 860
                self.cache[scope].set_many(set_many_data)
                # If save is successful on these fields, add it to
861
                # the list of successful saves
862 863 864 865
                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)
866

867 868 869 870 871 872 873 874 875 876
    @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
        """
877 878 879 880 881 882 883 884 885

        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)

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

888 889 890 891 892 893 894 895 896 897
    @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
        """
898 899 900 901 902 903 904 905 906

        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

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

909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
    @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)
928 929 930

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


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):
        """Basic constructor. from_field_data_cache() is more appopriate for most uses."""
        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)
            )
        return self._locations_to_scores.get(location)

    @classmethod
    def from_field_data_cache(cls, fd_cache):
        """Create a ScoresClient from a populated FieldDataCache."""
        client = cls(fd_cache.course_id, fd_cache.user.id)
        client.fetch_scores(fd_cache.scorable_locations)
        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()