posthog-ruby 3.33.0 → 3.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 8da64dae9d5b02bfb1ad78f4557e4b9bfcba9c5e629dec50f71bb451968029e8
4
- data.tar.gz: bcbd76ebc1e9f82e7cadd467be7793ab84255e0c67f8cbdfec1582fd1e9a1a48
3
+ metadata.gz: 6919dc872a176602af603c80aaefdb26035bf4b7ba72031f2e211fd3189d000c
4
+ data.tar.gz: e6f4ce3c0b53588f1dfc353520a4c05863953dc7a870fa71d9b25f8fad20684f
5
5
  SHA512:
6
- metadata.gz: b8c19b770ee14ddc7b7dfabbce0fd50b1cfa421f544ab02ab0418a75673ded97a4f84b41eaf25be1b0dc31a0b1d8d6f87d49a9bb83d600dc1398cbdbe09c04ca
7
- data.tar.gz: 070fad978093afa5ebbe163f2f56538f99812bfc90335e30f76c609ee521b9d521b34f0a387c70bad0ef51f8bdbe2ffc12ae38da96a08ffa827b0d28380e54ed
6
+ metadata.gz: 061547d55728f83bf33b42cde58fc6a9538d39a1ea9d88c8d39e14a8558876146e12a0f63dd447f79886b9ca79908bb5a3c1b48eaf952ab7ed6db94208ca2450
7
+ data.tar.gz: b09583c16690c67b64e065573829147666941283faf0cbca32d0090785e59d62d146d195ce0def0c4f446a514194e546b3cbaef3dff5780a18180b58c1e3f064
@@ -0,0 +1,188 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'digest'
4
+
5
+ require 'posthog/email_error'
6
+
7
+ module PostHog
8
+ # The files of one send: each file's bytes and SHA-256, checked against the limits of one email before any request.
9
+ #
10
+ # @api private
11
+ class EmailAttachments
12
+ MAX_FILES = 10
13
+ MAX_MESSAGE_BYTES = 40_000_000
14
+ HEADERS_AND_MIME_BOUNDARIES_BYTES = 64 * 1024
15
+ SUBJECT_BYTES_PER_ENCODED_WORD = 42
16
+ ENCODED_WORD_BYTES = 75
17
+ LIMIT = '10 files and 40 MB per email after Base64 encoding, about 29 MB of files'
18
+ FIELDS = %w[filename content content_type content_id].freeze
19
+ BASE64_LINE_WIDTHS = [60, 64, 76].freeze
20
+
21
+ # One file to attach: its bytes, their SHA-256, and what the send says about it.
22
+ Attachment = Struct.new(:bytes, :reference, :field, keyword_init: true) do
23
+ def sha256
24
+ @sha256 ||= Digest::SHA256.hexdigest(bytes)
25
+ end
26
+ end
27
+
28
+ # @param files [Object] What the caller passed as `attachments`.
29
+ # @param bodies [Array<String>] The email's HTML and text bodies, which count towards its size.
30
+ # @param subject [String, nil] The email's subject, which counts towards its size.
31
+ # @raise [EmailError] A file the client can't send, or more than one email can carry.
32
+ def self.from(files, bodies, subject)
33
+ raise invalid('attachments must be a list of files.', 'attachments') unless files.is_a?(Array)
34
+ raise too_many_files if files.size > MAX_FILES
35
+
36
+ new(files.each_with_index.map { |file, index| attachment(file, "attachments__#{index}") }, bodies, subject)
37
+ end
38
+
39
+ def self.attachment(file, field)
40
+ unless file.is_a?(Hash)
41
+ raise invalid("An attachment is a Hash with filename and content. Pass the file's bytes as its content.", field)
42
+ end
43
+
44
+ file = file.transform_keys(&:to_s).compact
45
+ check_keys(file, field)
46
+ bytes = file_bytes(file['content'], "#{field}__content")
47
+ Attachment.new(bytes: bytes, field: field, reference: file.slice('filename', 'content_type', 'content_id'))
48
+ end
49
+
50
+ def self.check_keys(file, field)
51
+ if file.key?('path')
52
+ raise invalid("PostHog can't fetch an attachment from a path or URL. Read the file with File.binread and " \
53
+ 'pass it as content instead.', "#{field}__path")
54
+ end
55
+ unknown = file.keys.find { |key| !FIELDS.include?(key) }
56
+ if unknown
57
+ raise invalid("An attachment takes filename, content, content_type and content_id, not #{unknown}.",
58
+ "#{field}__#{unknown}")
59
+ end
60
+
61
+ %w[filename content_type content_id].each do |name|
62
+ next if name != 'filename' && !file.key?(name)
63
+ next if file[name].is_a?(String)
64
+
65
+ raise invalid("An attachment's #{name} must be a String.", "#{field}__#{name}")
66
+ end
67
+ end
68
+
69
+ def self.file_bytes(content, field)
70
+ bytes = raw_bytes(content) || base64_bytes(content, field)
71
+ raise invalid("An attachment can't be empty. Pass the file's bytes as its content.", field) if bytes.empty?
72
+
73
+ bytes
74
+ end
75
+
76
+ def self.raw_bytes(content)
77
+ return content if content.is_a?(String) && content.encoding == Encoding::BINARY
78
+ return unless content.is_a?(Array) && content.all? { |byte| byte.is_a?(Integer) && byte.between?(0, 255) }
79
+
80
+ content.pack('C*')
81
+ end
82
+
83
+ def self.base64_bytes(content, field)
84
+ unless content.is_a?(String)
85
+ raise invalid('An attachment needs content: the bytes File.binread returns, a list of byte values, or the ' \
86
+ 'file encoded as Base64.', field)
87
+ end
88
+ raise ArgumentError if content.match?(/[\r\n]/) && !wrapped_base64?(content)
89
+
90
+ content.delete("\r\n").unpack1('m0')
91
+ rescue ArgumentError, EncodingError
92
+ raise invalid("An attachment's content is text that isn't Base64. Pass the file's bytes, read with " \
93
+ 'File.binread, or the file encoded as Base64.', field)
94
+ end
95
+
96
+ def self.wrapped_base64?(content)
97
+ text = content.gsub("\r\n", "\n")
98
+ return false if text.include?("\r")
99
+
100
+ text = text.delete_suffix("\n")
101
+ width = text.index("\n")
102
+ return true if width.nil?
103
+
104
+ text.ascii_only? && BASE64_LINE_WIDTHS.include?(width) && lines_of_width?(text, width)
105
+ end
106
+
107
+ def self.lines_of_width?(text, width)
108
+ line_break = width
109
+ while (next_break = text.index("\n", line_break + 1))
110
+ return false unless next_break == line_break + width + 1
111
+
112
+ line_break = next_break
113
+ end
114
+ (text.length - line_break - 1).between?(1, width)
115
+ end
116
+
117
+ def self.invalid(message, field)
118
+ EmailError.new(code: 'invalid_attachment', message: message, field: field)
119
+ end
120
+
121
+ def self.too_many_files
122
+ EmailError.new(code: 'too_many_attachments', field: 'attachments',
123
+ message: "An email carries at most #{MAX_FILES} files, so no email was sent.",
124
+ why: "An email carries at most #{MAX_FILES} files.",
125
+ fix: "Attach at most #{MAX_FILES} files, and link to any others from the email body.")
126
+ end
127
+
128
+ private_class_method :new, :attachment, :check_keys, :file_bytes, :raw_bytes, :base64_bytes,
129
+ :wrapped_base64?, :lines_of_width?, :invalid, :too_many_files
130
+
131
+ def initialize(attachments, bodies, subject)
132
+ @attachments = attachments
133
+ check_size(bodies, subject)
134
+ end
135
+
136
+ def empty?
137
+ @attachments.empty?
138
+ end
139
+
140
+ # @return [Array<Hash>] The files as the send names them.
141
+ def references
142
+ @attachments.map { |attachment| { 'sha256' => attachment.sha256 }.merge(attachment.reference) }
143
+ end
144
+
145
+ # @return [Array<Attachment>] Each distinct file once, in the order the caller gave them.
146
+ def distinct
147
+ @attachments.uniq(&:sha256)
148
+ end
149
+
150
+ private
151
+
152
+ def check_size(bodies, subject)
153
+ return if empty? || message_bytes(bodies, subject) <= MAX_MESSAGE_BYTES
154
+
155
+ raise EmailError.new(
156
+ code: 'message_too_large', field: 'attachments',
157
+ message: 'The files are too large for one email, so no email was sent.',
158
+ why: "PostHog's email provider takes emails up to 40 MB, and Base64 encoding makes each file about a " \
159
+ 'third larger.',
160
+ fix: "Keep the email under #{LIMIT}: attach fewer or smaller files, or link to large files from the email " \
161
+ 'body.'
162
+ )
163
+ end
164
+
165
+ def message_bytes(bodies, subject)
166
+ files = @attachments.sum { |attachment| encoded_bytes(attachment.bytes.bytesize) }
167
+ files + bodies.sum { |body| encoded_bytes(utf8_bytesize(body)) } + subject_bytes(subject) +
168
+ HEADERS_AND_MIME_BOUNDARIES_BYTES
169
+ end
170
+
171
+ def subject_bytes(subject)
172
+ return 0 unless subject.is_a?(String)
173
+
174
+ (utf8_bytesize(subject) + SUBJECT_BYTES_PER_ENCODED_WORD - 1) / SUBJECT_BYTES_PER_ENCODED_WORD *
175
+ ENCODED_WORD_BYTES
176
+ end
177
+
178
+ def utf8_bytesize(body)
179
+ body.encoding == Encoding::BINARY ? body.bytesize : body.encode(Encoding::UTF_8).bytesize
180
+ rescue EncodingError
181
+ body.bytesize
182
+ end
183
+
184
+ def encoded_bytes(size)
185
+ (((size + 2) / 3 * 4 * 78) + 75) / 76
186
+ end
187
+ end
188
+ end
@@ -11,7 +11,7 @@ module PostHog
11
11
  attr_reader :name
