All files / src/storage EventStorage.js

100% Statements 88/88
77.41% Branches 24/31
100% Functions 13/13
100% Lines 88/88

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 3496x 6x 6x                                 31x           31x 31x   31x             2x 2x       2x 2x 2x   2x                             2x 2x   2x           2x 1x 1x     1x 1x               3x 3x               3x 2x     1x 1x               2x 2x                           2x 1x     1x 1x               2x 2x 2x   2x                     2x 1x     1x 1x               2x 2x   2x                       2x 1x     1x 1x               2x 2x                         2x 1x     1x 1x               2x 2x               2x 1x     1x 1x               3x 3x                     3x 1x     3x   3x   2x           1x 1x               3x   3x     3x                               3x 2x     2x 1x       1x 1x               5x   5x     5x                               5x     4x 5x     4x     1x 1x         6x
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
const { DynamoDBDocumentClient, PutCommand, GetCommand, QueryCommand, UpdateCommand, DeleteCommand } = require('@aws-sdk/lib-dynamodb');
const { v4: uuidv4 } = require('uuid');
 
/**
 * EventStorage - Manages event data in DynamoDB
 * 
 * Provides persistent storage for community events with automatic cleanup and reminder tracking.
 * Uses DynamoDB for scalability and automatic TTL-based cleanup of old events.
 * 
 * Storage design rationale:
 * - DynamoDB provides serverless scaling for varying community sizes
 * - TTL automatically removes old events without manual cleanup
 * - Composite keys enable efficient querying by guild and time ranges
 * - Document model allows flexible event metadata without schema changes
 */
class EventStorage {
    constructor(tableName, region = 'us-west-2') {
        // Create DynamoDB v3 client
        const client = new DynamoDBClient({ 
            region,
            maxAttempts: 3,
            requestTimeout: 30000
        });
        
        this.docClient = DynamoDBDocumentClient.from(client);
        this.tableName = tableName || process.env.DYNAMODB_EVENTS_TABLE || 'discord-events-main';
        
        console.log(`EventStorage initialized with table: ${this.tableName}`);
    }
 
    /**
     * Create a new event
     */
    async createEvent(guildId, eventData) {
        const eventId = uuidv4();
        const now = new Date().toISOString();
        
        // Calculate TTL for automatic cleanup (30 days after event date)
        // This prevents the table from growing indefinitely with historical events
        const eventDate = new Date(eventData.eventDate);
        const ttlDate = new Date(eventDate.getTime() + (30 * 24 * 60 * 60 * 1000));
        const ttl = Math.floor(ttlDate.getTime() / 1000);
 
        const event = {
            guild_id: guildId,
            event_id: eventId,
            name: eventData.name,
            description: eventData.description || '',
            region: eventData.region,
            location: eventData.location || '',
            event_date: eventData.eventDate, // Should already be ISO string from EventManager validation
            link: eventData.link || '',
            created_by: eventData.createdBy,
            created_at: now,
            reminder_status: 'pending', // pending, week_sent, day_sent, completed
            ttl: ttl
        };
 
        try {
            console.log('Creating event in DynamoDB:', { eventId, name: event.name });
            
            const command = new PutCommand({
                TableName: this.tableName,
                Item: event,
                ConditionExpression: 'attribute_not_exists(event_id)' // Prevent overwrites
            });
 
            await this.docClient.send(command);
            console.log('✅ Event created successfully in DynamoDB');
            return event;
            
        } catch (error) {
            console.error('Error creating event in DynamoDB:', error);
            throw new Error('Failed to create event');
        }
    }
 
    /**
     * Get event by ID
     */
    async getEvent(guildId, eventId) {
        try {
            const command = new GetCommand({
                TableName: this.tableName,
                Key: {
                    guild_id: guildId,
                    event_id: eventId
                }
            });
 
            const result = await this.docClient.send(command);
            return result.Item || null;
            
        } catch (error) {
            console.error(`Error getting event ${eventId}:`, error);
            throw error;
        }
    }
 
    /**
     * Get events by region
     */
    async getEventsByRegion(guildId, region) {
        try {
            const command = new QueryCommand({
                TableName: this.tableName,
                IndexName: 'region-index',
                KeyConditionExpression: 'guild_id = :guildId AND #region = :region',
                ExpressionAttributeNames: {
                    '#region': 'region'
                },
                ExpressionAttributeValues: {
                    ':guildId': guildId,
                    ':region': region
                },
                ScanIndexForward: true // Sort by range key ascending
            });
 
            const result = await this.docClient.send(command);
            return result.Items || [];
            
        } catch (error) {
            console.error(`Error getting events for region ${region}:`, error);
            return [];
        }
    }
 
    /**
     * Get upcoming events for reminders (next 7 days)
     */
    async getUpcomingEvents(guildId) {
        try {
            const now = new Date().toISOString();
            const weekFromNow = new Date(Date.now() + (7 * 24 * 60 * 60 * 1000)).toISOString();
            
            const command = new QueryCommand({
                TableName: this.tableName,
                IndexName: 'date-index',
                KeyConditionExpression: 'guild_id = :guildId AND event_date BETWEEN :now AND :weekFromNow',
                ExpressionAttributeValues: {
                    ':guildId': guildId,
                    ':now': now,
                    ':weekFromNow': weekFromNow
                }
            });
 
            const result = await this.docClient.send(command);
            return result.Items || [];
            
        } catch (error) {
            console.error('Error getting upcoming events:', error);
            return [];
        }
    }
 
