Skip to content

Commit

Permalink
add samples
Browse files Browse the repository at this point in the history
  • Loading branch information
reyang committed Mar 19, 2019
1 parent 447a04b commit 8255e0e
Show file tree
Hide file tree
Showing 4 changed files with 133 additions and 36 deletions.
18 changes: 18 additions & 0 deletions contrib/opencensus-context/examples/py27.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from opencensus.common.runtime_context import RuntimeContext

RuntimeContext.register_slot('correlation_context', lambda: {})

def hello(name):
correlation_context = RuntimeContext.correlation_context.copy()
correlation_context['name'] = name
RuntimeContext.correlation_context = correlation_context

print(RuntimeContext)

if __name__ == '__main__':
print(RuntimeContext)
RuntimeContext.correlation_context['test'] = True
print(RuntimeContext)
hello('hello')
RuntimeContext.clear()
print(RuntimeContext)
34 changes: 34 additions & 0 deletions contrib/opencensus-context/examples/py37.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import asyncio

from opencensus.common.runtime_context import RuntimeContext

RuntimeContext.register_slot('correlation_context', lambda: dict())

async def hello(name):
correlation_context = RuntimeContext.correlation_context.copy()
correlation_context['name'] = name
RuntimeContext.correlation_context = correlation_context

for i in range(3):
print('Hello {} {} {}'.format(
name,
i,
RuntimeContext,
))
await asyncio.sleep(0.1)

async def main():
print(RuntimeContext)
RuntimeContext.correlation_context['test'] = True
print(RuntimeContext)
await asyncio.gather(
hello('foo'),
hello('bar'),
hello('baz'),
)
print(RuntimeContext)
RuntimeContext.clear()
print(RuntimeContext)

if __name__ == '__main__':
asyncio.run(main())
26 changes: 26 additions & 0 deletions contrib/opencensus-context/examples/span.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from opencensus.common.runtime_context import RuntimeContext

RuntimeContext.register_slot('current_span', None)

class Span(object):
def __init__(self, name):
self.name = name
self.parent = RuntimeContext.current_span

def __repr__(self):
return ('{}({})'.format(type(self).__name__, self.name))

def __enter__(self):
RuntimeContext.current_span = self

def __exit__(self, type, value, traceback):
RuntimeContext.current_span = self.parent

if __name__ == '__main__':
print(RuntimeContext)
with Span('foo'):
print(RuntimeContext)
with Span('bar'):
print(RuntimeContext)
print(RuntimeContext)
print(RuntimeContext)
Original file line number Diff line number Diff line change
Expand Up @@ -26,25 +26,59 @@ def clear(cls):
def register_slot(cls, name, default = None):
raise NotImplementedError # pragma: NO COVER

def __init__(self):
pass

def __repr__(self):
return repr(self._slots)
return ('{}({})'
.format(
type(self).__name__,
dict((n, self._slots[n].get()) for n in self._slots)
))

def __getattr__(self, name):
if name not in self._slots:
raise AttributeError('{} is not a registered context slot'.format(name))
slot = self._slots[name]
return slot.get()

def __setattr__(self, name, value):
if name not in self._slots:
raise AttributeError('{} is not a registered context slot'.format(name))
slot = self._slots[name]
slot.set(value)

class _TlsRuntimeContext(_RuntimeContext):
_lock = threading.Lock()
_slots = {}
_tls = threading.local()

class Slot(object):
_tls = threading.local()

def __init__(self, name, default):
self.name = name
self.default = default
self.default = default if callable(default) else (lambda: default)

def clear(self):
setattr(self._tls, self.name, self.default())

def get(self):
try:
return getattr(self._tls, self.name)
except AttributeError:
value = self.default()
self.set(value)
return value

def set(self, value):
setattr(self._tls, self.name, value)

@classmethod
def clear(cls):
with cls._lock:
for name in cls._slots:
slot = self._slots[name]
setattr(cls._tls, name, slot.default)
slot = cls._slots[name]
slot.clear()

@classmethod
def register_slot(cls, name, default = None):
Expand All @@ -53,20 +87,6 @@ def register_slot(cls, name, default = None):
raise ValueError('slot {} already registered'.format(name))
cls._slots[name] = cls.Slot(name, default)

def __init__(self):
pass

def __getattr__(self, name):
if name in self._slots:
slot = self._slots[name]
return getattr(self._tls, name, slot.default)
raise AttributeError('{} is not a registered context slot'.format(name))

def __setattr__(self, name, value):
if name in self._slots:
return setattr(self._tls, name, value)
raise AttributeError('{} is not a registered context slot'.format(name))

class _AsyncRuntimeContext(_RuntimeContext):
_lock = threading.Lock()
_slots = {}
Expand All @@ -76,14 +96,28 @@ def __init__(self, name, default):
import contextvars
self.name = name
self.contextvar = contextvars.ContextVar(name)
self.default = default
self.default = default if callable(default) else (lambda: default)

def clear(self):
self.contextvar.set(self.default())

def get(self):
try:
return self.contextvar.get()
except LookupError:
value = self.default()
self.set(value)
return value

def set(self, value):
self.contextvar.set(value)

@classmethod
def clear(cls):
with cls._lock:
for name in cls._slots:
slot = cls._slots[name]
slot.contextvar.set(slot.default)
slot.clear()

@classmethod
def register_slot(cls, name, default = None):
Expand All @@ -92,21 +126,6 @@ def register_slot(cls, name, default = None):
raise ValueError('slot {} already registered'.format(name))
cls._slots[name] = cls.Slot(name, default)

def __init__(self):
pass

def __getattr__(self, name):
if name in self._slots:
slot = self._slots[name]
return slot.contextvar.get(slot.default)
raise AttributeError('{} is not a registered context slot'.format(name))

def __setattr__(self, name, value):
if name in self._slots:
slot = self._slots[name]
return slot.contextvar.set(value)
raise AttributeError('{} is not a registered context slot'.format(name))

RuntimeContext = _TlsRuntimeContext()

if sys.version_info >= (3, 7):
Expand Down

0 comments on commit 8255e0e

Please sign in to comment.