Skip to content

Commit

Permalink
Refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
robertobadjio committed Oct 13, 2024
1 parent cf916ad commit 1d88fbb
Show file tree
Hide file tree
Showing 24 changed files with 326 additions and 285 deletions.
5 changes: 1 addition & 4 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
.idea
.env
config/config.yaml

deploy/deploy.config
.env
51 changes: 51 additions & 0 deletions .golangci.pipeline.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# More info on config here: https://golangci-lint.run/usage/configuration/#config-file
run:
concurrency: 8
timeout: 10m
issues-exit-code: 1
tests: true
issues:
exclude-files:
- \.pb\.go$
- \.pb\.gw\.go$
exclude-dirs:
- bin
- vendor
- var
- tmp
- .cache

output:
formats: colored-line-number
print-issued-lines: true
print-linter-name: true

linters-settings:
govet:
shadow: true
dupl:
threshold: 100
goconst:
min-len: 2
min-occurrences: 2

linters:
disable-all: true
enable:
- errcheck
- goconst
- goimports
- gosec
- govet
- ineffassign
- revive
- typecheck
- unused

issues:
exclude-use-default: false
exclude:
- G104 # _ instead of err checks
- exported func .* returns unexported type .*, which can be annoying to use
- should have a package comment
- don't use an underscore in package name
29 changes: 17 additions & 12 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,32 @@

DOCKER_COMPOSE ?= docker compose -f docker-compose.yml

include .env
ENV ?= dev

ifdef ENV
ifneq "$(ENV)" ""
ifneq ("$(wildcard docker-compose.$(ENV).yml)","")
DOCKER_COMPOSE := $(DOCKER_COMPOSE) -f docker-compose.$(ENV).yml
endif
endif
endif

export GOOS=linux
export GOARCH=amd64

help: ## Help
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(firstword $(MAKEFILE_LIST)) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'

fmt: ## Automatically format source code
go fmt ./...
.PHONY:fmt

lint: fmt ## Check code (lint)
golangci-lint run ./... --config .golangci.pipeline.yaml
.PHONY:lint

vet: fmt ## Check code (vet)
go vet -vettool=$(which shadow) ./...
.PHONY:vet

vet-shadow: fmt ## Check code with detect shadow (vet)
go vet -vettool=$(which shadow) ./...
.PHONY:vet

build: ## Build service containers
$(DOCKER_COMPOSE) build

up: ## Start services
up: vet ## Start services
$(DOCKER_COMPOSE) up -d $(SERVICES)

down: ## Down services
Expand Down
20 changes: 11 additions & 9 deletions cmd/notifier/notifier.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,19 @@ package main

import (
"context"
"github.com/go-kit/kit/log"
_ "github.com/lib/pq"
"net/http"
"os"
"tgtime-notifier/internal/background"
"tgtime-notifier/internal/config"
kafkaLib "tgtime-notifier/internal/kafka"
"tgtime-notifier/internal/notifier/telegram"
"time"

"github.com/go-kit/kit/log"
_ "github.com/lib/pq"
"github.com/robertobadjio/tgtime-notifier/internal/background"
"github.com/robertobadjio/tgtime-notifier/internal/config"
kafkaLib "github.com/robertobadjio/tgtime-notifier/internal/kafka"
"github.com/robertobadjio/tgtime-notifier/internal/notifier/telegram"
)

const CheckSecondsInOffice = 10
const сheckSecondsInOffice = 10

