1
0

post_agent.rb 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. module Agents
  2. class PostAgent < Agent
  3. include WebRequestConcern
  4. include FileHandling
  5. consumes_file_pointer!
  6. MIME_RE = /\A\w+\/.+\z/
  7. can_dry_run!
  8. no_bulk_receive!
  9. default_schedule "never"
  10. description do
  11. <<-MD
  12. A Post Agent receives events from other agents (or runs periodically), merges those events with the [Liquid-interpolated](https://github.com/huginn/huginn/wiki/Formatting-Events-using-Liquid) contents of `payload`, and sends the results as POST (or GET) requests to a specified url. To skip merging in the incoming event, but still send the interpolated payload, set `no_merge` to `true`.
  13. The `post_url` field must specify where you would like to send requests. Please include the URI scheme (`http` or `https`).
  14. The `method` used can be any of `get`, `post`, `put`, `patch`, and `delete`.
  15. By default, non-GETs will be sent with form encoding (`application/x-www-form-urlencoded`).
  16. Change `content_type` to `json` to send JSON instead.
  17. Change `content_type` to `xml` to send XML, where the name of the root element may be specified using `xml_root`, defaulting to `post`.
  18. When `content_type` contains a [MIME](https://en.wikipedia.org/wiki/Media_type) type, and `payload` is a string, its interpolated value will be sent as a string in the HTTP request's body and the request's `Content-Type` HTTP header will be set to `content_type`. When `payload` is a string `no_merge` has to be set to `true`.
  19. If `emit_events` is set to `true`, the server response will be emitted as an Event and can be fed to a WebsiteAgent for parsing (using its `data_from_event` and `type` options). No data processing
  20. will be attempted by this Agent, so the Event's "body" value will always be raw text.
  21. The Event will also have a "headers" hash and a "status" integer value.
  22. If `output_mode` is set to `merge`, the emitted Event will be merged into the original contents of the received Event.
  23. Set `event_headers_style` to one of the following values to normalize the keys of "headers" for downstream agents' convenience:
  24. * `capitalized` (default) - Header names are capitalized; e.g. "Content-Type"
  25. * `downcased` - Header names are downcased; e.g. "content-type"
  26. * `snakecased` - Header names are snakecased; e.g. "content_type"
  27. * `raw` - Backward compatibility option to leave them unmodified from what the underlying HTTP library returns.
  28. Other Options:
  29. * `headers` - When present, it should be a hash of headers to send with the request.
  30. * `basic_auth` - Specify HTTP basic auth parameters: `"username:password"`, or `["username", "password"]`.
  31. * `disable_ssl_verification` - Set to `true` to disable ssl verification.
  32. * `user_agent` - A custom User-Agent name (default: "Faraday v#{Faraday::VERSION}").
  33. #{receiving_file_handling_agent_description}
  34. When receiving a `file_pointer` the request will be sent with multipart encoding (`multipart/form-data`) and `content_type` is ignored. `upload_key` can be used to specify the parameter in which the file will be sent, it defaults to `file`.
  35. MD
  36. end
  37. event_description <<-MD
  38. Events look like this:
  39. {
  40. "status": 200,
  41. "headers": {
  42. "Content-Type": "text/html",
  43. ...
  44. },
  45. "body": "<html>Some data...</html>"
  46. }
  47. Original event contents will be merged when `output_mode` is set to `merge`.
  48. MD
  49. def default_options
  50. {
  51. 'post_url' => "http://www.example.com",
  52. 'expected_receive_period_in_days' => '1',
  53. 'content_type' => 'form',
  54. 'method' => 'post',
  55. 'payload' => {
  56. 'key' => 'value',
  57. 'something' => 'the event contained {{ somekey }}'
  58. },
  59. 'headers' => {},
  60. 'emit_events' => 'false',
  61. 'no_merge' => 'false',
  62. 'output_mode' => 'clean'
  63. }
  64. end
  65. def working?
  66. last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
  67. end
  68. def method
  69. (interpolated['method'].presence || 'post').to_s.downcase
  70. end
  71. def validate_options
  72. unless options['post_url'].present? && options['expected_receive_period_in_days'].present?
  73. errors.add(:base, "post_url and expected_receive_period_in_days are required fields")
  74. end
  75. if options['payload'].present? && %w[get delete].include?(method) && !(options['payload'].is_a?(Hash) || options['payload'].is_a?(Array))
  76. errors.add(:base, "if provided, payload must be a hash or an array")
  77. end
  78. if options['payload'].present? && %w[post put patch].include?(method)
  79. if !(options['payload'].is_a?(Hash) || options['payload'].is_a?(Array)) && options['content_type'] !~ MIME_RE
  80. errors.add(:base, "if provided, payload must be a hash or an array")
  81. end
  82. end
  83. if options['content_type'] =~ MIME_RE && options['payload'].is_a?(String) && boolify(options['no_merge']) != true
  84. errors.add(:base, "when the payload is a string, `no_merge` has to be set to `true`")
  85. end
  86. if options['content_type'] == 'form' && options['payload'].present? && options['payload'].is_a?(Array)
  87. errors.add(:base, "when content_type is a form, if provided, payload must be a hash")
  88. end
  89. if options.has_key?('emit_events') && boolify(options['emit_events']).nil?
  90. errors.add(:base, "if provided, emit_events must be true or false")
  91. end
  92. begin
  93. normalize_response_headers({})
  94. rescue ArgumentError => e
  95. errors.add(:base, e.message)
  96. end
  97. unless %w[post get put delete patch].include?(method)
  98. errors.add(:base, "method must be 'post', 'get', 'put', 'delete', or 'patch'")
  99. end
  100. if options['no_merge'].present? && !%[true false].include?(options['no_merge'].to_s)
  101. errors.add(:base, "if provided, no_merge must be 'true' or 'false'")
  102. end
  103. if options['output_mode'].present? && !options['output_mode'].to_s.include?('{') && !%[clean merge].include?(options['output_mode'].to_s)
  104. errors.add(:base, "if provided, output_mode must be 'clean' or 'merge'")
  105. end
  106. unless headers.is_a?(Hash)
  107. errors.add(:base, "if provided, headers must be a hash")
  108. end
  109. validate_web_request_options!
  110. end
  111. def receive(incoming_events)
  112. incoming_events.each do |event|
  113. interpolate_with(event) do
  114. outgoing = interpolated['payload'].presence || {}
  115. if boolify(interpolated['no_merge'])
  116. handle outgoing, event, headers(interpolated[:headers])
  117. else
  118. handle outgoing.merge(event.payload), event, headers(interpolated[:headers])
  119. end
  120. end
  121. end
  122. end
  123. def check
  124. handle interpolated['payload'].presence || {}, headers
  125. end
  126. private
  127. def normalize_response_headers(headers)
  128. case interpolated['event_headers_style']
  129. when nil, '', 'capitalized'
  130. normalize = ->name {
  131. name.gsub(/(?:\A|(?<=-))([[:alpha:]])|([[:alpha:]]+)/) {
  132. $1 ? $1.upcase : $2.downcase
  133. }
  134. }
  135. when 'downcased'
  136. normalize = :downcase.to_proc
  137. when 'snakecased', nil
  138. normalize = ->name { name.tr('A-Z-', 'a-z_') }
  139. when 'raw'
  140. normalize = ->name { name } # :itself.to_proc in Ruby >= 2.2
  141. else
  142. raise ArgumentError, "if provided, event_headers_style must be 'capitalized', 'downcased', 'snakecased' or 'raw'"
  143. end
  144. headers.each_with_object({}) { |(key, value), hash|
  145. hash[normalize[key]] = value
  146. }
  147. end
  148. def handle(data, event = Event.new, headers)
  149. url = interpolated(event.payload)[:post_url]
  150. case method
  151. when 'get', 'delete'
  152. params, body = data, nil
  153. when 'post', 'put', 'patch'
  154. params = nil
  155. content_type =
  156. if has_file_pointer?(event)
  157. data[interpolated(event.payload)['upload_key'].presence || 'file'] = get_upload_io(event)
  158. nil
  159. else
  160. interpolated(event.payload)['content_type']
  161. end
  162. case content_type
  163. when 'json'
  164. headers['Content-Type'] = 'application/json; charset=utf-8'
  165. body = data.to_json
  166. when 'xml'
  167. headers['Content-Type'] = 'text/xml; charset=utf-8'
  168. body = data.to_xml(root: (interpolated(event.payload)[:xml_root] || 'post'))
  169. when MIME_RE
  170. headers['Content-Type'] = content_type
  171. body = data.to_s
  172. else
  173. body = data
  174. end
  175. else
  176. error "Invalid method '#{method}'"
  177. end
  178. response = faraday.run_request(method.to_sym, url, body, headers) { |request|
  179. request.params.update(params) if params
  180. }
  181. if boolify(interpolated['emit_events'])
  182. new_event = interpolated['output_mode'].to_s == 'merge' ? event.payload.dup : {}
  183. create_event payload: new_event.merge(
  184. body: response.body,
  185. headers: normalize_response_headers(response.headers),
  186. status: response.status
  187. )
  188. end
  189. end
  190. end
  191. end