Class: Itsi::Server::Config::DSL

Inherits:
Object
  • Object
show all
Defined in:
lib/itsi/server/config/dsl.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parent = nil, routes: [], methods: [], protocols: [], hosts: [], ports: [], extensions: [], content_types: [], accepts: [], controller: self, &block) ⇒ DSL

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



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
# File 'lib/itsi/server/config/dsl.rb', line 30

def initialize( # rubocop:disable Metrics/AbcSize,Metrics/MethodLength,Metrics/PerceivedComplexity,Metrics/CyclomaticComplexity
  parent = nil,
  routes: [],
  methods: [],
  protocols: [],
  hosts: [],
  ports: [],
  extensions: [],
  content_types: [],
  accepts: [],
  controller: self,
  &block
)
  @parent           = parent
  @children         = []
  @middleware       = {}

  @controller = controller
  @routes = Array(routes).flatten
  @http_methods = methods.map { |s| s.is_a?(Regexp) ? s : s.to_s }
  @protocols = protocols.map { |s| s.is_a?(Regexp) ? s : s.to_s }
  @hosts = hosts.map { |s| s.is_a?(Regexp) ? s : s.to_s }
  @ports = ports.map { |s| s.is_a?(Regexp) ? s : s.to_s }
  @extensions = extensions.map { |s| s.is_a?(Regexp) ? s : s.to_s }
  @content_types = content_types.map { |s| s.is_a?(Regexp) ? s : s.to_s }
  @accepts = accepts.map { |s| s.is_a?(Regexp) ? s : s.to_s }

  @options = {
    nested_locations: [],
    middleware_loader: lambda do
      @options[:nested_locations].each(&:call)
      @middleware[:app] = { app_proc: DEFAULT_APP[] } unless @middleware[:app] || @middleware[:static_assets]
      [flatten_routes, Config.errors_to_error_lines(errors)]
    end
  }

  @errors = []
  instance_exec(&block)
end

Instance Attribute Details

#acceptsObject (readonly)

Returns the value of attribute accepts.



12
13
14
# File 'lib/itsi/server/config/dsl.rb', line 12

def accepts
  @accepts
end

#childrenObject (readonly)

Returns the value of attribute children.



12
13
14
# File 'lib/itsi/server/config/dsl.rb', line 12

def children
  @children
end

#content_typesObject (readonly)

Returns the value of attribute content_types.



12
13
14
# File 'lib/itsi/server/config/dsl.rb', line 12

def content_types
  @content_types
end

#controllerObject (readonly)

Returns the value of attribute controller.



12
13
14
# File 'lib/itsi/server/config/dsl.rb', line 12

def controller
  @controller
end

#extensionsObject (readonly)

Returns the value of attribute extensions.



12
13
14
# File 'lib/itsi/server/config/dsl.rb', line 12

def extensions
  @extensions
end

#hostsObject (readonly)

Returns the value of attribute hosts.



12
13
14
# File 'lib/itsi/server/config/dsl.rb', line 12

def hosts
  @hosts
end

#http_methodsObject (readonly)

Returns the value of attribute http_methods.



12
13
14
# File 'lib/itsi/server/config/dsl.rb', line 12

def http_methods
  @http_methods
end

#middlewareObject (readonly)

Returns the value of attribute middleware.



12
13
14
# File 'lib/itsi/server/config/dsl.rb', line 12

def middleware
  @middleware
end

#optionsObject (readonly)

Returns the value of attribute options.



12
13
14
# File 'lib/itsi/server/config/dsl.rb', line 12

def options
  @options
end

#parentObject (readonly)

Returns the value of attribute parent.



12
13
14
# File 'lib/itsi/server/config/dsl.rb', line 12

def parent
  @parent
end

#portsObject (readonly)

Returns the value of attribute ports.



12
13
14
# File 'lib/itsi/server/config/dsl.rb', line 12

def ports
  @ports
end

#protocolsObject (readonly)

Returns the value of attribute protocols.



12
13
14
# File 'lib/itsi/server/config/dsl.rb', line 12

def protocols
  @protocols
end

#routesObject (readonly)

Returns the value of attribute routes.



12
13
14
# File 'lib/itsi/server/config/dsl.rb', line 12

def routes
  @routes
end

Class Method Details

.evaluate(config = Itsi::Server::Config.config_file_path, &blk) ⇒ Object

rubocop:disable Metrics/MethodLength



15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/itsi/server/config/dsl.rb', line 15

def self.evaluate(config = Itsi::Server::Config.config_file_path, &blk) # rubocop:disable Metrics/MethodLength
  config = new(routes: ["/"]) do
    if blk
      instance_exec(&blk)
    else
      code = IO.read(config)
      instance_eval(code, config.to_s, 1)
    end
    location("*") {}
  end
  [config.options, config.errors]
rescue Exception => e # rubocop:disable Lint/RescueException
  [{}, [[e, e.backtrace[0]]]]
end

Instance Method Details

#deep_stringify_keys(obj) ⇒ Object



194
195
196
197
198
199
200
201
202
203
204
# File 'lib/itsi/server/config/dsl.rb', line 194

def deep_stringify_keys(obj)
  case obj
  when Hash
    obj.transform_keys!(&:to_s)
    obj.transform_values! { |v| deep_stringify_keys(v) }
  when Array
    obj.map { |v| deep_stringify_keys(v) }
  else
    obj
  end
end

#effective_middlewareObject



168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/itsi/server/config/dsl.rb', line 168

def effective_middleware
  chain = []
  node = self
  while node
    if node.middleware[:app]&.[](:preloader)
      node.middleware[:app][:app_proc] = node.middleware[:app].delete(:preloader).call
    end
    chain << node
    node = node.parent
  end
  chain.reverse!

  merged = {}

  chain.each do |n|
    n.middleware.each do |k, v|
      merged[k] = if v[:combine]
                    ([merged[k] || []] + [v]).flatten
                  else
                    v
                  end
    end
  end
  deep_stringify_keys(merged)
end

#errorsObject



70
71
72
# File 'lib/itsi/server/config/dsl.rb', line 70

def errors
  @children.map(&:errors).flatten(1) + @errors
end

#file_server(**args) ⇒ Object



106
107
108
109
# File 'lib/itsi/server/config/dsl.rb', line 106

def file_server(**args)
  Itsi.log_info "Note: file_server is an alias for static_assets"
  static_assets(**args)
end

#flatten_routesObject



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/itsi/server/config/dsl.rb', line 111

def flatten_routes
  result = []
  result.concat(@children.flat_map(&:flatten_routes))
  route_options = paths_from_parent
  if route_options
    result << deep_stringify_keys(
      {
        route: Regexp.new("^#{route_options}/?$"),
        methods: @http_methods.any? ? @http_methods : nil,
        protocols: @protocols.any? ? @protocols : nil,
        hosts: @hosts.any? ? @hosts : nil,
        ports: @ports.any? ? @ports : nil,
        extensions: @extensions.any? ? @extensions : nil,
        content_types: @content_types.any? ? @content_types : nil,
        accepts: @accepts.any? ? @accepts : nil,
        middleware: effective_middleware
      }
    )
  end
  result
end

#grpc_reflection(handlers) ⇒ Object



94
95
96
97
98
99
100
101
102
103
104
# File 'lib/itsi/server/config/dsl.rb', line 94

def grpc_reflection(handlers)
  @grpc_reflected_services ||= []
  @grpc_reflected_services.concat(handlers)

  location("grpc.reflection.v1alpha.ServerReflection/ServerReflectionInfo",
           "grpc.reflection.v1.ServerReflection/ServerReflectionInfo") do
    @middleware[:app] = { preloader: lambda {
      Itsi::Server::GrpcInterface.reflection_for(handlers)
    }, request_type: "grpc" }
  end
end

#paths_from_parentObject



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/itsi/server/config/dsl.rb', line 133

def paths_from_parent
  return nil unless @routes.any?

  route_or_str = @routes.map do |seg|
    case seg
    when Regexp
      seg.source
    else
      parts = seg.split("/")
      parts.map do |part|
        case part
        when /^:([A-Za-z_]\w*)(?:\(([^)]*)\))?$/
          param_name = Regexp.last_match(1)
          custom     = Regexp.last_match(2)
          if custom && !custom.empty?
            "(?<#{param_name}>#{custom})"
          else
            "(?<#{param_name}>[^/]+)"
          end
        when /\*/
          part.gsub(/\*/, ".*")
        else
          Regexp.escape(part)
        end
      end.join("/")
    end
  end.join("|")
  if parent && parent.paths_from_parent && parent.paths_from_parent != "(?:/)"
    "#{parent.paths_from_parent}#{route_or_str != "" ? "(?:#{route_or_str})" : ""}"
  else
    route_or_str = "/#{route_or_str}" unless route_or_str.start_with?("/")
    "(?:#{route_or_str})"
  end
end