ottertrail 0.1.0 → 0.2.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: aa5db014faa43fb8e579efc1d72039e3b3abdb837b598e1b315d0029b0c2cdd6
4
- data.tar.gz: d901e97fc0eb1ed16838400a766a9ba7f35bbcb43736dc2c23cb606299214968
3
+ metadata.gz: abdd0413d8bd071b0cb5982c0fef6ac786f6b077df1719201735b15b64889e98
4
+ data.tar.gz: b38ef29424fc9cc0f67b51770a8795674deb2350ec8a9c444e20628283228bf5
5
5
  SHA512:
6
- metadata.gz: 825e6b0ea42f83860c593232ee934c95929369f11a18e67019d3d4e890c6bc673d7c3d8fc98e3761a3dfaa62cb35dd4046f51fa3e7ab2f32baba9fb5e522f0c3
7
- data.tar.gz: d10cc4c25fea5d6ca544bad103ba1b161ce6c106e554d7968906add6122e4fe0b63775f9746ba6cdc878af01617a8212781aa9ced307d01706a29ed9d44e4fc6
6
+ metadata.gz: 73f73e455e70d5b8e1ecef00b026bc44470f1554f6a28886e6eec736b9cc804f0593f474bed7ad908b56b9554c86736f732e4523db438c7de744ee01585efa4e
7
+ data.tar.gz: 17ed2d410e6b596e7a49372b5f05e3da4b3b8ce69e0cc725caff45953fb77add080e9cc50ade4828921585c455a6251e97cade89ab042ec61d83e5832f4c4c52
data/README.md CHANGED
@@ -2,7 +2,10 @@
2
2
 
