How to use the grpclib.encoding.proto.ProtoCodec function in grpclib

To help you get started, we’ve selected a few grpclib examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github vmagamedov / grpclib / tests / conn.py View on Github external
def grpc_decode(message_bin, message_type=None, codec=ProtoCodec()):
    message_len = struct.unpack('>I', message_bin[1:5])[0]
    assert len(message_bin) == message_len + 5
    message = codec.decode(message_bin[5:], message_type)
    return message
github vmagamedov / grpclib / tests / test_server_stream.py View on Github external
def _stream_streaming(stub):
    stream = Stream(stub, '/svc/Method', Cardinality.UNARY_STREAM,
                    DummyRequest, DummyReply,
                    codec=ProtoCodec(), status_details_codec=None,
                    dispatch=_DispatchServerEvents())
    stream.metadata = MultiDict()
    return stream
github vmagamedov / grpclib / tests / test_codec.py View on Github external
def test_proto_invalid_type():
    codec = ProtoCodec()
    assert codec.encode(DummyRequest(value='42'), DummyRequest) == \
        DummyRequest(value='42').SerializeToString()
    with pytest.raises(TypeError, match='Message must be of type'):
        codec.encode(1, DummyRequest)
github vmagamedov / grpclib / tests / test_client_stream.py View on Github external
async def test_connection_error():
    class BrokenChannel:
        _calls_started = 0

        def __connect__(self):
            raise IOError('Intentionally broken connection')

    stream = Stream(BrokenChannel(), '/foo/bar', MultiDict(),
                    Cardinality.UNARY_UNARY, DummyRequest, DummyReply,
                    codec=ProtoCodec(), status_details_codec=None,
                    dispatch=_DispatchChannelEvents())

    with pytest.raises(IOError) as err:
        async with stream:
            await stream.send_request()
    err.match('Intentionally broken connection')
github vmagamedov / grpclib / tests / test_server_stream.py View on Github external
to_client_transport = TransportStub(client_h2c)
    to_server_transport = TransportStub(server_h2c)

    client_conn = Connection(client_h2c, to_server_transport, config=config)
    server_conn = Connection(server_h2c, to_client_transport, config=config)

    server_proc = EventsProcessor(DummyHandler(), server_conn)
    client_proc = EventsProcessor(DummyHandler(), client_conn)

    client_h2_stream = client_conn.create_stream()
    await client_h2_stream.send_request(create_headers(),
                                        _processor=client_proc)

    request = DummyRequest(value='ping')
    await send_message(client_h2_stream, ProtoCodec(), request, DummyRequest,
                       end=True)
    to_server_transport.process(server_proc)

    server_h2_stream = server_proc.handler.stream
    request_metadata = decode_metadata(server_proc.handler.headers)

    async with mk_stream(server_h2_stream, request_metadata) as server_stream:
        await server_stream.recv_message()

        # simulating client closing stream
        await client_h2_stream.reset()
        to_server_transport.process(server_proc)

        # we should fail here on this attempt to send something
        await server_stream.send_message(DummyReply(value='pong'))
github vmagamedov / grpclib / tests / test_server_stream.py View on Github external
def mk_stream(h2_stream, metadata):
    stream = Stream(h2_stream, '/svc/Method', Cardinality.UNARY_UNARY,
                    DummyRequest, DummyReply, codec=ProtoCodec(),
                    status_details_codec=None,
                    dispatch=_DispatchServerEvents())
    stream.metadata = metadata
    return stream
github vmagamedov / grpclib / grpclib / server.py View on Github external
) -> None:
    try:
        headers_map = dict(headers)

        if headers_map[':method'] != 'POST':
            await _abort(_stream, 405)
            return

        content_type = headers_map.get('content-type')
        if content_type is None:
            await _abort(_stream, 415, Status.UNKNOWN,
                         'Missing content-type header')
            return

        base_content_type, _, sub_type = content_type.partition('+')
        sub_type = sub_type or ProtoCodec.__content_subtype__
        if (
            base_content_type != GRPC_CONTENT_TYPE
            or sub_type != codec.__content_subtype__
        ):
            await _abort(_stream, 415, Status.UNKNOWN,
                         'Unacceptable content-type header')
            return

        if headers_map.get('te') != 'trailers':
            await _abort(_stream, 400, Status.UNKNOWN,
                         'Required "te: trailers" header is missing')
            return

        method_name = headers_map[':path']
        method = mapping.get(method_name)
        if method is None:
github vmagamedov / grpclib / scripts / bench.py View on Github external
def grpc_encode(message, message_type, codec=ProtoCodec()):
    message_bin = codec.encode(message, message_type)
    header = struct.pack('?', False) + struct.pack('>I', len(message_bin))
    return header + message_bin
github vmagamedov / grpclib / grpclib / server.py View on Github external
``ProtoStatusDetailsCodec`` is used by default
        """
        if loop:
            warnings.warn("The loop argument is deprecated and scheduled "
                          "for removal in grpclib 0.4",
                          DeprecationWarning, stacklevel=2)

        mapping: Dict[str, 'const.Handler'] = {}
        for handler in handlers:
            mapping.update(handler.__mapping__())

        self._mapping = mapping
        self._loop = loop or asyncio.get_event_loop()

        if codec is None:
            codec = ProtoCodec()
            if status_details_codec is None and _googleapis_available():
                status_details_codec = ProtoStatusDetailsCodec()

        self._codec = codec
        self._status_details_codec = status_details_codec

        self._h2_config = h2.config.H2Configuration(
            client_side=False,
            header_encoding='ascii',
            validate_inbound_headers=False,
            validate_outbound_headers=False,
            normalize_inbound_headers=False,
            normalize_outbound_headers=False,
        )

        config = Configuration() if config is None else config