-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathqueue.py
More file actions
1614 lines (1306 loc) · 52.1 KB
/
queue.py
File metadata and controls
1614 lines (1306 loc) · 52.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from typing import List, Optional, TYPE_CHECKING
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.asyncio import create_async_engine
from .schema import Message, QueueMetrics
from ._types import ENGINE_TYPE, SESSION_TYPE
from ._utils import (
get_session_type,
is_async_session_maker,
is_async_dsn,
)
from .operation import PGMQOperation
if TYPE_CHECKING:
from sqlalchemy.orm import Session
from sqlalchemy.ext.asyncio import AsyncSession
class PGMQueue:
engine: ENGINE_TYPE = None
session_maker: sessionmaker = None
delay: int = 0
vt: int = 30
is_async: bool = False
is_pg_partman_ext_checked: bool = False
def __init__(
self,
dsn: Optional[str] = None,
engine: Optional[ENGINE_TYPE] = None,
session_maker: Optional[sessionmaker] = None,
) -> None:
"""
| There are **3** ways to initialize ``PGMQueue`` class:
| 1. Initialize with a ``dsn``:
.. code-block:: python
from pgmq_sqlalchemy import PGMQueue
pgmq_client = PGMQueue(dsn='postgresql+psycopg://postgres:postgres@localhost:5432/postgres')
# or async dsn
async_pgmq_client = PGMQueue(dsn='postgresql+asyncpg://postgres:postgres@localhost:5432/postgres')
| 2. Initialize with an ``engine`` or ``async_engine``:
.. code-block:: python
from pgmq_sqlalchemy import PGMQueue
from sqlalchemy import create_engine
from sqlalchemy.ext.asyncio import create_async_engine
engine = create_engine('postgresql+psycopg://postgres:postgres@localhost:5432/postgres')
pgmq_client = PGMQueue(engine=engine)
# or async engine
async_engine = create_async_engine('postgresql+asyncpg://postgres:postgres@localhost:5432/postgres')
async_pgmq_client = PGMQueue(engine=async_engine)
| 3. Initialize with a ``session_maker``:
.. code-block:: python
from pgmq_sqlalchemy import PGMQueue
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
engine = create_engine('postgresql+psycopg://postgres:postgres@localhost:5432/postgres')
session_maker = sessionmaker(bind=engine)
pgmq_client = PGMQueue(session_maker=session_maker)
# or async session_maker
async_engine = create_async_engine('postgresql+asyncpg://postgres:postgres@localhost:5432/post
async_session_maker = sessionmaker(bind=async_engine, class_=AsyncSession)
async_pgmq_client = PGMQueue(session_maker=async_session_maker)
Args:
dsn (Optional[str]): Database connection string.
engine (Optional[ENGINE_TYPE]): SQLAlchemy engine (sync or async).
session_maker (Optional[sessionmaker]): SQLAlchemy session maker.
.. note::
| ``PGMQueue`` will **auto create** the ``pgmq`` extension ( and ``pg_partman`` extension if the method is related with **partitioned_queue** ) if it does not exist in the Postgres.
| But you must make sure that the ``pgmq`` extension ( or ``pg_partman`` extension ) already **installed** in the Postgres.
"""
if not dsn and not engine and not session_maker:
raise ValueError("Must provide either dsn, engine, or session_maker")
# initialize the engine and session_maker
if session_maker:
self.session_maker = session_maker
self.is_async = is_async_session_maker(session_maker)
elif engine:
self.engine = engine
self.is_async = self.engine.dialect.is_async
self.session_maker = sessionmaker(
bind=self.engine, class_=get_session_type(self.engine)
)
else:
self.engine = (
create_async_engine(dsn) if is_async_dsn(dsn) else create_engine(dsn)
)
self.is_async = self.engine.dialect.is_async
self.session_maker = sessionmaker(
bind=self.engine, class_=get_session_type(self.engine)
)
def _execute_operation(
self,
op_sync,
session: Optional["Session"],
commit: bool,
*args,
**kwargs,
):
"""Helper method to execute sync or async operations with session management.
Args:
op_sync: The synchronous operation function from PGMQOperation
session: Optional session to use (if None, creates a new one)
commit: Whether to commit the transaction
*args: Positional arguments to pass to the operation
**kwargs: Keyword arguments to pass to the operation
Returns:
The result from the operation
"""
if session is None:
with self.session_maker() as s:
return op_sync(*args, session=s, commit=commit, **kwargs)
return op_sync(*args, session=session, commit=commit, **kwargs)
async def _execute_async_operation(
self,
op_async,
session: Optional["AsyncSession"],
commit: bool,
*args,
**kwargs,
):
"""Helper method to execute sync or async operations with session management.
Args:
op_async: The asynchronous operation function from PGMQOperation
session: Optional session to use (if None, creates a new one)
commit: Whether to commit the transaction
*args: Positional arguments to pass to the operation
**kwargs: Keyword arguments to pass to the operation
Returns:
The result from the operation
"""
if session is None:
async with self.session_maker() as s:
return await op_async(*args, session=s, commit=commit, **kwargs)
return await op_async(*args, session=session, commit=commit, **kwargs)
def create_queue(
self,
queue_name: str,
unlogged: bool = False,
*,
session: Optional[SESSION_TYPE] = None,
commit: bool = True,
) -> None:
"""
.. _unlogged_table: https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-UNLOGGED
.. |unlogged_table| replace:: **UNLOGGED TABLE**
**Create a new queue.**
* if ``unlogged`` is ``True``, the queue will be created as an |unlogged_table|_ .
* ``queue_name`` must be **less than 48 characters**.
.. code-block:: python
pgmq_client.create_queue('my_queue')
# or unlogged table queue
pgmq_client.create_queue('my_queue', unlogged=True)
"""
return self._execute_operation(
PGMQOperation.create_queue,
session,
commit,
queue_name,
unlogged,
)
async def create_queue_async(
self,
queue_name: str,
unlogged: bool = False,
*,
session: Optional[SESSION_TYPE] = None,
commit: bool = True,
) -> None:
"""
**Create a new queue.**
* if ``unlogged`` is ``True``, the queue will be created as an |unlogged_table|_ .
* ``queue_name`` must be **less than 48 characters**.
.. code-block:: python
await pgmq_client.create_queue_async('my_queue')
# or unlogged table queue
await pgmq_client.create_queue_async('my_queue', unlogged=True)
"""
return await self._execute_async_operation(
PGMQOperation.create_queue_async,
session,
commit,
queue_name,
unlogged,
)
def create_partitioned_queue(
self,
queue_name: str,
partition_interval: int = 10000,
retention_interval: int = 100000,
*,
session: Optional[SESSION_TYPE] = None,
commit: bool = True,
) -> None:
"""Create a new **partitioned** queue.
.. _pgmq_partitioned_queue: https://github.com/tembo-io/pgmq?tab=readme-ov-file#partitioned-queues
.. |pgmq_partitioned_queue| replace:: **PGMQ: Partitioned Queues**
.. code-block:: python
# Numeric partitioning (by msg_id)
pgmq_client.create_partitioned_queue('my_partitioned_queue', partition_interval=10000, retention_interval=100000)
# Time-based partitioning (by enqueued_at)
pgmq_client.create_partitioned_queue('my_time_queue', partition_interval='1 day', retention_interval='7 days')
Args:
queue_name (str): The name of the queue, should be less than 48 characters.
partition_interval (Union[int, str]): For numeric partitioning, the number of messages per partition.
For time-based partitioning, a PostgreSQL interval string (e.g., '1 day', '1 hour').
retention_interval (Union[int, str]): For numeric partitioning, messages with msg_id less than max(msg_id) - retention_interval will be dropped.
For time-based partitioning, a PostgreSQL interval string (e.g., '7 days').
.. note::
| Supports both **numeric** (by ``msg_id``) and **time-based** (by ``enqueued_at``) partitioning.
| For time-based partitioning, use interval strings like '1 day', '1 hour', '7 days', etc.
| For numeric partitioning, use integer values.
.. important::
| You must make sure that the ``pg_partman`` extension already **installed** in the Postgres.
| ``pgmq-sqlalchemy`` will **auto create** the ``pg_partman`` extension if it does not exist in the Postgres.
| For more details about ``pgmq`` with ``pg_partman``, checkout the |pgmq_partitioned_queue|_.
"""
# check if the pg_partman extension exists before creating a partitioned queue at runtime
self._execute_operation(
PGMQOperation.check_pg_partman_ext, session=session, commit=False
)
return self._execute_operation(
PGMQOperation.create_partitioned_queue,
session,
commit,
queue_name,
str(partition_interval),
str(retention_interval),
)
async def create_partitioned_queue_async(
self,
queue_name: str,
partition_interval: int = 10000,
retention_interval: int = 100000,
*,
session: Optional[SESSION_TYPE] = None,
commit: bool = True,
) -> None:
"""Create a new **partitioned** queue.
.. code-block:: python
# Numeric partitioning (by msg_id)
await pgmq_client.create_partitioned_queue_async('my_partitioned_queue', partition_interval=10000, retention_interval=100000)
# Time-based partitioning (by enqueued_at)
await pgmq_client.create_partitioned_queue_async('my_time_queue', partition_interval='1 day', retention_interval='7 days')
Args:
queue_name (str): The name of the queue, should be less than 48 characters.
partition_interval (Union[int, str]): For numeric partitioning, the number of messages per partition.
For time-based partitioning, a PostgreSQL interval string (e.g., '1 day', '1 hour').
retention_interval (Union[int, str]): For numeric partitioning, messages with msg_id less than max(msg_id) - retention_interval will be dropped.
For time-based partitioning, a PostgreSQL interval string (e.g., '7 days').
.. note::
| Supports both **numeric** (by ``msg_id``) and **time-based** (by ``enqueued_at``) partitioning.
| For time-based partitioning, use interval strings like '1 day', '1 hour', '7 days', etc.
| For numeric partitioning, use integer values.
.. important::
| You must make sure that the ``pg_partman`` extension already **installed** in the Postgres.
| ``pgmq-sqlalchemy`` will **auto create** the ``pg_partman`` extension if it does not exist in the Postgres.
| For more details about ``pgmq`` with ``pg_partman``, checkout the |pgmq_partitioned_queue|_.
"""
# check if the pg_partman extension exists before creating a partitioned queue at runtime
await self._execute_async_operation(
PGMQOperation.check_pg_partman_ext_async, session=session, commit=False
)
return await self._execute_async_operation(
PGMQOperation.create_partitioned_queue_async,
session,
commit,
queue_name,
str(partition_interval),
str(retention_interval),
)
def validate_queue_name(
self,
queue_name: str,
*,
session: Optional[SESSION_TYPE] = None,
commit: bool = True,
) -> None:
"""
* Will raise an error if the ``queue_name`` is more than 48 characters.
"""
return self._execute_operation(
PGMQOperation.validate_queue_name,
session,
commit,
queue_name,
)
async def validate_queue_name_async(
self,
queue_name: str,
*,
session: Optional[SESSION_TYPE] = None,
commit: bool = True,
) -> None:
"""
* Will raise an error if the ``queue_name`` is more than 48 characters.
"""
return await self._execute_async_operation(
PGMQOperation.validate_queue_name_async,
session,
commit,
queue_name,
)
def drop_queue(
self,
queue: str,
partitioned: bool = False,
*,
session: Optional[SESSION_TYPE] = None,
commit: bool = True,
) -> bool:
"""Drop a queue.
.. _drop_queue_method: ref:`pgmq_sqlalchemy.PGMQueue.drop_queue`
.. |drop_queue_method| replace:: :py:meth:`~pgmq_sqlalchemy.PGMQueue.drop_queue`
.. code-block:: python
pgmq_client.drop_queue('my_queue')
# for partitioned queue
pgmq_client.drop_queue('my_partitioned_queue', partitioned=True)
.. warning::
| All messages and queue itself will be deleted. (``pgmq.q_<queue_name>`` table)
| **Archived tables** (``pgmq.a_<queue_name>`` table **will be dropped as well. )**
|
| See |archive_method|_ for more details.
"""
# check if the pg_partman extension exists before dropping a partitioned queue at runtime
if partitioned:
self._execute_operation(
PGMQOperation.check_pg_partman_ext, session=session, commit=False
)
return self._execute_operation(
PGMQOperation.drop_queue,
session,
commit,
queue,
partitioned,
)
async def drop_queue_async(
self,
queue: str,
partitioned: bool = False,
*,
session: Optional[SESSION_TYPE] = None,
commit: bool = True,
) -> bool:
"""Drop a queue.
.. code-block:: python
await pgmq_client.drop_queue_async('my_queue')
# for partitioned queue
await pgmq_client.drop_queue_async('my_partitioned_queue', partitioned=True)
.. warning::
| All messages and queue itself will be deleted. (``pgmq.q_<queue_name>`` table)
| **Archived tables** (``pgmq.a_<queue_name>`` table **will be dropped as well. )**
|
| See |archive_method|_ for more details.
"""
# check if the pg_partman extension exists before dropping a partitioned queue at runtime
if partitioned:
await self._execute_async_operation(
PGMQOperation.check_pg_partman_ext_async, session=session, commit=False
)
return await self._execute_async_operation(
PGMQOperation.drop_queue_async,
session,
commit,
queue,
partitioned,
)
def list_queues(
self,
*,
session: Optional[SESSION_TYPE] = None,
commit: bool = True,
) -> List[str]:
"""List all queues.
.. code-block:: python
queue_list = pgmq_client.list_queues()
print(queue_list)
"""
return self._execute_operation(
PGMQOperation.list_queues,
session,
commit,
)
async def list_queues_async(
self,
*,
session: Optional[SESSION_TYPE] = None,
commit: bool = True,
) -> List[str]:
"""List all queues.
.. code-block:: python
queue_list = await pgmq_client.list_queues_async()
print(queue_list)
"""
return await self._execute_async_operation(
PGMQOperation.list_queues_async,
session,
commit,
)
def send(
self,
queue_name: str,
message: dict,
delay: int = 0,
*,
session: Optional[SESSION_TYPE] = None,
commit: bool = True,
) -> int:
"""Send a message to a queue.
.. code-block:: python
msg_id = pgmq_client.send('my_queue', {'key': 'value', 'key2': 'value2'})
print(msg_id)
Example with delay:
.. code-block:: python
msg_id = pgmq_client.send('my_queue', {'key': 'value', 'key2': 'value2'}, delay=10)
msg = pgmq_client.read('my_queue')
assert msg is None
time.sleep(10)
msg = pgmq_client.read('my_queue')
assert msg is not None
"""
return self._execute_operation(
PGMQOperation.send,
session,
commit,
queue_name,
message,
delay,
)
async def send_async(
self,
queue_name: str,
message: dict,
delay: int = 0,
*,
session: Optional[SESSION_TYPE] = None,
commit: bool = True,
) -> int:
"""Send a message to a queue.
.. code-block:: python
msg_id = await pgmq_client.send_async('my_queue', {'key': 'value', 'key2': 'value2'})
print(msg_id)
Example with delay:
.. code-block:: python
msg_id = await pgmq_client.send_async('my_queue', {'key': 'value', 'key2': 'value2'}, delay=10)
msg = await pgmq_client.read_async('my_queue')
assert msg is None
await asyncio.sleep(10)
msg = await pgmq_client.read_async('my_queue')
assert msg is not None
"""
return await self._execute_async_operation(
PGMQOperation.send_async,
session,
commit,
queue_name,
message,
delay,
)
def send_batch(
self,
queue_name: str,
messages: List[dict],
delay: int = 0,
*,
session: Optional[SESSION_TYPE] = None,
commit: bool = True,
) -> List[int]:
"""
Send a batch of messages to a queue.
.. code-block:: python
msgs = [{'key': 'value', 'key2': 'value2'}, {'key': 'value', 'key2': 'value2'}]
msg_ids = pgmq_client.send_batch('my_queue', msgs)
print(msg_ids)
# send with delay
msg_ids = pgmq_client.send_batch('my_queue', msgs, delay=10)
"""
return self._execute_operation(
PGMQOperation.send_batch,
session,
commit,
queue_name,
messages,
delay,
)
async def send_batch_async(
self,
queue_name: str,
messages: List[dict],
delay: int = 0,
*,
session: Optional[SESSION_TYPE] = None,
commit: bool = True,
) -> List[int]:
"""
Send a batch of messages to a queue.
.. code-block:: python
msgs = [{'key': 'value', 'key2': 'value2'}, {'key': 'value', 'key2': 'value2'}]
msg_ids = await pgmq_client.send_batch_async('my_queue', msgs)
print(msg_ids)
# send with delay
msg_ids = await pgmq_client.send_batch_async('my_queue', msgs, delay=10)
"""
return await self._execute_async_operation(
PGMQOperation.send_batch_async,
session,
commit,
queue_name,
messages,
delay,
)
def read(
self,
queue_name: str,
vt: Optional[int] = None,
*,
session: Optional[SESSION_TYPE] = None,
commit: bool = True,
) -> Optional[Message]:
"""
.. _for_update_skip_locked: https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE
.. |for_update_skip_locked| replace:: **FOR UPDATE SKIP LOCKED**
.. _read_method: ref:`pgmq_sqlalchemy.PGMQueue.read`
.. |read_method| replace:: :py:meth:`~pgmq_sqlalchemy.PGMQueue.read`
Read a message from the queue.
Returns:
|schema_message_class|_ or ``None`` if the queue is empty.
.. note::
| ``PGMQ`` use |for_update_skip_locked|_ lock to make sure **a message is only read by one consumer**.
| See the `pgmq.read <https://github.com/tembo-io/pgmq/blob/main/pgmq-extension/sql/pgmq.sql?plain=1#L44-L75>`_ function for more details.
|
| For **consumer retries mechanism** (e.g. mark a message as failed after a certain number of retries) can be implemented by using the ``read_ct`` field in the |schema_message_class|_ object.
.. important::
| ``vt`` is the **visibility timeout** in seconds.
| When a message is read from the queue, it will be invisible to other consumers for the duration of the ``vt``.
Usage:
.. code-block:: python
from pgmq_sqlalchemy.schema import Message
msg:Message = pgmq_client.read('my_queue')
print(msg.msg_id)
print(msg.message)
print(msg.read_ct) # read count, how many times the message has been read
Example with ``vt``:
.. code-block:: python
# assert `read_vt_demo` is empty
pgmq_client.send('read_vt_demo', {'key': 'value', 'key2': 'value2'})
msg = pgmq_client.read('read_vt_demo', vt=10)
assert msg is not None
# try to read immediately
msg = pgmq_client.read('read_vt_demo')
assert msg is None # will return None because the message is still invisible
# try to read after 5 seconds
time.sleep(5)
msg = pgmq_client.read('read_vt_demo')
assert msg is None # still invisible after 5 seconds
# try to read after 11 seconds
time.sleep(6)
msg = pgmq_client.read('read_vt_demo')
assert msg is not None # the message is visible after 10 seconds
"""
if vt is None:
vt = self.vt
return self._execute_operation(
PGMQOperation.read,
session,
commit,
queue_name,
vt,
)
async def read_async(
self,
queue_name: str,
vt: Optional[int] = None,
*,
session: Optional[SESSION_TYPE] = None,
commit: bool = True,
) -> Optional[Message]:
"""
Read a message from the queue.
Returns:
|schema_message_class|_ or ``None`` if the queue is empty.
.. note::
| ``PGMQ`` use |for_update_skip_locked|_ lock to make sure **a message is only read by one consumer**.
| See the `pgmq.read <https://github.com/tembo-io/pgmq/blob/main/pgmq-extension/sql/pgmq.sql?plain=1#L44-L75>`_ function for more details.
|
| For **consumer retries mechanism** (e.g. mark a message as failed after a certain number of retries) can be implemented by using the ``read_ct`` field in the |schema_message_class|_ object.
.. important::
| ``vt`` is the **visibility timeout** in seconds.
| When a message is read from the queue, it will be invisible to other consumers for the duration of the ``vt``.
Usage:
.. code-block:: python
from pgmq_sqlalchemy.schema import Message
msg:Message = await pgmq_client.read_async('my_queue')
print(msg.msg_id)
print(msg.message)
print(msg.read_ct) # read count, how many times the message has been read
Example with ``vt``:
.. code-block:: python
# assert `read_vt_demo` is empty
await pgmq_client.send_async('read_vt_demo', {'key': 'value', 'key2': 'value2'})
msg = await pgmq_client.read_async('read_vt_demo', vt=10)
assert msg is not None
# try to read immediately
msg = await pgmq_client.read_async('read_vt_demo')
assert msg is None # will return None because the message is still invisible
# try to read after 5 seconds
await asyncio.sleep(5)
msg = await pgmq_client.read_async('read_vt_demo')
assert msg is None # still invisible after 5 seconds
# try to read after 11 seconds
await asyncio.sleep(6)
msg = await pgmq_client.read_async('read_vt_demo')
assert msg is not None # the message is visible after 10 seconds
"""
if vt is None:
vt = self.vt
return await self._execute_async_operation(
PGMQOperation.read_async,
session,
commit,
queue_name,
vt,
)
def read_batch(
self,
queue_name: str,
batch_size: int = 1,
vt: Optional[int] = None,
*,
session: Optional[SESSION_TYPE] = None,
commit: bool = True,
) -> Optional[List[Message]]:
"""
| Read a batch of messages from the queue.
| Usage:
Returns:
List of |schema_message_class|_ or ``None`` if the queue is empty.
.. code-block:: python
from pgmq_sqlalchemy.schema import Message
msgs:List[Message] = pgmq_client.read_batch('my_queue', batch_size=10)
# with vt
msgs:List[Message] = pgmq_client.read_batch('my_queue', batch_size=10, vt=10)
"""
if vt is None:
vt = self.vt
return self._execute_operation(
PGMQOperation.read_batch,
session,
commit,
queue_name,
vt,
batch_size,
)
async def read_batch_async(
self,
queue_name: str,
batch_size: int = 1,
vt: Optional[int] = None,
*,
session: Optional[SESSION_TYPE] = None,
commit: bool = True,
) -> Optional[List[Message]]:
"""
| Read a batch of messages from the queue.
| Usage:
Returns:
List of |schema_message_class|_ or ``None`` if the queue is empty.
.. code-block:: python
from pgmq_sqlalchemy.schema import Message
msgs:List[Message] = await pgmq_client.read_batch_async('my_queue', batch_size=10)
# with vt
msgs:List[Message] = await pgmq_client.read_batch_async('my_queue', batch_size=10, vt=10)
"""
if vt is None:
vt = self.vt
return await self._execute_async_operation(
PGMQOperation.read_batch_async,
session,
commit,
queue_name,
vt,
batch_size,
)
def read_with_poll(
self,
queue_name: str,
vt: Optional[int] = None,
qty: int = 1,
max_poll_seconds: int = 5,
poll_interval_ms: int = 100,
*,
session: Optional[SESSION_TYPE] = None,
commit: bool = True,
) -> Optional[List[Message]]:
"""
.. _read_with_poll_method: ref:`pgmq_sqlalchemy.PGMQueue.read_with_poll`
.. |read_with_poll_method| replace:: :py:meth:`~pgmq_sqlalchemy.PGMQueue.read_with_poll`
| Read messages from a queue with long-polling.
|
| When the queue is empty, the function block at most ``max_poll_seconds`` seconds.
| During the polling, the function will check the queue every ``poll_interval_ms`` milliseconds, until the queue has ``qty`` messages.
Args:
queue_name (str): The name of the queue.
vt (Optional[int]): The visibility timeout in seconds.
qty (int): The number of messages to read.
max_poll_seconds (int): The maximum number of seconds to poll.
poll_interval_ms (int): The interval in milliseconds to poll.
Returns:
List of |schema_message_class|_ or ``None`` if the queue is empty.
Usage:
.. code-block:: python
msg_id = pgmq_client.send('my_queue', {'key': 'value'}, delay=6)
# the following code will block for 5 seconds
msgs = pgmq_client.read_with_poll('my_queue', qty=1, max_poll_seconds=5, poll_interval_ms=100)
assert msgs is None
# try read_with_poll again
# the following code will only block for 1 second
msgs = pgmq_client.read_with_poll('my_queue', qty=1, max_poll_seconds=5, poll_interval_ms=100)
assert msgs is not None
Another example:
.. code-block:: python
msg = {'key': 'value'}
msg_ids = pgmq_client.send_batch('my_queue', [msg, msg, msg, msg], delay=3)
# the following code will block for 3 seconds
msgs = pgmq_client.read_with_poll('my_queue', qty=3, max_poll_seconds=5, poll_interval_ms=100)
assert len(msgs) == 3 # will read at most 3 messages (qty=3)
"""
if vt is None:
vt = self.vt
return self._execute_operation(
PGMQOperation.read_with_poll,
session,
commit,
queue_name,
vt,
qty,
max_poll_seconds,
poll_interval_ms,
)
async def read_with_poll_async(
self,
queue_name: str,
vt: Optional[int] = None,
qty: int = 1,
max_poll_seconds: int = 5,
poll_interval_ms: int = 100,
*,
session: Optional[SESSION_TYPE] = None,
commit: bool = True,
) -> Optional[List[Message]]:
"""
| Read messages from a queue with long-polling.
|
| When the queue is empty, the function block at most ``max_poll_seconds`` seconds.
| During the polling, the function will check the queue every ``poll_interval_ms`` milliseconds, until the queue has ``qty`` messages.
Args:
queue_name (str): The name of the queue.
vt (Optional[int]): The visibility timeout in seconds.
qty (int): The number of messages to read.
max_poll_seconds (int): The maximum number of seconds to poll.
poll_interval_ms (int): The interval in milliseconds to poll.
Returns:
List of |schema_message_class|_ or ``None`` if the queue is empty.
Usage:
.. code-block:: python
msg_id = await pgmq_client.send_async('my_queue', {'key': 'value'}, delay=6)
# the following code will block for 5 seconds
msgs = await pgmq_client.read_with_poll_async('my_queue', qty=1, max_poll_seconds=5, poll_interval_ms=100)
assert msgs is None
# try read_with_poll again
# the following code will only block for 1 second
msgs = await pgmq_client.read_with_poll_async('my_queue', qty=1, max_poll_seconds=5, poll_interval_ms=100)
assert msgs is not None
Another example:
.. code-block:: python
msg = {'key': 'value'}
msg_ids = await pgmq_client.send_batch_async('my_queue', [msg, msg, msg, msg], delay=3)
# the following code will block for 3 seconds
msgs = await pgmq_client.read_with_poll_async('my_queue', qty=3, max_poll_seconds=5, poll_interval_ms=100)
assert len(msgs) == 3 # will read at most 3 messages (qty=3)
"""
if vt is None:
vt = self.vt
return await self._execute_async_operation(
PGMQOperation.read_with_poll_async,
session,
commit,
queue_name,
vt,
qty,
max_poll_seconds,
poll_interval_ms,
)
def set_vt(
self,
queue_name: str,
msg_id: int,
vt: int,
*,
session: Optional[SESSION_TYPE] = None,
commit: bool = True,
) -> Optional[Message]:
"""
.. _set_vt_method: ref:`pgmq_sqlalchemy.PGMQueue.set_vt`
.. |set_vt_method| replace:: :py:meth:`~pgmq_sqlalchemy.PGMQueue.set_vt`
Set the visibility timeout for a message.
Args:
queue_name (str): The name of the queue.
msg_id (int): The message id.
vt (int): The visibility timeout in seconds.
Returns:
|schema_message_class|_ or ``None`` if the message does not exist.
Usage:
.. code-block:: python
msg_id = pgmq_client.send('my_queue', {'key': 'value'}, delay=10)