Spaces:
Paused
Paused
File size: 11,388 Bytes
83a59ca | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 | package repositories
import (
"context"
"errors"
"fmt"
"gorm.io/gorm/clause"
"github.com/NdoleStudio/httpsms/pkg/entities"
"github.com/NdoleStudio/httpsms/pkg/telemetry"
"github.com/NdoleStudio/stacktrace"
"github.com/cockroachdb/cockroach-go/v2/crdb/crdbgorm"
"github.com/google/uuid"
"gorm.io/gorm"
)
// gormMessageRepository is responsible for persisting entities.Message
type gormMessageRepository struct {
logger telemetry.Logger
tracer telemetry.Tracer
db *gorm.DB
}
// NewGormMessageRepository creates the GORM version of the MessageRepository
func NewGormMessageRepository(
logger telemetry.Logger,
tracer telemetry.Tracer,
db *gorm.DB,
) MessageRepository {
return &gormMessageRepository{
logger: logger.WithService(fmt.Sprintf("%T", &gormMessageRepository{})),
tracer: tracer,
db: db,
}
}
func (repository *gormMessageRepository) DeleteAllForUser(ctx context.Context, userID entities.UserID) error {
ctx, span := repository.tracer.Start(ctx)
defer span.End()
if err := repository.db.WithContext(ctx).Where("user_id = ?", userID).Delete(&entities.Message{}).Error; err != nil {
return repository.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot delete all [%T] for user with ID [%s]", &entities.Message{}, userID))
}
return nil
}
// DeleteByOwnerAndContact deletes all the messages between and owner and a contact
func (repository *gormMessageRepository) DeleteByOwnerAndContact(ctx context.Context, userID entities.UserID, owner string, contact string) error {
ctx, span := repository.tracer.Start(ctx)
defer span.End()
err := repository.db.WithContext(ctx).
Where("user_id = ?", userID).
Where("owner = ?", owner).
Where("contact = ?", contact).
Delete(&entities.Message{}).
Error
if err != nil {
return repository.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot delete messages between owner [%s] and contact [%s] for user with ID [%s]", owner, contact, userID))
}
return nil
}
// Delete a message by the ID
func (repository *gormMessageRepository) Delete(ctx context.Context, userID entities.UserID, messageID uuid.UUID) error {
ctx, span := repository.tracer.Start(ctx)
defer span.End()
err := repository.db.WithContext(ctx).Where("user_id = ?", userID).Where("id = ?", messageID).Delete(&entities.Message{}).Error
if err != nil {
return repository.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot delete message with ID [%s] for user with ID [%s]", messageID, userID))
}
return nil
}
// Index entities.Message between 2 parties
func (repository *gormMessageRepository) Index(ctx context.Context, userID entities.UserID, owner string, contact string, params IndexParams) (*[]entities.Message, error) {
ctx, span := repository.tracer.Start(ctx)
defer span.End()
query := repository.db.
WithContext(ctx).
Where("user_id = ?", userID).
Where("owner = ?", owner).
Where("contact = ?", contact)
if len(params.Query) > 0 {
queryPattern := "%" + params.Query + "%"
query.Where("content ILIKE ?", queryPattern)
}
messages := new([]entities.Message)
if err := query.Order("order_timestamp DESC").Limit(params.Limit).Offset(params.Skip).Find(&messages).Error; err != nil {
return nil, repository.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot fetch messges with owner [%s] and contact [%s] and params [%+#v]", owner, contact, params))
}
return messages, nil
}
func (repository *gormMessageRepository) LastMessage(ctx context.Context, userID entities.UserID, owner string, contact string) (*entities.Message, error) {
ctx, span := repository.tracer.Start(ctx)
defer span.End()
query := repository.db.
WithContext(ctx).
Where("user_id = ?", userID).
Where("owner = ?", owner).
Where("contact = ?", contact)
message := new(entities.Message)
err := query.Order("order_timestamp DESC").First(&message).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, repository.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCodef(err, ErrCodeNotFound, "cannot get last message for [%s] with owner [%s] and contact [%s]", userID, owner, contact))
}
if err != nil {
return nil, repository.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot get last message for [%s] with owner [%s] and contact [%s]", userID, owner, contact))
}
return message, nil
}
func (repository *gormMessageRepository) Search(ctx context.Context, userID entities.UserID, owners []string, types []entities.MessageType, statuses []entities.MessageStatus, params IndexParams) ([]*entities.Message, error) {
ctx, span := repository.tracer.Start(ctx)
defer span.End()
query := repository.db.
WithContext(ctx).
Where("user_id = ?", userID)
if len(owners) > 0 {
query = query.Where("owner IN ?", owners)
}
if len(types) > 0 {
query = query.Where("type IN ?", types)
}
if len(statuses) > 0 {
query = query.Where("status IN ?", statuses)
}
if len(params.Query) > 0 {
queryPattern := "%" + params.Query + "%"
subQuery := repository.db.Where("content ILIKE ?", queryPattern).
Or("contact ILIKE ?", queryPattern).
Or("failure_reason ILIKE ?", queryPattern).
Or("request_id ILIKE ?", queryPattern)
if _, err := uuid.Parse(params.Query); err == nil {
subQuery = subQuery.Or("id = ?", params.Query)
}
query = query.Where(subQuery)
}
messages := make([]*entities.Message, 0, params.Limit)
err := query.Order(repository.order(params, "created_at")).
Limit(params.Limit).
Offset(params.Skip).
Find(&messages).
Error
if err != nil {
return nil, repository.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot search messages with for user [%s] params [%+#v]", userID, params))
}
return messages, nil
}
// GetBulkMessages fetches the last bulk message summaries for a user
func (repository *gormMessageRepository) GetBulkMessages(ctx context.Context, userID entities.UserID, limit int) ([]*entities.BulkMessage, error) {
ctx, span := repository.tracer.Start(ctx)
defer span.End()
orders := make([]*entities.BulkMessage, 0)
err := repository.db.WithContext(ctx).Raw(`
SELECT
request_id,
COUNT(*) as total,
COUNT(*) FILTER (WHERE status = 'scheduled') as scheduled_count,
COUNT(*) FILTER (WHERE status = 'pending') as pending_count,
COUNT(*) FILTER (WHERE status = 'failed') as failed_count,
COUNT(*) FILTER (WHERE status = 'expired') as expired_count,
COUNT(*) FILTER (WHERE status = 'sent') as sent_count,
COUNT(*) FILTER (WHERE status = 'delivered') as delivered_count,
MIN(created_at) as created_at
FROM messages
WHERE user_id = ? AND request_id LIKE 'bulk-%'
GROUP BY request_id
ORDER BY MIN(created_at) DESC
LIMIT ?
`, userID, limit).Scan(&orders).Error
if err != nil {
return nil, repository.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot fetch bulk message orders for user [%s]", userID))
}
return orders, nil
}
// Store a new entities.Message
func (repository *gormMessageRepository) Store(ctx context.Context, message *entities.Message) error {
ctx, span := repository.tracer.Start(ctx)
defer span.End()
if err := repository.db.WithContext(ctx).Create(message).Error; err != nil {
return repository.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot save message with ID [%s]", message.ID))
}
return nil
}
// Load an entities.Message by ID
func (repository *gormMessageRepository) Load(ctx context.Context, userID entities.UserID, messageID uuid.UUID) (*entities.Message, error) {
ctx, span := repository.tracer.Start(ctx)
defer span.End()
message := new(entities.Message)
err := repository.db.WithContext(ctx).Where("user_id = ?", userID).Where("id = ?", messageID).First(message).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, repository.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCodef(err, ErrCodeNotFound, "message with ID [%s] and userID [%s] does not exist", messageID, userID))
}
if err != nil {
return nil, repository.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot load message with ID [%s]", messageID))
}
return message, nil
}
// Update an entities.Message
func (repository *gormMessageRepository) Update(ctx context.Context, message *entities.Message) error {
ctx, span := repository.tracer.Start(ctx)
defer span.End()
// Send attempts are owned by the atomic increment, not a loaded status snapshot.
if err := repository.db.WithContext(ctx).Omit("send_attempt_count").Save(message).Error; err != nil {
return repository.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot update message with ID [%s]", message.ID))
}
return nil
}
func (repository *gormMessageRepository) IncreaseSendAttemptCount(ctx context.Context, userID entities.UserID, messageID uuid.UUID) error {
ctx, span := repository.tracer.Start(ctx)
defer span.End()
result := repository.db.WithContext(ctx).
Model(&entities.Message{}).
Where("user_id = ?", userID).
Where("id = ?", messageID).
Update("send_attempt_count", gorm.Expr("send_attempt_count + ?", 1))
if result.Error != nil {
return repository.tracer.WrapErrorSpan(span, stacktrace.Propagatef(result.Error, "cannot increment send attempts for message [%s] for user [%s]", messageID, userID))
}
if result.RowsAffected == 0 {
return repository.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCodef(gorm.ErrRecordNotFound, ErrCodeNotFound, "message [%s] for user [%s] does not exist", messageID, userID))
}
return nil
}
// GetOutstanding fetches messages that still to be sent to the phone
func (repository *gormMessageRepository) GetOutstanding(ctx context.Context, userID entities.UserID, messageID uuid.UUID, phoneNumbers []string) (*entities.Message, error) {
ctx, span := repository.tracer.Start(ctx)
defer span.End()
message := new(entities.Message)
err := crdbgorm.ExecuteTx(
ctx, repository.db, nil,
func(tx *gorm.DB) error {
query := tx.WithContext(ctx).Model(message).
Clauses(clause.Returning{}).
Where("user_id = ?", userID).
Where("id = ?", messageID)
if len(phoneNumbers) > 0 {
query = query.Where("owner IN ?", phoneNumbers)
}
return query.Where(repository.db.Where("status = ?", entities.MessageStatusScheduled).Or("status = ?", entities.MessageStatusPending).Or("status = ?", entities.MessageStatusExpired)).
Update("status", entities.MessageStatusSending).Error
},
)
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, repository.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCodef(err, ErrCodeNotFound, "outstanding message with ID [%s] and userID [%s] does not exist", messageID, userID))
}
if err != nil {
return nil, repository.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot fetch outstanding message with userID [%s] and messageID [%s]", userID, messageID))
}
if message == nil || message.ID == uuid.Nil {
return nil, repository.tracer.WrapErrorSpan(span, stacktrace.NewErrorWithCodef(ErrCodeNotFound, "outstanding message with ID [%s] and userID [%s] does not exist", messageID, userID))
}
return message, nil
}
func (repository *gormMessageRepository) order(params IndexParams, defaultSortBy string) string {
sortBy := defaultSortBy
if len(params.SortBy) > 0 {
sortBy = params.SortBy
}
direction := "ASC"
if params.SortDescending {
direction = "DESC"
}
return fmt.Sprintf("%s %s", sortBy, direction)
}
|