Class: Ligarb::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/ligarb/server.rb

Defined Under Namespace

Classes: BookEntry

Constant Summary collapse

INJECTED_ASSETS =
%w[serve.js review.js review.css].freeze

Instance Method Summary collapse

Constructor Details

#initialize(config_paths, port: 3000, host: "127.0.0.1", multi: false) ⇒ Server

Returns a new instance of Server.



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/ligarb/server.rb', line 17

def initialize(config_paths, port: 3000, host: "127.0.0.1", multi: false)
  @port = port
  @host = host
  @assets_dir = File.join(File.dirname(__FILE__), "..", "..", "assets")
  @sse_clients = [] # [[slug, queue], ...]
  @sse_mutex = Mutex.new
  @write_jobs = {} # slug => { title:, status:, error: }
  @write_mutex = Mutex.new

  @books = {}
  config_paths.each do |cp|
    config = Config.new(cp)
    slug = File.basename(config.base_dir)
    abort "Error: duplicate book slug '#{slug}' — use distinct directory names" if @books.key?(slug)
    @books[slug] = BookEntry.new(
      slug: slug,
      config: config,
      config_path: File.expand_path(cp),
      build_dir: config.output_path,
      store: ReviewStore.new(config.base_dir),
      claude: ClaudeRunner.new(config)
    )
  end

  @multi = multi || @books.size > 1

  @operation_queue = Queue.new
  @operation_thread = Thread.new { operation_worker }
  @operation_thread.abort_on_exception = true
end

Instance Method Details

#startObject



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/ligarb/server.rb', line 48

def start
  require_relative "builder"
  @books.each_value do |book|
    puts "Building #{book.config.title}..."
    Builder.new(book.config_path).build
  end

  warn_if_exposed

  server = WEBrick::HTTPServer.new(
    Port: @port,
    BindAddress: @host,
    Logger: WEBrick::Log.new($stderr, WEBrick::Log::INFO),
    AccessLog: [[File.open(File::NULL, "w"), WEBrick::AccessLog::COMMON_LOG_FORMAT]],
    RequestBodyMaxSize: 50 * 1024 * 1024
  )

  server.mount_proc("/_ligarb/") { |req, res| handle_api(req, res) }
  server.mount_proc("/") { |req, res| handle_static(req, res) }

  trap("INT") { Thread.new { close_sse_clients; server.shutdown } }
  trap("TERM") { Thread.new { close_sse_clients; server.shutdown } }

  @books.each_value { |book| start_build_watcher(book) }

  base_url = "http://#{display_host}:#{@port}"
  if @multi
    puts "Serving #{@books.size} books at #{base_url}"
    @books.each_value { |b| puts "  /#{b.slug}/ — #{b.config.title}" }
  else
    book = @books.values.first
    puts "Serving #{book.config.title} at #{base_url}"
    puts "  Build directory: #{book.build_dir}"
  end
  puts "  Press Ctrl+C to stop"

  server.start
end