Class: Portless::RouteStore

Inherits:
Object
  • Object
show all
Defined in:
lib/portless/route_store.rb

Overview

The on-disk routing table (routes.json): host → backend port → owning pid. No daemon API — apps register/deregister by editing this file under a directory mutex (atomic mkdir), and the proxy watches it. Dead-pid entries are reaped on every load. Mirrors portless's RouteStore.

Defined Under Namespace

Classes: Route

Constant Summary collapse

LOCK_STALE_SECONDS =
10
LOCK_BUDGET_SECONDS =
5

Instance Method Summary collapse

Constructor Details

#initialize(file: State.routes_file, lock: State.routes_lock) ⇒ RouteStore

Returns a new instance of RouteStore.



19
20
21
22
# File 'lib/portless/route_store.rb', line 19

def initialize(file: State.routes_file, lock: State.routes_lock)
  @file = file
  @lock = lock
end

Instance Method Details

#add(hostname:, port:, pid:, force: false) ⇒ Object

Register (or replace) a route. Conflicts with a live different owner raise unless force, which SIGTERMs the incumbent. Alias routes use pid 0.



30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/portless/route_store.rb', line 30

def add(hostname:, port:, pid:, force: false)
  with_lock do
    all = load.reject { |r| dead?(r["pid"]) }
    existing = all.find { |r| r["hostname"] == hostname }
    if existing && existing["pid"].to_i != pid.to_i && !dead?(existing["pid"])
      raise Error, "#{hostname} is already served by pid #{existing['pid']}" unless force
      terminate(existing["pid"])
    end
    all.reject! { |r| r["hostname"] == hostname }
    all << { "hostname" => hostname, "port" => port, "pid" => pid }
    write(all)
  end
end

#pruneObject



56
57
58
# File 'lib/portless/route_store.rb', line 56

def prune
  with_lock { write(load.reject { |r| dead?(r["pid"]) }) }
end

#remove(hostname, owner_pid: nil) ⇒ Object

Remove a route only if still owned by owner_pid (so a force-replaced predecessor doesn't delete the successor's route on its way out).



46
47
48
49
50
51
52
53
54
# File 'lib/portless/route_store.rb', line 46

def remove(hostname, owner_pid: nil)
  with_lock do
    all = load
    all.reject! do |r|
      r["hostname"] == hostname && (owner_pid.nil? || r["pid"].to_i == owner_pid.to_i)
    end
    write(all)
  end
end

#routesObject



24
25
26
# File 'lib/portless/route_store.rb', line 24

def routes
  load.map { |h| Route.new(hostname: h["hostname"], port: h["port"], pid: h["pid"]) }
end