├── example ├── buf.work.yaml ├── buf.gen.yaml ├── Makefile ├── proto │ ├── mattv1 │ │ └── matt.proto │ └── elizav1 │ │ └── eliza.proto ├── client.py └── gen │ ├── mattv1 │ ├── matt_connect.py │ └── matt_pb2.py │ └── elizav1 │ ├── eliza_connect.py │ └── eliza_pb2.py ├── requirements-dev.txt ├── .gitignore ├── src └── connect │ ├── __init__.py │ └── client.py ├── go.mod ├── README.md ├── go.sum ├── Makefile ├── pyproject.toml ├── cmd └── protoc-gen-connect-python │ └── main.go └── LICENSE /example/buf.work.yaml: -------------------------------------------------------------------------------- 1 | version: v1 2 | directories: 3 | - proto 4 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | -e .[http2] 2 | 3 | ruff 4 | build 5 | twine 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | .ruff_cache 3 | .envrc 4 | *.egg-info 5 | bin/ 6 | dist/ 7 | -------------------------------------------------------------------------------- /src/connect/__init__.py: -------------------------------------------------------------------------------- 1 | from .client import Client, Code, GzipCompressor # noqa: F401 2 | -------------------------------------------------------------------------------- /example/buf.gen.yaml: -------------------------------------------------------------------------------- 1 | version: v1 2 | plugins: 3 | - name: python 4 | out: gen 5 | - name: connect-python 6 | out: gen 7 | path: ../bin/protoc-gen-connect-python 8 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module go.withmatt.com/connect-python 2 | 3 | go 1.22 4 | 5 | require ( 6 | golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f 7 | google.golang.org/protobuf v1.33.0 8 | ) 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 🚧 Currently pending [an open RFC to be moved into the Connect RPC org](https://github.com/connectrpc/connectrpc.com/pull/71). Please show support. 🚧 2 | 3 | --- 4 | 5 | # connect-python 6 | 7 | Python client implementation for the [Connect](https://connect.build) RPC protocol. 8 | -------------------------------------------------------------------------------- /example/Makefile: -------------------------------------------------------------------------------- 1 | fmt: 2 | python -m ruff format *.py 3 | 4 | lint: 5 | python -m ruff check *.py 6 | 7 | protoc-gen-connect-python: 8 | $(MAKE) -C .. bin/protoc-gen-connect-python 9 | 10 | proto: protoc-gen-connect-python 11 | buf generate -v 12 | 13 | .PHONY: fmt lint proto protoc-gen-connect-python 14 | -------------------------------------------------------------------------------- /example/proto/mattv1/matt.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package matt.v1; 4 | 5 | import "elizav1/eliza.proto"; 6 | 7 | service MattService { 8 | rpc Hey(HeyRequest) returns (HeyResponse) {} 9 | rpc Say(connectrpc.eliza.v1.SayRequest) returns (connectrpc.eliza.v1.SayResponse) {} 10 | } 11 | 12 | service OtherService { 13 | 14 | } 15 | 16 | message HeyRequest {} 17 | 18 | message HeyResponse{} 19 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= 2 | golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f h1:99ci1mjWVBWwJiEKYY6jWa4d2nTQVIEhZIptnrVb1XY= 3 | golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f/go.mod h1:/lliqkxwWAhPjf5oSOIJup2XcqJaw8RGS6k3TGEc7GI= 4 | google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= 5 | google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= 6 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | PY = python -m 2 | 3 | plugin = protoc-gen-connect-python 4 | 5 | dev: 6 | $(PY) pip install -r requirements-dev.txt 7 | 8 | fmt: 9 | $(PY) ruff format src 10 | 11 | lint: 12 | $(PY) ruff check src 13 | 14 | clean: 15 | rm -f bin/protoc-gen-connect-python 16 | rm -rf dist 17 | 18 | upload: clean 19 | $(PY) build 20 | $(PY) twine upload --repository=connect-python dist/* 21 | 22 | 23 | bin/$(plugin): $(wildcard cmd/$(plugin)/*.go) pyproject.toml Makefile 24 | go build -o $@ \ 25 | -ldflags "-w -s" \ 26 | ./cmd/$(plugin) 27 | 28 | .PHONY: dev fmt lint upload clean 29 | -------------------------------------------------------------------------------- /example/client.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from pathlib import Path 3 | 4 | proto_folder = Path(".") / "gen" 5 | 6 | sys.path.append(str(proto_folder.absolute())) 7 | 8 | from elizav1 import eliza_connect, eliza_pb2 9 | from mattv1 import matt_connect, matt_pb2 10 | 11 | import connect 12 | 13 | eliza_client = eliza_connect.ElizaServiceClient( 14 | "https://demo.connectrpc.com", 15 | compressor=connect.GzipCompressor, 16 | json=True, 17 | ) 18 | print( 19 | eliza_client.say( 20 | eliza_pb2.SayRequest(sentence="hello"), 21 | headers={"foo": "bar", "user-agent": "hello"}, 22 | ) 23 | ) 24 | 25 | for resp in eliza_client.introduce(eliza_pb2.IntroduceRequest(name="Matt")): 26 | print(resp) 27 | 28 | matt_connect.MattServiceClient("") 29 | matt_connect.OtherServiceClient("") 30 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "connect-python" 3 | version = "0.1.0.dev2" 4 | authors = [{ email = "matt@ydekproductions.com" }] 5 | description = "Client implementation for the Connect RPC protocol" 6 | readme = "README.md" 7 | requires-python = ">=3.12" 8 | classifiers = [ 9 | "Programming Language :: Python :: 3", 10 | "License :: OSI Approved :: Apache Software License", 11 | "Operating System :: OS Independent", 12 | ] 13 | dependencies = [ 14 | "protobuf", 15 | "httpcore", 16 | ] 17 | 18 | [tool.hatch.build] 19 | include = [ 20 | "/src", 21 | ] 22 | 23 | [tool.hatch.build.targets.wheel] 24 | packages = ["src/connect"] 25 | 26 | [project.urls] 27 | "Homepage" = "https://github.com/mattrobenolt/connect-python" 28 | "Bug Tracker" = "https://github.com/mattrobenolt/connect-python/issues" 29 | 30 | [project.optional-dependencies] 31 | http2 = ["h2"] 32 | 33 | [build-system] 34 | requires = ["hatchling"] 35 | build-backend = "hatchling.build" 36 | -------------------------------------------------------------------------------- /example/gen/mattv1/matt_connect.py: -------------------------------------------------------------------------------- 1 | # Code generated by protoc-gen-connect-python 0.1.0.dev2, DO NOT EDIT. 2 | import connect 3 | 4 | from elizav1 import eliza_pb2 as elizav1_dot_eliza__pb2 5 | from mattv1 import matt_pb2 as mattv1_dot_matt__pb2 6 | 7 | MattServiceName = "matt.v1.MattService" 8 | OtherServiceName = "matt.v1.OtherService" 9 | 10 | 11 | class MattServiceClient: 12 | def __init__(self, base_url, *, pool=None, compressor=None, json=False, **opts): 13 | self._hey = connect.Client( 14 | pool=pool, 15 | url=f"{base_url}/{MattServiceName}/Hey", 16 | response_type=mattv1_dot_matt__pb2.HeyResponse, 17 | compressor=compressor, 18 | json=json, 19 | **opts 20 | ) 21 | self._say = connect.Client( 22 | pool=pool, 23 | url=f"{base_url}/{MattServiceName}/Say", 24 | response_type=elizav1_dot_eliza__pb2.SayResponse, 25 | compressor=compressor, 26 | json=json, 27 | **opts 28 | ) 29 | 30 | def hey(self, req, **opts): 31 | return self._hey.call_unary(req, **opts) 32 | 33 | def say(self, req, **opts): 34 | return self._say.call_unary(req, **opts) 35 | 36 | 37 | class OtherServiceClient: 38 | def __init__(self, base_url, *, pool=None, compressor=None, json=False, **opts): 39 | pass 40 | -------------------------------------------------------------------------------- /example/gen/elizav1/eliza_connect.py: -------------------------------------------------------------------------------- 1 | # Code generated by protoc-gen-connect-python 0.1.0.dev2, DO NOT EDIT. 2 | import connect 3 | 4 | from elizav1 import eliza_pb2 as elizav1_dot_eliza__pb2 5 | 6 | ElizaServiceName = "connectrpc.eliza.v1.ElizaService" 7 | 8 | 9 | class ElizaServiceClient: 10 | def __init__(self, base_url, *, pool=None, compressor=None, json=False, **opts): 11 | self._say = connect.Client( 12 | pool=pool, 13 | url=f"{base_url}/{ElizaServiceName}/Say", 14 | response_type=elizav1_dot_eliza__pb2.SayResponse, 15 | compressor=compressor, 16 | json=json, 17 | **opts 18 | ) 19 | self._converse = connect.Client( 20 | pool=pool, 21 | url=f"{base_url}/{ElizaServiceName}/Converse", 22 | response_type=elizav1_dot_eliza__pb2.ConverseResponse, 23 | compressor=compressor, 24 | json=json, 25 | **opts 26 | ) 27 | self._introduce = connect.Client( 28 | pool=pool, 29 | url=f"{base_url}/{ElizaServiceName}/Introduce", 30 | response_type=elizav1_dot_eliza__pb2.IntroduceResponse, 31 | compressor=compressor, 32 | json=json, 33 | **opts 34 | ) 35 | 36 | def say(self, req, **opts): 37 | return self._say.call_unary(req, **opts) 38 | 39 | def converse(self, req, **opts): 40 | return self._converse.call_bidi_stream(req, **opts) 41 | 42 | def introduce(self, req, **opts): 43 | return self._introduce.call_server_stream(req, **opts) 44 | -------------------------------------------------------------------------------- /example/gen/mattv1/matt_pb2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by the protocol buffer compiler. DO NOT EDIT! 3 | # source: mattv1/matt.proto 4 | # Protobuf Python Version: 5.26.1 5 | """Generated protocol buffer code.""" 6 | from google.protobuf import descriptor as _descriptor 7 | from google.protobuf import descriptor_pool as _descriptor_pool 8 | from google.protobuf import symbol_database as _symbol_database 9 | from google.protobuf.internal import builder as _builder 10 | # @@protoc_insertion_point(imports) 11 | 12 | _sym_db = _symbol_database.Default() 13 | 14 | 15 | from elizav1 import eliza_pb2 as elizav1_dot_eliza__pb2 16 | 17 | 18 | DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x11mattv1/matt.proto\x12\x07matt.v1\x1a\x13\x65lizav1/eliza.proto\"\x0c\n\nHeyRequest\"\r\n\x0bHeyResponse2\x8d\x01\n\x0bMattService\x12\x32\n\x03Hey\x12\x13.matt.v1.HeyRequest\x1a\x14.matt.v1.HeyResponse\"\x00\x12J\n\x03Say\x12\x1f.connectrpc.eliza.v1.SayRequest\x1a .connectrpc.eliza.v1.SayResponse\"\x00\x32\x0e\n\x0cOtherServiceb\x06proto3') 19 | 20 | _globals = globals() 21 | _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) 22 | _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'mattv1.matt_pb2', _globals) 23 | if not _descriptor._USE_C_DESCRIPTORS: 24 | DESCRIPTOR._loaded_options = None 25 | _globals['_HEYREQUEST']._serialized_start=51 26 | _globals['_HEYREQUEST']._serialized_end=63 27 | _globals['_HEYRESPONSE']._serialized_start=65 28 | _globals['_HEYRESPONSE']._serialized_end=78 29 | _globals['_MATTSERVICE']._serialized_start=81 30 | _globals['_MATTSERVICE']._serialized_end=222 31 | _globals['_OTHERSERVICE']._serialized_start=224 32 | _globals['_OTHERSERVICE']._serialized_end=238 33 | # @@protoc_insertion_point(module_scope) 34 | -------------------------------------------------------------------------------- /example/gen/elizav1/eliza_pb2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by the protocol buffer compiler. DO NOT EDIT! 3 | # source: elizav1/eliza.proto 4 | # Protobuf Python Version: 5.26.1 5 | """Generated protocol buffer code.""" 6 | from google.protobuf import descriptor as _descriptor 7 | from google.protobuf import descriptor_pool as _descriptor_pool 8 | from google.protobuf import symbol_database as _symbol_database 9 | from google.protobuf.internal import builder as _builder 10 | # @@protoc_insertion_point(imports) 11 | 12 | _sym_db = _symbol_database.Default() 13 | 14 | 15 | 16 | 17 | DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x13\x65lizav1/eliza.proto\x12\x13\x63onnectrpc.eliza.v1\"(\n\nSayRequest\x12\x1a\n\x08sentence\x18\x01 \x01(\tR\x08sentence\")\n\x0bSayResponse\x12\x1a\n\x08sentence\x18\x01 \x01(\tR\x08sentence\"-\n\x0f\x43onverseRequest\x12\x1a\n\x08sentence\x18\x01 \x01(\tR\x08sentence\".\n\x10\x43onverseResponse\x12\x1a\n\x08sentence\x18\x01 \x01(\tR\x08sentence\"&\n\x10IntroduceRequest\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\"/\n\x11IntroduceResponse\x12\x1a\n\x08sentence\x18\x01 \x01(\tR\x08sentence2\x99\x02\n\x0c\x45lizaService\x12J\n\x03Say\x12\x1f.connectrpc.eliza.v1.SayRequest\x1a .connectrpc.eliza.v1.SayResponse\"\x00\x12]\n\x08\x43onverse\x12$.connectrpc.eliza.v1.ConverseRequest\x1a%.connectrpc.eliza.v1.ConverseResponse\"\x00(\x01\x30\x01\x12^\n\tIntroduce\x12%.connectrpc.eliza.v1.IntroduceRequest\x1a&.connectrpc.eliza.v1.IntroduceResponse\"\x00\x30\x01\x62\x06proto3') 18 | 19 | _globals = globals() 20 | _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) 21 | _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'elizav1.eliza_pb2', _globals) 22 | if not _descriptor._USE_C_DESCRIPTORS: 23 | DESCRIPTOR._loaded_options = None 24 | _globals['_SAYREQUEST']._serialized_start=44 25 | _globals['_SAYREQUEST']._serialized_end=84 26 | _globals['_SAYRESPONSE']._serialized_start=86 27 | _globals['_SAYRESPONSE']._serialized_end=127 28 | _globals['_CONVERSEREQUEST']._serialized_start=129 29 | _globals['_CONVERSEREQUEST']._serialized_end=174 30 | _globals['_CONVERSERESPONSE']._serialized_start=176 31 | _globals['_CONVERSERESPONSE']._serialized_end=222 32 | _globals['_INTRODUCEREQUEST']._serialized_start=224 33 | _globals['_INTRODUCEREQUEST']._serialized_end=262 34 | _globals['_INTRODUCERESPONSE']._serialized_start=264 35 | _globals['_INTRODUCERESPONSE']._serialized_end=311 36 | _globals['_ELIZASERVICE']._serialized_start=314 37 | _globals['_ELIZASERVICE']._serialized_end=595 38 | # @@protoc_insertion_point(module_scope) 39 | -------------------------------------------------------------------------------- /example/proto/elizav1/eliza.proto: -------------------------------------------------------------------------------- 1 | // Copyright 2022 Buf Technologies, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | syntax = "proto3"; 16 | 17 | package connectrpc.eliza.v1; 18 | 19 | // ElizaService provides a way to talk to the ELIZA, which is a port of 20 | // the DOCTOR script for Joseph Weizenbaum's original ELIZA program. 21 | // Created in the mid-1960s at the MIT Artificial Intelligence Laboratory, 22 | // ELIZA demonstrates the superficiality of human-computer communication. 23 | // DOCTOR simulates a psychotherapist, and is commonly found as an Easter 24 | // egg in emacs distributions. 25 | service ElizaService { 26 | // Say is a unary request demo. This method should allow for a one sentence 27 | // response given a one sentence request. 28 | rpc Say(SayRequest) returns (SayResponse) {} 29 | // Converse is a bi-directional streaming request demo. This method should allow for 30 | // many requests and many responses. 31 | rpc Converse(stream ConverseRequest) returns (stream ConverseResponse) {} 32 | // Introduce is a server-streaming request demo. This method allows for a single request that will return a series 33 | // of responses 34 | rpc Introduce(IntroduceRequest) returns (stream IntroduceResponse) {} 35 | } 36 | 37 | // SayRequest describes the sentence said to the ELIZA program. 38 | message SayRequest { 39 | string sentence = 1; 40 | } 41 | 42 | // SayResponse describes the sentence responded by the ELIZA program. 43 | message SayResponse { 44 | string sentence = 1; 45 | } 46 | 47 | // ConverseRequest describes the sentence said to the ELIZA program. 48 | message ConverseRequest { 49 | string sentence = 1; 50 | } 51 | 52 | // ConverseResponse describes the sentence responded by the ELIZA program. 53 | message ConverseResponse { 54 | string sentence = 1; 55 | } 56 | 57 | // IntroduceRequest describes a request for details from the ELIZA program. 58 | message IntroduceRequest { 59 | string name = 1; 60 | } 61 | 62 | // IntroduceResponse describes the sentence responded by the ELIZA program. 63 | message IntroduceResponse { 64 | string sentence = 1; 65 | } 66 | -------------------------------------------------------------------------------- /src/connect/client.py: -------------------------------------------------------------------------------- 1 | import gzip 2 | import json 3 | import struct 4 | from enum import Flag, IntEnum 5 | 6 | from google.protobuf import json_format 7 | 8 | 9 | class EnvelopeFlags(Flag): 10 | compressed = 0b00000001 11 | end_stream = 0b00000010 12 | 13 | 14 | class Code(IntEnum): 15 | canceled = 408 16 | unknown = 500 17 | invalid_argument = 400 18 | deadline_exceeded = 408 19 | not_found = 404 20 | already_exists = 409 21 | permission_denied = 403 22 | resource_exhausted = 429 23 | failed_precondition = 412 24 | aborted = 409 25 | out_of_range = 400 26 | unimplemented = 404 27 | internal = 500 28 | unavailable = 503 29 | data_loss = 500 30 | unauthenticated = 401 31 | 32 | 33 | class Error(Exception): 34 | def __init__(self, code, message): 35 | self.code = code 36 | self.message = message 37 | 38 | 39 | envelope_header_length = 5 40 | envelope_header_pack = ">BI" 41 | 42 | _default_connection_pool = None 43 | 44 | 45 | def default_connection_pool(): 46 | global _default_connection_pool 47 | if _default_connection_pool is None: 48 | import httpcore 49 | 50 | try: 51 | import h2 # noqa: F401 52 | 53 | http2 = True 54 | del h2 55 | except ModuleNotFoundError: 56 | http2 = False 57 | _default_connection_pool = httpcore.ConnectionPool(http2=http2) 58 | 59 | return _default_connection_pool 60 | 61 | 62 | def encode_envelope(*, flags: EnvelopeFlags, data): 63 | return encode_envelope_header(flags=flags.value, data=data) + data 64 | 65 | 66 | def encode_envelope_header(*, flags, data): 67 | return struct.pack(envelope_header_pack, flags, len(data)) 68 | 69 | 70 | def decode_envelope_header(header): 71 | flags, data_len = struct.unpack(envelope_header_pack, header) 72 | return EnvelopeFlags(flags), data_len 73 | 74 | 75 | def error_for_response(http_resp): 76 | try: 77 | error = json.loads(http_resp.content) 78 | except (json.decoder.JSONDecodeError, KeyError): 79 | return Error(Code(http_resp.status), http_resp.reason) 80 | else: 81 | return make_error(error) 82 | 83 | 84 | def make_error(error): 85 | try: 86 | code = Code[error["code"]] 87 | except KeyError: 88 | code = Code.unknown 89 | return Error(code, error.get("message", "")) 90 | 91 | 92 | class GzipCompressor: 93 | name = "gzip" 94 | decompress = gzip.decompress 95 | compress = gzip.compress 96 | 97 | 98 | class JSONCodec: 99 | content_type = "json" 100 | 101 | @staticmethod 102 | def encode(msg): 103 | return json_format.MessageToJson(msg).encode("utf8") 104 | 105 | @staticmethod 106 | def decode(data, *, msg_type): 107 | msg = msg_type() 108 | json_format.Parse(data.decode("utf8"), msg) 109 | return msg 110 | 111 | 112 | class ProtobufCodec: 113 | content_type = "proto" 114 | 115 | @staticmethod 116 | def encode(msg): 117 | return msg.SerializeToString() 118 | 119 | @staticmethod 120 | def decode(data, *, msg_type): 121 | msg = msg_type() 122 | msg.ParseFromString(data) 123 | return msg 124 | 125 | 126 | class Client: 127 | def __init__( 128 | self, *, pool, url, response_type, compressor=None, json=False, headers=None 129 | ): 130 | if pool is None: 131 | pool = default_connection_pool() 132 | 133 | if headers is None: 134 | headers = {} 135 | 136 | self.pool = pool 137 | self.url = url 138 | self._codec = JSONCodec if json else ProtobufCodec 139 | self._response_type = response_type 140 | self._compressor = compressor 141 | self._headers = {"user-agent": "connect-python"} | headers 142 | 143 | def call_unary(self, req, **opts): 144 | data = self._codec.encode(req) 145 | 146 | if self._compressor is not None: 147 | data = self._compressor.compress(data) 148 | 149 | http_resp = self.pool.request( 150 | "POST", 151 | self.url, 152 | content=data, 153 | headers=self._headers 154 | | opts.get("headers", {}) 155 | | { 156 | "connect-protocol-version": "1", 157 | "content-encoding": "identity" 158 | if self._compressor is None 159 | else self._compressor.name, 160 | "content-type": f"application/{self._codec.content_type}", 161 | }, 162 | ) 163 | 164 | if http_resp.status != 200: 165 | raise error_for_response(http_resp) 166 | 167 | return self._codec.decode( 168 | http_resp.content, 169 | msg_type=self._response_type, 170 | ) 171 | 172 | def call_server_stream(self, req, **opts): 173 | data = self._codec.encode(req) 174 | flags = EnvelopeFlags(0) 175 | 176 | if self._compressor is not None: 177 | data = self._compressor.compress(data) 178 | flags |= EnvelopeFlags.compressed 179 | 180 | with self.pool.stream( 181 | "POST", 182 | self.url, 183 | content=encode_envelope( 184 | flags=flags, 185 | data=data, 186 | ), 187 | headers=self._headers 188 | | opts.get("headers", {}) 189 | | { 190 | "connect-protocol-version": "1", 191 | "connect-content-encoding": "identity" 192 | if self._compressor is None 193 | else self._compressor.name, 194 | "content-type": f"application/connect+{self._codec.content_type}", 195 | }, 196 | ) as http_resp: 197 | if http_resp.status != 200: 198 | raise error_for_response(http_resp) 199 | 200 | buffer = b"" 201 | end_stream = False 202 | needs_header = True 203 | flags, data_len = 0, 0 204 | 205 | for chunk in http_resp.iter_stream(): 206 | buffer += chunk 207 | 208 | if needs_header: 209 | header = buffer[:envelope_header_length] 210 | buffer = buffer[envelope_header_length:] 211 | flags, data_len = decode_envelope_header(header) 212 | needs_header = False 213 | end_stream = EnvelopeFlags.end_stream in flags 214 | 215 | if len(buffer) >= data_len: 216 | buffer = buffer[:data_len] 217 | 218 | if end_stream: 219 | data = json.loads(buffer) 220 | if "error" in data: 221 | raise make_error(data["error"]) 222 | 223 | # TODO: Figure out what else might be possible 224 | return 225 | 226 | # TODO: handle server message compression 227 | # if EnvelopeFlags.compression in flags: 228 | # TODO: should the client potentially use a different codec 229 | # based on response header? Or can we assume they're always 230 | # the same and an error otherwise. 231 | yield self._codec.decode(buffer, msg_type=self._response_type) 232 | 233 | buffer = buffer[data_len:] 234 | needs_header = True 235 | 236 | def call_client_stream(self, req, **opts): 237 | raise NotImplementedError("client stream not supported") 238 | 239 | def call_bidi_stream(self, req, **opts): 240 | raise NotImplementedError("bidi stream not supported") 241 | -------------------------------------------------------------------------------- /cmd/protoc-gen-connect-python/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "os" 7 | "path/filepath" 8 | "regexp" 9 | "sort" 10 | "strings" 11 | 12 | log "golang.org/x/exp/slog" 13 | "google.golang.org/protobuf/proto" 14 | descriptor "google.golang.org/protobuf/types/descriptorpb" 15 | "google.golang.org/protobuf/types/pluginpb" 16 | ) 17 | 18 | const pluginVersion = "0.1.0.dev2" 19 | 20 | func init() { 21 | ll := log.New(log.NewTextHandler(os.Stderr, &log.HandlerOptions{ 22 | Level: log.LevelDebug, 23 | ReplaceAttr: func(groups []string, a log.Attr) log.Attr { 24 | if a.Key == log.TimeKey && len(groups) == 0 { 25 | return log.Attr{} 26 | } 27 | return a 28 | }, 29 | })) 30 | log.SetDefault(ll.With(log.Int("pid", os.Getpid()))) 31 | } 32 | 33 | func main() { 34 | if len(os.Args) == 2 && os.Args[1] == "--version" { 35 | fmt.Fprintln(os.Stdout, pluginVersion) 36 | os.Exit(0) 37 | } 38 | 39 | f := func(plugin *Plugin) error { 40 | for _, f := range plugin.filesToGenerate { 41 | generate(plugin, f) 42 | } 43 | return nil 44 | } 45 | if err := run(f); err != nil { 46 | fmt.Fprintf(os.Stderr, "%s: %v\n", filepath.Base(os.Args[0]), err) 47 | os.Exit(1) 48 | } 49 | } 50 | 51 | func run(f func(*Plugin) error) error { 52 | in, err := io.ReadAll(os.Stdin) 53 | if err != nil { 54 | return err 55 | } 56 | req := &pluginpb.CodeGeneratorRequest{} 57 | if err := proto.Unmarshal(in, req); err != nil { 58 | return err 59 | } 60 | gen, err := newPlugin(req) 61 | if err != nil { 62 | return err 63 | } 64 | if err := f(gen); err != nil { 65 | gen.Error(err) 66 | } 67 | resp := gen.Response() 68 | out, err := proto.Marshal(resp) 69 | if err != nil { 70 | return err 71 | } 72 | _, err = os.Stdout.Write(out) 73 | return err 74 | } 75 | 76 | func newPlugin(req *pluginpb.CodeGeneratorRequest) (*Plugin, error) { 77 | gen := &Plugin{ 78 | request: req, 79 | filesByPackage: make(map[string]*descriptor.FileDescriptorProto), 80 | filesByPath: make(map[string]*descriptor.FileDescriptorProto), 81 | messagesByType: make(map[string]*descriptor.DescriptorProto), 82 | } 83 | 84 | for _, f := range gen.request.ProtoFile { 85 | name := f.GetName() 86 | pkg := f.GetPackage() 87 | log.Debug("ProtoFile", 88 | log.String("name", name), 89 | log.String("pkg", pkg), 90 | ) 91 | if _, ok := gen.filesByPackage[pkg]; ok { 92 | return nil, fmt.Errorf("duplicate package: %q", name) 93 | } 94 | gen.filesByPackage[pkg] = f 95 | if _, ok := gen.filesByPath[name]; ok { 96 | return nil, fmt.Errorf("duplicate file name: %q", name) 97 | } 98 | gen.filesByPath[name] = f 99 | for _, msg := range f.GetMessageType() { 100 | msgKey := f.GetPackage() + "." + msg.GetName() 101 | if _, ok := gen.messagesByType[msgKey]; ok { 102 | return nil, fmt.Errorf("duplicate message: %q", msgKey) 103 | } 104 | gen.messagesByType[msgKey] = msg 105 | log.Debug("MessageType", 106 | log.String("name", msgKey), 107 | ) 108 | } 109 | gen.files = append(gen.files, f) 110 | } 111 | 112 | for _, name := range req.FileToGenerate { 113 | if f, ok := gen.filesByPath[name]; ok { 114 | log.Debug("FileToGenerate", 115 | log.String("name", name), 116 | log.Any("deps", f.Dependency), 117 | log.Int("services", len(f.Service)), 118 | ) 119 | if len(f.Service) > 0 { 120 | gen.filesToGenerate = append(gen.filesToGenerate, f) 121 | } 122 | } else { 123 | return nil, fmt.Errorf("missing file: %q", name) 124 | } 125 | } 126 | 127 | return gen, nil 128 | } 129 | 130 | type Plugin struct { 131 | request *pluginpb.CodeGeneratorRequest 132 | 133 | files []*descriptor.FileDescriptorProto 134 | filesByPackage map[string]*descriptor.FileDescriptorProto 135 | filesByPath map[string]*descriptor.FileDescriptorProto 136 | messagesByType map[string]*descriptor.DescriptorProto 137 | filesToGenerate []*descriptor.FileDescriptorProto 138 | 139 | generatedFiles []*pluginpb.CodeGeneratorResponse_File 140 | 141 | err error 142 | } 143 | 144 | func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse { 145 | resp := &pluginpb.CodeGeneratorResponse{} 146 | if gen.err != nil { 147 | resp.Error = Ptr(gen.err.Error()) 148 | return resp 149 | } 150 | resp.File = gen.generatedFiles 151 | return resp 152 | } 153 | 154 | func (gen *Plugin) Error(err error) { 155 | if gen.err == nil { 156 | gen.err = err 157 | } 158 | } 159 | 160 | func Ptr[T any](v T) *T { 161 | return &v 162 | } 163 | 164 | func print(buf *strings.Builder, tpl string, args ...interface{}) { 165 | buf.WriteString(fmt.Sprintf(tpl, args...)) 166 | buf.WriteByte('\n') 167 | } 168 | 169 | func getPackage(path string) string { 170 | return strings.ReplaceAll(filepath.Dir(path), "/", ".") 171 | } 172 | 173 | func getModule(path string) string { 174 | path = filepath.Base(path) 175 | ext := filepath.Ext(path) 176 | return strings.TrimSuffix(path, ext) 177 | } 178 | 179 | func getProtoModule(path string) string { 180 | return getModule(path) + "_pb2" 181 | } 182 | 183 | func getConnectModule(path string) string { 184 | return getModule(path) + "_connect" 185 | } 186 | 187 | func getProtoModuleAlias(path string) string { 188 | path = getPackage(path) + "." + getProtoModule(path) 189 | path = strings.ReplaceAll(path, "_", "__") 190 | path = strings.ReplaceAll(path, ".", "_dot_") 191 | return path 192 | } 193 | 194 | func getServiceName(svc *descriptor.ServiceDescriptorProto) string { 195 | return svc.GetName() + "Name" 196 | } 197 | 198 | func getServiceClient(svc *descriptor.ServiceDescriptorProto) string { 199 | return svc.GetName() + "Client" 200 | } 201 | 202 | func getServiceBasePath(file *descriptor.FileDescriptorProto, svc *descriptor.ServiceDescriptorProto) string { 203 | return file.GetPackage() + "." + svc.GetName() 204 | } 205 | 206 | func getMethodProperty(m *descriptor.MethodDescriptorProto) string { 207 | return "_" + toSnakeCase(m.GetName()) 208 | } 209 | 210 | func getMethodType(m *descriptor.MethodDescriptorProto) string { 211 | switch { 212 | case m.GetClientStreaming() && m.GetServerStreaming(): 213 | return "bidi_stream" 214 | case m.GetClientStreaming(): 215 | return "client_stream" 216 | case m.GetServerStreaming(): 217 | return "server_stream" 218 | default: 219 | return "unary" 220 | } 221 | } 222 | 223 | func splitPackageType(path string) (string, string) { 224 | lastDot := strings.LastIndexByte(path, '.') 225 | return path[:lastDot], path[lastDot+1:] 226 | } 227 | 228 | func resolveMessageFromMethod(gen *Plugin, m *descriptor.MethodDescriptorProto) (string, string) { 229 | fullyQualifiedName := m.GetOutputType()[1:] // strip prefixed "." 230 | pkgName, msgName := splitPackageType(fullyQualifiedName) 231 | filename := gen.filesByPackage[pkgName].GetName() 232 | return filename, msgName 233 | } 234 | 235 | func getResponseType(gen *Plugin, m *descriptor.MethodDescriptorProto) string { 236 | filename, msgName := resolveMessageFromMethod(gen, m) 237 | 238 | log.Debug("ResponseType", 239 | log.String("msg", msgName), 240 | log.String("import", filename), 241 | log.String("alias", getProtoModuleAlias(filename)), 242 | ) 243 | return getProtoModuleAlias(filename) + "." + msgName 244 | } 245 | 246 | var ( 247 | matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)") 248 | matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])") 249 | ) 250 | 251 | func toSnakeCase(str string) string { 252 | snake := matchFirstCap.ReplaceAllString(str, "${1}_${2}") 253 | snake = matchAllCap.ReplaceAllString(snake, "${1}_${2}") 254 | return strings.ToLower(snake) 255 | } 256 | 257 | func generate(gen *Plugin, file *descriptor.FileDescriptorProto) { 258 | filename := file.GetName() 259 | 260 | dir := filepath.Dir(filename) 261 | pkgName := getPackage(filename) 262 | modName := getModule(filename) 263 | 264 | log.Debug("Generate", 265 | log.String("name", filename), 266 | log.String("pkg", pkgName), 267 | log.String("mod", modName), 268 | ) 269 | 270 | b := new(strings.Builder) 271 | 272 | depsUniq := make(map[string]struct{}) 273 | for _, svc := range file.Service { 274 | for _, method := range svc.Method { 275 | filename, _ := resolveMessageFromMethod(gen, method) 276 | depsUniq[filename] = struct{}{} 277 | } 278 | } 279 | deps := make([]string, 0, len(depsUniq)) 280 | for dep := range depsUniq { 281 | deps = append(deps, dep) 282 | } 283 | sort.Strings(deps) 284 | 285 | print(b, "# Code generated by protoc-gen-connect-python %s, DO NOT EDIT.", pluginVersion) 286 | 287 | print(b, "import connect") 288 | if len(deps) > 0 { 289 | print(b, "") 290 | for _, dep := range deps { 291 | print(b, "from %s import %s as %s", getPackage(dep), getProtoModule(dep), getProtoModuleAlias(dep)) 292 | } 293 | } 294 | print(b, "") 295 | 296 | for _, svc := range file.Service { 297 | print(b, `%s = "%s"`, getServiceName(svc), getServiceBasePath(file, svc)) 298 | } 299 | 300 | for _, svc := range file.Service { 301 | print(b, "") 302 | print(b, "") 303 | print(b, `class %s:`, getServiceClient(svc)) 304 | print(b, " def __init__(self, base_url, *, pool=None, compressor=None, json=False, **opts):") 305 | if len(svc.Method) == 0 { 306 | print(b, " pass") 307 | continue 308 | } 309 | for _, method := range svc.Method { 310 | print(b, " self.%s = connect.Client(", getMethodProperty(method)) 311 | print(b, " pool=pool,") 312 | print(b, ` url=f"{base_url}/{%s}/%s",`, getServiceName(svc), method.GetName()) 313 | print(b, ` response_type=%s,`, getResponseType(gen, method)) 314 | print(b, ` compressor=compressor,`) 315 | print(b, ` json=json,`) 316 | print(b, ` **opts`) 317 | print(b, " )") 318 | } 319 | for _, method := range svc.Method { 320 | print(b, "") 321 | print(b, " def %s(self, req, **opts):", toSnakeCase(method.GetName())) 322 | print(b, " return self.%s.call_%s(req, **opts)", getMethodProperty(method), getMethodType(method)) 323 | } 324 | 325 | } 326 | 327 | gen.generatedFiles = append(gen.generatedFiles, &pluginpb.CodeGeneratorResponse_File{ 328 | Name: Ptr(filepath.Join(dir, getConnectModule(filename)+".py")), 329 | Content: Ptr(b.String()), 330 | }) 331 | } 332 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2021-2024 The Connect Authors 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------