Skip to content

Commit

Permalink
feat(pkg/discord): add discord package (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
aqyuki authored Dec 24, 2024
1 parent df32bc4 commit a0e15a3
Show file tree
Hide file tree
Showing 5 changed files with 246 additions and 2 deletions.
13 changes: 11 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@ module github.com/aqyuki/felm

go 1.23.4

require go.uber.org/zap v1.27.0
require (
github.com/bwmarrin/discordgo v0.28.1
github.com/rs/xid v1.6.0
go.uber.org/zap v1.27.0
)

require go.uber.org/multierr v1.10.0 // indirect
require (
github.com/gorilla/websocket v1.4.2 // indirect
go.uber.org/multierr v1.10.0 // indirect
golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b // indirect
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68 // indirect
)
14 changes: 14 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
github.com/bwmarrin/discordgo v0.28.1 h1:gXsuo2GBO7NbR6uqmrrBDplPUx2T3nzu775q/Rd1aG4=
github.com/bwmarrin/discordgo v0.28.1/go.mod h1:NJZpH+1AfhIcyQsPeuBKsUtYrRnjkyu0kIVMCHkZtRY=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
Expand All @@ -10,5 +16,13 @@ go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b h1:7mWr3k41Qtv8XlltBkDkl8LoP3mpSgBW8BUoxtEdbXg=
golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68 h1:nxC68pudNYkKU6jWhgrqdreuFiOQWj1Fs7T3VrH4Pjw=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
165 changes: 165 additions & 0 deletions pkg/discord/conn.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
package discord

import (
"context"
"fmt"
"time"

"github.com/aqyuki/felm/pkg/logging"
"github.com/aqyuki/felm/pkg/trace"
"github.com/bwmarrin/discordgo"
"go.uber.org/zap"
)

// MessageCreateHandler is a function that handles a message creation event.
type MessageCreateHandler func(context.Context, *discordgo.Session, *discordgo.MessageCreate) error

// MinimumHandlerTimeout is the minimum timeout for the handler.
const MinimumHandlerTimeout = 5 * time.Second

// Option is a function that configures a Conn.
type Option func(*Conn)

// WithHandlerTimeout sets the timeout for the handler.
func WithHandlerTimeout(timeout time.Duration) Option {
return func(c *Conn) {
if timeout < MinimumHandlerTimeout {
timeout = MinimumHandlerTimeout
}
c.handlerDeadline = timeout
}
}

// WithMessageCreateHandler adds a handler for the message creation event.
func WithMessageCreateHandler(handler MessageCreateHandler) Option {
return func(c *Conn) {
c.messageCreateHandlers = append(c.messageCreateHandlers, handler)
}
}

// WithBaseContext sets the base context for the handler.
func WithBaseContext(ctx context.Context) Option {
return func(c *Conn) {
if ctx != nil {
c.baseContext = ctx
}
}
}

// Conn manages the session with the Discord API.
type Conn struct {
session *discordgo.Session
messageCreateHandlers []MessageCreateHandler
preClose []func()

// handlerDeadline is the timeout for the handler.
handlerDeadline time.Duration

// baseContext is the base context for the handler.
baseContext context.Context
}

func defaultConn() *Conn {
return &Conn{
session: nil,
messageCreateHandlers: make([]MessageCreateHandler, 0),
handlerDeadline: MinimumHandlerTimeout,
baseContext: context.Background(),
}
}

func NewConn(token string, option ...Option) *Conn {
conn := defaultConn()

// discordgo#New does not return an error, so don't handle it.
session, _ := discordgo.New("Bot " + token)
conn.session = session

// apply options
for _, opt := range option {
opt(conn)
}
return conn
}

// Open opens a connection to the Discord API.
func (c *Conn) Open() error {
// register handlers and save the function to unregister them later.
for _, handler := range c.messageCreateHandlers {
fn := c.session.AddHandler(buildMessageCreateHandler(c.baseContext, handler))
c.preClose = append(c.preClose, fn)
}

if err := c.session.Open(); err != nil {
return fmt.Errorf("error was occurred when trying to connect to discord: %w", err)
}
return nil
}

// Close closes the connection to the Discord API.
func (c *Conn) Close() error {
// unregister handlers
for _, fn := range c.preClose {
fn()
}
if err := c.session.Close(); err != nil {
return fmt.Errorf("error was occurred when trying to disconnect from discord: %w", err)
}
return nil
}

// buildMessageCreateHandler creates a handler for the message creation event.
func buildMessageCreateHandler(ctx context.Context, handler MessageCreateHandler) func(*discordgo.Session, *discordgo.MessageCreate) {
return func(s *discordgo.Session, m *discordgo.MessageCreate) {
start := time.Now()

// attach trace id to the context
ctx = trace.WithTraceID(ctx)
traceID := trace.AcquireTraceID(ctx)

// debug information
logger := logging.FromContext(ctx)
logger.Debug("MessageCreate event received",
zap.String("trace_id", traceID),
zap.Dict("message",
zap.String("guild_id", m.GuildID),
zap.String("channel_id", m.ChannelID),
zap.String("message_id", m.ID),
zap.String("author_id", m.Author.ID),
),
)

// create a new context from the base context with the deadline.
ctx, cancel := context.WithTimeout(ctx, MinimumHandlerTimeout)
defer cancel()

// execute the handler in a other goroutine.
errCh := make(chan error)
go func() {
errCh <- handler(ctx, s, m)
}()

// wait for the handler to finish.
// if the handler does not finish in time, cancel the context.
select {
case <-ctx.Done():
logger.Warn("handler timed out",
zap.String("trace_id", traceID),
)
case err := <-errCh:
if err != nil {
logger.Error("error occurred in handler",
zap.String("trace_id", traceID),
zap.Error(err),
)
}
}

// debug information
latency := time.Since(start)
logger.Debug("MessageCreate event handled",
zap.String("trace_id", traceID),
zap.Duration("latency", latency),
)
}
}
25 changes: 25 additions & 0 deletions pkg/trace/trace.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package trace

import (
"context"
"errors"

"github.com/rs/xid"
)

type contextKey string

const traceIDKey = contextKey("traceID")

var ErrTraceIDNotFound = errors.New("trace ID not found")

func WithTraceID(ctx context.Context) context.Context {
return context.WithValue(ctx, traceIDKey, xid.New().String())
}

func AcquireTraceID(ctx context.Context) string {
if traceID, ok := ctx.Value(traceIDKey).(string); ok {
return traceID
}
return ""
}
31 changes: 31 additions & 0 deletions pkg/trace/trace_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package trace

import (
"context"
"testing"
)

func TestTraceID(t *testing.T) {
t.Parallel()

t.Run("expect to return a new context with a trace ID", func(t *testing.T) {
t.Parallel()

ctx := WithTraceID(context.Background())
traceID := AcquireTraceID(ctx)

if traceID == "" {
t.Errorf("expected trace ID to be not empty, but got empty")
}
})

t.Run("expect to return a empty string when trace ID is not found", func(t *testing.T) {
t.Parallel()

traceID := AcquireTraceID(context.Background())

if traceID != "" {
t.Errorf("expected trace ID to be empty, but got %s", traceID)
}
})
}

0 comments on commit a0e15a3

Please sign in to comment.