12
12
  # @return [String] PostHog's error code, such as `quota_limited`, or an SDK code such as `network_error`.
13
13
  attr_reader :code
14
- # @return [Integer, nil] The HTTP status, when PostHog answered.
14
+ # @return [Integer, nil] The HTTP status, when PostHog answered, or file storage's for `attachment_upload_failed`.
15
15
  attr_reader :status_code
16
16
  # @return [String, nil] Why PostHog refused the email.
17
17
  attr_reader :why
@@ -37,10 +37,19 @@ module PostHog
37
37
  @retry_after = retry_after
38
38
  end
39
39
 
40
+ SDK_ERROR_NAMES = {
41
+ 'network_error' => 'service_unavailable',
42
+ 'invalid_attachment' => 'validation_error',
43
+ 'too_many_attachments' => 'validation_error',
44
+ 'message_too_large' => 'validation_error'
45
+ }.freeze
46
+ private_constant :SDK_ERROR_NAMES
47
+
40
48
  # @api private
41
49
  def self.name_for(status_code, code)
50
+ return status_code.to_i >= 500 ? 'service_unavailable' : 'application_error' if code == 'attachment_upload_failed'
42
51
  return 'missing_api_key' if code == 'missing_secret_key' || status_code == 401
43
- return code == 'network_error' ? 'service_unavailable' : 'application_error' if status_code.nil?
52
+ return SDK_ERROR_NAMES.fetch(code, 'application_error') if status_code.nil?
44
53
 
