PK!H 22aiodogstatsd/__init__.pyfrom .client import Client __all__ = ("Client",) PK!b |aaaiodogstatsd/client.pyimport asyncio from asyncio.transports import DatagramTransport from random import random from typing import Optional from aiodogstatsd import protocol, typedefs __all__ = ("Client",) class Client: __slots__ = ( "_host", "_port", "_namespace", "_constant_tags", "_closing", "_protocol", "_queue", "_listen_future", "_listen_future_join", "_read_timeout", "_close_timeout", ) def __init__( self, *, host: str = "localhost", port: int = 9125, namespace: Optional[typedefs.MNamespace] = None, constant_tags: Optional[typedefs.MTags] = None, read_timeout: float = 0.5, close_timeout: Optional[float] = None, ) -> None: """ Initialize a client object. You can pass host and port of the DogStatsD server, namespace to prefix all metric names, constant tags to attach to all metrics. Also, you can specify default read timeout which will be used to read messages from an AsyncIO queue, and you can specify close timeout which will be used as wait time for client closing. """ self._host = host self._port = port self._namespace = namespace self._constant_tags = constant_tags or {} self._closing = False self._protocol = DatagramProtocol() self._queue: asyncio.Queue = asyncio.Queue() self._listen_future: asyncio.Future self._listen_future_join: asyncio.Future = asyncio.Future() self._read_timeout = read_timeout self._close_timeout = close_timeout async def connect(self) -> None: loop = asyncio.get_running_loop() await loop.create_datagram_endpoint( lambda: self._protocol, remote_addr=(self._host, self._port) ) self._listen_future = asyncio.ensure_future(self._listen()) async def close(self) -> None: self._closing = True try: await asyncio.wait_for(self._close(), timeout=self._close_timeout) except asyncio.TimeoutError: pass async def _close(self) -> None: await self._listen_future_join self._listen_future.cancel() await self._protocol.close() def gauge( self, name: typedefs.MName, *, value: typedefs.MValue, tags: Optional[typedefs.MTags] = None, sample_rate: typedefs.MSampleRate = 1, ) -> None: """ Record the value of a gauge, optionally setting tags and a sample rate. """ self._report(name, typedefs.MType.GAUGE, value, tags, sample_rate) def increment( self, name: typedefs.MName, *, value: typedefs.MValue = 1, tags: Optional[typedefs.MTags] = None, sample_rate: typedefs.MSampleRate = 1, ) -> None: """ Increment a counter, optionally setting a value, tags and a sample rate. """ self._report(name, typedefs.MType.COUNTER, value, tags, sample_rate) def decrement( self, name: typedefs.MName, *, value: typedefs.MValue = 1, tags: Optional[typedefs.MTags] = None, sample_rate: typedefs.MSampleRate = 1, ) -> None: """ Decrement a counter, optionally setting a value, tags and a sample rate. """ value = -value if value else value self._report(name, typedefs.MType.COUNTER, value, tags, sample_rate) def histogram( self, name: typedefs.MName, *, value: typedefs.MValue, tags: Optional[typedefs.MTags] = None, sample_rate: typedefs.MSampleRate = 1, ) -> None: """ Sample a histogram value, optionally setting tags and a sample rate. """ self._report(name, typedefs.MType.HISTOGRAM, value, tags, sample_rate) def distribution( self, name: typedefs.MName, *, value: typedefs.MValue, tags: Optional[typedefs.MTags] = None, sample_rate: typedefs.MSampleRate = 1, ) -> None: """ Send a global distribution value, optionally setting tags and a sample rate. """ self._report(name, typedefs.MType.DISTRIBUTION, value, tags, sample_rate) def timing( self, name: typedefs.MName, *, value: typedefs.MValue, tags: Optional[typedefs.MTags] = None, sample_rate: typedefs.MSampleRate = 1, ) -> None: """ Record a timing, optionally setting tags and a sample rate. """ self._report(name, typedefs.MType.TIMING, value, tags, sample_rate) async def _listen(self) -> None: while not self._closing: await self._listen_and_send() # Try to send remaining enqueued metrics if any while not self._queue.empty(): await self._listen_and_send() self._listen_future_join.set_result(True) async def _listen_and_send(self) -> None: coro = self._queue.get() try: buf = await asyncio.wait_for(coro, timeout=self._read_timeout) except asyncio.TimeoutError: pass else: self._protocol.send(buf) def _report( self, name: typedefs.MName, type_: typedefs.MType, value: typedefs.MValue, tags: Optional[typedefs.MTags] = None, sample_rate: typedefs.MSampleRate = 1, ) -> None: # If client in closing state, then ignore any new incoming metric if self._closing: return if sample_rate != 1 and random() > sample_rate: return # Resolve full tags list all_tags = dict(self._constant_tags, **tags or {}) # Build and enqueue metric self._queue.put_nowait( protocol.build( name=name, namespace=self._namespace, value=value, type_=type_, tags=all_tags, sample_rate=sample_rate, ) ) class DatagramProtocol(asyncio.DatagramProtocol): __slots__ = ("_transport", "_closed") def __init__(self) -> None: self._transport: Optional[DatagramTransport] = None self._closed: asyncio.Future = asyncio.Future() async def close(self) -> None: if self._transport is None: return self._transport.close() await self._closed def connection_made(self, transport): self._transport = transport def connection_lost(self, _exc): self._transport = None self._closed.set_result(True) def send(self, data: bytes) -> None: if self._transport is None: return try: self._transport.sendto(data) except Exception: # Errors should fail silently so they don't affect anything else pass PK!Caiodogstatsd/protocol.pyfrom typing import Optional from aiodogstatsd import typedefs __all__ = ("build", "build_tags") def build( *, name: typedefs.MName, namespace: Optional[typedefs.MNamespace], value: typedefs.MValue, type_: typedefs.MType, tags: typedefs.MTags, sample_rate: typedefs.MSampleRate, ) -> bytes: p_name = f"{namespace}.{name}" if namespace is not None else name p_sample_rate = f"|@{sample_rate}" if sample_rate != 1 else "" p_tags = build_tags(tags) p_tags = f"|#{p_tags}" if p_tags else "" return f"{p_name}:{value}|{type_.value}{p_sample_rate}{p_tags}".encode("utf-8") def build_tags(tags: typedefs.MTags) -> str: if not tags: return "" return ",".join(f"{k}={v}" for k, v in tags.items()) PK!4/aiodogstatsd/py.typedMarker PK!Waiodogstatsd/typedefs.pyimport enum from typing import Dict, Union __all__ = ( "MName", "MNamespace", "MType", "MValue", "MSampleRate", "MTagKey", "MTagValue", "MTags", ) MName = str MNamespace = str MValue = Union[float, int] MSampleRate = Union[float, int] MTagKey = str MTagValue = Union[float, int, str] MTags = Dict[MTagKey, MTagValue] @enum.unique class MType(enum.Enum): COUNTER = "c" DISTRIBUTION = "d" GAUGE = "g" HISTOGRAM = "h" TIMING = "ms" PK!`x\//$aiodogstatsd-0.1.0.dist-info/LICENSEMIT License Copyright (c) 2019 Nikita Grishko Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK!HڽTU"aiodogstatsd-0.1.0.dist-info/WHEEL A н#Z;/"d&F[xzw@Zpy3Fv]\fi4WZ^EgM_-]#0(q7PK!H-U%aiodogstatsd-0.1.0.dist-info/METADATAU]k6}ׯl g[6$ MK&ۗPj}VJr&H)м:>\=zYJ/:E:s [@**r^zW}}zm3 ] EZ:,hjPJWТp V 씯uƐ@jG&_Ȋ-u봠vɞ?,Oީ+9Il b%m84|M6U^'\8V&ʞƒ'.:e%_zNe~p^.~Insjh! ya |TYٶ; ät_˓'2mNZ|L$굕V;sOeנ]DBEgk^Q,ס&0#X~+>5Y,iT<8UQ @,mo.*G8e'`Acd1TBjبQV8;Vɿɪ PK!H2޽D#aiodogstatsd-0.1.0.dist-info/RECORD}n@@}e#: ,q-f0T`CA|D{8qS.DJiٔDHsQbVk(ITMclܶ73`G|F}|*Y=`fu4`:X &qY!"5y6}B홻|'z>}೚۲dYcp9>U& ʏ8 K&?5D?x^T.0rh3axH;DždN`F0f}oJ{fS&F1%Ip2IZN*nM!)6dK9B?mYmXRkX\kL!kBwo nPV/.e]3XEި][z*__~ݐ| (^ȨGF[q\puҝ 0~qPK!H 22aiodogstatsd/__init__.pyPK!b |aahaiodogstatsd/client.pyPK!Caiodogstatsd/protocol.pyPK!4/+aiodogstatsd/py.typedPK!Weaiodogstatsd/typedefs.pyPK!`x\//$!aiodogstatsd-0.1.0.dist-info/LICENSEPK!HڽTU"%aiodogstatsd-0.1.0.dist-info/WHEELPK!H-U%&aiodogstatsd-0.1.0.dist-info/METADATAPK!H2޽D#i*aiodogstatsd-0.1.0.dist-info/RECORDPK a,