File: managers.py

package info (click to toggle)
freenub 0.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,168 kB
  • sloc: python: 10,664; makefile: 7; sh: 6
file content (575 lines) | stat: -rw-r--r-- 19,942 bytes parent folder | download
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
import base64
import copy
import logging
import math
import time
from abc import ABCMeta, abstractmethod

from cbor2 import loads

from . import utils
from .callbacks import ReconnectionCallback, SubscribeCallback
from .dtos import SubscribeOperation, UnsubscribeOperation
from .enums import PNOperationType, PNReconnectionPolicy, PNStatusCategory
from .errors import PNERR_INVALID_ACCESS_TOKEN
from .exceptions import PubNubException
from .models.consumer.common import PNStatus
from .models.server.subscribe import SubscribeEnvelope
from .models.subscription_item import SubscriptionItem

logger = logging.getLogger("pubnub")


class PublishSequenceManager:
    def __init__(self, provided_max_sequence):
        self.max_sequence = provided_max_sequence
        self.next_sequence = 0

    @abstractmethod
    def get_next_sequence(self):
        if self.max_sequence == self.next_sequence:
            self.next_sequence = 1
        else:
            self.next_sequence += 1
        return self.next_sequence


class BasePathManager:
    MAX_SUBDOMAIN = 20
    DEFAULT_SUBDOMAIN = "pubsub"
    DEFAULT_BASE_PATH = "pubnub.com"

    def __init__(self, initial_config):
        self.config = initial_config
        self._current_subdomain = 1

    def get_base_path(self):
        if self.config.origin:
            return self.config.origin
        else:
            return f"{BasePathManager.DEFAULT_SUBDOMAIN}.{BasePathManager.DEFAULT_BASE_PATH}"


class ReconnectionManager:
    INTERVAL = 3
    MINEXPONENTIALBACKOFF = 1
    MAXEXPONENTIALBACKOFF = 32

    def __init__(self, pubnub):
        self._pubnub = pubnub
        self._callback = None
        self._timer = None
        self._timer_interval = None
        self._connection_errors = 1

    def set_reconnection_listener(self, reconnection_callback):
        assert isinstance(reconnection_callback, ReconnectionCallback)
        self._callback = reconnection_callback

    def _recalculate_interval(self):
        if self._pubnub.config.reconnect_policy == PNReconnectionPolicy.EXPONENTIAL:
            self._timer_interval = int(math.pow(2, self._connection_errors) - 1)
            if self._timer_interval > self.MAXEXPONENTIALBACKOFF:
                self._timer_interval = self.MINEXPONENTIALBACKOFF
                self._connection_errors = 1
                logger.debug(
                    "timerInterval > MAXEXPONENTIALBACKOFF at: %s"
                    % utils.datetime_now()
                )
            elif self._timer_interval < 1:
                self._timer_interval = self.MINEXPONENTIALBACKOFF
            logger.debug(
                "timerInterval = %d at: %s"
                % (self._timer_interval, utils.datetime_now())
            )
        else:
            self._timer_interval = self.INTERVAL

    @abstractmethod
    def start_polling(self):
        pass

    def _stop_heartbeat_timer(self):
        if self._timer is not None:
            self._timer.stop()
            self._timer = None


class StateManager:
    def __init__(self):
        self._channels = {}
        self._groups = {}
        self._presence_channels = {}
        self._presence_groups = {}

    def is_empty(self):
        return (
            len(self._channels) == 0
            and len(self._groups) == 0
            and len(self._presence_channels) == 0
            and len(self._presence_groups) == 0
        )

    def subscribed_to_the_only_channel(self):
        return (
            len(self._channels) == 1
            and len(self._groups) == 0
            and len(self._presence_channels) == 0
            and len(self._presence_groups) == 0
        )

    def prepare_channel_list(self, include_presence):
        return StateManager._prepare_membership_list(
            self._channels, self._presence_channels, include_presence
        )

    def prepare_channel_group_list(self, include_presence):
        return StateManager._prepare_membership_list(
            self._groups, self._presence_groups, include_presence
        )

    def adapt_subscribe_builder(self, subscribe_operation):
        for channel in subscribe_operation.channels:
            self._channels[channel] = SubscriptionItem(name=channel)

            if subscribe_operation.presence_enabled:
                self._presence_channels[channel] = SubscriptionItem(name=channel)

        for group in subscribe_operation.channel_groups:
            self._groups[group] = SubscriptionItem(name=group)

            if subscribe_operation.presence_enabled:
                self._presence_groups[group] = SubscriptionItem(name=group)

    def adapt_unsubscribe_builder(self, unsubscribe_operation):
        for channel in unsubscribe_operation.channels:
            self._channels.pop(channel, None)
            if channel in self._presence_channels:
                self._presence_channels.pop(channel, None)

        for group in unsubscribe_operation.channel_groups:
            self._groups.pop(group)
            if group in self._presence_groups:
                self._presence_groups.pop(group)

    def adapt_state_builder(self, state_operation):
        for channel in state_operation.channels:
            subscribed_channel = self._channels.get(channel)

            if subscribed_channel is not None:
                subscribed_channel.state = state_operation.state

        for group in state_operation.channel_groups:
            subscribed_group = self._channels.get(group)

            if subscribed_group is not None:
                subscribed_group.state = state_operation.state

    def state_payload(self):
        state = {}

        for channel in self._channels.values():
            if channel.state is not None:
                state[channel.name] = channel.state

        for group in self._groups.values():
            if group.state is not None:
                state[group.name] = group.state

        return state

    @staticmethod
    def _prepare_membership_list(data_storage, presence_storage, include_presence):
        response = []

        for item in data_storage.values():
            response.append(item.name)

        if include_presence:
            for item in presence_storage.values():
                response.append(item.name + "-pnpres")

        return response


