Skip to content

Pubsub

Consumer class to read messages from a Redis stream using consumer groups.

Source code in blue/pubsub.py
 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
class Consumer:
    """Consumer class to read messages from a Redis stream using consumer groups."""

    def __init__(self, stream, name="STREAM", id=None, sid=None, cid=None, prefix=None, suffix=None, owner=None, listener=None, properties=None, on_stop=None):
        """Initialize the Consumer.

        Parameters:
            stream: Stream identifier to consume from.
            name: Name of the consumer. Defaults to "STREAM".
            id (str): Unique identifier for the consumer. If None, a UUID will be generated.
            sid (str): Short identifier for the consumer. If None, it will be generated from name and id.
            cid (str): Canonical identifier for the consumer. If None, it will be generated from sid, prefix, and suffix.
            prefix (str): Optional prefix for the cid.
            suffix (str): Optional suffix for the cid.
            owner: Owner of the consumer for metadata
            listener: Callback function to process each message.
            properties: Properties for the consumer. Defaults to None.
            on_stop (callable): Callback function to be called when the consumer stops.
        """
        self.stream_cid = stream
        self.name = name
        if id:
            self.id = id
        else:
            self.id = uuid_utils.create_uuid()

        if sid:
            self.sid = sid
        else:
            self.sid = self.name + ":" + self.id

        self.prefix = prefix
        self.suffix = suffix
        self.cid = cid

        if self.cid == None:
            self.cid = self.sid

            if self.prefix:
                self.cid = self.prefix + ":" + self.cid
            if self.suffix:
                self.cid = self.cid + ":" + self.suffix

        self.owner = owner

        if properties is None:
            properties = {}
        self._initialize(properties=properties)

        self.stream = Stream(self.stream_cid, properties=self.properties)

        if listener is None:
            listener = lambda message: print("{message}".format(message=message))

        self.listener = listener

        self.on_stop = on_stop
        self.threads = []

        # last processed
        self.last_processed = None

        # for pairing mode
        # self.pairer_task = None
        # self.left_param = None
        # self.left_queue = None
        # self.right_param = None
        # self.right_queue = None

    ###### initialization
    def _initialize(self, properties=None):
        """Initialize the consumer with properties.

        Parameters:
            properties: Properties to configure the consumer.
        """
        self._initialize_properties()
        self._update_properties(properties=properties)

        self._initialize_logger()

    def _initialize_properties(self):
        """Initialize default properties for the consumer."""
        self.properties = {}
        self.properties['num_threads'] = 1
        self.properties['db.host'] = 'localhost'
        self.properties['db.port'] = 6379

    def _update_properties(self, properties=None):
        """Update consumer properties with provided values.

        Parameters:
            properties: Dictionary of properties to update.
        """
        if properties is None:
            return

        # override
        for p in properties:
            self.properties[p] = properties[p]

    def _initialize_logger(self):
        """Initialize the logger for the consumer. Sets consumer and stream in log data."""
        self.logger = log_utils.CustomLogger()
        # customize log
        self.logger.set_config_data(
            "stack",
            "%(call_stack)s",
        )
        self.logger.set_config_data("consumer", self.sid, -1)
        self.logger.set_config_data("stream", self.stream_cid, -1)

    ####### open connection, create group, start threads
    def _extract_epoch(self, id):
        """Extract epoch time from Redis stream ID."""
        e = id.split("-")[0]
        return int(int(e) / 1000)

    def _idle_tracker_callback(self, data, tracker=None, properties=None):
        """Callback function for idle tracking. Expires the consumer if idle beyond `consumer.expiration` based on `last_active`"""
        if properties is None:
            properties = self.properties

        expiration = None
        if "consumer.expiration" in properties:
            expiration = properties['consumer.expiration']

        # expire?
        if expiration != None and expiration > 0:
            last_active = tracker.getValue('last_active')
            current = tracker.getValue('metadata.current')

            if last_active and current:
                if last_active + expiration < current:
                    self.logger.info("Expired Consumer: " + self.cid)
                    self._stop()

    def _init_tracker(self):
        """Initialize the idle tracker for the consumer."""
        self._tracker = IdleTracker(self, properties=self.properties, callback=lambda *args, **kwargs,: self._idle_tracker_callback(*args, **kwargs))
        self._tracker.start()

    def _start_tracker(self):
        """Start the idle tracker for the consumer."""
        # start tracker
        self._tracker.start()

    def _stop_tracker(self):
        """Stop the idle tracker for the consumer."""
        self._tracker.stop()

    def _terminate_tracker(self):
        """Terminate the idle tracker for the consumer."""
        self._tracker.terminate()

    def start(self):
        """Start the consumer: open connection, create group, and start threads."""
        # self.logger.info("Starting consumer {c} for stream {s}".format(c=self.sid,s=self.stream_cid))
        self.stop_signal = False

        self._start_connection()

        self._start_group()

        self._start_threads()

        # init tracker
        self._init_tracker()

        # self.logger.info("Started consumer {c} for stream {s}".format(c=self.sid, s=self.stream_cid))

    def stop(self):
        """Stop the consumer and terminate the idle tracker."""
        self._terminate_tracker()

        self.stop_signal = True

    def _stop(self):
        """Internal method to stop the consumer and call the on_stop callback."""
        self._terminate_tracker()

        self.stop_signal = True

        if self.on_stop:
            self.on_stop(self.sid)

    def wait(self):
        """Wait for all consumer threads to finish."""
        for t in self.threads:
            t.join()

    def _start_connection(self):
        """Start the connection to the Redis server."""
        self.connection_factory = PooledConnectionFactory(properties=self.properties)
        self.connection = self.connection_factory.get_connection()

    def _start_group(self):
        """Create the consumer group if it doesn't exist."""
        s = self.stream_cid
        g = self.cid
        r = self.connection

        try:
            # self.logger.info("Creating group {g}...".format(g=g))
            r.xgroup_create(name=s, groupname=g, id=0)
        except:
            self.logger.info("Group {g} exists...".format(g=g))

        # self._print_group_info()

    def _print_group_info(self):
        s = self.stream_cid
        g = self.cid
        r = self.connection

        self.logger.info("Group info for stream {s}".format(s=s))
        res = r.xinfo_groups(name=s)
        for i in res:
            self.logger.info(f"{s} -> group name: {i['name']} with {i['consumers']} consumers and {i['last-delivered-id']}" + f" as last read id")

    def get_stream(self):
        """Get the stream ID for the consumer."""
        return self.stream_cid

    def get_group(self):
        """Get the consumer group ID."""
        return self.cid

    # async def response_handler(self, message: Message):
    #     if self.pairer_task is not None:
    #         if message.isEOS():
    #             await asyncio.sleep(1)
    #             # wait until all items in the queue have been processed
    #             if self.left_queue is not None:
    #                 self.left_queue.join()
    #             if self.right_queue is not None:
    #                 self.right_queue.join()
    #             self.pairer_task.cancel()
    #         else:
    #             # pushing messages to pairing queue
    #             left_parameter = message.getParam(self.left_param)
    #             right_parameter = message.getParam(self.right_param)
    #             if left_parameter is not None:
    #                 await self.left_queue.put(left_parameter)
    #             if right_parameter is not None:
    #                 await self.right_queue.put(right_parameter)
    #     else:
    #         self.listener(message)

    # async def _consume_stream(self, c):
    def _consume_stream(self, c):
        """Consume messages from the Redis stream using consumer group. Construct a `Message` object for each message and pass it to the listener callback."""
        s = self.stream_cid
        g = self.cid
        r = self.connection

        # self.logger.info("[Thread {c}]: starting".format(c=c))
        while True:

            if self.stop_signal:
                break

            # check any pending, if so claim
            m = r.xautoclaim(count=1, name=s, groupname=g, consumername=str(c), min_idle_time=10000, justid=False)

            if len(m) > 0:
                d = m
                id = d[0]
                m_json = d[1]

                # check special token (no data to claim)
                if id == "0-0":
                    pass
                else:
                    # self.logger.info("[Thread {c}]: reclaiming... {s} {id}".format(c=c, s=s, id=id))

                    # listen
                    message = Message.fromJSON(json.dumps(m_json))
                    message.setID(id)
                    message.setStream(s)
                    # await self.response_handler(message)
                    self.listener(message)

                    # last processed
                    self.last_processed = int(time.time())  # self._extract_epoch(id)

                    # update stream metadata
                    if self.owner:
                        metadata = {'message': id, 'time': self.last_processed}
                        self.stream.set_metadata('consumers.' + self.owner, metadata)

                    # ack
                    r.xack(s, g, id)
                    continue

            # otherwise read new
            m = r.xreadgroup(count=1, streams={s: '>'}, block=200, groupname=g, consumername=str(c))

            if len(m) > 0:
                e = m[0]
                s = e[0]
                d = e[1][0]
                id = d[0]
                m_json = d[1]

                # self.logger.info("[Thread {c}]: listening... stream:{s} id:{id} message:{message}".format(c=c, s=s, id=id, message=m_json))

                # listen
                message = Message.fromJSON(json.dumps(m_json))
                message.setID(id)
                message.setStream(s)
                # await self.response_handler(message)
                self.listener(message)

                # last processed
                self.last_processed = int(time.time())  # self._extract_epoch(id)

                # update stream metadata
                if self.owner:
                    metadata = {'message': id, 'time': self.last_processed}
                    self.stream.set_metadata('consumers.' + self.owner, metadata)

                # occasionally throw exception (for testing failed threads)
                # if random.random() > 0.5:
                #    print("[Thread {c}]: throwing exception".format(c=c))
                #    raise Exception("exception")

                # ack
                r.xack(s, g, id)

                # on EOS, stop
                if message.isEOS():
                    self._stop()

        # self.logger.info("[Thread {c}]: finished".format(c=c))

    def _start_threads(self):
        """Start consumer threads to read from the stream."""
        # start threads
        num_threads = self.properties['num_threads']

        for i in range(num_threads):
            # t = threading.Thread(target=lambda: asyncio.run(self._consume_stream(self.cid + "-" + str(i))), daemon=True)
            t = threading.Thread(target=lambda: self._consume_stream(self.cid + "-" + str(i)), daemon=True)
            t.name = "Thread-" + self.__class__.__name__ + "-" + self.sid
            t.start()
            self.threads.append(t)

    def _delete_stream(self):
        """Delete all messages from the stream."""
        s = self.stream_cid
        r = self.connection

        l = r.xread(streams={s: 0})
        for _, m in l:
            [r.xdel(s, i[0]) for i in m]