45
54
  case status_code
46
55
  when 400 then 'validation_error'
@@ -8,6 +8,7 @@ require 'time'
8
8
  require 'uri'
9
9
  require 'zlib'
10
10
 
11
+ require 'posthog/email_attachments'
11
12
  require 'posthog/email_error'
12
13
  require 'posthog/logging'
13
14
  require 'posthog/utils'
@@ -71,6 +72,7 @@ module PostHog
71
72
  Status = Struct.new(:id, :status, :created_at, :status_at, :reason, keyword_init: true)
72
73
 
73
74
  SEND_PATH = '/api/projects/@current/messaging/send/email/'
75
+ UPLOADS_PATH = '/api/projects/@current/messaging/attachments/uploads/'
74
76
  STATUS_PATH = '/api/projects/@current/messaging/emails/%<message_id>s/'
75
77
  US_APP_HOST = 'https://us.posthog.com'
76
78
  EU_APP_HOST = 'https://eu.posthog.com'
@@ -86,6 +88,7 @@ module PostHog
86
88
  IDEMPOTENCY_KEY_PATTERN = /\A[\x21-\x7e]{1,255}\z/
87
89
  TEMPLATE_KEY_PATTERN = /\A[a-zA-Z0-9_-]{1,400}\z/
88
90
  HEADER_TOKEN_PATTERN = /\A[\x21-\x7e]+\z/
