1# Copyright (C) 2010 Google Inc. All rights reserved.
2#
3# Redistribution and use in source and binary forms, with or without
4# modification, are permitted provided that the following conditions are
5# met:
6#
7#     * Redistributions of source code must retain the above copyright
8# notice, this list of conditions and the following disclaimer.
9#     * Redistributions in binary form must reproduce the above
10# copyright notice, this list of conditions and the following disclaimer
11# in the documentation and/or other materials provided with the
12# distribution.
13#     * Neither the name of Google Inc. nor the names of its
14# contributors may be used to endorse or promote products derived from
15# this software without specific prior written permission.
16#
17# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29from google.appengine.ext import db
30
31from datetime import timedelta, datetime
32import time
33
34from model.queuepropertymixin import QueuePropertyMixin
35
36
37class ActiveWorkItems(db.Model, QueuePropertyMixin):
38    queue_name = db.StringProperty()
39    item_ids = db.ListProperty(int)
40    item_dates = db.ListProperty(float)
41    date = db.DateTimeProperty(auto_now_add=True)
42
43    # The id/date pairs should probably just be their own class.
44    def _item_time_pairs(self):
45        return zip(self.item_ids, self.item_dates)
46
47    def _set_item_time_pairs(self, pairs):
48        if pairs:
49            # The * operator raises on an empty list.
50            # db.Model does not tuples, we have to make lists.
51            self.item_ids, self.item_dates = map(list, zip(*pairs))
52        else:
53            self.item_ids = []
54            self.item_dates = []
55
56    def _append_item_time_pair(self, pair):
57        self.item_ids.append(pair[0])
58        self.item_dates.append(pair[1])
59
60    def _remove_item(self, item_id):
61        nonexpired_pairs = [pair for pair in self._item_time_pairs() if pair[0] != item_id]
62        self._set_item_time_pairs(nonexpired_pairs)
63
64    @classmethod
65    def key_for_queue(cls, queue_name):
66        return "active-work-items-%s" % (queue_name)
67
68    @classmethod
69    def lookup_by_queue(cls, queue_name):
70        return cls.get_or_insert(key_name=cls.key_for_queue(queue_name), queue_name=queue_name)
71
72    @staticmethod
73    def _expire_item(key, item_id):
74        active_work_items = db.get(key)
75        active_work_items._remove_item(item_id)
76        active_work_items.put()
77
78    def expire_item(self, item_id):
79        return db.run_in_transaction(self._expire_item, self.key(), item_id)
80
81    def deactivate_expired(self, now):
82        one_hour_ago = time.mktime((now - timedelta(minutes=60)).timetuple())
83        nonexpired_pairs = [pair for pair in self._item_time_pairs() if pair[1] > one_hour_ago]
84        self._set_item_time_pairs(nonexpired_pairs)
85
86    def next_item(self, work_item_ids, now):
87        for item_id in work_item_ids:
88            if item_id not in self.item_ids:
89                self._append_item_time_pair([item_id, time.mktime(now.timetuple())])
90                return item_id
91        return None
92
93    def time_for_item(self, item_id):
94        for active_item_id, time in self._item_time_pairs():
95            if active_item_id == item_id:
96                return datetime.fromtimestamp(time)
97        return None
98