项目作者: so1n

项目描述 :
rap(par[::-1]) is advanced and fast python async rpc
高级语言: Python
项目地址: git://github.com/so1n/rap.git
创建时间: 2020-08-06T03:00:26Z
项目社区:https://github.com/so1n/rap

开源协议:Apache License 2.0

下载


rap

rap(par[::-1]) is advanced and fast python async rpc

rap achieves very fast communication through msgpack and Python asyncio and multiplexing transport, while supporting high concurrency.
Implement the protobuf of Grpc through Python functions and TypeHint.

Note: The current rap API may change significantly in subsequent versions

The rap first version feature idea comes from aiorpc

Warning
There will be an architectural change in version 0.6

中文文档

1.Installation

  1. pip install rap

2.Quick Start

Server

  1. import asyncio
  2. from typing import AsyncIterator
  3. from rap.server import Server
  4. def sync_sum(a: int, b: int) -> int:
  5. return a + b
  6. async def async_sum(a: int, b: int) -> int:
  7. await asyncio.sleep(1) # mock io
  8. return a + b
  9. async def async_gen(a: int) -> AsyncIterator[int]:
  10. for i in range(a):
  11. yield i
  12. loop = asyncio.new_event_loop()
  13. rpc_server = Server() # init service
  14. # register func
  15. rpc_server.register(sync_sum)
  16. rpc_server.register(async_sum)
  17. rpc_server.register(async_gen)
  18. # run server
  19. loop.run_until_complete(rpc_server.create_server())
  20. try:
  21. loop.run_forever()
  22. except KeyboardInterrupt:
  23. # stop server
  24. loop.run_until_complete(rpc_server.shutdown())

Client

The client supports to invoke the service by invoke_by_name and invoke methods, but this can not fully use the functions of TypeHint, it is recommended to use @client.register to register the function and then invoke it.

Note: For rap.client there is no distinction between async def and def, but functions registered with @client.register can be used directly by the user, so functions decorated with @client.register should be similar to:

  1. async def demo(): pass

example:

  1. import asyncio
  2. from typing import AsyncIterator
  3. from rap.client import Client
  4. client: "Client" = Client() # init client
  5. # Declare a function with no function. The function name, function type and return type must be the same as the server side function (async def does not differ from def)
  6. def sync_sum(a: int, b: int) -> int:
  7. pass
  8. # The decorated function must be an async def function
  9. @client.register()
  10. async def sync_sum(a: int, b: int) -> int:
  11. pass
  12. # The decorated function must be the async def function, because the function is a generator syntax, to `yield` instead of `pass`
  13. @client.register()
  14. async def async_gen(a: int) -> AsyncIterator:
  15. yield
  16. async def main():
  17. client.add_conn("localhost", 9000)
  18. await client.start()
  19. # Call the invoke method; read the function name and then invoke `invoke_by_name`.
  20. print(f"invoke result: {await client.invoke(sync_sum, {'a': 1, 'b': 2})}")
  21. # Basic calls to rap.client
  22. print(f"raw invoke result: {await client.invoke_by_name('sync_sum', {'a': 1, 'b': 2})}")
  23. # Functions registered through `@client.register` can be used directly
  24. # await async_sum(1,3) == await client.invoke_by_name('async_sum', 1, 2)
  25. # It is recommended to use the @client.register method, which can be used by tools such as IDE to determine whether the parameter type is wrong
  26. print(f"decorator result: {await sync_sum(1, 3)}")
  27. async_gen_result: list = []
  28. # Example of an asynchronous generator, which by default opens or reuses the current session of the rap (about the session will be mentioned below)
  29. async for i in async_gen(10):
  30. async_gen_result.append(i)
  31. print(f"async gen result:{async_gen_result}")
  32. asyncio.run(main())

3.Function Introduction

3.1.Register function

The server side supports def and async def, if it is a def function, it will be run with multiple threads. When registering, the TypeHints of the function’s parameters and return value will be checked, and an error will be reported if the type does not match the type specified by json.

The server comes with a registration library. If there are duplicate registrations in the same group, an error will be reported. You can use the group parameter to define the group to be registered or redefine the name of the registration with the name parameter (you also need to specify the corresponding group when the client calls it).

