-
Notifications
You must be signed in to change notification settings - Fork 64
/
context.py
701 lines (544 loc) · 22.6 KB
/
context.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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
# -*- coding: utf-8 -*-
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Context for currently running tasks and transactions."""
import collections
import contextlib
import contextvars
import itertools
import os
import threading
import uuid
from google.cloud.ndb import _eventloop
from google.cloud.ndb import exceptions
from google.cloud.ndb import key as key_module
class _ContextIds:
"""Iterator which generates a sequence of context ids.
Useful for debugging complicated interactions among concurrent processes and
threads.
Each value in the sequence is a string that include the machine's "node", acquired
via `uuid.getnode()`, the current process id, and a sequence number which increases
monotonically starting from one in each process. The combination of all three is
sufficient to uniquely identify the context in which a particular piece of code is
being run. Each context, as it is created, is assigned the next id in this sequence.
The context id is used by `utils.logging_debug` to grant insight into where a debug
logging statement is coming from in a cloud environment.
"""
def __init__(self):
self.prefix = "{}-{}-".format(uuid.getnode(), os.getpid())
self.counter = itertools.count(1)
self.lock = threading.Lock()
def __next__(self):
with self.lock:
sequence_number = next(self.counter)
return self.prefix + str(sequence_number)
next = __next__ # Python 2.7
_context_ids = _ContextIds()
class _LocalState:
"""Thread local state."""
def __init__(self):
self._toplevel_context = contextvars.ContextVar(
"_toplevel_context", default=None
)
self._context = contextvars.ContextVar("_context", default=None)
@property
def context(self):
return self._context.get()
@context.setter
def context(self, value):
self._context.set(value)
@property
def toplevel_context(self):
return self._toplevel_context.get()
@toplevel_context.setter
def toplevel_context(self, value):
self._toplevel_context.set(value)
_state = _LocalState()
def get_context(raise_context_error=True):
"""Get the current context.
This function should be called within a context established by
:meth:`google.cloud.ndb.client.Client.context`.
Args:
raise_context_error (bool): If set to :data:`True`, will raise an
exception if called outside of a context. Set this to :data:`False`
in order to have it just return :data:`None` if called outside of a
context. Default: :data:`True`
Returns:
Context: The current context.
Raises:
.ContextError: If called outside of a context
established by :meth:`google.cloud.ndb.client.Client.context` and
``raise_context_error`` is :data:`True`.
"""
context = _state.context
if context:
return context
if raise_context_error:
raise exceptions.ContextError()
def get_toplevel_context(raise_context_error=True):
"""Get the current top level context.
This function should be called within a context established by
:meth:`google.cloud.ndb.client.Client.context`.
The toplevel context is the context created by the call to
:meth:`google.cloud.ndb.client.Client.context`. At times, this context will
be superseded by subcontexts, which are used, for example, during
transactions. This function will always return the top level context
regardless of whether one of these subcontexts is the current one.
Args:
raise_context_error (bool): If set to :data:`True`, will raise an
exception if called outside of a context. Set this to :data:`False`
in order to have it just return :data:`None` if called outside of a
context. Default: :data:`True`
Returns:
Context: The current context.
Raises:
.ContextError: If called outside of a context
established by :meth:`google.cloud.ndb.client.Client.context` and
``raise_context_error`` is :data:`True`.
"""
context = _state.toplevel_context
if context:
return context
if raise_context_error:
raise exceptions.ContextError()
def _default_policy(attr_name, value_type):
"""Factory for producing default policies.
Born of the observation that all default policies are more less the
same—they defer to some attribute on the model class for the key's kind and
expects the value to be either of a particular type or a callable.
Returns:
Callable[[key], value_type]: A policy function suitable for use as a
default policy.
"""
# avoid circular imports on Python 2.7
from google.cloud.ndb import model
def policy(key):
value = None
if key is not None:
kind = key.kind
if callable(kind):
kind = kind()
modelclass = model.Model._kind_map.get(kind)
if modelclass is not None:
policy = getattr(modelclass, attr_name, None)
if policy is not None:
if isinstance(policy, value_type):
value = policy
else:
value = policy(key)
return value
return policy
_default_cache_policy = _default_policy("_use_cache", bool)
"""The default cache policy.
Defers to ``_use_cache`` on the Model class for the key's kind.
See: :meth:`~google.cloud.ndb.context.Context.set_cache_policy`
"""
_default_global_cache_policy = _default_policy("_use_global_cache", bool)
"""The default global cache policy.
Defers to ``_use_global_cache`` on the Model class for the key's kind.
See: :meth:`~google.cloud.ndb.context.Context.set_global_cache_policy`
"""
_default_global_cache_timeout_policy = _default_policy("_global_cache_timeout", int)
"""The default global cache timeout policy.
Defers to ``_global_cache_timeout`` on the Model class for the key's kind.
See: :meth:`~google.cloud.ndb.context.Context.set_global_cache_timeout_policy`
"""
_default_datastore_policy = _default_policy("_use_datastore", bool)
"""The default datastore policy.
Defers to ``_use_datastore`` on the Model class for the key's kind.
See: :meth:`~google.cloud.ndb.context.Context.set_datastore_policy`
"""
_ContextTuple = collections.namedtuple(
"_ContextTuple",
[
"id",
"client",
"namespace",
"eventloop",
"batches",
"commit_batches",
"transaction",
"cache",
"global_cache",
"on_commit_callbacks",
"transaction_complete_callbacks",
"legacy_data",
],
)
class _Context(_ContextTuple):
"""Current runtime state.
Instances of this class hold on to runtime state such as the current event
loop, current transaction, etc. Instances are shallowly immutable, but
contain references to data structures which are mutable, such as the event
loop. A new context can be derived from an existing context using
:meth:`new`.
:class:`Context` is a subclass of :class:`_Context` which provides only
publicly facing interface. The use of two classes is only to provide a
distinction between public and private API.
Arguments:
client (client.Client): The NDB client for this context.
"""
def __new__(
cls,
client,
id=None,
namespace=key_module.UNDEFINED,
eventloop=None,
batches=None,
commit_batches=None,
transaction=None,
cache=None,
cache_policy=None,
global_cache=None,
global_cache_policy=None,
global_cache_timeout_policy=None,
datastore_policy=None,
on_commit_callbacks=None,
transaction_complete_callbacks=None,
legacy_data=True,
retry=None,
rpc_time=None,
wait_time=None,
):
# Prevent circular import in Python 2.7
from google.cloud.ndb import _cache
if id is None:
id = next(_context_ids)
if eventloop is None:
eventloop = _eventloop.EventLoop()
if batches is None:
batches = {}
if commit_batches is None:
commit_batches = {}
# Create a cache and, if an existing cache was passed into this
# method, duplicate its entries.
new_cache = _cache.ContextCache()
if cache:
new_cache.update(cache)
context = super(_Context, cls).__new__(
cls,
id=id,
client=client,
namespace=namespace,
eventloop=eventloop,
batches=batches,
commit_batches=commit_batches,
transaction=transaction,
cache=new_cache,
global_cache=global_cache,
on_commit_callbacks=on_commit_callbacks,
transaction_complete_callbacks=transaction_complete_callbacks,
legacy_data=legacy_data,
)
context.set_cache_policy(cache_policy)
context.set_global_cache_policy(global_cache_policy)
context.set_global_cache_timeout_policy(global_cache_timeout_policy)
context.set_datastore_policy(datastore_policy)
context.set_retry_state(retry)
return context
def new(self, **kwargs):
"""Create a new :class:`_Context` instance.
New context will be the same as context except values from ``kwargs``
will be substituted.
"""
fields = self._fields + tuple(self.__dict__.keys())
state = {
name: getattr(self, name) for name in fields if not name.startswith("_")
}
state.update(kwargs)
return type(self)(**state)
@contextlib.contextmanager
def use(self):
"""Use this context as the current context.
This method returns a context manager for use with the ``with``
statement. Code inside the ``with`` context will see this context as
the current context.
"""
prev_context = _state.context
_state.context = self
if not prev_context:
_state.toplevel_context = self
self.rpc_time = 0
self.wait_time = 0
try:
yield self
finally:
if prev_context:
prev_context.cache.update(self.cache)
else:
_state.toplevel_context = None
_state.context = prev_context
def _use_cache(self, key, options=None):
"""Return whether to use the context cache for this key."""
flag = options.use_cache if options else None
if flag is None:
flag = self.cache_policy(key)
if flag is None:
flag = True
return flag
def _use_global_cache(self, key, options=None):
"""Return whether to use the global cache for this key."""
if self.global_cache is None:
return False
flag = options.use_global_cache if options else None
if flag is None:
flag = self.global_cache_policy(key)
if flag is None:
flag = True
return flag
def _global_cache_timeout(self, key, options):
"""Return global cache timeout (expiration) for this key."""
timeout = None
if options:
timeout = options.global_cache_timeout
if timeout is None:
timeout = self.global_cache_timeout_policy(key)
return timeout
def _use_datastore(self, key, options=None):
"""Return whether to use the Datastore for this key."""
flag = options.use_datastore if options else None
if flag is None:
flag = self.datastore_policy(key)
if flag is None:
flag = True
return flag
class Context(_Context):
"""User management of cache and other policy."""
def clear_cache(self):
"""Clears the in-memory cache.
This does not affect global cache.
"""
self.cache.clear()
def flush(self):
"""Force any pending batch operations to go ahead and run."""
self.eventloop.run()
def get_namespace(self):
"""Return the current context namespace.
If `namespace` isn't set on the context, the client's namespace will be
returned.
Returns:
str: The namespace, or `None`.
"""
if self.namespace is key_module.UNDEFINED:
return self.client.namespace
return self.namespace
def get_cache_policy(self):
"""Return the current context cache policy function.
Returns:
Callable: A function that accepts a
:class:`~google.cloud.ndb.key.Key` instance as a single
positional argument and returns a ``bool`` indicating if it
should be cached. May be :data:`None`.
"""
return self.cache_policy
def get_datastore_policy(self):
"""Return the current context datastore policy function.
Returns:
Callable: A function that accepts a
:class:`~google.cloud.ndb.key.Key` instance as a single
positional argument and returns a ``bool`` indicating if it
should use the datastore. May be :data:`None`.
"""
raise NotImplementedError
def get_global_cache_policy(self):
"""Return the current global cache policy function.
Returns:
Callable: A function that accepts a
:class:`~google.cloud.ndb.key.Key` instance as a single
positional argument and returns a ``bool`` indicating if it
should be cached. May be :data:`None`.
"""
return self.global_cache_policy
get_memcache_policy = get_global_cache_policy # backwards compatibility
def get_global_cache_timeout_policy(self):
"""Return the current policy function global cache timeout (expiration).
Returns:
Callable: A function that accepts a
:class:`~google.cloud.ndb.key.Key` instance as a single
positional argument and returns an ``int`` indicating the
timeout, in seconds, for the key. ``0`` implies the default
timeout. May be :data:`None`.
"""
return self.global_cache_timeout_policy
get_memcache_timeout_policy = get_global_cache_timeout_policy
def set_cache_policy(self, policy):
"""Set the context cache policy function.
Args:
policy (Callable): A function that accepts a
:class:`~google.cloud.ndb.key.Key` instance as a single
positional argument and returns a ``bool`` indicating if it
should be cached. May be :data:`None`.
"""
if policy is None:
policy = _default_cache_policy
elif isinstance(policy, bool):
flag = policy
def policy(key):
return flag
self.cache_policy = policy
def set_datastore_policy(self, policy):
"""Set the context datastore policy function.
Args:
policy (Callable): A function that accepts a
:class:`~google.cloud.ndb.key.Key` instance as a single
positional argument and returns a ``bool`` indicating if it
should use the datastore. May be :data:`None`.
"""
if policy is None:
policy = _default_datastore_policy
elif isinstance(policy, bool):
flag = policy
def policy(key):
return flag
self.datastore_policy = policy
def set_global_cache_policy(self, policy):
"""Set the global cache policy function.
Args:
policy (Callable): A function that accepts a
:class:`~google.cloud.ndb.key.Key` instance as a single
positional argument and returns a ``bool`` indicating if it
should be cached. May be :data:`None`.
"""
if policy is None:
policy = _default_global_cache_policy
elif isinstance(policy, bool):
flag = policy
def policy(key):
return flag
self.global_cache_policy = policy
set_memcache_policy = set_global_cache_policy # backwards compatibility
def set_global_cache_timeout_policy(self, policy):
"""Set the policy function for global cache timeout (expiration).
Args:
policy (Callable): A function that accepts a
:class:`~google.cloud.ndb.key.Key` instance as a single
positional argument and returns an ``int`` indicating the
timeout, in seconds, for the key. ``0`` implies the default
timeout. May be :data:`None`.
"""
if policy is None:
policy = _default_global_cache_timeout_policy
elif isinstance(policy, int):
timeout = policy
def policy(key):
return timeout
self.global_cache_timeout_policy = policy
set_memcache_timeout_policy = set_global_cache_timeout_policy
def get_retry_state(self):
return self._retry
def set_retry_state(self, state):
self._retry = state
def clear_retry_state(self):
self._retry = None
def call_on_commit(self, callback):
"""Call a callback upon successful commit of a transaction.
If not in a transaction, the callback is called immediately.
In a transaction, multiple callbacks may be registered and will be
called once the transaction commits, in the order in which they
were registered. If the transaction fails, the callbacks will not
be called.
If the callback raises an exception, it bubbles up normally. This
means: If the callback is called immediately, any exception it
raises will bubble up immediately. If the call is postponed until
commit, remaining callbacks will be skipped and the exception will
bubble up through the transaction() call. (However, the
transaction is already committed at that point.)
Args:
callback (Callable): The callback function.
"""
if self.in_transaction():
self.on_commit_callbacks.append(callback)
else:
callback()
def call_on_transaction_complete(self, callback):
"""Call a callback upon completion of a transaction.
If not in a transaction, the callback is called immediately.
In a transaction, multiple callbacks may be registered and will be called once
the transaction completes, in the order in which they were registered. Callbacks
are called regardless of whether transaction is committed or rolled back.
If the callback raises an exception, it bubbles up normally. This means: If the
callback is called immediately, any exception it raises will bubble up
immediately. If the call is postponed until commit, remaining callbacks will be
skipped and the exception will bubble up through the transaction() call.
(However, the transaction is already committed or rolled back at that point.)
Args:
callback (Callable): The callback function.
"""
if self.in_transaction():
self.transaction_complete_callbacks.append(callback)
else:
callback()
def in_transaction(self):
"""Get whether a transaction is currently active.
Returns:
bool: :data:`True` if currently in a transaction, otherwise
:data:`False`.
"""
return self.transaction is not None
def in_retry(self):
"""Get whether we are already in a retry block.
Returns:
bool: :data:`True` if currently in a retry block, otherwise
:data:`False`.
"""
return self._retry is not None
def memcache_add(self, *args, **kwargs):
"""Direct pass-through to memcache client. No longer implemented."""
raise exceptions.NoLongerImplementedError()
def memcache_cas(self, *args, **kwargs):
"""Direct pass-through to memcache client. No longer implemented."""
raise exceptions.NoLongerImplementedError()
def memcache_decr(self, *args, **kwargs):
"""Direct pass-through to memcache client. No longer implemented."""
raise exceptions.NoLongerImplementedError()
def memcache_delete(self, *args, **kwargs):
"""Direct pass-through to memcache client. No longer implemented."""
raise exceptions.NoLongerImplementedError()
def memcache_get(self, *args, **kwargs):
"""Direct pass-through to memcache client. No longer implemented."""
raise exceptions.NoLongerImplementedError()
def memcache_gets(self, *args, **kwargs):
"""Direct pass-through to memcache client. No longer implemented."""
raise exceptions.NoLongerImplementedError()
def memcache_incr(self, *args, **kwargs):
"""Direct pass-through to memcache client. No longer implemented."""
raise exceptions.NoLongerImplementedError()
def memcache_replace(self, *args, **kwargs):
"""Direct pass-through to memcache client. No longer implemented."""
raise exceptions.NoLongerImplementedError()
def memcache_set(self, *args, **kwargs):
"""Direct pass-through to memcache client. No longer implemented."""
raise exceptions.NoLongerImplementedError()
def urlfetch(self, *args, **kwargs):
"""Fetch a resource using HTTP. No longer implemented."""
raise exceptions.NoLongerImplementedError()
class ContextOptions(object):
def __init__(self, *args, **kwargs):
raise exceptions.NoLongerImplementedError()
class TransactionOptions(object):
NESTED = 1 # join=False
MANDATORY = 2 # join=True
ALLOWED = 3 # join=True
INDEPENDENT = 4 # join=False
_PROPAGATION = frozenset((NESTED, MANDATORY, ALLOWED, INDEPENDENT))
_JOINABLE = frozenset((MANDATORY, ALLOWED))
_INT_TO_NAME = {
NESTED: "nested",
MANDATORY: "mandatory",
ALLOWED: "allowed",
INDEPENDENT: "independent",
}
class AutoBatcher(object):
def __init__(self, *args, **kwargs):
raise exceptions.NoLongerImplementedError()