Skip to content

A FastAPI-based microservice for tracking Near-Earth Objects (NEOs) deployed on Google Cloud Run with real-time astronomical calculations and geocentric coordinate precision

Notifications You must be signed in to change notification settings

AlverGant/neo-tracker-api

Repository files navigation

🌌 NEO Tracker API

A FastAPI-based microservice for tracking Near-Earth Objects (NEOs) deployed on Google Cloud Run with real-time astronomical calculations and geocentric coordinate precision.

πŸš€ Overview

This API service provides real-time asteroid tracking, visibility predictions, and comprehensive astronomical data using NASA's JPL services. Features real-time geocentric coordinate calculations, automatic caching, and scalable deployment on Google Cloud Run.

✨ Features

🌌 Real-time NEO Data

  • Live data from NASA JPL CAD API
  • Real astronomical calculations using JPL Horizons
  • Geocentric coordinate calculations with 3-hour refresh intervals
  • Intelligent distance tracking - distance_km field with prioritized data sources:
    • πŸ₯‡ CAD API - Official NASA approach distances (most reliable for recent asteroids)
    • πŸ₯ˆ JPL Horizons - Real-time geocentric coordinates (when available)
    • πŸ₯‰ Calculated fallback - Computed from orbital parameters
  • 3D coordinate support - Optional geocentric X,Y,Z coordinates via include_3d_coords=true
  • Location-based visibility calculations with altitude/azimuth precision
  • Background cache refresh every 3 hours for optimal data freshness

πŸ“Š API Endpoints

  • GET /neos - Get NEO data with customizable parameters and real-time coordinates
  • GET /neos/visible - Get currently visible NEOs based on location and time
  • GET /neos/{neo_id}/visibility - Get 5-day visibility prediction for specific NEO
  • POST /cache/refresh - Manually trigger cache refresh and coordinate recalculation
  • GET /health - Health check with cache status and coordinate update timestamps

βš™οΈ Configuration Parameters

  • mag_limit - Telescope magnitude limit (default: 16.0, max: 35.0 to handle all detected NEOs)
  • visibility_mag_limit - Client-side magnitude filtering (default: 16.0, max: 35.0)
  • min_altitude - Minimum observation altitude (default: 0.0Β° - horizon)
  • latitude/longitude - Observation location (default: Rio de Janeiro -22.9068, -43.1729)
  • days_interval - Search interval (default: 7 days)
  • total_days - Total search period (default: 30 days)
  • dist_max_au - Maximum distance in AU (default: 1.0)
  • top_asteroids_count - Number of asteroids to process (default: 200)
  • include_3d_coords - Include geocentric 3D coordinates (default: false)
  • use_jpl_horizons - Enable enhanced JPL Horizons calculations (default: false)

πŸ› οΈ Technical Stack

  • FastAPI - Modern Python web framework
  • Astropy - Astronomical calculations
  • Astroquery - JPL Horizons integration
  • Docker - Containerization
  • Google Cloud Run - Serverless deployment
  • Terraform - Infrastructure as Code

Getting Started

Prerequisites

  • Python 3.11+
  • Docker
  • Google Cloud CLI
  • Terraform (for infrastructure deployment)

Local Development

  1. Install dependencies:
pip install -r requirements.txt
  1. Run locally:
python main.py
# API will be available at http://localhost:8080
  1. Test API:
curl http://localhost:8080/health
curl http://localhost:8080/neos

Docker Development

  1. Build Docker image:
docker build -t neo-tracker-api .
  1. Run container:
docker run -p 8080:8080 neo-tracker-api

πŸš€ Deployment

Option 1: Using Deployment Script

  1. Provide required project and bucket information:
./deploy.sh -p your-project-id -b your-cache-bucket -r us-central1

Option 2: Using Terraform

  1. Setup Terraform:
cd terraform
cp terraform.tfvars.example terraform.tfvars
# Edit terraform.tfvars with your values
  1. Deploy infrastructure:
terraform init
terraform plan
terraform apply

Option 3: Manual Cloud Run Deployment

  1. Build and push to Google Container Registry:
gcloud builds submit --tag gcr.io/PROJECT_ID/neo-tracker-api
  1. Deploy to Cloud Run:
gcloud run deploy neo-tracker-api \
  --image gcr.io/PROJECT_ID/neo-tracker-api \
  --platform managed \
  --region us-central1 \
  --allow-unauthenticated \
  --memory 4Gi \
  --cpu 2 \
  --timeout 900

πŸ“ Project Structure

