Skip to content

Commit

Permalink
demo finished
Browse files Browse the repository at this point in the history
  • Loading branch information
Marius Godeanu Costache committed Mar 19, 2021
1 parent 74cab26 commit 0a9f7a3
Show file tree
Hide file tree
Showing 10 changed files with 178 additions and 30 deletions.
4 changes: 1 addition & 3 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
.PHONY: proto run down

proto:
protoc --go_out=. --go_opt=paths=source_relative \
--go-grpc_out=. --go-grpc_opt=paths=source_relative \
salesservice/proto/sales.proto
protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative salesservice/proto/sales.proto

run:
docker-compose up -d
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ require (
github.com/google/uuid v1.1.4
github.com/gorilla/mux v1.8.0
github.com/lib/pq v1.8.0
github.com/opentracing-contrib/go-grpc v0.0.0-20210225150812-73cb765af46e
github.com/opentracing/opentracing-go v1.2.0
github.com/pkg/errors v0.9.1 // indirect
github.com/uber/jaeger-client-go v2.25.0+incompatible
Expand Down
7 changes: 7 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,17 @@ github.com/google/uuid v1.1.4 h1:0ecGp3skIrHWPNGPJDaBIghfA6Sp7Ruo2Io8eLKzWm0=
github.com/google/uuid v1.1.4/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/grpc-ecosystem/grpc-opentracing v0.0.0-20180507213350-8e809c8a8645/go.mod h1:6iZfnjpejD4L/4DwD7NryNaJyCQdzwWwH2MWhCA90Kw=
github.com/jung-kurt/gofpdf v1.0.3-0.20190309125859-24315acbbda5/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/lib/pq v1.8.0 h1:9xohqzkUwzR4Ga4ivdTcawVS89YSDVxXMa3xJX3cGzg=
github.com/lib/pq v1.8.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/opentracing-contrib/go-grpc v0.0.0-20210225150812-73cb765af46e h1:4cPxUYdgaGzZIT5/j0IfqOrrXmq6bG8AwvwisMXpdrg=
github.com/opentracing-contrib/go-grpc v0.0.0-20210225150812-73cb765af46e/go.mod h1:DYR5Eij8rJl8h7gblRrOZ8g0kW1umSpKqYIBTgeDtLo=
github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs=
github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
Expand All @@ -61,6 +65,7 @@ github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:
github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
Expand Down Expand Up @@ -92,6 +97,7 @@ golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73r
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190921015927-1a5e07d1ff72/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201224014010-6772e930b67b h1:iFwSg7t5GZmB/Q5TjiEAsdoLDrdJRC1RiF2WhuV29Qw=
golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
Expand Down Expand Up @@ -135,6 +141,7 @@ google.golang.org/genproto v0.0.0-20210106152847-07624b53cd92 h1:jOTk2Z6KYaWoptU
google.golang.org/genproto v0.0.0-20210106152847-07624b53cd92/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.23.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/grpc v1.34.0 h1:raiipEjMOIC/TO2AvyTxP25XFdLxNIBwzDh3FM3XztI=
Expand Down
44 changes: 37 additions & 7 deletions productservice/internal/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ import (
"log"
"time"

otgrpc "github.com/opentracing-contrib/go-grpc"
opentracing "github.com/opentracing/opentracing-go"
pb "github.com/tacheshun/golang-rest-api/salesservice/proto"
"github.com/uber/jaeger-client-go/config"
)

const (
address = "localhost:50051"
defaultName = "world"
address = ":50051"
)

func InitTracer(serviceName, host string) (opentracing.Tracer, error) {
Expand All @@ -38,9 +38,14 @@ func InitTracer(serviceName, host string) (opentracing.Tracer, error) {
}

func Send() (interface{}, error) {

tracer, err := InitTracer("product", "127.0.0.1:16686")
if err != nil {
panic("cannot start tracer")
}
// Set up a connection to the server.
conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock())
conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithUnaryInterceptor(
otgrpc.OpenTracingClientInterceptor(tracer)), grpc.WithStreamInterceptor(
otgrpc.OpenTracingStreamClientInterceptor(tracer)), grpc.WithBlock())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
Expand All @@ -49,15 +54,40 @@ func Send() (interface{}, error) {

// Contact the server and print out its response.
var productId uint32
productId = 1
productId = 2
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
r, err := c.GetProductWithHighestSales(ctx, &pb.ProductIdRequest{ProductId: productId})
if err != nil {
log.Fatalf("could not fetch: %v", err)
}
fmt.Println(r)
log.Printf("Product wth the highest sales is: %v, %v", r.Product, r.TotalSales)

return r, nil
}

func GetSalesForProductRPC(productId uint32) (map[string]interface{}, error) {
tracer, err := InitTracer("product", "127.0.0.1:16686")
if err != nil {
panic("cannot start tracer")
}
// Set up a connection to the server.
conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithUnaryInterceptor(
otgrpc.OpenTracingClientInterceptor(tracer)), grpc.WithStreamInterceptor(
otgrpc.OpenTracingStreamClientInterceptor(tracer)), grpc.WithBlock())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := pb.NewSalesClient(conn)

// Contact the server and print out its response.
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()

res, err := c.GetSalesForProduct(ctx, &pb.ProductIdRequest{ProductId: productId})
if err != nil {
log.Fatalf("could not fetch: %v", err)
}

return map[string]interface{}{"productId":res.ProductId, "quantity":res.Quantity}, nil
}
7 changes: 7 additions & 0 deletions productservice/internal/handlers/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ func (a *App) GetProduct(w http.ResponseWriter, r *http.Request) {
}