In addition, you can set is_private to True when registering, so that the function can only be called by the local rap.client.

  1. import asyncio
  2. from typing import AsyncIterator
  3. from rap.server import Server
  4. def demo1(a: int, b: int) -> int:
  5. return a + b
  6. async def demo2(a: int, b: int) -> int:
  7. await asyncio.sleep(1)
  8. return a + b
  9. async def demo_gen(a: int) -> AsyncIterator[int]:
  10. for i in range(a):
  11. yield i
  12. server: Server = Server()
  13. server.register(demo1) # register def func
  14. server.register(demo2) # register async def func
  15. server.register(demo_gen) # register async iterator func
  16. server.register(demo2, name='demo2-alias') # Register with the value of `name`
  17. server.register(demo2, group='new-correlation_id') # Register and set the groups to be registered
  18. server.register(demo2, group='root', is_private=True) # Register and set the correlation_id to be registered, and set it to private

For clients, it is recommended to use client.register instead of client.invoke, client.invoke_by_name.
client.register uses Python syntax to define function names, arguments, parameter types, and return value types,
It allows the caller to invoke the function as if it were a normal function, and the function can be checked through tools using the TypeHint feature.
Note: When using client.register, be sure to use async def ....

  1. from typing import AsyncIterator
  2. from rap.client import Client
  3. client: Client = Client()
  4. # register func
  5. @client.register()
  6. async def demo1(a: int, b: int) -> int: pass
  7. # register async iterator fun, replace `pass` with `yield`
  8. # Since `async for` will make multiple requests to the same transport over time, it will check if the session is enabled and automatically reuse the current session if it is enabled, otherwise it will create a new session and use it.
  9. @client.register()
  10. async def demo_gen(a: int) -> AsyncIterator: yield
  11. # Register the general function and set the name to demo2-alias
  12. @client.register(name='demo2-alias')
  13. async def demo2(a: int, b: int) -> int: pass
  14. # Register the general function and set the correlation_id to new-correlation_id
  15. @client.register(group='new-correlation_id')
  16. async def demo2(a: int, b: int) -> int: pass

3.2.session

example

rap client support session function, after enabling the session, all requests will only be requested through the current session’s transport to the corresponding server, while each request, the session_id in the header will set the current session id, convenient for the server to identify.
rap sessions support explicit and implicit settings, each with its own advantages and disadvantages, without mandatory restrictions.

  1. from typing import AsyncIterator
  2. from rap.client import Client
  3. client = Client()
  4. def sync_sum(a: int, b: int) -> int:
  5. pass
  6. @client.register()
  7. async def async_sum(a: int, b: int) -> int:
  8. pass
  9. @client.register()
  10. async def async_gen(a: int) -> AsyncIterator[int]:
  11. yield
  12. async def no_param_run():
  13. # The rap internal implementation uses the session implicitly via the `contextvar` module
  14. print(f"sync result: {await client.invoke(sync_sum, 1, 2)}")
  15. print(f"async result: {await async_sum(1, 3)}")
  16. # The asynchronous generator detects if a session is enabled, and if so, it automatically reuses the current session, otherwise it creates a session
  17. async for i in async_gen(10):
  18. print(f"async gen result:{i}")
  19. async def param_run(session: "Session"):
  20. # By explicitly passing the session parameters in
  21. print(f"sync result: {await client.invoke(sync_sum, 1, 2, session=session)}")
  22. print(f"sync result: {await client.invoke_by_name('sync_sum', 1, 2, session=session)}")
  23. # May be a bit unfriendly
  24. print(f"async result: {await async_sum(1, 3, session=session)}")
  25. # The asynchronous generator detects if a session is enabled, and if so, it automatically reuses the current session, otherwise it creates a session
  26. async for i in async_gen(10):
  27. print(f"async gen result:{i}")
  28. async def execute(session: "Session"):
  29. # The best way to invoke a session explicitly, using a method similar to the mysql cursor
  30. # execute will automatically recognize the type of invoke
  31. print(f"sync result: {await session.execute(sync_sum, arg_list=[1, 2])}")
  32. print(f"sync result: {await session.execute('sync_sum', arg_list=[1, 2])}")
  33. print(f"async result: {await session.execute(async_sum(1, 3))}")
  34. # The asynchronous generator detects if a session is enabled, and if so, it automatically reuses the current session, otherwise it creates a session
  35. async for i in async_gen(10):
  36. print(f"async gen result:{i}")
  37. async def run_once():
  38. client.add_conn("localhost", 9000)
  39. await client.start()
  40. # init session
  41. async with client.session as s:
  42. await no_param_run()
  43. await param_run(s)
  44. await execute(s)
  45. await client.stop()

