Metadata-Version: 2.4
Name: signalrcore
Version: 1.1.0
Summary: Python SignalR Core full client (transports and encodings). Compatible with azure / serverless functions. Also with automatic reconnect and manually reconnect.
Author-email: mandrewcito <signalrcore@mandrewcito.dev>
License-Expression: MIT
Project-URL: Homepage, https://signalrcore.mandrewcito.dev
Project-URL: Documentation, https://mandrewcito.github.io/signalrcore/
Project-URL: Repository, https://github.com/mandrewcito/signalrcore
Project-URL: Tracker, https://github.com/mandrewcito/signalrcore/issues
Project-URL: Changelog, https://github.com/mandrewcito/signalrcore/releases
Keywords: signalr,core,client,3.1+
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: OS Independent
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: msgpack==1.2.4
Provides-Extra: dev
Requires-Dist: requests; extra == "dev"
Requires-Dist: flake8; extra == "dev"
Requires-Dist: coverage; extra == "dev"
Requires-Dist: pytest; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"
Requires-Dist: build; extra == "dev"
Dynamic: license-file


![logo alt](https://raw.githubusercontent.com/mandrewcito/signalrcore/master/docs/img/logo_temp.128.svg.png)


# SignalR core client
[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg?logo=paypal&style=flat-square)](https://www.paypal.me/mandrewcito/1)
![Pypi](https://img.shields.io/pypi/v/signalrcore.svg)
[![Downloads](https://pepy.tech/badge/signalrcore/month)](https://pepy.tech/project/signalrcore/month)
[![Downloads](https://pepy.tech/badge/signalrcore)](https://pepy.tech/project/signalrcore)
![Issues](https://img.shields.io/github/issues/mandrewcito/signalrcore.svg)
![Open issues](https://img.shields.io/github/issues-raw/mandrewcito/signalrcore.svg)
![codecov.io](https://codecov.io/github/mandrewcito/signalrcore/coverage.svg?branch=master)

Python signalr core client library, made by a guy born in Vilalba (Lugo).

## About V1.0.0 (aka poluca)  

Feature list:
* All kind of communications with the server (streaming, sending messages)
* All transports implemented (sse, long polling and web sockets)
* All encodings (text, binary - msgpack)
* Authentication
* Automatic reconnection with different strategies 
* Custom ssl context passthrough ([see certificates article](https://github.com/mandrewcito/signalrcore/blob/main/docs/articles/CustomClientCert.md))
* AsyncIO implementation: transports, streaming, async callbacks and reconnection
* ... 

## Upcoming changes

* Test suite, divide test into integration and unit. Making stubs of clients which enable testing without server
  * Managed solution azure server. For testing purposes only (PRs targeting main branch)
* Ack/Sequence implementation
* ...

# Links 

* [Dev to posts with library examples and implementation](https://dev.to/mandrewcito/singlar-core-python-client-58e7)

* [Pypi](https://pypi.org/project/signalrcore/)

* [Documentation](https://mandrewcito.github.io/signalrcore/)

* [Aspnetcore SignalR docs](https://github.com/dotnet/aspnetcore/tree/main/src/SignalR/docs)

# Development
Software requirements:
> - python >= 3.10 (recommended 3.12 LTS)
> - virtualenv
> - pip
> - docker
> - docker compose
> 
> Test environment has as a requirement a signalr core server, is available in [here](https://github.com/mandrewcito/signalrcore-containertestservers)

Clone repos and install virtual environment:

```bash
git clone https://github.com/mandrewcito/signalrcore-containertestservers
cd signalrcore
make dev-install
git clone https://github.com/mandrewcito/signalrcore-containertestservers
cd signalrcore-containertestservers
docker compose up
cd ../signalrcore
make tests
```
Have fun :)

# A Tiny How To

You can reach a lot of examples in *tests* folder, raw implementations in *playground* and fully working examples at the *examples* folder.

## Connect to a server without auth

```python
hub_connection = HubConnectionBuilder()\
    .with_url(server_url)\
    .configure_logging(logging.DEBUG)\
    .with_automatic_reconnect({
        "type": "raw",
        "keep_alive_interval": 10,
        "reconnect_interval": 5,
        "max_attempts": 5
    }).build()
```
## Connect to a server with auth

login_function must provide auth token

```python
hub_connection = HubConnectionBuilder()\
            .with_url(server_url,
            options={
                "access_token_factory": login_function,
                "headers": {
                    "mycustomheader": "mycustomheadervalue"
                }
            })\
            .configure_logging(logging.DEBUG)\
            .with_automatic_reconnect({
                "type": "raw",
                "keep_alive_interval": 10,
                "reconnect_interval": 5,
                "max_attempts": 5
            }).build()
```
### Unauthorized errors
A login function must provide an error controller if authorization fails. When connection starts, if authorization fails exception will be propagated. Exceptions raised by the token factory are passed through unchanged; negotiate rejections raise `UnAuthorizedHubError` for HTTP 401 and `HubError` for any other non-200 status or invalid body.

```python
    def login(self):
        response = requests.post(
            self.login_url,
            json={
                "username": self.email,
                "password": self.password
                },verify=False)
        if response.status_code == 200:
            return response.json()["token"]
        raise requests.exceptions.ConnectionError()

    hub_connection.start()   # this code will raise  requests.exceptions.ConnectionError() if auth fails
```
## Configure logging

```python
HubConnectionBuilder()\
    .with_url(server_url)\
    .configure_logging(logging.DEBUG)
    ...
```

Calling `configure_logging()` more than once reuses the same handler and updates its level and formatter, so each message is logged once.

## Configure socket trace
```python 
HubConnectionBuilder()\
    .with_url(server_url,
    .configure_logging(logging.DEBUG, socket_trace=True) 
    ... 
 ```
## Configure your own handler
```python
 import logging
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
hub_connection = HubConnectionBuilder()\
    .with_url(server_url, options={"verify_ssl": False}) \
    .configure_logging(logging.DEBUG, socket_trace=True, handler=handler)
    ...
 ```

A custom handler is only attached once, even if `configure_logging()` is called repeatedly with the same handler.
 
## Configuring reconnection
After reaching max_attempts an exception will be thrown and on_disconnect event will be fired.
```python
hub_connection = HubConnectionBuilder()\
    .with_url(server_url)\
    ...
    .build()
```
## Configuring additional headers
```python
hub_connection = HubConnectionBuilder()\
            .with_url(server_url,
            options={
                "headers": {
                    "mycustomheader": "mycustomheadervalue"
                }
            })
            ...
            .build()
```

## Configuring additional querystring parameters
```python
server_url ="http.... /?myQueryStringParam=134&foo=bar"
connection = HubConnectionBuilder()\
            .with_url(server_url,
            options={
            })\
            .build()
```

## Configuring skip negotiation
```python
hub_connection = HubConnectionBuilder() \
        .with_url("ws://"+server_url, options={
            "verify_ssl": False,
            "skip_negotiation": False,
            "headers": {
            }
        }) \
        .configure_logging(logging.DEBUG, socket_trace=True, handler=handler) \
        .build()

```

## Configuring ping(keep alive)

keep_alive_interval sets the seconds of ping message

```python
hub_connection = HubConnectionBuilder()\
    .with_url(server_url)\
    .configure_logging(logging.DEBUG)\
    .with_automatic_reconnect({
        "type": "raw",
        "keep_alive_interval": 10,
        "reconnect_interval": 5,
        "max_attempts": 5
    }).build()
```

## Configuring logging
```python
hub_connection = HubConnectionBuilder()\
    .with_url(server_url)\
    .configure_logging(logging.DEBUG)\
    .with_automatic_reconnect({
        "type": "raw",
        "keep_alive_interval": 10,
        "reconnect_interval": 5,
        "max_attempts": 5
    }).build()
```

## Configure messagepack

```python
from signalrcore.protocol.messagepack_protocol import MessagePackHubProtocol

HubConnectionBuilder()\
            .with_url(self.server_url, options={"verify_ssl":False})\
                ... 
            .with_hub_protocol(MessagePackHubProtocol())\
                ...
            .build()
```
## Configure custom ssl context
You can add a custom ssl context to all requests and sockets

```python
MY_CA_FILE_PATH = "ca.crt"
context = ssl.create_default_context(
    cafile=MY_CA_FILE_PATH
)

options = {
    "ssl_context": context
}

builder = HubConnectionBuilder()\
    .with_url(self.server_url, options=options)\
    .configure_logging(
        logging.INFO,
        socket_trace=True)
 
connection = builder.build()
``` 

More info about certificates [here](https://github.com/mandrewcito/signalrcore/blob/main/docs/articles/CustomClientCert.md)

### Websockets

Will be used as transport layer by default, you do not need to specify it.

```python
HubConnectionBuilder()\
    .with_url(server_http_url, options={
        ...
        "transport": HttpTransportType.web_sockets
        })\
    .configure_logging(logging.ERROR)\
    .build()
```

### Server sent events

```python
HubConnectionBuilder()\
    .with_url(server_http_url, options={
        ...
        "transport": HttpTransportType.server_sent_events
        })\
    .configure_logging(logging.ERROR)\
    .build()
```
### Long polling

```python
HubConnectionBuilder()\
    .with_url(server_http_url, options={
        ...
        "transport": HttpTransportType.long_polling
        })\
    .configure_logging(logging.ERROR)\
    .build()
```
## Events

### On Connect / On Disconnect
on_open - fires when connection is opened and ready to send messages
on_close - fires when connection is closed
```python
hub_connection.on_open(lambda: print("connection opened and handshake received ready to send messages"))
hub_connection.on_close(lambda: print("connection closed"))

```
### On Hub Error (Hub Exceptions ...)
```
hub_connection.on_error(lambda data: print(f"An exception was thrown closed{data.error}"))
```
### Register an operation 
ReceiveMessage - signalr method
print - function that has as parameters args of signalr method
```python
hub_connection.on("ReceiveMessage", print)
```
## Sending messages
SendMessage - signalr method
username, message - parameters of signalrmethod
```python
    hub_connection.send("SendMessage", [username, message])
```

## Sending messages with callback
SendMessage - signalr method
username, message - parameters of signalrmethod
```python
    send_callback_received = threading.Lock()
    send_callback_received.acquire()
    self.connection.send(
        "SendMessage", # Method
        [self.username, self.message], # Params
        lambda m: send_callback_received.release()) # Callback
    if not send_callback_received.acquire(timeout=1):
        raise ValueError("CALLBACK NOT RECEIVED")
```

## Requesting streaming (Server to client)
```python
hub_connection.stream(
            "Counter",
            [len(self.items), 500]).subscribe({
                "next": self.on_next,
                "complete": self.on_complete,
                "error": self.on_error
            })
```

`stream()` requires a running transport. If the connection is not started, stopped, or reconnecting, it raises `HubConnectionError` and does not register the stream handler. `send()` and `invoke()` behave the same way.

## Client side Streaming
```python
from signalrcore.subject import  Subject

subject = Subject()

# Start Streaming
hub_connection.send("UploadStream", subject)

# Each iteration
subject.next(str(iteration))

# End streaming
subject.complete()
```

# AIO

The AIO client is an asyncio-native implementation built with the standard library. It supports WebSockets, Server-Sent Events and Long Polling, JSON and MessagePack, authentication, proxies, TLS, automatic reconnection and streaming. Every network operation is a coroutine, and callbacks may be synchronous or asynchronous.

See the [AsyncIO documentation](docs/aio.md) for the complete reference.

## Create connection

```python
from signalrcore.aio.aio_hub_connection_builder import AIOHubConnectionBuilder

builder = AIOHubConnectionBuilder()\
    .with_url(self.server_url, options=options)\
    .configure_logging(
        self.get_log_level(),
        socket_trace=self.is_debug())\
    .with_automatic_reconnect({
        "type": "raw",
        "keep_alive_interval": 10,
        "reconnect_interval": 5,
        "max_attempts": 5
    })

hub = builder.build()

await hub.start()

await hub.invoke("SendMessage", [username, message])

await hub.stop()
```

`await hub.start()` waits until the handshake completes for at most `AIO_CONNECTION_TIMEOUT` seconds (30 by default). Negotiation and the transport connection have their own bounds, and `await hub.stop()` bounds shutdown with `AIO_CLOSE_TIMEOUT` (10 seconds by default). If a stage does not complete, `TimeoutError` is raised instead of hanging. `await hub.stop()` is safe to call before `start()`. The state can also be awaited explicitly:

```python
from signalrcore.transport.base_transport import TransportState

await hub.wait_until_state(TransportState.connected, timeout=10)
```

## Transports and encoding

The negotiated WebSockets transport is used by default. To force another transport, pass `HttpTransportType` in the options:

```python
from signalrcore.types import HttpTransportType

hub = AIOHubConnectionBuilder()\
    .with_url(
        "https://localhost:5001/chatHub",
        options={
            "verify_ssl": False,
            "transport": HttpTransportType.long_polling
        })\
    .build()
```

Use `MessagePackHubProtocol` for binary encoding. MessagePack requires a transport that supports the `Binary` transfer format, such as WebSockets or Long Polling:

```python
from signalrcore.protocol.messagepack_protocol import MessagePackHubProtocol

hub = AIOHubConnectionBuilder()\
    .with_url(server_url, options={"verify_ssl": False})\
    .with_hub_protocol(MessagePackHubProtocol())\
    .build()
```

## Async callbacks

Event, lifecycle, invocation and stream callbacks can be plain functions or coroutine functions. Coroutine callbacks are awaited before message processing continues:

```python
async def on_open():
    print("Connected")

async def on_message(arguments):
    await asyncio.sleep(0)
    print(arguments)

hub.on_open(on_open)
hub.on("ReceiveMessage", on_message)
```

Do not block the event loop from a callback. Use `await asyncio.sleep()` and async clients instead of `time.sleep()` or synchronous network calls.

## Streaming

Server streaming uses an awaited `stream()` call followed by `subscribe()`:

```python
import asyncio

done = asyncio.Event()

stream = await hub.stream("Counter", [10, 500])
stream.subscribe({
    "next": lambda item: print("Received:", item),
    "complete": lambda message: done.set(),
    "error": lambda message: done.set()
})

await done.wait()
```

Client-to-server streaming uses `AIOSubject`. Its operations are coroutines:

```python
from signalrcore.aio.subject import AIOSubject

subject = AIOSubject()
await hub.send("UploadStream", subject)

for i in range(10):
    await subject.next(str(i))

await subject.complete()
```

The synchronous `signalrcore.subject.Subject` is not compatible with asyncio connections; passing it raises a clear `TypeError`.

## Authentication and proxies

`access_token_factory` may be a normal function or a coroutine function. The token is fetched before connecting and sent as a bearer token:

```python
async def get_token():
    return await fetch_token()

hub = AIOHubConnectionBuilder()\
    .with_url(
        server_url,
        options={
            "verify_ssl": False,
            "access_token_factory": get_token
        })\
    .configure_proxies({
        "http": "http://proxy.example.com:8080",
        "https": "http://proxy.example.com:8080"
    })\
    .build()
```

Plain HTTP proxy requests use the absolute-form target, while HTTPS/WSS connections use `CONNECT` tunnelling followed by TLS. Use `verify_ssl: False` for local development or pass a custom `ssl_context` for certificate configuration.

# Full Examples

Examples will be available [here](https://github.com/mandrewcito/signalrcore/tree/master/test/examples)
It were developed using package from [aspnet core - SignalRChat](https://codeload.github.com/aspnet/Docs/zip/master) 

## Chat example
A mini example could be something like this:

```python
import logging
import sys
from signalrcore.hub_connection_builder import HubConnectionBuilder


def input_with_default(input_text, default_value):
    value = input(input_text.format(default_value))
    return default_value if value is None or value.strip() == "" else value


server_url = input_with_default('Enter your server url(default: {0}): ', "wss://localhost:44376/chatHub")
username = input_with_default('Enter your username (default: {0}): ', "mandrewcito")
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
hub_connection = HubConnectionBuilder()\
    .with_url(server_url, options={"verify_ssl": False}) \
    .configure_logging(logging.DEBUG, socket_trace=True, handler=handler) \
    .with_automatic_reconnect({
            "type": "interval",
            "keep_alive_interval": 10,
            "intervals": [1, 3, 5, 6, 7, 87, 3]
        }).build()

hub_connection.on_open(lambda: print("connection opened and handshake received ready to send messages"))
hub_connection.on_close(lambda: print("connection closed"))

hub_connection.on("ReceiveMessage", print)
hub_connection.start()
message = None

# Do login

while message != "exit()":
    message = input(">> ")
    if message is not None and message != "" and message != "exit()":
        hub_connection.send("SendMessage", [username, message])

hub_connection.stop()

sys.exit(0)

```
