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
}
+210
View File
@@ -0,0 +1,210 @@
package modular
import (
"context"
"fmt"
"io"
"math/rand"
"time"
"grpccanary/lib/grpc/modular/protoapi"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
func AskingDateTime(ctx context.Context, m protoapi.CoreServiceClient) (*protoapi.DateTime, error) {
request := &protoapi.RequestDateTime{
Value: "Please send me the date and time",
}
return m.GetDate(ctx, request)
}
func AskPass(ctx context.Context, m protoapi.CoreServiceClient, seed int64, length int64) (*protoapi.RandomPass, error) {
request := &protoapi.RequestPass{
Seed: seed,
Length: length,
}
return m.GetRandomPass(ctx, request)
}
func AskUpdateSensingData(ctx context.Context, m protoapi.CoreServiceClient, deviceId string, temp float64, humid float64) (*protoapi.SensingResponse, error) {
request := &protoapi.SensingData{
DeviceId: deviceId,
Temperature: temp,
Humidity: humid,
}
return m.UpdateSensingData(ctx, request)
}
func AskUploadFile(ctx context.Context, m protoapi.FileTransferServiceClient, fileName string, fileData []byte) (*protoapi.UploadStatus, error) {
stream, err := m.UploadFile(ctx)
if err != nil {
return nil, err
}
chunkSize := 1024
totalBytes := len(fileData)
for i := 0; i < totalBytes; i += chunkSize {
end := i + chunkSize
if end > totalBytes {
end = totalBytes
}
err := stream.Send(&protoapi.FileChunk{
FileName: fileName,
Content: fileData[i:end],
})
if err != nil {
return nil, err
}
}
return stream.CloseAndRecv()
}
func AskListFiles(ctx context.Context, m protoapi.FileTransferServiceClient) (*protoapi.FileList, error) {
return m.ListFiles(ctx, &protoapi.EmptyRequest{})
}
func AskDownloadFile(ctx context.Context, m protoapi.FileTransferServiceClient, fileName string) ([]byte, error) {
stream, err := m.DownloadFile(ctx, &protoapi.DownloadRequest{FileName: fileName})
if err != nil {
return nil, err
}
var buffer []byte
for {
chunk, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
buffer = append(buffer, chunk.GetContent()...)
}
return buffer, nil
}
func AskSubscribeAlerts(ctx context.Context, m protoapi.AlertServiceClient, clientId string, topic string) {
stream, err := m.SubscribeAlerts(ctx, &protoapi.AlertSubscription{
ClientId: clientId,
Topic: topic,
})
if err != nil {
fmt.Println("[Modular Client] Failed to subscribe alerts:", err)
return
}
for {
alert, err := stream.Recv()
if err == io.EOF {
fmt.Println("[Modular Client] Alert subscription stream closed by server.")
break
}
if err != nil {
break
}
fmt.Printf("\n🔔 [Modular ALERT RECEIVED] ID: %s | Device: %s | Msg: %s | Time: %s\n\n",
alert.GetAlertId(), alert.GetDeviceId(), alert.GetMessage(),
time.Unix(alert.GetTimestamp(), 0).Format("15:04:05"))
}
}
func ClientRun(addr string) {
conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
fmt.Println("[Modular Client] NewClient error:", err)
return
}
defer conn.Close()
coreClient := protoapi.NewCoreServiceClient(conn)
fileClient := protoapi.NewFileTransferServiceClient(conn)
alertClient := protoapi.NewAlertServiceClient(conn)
// Background Subscription
alertCtx, alertCancel := context.WithCancel(context.Background())
defer alertCancel()
go AskSubscribeAlerts(alertCtx, alertClient, "modular-client-01", "temperature_warnings")
time.Sleep(50 * time.Millisecond)
r, err := AskingDateTime(context.Background(), coreClient)
if err != nil {
fmt.Println("[Modular Client] GetDate error:", err)
return
}
fmt.Println("[Modular Client] Server Date and Time:", r.Value)
length := int64(rand.Intn(20))
p, err := AskPass(context.Background(), coreClient, 100, length+1)
if err != nil {
fmt.Println("[Modular Client] GetRandomPass error:", err)
return
}
fmt.Println("[Modular Client] Random Password:", p.Password)
res, err := AskUpdateSensingData(context.Background(), coreClient, "modular-sensor-01", 24.5, 52.3)
if err != nil {
fmt.Println("[Modular Client] UpdateSensingData error:", err)
return
}
fmt.Println("[Modular Client] Sensing Update Success:", res.Success)
// File Upload
dummyData := make([]byte, 10240)
for i := range dummyData {
dummyData[i] = byte(rand.Intn(256))
}
fmt.Println("[Modular Client] Uploading dummy file...")
status, err := AskUploadFile(context.Background(), fileClient, "firmware_modular.bin", dummyData)
if err != nil {
fmt.Println("[Modular Client] File upload failed:", err)
return
}
fmt.Println("[Modular Client] Upload Success:", status.Success)
// File List
list, err := AskListFiles(context.Background(), fileClient)
if err != nil {
fmt.Println("[Modular Client] ListFiles failed:", err)
return
}
for i, f := range list.GetFiles() {
fmt.Printf("[Modular Client] File [%d]: %s, size: %d\n", i+1, f.GetFileName(), f.GetFileSize())
}
// File Download & Verification
downloadedData, err := AskDownloadFile(context.Background(), fileClient, "firmware_modular.bin")
if err != nil {
fmt.Println("[Modular Client] Download failed:", err)
return
}
fmt.Printf("[Modular Client] Downloaded %d bytes.\n", len(downloadedData))
isMatch := true
if len(dummyData) != len(downloadedData) {
isMatch = false
} else {
for i := range dummyData {
if dummyData[i] != downloadedData[i] {
isMatch = false
break
}
}
}
fmt.Printf("[Modular Client] Data Integrity Checked: %t\n", isMatch)
// Trigger alert
fmt.Println("[Modular Client] Triggering abnormal high-temperature...")
_, err = AskUpdateSensingData(context.Background(), coreClient, "modular-sensor-01", 45.8, 60.1)
if err != nil {
fmt.Println("[Modular Client] UpdateSensingData (abnormal) error:", err)
return
}
time.Sleep(100 * time.Millisecond)
}
+26
View File
@@ -0,0 +1,26 @@
package modular
import (
"net"
"testing"
"time"
)
func TestModularServerClient(t *testing.T) {
// Find an ephemeral port
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to listen: %v", err)
}
addr := lis.Addr().String()
lis.Close()
// Start server in background
go ServerRun(addr)
// Wait for server to start
time.Sleep(100 * time.Millisecond)
// Run client against the server
ClientRun(addr)
}
+21
View File
@@ -0,0 +1,21 @@
syntax = "proto3";
option go_package = "./protoapi/;protoapi";
import "common.proto";
service AlertService {
rpc SubscribeAlerts (AlertSubscription) returns (stream AlertMessage);
}
message AlertSubscription {
string ClientId = 1;
string Topic = 2;
}
message AlertMessage {
string AlertId = 1;
string DeviceId = 2;
string Message = 3;
int64 Timestamp = 4;
}
+22
View File
@@ -0,0 +1,22 @@
syntax = "proto3";
option go_package = "./protoapi/;protoapi";
message DateTime {
string Value = 1;
}
message RequestDateTime {
string Value = 2;
}
message RequestPass {
int64 Seed = 1;
int64 Length = 8;
}
message RandomPass {
string Password = 1;
}
message EmptyRequest {}
+22
View File
@@ -0,0 +1,22 @@
syntax = "proto3";
option go_package = "./protoapi/;protoapi";
import "common.proto";
service CoreService {
rpc GetDate (RequestDateTime) returns (DateTime);
rpc UpdateSensingData (SensingData) returns (SensingResponse);
rpc GetRandomPass (RequestPass) returns (RandomPass);
}
message SensingData {
string DeviceId = 1;
double Temperature = 2;
double Humidity = 3;
}
message SensingResponse {
bool Success = 1;
string Message = 2;
}
+36
View File
@@ -0,0 +1,36 @@
syntax = "proto3";
option go_package = "./protoapi/;protoapi";
import "common.proto";
service FileTransferService {
rpc UploadFile (stream FileChunk) returns (UploadStatus);
rpc ListFiles (EmptyRequest) returns (FileList);
rpc DownloadFile (DownloadRequest) returns (stream FileChunk);
}
message FileChunk {
string FileName = 1;
bytes Content = 2;
}
message UploadStatus {
bool Success = 1;
string Message = 2;
int64 BytesUploaded = 3;
}
message FileMetadata {
string FileName = 1;
int64 FileSize = 2;
int64 UploadedAt = 3;
}
message FileList {
repeated FileMetadata Files = 1;
}
message DownloadRequest {
string FileName = 1;
}
+210
View File
@@ -0,0 +1,210 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.11
// protoc v3.21.12
// source: alerts.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 AlertSubscription struct {
state protoimpl.MessageState `protogen:"open.v1"`
ClientId string `protobuf:"bytes,1,opt,name=ClientId,proto3" json:"ClientId,omitempty"`
Topic string `protobuf:"bytes,2,opt,name=Topic,proto3" json:"Topic,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *AlertSubscription) Reset() {
*x = AlertSubscription{}
mi := &file_alerts_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *AlertSubscription) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AlertSubscription) ProtoMessage() {}
func (x *AlertSubscription) ProtoReflect() protoreflect.Message {
mi := &file_alerts_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 AlertSubscription.ProtoReflect.Descriptor instead.
func (*AlertSubscription) Descriptor() ([]byte, []int) {
return file_alerts_proto_rawDescGZIP(), []int{0}
}
func (x *AlertSubscription) GetClientId() string {
if x != nil {
return x.ClientId
}
return ""
}
func (x *AlertSubscription) GetTopic() string {
if x != nil {
return x.Topic
}
return ""
}
type AlertMessage struct {
state protoimpl.MessageState `protogen:"open.v1"`
AlertId string `protobuf:"bytes,1,opt,name=AlertId,proto3" json:"AlertId,omitempty"`
DeviceId string `protobuf:"bytes,2,opt,name=DeviceId,proto3" json:"DeviceId,omitempty"`
Message string `protobuf:"bytes,3,opt,name=Message,proto3" json:"Message,omitempty"`
Timestamp int64 `protobuf:"varint,4,opt,name=Timestamp,proto3" json:"Timestamp,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *AlertMessage) Reset() {
*x = AlertMessage{}
mi := &file_alerts_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *AlertMessage) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AlertMessage) ProtoMessage() {}
func (x *AlertMessage) ProtoReflect() protoreflect.Message {
mi := &file_alerts_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 AlertMessage.ProtoReflect.Descriptor instead.
func (*AlertMessage) Descriptor() ([]byte, []int) {
return file_alerts_proto_rawDescGZIP(), []int{1}
}
func (x *AlertMessage) GetAlertId() string {
if x != nil {
return x.AlertId
}
return ""
}
func (x *AlertMessage) GetDeviceId() string {
if x != nil {
return x.DeviceId
}
return ""
}
func (x *AlertMessage) GetMessage() string {
if x != nil {
return x.Message
}
return ""
}
func (x *AlertMessage) GetTimestamp() int64 {
if x != nil {
return x.Timestamp
}
return 0
}
var File_alerts_proto protoreflect.FileDescriptor
const file_alerts_proto_rawDesc = "" +
"\n" +
"\falerts.proto\x1a\fcommon.proto\"E\n" +
"\x11AlertSubscription\x12\x1a\n" +
"\bClientId\x18\x01 \x01(\tR\bClientId\x12\x14\n" +
"\x05Topic\x18\x02 \x01(\tR\x05Topic\"|\n" +
"\fAlertMessage\x12\x18\n" +
"\aAlertId\x18\x01 \x01(\tR\aAlertId\x12\x1a\n" +
"\bDeviceId\x18\x02 \x01(\tR\bDeviceId\x12\x18\n" +
"\aMessage\x18\x03 \x01(\tR\aMessage\x12\x1c\n" +
"\tTimestamp\x18\x04 \x01(\x03R\tTimestamp2F\n" +
"\fAlertService\x126\n" +
"\x0fSubscribeAlerts\x12\x12.AlertSubscription\x1a\r.AlertMessage0\x01B\x16Z\x14./protoapi/;protoapib\x06proto3"
var (
file_alerts_proto_rawDescOnce sync.Once
file_alerts_proto_rawDescData []byte
)
func file_alerts_proto_rawDescGZIP() []byte {
file_alerts_proto_rawDescOnce.Do(func() {
file_alerts_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_alerts_proto_rawDesc), len(file_alerts_proto_rawDesc)))
})
return file_alerts_proto_rawDescData
}
var file_alerts_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_alerts_proto_goTypes = []any{
(*AlertSubscription)(nil), // 0: AlertSubscription
(*AlertMessage)(nil), // 1: AlertMessage
}
var file_alerts_proto_depIdxs = []int32{
0, // 0: AlertService.SubscribeAlerts:input_type -> AlertSubscription
1, // 1: AlertService.SubscribeAlerts:output_type -> AlertMessage
1, // [1:2] is the sub-list for method output_type
0, // [0:1] 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_alerts_proto_init() }
func file_alerts_proto_init() {
if File_alerts_proto != nil {
return
}
file_common_proto_init()
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_alerts_proto_rawDesc), len(file_alerts_proto_rawDesc)),
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_alerts_proto_goTypes,
DependencyIndexes: file_alerts_proto_depIdxs,
MessageInfos: file_alerts_proto_msgTypes,
}.Build()
File_alerts_proto = out.File
file_alerts_proto_goTypes = nil
file_alerts_proto_depIdxs = nil
}
+124
View File
@@ -0,0 +1,124 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.6.2
// - protoc v3.21.12
// source: alerts.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 (
AlertService_SubscribeAlerts_FullMethodName = "/AlertService/SubscribeAlerts"
)
// AlertServiceClient is the client API for AlertService 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 AlertServiceClient interface {
SubscribeAlerts(ctx context.Context, in *AlertSubscription, opts ...grpc.CallOption) (grpc.ServerStreamingClient[AlertMessage], error)
}
type alertServiceClient struct {
cc grpc.ClientConnInterface
}
func NewAlertServiceClient(cc grpc.ClientConnInterface) AlertServiceClient {
return &alertServiceClient{cc}
}
func (c *alertServiceClient) SubscribeAlerts(ctx context.Context, in *AlertSubscription, opts ...grpc.CallOption) (grpc.ServerStreamingClient[AlertMessage], error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
stream, err := c.cc.NewStream(ctx, &AlertService_ServiceDesc.Streams[0], AlertService_SubscribeAlerts_FullMethodName, cOpts...)
if err != nil {
return nil, err
}
x := &grpc.GenericClientStream[AlertSubscription, AlertMessage]{ClientStream: stream}
if err := x.ClientStream.SendMsg(in); err != nil {
return nil, err
}
if err := x.ClientStream.CloseSend(); err != nil {
return nil, err
}
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 AlertService_SubscribeAlertsClient = grpc.ServerStreamingClient[AlertMessage]
// AlertServiceServer is the server API for AlertService service.
// All implementations must embed UnimplementedAlertServiceServer
// for forward compatibility.
type AlertServiceServer interface {
SubscribeAlerts(*AlertSubscription, grpc.ServerStreamingServer[AlertMessage]) error
mustEmbedUnimplementedAlertServiceServer()
}
// UnimplementedAlertServiceServer 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 UnimplementedAlertServiceServer struct{}
func (UnimplementedAlertServiceServer) SubscribeAlerts(*AlertSubscription, grpc.ServerStreamingServer[AlertMessage]) error {
return status.Error(codes.Unimplemented, "method SubscribeAlerts not implemented")
}
func (UnimplementedAlertServiceServer) mustEmbedUnimplementedAlertServiceServer() {}
func (UnimplementedAlertServiceServer) testEmbeddedByValue() {}
// UnsafeAlertServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to AlertServiceServer will
// result in compilation errors.
type UnsafeAlertServiceServer interface {
mustEmbedUnimplementedAlertServiceServer()
}
func RegisterAlertServiceServer(s grpc.ServiceRegistrar, srv AlertServiceServer) {
// If the following call panics, it indicates UnimplementedAlertServiceServer 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(&AlertService_ServiceDesc, srv)
}
func _AlertService_SubscribeAlerts_Handler(srv interface{}, stream grpc.ServerStream) error {
m := new(AlertSubscription)
if err := stream.RecvMsg(m); err != nil {
return err
}
return srv.(AlertServiceServer).SubscribeAlerts(m, &grpc.GenericServerStream[AlertSubscription, AlertMessage]{ServerStream: stream})
}
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type AlertService_SubscribeAlertsServer = grpc.ServerStreamingServer[AlertMessage]
// AlertService_ServiceDesc is the grpc.ServiceDesc for AlertService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var AlertService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "AlertService",
HandlerType: (*AlertServiceServer)(nil),
Methods: []grpc.MethodDesc{},
Streams: []grpc.StreamDesc{
{
StreamName: "SubscribeAlerts",
Handler: _AlertService_SubscribeAlerts_Handler,
ServerStreams: true,
},
},
Metadata: "alerts.proto",
}
+311
View File
@@ -0,0 +1,311 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.11
// protoc v3.21.12
// source: common.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 DateTime struct {
state protoimpl.MessageState `protogen:"open.v1"`
Value string `protobuf:"bytes,1,opt,name=Value,proto3" json:"Value,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *DateTime) Reset() {
*x = DateTime{}
mi := &file_common_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *DateTime) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*DateTime) ProtoMessage() {}
func (x *DateTime) ProtoReflect() protoreflect.Message {
mi := &file_common_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 DateTime.ProtoReflect.Descriptor instead.
func (*DateTime) Descriptor() ([]byte, []int) {
return file_common_proto_rawDescGZIP(), []int{0}
}
func (x *DateTime) GetValue() string {
if x != nil {
return x.Value
}
return ""
}
type RequestDateTime struct {
state protoimpl.MessageState `protogen:"open.v1"`
Value string `protobuf:"bytes,2,opt,name=Value,proto3" json:"Value,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *RequestDateTime) Reset() {
*x = RequestDateTime{}
mi := &file_common_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *RequestDateTime) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RequestDateTime) ProtoMessage() {}
func (x *RequestDateTime) ProtoReflect() protoreflect.Message {
mi := &file_common_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 RequestDateTime.ProtoReflect.Descriptor instead.
func (*RequestDateTime) Descriptor() ([]byte, []int) {
return file_common_proto_rawDescGZIP(), []int{1}
}
func (x *RequestDateTime) GetValue() string {
if x != nil {
return x.Value
}
return ""
}
type RequestPass struct {
state protoimpl.MessageState `protogen:"open.v1"`
Seed int64 `protobuf:"varint,1,opt,name=Seed,proto3" json:"Seed,omitempty"`
Length int64 `protobuf:"varint,8,opt,name=Length,proto3" json:"Length,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *RequestPass) Reset() {
*x = RequestPass{}
mi := &file_common_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *RequestPass) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RequestPass) ProtoMessage() {}
func (x *RequestPass) ProtoReflect() protoreflect.Message {
mi := &file_common_proto_msgTypes[2]
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 RequestPass.ProtoReflect.Descriptor instead.
func (*RequestPass) Descriptor() ([]byte, []int) {
return file_common_proto_rawDescGZIP(), []int{2}
}
func (x *RequestPass) GetSeed() int64 {
if x != nil {
return x.Seed
}
return 0
}
func (x *RequestPass) GetLength() int64 {
if x != nil {
return x.Length
}
return 0
}
type RandomPass struct {
state protoimpl.MessageState `protogen:"open.v1"`
Password string `protobuf:"bytes,1,opt,name=Password,proto3" json:"Password,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *RandomPass) Reset() {
*x = RandomPass{}
mi := &file_common_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *RandomPass) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RandomPass) ProtoMessage() {}
func (x *RandomPass) ProtoReflect() protoreflect.Message {
mi := &file_common_proto_msgTypes[3]
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 RandomPass.ProtoReflect.Descriptor instead.
func (*RandomPass) Descriptor() ([]byte, []int) {
return file_common_proto_rawDescGZIP(), []int{3}
}
func (x *RandomPass) GetPassword() string {
if x != nil {
return x.Password
}
return ""
}
type EmptyRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *EmptyRequest) Reset() {
*x = EmptyRequest{}
mi := &file_common_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *EmptyRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*EmptyRequest) ProtoMessage() {}
func (x *EmptyRequest) ProtoReflect() protoreflect.Message {
mi := &file_common_proto_msgTypes[4]
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 EmptyRequest.ProtoReflect.Descriptor instead.
func (*EmptyRequest) Descriptor() ([]byte, []int) {
return file_common_proto_rawDescGZIP(), []int{4}
}
var File_common_proto protoreflect.FileDescriptor
const file_common_proto_rawDesc = "" +
"\n" +
"\fcommon.proto\" \n" +
"\bDateTime\x12\x14\n" +
"\x05Value\x18\x01 \x01(\tR\x05Value\"'\n" +
"\x0fRequestDateTime\x12\x14\n" +
"\x05Value\x18\x02 \x01(\tR\x05Value\"9\n" +
"\vRequestPass\x12\x12\n" +
"\x04Seed\x18\x01 \x01(\x03R\x04Seed\x12\x16\n" +
"\x06Length\x18\b \x01(\x03R\x06Length\"(\n" +
"\n" +
"RandomPass\x12\x1a\n" +
"\bPassword\x18\x01 \x01(\tR\bPassword\"\x0e\n" +
"\fEmptyRequestB\x16Z\x14./protoapi/;protoapib\x06proto3"
var (
file_common_proto_rawDescOnce sync.Once
file_common_proto_rawDescData []byte
)
func file_common_proto_rawDescGZIP() []byte {
file_common_proto_rawDescOnce.Do(func() {
file_common_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_common_proto_rawDesc), len(file_common_proto_rawDesc)))
})
return file_common_proto_rawDescData
}
var file_common_proto_msgTypes = make([]protoimpl.MessageInfo, 5)
var file_common_proto_goTypes = []any{
(*DateTime)(nil), // 0: DateTime
(*RequestDateTime)(nil), // 1: RequestDateTime
(*RequestPass)(nil), // 2: RequestPass
(*RandomPass)(nil), // 3: RandomPass
(*EmptyRequest)(nil), // 4: EmptyRequest
}
var file_common_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] 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_common_proto_init() }
func file_common_proto_init() {
if File_common_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_common_proto_rawDesc), len(file_common_proto_rawDesc)),
NumEnums: 0,
NumMessages: 5,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_common_proto_goTypes,
DependencyIndexes: file_common_proto_depIdxs,
MessageInfos: file_common_proto_msgTypes,
}.Build()
File_common_proto = out.File
file_common_proto_goTypes = nil
file_common_proto_depIdxs = nil
}
+212
View File
@@ -0,0 +1,212 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.11
// protoc v3.21.12
// source: core.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 SensingData struct {
state protoimpl.MessageState `protogen:"open.v1"`
DeviceId string `protobuf:"bytes,1,opt,name=DeviceId,proto3" json:"DeviceId,omitempty"`
Temperature float64 `protobuf:"fixed64,2,opt,name=Temperature,proto3" json:"Temperature,omitempty"`
Humidity float64 `protobuf:"fixed64,3,opt,name=Humidity,proto3" json:"Humidity,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *SensingData) Reset() {
*x = SensingData{}
mi := &file_core_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *SensingData) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SensingData) ProtoMessage() {}
func (x *SensingData) ProtoReflect() protoreflect.Message {
mi := &file_core_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 SensingData.ProtoReflect.Descriptor instead.
func (*SensingData) Descriptor() ([]byte, []int) {
return file_core_proto_rawDescGZIP(), []int{0}
}
func (x *SensingData) GetDeviceId() string {
if x != nil {
return x.DeviceId
}
return ""
}
func (x *SensingData) GetTemperature() float64 {
if x != nil {
return x.Temperature
}
return 0
}
func (x *SensingData) GetHumidity() float64 {
if x != nil {
return x.Humidity
}
return 0
}
type SensingResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
Success bool `protobuf:"varint,1,opt,name=Success,proto3" json:"Success,omitempty"`
Message string `protobuf:"bytes,2,opt,name=Message,proto3" json:"Message,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *SensingResponse) Reset() {
*x = SensingResponse{}
mi := &file_core_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *SensingResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SensingResponse) ProtoMessage() {}
func (x *SensingResponse) ProtoReflect() protoreflect.Message {
mi := &file_core_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 SensingResponse.ProtoReflect.Descriptor instead.
func (*SensingResponse) Descriptor() ([]byte, []int) {
return file_core_proto_rawDescGZIP(), []int{1}
}
func (x *SensingResponse) GetSuccess() bool {
if x != nil {
return x.Success
}
return false
}
func (x *SensingResponse) GetMessage() string {
if x != nil {
return x.Message
}
return ""
}
var File_core_proto protoreflect.FileDescriptor
const file_core_proto_rawDesc = "" +
"\n" +
"\n" +
"core.proto\x1a\fcommon.proto\"g\n" +
"\vSensingData\x12\x1a\n" +
"\bDeviceId\x18\x01 \x01(\tR\bDeviceId\x12 \n" +
"\vTemperature\x18\x02 \x01(\x01R\vTemperature\x12\x1a\n" +
"\bHumidity\x18\x03 \x01(\x01R\bHumidity\"E\n" +
"\x0fSensingResponse\x12\x18\n" +
"\aSuccess\x18\x01 \x01(\bR\aSuccess\x12\x18\n" +
"\aMessage\x18\x02 \x01(\tR\aMessage2\x96\x01\n" +
"\vCoreService\x12&\n" +
"\aGetDate\x12\x10.RequestDateTime\x1a\t.DateTime\x123\n" +
"\x11UpdateSensingData\x12\f.SensingData\x1a\x10.SensingResponse\x12*\n" +
"\rGetRandomPass\x12\f.RequestPass\x1a\v.RandomPassB\x16Z\x14./protoapi/;protoapib\x06proto3"
var (
file_core_proto_rawDescOnce sync.Once
file_core_proto_rawDescData []byte
)
func file_core_proto_rawDescGZIP() []byte {
file_core_proto_rawDescOnce.Do(func() {
file_core_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_core_proto_rawDesc), len(file_core_proto_rawDesc)))
})
return file_core_proto_rawDescData
}
var file_core_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_core_proto_goTypes = []any{
(*SensingData)(nil), // 0: SensingData
(*SensingResponse)(nil), // 1: SensingResponse
(*RequestDateTime)(nil), // 2: RequestDateTime
(*RequestPass)(nil), // 3: RequestPass
(*DateTime)(nil), // 4: DateTime
(*RandomPass)(nil), // 5: RandomPass
}
var file_core_proto_depIdxs = []int32{
2, // 0: CoreService.GetDate:input_type -> RequestDateTime
0, // 1: CoreService.UpdateSensingData:input_type -> SensingData
3, // 2: CoreService.GetRandomPass:input_type -> RequestPass
4, // 3: CoreService.GetDate:output_type -> DateTime
1, // 4: CoreService.UpdateSensingData:output_type -> SensingResponse
5, // 5: CoreService.GetRandomPass:output_type -> RandomPass
3, // [3:6] is the sub-list for method output_type
0, // [0:3] 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_core_proto_init() }
func file_core_proto_init() {
if File_core_proto != nil {
return
}
file_common_proto_init()
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_core_proto_rawDesc), len(file_core_proto_rawDesc)),
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_core_proto_goTypes,
DependencyIndexes: file_core_proto_depIdxs,
MessageInfos: file_core_proto_msgTypes,
}.Build()
File_core_proto = out.File
file_core_proto_goTypes = nil
file_core_proto_depIdxs = nil
}
+197
View File
@@ -0,0 +1,197 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.6.2
// - protoc v3.21.12
// source: core.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 (
CoreService_GetDate_FullMethodName = "/CoreService/GetDate"
CoreService_UpdateSensingData_FullMethodName = "/CoreService/UpdateSensingData"
CoreService_GetRandomPass_FullMethodName = "/CoreService/GetRandomPass"
)
// CoreServiceClient is the client API for CoreService 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 CoreServiceClient interface {
GetDate(ctx context.Context, in *RequestDateTime, opts ...grpc.CallOption) (*DateTime, error)
UpdateSensingData(ctx context.Context, in *SensingData, opts ...grpc.CallOption) (*SensingResponse, error)
GetRandomPass(ctx context.Context, in *RequestPass, opts ...grpc.CallOption) (*RandomPass, error)
}
type coreServiceClient struct {
cc grpc.ClientConnInterface
}
func NewCoreServiceClient(cc grpc.ClientConnInterface) CoreServiceClient {
return &coreServiceClient{cc}
}
func (c *coreServiceClient) GetDate(ctx context.Context, in *RequestDateTime, opts ...grpc.CallOption) (*DateTime, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(DateTime)
err := c.cc.Invoke(ctx, CoreService_GetDate_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *coreServiceClient) UpdateSensingData(ctx context.Context, in *SensingData, opts ...grpc.CallOption) (*SensingResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(SensingResponse)
err := c.cc.Invoke(ctx, CoreService_UpdateSensingData_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *coreServiceClient) GetRandomPass(ctx context.Context, in *RequestPass, opts ...grpc.CallOption) (*RandomPass, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RandomPass)
err := c.cc.Invoke(ctx, CoreService_GetRandomPass_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// CoreServiceServer is the server API for CoreService service.
// All implementations must embed UnimplementedCoreServiceServer
// for forward compatibility.
type CoreServiceServer interface {
GetDate(context.Context, *RequestDateTime) (*DateTime, error)
UpdateSensingData(context.Context, *SensingData) (*SensingResponse, error)
GetRandomPass(context.Context, *RequestPass) (*RandomPass, error)
mustEmbedUnimplementedCoreServiceServer()
}
// UnimplementedCoreServiceServer 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 UnimplementedCoreServiceServer struct{}
func (UnimplementedCoreServiceServer) GetDate(context.Context, *RequestDateTime) (*DateTime, error) {
return nil, status.Error(codes.Unimplemented, "method GetDate not implemented")
}
func (UnimplementedCoreServiceServer) UpdateSensingData(context.Context, *SensingData) (*SensingResponse, error) {
return nil, status.Error(codes.Unimplemented, "method UpdateSensingData not implemented")
}
func (UnimplementedCoreServiceServer) GetRandomPass(context.Context, *RequestPass) (*RandomPass, error) {
return nil, status.Error(codes.Unimplemented, "method GetRandomPass not implemented")
}
func (UnimplementedCoreServiceServer) mustEmbedUnimplementedCoreServiceServer() {}
func (UnimplementedCoreServiceServer) testEmbeddedByValue() {}
// UnsafeCoreServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to CoreServiceServer will
// result in compilation errors.
type UnsafeCoreServiceServer interface {
mustEmbedUnimplementedCoreServiceServer()
}
func RegisterCoreServiceServer(s grpc.ServiceRegistrar, srv CoreServiceServer) {
// If the following call panics, it indicates UnimplementedCoreServiceServer 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(&CoreService_ServiceDesc, srv)
}
func _CoreService_GetDate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RequestDateTime)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(CoreServiceServer).GetDate(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: CoreService_GetDate_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(CoreServiceServer).GetDate(ctx, req.(*RequestDateTime))
}
return interceptor(ctx, in, info, handler)
}
func _CoreService_UpdateSensingData_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SensingData)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(CoreServiceServer).UpdateSensingData(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: CoreService_UpdateSensingData_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(CoreServiceServer).UpdateSensingData(ctx, req.(*SensingData))
}
return interceptor(ctx, in, info, handler)
}
func _CoreService_GetRandomPass_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RequestPass)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(CoreServiceServer).GetRandomPass(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: CoreService_GetRandomPass_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(CoreServiceServer).GetRandomPass(ctx, req.(*RequestPass))
}
return interceptor(ctx, in, info, handler)
}
// CoreService_ServiceDesc is the grpc.ServiceDesc for CoreService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var CoreService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "CoreService",
HandlerType: (*CoreServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "GetDate",
Handler: _CoreService_GetDate_Handler,
},
{
MethodName: "UpdateSensingData",
Handler: _CoreService_UpdateSensingData_Handler,
},
{
MethodName: "GetRandomPass",
Handler: _CoreService_GetRandomPass_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "core.proto",
}
@@ -0,0 +1,373 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.11
// protoc v3.21.12
// source: filetransfer.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 FileChunk struct {
state protoimpl.MessageState `protogen:"open.v1"`
FileName string `protobuf:"bytes,1,opt,name=FileName,proto3" json:"FileName,omitempty"`
Content []byte `protobuf:"bytes,2,opt,name=Content,proto3" json:"Content,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *FileChunk) Reset() {
*x = FileChunk{}
mi := &file_filetransfer_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *FileChunk) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*FileChunk) ProtoMessage() {}
func (x *FileChunk) ProtoReflect() protoreflect.Message {
mi := &file_filetransfer_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 FileChunk.ProtoReflect.Descriptor instead.
func (*FileChunk) Descriptor() ([]byte, []int) {
return file_filetransfer_proto_rawDescGZIP(), []int{0}
}
func (x *FileChunk) GetFileName() string {
if x != nil {
return x.FileName
}
return ""
}
func (x *FileChunk) GetContent() []byte {
if x != nil {
return x.Content
}
return nil
}
type UploadStatus struct {
state protoimpl.MessageState `protogen:"open.v1"`
Success bool `protobuf:"varint,1,opt,name=Success,proto3" json:"Success,omitempty"`
Message string `protobuf:"bytes,2,opt,name=Message,proto3" json:"Message,omitempty"`
BytesUploaded int64 `protobuf:"varint,3,opt,name=BytesUploaded,proto3" json:"BytesUploaded,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *UploadStatus) Reset() {
*x = UploadStatus{}
mi := &file_filetransfer_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *UploadStatus) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UploadStatus) ProtoMessage() {}
func (x *UploadStatus) ProtoReflect() protoreflect.Message {
mi := &file_filetransfer_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 UploadStatus.ProtoReflect.Descriptor instead.
func (*UploadStatus) Descriptor() ([]byte, []int) {
return file_filetransfer_proto_rawDescGZIP(), []int{1}
}
func (x *UploadStatus) GetSuccess() bool {
if x != nil {
return x.Success
}
return false
}
func (x *UploadStatus) GetMessage() string {
if x != nil {
return x.Message
}
return ""
}
func (x *UploadStatus) GetBytesUploaded() int64 {
if x != nil {
return x.BytesUploaded
}
return 0
}
type FileMetadata struct {
state protoimpl.MessageState `protogen:"open.v1"`
FileName string `protobuf:"bytes,1,opt,name=FileName,proto3" json:"FileName,omitempty"`
FileSize int64 `protobuf:"varint,2,opt,name=FileSize,proto3" json:"FileSize,omitempty"`
UploadedAt int64 `protobuf:"varint,3,opt,name=UploadedAt,proto3" json:"UploadedAt,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *FileMetadata) Reset() {
*x = FileMetadata{}
mi := &file_filetransfer_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *FileMetadata) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*FileMetadata) ProtoMessage() {}
func (x *FileMetadata) ProtoReflect() protoreflect.Message {
mi := &file_filetransfer_proto_msgTypes[2]
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 FileMetadata.ProtoReflect.Descriptor instead.
func (*FileMetadata) Descriptor() ([]byte, []int) {
return file_filetransfer_proto_rawDescGZIP(), []int{2}
}
func (x *FileMetadata) GetFileName() string {
if x != nil {
return x.FileName
}
return ""
}
func (x *FileMetadata) GetFileSize() int64 {
if x != nil {
return x.FileSize
}
return 0
}
func (x *FileMetadata) GetUploadedAt() int64 {
if x != nil {
return x.UploadedAt
}
return 0
}
type FileList struct {
state protoimpl.MessageState `protogen:"open.v1"`
Files []*FileMetadata `protobuf:"bytes,1,rep,name=Files,proto3" json:"Files,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *FileList) Reset() {
*x = FileList{}
mi := &file_filetransfer_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *FileList) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*FileList) ProtoMessage() {}
func (x *FileList) ProtoReflect() protoreflect.Message {
mi := &file_filetransfer_proto_msgTypes[3]
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 FileList.ProtoReflect.Descriptor instead.
func (*FileList) Descriptor() ([]byte, []int) {
return file_filetransfer_proto_rawDescGZIP(), []int{3}
}
func (x *FileList) GetFiles() []*FileMetadata {
if x != nil {
return x.Files
}
return nil
}
type DownloadRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
FileName string `protobuf:"bytes,1,opt,name=FileName,proto3" json:"FileName,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *DownloadRequest) Reset() {
*x = DownloadRequest{}
mi := &file_filetransfer_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *DownloadRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*DownloadRequest) ProtoMessage() {}
func (x *DownloadRequest) ProtoReflect() protoreflect.Message {
mi := &file_filetransfer_proto_msgTypes[4]
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 DownloadRequest.ProtoReflect.Descriptor instead.
func (*DownloadRequest) Descriptor() ([]byte, []int) {
return file_filetransfer_proto_rawDescGZIP(), []int{4}
}
func (x *DownloadRequest) GetFileName() string {
if x != nil {
return x.FileName
}
return ""
}
var File_filetransfer_proto protoreflect.FileDescriptor
const file_filetransfer_proto_rawDesc = "" +
"\n" +
"\x12filetransfer.proto\x1a\fcommon.proto\"A\n" +
"\tFileChunk\x12\x1a\n" +
"\bFileName\x18\x01 \x01(\tR\bFileName\x12\x18\n" +
"\aContent\x18\x02 \x01(\fR\aContent\"h\n" +
"\fUploadStatus\x12\x18\n" +
"\aSuccess\x18\x01 \x01(\bR\aSuccess\x12\x18\n" +
"\aMessage\x18\x02 \x01(\tR\aMessage\x12$\n" +
"\rBytesUploaded\x18\x03 \x01(\x03R\rBytesUploaded\"f\n" +
"\fFileMetadata\x12\x1a\n" +
"\bFileName\x18\x01 \x01(\tR\bFileName\x12\x1a\n" +
"\bFileSize\x18\x02 \x01(\x03R\bFileSize\x12\x1e\n" +
"\n" +
"UploadedAt\x18\x03 \x01(\x03R\n" +
"UploadedAt\"/\n" +
"\bFileList\x12#\n" +
"\x05Files\x18\x01 \x03(\v2\r.FileMetadataR\x05Files\"-\n" +
"\x0fDownloadRequest\x12\x1a\n" +
"\bFileName\x18\x01 \x01(\tR\bFileName2\x97\x01\n" +
"\x13FileTransferService\x12)\n" +
"\n" +
"UploadFile\x12\n" +
".FileChunk\x1a\r.UploadStatus(\x01\x12%\n" +
"\tListFiles\x12\r.EmptyRequest\x1a\t.FileList\x12.\n" +
"\fDownloadFile\x12\x10.DownloadRequest\x1a\n" +
".FileChunk0\x01B\x16Z\x14./protoapi/;protoapib\x06proto3"
var (
file_filetransfer_proto_rawDescOnce sync.Once
file_filetransfer_proto_rawDescData []byte
)
func file_filetransfer_proto_rawDescGZIP() []byte {
file_filetransfer_proto_rawDescOnce.Do(func() {
file_filetransfer_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_filetransfer_proto_rawDesc), len(file_filetransfer_proto_rawDesc)))
})
return file_filetransfer_proto_rawDescData
}
var file_filetransfer_proto_msgTypes = make([]protoimpl.MessageInfo, 5)
var file_filetransfer_proto_goTypes = []any{
(*FileChunk)(nil), // 0: FileChunk
(*UploadStatus)(nil), // 1: UploadStatus
(*FileMetadata)(nil), // 2: FileMetadata
(*FileList)(nil), // 3: FileList
(*DownloadRequest)(nil), // 4: DownloadRequest
(*EmptyRequest)(nil), // 5: EmptyRequest
}
var file_filetransfer_proto_depIdxs = []int32{
2, // 0: FileList.Files:type_name -> FileMetadata
0, // 1: FileTransferService.UploadFile:input_type -> FileChunk
5, // 2: FileTransferService.ListFiles:input_type -> EmptyRequest
4, // 3: FileTransferService.DownloadFile:input_type -> DownloadRequest
1, // 4: FileTransferService.UploadFile:output_type -> UploadStatus
3, // 5: FileTransferService.ListFiles:output_type -> FileList
0, // 6: FileTransferService.DownloadFile:output_type -> FileChunk
4, // [4:7] is the sub-list for method output_type
1, // [1:4] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
}
func init() { file_filetransfer_proto_init() }
func file_filetransfer_proto_init() {
if File_filetransfer_proto != nil {
return
}
file_common_proto_init()
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_filetransfer_proto_rawDesc), len(file_filetransfer_proto_rawDesc)),
NumEnums: 0,
NumMessages: 5,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_filetransfer_proto_goTypes,
DependencyIndexes: file_filetransfer_proto_depIdxs,
MessageInfos: file_filetransfer_proto_msgTypes,
}.Build()
File_filetransfer_proto = out.File
file_filetransfer_proto_goTypes = nil
file_filetransfer_proto_depIdxs = nil
}
@@ -0,0 +1,194 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.6.2
// - protoc v3.21.12
// source: filetransfer.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 (
FileTransferService_UploadFile_FullMethodName = "/FileTransferService/UploadFile"
FileTransferService_ListFiles_FullMethodName = "/FileTransferService/ListFiles"
FileTransferService_DownloadFile_FullMethodName = "/FileTransferService/DownloadFile"
)
// FileTransferServiceClient is the client API for FileTransferService 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 FileTransferServiceClient interface {
UploadFile(ctx context.Context, opts ...grpc.CallOption) (grpc.ClientStreamingClient[FileChunk, UploadStatus], error)
ListFiles(ctx context.Context, in *EmptyRequest, opts ...grpc.CallOption) (*FileList, error)
DownloadFile(ctx context.Context, in *DownloadRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[FileChunk], error)
}
type fileTransferServiceClient struct {
cc grpc.ClientConnInterface
}
func NewFileTransferServiceClient(cc grpc.ClientConnInterface) FileTransferServiceClient {
return &fileTransferServiceClient{cc}
}
func (c *fileTransferServiceClient) UploadFile(ctx context.Context, opts ...grpc.CallOption) (grpc.ClientStreamingClient[FileChunk, UploadStatus], error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
stream, err := c.cc.NewStream(ctx, &FileTransferService_ServiceDesc.Streams[0], FileTransferService_UploadFile_FullMethodName, cOpts...)
if err != nil {
return nil, err
}
x := &grpc.GenericClientStream[FileChunk, UploadStatus]{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 FileTransferService_UploadFileClient = grpc.ClientStreamingClient[FileChunk, UploadStatus]
func (c *fileTransferServiceClient) ListFiles(ctx context.Context, in *EmptyRequest, opts ...grpc.CallOption) (*FileList, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(FileList)
err := c.cc.Invoke(ctx, FileTransferService_ListFiles_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *fileTransferServiceClient) DownloadFile(ctx context.Context, in *DownloadRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[FileChunk], error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
stream, err := c.cc.NewStream(ctx, &FileTransferService_ServiceDesc.Streams[1], FileTransferService_DownloadFile_FullMethodName, cOpts...)
if err != nil {
return nil, err
}
x := &grpc.GenericClientStream[DownloadRequest, FileChunk]{ClientStream: stream}
if err := x.ClientStream.SendMsg(in); err != nil {
return nil, err
}
if err := x.ClientStream.CloseSend(); err != nil {
return nil, err
}
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 FileTransferService_DownloadFileClient = grpc.ServerStreamingClient[FileChunk]
// FileTransferServiceServer is the server API for FileTransferService service.
// All implementations must embed UnimplementedFileTransferServiceServer
// for forward compatibility.
type FileTransferServiceServer interface {
UploadFile(grpc.ClientStreamingServer[FileChunk, UploadStatus]) error
ListFiles(context.Context, *EmptyRequest) (*FileList, error)
DownloadFile(*DownloadRequest, grpc.ServerStreamingServer[FileChunk]) error
mustEmbedUnimplementedFileTransferServiceServer()
}
// UnimplementedFileTransferServiceServer 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 UnimplementedFileTransferServiceServer struct{}
func (UnimplementedFileTransferServiceServer) UploadFile(grpc.ClientStreamingServer[FileChunk, UploadStatus]) error {
return status.Error(codes.Unimplemented, "method UploadFile not implemented")
}
func (UnimplementedFileTransferServiceServer) ListFiles(context.Context, *EmptyRequest) (*FileList, error) {
return nil, status.Error(codes.Unimplemented, "method ListFiles not implemented")
}
func (UnimplementedFileTransferServiceServer) DownloadFile(*DownloadRequest, grpc.ServerStreamingServer[FileChunk]) error {
return status.Error(codes.Unimplemented, "method DownloadFile not implemented")
}
func (UnimplementedFileTransferServiceServer) mustEmbedUnimplementedFileTransferServiceServer() {}
func (UnimplementedFileTransferServiceServer) testEmbeddedByValue() {}
// UnsafeFileTransferServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to FileTransferServiceServer will
// result in compilation errors.
type UnsafeFileTransferServiceServer interface {
mustEmbedUnimplementedFileTransferServiceServer()
}
func RegisterFileTransferServiceServer(s grpc.ServiceRegistrar, srv FileTransferServiceServer) {
// If the following call panics, it indicates UnimplementedFileTransferServiceServer 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(&FileTransferService_ServiceDesc, srv)
}
func _FileTransferService_UploadFile_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(FileTransferServiceServer).UploadFile(&grpc.GenericServerStream[FileChunk, UploadStatus]{ServerStream: stream})
}
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type FileTransferService_UploadFileServer = grpc.ClientStreamingServer[FileChunk, UploadStatus]
func _FileTransferService_ListFiles_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(EmptyRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(FileTransferServiceServer).ListFiles(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: FileTransferService_ListFiles_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(FileTransferServiceServer).ListFiles(ctx, req.(*EmptyRequest))
}
return interceptor(ctx, in, info, handler)
}
func _FileTransferService_DownloadFile_Handler(srv interface{}, stream grpc.ServerStream) error {
m := new(DownloadRequest)
if err := stream.RecvMsg(m); err != nil {
return err
}
return srv.(FileTransferServiceServer).DownloadFile(m, &grpc.GenericServerStream[DownloadRequest, FileChunk]{ServerStream: stream})
}
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type FileTransferService_DownloadFileServer = grpc.ServerStreamingServer[FileChunk]
// FileTransferService_ServiceDesc is the grpc.ServiceDesc for FileTransferService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var FileTransferService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "FileTransferService",
HandlerType: (*FileTransferServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "ListFiles",
Handler: _FileTransferService_ListFiles_Handler,
},
},
Streams: []grpc.StreamDesc{
{
StreamName: "UploadFile",
Handler: _FileTransferService_UploadFile_Handler,
ClientStreams: true,
},
{
StreamName: "DownloadFile",
Handler: _FileTransferService_DownloadFile_Handler,
ServerStreams: true,
},
},
Metadata: "filetransfer.proto",
}
+257
View File
@@ -0,0 +1,257 @@
package modular
import (
"context"
"fmt"
"io"
"math/rand"
"net"
"sync"
"time"
"grpccanary/lib/grpc/modular/protoapi"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/reflection"
"google.golang.org/grpc/status"
)
type UploadedFile struct {
FileName string
Content []byte
UploadedAt int64
}
type AlertSubscriber struct {
ClientId string
Channel chan *protoapi.AlertMessage
}
var (
fileStore = make(map[string]*UploadedFile)
storeMu sync.RWMutex
subscribers = make(map[string]*AlertSubscriber)
subMu sync.Mutex
)
func publishAlert(alert *protoapi.AlertMessage) {
subMu.Lock()
defer subMu.Unlock()
for _, sub := range subscribers {
select {
case sub.Channel <- alert:
default:
fmt.Printf("Alert channel blocked for client %s, dropping event\n", sub.ClientId)
}
}
}
func random(min, max int, src rand.Source) int {
return rand.New(src).Intn(max-min) + min
}
func getString(len int64, src rand.Source) string {
temp := ""
startChar := "!"
var i int64 = 1
for {
myRand := random(0, 94, src)
newChar := string(startChar[0] + byte(myRand))
temp = temp + newChar
if i == len {
break
}
i++
}
return temp
}
// 1. Core Server Implementation
type CoreServer struct {
protoapi.UnimplementedCoreServiceServer
}
func (CoreServer) GetDate(ctx context.Context, r *protoapi.RequestDateTime) (*protoapi.DateTime, error) {
currentTime := time.Now()
return &protoapi.DateTime{
Value: currentTime.String(),
}, nil
}
func (CoreServer) UpdateSensingData(ctx context.Context, r *protoapi.SensingData) (*protoapi.SensingResponse, error) {
fmt.Printf("[Modular Core] Received sensing data - Device: %s, Temp: %.2f°C, Humid: %.2f%%\n", r.GetDeviceId(), r.GetTemperature(), r.GetHumidity())
if r.GetTemperature() > 40.0 {
fmt.Printf("⚠️ [Modular Core] Critical temperature detected: %.2f°C! Publishing warning...\n", r.GetTemperature())
publishAlert(&protoapi.AlertMessage{
AlertId: fmt.Sprintf("alert-%d", time.Now().UnixNano()),
DeviceId: r.GetDeviceId(),
Message: fmt.Sprintf("Critical high temperature: %.2f°C (Humidity: %.2f%%)", r.GetTemperature(), r.GetHumidity()),
Timestamp: time.Now().Unix(),
})
}
return &protoapi.SensingResponse{
Success: true,
Message: fmt.Sprintf("Sensing data updated successfully for device %s", r.GetDeviceId()),
}, nil
}
func (CoreServer) GetRandomPass(ctx context.Context, r *protoapi.RequestPass) (*protoapi.RandomPass, error) {
src := rand.NewSource(r.GetSeed())
temp := getString(r.GetLength(), src)
return &protoapi.RandomPass{
Password: temp,
}, nil
}
// 2. File Transfer Server Implementation
type FileTransferServer struct {
protoapi.UnimplementedFileTransferServiceServer
}
func (FileTransferServer) UploadFile(stream protoapi.FileTransferService_UploadFileServer) error {
var totalBytes int64
var fileName string
var buffer []byte
for {
chunk, err := stream.Recv()
if err == io.EOF {
fmt.Printf("[Modular File] File upload completed. Received %d bytes for file '%s'\n", totalBytes, fileName)
if fileName != "" {
storeMu.Lock()
fileStore[fileName] = &UploadedFile{
FileName: fileName,
Content: buffer,
UploadedAt: time.Now().Unix(),
}
storeMu.Unlock()
}
return stream.SendAndClose(&protoapi.UploadStatus{
Success: true,
Message: fmt.Sprintf("File '%s' uploaded successfully.", fileName),
BytesUploaded: totalBytes,
})
}
if err != nil {
fmt.Println("[Modular File] File upload error:", err)
return err
}
if fileName == "" {
fileName = chunk.GetFileName()
}
buffer = append(buffer, chunk.GetContent()...)
totalBytes += int64(len(chunk.GetContent()))
}
}
func (FileTransferServer) ListFiles(ctx context.Context, r *protoapi.EmptyRequest) (*protoapi.FileList, error) {
storeMu.RLock()
defer storeMu.RUnlock()
var files []*protoapi.FileMetadata
for _, f := range fileStore {
files = append(files, &protoapi.FileMetadata{
FileName: f.FileName,
FileSize: int64(len(f.Content)),
UploadedAt: f.UploadedAt,
})
}
return &protoapi.FileList{Files: files}, nil
}
func (FileTransferServer) DownloadFile(r *protoapi.DownloadRequest, stream protoapi.FileTransferService_DownloadFileServer) error {
storeMu.RLock()
f, exists := fileStore[r.GetFileName()]
storeMu.RUnlock()
if !exists {
return status.Errorf(codes.NotFound, "file %s not found", r.GetFileName())
}
chunkSize := 1024
totalBytes := len(f.Content)
for i := 0; i < totalBytes; i += chunkSize {
end := i + chunkSize
if end > totalBytes {
end = totalBytes
}
err := stream.Send(&protoapi.FileChunk{
FileName: f.FileName,
Content: f.Content[i:end],
})
if err != nil {
return err
}
}
return nil
}
// 3. Alert Server Implementation
type AlertServer struct {
protoapi.UnimplementedAlertServiceServer
}
func (AlertServer) SubscribeAlerts(r *protoapi.AlertSubscription, stream protoapi.AlertService_SubscribeAlertsServer) error {
clientId := r.GetClientId()
ch := make(chan *protoapi.AlertMessage, 10)
sub := &AlertSubscriber{
ClientId: clientId,
Channel: ch,
}
subMu.Lock()
subscribers[clientId] = sub
subMu.Unlock()
fmt.Printf("[Modular Alert] Client %s subscribed to alerts on topic '%s'\n", clientId, r.GetTopic())
for {
select {
case alert := <-ch:
err := stream.Send(alert)
if err != nil {
subMu.Lock()
delete(subscribers, clientId)
subMu.Unlock()
fmt.Printf("[Modular Alert] Client %s alert subscription disconnected: %v\n", clientId, err)
return err
}
case <-stream.Context().Done():
subMu.Lock()
delete(subscribers, clientId)
subMu.Unlock()
fmt.Printf("[Modular Alert] Client %s unsubscribed (context done)\n", clientId)
return nil
}
}
}
func ServerRun(addr string) {
server := grpc.NewServer()
// Register multiple services on the same gRPC server
protoapi.RegisterCoreServiceServer(server, CoreServer{})
protoapi.RegisterFileTransferServiceServer(server, FileTransferServer{})
protoapi.RegisterAlertServiceServer(server, AlertServer{})
reflection.Register(server)
listen, err := net.Listen("tcp", addr)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("[Modular Server] Listening on %s...\n", addr)
server.Serve(listen)
}