Passed
Push — main ( 70403e...e2587c )
by
unknown
01:20
created

pincer.core.heartbeat.get_heartbeat()   A

Complexity

Conditions 1

Size

Total Lines 10
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 10
rs 10
c 0
b 0
f 0
cc 1
nop 0
1
# -*- coding: utf-8 -*-
0 ignored issues
show
introduced by
Missing module docstring
Loading history...
2
# MIT License
3
#
4
# Copyright (c) 2021 Pincer
5
#
6
# Permission is hereby granted, free of charge, to any person obtaining
7
# a copy of this software and associated documentation files
8
# (the "Software"), to deal in the Software without restriction,
9
# including without limitation the rights to use, copy, modify, merge,
10
# publish, distribute, sublicense, and/or sell copies of the Software,
11
# and to permit persons to whom the Software is furnished to do so,
12
# subject to the following conditions:
13
#
14
# The above copyright notice and this permission notice shall be
15
# included in all copies or substantial portions of the Software.
16
#
17
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
21
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24
25
from __future__ import annotations
26
27
import logging
28
from asyncio import sleep
29
from typing import Optional
30
31
from websockets.legacy.client import WebSocketClientProtocol
32
33
from pincer import __package__
1 ignored issue
show
Bug Best Practice introduced by
This seems to re-define the built-in __package__.

It is generally discouraged to redefine built-ins as this makes code very hard to read.

Loading history...
34
from pincer.core.dispatch import GatewayDispatch
35
from pincer.exceptions import HeartbeatError
36
37
heartbeat: float = 0
38
sequence: Optional[int] = None
39
40
log = logging.getLogger(__package__)
41
42
43
def get_heartbeat() -> float:
44
    """
45
    Get the current heartbeat.
46
47
    :return:
48
        The current heartbeat of the client.
49
        Default is 0 (client has not initialized the heartbeat yet.)
50
51
    """
52
    return heartbeat
53
54
55
async def __send_heartbeat(socket: WebSocketClientProtocol):
56
    """
57
    Sends a heartbeat to the API gateway.
58
    """
59
    global sequence
1 ignored issue
show
Coding Style Naming introduced by
Constant name "sequence" doesn't conform to UPPER_CASE naming style ('([^\\W\\da-z][^\\Wa-z]*|__.*__)$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
Coding Style introduced by
Usage of the global statement should be avoided.

Usage of global can make code hard to read and test, its usage is generally not recommended unless you are dealing with legacy code.

Loading history...
60
61
    log.debug(f"Sending heartbeat (seq: {sequence})")
0 ignored issues
show
introduced by
Use lazy % formatting in logging functions
Loading history...
62
    await socket.send(str(GatewayDispatch(1, sequence)))
63
64
65
async def handle_hello(socket: WebSocketClientProtocol,
66
                       payload: GatewayDispatch):
67
    """
68
    Handshake between the discord API and the client.
69
    Retrieve the heartbeat for maintaining a connection.
70
    """
71
    global heartbeat
1 ignored issue
show
Coding Style Naming introduced by
Constant name "heartbeat" doesn't conform to UPPER_CASE naming style ('([^\\W\\da-z][^\\Wa-z]*|__.*__)$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
Coding Style introduced by
Usage of the global statement should be avoided.

Usage of global can make code hard to read and test, its usage is generally not recommended unless you are dealing with legacy code.

Loading history...
72
73
    log.debug("Handling initial discord hello websocket message.")
74
    heartbeat = payload.data.get("heartbeat_interval")
75
76
    if not heartbeat:
77
        log.error(
0 ignored issues
show
introduced by
Use lazy % formatting in logging functions
Loading history...
78
            "No `heartbeat_interval` is present. Has the API changed? "
79
            f"(payload: {payload})"
80
        )
81
82
        raise HeartbeatError(
83
            "Discord hello is missing `heartbeat_interval` in payload."
84
            "Because of this the client can not maintain a connection. "
85
            "Check logging for more information."
86
        )
87
88
    heartbeat /= 1000
89
    log.debug(f"Maintaining a connection with heartbeat: {heartbeat}")
0 ignored issues
show
introduced by
Use lazy % formatting in logging functions
Loading history...
90
91
    if sequence:
92
        await socket.send(str(GatewayDispatch(6, sequence, seq=sequence)))
93
    else:
94
        await __send_heartbeat(socket)
95
96
97
async def handle_heartbeat(socket: WebSocketClientProtocol, _):
98
    """
99
    Handles a heartbeat, which means that it rests and then sends a new
100
    heartbeat.
101
    """
102
    global heartbeat
1 ignored issue
show
Coding Style introduced by
Usage of the global statement should be avoided.

Usage of global can make code hard to read and test, its usage is generally not recommended unless you are dealing with legacy code.

Loading history...
Coding Style Naming introduced by
Constant name "heartbeat" doesn't conform to UPPER_CASE naming style ('([^\\W\\da-z][^\\Wa-z]*|__.*__)$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
103
104
    logging.debug(f"Resting heart for {heartbeat}s")
0 ignored issues
show
introduced by
Use lazy % formatting in logging functions
Loading history...
105
    await sleep(heartbeat)
106
    await __send_heartbeat(socket)
107
108
109
def update_sequence(seq: int):
110
    """
111
    Update the heartbeat sequence.
112
113
    :param seq:
114
        The new heartbeat sequence to be updated with.
115
    """
116
    global sequence
1 ignored issue
show
Coding Style introduced by
Usage of the global statement should be avoided.

Usage of global can make code hard to read and test, its usage is generally not recommended unless you are dealing with legacy code.

Loading history...
Coding Style Naming introduced by
Constant name "sequence" doesn't conform to UPPER_CASE naming style ('([^\\W\\da-z][^\\Wa-z]*|__.*__)$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
117
    log.debug("Updating heartbeat sequence...")
118
    sequence = seq
119