From 544298eb991fe1b281986842c7bb09eae4f1d5d9 Mon Sep 17 00:00:00 2001
From: Piotr Biernat <keedosn@gmail.com>
Date: Sat, 20 Jul 2024 19:23:18 +0200
Subject: [PATCH] refactor, TLS support, v0.5

---
 .app.config                   | 14 +++++++
 .env.dist                     |  2 +-
 Dockerfile.target             |  5 ++-
 bin/entrypoint.sh             |  2 +-
 src/cmd/migrate/main.go       |  2 +-
 src/go.mod                    |  2 +-
 src/go.sum                    |  4 +-
 src/internal/server/config.go |  2 +-
 src/internal/server/server.go | 12 +++++-
 src/internal/worker/worker.go | 70 +++++++++++++++++++++--------------
 10 files changed, 76 insertions(+), 39 deletions(-)
 create mode 100644 .app.config

diff --git a/.app.config b/.app.config
new file mode 100644
index 0000000..b0455ba
--- /dev/null
+++ b/.app.config
@@ -0,0 +1,14 @@
+{
+	"ID": "order",
+	"Name": "order",
+	"Address": "__IP__",
+	"Tags": ["order-svc", "order", "https", "service"],
+	"Port": 443,
+	"Connect": {
+		"Native": true
+	},
+	"Check": {
+		"TCP": "__IP__:443",
+		"DeregisterCriticalServiceAfter": "10s"
+	}
+}
\ No newline at end of file
diff --git a/.env.dist b/.env.dist
index ab4da55..5e442c4 100644
--- a/.env.dist
+++ b/.env.dist
@@ -1,4 +1,4 @@
-SERVER_ADDR=:80
+SERVER_ADDR=:443
 
 APP_NAME=order-svc
 APP_DOMAIN=order.service.ego.io
diff --git a/Dockerfile.target b/Dockerfile.target
index a934e6f..1f0475d 100644
--- a/Dockerfile.target
+++ b/Dockerfile.target
@@ -21,13 +21,14 @@ WORKDIR /
 COPY --from=builder $BIN_OUTPUT /app
 COPY --from=builder /go/bin/migrate /bin/migrate
 COPY --from=builder /go/bin/health /bin/health
-COPY .env.dist /.env
+COPY .env.docker /.env
+COPY ./.app.config /
 COPY ./bin /bin
 RUN chmod 755 /bin/entrypoint.sh /bin/migrate.sh
 
 RUN apk add curl
 
-EXPOSE 80
+EXPOSE 443
 
 ENTRYPOINT ["entrypoint.sh"]
 CMD ["sh", "-c", "/app"]
diff --git a/bin/entrypoint.sh b/bin/entrypoint.sh
index 44acbde..764b78e 100755
--- a/bin/entrypoint.sh
+++ b/bin/entrypoint.sh
@@ -21,7 +21,7 @@ waitForService "api-registry:8500"
 waitForService "postgres-db:5432"
 waitForService "api-eventbus:5672"
 waitForService "api-logger:24224"
-waitForService "basket-svc:80"
+waitForService "basket-svc:443"
 
 # run migrations
 migrate.sh
diff --git a/src/cmd/migrate/main.go b/src/cmd/migrate/main.go
index 7002eac..c504aed 100644
--- a/src/cmd/migrate/main.go
+++ b/src/cmd/migrate/main.go
@@ -55,7 +55,7 @@ func main() {
 		log.Fatalf("Error parsing logger addr: %s. Err: %v", c.LoggerAddr, err)
 	}
 
-	logger, err := fluentd.NewLogger(c.Base.GetAppFullName(), logHost, logPort) // @Refactor NewLogger return (logger, error)
+	logger, err := fluentd.NewLogger(c.GetAppFullName(), logHost, logPort) // @Refactor NewLogger return (logger, error)
 	if err != nil {
 		log.Fatalf("Error connecting to %s:%d. Err: %v", logHost, logPort, err)
 	}