class ListenerManager:
    def __init__(self, pubnub_instance):
        self._pubnub = pubnub_instance
        self._listeners = []

    def add_listener(self, listener):
        assert isinstance(listener, SubscribeCallback)
        self._listeners.append(listener)

    def remove_listener(self, listener):
        assert isinstance(listener, SubscribeCallback)
        self._listeners.remove(listener)

    def announce_status(self, status):
        for callback in self._listeners:
            callback.status(self._pubnub, status)

    def announce_message(self, message):
        for callback in self._listeners:
            callback.message(self._pubnub, message)

    def announce_signal(self, signal):
        for callback in self._listeners:
            callback.signal(self._pubnub, signal)

    def announce_channel(self, channel):
        for callback in self._listeners:
            callback.channel(self._pubnub, channel)

    def announce_uuid(self, uuid):
        for callback in self._listeners:
            callback.uuid(self._pubnub, uuid)

    def announce_membership(self, membership):
        for callback in self._listeners:
            callback.membership(self._pubnub, membership)

    def announce_message_action(self, message_action):
        for callback in self._listeners:
            callback.message_action(self._pubnub, message_action)

    def announce_presence(self, presence):
        for callback in self._listeners:
            callback.presence(self._pubnub, presence)

    def announce_file_message(self, file_message):
        for callback in self._listeners:
            callback.file(self._pubnub, file_message)


class SubscriptionManager:
    __metaclass__ = ABCMeta

    HEARTBEAT_INTERVAL_MULTIPLIER = 1000

    def __init__(self, pubnub_instance):
        self._pubnub = pubnub_instance
        self._subscription_status_announced = False

        self._subscription_state = StateManager()
        self._listener_manager = ListenerManager(self._pubnub)
        self._timetoken = 0
        self._region = None

        self._should_stop = False

        self._subscribe_request_task = None
        self._heartbeat_call = None

    @abstractmethod
    def _start_worker(self):
        pass

    @abstractmethod
    def _set_consumer_event(self):
        pass

    @abstractmethod
    def _message_queue_put(self, message):
        pass

    @abstractmethod
    def _start_subscribe_loop(self):
        pass

    @abstractmethod
    def _stop_subscribe_loop(self):
        pass

    @abstractmethod
    def _stop_heartbeat_timer(self):
        pass

    @abstractmethod
    def _perform_heartbeat_loop(self):
        pass

    @abstractmethod
    def _send_leave(self, unsubscribe_operation):
        pass

    def add_listener(self, listener):
        self._listener_manager.add_listener(listener)

    def remove_listener(self, listener):
        self._listener_manager.remove_listener(listener)

    def get_subscribed_channels(self):
        return self._subscription_state.prepare_channel_list(False)

    def get_subscribed_channel_groups(self):
        return self._subscription_state.prepare_channel_group_list(False)

    def unsubscribe_all(self):
        self.adapt_unsubscribe_builder(
            UnsubscribeOperation(
                channels=self._subscription_state.prepare_channel_list(False),
                channel_groups=self._subscription_state.prepare_channel_group_list(
                    False
                ),
            )
        )

    def adapt_subscribe_builder(self, subscribe_operation):
        assert isinstance(subscribe_operation, SubscribeOperation)
        self._subscription_state.adapt_subscribe_builder(subscribe_operation)
        self._subscription_status_announced = False

        if subscribe_operation.timetoken is not None:
            self._timetoken = subscribe_operation.timetoken

        self.reconnect()

    def adapt_unsubscribe_builder(self, unsubscribe_operation):
        assert isinstance(unsubscribe_operation, UnsubscribeOperation)

        self._subscription_state.adapt_unsubscribe_builder(unsubscribe_operation)

        if not self._pubnub.config.suppress_leave_events:
            self._send_leave(unsubscribe_operation)

        if self._subscription_state.is_empty():
            self._region = None
            self._timetoken = 0
        self.reconnect()

    def adapt_state_builder(self, state_operation):
        self._subscription_state.adapt_state_builder(state_operation)
        self.reconnect()

    @abstractmethod
    def reconnect(self):
        pass

    def stop(self):
        self._should_stop = True
        self._stop_subscribe_loop()
        self._stop_heartbeat_timer()
        self._set_consumer_event()

    def _handle_endpoint_call(self, raw_result, status):
        assert isinstance(status, PNStatus)

        if not self._subscription_status_announced:
            pn_status = PNStatus()
            pn_status.category = PNStatusCategory.PNConnectedCategory
            pn_status.status_code = status.status_code
            pn_status.auth_key = status.auth_key
            pn_status.operation = status.operation
            pn_status.client_request = status.client_request
            pn_status.origin = status.origin
            pn_status.tls_enabled = status.tls_enabled
            pn_status.affected_channels = status.affected_channels
            pn_status.affected_groups = status.affected_groups

            self._subscription_status_announced = True
            self._listener_manager.announce_status(pn_status)

        result = SubscribeEnvelope.from_json(raw_result)
        only_channel = self._subscription_state.subscribed_to_the_only_channel()
        if result.messages is not None and len(result.messages) > 0:
            for message in result.messages:
                if only_channel:
                    message.only_channel_subscription = True
                self._message_queue_put(message)

        self._timetoken = int(result.metadata.timetoken)
        self._region = int(result.metadata.region)

    # TODO: make abstract
    def _register_heartbeat_timer(self):
        self._stop_heartbeat_timer()


