Add grpc client in broker service

This commit is contained in:
vinchent 2024-09-06 23:11:49 +02:00
parent 29135938c2
commit 5825d0018d
9 changed files with 137 additions and 9 deletions

View File

@ -1,8 +1,10 @@
package main package main
import ( import (
"broker/cmd/api/event" "broker/event"
"broker/logs"
"bytes" "bytes"
"context"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
@ -10,13 +12,16 @@ import (
"net/http" "net/http"
"net/rpc" "net/rpc"
"time" "time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
) )
type RequestPayload struct { type RequestPayload struct {
Action string `string:"action"` Action string `string:"action"`
Auth AuthPayload `json:"auth,omitempty"` Auth AuthPayload ` json:"auth,omitempty"`
Log LogPayload `json:"log,omitempty"` Log LogPayload ` json:"log,omitempty"`
Mail MailPayload `json:"mail,omitempty"` Mail MailPayload ` json:"mail,omitempty"`
} }
type AuthPayload struct { type AuthPayload struct {
@ -57,12 +62,14 @@ func (app *Config) HandleSubmission(w http.ResponseWriter, r *http.Request) {
switch requestPayload.Action { switch requestPayload.Action {
case "auth": case "auth":
app.authenticate(w, requestPayload.Auth) app.authenticate(w, requestPayload.Auth)
case "logHttp": // 2729 us case "logHttp": // 2336 us
app.LogItem(w, requestPayload.Log) app.LogItem(w, requestPayload.Log)
case "logRabbit": // 10007 us case "logRabbit": // 7825 us
app.logEventViaRabbit(w, requestPayload.Log) app.logEventViaRabbit(w, requestPayload.Log)
case "logRpc": // 555 us case "logRpc": // 2097 us
app.logItemViaRPC(w, requestPayload.Log) app.logItemViaRPC(w, requestPayload.Log)
case "logGrpc": // 236882 us
app.LogViaGRPC(w, requestPayload.Log)
case "mail": case "mail":
app.SendMail(w, requestPayload.Mail) app.SendMail(w, requestPayload.Mail)
default: default:
@ -253,3 +260,39 @@ func (app *Config) logItemViaRPC(w http.ResponseWriter, l LogPayload) {
app.writeJSON(w, http.StatusOK, payload) app.writeJSON(w, http.StatusOK, payload)
} }
func (app *Config) LogViaGRPC(w http.ResponseWriter, l LogPayload) {
conn, err := grpc.NewClient(
"logger-service:50001",
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
app.errorJSON(w, err)
return
}
defer conn.Close()
now := time.Now()
l.Data += fmt.Sprintf("gRPC sent date %d", now.UnixMicro())
c := logs.NewLogServiceClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_, err = c.WriteLog(ctx, &logs.LogRequest{
LogEntry: &logs.Log{
Name: l.Name,
Data: l.Data,
},
})
if err != nil {
app.errorJSON(w, err)
return
}
var payload jsonResponse
payload.Error = false
payload.Message = "logged via gRPC"
app.writeJSON(w, http.StatusOK, payload)
}

View File

@ -7,4 +7,15 @@ require (
github.com/go-chi/cors v1.2.1 github.com/go-chi/cors v1.2.1
) )
require github.com/rabbitmq/amqp091-go v1.10.0 require (
github.com/rabbitmq/amqp091-go v1.10.0
google.golang.org/grpc v1.66.0
google.golang.org/protobuf v1.34.1
)
require (
golang.org/x/net v0.26.0 // indirect
golang.org/x/sys v0.21.0 // indirect
golang.org/x/text v0.16.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240604185151-ef581f913117 // indirect
)

View File

@ -2,7 +2,21 @@ github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw=
github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/go-chi/cors v1.2.1 h1:xEC8UT3Rlp2QuWNEr4Fs/c2EAGVKBwy/1vHx3bppil4= github.com/go-chi/cors v1.2.1 h1:xEC8UT3Rlp2QuWNEr4Fs/c2EAGVKBwy/1vHx3bppil4=
github.com/go-chi/cors v1.2.1/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58= github.com/go-chi/cors v1.2.1/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/rabbitmq/amqp091-go v1.10.0 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw= github.com/rabbitmq/amqp091-go v1.10.0 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw=
github.com/rabbitmq/amqp091-go v1.10.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o= github.com/rabbitmq/amqp091-go v1.10.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
golang.org/x/net v0.26.0 h1:soB7SVo0PWrY4vPW/+ay0jKDNScG2X9wFeYlXIvJsOQ=
golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE=
golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws=
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240604185151-ef581f913117 h1:1GBuWVLM/KMVUv1t1En5Gs+gFZCNd360GGb4sSxtrhU=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240604185151-ef581f913117/go.mod h1:EfXuqaE1J41VCDicxHzUDm+8rk+7ZdXzHV0IhO/I6s0=
google.golang.org/grpc v1.66.0 h1:DibZuoBznOxbDQxRINckZcUvnCEvrW9pcWIE2yF9r1c=
google.golang.org/grpc v1.66.0/go.mod h1:s3/l6xSSCURdVfAnL+TqCNMyTDAGN6+lZeVxnZR128Y=
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=

View File

@ -0,0 +1,23 @@
syntax = "proto3";
package logs;
option go_package = "/logs";
message Log {
string name = 1;
string data = 2;
}
message LogRequest {
Log logEntry = 1;
}
message LogResponse {
string result = 1;
}
service LogService {
rpc WriteLog(LogRequest) returns (LogResponse);
}

View File

@ -12,6 +12,7 @@
<a id="logHttpBtn" class="btn btn-outline-secondary" href="javascript:void(0);">Test HTTP Log</a> <a id="logHttpBtn" class="btn btn-outline-secondary" href="javascript:void(0);">Test HTTP Log</a>
<a id="logRabbitBtn" class="btn btn-outline-secondary" href="javascript:void(0);">Test Rabbit Log</a> <a id="logRabbitBtn" class="btn btn-outline-secondary" href="javascript:void(0);">Test Rabbit Log</a>
<a id="logRpcBtn" class="btn btn-outline-secondary" href="javascript:void(0);">Test RPC Log</a> <a id="logRpcBtn" class="btn btn-outline-secondary" href="javascript:void(0);">Test RPC Log</a>
<a id="logGrpcBtn" class="btn btn-outline-secondary" href="javascript:void(0);">Test gRPC Log</a>
<a id="mailBtn" class="btn btn-outline-secondary" href="javascript:void(0);">Test Mail</a> <a id="mailBtn" class="btn btn-outline-secondary" href="javascript:void(0);">Test Mail</a>
<div id="output" class="mt-5" style="outline: 1px solid silver; padding: 2em;"> <div id="output" class="mt-5" style="outline: 1px solid silver; padding: 2em;">
@ -44,6 +45,7 @@
let logHttpBtn = document.getElementById("logHttpBtn"); let logHttpBtn = document.getElementById("logHttpBtn");
let logRabbitBtn = document.getElementById("logRabbitBtn"); let logRabbitBtn = document.getElementById("logRabbitBtn");
let logRpcBtn = document.getElementById("logRpcBtn"); let logRpcBtn = document.getElementById("logRpcBtn");
let logGrpcBtn = document.getElementById("logGrpcBtn");
let output = document.getElementById("output"); let output = document.getElementById("output");
let sent = document.getElementById("payload"); let sent = document.getElementById("payload");
let received = document.getElementById("received"); let received = document.getElementById("received");
@ -196,6 +198,38 @@
}); });
}); });
logGrpcBtn.addEventListener("click", () => {
const payload = {
action: "logGrpc",
log: {
name: "event",
data: "some kind of data",
}
};
const headers = new Headers();
headers.append("Content-Type", "application/json");
const body = {
method: 'POST',
body: JSON.stringify(payload),
headers: headers,
}
fetch("http:\/\/localhost:8080/handle", body)
.then((response) => response.json())
.then((data) => {
sent.innerHTML = JSON.stringify(payload, undefined, 4);
received.innerHTML = JSON.stringify(data, undefined, 4);
if (data.error) {
console.log(data.message);
output.innerHTML += `<br><strong>Error:</strong>: ${data.message}`;
} else {
output.innerHTML += `<br><strong>Response from broker service</strong>: ${data.message}`;
}
})
.catch((error) => {
output.innerHTML += "<br><br>Error: " + error;
});
});
mailBtn.addEventListener("click", () => { mailBtn.addEventListener("click", () => {
const payload = { const payload = {
action: "mail", action: "mail",

View File

@ -7,6 +7,7 @@ import (
"logger/data" "logger/data"
"logger/logs" "logger/logs"
"net" "net"
"time"
"google.golang.org/grpc" "google.golang.org/grpc"
) )
@ -20,6 +21,7 @@ func (l *LogServer) WriteLog(
ctx context.Context, ctx context.Context,
req *logs.LogRequest, req *logs.LogRequest,
) (*logs.LogResponse, error) { ) (*logs.LogResponse, error) {
now := time.Now()
input := req.GetLogEntry() input := req.GetLogEntry()
// write the log // write the log
@ -28,6 +30,7 @@ func (l *LogServer) WriteLog(
Data: input.Data, Data: input.Data,
} }
logEntry.Data += fmt.Sprintf(" received date %d", now.UnixMicro())
err := l.Models.LogEntry.Insert(logEntry) err := l.Models.LogEntry.Insert(logEntry)
if err != nil { if err != nil {
res := &logs.LogResponse{Result: "failed"} res := &logs.LogResponse{Result: "failed"}

View File

@ -15,6 +15,7 @@ type JSONPayload struct {
func (app *Config) WriteLog(w http.ResponseWriter, r *http.Request) { func (app *Config) WriteLog(w http.ResponseWriter, r *http.Request) {
// read json into var // read json into var
now := time.Now()
var requestPayload JSONPayload var requestPayload JSONPayload
err := app.readJSON(w, r, &requestPayload) err := app.readJSON(w, r, &requestPayload)
if err != nil { if err != nil {
@ -29,7 +30,6 @@ func (app *Config) WriteLog(w http.ResponseWriter, r *http.Request) {
Data: requestPayload.Data, Data: requestPayload.Data,
} }
now := time.Now()
event.Data += fmt.Sprintf(" received date %d", now.UnixMicro()) event.Data += fmt.Sprintf(" received date %d", now.UnixMicro())
log.Println("event", event) log.Println("event", event)