summaryrefslogtreecommitdiff
path: root/lua/clever_f/sequence_coordinator.lua
blob: 0da3ef3fcb6a5a3ce039a68e57f9bf04b400aa27 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
local domain = require("clever_f.domain")

local M = {}
local SequenceCoordinator = {}
SequenceCoordinator.__index = SequenceCoordinator
M.SequenceCoordinator = SequenceCoordinator

local coordinator_records = setmetatable({}, { __mode = "k" })

local function fail(message, level)
  error(message, (level or 1) + 1)
end

local function descriptor_text(value)
  if domain.Descriptor.is(value) then
    return value.value
  end
  return tostring(value)
end

function M.validate_primary_descriptor(value)
  local descriptor = domain.Descriptor.try_from_string(value)
  if descriptor == nil then
    fail("clever-f: Invalid mapping '" .. descriptor_text(value) .. "'", 2)
  end
  return descriptor
end

function SequenceCoordinator.new(options)
  if SequenceCoordinator.is(options) then
    return options
  end
  if type(options) ~= "table" then
    fail("SequenceCoordinator options must be a table", 2)
  end
  local coordinator = setmetatable({}, SequenceCoordinator)
  coordinator_records[coordinator] = {
    host = options.host or options,
  }
  return coordinator
end

function SequenceCoordinator.is(value)
  return type(value) == "table" and coordinator_records[value] ~= nil
end

function SequenceCoordinator:validate_primary_descriptor(value)
  return M.validate_primary_descriptor(value)
end

function SequenceCoordinator:primary(value)
  return self:validate_primary_descriptor(value)
end

function M.new(options)
  return SequenceCoordinator.new(options)
end

setmetatable(M, {
  __call = function(_, options)
    return SequenceCoordinator.new(options)
  end,
})

return M