3.3.channel

example

channel supports client-server interaction in a duplex manner, similar to Http’s WebSocket, it should be noted that the channel does not support group settings.

Only @client.register is supported on the client side to register the channel function, which is characterized by a single argument of type Channel.
The channel will maintain a session and will only communicate with the server via a transport from the time the channel is enabled to the time it is closed.
To avoid the use of ‘while True’, the channel supports the use of ‘async for’ syntax and the use of ‘while await channel.loop()` syntax instead of ‘while True

  1. from rap.client import Channel, Client
  2. from rap.client.model import Response
  3. client = Client()
  4. @client.register()
  5. async def async_channel(channel: Channel) -> None:
  6. await channel.write_to_conn("hello") # send data
  7. cnt: int = 0
  8. while await channel.loop(cnt < 3):
  9. cnt += 1
  10. print(await channel.read_body()) # read data
  11. @client.register()
  12. async def echo_body(channel: Channel) -> None:
  13. await channel.write_to_conn("hi!")
  14. # Reads data, returns only when data is read, and exits the loop if it receives a signal to close the channel
  15. async for body in channel.iter_body():
  16. print(f"body:{body}")
  17. await channel.write_to_conn(body)
  18. @client.register()
  19. async def echo_response(channel: Channel) -> None:
  20. await channel.write_to_conn("hi!")
  21. # Read the response data (including header data), and return only if the data is read, or exit the loop if a signal is received to close the channel
  22. async for response in channel.iter():
  23. response: Response = response # help IDE check type....
  24. print(f"response: {response}")
  25. await channel.write_to_conn(response.body)

3.4.ssl

example

Due to the high degree of encapsulation of the Python asyncio module, rap can be used very easily with ssl

  1. # Quickly generate ssl.crt and ssl.key
  2. openssl req -newkey rsa:2048 -nodes -keyout rap_ssl.key -x509 -days 365 -out rap_ssl.crt

client.py

  1. from rap.client import Client
  2. client = Client(ssl_crt_path="./rap_ssl.crt")

server.py

  1. from rap.server import Server
  2. rpc_server = Server(
  3. ssl_crt_path="./rap_ssl.crt",
  4. ssl_key_path="./rap_ssl.key",
  5. )

3.5.event

The server side supports start_event and stop_event for event handling before start and after shutdown respectively.

  1. from rap.server import Server
  2. async def mock_start():
  3. print('start event')
  4. async def mock_stop():
  5. print('stop event')
  6. # example 1
  7. server = Server(start_event_list=[mock_start()], stop_event_list=[mock_stop()])
  8. # example 2
  9. server = Server()
  10. server.load_before_start_event([mock_start()])
  11. server.load_after_stop_event([mock_stop()])

3.6.middleware

rap currently supports 2 types of middleware::

  • Conn middleware: Used when creating transport, such as limiting the total number of links, etc…
    reference block.py,
    The dispatch method will pass in a transport object, and then determine whether to release it according to the rules (return await self.call_next(transport)) or reject it (await transport.close)
  • Message middleware: only supports normal function calls (no support for Channel), similar to the use of starlette middleware
    reference access.py
    Message middleware will pass in 4 parameters: request(current request object), call_id(current invoke id), func(current invoke function), param(current parameter) and request to return call_id and result(function execution result or exception object)

In addition, the middleware supports start_event_handle and stop_event_handle methods, which are called when the Server starts and shuts down respectively.

example:

  1. from rap.server import Server
  2. from rap.server.plugin.middleware import ConnLimitMiddleware
  3. rpc_server = Server()
  4. rpc_server.load_middleware([ConnLimitMiddleware()])

3.7.processor

The rap processor is used to handle inbound and outbound traffic, where on_request is for inbound traffic and on_response is for outbound traffic.

The methods of rap.client and rap.server processors are basically the same, rap.server supports start_event_handle and stop_event_handle methods, which are called when Server starts and shuts down respectively

server crypto processor example

client crypto processor example

client load processor example

  1. from rap.client import Client
  2. from rap.client.processor import CryptoProcessor
  3. client = Client()
  4. client.load_processor([CryptoProcessor('key_id', 'xxxxxxxxxxxxxxxx')])

server load processor example

  1. from rap.server import Server
  2. from rap.server.plugin.processor import CryptoProcessor
  3. server = Server()
  4. server.load_processor([CryptoProcessor({'key_id': 'xxxxxxxxxxxxxxxx'})])

4.Plugin

rap supports plug-in functionality through middleware and processor, middleware only supports the server side, processor supports the client and server side

4.1.Encrypted transmission

Encrypted transmission only encrypts the request and response body content, not the header etc. While encrypting, the nonce parameter is added to prevent replay, and the timestamp parameter is added to prevent timeout access.

client example:

  1. from rap.client import Client
  2. from rap.client.processor import CryptoProcessor
  3. client = Client()
  4. # The first parameter is the id of the secret key, the server determines which secret key is used for the current request by the id of the secret key
  5. # The second parameter is the key of the secret key, currently only support the length of 16 bits of the secret key
  6. # timeout: Requests that exceed the timeout value compared to the current timestamp will be discarded
  7. # interval: Clear the nonce interval, the shorter the interval, the more frequent the execution, the greater the useless work, the longer the interval, the more likely to occupy memory, the recommended value is the timeout value is 2 times
  8. client.load_processor([CryptoProcessor("demo_id", "xxxxxxxxxxxxxxxx", timeout=60, interval=120)])

server example:

  1. from rap.server import Server
  2. from rap.server.plugin.processor import CryptoProcessor
  3. server = Server()
  4. # The first parameter is the secret key key-value pair, key is the secret key id, value is the secret key
  5. # timeout: Requests that exceed the timeout value compared to the current timestamp will be discarded
  6. # nonce_timeout: The expiration time of nonce, the recommended setting is greater than timeout
  7. server.load_processor([CryptoProcessor({"demo_id": "xxxxxxxxxxxxxxxx"}, timeout=60, nonce_timeout=120)])

4.2. Limit the maximum number of transport

Server-side use only, you can limit the maximum number of links on the server side, more than the set value will not handle new requests

  1. from rap.server import Server
  2. from rap.server.plugin.middleware import ConnLimitMiddleware, IpMaxConnMiddleware
  3. server = Server()
  4. server.load_middleware(
  5. [
  6. # max_conn: Current maximum number of transport
  7. # block_timeout: Access ban time after exceeding the maximum number of transport
  8. ConnLimitMiddleware(max_conn=100, block_time=60),
  9. # ip_max_conn: Maximum number of transport per ip
  10. # timeout: The maximum statistics time for each ip, after the time no new requests come in, the relevant statistics will be cleared
  11. IpMaxConnMiddleware(ip_max_conn=10, timeout=60),
  12. ]
  13. )

4.3.Limit ip access

Support restrict single ip or whole segment ip, support both whitelist and blacklist mode, if whitelist is enabled, blacklist mode is disabled by default

  1. from rap.server import Server
  2. from rap.server.plugin.middleware import IpFilterMiddleware
  3. server = Server()
  4. # allow_ip_list: whitelist, support network segment ip, if filled with allow_ip_list, black_ip_list will be invalid
  5. # black_ip_list: blacklist, support network segment ip
  6. server.load_middleware([IpFilterMiddleware(allow_ip_list=['192.168.0.0/31'], block_ip_list=['192.168.0.2'])])

5.Advanced Features

TODO, This feature is not yet implemented

6.Protocol Design

TODO, Document is being edited

7.Introduction to the rap transport

TODO, Document is being edited