docs: refine gRPC guide section numbers and add CloseAndRecv & fileStore explanations

This commit is contained in:
2026-07-17 22:15:58 +09:00
parent d90553ecdf
commit 50f63633ea
23 changed files with 2964 additions and 130 deletions
+99
View File
@@ -0,0 +1,99 @@
package http3
import (
"context"
"crypto/tls"
"fmt"
"io"
"net"
"time"
"grpccanary/lib/grpc/http3/protoapi"
"github.com/quic-go/quic-go"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
func quicDialer(tlsConf *tls.Config) func(context.Context, string) (net.Conn, error) {
return func(ctx context.Context, addr string) (net.Conn, error) {
qconn, err := quic.DialAddr(ctx, addr, tlsConf, &quic.Config{
KeepAlivePeriod: 10 * time.Second,
})
if err != nil {
return nil, fmt.Errorf("quic dial failed: %w", err)
}
stream, err := qconn.OpenStreamSync(ctx)
if err != nil {
_ = qconn.CloseWithError(0, "failed to open stream")
return nil, fmt.Errorf("failed to open stream: %w", err)
}
return &quicNetConn{Stream: stream, conn: qconn}, nil
}
}
func ClientRun(addr string) error {
tlsConf := &tls.Config{
InsecureSkipVerify: true,
NextProtos: []string{"grpc-http3-canary"},
}
conn, err := grpc.NewClient(addr,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithContextDialer(quicDialer(tlsConf)),
)
if err != nil {
return fmt.Errorf("failed to create grpc client: %w", err)
}
defer conn.Close()
client := protoapi.NewHttp3ServiceClient(conn)
// Call 1: First Unary Ping
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
res1, err := client.Ping(ctx, &protoapi.PingRequest{Message: "First Message"})
if err != nil {
return fmt.Errorf("unary ping 1 failed: %w", err)
}
fmt.Printf("[HTTP3 Client] Received Ping 1 Response: Message='%s', Transport='%s'\n", res1.GetMessage(), res1.GetTransport())
// Call 2: Second Unary Ping (to verify stream multiplexing / reuse over same QUIC connection)
ctx2, cancel2 := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel2()
res2, err := client.Ping(ctx2, &protoapi.PingRequest{Message: "Second Message"})
if err != nil {
return fmt.Errorf("unary ping 2 failed: %w", err)
}
fmt.Printf("[HTTP3 Client] Received Ping 2 Response: Message='%s', Transport='%s'\n", res2.GetMessage(), res2.GetTransport())
// Call 3: Bidirectional Streaming Ping
streamCtx, streamCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer streamCancel()
stream, err := client.StreamPing(streamCtx)
if err != nil {
return fmt.Errorf("failed to open bi-directional stream: %w", err)
}
for i := 1; i <= 3; i++ {
msg := fmt.Sprintf("Stream Message %d", i)
err := stream.Send(&protoapi.PingRequest{Message: msg})
if err != nil {
return fmt.Errorf("failed to send stream message %d: %w", i, err)
}
res, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
return fmt.Errorf("failed to receive stream response %d: %w", i, err)
}
fmt.Printf("[HTTP3 Client] Received Stream Response %d: Message='%s', Transport='%s'\n", i, res.GetMessage(), res.GetTransport())
}
_ = stream.CloseSend()
return nil
}
+26
View File
@@ -0,0 +1,26 @@
package http3
import (
"testing"
"time"
)
func TestHttp3ServerClient(t *testing.T) {
// Start server on ephemeral port
lis, cleanup, err := ServerRun("127.0.0.1:0")
if err != nil {
t.Fatalf("failed to start server: %v", err)
}
defer cleanup()
addr := lis.Addr().String()
// Wait for server to be fully ready
time.Sleep(100 * time.Millisecond)
// Run client against the server
err = ClientRun(addr)
if err != nil {
t.Fatalf("client run failed: %v", err)
}
}
+17
View File
@@ -0,0 +1,17 @@
syntax = "proto3";
option go_package = "./protoapi/;protoapi";
service Http3Service {
rpc Ping (PingRequest) returns (PingResponse);
rpc StreamPing (stream PingRequest) returns (stream PingResponse);
}
message PingRequest {
string Message = 1;
}
message PingResponse {
string Message = 1;
string Transport = 2; // Should return "quic"
}
+186
View File
@@ -0,0 +1,186 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.11
// protoc v3.21.12
// source: protoapi.proto
package protoapi
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type PingRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Message string `protobuf:"bytes,1,opt,name=Message,proto3" json:"Message,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *PingRequest) Reset() {
*x = PingRequest{}
mi := &file_protoapi_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *PingRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*PingRequest) ProtoMessage() {}
func (x *PingRequest) ProtoReflect() protoreflect.Message {
mi := &file_protoapi_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use PingRequest.ProtoReflect.Descriptor instead.
func (*PingRequest) Descriptor() ([]byte, []int) {
return file_protoapi_proto_rawDescGZIP(), []int{0}
}
func (x *PingRequest) GetMessage() string {
if x != nil {
return x.Message
}
return ""
}
type PingResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
Message string `protobuf:"bytes,1,opt,name=Message,proto3" json:"Message,omitempty"`
Transport string `protobuf:"bytes,2,opt,name=Transport,proto3" json:"Transport,omitempty"` // Should return "quic"
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *PingResponse) Reset() {
*x = PingResponse{}
mi := &file_protoapi_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *PingResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*PingResponse) ProtoMessage() {}
func (x *PingResponse) ProtoReflect() protoreflect.Message {
mi := &file_protoapi_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use PingResponse.ProtoReflect.Descriptor instead.
func (*PingResponse) Descriptor() ([]byte, []int) {
return file_protoapi_proto_rawDescGZIP(), []int{1}
}
func (x *PingResponse) GetMessage() string {
if x != nil {
return x.Message
}
return ""
}
func (x *PingResponse) GetTransport() string {
if x != nil {
return x.Transport
}
return ""
}
var File_protoapi_proto protoreflect.FileDescriptor
const file_protoapi_proto_rawDesc = "" +
"\n" +
"\x0eprotoapi.proto\"'\n" +
"\vPingRequest\x12\x18\n" +
"\aMessage\x18\x01 \x01(\tR\aMessage\"F\n" +
"\fPingResponse\x12\x18\n" +
"\aMessage\x18\x01 \x01(\tR\aMessage\x12\x1c\n" +
"\tTransport\x18\x02 \x01(\tR\tTransport2b\n" +
"\fHttp3Service\x12#\n" +
"\x04Ping\x12\f.PingRequest\x1a\r.PingResponse\x12-\n" +
"\n" +
"StreamPing\x12\f.PingRequest\x1a\r.PingResponse(\x010\x01B\x16Z\x14./protoapi/;protoapib\x06proto3"
var (
file_protoapi_proto_rawDescOnce sync.Once
file_protoapi_proto_rawDescData []byte
)
func file_protoapi_proto_rawDescGZIP() []byte {
file_protoapi_proto_rawDescOnce.Do(func() {
file_protoapi_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_protoapi_proto_rawDesc), len(file_protoapi_proto_rawDesc)))
})
return file_protoapi_proto_rawDescData
}
var file_protoapi_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_protoapi_proto_goTypes = []any{
(*PingRequest)(nil), // 0: PingRequest
(*PingResponse)(nil), // 1: PingResponse
}
var file_protoapi_proto_depIdxs = []int32{
0, // 0: Http3Service.Ping:input_type -> PingRequest
0, // 1: Http3Service.StreamPing:input_type -> PingRequest
1, // 2: Http3Service.Ping:output_type -> PingResponse
1, // 3: Http3Service.StreamPing:output_type -> PingResponse
2, // [2:4] is the sub-list for method output_type
0, // [0:2] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_protoapi_proto_init() }
func file_protoapi_proto_init() {
if File_protoapi_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_protoapi_proto_rawDesc), len(file_protoapi_proto_rawDesc)),
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_protoapi_proto_goTypes,
DependencyIndexes: file_protoapi_proto_depIdxs,
MessageInfos: file_protoapi_proto_msgTypes,
}.Build()
File_protoapi_proto = out.File
file_protoapi_proto_goTypes = nil
file_protoapi_proto_depIdxs = nil
}
+154
View File
@@ -0,0 +1,154 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.6.2
// - protoc v3.21.12
// source: protoapi.proto
package protoapi
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.64.0 or later.
const _ = grpc.SupportPackageIsVersion9
const (
Http3Service_Ping_FullMethodName = "/Http3Service/Ping"
Http3Service_StreamPing_FullMethodName = "/Http3Service/StreamPing"
)
// Http3ServiceClient is the client API for Http3Service service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type Http3ServiceClient interface {
Ping(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (*PingResponse, error)
StreamPing(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[PingRequest, PingResponse], error)
}
type http3ServiceClient struct {
cc grpc.ClientConnInterface
}
func NewHttp3ServiceClient(cc grpc.ClientConnInterface) Http3ServiceClient {
return &http3ServiceClient{cc}
}
func (c *http3ServiceClient) Ping(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (*PingResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(PingResponse)
err := c.cc.Invoke(ctx, Http3Service_Ping_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *http3ServiceClient) StreamPing(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[PingRequest, PingResponse], error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
stream, err := c.cc.NewStream(ctx, &Http3Service_ServiceDesc.Streams[0], Http3Service_StreamPing_FullMethodName, cOpts...)
if err != nil {
return nil, err
}
x := &grpc.GenericClientStream[PingRequest, PingResponse]{ClientStream: stream}
return x, nil
}
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type Http3Service_StreamPingClient = grpc.BidiStreamingClient[PingRequest, PingResponse]
// Http3ServiceServer is the server API for Http3Service service.
// All implementations must embed UnimplementedHttp3ServiceServer
// for forward compatibility.
type Http3ServiceServer interface {
Ping(context.Context, *PingRequest) (*PingResponse, error)
StreamPing(grpc.BidiStreamingServer[PingRequest, PingResponse]) error
mustEmbedUnimplementedHttp3ServiceServer()
}
// UnimplementedHttp3ServiceServer must be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedHttp3ServiceServer struct{}
func (UnimplementedHttp3ServiceServer) Ping(context.Context, *PingRequest) (*PingResponse, error) {
return nil, status.Error(codes.Unimplemented, "method Ping not implemented")
}
func (UnimplementedHttp3ServiceServer) StreamPing(grpc.BidiStreamingServer[PingRequest, PingResponse]) error {
return status.Error(codes.Unimplemented, "method StreamPing not implemented")
}
func (UnimplementedHttp3ServiceServer) mustEmbedUnimplementedHttp3ServiceServer() {}
func (UnimplementedHttp3ServiceServer) testEmbeddedByValue() {}
// UnsafeHttp3ServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to Http3ServiceServer will
// result in compilation errors.
type UnsafeHttp3ServiceServer interface {
mustEmbedUnimplementedHttp3ServiceServer()
}
func RegisterHttp3ServiceServer(s grpc.ServiceRegistrar, srv Http3ServiceServer) {
// If the following call panics, it indicates UnimplementedHttp3ServiceServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
t.testEmbeddedByValue()
}
s.RegisterService(&Http3Service_ServiceDesc, srv)
}
func _Http3Service_Ping_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(PingRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(Http3ServiceServer).Ping(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Http3Service_Ping_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(Http3ServiceServer).Ping(ctx, req.(*PingRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Http3Service_StreamPing_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(Http3ServiceServer).StreamPing(&grpc.GenericServerStream[PingRequest, PingResponse]{ServerStream: stream})
}
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type Http3Service_StreamPingServer = grpc.BidiStreamingServer[PingRequest, PingResponse]
// Http3Service_ServiceDesc is the grpc.ServiceDesc for Http3Service service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var Http3Service_ServiceDesc = grpc.ServiceDesc{
ServiceName: "Http3Service",
HandlerType: (*Http3ServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Ping",
Handler: _Http3Service_Ping_Handler,
},
},
Streams: []grpc.StreamDesc{
{
StreamName: "StreamPing",
Handler: _Http3Service_StreamPing_Handler,
ServerStreams: true,
ClientStreams: true,
},
},
Metadata: "protoapi.proto",
}
+212
View File
@@ -0,0 +1,212 @@
package http3
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io"
"math/big"
"net"
"time"
"grpccanary/lib/grpc/http3/protoapi"
"github.com/quic-go/quic-go"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
// 1. self-signed certificate generation
func generateTLSConfig() (*tls.Config, error) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, err
}
template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
Organization: []string{"gRPC HTTP3 Canary"},
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(365 * 24 * time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
DNSNames: []string{"localhost"},
IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")},
}
certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
if err != nil {
return nil, err
}
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
privBytes, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
return nil, err
}
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privBytes})
tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
return nil, err
}
return &tls.Config{
Certificates: []tls.Certificate{tlsCert},
NextProtos: []string{"grpc-http3-canary"},
}, nil
}
// 2. net.Conn wrapper for quic.Stream
type quicNetConn struct {
*quic.Stream
conn *quic.Conn
}
func (c *quicNetConn) LocalAddr() net.Addr {
return c.conn.LocalAddr()
}
func (c *quicNetConn) RemoteAddr() net.Addr {
return c.conn.RemoteAddr()
}
// 3. net.Listener wrapper for quic.Listener using non-blocking channels
type quicListener struct {
lis *quic.Listener
connChan chan net.Conn
errChan chan error
ctx context.Context
cancel context.CancelFunc
}
func NewQuicListener(lis *quic.Listener) *quicListener {
ctx, cancel := context.WithCancel(context.Background())
ql := &quicListener{
lis: lis,
connChan: make(chan net.Conn, 100),
errChan: make(chan error, 10),
ctx: ctx,
cancel: cancel,
}
go ql.listenLoop()
return ql
}
func (ql *quicListener) listenLoop() {
for {
qconn, err := ql.lis.Accept(ql.ctx)
if err != nil {
select {
case ql.errChan <- err:
default:
}
return
}
go ql.acceptStreams(qconn)
}
}
func (ql *quicListener) acceptStreams(qconn *quic.Conn) {
for {
stream, err := qconn.AcceptStream(ql.ctx)
if err != nil {
// Stop checking this connection when it closes
return
}
ql.connChan <- &quicNetConn{Stream: stream, conn: qconn}
}
}
func (ql *quicListener) Accept() (net.Conn, error) {
select {
case conn := <-ql.connChan:
return conn, nil
case err := <-ql.errChan:
return nil, err
case <-ql.ctx.Done():
return nil, io.EOF
}
}
func (ql *quicListener) Close() error {
ql.cancel()
return ql.lis.Close()
}
func (ql *quicListener) Addr() net.Addr {
return ql.lis.Addr()
}
// 4. Http3Service Server Implementation
type Http3Server struct {
protoapi.UnimplementedHttp3ServiceServer
}
func (Http3Server) Ping(ctx context.Context, r *protoapi.PingRequest) (*protoapi.PingResponse, error) {
return &protoapi.PingResponse{
Message: "Pong: " + r.GetMessage(),
Transport: "quic",
}, nil
}
func (Http3Server) StreamPing(stream protoapi.Http3Service_StreamPingServer) error {
for {
req, err := stream.Recv()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
err = stream.Send(&protoapi.PingResponse{
Message: "Pong Stream: " + req.GetMessage(),
Transport: "quic",
})
if err != nil {
return err
}
}
}
func ServerRun(addr string) (*quic.Listener, func(), error) {
tlsConf, err := generateTLSConfig()
if err != nil {
return nil, nil, err
}
lis, err := quic.ListenAddr(addr, tlsConf, &quic.Config{
KeepAlivePeriod: 10 * time.Second,
})
if err != nil {
return nil, nil, err
}
qlis := NewQuicListener(lis)
server := grpc.NewServer()
protoapi.RegisterHttp3ServiceServer(server, Http3Server{})
reflection.Register(server)
go func() {
fmt.Printf("[HTTP3 Server] Serving gRPC on UDP/QUIC %s...\n", addr)
if err := server.Serve(qlis); err != nil {
fmt.Println("[HTTP3 Server] Server closed:", err)
}
}()
cleanup := func() {
server.GracefulStop()
qlis.Close()
}
return lis, cleanup, nil
}