mochi-analytics 1.0.0__tar.gz

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.
@@ -0,0 +1,10 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ build/
5
+ dist/
6
+ .venv/
7
+ venv/
8
+ .pytest_cache/
9
+ .ruff_cache/
10
+ .mypy_cache/
@@ -0,0 +1,8 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0 (2026-07-09)
4
+
5
+
6
+ ### Features
7
+
8
+ * initial public release of mochi-analytics and the discord.py adapter ([d0b2eaa](https://github.com/mochi-analytics/mochi-py/commit/d0b2eaa1a71da5acfbf1afcc79c9bd5ae51f2b24))
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: mochi-analytics
3
+ Version: 1.0.0
4
+ Summary: Core client for Mochi - self-hosted analytics for Discord bots
5
+ Project-URL: Homepage, https://github.com/mochi-analytics/mochi-py
6
+ Project-URL: Repository, https://github.com/mochi-analytics/mochi-py
7
+ Project-URL: Bug Tracker, https://github.com/mochi-analytics/mochi-py/issues
8
+ Author-email: Mochi Analytics <contact@bwmp.dev>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: analytics,bot,discord,mochi
12
+ Classifier: Framework :: AsyncIO
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Requires-Python: >=3.9
17
+ Requires-Dist: aiohttp>=3.9
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
20
+ Requires-Dist: pytest>=8; extra == 'dev'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # mochi-analytics
24
+
25
+ Core client for Mochi — self-hosted analytics for Discord bots. Asyncio-native,
26
+ batching, and non-blocking: `track()` never blocks or raises into your bot.
27
+
28
+ ## Install
29
+
30
+ ```sh
31
+ pip install mochi-analytics
32
+ ```
33
+
34
+ ## Usage
35
+
36
+ ```python
37
+ from mochi_analytics import MochiClient, MochiEvent, MochiSnapshot
38
+
39
+ mochi = MochiClient(url="https://mochi.example.com", api_key="mochi_sk_...")
40
+
41
+ # Queue events — sent in the background, batched.
42
+ mochi.track(MochiEvent(type="command", name="play", user_id="123"))
43
+ mochi.track_command("play", guild_id="456")
44
+
45
+ # Send a health snapshot immediately.
46
+ await mochi.snapshot(MochiSnapshot(guild_count=1204, ws_ping_ms=38))
47
+
48
+ # On shutdown, flush anything still queued.
49
+ await mochi.shutdown()
50
+ ```
51
+
52
+ ## Design guarantees
53
+
54
+ - Events are batched (flushed every 5 s or 100 events) and sent in the
55
+ background — `track()` never blocks or raises.
56
+ - Transient failures (429 / 5xx / network) retry with exponential backoff;
57
+ the queue is bounded (oldest dropped first), so a dead Mochi instance can
58
+ never leak memory or crash the bot.
59
+ - Errors are routed to the optional `on_error` callback, never raised.
60
+
61
+ ## Options
62
+
63
+ | Argument | Default | Notes |
64
+ |---|---|---|
65
+ | `flush_interval` | `5.0` | Seconds between background flushes. |
66
+ | `max_batch_size` | `100` | Events per request (server limit is 100). |
67
+ | `max_queue_size` | `10000` | Events beyond this are dropped oldest-first. |
68
+ | `max_retries` | `3` | Retry attempts for retryable failures. |
69
+ | `on_error` | no-op | `Callable[[Exception], None]` for dropped/failed sends. |
70
+ | `transport` | aiohttp | Injectable `async (url, body) -> (status, text)` for testing. |
71
+
72
+ ## License
73
+
74
+ Apache-2.0
@@ -0,0 +1,52 @@
1
+ # mochi-analytics
2
+
3
+ Core client for Mochi — self-hosted analytics for Discord bots. Asyncio-native,
4
+ batching, and non-blocking: `track()` never blocks or raises into your bot.
5
+
6
+ ## Install
7
+
8
+ ```sh
9
+ pip install mochi-analytics
10
+ ```
11
+
12
+ ## Usage
13
+
14
+ ```python
15
+ from mochi_analytics import MochiClient, MochiEvent, MochiSnapshot
16
+
17
+ mochi = MochiClient(url="https://mochi.example.com", api_key="mochi_sk_...")
18
+
19
+ # Queue events — sent in the background, batched.
20
+ mochi.track(MochiEvent(type="command", name="play", user_id="123"))
21
+ mochi.track_command("play", guild_id="456")
22
+
23
+ # Send a health snapshot immediately.
24
+ await mochi.snapshot(MochiSnapshot(guild_count=1204, ws_ping_ms=38))
25
+
26
+ # On shutdown, flush anything still queued.
27
+ await mochi.shutdown()
28
+ ```
29
+
30
+ ## Design guarantees
31
+
32
+ - Events are batched (flushed every 5 s or 100 events) and sent in the
33
+ background — `track()` never blocks or raises.
34
+ - Transient failures (429 / 5xx / network) retry with exponential backoff;
35
+ the queue is bounded (oldest dropped first), so a dead Mochi instance can
36
+ never leak memory or crash the bot.
37
+ - Errors are routed to the optional `on_error` callback, never raised.
38
+
39
+ ## Options
40
+
41
+ | Argument | Default | Notes |
42
+ |---|---|---|
43
+ | `flush_interval` | `5.0` | Seconds between background flushes. |
44
+ | `max_batch_size` | `100` | Events per request (server limit is 100). |
45
+ | `max_queue_size` | `10000` | Events beyond this are dropped oldest-first. |
46
+ | `max_retries` | `3` | Retry attempts for retryable failures. |
47
+ | `on_error` | no-op | `Callable[[Exception], None]` for dropped/failed sends. |
48
+ | `transport` | aiohttp | Injectable `async (url, body) -> (status, text)` for testing. |
49
+
50
+ ## License
51
+
52
+ Apache-2.0
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "mochi-analytics"
7
+ version = "1.0.0"
8
+ description = "Core client for Mochi - self-hosted analytics for Discord bots"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.9"
12
+ keywords = ["discord", "bot", "analytics", "mochi"]
13
+ authors = [{ name = "Mochi Analytics", email = "contact@bwmp.dev" }]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: Apache Software License",
17
+ "Framework :: AsyncIO",
18
+ "Intended Audience :: Developers",
19
+ ]
20
+ dependencies = ["aiohttp>=3.9"]
21
+
22
+ [project.urls]
23
+ Homepage = "https://github.com/mochi-analytics/mochi-py"
24
+ Repository = "https://github.com/mochi-analytics/mochi-py"
25
+ "Bug Tracker" = "https://github.com/mochi-analytics/mochi-py/issues"
26
+
27
+ [project.optional-dependencies]
28
+ dev = ["pytest>=8", "pytest-asyncio>=0.23"]
29
+
30
+ [tool.hatch.build.targets.wheel]
31
+ packages = ["src/mochi_analytics"]
32
+
33
+ [tool.pytest.ini_options]
34
+ asyncio_mode = "auto"
35
+ testpaths = ["tests"]
@@ -0,0 +1,23 @@
1
+ """Core client for Mochi - self-hosted analytics for Discord bots."""
2
+
3
+ from mochi_analytics.client import (
4
+ MochiChannelType,
5
+ MochiClient,
6
+ MochiError,
7
+ MochiEvent,
8
+ MochiEventType,
9
+ MochiSnapshot,
10
+ Transport,
11
+ )
12
+
13
+ __all__ = [
14
+ "MochiChannelType",
15
+ "MochiClient",
16
+ "MochiError",
17
+ "MochiEvent",
18
+ "MochiEventType",
19
+ "MochiSnapshot",
20
+ "Transport",
21
+ ]
22
+
23
+ __version__ = "1.0.0" # x-release-please-version
@@ -0,0 +1,327 @@
1
+ """Batching, non-blocking analytics client for Mochi.
2
+
3
+ Failures never propagate into the caller: analytics must not be able to crash
4
+ a bot. Mirrors the design of ``@mochi-analytics/core`` but is asyncio-native.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ from dataclasses import dataclass, field
11
+ from datetime import datetime, timezone
12
+ from typing import Any, Awaitable, Callable, Optional
13
+
14
+ try: # aiohttp is optional at import time so tests can inject a transport.
15
+ import aiohttp
16
+ except ImportError: # pragma: no cover - exercised only without aiohttp
17
+ aiohttp = None # type: ignore[assignment]
18
+
19
+ MochiEventType = str # "command" | "guild_join" | "guild_leave" | "error" | "custom"
20
+ MochiChannelType = str # "guild_text" | "guild_voice" | "thread" | "dm" | "group_dm" | "other"
21
+
22
+ RETRYABLE_STATUS = frozenset({429, 500, 502, 503, 504})
23
+
24
+ #: A transport sends one request and returns ``(status_code, body_text)`` or
25
+ #: ``(status_code, body_text, headers)``. Headers are optional and only used to
26
+ #: read ``Retry-After`` on a 429. The default uses aiohttp; tests inject a fake.
27
+ Transport = Callable[[str, Any], Awaitable[Any]]
28
+
29
+
30
+ class MochiError(Exception):
31
+ """Raised internally on a permanent request failure; routed to ``on_error``."""
32
+
33
+
34
+ def _iso_now() -> str:
35
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
36
+
37
+
38
+ def _header(headers: Any, name: str) -> Optional[str]:
39
+ """Case-insensitive header lookup tolerant of plain dicts and CIMultiDicts."""
40
+ if headers is None:
41
+ return None
42
+ getter = getattr(headers, "get", None)
43
+ if getter is None:
44
+ return None
45
+ value = getter(name)
46
+ if value is None:
47
+ value = getter(name.lower())
48
+ return value
49
+
50
+
51
+ def _parse_retry_after(value: Optional[str]) -> Optional[float]:
52
+ """Parse a Retry-After header (delta-seconds or HTTP-date) into seconds."""
53
+ if not value:
54
+ return None
55
+ value = value.strip()
56
+ try:
57
+ seconds = float(value)
58
+ return seconds if seconds >= 0 else None
59
+ except ValueError:
60
+ pass
61
+ from email.utils import parsedate_to_datetime
62
+
63
+ try:
64
+ when = parsedate_to_datetime(value)
65
+ except (TypeError, ValueError):
66
+ return None
67
+ if when is None:
68
+ return None
69
+ if when.tzinfo is None:
70
+ when = when.replace(tzinfo=timezone.utc)
71
+ return max((when - datetime.now(timezone.utc)).total_seconds(), 0.0)
72
+
73
+
74
+ @dataclass
75
+ class MochiEvent:
76
+ """A single analytics event.
77
+
78
+ Attributes use idiomatic snake_case; they are serialized to the camelCase
79
+ wire format by :meth:`to_wire`.
80
+ """
81
+
82
+ type: MochiEventType
83
+ name: Optional[str] = None
84
+ guild_id: Optional[str] = None
85
+ #: Raw Discord user id - hashed server-side with a per-bot salt, never stored.
86
+ user_id: Optional[str] = None
87
+ channel_type: Optional[MochiChannelType] = None
88
+ shard_id: Optional[int] = None
89
+ success: Optional[bool] = None
90
+ duration_ms: Optional[int] = None
91
+ meta: Optional[dict[str, Any]] = None
92
+ #: ISO 8601 timestamp; defaults to send time when omitted.
93
+ ts: Optional[str] = None
94
+
95
+ def to_wire(self) -> dict[str, Any]:
96
+ wire: dict[str, Any] = {"type": self.type}
97
+ if self.name is not None:
98
+ wire["name"] = self.name
99
+ if self.guild_id is not None:
100
+ wire["guildId"] = self.guild_id
101
+ if self.user_id is not None:
102
+ wire["userId"] = self.user_id
103
+ if self.channel_type is not None:
104
+ wire["channelType"] = self.channel_type
105
+ if self.shard_id is not None:
106
+ wire["shardId"] = self.shard_id
107
+ if self.success is not None:
108
+ wire["success"] = self.success
109
+ if self.duration_ms is not None:
110
+ wire["durationMs"] = self.duration_ms
111
+ if self.meta is not None:
112
+ wire["meta"] = self.meta
113
+ wire["ts"] = self.ts or _iso_now()
114
+ return wire
115
+
116
+
117
+ @dataclass
118
+ class MochiSnapshot:
119
+ """A guild-count / health sample."""
120
+
121
+ guild_count: int
122
+ shard_id: Optional[int] = None
123
+ total_shards: Optional[int] = None
124
+ approximate_member_sum: Optional[int] = None
125
+ ws_ping_ms: Optional[int] = None
126
+ ts: Optional[str] = None
127
+
128
+ def to_wire(self) -> dict[str, Any]:
129
+ wire: dict[str, Any] = {"guildCount": self.guild_count}
130
+ if self.shard_id is not None:
131
+ wire["shardId"] = self.shard_id
132
+ if self.total_shards is not None:
133
+ wire["totalShards"] = self.total_shards
134
+ if self.approximate_member_sum is not None:
135
+ wire["approximateMemberSum"] = self.approximate_member_sum
136
+ if self.ws_ping_ms is not None:
137
+ wire["wsPingMs"] = self.ws_ping_ms
138
+ if self.ts is not None:
139
+ wire["ts"] = self.ts
140
+ return wire
141
+
142
+
143
+ class MochiClient:
144
+ """Batching, non-blocking analytics client.
145
+
146
+ ``track`` is synchronous and returns immediately - events are queued and
147
+ flushed by a background asyncio task (every ``flush_interval`` seconds or
148
+ whenever the batch fills). Transient failures retry with exponential
149
+ backoff; the queue is bounded so a dead Mochi instance can never leak
150
+ memory or crash the bot.
151
+
152
+ The background flush loop starts lazily the first time ``track`` /
153
+ ``snapshot`` / ``flush`` is called while an event loop is running, so a
154
+ client can be constructed outside of a running loop.
155
+ """
156
+
157
+ def __init__(
158
+ self,
159
+ url: str,
160
+ api_key: str,
161
+ *,
162
+ flush_interval: float = 5.0,
163
+ max_batch_size: int = 100,
164
+ max_queue_size: int = 10_000,
165
+ max_retries: int = 3,
166
+ on_error: Optional[Callable[[Exception], None]] = None,
167
+ transport: Optional[Transport] = None,
168
+ ) -> None:
169
+ base = url.rstrip("/")
170
+ self._ingest_url = f"{base}/api/v1/ingest"
171
+ self._snapshot_url = f"{base}/api/v1/snapshot"
172
+ self._api_key = api_key
173
+ self._flush_interval = flush_interval
174
+ self._max_batch_size = min(max_batch_size, 100)
175
+ self._max_queue_size = max_queue_size
176
+ self._max_retries = max_retries
177
+ self._on_error = on_error or (lambda _err: None)
178
+ self._transport = transport or self._default_transport
179
+
180
+ self._queue: list[dict[str, Any]] = []
181
+ self._flush_loop_task: Optional[asyncio.Task[None]] = None
182
+ self._flushing: Optional[asyncio.Task[None]] = None
183
+ self._shutdown = False
184
+ self._session: Optional[Any] = None
185
+
186
+ # -- public API -----------------------------------------------------
187
+
188
+ def track(self, event: MochiEvent) -> None:
189
+ """Queue an event. Returns immediately; sending happens in the background."""
190
+ if self._shutdown:
191
+ return
192
+ self._queue.append(event.to_wire())
193
+ overflow = len(self._queue) - self._max_queue_size
194
+ if overflow > 0:
195
+ del self._queue[:overflow]
196
+ self._report(MochiError("mochi: event queue overflow, dropped oldest"))
197
+ self._ensure_loop()
198
+ if len(self._queue) >= self._max_batch_size:
199
+ self._schedule_flush()
200
+
201
+ def track_command(self, name: str, **context: Any) -> None:
202
+ """Convenience wrapper for a ``command`` event."""
203
+ self.track(MochiEvent(type="command", name=name, **context))
204
+
205
+ async def snapshot(self, snapshot: MochiSnapshot) -> None:
206
+ """Send a guild-count / health snapshot immediately (with retries)."""
207
+ try:
208
+ await self._send(self._snapshot_url, snapshot.to_wire())
209
+ except Exception as error: # never propagate into the caller
210
+ self._report(error)
211
+
212
+ async def flush(self) -> None:
213
+ """Drain the queue. Safe to call concurrently; flushes are serialized."""
214
+ if self._flushing and not self._flushing.done():
215
+ await self._flushing
216
+ return
217
+ self._flushing = asyncio.ensure_future(self._drain())
218
+ try:
219
+ await self._flushing
220
+ finally:
221
+ self._flushing = None
222
+
223
+ async def shutdown(self) -> None:
224
+ """Stop the background loop and flush remaining events. Call on exit."""
225
+ self._shutdown = True
226
+ if self._flush_loop_task:
227
+ self._flush_loop_task.cancel()
228
+ try:
229
+ await self._flush_loop_task
230
+ except asyncio.CancelledError:
231
+ pass
232
+ self._flush_loop_task = None
233
+ await self.flush()
234
+ if self._session is not None:
235
+ await self._session.close()
236
+ self._session = None
237
+
238
+ # -- internals ------------------------------------------------------
239
+
240
+ def _ensure_loop(self) -> None:
241
+ if self._flush_loop_task is not None or self._shutdown:
242
+ return
243
+ try:
244
+ loop = asyncio.get_running_loop()
245
+ except RuntimeError:
246
+ return # no loop yet; loop starts on the next call inside one
247
+ self._flush_loop_task = loop.create_task(self._flush_loop())
248
+
249
+ async def _flush_loop(self) -> None:
250
+ while not self._shutdown:
251
+ await asyncio.sleep(self._flush_interval)
252
+ await self.flush()
253
+
254
+ def _schedule_flush(self) -> None:
255
+ if self._flushing and not self._flushing.done():
256
+ return
257
+ try:
258
+ loop = asyncio.get_running_loop()
259
+ except RuntimeError:
260
+ return
261
+ self._flushing = loop.create_task(self._drain())
262
+
263
+ async def _drain(self) -> None:
264
+ while self._queue:
265
+ batch = self._queue[: self._max_batch_size]
266
+ del self._queue[: self._max_batch_size]
267
+ try:
268
+ await self._send(self._ingest_url, {"events": batch})
269
+ except Exception as error:
270
+ # Batch is dropped; don't spin on a failing endpoint.
271
+ self._report(error)
272
+ return
273
+
274
+ async def _send(self, url: str, body: Any) -> None:
275
+ last_error: Optional[Exception] = None
276
+ retry_after: Optional[float] = None # seconds, from a prior 429
277
+ for attempt in range(self._max_retries + 1):
278
+ if attempt > 0:
279
+ # Honor a server-provided Retry-After in preference to the
280
+ # computed backoff; otherwise use exponential backoff.
281
+ delay = retry_after if retry_after is not None else 0.5 * 2 ** (attempt - 1)
282
+ retry_after = None
283
+ await asyncio.sleep(delay)
284
+ try:
285
+ # Transport returns (status, text) or (status, text, headers).
286
+ status, text, *rest = await self._transport(url, body)
287
+ except Exception as error: # network error -> retry
288
+ last_error = error
289
+ continue
290
+ if 200 <= status < 300:
291
+ return
292
+ if status not in RETRYABLE_STATUS:
293
+ raise MochiError(f"mochi: request rejected ({status}) {text}")
294
+ if status == 429 and rest:
295
+ retry_after = _parse_retry_after(_header(rest[0], "Retry-After"))
296
+ last_error = MochiError(f"mochi: server returned {status}")
297
+ raise last_error or MochiError("mochi: request failed")
298
+
299
+ async def _default_transport(self, url: str, body: Any) -> "tuple[int, str]":
300
+ if aiohttp is None: # pragma: no cover
301
+ raise MochiError(
302
+ "mochi: aiohttp is not installed; install mochi-analytics with its "
303
+ "default dependencies or pass a custom transport"
304
+ )
305
+ session = await self._get_session()
306
+ async with session.post(
307
+ url,
308
+ json=body,
309
+ headers={
310
+ "Content-Type": "application/json",
311
+ "Authorization": f"Bearer {self._api_key}",
312
+ },
313
+ ) as response:
314
+ text = await response.text()
315
+ # response.headers is a case-insensitive CIMultiDict.
316
+ return response.status, text, response.headers
317
+
318
+ async def _get_session(self) -> Any:
319
+ if self._session is None:
320
+ self._session = aiohttp.ClientSession()
321
+ return self._session
322
+
323
+ def _report(self, error: Exception) -> None:
324
+ try:
325
+ self._on_error(error)
326
+ except Exception: # an error handler must never take down the bot
327
+ pass
@@ -0,0 +1,180 @@
1
+ """Mirrors the @mochi-analytics/core vitest suite."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from typing import Any, Callable
7
+
8
+ import pytest
9
+
10
+ from mochi_analytics import MochiClient, MochiEvent, MochiSnapshot
11
+
12
+
13
+ class Call:
14
+ def __init__(self, url: str, body: Any) -> None:
15
+ self.url = url
16
+ self.body = body
17
+
18
+
19
+ def make_transport(responder: Callable[[Call, int], int]):
20
+ """Build a fake transport that records calls and returns a status per call."""
21
+ calls: list[Call] = []
22
+
23
+ async def transport(url: str, body: Any) -> "tuple[int, str]":
24
+ call = Call(url, body)
25
+ calls.append(call)
26
+ status = responder(call, len(calls) - 1)
27
+ return status, "{}"
28
+
29
+ return calls, transport
30
+
31
+
32
+ def make_client(transport, **extra):
33
+ errors: list[Exception] = []
34
+ client = MochiClient(
35
+ "http://localhost:9999/",
36
+ "mochi_sk_test",
37
+ flush_interval=60.0, # effectively disabled; tests flush manually
38
+ max_retries=2,
39
+ on_error=errors.append,
40
+ transport=transport,
41
+ **extra,
42
+ )
43
+ return client, errors
44
+
45
+
46
+ async def test_batches_events_into_one_request_with_auth():
47
+ calls, transport = make_transport(lambda *_: 202)
48
+ client, _ = make_client(transport)
49
+
50
+ client.track(MochiEvent(type="command", name="play", user_id="1"))
51
+ client.track(MochiEvent(type="guild_join", guild_id="2"))
52
+ await client.flush()
53
+
54
+ assert len(calls) == 1
55
+ assert calls[0].url == "http://localhost:9999/api/v1/ingest"
56
+ assert len(calls[0].body["events"]) == 2
57
+ assert calls[0].body["events"][0]["ts"]
58
+ assert calls[0].body["events"][0]["userId"] == "1"
59
+ await client.shutdown()
60
+
61
+
62
+ async def test_auto_flushes_when_batch_size_reached():
63
+ calls, transport = make_transport(lambda *_: 202)
64
+ client, _ = make_client(transport, max_batch_size=5)
65
+
66
+ for _ in range(5):
67
+ client.track(MochiEvent(type="command", name="x"))
68
+ await client.flush()
69
+
70
+ total = sum(len(c.body["events"]) for c in calls)
71
+ assert total == 5
72
+ await client.shutdown()
73
+
74
+
75
+ async def test_splits_oversized_queue_into_multiple_batches():
76
+ calls, transport = make_transport(lambda *_: 202)
77
+ client, _ = make_client(transport, max_batch_size=10)
78
+
79
+ for _ in range(25):
80
+ client.track(MochiEvent(type="command", name="x"))
81
+ await client.flush()
82
+
83
+ assert len(calls) >= 3
84
+ total = sum(len(c.body["events"]) for c in calls)
85
+ assert total == 25
86
+ await client.shutdown()
87
+
88
+
89
+ async def test_retries_retryable_failure_then_succeeds():
90
+ calls, transport = make_transport(lambda _call, index: 503 if index == 0 else 202)
91
+ client, errors = make_client(transport)
92
+
93
+ client.track(MochiEvent(type="command", name="play"))
94
+ await client.flush()
95
+
96
+ assert len(calls) == 2
97
+ assert errors == []
98
+ await client.shutdown()
99
+
100
+
101
+ async def test_drops_batch_and_reports_on_non_retryable_error():
102
+ calls, transport = make_transport(lambda *_: 400)
103
+ client, errors = make_client(transport)
104
+
105
+ client.track(MochiEvent(type="command", name="play"))
106
+ await client.flush()
107
+
108
+ assert len(calls) == 1 # no retries on 400
109
+ assert len(errors) == 1
110
+ assert "400" in str(errors[0])
111
+ await client.shutdown()
112
+
113
+
114
+ async def test_drops_oldest_events_on_queue_overflow():
115
+ calls, transport = make_transport(lambda *_: 202)
116
+ client, errors = make_client(transport, max_queue_size=3, max_batch_size=100)
117
+
118
+ for i in range(5):
119
+ client.track(MochiEvent(type="custom", name=f"event-{i}"))
120
+ await client.flush()
121
+
122
+ assert len(errors) > 0
123
+ names = [e["name"] for c in calls for e in c.body["events"]]
124
+ assert names == ["event-2", "event-3", "event-4"]
125
+ await client.shutdown()
126
+
127
+
128
+ async def test_sends_snapshots_immediately():
129
+ calls, transport = make_transport(lambda *_: 202)
130
+ client, _ = make_client(transport)
131
+
132
+ await client.snapshot(MochiSnapshot(guild_count=42, ws_ping_ms=30))
133
+
134
+ assert len(calls) == 1
135
+ assert calls[0].url == "http://localhost:9999/api/v1/snapshot"
136
+ assert calls[0].body["guildCount"] == 42
137
+ await client.shutdown()
138
+
139
+
140
+ async def test_honors_retry_after_on_429():
141
+ timestamps: list[float] = []
142
+
143
+ async def transport(url: str, body: Any):
144
+ timestamps.append(time.monotonic())
145
+ if len(timestamps) == 1:
146
+ return 429, "{}", {"Retry-After": "1"}
147
+ return 202, "{}"
148
+
149
+ client, errors = make_client(transport)
150
+
151
+ start = time.monotonic()
152
+ client.track(MochiEvent(type="command", name="play"))
153
+ await client.flush()
154
+
155
+ assert len(timestamps) == 2
156
+ assert errors == []
157
+ # Retry-After: 1s must dominate the 0.5s computed backoff.
158
+ assert time.monotonic() - start >= 0.9
159
+ await client.shutdown()
160
+
161
+
162
+ async def test_never_raises_when_on_error_raises():
163
+ calls, transport = make_transport(lambda *_: 202)
164
+
165
+ def boom(_err: Exception) -> None:
166
+ raise RuntimeError("handler blew up")
167
+
168
+ client = MochiClient(
169
+ "http://localhost:9999/",
170
+ "mochi_sk_test",
171
+ flush_interval=60.0,
172
+ max_queue_size=1,
173
+ on_error=boom,
174
+ transport=transport,
175
+ )
176
+
177
+ # Overflow reports from inside track(); a throwing handler must not escape.
178
+ client.track(MochiEvent(type="custom", name="a"))
179
+ client.track(MochiEvent(type="custom", name="b"))
180
+ await client.shutdown()