airdun 0.1.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 364d4eb31785cecb287ca56f072abcc847834ef0448e0baa826700471abc2737
4
+ data.tar.gz: 3372b5a3e081f67f26bc4103a11d5194ea695bfc5eaf55db57af96f300f6694b
5
+ SHA512:
6
+ metadata.gz: 430f28858e1ff4fd84f0d62d383ef5046b18fe5cc91d72f1f1cdf2c7251e3270df8e5e19ebbd9a2ebfdc25a72e3a370378edb087780eff362b985e4bb6beef42
7
+ data.tar.gz: 251d227a3ec8b0cb129493362ae23f9a5d35b166812e262d01a20b282278671880c42b1c42db43006fcbda0edad18c14717a9d26b3194f4bb49feb48eab4434b
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ First version. `identify`, `track` and `batch` against the Airdun server API, direct sending (no queue, no thread), automatic idempotency keys for events, retries on network errors, timeouts, 429 and 5xx, typed errors, no runtime dependency. `identify`, `track` and `batch` items accept `subscriptions` (`email`, `sms`, `whatsapp`: `subscribed` | `unsubscribed`) and the result reports what became of each (`applied`, `ignored_older`, `no_address`). Same behaviour as the Node SDK 0.1.0.
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Airdun
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,254 @@
1
+ # airdun
2
+
3
+ The official Ruby server SDK for Airdun. Send your contacts and your events from your backend.
4
+
5
+ - Ruby 2.7 or newer. No runtime dependency (`net/http`, `json`, `securerandom`, `uri`, `time`).
6
+ - Server only. The API key is a secret: never put it in a mobile app or any code your users can read.
7
+ - One client is safe to share across threads.
8
+
9
+ ## Install
10
+
11
+ ```ruby
12
+ # Gemfile
13
+ gem 'airdun'
14
+ ```
15
+
16
+ or `gem install airdun`.
17
+
18
+ ## Quick start
19
+
20
+ ```ruby
21
+ require 'airdun'
22
+
23
+ airdun = Airdun::Client.new(ENV.fetch('AIRDUN_API_KEY'))
24
+
25
+ # Create or update a contact.
26
+ airdun.identify(
27
+ user_id: 'user_123',
28
+ email: 'ada@example.com',
29
+ properties: { first_name: 'Ada', plan: 'pro' }
30
+ )
31
+
32
+ # Record an event.
33
+ airdun.track(event: 'project_created', user_id: 'user_123', properties: { template: 'blank' })
34
+ ```
35
+
36
+ Create a key in Airdun, Settings, API keys. It is shown once. Keep it in an environment variable or your secret manager.
37
+
38
+ ## The three calls
39
+
40
+ Every call is sent at once and answered when Airdun has stored the data. There is no queue, no thread and no timer, so there is nothing to flush when a process stops.
41
+
42
+ Arguments are Ruby keywords in snake_case (or one Hash: `airdun.track({ event: 'x', user_id: 'u' })`) (`user_id`, `contact_properties`, `idempotency_key`); hash keys may be Symbols or Strings. Results are plain Hashes with snake_case Symbol keys (`contact_id`, `changed_keys`, `event_id`). Values in a result stay as the API wrote them (strings such as `'applied'`).
43
+
44
+ ### `identify`: create or update a contact
45
+
46
+ Airdun finds the contact by `user_id`, then by `email`, and creates it when neither matches. At least one of the two is required.
47
+
48
+ ```ruby
49
+ result = airdun.identify(
50
+ user_id: 'user_123',
51
+ email: 'ada@example.com',
52
+ properties: { plan: 'pro', trial_ends: nil }, # nil clears a property
53
+ subscriptions: { email: :subscribed }, # optional, see below
54
+ timestamp: Time.now # optional: when the data was true
55
+ )
56
+ result[:contact_id] # => "..."
57
+ result[:created] # => true when this call created the contact
58
+ result[:changed_keys] # => ["plan"]
59
+ result[:ignored_properties] # => [{ key: 'loyalty', code: 'PROPERTY_UNKNOWN' }]
60
+ ```
61
+
62
+ Properties are not created by the API. A key Airdun does not know is skipped and listed in `ignored_properties` (`PROPERTY_UNKNOWN`), the call still succeeds, and the key shows up in Airdun as "received but not created". A known property whose value has the wrong type refuses the whole call. Property values are strings, numbers, booleans or `nil`. `Time`, `Date` and `DateTime` values are sent as ISO 8601 in UTC.
63
+
64
+ `user_id` may be a String or an Integer (an Integer is sent as text).
65
+
66
+ ### `track`: record an event
67
+
68
+ ```ruby
69
+ result = airdun.track(
70
+ event: 'order_placed', # lowercase letters, digits, underscore; max 64 characters
71
+ email: 'ada@example.com', # or user_id
72
+ properties: { order_id: 'A-1042', total: 49.9 }, # the event's own fields, 8 KB max
73
+ contact_properties: { plan: 'pro' }, # contact properties, handled like identify
74
+ timestamp: Time.now, # optional
75
+ idempotency_key: 'order-A-1042' # optional
76
+ )
77
+ result[:event_id]
78
+ result[:replayed] # true when the idempotency key was already used
79
+ ```
80
+
81
+ The contact is created when it does not exist. Send identifiers such as an order id as text, not as numbers. The result also carries everything `identify` returns.
82
+
83
+ ### `batch`: up to 100 items in one call
84
+
85
+ ```ruby
86
+ result = airdun.batch([
87
+ { type: :identify, user_id: 'u1', properties: { plan: 'pro' } },
88
+ { type: :track, user_id: 'u1', event: 'project_created' }
89
+ ])
90
+
91
+ result[:results].each do |item|
92
+ if item[:ok]
93
+ puts "#{item[:index]} #{item[:type]} #{item[:contact_id]}"
94
+ else
95
+ warn "#{item[:index]} #{item[:error][:code]}"
96
+ end
97
+ end
98
+ ```
99
+
100
+ An item takes the same keywords as `identify` or `track`, plus `type: :identify` or `type: :track`. Each item runs on its own: one that fails does not stop the others. `batch` raises only when the whole call is refused (bad key, rate limit, body too large). Read `results` for the rest. A batch of N items counts as N requests against the rate limit. An unknown key in an item (a typo) raises `Airdun::InvalidArgumentError` before anything is sent; the message names the key and the item's index (the Node SDK ignores such a key).
101
+
102
+ ## Marketing subscriptions
103
+
104
+ `identify`, `track` and batch items can state whether a contact accepts marketing messages, per channel:
105
+
106
+ ```ruby
107
+ r = airdun.identify(email: 'ada@example.com', subscriptions: { email: :subscribed, sms: :unsubscribed })
108
+ r[:subscriptions] # => { email: 'applied', sms: 'no_address' }
109
+ ```
110
+
111
+ The statement applies to the contact's address on that channel (its email for `email`, its phone number for `sms` and `whatsapp`) after the call's own contact write. It is dated by the call's `timestamp` (never later than now). A channel you leave out is left as it is.
112
+
113
+ `subscriptions` in the result is present only when you stated something:
114
+
115
+ - `applied`: recorded.
116
+ - `ignored_older`: the address already has a later statement, so yours was not applied. A backend cannot override a customer's own unsubscribe with an older statement.
117
+ - `no_address`: the contact has no address on that channel. Not an error.
118
+
119
+ Consent is your responsibility. Airdun records what you state and always honours an unsubscribe. A replayed `track` applies nothing again and answers without `subscriptions`.
120
+
121
+ ## Idempotency
122
+
123
+ `track` always sends an idempotency key: yours, or a random UUID made when you call. Every retry of that call reuses it, so a lost answer followed by a retry records the event once. When Airdun has already seen the key, nothing is written and the result has `replayed: true` with the first event's `event_id`.
124
+
125
+ Use your own key when the same event can reach you twice (a webhook delivered again, a job retried): `idempotency_key: 'order-A-1042'`. In a batch, each `track` item gets its own key unless it brings one. A key is a String of 1 to 128 letters, digits and `_ . : -`; anything else raises `Airdun::InvalidArgumentError` before sending. The same key with another event name is refused (`SERVER_API.IDEMPOTENCY_KEY_REUSED`).
126
+
127
+ `identify`, `track` and every batch item are stamped with the time of the call when you give no `timestamp`, so a late retry never overwrites fresher data.
128
+
129
+ ## Errors
130
+
131
+ Everything the SDK raises is an `Airdun::Error` (`code`, `status`, `message`, `details`, `retry_after_seconds`).
132
+
133
+ | Class | When |
134
+ |---|---|
135
+ | `Airdun::ApiError` | Airdun answered and refused (or answered something that is not its JSON). Subclasses by status: `AuthenticationError` (401), `PermissionError` (403), `ConflictError` (409), `RateLimitError` (429), `ValidationError` (400, 413, 415, 422), `ServerError` (5xx). |
136
+ | `Airdun::ConnectionError` | No answer: network error, after the retries. `attempts`, `timed_out?`, `cause`. `Airdun::TimeoutError` is the subclass raised on a timeout. |
137
+ | `Airdun::InvalidArgumentError` | The SDK refused the call before sending it (`status` is 0). |
138
+
139
+ ```ruby
140
+ begin
141
+ airdun.identify(email: 'ada@example.com')
142
+ rescue Airdun::ApiError => e
143
+ e.code # 'SERVER_API.CONTACT_CONFLICT'
144
+ e.status # 409
145
+ e.details # { reason: 'USER_ID_TAKEN', ... } (snake_case Symbol keys)
146
+ e.retry_after_seconds # set on a 429
147
+ rescue Airdun::ConnectionError => e
148
+ e.timed_out?
149
+ end
150
+ ```
151
+
152
+ Read `code` and `details`, never the message text. The codes are the API's `SERVER_API.*` codes (`KEY_INVALID`, `KEY_REVOKED`, `RATE_LIMITED`, `VALIDATION_FAILED`, `CONTACT_CONFLICT`, `PROPERTY_INVALID_VALUE`, `EVENT_NAME_INVALID`, ...); the table is `Airdun::SERVER_API_ERROR_STATUS`. Refusals raised by the SDK have `status` 0 and a `SDK.*` code: `SDK.INVALID_ARGUMENT`, `SDK.BATCH_TOO_LARGE`, `SDK.BODY_TOO_LARGE`. `SDK.UNEXPECTED_RESPONSE` means Airdun answered something that is not its JSON (a proxy page, for example), `SDK.REDIRECTED` that the base URL redirected.
153
+
154
+ ## Retries
155
+
156
+ The SDK retries a call on: a network error, a timeout, a 429 and any 5xx (503 included). It never retries any other 4xx: a 400, 401, 403, 409, 413 or 422 would answer the same again. A redirect is never followed (the key must not travel elsewhere) nor retried.
157
+
158
+ - Backoff is exponential with jitter, starting near 250 to 500 ms and capped at 8 s per wait.
159
+ - `Retry-After` (seconds or an HTTP date) is honoured on a 429 and a 503.
160
+ - `max_retries` defaults to 3 (four tries at most). The retries of one call spend at most `max_retry_wait` seconds waiting (default 30); a `Retry-After` longer than what is left is not waited for and the error is raised at once, with `retry_after_seconds`.
161
+ - Each try has its own `timeout` (default 30 seconds) for the WHOLE try: connecting, sending and reading the answer are checked against one deadline, so a server that sends its answer a few bytes at a time cannot hold a call longer.
162
+ - A TLS or certificate error is never retried: it raises `ConnectionError` at once. Connection resets and refused connections are retried.
163
+ - `Retry-After` is read as a number of seconds or an HTTP date; any other value is ignored.
164
+
165
+ ## Options
166
+
167
+ ```ruby
168
+ Airdun::Client.new(
169
+ api_key, # or api_key: ...
170
+ base_url: 'https://api.airdun.com/v1', # default
171
+ timeout: 30, # seconds, for the whole of one try
172
+ max_retries: 3, # 0 turns retries off, 10 at most
173
+ max_retry_wait: 30, # seconds spent waiting across the retries of one call
174
+ logger: Rails.logger # optional: anything with #debug and #warn
175
+ )
176
+ ```
177
+
178
+ `base_url` must be https (http is accepted for localhost). The logger sees `adn_sk_live_` or `adn_sk_test_` at most, never a secret character of the key, never the Authorization header, and no payload value. `inspect`, `to_s`, `to_yaml` and `as_json` of a client show the same prefix; no instance variable holds the key, and a client cannot be marshalled.
179
+
180
+ ## Rails
181
+
182
+ Build ONE client at boot.
183
+
184
+ ```ruby
185
+ # config/initializers/airdun.rb
186
+ AIRDUN = Airdun::Client.new(ENV.fetch('AIRDUN_API_KEY'), logger: Rails.logger)
187
+ ```
188
+
189
+ From a controller:
190
+
191
+ ```ruby
192
+ class ProjectsController < ApplicationController
193
+ def create
194
+ project = current_user.projects.create!(project_params)
195
+ AIRDUN.track(event: 'project_created', user_id: current_user.id,
196
+ properties: { project_id: project.id.to_s })
197
+ redirect_to project
198
+ rescue Airdun::Error => e
199
+ Rails.logger.warn("airdun: #{e.code}")
200
+ redirect_to project
201
+ end
202
+ end
203
+ ```
204
+
205
+ A call waits for Airdun (up to the retries). Do not make a user wait for it: from a request, prefer a job.
206
+
207
+ From an ActiveJob (or Sidekiq) job, generate the idempotency key BEFORE enqueueing, so that a retry of the job reuses it and the event is counted once:
208
+
209
+ ```ruby
210
+ class TrackEventJob < ApplicationJob
211
+ retry_on Airdun::ConnectionError, Airdun::ServerError, Airdun::RateLimitError, wait: :polynomially_longer, attempts: 8
212
+
213
+ def perform(event, user_id, properties, idempotency_key, occurred_at)
214
+ AIRDUN.track(event: event, user_id: user_id, properties: properties,
215
+ idempotency_key: idempotency_key, timestamp: Time.iso8601(occurred_at))
216
+ end
217
+ end
218
+
219
+ # where the thing happens (arguments must be JSON-friendly: pass the time as a string)
220
+ TrackEventJob.perform_later('project_created', current_user.id, { project_id: project.id.to_s },
221
+ SecureRandom.uuid, Time.current.iso8601(3))
222
+ ```
223
+
224
+ The `timestamp` is also made at enqueue time, so a job that runs late still dates the event when it happened. For a Sidekiq worker the same applies: build the key and the time where the event happens, pass them as arguments.
225
+
226
+ ## Thread safety
227
+
228
+ A client holds nothing that changes after it is built (it is frozen), and each request opens its own connection. One client can serve every thread of a Puma or Sidekiq process. The SDK keeps no global state and starts no thread.
229
+
230
+ ## Limits
231
+
232
+ | What | Limit |
233
+ |---|---|
234
+ | Items in a batch | 100 |
235
+ | Body of one call | 512 KB |
236
+ | Properties per call | 100 |
237
+ | Event payload | 8 KB |
238
+ | Event names per workspace | 200 |
239
+ | Requests per key | 600 a minute (a batch of N costs N) |
240
+ | A `timestamp` in the future | 24 hours at most |
241
+
242
+ The SDK refuses a batch of more than 100 items and a body over 512 KB (counted in bytes) before any network call, and refuses `NaN` and `Infinity`. The limits are exported: `Airdun::MAX_BATCH_ITEMS`, `Airdun::MAX_BODY_BYTES`.
243
+
244
+ ## Test and live keys
245
+
246
+ `adn_sk_live_...` works on a live workspace, `adn_sk_test_...` on a workspace connected to a Stripe sandbox. A key whose mode no longer matches its workspace is refused (`SERVER_API.KEY_MODE_MISMATCH`). Revoke a key in Settings, API keys: calls stop at once.
247
+
248
+ ## Supported Ruby versions
249
+
250
+ Ruby 2.7 and newer.
251
+
252
+ ## License
253
+
254
+ MIT. See the LICENSE file.
@@ -0,0 +1,354 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'net/http'
5
+ require 'securerandom'
6
+ require 'time'
7
+ require 'timeout'
8
+ require 'uri'
9
+
10
+ module Airdun
11
+ # The Airdun server client. Every call is sent at once and answered when Airdun has the data: no queue, no thread,
12
+ # no timer left behind, so it is safe in a job or a serverless function. The key is a SECRET: never use it in a
13
+ # browser or an app your users run.
14
+ #
15
+ # A client holds no state that changes after construction (it is frozen), and every request opens its own
16
+ # connection: share ONE client across threads (Puma, Sidekiq) freely.
17
+ class Client
18
+ OPTION_KEYS = %i[base_url timeout max_retries max_retry_wait logger sleeper random now].freeze
19
+ BACKOFF_BASE_SECONDS = 0.5
20
+ BACKOFF_MAX_SECONDS = 8.0
21
+
22
+ # Result of one try: an HTTP answer, or the exception that kept it from coming.
23
+ Attempt = Struct.new(:status, :retry_after_header, :text, :error, :timed_out, :tls)
24
+
25
+ # `Airdun::Client.new(api_key, base_url:, timeout:, max_retries:, max_retry_wait:, logger:)`; the key can also be
26
+ # given as `api_key:`. `sleeper:`, `random:` and `now:` (callables) exist for tests.
27
+ def initialize(api_key = nil, **options)
28
+ api_key = options.delete(:api_key) if api_key.nil? && options.key?(:api_key)
29
+ unknown = options.keys - OPTION_KEYS
30
+ raise invalid("Unknown option: #{unknown.join(', ')}.") unless unknown.empty?
31
+
32
+ if api_key.nil? || (api_key.is_a?(String) && api_key.strip.empty?)
33
+ raise invalid('An Airdun API key is required: Airdun::Client.new(api_key). Create one in Settings, API keys.')
34
+ end
35
+ raise invalid('That is not an Airdun secret key. It starts with adn_sk_live_ or adn_sk_test_.') unless api_key.is_a?(String) && KEY_PATTERN.match?(api_key)
36
+
37
+ secret = api_key.dup.freeze
38
+ # The key lives in this closure only: no instance variable holds it, so a dump of the instance (YAML, JSON,
39
+ # an error tracker reading ivars) never reaches it.
40
+ @secret = -> { secret }
41
+ @visible = secret[0, VISIBLE_PREFIX_CHARS].freeze
42
+ @base_url = normalize_base_url(options.fetch(:base_url, DEFAULT_BASE_URL))
43
+ @timeout = positive(options.fetch(:timeout, DEFAULT_TIMEOUT), 'timeout')
44
+ @max_retries = retry_count(options.fetch(:max_retries, DEFAULT_MAX_RETRIES))
45
+ @max_retry_wait = non_negative(options.fetch(:max_retry_wait, DEFAULT_MAX_RETRY_WAIT), 'max_retry_wait')
46
+ @logger = options[:logger]
47
+ @sleeper = options[:sleeper] || Kernel.method(:sleep)
48
+ @random = options[:random] || Random.method(:rand)
49
+ @now = options[:now] || Time.method(:now)
50
+ freeze
51
+ end
52
+
53
+ # Never prints the key.
54
+ def inspect
55
+ "#<#{self.class.name} base_url=#{@base_url.inspect} key=\"#{visible_key}...\">"
56
+ end
57
+ alias to_s inspect
58
+
59
+ # Serialisers (Psych, ActiveSupport, JSON) see the address and the key's mode prefix only.
60
+ def encode_with(coder)
61
+ coder['base_url'] = @base_url
62
+ coder['key'] = "#{visible_key}..."
63
+ end
64
+
65
+ def as_json(*)
66
+ { 'base_url' => @base_url, 'key' => "#{visible_key}..." }
67
+ end
68
+
69
+ def to_json(*args)
70
+ as_json.to_json(*args)
71
+ end
72
+
73
+ def instance_variables
74
+ []
75
+ end
76
+
77
+ # A client is never serialised: the key would travel with it.
78
+ def marshal_dump
79
+ raise TypeError, 'An Airdun::Client holds a secret key and cannot be marshalled.'
80
+ end
81
+
82
+ # Arguments are keywords, or one Hash (`identify({ user_id: 'u' })`), or both.
83
+ #
84
+ # Create or update a contact. Safe to retry: the call is stamped with the moment it was made, and an older write
85
+ # never overwrites fresher data. At least one of `user_id`, `email`.
86
+ #
87
+ # Returns a Hash with snake_case Symbol keys: `contact_id`, `created`, `changed_keys`, `ignored_properties`,
88
+ # and `subscriptions` when the call stated some.
89
+ def identify(params = nil, **keywords)
90
+ args = Wire.arguments(params, keywords, Wire::IDENTIFY_ARGS)
91
+ post('identify', Wire.identify_body(now: @now.call, **args))
92
+ end
93
+
94
+ # Record one event on a contact (created when unknown). Sent with an idempotency key (yours, or a UUID made
95
+ # here, at call time) that every retry reuses, so the event is counted once. Returns what `identify` returns
96
+ # plus `event_id` and `replayed`.
97
+ def track(params = nil, **keywords)
98
+ args = Wire.arguments(params, keywords, Wire::TRACK_ARGS)
99
+ post('track', Wire.track_body(now: @now.call, **args))
100
+ end
101
+
102
+ # Up to 100 identify / track items in one call. Each item is a Hash with `type: :identify` or `type: :track`
103
+ # and that call's arguments. Each item succeeds or fails alone: read `results`. Each track item gets its own
104
+ # idempotency key unless it brings one. The call raises only when the batch as a whole was refused (a bad key,
105
+ # the rate limit, a body over 512 KB). Returns `{ results:, succeeded:, failed: }`.
106
+ def batch(items)
107
+ raise invalid("batch needs an Array of 1 to #{MAX_BATCH_ITEMS} items.") unless items.is_a?(Array) && !items.empty?
108
+
109
+ if items.length > MAX_BATCH_ITEMS
110
+ raise InvalidArgumentError.new(
111
+ "A batch holds at most #{MAX_BATCH_ITEMS} items, got #{items.length}. Split it.",
112
+ code: 'SDK.BATCH_TOO_LARGE', status: 0, details: { max: MAX_BATCH_ITEMS, received: items.length }
113
+ )
114
+ end
115
+ now = @now.call
116
+ post('batch', { 'items' => items.each_with_index.map { |item, index| Wire.batch_item(item, now, index) } })
117
+ end
118
+
119
+ private
120
+
121
+ def invalid(message)
122
+ Wire.invalid(message)
123
+ end
124
+
125
+ def visible_key
126
+ @visible
127
+ end
128
+
129
+ # ─── transport ──────────────────────────────────────────────────────────────────────────────────────────────
130
+
131
+ def post(route, body)
132
+ payload = begin
133
+ JSON.generate(body)
134
+ rescue JSON::JSONError
135
+ raise invalid('The call holds a value that cannot be sent as JSON (nested too deep, for example).')
136
+ end
137
+ bytes = payload.bytesize
138
+ if bytes > MAX_BODY_BYTES
139
+ raise InvalidArgumentError.new(
140
+ "The body is #{bytes} bytes, the limit is #{MAX_BODY_BYTES}. Send less per call.",
141
+ code: 'SDK.BODY_TOO_LARGE', status: 0, details: { max: MAX_BODY_BYTES, bytes: bytes }
142
+ )
143
+ end
144
+
145
+ attempts = 0
146
+ waited = 0.0
147
+ loop do
148
+ attempts += 1
149
+ log_debug("POST /#{route} attempt #{attempts} key #{visible_key}...")
150
+ last = attempt(route, payload)
151
+ failure = last.error ? connection_error(last, attempts) : nil
152
+ return parse_success(last) if failure.nil? && last.status >= 200 && last.status < 300
153
+
154
+ api_error = failure.nil? ? api_error_for(last) : nil
155
+ retryable = failure.nil? ? (last.status == 429 || last.status >= 500) : !last.tls
156
+ if retryable && attempts <= @max_retries
157
+ delay = delay_for(attempts, api_error&.retry_after_seconds)
158
+ if waited + delay <= @max_retry_wait
159
+ waited += delay
160
+ log_warn("Airdun call to /#{route} #{failure ? (failure.timed_out? ? 'timed out' : 'failed (network)') : "answered #{last.status}"}, " \
161
+ "retrying in #{(delay * 1000).round} ms (retry #{attempts} of #{@max_retries}).")
162
+ @sleeper.call(delay)
163
+ next
164
+ end
165
+ end
166
+ raise failure, cause: last.error if failure
167
+
168
+ raise api_error
169
+ end
170
+ end
171
+
172
+ # One try, bounded by a monotonic deadline of `timeout` seconds in all: connecting and writing get the budget,
173
+ # and the answer is read in chunks, each checked against what is left (so a server dripping bytes cannot hold a
174
+ # call past it). No Timeout.timeout, no extra thread. The one thing it cannot cut is a server dripping the
175
+ # response HEADERS one byte at a time (each read still has the remaining budget).
176
+ def attempt(route, payload)
177
+ deadline = monotonic + @timeout
178
+ uri = URI.parse("#{@base_url}/#{route}")
179
+ http = Net::HTTP.new(uri.hostname, uri.port)
180
+ http.use_ssl = uri.scheme == 'https'
181
+ http.open_timeout = @timeout
182
+ http.write_timeout = @timeout
183
+ http.read_timeout = @timeout
184
+ http.max_retries = 0
185
+ request = Net::HTTP::Post.new(uri.request_uri)
186
+ request['Authorization'] = "Bearer #{@secret.call}"
187
+ request['Content-Type'] = 'application/json'
188
+ request['Accept'] = 'application/json'
189
+ request['User-Agent'] = "airdun-ruby/#{VERSION}"
190
+ request.body = payload
191
+ http.start do |connection|
192
+ connection.request(request) do |response|
193
+ text = +''
194
+ check_deadline(deadline)
195
+ response.read_body do |chunk|
196
+ text << chunk
197
+ check_deadline(deadline)
198
+ connection.read_timeout = remaining(deadline)
199
+ end
200
+ return Attempt.new(response.code.to_i, response['retry-after'], text.force_encoding(Encoding::UTF_8), nil, false, false)
201
+ end
202
+ end
203
+ rescue Timeout::Error => e
204
+ Attempt.new(0, nil, '', e, true, false)
205
+ rescue StandardError => e
206
+ Attempt.new(0, nil, '', e, false, tls_error?(e))
207
+ end
208
+
209
+ def monotonic
210
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
211
+ end
212
+
213
+ def remaining(deadline)
214
+ [deadline - monotonic, 0.001].max
215
+ end
216
+
217
+ def check_deadline(deadline)
218
+ raise Timeout::Error, 'deadline' if monotonic >= deadline
219
+ end
220
+
221
+ # A TLS or certificate failure answers the same again: never retried.
222
+ def tls_error?(error)
223
+ defined?(OpenSSL::SSL::SSLError) && error.is_a?(OpenSSL::SSL::SSLError)
224
+ end
225
+
226
+ def connection_error(last, attempts)
227
+ klass = last.timed_out ? TimeoutError : ConnectionError
228
+ message = if last.timed_out
229
+ "The call to Airdun timed out after #{@timeout} seconds."
230
+ elsif last.tls
231
+ 'The TLS connection to Airdun failed (certificate or protocol error); it is not retried.'
232
+ else
233
+ 'The call to Airdun failed before an answer came back (network error).'
234
+ end
235
+ klass.new(message, timed_out: last.timed_out, attempts: attempts)
236
+ end
237
+
238
+ # The wait before the next try, in seconds: `Retry-After` when the API gave one, else jittered exponential.
239
+ def delay_for(attempt, retry_after_seconds)
240
+ return retry_after_seconds.to_f unless retry_after_seconds.nil?
241
+
242
+ ceiling = [BACKOFF_MAX_SECONDS, BACKOFF_BASE_SECONDS * (2**(attempt - 1))].min
243
+ (ceiling / 2.0) + (@random.call * ceiling / 2.0)
244
+ end
245
+
246
+ def parse_success(last)
247
+ parsed = JSON.parse(last.text)
248
+ raise JSON::ParserError, 'not an object' unless parsed.is_a?(Hash)
249
+
250
+ Wire.snake(parsed)
251
+ rescue JSON::ParserError
252
+ raise ApiError.new("Airdun answered #{last.status} with a body that is not JSON.", code: 'SDK.UNEXPECTED_RESPONSE', status: last.status)
253
+ end
254
+
255
+ def api_error_for(last)
256
+ status = last.status
257
+ if status >= 300 && status < 400
258
+ return ApiError.new("The base URL redirected (HTTP #{status}). The SDK never follows a redirect, since the key must not travel elsewhere: set base_url to the final address.",
259
+ code: 'SDK.REDIRECTED', status: status)
260
+ end
261
+
262
+ json = begin
263
+ JSON.parse(last.text)
264
+ rescue JSON::ParserError
265
+ nil
266
+ end
267
+ if json.is_a?(Hash) && json['code'].is_a?(String)
268
+ raw_details = json['details'].is_a?(Hash) ? json['details'] : nil
269
+ return ApiError.class_for(status).new(
270
+ json['message'].is_a?(String) ? json['message'] : "Airdun refused the call (#{json['code']}).",
271
+ code: json['code'], status: status, details: Wire.snake(raw_details || {}),
272
+ retry_after_seconds: parse_retry_after(last.retry_after_header, raw_details)
273
+ )
274
+ end
275
+ ApiError.class_for(status).new("Airdun answered #{status} with a body that is not an Airdun error.",
276
+ code: 'SDK.UNEXPECTED_RESPONSE', status: status,
277
+ retry_after_seconds: parse_retry_after(last.retry_after_header, nil))
278
+ end
279
+
280
+ # Seconds, from the header (a number of seconds or an HTTP date), else from the body's `retryAfterSeconds`.
281
+ def parse_retry_after(header, raw_details)
282
+ text = header.to_s.strip
283
+ unless text.empty?
284
+ return text.to_f if text.match?(/\A\d+(\.\d+)?\z/)
285
+
286
+ date = parse_http_date(text)
287
+ return [0, (date - @now.call).ceil].max unless date.nil?
288
+ end
289
+ from_body = raw_details.is_a?(Hash) ? raw_details['retryAfterSeconds'] : nil
290
+ return from_body if from_body.is_a?(Numeric) && from_body.finite? && from_body >= 0
291
+
292
+ nil
293
+ end
294
+
295
+ def parse_http_date(text)
296
+ Time.httpdate(text)
297
+ rescue ArgumentError
298
+ nil
299
+ end
300
+
301
+ # ─── options ────────────────────────────────────────────────────────────────────────────────────────────────
302
+
303
+ def normalize_base_url(raw)
304
+ uri = begin
305
+ URI.parse(raw.to_s)
306
+ rescue URI::InvalidURIError
307
+ raise invalid('base_url is not a valid URL.')
308
+ end
309
+ raise invalid('base_url is not a valid URL.') if uri.host.nil? || uri.host.empty?
310
+
311
+ host = uri.host.downcase
312
+ scheme = uri.scheme.to_s.downcase
313
+ local = ['localhost', '127.0.0.1', '[::1]', '::1'].include?(host)
314
+ unless scheme == 'https' || (scheme == 'http' && local)
315
+ raise invalid('base_url must be https (http is accepted for localhost only): the key travels in every call.')
316
+ end
317
+
318
+ port = uri.port == uri.class.default_port ? '' : ":#{uri.port}"
319
+ "#{scheme}://#{host}#{port}#{uri.path.sub(%r{/+\z}, '')}"
320
+ end
321
+
322
+ def positive(value, name)
323
+ raise invalid("#{name} must be a positive number.") unless value.is_a?(Numeric) && value.finite? && value.positive?
324
+
325
+ value
326
+ end
327
+
328
+ def non_negative(value, name)
329
+ raise invalid("#{name} must be a number, 0 or more.") unless value.is_a?(Numeric) && value.finite? && value >= 0
330
+
331
+ value
332
+ end
333
+
334
+ def retry_count(value)
335
+ raise invalid('max_retries must be an integer from 0 to 10.') unless value.is_a?(Integer) && value >= 0 && value <= 10
336
+
337
+ value
338
+ end
339
+
340
+ # ─── logging ────────────────────────────────────────────────────────────────────────────────────────────────
341
+
342
+ def log_debug(message)
343
+ @logger&.debug(message)
344
+ rescue StandardError
345
+ nil # a broken logger never breaks a call
346
+ end
347
+
348
+ def log_warn(message)
349
+ @logger&.warn(message)
350
+ rescue StandardError
351
+ nil
352
+ end
353
+ end
354
+ end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Airdun
4
+ # Where the API lives.
5
+ DEFAULT_BASE_URL = 'https://api.airdun.com/v1'
6
+
7
+ # Items in one batch (the API refuses more).
8
+ MAX_BATCH_ITEMS = 100
9
+ # The body of one call, in bytes (the API answers 413 above).
10
+ MAX_BODY_BYTES = 512 * 1024
11
+ # Requests per key per minute; a batch of N costs N. Information only: the SDK does not throttle.
12
+ RATE_LIMIT_PER_MINUTE = 600
13
+
14
+ # Seconds, per attempt.
15
+ DEFAULT_TIMEOUT = 30
16
+ DEFAULT_MAX_RETRIES = 3
17
+ # The most time (seconds) all the retries of one call may spend waiting.
18
+ DEFAULT_MAX_RETRY_WAIT = 30
19
+
20
+ # A key is `adn_sk_live_...` or `adn_sk_test_...`.
21
+ KEY_PATTERN = /\Aadn_sk_(live|test)_[A-Za-z0-9_-]{16,}\z/.freeze
22
+ # How much of a key a log line may show: `adn_sk_live_` or `adn_sk_test_`, no secret character (Node shows 16).
23
+ VISIBLE_PREFIX_CHARS = 12
24
+
25
+ # Every `code` the API can answer, with its HTTP status. One entry per line: the API's drift guard parses this
26
+ # table (apps/api/src/modules/server-api/ruby-sdk.integration-spec.ts).
27
+ SERVER_API_ERROR_STATUS = {
28
+ 'SERVER_API.KEY_MISSING' => 401,
29
+ 'SERVER_API.KEY_INVALID' => 401,
30
+ 'SERVER_API.KEY_REVOKED' => 401,
31
+ 'SERVER_API.KEY_MODE_MISMATCH' => 403,
32
+ 'SERVER_API.BROWSER_NOT_ALLOWED' => 403,
33
+ 'SERVER_API.RATE_LIMITED' => 429,
34
+ 'SERVER_API.BODY_TOO_LARGE' => 413,
35
+ 'SERVER_API.CONTENT_TYPE_UNSUPPORTED' => 415,
36
+ 'SERVER_API.BODY_NOT_JSON' => 400,
37
+ 'SERVER_API.VALIDATION_FAILED' => 400,
38
+ 'SERVER_API.NUL_CHARACTER' => 400,
39
+ 'SERVER_API.NESTING_TOO_DEEP' => 400,
40
+ 'SERVER_API.IDENTIFIER_REQUIRED' => 400,
41
+ 'SERVER_API.CONTACT_CONFLICT' => 409,
42
+ 'SERVER_API.PROPERTY_INVALID_VALUE' => 400,
43
+ 'SERVER_API.TOO_MANY_PROPERTIES' => 400,
44
+ 'SERVER_API.EVENT_NAME_INVALID' => 400,
45
+ 'SERVER_API.EVENT_NAMES_LIMIT' => 422,
46
+ 'SERVER_API.EVENT_PROPERTIES_INVALID' => 400,
47
+ 'SERVER_API.TIMESTAMP_INVALID' => 400,
48
+ 'SERVER_API.IDEMPOTENCY_KEY_REUSED' => 409,
49
+ 'SERVER_API.UNAVAILABLE' => 503,
50
+ 'SERVER_API.INTERNAL_ERROR' => 500
51
+ }.freeze
52
+
53
+ # Refusals raised by the SDK itself, before or instead of an API answer.
54
+ SDK_ERROR_CODES = %w[
55
+ SDK.INVALID_ARGUMENT
56
+ SDK.BATCH_TOO_LARGE
57
+ SDK.BODY_TOO_LARGE
58
+ SDK.UNEXPECTED_RESPONSE
59
+ SDK.REDIRECTED
60
+ ].freeze
61
+ end
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Airdun
4
+ # Base class of everything the SDK raises. `rescue Airdun::Error` catches it all.
5
+ #
6
+ # Read `code` and `details`, never `message`. `status` is the HTTP status, 0 when the SDK refused the call before
7
+ # sending (or never got an answer).
8
+ class Error < StandardError
9
+ attr_reader :code, :status, :details, :retry_after_seconds
10
+
11
+ def initialize(message = nil, code: nil, status: 0, details: nil, retry_after_seconds: nil)
12
+ super(message)
13
+ @code = code
14
+ @status = status
15
+ @details = details || {}
16
+ @retry_after_seconds = retry_after_seconds
17
+ end
18
+
19
+ alias retry_after retry_after_seconds
20
+ end
21
+
22
+ # The SDK refused the call before sending it: a bad argument (`SDK.INVALID_ARGUMENT`), a batch of more than 100
23
+ # items (`SDK.BATCH_TOO_LARGE`) or a body over 512 KB (`SDK.BODY_TOO_LARGE`). `status` is 0, nothing was sent.
24
+ class InvalidArgumentError < Error; end
25
+
26
+ # Airdun answered, and refused (a `SERVER_API.*` code) or answered something that is not its JSON
27
+ # (`SDK.UNEXPECTED_RESPONSE`, `SDK.REDIRECTED`). Node's `AirdunError`.
28
+ class ApiError < Error
29
+ # The most specific class for an answer; every one of them is an ApiError, `code` stays the contract.
30
+ def self.class_for(status)
31
+ case status
32
+ when 401 then AuthenticationError
33
+ when 403 then PermissionError
34
+ when 429 then RateLimitError
35
+ when 409 then ConflictError
36
+ when 400, 413, 415, 422 then ValidationError
37
+ when 500..599 then ServerError
38
+ else self
39
+ end
40
+ end
41
+ end
42
+
43
+ # 401: the key is missing, unknown or revoked.
44
+ class AuthenticationError < ApiError; end
45
+ # 403: the key's mode no longer matches its workspace, or the call came from a browser.
46
+ class PermissionError < ApiError; end
47
+ # 429: `retry_after_seconds` says when to try again (the SDK already waited and retried within its budget).
48
+ class RateLimitError < ApiError; end
49
+ # 409: a contact conflict, or an idempotency key used by another event.
50
+ class ConflictError < ApiError; end
51
+ # 400, 413, 415, 422: the call itself is wrong. Read `details`.
52
+ class ValidationError < ApiError; end
53
+ # 5xx, after the retries.
54
+ class ServerError < ApiError; end
55
+
56
+ # The call never got an answer: network error or timeout, after the retries.
57
+ class ConnectionError < Error
58
+ # How many times the call was tried.
59
+ attr_reader :attempts
60
+
61
+ def initialize(message = nil, timed_out: false, attempts: 1)
62
+ super(message, code: nil, status: 0)
63
+ @timed_out = timed_out
64
+ @attempts = attempts
65
+ end
66
+
67
+ def timed_out?
68
+ @timed_out
69
+ end
70
+ end
71
+
72
+ # No answer within the timeout, after the retries.
73
+ class TimeoutError < ConnectionError; end
74
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Airdun
4
+ # Kept equal to the gemspec's version (a test fails when they differ).
5
+ VERSION = '0.1.0'
6
+ end
@@ -0,0 +1,210 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'date'
4
+ require 'securerandom'
5
+ require 'time'
6
+
7
+ module Airdun
8
+ # Ruby arguments to the wire's exact shapes (and the wire's keys back to snake_case symbols). Pure functions.
9
+ module Wire
10
+ MAX_DEPTH = 100
11
+ IDEMPOTENCY_KEY_PATTERN = /\A[A-Za-z0-9_.:-]{1,128}\z/.freeze
12
+ IDENTIFY_ARGS = %i[email user_id properties subscriptions timestamp].freeze
13
+ TRACK_ARGS = %i[event email user_id properties contact_properties subscriptions timestamp idempotency_key].freeze
14
+ IDENTIFY_KEYS = %i[type user_id email properties subscriptions timestamp].freeze
15
+ TRACK_KEYS = %i[type event user_id email properties contact_properties subscriptions timestamp idempotency_key].freeze
16
+
17
+ module_function
18
+
19
+ def invalid(message)
20
+ InvalidArgumentError.new(message, code: 'SDK.INVALID_ARGUMENT', status: 0)
21
+ end
22
+
23
+ def time_like?(value)
24
+ value.is_a?(Time) || value.is_a?(Date)
25
+ end
26
+
27
+ # A Time, Date or DateTime as ISO 8601 in UTC, with milliseconds (what JavaScript's toISOString writes).
28
+ def iso(value)
29
+ if value.is_a?(DateTime)
30
+ value.to_time.getutc.iso8601(3)
31
+ elsif value.is_a?(Date)
32
+ Time.utc(value.year, value.month, value.day).iso8601(3)
33
+ else
34
+ value.getutc.iso8601(3)
35
+ end
36
+ end
37
+
38
+ # The timestamp of a call: a Time / Date / DateTime, or an ISO 8601 String sent as given.
39
+ def timestamp(value, now)
40
+ return iso(now) if value.nil?
41
+ return iso(value) if time_like?(value)
42
+ return value if value.is_a?(String) && value.valid_encoding?
43
+
44
+ raise invalid('timestamp must be a Time, a Date or an ISO 8601 string.')
45
+ end
46
+
47
+ # A value of a JSON body: validated and turned into what JSON.generate takes. Never echoes a value in a message.
48
+ def value(value, depth = 0)
49
+ raise invalid('The call holds a value that cannot be sent as JSON (nested too deep, or a cycle).') if depth > MAX_DEPTH
50
+
51
+ case value
52
+ when nil, true, false, Integer then value
53
+ when String then string(value)
54
+ when Symbol then string(value.to_s)
55
+ when Float then finite(value)
56
+ when Numeric then finite(numeric_to_f(value))
57
+ when Hash then hash_value(value, depth)
58
+ when Array then value.map { |item| value(item, depth + 1) }
59
+ else
60
+ return iso(value) if time_like?(value)
61
+
62
+ raise invalid("The call holds a #{value.class} value, which cannot be sent as JSON. Use strings, numbers, booleans, nil, Time, Hash and Array.")
63
+ end
64
+ end
65
+
66
+ def string(str)
67
+ utf8 = str.encoding == Encoding::UTF_8 ? str : str.encode(Encoding::UTF_8)
68
+ raise invalid('The call holds a string that is not valid UTF-8.') unless utf8.valid_encoding?
69
+
70
+ utf8
71
+ rescue EncodingError
72
+ raise invalid('The call holds a string that is not valid UTF-8.')
73
+ end
74
+
75
+ def numeric_to_f(num)
76
+ Float(num)
77
+ rescue ArgumentError, TypeError, RangeError
78
+ raise invalid('The call holds a number that cannot be sent as JSON.')
79
+ end
80
+
81
+ def finite(float)
82
+ raise invalid('The call holds NaN or Infinity, which JSON cannot carry.') unless float.finite?
83
+
84
+ float
85
+ end
86
+
87
+ def hash_value(source, depth)
88
+ out = {}
89
+ source.each do |key, item|
90
+ raise invalid('A key of the call is neither a String nor a Symbol.') unless key.is_a?(String) || key.is_a?(Symbol)
91
+
92
+ name = string(key.to_s)
93
+ raise invalid("The call holds the key #{name.inspect} twice (as a String and as a Symbol).") if out.key?(name)
94
+
95
+ out[name] = value(item, depth + 1)
96
+ end
97
+ out
98
+ end
99
+
100
+ def object(source, field)
101
+ return nil if source.nil?
102
+ raise invalid("#{field} must be a Hash.") unless source.is_a?(Hash)
103
+
104
+ value(source)
105
+ end
106
+
107
+ def identifier(value, field)
108
+ return nil if value.nil?
109
+ return value.to_s if value.is_a?(Integer)
110
+ return string(value) if value.is_a?(String)
111
+ return string(value.to_s) if value.is_a?(Symbol)
112
+
113
+ raise invalid("#{field} must be a String.")
114
+ end
115
+
116
+ # A key is letters, digits and `_ . : -`, 1 to 128 characters (the API's rule).
117
+ def idempotency(key)
118
+ unless key.is_a?(String) && IDEMPOTENCY_KEY_PATTERN.match?(key)
119
+ raise invalid('idempotency_key must be a String of 1 to 128 letters, digits and _ . : - (leave it out to get a generated one).')
120
+ end
121
+
122
+ key
123
+ end
124
+
125
+ # The arguments of identify / track: an optional positional Hash merged with the keywords.
126
+ def arguments(positional, keywords, allowed)
127
+ unless positional.nil? || positional.is_a?(Hash)
128
+ raise invalid('Pass the arguments as keywords, or as one Hash.')
129
+ end
130
+
131
+ merged = {}
132
+ (positional || {}).each { |key, item| merged[key.to_s.to_sym] = item }
133
+ keywords.each { |key, item| merged[key] = item }
134
+ unknown = merged.keys - allowed
135
+ raise invalid("Unknown argument(s): #{unknown.join(', ')}. Known: #{allowed.join(', ')}.") unless unknown.empty?
136
+
137
+ merged
138
+ end
139
+
140
+ # Drops the nil fields, like JSON.stringify drops `undefined`.
141
+ def compact(hash)
142
+ hash.reject { |_key, item| item.nil? }
143
+ end
144
+
145
+ def identify_body(now:, email: nil, user_id: nil, properties: nil, subscriptions: nil, timestamp: nil)
146
+ compact(
147
+ 'userId' => identifier(user_id, 'user_id'),
148
+ 'email' => identifier(email, 'email'),
149
+ 'properties' => object(properties, 'properties'),
150
+ 'subscriptions' => object(subscriptions, 'subscriptions'),
151
+ 'timestamp' => timestamp(timestamp, now)
152
+ )
153
+ end
154
+
155
+ def track_body(event:, now:, email: nil, user_id: nil, properties: nil, contact_properties: nil, subscriptions: nil,
156
+ timestamp: nil, idempotency_key: nil)
157
+ raise invalid('track needs an event name (a non empty string).') unless (event.is_a?(String) || event.is_a?(Symbol)) && !event.to_s.empty?
158
+
159
+ compact(
160
+ 'event' => string(event.to_s),
161
+ 'userId' => identifier(user_id, 'user_id'),
162
+ 'email' => identifier(email, 'email'),
163
+ 'properties' => object(properties, 'properties'),
164
+ 'contactProperties' => object(contact_properties, 'contact_properties'),
165
+ 'subscriptions' => object(subscriptions, 'subscriptions'),
166
+ 'timestamp' => timestamp(timestamp, now),
167
+ 'idempotencyKey' => idempotency_key.nil? ? SecureRandom.uuid : idempotency(idempotency_key)
168
+ )
169
+ end
170
+
171
+ # One item of a batch. An item that is not an identify / track Hash goes through as given: the API reports it
172
+ # item by item.
173
+ def batch_item(item, now, index = 0)
174
+ return value(item) unless item.is_a?(Hash)
175
+
176
+ fields = {}
177
+ item.each { |key, item_value| fields[key.to_s.to_sym] = item_value }
178
+ case fields[:type].to_s
179
+ when 'identify'
180
+ reject_unknown(fields, IDENTIFY_KEYS, index)
181
+ { 'type' => 'identify' }.merge(identify_body(**fields.reject { |key, _| key == :type }, now: now))
182
+ when 'track'
183
+ reject_unknown(fields, TRACK_KEYS, index)
184
+ { 'type' => 'track' }.merge(track_body(**fields.reject { |key, _| key == :type }, now: now))
185
+ else
186
+ value(item)
187
+ end
188
+ end
189
+
190
+ def reject_unknown(fields, allowed, index)
191
+ unknown = fields.keys - allowed
192
+ return if unknown.empty?
193
+
194
+ raise invalid("Batch item #{index} holds unknown key(s): #{unknown.map(&:to_s).join(', ')}. Known keys: #{allowed.join(', ')}.")
195
+ end
196
+
197
+ # The wire's camelCase keys as snake_case symbols, deeply. Values are left as they are.
198
+ def snake(node)
199
+ case node
200
+ when Hash then node.each_with_object({}) { |(key, item), out| out[snake_key(key)] = snake(item) }
201
+ when Array then node.map { |item| snake(item) }
202
+ else node
203
+ end
204
+ end
205
+
206
+ def snake_key(key)
207
+ key.to_s.gsub(/([a-z\d])([A-Z])/, '\1_\2').downcase.to_sym
208
+ end
209
+ end
210
+ end
data/lib/airdun.rb ADDED
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'airdun/version'
4
+ require 'airdun/constants'
5
+ require 'airdun/errors'
6
+ require 'airdun/wire'
7
+ require 'airdun/client'
8
+
9
+ # The official Ruby server SDK for Airdun: send your contacts and your events from your backend.
10
+ module Airdun
11
+ end
metadata ADDED
@@ -0,0 +1,50 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: airdun
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Airdun
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: Identify contacts and track events from your Ruby backend. Direct sending,
13
+ automatic idempotency keys, retries on network errors, timeouts, 429 and 5xx. No
14
+ runtime dependency.
15
+ executables: []
16
+ extensions: []
17
+ extra_rdoc_files: []
18
+ files:
19
+ - CHANGELOG.md
20
+ - LICENSE
21
+ - README.md
22
+ - lib/airdun.rb
23
+ - lib/airdun/client.rb
24
+ - lib/airdun/constants.rb
25
+ - lib/airdun/errors.rb
26
+ - lib/airdun/version.rb
27
+ - lib/airdun/wire.rb
28
+ homepage: https://airdun.com
29
+ licenses:
30
+ - MIT
31
+ metadata:
32
+ rubygems_mfa_required: 'true'
33
+ rdoc_options: []
34
+ require_paths:
35
+ - lib
36
+ required_ruby_version: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '2.7'
41
+ required_rubygems_version: !ruby/object:Gem::Requirement
42
+ requirements:
43
+ - - ">="
44
+ - !ruby/object:Gem::Version
45
+ version: '0'
46
+ requirements: []
47
+ rubygems_version: 4.0.16
48
+ specification_version: 4
49
+ summary: Official Ruby server SDK for the Airdun API.
50
+ test_files: []