3
3
  The Ruby SDK for [Ottertrail](https://ottertrail.dev), web analytics and error tracking.
4
4
 
5
- Version 0.1 has one method, `Ottertrail.sign_user_id`. It signs the ID of a signed-in user on your server, so that Ottertrail can trust that the ID came from you.
5
+ It has two methods, for your server:
6
+
7
+ - `Ottertrail.sign_user_id` signs the ID of a signed-in user, so that Ottertrail can trust that the ID came from you.
8
+ - `Ottertrail.track` sends events of signed-in users from your server, such as a payment or a cancelled subscription.
6
9
 
7
10
  ## Install
8
11
 
@@ -135,6 +138,107 @@ It raises an `ArgumentError` when:
135
138
 
136
139
  The error message never contains the secret key.
137
140
 
141
+ ## Send events from your server
142
+
143
+ Some events happen on your server, not in the browser: a payment, a renewed subscription, a cancelled order. `Ottertrail.track` sends them to Ottertrail with the project's secret key.
144
+
145
+ ```ruby
146
+ require "ottertrail"
147
+
148
+ # Reads OTTERTRAIL_HOST and OTTERTRAIL_SECRET_KEY.
149
+ result = Ottertrail.track(
150
+ {name: "subscription_started", user_id: user.id, properties: {plan: "team"}}
151
+ )
152
+ result.stored # => 1
153
+ ```
154
+
155
+ Set two variables where your server runs:
156
+
157
+ ```sh
158
+ export OTTERTRAIL_HOST=https://your-instance.ottertrail.app
159
+ export OTTERTRAIL_SECRET_KEY=sk_...
160
+ ```
161
+
162
+ `OTTERTRAIL_HOST` is the address where your instance's dashboard opens. The secret key is in the project's settings: on the General tab, under Keys, press Show.
163
+
164
+ The events show in Users and on each user's page, in Retention, and in Custom events. They do not show in Web analytics, Funnels, or Experiments, because those count visits, and an event from your server has no visit.
165
+
166
+ ### `Ottertrail.track(events, host: nil, secret_key: nil, environment: nil, release: nil, timeout: 10)`
167
+
168
+ It sends the events in one request, waits for the answer, and returns an `Ottertrail::Result` with three counts:
169
+
170
+ - `stored`: the events that were stored. An event that was sent before, with the same ID, counts here too.
171
+ - `too_old`: the events more than 24 hours old. They are not stored.
172
+ - `ignored`: the events that your plan does not store, for example above its monthly limit.
173
+
174
+ `events` is one event, or an Array of 1 to 50. Each event is a Hash with Symbol keys:
175
+
176
+ | Key | Required | Value |
177
+ | -------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
178
+ | `:name` | Yes | 1 to 200 characters, without control characters. The tracker's names are refused: `pageview`, `engagement`, `experiment`, `error`, `outbound_link`, `file_download`, `not_found`, and `vitals`. |
179
+ | `:user_id` | Yes | A `String`, or an `Integer` from -(2\*\*53 - 1) to 2\*\*53 - 1. It is trimmed as `Ottertrail.sign_user_id` trims it, and has 1 to 200 characters after that, on one line. Use the same ID as the tracker, so the events join that user. |
180
+ | `:properties` | No | A flat Hash of at most 30 entries. Each name is a `String` or a `Symbol` of 1 to 100 characters. Each value is a `String` of at most 500 characters, an `Integer`, a finite `Float`, `true`, `false`, or `nil`. At most 8 KB as JSON. |
181
+ | `:path` | No | The page that the event is about, such as `/checkout`. It starts with one `/`, and has at most 2,048 characters. The instance drops a query or a fragment. |
182
+ | `:occurred_at` | No | When it happened: a `Time`, or an `Integer` of milliseconds since 1970. The default is now. |
183
+ | `:id` | No | A UUID. The default is a new random UUID. Send the same ID again, and the instance stores the event once. |
184
+
185
+ The options:
186
+
187
+ - `host`: the instance's address, such as `https://your-instance.ottertrail.app`. The default is `ENV["OTTERTRAIL_HOST"]`. It must start with `https://`. Only `localhost`, `127.0.0.1`, and `[::1]` can use `http://`.
188
+ - `secret_key`: the project's secret key. The default is `ENV["OTTERTRAIL_SECRET_KEY"]`.
189
+ - `environment`: such as `staging`. 1 to 64 letters, digits, dots, underscores, or hyphens, starting with a letter or a digit. Leave it out for production.
190
+ - `release`: the release of your server, such as `api@2.3.0`. 1 to 200 characters, without spaces.
191
+ - `timeout`: the seconds that each try waits to connect, to send, and for the answer. The default is 10.
192
+
193
+ ```ruby
194
+ Ottertrail.track(
195
+ [
196
+ {name: "invoice_paid", user_id: 42, properties: {amount: 49.0, currency: "EUR"}},
197
+ {name: "seats_changed", user_id: 42, properties: {seats: 12}, occurred_at: Time.now - 60}
198
+ ],
199
+ environment: "staging",
200
+ release: "api@2.3.0"
201
+ )
202
+ ```
203
+
204
+ ### Retries
205
+
206
+ A request can fail on the way, or the instance can be busy. Then `Ottertrail.track` tries again, up to 3 tries in all. It retries after a network error or a timeout, and after the answers 429 and 503. It waits as long as the instance's `Retry-After` header says, at most 30 seconds. Without the header, it waits 1 second, then 2. Every try sends the same events with the same IDs, so the instance stores each one once.
207
+
208
+ `Ottertrail.track` blocks while it waits. To keep a web request fast, call it from a background job.
209
+
210
+ ### Errors
211
+
212
+ Before it sends anything, `Ottertrail.track` checks every argument. When one is wrong, it raises a `TypeError` for a wrong type, or an `ArgumentError` for a wrong value, and sends nothing. Each message starts with `Ottertrail: ` and says what is wrong.
213
+
214
+ When the instance refuses the events, or when the last try fails, it raises an `Ottertrail::Error`:
215
+
216
+ - `status`: the HTTP status, such as `401`. It is `nil` when no answer came.
217
+ - `code`: the instance's error code, such as `unknown_key`, or `nil`.
218
+ - `message`: the status, the code, and the instance's message.
219
+
220
+ ```ruby
221
+ begin
222
+ Ottertrail.track({name: "invoice_paid", user_id: 42})
223
+ rescue Ottertrail::Error => error
224
+ logger.warn("Ottertrail: #{error.status} #{error.code}")
225
+ end
226
+ ```
227
+
228
+ The codes:
229
+
230
+ | Status | Code | Why |
231
+ | ------ | ------------- | ------------------------------------------------------------------------------------ |
232
+ | 400 | `bad_request` | The request does not have the form that the instance expects. |
233
+ | 400 | `bad_event` | An event is not valid, for example its `occurred_at` is more than 5 minutes ahead. |
234
+ | 401 | `unknown_key` | No project has this secret key. It may have been replaced in the project's settings. |
235
+ | 403 | `refused` | The instance cannot save events now. |
236
+ | 413 | | The request is larger than 64 KB. Send fewer events at a time. |
237
+ | 429 | `too_many` | Too many events. Retried first. |
238
+ | 503 | `unavailable` | The instance could not save the events. Retried first. |
239
+
240
+ No error message contains the secret key.
241
+
138
242
  ## Ruby versions
139
243
 
140
244
  Ruby 3.3 and later. Each version is tested on Ruby 3.3, 3.4, and 4.0.
@@ -0,0 +1,417 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "net/http"
5
+ require "openssl"
6
+ require "securerandom"
7
+ require "uri"
8
+
9
+ module Ottertrail
10
+ # Raised by Ottertrail.track when the instance refused the events, or when they could not be
11
+ # sent after every try. The message never contains the secret key.
12
+ class Error < StandardError
13
+ # @return [Integer, nil] The HTTP status of the instance's answer, or nil when no answer came.
14
+ attr_reader :status
15
+ # @return [String, nil] The instance's error code, such as "unknown_key" or "bad_event".
16
+ attr_reader :code
17
+
18
+ def initialize(message, status: nil, code: nil)
19
+ super(message)
20
+ @status = status
21
+ @code = code
22
+ end
23
+ end
24
+
25
+ # What the instance did with the events that Ottertrail.track sent.
26
+ #
27
+ # - +stored+: the events stored, a retry's events included.
28
+ # - +too_old+: the events more than 24 hours old, which are not stored.
29
+ # - +ignored+: the events that the instance's plan does not store, as above its limit.
30
+ Result = Data.define(:stored, :too_old, :ignored)
31
+
32
+ HOST_VARIABLE = "OTTERTRAIL_HOST"
33
+ EVENTS_PATH = "/api/server-events"
34
+ MAX_EVENTS = 50
35
+ MAX_EVENT_NAME = 200
36
+ MAX_PATH = 2_048
37
+ MAX_PROPERTIES = 30
38
+ MAX_PROPERTY_NAME = 100
39
+ MAX_PROPERTY_TEXT = 500
40
+ MAX_PROPERTIES_BYTES = 8_192
41
+ # The latest time that JavaScript's Date holds, which the instance takes.
42
+ MAX_MOMENT = 8_640_000_000_000_000
43
+ # The tracker's, which mean a page and a visit, and one that a later version may give a meaning.
44
+ RESERVED_NAMES = %w[
45
+ pageview engagement experiment error outbound_link file_download not_found vitals
46
+ ].freeze
47
+ EVENT_KEYS = %i[name user_id properties path occurred_at id].freeze
48
+ UUID = /\A\h{8}(?:-\h{4}){3}-\h{12}\z/
49
+ ENVIRONMENT = /\A[A-Za-z0-9][A-Za-z0-9._-]{0,63}\z/
50
+ # The rule of the tracker's data-release. Its \s is JavaScript's: the controls among them, and
51
+ # Zs, U+2028, U+2029, and U+FEFF.
52
+ RELEASE = /\A[^\p{Cc}\p{Cs}\p{Zs}\u2028\u2029\uFEFF]{1,200}\z/
53
+ LOCAL_HOSTS = %w[localhost 127.0.0.1 [::1]].freeze
54
+ DEFAULT_TIMEOUT = 10
55
+ MAX_ATTEMPTS = 3
56
+ # The waits before the second and the third try, when the instance does not say.
57
+ RETRY_WAITS = [1, 2].freeze
58
+ MAX_RETRY_AFTER = 30
59
+ RETRY_STATUSES = [429, 503].freeze
60
+ # A broken answer counts too: a proxy or a dropped connection can cut it.
61
+ NETWORK_ERRORS = [
62
+ IOError, SocketError, SystemCallError, Timeout::Error, OpenSSL::SSL::SSLError,
63
+ Net::HTTPBadResponse, Net::ProtocolError
64
+ ].freeze
65
+ private_constant :HOST_VARIABLE, :EVENTS_PATH, :MAX_EVENTS, :MAX_EVENT_NAME, :MAX_PATH,
66
+ :MAX_PROPERTIES, :MAX_PROPERTY_NAME, :MAX_PROPERTY_TEXT, :MAX_PROPERTIES_BYTES, :MAX_MOMENT,
67
+ :RESERVED_NAMES, :EVENT_KEYS, :UUID, :ENVIRONMENT, :RELEASE, :LOCAL_HOSTS, :DEFAULT_TIMEOUT,
68
+ :MAX_ATTEMPTS, :RETRY_WAITS, :MAX_RETRY_AFTER, :RETRY_STATUSES, :NETWORK_ERRORS
69
+
70
+ class << self
71
+ # Sends events of signed-in users from your server, and waits for the instance's answer.
72
+ #
73
+ # @param events [Hash, Array<Hash>] One event, or an Array of 1 to 50. Each is a Hash with the
74
+ # keys +:name+ and +:user_id+, and optionally +:properties+, +:path+, +:occurred_at+, and +:id+.
75
+ # @param host [String, nil] The instance's address, such as https://name.ottertrail.app.
76
+ # Defaults to +ENV["OTTERTRAIL_HOST"]+.
77
+ # @param secret_key [String, nil] The project's secret key. Defaults to
78
+ # +ENV["OTTERTRAIL_SECRET_KEY"]+.
79
+ # @param environment [String, nil] Such as "staging". Nil means production.
80
+ # @param release [String, nil] The release of your server, such as "api@2.3.0".
81
+ # @param timeout [Numeric] The seconds that each try waits for the instance.
82
+ # @return [Result] How many events were stored, too old, and ignored.
83
+ # @raise [TypeError] If an argument has the wrong type.
84
+ # @raise [ArgumentError] If an argument is not valid. Nothing is sent then.
85
+ # @raise [Ottertrail::Error] If the instance refused the events, or every try failed.
86
+ def track(events, host: nil, secret_key: nil, environment: nil, release: nil,
87
+ timeout: DEFAULT_TIMEOUT)
88
+ batch = {v: 1} # : Hash[Symbol, untyped]
89
+ batch[:environment] = clean_environment(environment) unless environment.nil?
90
+ batch[:release] = clean_release(release) unless release.nil?
91
+ batch[:events] = clean_events(events)
92
+ seconds = clean_timeout(timeout)
93
+ uri = clean_host(host.nil? ? ENV[HOST_VARIABLE] : host)
94
+ key = clean_secret_key(secret_key.nil? ? ENV[SECRET_KEY_VARIABLE] : secret_key, "track")
95
+ # One body for every try, so that the instance stores each event once, by its ID.
96
+ send_events(uri, key, JSON.generate(batch), seconds)
97
+ end
98
+
99
+ private
100
+
101
+ def clean_events(events)
102
+ list = case events
103
+ when Hash then [events]
104
+ when Array then events
105
+ else
106
+ raise TypeError, "Ottertrail: the events must be a Hash, or an Array of Hashes."
107
+ end
108
+ if list.empty? || list.length > MAX_EVENTS
109
+ raise ArgumentError, "Ottertrail: send 1 to #{MAX_EVENTS} events at a time."
110
+ end
111
+ now = epoch_ms(Time.now)
112
+ list.map { |event| clean_event(event, now) }
113
+ end
114
+
115
+ def clean_event(event, now)
116
+ raise TypeError, "Ottertrail: each event must be a Hash." unless event.is_a?(Hash)
117
+ check_event_keys(event)
118
+ raise ArgumentError, "Ottertrail: every event needs a :name." if event[:name].nil?
119
+ raise ArgumentError, "Ottertrail: every event needs a :user_id." if event[:user_id].nil?
120
+
121
+ cleaned = {
122
+ id: clean_id(event[:id]),
123
+ name: clean_name(event[:name]),
124
+ occurredAt: clean_occurred_at(event[:occurred_at], now),
125
+ userId: clean_user_id(event[:user_id])
126
+ } # : Hash[Symbol, untyped]
127
+ cleaned[:path] = clean_path(event[:path]) unless event[:path].nil?
128
+ cleaned[:properties] = clean_properties(event[:properties]) unless event[:properties].nil?
129
+ cleaned
130
+ end
131
+
132
+ def check_event_keys(event)
133
+ unknown = event.keys.find { |key| !EVENT_KEYS.include?(key) }
134
+ return if unknown.nil?
135
+
136
+ keys = "Its keys are :name, :user_id, :properties, :path, :occurred_at, and :id."
137
+ if unknown.is_a?(String) && EVENT_KEYS.include?(unknown.to_sym)
138
+ raise ArgumentError, "Ottertrail: an event's keys must be Symbols, such as :user_id. #{keys}"
139
+ end
140
+ if unknown.is_a?(Symbol)
141
+ raise ArgumentError, "Ottertrail: an event has an unknown key, #{unknown.inspect}. #{keys}"
142
+ end
143
+ raise ArgumentError, "Ottertrail: an event has an unknown key. #{keys}"
144
+ end
145
+
146
+ def clean_id(id)
147
+ return SecureRandom.uuid if id.nil?
148
+ raise TypeError, "Ottertrail: an event's id must be a string." unless id.is_a?(String)
149
+ return id.encode(Encoding::UTF_8) if id.ascii_only? && UUID.match?(id)
150
+
151
+ raise ArgumentError,
152
+ "Ottertrail: an event's id must be a UUID, such as 1b4e28ba-2fa1-41d2-883f-0016d3cca427."
153
+ end
154
+
155
+ def clean_name(name)
156
+ raise TypeError, "Ottertrail: an event's name must be a string." unless name.is_a?(String)
157
+ text = utf8(name, "an event's name")
158
+ if text.empty? || text.length > MAX_EVENT_NAME
159
+ raise ArgumentError, "Ottertrail: an event's name must be 1 to #{MAX_EVENT_NAME} characters."
160
+ end
161
+ if CONTROL_OR_SURROGATE.match?(text)
162
+ raise ArgumentError, "Ottertrail: an event's name must not contain control characters."
163
+ end
164
+ if RESERVED_NAMES.include?(text)
165
+ raise ArgumentError,
166
+ "Ottertrail: an event from your server cannot have the tracker's name #{text}. " \
167
+ "The tracker's names are: #{RESERVED_NAMES.join(", ")}."
168
+ end
169
+ text
170
+ end
171
+
172
+ def clean_occurred_at(occurred_at, now)
173
+ ms = case occurred_at
174
+ when nil then now
175
+ when Time then epoch_ms(occurred_at)
176
+ when Integer then occurred_at
177
+ else
178
+ raise TypeError,
179
+ "Ottertrail: an event's occurred_at must be a Time, or an Integer of milliseconds since 1970."
180
+ end
181
+ return ms if ms.between?(0, MAX_MOMENT)
182
+
183
+ raise ArgumentError,
184
+ "Ottertrail: an event's occurred_at must be from 1970 to the year 275760, " \
185
+ "or 0 to #{MAX_MOMENT} milliseconds."
186
+ end
187
+
188
+ def epoch_ms(time)
189
+ (time.to_r * 1000).floor
190
+ end
191
+
192
+ def clean_path(path)
193
+ raise TypeError, "Ottertrail: an event's path must be a string." unless path.is_a?(String)
194
+ text = utf8(path, "an event's path")
195
+ return text if text.start_with?("/") && !text.start_with?("//") && text.length <= MAX_PATH
196
+
197
+ raise ArgumentError,
198
+ "Ottertrail: an event's path must start with one /, such as /checkout, " \
199
+ "and have at most #{MAX_PATH} characters."
200
+ end
201
+
202
+ def clean_properties(properties)
203
+ unless properties.is_a?(Hash)
204
+ raise TypeError, "Ottertrail: an event's properties must be a Hash."
205
+ end
206
+ if properties.length > MAX_PROPERTIES
207
+ raise ArgumentError, "Ottertrail: an event can have at most #{MAX_PROPERTIES} properties."
208
+ end
209
+ cleaned = {} # : Hash[String, untyped]
210
+ properties.each do |name, value|
211
+ key = clean_property_name(name)
212
+ if cleaned.key?(key)
213
+ raise ArgumentError, "Ottertrail: two of an event's properties have the same name."
214
+ end
215
+ cleaned[key] = clean_property_value(value)
216
+ end
217
+ if JSON.generate(cleaned).bytesize > MAX_PROPERTIES_BYTES
218
+ raise ArgumentError, "Ottertrail: an event's properties must be at most 8 KB as JSON."
219
+ end
220
+ cleaned
221
+ end
222
+
223
+ def clean_property_name(name)
224
+ unless name.is_a?(String) || name.is_a?(Symbol)
225
+ raise TypeError, "Ottertrail: a property's name must be a String or a Symbol."
226
+ end
227
+ text = utf8(name.to_s, "a property's name")
228
+ if text.empty? || utf16_length(text, MAX_PROPERTY_NAME) > MAX_PROPERTY_NAME
229
+ raise ArgumentError,
230
+ "Ottertrail: a property's name must be 1 to #{MAX_PROPERTY_NAME} characters."
231
+ end
232
+ if text.include?("\0")
233
+ raise ArgumentError, "Ottertrail: a property's name must not contain a NUL character."
234
+ end
235
+ text
236
+ end
237
+
238
+ def clean_property_value(value)
239
+ case value
240
+ when nil, true, false then value
241
+ when String then clean_property_text(value)
242
+ when Integer
243
+ return value if value.between?(-MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)
244
+
245
+ raise ArgumentError,
246
+ "Ottertrail: a property that is an integer must be a safe integer, " \
247
+ "from -(2**53 - 1) to 2**53 - 1."
248
+ when Float
249
+ return value if value.finite?
250
+
251
+ raise ArgumentError, "Ottertrail: a property that is a number must be finite."
252
+ else
253
+ raise TypeError,
254
+ "Ottertrail: a property's value must be a String, an Integer, a Float, true, false, or nil."
255
+ end
256
+ end
257
+
258
+ def clean_property_text(value)
259
+ text = utf8(value, "a property's value")
260
+ if utf16_length(text, MAX_PROPERTY_TEXT) > MAX_PROPERTY_TEXT
261
+ raise ArgumentError,
262
+ "Ottertrail: a property's value must be at most #{MAX_PROPERTY_TEXT} characters."
263
+ end
264
+ if text.include?("\0")
265
+ raise ArgumentError, "Ottertrail: a property's value must not contain a NUL character."
266
+ end
267
+ text
268
+ end
269
+
270
+ def clean_environment(environment)
271
+ raise TypeError, "Ottertrail: the environment must be a string." unless environment.is_a?(String)
272
+ text = utf8(environment, "the environment")
273
+ return text if ENVIRONMENT.match?(text)
274
+
275
+ raise ArgumentError,
276
+ "Ottertrail: the environment must be 1 to 64 letters, digits, dots, underscores, or " \
277
+ "hyphens, and start with a letter or a digit, such as staging."
278
+ end
279
+
280
+ def clean_release(release)
281
+ raise TypeError, "Ottertrail: the release must be a string." unless release.is_a?(String)
282
+ text = utf8(release, "the release")
283
+ return text if RELEASE.match?(text)
284
+
285
+ raise ArgumentError,
286
+ "Ottertrail: the release must be 1 to 200 characters, without spaces or control characters."
287
+ end
288
+
289
+ def clean_timeout(timeout)
290
+ seconds = case timeout
291
+ when Integer, Float, Rational then timeout.to_f
292
+ else raise TypeError, "Ottertrail: the timeout must be a number of seconds."
293
+ end
294
+ return seconds if seconds.positive? && seconds.finite?
295
+
296
+ raise ArgumentError, "Ottertrail: the timeout must be a number of seconds above 0."
297
+ end
298
+
299
+ def clean_host(host)
300
+ if host.nil? || host == ""
301
+ raise ArgumentError,
302
+ "Ottertrail: no instance address. Pass host:, or set #{HOST_VARIABLE}, to the address " \
303
+ "where the instance's dashboard opens, such as https://name.ottertrail.app."
304
+ end
305
+ raise TypeError, "Ottertrail: the host must be a string." unless host.is_a?(String)
306
+
307
+ uri = parse_host(host)
308
+ problem = uri.nil? ? "is not a URL" : host_problem(host, uri)
309
+ return uri if uri.is_a?(URI::HTTP) && problem.nil?
310
+
311
+ raise ArgumentError,
312
+ "Ottertrail: the host #{problem}. Use the address where the " \
313
+ "instance's dashboard opens, such as https://name.ottertrail.app."
314
+ end
315
+
316
+ def parse_host(host)
317
+ host.ascii_only? ? URI.parse(host) : nil
318
+ rescue URI::InvalidURIError
319
+ nil
320
+ end
321
+
322
+ def host_problem(text, uri)
323
+ scheme = "must start with https:// (http:// only for localhost)"
324
+ return scheme unless uri.is_a?(URI::HTTP)
325
+
326
+ name = uri.host.to_s.downcase
327
+ return "is not a URL" if name.empty?
328
+ return scheme unless uri.scheme == "https" || LOCAL_HOSTS.include?(name)
329
+ return "must not have a user name or a password" unless uri.userinfo.nil?
330
+ if !["", "/"].include?(uri.path) || text.include?("?") || text.include?("#")
331
+ return "must have no path, query, or fragment"
332
+ end
333
+ nil
334
+ end
335
+
336
+ def send_events(uri, key, body, timeout)
337
+ attempt = 1
338
+ loop do
339
+ response = begin
340
+ post(uri, key, body, timeout)
341
+ rescue *NETWORK_ERRORS => error
342
+ raise Error, "Ottertrail: the events could not be sent: #{error.message}" if attempt == MAX_ATTEMPTS
343
+
344
+ pause(RETRY_WAITS.fetch(attempt - 1))
345
+ attempt += 1
346
+ next
347
+ end
348
+ status = response.code.to_i
349
+ return read_result(response, status) if status == 202
350
+ raise error_of(response, status) unless RETRY_STATUSES.include?(status) && attempt < MAX_ATTEMPTS
351
+
352
+ pause(retry_after(response["retry-after"]) || RETRY_WAITS.fetch(attempt - 1))
353
+ attempt += 1
354
+ end
355
+ end
356
+
357
+ def post(uri, key, body, timeout)
358
+ http = Net::HTTP.new(uri.hostname.to_s, uri.port)
359
+ http.use_ssl = uri.scheme == "https"
360
+ http.open_timeout = timeout
361
+ http.read_timeout = timeout
362
+ http.write_timeout = timeout
363
+ http.ssl_timeout = timeout
364
+ # The tries are counted here, with the waits that the instance asks for.
365
+ http.max_retries = 0
366
+ request = Net::HTTP::Post.new(EVENTS_PATH)
367
+ request["Authorization"] = "Bearer #{key}"
368
+ request["Content-Type"] = "application/json"
369
+ request["Accept"] = "application/json"
370
+ request["User-Agent"] = "ottertrail-ruby/#{VERSION}"
371
+ request.body = body
372
+ http.start { |connection| connection.request(request) }
373
+ end
374
+
375
+ # Seconds as digits, at most MAX_RETRY_AFTER. Nil for anything else, such as a date.
376
+ def retry_after(value)
377
+ text = value.to_s.strip
378
+ return nil unless /\A\d{1,9}\z/.match?(text)
379
+
380
+ [text.to_i, MAX_RETRY_AFTER].min
381
+ end
382
+
383
+ def pause(seconds)
384
+ sleep(seconds) if seconds.positive?
385
+ end
386
+
387
+ def read_result(response, status)
388
+ answer = parse_answer(response)
389
+ counts = answer&.values_at("stored", "tooOld", "ignored")
390
+ if counts.nil? || !counts.all? { |count| count.is_a?(Integer) && count >= 0 }
391
+ raise Error.new("Ottertrail: the instance's answer could not be read.", status:)
392
+ end
393
+ stored, too_old, ignored = counts
394
+ Result.new(stored:, too_old:, ignored:)
395
+ end
396
+
397
+ def error_of(response, status)
398
+ answer = parse_answer(response)
399
+ code = answer && answer["error"]
400
+ code = nil unless code.is_a?(String)
401
+ message = answer && answer["message"]
402
+ text = "Ottertrail: the instance answered #{status}"
403
+ text += " #{code}" if code
404
+ text += message.is_a?(String) ? ": #{message}" : "."
405
+ Error.new(text, status:, code:)
406
+ end
407
+
408
+ def parse_answer(response)
409
+ return nil unless response["content-type"].to_s.downcase.start_with?("application/json")
410
+
411
+ answer = JSON.parse(response.body.to_s)
412
+ answer.is_a?(Hash) ? answer : nil
413
+ rescue JSON::ParserError
414
+ nil
415
+ end
416
+ end
417
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Ottertrail
4
- VERSION = "0.1.0"
4
+ VERSION = "0.2.0"
5
5
  end
data/lib/ottertrail.rb CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "openssl"
4
4
 
5
+ require_relative "ottertrail/track"
5
6
  require_relative "ottertrail/version"
6
7
 
7
8
  # The Ruby SDK for Ottertrail.
@@ -32,7 +33,7 @@ module Ottertrail
32
33
  # @raise [ArgumentError] If the ID or the key is not valid.
33
34
  def sign_user_id(user_id, secret_key = nil)
34
35
  id = clean_user_id(user_id)
35
- key = clean_secret_key(secret_key.nil? ? ENV[SECRET_KEY_VARIABLE] : secret_key)
36
+ key = clean_secret_key(secret_key.nil? ? ENV[SECRET_KEY_VARIABLE] : secret_key, "sign_user_id")
36
37
  OpenSSL::HMAC.hexdigest("SHA256", key, id).force_encoding(Encoding::UTF_8)
37
38
  end
38
39
 
@@ -40,7 +41,7 @@ module Ottertrail
40
41
 
41
42
  def clean_user_id(user_id)
42
43
  text = case user_id
43
- when String then utf8(user_id)
44
+ when String then utf8(user_id, "the user ID")
44
45
  when Integer
45
46
  unless user_id.between?(-MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)
46
47
  raise ArgumentError,
@@ -52,7 +53,7 @@ module Ottertrail
52
53
  end
53
54
  # The tracker trims the ID before it sends it, so the trimmed text is what the instance checks.
54
55
  id = js_trim(text)
55
- if id.empty? || utf16_length(id) > MAX_USER_ID
56
+ if id.empty? || utf16_length(id, MAX_USER_ID) > MAX_USER_ID
56
57
  raise ArgumentError,
57
58
  "Ottertrail: the user ID must be 1 to #{MAX_USER_ID} characters after trimming."
58
59
  end
@@ -63,13 +64,14 @@ module Ottertrail
63
64
  id
64
65
  end
65
66
 
66
- def utf8(text)
67
+ # what: the text's name in the message, such as "the user ID".
68
+ def utf8(text, what)
67
69
  converted = (text.encoding == Encoding::UTF_8) ? text : text.encode(Encoding::UTF_8)
68
70
  return converted if converted.valid_encoding?
69
71
 
70
- raise ArgumentError, "Ottertrail: the user ID must be valid UTF-8."
72
+ raise ArgumentError, "Ottertrail: #{what} must be valid UTF-8."
71
73
  rescue EncodingError
72
- raise ArgumentError, "Ottertrail: the user ID must be valid UTF-8."
74
+ raise ArgumentError, "Ottertrail: #{what} must be valid UTF-8."
73
75
  end
74
76
 
75
77
  # Searches for the first and the last other character, which takes linear time on any input.
@@ -80,18 +82,19 @@ module Ottertrail
80
82
  text[first..text.rindex(NOT_JS_WHITESPACE)] || ""
81
83
  end
82
84
 
83
- # JavaScript's length: a character above U+FFFF counts 2.
84
- def utf16_length(text)
85
- return text.length if text.length > MAX_USER_ID
85
+ # JavaScript's length: a character above U+FFFF counts 2. Any length above the limit is enough
86
+ # to refuse the text, so a long text is not converted.
87
+ def utf16_length(text, limit)
88
+ return text.length if text.length > limit
86
89
 
87
90
  text.encode(Encoding::UTF_16LE).bytesize / 2
88
91
  end
89
92
 
90
93
  # The messages never include the value: it is a secret.
91
- def clean_secret_key(secret_key)
94
+ def clean_secret_key(secret_key, method)
92
95
  if secret_key.nil? || secret_key == ""
93
96
  raise ArgumentError,
94
- "Ottertrail: no secret key. Pass it to Ottertrail.sign_user_id, or set OTTERTRAIL_SECRET_KEY."
97
+ "Ottertrail: no secret key. Pass it to Ottertrail.#{method}, or set OTTERTRAIL_SECRET_KEY."
95
98
  end
96
99
  raise TypeError, "Ottertrail: the secret key must be a string." unless secret_key.is_a?(String)
97
100
  # ascii_only? is false for bytes that are not valid, so the match never raises an error that
data/sig/ottertrail.rbs CHANGED
@@ -1,9 +1,51 @@
1
1
  module Ottertrail
2
2
  VERSION: String
3
3
 
4
+ type property_value = String | Integer | Float | bool | nil
5
+
6
+ type event = {
7
+ name: String,
8
+ user_id: String | Integer,
9
+ ?properties: Hash[String | Symbol, property_value]?,
10
+ ?path: String?,
11
+ ?occurred_at: Time | Integer | nil,
12
+ ?id: String?
13
+ }
14
+
4
15
  # Signs the ID of a signed-in user, so that Ottertrail can trust it.
5
16
  def self.sign_user_id: (String | Integer user_id, ?String? secret_key) -> String
6
17
 
18
+ # Sends events of signed-in users from your server, and waits for the instance's answer.
19
+ def self.track: (
20
+ event | Array[event] events,
21
+ ?host: String?,
22
+ ?secret_key: String?,
23
+ ?environment: String?,
24
+ ?release: String?,
25
+ ?timeout: Numeric
26
+ ) -> Result
27
+
28
+ # Raised by Ottertrail.track when the instance refused the events, or every try failed.
29
+ class Error < StandardError
30
+ attr_reader status: Integer?
31
+ attr_reader code: String?
32
+
33
+ def initialize: (String message, ?status: Integer?, ?code: String?) -> void
34
+ end
35
+
36
+ # What the instance did with the events that Ottertrail.track sent.
37
+ class Result < Data
38
+ attr_reader stored: Integer
39
+ attr_reader too_old: Integer
40
+ attr_reader ignored: Integer
41
+
42
+ def self.new: (stored: Integer, too_old: Integer, ignored: Integer) -> Result
43
+ | (Integer stored, Integer too_old, Integer ignored) -> Result
44
+
45
+ def with: (?stored: Integer, ?too_old: Integer, ?ignored: Integer) -> Result
46
+ def to_h: () -> { stored: Integer, too_old: Integer, ignored: Integer }
47
+ end
48
+
7
49
  # Private: what the type check of lib/ needs.
8
50
 
9
51
  SECRET_KEY_VARIABLE: String
@@ -12,10 +54,57 @@ module Ottertrail
12
54
  MAX_SAFE_INTEGER: Integer
13
55
  NOT_JS_WHITESPACE: Regexp
14
56
  CONTROL_OR_SURROGATE: Regexp
57
+ HOST_VARIABLE: String
58
+ EVENTS_PATH: String
59
+ MAX_EVENTS: Integer
60
+ MAX_EVENT_NAME: Integer
61
+ MAX_PATH: Integer
62
+ MAX_PROPERTIES: Integer
63
+ MAX_PROPERTY_NAME: Integer
64
+ MAX_PROPERTY_TEXT: Integer
65
+ MAX_PROPERTIES_BYTES: Integer
66
+ MAX_MOMENT: Integer
67
+ RESERVED_NAMES: Array[String]
68
+ EVENT_KEYS: Array[Symbol]
69
+ UUID: Regexp
70
+ ENVIRONMENT: Regexp
71
+ RELEASE: Regexp
72
+ LOCAL_HOSTS: Array[String]
73
+ DEFAULT_TIMEOUT: Integer
74
+ MAX_ATTEMPTS: Integer
75
+ RETRY_WAITS: Array[Integer]
76
+ MAX_RETRY_AFTER: Integer
77
+ RETRY_STATUSES: Array[Integer]
78
+ NETWORK_ERRORS: Array[singleton(Exception)]
15
79
 
16
80
  private def self.clean_user_id: (untyped user_id) -> String
17
- private def self.utf8: (String text) -> String
81
+ private def self.utf8: (String text, String what) -> String
18
82
  private def self.js_trim: (String text) -> String
19
- private def self.utf16_length: (String text) -> Integer
20
- private def self.clean_secret_key: (untyped secret_key) -> String
83
+ private def self.utf16_length: (String text, Integer limit) -> Integer
84
+ private def self.clean_secret_key: (untyped secret_key, String method) -> String
85
+ private def self.clean_events: (untyped events) -> Array[Hash[Symbol, untyped]]
86
+ private def self.clean_event: (untyped event, Integer now) -> Hash[Symbol, untyped]
87
+ private def self.check_event_keys: (Hash[untyped, untyped] event) -> void
88
+ private def self.clean_id: (untyped id) -> String
89
+ private def self.clean_name: (untyped name) -> String
90
+ private def self.clean_occurred_at: (untyped occurred_at, Integer now) -> Integer
91
+ private def self.epoch_ms: (Time time) -> Integer
92
+ private def self.clean_path: (untyped path) -> String
93
+ private def self.clean_properties: (untyped properties) -> Hash[String, property_value]
94
+ private def self.clean_property_name: (untyped name) -> String
95
+ private def self.clean_property_value: (untyped value) -> property_value
96
+ private def self.clean_property_text: (String value) -> String
97
+ private def self.clean_environment: (untyped environment) -> String
98
+ private def self.clean_release: (untyped release) -> String
99
+ private def self.clean_timeout: (untyped timeout) -> Float
100
+ private def self.clean_host: (untyped host) -> URI::HTTP
101
+ private def self.parse_host: (String host) -> URI::Generic?
102
+ private def self.host_problem: (String text, URI::Generic uri) -> String?
103
+ private def self.send_events: (URI::HTTP uri, String key, String body, Float timeout) -> Result
104
+ private def self.post: (URI::HTTP uri, String key, String body, Float timeout) -> Net::HTTPResponse
105
+ private def self.retry_after: (String? value) -> Integer?
106
+ private def self.pause: (Integer seconds) -> void
107
+ private def self.read_result: (Net::HTTPResponse response, Integer status) -> Result
108
+ private def self.error_of: (Net::HTTPResponse response, Integer status) -> Error
109
+ private def self.parse_answer: (Net::HTTPResponse response) -> Hash[String, untyped]?
21
110
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ottertrail
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - The Ottertrail authors
@@ -10,7 +10,8 @@ cert_chain: []
10
10
  date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies: []
12
12
  description: Signs the IDs of signed-in users with a project's secret key, so that
13
- Ottertrail can trust the user IDs that a site's tracker sends.
13
+ Ottertrail can trust the user IDs that a site's tracker sends, and sends events
14
+ of signed-in users from your server.
14
15
  executables: []
15
16
  extensions: []
16
17
  extra_rdoc_files: []
@@ -18,6 +19,7 @@ files:
18
19
  - LICENSE
19
20
  - README.md
20
21
  - lib/ottertrail.rb
22
+ - lib/ottertrail/track.rb
21
23
  - lib/ottertrail/version.rb
22
24
  - sig/ottertrail.rbs
23
25
  homepage: https://github.com/ottertrail/ottertrail-ruby
@@ -47,5 +49,5 @@ required_rubygems_version: !ruby/object:Gem::Requirement
47
49
  requirements: []
48
50
  rubygems_version: 4.0.20
49
51
  specification_version: 4
50
- summary: 'Ruby SDK for Ottertrail: sign user IDs on your server.'
52
+ summary: 'Ruby SDK for Ottertrail: sign user IDs and send events from your server.'
51
53
  test_files: []