sentry-sdk 0.7.5__py2.py3-none-any.whl → 2.46.0__py2.py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sentry_sdk/__init__.py +48 -30
- sentry_sdk/_compat.py +74 -61
- sentry_sdk/_init_implementation.py +84 -0
- sentry_sdk/_log_batcher.py +172 -0
- sentry_sdk/_lru_cache.py +47 -0
- sentry_sdk/_metrics_batcher.py +167 -0
- sentry_sdk/_queue.py +289 -0
- sentry_sdk/_types.py +338 -0
- sentry_sdk/_werkzeug.py +98 -0
- sentry_sdk/ai/__init__.py +7 -0
- sentry_sdk/ai/monitoring.py +137 -0
- sentry_sdk/ai/utils.py +144 -0
- sentry_sdk/api.py +496 -80
- sentry_sdk/attachments.py +75 -0
- sentry_sdk/client.py +1023 -103
- sentry_sdk/consts.py +1438 -66
- sentry_sdk/crons/__init__.py +10 -0
- sentry_sdk/crons/api.py +62 -0
- sentry_sdk/crons/consts.py +4 -0
- sentry_sdk/crons/decorator.py +135 -0
- sentry_sdk/debug.py +15 -14
- sentry_sdk/envelope.py +369 -0
- sentry_sdk/feature_flags.py +71 -0
- sentry_sdk/hub.py +611 -280
- sentry_sdk/integrations/__init__.py +276 -49
- sentry_sdk/integrations/_asgi_common.py +108 -0
- sentry_sdk/integrations/_wsgi_common.py +180 -44
- sentry_sdk/integrations/aiohttp.py +291 -42
- sentry_sdk/integrations/anthropic.py +439 -0
- sentry_sdk/integrations/argv.py +9 -8
- sentry_sdk/integrations/ariadne.py +161 -0
- sentry_sdk/integrations/arq.py +247 -0
- sentry_sdk/integrations/asgi.py +341 -0
- sentry_sdk/integrations/asyncio.py +144 -0
- sentry_sdk/integrations/asyncpg.py +208 -0
- sentry_sdk/integrations/atexit.py +17 -10
- sentry_sdk/integrations/aws_lambda.py +377 -62
- sentry_sdk/integrations/beam.py +176 -0
- sentry_sdk/integrations/boto3.py +137 -0
- sentry_sdk/integrations/bottle.py +221 -0
- sentry_sdk/integrations/celery/__init__.py +529 -0
- sentry_sdk/integrations/celery/beat.py +293 -0
- sentry_sdk/integrations/celery/utils.py +43 -0
- sentry_sdk/integrations/chalice.py +134 -0
- sentry_sdk/integrations/clickhouse_driver.py +177 -0
- sentry_sdk/integrations/cloud_resource_context.py +280 -0
- sentry_sdk/integrations/cohere.py +274 -0
- sentry_sdk/integrations/dedupe.py +48 -14
- sentry_sdk/integrations/django/__init__.py +584 -191
- sentry_sdk/integrations/django/asgi.py +245 -0
- sentry_sdk/integrations/django/caching.py +204 -0
- sentry_sdk/integrations/django/middleware.py +187 -0
- sentry_sdk/integrations/django/signals_handlers.py +91 -0
- sentry_sdk/integrations/django/templates.py +79 -5
- sentry_sdk/integrations/django/transactions.py +49 -22
- sentry_sdk/integrations/django/views.py +96 -0
- sentry_sdk/integrations/dramatiq.py +226 -0
- sentry_sdk/integrations/excepthook.py +50 -13
- sentry_sdk/integrations/executing.py +67 -0
- sentry_sdk/integrations/falcon.py +272 -0
- sentry_sdk/integrations/fastapi.py +141 -0
- sentry_sdk/integrations/flask.py +142 -88
- sentry_sdk/integrations/gcp.py +239 -0
- sentry_sdk/integrations/gnu_backtrace.py +99 -0
- sentry_sdk/integrations/google_genai/__init__.py +301 -0
- sentry_sdk/integrations/google_genai/consts.py +16 -0
- sentry_sdk/integrations/google_genai/streaming.py +155 -0
- sentry_sdk/integrations/google_genai/utils.py +576 -0
- sentry_sdk/integrations/gql.py +162 -0
- sentry_sdk/integrations/graphene.py +151 -0
- sentry_sdk/integrations/grpc/__init__.py +168 -0
- sentry_sdk/integrations/grpc/aio/__init__.py +7 -0
- sentry_sdk/integrations/grpc/aio/client.py +95 -0
- sentry_sdk/integrations/grpc/aio/server.py +100 -0
- sentry_sdk/integrations/grpc/client.py +91 -0
- sentry_sdk/integrations/grpc/consts.py +1 -0
- sentry_sdk/integrations/grpc/server.py +66 -0
- sentry_sdk/integrations/httpx.py +178 -0
- sentry_sdk/integrations/huey.py +174 -0
- sentry_sdk/integrations/huggingface_hub.py +378 -0
- sentry_sdk/integrations/langchain.py +1132 -0
- sentry_sdk/integrations/langgraph.py +337 -0
- sentry_sdk/integrations/launchdarkly.py +61 -0
- sentry_sdk/integrations/litellm.py +287 -0
- sentry_sdk/integrations/litestar.py +315 -0
- sentry_sdk/integrations/logging.py +307 -96
- sentry_sdk/integrations/loguru.py +213 -0
- sentry_sdk/integrations/mcp.py +566 -0
- sentry_sdk/integrations/modules.py +14 -31
- sentry_sdk/integrations/openai.py +725 -0
- sentry_sdk/integrations/openai_agents/__init__.py +61 -0
- sentry_sdk/integrations/openai_agents/consts.py +1 -0
- sentry_sdk/integrations/openai_agents/patches/__init__.py +5 -0
- sentry_sdk/integrations/openai_agents/patches/agent_run.py +140 -0
- sentry_sdk/integrations/openai_agents/patches/error_tracing.py +77 -0
- sentry_sdk/integrations/openai_agents/patches/models.py +50 -0
- sentry_sdk/integrations/openai_agents/patches/runner.py +45 -0
- sentry_sdk/integrations/openai_agents/patches/tools.py +77 -0
- sentry_sdk/integrations/openai_agents/spans/__init__.py +5 -0
- sentry_sdk/integrations/openai_agents/spans/agent_workflow.py +21 -0
- sentry_sdk/integrations/openai_agents/spans/ai_client.py +42 -0
- sentry_sdk/integrations/openai_agents/spans/execute_tool.py +48 -0
- sentry_sdk/integrations/openai_agents/spans/handoff.py +19 -0
- sentry_sdk/integrations/openai_agents/spans/invoke_agent.py +86 -0
- sentry_sdk/integrations/openai_agents/utils.py +199 -0
- sentry_sdk/integrations/openfeature.py +35 -0
- sentry_sdk/integrations/opentelemetry/__init__.py +7 -0
- sentry_sdk/integrations/opentelemetry/consts.py +5 -0
- sentry_sdk/integrations/opentelemetry/integration.py +58 -0
- sentry_sdk/integrations/opentelemetry/propagator.py +117 -0
- sentry_sdk/integrations/opentelemetry/span_processor.py +391 -0
- sentry_sdk/integrations/otlp.py +82 -0
- sentry_sdk/integrations/pure_eval.py +141 -0
- sentry_sdk/integrations/pydantic_ai/__init__.py +47 -0
- sentry_sdk/integrations/pydantic_ai/consts.py +1 -0
- sentry_sdk/integrations/pydantic_ai/patches/__init__.py +4 -0
- sentry_sdk/integrations/pydantic_ai/patches/agent_run.py +215 -0
- sentry_sdk/integrations/pydantic_ai/patches/graph_nodes.py +110 -0
- sentry_sdk/integrations/pydantic_ai/patches/model_request.py +40 -0
- sentry_sdk/integrations/pydantic_ai/patches/tools.py +98 -0
- sentry_sdk/integrations/pydantic_ai/spans/__init__.py +3 -0
- sentry_sdk/integrations/pydantic_ai/spans/ai_client.py +246 -0
- sentry_sdk/integrations/pydantic_ai/spans/execute_tool.py +49 -0
- sentry_sdk/integrations/pydantic_ai/spans/invoke_agent.py +112 -0
- sentry_sdk/integrations/pydantic_ai/utils.py +223 -0
- sentry_sdk/integrations/pymongo.py +214 -0
- sentry_sdk/integrations/pyramid.py +112 -68
- sentry_sdk/integrations/quart.py +237 -0
- sentry_sdk/integrations/ray.py +165 -0
- sentry_sdk/integrations/redis/__init__.py +48 -0
- sentry_sdk/integrations/redis/_async_common.py +116 -0
- sentry_sdk/integrations/redis/_sync_common.py +119 -0
- sentry_sdk/integrations/redis/consts.py +19 -0
- sentry_sdk/integrations/redis/modules/__init__.py +0 -0
- sentry_sdk/integrations/redis/modules/caches.py +118 -0
- sentry_sdk/integrations/redis/modules/queries.py +65 -0
- sentry_sdk/integrations/redis/rb.py +32 -0
- sentry_sdk/integrations/redis/redis.py +69 -0
- sentry_sdk/integrations/redis/redis_cluster.py +107 -0
- sentry_sdk/integrations/redis/redis_py_cluster_legacy.py +50 -0
- sentry_sdk/integrations/redis/utils.py +148 -0
- sentry_sdk/integrations/rq.py +95 -37
- sentry_sdk/integrations/rust_tracing.py +284 -0
- sentry_sdk/integrations/sanic.py +294 -123
- sentry_sdk/integrations/serverless.py +48 -19
- sentry_sdk/integrations/socket.py +96 -0
- sentry_sdk/integrations/spark/__init__.py +4 -0
- sentry_sdk/integrations/spark/spark_driver.py +316 -0
- sentry_sdk/integrations/spark/spark_worker.py +116 -0
- sentry_sdk/integrations/sqlalchemy.py +142 -0
- sentry_sdk/integrations/starlette.py +737 -0
- sentry_sdk/integrations/starlite.py +292 -0
- sentry_sdk/integrations/statsig.py +37 -0
- sentry_sdk/integrations/stdlib.py +235 -29
- sentry_sdk/integrations/strawberry.py +394 -0
- sentry_sdk/integrations/sys_exit.py +70 -0
- sentry_sdk/integrations/threading.py +158 -28
- sentry_sdk/integrations/tornado.py +84 -52
- sentry_sdk/integrations/trytond.py +50 -0
- sentry_sdk/integrations/typer.py +60 -0
- sentry_sdk/integrations/unleash.py +33 -0
- sentry_sdk/integrations/unraisablehook.py +53 -0
- sentry_sdk/integrations/wsgi.py +201 -119
- sentry_sdk/logger.py +96 -0
- sentry_sdk/metrics.py +81 -0
- sentry_sdk/monitor.py +120 -0
- sentry_sdk/profiler/__init__.py +49 -0
- sentry_sdk/profiler/continuous_profiler.py +730 -0
- sentry_sdk/profiler/transaction_profiler.py +839 -0
- sentry_sdk/profiler/utils.py +195 -0
- sentry_sdk/py.typed +0 -0
- sentry_sdk/scope.py +1713 -85
- sentry_sdk/scrubber.py +177 -0
- sentry_sdk/serializer.py +405 -0
- sentry_sdk/session.py +177 -0
- sentry_sdk/sessions.py +275 -0
- sentry_sdk/spotlight.py +242 -0
- sentry_sdk/tracing.py +1486 -0
- sentry_sdk/tracing_utils.py +1236 -0
- sentry_sdk/transport.py +806 -134
- sentry_sdk/types.py +52 -0
- sentry_sdk/utils.py +1625 -465
- sentry_sdk/worker.py +54 -25
- sentry_sdk-2.46.0.dist-info/METADATA +268 -0
- sentry_sdk-2.46.0.dist-info/RECORD +189 -0
- {sentry_sdk-0.7.5.dist-info → sentry_sdk-2.46.0.dist-info}/WHEEL +1 -1
- sentry_sdk-2.46.0.dist-info/entry_points.txt +2 -0
- sentry_sdk-2.46.0.dist-info/licenses/LICENSE +21 -0
- sentry_sdk/integrations/celery.py +0 -119
- sentry_sdk-0.7.5.dist-info/LICENSE +0 -9
- sentry_sdk-0.7.5.dist-info/METADATA +0 -36
- sentry_sdk-0.7.5.dist-info/RECORD +0 -39
- {sentry_sdk-0.7.5.dist-info → sentry_sdk-2.46.0.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import random
|
|
3
|
+
import threading
|
|
4
|
+
from datetime import datetime, timezone
|
|
5
|
+
from typing import Optional, List, Callable, TYPE_CHECKING, Any, Union
|
|
6
|
+
|
|
7
|
+
from sentry_sdk.utils import format_timestamp, safe_repr
|
|
8
|
+
from sentry_sdk.envelope import Envelope, Item, PayloadRef
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from sentry_sdk._types import Metric
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class MetricsBatcher:
|
|
15
|
+
MAX_METRICS_BEFORE_FLUSH = 1000
|
|
16
|
+
MAX_METRICS_BEFORE_DROP = 10_000
|
|
17
|
+
FLUSH_WAIT_TIME = 5.0
|
|
18
|
+
|
|
19
|
+
def __init__(
|
|
20
|
+
self,
|
|
21
|
+
capture_func, # type: Callable[[Envelope], None]
|
|
22
|
+
record_lost_func, # type: Callable[..., None]
|
|
23
|
+
):
|
|
24
|
+
# type: (...) -> None
|
|
25
|
+
self._metric_buffer = [] # type: List[Metric]
|
|
26
|
+
self._capture_func = capture_func
|
|
27
|
+
self._record_lost_func = record_lost_func
|
|
28
|
+
self._running = True
|
|
29
|
+
self._lock = threading.Lock()
|
|
30
|
+
|
|
31
|
+
self._flush_event = threading.Event() # type: threading.Event
|
|
32
|
+
|
|
33
|
+
self._flusher = None # type: Optional[threading.Thread]
|
|
34
|
+
self._flusher_pid = None # type: Optional[int]
|
|
35
|
+
|
|
36
|
+
def _ensure_thread(self):
|
|
37
|
+
# type: (...) -> bool
|
|
38
|
+
if not self._running:
|
|
39
|
+
return False
|
|
40
|
+
|
|
41
|
+
pid = os.getpid()
|
|
42
|
+
if self._flusher_pid == pid:
|
|
43
|
+
return True
|
|
44
|
+
|
|
45
|
+
with self._lock:
|
|
46
|
+
if self._flusher_pid == pid:
|
|
47
|
+
return True
|
|
48
|
+
|
|
49
|
+
self._flusher_pid = pid
|
|
50
|
+
|
|
51
|
+
self._flusher = threading.Thread(target=self._flush_loop)
|
|
52
|
+
self._flusher.daemon = True
|
|
53
|
+
|
|
54
|
+
try:
|
|
55
|
+
self._flusher.start()
|
|
56
|
+
except RuntimeError:
|
|
57
|
+
self._running = False
|
|
58
|
+
return False
|
|
59
|
+
|
|
60
|
+
return True
|
|
61
|
+
|
|
62
|
+
def _flush_loop(self):
|
|
63
|
+
# type: (...) -> None
|
|
64
|
+
while self._running:
|
|
65
|
+
self._flush_event.wait(self.FLUSH_WAIT_TIME + random.random())
|
|
66
|
+
self._flush_event.clear()
|
|
67
|
+
self._flush()
|
|
68
|
+
|
|
69
|
+
def add(
|
|
70
|
+
self,
|
|
71
|
+
metric, # type: Metric
|
|
72
|
+
):
|
|
73
|
+
# type: (...) -> None
|
|
74
|
+
if not self._ensure_thread() or self._flusher is None:
|
|
75
|
+
return None
|
|
76
|
+
|
|
77
|
+
with self._lock:
|
|
78
|
+
if len(self._metric_buffer) >= self.MAX_METRICS_BEFORE_DROP:
|
|
79
|
+
self._record_lost_func(
|
|
80
|
+
reason="queue_overflow",
|
|
81
|
+
data_category="trace_metric",
|
|
82
|
+
quantity=1,
|
|
83
|
+
)
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
self._metric_buffer.append(metric)
|
|
87
|
+
if len(self._metric_buffer) >= self.MAX_METRICS_BEFORE_FLUSH:
|
|
88
|
+
self._flush_event.set()
|
|
89
|
+
|
|
90
|
+
def kill(self):
|
|
91
|
+
# type: (...) -> None
|
|
92
|
+
if self._flusher is None:
|
|
93
|
+
return
|
|
94
|
+
|
|
95
|
+
self._running = False
|
|
96
|
+
self._flush_event.set()
|
|
97
|
+
self._flusher = None
|
|
98
|
+
|
|
99
|
+
def flush(self):
|
|
100
|
+
# type: (...) -> None
|
|
101
|
+
self._flush()
|
|
102
|
+
|
|
103
|
+
@staticmethod
|
|
104
|
+
def _metric_to_transport_format(metric):
|
|
105
|
+
# type: (Metric) -> Any
|
|
106
|
+
def format_attribute(val):
|
|
107
|
+
# type: (Union[int, float, str, bool]) -> Any
|
|
108
|
+
if isinstance(val, bool):
|
|
109
|
+
return {"value": val, "type": "boolean"}
|
|
110
|
+
if isinstance(val, int):
|
|
111
|
+
return {"value": val, "type": "integer"}
|
|
112
|
+
if isinstance(val, float):
|
|
113
|
+
return {"value": val, "type": "double"}
|
|
114
|
+
if isinstance(val, str):
|
|
115
|
+
return {"value": val, "type": "string"}
|
|
116
|
+
return {"value": safe_repr(val), "type": "string"}
|
|
117
|
+
|
|
118
|
+
res = {
|
|
119
|
+
"timestamp": metric["timestamp"],
|
|
120
|
+
"trace_id": metric["trace_id"],
|
|
121
|
+
"name": metric["name"],
|
|
122
|
+
"type": metric["type"],
|
|
123
|
+
"value": metric["value"],
|
|
124
|
+
"attributes": {
|
|
125
|
+
k: format_attribute(v) for (k, v) in metric["attributes"].items()
|
|
126
|
+
},
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if metric.get("span_id") is not None:
|
|
130
|
+
res["span_id"] = metric["span_id"]
|
|
131
|
+
|
|
132
|
+
if metric.get("unit") is not None:
|
|
133
|
+
res["unit"] = metric["unit"]
|
|
134
|
+
|
|
135
|
+
return res
|
|
136
|
+
|
|
137
|
+
def _flush(self):
|
|
138
|
+
# type: (...) -> Optional[Envelope]
|
|
139
|
+
|
|
140
|
+
envelope = Envelope(
|
|
141
|
+
headers={"sent_at": format_timestamp(datetime.now(timezone.utc))}
|
|
142
|
+
)
|
|
143
|
+
with self._lock:
|
|
144
|
+
if len(self._metric_buffer) == 0:
|
|
145
|
+
return None
|
|
146
|
+
|
|
147
|
+
envelope.add_item(
|
|
148
|
+
Item(
|
|
149
|
+
type="trace_metric",
|
|
150
|
+
content_type="application/vnd.sentry.items.trace-metric+json",
|
|
151
|
+
headers={
|
|
152
|
+
"item_count": len(self._metric_buffer),
|
|
153
|
+
},
|
|
154
|
+
payload=PayloadRef(
|
|
155
|
+
json={
|
|
156
|
+
"items": [
|
|
157
|
+
self._metric_to_transport_format(metric)
|
|
158
|
+
for metric in self._metric_buffer
|
|
159
|
+
]
|
|
160
|
+
}
|
|
161
|
+
),
|
|
162
|
+
)
|
|
163
|
+
)
|
|
164
|
+
self._metric_buffer.clear()
|
|
165
|
+
|
|
166
|
+
self._capture_func(envelope)
|
|
167
|
+
return envelope
|
sentry_sdk/_queue.py
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
"""
|
|
2
|
+
A fork of Python 3.6's stdlib queue (found in Pythons 'cpython/Lib/queue.py')
|
|
3
|
+
with Lock swapped out for RLock to avoid a deadlock while garbage collecting.
|
|
4
|
+
|
|
5
|
+
https://github.com/python/cpython/blob/v3.6.12/Lib/queue.py
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
See also
|
|
9
|
+
https://codewithoutrules.com/2017/08/16/concurrency-python/
|
|
10
|
+
https://bugs.python.org/issue14976
|
|
11
|
+
https://github.com/sqlalchemy/sqlalchemy/blob/4eb747b61f0c1b1c25bdee3856d7195d10a0c227/lib/sqlalchemy/queue.py#L1
|
|
12
|
+
|
|
13
|
+
We also vendor the code to evade eventlet's broken monkeypatching, see
|
|
14
|
+
https://github.com/getsentry/sentry-python/pull/484
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
|
|
18
|
+
2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Python Software Foundation;
|
|
19
|
+
|
|
20
|
+
All Rights Reserved
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
|
|
24
|
+
--------------------------------------------
|
|
25
|
+
|
|
26
|
+
1. This LICENSE AGREEMENT is between the Python Software Foundation
|
|
27
|
+
("PSF"), and the Individual or Organization ("Licensee") accessing and
|
|
28
|
+
otherwise using this software ("Python") in source or binary form and
|
|
29
|
+
its associated documentation.
|
|
30
|
+
|
|
31
|
+
2. Subject to the terms and conditions of this License Agreement, PSF hereby
|
|
32
|
+
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
|
|
33
|
+
analyze, test, perform and/or display publicly, prepare derivative works,
|
|
34
|
+
distribute, and otherwise use Python alone or in any derivative version,
|
|
35
|
+
provided, however, that PSF's License Agreement and PSF's notice of copyright,
|
|
36
|
+
i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
|
|
37
|
+
2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Python Software Foundation;
|
|
38
|
+
All Rights Reserved" are retained in Python alone or in any derivative version
|
|
39
|
+
prepared by Licensee.
|
|
40
|
+
|
|
41
|
+
3. In the event Licensee prepares a derivative work that is based on
|
|
42
|
+
or incorporates Python or any part thereof, and wants to make
|
|
43
|
+
the derivative work available to others as provided herein, then
|
|
44
|
+
Licensee hereby agrees to include in any such work a brief summary of
|
|
45
|
+
the changes made to Python.
|
|
46
|
+
|
|
47
|
+
4. PSF is making Python available to Licensee on an "AS IS"
|
|
48
|
+
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
|
49
|
+
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
|
|
50
|
+
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
|
51
|
+
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
|
|
52
|
+
INFRINGE ANY THIRD PARTY RIGHTS.
|
|
53
|
+
|
|
54
|
+
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
|
|
55
|
+
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
|
|
56
|
+
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
|
|
57
|
+
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
|
58
|
+
|
|
59
|
+
6. This License Agreement will automatically terminate upon a material
|
|
60
|
+
breach of its terms and conditions.
|
|
61
|
+
|
|
62
|
+
7. Nothing in this License Agreement shall be deemed to create any
|
|
63
|
+
relationship of agency, partnership, or joint venture between PSF and
|
|
64
|
+
Licensee. This License Agreement does not grant permission to use PSF
|
|
65
|
+
trademarks or trade name in a trademark sense to endorse or promote
|
|
66
|
+
products or services of Licensee, or any third party.
|
|
67
|
+
|
|
68
|
+
8. By copying, installing or otherwise using Python, Licensee
|
|
69
|
+
agrees to be bound by the terms and conditions of this License
|
|
70
|
+
Agreement.
|
|
71
|
+
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
import threading
|
|
75
|
+
|
|
76
|
+
from collections import deque
|
|
77
|
+
from time import time
|
|
78
|
+
|
|
79
|
+
from typing import TYPE_CHECKING
|
|
80
|
+
|
|
81
|
+
if TYPE_CHECKING:
|
|
82
|
+
from typing import Any
|
|
83
|
+
|
|
84
|
+
__all__ = ["EmptyError", "FullError", "Queue"]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class EmptyError(Exception):
|
|
88
|
+
"Exception raised by Queue.get(block=0)/get_nowait()."
|
|
89
|
+
|
|
90
|
+
pass
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class FullError(Exception):
|
|
94
|
+
"Exception raised by Queue.put(block=0)/put_nowait()."
|
|
95
|
+
|
|
96
|
+
pass
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class Queue:
|
|
100
|
+
"""Create a queue object with a given maximum size.
|
|
101
|
+
|
|
102
|
+
If maxsize is <= 0, the queue size is infinite.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
def __init__(self, maxsize=0):
|
|
106
|
+
self.maxsize = maxsize
|
|
107
|
+
self._init(maxsize)
|
|
108
|
+
|
|
109
|
+
# mutex must be held whenever the queue is mutating. All methods
|
|
110
|
+
# that acquire mutex must release it before returning. mutex
|
|
111
|
+
# is shared between the three conditions, so acquiring and
|
|
112
|
+
# releasing the conditions also acquires and releases mutex.
|
|
113
|
+
self.mutex = threading.RLock()
|
|
114
|
+
|
|
115
|
+
# Notify not_empty whenever an item is added to the queue; a
|
|
116
|
+
# thread waiting to get is notified then.
|
|
117
|
+
self.not_empty = threading.Condition(self.mutex)
|
|
118
|
+
|
|
119
|
+
# Notify not_full whenever an item is removed from the queue;
|
|
120
|
+
# a thread waiting to put is notified then.
|
|
121
|
+
self.not_full = threading.Condition(self.mutex)
|
|
122
|
+
|
|
123
|
+
# Notify all_tasks_done whenever the number of unfinished tasks
|
|
124
|
+
# drops to zero; thread waiting to join() is notified to resume
|
|
125
|
+
self.all_tasks_done = threading.Condition(self.mutex)
|
|
126
|
+
self.unfinished_tasks = 0
|
|
127
|
+
|
|
128
|
+
def task_done(self):
|
|
129
|
+
"""Indicate that a formerly enqueued task is complete.
|
|
130
|
+
|
|
131
|
+
Used by Queue consumer threads. For each get() used to fetch a task,
|
|
132
|
+
a subsequent call to task_done() tells the queue that the processing
|
|
133
|
+
on the task is complete.
|
|
134
|
+
|
|
135
|
+
If a join() is currently blocking, it will resume when all items
|
|
136
|
+
have been processed (meaning that a task_done() call was received
|
|
137
|
+
for every item that had been put() into the queue).
|
|
138
|
+
|
|
139
|
+
Raises a ValueError if called more times than there were items
|
|
140
|
+
placed in the queue.
|
|
141
|
+
"""
|
|
142
|
+
with self.all_tasks_done:
|
|
143
|
+
unfinished = self.unfinished_tasks - 1
|
|
144
|
+
if unfinished <= 0:
|
|
145
|
+
if unfinished < 0:
|
|
146
|
+
raise ValueError("task_done() called too many times")
|
|
147
|
+
self.all_tasks_done.notify_all()
|
|
148
|
+
self.unfinished_tasks = unfinished
|
|
149
|
+
|
|
150
|
+
def join(self):
|
|
151
|
+
"""Blocks until all items in the Queue have been gotten and processed.
|
|
152
|
+
|
|
153
|
+
The count of unfinished tasks goes up whenever an item is added to the
|
|
154
|
+
queue. The count goes down whenever a consumer thread calls task_done()
|
|
155
|
+
to indicate the item was retrieved and all work on it is complete.
|
|
156
|
+
|
|
157
|
+
When the count of unfinished tasks drops to zero, join() unblocks.
|
|
158
|
+
"""
|
|
159
|
+
with self.all_tasks_done:
|
|
160
|
+
while self.unfinished_tasks:
|
|
161
|
+
self.all_tasks_done.wait()
|
|
162
|
+
|
|
163
|
+
def qsize(self):
|
|
164
|
+
"""Return the approximate size of the queue (not reliable!)."""
|
|
165
|
+
with self.mutex:
|
|
166
|
+
return self._qsize()
|
|
167
|
+
|
|
168
|
+
def empty(self):
|
|
169
|
+
"""Return True if the queue is empty, False otherwise (not reliable!).
|
|
170
|
+
|
|
171
|
+
This method is likely to be removed at some point. Use qsize() == 0
|
|
172
|
+
as a direct substitute, but be aware that either approach risks a race
|
|
173
|
+
condition where a queue can grow before the result of empty() or
|
|
174
|
+
qsize() can be used.
|
|
175
|
+
|
|
176
|
+
To create code that needs to wait for all queued tasks to be
|
|
177
|
+
completed, the preferred technique is to use the join() method.
|
|
178
|
+
"""
|
|
179
|
+
with self.mutex:
|
|
180
|
+
return not self._qsize()
|
|
181
|
+
|
|
182
|
+
def full(self):
|
|
183
|
+
"""Return True if the queue is full, False otherwise (not reliable!).
|
|
184
|
+
|
|
185
|
+
This method is likely to be removed at some point. Use qsize() >= n
|
|
186
|
+
as a direct substitute, but be aware that either approach risks a race
|
|
187
|
+
condition where a queue can shrink before the result of full() or
|
|
188
|
+
qsize() can be used.
|
|
189
|
+
"""
|
|
190
|
+
with self.mutex:
|
|
191
|
+
return 0 < self.maxsize <= self._qsize()
|
|
192
|
+
|
|
193
|
+
def put(self, item, block=True, timeout=None):
|
|
194
|
+
"""Put an item into the queue.
|
|
195
|
+
|
|
196
|
+
If optional args 'block' is true and 'timeout' is None (the default),
|
|
197
|
+
block if necessary until a free slot is available. If 'timeout' is
|
|
198
|
+
a non-negative number, it blocks at most 'timeout' seconds and raises
|
|
199
|
+
the FullError exception if no free slot was available within that time.
|
|
200
|
+
Otherwise ('block' is false), put an item on the queue if a free slot
|
|
201
|
+
is immediately available, else raise the FullError exception ('timeout'
|
|
202
|
+
is ignored in that case).
|
|
203
|
+
"""
|
|
204
|
+
with self.not_full:
|
|
205
|
+
if self.maxsize > 0:
|
|
206
|
+
if not block:
|
|
207
|
+
if self._qsize() >= self.maxsize:
|
|
208
|
+
raise FullError()
|
|
209
|
+
elif timeout is None:
|
|
210
|
+
while self._qsize() >= self.maxsize:
|
|
211
|
+
self.not_full.wait()
|
|
212
|
+
elif timeout < 0:
|
|
213
|
+
raise ValueError("'timeout' must be a non-negative number")
|
|
214
|
+
else:
|
|
215
|
+
endtime = time() + timeout
|
|
216
|
+
while self._qsize() >= self.maxsize:
|
|
217
|
+
remaining = endtime - time()
|
|
218
|
+
if remaining <= 0.0:
|
|
219
|
+
raise FullError()
|
|
220
|
+
self.not_full.wait(remaining)
|
|
221
|
+
self._put(item)
|
|
222
|
+
self.unfinished_tasks += 1
|
|
223
|
+
self.not_empty.notify()
|
|
224
|
+
|
|
225
|
+
def get(self, block=True, timeout=None):
|
|
226
|
+
"""Remove and return an item from the queue.
|
|
227
|
+
|
|
228
|
+
If optional args 'block' is true and 'timeout' is None (the default),
|
|
229
|
+
block if necessary until an item is available. If 'timeout' is
|
|
230
|
+
a non-negative number, it blocks at most 'timeout' seconds and raises
|
|
231
|
+
the EmptyError exception if no item was available within that time.
|
|
232
|
+
Otherwise ('block' is false), return an item if one is immediately
|
|
233
|
+
available, else raise the EmptyError exception ('timeout' is ignored
|
|
234
|
+
in that case).
|
|
235
|
+
"""
|
|
236
|
+
with self.not_empty:
|
|
237
|
+
if not block:
|
|
238
|
+
if not self._qsize():
|
|
239
|
+
raise EmptyError()
|
|
240
|
+
elif timeout is None:
|
|
241
|
+
while not self._qsize():
|
|
242
|
+
self.not_empty.wait()
|
|
243
|
+
elif timeout < 0:
|
|
244
|
+
raise ValueError("'timeout' must be a non-negative number")
|
|
245
|
+
else:
|
|
246
|
+
endtime = time() + timeout
|
|
247
|
+
while not self._qsize():
|
|
248
|
+
remaining = endtime - time()
|
|
249
|
+
if remaining <= 0.0:
|
|
250
|
+
raise EmptyError()
|
|
251
|
+
self.not_empty.wait(remaining)
|
|
252
|
+
item = self._get()
|
|
253
|
+
self.not_full.notify()
|
|
254
|
+
return item
|
|
255
|
+
|
|
256
|
+
def put_nowait(self, item):
|
|
257
|
+
"""Put an item into the queue without blocking.
|
|
258
|
+
|
|
259
|
+
Only enqueue the item if a free slot is immediately available.
|
|
260
|
+
Otherwise raise the FullError exception.
|
|
261
|
+
"""
|
|
262
|
+
return self.put(item, block=False)
|
|
263
|
+
|
|
264
|
+
def get_nowait(self):
|
|
265
|
+
"""Remove and return an item from the queue without blocking.
|
|
266
|
+
|
|
267
|
+
Only get an item if one is immediately available. Otherwise
|
|
268
|
+
raise the EmptyError exception.
|
|
269
|
+
"""
|
|
270
|
+
return self.get(block=False)
|
|
271
|
+
|
|
272
|
+
# Override these methods to implement other queue organizations
|
|
273
|
+
# (e.g. stack or priority queue).
|
|
274
|
+
# These will only be called with appropriate locks held
|
|
275
|
+
|
|
276
|
+
# Initialize the queue representation
|
|
277
|
+
def _init(self, maxsize):
|
|
278
|
+
self.queue = deque() # type: Any
|
|
279
|
+
|
|
280
|
+
def _qsize(self):
|
|
281
|
+
return len(self.queue)
|
|
282
|
+
|
|
283
|
+
# Put a new item in the queue
|
|
284
|
+
def _put(self, item):
|
|
285
|
+
self.queue.append(item)
|
|
286
|
+
|
|
287
|
+
# Get an item from the queue
|
|
288
|
+
def _get(self):
|
|
289
|
+
return self.queue.popleft()
|