Class: Etna::Controller

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

Constant Summary collapse

VIEW_PATH =

methods for returning a view

:VIEW_PATH

Instance Method Summary collapse

Constructor Details

#initialize(request, action = nil) ⇒ Controller

Returns a new instance of Controller.



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/etna/controller.rb', line 6

def initialize(request, action = nil)
  @request = request
  @action = action
  @response = Rack::Response.new
  @params = @request.env['rack.request.params']
  @errors = []
  @server = @request.env['etna.server']
  @logger = @request.env['etna.logger']
  @user = @request.env['etna.user']
  @request_id = @request.env['etna.request_id']
  @hmac = @request.env['etna.hmac']
end

Instance Method Details

#applicationObject



19
20
21
# File 'lib/etna/controller.rb', line 19

def application
  Etna::Application.instance
end

#config_hostsObject



159
160
161
162
163
# File 'lib/etna/controller.rb', line 159

def config_hosts
  [:janus, :magma, :timur, :metis, :vulcan, :polyphemus, :gnomon, :vesta].map do |host|
    [ :"#{host}_host", application.config(host)&.dig(:host) ]
  end.to_h.compact
end

#erb_partial(name) ⇒ Object



148
149
150
151
# File 'lib/etna/controller.rb', line 148

def erb_partial(name)
  txt = File.read("#{self.class::VIEW_PATH}/#{name}.html.erb")
  ERB.new(txt).result(binding)
end

#erb_view(name) ⇒ Object



153
154
155
156
157
# File 'lib/etna/controller.rb', line 153

def erb_view(name)
  @response['Content-Type'] = 'text/html'
  @response.write(erb_partial(name))
  @response.finish
end

#event_log(params) ⇒ Object



27
28
29
30
31
32
33
34
35
36
# File 'lib/etna/controller.rb', line 27

def event_log(params)
  begin
    Etna::Application.instance.event_log(**{
      project_name: @params[:project_name],
      user: @user
    }.compact.merge(params))
  rescue Exception => e
    log("event_log failed with #{e.backtrace} #{e.message}")
  end
end

#handle_error(e) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/etna/controller.rb', line 38

def handle_error(e)
  case e
  when Etna::Error
    Rollbar.error(e)
    @logger.error(request_msg("Exiting with #{e.status}, #{e.message}"))
    return failure(e.status, error: e.message)
  else
    Rollbar.error(e)
    @logger.error(request_msg('Caught unspecified error'))
    @logger.error(request_msg(e.message))
    e.backtrace.each do |trace|
      @logger.error(request_msg(trace))
    end
    return failure(500, error: 'Server error.')
  end
end

#log(line) ⇒ Object



23
24
25
# File 'lib/etna/controller.rb', line 23

def log(line)
  @logger.warn(request_msg(line))
end

#require_params(*params) ⇒ Object Also known as: require_param

Raises:



122
123
124
125
# File 'lib/etna/controller.rb', line 122

def require_params(*params)
  missing_params = params.reject{|p| @params.key?(p) }
  raise Etna::BadRequest, "Missing param #{missing_params.join(', ')}" unless missing_params.empty?
end

#response(&block) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/etna/controller.rb', line 55

def response(&block)
  return instance_eval(&block) if block_given?
  return send(@action) if @action

  [501, {}, ['This controller is not implemented.']]
rescue Exception => e
  error = e
ensure
  log_request if !@request.env['etna.dont_log'] || error
  return handle_error(error) if error
end

#route_path(name, params = {}) ⇒ Object



128
129
130
# File 'lib/etna/controller.rb', line 128

def route_path(name, params={})
  @server.class.route_path(@request, name, params)
end

#route_url(name, params = {}) ⇒ Object



132
133
134
135
136
# File 'lib/etna/controller.rb', line 132

def route_url(name, params={})
  path = route_path(name,params)
  return nil unless path
  @request.scheme + '://' + application.host + path
end

#send_email(to_name, to_email, subject, content) ⇒ Object



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/etna/controller.rb', line 104

def send_email(to_name, to_email, subject, content)
  message = <<MESSAGE_END
From: Data Library <noreply@janus>
To: #{to_name} <#{to_email}>
Subject: #{subject}

#{content}
MESSAGE_END

  unless application.test?
    Net::SMTP.start('smtp.ucsf.edu') do |smtp|
      smtp.send_message message, 'noreply@janus', to_email
    end
  end
rescue => e
  @logger.log_error(e)
end

#try_stream(content_type, &block) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/etna/controller.rb', line 67

def try_stream(content_type, &block)
  if @request.env['rack.hijack?']
    @request.env['rack.hijack'].call
    stream = @request.env['rack.hijack_io']

    headers = [
      "HTTP/1.1 200 OK",
      "Content-Type: #{content_type}"
    ]
    stream.write(headers.map { |header| header + "\r\n" }.join)
    stream.write("\r\n")
    stream.flush

    Thread.new do
      block.call(stream)
    ensure
      stream.close
    end

    # IO is now streaming and will be processed by above thread.
    @response.close
  else
    @response['Content-Type'] = content_type
    response = @response
    # Rack::Response is not a full IO object in Rack 3. JSON.dump calls
    # flush after writing, so adapt the non-hijack/test response path to
    # the same small stream interface provided by a hijacked socket.
    stream = Object.new
    stream.define_singleton_method(:write) { |data| response.write(data) }
    stream.define_singleton_method(:<<) { |data| write(data) }
    stream.define_singleton_method(:flush) {}

    block.call(stream)
    @response.finish
  end
end

#view(name) ⇒ Object



141
142
143
144
145
146
# File 'lib/etna/controller.rb', line 141

def view(name)
  txt = File.read("#{self.class::VIEW_PATH}/#{name}.html")
  @response['Content-Type'] = 'text/html'
  @response.write(txt)
  @response.finish
end