Preserve Discord bridge state codes and retry logic
This commit is contained in:
@@ -61,6 +61,7 @@ func (dc *DiscordClient) FetchMessages(ctx context.Context, fetchParams bridgev2
|
||||
log.Debug().Msg("Fetching channel history for backfill")
|
||||
msgs, err := dc.Session.ChannelMessages(channelID, count, beforeID, afterID, "")
|
||||
if err != nil {
|
||||
dc.handlePossible40002(err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
||||
@@ -17,26 +17,30 @@
|
||||
package connector
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/bwmarrin/discordgo"
|
||||
"maunium.net/go/mautrix/bridgev2/status"
|
||||
)
|
||||
|
||||
const (
|
||||
DiscordNotLoggedIn status.BridgeStateErrorCode = "discord-not-logged-in"
|
||||
DiscordInvalidAuth status.BridgeStateErrorCode = "discord-invalid-auth"
|
||||
DiscordDisconnected status.BridgeStateErrorCode = "discord-disconnected"
|
||||
DiscordConnectFailed status.BridgeStateErrorCode = "discord-connect-failed"
|
||||
DiscordNotLoggedIn status.BridgeStateErrorCode = "dc-not-logged-in"
|
||||
DiscordTransientDisconnect status.BridgeStateErrorCode = "dc-transient-disconnect"
|
||||
DiscordInvalidAuth status.BridgeStateErrorCode = "dc-websocket-disconnect-4004"
|
||||
DiscordHTTP40002 status.BridgeStateErrorCode = "dc-http-40002"
|
||||
DiscordUnknownWebsocketErr status.BridgeStateErrorCode = "dc-unknown-websocket-error"
|
||||
)
|
||||
|
||||
const discordDisconnectDebounce = 7 * time.Second
|
||||
|
||||
func init() {
|
||||
status.BridgeStateHumanErrors.Update(status.BridgeStateErrorMap{
|
||||
DiscordNotLoggedIn: "You're not logged into Discord. Relogin to continue using the bridge.",
|
||||
DiscordInvalidAuth: "You were logged out of Discord. Relogin to continue using the bridge.",
|
||||
DiscordDisconnected: "Disconnected from Discord. Trying to reconnect.",
|
||||
DiscordConnectFailed: "Connecting to Discord failed.",
|
||||
DiscordNotLoggedIn: "You're not logged into Discord. Relogin to continue using the bridge.",
|
||||
DiscordTransientDisconnect: "Temporarily disconnected from Discord, trying to reconnect.",
|
||||
DiscordInvalidAuth: "Discord access token is no longer valid, please log in again.",
|
||||
DiscordHTTP40002: "Discord requires a verified account, please verify and log in again.",
|
||||
DiscordUnknownWebsocketErr: "Unknown Discord websocket error.",
|
||||
})
|
||||
}
|
||||
|
||||
@@ -79,6 +83,7 @@ func (d *DiscordClient) markInvalidAuth(message string) {
|
||||
StateEvent: status.StateBadCredentials,
|
||||
Error: DiscordInvalidAuth,
|
||||
Message: message,
|
||||
UserAction: status.UserActionRelogin,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -105,23 +110,44 @@ func (d *DiscordClient) scheduleTransientDisconnect(message string) {
|
||||
}
|
||||
login.BridgeState.Send(status.BridgeState{
|
||||
StateEvent: status.StateTransientDisconnect,
|
||||
Error: DiscordDisconnected,
|
||||
Error: DiscordTransientDisconnect,
|
||||
Message: message,
|
||||
})
|
||||
})
|
||||
d.bridgeStateLock.Unlock()
|
||||
}
|
||||
|
||||
func (d *DiscordClient) sendConnectFailure(err error) {
|
||||
func (d *DiscordClient) sendConnectFailure(err error, final bool) {
|
||||
if d.UserLogin == nil || err == nil {
|
||||
return
|
||||
}
|
||||
stateEvent := status.StateTransientDisconnect
|
||||
if final {
|
||||
stateEvent = status.StateUnknownError
|
||||
}
|
||||
d.UserLogin.BridgeState.Send(status.BridgeState{
|
||||
StateEvent: status.StateUnknownError,
|
||||
Error: DiscordConnectFailed,
|
||||
StateEvent: stateEvent,
|
||||
Error: DiscordUnknownWebsocketErr,
|
||||
Message: err.Error(),
|
||||
Info: map[string]any{
|
||||
"go_error": err.Error(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (d *DiscordClient) handlePossible40002(err error) bool {
|
||||
var restErr *discordgo.RESTError
|
||||
if !errors.As(err, &restErr) || restErr.Message == nil || restErr.Message.Code != discordgo.ErrCodeActionRequiredVerifiedAccount {
|
||||
return false
|
||||
}
|
||||
if d.UserLogin == nil {
|
||||
return true
|
||||
}
|
||||
d.UserLogin.BridgeState.Send(status.BridgeState{
|
||||
StateEvent: status.StateBadCredentials,
|
||||
Error: DiscordHTTP40002,
|
||||
Message: restErr.Message.Message,
|
||||
UserAction: status.UserActionRelogin,
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -110,6 +110,7 @@ func (d *DiscordClient) Connect(ctx context.Context) {
|
||||
d.UserLogin.BridgeState.Send(status.BridgeState{
|
||||
StateEvent: status.StateBadCredentials,
|
||||
Error: DiscordNotLoggedIn,
|
||||
UserAction: status.UserActionRelogin,
|
||||
})
|
||||
return
|
||||
}
|
||||
@@ -117,9 +118,7 @@ func (d *DiscordClient) Connect(ctx context.Context) {
|
||||
d.UserLogin.BridgeState.Send(status.BridgeState{
|
||||
StateEvent: status.StateConnecting,
|
||||
})
|
||||
if err := d.connect(ctx); err != nil {
|
||||
log.Err(err).Msg("Couldn't connect to Discord")
|
||||
}
|
||||
d.connectWithRetry(ctx, 0)
|
||||
}
|
||||
|
||||
func (cl *DiscordClient) handleDiscordEventSync(event any) {
|
||||
@@ -140,7 +139,6 @@ func (cl *DiscordClient) connect(ctx context.Context) error {
|
||||
}
|
||||
if err != nil {
|
||||
log.Err(err).Msg("Failed to connect to Discord")
|
||||
cl.sendConnectFailure(err)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -148,7 +146,6 @@ func (cl *DiscordClient) connect(ctx context.Context) error {
|
||||
if !cl.IsLoggedIn() {
|
||||
err := fmt.Errorf("unknown identity even after connecting to Discord")
|
||||
log.Err(err).Msg("No Discord user available after connecting")
|
||||
cl.sendConnectFailure(err)
|
||||
return err
|
||||
}
|
||||
user := cl.Session.State.User
|
||||
@@ -170,6 +167,27 @@ func (cl *DiscordClient) connect(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DiscordClient) connectWithRetry(ctx context.Context, retryCount int) {
|
||||
err := d.connect(ctx)
|
||||
if err == nil || ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if retryCount < 6 {
|
||||
d.sendConnectFailure(err, false)
|
||||
retryInSeconds := 2 << retryCount
|
||||
zerolog.Ctx(ctx).Debug().Int("retry_in_seconds", retryInSeconds).Msg("Sleeping and retrying connection")
|
||||
select {
|
||||
case <-time.After(time.Duration(retryInSeconds) * time.Second):
|
||||
case <-ctx.Done():
|
||||
zerolog.Ctx(ctx).Info().Msg("Context canceled, exiting connect retry loop")
|
||||
return
|
||||
}
|
||||
d.connectWithRetry(ctx, retryCount+1)
|
||||
} else {
|
||||
d.sendConnectFailure(err, true)
|
||||
}
|
||||
}
|
||||
|
||||
func (d *DiscordClient) Disconnect() {
|
||||
d.UserLogin.Log.Info().Msg("Disconnecting session")
|
||||
d.Session.Close()
|
||||
@@ -398,6 +416,7 @@ func (d *DiscordClient) bridgeGuild(ctx context.Context, guildID string) error {
|
||||
Threads: true,
|
||||
})
|
||||
if err != nil {
|
||||
d.handlePossible40002(err)
|
||||
log.Warn().Err(err).Msg("Failed to subscribe to guild; proceeding")
|
||||
}
|
||||
|
||||
|
||||
@@ -56,6 +56,7 @@ func (d *DiscordClient) HandleMatrixMessage(ctx context.Context, msg *bridgev2.M
|
||||
|
||||
sentMsg, err := d.Session.ChannelMessageSendComplex(discordid.ParsePortalID(msg.Portal.ID), sendReq, options...)
|
||||
if err != nil {
|
||||
d.handlePossible40002(err)
|
||||
return nil, err
|
||||
}
|
||||
sentMsgTimestamp, _ := discordgo.SnowflakeTimestamp(sentMsg.ID)
|
||||
@@ -90,6 +91,9 @@ func (d *DiscordClient) HandleMatrixReaction(ctx context.Context, reaction *brid
|
||||
meta := portal.Metadata.(*discordid.PortalMetadata)
|
||||
|
||||
err := d.Session.MessageReactionAddUser(meta.GuildID, discordid.ParsePortalID(portal.ID), discordid.ParseMessageID(reaction.TargetMessage.ID), relatesToKey)
|
||||
if err != nil {
|
||||
d.handlePossible40002(err)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -100,13 +104,20 @@ func (d *DiscordClient) HandleMatrixReactionRemove(ctx context.Context, removal
|
||||
guildID := removal.Portal.Metadata.(*discordid.PortalMetadata).GuildID
|
||||
|
||||
err := d.Session.MessageReactionRemoveUser(guildID, channelID, discordid.ParseMessageID(removing.MessageID), discordid.ParseEmojiID(emojiID), discordid.ParseUserLoginID(d.UserLogin.ID))
|
||||
if err != nil {
|
||||
d.handlePossible40002(err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *DiscordClient) HandleMatrixMessageRemove(ctx context.Context, removal *bridgev2.MatrixMessageRemove) error {
|
||||
channelID := discordid.ParsePortalID(removal.Portal.ID)
|
||||
messageID := discordid.ParseMessageID(removal.TargetMessage.ID)
|
||||
return d.Session.ChannelMessageDelete(channelID, messageID)
|
||||
err := d.Session.ChannelMessageDelete(channelID, messageID)
|
||||
if err != nil {
|
||||
d.handlePossible40002(err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *DiscordClient) HandleMatrixReadReceipt(ctx context.Context, msg *bridgev2.MatrixReadReceipt) error {
|
||||
@@ -153,6 +164,7 @@ func (d *DiscordClient) HandleMatrixReadReceipt(ctx context.Context, msg *bridge
|
||||
channelID := discordid.ParsePortalID(msg.Portal.ID)
|
||||
resp, err := d.Session.ChannelMessageAckNoToken(channelID, targetMessageID, discordgo.WithChannelReferer(guildID, channelID))
|
||||
if err != nil {
|
||||
d.handlePossible40002(err)
|
||||
log.Err(err).Msg("Failed to send read receipt to Discord")
|
||||
return err
|
||||
} else if resp.Token != nil {
|
||||
@@ -186,6 +198,7 @@ func (d *DiscordClient) viewingChannel(ctx context.Context, portal *bridgev2.Por
|
||||
err := d.Session.MarkViewing(channelID)
|
||||
|
||||
if err != nil {
|
||||
d.handlePossible40002(err)
|
||||
log.Error().Err(err).Msg("Failed to mark user as viewing channel")
|
||||
return err
|
||||
}
|
||||
@@ -211,6 +224,7 @@ func (d *DiscordClient) HandleMatrixTyping(ctx context.Context, msg *bridgev2.Ma
|
||||
err := d.Session.ChannelTyping(channelID, discordgo.WithChannelReferer(guildID, channelID))
|
||||
|
||||
if err != nil {
|
||||
d.handlePossible40002(err)
|
||||
log.Warn().Err(err).Msg("Failed to mark user as typing")
|
||||
return err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user