    /**
     * Get all future events (no time limit) - for command listings
     */
    async getAllUpcomingEvents(guildId, limit = 50) {
        try {
            const now = new Date().toISOString();
            
            const command = new QueryCommand({
                TableName: this.tableName,
                IndexName: 'date-index',
                KeyConditionExpression: 'guild_id = :guildId AND event_date >= :now',
                ExpressionAttributeValues: {
                    ':guildId': guildId,
                    ':now': now
                },
                Limit: limit,
                ScanIndexForward: true // Chronological order (earliest first)
            });
 
            const result = await this.docClient.send(command);
            return result.Items || [];
            
        } catch (error) {
            console.error('Error getting all upcoming events:', error);
            return [];
        }
    }
 
    /**
     * Update event reminder status
     */
    async updateReminderStatus(guildId, eventId, status) {
        try {
            const command = new UpdateCommand({
                TableName: this.tableName,
                Key: {
                    guild_id: guildId,
                    event_id: eventId
                },
                UpdateExpression: 'SET reminder_status = :status, updated_at = :now',
                ExpressionAttributeValues: {
                    ':status': status,
                    ':now': new Date().toISOString()
                }
            });
 
            await this.docClient.send(command);
            console.log(`Updated reminder status for event ${eventId}: ${status}`);
            
        } catch (error) {
            console.error(`Error updating reminder status for event ${eventId}:`, error);
            throw error;
        }
    }
 
    /**
     * Delete event
     */
    async deleteEvent(guildId, eventId) {
        try {
            const command = new DeleteCommand({
                TableName: this.tableName,
                Key: {
                    guild_id: guildId,
                    event_id: eventId
                }
            });
 
            await this.docClient.send(command);
            console.log(`Deleted event ${eventId}`);
            
        } catch (error) {
            console.error(`Error deleting event ${eventId}:`, error);
            throw error;
        }
    }
 
    /**
     * Get all events for guild (with pagination)
     */
    async getAllEvents(guildId, limit = 50, lastEvaluatedKey = null) {
        try {
            const queryParams = {
                TableName: this.tableName,
                KeyConditionExpression: 'guild_id = :guildId',
                ExpressionAttributeValues: {
                    ':guildId': guildId
                },
                Limit: limit,
                ScanIndexForward: false // Most recent first
            };
            
            // Only add ExclusiveStartKey if it's not null
            if (lastEvaluatedKey) {
                queryParams.ExclusiveStartKey = lastEvaluatedKey;
            }
            
            const command = new QueryCommand(queryParams);
 
            const result = await this.docClient.send(command);
            
            return {
                events: result.Items || [],
                lastEvaluatedKey: result.LastEvaluatedKey
            };
            
        } catch (error) {
            console.error('Error getting all events:', error);
            return { events: [], lastEvaluatedKey: null };
        }
    }
 
    /**
     * Get upcoming events for a specific region (next 3, includes events up to 1h after start)
     */
    async getUpcomingEventsByRegion(guildId, region, limit = 3) {
        try {
            // Show events up to 1 hour after they started
            const cutoffTime = new Date(Date.now() - (1 * 60 * 60 * 1000)).toISOString();
            
            // Use date-index to efficiently query by date range, then filter by region
            const command = new QueryCommand({
                TableName: this.tableName,
                IndexName: 'date-index',
                KeyConditionExpression: 'guild_id = :guildId AND event_date >= :cutoffTime',
                FilterExpression: '#region = :region',
                ExpressionAttributeNames: {
                    '#region': 'region'
                },
                ExpressionAttributeValues: {
                    ':guildId': guildId,
                    ':region': region,
                    ':cutoffTime': cutoffTime
                },
                ScanIndexForward: true // Earliest first
            });
 
            const result = await this.docClient.send(command);
            const items = result.Items || [];
            
            // Sort by event_date and limit to requested number
            return items
                .sort((a, b) => a.event_date.localeCompare(b.event_date))
                .slice(0, limit);
            
        } catch (error) {
            console.error(`Error getting upcoming events for region ${region}:`, error);
            return [];
        }
    }
 
    /**
     * Get upcoming events for a specific location (next 3, includes events up to 1h after start)
     */
    async getUpcomingEventsByLocation(guildId, location, limit = 3) {
        try {
            // Show events up to 1 hour after they started
            const cutoffTime = new Date(Date.now() - (1 * 60 * 60 * 1000)).toISOString();
            
            // Use date-index to efficiently query by date range, then filter by location
            const command = new QueryCommand({
                TableName: this.tableName,
                IndexName: 'date-index',
                KeyConditionExpression: 'guild_id = :guildId AND event_date >= :cutoffTime',
                FilterExpression: '#location = :location',
                ExpressionAttributeNames: {
                    '#location': 'location'
                },
                ExpressionAttributeValues: {
                    ':guildId': guildId,
                    ':location': location,
                    ':cutoffTime': cutoffTime
                },
                ScanIndexForward: true
            });
 
            const result = await this.docClient.send(command);
            
            // Sort by event date since we can't use an index for location + date
            const sortedEvents = (result.Items || []).sort((a, b) => 
                new Date(a.event_date) - new Date(b.event_date)
            );
            
            return sortedEvents.slice(0, limit);
            
        } catch (error) {
            console.error(`Error getting upcoming events for location ${location}:`, error);
            return [];
        }
    }
}
 
module.exports = EventStorage;