Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: try to write better code #115

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ charset = utf-8
trim_trailing_whitespace = true
indent_style = tab
indent_size = 2
max_line_length = 120
max_line_length = 100

[*.yaml]
indent_style = space
Expand Down
148 changes: 148 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
# https://golangci-lint.run/usage/configuration/#config-file
linters:
disable-all: true
enable:
- errcheck
- gosimple
- govet
- ineffassign
- unused

- errname
- exhaustive
- containedctx
- gocheckcompilerdirectives
- gochecknoinits
- goconst
- gocritic
- ireturn
- perfsprint
- prealloc
- protogetter
- sqlclosecheck
- whitespace
- goerr113
- goimports
- revive
- staticcheck
- vet
- forbidigo
- tagliatelle

run:
skip-dirs:
- ^api
- ^proto
- ^.git
- libs/grpc
linters-settings:
govet:
fieldalignment: 0
forbidigo:
forbid:
- p: ^time\.After$
msg: "time.After may leak resources. Use time.NewTimer instead."
revive:
severity: error
confidence: 0.8
enable-all-rules: true
rules:
# Disabled rules
- name: add-constant
disabled: true
- name: argument-limit
disabled: true
- name: bare-return
disabled: true
- name: banned-characters
disabled: true
- name: bool-literal-in-expr
disabled: true
- name: confusing-naming
disabled: true
- name: empty-lines
disabled: true
- name: error-naming
disabled: true
- name: errorf
disabled: true
- name: exported
disabled: true
- name: file-header
disabled: true
- name: function-length
disabled: true
- name: imports-blacklist
disabled: true
- name: increment-decrement
disabled: true
- name: line-length-limit
disabled: true
- name: max-public-structs
disabled: true
- name: nested-structs
disabled: true
- name: package-comments
disabled: true
- name: string-format
disabled: true
- name: unexported-naming
disabled: true
- name: unexported-return
disabled: true
- name: unused-parameter
disabled: true
- name: unused-receiver
disabled: true
- name: use-any
disabled: true
- name: var-naming
disabled: true
- name: empty-block
disabled: true
- name: flag-parameter
disabled: true

# Rule tuning
- name: cognitive-complexity
arguments:
- 25
- name: cyclomatic
arguments:
- 25
- name: function-result-limit
arguments:
- 5
- name: unhandled-error
arguments:
- "fmt.*"
- "bytes.Buffer.*"
- "strings.Builder.*"
tagliatelle:
# Check the struck tag name case.
case:
# Use the struct field name to check the name of the struct tag.
# Default: false
use-field-name: true
rules:
# Any struct tag type can be used.
# Support string case: `camel`, `pascal`, `kebab`, `snake`, `upperSnake`, `goCamel`, `goPascal`, `goKebab`, `goSnake`, `upper`, `lower`, `header`.
json: snake
yaml: snake
xml: snake
toml: snake

issues:
# Exclude cyclomatic and cognitive complexity rules for functional tests in the `tests` root directory.
exclude-rules:
- path: ^tests\/.+\.go
text: "(cyclomatic|cognitive)"
linters:
- revive
- path: _test\.go|^common/persistence\/tests\/.+\.go # Ignore things like err = errors.New("test error") in tests
linters:
- goerr113
- path: ^tools\/.+\.go
linters:
- goerr113
- revive
7 changes: 7 additions & 0 deletions .mockery.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
quiet: False
keeptree: True
disable-version-string: True
with-expecter: True
mockname: "{{.InterfaceName}}"
filename: "{{.MockName}}.go"
outpkg: mocks
171 changes: 32 additions & 139 deletions cmd/main.go
Original file line number Diff line number Diff line change
@@ -1,146 +1,39 @@
package main

import (
"context"
"log"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"

"github.com/getsentry/sentry-go"

"entgo.io/ent/dialect/sql"
"github.com/TheZeroSlave/zapsentry"
"github.com/lib/pq"
"github.com/satont/twitch-notifier/ent"
"github.com/satont/twitch-notifier/internal/config"
"github.com/satont/twitch-notifier/internal/db"
"github.com/satont/twitch-notifier/internal/message_sender"
"github.com/satont/twitch-notifier/internal/telegram"
"github.com/satont/twitch-notifier/internal/twitch"
"github.com/satont/twitch-notifier/internal/twitch_streams_cheker"
"github.com/satont/twitch-notifier/internal/types"
"github.com/satont/twitch-notifier/pkg/i18n"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
announcesender "github.com/satont/twitch-notifier/internal/announcesender/temporal"
i18nstore "github.com/satont/twitch-notifier/internal/i18n/store"
messagesender "github.com/satont/twitch-notifier/internal/messagesender/fx"
"github.com/satont/twitch-notifier/internal/pgx"
repositories "github.com/satont/twitch-notifier/internal/repository/fx"
thumbnailchecker "github.com/satont/twitch-notifier/internal/thumbnailchecker/temporal"
"github.com/satont/twitch-notifier/internal/twitchclient"
"github.com/satont/twitch-notifier/internal/twitchclient/twitchclientimpl"
"github.com/satont/twitch-notifier/pkg/config"
"github.com/satont/twitch-notifier/pkg/logger"
"go.uber.org/fx"
)

