Gracefully handle creating duplicate notifications

This commit is contained in:
Eli Ribble 2026-02-12 21:06:08 +00:00
parent 8e68230f4a
commit a82231859d
No known key found for this signature in database

View file

@ -6,11 +6,13 @@ import (
"strings" "strings"
"time" "time"
"github.com/Gleipnir-Technology/bob/dialect/psql"
"github.com/Gleipnir-Technology/bob/dialect/psql/im"
"github.com/Gleipnir-Technology/nidus-sync/db" "github.com/Gleipnir-Technology/nidus-sync/db"
enums "github.com/Gleipnir-Technology/nidus-sync/db/enums" enums "github.com/Gleipnir-Technology/nidus-sync/db/enums"
"github.com/Gleipnir-Technology/nidus-sync/db/models" "github.com/Gleipnir-Technology/nidus-sync/db/models"
"github.com/Gleipnir-Technology/nidus-sync/debug" "github.com/Gleipnir-Technology/nidus-sync/debug"
"github.com/aarondl/opt/omit" //"github.com/aarondl/opt/omit"
"github.com/aarondl/opt/omitnull" "github.com/aarondl/opt/omitnull"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
) )
@ -45,15 +47,32 @@ func ClearOauth(ctx context.Context, user *models.User) {
func NotifyOauthInvalid(ctx context.Context, user *models.User) { func NotifyOauthInvalid(ctx context.Context, user *models.User) {
msg := "Oauth token invalidated" msg := "Oauth token invalidated"
notificationSetter := models.NotificationSetter{ _, err := psql.Insert(
Created: omit.From(time.Now()), im.Into("notification", "created", "id", "link", "message", "resolved_at", "type", "user_id"),
Message: omit.From(msg), im.Values(
Link: omit.From(NotificationPathOauthReset), psql.Arg(time.Now()),
Type: omit.From(enums.NotificationtypeOauthTokenInvalidated), psql.Raw("DEFAULT"),
} psql.Arg(NotificationPathOauthReset),
err := user.InsertUserNotifications(ctx, db.PGInstance.BobDB, &notificationSetter) psql.Arg(msg),
psql.Raw("NULL"),
psql.Arg(enums.NotificationtypeOauthTokenInvalidated),
psql.Arg(user.ID),
),
//im.OnConflict("user_id", "link").DoNothing(),
//im.OnConflictOnConstraint("unique_user_link_not_resolved").DoNothing(),
im.OnConflict("user_id", "link").Where("resolved_at IS NULL").DoNothing(),
).Exec(ctx, db.PGInstance.BobDB)
/*
notificationSetter := models.NotificationSetter{
Created: omit.From(time.Now()),
Message: omit.From(msg),
Link: omit.From(NotificationPathOauthReset),
Type: omit.From(enums.NotificationtypeOauthTokenInvalidated),
}
err := user.InsertUserNotifications(ctx, db.PGInstance.BobDB, &notificationSetter)
*/
if err != nil { if err != nil {
if strings.HasPrefix(err.Error(), "ERROR: duplicate key value violates unique constraint") { if strings.Contains(err.Error(), "ERROR: duplicate key value violates unique constraint") {
log.Info().Str("msg", msg).Int("user_id", int(user.ID)).Msg("Refusing to add another notification with the same type") log.Info().Str("msg", msg).Int("user_id", int(user.ID)).Msg("Refusing to add another notification with the same type")
return return
} }