@ -7,10 +7,8 @@ import (
"flag"
"flag"
"fmt"
"fmt"
"net/http"
"net/http"
"net/url"
"os"
"os"
"os/signal"
"os/signal"
"runtime/pprof"
"sort"
"sort"
"strconv"
"strconv"
"strings"
"strings"
@ -19,21 +17,9 @@ import (
"github.com/bwmarrin/discordgo"
"github.com/bwmarrin/discordgo"
_ "github.com/mattn/go-sqlite3"
_ "github.com/mattn/go-sqlite3"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/rs/zerolog/log"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.24.0"
"go.opentelemetry.io/otel/trace"
"go.wperron.io/flydetector"
"go.wperron.io/sqliteexporter"
"go.wperron.io/themis"
"go.wperron.io/themis"
"go.wperron.io/themis/correlation"
)
)
const (
const (
@ -41,52 +27,19 @@ const (
)
)
var (
var (
dbFile = flag . String ( "db" , "" , "SQlite database file path." )
dbFile = flag . String ( "db" , "" , "SQlite database file path" )
debug = flag . Bool ( "debug" , false , "Set log level to DEBUG." )
cpuProfile = flag . String ( "cpuprofile" , "" , "Output file for pprof profiling." )
store * themis . Store
store * themis . Store
tracer trace . Tracer
propagator = propagation . TraceContext { }
)
)
type Handler func ( ctx context . Context , s * discordgo . Session , i * discordgo . InteractionCreate ) error
type Handler func ( s * discordgo . Session , i * discordgo . InteractionCreate )
func main ( ) {
func main ( ) {
log . Info ( ) . Msg ( "startup." )
start := time . Now ( )
ctx , cancel := signal . NotifyContext ( context . Background ( ) , syscall . SIGTERM , syscall . SIGKILL , syscall . SIGINT )
ctx , cancel := signal . NotifyContext ( context . Background ( ) , syscall . SIGTERM , syscall . SIGKILL , syscall . SIGINT )
defer cancel ( )
defer cancel ( )
flag . Parse ( )
flag . Parse ( )
zerolog . SetGlobalLevel ( zerolog . InfoLevel )
if * debug {
zerolog . SetGlobalLevel ( zerolog . DebugLevel )
}
log . Logger = log . Output ( zerolog . ConsoleWriter { Out : os . Stdout } )
log . Logger = log . Logger . Hook ( correlation . TraceContextHook { } )
zerolog . DurationFieldUnit = time . Millisecond
if * cpuProfile != "" && os . Getenv ( "ENV" ) != "production" {
log . Info ( ) . Str ( "file" , * cpuProfile ) . Msg ( "starting profiler" )
f , err := os . Create ( * cpuProfile )
if err != nil {
log . Fatal ( ) . Err ( err ) . Msg ( "failed to create cpu profile output file" )
}
_ = pprof . StartCPUProfile ( f )
defer pprof . StopCPUProfile ( )
}
go func ( ) {
if err := serve ( ":8080" ) ; err != nil {
log . Error ( ) . Err ( err ) . Msg ( "failed to serve requests" )
}
cancel ( )
} ( )
err := touchDbFile ( * dbFile )
err := touchDbFile ( * dbFile )
if err != nil {
if err != nil {
log . Fatal ( ) . Err ( err ) . Msg ( "failed to touch database file" )
log . Fatal ( ) . Err ( err ) . Msg ( "failed to touch database file" )
@ -94,23 +47,13 @@ func main() {
connString := fmt . Sprintf ( CONN_STRING_PATTERN , * dbFile )
connString := fmt . Sprintf ( CONN_STRING_PATTERN , * dbFile )
log . Debug ( ) . Str ( "connection_string" , connString ) . Msg ( "opening sqlite3 database" )
store , err = themis . NewStore ( connString )
db , err := sql . Open ( "sqlite3" , connString )
if err != nil {
log . Fatal ( ) . Err ( err ) . Msg ( "failed to open database" )
}
store , err = themis . NewStore ( db , log . Logger )
if err != nil {
if err != nil {
log . Fatal ( ) . Err ( err ) . Msg ( "failed to initialize database" )
log . Fatal ( ) . Err ( err ) . Msg ( "failed to initialize database" )
}
}
defer store . Close ( )
defer store . Close ( )
if err := initTracing ( ctx , db ) ; err != nil {
notifChan := make ( chan struct { } )
log . Fatal ( ) . Err ( err ) . Msg ( "failed to initialize tracing" )
}
notifChan := make ( chan context . Context )
notifier := themis . NewNotifier ( notifChan )
notifier := themis . NewNotifier ( notifChan )
go notifier . Start ( ctx )
go notifier . Start ( ctx )
@ -226,12 +169,6 @@ func main() {
Description : "Get the schedule for the following weeks." ,
Description : "Get the schedule for the following weeks." ,
Type : discordgo . ChatApplicationCommand ,
Type : discordgo . ChatApplicationCommand ,
} ,
} ,
{
Name : "send-schedule" ,
Description : "Trigger the scheduled message. Admins only" ,
Type : discordgo . ChatApplicationCommand ,
DefaultMemberPermissions : new ( int64 ) , // default 0 == admins only
} ,
{
{
Name : "absent" ,
Name : "absent" ,
Description : "Mark yourself as absent for a session" ,
Description : "Mark yourself as absent for a session" ,
@ -247,9 +184,10 @@ func main() {
} ,
} ,
}
}
handlers := map [ string ] Handler {
handlers := map [ string ] Handler {
"info" : func ( ctx context . Context , s * discordgo . Session , i * discordgo . InteractionCreate ) error {
"info" : func ( s * discordgo . Session , i * discordgo . InteractionCreate ) {
uptime , err := themis . Uptime ( ctx )
uptime , err := themis . Uptime ( )
if err != nil {
if err != nil {
log . Error ( ) . Err ( err ) . Msg ( "failed to get server uptime" )
err := s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
err := s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Data : & discordgo . InteractionResponseData {
Data : & discordgo . InteractionResponseData {
@ -257,13 +195,13 @@ func main() {
} ,
} ,
} )
} )
if err != nil {
if err != nil {
return fmt . Errorf ( "failed to respond to interaction : %w ", err )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction ")
}
}
return fmt . Errorf ( "failed to get server uptime: %w" , err )
}
}
claimCount , uniquePlayers , err := store . CountClaims ( ctx )
claimCount , uniquePlayers , err := store . CountClaims ( ctx )
if err != nil {
if err != nil {
log . Error ( ) . Err ( err ) . Msg ( "failed to count claims" )
err := s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
err := s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Data : & discordgo . InteractionResponseData {
Data : & discordgo . InteractionResponseData {
@ -271,45 +209,24 @@ func main() {
} ,
} ,
} )
} )
if err != nil {
if err != nil {
return fmt . Errorf ( "failed to respond to interaction: %w" , err )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction" )
}
return fmt . Errorf ( "failed to count claims: %w" , err )
}
ev , err := store . LastOf ( ctx , themis . EventFlush )
var lastFlush string
if err != nil {
if err != themis . ErrNever {
err := s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Data : & discordgo . InteractionResponseData {
Content : "Oops, something went wrong! :(" ,
} ,
} )
if err != nil {
return fmt . Errorf ( "failed to respond to interaction: %w" , err )
}
return fmt . Errorf ( "failed get last flush event: %w" , err )
}
}
lastFlush = "never"
} else {
lastFlush = ev . Timestamp . Format ( time . DateTime )
}
}
err = s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
err = s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Data : & discordgo . InteractionResponseData {
Data : & discordgo . InteractionResponseData {
Content : fmt . Sprintf ( "Server has been up for %s, has %d claims from %d unique players .\nThe last time claims were flushed was: %s. ", uptime , claimCount , uniquePlayers , lastFlush ) ,
Content : fmt . Sprintf ( "Server has been up for %s, has %d claims from %d unique players" , uptime , claimCount , uniquePlayers ) ,
} ,
} ,
} )
} )
if err != nil {
if err != nil {
return fmt . Errorf ( "failed to respond to interaction : %w ", err )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction" )
}
}
return nil
} ,
} ,
"list-claims" : func ( ctx context . Context , s * discordgo . Session , i * discordgo . InteractionCreate ) error {
"list-claims" : func ( s * discordgo . Session , i * discordgo . InteractionCreate ) {
claims , err := store . ListClaims ( ctx )
claims , err := store . ListClaims ( ctx )
if err != nil {
if err != nil {
log . Error ( ) . Err ( err ) . Msg ( "failed to list claims" )
err := s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
err := s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Data : & discordgo . InteractionResponseData {
Data : & discordgo . InteractionResponseData {
@ -317,9 +234,8 @@ func main() {
} ,
} ,
} )
} )
if err != nil {
if err != nil {
return fmt . Errorf ( "failed to respond to interaction : %w ", err )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction ")
}
}
return fmt . Errorf ( "failed to list claims: %w" , err )
}
}
sb := strings . Builder { }
sb := strings . Builder { }
@ -335,16 +251,13 @@ func main() {
} ,
} ,
} )
} )
if err != nil {
if err != nil {
return fmt . Errorf ( "failed to respond to interaction : %w ", err )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction ")
}
}
return nil
} ,
} ,
"claim" : func ( ctx context . Context , s * discordgo . Session , i * discordgo . InteractionCreate ) error {
"claim" : func ( s * discordgo . Session , i * discordgo . InteractionCreate ) {
if i . Type == discordgo . InteractionApplicationCommandAutocomplete {
if i . Type == discordgo . InteractionApplicationCommandAutocomplete {
log . Debug ( ) . Ctx ( ctx ) . Msg ( "command type interaction autocomplete" )
// TODO(wperron) fix this
handleClaimAutocomplete ( ctx , store , s , i )
handleClaimAutocomplete ( ctx , store , s , i )
return nil
return
}
}
opts := i . ApplicationCommandData ( ) . Options
opts := i . ApplicationCommandData ( ) . Options
@ -352,29 +265,28 @@ func main() {
err = s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
err = s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Data : & discordgo . InteractionResponseData {
Data : & discordgo . InteractionResponseData {
Flags : discordgo . MessageFlagsEphemeral ,
Content : "`claim-type` and `name` are mandatory parameters" ,
Content : "`claim-type` and `name` are mandatory parameters" ,
} ,
} ,
} )
} )
if err != nil {
if err != nil {
return fmt . Errorf ( "failed to respond to interaction : %w ", err )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction ")
}
}
return nil
return
}
}
claimType , err := themis . ClaimTypeFromString ( opts [ 0 ] . StringValue ( ) )
claimType , err := themis . ClaimTypeFromString ( opts [ 0 ] . StringValue ( ) )
if err != nil {
if err != nil {
log . Error ( ) . Err ( err ) . Str ( "claim_type" , opts [ 0 ] . StringValue ( ) ) . Msg ( "failed to parse claim" )
err = s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
err = s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Data : & discordgo . InteractionResponseData {
Data : & discordgo . InteractionResponseData {
Flags : discordgo . MessageFlagsEphemeral ,
Content : "You can only take claims of types `area`, `region` or `trade`" ,
Content : "You can only take claims of types `area`, `region` or `trade`" ,
} ,
} ,
} )
} )
if err != nil {
if err != nil {
return fmt . Errorf ( "failed to respond to interaction : %w ", err )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction ")
}
}
return fmt . Errorf ( "failed to parse claim: %w" , err )
return
}
}
name := opts [ 1 ] . StringValue ( )
name := opts [ 1 ] . StringValue ( )
@ -387,7 +299,6 @@ func main() {
_ , err = store . Claim ( ctx , userId , player , name , claimType )
_ , err = store . Claim ( ctx , userId , player , name , claimType )
if err != nil {
if err != nil {
// TODO(wperron) fix this error cast
conflict , ok := err . ( themis . ErrConflict )
conflict , ok := err . ( themis . ErrConflict )
if ok {
if ok {
sb := strings . Builder { }
sb := strings . Builder { }
@ -400,27 +311,26 @@ func main() {
err = s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
err = s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Data : & discordgo . InteractionResponseData {
Data : & discordgo . InteractionResponseData {
Flags : discordgo . MessageFlagsEphemeral ,
Content : sb . String ( ) ,
Content : sb . String ( ) ,
} ,
} ,
} )
} )
if err != nil {
if err != nil {
return fmt . Errorf ( "failed to respond to interaction" )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction" )
}
}
return nil
return
}
}
log . Error ( ) . Err ( err ) . Msg ( "failed to acquire claim" )
err = s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
err = s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Data : & discordgo . InteractionResponseData {
Data : & discordgo . InteractionResponseData {
Flags : discordgo . MessageFlagsEphemeral ,
Content : "failed to acquire claim :(" ,
Content : "failed to acquire claim :(" ,
} ,
} ,
} )
} )
if err != nil {
if err != nil {
return fmt . Errorf ( "failed to respond to interaction : %w ", err )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction ")
}
}
return fmt . Errorf ( "failed to acquire claim: %w" , err )
return
}
}
err = s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
err = s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
@ -430,14 +340,14 @@ func main() {
} ,
} ,
} )
} )
if err != nil {
if err != nil {
return fmt . Errorf ( "failed to respond to interaction : %w ", err )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction ")
}
}
return nil
} ,
} ,
"describe-claim" : func ( ctx context . Context , s * discordgo . Session , i * discordgo . InteractionCreate ) error {
"describe-claim" : func ( s * discordgo . Session , i * discordgo . InteractionCreate ) {
id := i . ApplicationCommandData ( ) . Options [ 0 ]
id := i . ApplicationCommandData ( ) . Options [ 0 ]
detail , err := store . DescribeClaim ( ctx , int ( id . IntValue ( ) ) )
detail , err := store . DescribeClaim ( ctx , int ( id . IntValue ( ) ) )
if err != nil {
if err != nil {
log . Error ( ) . Err ( err ) . Msg ( "failed to describe claim" )
err = s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
err = s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Data : & discordgo . InteractionResponseData {
Data : & discordgo . InteractionResponseData {
@ -445,9 +355,8 @@ func main() {
} ,
} ,
} )
} )
if err != nil {
if err != nil {
return fmt . Errorf ( "failed to respond to interaction : %w ", err )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction ")
}
}
return fmt . Errorf ( "failed to describe claim: %w" , err )
}
}
sb := strings . Builder { }
sb := strings . Builder { }
@ -463,19 +372,19 @@ func main() {
} ,
} ,
} )
} )
if err != nil {
if err != nil {
return fmt . Errorf ( "failed to respond to interaction : %w ", err )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction ")
}
}
return nil
} ,
} ,
"delete-claim" : func ( ctx context . Context , s * discordgo . Session , i * discordgo . InteractionCreate ) error {
"delete-claim" : func ( s * discordgo . Session , i * discordgo . InteractionCreate ) {
id := i . ApplicationCommandData ( ) . Options [ 0 ]
id := i . ApplicationCommandData ( ) . Options [ 0 ]
userId := i . Member . User . ID
userId := i . Member . User . ID
err := store . DeleteClaim ( ctx , int ( id . IntValue ( ) ) , userId )
err := store . DeleteClaim ( ctx , int ( id . IntValue ( ) ) , userId )
if err != nil {
if err != nil {
msg := "Oops, something went wrong :( blame < @wperron> "
msg := "Oops, something went wrong :( blame @wperron"
if errors . Is ( err , themis . ErrNoSuchClaim ) {
if errors . Is ( err , themis . ErrNoSuchClaim ) {
msg = fmt . Sprintf ( "Claim #%d not found for %s" , id . IntValue ( ) , i . Member . Nick )
msg = fmt . Sprintf ( "Claim #%d not found for %s" , id . IntValue ( ) , i . Member . Nick )
}
}
log . Error ( ) . Err ( err ) . Msg ( "failed to delete claim" )
err = s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
err = s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Data : & discordgo . InteractionResponseData {
Data : & discordgo . InteractionResponseData {
@ -483,48 +392,29 @@ func main() {
} ,
} ,
} )
} )
if err != nil {
if err != nil {
return fmt . Errorf ( "failed to respond to interaction : %w ", err )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction ")
}
}
return fmt . Errorf ( "failed to delete claim: %w" , err )
}
}
err = s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
err = s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Data : & discordgo . InteractionResponseData {
Data : & discordgo . InteractionResponseData {
Flags : discordgo . MessageFlagsEphemeral ,
Content : "Got it chief." ,
Content : "Got it chief." ,
} ,
} ,
} )
} )
if err != nil {
if err != nil {
return fmt . Errorf ( "failed to respond to interaction : %w ", err )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction ")
}
}
return nil
} ,
} ,
"flush" : func ( ctx context . Context , s * discordgo . Session , i * discordgo . InteractionCreate ) error {
"flush" : func ( s * discordgo . Session , i * discordgo . InteractionCreate ) {
baggage := make ( url . Values )
propagator . Inject ( ctx , correlation . UrlValuesCarrier ( baggage ) )
sb := strings . Builder { }
sb . WriteString ( "modal_flush" )
if len ( baggage ) != 0 {
sb . WriteRune ( ':' )
sb . WriteString ( baggage . Encode ( ) )
}
if err := s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
if err := s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
Type : discordgo . InteractionResponseModal ,
Type : discordgo . InteractionResponseModal ,
Data : & discordgo . InteractionResponseData {
Data : & discordgo . InteractionResponseData {
CustomID : sb . String ( ) ,
CustomID : "modals_flush_" + i . Interaction . Member . User . ID ,
Title : "Are you sure?" ,
Title : "Are you sure?" ,
Components : [ ] discordgo . MessageComponent {
Components : [ ] discordgo . MessageComponent {
discordgo . ActionsRow {
discordgo . ActionsRow {
Components : [ ] discordgo . MessageComponent {
Components : [ ] discordgo . MessageComponent {
// Note: Currently, Discord *requires* modal have at least one field present, it's not
// possible to simply have a cancel/confirm box. That is why this modal uses an old
// school [y/N] confirmation.
//
// source: https://stackoverflow.com/questions/71874810/discord-modals-without-textinputcomponent-but-a-text-and-button-only#answer-74317739
discordgo . TextInput {
discordgo . TextInput {
CustomID : "confirmation" ,
CustomID : "confirmation" ,
Label : "Delete all claims permanently? [y/N]" ,
Label : "Delete all claims permanently? [y/N]" ,
@ -540,14 +430,13 @@ func main() {
} ,
} ,
} ,
} ,
} ) ; err != nil {
} ) ; err != nil {
return fmt . Errorf ( "failed to respond to interaction : %w ", err )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction ")
}
}
return nil
} ,
} ,
"query" : func ( ctx context . Context , s * discordgo . Session , i * discordgo . InteractionCreate ) error {
"query" : func ( s * discordgo . Session , i * discordgo . InteractionCreate ) {
roDB , err := sql . Open ( "sqlite3" , fmt . Sprintf ( "file:%s?cache=private&mode=ro" , * dbFile ) )
roDB , err := sql . Open ( "sqlite3" , fmt . Sprintf ( "file:%s?cache=private&mode=ro" , * dbFile ) )
if err != nil {
if err != nil {
return fmt . Errorf ( "failed to open read-only copy of datab a se: %w ", err )
log . Error ( ) . Err ( err ) . Msg ( "failed to open read-only copy of datab se")
}
}
q := i . ApplicationCommandData ( ) . Options [ 0 ] . StringValue ( )
q := i . ApplicationCommandData ( ) . Options [ 0 ] . StringValue ( )
@ -555,12 +444,13 @@ func main() {
defer cancelDeadline ( )
defer cancelDeadline ( )
rows , err := roDB . QueryContext ( deadlined , q )
rows , err := roDB . QueryContext ( deadlined , q )
if err != nil {
if err != nil {
return fmt . Errorf ( "faied to exec user-provided query: %w" , err )
log . Error ( ) . Err ( err ) . Msg ( "failed to exec user-provided query" )
return
}
}
fmtd , err := themis . FormatRows ( ctx, rows)
fmtd , err := themis . FormatRows ( rows)
if err != nil {
if err != nil {
return fmt . Errorf ( "failed to format rows: %w" , err )
log . Error ( ) . Err ( err ) . Msg ( "failed to format rows" )
}
}
// 2000 is a magic number here, it's the character limit for a discord
// 2000 is a magic number here, it's the character limit for a discord
@ -574,24 +464,22 @@ func main() {
Content : table ,
Content : table ,
} ,
} ,
} ) ; err != nil {
} ) ; err != nil {
log . Error ( ) . Ctx ( ctx ) . Err ( err ) . Msg ( "failed to respond to interaction" )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction" )
return fmt . Errorf ( "failed to respond to interaction: %w" , err )
}
}
return nil
} ,
} ,
"schedule" : func ( ctx context . Context , s * discordgo . Session , i * discordgo . InteractionCreate ) error {
"schedule" : func ( s * discordgo . Session , i * discordgo . InteractionCreate ) {
// get schedule from now to 4 mondays into the future
// get schedule from now to 4 mondays into the future
sched , err := store . GetSchedule ( ctx , themis . NextMonday ( ) , themis . NextMonday ( ) . Add ( 4 * 7 * 24 * time . Hour ) )
sched , err := store . GetSchedule ( ctx , themis . NextMonday ( ) , themis . NextMonday ( ) . Add ( 4 * 7 * 24 * time . Hour ) )
if err != nil {
if err != nil {
log . Error ( ) . Err ( err ) . Msg ( "failed to get schedule" )
if err := s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
if err := s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Data : & discordgo . InteractionResponseData {
Data : & discordgo . InteractionResponseData {
Content : "failed to get schedule, check logs for more info." ,
Content : "failed to get schedule, check logs for more info." ,
} ,
} ,
} ) ; err != nil {
} ) ; err != nil {
return fmt . Errorf ( "failed to respond to interaction : %w ", err )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction ")
}
}
return fmt . Errorf ( "failed to get schedule: %w" , err )
}
}
sb := strings . Builder { }
sb := strings . Builder { }
@ -620,27 +508,10 @@ func main() {
Content : sb . String ( ) ,
Content : sb . String ( ) ,
} ,
} ,
} ) ; err != nil {
} ) ; err != nil {
log . Error ( ) . Ctx ( ctx ) . Err ( err ) . Msg ( "failed to respond to interaction" )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction" )
return fmt . Errorf ( "failed to respond to interaction: %w" , err )
}
return nil
} ,
"send-schedule" : func ( ctx context . Context , s * discordgo . Session , i * discordgo . InteractionCreate ) error {
notifier . Send ( ctx )
if err := s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Data : & discordgo . InteractionResponseData {
Flags : discordgo . MessageFlagsEphemeral ,
Content : "Done." ,
} ,
} ) ; err != nil {
log . Error ( ) . Ctx ( ctx ) . Err ( err ) . Msg ( "failed to respond to interaction" )
return fmt . Errorf ( "failed to respond to interaction: %w" , err )
}
}
return nil
} ,
} ,
"absent" : func ( ctx context . Context , s * discordgo . Session , i * discordgo . InteractionCreate ) error {
"absent" : func ( s * discordgo . Session , i * discordgo . InteractionCreate ) {
var rawDate string
var rawDate string
if len ( i . ApplicationCommandData ( ) . Options ) == 0 {
if len ( i . ApplicationCommandData ( ) . Options ) == 0 {
rawDate = themis . NextMonday ( ) . Format ( time . DateOnly )
rawDate = themis . NextMonday ( ) . Format ( time . DateOnly )
@ -653,40 +524,34 @@ func main() {
if err := s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
if err := s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Data : & discordgo . InteractionResponseData {
Data : & discordgo . InteractionResponseData {
Flags : discordgo . MessageFlagsEphemeral ,
Content : "failed to parse provided date, make sure to use the YYYY-MM-DD format." ,
Content : "failed to parse provided date, make sure to use the YYYY-MM-DD format." ,
} ,
} ,
} ) ; err != nil {
} ) ; err != nil {
return fmt . Errorf ( "failed to respond to interaction : %w ", err )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction ")
}
}
return nil
}
}
if date . Before ( time . Now ( ) ) {
if date . Before ( time . Now ( ) ) {
if err := s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
if err := s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Data : & discordgo . InteractionResponseData {
Data : & discordgo . InteractionResponseData {
Flags : discordgo . MessageFlagsEphemeral ,
Content : "The date must be some time in the future." ,
Content : "The date must be some time in the future." ,
} ,
} ,
} ) ; err != nil {
} ) ; err != nil {
return fmt . Errorf ( "failed to respond to interaction : %w ", err )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction ")
}
}
return nil
}
}
if date . Weekday ( ) != time . Monday {
if date . Weekday ( ) != time . Monday {
if err := s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
if err := s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Data : & discordgo . InteractionResponseData {
Data : & discordgo . InteractionResponseData {
Flags : discordgo . MessageFlagsEphemeral ,
Content : "The date you provided is not a Monday." ,
Content : "The date you provided is not a Monday." ,
} ,
} ,
} ) ; err != nil {
} ) ; err != nil {
return fmt . Errorf ( "failed to respond to interaction : %w ", err )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction ")
}
}
// TODO(wperron) suggest Mondays before and after?
// TODO(wperron) suggest Mondays before and after?
return nil
}
}
userId := i . Member . User . ID
userId := i . Member . User . ID
@ -697,22 +562,19 @@ func main() {
Content : "something went wrong recording your absence, check logs for more info." ,
Content : "something went wrong recording your absence, check logs for more info." ,
} ,
} ,
} ) ; err != nil {
} ) ; err != nil {
return fmt . Errorf ( "failed to respond to interaction : %w ", err )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction ")
}
}
return fmt . Errorf ( "failed to record absence: %w" , err )
}
}
err = s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
err = s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Data : & discordgo . InteractionResponseData {
Data : & discordgo . InteractionResponseData {
Flags : discordgo . MessageFlagsEphemeral ,
Content : "Okey dokey." ,
Content : "Okey dokey." ,
} ,
} ,
} )
} )
if err != nil {
if err != nil {
return fmt . Errorf ( "failed to respond to interaction : %w ", err )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction ")
}
}
return nil
} ,
} ,
}
}
@ -724,21 +586,25 @@ func main() {
}
}
defer discord . Close ( )
defer discord . Close ( )
log . Debug ( ) . Int ( "count" , len ( commands ) ) . Msg ( "registering commands via bulk overwrite" )
registeredCommands := make ( [ ] * discordgo . ApplicationCommand , len ( commands ) )
created , err := discord . ApplicationCommandBulkOverwrite ( appId , guildId , commands )
for i , c := range commands {
command , err := discord . ApplicationCommandCreate ( appId , guildId , c )
if err != nil {
if err != nil {
log . Fatal ( ) . Err ( err ) . Msg ( "failed to register commands with discord" )
log . Fatal ( ) . Err ( err ) . Msg ( "failed to register command" )
}
registeredCommands [ i ] = command
}
}
log . Info ( ) . Int ( "count" , len ( created ) ) . Dur ( "startup_latency_ms" , time . Since ( start ) ) . Msg ( "registered commands, ready to operate" )
go notifier . NotifyFunc ( ctx , func ( ctx context . Context ) {
log . Info ( ) . Int ( "count" , len ( registeredCommands ) ) . Msg ( "registered commands" )
ctx , cancel := context . WithTimeout ( ctx , 5 * time . Second )
defer cancel ( )
ctx , span := tracer . Start ( ctx , "weekly_notification" )
go func ( ) {
defer span . End ( )
if err := serve ( ":8080" ) ; err != nil {
log . Error ( ) . Err ( err ) . Msg ( "failed to serve requests" )
}
cancel ( )
} ( )
log . Info ( ) . Msg ( "sending weekly reminder" )
go notifier . NotifyFunc ( ctx , func ( ) {
absentees , err := store . GetAbsentees ( ctx , themis . NextMonday ( ) )
absentees , err := store . GetAbsentees ( ctx , themis . NextMonday ( ) )
if err != nil {
if err != nil {
log . Error ( ) . Err ( err ) . Msg ( "failed to get absentees for next session" )
log . Error ( ) . Err ( err ) . Msg ( "failed to get absentees for next session" )
@ -751,32 +617,13 @@ func main() {
}
}
var msg string
var msg string
var components [ ] discordgo . MessageComponent
if len ( absentees ) == 0 {
if len ( absentees ) == 0 {
msg = "Everybody can make it next Monday, see you then! 🎉"
msg = "Everybody can make it next Monday, see you then!"
components = [ ] discordgo . MessageComponent {
discordgo . ActionsRow {
Components : [ ] discordgo . MessageComponent {
discordgo . Button {
CustomID : "schedule-response" ,
Label : "I Can't Make It" ,
Style : discordgo . DangerButton ,
Disabled : false ,
Emoji : discordgo . ComponentEmoji {
Name : "🙁" ,
} ,
} ,
} ,
} ,
}
} else {
} else {
msg = fmt . Sprintf ( "%s can't make it next Monday. 🙁 ", themis . FormatStringSlice ( absentees ) )
msg = fmt . Sprintf ( "%s can't make it next Monday. :sad:" , themis . FormatStringSlice ( absentees ) )
}
}
_ , err = discord . ChannelMessageSendComplex ( channelId , & discordgo . MessageSend {
_ , err = discord . ChannelMessageSend ( channelId , msg )
Content : msg ,
Components : components ,
} )
if err != nil {
if err != nil {
log . Error ( ) . Err ( err ) . Msg ( "failed to send scheduled notification" )
log . Error ( ) . Err ( err ) . Msg ( "failed to send scheduled notification" )
}
}
@ -784,11 +631,18 @@ func main() {
<- ctx . Done ( )
<- ctx . Done ( )
log . Info ( ) . Msg ( "context cancelled, exiting" )
log . Info ( ) . Msg ( "context cancelled, exiting" )
store . Close ( )
for _ , c := range registeredCommands {
err = discord . ApplicationCommandDelete ( appId , guildId , c . ID )
if err != nil {
log . Error ( ) . Err ( err ) . Msg ( "failed to deregister commands" )
}
}
log . Info ( ) . Msg ( "deregistered commands, exiting" )
os . Exit ( 0 )
}
}
func touchDbFile ( path string ) error {
func touchDbFile ( path string ) error {
log . Debug ( ) . Str ( "path" , path ) . Msg ( "touching database file" )
f , err := os . Open ( path )
f , err := os . Open ( path )
if err != nil {
if err != nil {
if errors . Is ( err , os . ErrNotExist ) {
if errors . Is ( err , os . ErrNotExist ) {
@ -813,34 +667,18 @@ func registerHandlers(sess *discordgo.Session, handlers map[string]Handler) {
sess . AddHandler ( func ( s * discordgo . Session , i * discordgo . InteractionCreate ) {
sess . AddHandler ( func ( s * discordgo . Session , i * discordgo . InteractionCreate ) {
switch i . Type {
switch i . Type {
case discordgo . InteractionApplicationCommand :
case discordgo . InteractionApplicationCommand :
ctx , cancel := context . WithTimeout ( context . Background ( ) , 5 * time . Second )
defer cancel ( )
if h , ok := handlers [ i . ApplicationCommandData ( ) . Name ] ; ok {
if h , ok := handlers [ i . ApplicationCommandData ( ) . Name ] ; ok {
_ = inSpan( i . ApplicationCommandData ( ) . Name , wit hLogging ( i . ApplicationCommandData ( ) . Name , h ) ) ( ctx , s , i )
h ( s , i )
}
}
case discordgo . InteractionModalSubmit :
case discordgo . InteractionModalSubmit :
ctx , cancel := context . WithTimeout ( context . Background ( ) , 5 * time . Second )
if strings . HasPrefix ( i . ModalSubmitData ( ) . CustomID , "modals_flush_" ) {
defer cancel ( )
state , err := parseCustomIDState ( i . ModalSubmitData ( ) . CustomID )
if err != nil {
log . Error ( ) . Ctx ( ctx ) . Err ( err ) . Msg ( "unexpected error occurred while parsing state from custom id, returning early." )
return
}
ctx = propagator . Extract ( ctx , correlation . UrlValuesCarrier ( state ) )
if strings . HasPrefix ( i . ModalSubmitData ( ) . CustomID , "modal_flush" ) {
sub := i . ModalSubmitData ( ) . Components [ 0 ] . ( * discordgo . ActionsRow ) . Components [ 0 ] . ( * discordgo . TextInput ) . Value
sub := i . ModalSubmitData ( ) . Components [ 0 ] . ( * discordgo . ActionsRow ) . Components [ 0 ] . ( * discordgo . TextInput ) . Value
sub = strings . ToLower ( sub )
sub = strings . ToLower ( sub )
log . Debug ( ) . Ctx ( ctx ) . Str ( "value" , sub ) . Msg ( "flush modal submitted" )
if sub == "y" || sub == "ye" || sub == "yes" {
if sub == "y" || sub == "ye" || sub == "yes" {
err := store . Flush ( c tx, i . Member . User . ID )
err := store . Flush ( context . Background ( ) )
msg := "Flushed all claims!"
msg := "Flushed all claims!"
if err != nil {
if err != nil {
log . Error ( ) . Ctx( ctx ) . Err( err ) . Msg ( "failed to flush claims" )
log . Error ( ) . Err ( err ) . Msg ( "failed to flush claims" )
msg = "failed to flush claims from database"
msg = "failed to flush claims from database"
}
}
@ -851,7 +689,7 @@ func registerHandlers(sess *discordgo.Session, handlers map[string]Handler) {
} ,
} ,
} )
} )
if err != nil {
if err != nil {
log . Error ( ) . Ctx( ctx ) . Err( err ) . Msg ( "failed to respond to interaction" )
log . Error ( ) . Err( err ) . Msg ( "failed to respond to interaction" )
}
}
return
return
}
}
@ -863,49 +701,10 @@ func registerHandlers(sess *discordgo.Session, handlers map[string]Handler) {
} ,
} ,
} )
} )
if err != nil {
if err != nil {
log . Error ( ) . Ctx ( ctx ) . Err ( err ) . Msg ( "failed to respond to interaction" )
}
return
}
case discordgo . InteractionMessageComponent :
ctx , cancel := context . WithTimeout ( context . Background ( ) , 5 * time . Second )
defer cancel ( )
state , err := parseCustomIDState ( i . MessageComponentData ( ) . CustomID )
if err != nil {
log . Error ( ) . Ctx ( ctx ) . Err ( err ) . Msg ( "unexpected error occured while parsing state from custom id, returning early." )
return
}
ctx = propagator . Extract ( ctx , correlation . UrlValuesCarrier ( state ) )
switch i . MessageComponentData ( ) . CustomID {
case "schedule-response" :
userId := i . Member . User . ID
log . Info ( ) . Ctx ( ctx ) . Str ( "message_component" , "schedule-response" ) . Str ( "userid" , userId ) . Msg ( "handling message component interaction" )
if err := store . AddAbsence ( ctx , themis . NextMonday ( ) , userId ) ; err != nil {
if err := s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Data : & discordgo . InteractionResponseData {
Content : "something went wrong recording your absence, check logs for more info." ,
} ,
} ) ; err != nil {
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction" )
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction" )
}
}
return
return
}
}
err := s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
Type : discordgo . InteractionResponseChannelMessageWithSource ,
Data : & discordgo . InteractionResponseData {
Content : fmt . Sprintf ( "Looks like <@%s> can't make it after all." , userId ) ,
} ,
} )
if err != nil {
log . Error ( ) . Err ( err ) . Msg ( "failed to respond to interaction" )
}
}
}
}
} )
} )
}
}
@ -942,7 +741,6 @@ func formatClaimsTable(claims []themis.Claim) string {
}
}
func handleClaimAutocomplete ( ctx context . Context , store * themis . Store , s * discordgo . Session , i * discordgo . InteractionCreate ) {
func handleClaimAutocomplete ( ctx context . Context , store * themis . Store , s * discordgo . Session , i * discordgo . InteractionCreate ) {
log . Debug ( ) . Msg ( "getting autocomplete data for claim" )
opts := i . ApplicationCommandData ( ) . Options
opts := i . ApplicationCommandData ( ) . Options
claimType , err := themis . ClaimTypeFromString ( opts [ 0 ] . StringValue ( ) )
claimType , err := themis . ClaimTypeFromString ( opts [ 0 ] . StringValue ( ) )
if err != nil {
if err != nil {
@ -964,8 +762,6 @@ func handleClaimAutocomplete(ctx context.Context, store *themis.Store, s *discor
} )
} )
}
}
log . Debug ( ) . Int ( "len" , len ( choices ) ) . Msg ( "found autocomplete suggestions" )
if err := s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
if err := s . InteractionRespond ( i . Interaction , & discordgo . InteractionResponse {
Type : discordgo . InteractionApplicationCommandAutocompleteResult ,
Type : discordgo . InteractionApplicationCommandAutocompleteResult ,
Data : & discordgo . InteractionResponseData {
Data : & discordgo . InteractionResponseData {
@ -984,108 +780,9 @@ func serve(address string) error {
return http . ListenAndServe ( address , nil )
return http . ListenAndServe ( address , nil )
}
}
func inSpan ( name string , h Handler ) Handler {
return func ( ctx context . Context , s * discordgo . Session , i * discordgo . InteractionCreate ) error {
ctx , span := tracer . Start ( ctx , fmt . Sprintf ( "discord_command %s" , name ) )
defer span . End ( )
return h ( ctx , s , i )
}
}
func withLogging ( name string , h Handler ) Handler {
return func ( ctx context . Context , s * discordgo . Session , i * discordgo . InteractionCreate ) error {
start := time . Now ( )
logCommandInvocation ( ctx , name , s , i )
err := h ( ctx , s , i )
debugCommandCompletion ( ctx , name , time . Since ( start ) , err , s , i )
return nil
}
}
func logCommandInvocation ( ctx context . Context , name string , s * discordgo . Session , i * discordgo . InteractionCreate ) {
span := trace . SpanFromContext ( ctx )
span . SetAttributes (
attribute . String ( "user_id" , i . Member . User . ID ) ,
attribute . String ( "username" , i . Member . User . Username ) ,
attribute . String ( "command_name" , name ) ,
)
for _ , o := range i . ApplicationCommandData ( ) . Options {
switch o . Type {
case discordgo . ApplicationCommandOptionSubCommand , discordgo . ApplicationCommandOptionSubCommandGroup :
panic ( "unreachable" )
case discordgo . ApplicationCommandOptionString :
span . SetAttributes ( attribute . String ( fmt . Sprintf ( "command_option.%s" , o . Name ) , o . StringValue ( ) ) )
case discordgo . ApplicationCommandOptionInteger :
span . SetAttributes ( attribute . Int64 ( fmt . Sprintf ( "command_option.%s" , o . Name ) , o . IntValue ( ) ) )
case discordgo . ApplicationCommandOptionBoolean :
span . SetAttributes ( attribute . Bool ( fmt . Sprintf ( "command_option.%s" , o . Name ) , o . BoolValue ( ) ) )
default :
span . SetAttributes ( attribute . String ( fmt . Sprintf ( "command_option.%s" , o . Name ) , "unsupported_type" ) )
}
}
log . Info ( ) . Ctx ( ctx ) . Msg ( "command invoked" )
}
func debugCommandCompletion ( ctx context . Context , name string , dur time . Duration , err error , s * discordgo . Session , i * discordgo . InteractionCreate ) {
span := trace . SpanFromContext ( ctx )
if err != nil {
span . SetStatus ( codes . Error , err . Error ( ) )
}
log . Info ( ) . Ctx ( ctx ) . Dur ( "latency_ms" , dur ) . Msg ( "command completed" )
}
func min ( a , b int ) int {
func min ( a , b int ) int {
if a < b {
if a < b {
return a
return a
}
}
return b
return b
}
}
func parseCustomIDState ( qs string ) ( url . Values , error ) {
parts := strings . Split ( qs , ":" )
if len ( parts ) == 1 {
return make ( url . Values ) , nil
}
v , err := url . ParseQuery ( parts [ 1 ] )
if err != nil {
return nil , err
}
return v , nil
}
func initTracing ( ctx context . Context , db * sql . DB ) error {
fd , _ := flydetector . NewDetector ( ) . Detect ( ctx ) // this can't error
rd , err := resource . New ( ctx ,
resource . WithHost ( ) ,
resource . WithOS ( ) ,
resource . WithProcess ( ) ,
resource . WithTelemetrySDK ( ) ,
resource . WithAttributes ( semconv . ServiceName ( "themis" ) ) ,
)
if err != nil {
return fmt . Errorf ( "failed to create resource: %w" , err )
}
res , err := resource . Merge ( fd , rd )
if err != nil {
return fmt . Errorf ( "failed to merge resources: %w" , err )
}
ex , err := sqliteexporter . NewSqliteSDKTraceExporterWithDB ( db )
if err != nil {
return fmt . Errorf ( "failed to create span exporter: %w" , err )
}
tp := sdktrace . NewTracerProvider (
sdktrace . WithBatcher ( ex , sdktrace . WithExportTimeout ( time . Second ) ) ,
sdktrace . WithResource ( res ) ,
)
otel . SetTracerProvider ( tp )
tracer = tp . Tracer ( "themis" )
return nil
}