This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
/
query_cache.py
372 lines (282 loc) · 11.1 KB
/
query_cache.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
# The contents of this file are subject to the Common Public Attribution
# License Version 1.0. (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://code.reddit.com/LICENSE. The License is based on the Mozilla Public
# License Version 1.1, but Sections 14 and 15 have been added to cover use of
# software over a computer network and provide for limited attribution for the
# Original Developer. In addition, Exhibit A has been modified to be consistent
# with Exhibit B.
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
# the specific language governing rights and limitations under the License.
#
# The Original Code is reddit.
#
# The Original Developer is the Initial Developer. The Initial Developer of
# the Original Code is reddit Inc.
#
# All portions of the code written by reddit are Copyright (c) 2006-2012 reddit
# Inc. All Rights Reserved.
###############################################################################
import random
import datetime
import collections
from pylons import g
from pycassa.system_manager import ASCII_TYPE, UTF8_TYPE
from pycassa.batch import Mutator
from r2.models import Thing
from r2.lib.db import tdb_cassandra
from r2.lib.db.operators import asc
from r2.lib.db.sorts import epoch_seconds
from r2.lib.utils import flatten, to36
from r2.lib.db.tdb_cassandra import json
CONNECTION_POOL = g.cassandra_pools['main']
PRUNE_CHANCE = g.querycache_prune_chance
MAX_CACHED_ITEMS = 1000
LOG = g.log
class ThingTupleComparator(object):
def __init__(self, sorts):
self.sorts = sorts
def __call__(self, t1, t2):
for i, s in enumerate(self.sorts):
# t1 and t2 are tuples of (fullname, *sort_cols), so we
# can get the value to compare right out of the tuple
v1, v2 = t1[i + 1], t2[i + 1]
if v1 != v2:
return cmp(v1, v2) if isinstance(s, asc) else cmp(v2, v1)
#they're equal
return 0
class CachedQueryBase(object):
def __init__(self, sort):
self.sort = sort
self.sort_cols = [s.col for s in self.sort]
self.data = []
self._fetched = False
def fetch(self, force=False, data=None):
if not force and self._fetched:
return
self._fetch()
self._sort_data()
self._fetched = True
def _fetch(self):
raise NotImplementedError()
def _sort_data(self):
comparator = ThingTupleComparator(self.sort_cols)
self.data.sort(cmp=comparator)
def __iter__(self):
self.fetch()
for x in self.data:
yield x[0]
class CachedQuery(CachedQueryBase):
def __init__(self, model, key, sort, filter_fn):
self.model = model
self.key = key
self.sort = sort
self.filter = filter_fn
self.timestamps = None # column timestamps, for safe pruning
super(CachedQuery, self).__init__(sort)
def _make_item_tuple(self, item):
"""Given a single 'item' from the result of a query build the tuple
that will be stored in the query cache. It is effectively the
fullname of the item after passing through the filter plus the
columns of the unfiltered item to sort by."""
filtered_item = self.filter(item)
lst = [filtered_item._fullname]
for col in self.sort_cols:
# take the property of the original
attr = getattr(item, col)
# convert dates to epochs to take less space
if isinstance(attr, datetime.datetime):
attr = epoch_seconds(attr)
lst.append(attr)
return tuple(lst)
def _fetch(self):
self._fetch_multi([self])
@classmethod
def _fetch_multi(self, queries):
by_model = collections.defaultdict(list)
for q in queries:
by_model[q.model].append(q)
cached_queries = {}
for model, queries in by_model.iteritems():
fetched = model.get([q.key for q in queries])
cached_queries.update(fetched)
for q in queries:
cached_query = cached_queries.get(q.key)
if cached_query:
q.data, q.timestamps = cached_query
def _insert(self, mutator, things):
if not things:
return
values = {}
for thing in things:
t = self._make_item_tuple(thing)
values[t[0]] = tuple(t[1:])
self.model.insert(mutator, self.key, values)
def _delete(self, mutator, things):
if not things:
return
fullnames = [self.filter(x)._fullname for x in things]
self.model.remove(mutator, self.key, fullnames)
def _prune(self, mutator):
extraneous_ids = [t[0] for t in self.data[MAX_CACHED_ITEMS:]]
if extraneous_ids:
self.model.remove_if_unchanged(mutator, self.key,
extraneous_ids, self.timestamps)
cf_name = self.model.__name__
query_name = self.key.split('.')[0]
counter_key = "cache.%s.%s" % (cf_name, query_name)
counter = g.stats.get_counter(counter_key)
if counter:
counter.increment('pruned', delta=len(extraneous_ids))
def update(self):
raise NotImplementedError()
@classmethod
def _prune_multi(cls, queries):
cls._fetch_multi(queries)
with Mutator(CONNECTION_POOL) as m:
for q in queries:
q._sort_data()
q._prune(m)
def __hash__(self):
return hash(self.key)
def __eq__(self, other):
return self.key == other.key
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return "%s(%s, %r)" % (self.__class__.__name__,
self.model.__name__, self.key)
class SqlCachedQuery(CachedQuery):
def __init__(self, model, key, query, filter_fn):
self.query = query
# ensure that .update() doesn't fetch more items than we need
self.query._limit = MAX_CACHED_ITEMS
super(SqlCachedQuery, self).__init__(model, key, query._sort,
filter_fn)
def update(self):
things = list(self.query)
with Mutator(CONNECTION_POOL) as m:
self.model.remove(m, self.key, None) # empty the whole row
self._insert(m, things)
class CassandraCachedQuery(CachedQuery):
pass
class MergedCachedQuery(CachedQueryBase):
def __init__(self, queries):
self.queries = queries
if queries:
sort = queries[0].sort
assert all(sort == q.sort for q in queries)
else:
sort = []
super(MergedCachedQuery, self).__init__(sort)
def _fetch(self):
CachedQuery._fetch_multi(self.queries)
self.data = flatten([q.data for q in self.queries])
def update(self):
for q in self.queries:
q.update()
class CachedQueryMutator(object):
def __init__(self):
self.mutator = Mutator(CONNECTION_POOL)
self.to_prune = set()
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.send()
def insert(self, query, things):
if not things:
return
LOG.debug("Inserting %r into query %r", things, query)
query._insert(self.mutator, things)
if (random.random() / len(things)) < PRUNE_CHANCE:
self.to_prune.add(query)
def delete(self, query, things):
if not things:
return
LOG.debug("Deleting %r from query %r", things, query)
query._delete(self.mutator, things)
def send(self):
self.mutator.send()
if self.to_prune:
LOG.debug("Pruning queries %r", self.to_prune)
CachedQuery._prune_multi(self.to_prune)
def filter_identity(x):
return x
def filter_thing2(x):
"""A filter to apply to the results of a relationship query returns
the object of the relationship."""
return x._thing2
def cached_query(model, filter_fn=filter_identity, sort=None):
def cached_query_decorator(fn):
def cached_query_wrapper(*args):
# build the row key from the function name and arguments
row_key_components = [fn.__name__[len('get_'):]]
if len(args) > 0:
# we want to accept either a Thing or a thing's ID at this
# layer, but the query itself should always get just an ID
if isinstance(args[0], Thing):
args = list(args)
args[0] = args[0]._id
thing_id = to36(args[0])
row_key_components.append(thing_id)
row_key_components.extend(str(x) for x in args[1:])
row_key = '.'.join(row_key_components)
if sort:
return CassandraCachedQuery(model, row_key, sort, filter_fn)
else:
# call the wrapped function to get a query
query = fn(*args)
# cached results for everyone!
return SqlCachedQuery(model, row_key, query, filter_fn)
return cached_query_wrapper
return cached_query_decorator
def merged_cached_query(fn):
def merge_wrapper(*args):
queries = fn(*args)
return MergedCachedQuery(queries)
return merge_wrapper
class BaseQueryCache(object):
__metaclass__ = tdb_cassandra.ThingMeta
_connection_pool = 'main'
_extra_schema_creation_args = dict(key_validation_class=ASCII_TYPE,
default_validation_class=UTF8_TYPE)
_compare_with = ASCII_TYPE
_use_db = False
_type_prefix = None
_cf_name = None
@classmethod
def get(cls, keys):
rows = cls._cf.multiget(keys, include_timestamp=True,
column_count=tdb_cassandra.max_column_count)
res = {}
for row, columns in rows.iteritems():
data = []
timestamps = []
for (key, (value, timestamp)) in columns.iteritems():
value = json.loads(value)
data.append((key,) + tuple(value))
timestamps.append((key, timestamp))
res[row] = (data, dict(timestamps))
return res
@classmethod
@tdb_cassandra.will_write
def insert(cls, mutator, key, columns):
updates = dict((key, json.dumps(value))
for key, value in columns.iteritems())
mutator.insert(cls._cf, key, updates)
@classmethod
@tdb_cassandra.will_write
def remove(cls, mutator, key, columns):
mutator.remove(cls._cf, key, columns=columns)
@classmethod
@tdb_cassandra.will_write
def remove_if_unchanged(cls, mutator, key, columns, timestamps):
for col in columns:
mutator.remove(cls._cf, key, columns=[col],
timestamp=timestamps.get(col))
class UserQueryCache(BaseQueryCache):
_use_db = True
class SubredditQueryCache(BaseQueryCache):
_use_db = True