Class: Palapala::PersistentServer

Inherits:
Object
  • Object
show all
Defined in:
lib/palapala/persistent_server.rb

Overview

Persistent server that stays running and serves HTML content from memory Eliminates the overhead of creating/destroying servers for each PDF

Constant Summary collapse

@@instance =
nil
@@files =
{}
@@mutex =
Mutex.new

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(port: 9223) ⇒ PersistentServer

Returns a new instance of PersistentServer.



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
47
48
# File 'lib/palapala/persistent_server.rb', line 19

def initialize(port: 9223)
  @port = find_available_port(port)
  @server = WEBrick::HTTPServer.new(
    Port: @port,
    Logger: WEBrick::Log.new("/dev/null"),
    AccessLog: []
  )

  # Custom handler to serve files from memory
  @server.mount_proc '/file' do |req, res|
    file_key = req.path.sub('/file/', '')

    @@mutex.synchronize do
      if @@files.key?(file_key)
        res.status = 200
        res['Content-Type'] = 'text/html'
        res.body = @@files[file_key]
      else
        res.status = 404
        res.body = 'File not found'
      end
    end
  end

  # Start server in background thread
  @thread = Thread.new { @server.start }

  # Wait for server to be ready
  sleep 0.1 until @server.status == :Running
end

Class Method Details

.instanceObject



13
14
15
16
17
# File 'lib/palapala/persistent_server.rb', line 13

def self.instance
  @@mutex.synchronize do
    @@instance ||= new
  end
end

Instance Method Details

#cleanup(key) ⇒ Object

Clean up served content



64
65
66
67
68
# File 'lib/palapala/persistent_server.rb', line 64

def cleanup(key)
  @@mutex.synchronize do
    @@files.delete(key)
  end
end

#portObject

Get current port



71
72
73
# File 'lib/palapala/persistent_server.rb', line 71

def port
  @port
end

#running?Boolean

Check if server is running

Returns:

  • (Boolean)


76
77
78
# File 'lib/palapala/persistent_server.rb', line 76

def running?
  @server.status == :Running
end

#serve_html(html) ⇒ Object

Serve HTML content and return URL



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/palapala/persistent_server.rb', line 51

def serve_html(html)
  puts "PersistentServer: Serving HTML content (#{html.bytesize} bytes)" if defined?(Palapala) && Palapala.debug
  key = SecureRandom.hex
  @@mutex.synchronize do
    @@files[key] = html
    puts "PersistentServer: Stored content with key #{key}" if defined?(Palapala) && Palapala.debug
  end
  url = "http://localhost:#{@port}/file/#{key}"
  puts "PersistentServer: Returning URL #{url}" if defined?(Palapala) && Palapala.debug
  url
end

#stopObject

Stop the server



81
82
83
84
# File 'lib/palapala/persistent_server.rb', line 81

def stop
  @server.shutdown
  @thread.join
end