Class: MudisServer

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

Overview

Simple UNIX socket server for handling Mudis operations via IPC mode

Constant Summary collapse

SOCKET_PATH =
"/tmp/mudis.sock"

Class Method Summary collapse

Class Method Details

.handle_client(sock) ⇒ Object

rubocop:disable Metrics/CyclomaticComplexity,Metrics/AbcSize,Metrics/MethodLength



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
# File 'lib/mudis_server.rb', line 29

def self.handle_client(sock) # rubocop:disable Metrics/CyclomaticComplexity,Metrics/AbcSize,Metrics/MethodLength
  request_line = sock.gets
  return unless request_line

  req = JSON.parse(request_line, symbolize_names: true)
  cmd  = req[:cmd]
  key  = req[:key]
  ns   = req[:namespace]
  val  = req[:value]
  ttl  = req[:ttl]

  begin
    case cmd
    when "read"
      result = Mudis.read(key, namespace: ns)
      sock.puts(JSON.dump({ ok: true, value: result }))

    when "write"
      Mudis.write(key, val, expires_in: ttl, namespace: ns)
      sock.puts(JSON.dump({ ok: true }))

    when "delete"
      Mudis.delete(key, namespace: ns)
      sock.puts(JSON.dump({ ok: true }))

    when "exists"
      sock.puts(JSON.dump({ ok: true, value: Mudis.exists?(key, namespace: ns) }))

    when "fetch"
      result = Mudis.fetch(key, expires_in: ttl, namespace: ns) { req[:fallback] }
      sock.puts(JSON.dump({ ok: true, value: result }))

    when "metrics"
      sock.puts(JSON.dump({ ok: true, value: Mudis.metrics }))

    when "reset_metrics"
      Mudis.reset_metrics!
      sock.puts(JSON.dump({ ok: true }))

    when "reset"
      Mudis.reset!
      sock.puts(JSON.dump({ ok: true }))

    else
      sock.puts(JSON.dump({ ok: false, error: "unknown command: #{cmd}" }))
    end
  rescue StandardError => e
    sock.puts(JSON.dump({ ok: false, error: e.message }))
  ensure
    sock.close
  end
end

.start!Object

rubocop:disable Metrics/MethodLength



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/mudis_server.rb', line 11

def self.start! # rubocop:disable Metrics/MethodLength
  # Clean up old socket if it exists
  File.unlink(SOCKET_PATH) if File.exist?(SOCKET_PATH)

  server = UNIXServer.new(SOCKET_PATH)
  server.listen(128)
  puts "[MudisServer] Listening on #{SOCKET_PATH}"

  Thread.new do
    loop do
      client = server.accept
      Thread.new(client) do |sock|
        handle_client(sock)
      end
    end
  end
end