__init__(stream, name='STREAM', id=None, sid=None, cid=None, prefix=None, suffix=None, owner=None, listener=None, properties=None, on_stop=None)

Initialize the Consumer.

Parameters:

Name Type Description Default
stream

Stream identifier to consume from.

required
name

Name of the consumer. Defaults to "STREAM".

'STREAM'
id str

Unique identifier for the consumer. If None, a UUID will be generated.

None
sid str

Short identifier for the consumer. If None, it will be generated from name and id.

None
cid str

Canonical identifier for the consumer. If None, it will be generated from sid, prefix, and suffix.

None
prefix str

Optional prefix for the cid.

None
suffix str

Optional suffix for the cid.

None
owner

Owner of the consumer for metadata

None
listener

Callback function to process each message.

None
properties

Properties for the consumer. Defaults to None.

None
on_stop callable

Callback function to be called when the consumer stops.

None
Source code in blue/pubsub.py
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
def __init__(self, stream, name="STREAM", id=None, sid=None, cid=None, prefix=None, suffix=None, owner=None, listener=None, properties=None, on_stop=None):
    """Initialize the Consumer.

    Parameters:
        stream: Stream identifier to consume from.
        name: Name of the consumer. Defaults to "STREAM".
        id (str): Unique identifier for the consumer. If None, a UUID will be generated.
        sid (str): Short identifier for the consumer. If None, it will be generated from name and id.
        cid (str): Canonical identifier for the consumer. If None, it will be generated from sid, prefix, and suffix.
        prefix (str): Optional prefix for the cid.
        suffix (str): Optional suffix for the cid.
        owner: Owner of the consumer for metadata
        listener: Callback function to process each message.
        properties: Properties for the consumer. Defaults to None.
        on_stop (callable): Callback function to be called when the consumer stops.
    """
    self.stream_cid = stream
    self.name = name
    if id:
        self.id = id
    else:
        self.id = uuid_utils.create_uuid()

    if sid:
        self.sid = sid
    else:
        self.sid = self.name + ":" + self.id

    self.prefix = prefix
    self.suffix = suffix
    self.cid = cid

    if self.cid == None:
        self.cid = self.sid

        if self.prefix:
            self.cid = self.prefix + ":" + self.cid
        if self.suffix:
            self.cid = self.cid + ":" + self.suffix

    self.owner = owner

    if properties is None:
        properties = {}
    self._initialize(properties=properties)

    self.stream = Stream(self.stream_cid, properties=self.properties)

    if listener is None:
        listener = lambda message: print("{message}".format(message=message))

    self.listener = listener

    self.on_stop = on_stop
    self.threads = []

    # last processed
    self.last_processed = None