diff --git a/src/go.mod b/src/go.mod
index baa7128..7dbd68c 100644
--- a/src/go.mod
+++ b/src/go.mod
@@ -4,7 +4,7 @@ go 1.18
 
 require (
 	git.pbiernat.io/egommerce/api-entities v0.2.3
-	git.pbiernat.io/egommerce/go-api-pkg v0.2.88
+	git.pbiernat.io/egommerce/go-api-pkg v0.3.18
 	github.com/georgysavva/scany/v2 v2.0.0
 	github.com/go-pg/migrations/v8 v8.1.0
 	github.com/go-pg/pg/v10 v10.10.7
diff --git a/src/go.sum b/src/go.sum
index 2b583aa..71deaec 100644
--- a/src/go.sum
+++ b/src/go.sum
@@ -37,8 +37,8 @@ cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9
 dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
 git.pbiernat.io/egommerce/api-entities v0.2.3 h1:mR6EYfZkAzh4teydb7KXDBWoxwVW3qasnmmH5J3mnas=
 git.pbiernat.io/egommerce/api-entities v0.2.3/go.mod h1:INXAG5x4+i+vNwg1NpfPHiDW8nY1kn1K7pgLOtX+/I0=
-git.pbiernat.io/egommerce/go-api-pkg v0.2.88 h1:xya/39BnFeha3Oc76ad/ppoQd6AstTGQd87Qszamr1A=
-git.pbiernat.io/egommerce/go-api-pkg v0.2.88/go.mod h1:XIy2mmvRNIzQmYIUAcDZafhRPxTQFS2HDmsK7ZQ6980=
+git.pbiernat.io/egommerce/go-api-pkg v0.3.18 h1:0+C9BMsllrNvRbh4kb7dJ5lrzP1Lc7J4pb+KV76YrXk=
+git.pbiernat.io/egommerce/go-api-pkg v0.3.18/go.mod h1:XIy2mmvRNIzQmYIUAcDZafhRPxTQFS2HDmsK7ZQ6980=
 github.com/Azure/azure-sdk-for-go v44.0.0+incompatible h1:e82Yv2HNpS0kuyeCrV29OPKvEiqfs2/uJHic3/3iKdg=
 github.com/Azure/go-autorest v14.2.0+incompatible h1:V5VMDjClD3GiElqLWO7mz2MxNAK/vTfRHdAubSIPRgs=
 github.com/Azure/go-autorest/autorest v0.11.18 h1:90Y4srNYrwOtAgVo3ndrQkTYn6kf1Eg/AjTFJ8Is2aM=
diff --git a/src/internal/server/config.go b/src/internal/server/config.go
index b94d787..8419411 100644
--- a/src/internal/server/config.go
+++ b/src/internal/server/config.go
@@ -18,7 +18,7 @@ const (
 	defEventBusURL      = "amqp://guest:guest@api-eventbus:5672"
 	defKVNmspc          = "dev.egommerce/service/order"
 	defLoggerAddr       = "api-logger:24224"
-	defNetAddr          = ":80"
+	defNetAddr          = ":443"
 	defMongoDbURL       = "mongodb://mongodb:12345678@mongo-db:27017"
 	defPathPrefix       = "/order"
 	defRegistryAddr     = "api-registry:8500"
diff --git a/src/internal/server/server.go b/src/internal/server/server.go
index 6799c72..1bfa7b6 100644
--- a/src/internal/server/server.go
+++ b/src/internal/server/server.go
@@ -1,6 +1,8 @@
 package server
 
 import (
+	"crypto/tls"
+	"log"
 	"net"
 	"time"
 
@@ -19,7 +21,7 @@ type (
 		*fiber.App
 
 		ID       string
-		addr     string // e.g. "127.0.0.1:80"
+		addr     string // e.g. "127.0.0.1:443"
 		handlers map[string]any
 	}
 	HeaderRequestID struct {
@@ -47,8 +49,14 @@ func (s *Server) Start() error {
 	SetupRouter(s)
 
 	// fmt.Printf("Starting server at: %s...\n", s.addr)
+	cer, err := tls.LoadX509KeyPair("certs/client.crt", "certs/client.key")
+	if err != nil {
+		log.Fatal(err)
+	}
+	tlsCnf := &tls.Config{Certificates: []tls.Certificate{cer}}
+
 	ln, _ := net.Listen("tcp", s.addr)
-	// ln = tls.NewListener(ln, s.App.Server().TLSConfig)
+	ln = tls.NewListener(ln, tlsCnf)
 
 	return s.Listener(ln)
 }
diff --git a/src/internal/worker/worker.go b/src/internal/worker/worker.go
index e70b51f..8359e8e 100644
--- a/src/internal/worker/worker.go
+++ b/src/internal/worker/worker.go
@@ -38,34 +38,9 @@ func New(c *Config) *Worker {
 }
 
 func (w *Worker) Start() error {
-	// Init
-	err := rabbitmq.NewExchange(w.GetEventBus(), w.cnf.EventBusExchange)
-	if err != nil {
-		w.GetLogger().Log("Failed to declare EventBus exchange: %v\n", err)
-		fmt.Printf("Failed to declare EventBus exchange: %v\n", err)
+	setupQueues(w)
 
-		os.Exit(1)
-	}
-
-	_, err = w.GetEventBus().QueueDeclare(
-		w.cnf.EventBusQueue, // name
-		false,               // durable
-		false,               // delete when unused
-		false,               // exclusive
-		false,               // no-wait
-		nil,                 // arguments
-	)
-	if err != nil {
-		w.GetLogger().Log("Failed to declare EventBus queue: %v\n", err)
-		fmt.Printf("Failed to declare EventBus queue: %v\n", err)
-
-		os.Exit(1)
-	}
-
-	// 		// w.bindQueues()
-	rabbitmq.BindQueueToExchange(w.GetEventBus(), w.cnf.EventBusQueue, w.cnf.EventBusExchange, "basket.order.basketCheckout")
-
-	err = w.doWork(w.doWrkUntil)
+	err := w.doWork(w.doWrkUntil)
 	if err != nil {
 		log.Fatalf("Failed to start worker: %s. Reason: %v\n", w.ID, err)
 		close(w.doWrkUntil)
@@ -99,6 +74,8 @@ func (w *Worker) RegisterHandler(name string, fn func() any) {
 func (w *Worker) OnShutdown() {
 	w.GetLogger().Log("Worker %s is going down...", w.ID)
 	// fmt.Printf("Worker %s is going down...\n", w.ID)
+
+	unbindQueues(w)
 	w.GetEventBus().Close()
 	w.GetDatabase().Close()
 	w.GetLogger().Log("Gone.")
@@ -161,6 +138,7 @@ func (w *Worker) processMsg(srvc *service.OrderService, m amqp.Delivery) {
 	msg, err := rabbitmq.Deserialize(m.Body)
 	if err != nil {
 		w.GetLogger().Log("Deserialization error: %v\n", err)
+		fmt.Printf("Deserialization error: %v\n", err)
 		m.Reject(false)
 
 		return
@@ -171,6 +149,7 @@ func (w *Worker) processMsg(srvc *service.OrderService, m amqp.Delivery) {
 	// reqID := (data["request_id"]).(string) // FIXME Check input params!
 
 	w.GetLogger().Log("Processing message \"%s\" with data: %v\n", name, data)
+	fmt.Printf("Processing message \"%s\" with data: %v\n", name, data)
 
 	var ok = false
 	switch true { // Refactor -> use case for polymorphism
@@ -197,10 +176,45 @@ func (w *Worker) processMsg(srvc *service.OrderService, m amqp.Delivery) {
 	ok, _ = rnr.run(data)
 	if ok {
 		w.GetLogger().Log("Successful executed message \"%s\"\n", name)
+		fmt.Printf("Successful executed message \"%s\"\n", name)
 		m.Ack(false)
 		return
 	}
 
-	w.GetLogger().Log("Error processing \"%s\": %s (%v)", name, err.Error(), err)
+	w.GetLogger().Log("Error processing \"%s\": %v", name, err)
+	fmt.Printf("Error processing \"%s\": %v\n", name, err)
 	m.Reject(false) // FIXME: or Nack(repeat until success - maybe message shout know...?
 }
+
+func setupQueues(w *Worker) {
+	err := rabbitmq.NewExchange(w.GetEventBus(), w.cnf.EventBusExchange)
+	if err != nil {
+		w.GetLogger().Log("Failed to declare EventBus exchange: %v\n", err)
+		fmt.Printf("Failed to declare EventBus exchange: %v\n", err)
+
+		os.Exit(1)
+	}
+
+	args := amqp.Table{}
+	args["x-message-ttl"] = 5
+	_, err = w.GetEventBus().QueueDeclare(
+		w.cnf.EventBusQueue, // name
+		true,                // durable
+		false,               // delete when unused
+		false,               // exclusive
+		false,               // no-wait
+		args,                // arguments
+	)
+	if err != nil {
+		w.GetLogger().Log("Failed to declare EventBus queue: %v\n", err)
+		fmt.Printf("Failed to declare EventBus queue: %v\n", err)
+
+		os.Exit(1)
+	}
+
+	rabbitmq.BindQueueToExchange(w.GetEventBus(), w.cnf.EventBusQueue, w.cnf.EventBusExchange, "basket.order.basketCheckout")
+}
+
+func unbindQueues(w *Worker) {
+	w.GetEventBus().QueueUnbind(w.cnf.EventBusQueue, "basket.order.basketCheckout", w.cnf.EventBusExchange, nil)
+}