python-vk-bot 0.3.0__tar.gz → 0.4.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.
Files changed (32) hide show
  1. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/CHANGELOG.md +18 -0
  2. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/PKG-INFO +14 -1
  3. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/README.md +13 -0
  4. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/examples/README.md +19 -0
  5. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/pyproject.toml +1 -1
  6. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/python_vk_bot/__init__.py +6 -1
  7. python_vk_bot-0.4.0/python_vk_bot/application.py +491 -0
  8. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/python_vk_bot/context.py +1 -0
  9. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/python_vk_bot/errors.py +4 -0
  10. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/python_vk_bot/handlers.py +38 -0
  11. python_vk_bot-0.4.0/python_vk_bot/queues.py +86 -0
  12. python_vk_bot-0.3.0/python_vk_bot/application.py +0 -221
  13. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/.gitignore +0 -0
  14. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/LICENSE +0 -0
  15. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/docs/decisions/README.md +0 -0
  16. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/python_vk_bot/.agents/skills/telegram-to-vk/SKILL.md +0 -0
  17. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/python_vk_bot/.agents/skills/telegram-to-vk/references/migration-mapping.md +0 -0
  18. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/python_vk_bot/_config.py +0 -0
  19. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/python_vk_bot/bot.py +0 -0
  20. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/python_vk_bot/callback.py +0 -0
  21. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/python_vk_bot/filters.py +0 -0
  22. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/python_vk_bot/long_poll.py +0 -0
  23. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/python_vk_bot/models/__init__.py +0 -0
  24. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/python_vk_bot/models/api.py +0 -0
  25. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/python_vk_bot/models/attachments.py +0 -0
  26. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/python_vk_bot/models/base.py +0 -0
  27. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/python_vk_bot/models/events.py +0 -0
  28. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/python_vk_bot/models/keyboards.py +0 -0
  29. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/python_vk_bot/models/messages.py +0 -0
  30. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/python_vk_bot/py.typed +0 -0
  31. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/python_vk_bot/settings.py +0 -0
  32. {python_vk_bot-0.3.0 → python_vk_bot-0.4.0}/python_vk_bot/transport.py +0 -0
@@ -2,6 +2,24 @@
2
2
 
3
3
  All notable changes will be documented here, following Keep a Changelog.
4
4
 