func main() {
var logger log.Logger
Expand All @@ -31,6 +32,7 @@ func main() {

updates := tgNotifier.GetBot().ListenForWebhook("/" + cfg.WebHookPath)
go func() {
// TODO: timeouts https://kovardin.ru/articles/go/rukovodstvo-po-nethttp-taimautam-v-go/
err := http.ListenAndServe(":8441", nil) // TODO: const
if err != nil {
_ = logger.Log("telegram", "updates", "type", "serve", "msg", err)
Expand All @@ -49,7 +51,7 @@ func startCheckInOffice(
ctx context.Context,
cfg *config.Config,
logger log.Logger,
tgNotifier *telegram.TelegramNotifier,
tgNotifier *telegram.Notifier,
) {
f := func() {
kafka := kafkaLib.NewKafka(logger, cfg.KafkaHost, cfg.KafkaPort)
Expand All @@ -58,7 +60,7 @@ func startCheckInOffice(
_ = logger.Log("kafka", "consume", "type", "in office message", "msg", err)
}
}
bc := background.NewBackground(time.Duration(CheckSecondsInOffice)*time.Second, f)
bc := background.NewBackground(time.Duration(сheckSecondsInOffice)*time.Second, f)
bc.Start()
}

Expand Down
45 changes: 0 additions & 45 deletions docker-compose.dev.yml

This file was deleted.

File renamed without changes.
44 changes: 43 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
services:
tgtime-notifier-app:
image: ghcr.io/tgtime-notifier:master
build:
context: .
dockerfile: ./docker/app/Dockerfile
Expand All @@ -9,6 +8,49 @@ services:
- "1122:8080"
networks:
- tgtime-notifier-network
depends_on:
tgtime-api:
condition: service_healthy
tgtime-api:
build:
context: .
dockerfile: ./docker/tgtime-api/Dockerfile
ports:
- "1080:1080"
environment:
MOCKSERVER_INITIALIZATION_JSON_PATH: /config/initializerJson.json
MOCKSERVER_LOG_LEVEL: INFO
MOCKSERVER_PROPERTY_FILE: /config/mockserver.properties
volumes:
- ./docker/tgtime-api/config:/config
- ./docker/tgtime-api/config/mockserver.properties:/config/mockserver.properties
networks:
- tgtime-notifier-network
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:1080/liveness/probe"]
interval: 10s
timeout: 10s
retries: 5
zookeeper:
image: confluentinc/cp-zookeeper:latest
environment:
- ZOOKEEPER_CLIENT_PORT=${ZOOKEEPER_PORT}
networks:
- tgtime-notifier-network
kafka:
image: confluentinc/cp-kafka:latest
container_name: kafka
depends_on:
- zookeeper
environment:
- KAFKA_ZOOKEEPER_CONNECT=zookeeper:${ZOOKEEPER_PORT}
- KAFKA_LOG_RETENTION_MS=10000
- KAFKA_CLEANUP_POLICY=delete
- KAFKA_CLEANUP_ENABLE=true
- KAFKA_LOG_RETENTION_CHECK_INTERVAL_MS=5000
- KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://kafka:${ZOOKEEPER_PORT}
networks:
- tgtime-notifier-network

networks:
tgtime-notifier-network:
Expand Down
2 changes: 1 addition & 1 deletion docker/app/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM golang:1.22-alpine AS build
FROM golang:1.23-alpine AS build

RUN apk update && apk add tzdata

Expand Down
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module tgtime-notifier
module github.com/robertobadjio/tgtime-notifier

go 1.22.0
go 1.23.0

require (
github.com/go-kit/kit v0.13.0
Expand Down
66 changes: 34 additions & 32 deletions internal/aggregator/aggregator.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,64 +3,66 @@ package aggregator
import (
"context"
"fmt"
"github.com/go-kit/kit/log"
pb "github.com/robertobadjio/tgtime-aggregator/api/v1/pb/aggregator"

"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"tgtime-notifier/internal/config"
"time"

"github.com/go-kit/kit/log"
pb "github.com/robertobadjio/tgtime-aggregator/api/v1/pb/aggregator"
"github.com/robertobadjio/tgtime-notifier/internal/config"
)

// Client gRPC-клиент для подключения к сервису Агрегатор
type Client struct {
cfg *config.Config
logger log.Logger
client pb.AggregatorClient
}

// NewClient Конструктор gRPC-клиента для подключения к сервису Агрегатор
func NewClient(cfg config.Config, logger log.Logger) *Client {
return &Client{cfg: &cfg, logger: logger}
}

func (tc Client) GetTimeSummary(ctx context.Context, macAddress, date string) (*pb.GetTimeSummaryResponse, error) {
client, err := grpc.NewClient(
tc.buildAddress(),
conn, _ := grpc.NewClient(
buildAddress(cfg.TgTimeAPIHost, cfg.TgTimeAPIPort),
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
return nil, fmt.Errorf("could not connect: %v", err)
}
defer func() { _ = client.Close() }()

timeAggregatorClient := pb.NewAggregatorClient(client)
ctxTemp, cancel := context.WithTimeout(ctx, 120*time.Second)
defer cancel()
return &Client{cfg: &cfg, logger: logger, client: pb.NewAggregatorClient(conn)}
}

// GetTimeSummary Получение времени сотрудника
func (tc Client) GetTimeSummary(
ctx context.Context,
macAddress, date string,
) (*pb.GetTimeSummaryResponse, error) {
filters := make([]*pb.Filter, 0, 2)
filters = append(filters, &pb.Filter{Key: "mac_address", Value: macAddress})
filters = append(filters, &pb.Filter{Key: "date", Value: date})
timeSummary, err := timeAggregatorClient.GetTimeSummary(
ctxTemp,
timeSummary, err := tc.client.GetTimeSummary(
ctx,
&pb.GetTimeSummaryRequest{Filters: filters},
)

if err != nil {
if s, ok := status.FromError(err); ok {
// Handle the error based on its status code
if s.Code() == codes.NotFound {
return nil, fmt.Errorf("requested resource not found")
} else {
return nil, fmt.Errorf("RPC error: %v, %v", s.Message(), ctxTemp.Err())
}
} else {
// Handle non-RPC errors
return nil, fmt.Errorf("Non-RPC error: %v", err)
}
return nil, handleError(ctx, err)
}

return timeSummary, nil
}

func (tc Client) buildAddress() string {
return fmt.Sprintf("%s:%s", tc.cfg.TgTimeAggregatorHost, tc.cfg.TgTimeAggregatorPort)
func handleError(ctx context.Context, err error) error {
if s, ok := status.FromError(err); ok {
// Handle the error based on its status code
if s.Code() == codes.NotFound {
return fmt.Errorf("requested resource not found")
}
return fmt.Errorf("RPC error: %v, %v", s.Message(), ctx.Err())
}

return fmt.Errorf("Non-RPC error: %v", err)
}

func buildAddress(host, port string) string {
return fmt.Sprintf("%s:%s", host, port)
}
Loading

0 comments on commit 1d88fbb

Please sign in to comment.