91
+ JSON_CONTENT = { 'Content-Type' => 'application/json' }.freeze
89
92
  SEND_KEY_NEEDED = 'Sending email needs secret_key, a project secret API key with the ' \
90
93
  'transactional_email:write scope.'
91
94
  READ_KEY_NEEDED = 'Reading an email status needs secret_key, a project secret API key with the ' \
@@ -94,14 +97,14 @@ module PostHog
94
97
  "project's engagement setting."
95
98
  CODE_FORM_WHY = 'A send with template_key takes its content from your code.'
96
99
  TEMPLATE_FIELDS = %i[template_data].freeze
97
- CODE_FIELDS = %i[subject html text from reply_to sensitive tracking capture_engagement].freeze
100
+ CODE_FIELDS = %i[subject html text from reply_to cc bcc attachments sensitive tracking capture_engagement].freeze
98
101
  NETWORK_ERRORS = [
99
102
  Timeout::Error, SocketError, SystemCallError, IOError, EOFError, OpenSSL::SSL::SSLError,
100
103
  Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError, Zlib::Error
101
104
  ].freeze
102
- private_constant :SEND_PATH, :STATUS_PATH, :US_APP_HOST, :EU_APP_HOST, :CLOUD_APP_HOSTS,
105
+ private_constant :SEND_PATH, :UPLOADS_PATH, :STATUS_PATH, :US_APP_HOST, :EU_APP_HOST, :CLOUD_APP_HOSTS,
103
106
  :MAX_RETRY_DELAY_SECONDS, :UUID_PATTERN, :IDEMPOTENCY_KEY_PATTERN, :TEMPLATE_KEY_PATTERN,
104
- :HEADER_TOKEN_PATTERN, :SEND_KEY_NEEDED, :READ_KEY_NEEDED, :TEMPLATE_FORM_WHY,
107
+ :HEADER_TOKEN_PATTERN, :JSON_CONTENT, :SEND_KEY_NEEDED, :READ_KEY_NEEDED, :TEMPLATE_FORM_WHY,
105
108
  :CODE_FORM_WHY, :TEMPLATE_FIELDS, :CODE_FIELDS, :NETWORK_ERRORS
106
109
 
107
110
  # @api private
@@ -140,6 +143,20 @@ module PostHog
140
143
  # @param from [String] Code form: a verified sender, such as `Acme <hello@example.com>`. Without it, the
141
144
  # project's default sender.
142
145
  # @param reply_to [String, Array<String>] Code form: one address or a list of addresses.
146
+ # @param cc [String, Array<String>] Code form: one address or a list of addresses that get a visible copy, at
147
+ # most 10. An empty list sends no copy.
148
+ # @param bcc [String, Array<String>] Code form: one address or a list of addresses that get a hidden copy, at
149
+ # most 10. An empty list sends no copy.
150
+ # @param attachments [Array<Hash>] Code form: files sent with the email, at most 10 files and 40 MB per email
151
+ # after Base64 encoding, about 29 MB of files. The client hashes each file, uploads the files PostHog doesn't
152
+ # have yet straight to PostHog's file storage, then sends the email naming the files by their SHA-256. A file
153
+ # sent before by the same project uploads nothing again. Each file is a Hash with:
154
+ # - +filename+ [String] the name the recipient sees, such as `invoice.pdf`;
155
+ # - +content+ [String, Array<Integer>] the file's bytes, as a binary String such as `File.binread(path)`
156
+ # returns or as a list of byte values. Any other String is taken as the file encoded as Base64, on one
157
+ # line or wrapped at 60, 64 or 76 characters. PostHog can't fetch a file from a path or URL;
158
+ # - +content_type+ [String] the MIME type, optional. Without it, the type follows the file name;
159
+ # - +content_id+ [String] optional: shows the file inline where `html` has `<img src="cid:...">` with this ID.
143
160
  # @param sensitive [Boolean] Code form: +true+ when the email carries login links, reset tokens or codes. A
