🔍 Code Extractor

function run_server

Maturity: 44

Initializes and runs an asynchronous SMTP server with platform-specific event loop configuration and error handling.

File:
/tf/active/vicechatdev/email-forwarder/src/main.py
Lines:
75 - 93
Complexity:
moderate

Purpose

This function serves as the entry point for starting an SMTP server application. It handles platform-specific asyncio event loop setup (particularly for Windows), creates a new event loop, executes the main server coroutine, and ensures proper cleanup. It includes error handling to catch startup failures and exit gracefully with appropriate error messages.

Source Code

def run_server():
    """Run the server with proper event loop handling."""
    try:
        if sys.platform == 'win32':
            # Windows specific event loop policy
            asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
        
        # Create and run event loop
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        
        try:
            loop.run_until_complete(main())
        finally:
            loop.close()
            
    except Exception as e:
        print(f"Failed to start server: {e}")
        sys.exit(1)

Return Value

This function does not return any value. It either runs the server successfully until completion or exits the program with status code 1 if an exception occurs during startup.

Dependencies

  • asyncio
  • sys
  • logging
  • signal
  • datetime

Required Imports

import asyncio
import sys
import logging
import signal
from datetime import datetime
from config import settings
from utils.logger import setup_logging
from forwarder.smtp_server import SMTPServer

Usage Example

# Assuming all required modules and main() coroutine are defined
import asyncio
import sys
from config import settings
from utils.logger import setup_logging
from forwarder.smtp_server import SMTPServer

async def main():
    """Main server coroutine."""
    server = SMTPServer()
    await server.start()
    # Keep server running
    await asyncio.Event().wait()

def run_server():
    """Run the server with proper event loop handling."""
    try:
        if sys.platform == 'win32':
            asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
        
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        
        try:
            loop.run_until_complete(main())
        finally:
            loop.close()
            
    except Exception as e:
        print(f"Failed to start server: {e}")
        sys.exit(1)

if __name__ == '__main__':
    run_server()

Best Practices

  • This function should be called as the main entry point of the application, typically in an 'if __name__ == "__main__"' block
  • Ensure the 'main()' coroutine is defined before calling run_server()
  • The function handles Windows-specific event loop requirements automatically, making it cross-platform compatible
  • Always ensure proper cleanup of resources in the main() coroutine as the event loop will be closed after execution
  • The function uses sys.exit(1) on failure, so it should only be used in top-level application code, not in library functions
  • Consider implementing signal handlers in the main() coroutine for graceful shutdown (SIGTERM, SIGINT)
  • The event loop is explicitly closed in the finally block to prevent resource leaks

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function run_smtp_server 89.9% similar

    Initializes and runs an asynchronous SMTP server using a new event loop, with proper error handling and graceful shutdown.

    From: /tf/active/vicechatdev/email-forwarder/src/forwarder/smtp_server.py
  • function main_v9 69.9% similar

    Asynchronous main entry point function that initializes and runs an email forwarding SMTP server with logging, configuration validation, and graceful shutdown handling.

    From: /tf/active/vicechatdev/email-forwarder/src/main.py
  • class SMTPServer 64.2% similar

    SMTPServer is a class that manages an SMTP server for receiving emails, handling their forwarding, and providing server statistics.

    From: /tf/active/vicechatdev/email-forwarder/src/forwarder/smtp_server.py
  • class TestSmtpServer 60.5% similar

    A test class for validating the functionality of the SmtpServer class, including server startup, email handling, email forwarding, and error handling for invalid inputs.

    From: /tf/active/vicechatdev/email-forwarder/tests/test_smtp_server.py
  • function main_v69 54.7% similar

    Command-line interface function that parses arguments and sends a test email through an SMTP forwarder service, displaying connection details and returning an exit code based on success.

    From: /tf/active/vicechatdev/email-forwarder/send_test_email.py
← Back to Browse