API Reference¶
This sections outlines the shinkei API.
Client¶
-
shinkei.
connect
(url, application_id, client_id, auth=None, *, tags=None, reconnect=True, session=None, loop=None, klass=None, handlers=None, proxy_ip=None, **kwargs)¶ Connect to singyeong.
Since this returns a context manager mixin of
Client
, bothasync with shinkei.connect(*args, **kwargs): # ....
and
client = await shinkei.connect(*args, **kwargs): try: # ... finally: await client.close()
are valid and do the same thing.
- Parameters
url (
str
) – The base url for the WebSocket url.application_id (
str
) – A unique id which should be shared among all related clients.client_id (
str
) – An id unique across all clients connected to the same application.auth (Optional[
str
]) – A password used to access the server. If an incorrect password is sent the client will be put in restricted mode. Defaults toNone
.tags (Optional[
list
]) – A list of tags to identify the client and to allow the discovery of it’s application id. If the client is restricted the tags will be ignored.reconnect (Optional[
bool
]) – Whether or not to reconnect when singyeong sends a GOODBYE payload or when the WebSocket disconnects for other reasons. Defaults toTrue
handlers (Optional[List[
Handler
]]) – The initial handlers to register.session (Optional[
aiohttp.ClientSession
]) – The session used for HTTP requests. If none is provided, a new one will be created.loop (Optional[
asyncio.AbstractEventLoop
]) – The loop used to connect to the websocket and make HTTP requests. If non is provided,asyncio.get_event_loop()
will be used to get one.klass (Optional[Type[
Client
]]) – The classed used to instantiate the client. Defaults toClient
.proxy_ip (Optional[
str
]) – The IP that the server will use to proxy HTTP requests.kwargs – All other kwargs will be passed onto the Client class’
_connect
method. Useful when passing a custom class.
- Returns
The client.
- Return type
A context manager mixin of
Client
-
class
shinkei.
Client
¶ The main client connecting to singyeong.
This is not supposed to be instantiated manually but through
connect()
-
loop
¶ The loop used to connect to the websocket make HTTP requests.
-
session
¶ The aiohttp session used for HTTP requests.
-
restricted
¶ Whether or not the client is restricted. A client is restricted usually when it fails to provide the right password.
- Type
-
await
send
(data, *, target, nonce=None)¶ Send data to a client which matches the predicates of the
target
query.Restricted clients cannot use this method.
- Parameters
- Raises
ShinkeiWSException – The client is restricted.
-
await
broadcast
(data, *, target, nonce=None)¶ Send data to all clients which matches the predicates of the
target
query.Restricted clients cannot use this method.
- Parameters
- Raises
ShinkeiWSException – The client is restricted.
-
await
update_metadata
(data, *, cache=True)¶ Update metadata on singyeong.
The data is not consistent between server restarts but if
cache
is set toTrue
then it will persist between reconnects.- Parameters
- Raises
ShinkeiWSException – The metadata structure was invalid or a restricted key was used.
-
await
proxy_request
(method, route, *, target, body=None, headers=None)¶ Make a proxy HTTP request to a client.
- Parameters
method (
str
) – The HTTP method to use. Supports only POST, PATCH, PUT, DELETE, MOVE, GET and HEAD.route (
str
) – The route to make the request to.body (Optional[Union[
str
,dict
,list
]]) – The request body, silently ignored in GET and HEAD. If none is provided but the method requires one an empty string will be sent.target (
QueryBuilder
) – The query that is used to match the client.
- Returns
The HTTP response.
- Return type
- Raises
ValueError – An unsupported request method was passed.
ShinkeiHTTPException – The HTTP proxy request failed.
-
await
discover
(tags)¶ Discover an application id by it’s clients tags.
-
add_handler
(handler)¶ A function used to manually add handler to the client.
- Parameters
handler (
Handler
) – The handler to add.- Returns
The handler added.
- Return type
- Raises
ValueError – The handler was already registered. This is determined by the name of the handler.
-
remove_handler
(handler_name)¶ Remove a handler by name.
-
await
wait_for
(event, *, timeout=None, check=None)¶ Wait for an event.
- Parameters
- Returns
The return value of the event.
- Return type
Any
-
stream
(event, *, timeout=None, check=None, limit=None)¶ Return an async iterator which waits until an event is dispatched before continuing the iterations.
- Parameters
event (
str
) – Same asClient.wait_for()
.timeout (Optional[Union[
int
,float
]]) – Same asClient.wait_for()
.check (Optional[Callable[…,
bool
]]) – Same asClient.wait_for()
.limit (Optional[
int
]) – The maximum amount of iteration before the iterator stops. By default it never does.
- Yields
Any – The return value of the event.
-
await
close
()¶ Close the connection to singyeong.
Run this when cleaning up.
-
Event Reference¶
All the following events can be catched through event handlers
or specific methods like Client.wait_for()
or Client.stream()
.
-
shinkei.
data
¶ This event is fired whenever this client receives data from other clients trough
Client.send()
andClient.broadcast()
.The only argument returned is the data represented as
MetadataPayload
.
-
shinkei.
ready
¶ This event is fire whenever the WebSocket has connected and successfully identified.
No arguments are returned.
-
shinkei.
error
¶ This event is fired whenever the WebSocket returns an error message.
The only argument returned is the error message as a
str
.
-
shinkei.
connect
This event is fired whenever the WebSocket has successfully connected.
No arguments are returned.
-
shinkei.
disconnect
¶ This event is fired whenever the WebSocket has disconnected.
No arguments are returned.
Event Handlers¶
Events described in the event reference are handled through the proper handlers.
Event handlers are classes which subclass Handler
and have functions which listen to events decorated with
the listens_to()
.
See the following piece of code for an example:
class CustomHandler(shinkei.Handler, name="custom"):
@shinkei.listens_to("data")
async def data_receiver(self, data):
print("{0.qualified_name} received {1.payload}!".format(self, data))
# somewhere else...
client = await shinkei.connect(..., handlers=[CustomHandler()])
Through this handler, every time the client receives data it will print custom received <data-here>!
-
class
shinkei.
HandlerMeta
¶ A metaclass used to implement the main functionality of the handlers.
Not really to be used directly but rather to implement more complex custom handler classes.
Note
The listed args are meant to be passed in the type constructor as kwargs, like this:
class MyHandler(shinkei.Handler, name="My Handler"): pass
- Parameters
name (Optional[
str
]) – The name of the handler, used to determine if it has already been registered or not. Defaults to the class’s name.
-
class
shinkei.
Handler
¶ The base class for event handlers.
This class is made only for subclassing.
Query Builder¶
-
class
shinkei.
QueryBuilder
(application, key, **kwargs)¶ A utility to build queries which routes clients based on their metadata.
Used mostly in
Client.send()
andClient.broadcast()
.Example using key-value queries:
# this will target every client part of "my-cool-app" where "special_value" is greater then 5 shinkei.QueryBuilder(application="my-cool-app", key="uniquekey").gt("special_value", 5)
Example using
Node
based query:# this will target every client part of "my-cool-app" where "special_value" is greater then 5 or is equal to 10 shinkei.QueryBuilder(application="my-cool-app", key="uniquekey").either( "special_value", shinkei.Node().eq(10).gt(5) )
- Parameters
application (
str
) – The id of the target application.key (
str
) – The key used for consistent-hashing when choosing a client from the output.restricted (Optional[
bool
]) – Whether or not if restricted clients should be included. Defaults toFalse
.optional (Optional[
bool
]) – Whether or not to return a result even if the query fails. Defaults toFalse
.
-
eq
(key, value)¶ Match if the value of
key
equals tovalue
.
-
ne
(key, value)¶ Match if the value of
key
is not equal tovalue
.
-
gt
(key, value)¶ Match if the value of
key
is greater thenvalue
.
-
gte
(key, value)¶ Match if the value of
key
is equal to or greater thenvalue
.
-
lt
(key, value)¶ Match if the value of
key
is lower thenvalue
.
-
lte
(key, value)¶ Match if the value of
key
is equal to or lower thenvalue
.
-
ncontains
(key, value)¶ Match if
value
is not inside the value ofkey
.The value of
key
must be alist
.
-
class
shinkei.
Node
¶ Similar to
QueryBuilder
.Used only for predicates inside
also()
,either()
andneither()
.-
eq
(value)¶ Equal to
QueryBuilder.eq()
, but only takes a value.
-
ne
(value)¶ Equal to
QueryBuilder.ne()
, but only takes a value.
-
gt
(value)¶ Equal to
QueryBuilder.gt()
, but only takes a value.
-
gte
(value)¶ Equal to
QueryBuilder.gte()
, but only takes a value.
-
lt
(value)¶ Equal to
QueryBuilder.lt()
, but only takes a value.
-
lte
(value)¶ Equal to
QueryBuilder.lte()
, but only takes a value.
-
inside
(value)¶ Equal to
QueryBuilder.inside()
, but only takes a value.
-
ninside
(value)¶ Equal to
QueryBuilder.ninside()
, but only takes a value.
-
contains
(value)¶ Equal to
QueryBuilder.contains()
, but only takes a value.
-
ncontains
(value)¶ Equal to
QueryBuilder.ncontains()
, but only takes a value.
-
Data Classes¶
-
class
shinkei.
Version
¶ An object representing the API and singyeong version.
-
class
shinkei.
MetadataPayload
¶ An object representing a payload of data received from a client.
-
nonce
¶ A unique nonce used to identify the payload.
-
-
class
shinkei.
VersionMetadata
(fmt)¶ An object to represent a version object in
Client.update_metadata()
.This is NOT the same as
Version
.- Parameters
fmt (
str
) – The version string. Must be complient to the elixir specification.
Exceptions¶
-
class
shinkei.
ShinkeiException
¶ Base exception for this library.
All following exceptions inherit from this.
-
class
shinkei.
ShinkeiResumeWS
¶ An internal exception raised when the WebSocket has been disconnected but can resume.