Module: MongoKeepAlive

Defined in:
lib/keepalive.rb

Overview

Keep MongoDB Atlas free-tier clusters alive by periodically sending a ping command.

Defined Under Namespace

Classes: Handle

Constant Summary collapse

DEFAULT_INTERVAL =
"12h"
MAX_RETRIES =
3
RETRY_DELAY =
5

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.loggerLogger

Returns:

  • (Logger)


35
36
37
# File 'lib/keepalive.rb', line 35

def logger
  @logger ||= Logger.new($stdout, progname: "mongo-keepalive")
end

Class Method Details

.start_keep_alive(uri:, interval: DEFAULT_INTERVAL) ⇒ Handle

Start the keep-alive loop in a background thread.

Parameters:

  • uri (String)

    MongoDB connection string.

  • interval (String) (defaults to: DEFAULT_INTERVAL)

    Ping interval, e.g. "12h", "30m", "60s".

Returns:

Raises:

  • (ArgumentError)


46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/keepalive.rb', line 46

def start_keep_alive(uri:, interval: DEFAULT_INTERVAL)
  raise ArgumentError, "A MongoDB connection URI is required." if uri.nil? || uri.empty?

  interval_s = parse_interval(interval)
  logger.info("[mongo-keepalive] Starting with interval #{interval} (#{interval_s} s)")

  client = Mongo::Client.new(uri)
  db = client.use("admin").database

  # Initial ping
  ping_with_retry(db)

  thread = Thread.new do
    loop do
      sleep(interval_s)
      ping_with_retry(db)
    end
  end

  Handle.new(client, thread)
end