dynamodb-mock / ddbmock / database / table.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
# -*- coding: utf-8 -*-

from .key import Key, PrimaryKey
from .item import Item, ItemSize
from .storage import Store
from collections import defaultdict, namedtuple
from threading import Lock
from ddbmock import config
from ddbmock.errors import ValidationException, LimitExceededException, ResourceInUseException
from ddbmock.utils import schedule_action
import time, copy, datetime

# All validations are performed on *incomming* data => already done :)

# items: array
# size: ItemSize
Results = namedtuple('Results', ['items', 'size', 'last_key', 'scanned'])

class Table(object):
    """
    Table abstraction. Actual :py:class:`ddbmock.database.item.Item` are stored
    in :py:attr:`store`.
    """
    def __init__(self, name, rt, wt, hash_key, range_key, status='CREATING'):
        """
        Create a new ``Table``. When manually creating a table, make sure you
        registered it in :py:class:`ddbmock.database.db.DynamoDB` with a something
        like ``dynamodb.data[name] = Table(name, "...")``.

        Even though there are :py:const:`DELAY_CREATING` seconds before the status
        is updated to ``ACTIVE``, the table is immediately available. This is a
        slight difference with real DynamooDB to ease unit and functionnal tests.

        :param name: Valid table name. No further checks are performed.
        :param rt: Provisioned read throughput.
        :param wt: Provisioned write throughput.
        :param hash_key: :py:class:`ddbmock.database.key.Key` instance describe the ``hash_key``
        :param hash_key: :py:class:`ddbmock.database.key.Key` instance describe the ``range_key`` or ``None`` if table has no ``range_key``
        :param status: (optional) Valid initial table status. If Table needd to be avaible immediately, use ``ACTIVE``, otherwise, leave default value.

        .. note:: ``rt`` and ``wt`` are only used by ``DescribeTable`` and ``UpdateTable``. No throttling is nor will ever be done.
        """
        self.name = name
        self.rt = rt
        self.wt = wt
        self.hash_key = hash_key
        self.range_key = range_key
        self.status = status

        self.store = Store(name)
        self.write_lock = Lock()

        self.creation_time = time.time()
        self.last_increase_time = 0
        self.last_decrease_time = 0
        self.count = 0

        schedule_action(config.DELAY_CREATING, self.activate)

    def truncate(self):
        """
        Remove all Items from this table. This is like a reset. Might be very
        usefull in unit and functional tests.
        """
        self.store.truncate()

    def delete(self):
        """
        If the table was ``ACTIVE``, update its state to ``DELETING``. This is
        not a destructor, only a sate updater and the Table instance will still
        be valid afterward. In all othercases, raise :py:exc:`ddbmock.errors.ResourceInUseException.`

        If you want to perform the full table delete cycle, please use
        :py:meth:`ddbmock.database.db.DynamoDB.delete_table()` instead

        :raises: :py:exc:`ddbmock.errors.ResourceInUseException` is the table was not in ``Active`` state
        """
        if self.status != "ACTIVE":
            raise ResourceInUseException("Table {} is in {} state. Can not DELETE.".format(self.name, self.status))

        self.status = "DELETING"

    def activate(self):
        """
        Unconditionnaly set Table status to ``ACTIVE``. This method is automatically
        called by the constructor once :py:const:`DELAY_CREATING` is over.
        """
        self.status = "ACTIVE"

    def update_throughput(self, rt, wt):
        """
        Update table throughput. Same conditions and limitations as real DynamoDB
        applies:

        - No more that 1 decrease operation per UTC day.
        - No more than doubling throughput at once.
        - Table must be in ``ACTIVE`` state.

        Table status is then set to ``UPDATING`` until :py:const:`DELAY_UPDATING`
        delay is over. Like real DynamoDB, the Table can still be used during
        this period

        :param rt: New read throughput
        :param wt: New write throughput

        :raises: :py:exc:`ddbmock.errors.ResourceInUseException` if table was not in ``ACTIVE`` state
        :raises: :py:exc:`ddbmock.errors.LimitExceededException` if the other above conditions are not met.

        """
        if self.status != "ACTIVE":
            raise ResourceInUseException("Table {} is in {} state. Can not UPDATE.".format(self.name, self.status))

        # is decrease ?
        if self.rt > rt or self.wt > wt:
            current_time = time.time()
            current_date = datetime.date.fromtimestamp(current_time)
            last_decrease = datetime.date.fromtimestamp(self.last_decrease_time)
            if (current_date - last_decrease).days < config.MIN_TP_DEC_INTERVAL:
                last = datetime.datetime.fromtimestamp(self.last_decrease_time)
                current = datetime.datetime.fromtimestamp(current_time)
                raise LimitExceededException("Subscriber limit exceeded: Provisioned throughput can be decreased only once within the {} day. Last decrease time: Tuesday, {}. Request time: {}".format(config.MIN_TP_DEC_INTERVAL, last, current))
            self.last_decrease_time = current_time

        # is increase ?
        if self.rt < rt or self.wt < wt:
            if (rt - self.rt)/float(self.rt)*100 > config.MAX_TP_INC_CHANGE:
                raise LimitExceededException('Requested provisioned throughput change is not allowed. The ReadCapacityUnits change must be at most {} percent of current value. Current ReadCapacityUnits provisioned for the table: {}. Requested ReadCapacityUnits: {}.'.format(config.MAX_TP_INC_CHANGE, self.rt, rt))
            if (wt - self.wt)/float(self.wt)*100 > config.MAX_TP_INC_CHANGE:
                raise LimitExceededException('Requested provisioned throughput change is not allowed. The WriteCapacityUnits change must be at most {} percent of current value. Current WriteCapacityUnits provisioned for the table: {}. Requested WriteCapacityUnits: {}.'.format(config.MAX_TP_INC_CHANGE, self.wt, wt))
            self.last_increase_time = time.time()

        # real work
        self.status = "UPDATING"

        self.rt = rt
        self.wt = wt

        schedule_action(config.DELAY_UPDATING, self.activate)

    def delete_item(self, key, expected):
        """
        Delete item at ``key`` from the databse provided that it matches ``expected``
        values.

        This operation is atomic and blocks all other pending write operations.

        :param key: Raw DynamoDB request hash and range key dict.
        :param expected: Raw DynamoDB request conditions.

        :return: deepcopy of :py:class:`ddbmock.database.item.Item` as it was before deletion.

        :raises: :py:exc:`ddbmock.errors.ConditionalCheckFailedException` if conditions are not met.
        """
        key = Item(key)
        hash_key = key.read_key(self.hash_key, u'HashKeyElement')
        range_key = key.read_key(self.range_key, u'RangeKeyElement')

        with self.write_lock:
            try:
                old = copy.deepcopy(self.store[hash_key, range_key])
            except KeyError:
                return Item()

            old.assert_match_expected(expected)
            del self.store[hash_key, range_key]

        self.count -= 1
        return old

    def update_item(self, key, actions, expected):
        """
        Apply ``actions`` to item at ``key`` provided that it matches ``expected``.

        This operation is atomic and blocks all other pending write operations.

        :param key: Raw DynamoDB request hash and range key dict.
        :param actions: Raw DynamoDB request actions.
        :param expected: Raw DynamoDB request conditions.

        :return: both deepcopies of :py:class:`ddbmock.database.item.Item` as it was (before, after) the update.

        :raises: :py:exc:`ddbmock.errors.ConditionalCheckFailedException` if conditions are not met.
        :raises: :py:exc:`ddbmock.errors.ValidationException` if ``actions`` attempted to modify the key or the resulting Item is biggere than :py:const:`config.MAX_ITEM_SIZE`
        """
        key = Item(key)
        hash_key = key.read_key(self.hash_key, u'HashKeyElement', max_size=config.MAX_HK_SIZE)
        range_key = key.read_key(self.range_key, u'RangeKeyElement', max_size=config.MAX_RK_SIZE)

        with self.write_lock:
            # Need a deep copy as we will *modify* it
            try:
                old = self.store[hash_key, range_key]
                new = copy.deepcopy(old)
                old.assert_match_expected(expected)
            except KeyError:
                # Item was not in the DB yet
                old = Item()
                new = Item()
                self.count += 1
                # append the keys
                new[self.hash_key.name] = key['HashKeyElement']
                if self.range_key is not None:
                    new[self.range_key.name] = key['RangeKeyElement']


            # Make sure we are not altering a key
            if self.hash_key.name in actions:
                raise ValidationException("UpdateItem can not alter the hash_key.")
            if self.range_key is not None and self.range_key.name in actions:
                raise ValidationException("UpdateItem can not alter the range_key.")

            new.apply_actions(actions)
            self.store[hash_key, range_key] = new

            size = new.get_size()
            if size > config.MAX_ITEM_SIZE:
                self.store[hash_key, range_key] = old  # roll back
                raise ValidationException("Items must be smaller than {} bytes. Got {} after applying update".format(config.MAX_ITEM_SIZE, size))

        return old, new

    def put(self, item, expected):
        """
        Save ``item`` in the database provided that ``expected`` matches. Even
        though DynamoDB ``UpdateItem`` operation only supports returning ``ALL_OLD``
        or ``NONE``, this method returns both ``old`` and ``new`` values as the
        throughput, computed in the view, takes the maximum of both size into
        account.

        This operation is atomic and blocks all other pending write operations.

        :param item: Raw DynamoDB request item.
        :param expected: Raw DynamoDB request conditions.

        :return: both deepcopies of :py:class:`ddbmock.database.item.Item` as it was (before, after) the update or empty item if not found.

        :raises: :py:exc:`ddbmock.errors.ConditionalCheckFailedException` if conditions are not met.
        """
        item = Item(item)

        if item.get_size() > config.MAX_ITEM_SIZE:
            raise ValidationException("Items must be smaller than {} bytes. Got {}".format(config.MAX_ITEM_SIZE, item.get_size()))

        hash_key = item.read_key(self.hash_key, max_size=config.MAX_HK_SIZE)
        range_key = item.read_key(self.range_key, max_size=config.MAX_RK_SIZE)

        with self.write_lock:
            try:
                old = self.store[hash_key, range_key]
                old.assert_match_expected(expected)
            except KeyError:
                # Item was not in the DB yet
                self.count += 1
                old = Item()

            self.store[hash_key, range_key] = item
            new = copy.deepcopy(item)

        return old, new

    def get(self, key, fields):
        """
        Get ``fields`` from :py:class:`ddbmock.database.item.Item` at ``key``.

        :param key: Raw DynamoDB request key.
        :param fields: Raw DynamoDB request array of field names to return. Empty to return all.

        :return: reference to :py:class:`ddbmock.database.item.Item` at ``key`` or ``None`` when not found

        :raises: :py:exc:`ddbmock.errors.ValidationException` if a ``range_key`` was provided while table has none.
        """
        key = Item(key)
        hash_key = key.read_key(self.hash_key, u'HashKeyElement')
        range_key = key.read_key(self.range_key, u'RangeKeyElement')

        if self.range_key is None and u'RangeKeyElement' in key:
            raise ValidationException("Table {} has no range_key".format(self.name))

        try:
            item = self.store[hash_key, range_key]
            return item.filter(fields)
        except KeyError:
            # Item was not in the DB yet
            return None

    def query(self, hash_key, rk_condition, fields, start, reverse, limit):
        """
        Return ``fields`` of all items with provided ``hash_key`` whose ``range_key``
        matches ``rk_condition``.

        :param hash_key: Raw DynamoDB request hash_key.
        :param rk_condition: Raw DynamoDB request ``range_key`` condition.
        :param fields: Raw DynamoDB request array of field names to return. Empty to return all.
        :param start: Raw DynamoDB request key of the first item to scan. Empty array to indicate first item.
        :param reverse: Set to ``True`` to parse the range keys backward.
        :param limit: Maximum number of items to return in this batch. Set to 0 or less for no maximum.

        :return: Results(results, cumulated_size, last_key)

        :raises: :py:exc:`ddbmock.errors.ValidationException` if ``start['HashKeyElement']`` is not ``hash_key``
        """
        #FIXME: naive implementation
        #FIXME: what if an item disappears during the operation ?
        #TODO:
        # - size limit

        hash_value = self.hash_key.read(hash_key)
        rk_name = self.range_key.name
        size = ItemSize(0)
        good_item_count = 0
        results = []
        lek = None

        if start and start['HashKeyElement'] != hash_key:
            raise ValidationException("'HashKeyElement' element of 'ExclusiveStartKey' must be the same as the hash_key. Expected {}, got {}".format(hash_key, start['HashKeyElement']))

        try:
            data = self.store[hash_value, None]
        except KeyError:
            # fix #9: return empty result set if first key does not exist
            return Results(results, size, lek, -1)

        keys = sorted(data.keys())

        if reverse:
            keys.reverse()

        if start:
            first_key = self.range_key.read(start['RangeKeyElement'])
            index = keys.index(first_key) + 1  # May raise ValueError but that's OK
            keys = keys[index:]

        for key in keys:
            item = data[key]

            if item.field_match(rk_name, rk_condition):
                good_item_count += 1
                size += item.get_size()
                results.append(item.filter(fields))

            if good_item_count == limit:
                lek = {
                    u'HashKeyElement': hash_key,
                    u'RangeKeyElement': item[rk_name],
                }
                break

        return Results(results, size, lek, -1)

    def scan(self, scan_conditions, fields, start, limit):
        """
        Return ``fields`` of all items matching ``scan_conditions``. No matter the
        ``start`` key, ``scan`` allways starts from teh beginning so that it might
        be quite slow.

        :param scan_conditions: Raw DynamoDB request conditions.
        :param fields: Raw DynamoDB request array of field names to return. Empty to return all.
        :param start: Raw DynamoDB request key of the first item to scan. Empty array to indicate first item.
        :param limit: Maximum number of items to return in this batch. Set to 0 or less for no maximum.

        :return: Results(results, cumulated_size, last_key, scanned_count)
        """
        #FIXME: naive implementation (too)
        #TODO:
        # - esk
        # - size limit

        size = ItemSize(0)
        scanned = 0
        lek = {}
        results = []
        skip = start is not None
        hk_name = self.hash_key.name
        rk_name = self.range_key.name if self.range_key else None

        for item in self.store:
            # first, skip all items before start
            if skip:
                if start['HashKeyElement'] != item[hk_name]:
                    continue
                if rk_name and start['RangeKeyElement'] != item[rk_name]:
                    continue
                skip = False
                continue

            # match filters ?
            if item.match(scan_conditions):
                results.append(item.filter(fields))

            # update stats
            size += item.get_size()
            scanned += 1

            # quit ?
            if scanned == limit:
                lek[u'HashKeyElement'] = item[hk_name]
                if rk_name:
                    lek[u'RangeKeyElement'] = item[rk_name]
                break

        return Results(results, size, lek, scanned)

    @classmethod
    def from_dict(cls, data):
        """
        Alternate constructor which deciphers raw DynamoDB request data before
        ultimately calling regular ``__init__`` method.

        See :py:meth:`__init__` for more insight.

        :param data: raw DynamoDB request data.

        :return: fully initialized :py:class:`Table` instance
        """
        hash_key = PrimaryKey.from_dict(data[u'KeySchema'][u'HashKeyElement'])
        range_key = None
        if u'RangeKeyElement' in data[u'KeySchema']:
            range_key = PrimaryKey.from_dict(data[u'KeySchema'][u'RangeKeyElement'])

        return cls( data[u'TableName'],
                    data[u'ProvisionedThroughput'][u'ReadCapacityUnits'],
                    data[u'ProvisionedThroughput'][u'WriteCapacityUnits'],
                    hash_key,
                    range_key,
                  )

    def get_size(self):
        """
        Compute the whole table size using the same rules as the real DynamoDB.
        Actual memory usage in ddbmock will be much higher due to dict and Python
        overheadd.

        .. note:: Real DynamoDB updates this result every 6 hours or so while this is an "on demand" call.

        :return: cumulated size of all items following DynamoDB size computation.
        """
        # TODO: update size only every 6 hours
        size = 0

        for item in self.store:
            size += item.get_size().with_indexing_overhead()

        return size

    def to_dict(self, verbose=True):
        """
        Serialize this table to DynamoDB compatible format. Every fields are
        realistic, including the ``TableSizeBytes`` which relies on
        :py:meth:`get_size.`

        Some DynamoDB requests only send a minimal version of Table metadata. to
        reproduce this behavior, just set ``verbose`` to ``False``.

        :param verbose: Set to ``False`` to skip table size computation.

        :return: Serialized version of table metadata compatible with DynamoDB API syntax.
        """

        ret = {
            "CreationDateTime": self.creation_time,
            "KeySchema": {
                "HashKeyElement": self.hash_key.to_dict(),
            },
            "ProvisionedThroughput": {
                "ReadCapacityUnits": self.rt,
                "WriteCapacityUnits": self.wt,
            },
            "TableName": self.name,
            "TableStatus": self.status
        }

        if verbose:
            ret[u'ItemCount'] = self.count
            ret[u'TableSizeBytes'] = self.get_size()

        if self.last_increase_time:
            ret[u'ProvisionedThroughput'][u'LastIncreaseDateTime'] = self.last_increase_time
        if self.last_decrease_time:
            ret[u'ProvisionedThroughput'][u'LastDecreaseDateTime'] = self.last_decrease_time

        if self.range_key is not None:
            ret[u'KeySchema'][u'RangeKeyElement'] = self.range_key.to_dict()

        return ret

    # these 2 functions helps to pickle table schema (If store supports it)
    # please note that only the schema is persisted, not the state
    def __getstate__(self):
        return (
            self.name,
            self.rt,
            self.wt,
            self.hash_key,
            self.range_key,
            'ACTIVE',
        )

    def __setstate__(self, state):
        self.__init__(*state)  # quick and dirty (tm), but it does the job
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.