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, 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
# File 'lib/ligarb/server.rb', line 17

def initialize(config_paths, port: 3000, multi: false)
  @port = port
  @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



47
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
# File 'lib/ligarb/server.rb', line 47

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

  server = WEBrick::HTTPServer.new(
    Port: @port,
    BindAddress: "127.0.0.1",
    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) }

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

  server.start
end