144
161
  # sensitive email keeps its links unchanged unless +tracking+ turns clicks on, leaves its subject off engagement
145
162
  # events, and keeps its content out of logs. Left out, the email takes the setting of the template made in
@@ -166,23 +183,33 @@ module PostHog
166
183
  # retries off.
167
184
  # @return [SendResult] The queued email.
168
185
  # @raise [EmailError] PostHog did not queue the email, or the client could not tell whether it did.
186
+ # Before any request, {EmailError#code} is `invalid_attachment` for a file the client can't send,
187
+ # `too_many_attachments` for more than 10 files, and `message_too_large` for files too large for one email.
188
+ # It is `attachment_upload_failed` when file storage refused an upload, and `not_found` with
189
+ # {EmailError#field} `attachments` when PostHog has no upload route for this project. Unless `app_host` is
190
+ # an http URL, an upload URL without https raises `api_error` on the file's field, such as
191
+ # `attachments__0`, before any file goes out. No email was sent.
169
192
  # @raise [ArgumentError] An argument has the wrong type or format, or the call mixes the two forms.
170
193
  def send(
171
194
  to:, template_id: nil, template_data: nil, template_key: nil, subject: nil, html: nil, text: nil, from: nil,
172
- reply_to: nil, sensitive: nil, tracking: nil, capture_engagement: nil, distinct_id: nil, idempotency_key: nil,
173
- max_retries: nil
195
+ reply_to: nil, cc: nil, bcc: nil, attachments: nil, sensitive: nil, tracking: nil, capture_engagement: nil,
196
+ distinct_id: nil, idempotency_key: nil, max_retries: nil
174
197
  )
175
198
  fields = {
176
199
  template_data: template_data, subject: subject, html: html, text: text, from: from, reply_to: reply_to,
177
- sensitive: sensitive, tracking: tracking, capture_engagement: capture_engagement
200
+ cc: cc, bcc: bcc, attachments: attachments, sensitive: sensitive, tracking: tracking,
201
+ capture_engagement: capture_engagement
178
202
  }.compact
179
203
  check_recipient(to, distinct_id, idempotency_key, max_retries)
180
204
  payload = content(template_id, template_key, fields).merge(to: to)
205
+ files = EmailAttachments.from(fields.fetch(:attachments, []), bodies_with_derived_text(fields), fields[:subject])
206
+ payload[:attachments] = files.references unless files.empty?
181
207
  payload[:distinct_id] = distinct_id unless distinct_id.nil?
182
208
  body = JSON.generate(payload)
183
209
  headers = { 'Content-Type' => 'application/json', 'Idempotency-Key' => idempotency_key || SecureRandom.uuid }
184
210
 
185
211
  result = call('no email was sent', SEND_KEY_NEEDED) do |secret_key|
212
+ upload(files, secret_key, max_retries || @max_retries) unless files.empty?
186
213
  uri = URI(@app_host + SEND_PATH)
187
214
  with_retries(max_retries || @max_retries) do
188
215
  parse_send_reply(request(Net::HTTP::Post.new(uri), uri, secret_key, headers, body))
@@ -250,6 +277,11 @@ module PostHog
250
277
  value.is_a?(String) && UUID_PATTERN.match?(value)
251
278
  end
252
279
 
280
+ def bodies_with_derived_text(fields)
281
+ html, text = fields.values_at(:html, :text)
282
+ [html, text.to_s.empty? ? html : text].compact
283
+ end
284
+
253
285
  def resolve_app_host(host, app_host)
254
286
  explicit = app_host.is_a?(String) ? app_host.strip.chomp('/') : ''
255
287
  return CLOUD_APP_HOSTS[host.to_s.strip.chomp('/')] if explicit.empty?
@@ -325,7 +357,11 @@ module PostHog
325
357
  end
326
358
 
327
359
  code = fields.slice(:subject, :html, :text, :from).merge(template_key: template_key)
328
- code[:reply_to] = addresses(fields[:reply_to]) if fields.key?(:reply_to)
360
+ code[:reply_to] = addresses(:reply_to, fields[:reply_to]) if fields.key?(:reply_to)
361
+ %i[cc bcc].each do |name|
362
+ list = fields.key?(name) ? addresses(name, fields[name]) : []
363
+ code[name] = list unless list.empty?
364
+ end
329
365
  code[:capture_engagement] = fields[:capture_engagement] if fields.key?(:capture_engagement)
330
366
  code[:sensitive] = fields[:sensitive] if fields.key?(:sensitive)
331
367
  code[:tracking] = tracking(fields[:tracking]) if fields.key?(:tracking)
@@ -351,11 +387,11 @@ module PostHog
351
387
  raise ArgumentError, "#{message} #{why} Remove #{field}, or send with #{other_form}."
352
388
  end
353
389
 
354
- def addresses(reply_to)
355
- list = reply_to.is_a?(String) ? [reply_to] : reply_to
390
+ def addresses(name, value)
391
+ list = value.is_a?(String) ? [value] : value
356
392
  return list if list.is_a?(Array) && list.all? { |address| nonempty_string?(address) }
357
393
 
358
- raise ArgumentError, 'reply_to must be one address or a list of addresses.'
394
+ raise ArgumentError, "#{name} must be one address or a list of addresses."
359
395
  end
360
396
 
361
397
  def call(nothing_done, key_needed)
@@ -437,16 +473,96 @@ module PostHog
437
473
  case error.status_code
438
474
  when nil then error.code == 'network_error'
439
475
  when 409 then error.code == 'idempotency_key_in_flight'
440
- when 429 then error.code != 'quota_limited'
476
+ when 429 then !%w[quota_limited upload_quota_exceeded].include?(error.code)
477
+ when 500, 502, 504 then error.code == 'attachment_upload_failed'
441
478
  else error.status_code == 503
442
479
  end
443
480
  end
444
481
 