p := models.Product{ID: id}
if err != nil {
respondWithError(w, http.StatusBadRequest, "RPC request failed")
return
}

if err := p.GetProduct(a.DB); err != nil {
switch err {
case sql.ErrNoRows:
Expand All @@ -59,6 +64,8 @@ func (a *App) GetProduct(w http.ResponseWriter, r *http.Request) {
}
return
}
productTotalSales, err := client.GetSalesForProductRPC(uint32(id))
p.Sale = float64(productTotalSales["quantity"].(uint32))

respondWithJSON(w, http.StatusOK, p)
}
Expand Down
1 change: 1 addition & 0 deletions productservice/internal/models/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ type Product struct {
ID int `json:"id"`
Name string `json:"name"`
Price float64 `json:"price"`
Sale float64 `json:"total_sales,omitempty"`
Created time.Time `json:"-"`
Modified time.Time `json:"-"`
}
Expand Down
73 changes: 67 additions & 6 deletions salesservice/cmd/sales/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,18 @@ import (
"context"
"database/sql"
"encoding/json"
"fmt"
_ "github.com/lib/pq"
otgrpc "github.com/opentracing-contrib/go-grpc"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
pb "github.com/tacheshun/golang-rest-api/salesservice/proto"
"github.com/uber/jaeger-client-go/config"
"google.golang.org/grpc"
"log"
"net"
"net/http"
"time"
)

const (
Expand All @@ -24,9 +30,14 @@ func main() {
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
grpcServer := grpc.NewServer()
tracer, err := InitTracer("Sales", "127.0.0.1:16686")
grpcServer := grpc.NewServer(grpc.UnaryInterceptor(
otgrpc.OpenTracingServerInterceptor(tracer)),
grpc.StreamInterceptor(
otgrpc.OpenTracingStreamServerInterceptor(tracer)))
pb.RegisterSalesServer(grpcServer, &server{
repo: &app,
repo: &app,
tracer: tracer,
})
if err := grpcServer.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
Expand All @@ -38,9 +49,10 @@ type SalesApp struct {
}

type Sale struct {
SalesID int `json:"sale_id"`
ProductID int `json:"product_id"`
Quantity int `json:"quantity"`
SalesID int `json:"sale_id"`
ProductID int `json:"product_id"`
Quantity int `json:"quantity"`
Created time.Time `json:"created"`
}

type ProductSales struct {
Expand All @@ -58,10 +70,18 @@ func (s *SalesApp) Initialize() {

type server struct {
pb.UnimplementedSalesServer
repo *SalesApp
repo *SalesApp
tracer opentracing.Tracer
}

func (srv *server) GetProductWithHighestSales(ctx context.Context, in *pb.ProductIdRequest) (*pb.ProductWithSales, error) {
if span := opentracing.SpanFromContext(ctx); span != nil {
span := srv.tracer.StartSpan("GetProductWithHighestSales", opentracing.ChildOf(span.Context()))
span.SetTag("param.location", in.ProductId)
ext.SpanKindRPCClient.Set(span)
defer span.Finish()
ctx = opentracing.ContextWithSpan(ctx, span)
}
result, err := srv.repo.GetProductPlusHighestSales(in.GetProductId())
if err != nil {
return nil, err
Expand All @@ -74,6 +94,19 @@ func (srv *server) GetProductWithHighestSales(ctx context.Context, in *pb.Produc
return out, nil
}

func (srv *server) GetSalesForProduct(ctx context.Context, in *pb.ProductIdRequest) (*pb.Sale, error) {
result, err := srv.repo.GetSalesForProductID(in.GetProductId())
if err != nil {
return nil, err
}

out := &pb.Sale{}
//
out.ProductId = uint32(result.ProductID)
out.Quantity = uint32(result.Quantity)
return out, nil
}

func (s *SalesApp) GetProductPlusHighestSales(_ uint32) (*ProductSales, error) {
var productSales ProductSales
_ = s.DB.QueryRow(
Expand All @@ -82,6 +115,14 @@ func (s *SalesApp) GetProductPlusHighestSales(_ uint32) (*ProductSales, error) {
return &productSales, nil
}

func (s *SalesApp) GetSalesForProductID(productId uint32) (*Sale, error) {
var sale Sale
_ = s.DB.QueryRow(
"SELECT product_id, sum(quantity) as total_sales from sales WHERE product_id=$1 group by product_id", productId).Scan(&sale.ProductID, &sale.Quantity)

return &sale, nil
}

func respondWithError(w http.ResponseWriter, code int, message string) {
respondWithJSON(w, code, map[string]string{"error": message})
}
Expand All @@ -93,3 +134,23 @@ func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
w.WriteHeader(code)
_, _ = w.Write(response)
}

func InitTracer(serviceName, host string) (opentracing.Tracer, error) {
cfg := config.Configuration{
Sampler: &config.SamplerConfig{
Type: "const",
Param: 1,
},
Reporter: &config.ReporterConfig{
LogSpans: false,
BufferFlushInterval: 1 * time.Second,
LocalAgentHostPort: host,
},
}

tracer, _, err := cfg.New(serviceName)
if err != nil {
return nil, fmt.Errorf("new tracer error: %v", err)
}
return tracer, nil
}
32 changes: 19 additions & 13 deletions salesservice/proto/sales.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion salesservice/proto/sales.proto
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,5 @@ message ProductReply {

service Sales {
rpc GetProductWithHighestSales(ProductIdRequest) returns (ProductWithSales) {}
}
rpc GetSalesForProduct(ProductIdRequest) returns (Sale) {}
}
Loading

0 comments on commit 0a9f7a3

Please sign in to comment.