neo-tracker-api/
β”œβ”€β”€ main.py                 # FastAPI application
β”œβ”€β”€ neo_service.py          # NEO data processing service
β”œβ”€β”€ Dockerfile              # Container configuration
β”œβ”€β”€ requirements.txt        # Python dependencies
β”œβ”€β”€ deploy.sh               # Deployment script
β”œβ”€β”€ terraform/              # Infrastructure as Code
β”‚   β”œβ”€β”€ main.tf
β”‚   β”œβ”€β”€ variables.tf
β”‚   β”œβ”€β”€ outputs.tf
β”‚   └── terraform.tfvars.example
└── README.md               # This documentation

πŸ”§ Configuration

Environment Variables

  • PORT - Server port (default: 8080)
  • LOG_LEVEL - Logging level (default: INFO)

Google Cloud Resources

  • Memory: 4GB (configurable)
  • CPU: 2 vCPUs (configurable)
  • Timeout: 15 minutes
  • Auto-scaling: 0 to 10 instances

πŸ“Š API Usage Examples

Get NEOs with custom parameters:

curl "https://your-service-url/neos?mag_limit=14&min_altitude=5&latitude=-23.5&longitude=-46.6"

Get NEOs with 3D coordinates:

curl "https://your-service-url/neos?latitude=-22.9068&longitude=-43.1729&include_3d_coords=true"

Get currently visible NEOs:

curl "https://your-service-url/neos/visible"

Manual cache refresh:

curl -X POST "https://your-service-url/cache/refresh"

πŸ”„ Caching Strategy

  • Background refresh: Every 3 hours for optimal data freshness
  • Geocentric coordinates: Updated every 3 hours with real-time Earth-asteroid distances
  • Manual refresh: POST /cache/refresh endpoint triggers immediate coordinate recalculation
  • Location-based: Separate cache per observation location
  • Memory caching: In-memory cache for fast response times
  • Distance accuracy: distance_km field reflects real-time current distance from Earth

Understanding Distance Data

The distance_km field uses intelligent source prioritization for maximum reliability:

Data Source Priority:

  1. πŸ₯‡ CAD API - Official NASA approach distances (most reliable for recent asteroids)

    • Used for asteroids with recent approach dates
    • Provides precise distance at closest approach
    • Ideal for newly discovered NEOs like 2025 PN
  2. πŸ₯ˆ JPL Horizons - Real-time geocentric coordinates (when available)

    • Real-time calculated distances
    • Light-time corrected values
    • Updates every 3 hours with cache refresh
  3. πŸ₯‰ Calculated Fallback - Computed from orbital parameters

    • Mathematical estimation when APIs are unavailable
    • Ensures distance_km is never null

Note: For very recent asteroids, CAD approach distance may be used as current distance estimate.

🌍 3D Coordinate Support

Optional geocentric 3D coordinates available via include_3d_coords=true:

New Response Fields:

  • x_km - X coordinate in geocentric ecliptic J2000 frame (km)
  • y_km - Y coordinate in geocentric ecliptic J2000 frame (km)
  • z_km - Z coordinate in geocentric ecliptic J2000 frame (km)
  • coords_epoch - Timestamp when 3D coordinates were calculated

Usage:

  • Ideal for 3D visualization and mapping applications
  • Integrated with standard coordinate queries for efficiency
  • Cached with standard coordinate data for performance

🚨 Error Handling

  • Comprehensive error responses with detailed messages
  • Automatic fallback to cached data when NASA APIs are unavailable
  • Health check endpoint for monitoring
  • Structured logging for debugging

πŸ“ˆ Performance Considerations

  • Async processing: All NASA API calls are asynchronous
  • Resource optimization: Configurable CPU/memory limits
  • Auto-scaling: Scales to zero when not in use
  • Caching: Reduces API calls and improves response times

πŸ”’ Security

  • Service account with minimal required permissions
  • Container runs as non-root user
  • CORS properly configured for React Native
  • Input validation and sanitization

πŸ› Troubleshooting

Common Issues

  1. API returns empty results

    • Check search parameters (distance, magnitude limits)
    • Verify time window has NEOs in range
    • Use /cache/refresh to update data
  2. Slow response times

    • NASA APIs can be slow during peak hours
    • Consider adjusting timeout settings
    • Check Cloud Run instance memory allocation
  3. Build failures

    • Verify Python version compatibility
    • Check all dependencies in requirements.txt
    • Ensure Docker has sufficient resources

πŸ“ž Support

  • Health check: GET /health
  • API documentation: Available at /docs when running
  • Logs: Check Cloud Run logs in Google Cloud Console

License

This project is licensed under the MIT License.


NEO Tracker API v1.2.0 - Real-time geocentric coordinate tracking with enhanced distance calculations

About

A FastAPI-based microservice for tracking Near-Earth Objects (NEOs) deployed on Google Cloud Run with real-time astronomical calculations and geocentric coordinate precision

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •