github.com/blong14/gache@v0.0.0-20240124023949-89416fd8bbfa/internal/server/rpc.go (about)

     1  package server
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"net/rpc"
     7  	"time"
     8  
     9  	gdb "github.com/blong14/gache/internal/db"
    10  	gerrors "github.com/blong14/gache/internal/errors"
    11  	grpc "github.com/blong14/gache/internal/io/rpc"
    12  	glog "github.com/blong14/gache/internal/logging"
    13  	gproxy "github.com/blong14/gache/internal/proxy"
    14  	gache "github.com/blong14/gache/sql"
    15  )
    16  
    17  var ErrNilClient = gerrors.NewGError(errors.New("nil client"))
    18  
    19  type QueryService struct {
    20  	Proxy *gproxy.QueryProxy
    21  }
    22  
    23  type QueryRequest struct {
    24  	Queries []*gdb.Query
    25  	Query   *gdb.Query
    26  }
    27  
    28  type QueryResponse struct {
    29  	Success bool
    30  	Key     []byte
    31  	Value   []byte
    32  }
    33  
    34  func (qs *QueryService) OnQuery(req *QueryRequest, resp *QueryResponse) error {
    35  	start := time.Now()
    36  	ctx := context.Background()
    37  	query := req.Query
    38  	qry := gdb.NewQuery(ctx, nil)
    39  	qry.Header = query.Header
    40  	qry.Key = query.Key
    41  	qry.Value = query.Value
    42  	qry.Values = query.Values
    43  
    44  	qs.Proxy.Send(ctx, qry)
    45  	r := qry.GetResponse()
    46  	resp.Success = r.Success
    47  	resp.Key = r.Key
    48  	resp.Value = r.Value
    49  	glog.Track("%T %v in %s", req, resp.Success, time.Since(start))
    50  	return nil
    51  }
    52  
    53  func PublishQuery(client *rpc.Client, queries ...*gdb.Query) (*QueryResponse, error) {
    54  	if client == nil {
    55  		return nil, ErrNilClient
    56  	}
    57  	req := new(QueryRequest)
    58  	req.Query = queries[0]
    59  	resp := new(QueryResponse)
    60  	err := client.Call("QueryService.OnQuery", req, resp)
    61  	return resp, err
    62  }
    63  
    64  func RPCHandlers() []grpc.Handler {
    65  	proxy, err := gache.GetProxy()
    66  	if err != nil {
    67  		panic(err)
    68  	}
    69  	return []grpc.Handler{
    70  		&QueryService{
    71  			Proxy: proxy,
    72  		},
    73  	}
    74  }