Files
PriceUpdaterAppv2/.kiro/specs/scheduled-price-updates/design.md

9.3 KiB

Design Document

Overview

The scheduled price updates feature extends the existing Shopify Price Updater with optional scheduling capabilities. This allows users to configure price updates or rollbacks to execute at specific future times without requiring manual intervention. The design maintains backward compatibility while adding a new scheduling layer that wraps the existing application logic.

Architecture

High-Level Architecture

The scheduling functionality will be implemented as a wrapper around the existing ShopifyPriceUpdater class, using Node.js's built-in setTimeout for scheduling and the node-cron library for more advanced scheduling patterns if needed in the future.

┌─────────────────────────────────────────────────────────────┐
│                    Scheduled Execution Layer                │
├─────────────────────────────────────────────────────────────┤
│  ScheduleManager                                           │
│  - Parse scheduled time                                     │
│  - Validate scheduling parameters                           │
│  - Handle countdown display                                 │
│  - Manage cancellation signals                              │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                 Existing Application Layer                  │
├─────────────────────────────────────────────────────────────┤
│  ShopifyPriceUpdater (unchanged)                           │
│  - Product fetching and validation                          │
│  - Price update/rollback operations                         │
│  - Error handling and logging                               │
└─────────────────────────────────────────────────────────────┘

Integration Approach

The scheduling feature will be integrated at the entry point (src/index.js) with minimal changes to existing code:

  1. Environment Configuration: Add SCHEDULED_EXECUTION_TIME to environment validation
  2. Execution Flow: Modify the main execution flow to check for scheduling before running operations
  3. Scheduling Service: Create a new ScheduleService to handle all scheduling logic
  4. Graceful Cancellation: Enhance existing signal handlers to support scheduled operation cancellation

Components and Interfaces

1. ScheduleService

Location: src/services/schedule.js

Responsibilities:

  • Parse and validate scheduled execution times
  • Calculate delay until execution
  • Display countdown and status messages
  • Handle cancellation signals during waiting period
  • Execute the scheduled operation at the specified time

Interface:

class ScheduleService {
  constructor(logger)

  // Parse and validate scheduled time from environment variable
  parseScheduledTime(scheduledTimeString): Date

  // Calculate milliseconds until scheduled execution
  calculateDelay(scheduledTime): number

  // Display scheduling confirmation and countdown
  displayScheduleInfo(scheduledTime): Promise<void>

  // Wait until scheduled time with cancellation support
  waitUntilScheduledTime(scheduledTime, onCancel): Promise<boolean>

  // Execute the scheduled operation
  executeScheduledOperation(operationCallback): Promise<number>
}

2. Environment Configuration Updates

Location: src/config/environment.js

Changes:

  • Add SCHEDULED_EXECUTION_TIME as optional environment variable
  • Add validation for datetime format when provided
  • Ensure backward compatibility when scheduling is not used

New Configuration Properties:

{
  // ... existing properties
  scheduledExecutionTime: string | null, // ISO 8601 datetime or null
  isScheduled: boolean // derived property for convenience
}

3. Main Application Updates

Location: src/index.js

Changes:

  • Integrate ScheduleService into the main execution flow
  • Add scheduling logic before existing operation execution
  • Enhance signal handlers to support scheduled operation cancellation
  • Maintain all existing functionality when scheduling is not used

Data Models

Scheduled Execution Configuration

{
  scheduledTime: Date,           // Parsed execution time
  originalTimeString: string,    // Original input for logging
  delayMs: number,              // Milliseconds until execution
  timezone: string,             // Detected or specified timezone
  isValid: boolean,             // Validation result
  validationError: string | null // Error message if invalid
}

Schedule Status

{
  status: 'waiting' | 'executing' | 'cancelled' | 'completed',
  scheduledTime: Date,
  currentTime: Date,
  remainingMs: number,
  countdownDisplay: string
}

Error Handling

Scheduling-Specific Errors

  1. Invalid DateTime Format

    • Error: Clear message explaining expected format (ISO 8601)
    • Action: Exit with status code 1
    • Logging: Log error to console and progress file
  2. Past DateTime

    • Error: Message indicating scheduled time is in the past
    • Action: Exit with status code 1
    • Logging: Log error with current time for reference
  3. System Clock Issues

    • Error: Handle cases where system time is unreliable
    • Action: Display warning but continue if reasonable
    • Logging: Log warning about potential timing issues

Execution-Time Errors

  1. Network Issues During Scheduled Execution

    • Behavior: Use existing retry logic from ShopifyPriceUpdater
    • Enhancement: Add context that this was a scheduled operation
    • Logging: Include scheduling information in error logs
  2. Cancellation During Execution

    • Behavior: Allow graceful cancellation during waiting period
    • Restriction: Cannot cancel once actual price updates begin
    • Logging: Log cancellation with timestamp and reason

Testing Strategy

Unit Tests

  1. ScheduleService Tests

    • DateTime parsing with various formats
    • Delay calculation accuracy
    • Validation logic for edge cases
    • Cancellation handling
  2. Environment Configuration Tests

    • Optional scheduling parameter handling
    • Backward compatibility verification
    • Invalid datetime format handling
  3. Integration Tests

    • End-to-end scheduling workflow
    • Cancellation during waiting period
    • Scheduled execution with both update and rollback modes

Test Scenarios

  1. Valid Scheduling Scenarios

    • Schedule update operation 5 minutes in future
    • Schedule rollback operation with timezone specification
    • Schedule operation without timezone (use system default)
  2. Error Scenarios

    • Invalid datetime formats
    • Past datetime values
    • Extremely distant future dates (>7 days warning)
  3. Cancellation Scenarios

    • Cancel during countdown period
    • Attempt to cancel during execution (should not interrupt)
    • Multiple cancellation signals
  4. Backward Compatibility

    • Run existing operations without scheduling
    • Ensure no performance impact when scheduling not used
    • Verify all existing environment variables still work

Implementation Considerations

DateTime Handling

  • Primary Format: ISO 8601 (YYYY-MM-DDTHH:MM:SS)
  • Timezone Support: Accept timezone suffixes or default to system timezone
  • Validation: Strict parsing with clear error messages for invalid formats
  • Edge Cases: Handle daylight saving time transitions

Performance Impact

  • Minimal Overhead: Scheduling logic only active when SCHEDULED_EXECUTION_TIME is set
  • Memory Usage: Minimal additional memory for scheduling state
  • CPU Usage: Efficient countdown display (update every 30 seconds, not every second)

User Experience

  • Clear Feedback: Immediate confirmation of scheduled time
  • Progress Indication: Countdown display showing time remaining
  • Cancellation: Clear instructions on how to cancel (Ctrl+C)
  • Logging: All scheduling events logged to Progress.md file

Security Considerations

  • Input Validation: Strict datetime parsing to prevent injection attacks
  • Resource Limits: Reasonable limits on future scheduling (warning for >7 days)
  • Process Management: Proper cleanup of timers and resources on cancellation

Deployment Considerations

  • Dependencies: Minimal new dependencies (prefer built-in Node.js features)
  • Environment Variables: Optional configuration maintains backward compatibility
  • Process Management: Works with existing process managers and containers
  • Logging: Scheduling events integrate with existing logging infrastructure