class TelemetryManager:
    TIMESTAMP_DIVIDER = 1000
    MAXIMUM_LATENCY_DATA_AGE = 60
    CLEAN_UP_INTERVAL = 1
    CLEAN_UP_INTERVAL_MULTIPLIER = 1000

    def __init__(self):
        self.latencies = {}

    @abstractmethod
    def _start_clean_up_timer(self):
        pass

    @abstractmethod
    def _stop_clean_up_timer(self):
        pass

    def operation_latencies(self):
        operation_latencies = {}

        for endpoint_name, endpoint_latencies in self.latencies.items():
            latency_key = "l_" + endpoint_name

            endpoint_average_latency = self.average_latency_from_data(
                endpoint_latencies
            )

            if endpoint_average_latency > 0:
                operation_latencies[latency_key] = endpoint_average_latency

        return operation_latencies

    def clean_up_telemetry_data(self):
        current_timestamp = time.time()
        copy_latencies = copy.deepcopy(self.latencies)

        for endpoint_name, endpoint_latencies in copy_latencies.items():
            for latency_information in endpoint_latencies:
                if (
                    current_timestamp - latency_information["timestamp"]
                    > self.MAXIMUM_LATENCY_DATA_AGE
                ):
                    self.latencies[endpoint_name].remove(latency_information)

            if len(self.latencies[endpoint_name]) == 0:
                del self.latencies[endpoint_name]

    def store_latency(self, latency, operation_type):
        if operation_type != PNOperationType.PNSubscribeOperation and latency > 0:
            endpoint_name = self.endpoint_name_for_operation(operation_type)

            store_timestamp = time.time()

            if endpoint_name not in self.latencies:
                self.latencies[endpoint_name] = []

            latency_entry = {
                "timestamp": store_timestamp,
                "latency": latency,
            }

            self.latencies[endpoint_name].append(latency_entry)

    @staticmethod
    def average_latency_from_data(endpoint_latencies):
        total_latency = 0

        for latency_data in endpoint_latencies:
            total_latency += latency_data["latency"]

        return total_latency / len(endpoint_latencies)

    @staticmethod
    def endpoint_name_for_operation(operation_type):
        endpoint = {
            PNOperationType.PNPublishOperation: "pub",
            PNOperationType.PNFireOperation: "pub",
            PNOperationType.PNHistoryOperation: "hist",
            PNOperationType.PNHistoryDeleteOperation: "hist",
            PNOperationType.PNMessageCountOperation: "mc",
            PNOperationType.PNUnsubscribeOperation: "pres",
            PNOperationType.PNWhereNowOperation: "pres",
            PNOperationType.PNHereNowOperation: "pres",
            PNOperationType.PNGetState: "pres",
            PNOperationType.PNSetStateOperation: "pres",
            PNOperationType.PNHeartbeatOperation: "pres",
            PNOperationType.PNAddChannelsToGroupOperation: "cg",
            PNOperationType.PNRemoveChannelsFromGroupOperation: "cg",
            PNOperationType.PNChannelGroupsOperation: "cg",
            PNOperationType.PNChannelsForGroupOperation: "cg",
            PNOperationType.PNRemoveGroupOperation: "cg",
            PNOperationType.PNAddPushNotificationsOnChannelsOperation: "push",
            PNOperationType.PNPushNotificationEnabledChannelsOperation: "push",
            PNOperationType.PNRemoveAllPushNotificationsOperation: "push",
            PNOperationType.PNRemovePushNotificationsFromChannelsOperation: "push",
            PNOperationType.PNAccessManagerAudit: "pam",
            PNOperationType.PNAccessManagerGrant: "pam",
            PNOperationType.PNAccessManagerRevoke: "pam",
            PNOperationType.PNTimeOperation: "pam",
            PNOperationType.PNAccessManagerGrantToken: "pamv3",
            PNOperationType.PNAccessManagerRevokeToken: "pamv3",
            PNOperationType.PNSignalOperation: "sig",
            PNOperationType.PNSetUuidMetadataOperation: "obj",
            PNOperationType.PNGetUuidMetadataOperation: "obj",
            PNOperationType.PNRemoveUuidMetadataOperation: "obj",
            PNOperationType.PNGetAllUuidMetadataOperation: "obj",
            PNOperationType.PNSetChannelMetadataOperation: "obj",
            PNOperationType.PNGetChannelMetadataOperation: "obj",
            PNOperationType.PNRemoveChannelMetadataOperation: "obj",
            PNOperationType.PNGetAllChannelMetadataOperation: "obj",
            PNOperationType.PNSetChannelMembersOperation: "obj",
            PNOperationType.PNGetChannelMembersOperation: "obj",
            PNOperationType.PNRemoveChannelMembersOperation: "obj",
            PNOperationType.PNManageChannelMembersOperation: "obj",
            PNOperationType.PNSetMembershipsOperation: "obj",
            PNOperationType.PNGetMembershipsOperation: "obj",
            PNOperationType.PNRemoveMembershipsOperation: "obj",
            PNOperationType.PNManageMembershipsOperation: "obj",
            PNOperationType.PNAddMessageAction: "msga",
            PNOperationType.PNGetMessageActions: "msga",
            PNOperationType.PNDeleteMessageAction: "msga",
            PNOperationType.PNGetFilesAction: "file",
            PNOperationType.PNDeleteFileOperation: "file",
            PNOperationType.PNGetFileDownloadURLAction: "file",
            PNOperationType.PNFetchFileUploadS3DataAction: "file",
            PNOperationType.PNDownloadFileAction: "file",
            PNOperationType.PNSendFileAction: "file",
        }[operation_type]

        return endpoint


