UptimeFlare Documentation

repository·main·Indexed 25 days ago

https://github.com/lyc8503/uptimeflare

A serverless uptime monitoring service and status page provider built on Cloudflare Workers. It supports HTTP, HTTPS, and TCP port monitoring across 310+ global nodes, providing up to 90 days of history, customizable status pages with interactive ping charts, and notifications via Apprise and custom Webhooks. The system utilizes Cloudflare Durable Objects and D1 databases for distributed checking and state storage.

Tokens
4.4K
Snippets
6
Records
19
Agent score
86%

What's inside UptimeFlare

  1. Overview of UptimeFlare

    main

    UptimeFlare is a feature-rich, serverless, and free uptime monitoring and status page solution powered by Cloudflare Workers. It is open-source and designed for easy deployment (under 10 minutes) without requiring local tools.

    Key Monitoring Features

    • Scale: Supports up to 50 checks with 1-minute precision.
    • Global Nodes: Monitoring nodes available in over 310+ Cloudflare cities.
    • Protocols: Supports HTTP, HTTPS, and TCP port monitoring.
    • History: Up to 90 days of uptime history and percentage tracking.
    • Customization: Supports custom HTTP(s) methods, headers, bodies, status codes, and keyword checks.
    • Notifications: Supports over 100 notification channels via Apprise and custom Webhooks.
    • Localization: Supports English and Chinese.

    Status Page Features

    • Visualization: Interactive ping (response time) charts for all monitor types.
    • UI: Responsive design for PC/Mobile with Light/Dark mode support.
    • Customization: Rich configuration options, including custom domains (via CNAME) and optional password protection for private status pages.
    • Data Access: Provides a JSON API for retrieving real-time status data.
  2. Configure Monitors via WorkerConfig

    main

    The WorkerConfig object contains the monitors array where you define the health checks.

    HTTP Monitors

    Set method to a valid HTTP method (e.g., GET, POST).

    • id: Unique identifier (required for history tracking).
    • target: The URL to check.
    • expectedCodes: Array of acceptable HTTP response codes (defaults to 2xx).
    • timeout: Timeout in milliseconds (defaults to 10000).
    • headers: Object containing HTTP headers to send.
    • body: String body (required for POST, PUT, or PATCH).
    • responseKeyword: The response must contain this string to be considered operational.
    • responseForbiddenKeyword: The response must NOT contain this string to be considered operational.
    • checkProxy: Use for geo-specific checks. Supports worker://, globalping://, and http(s)://.
    • checkProxyFallback: If true, falls back to local check if the proxy is down.

    TCP Monitors

    Set method to TCP_PING.

    • target: Must be in host:port format (e.g., 1.2.3.4:22).
    • timeout: Timeout in milliseconds.
    const workerConfig: WorkerConfig = {
      monitors: [
        {
          id: 'foo_monitor',
          name: 'My API Monitor',
          method: 'GET',
          target: 'https://example.com',
          expectedCodes: [200],
          timeout: 10000,
          headers: {
            'User-Agent': 'Uptimeflare',
          },
        },
        {
          id: 'test_tcp_monitor',
          name: 'Example TCP Monitor',
          method: 'TCP_PING',
          target: '1.2.3.4:22',
          timeout: 5000,
        },
      ],
    }
  3. Configure the Status Page via PageConfig

    main

    Use PageConfig to customize the appearance of your public status page. You can set a global title and define a list of header links. Links can be highlighted using the highlight property.

    const pageConfig: PageConfig = {
      title: "lyc8503's Status Page",
      links: [
        { link: 'https://github.com/lyc8503', label: 'GitHub' },
        { link: 'https://blog.lyc8503.net/', label: 'Blog' },
        { link: 'mailto:me@lyc8503.net', label: 'Email Me', highlight: true },
      ],
    }
  4. Configure Notifications and Webhooks

    main

    Notifications are configured within workerConfig.notification.

    Webhook Settings

    • url: The webhook endpoint (e.g., Telegram Bot API).
    • payloadType: How to encode the payload. Must be one of:
      • param: Append to URL search parameters.
      • json: POST JSON body with application/json content-type.
      • x-www-form-urlencoded: POST url-encoded body.
    • payload: The data to send. Use $MSG to include the human-readable notification message.
    • method: HTTP method (defaults to GET for param, POST otherwise).
    • timeout: Timeout in milliseconds (defaults to 5000).

    Global Notification Settings

    • timeZone: Timezone for messages (defaults to Etc/GMT).
    • gracePeriod: Number of continuous failed checks required before sending a notification (in minutes). If not specified, notifications are sent immediately.
    const workerConfig: WorkerConfig = {
      notification: {
        webhook: {
          url: 'https://api.telegram.org/bot123456:ABCDEF/sendMessage',
          payloadType: 'x-www-form-urlencoded',
          payload: {
            chat_id: 12345678,
            text: '$MSG',
          },
          timeout: 10000,
        },
        timeZone: 'Asia/Shanghai',
        gracePeriod: 5,
      },
    }
  5. Schedule Maintenance via MaintenanceConfig

    main

    Use MaintenanceConfig to define scheduled downtime. During maintenance, an alert is shown on the status page and related downtime notifications are skipped.

    • monitors: Array of monitor IDs affected by this maintenance.
    • title: Title of the maintenance (defaults to "Scheduled Maintenance").
    • body: Description shown on the status page.
    • start: Start time in UNIX timestamp or ISO 8601 format.
    • end: End time in UNIX timestamp or ISO 8601 format (if omitted, maintenance is ongoing).
    • color: Color of the alert (e.g., blue, yellow).
    const maintenances: MaintenanceConfig[] = [
      {
        monitors: ['foo_monitor', 'bar_monitor'],
        title: 'Test Maintenance',
        body: 'This is a test maintenance, server software upgrade',
        start: '2020-01-01T00:00:00+08:00',
        end: '2050-01-01T00:00:00+08:00',
        color: 'blue',
      },
    ]
  6. Handle inconsistent data errors in CompactedMonitorStateWrapper

    main

    When using CompactedMonitorStateWrapper.uncompact(), the following errors may be thrown if the underlying data structure is corrupted or inconsistent:

    • Inconsistent incident data lengths, please report an issue at https://github.com/lyc8503/UptimeFlare (occurs if start, end, or error arrays in an incident have different lengths).
    • Inconsistent latency data lengths, please report an issue at https://github.com/lyc8503/UptimeFlare. (occurs if the hex-encoded time, ping, or location data lengths do not match).
    • Index out of bounds or monitor not found (occurs when accessing specific incidents via getIncident or setIncident).
  7. Configure TCP_PING monitoring

    main

    To monitor a raw TCP port, set the method to 'TCP_PING'. The target field must be provided in a format that can be parsed as a URL (e.g., https://example.com:80) so the proxy can extract the hostname and port.

    Example configuration for a TCP check:

    {
      "name": "My Database Port",
      "method": "TCP_PING",
      "target": "https://127.0.0.1:5432",
      "timeout": 2000
    }
  8. Interact with D1 storage using getFromStore and setToStore

    main

    The worker package provides utility functions to interact with the Cloudflare D1 database via the UPTIMEFLARE_D1 binding in the Env object. These functions use a simple key-value pattern within the uptimeflare table.

    • getFromStore(env, key): Retrieves the string value associated with a specific key. Returns null if the key does not exist.
    • setToStore(env, key, value): Stores a string value for a given key. If the key already exists, it performs an upsert (updates the existing value).
  9. Execute a local monitor check with `getStatus`

    main

    The getStatus function performs a direct check from the current execution environment. It supports two monitoring methods:

    • TCP_PING: Attempts to establish a TCP connection to the target using cloudflare:sockets. Success is determined by the connection being opened within the timeout period.
    • HTTP Endpoint: Performs a fetch request to the target. It supports GET, HEAD, and OPTIONS methods.

    HTTP Validation Logic:

    • Status Codes: If expectedCodes is provided in the monitor config, the response must match one of them. Otherwise, it expects a 2xx status code.
    • Keywords: If responseKeyword is set, the response body must contain it. If responseForbiddenKeyword is set, the response body must NOT contain it.
    • TLS: For https targets, the TLS certificate must be authorized/trusted.
  10. Perform a monitor check with `doMonitor`

    main

    The doMonitor function is the primary entrypoint for executing a monitoring check for a given MonitorTarget. It supports three types of proxy-based checks via the checkProxy field:

    1. Durable Object Proxy: If checkProxy starts with worker://, it uses a Cloudflare Durable Object to perform the check at a specific location.
    2. Globalping Proxy: If checkProxy starts with globalping://, it uses the Globalping API to perform geo-distributed measurements.
    3. HTTP Proxy: Any other URL is treated as an external HTTP endpoint that accepts a POST request containing the MonitorTarget JSON.

    If a proxy check fails and checkProxyFallback is enabled, the function will fall back to a local check using getStatus. If no proxy is provided, it performs a local check.

  11. Execute a geo-distributed check with `getStatusWithGlobalPing`

    main

    The getStatusWithGlobalPing function uses the Globalping API to perform remote measurements.

    Requirements:

    • The monitor.checkProxy must use the globalping: protocol (e.g., globalping://<token>?magic=<value>).
    • The token is extracted from the hostname of the checkProxy URL.

    Supported Methods:

    • TCP_PING: Performs a TCP port probe.
    • HTTP: Supports GET, HEAD, and OPTIONS methods. It validates status codes, keywords, and TLS authorization.

    Note: Custom request bodies are not supported for HTTP checks via Globalping.

  12. Implement custom callbacks in uptime.config.ts

    main

    The UptimeFlare worker supports custom lifecycle callbacks that can be triggered during monitoring events. These callbacks are executed within the scheduled event handler.

    Available callbacks in workerConfig:

    • onStatusChange(env, monitor, isUp, startTime, currentTime, statusOrMessage): Triggered when a monitor's status changes (e.g., UP to DOWN or vice versa).
    • onIncident(env, monitor, startTime, currentTime, statusOrMessage): Triggered during incident lifecycle events.

    Arguments:

    • env: The Env object containing Cloudflare bindings.
    • monitor: The MonitorTarget being checked.
    • isUp: Boolean indicating if the monitor is currently UP (true) or DOWN (false).
    • startTime: The timestamp when the current incident started.
    • currentTime: The current execution timestamp.
    • statusOrMessage: The error message if DOWN, or 'OK' if UP.