get_group()

Get the consumer group ID.

Source code in blue/pubsub.py
250
251
252
def get_group(self):
    """Get the consumer group ID."""
    return self.cid

get_stream()

Get the stream ID for the consumer.

Source code in blue/pubsub.py
246
247
248
def get_stream(self):
    """Get the stream ID for the consumer."""
    return self.stream_cid

start()

Start the consumer: open connection, create group, and start threads.

Source code in blue/pubsub.py
181
182
183
184
185
186
187
188
189
190
191
192
193
def start(self):
    """Start the consumer: open connection, create group, and start threads."""
    # self.logger.info("Starting consumer {c} for stream {s}".format(c=self.sid,s=self.stream_cid))
    self.stop_signal = False

    self._start_connection()

    self._start_group()

    self._start_threads()

    # init tracker
    self._init_tracker()

stop()

Stop the consumer and terminate the idle tracker.

Source code in blue/pubsub.py
197
198
199
200
201
def stop(self):
    """Stop the consumer and terminate the idle tracker."""
    self._terminate_tracker()

    self.stop_signal = True

wait()

Wait for all consumer threads to finish.

Source code in blue/pubsub.py
212
213
214
215
def wait(self):
    """Wait for all consumer threads to finish."""
    for t in self.threads:
        t.join()
Last update: 2025-10-08