5
+ ## 0.4.0 - 2026-11-03
6
+
7
+ ### Added
8
+
9
+ - `ApplicationHandlerStop` to finish the current event successfully and skip later groups.
10
+ - `TypeHandler` and a bounded `Application.update_queue` for internal Python objects and
11
+ VK updates, with explicit user/peer state scopes and `Context.event`.
12
+ - `Application.create_task` for owned finite tasks and workers cancelled on stop.
13
+ - A once-per-run `post_stop` hook before Bot shutdown, and a local background-result example.
14
+
15
+ ### Changed
16
+
17
+ - Event processing uses a unified serial FIFO. Callback acknowledgement still waits for
18
+ dispatch; request cancellation cancels that event's pending or active execution.
19
+ - **Breaking:** after `stop()`, complete `shutdown()` and `initialize()` before starting
20
+ another run. Registration stays closed until shutdown completes. See the
21
+ [lifecycle and queue contracts](docs/development/event-processing.md#lifecycle-and-cleanup).
22
+
5
23
  ## 0.3.0 - 2026-11-02
6
24
 
7
25
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: python-vk-bot
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: An asynchronous framework for VK community bots.
5
5
  Project-URL: Homepage, https://github.com/fomenko-ai/python-vk-bot
6
6
  Project-URL: Repository, https://github.com/fomenko-ai/python-vk-bot
@@ -74,6 +74,7 @@ See the [examples guide](examples/README.md) for setup, required events and run
74
74
  | [Keyboards](examples/keyboards.py) | Ordinary text buttons and inline callback buttons with message editing |
75
75
  | [Interactive map](examples/interactive_map.py) | Generate, upload and replace a PNG using navigation buttons |
76
76
  | [Callback receiver](examples/callback.py) | Receive events through an ASGI application |
77
+ | [Background result](examples/background_result.py) | Return a local calculation through the unified event queue |
77
78
 
78
79
  ## Long Poll bot
79
80
 
@@ -287,6 +288,18 @@ The media API has network-free regression tests. Actual replacement of a photo i
287
288
  existing VK message has not yet been verified with a live token; an explicitly enabled
288
289
  [integration test](docs/development/media-api.md#live-integration-test) is provided.
289
290
 
291
+ ## Background tasks and internal events
292
+
293
+ Use `Application.create_task()` for background operations and `update_queue.put()` to
294
+ return Python objects to the shared serial dispatcher. `TypeHandler` routes these results;
295
+ `ApplicationHandlerStop` skips later handler groups for the current event. See the
296
+ [background-result example](examples/background_result.py).
297
+
298
+ The application manages task completion and calls `post_stop` before closing Bot.
299
+ Queue capacity, state scopes, cancellation, workers and shutdown are described in the
300
+ [event processing guide](docs/development/event-processing.md). The queue is in memory
301
+ and does not preserve work across restarts.
302
+
290
303
  ## Agent Skills
291
304
 
292
305
  The bundled **telegram-to-vk** Agent Skill helps AI coding agents migrate
@@ -48,6 +48,7 @@ See the [examples guide](examples/README.md) for setup, required events and run
48
48
  | [Keyboards](examples/keyboards.py) | Ordinary text buttons and inline callback buttons with message editing |
49
49
  | [Interactive map](examples/interactive_map.py) | Generate, upload and replace a PNG using navigation buttons |
50
50
  | [Callback receiver](examples/callback.py) | Receive events through an ASGI application |
51
+ | [Background result](examples/background_result.py) | Return a local calculation through the unified event queue |
51
52
 
52
53
  ## Long Poll bot
53
54
 
@@ -261,6 +262,18 @@ The media API has network-free regression tests. Actual replacement of a photo i
261
262
  existing VK message has not yet been verified with a live token; an explicitly enabled
262
263
  [integration test](docs/development/media-api.md#live-integration-test) is provided.
263
264
 
265
+ ## Background tasks and internal events
266
+
267
+ Use `Application.create_task()` for background operations and `update_queue.put()` to
268
+ return Python objects to the shared serial dispatcher. `TypeHandler` routes these results;
269
+ `ApplicationHandlerStop` skips later handler groups for the current event. See the
270
+ [background-result example](examples/background_result.py).
271
+
272
+ The application manages task completion and calls `post_stop` before closing Bot.
273
+ Queue capacity, state scopes, cancellation, workers and shutdown are described in the
274
+ [event processing guide](docs/development/event-processing.md). The queue is in memory
275
+ and does not preserve work across restarts.
276
+
264
277
  ## Agent Skills
265
278
 
266
279
  The bundled **telegram-to-vk** Agent Skill helps AI coding agents migrate
@@ -25,6 +25,7 @@ The Callback example uses its own HTTP delivery setup instead.
25
25
  | [keyboards.py](keyboards.py) | Ordinary and inline keyboards, payloads and message editing | `message_new`, `message_event` |
26
26
  | [interactive_map.py](interactive_map.py) | Photo upload and replacement with inline navigation | `message_new`, `message_event` |
27
27
  | [callback.py](callback.py) | A Callback API receiver using an ASGI factory | `message_new` |
28
+ | [background_result.py](background_result.py) | Managed computation, TypeHandler and event dispatch stopping | `message_new` |
28
29
 
29
30
  ## Echo bot
30
31
 
@@ -95,3 +96,21 @@ API settings. The confirmation value must match the code provided by VK.
95
96
  The receiver echoes text messages. `CallbackSettings` extends `BotSettings` with the
96
97
  required secret and confirmation fields, and the ASGI lifespan manages the application's
97
98
  resources. See [Callback API](../README.md#callback-api) for delivery semantics.
99
+
100
+ ## Background calculation
101
+
102
+ ```bash
103
+ uv run python examples/background_result.py
104
+ ```
105
+
106
+ Send `/background hello`. The command acknowledges the request, starts an owned finite
107
+ coroutine and raises ApplicationHandlerStop to skip later groups. The local coroutine
108
+ counts characters after a short asynchronous delay, then puts a BackgroundResult in the
109
+ same queue as incoming VK events. Its TypeHandler sends the result and updates peer_data.
110
+ The calculation uses no AI, speech models, database or broker. Running the full example
111
+ uses live VK for polling and messages; configure can also register the handlers on an
112
+ Application with a mocked Bot for offline verification.
113
+
114
+ The background coroutine never changes shared state directly. Queue admission does not
115
+ persist the job; restarts can lose it. Finite tasks are awaited on shutdown with the
116
+ consumer still active. See [queue and lifecycle contracts](../docs/development/event-processing.md).
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "python-vk-bot"
7
- version = "0.3.0"
7
+ version = "0.4.0"
8
8
  description = "An asynchronous framework for VK community bots."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.14"
@@ -5,7 +5,8 @@ from .application import Application
5
5
  from .bot import Bot
6
6
  from .callback import Callback
7
7
  from .context import Context
8
- from .handlers import CommandHandler, Handler, MessageEventHandler, MessageHandler
8
+ from .errors import ApplicationHandlerStop
9
+ from .handlers import CommandHandler, Handler, MessageEventHandler, MessageHandler, TypeHandler
9
10
  from .long_poll import LongPoll
10
11
  from .models import (
11
12
  Attachment,
@@ -23,10 +24,12 @@ from .models import (
23
24
  User,
24
25
  VideoAttachment,
25
26
  )
27
+ from .queues import UpdateQueue
26
28
  from .settings import BotSettings
27
29
 
28
30
  __all__ = [
29
31
  "Application",
32
+ "ApplicationHandlerStop",
30
33
  "Attachment",
31
34
  "AudioMessageAttachment",
32
35
  "Bot",
@@ -47,7 +50,9 @@ __all__ = [
47
50
  "MessageHandler",
48
51
  "PhotoAttachment",
49
52
  "TextButton",
53
+ "TypeHandler",
50
54
  "Update",
55
+ "UpdateQueue",
51
56
  "User",
52
57
  "VideoAttachment",
53
58
  "filters",
@@ -0,0 +1,491 @@
1
+ """Serial queued dispatch, managed tasks, and explicit resource ownership."""
2
+
3
+ import asyncio
4
+ import logging
5
+ from collections import OrderedDict
6
+ from collections.abc import Awaitable, Callable, Coroutine
7
+ from contextlib import aclosing, suppress
8
+ from types import TracebackType
9
+ from typing import Self
10
+
11
+ from .bot import Bot
12
+ from .context import Context
13
+ from .errors import ApplicationHandlerStop, LifecycleError
14
+ from .handlers import Handler, TypeHandler, _DispatchHandler
15
+ from .long_poll import LongPoll
16
+ from .models import Update
17
+ from .queues import UpdateQueue, _QueueItem
18
+
19
+ type ErrorCallback = Callable[[Update | None, Context], Awaitable[None]]
20
+ type LifecycleHook = Callable[[Application], Awaitable[None]]
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ async def _await_owned[T](task: asyncio.Task[T]) -> T:
26
+ """Finish owned cleanup even on repeated caller cancellation, then propagate it."""
27
+ interrupted = False
28
+ while not task.done():
29
+ try:
30
+ await asyncio.shield(task)
31
+ except asyncio.CancelledError:
32
+ interrupted = True
33
+ except BaseException:
34
+ break
35
+ if interrupted:
36
+ if not task.cancelled():
37
+ task.exception()
38
+ raise asyncio.CancelledError
39
+ return task.result()
40
+
41
+
42
+ class Application:
43
+ def __init__(
44
+ self,
45
+ bot: Bot,
46
+ group_id: int,
47
+ *,
48
+ deduplication_size: int = 4096,
49
+ update_queue_size: int = 256,
50
+ post_init: LifecycleHook | None = None,
51
+ post_stop: LifecycleHook | None = None,
52
+ post_shutdown: LifecycleHook | None = None,
53
+ ) -> None:
54
+ if group_id <= 0 or deduplication_size < 0:
55
+ raise ValueError("group_id must be positive and deduplication_size nonnegative")
56
+ self.bot = bot
57
+ self.group_id = group_id
58
+ self.bot_data: dict[str, object] = {}
59
+ self.user_data: dict[int, dict[str, object]] = {}
60
+ self.peer_data: dict[int, dict[str, object]] = {}
61
+ self._handlers: dict[int, list[_DispatchHandler]] = {}
62
+ self._error_handlers: list[ErrorCallback] = []
63
+ self._seen: OrderedDict[str, None] = OrderedDict()
64
+ self._deduplication_size = deduplication_size
65
+ self._post_init = post_init
66
+ self._post_stop = post_stop
67
+ self._post_shutdown = post_shutdown
68
+ self._lifecycle_lock = asyncio.Lock()
69
+ self._initialized = False
70
+ self._context_active = False
71
+ self._running = False
72
+ self._started = False
73
+ self._queue_open = False
74
+ self._post_stop_pending = False
75
+ self._update_queue = UpdateQueue(self, update_queue_size)
76
+ self._tasks: dict[asyncio.Task[object], bool] = {}
77
+ self._polling_task: asyncio.Task[None] | None = None
78
+ self._polling_waiting = False
79
+ self._consumer_task: asyncio.Task[None] | None = None
80
+ self._processing_task: asyncio.Task[bool] | None = None
81
+ self._finishing_handler: asyncio.Task[bool] | None = None
82
+ self._hook_task: asyncio.Task[object] | None = None
83
+ self._stop_task: asyncio.Task[None] | None = None
84
+ self._shutdown_task: asyncio.Task[None] | None = None
85
+
86
+ @property
87
+ def running(self) -> bool:
88
+ return self._running
89
+
90
+ @property
91
+ def update_queue(self) -> UpdateQueue:
92
+ """The current run's producer interface; only Application consumes events."""
93
+ return self._update_queue
94
+
95
+ def _check_lifecycle(self, *, stopping: bool = False) -> None:
96
+ current = asyncio.current_task()
97
+ if current is self._hook_task:
98
+ raise LifecycleError("Lifecycle hooks cannot recursively invoke lifecycle methods")
99
+ if not stopping and (current is self._processing_task or current in self._tasks):
100
+ raise LifecycleError(
101
+ "Use stop() inside a handler or task; shutdown belongs to the owner"
102
+ )
103
+
104
+ def add_handler[T](self, handler: Handler | TypeHandler[T], *, group: int = 0) -> None:
105
+ if self._started:
106
+ raise LifecycleError("Register handlers before starting the application")
107
+ self._handlers.setdefault(group, []).append(handler)
108
+
109
+ def add_error_handler(self, callback: ErrorCallback) -> None:
110
+ if self._started:
111
+ raise LifecycleError("Register error handlers before starting the application")
112
+ self._error_handlers.append(callback)
113
+
114
+ async def _call_hook(self, hook: LifecycleHook | None) -> None:
115
+ if hook is None:
116
+ return
117
+ self._hook_task = asyncio.current_task()
118
+ try:
119
+ await hook(self)
120
+ finally:
121
+ self._hook_task = None
122
+
123
+ async def initialize(self) -> None:
124
+ self._check_lifecycle()
125
+ if self._shutdown_task is not None and not self._shutdown_task.done():
126
+ raise LifecycleError("Application shutdown is in progress")
127
+ self._shutdown_task = None
128
+ async with self._lifecycle_lock:
129
+ if self._initialized:
130
+ return
131
+ try:
132
+ await self.bot.initialize()
133
+ await self._call_hook(self._post_init)
134
+ except BaseException:
135
+ cleanup = asyncio.create_task(self.bot.shutdown(), name="vk-startup-cleanup")
136
+ try:
137
+ await _await_owned(cleanup)
138
+ except BaseException as error:
139
+ logger.error("Startup cleanup failed (%s)", type(error).__name__)
140
+ raise
141
+ self._initialized = True
142
+
143
+ async def start(self) -> None:
144
+ self._check_lifecycle()
145
+ if not self._initialized:
146
+ raise LifecycleError("Initialize the application before starting it")
147
+ if self._shutdown_task is not None:
148
+ raise LifecycleError("Application shutdown is in progress")
149
+ if self._running:
150
+ return
151
+ if self._started:
152
+ raise LifecycleError("Shut down and initialize before starting another run")
153
+ if self._update_queue._closed:
154
+ self._update_queue = UpdateQueue(self, self._update_queue.maxsize)
155
+ self._stop_task = None
156
+ self._finishing_handler = None
157
+ self._queue_open = True
158
+ self._running = True
159
+ self._started = True
160
+ self._post_stop_pending = True
161
+ self._consumer_task = asyncio.create_task(self._consume(), name="vk-update-consumer")
162
+
163
+ async def stop(self) -> None:
164
+ """Stop intake and drain accepted work. Does not invoke post_stop or close Bot.
165
+
166
+ Inside a handler or managed task this requests stopping without awaiting
167
+ that same task. An external owner can await stop/shutdown for completion.
168
+ """
169
+ self._check_lifecycle(stopping=True)
170
+ if not self._started:
171
+ return
172
+ if self._stop_task is None:
173
+ self._running = False
174
+ self._finishing_handler = self._processing_task
175
+ self._update_queue._space.set()
176
+ self._stop_task = asyncio.create_task(self._stop(), name="vk-application-stop")
177
+ current = asyncio.current_task()
178
+ if current is self._processing_task or current in self._tasks:
179
+ return
180
+ await _await_owned(self._stop_task)
181
+
182
+ async def _stop(self) -> None:
183
+ # Polling awaiting a receipt must finish it; cancelling it would cancel
184
+ # the active handler. Only interrupt polling that is acquiring updates.
185
+ polling = self._polling_task
186
+ if polling is not None:
187
+ if not self._polling_waiting:
188
+ polling.cancel()
189
+ await asyncio.gather(polling, return_exceptions=True)
190
+ if self._finishing_handler is not None:
191
+ await asyncio.gather(self._finishing_handler, return_exceptions=True)
192
+ tasks = tuple(self._tasks)
193
+ for task in tasks:
194
+ if self._tasks.get(task):
195
+ task.cancel()
196
+ if tasks:
197
+ await asyncio.gather(*tasks, return_exceptions=True)
198
+ self._queue_open = False
199
+ self._update_queue._close()
200
+ if self._consumer_task is not None:
201
+ await self._consumer_task
202
+ self._finishing_handler = None
203
+
204
+ async def shutdown(self) -> None:
205
+ """Drain, invoke post_stop once, close Bot, then invoke post_shutdown."""
206
+ self._check_lifecycle()
207
+ if self._shutdown_task is None:
208
+ self._shutdown_task = asyncio.create_task(
209
+ self._shutdown(), name="vk-application-shutdown"
210
+ )
211
+ await _await_owned(self._shutdown_task)
212
+
213
+ async def _shutdown(self) -> None:
214
+ # Wait for initialization, but never retain this lock while waiting for
215
+ # handlers/tasks: their lifecycle requests are rejected or request stop.
216
+ async with self._lifecycle_lock:
217
+ initialized = self._initialized
218
+ if not initialized:
219
+ return
220
+ failure: BaseException | None = None
221
+ try:
222
+ await self.stop()
223
+ except BaseException as error:
224
+ failure = error
225
+ if self._post_stop_pending:
226
+ self._post_stop_pending = False
227
+ try:
228
+ await self._call_hook(self._post_stop)
229
+ except BaseException as error:
230
+ if failure is None:
231
+ failure = error
232
+ else:
233
+ logger.error("Post-stop hook failed (%s)", type(error).__name__)
234
+ try:
235
+ await self.bot.shutdown()
236
+ except BaseException as error:
237
+ if failure is None:
238
+ failure = error
239
+ else:
240
+ logger.error("Bot shutdown failed (%s)", type(error).__name__)
241
+ finally:
242
+ self._initialized = False
243
+ try:
244
+ await self._call_hook(self._post_shutdown)
245
+ except BaseException as error:
246
+ if failure is None:
247
+ failure = error
248
+ else:
249
+ logger.error("Post-shutdown hook failed (%s)", type(error).__name__)
250
+ finally:
251
+ self._started = False
252
+ if failure is not None:
253
+ raise failure
254
+
255
+ async def __aenter__(self) -> Self:
256
+ if self._initialized or self._context_active:
257
+ raise LifecycleError("Application context managers cannot be nested")
258
+ self._context_active = True
259
+ try:
260
+ await self.initialize()
261
+ await self.start()
262
+ except BaseException:
263
+ try:
264
+ await self.shutdown()
265
+ except BaseException as error:
266
+ logger.error("Application startup cleanup failed (%s)", type(error).__name__)
267
+ finally:
268
+ self._context_active = False
269
+ raise
270
+ return self
271
+
272
+ async def __aexit__(
273
+ self,
274
+ exc_type: type[BaseException] | None,
275
+ exc: BaseException | None,
276
+ traceback: TracebackType | None,
277
+ ) -> None:
278
+ try:
279
+ await self.shutdown()
280
+ except BaseException as error:
281
+ if exc is None:
282
+ raise
283
+ logger.error("Application cleanup failed (%s)", type(error).__name__)
284
+ finally:
285
+ self._context_active = False
286
+
287
+ def _check_enqueue(self, queue: UpdateQueue, item: _QueueItem) -> None:
288
+ current = asyncio.current_task()
289
+ finishing = current is self._finishing_handler or current in self._tasks
290
+ if (
291
+ queue is not self._update_queue
292
+ or not self._queue_open
293
+ or not (self._running or finishing)
294
+ ):
295
+ raise LifecycleError("Application is not running or accepting events")
296
+ if isinstance(item.event, Update):
297
+ if item.event.group_id != self.group_id:
298
+ raise ValueError("Update belongs to another community")
299
+ if item.user_id is not None or item.peer_id is not None:
300
+ raise ValueError("VK update state scopes are supplied by the update")
301
+
302
+ def _context(self, item: _QueueItem, error: Exception | None = None) -> Context:
303
+ event = item.event
304
+ user_id = event.user_id if isinstance(event, Update) else item.user_id
305
+ peer_id = event.peer_id if isinstance(event, Update) else item.peer_id
306
+ return Context(
307
+ application=self,
308
+ bot=self.bot,
309
+ user_data=self.user_data.setdefault(user_id, {}) if user_id is not None else {},
310
+ peer_data=self.peer_data.setdefault(peer_id, {}) if peer_id is not None else {},
311
+ bot_data=self.bot_data,
312
+ error=error,
313
+ event=event,
314
+ )
315
+
316
+ async def _report_error(self, item: _QueueItem, error: Exception) -> None:
317
+ context = self._context(item, error)
318
+ update = item.event if isinstance(item.event, Update) else None
319
+ logger.error("Event processing failed (%s)", type(error).__name__)
320
+ for callback in self._error_handlers:
321
+ try:
322
+ await callback(update, context)
323
+ except ApplicationHandlerStop:
324
+ break
325
+ except Exception as callback_error:
326
+ logger.error("Error handler failed (%s)", type(callback_error).__name__)
327
+
328
+ async def process_update(
329
+ self, update: object, *, user_id: int | None = None, peer_id: int | None = None
330
+ ) -> bool:
331
+ """Queue and await dispatch; False for a duplicate, otherwise True.
332
+
333
+ Cancellation skips queued work or cancels/awaits the active handler.
334
+ Internal objects can explicitly select user/peer state scopes.
335
+ """
336
+ if self._processing_task is asyncio.current_task():
337
+ raise LifecycleError("Recursive update dispatch is not supported")
338
+ return await self._submit(_QueueItem(update, user_id, peer_id))
339
+
340
+ async def _submit(self, item: _QueueItem) -> bool:
341
+ receipt = asyncio.get_running_loop().create_future()
342
+ item.receipt = receipt
343
+ try:
344
+ await self._update_queue._put(item)
345
+ return await asyncio.shield(receipt)
346
+ except asyncio.CancelledError:
347
+ item.cancelled = True
348
+ if receipt.done() and not receipt.cancelled():
349
+ receipt.exception()
350
+ receipt.cancel()
351
+ if item.task is not None and not item.task.done():
352
+ item.task.cancel()
353
+ with suppress(BaseException):
354
+ await _await_owned(item.task)
355
+ raise
356
+
357
+ async def _consume(self) -> None:
358
+ while True:
359
+ try:
360
+ item = await self._update_queue._get()
361
+ except asyncio.QueueShutDown:
362
+ return
363
+ try:
364
+ if item.cancelled:
365
+ continue
366
+ task = asyncio.create_task(self._dispatch(item), name="vk-event-dispatch")
367
+ item.task = task
368
+ self._processing_task = task
369
+ try:
370
+ result = await task
371
+ except asyncio.CancelledError:
372
+ if item.receipt is not None and not item.receipt.done():
373
+ item.receipt.cancel()
374
+ current = asyncio.current_task()
375
+ if current is not None and current.cancelling():
376
+ raise
377
+ except Exception as error:
378
+ if item.receipt is not None and not item.receipt.done():
379
+ item.receipt.set_exception(error)
380
+ else:
381
+ if item.receipt is not None and not item.receipt.done():
382
+ item.receipt.set_result(result)
383
+ finally:
384
+ self._processing_task = None
385
+ finally:
386
+ self._update_queue._queue.task_done()
387
+
388
+ async def _dispatch(self, item: _QueueItem) -> bool:
389
+ if item.error is not None:
390
+ await self._report_error(item, item.error)
391
+ return True
392
+ event = item.event
393
+ if isinstance(event, Update):
394
+ if event.group_id != self.group_id:
395
+ raise ValueError("Update belongs to another community")
396
+ if event.event_id in self._seen:
397
+ return False
398
+ try:
399
+ context = self._context(item)
400
+ for group in sorted(self._handlers):
401
+ for handler in self._handlers[group]:
402
+ if await handler._dispatch(event, context):
403
+ break
404
+ except ApplicationHandlerStop:
405
+ pass
406
+ except Exception as error:
407
+ await self._report_error(item, error)
408
+ raise
409
+ if isinstance(event, Update) and self._deduplication_size:
410
+ self._seen[event.event_id] = None
411
+ if len(self._seen) > self._deduplication_size:
412
+ self._seen.popitem(last=False)
413
+ return True
414
+
415
+ def create_task[T](
416
+ self,
417
+ coroutine: Coroutine[object, object, T],
418
+ *,
419
+ update: object = None,
420
+ name: str | None = None,
421
+ cancel_on_stop: bool = False,
422
+ ) -> asyncio.Task[T]:
423
+ """Own a running coroutine, report failures serially, and await it on stop.
424
+
425
+ Use cancel_on_stop for long-lived workers. Tasks must not directly mutate
426
+ Context state or be awaited by a handler if they depend on the consumer.
427
+ """
428
+ if not self._running:
429
+ coroutine.close()
430
+ raise LifecycleError("Create tasks only while the application is running")
431
+ if isinstance(update, Update) and update.group_id != self.group_id:
432
+ coroutine.close()
433
+ raise ValueError("Update belongs to another community")
434
+
435
+ async def run() -> T:
436
+ try:
437
+ return await coroutine
438
+ except Exception as error:
439
+ try:
440
+ await self._submit(_QueueItem(update, error=error))
441
+ except Exception as reporting_error:
442
+ logger.error("Task error reporting failed (%s)", type(reporting_error).__name__)
443
+ raise
444
+
445
+ task = asyncio.create_task(run(), name=name)
446
+ self._tasks[task] = cancel_on_stop
447
+
448
+ def finished(done: asyncio.Task[T]) -> None:
449
+ self._tasks.pop(done, None)
450
+ # Also close a coroutine cancelled before the wrapper's first step.
451
+ coroutine.close()
452
+ if not done.cancelled():
453
+ done.exception()
454
+
455
+ task.add_done_callback(finished)
456
+ return task
457
+
458
+ async def _poll(self, long_poll: LongPoll) -> None:
459
+ async with aclosing(long_poll.listen()) as updates:
460
+ async for update in updates:
461
+ if not self._running:
462
+ break
463
+ self._polling_waiting = True
464
+ try:
465
+ await self.process_update(update)
466
+ except Exception:
467
+ logger.warning("Skipping failed update in polling mode")
468
+ finally:
469
+ self._polling_waiting = False
470
+ if not self._running:
471
+ break
472
+
473
+ async def run_polling(self, *, wait: int = 25) -> None:
474
+ """Run until stop/cancellation; own lifecycle, not the caller's event loop."""
475
+ if self._polling_task is not None:
476
+ raise LifecycleError("Polling is already running")
477
+ long_poll = LongPoll(self.bot, self.group_id, wait=wait)
478
+ async with self:
479
+ task = asyncio.create_task(self._poll(long_poll), name="vk-long-poll")
480
+ self._polling_task = task
481
+ try:
482
+ await task
483
+ except asyncio.CancelledError:
484
+ current = asyncio.current_task()
485
+ if current is not None and current.cancelling():
486
+ raise
487
+ except Exception as error:
488
+ await self._submit(_QueueItem(None, error=error))
489
+ raise
490
+ finally:
491
+ self._polling_task = None
@@ -17,3 +17,4 @@ class Context:
17
17
  peer_data: dict[str, object]
18
18
  bot_data: dict[str, object]
19
19
  error: Exception | None = field(default=None, repr=False)
20
+ event: object | None = field(default=None, repr=False)
@@ -1,6 +1,10 @@
1
1
  """Safe exceptions: messages never include credentials or server payloads."""
2
2
 
3
3
 
4
+ class ApplicationHandlerStop(Exception):
5
+ """Finish the current event successfully without invoking further handlers."""
6
+
7
+
4
8
  class VKError(Exception):
5
9
  """Base class for library errors."""
6
10
 
@@ -1,6 +1,7 @@
1
1
  """Typed handler registration without a conversation-state framework."""
2
2
 
3
3
  from collections.abc import Awaitable, Callable
4
+ from typing import Protocol, TypeGuard
4
5
 
5
6
  from . import filters
6
7
  from .context import Context
@@ -9,6 +10,10 @@ from .models import Update
9
10
  type HandlerCallback = Callable[[Update, Context], Awaitable[None]]
10
11
 
11
12
 
13
+ class _DispatchHandler(Protocol):
14
+ async def _dispatch(self, update: object, context: Context) -> bool: ...
15
+
16
+
12
17
  class Handler:
13
18
  def __init__(
14
19
  self, callback: HandlerCallback, *, predicate: filters.Filter = filters.ALL
@@ -22,6 +27,39 @@ class Handler:
22
27
  async def handle_update(self, update: Update, context: Context) -> None:
23
28
  await self.callback(update, context)
24
29
 
30
+ async def _dispatch(self, update: object, context: Context) -> bool:
31
+ if not isinstance(update, Update) or not self.check_update(update):
32
+ return False
33
+ await self.handle_update(update, context)
34
+ return True
35
+
36
+
37
+ class TypeHandler[T]:
38
+ """Route a Python object by type, including validated VK Updates."""
39
+
40
+ def __init__(
41
+ self,
42
+ update_type: type[T],
43
+ callback: Callable[[T, Context], Awaitable[None]],
44
+ *,
45
+ strict: bool = False,
46
+ ) -> None:
47
+ self.type = update_type
48
+ self.callback = callback
49
+ self.strict = strict
50
+
51
+ def check_update(self, update: object) -> TypeGuard[T]:
52
+ return type(update) is self.type if self.strict else isinstance(update, self.type)
53
+
54
+ async def handle_update(self, update: T, context: Context) -> None:
55
+ await self.callback(update, context)
56
+
57
+ async def _dispatch(self, update: object, context: Context) -> bool:
58
+ if not self.check_update(update):
59
+ return False
60
+ await self.handle_update(update, context)
61
+ return True
62
+
25
63
 
26
64
  class MessageHandler(Handler):
27
65
  def __init__(
@@ -0,0 +1,86 @@
1
+ """Bounded, application-owned event admission; only Application consumes events."""
2
+
3
+ import asyncio
4
+ from dataclasses import dataclass, field
5
+ from typing import TYPE_CHECKING
6
+
7
+ if TYPE_CHECKING:
8
+ from .application import Application
9
+
10
+
11
+ @dataclass(slots=True)
12
+ class _QueueItem:
13
+ event: object
14
+ user_id: int | None = None
15
+ peer_id: int | None = None
16
+ error: Exception | None = field(default=None, repr=False)
17
+ receipt: asyncio.Future[bool] | None = field(default=None, repr=False)
18
+ task: asyncio.Task[bool] | None = field(default=None, repr=False)
19
+ cancelled: bool = False
20
+
21
+
22
+ class UpdateQueue:
23
+ """Producer interface to Application's FIFO, not a standalone asyncio.Queue.
24
+
25
+ put waits for capacity outside handlers. In a handler, a full queue raises
26
+ QueueFull instead of waiting for the consumer that is awaiting that handler.
27
+ Items and their state scopes are process-local; no durable acceptance is implied.
28
+ """
29
+
30
+ def __init__(self, application: Application, maxsize: int) -> None:
31
+ if maxsize <= 0:
32
+ raise ValueError("update_queue_size must be positive")
33
+ self._application = application
34
+ self._queue: asyncio.Queue[_QueueItem] = asyncio.Queue(maxsize)
35
+ self._space = asyncio.Event()
36
+ self._closed = False
37
+
38
+ @property
39
+ def maxsize(self) -> int:
40
+ return self._queue.maxsize
41
+
42
+ def qsize(self) -> int:
43
+ return self._queue.qsize()
44
+
45
+ def empty(self) -> bool:
46
+ return self._queue.empty()
47
+
48
+ def full(self) -> bool:
49
+ return self._queue.full()
50
+
51
+ async def put(
52
+ self, update: object, *, user_id: int | None = None, peer_id: int | None = None
53
+ ) -> None:
54
+ """Enqueue an event, waiting for capacity; does not wait for dispatch."""
55
+ await self._put(_QueueItem(update, user_id, peer_id))
56
+
57
+ def put_nowait(
58
+ self, update: object, *, user_id: int | None = None, peer_id: int | None = None
59
+ ) -> None:
60
+ """Enqueue an event or raise QueueFull/LifecycleError without waiting."""
61
+ self._put_nowait(_QueueItem(update, user_id, peer_id))
62
+
63
+ def _put_nowait(self, item: _QueueItem) -> None:
64
+ self._application._check_enqueue(self, item)
65
+ self._queue.put_nowait(item)
66
+
67
+ async def _put(self, item: _QueueItem) -> None:
68
+ while True:
69
+ try:
70
+ self._put_nowait(item)
71
+ return
72
+ except asyncio.QueueFull:
73
+ if self._application._processing_task is asyncio.current_task():
74
+ raise
75
+ self._space.clear()
76
+ await self._space.wait()
77
+
78
+ async def _get(self) -> _QueueItem:
79
+ item = await self._queue.get()
80
+ self._space.set()
81
+ return item
82
+
83
+ def _close(self) -> None:
84
+ self._closed = True
85
+ self._queue.shutdown()
86
+ self._space.set()
@@ -1,221 +0,0 @@
1
- """Serial dispatch with explicit lifecycle and bounded duplicate suppression."""
2
-
3
- import asyncio
4
- import logging
5
- from collections import OrderedDict
6
- from collections.abc import Awaitable, Callable
7
- from contextlib import aclosing
8
- from types import TracebackType
9
- from typing import Self
10
-
11
- from .bot import Bot
12
- from .context import Context
13
- from .errors import LifecycleError
14
- from .handlers import Handler
15
- from .long_poll import LongPoll
16
- from .models import Update
17
-
18
- type ErrorCallback = Callable[[Update | None, Context], Awaitable[None]]
19
- type LifecycleHook = Callable[[Application], Awaitable[None]]
20
-
21
- logger = logging.getLogger(__name__)
22
-
23
-
24
- class Application:
25
- def __init__(
26
- self,
27
- bot: Bot,
28
- group_id: int,
29
- *,
30
- deduplication_size: int = 4096,
31
- post_init: LifecycleHook | None = None,
32
- post_shutdown: LifecycleHook | None = None,
33
- ) -> None:
34
- if group_id <= 0 or deduplication_size < 0:
35
- raise ValueError("group_id must be positive and deduplication_size nonnegative")
36
- self.bot = bot
37
- self.group_id = group_id
38
- self.bot_data: dict[str, object] = {}
39
- self.user_data: dict[int, dict[str, object]] = {}
40
- self.peer_data: dict[int, dict[str, object]] = {}
41
- self._handlers: dict[int, list[Handler]] = {}
42
- self._error_handlers: list[ErrorCallback] = []
43
- self._seen: OrderedDict[str, None] = OrderedDict()
44
- self._deduplication_size = deduplication_size
45
- self._post_init = post_init
46
- self._post_shutdown = post_shutdown
47
- self._dispatch_lock = asyncio.Lock()
48
- self._lifecycle_lock = asyncio.Lock()
49
- self._initialized = False
50
- self._context_active = False
51
- self._running = False
52
- self._polling_task: asyncio.Task[None] | None = None
53
- self._processing_task: asyncio.Task[object] | None = None
54
-
55
- @property
56
- def running(self) -> bool:
57
- return self._running
58
-
59
- def add_handler(self, handler: Handler, *, group: int = 0) -> None:
60
- if self._running:
61
- raise LifecycleError("Register handlers before starting the application")
62
- self._handlers.setdefault(group, []).append(handler)
63
-
64
- def add_error_handler(self, callback: ErrorCallback) -> None:
65
- if self._running:
66
- raise LifecycleError("Register error handlers before starting the application")
67
- self._error_handlers.append(callback)
68
-
69
- async def initialize(self) -> None:
70
- async with self._lifecycle_lock:
71
- if self._initialized:
72
- return
73
- try:
74
- await self.bot.initialize()
75
- if self._post_init is not None:
76
- await self._post_init(self)
77
- except BaseException:
78
- await self.bot.shutdown()
79
- raise
80
- self._initialized = True
81
-
82
- async def start(self) -> None:
83
- if not self._initialized:
84
- raise LifecycleError("Initialize the application before starting it")
85
- self._running = True
86
-
87
- async def stop(self) -> None:
88
- """Stop intake, cancel owned polling, and wait for active dispatch to finish.
89
-
90
- A handler may call stop: its current dispatch completes before polling exits.
91
- """
92
- self._running = False
93
- task = self._polling_task
94
- current = asyncio.current_task()
95
- if task is not None and task is not current:
96
- task.cancel()
97
- await asyncio.gather(task, return_exceptions=True)
98
- if self._processing_task is not current:
99
- async with self._dispatch_lock:
100
- pass
101
-
102
- async def shutdown(self) -> None:
103
- if self._processing_task is asyncio.current_task():
104
- raise LifecycleError("Use stop() inside a handler; shutdown belongs to the owner")
105
- await self.stop()
106
- async with self._lifecycle_lock:
107
- if not self._initialized:
108
- return
109
- try:
110
- await self.bot.shutdown()
111
- finally:
112
- self._initialized = False
113
- if self._post_shutdown is not None:
114
- await self._post_shutdown(self)
115
-
116
- async def __aenter__(self) -> Self:
117
- if self._initialized or self._context_active:
118
- raise LifecycleError("Application context managers cannot be nested")
119
- self._context_active = True
120
- try:
121
- await self.initialize()
122
- await self.start()
123
- except BaseException:
124
- self._context_active = False
125
- raise
126
- return self
127
-
128
- async def __aexit__(
129
- self,
130
- exc_type: type[BaseException] | None,
131
- exc: BaseException | None,
132
- traceback: TracebackType | None,
133
- ) -> None:
134
- try:
135
- await self.shutdown()
136
- finally:
137
- self._context_active = False
138
-
139
- def _context(self, update: Update | None, error: Exception | None = None) -> Context:
140
- user_id = update.user_id if update is not None else None
141
- peer_id = update.peer_id if update is not None else None
142
- return Context(
143
- application=self,
144
- bot=self.bot,
145
- user_data=self.user_data.setdefault(user_id, {}) if user_id is not None else {},
146
- peer_data=self.peer_data.setdefault(peer_id, {}) if peer_id is not None else {},
147
- bot_data=self.bot_data,
148
- error=error,
149
- )
150
-
151
- async def _report_error(self, update: Update | None, error: Exception) -> None:
152
- context = self._context(update, error)
153
- logger.error("Update processing failed (%s)", type(error).__name__)
154
- for callback in self._error_handlers:
155
- try:
156
- await callback(update, context)
157
- except Exception as callback_error:
158
- logger.error("Error handler failed (%s)", type(callback_error).__name__)
159
-
160
- async def process_update(self, update: Update) -> bool:
161
- """Return False for a duplicate, True after dispatch; propagate handler errors."""
162
- if self._processing_task is asyncio.current_task():
163
- raise LifecycleError("Recursive update dispatch is not supported")
164
- async with self._dispatch_lock:
165
- if not self._running:
166
- raise LifecycleError("Application is not running")
167
- if update.group_id != self.group_id:
168
- raise ValueError("Update belongs to another community")
169
- if update.event_id in self._seen:
170
- return False
171
- self._processing_task = asyncio.current_task()
172
- try:
173
- context = self._context(update)
174
- for group in sorted(self._handlers):
175
- for handler in self._handlers[group]:
176
- if handler.check_update(update):
177
- await handler.handle_update(update, context)
178
- break
179
- except Exception as error:
180
- await self._report_error(update, error)
181
- raise
182
- finally:
183
- self._processing_task = None
184
- if self._deduplication_size:
185
- self._seen[update.event_id] = None
186
- if len(self._seen) > self._deduplication_size:
187
- self._seen.popitem(last=False)
188
- return True
189
-
190
- async def _poll(self, long_poll: LongPoll) -> None:
191
- async with aclosing(long_poll.listen()) as updates:
192
- async for update in updates:
193
- if not self._running:
194
- break
195
- try:
196
- await self.process_update(update)
197
- except Exception:
198
- # Dispatch already reported the error; never replay partial side effects.
199
- logger.warning("Skipping failed update in polling mode")
200
- if not self._running:
201
- break
202
-
203
- async def run_polling(self, *, wait: int = 25) -> None:
204
- """Run until stop or cancellation; own startup and shutdown, not the event loop."""
205
- if self._polling_task is not None:
206
- raise LifecycleError("Polling is already running")
207
- long_poll = LongPoll(self.bot, self.group_id, wait=wait)
208
- async with self:
209
- task = asyncio.create_task(self._poll(long_poll), name="vk-long-poll")
210
- self._polling_task = task
211
- try:
212
- await task
213
- except asyncio.CancelledError:
214
- current = asyncio.current_task()
215
- if current is not None and current.cancelling():
216
- raise
217
- except Exception as error:
218
- await self._report_error(None, error)
219
- raise
220
- finally:
221
- self._polling_task = None
File without changes
File without changes