482
+ def upload(files, secret_key, max_retries)
483
+ distinct = files.distinct
484
+ uri = URI(@app_host + UPLOADS_PATH)
485
+ body = JSON.generate(files: distinct.map { |file| { sha256: file.sha256, size: file.bytes.bytesize } })
486
+ slots = with_retries(max_retries) do
487
+ parse_uploads_reply(request(Net::HTTP::Post.new(uri), uri, secret_key, JSON_CONTENT, body), distinct)
488
+ end
489
+ distinct.zip(slots).each { |file, slot| put_file(file, slot, max_retries) if slot['status'] == 'upload' }
490
+ end
491
+
492
+ def parse_uploads_reply((status, payload, retry_after), files)
493
+ fields = payload.is_a?(Hash) ? payload : {}
494
+ fields = { 'code' => 'not_found', 'attr' => 'attachments' }.merge(fields.compact) if status == 404
495
+ raise reply_error(fields, status, retry_after) unless status.between?(200, 299)
496
+
497
+ slots = fields['files']
498
+ unless slots.is_a?(Array) && slots.size == files.size && files.zip(slots).all? { |pair| slot?(*pair) }
499
+ raise EmailError.new(code: 'api_error', message: "PostHog answered without the files' uploads.",
500
+ status_code: status)
501
+ end
502
+ file_without_tls, = files.zip(slots).find { |_, slot| without_tls?(slot) }
503
+ raise upload_without_tls(file_without_tls, status) if file_without_tls
504
+
505
+ slots
506
+ end
507
+
508
+ def without_tls?(slot)
509
+ slot['status'] == 'upload' && URI(@app_host).scheme == 'https' && URI(slot['url']).scheme != 'https'
510
+ end
511
+
512
+ def upload_without_tls(file, status)
513
+ filename = file.reference['filename']
514
+ EmailError.new(code: 'api_error', field: file.field, status_code: status,
515
+ message: "PostHog gave an upload URL for #{filename} that isn't https, so no file was uploaded " \
516
+ 'and no email was sent.',
517
+ why: "Your app_host uses https, and #{filename} would have gone to file storage unencrypted.",
518
+ fix: "Fix the file storage's URL so it uses https. For local development over http, set " \
519
+ 'app_host to an http URL.')
520
+ end
521
+
522
+ def slot?(file, slot)
523
+ return false unless slot.is_a?(Hash) && slot['sha256'] == file.sha256
524
+ return slot['status'] == 'present' unless slot['status'] == 'upload'
525
+
526
+ slot['method'] == 'PUT' && web_url?(slot['url'].to_s) && slot['headers'].is_a?(Hash) &&
527
+ slot['headers'].all? { |name, value| name.is_a?(String) && value.is_a?(String) }
528
+ end
529
+
530
+ def put_file(file, slot, max_retries)
531
+ uri = URI(slot['url'])
532
+ with_retries(max_retries) do
533
+ request = Net::HTTP::Put.new(uri)
534
+ request['Content-Type'] = 'application/octet-stream'
535
+ status, answer, retry_after = exchange(request, uri, slot['headers'], file.bytes)
536
+ raise upload_failed(file, status, answer, retry_after) unless status.between?(200, 299)
537
+ end
538
+ rescue EmailError => e
539
+ raise unless e.code == 'network_error'
540
+
541
+ raise EmailError.new(code: 'network_error', field: file.field, retry_after: e.retry_after,
542
+ message: "The upload of #{file.reference['filename']} to file storage failed, so no " \
543
+ 'email was sent.')
544
+ end
545
+
546
+ def upload_failed(file, status, answer, retry_after)
547
+ answer = answer.to_s.dup.force_encoding(Encoding::UTF_8).scrub
548
+ storage_said = [answer[%r{<Code>([^<]*)</Code>}, 1], answer[%r{<Message>([^<]*)</Message>}, 1]].compact
549
+ EmailError.new(
550
+ code: 'attachment_upload_failed', status_code: status, field: file.field, retry_after: retry_after,
551
+ message: "File storage refused the upload of #{file.reference['filename']} with HTTP #{status}" \
552
+ "#{" (#{storage_said.join(': ')})" unless storage_said.empty?}, so no email was sent."
553
+ )
554
+ end
555
+
445
556
  def request(request, uri, secret_key, headers, body = nil)
446
557
  request['Authorization'] = "Bearer #{secret_key}"
447
558
  request['Accept'] = 'application/json'
448
559
  request['User-Agent'] = @user_agent if @user_agent
449
560
  request['X-PostHog-Migrated-From'] = @migrated_from if @migrated_from
561
+ status, answer, retry_after = exchange(request, uri, headers, body)
562
+ [status, parse_json(answer), retry_after]
563
+ end
564
+
565
+ def exchange(request, uri, headers, body)
450
566
  headers.each { |name, value| request[name] = value }
451
567
  request.body = body if body
452
568
 
@@ -454,7 +570,7 @@ module PostHog
454
570
  response = Net::HTTP.start(uri.hostname, uri.port, connection_options(uri)) do |http|
455
571
  http.request(request) { |started| head = started }
456
572
  end
457
- [response.code.to_i, parse_json(response.body), parse_retry_after(response['Retry-After'])]
573
+ [response.code.to_i, response.body, parse_retry_after(response['Retry-After'])]
458
574
  rescue *NETWORK_ERRORS
459
575
  # A reply whose body broke off retries with the same idempotency key, after its Retry-After when it sent one.
460
576
  raise EmailError.new(code: 'network_error', message: 'The request to PostHog failed.',
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module PostHog
4
- VERSION = '3.33.0'
4
+ VERSION = '3.34.0'
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: posthog-ruby
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.33.0
4
+ version: 3.34.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - ''
@@ -38,6 +38,7 @@ files:
38
38
  - lib/posthog/backoff_policy.rb
39
39
  - lib/posthog/client.rb
40
40
  - lib/posthog/defaults.rb
41
+ - lib/posthog/email_attachments.rb
41
42
  - lib/posthog/email_error.rb
42
43
  - lib/posthog/emails.rb
43
44
  - lib/posthog/exception_capture.rb