class TokenManager:
    def __init__(self):
        self.token = None

    def set_token(self, token):
        self.token = token

    def get_token(self):
        return self.token

    @classmethod
    def parse_token(cls, token):
        token = cls.unwrap_token(token)

        parsed_token = {
            "version": token["v"],
            "timestamp": token["t"],
            "ttl": token["ttl"],
            "authorized_uuid": token.get("uuid"),
            "resources": {},
            "patterns": {},
            "meta": token["meta"],
        }

        perm_type_name_mapping = {"res": "resources", "pat": "patterns"}

        for resource_type in perm_type_name_mapping:
            for resource in token[resource_type]:
                if resource == "uuid":
                    parsed_token[perm_type_name_mapping[resource_type]]["uuids"] = (
                        utils.parse_pam_permissions(token[resource_type][resource])
                    )
                elif resource == "grp":
                    parsed_token[perm_type_name_mapping[resource_type]]["groups"] = (
                        utils.parse_pam_permissions(token[resource_type][resource])
                    )
                elif resource == "chan":
                    parsed_token[perm_type_name_mapping[resource_type]]["channels"] = (
                        utils.parse_pam_permissions(token[resource_type][resource])
                    )

        return parsed_token

    @staticmethod
    def unwrap_token(token):
        token = token.replace("_", "/").replace("-", "+")
        byte_array = base64.b64decode(token)

        try:
            unwrapped_obj = loads(byte_array)
            decoded_obj = utils.decode_utf8_dict(unwrapped_obj)

            return decoded_obj
        except Exception:
            raise PubNubException(pn_error=PNERR_INVALID_ACCESS_TOKEN)