func createEnt(cfg *config.Config) (*ent.Client, error) {
pgConnectionUrl, err := pq.ParseURL(cfg.DatabaseUrl)
if err != nil {
log.Fatalln(err)
}

drv, err := sql.Open("postgres", pgConnectionUrl)
if err != nil {
return nil, err
}

db := drv.DB()
db.SetMaxIdleConns(2)
db.SetMaxOpenConns(10)
db.SetConnMaxLifetime(time.Hour)
return ent.NewClient(ent.Driver(drv)), nil
}

func main() {
wd, err := os.Getwd()
if err != nil {
log.Fatalln(err)
}

cfg, err := config.NewConfig(nil)
if err != nil {
log.Fatalln(err)
}

logger, _ := zap.NewDevelopment()

if cfg.SentryDsn != "" {
sentryClient, err := sentry.NewClient(
sentry.ClientOptions{
Dsn: cfg.SentryDsn,
EnableTracing: true,
},
)
if err != nil {
log.Fatalln(err)
}
logger = modifyToSentryLogger(logger, sentryClient)
defer sentry.Flush(2 * time.Second)
}

zap.ReplaceGlobals(logger)

client, err := createEnt(cfg)
if err != nil {
logger.Sugar().Fatalln("failed opening connection to postgres: %v", err)
}
// Run the auto migration tool.
// if err := client.Schema.Create(context.Background()); err != nil {
// log.Fatalf("failed creating schema resources: %v", err)
// }

twitchService, err := twitch.NewTwitchService(cfg.TwitchClientId, cfg.TwitchClientSecret)
if err != nil {
logger.Sugar().Fatalln(err)
}

i18, err := i18n.NewI18n(filepath.Join(wd, "locales"))
if err != nil {
logger.Sugar().Fatalln(err)
}

services := &types.Services{
Config: cfg,
Twitch: twitchService,
Chat: db.NewChatEntRepository(client),
Channel: db.NewChannelEntService(client),
Follow: db.NewFollowService(client),
Stream: db.NewStreamEntService(client),
I18N: i18,
}

ctx, cancel := context.WithCancel(context.Background())

tg := telegram.NewTelegram(ctx, cfg.TelegramToken, services)
tg.StartPolling(ctx)

sender := message_sender.NewMessageSender(tg.Client)

checker := twitch_streams_cheker.NewTwitchStreamChecker(services, sender, nil)
checker.StartPolling(ctx)

logger.Sugar().Info("Started")
exitSignal := make(chan os.Signal, 1)
signal.Notify(exitSignal, syscall.SIGINT, syscall.SIGTERM)
<-exitSignal
logger.Sugar().Info("Closing...")
cancel()
_ = client.Close()
}

func modifyToSentryLogger(log *zap.Logger, client *sentry.Client) *zap.Logger {
cfg := zapsentry.Configuration{
Level: zapcore.ErrorLevel, // when to send message to sentry
EnableBreadcrumbs: true, // enable sending breadcrumbs to Sentry
BreadcrumbLevel: zapcore.InfoLevel, // at what level should we sent breadcrumbs to sentry
Tags: map[string]string{
"component": "system",
},
}
core, err := zapsentry.NewCore(cfg, zapsentry.NewSentryClientFromClient(client))

// in case of err it will return noop core. so we can safely attach it
if err != nil {
log.Warn("failed to init zap", zap.Error(err))
}

log = zapsentry.AttachCoreToLogger(core, log)

// to use breadcrumbs feature - create new scope explicitly
// and attach after attaching the core
return log.With(zapsentry.NewScope())
fx.New(
// fx.NopLogger,
fx.Provide(
config.New,
logger.FxOption,
fx.Annotate(
i18nstore.New,
fx.As(new(i18nstore.I18nStore)),
),
pgx.New,
fx.Annotate(
twitchclientimpl.New,
fx.As(new(twitchclient.TwitchClient)),
),
),
repositories.Module,
thumbnailchecker.Module,
messagesender.Module,
announcesender.Module,
fx.Invoke(pgx.New),
).Run()
}
3 changes: 0 additions & 3 deletions ent/generate.go

This file was deleted.

Loading