relaygrid 0.3.0 → 0.4.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 +4 -4
- data/CHANGELOG.md +38 -0
- data/QUICKSTART.md +2 -1
- data/README.md +129 -4
- data/lib/relaygrid/client.rb +11 -1
- data/lib/relaygrid/errors.rb +16 -2
- data/lib/relaygrid/resources/broadcasts.rb +84 -0
- data/lib/relaygrid/resources/notifications.rb +16 -58
- data/lib/relaygrid/resources/segments.rb +86 -0
- data/lib/relaygrid/resources/send_payload.rb +63 -0
- data/lib/relaygrid/resources/users.rb +7 -1
- data/lib/relaygrid/send_result.rb +4 -2
- data/lib/relaygrid/version.rb +1 -1
- data/lib/relaygrid.rb +3 -0
- metadata +5 -2
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: a94cfd9fa78b497d772a31d686e4e96ca5f7853680df49e9565dc1373566527d
|
|
4
|
+
data.tar.gz: 40b08dd748966a82721a91175905207793b790b579a02878a46f9586206a7fa2
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 53a3566ae4082ee00b2cb64c86c9fde68e5b524d5375a0f9c6586ffc19a6c4f9a246b7c523a46212317640f515950d35a4768145380edf08db361172d749269a
|
|
7
|
+
data.tar.gz: b7e291b2d26c9e29f2939baa9e390a2a0146071246f0ef2c95f4deac76394cd7f6fd9a3cb71cf13f8d16d0316321965d9abfb9c5812e39acd3a9894b67922086
|
data/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,44 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.4.0] - 2026-11-22
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- **`PermissionDeniedError`.** A 403 whose body names a `permission` now raises
|
|
15
|
+
`RelayGrid::PermissionDeniedError` and exposes the name as `#permission`. It
|
|
16
|
+
subclasses `AuthenticationError`, so existing rescues keep working; a 403
|
|
17
|
+
without `permission` (a suspended account) is still a plain
|
|
18
|
+
`AuthenticationError`.
|
|
19
|
+
|
|
20
|
+
- **Segments.** `client.segments` manages recipient segments: `list`, `get`
|
|
21
|
+
(includes a live `recipient_count`), `create`, `update`, `delete`, and
|
|
22
|
+
`preview(rules:)` for checking a rules payload without saving it. Rules are
|
|
23
|
+
`{ all: [{ field:, op:, value: }, ...] }`, AND-only, matched against
|
|
24
|
+
`first_name`, `middle_name`, `last_name`, `created_at`, `channel`
|
|
25
|
+
(`email`/`sms` only), and `traits.<key>`.
|
|
26
|
+
- **Broadcasts.** `client.broadcasts` fans one template out to every recipient a
|
|
27
|
+
segment matches, instead of sending one at a time:
|
|
28
|
+
`create(segment:, template:, attributes:, scheduled_at:)`, `get(id)`, and
|
|
29
|
+
`list`. `segment:` takes the segment's name (a String) or its id (an
|
|
30
|
+
Integer), the same way `template:` takes a message template's name -- a
|
|
31
|
+
numeric-looking String is read as a name, never an id. Resolution and delivery
|
|
32
|
+
happen in the background, so `create` returns the broadcast row (`{ id:,
|
|
33
|
+
segment_id:, recipient_count:, status: }`) as soon as it is enqueued; poll
|
|
34
|
+
`get` for `status` and `created_message_count`. `create` requires the
|
|
35
|
+
`user_segmentation` feature and raises `LimitExceededError` (402) without it,
|
|
36
|
+
while `list` and `get` stay readable. Like `notify`, it is never retried
|
|
37
|
+
automatically -- a retry would fan the segment out twice. A scheduled
|
|
38
|
+
broadcast is undone by cancelling its messages one at a time with
|
|
39
|
+
`messages.cancel_schedule`; there is no broadcast-level cancel.
|
|
40
|
+
- **`traits`**, a free-form hash of targeting data on the recipient -- what
|
|
41
|
+
segment rules (`traits.<key>`) match against. `users.upsert` gains a
|
|
42
|
+
`traits:` keyword, and the nested `user:` payload on `notify` forwards a
|
|
43
|
+
`traits:` key. On a send traits shallow-merge into the recipient's existing
|
|
44
|
+
traits and a `nil` value for a key deletes it; `users.upsert` replaces the
|
|
45
|
+
whole document. Traits are stored in the clear and are not a place for
|
|
46
|
+
secrets.
|
|
47
|
+
|
|
10
48
|
## [0.3.0] - 2026-08-26
|
|
11
49
|
|
|
12
50
|
### Added
|
data/QUICKSTART.md
CHANGED
|
@@ -126,9 +126,10 @@ ws.connect
|
|
|
126
126
|
|---|---|
|
|
127
127
|
| `ConfigurationError: api_key is required` | `RELAYGRID_API_KEY` isn't set in this environment. |
|
|
128
128
|
| `AuthenticationError` | Key is wrong, deactivated, expired, or the account is suspended. |
|
|
129
|
+
| `PermissionDeniedError` | The key is valid but restricted and lacks the permission in `error.permission`. |
|
|
129
130
|
| `TemplateNotFoundError` | Template name doesn't match, or the template is soft-deleted. |
|
|
130
131
|
| `LimitExceededError` | Monthly notification limit spent — check Usage in the dashboard. |
|
|
131
|
-
| `result.push_token` is `nil` | The template has no live push channel attached
|
|
132
|
+
| `result.push_token` is `nil` | The template has no live push channel attached, or the key lacks `recipients:token`. |
|
|
132
133
|
| Delivery stuck at `queued` | The delivery job hasn't run yet; poll again shortly. |
|
|
133
134
|
| Delivery `failed` | Read `delivery.friendly_error_message` — usually channel credentials. |
|
|
134
135
|
| `scheduled_at` gets a 422 | The timestamp has no UTC offset, or isn't a real date/time. Use `Time`/`DateTime`/`ActiveSupport::TimeWithZone`, or an explicit-offset ISO 8601 string. |
|
data/README.md
CHANGED
|
@@ -112,6 +112,36 @@ RelayGrid.client.users.set_contact("user-123", channel_type: "email", value: "ad
|
|
|
112
112
|
RelayGrid.client.users.delete_contact("user-123", channel_type: "email")
|
|
113
113
|
```
|
|
114
114
|
|
|
115
|
+
### Traits
|
|
116
|
+
|
|
117
|
+
`traits` is a free-form hash of targeting data on the recipient -- what
|
|
118
|
+
[segment rules](#segments) (`traits.<key>`) match against. Set it on a send or
|
|
119
|
+
independently:
|
|
120
|
+
|
|
121
|
+
```ruby
|
|
122
|
+
# On a send: shallow-merged into the recipient's existing traits.
|
|
123
|
+
RelayGrid.client.notify(
|
|
124
|
+
user: { id: "user-123", first_name: "Ada", traits: { plan: "pro", seats: 5 } },
|
|
125
|
+
template: "order_shipped"
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
# Also on a send: a nil value deletes just that key.
|
|
129
|
+
RelayGrid.client.notify(
|
|
130
|
+
user: { id: "user-123", traits: { seats: nil } },
|
|
131
|
+
template: "order_shipped"
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
# Through users.upsert: replaces the recipient's whole traits document.
|
|
135
|
+
RelayGrid.client.users.upsert(id: "user-123", first_name: "Ada", last_name: "Lovelace",
|
|
136
|
+
traits: { plan: "pro" })
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
The two paths differ deliberately: a send is a partial update of a recipient it
|
|
140
|
+
may be creating on the fly, while `users.upsert` writes the record you hand it.
|
|
141
|
+
|
|
142
|
+
Traits are targeting data, not a place for secrets -- they are stored in the
|
|
143
|
+
clear and are not encrypted at rest.
|
|
144
|
+
|
|
115
145
|
### The result
|
|
116
146
|
|
|
117
147
|
```ruby
|
|
@@ -182,6 +212,97 @@ RelayGrid.client.channel_tokens.create(user_id: "user-123")
|
|
|
182
212
|
# => { token: "eyJf...", expires_in: 3600, expires_at: 2026-07-28 11:00:00 +0000 }
|
|
183
213
|
```
|
|
184
214
|
|
|
215
|
+
## Segments
|
|
216
|
+
|
|
217
|
+
Segments match a group of recipients by their traits. `client.broadcasts` fans
|
|
218
|
+
one template out to everyone a segment matches, instead of sending one at a
|
|
219
|
+
time:
|
|
220
|
+
|
|
221
|
+
```ruby
|
|
222
|
+
segment = RelayGrid.client.segments.create(
|
|
223
|
+
name: "Pro plan",
|
|
224
|
+
rules: { all: [{ field: "traits.plan", op: "eq", value: "pro" }] }
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
# A String is the segment's name, an Integer its id -- just like template:
|
|
228
|
+
broadcast = RelayGrid.client.broadcasts.create(segment: "Pro plan", template: "spring_sale")
|
|
229
|
+
broadcast # => { "id" => 3, "segment_id" => 7, "recipient_count" => 4210, "status" => "pending" }
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
Resolution and delivery happen in the background, so `create` returns the
|
|
233
|
+
broadcast row as soon as it's enqueued -- there is no message id or deliveries
|
|
234
|
+
to report yet. Poll for the outcome:
|
|
235
|
+
|
|
236
|
+
```ruby
|
|
237
|
+
RelayGrid.client.broadcasts.get(3)
|
|
238
|
+
# => { "id" => 3, "status" => "finished", "created_message_count" => 4210, ... }
|
|
239
|
+
|
|
240
|
+
RelayGrid.client.broadcasts.list # => [{ "id" => 3, ... }, ...] newest first
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
`create` also takes `attributes:` for the template's `{{placeholders}}` and
|
|
244
|
+
`scheduled_at:`, serialized exactly like `notify`'s:
|
|
245
|
+
|
|
246
|
+
```ruby
|
|
247
|
+
RelayGrid.client.broadcasts.create(
|
|
248
|
+
segment: "Pro plan",
|
|
249
|
+
template: "spring_sale",
|
|
250
|
+
attributes: { discount: "20%" },
|
|
251
|
+
scheduled_at: Time.now + 3600
|
|
252
|
+
)
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
The deferral lands on each fanned-out message rather than on the broadcast, so
|
|
256
|
+
undoing a scheduled broadcast means cancelling its messages one at a time with
|
|
257
|
+
`client.messages.cancel_schedule(id)`. There is no broadcast-level cancel.
|
|
258
|
+
|
|
259
|
+
Creating a broadcast requires the `user_segmentation` feature; an account
|
|
260
|
+
without it gets `LimitExceededError` (402, carrying `feature_key`). `list` and
|
|
261
|
+
`get` stay readable either way, so past broadcasts survive the feature being
|
|
262
|
+
turned off.
|
|
263
|
+
|
|
264
|
+
Rules are `{ all: [{ field:, op:, value: }, ...] }` -- every condition must
|
|
265
|
+
match (AND-only, no nesting):
|
|
266
|
+
|
|
267
|
+
| Field | Notes |
|
|
268
|
+
|---|---|
|
|
269
|
+
| `first_name`, `middle_name`, `last_name` | |
|
|
270
|
+
| `created_at` | ISO 8601, or a rolling offset like `-7d` with `gt`/`lt` (see below) |
|
|
271
|
+
| `channel` | `email` or `sms` only -- whether the recipient has a live contact for that channel |
|
|
272
|
+
| `traits.<key>` | matched against the recipient's `traits` |
|
|
273
|
+
|
|
274
|
+
Ops: `eq`, `neq`, `contains`, `gt`, `lt`.
|
|
275
|
+
|
|
276
|
+
A `created_at` value can be a rolling offset -- `-<number><unit>`, where unit is
|
|
277
|
+
`h`, `d`, or `w` -- instead of a fixed date, with `gt`/`lt` only. It is resolved
|
|
278
|
+
each time the segment runs, so this keeps meaning "the last 7 days" tomorrow:
|
|
279
|
+
|
|
280
|
+
```ruby
|
|
281
|
+
client.segments.create(
|
|
282
|
+
name: "Recent signups",
|
|
283
|
+
rules: { all: [{ field: "created_at", op: "gt", value: "-7d" }] }
|
|
284
|
+
)
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
A fixed date would freeze on the day you saved it.
|
|
288
|
+
|
|
289
|
+
An empty `rules` payload (`{}`) matches every recipient, which is fine for
|
|
290
|
+
drafting and for `preview` below -- but broadcasting to an unconditioned segment
|
|
291
|
+
is refused with `ValidationError` (422) unless its rules carry `match_all: true`.
|
|
292
|
+
|
|
293
|
+
```ruby
|
|
294
|
+
RelayGrid.client.segments.list # => [{ "id" => 7, "name" => ..., "rules" => ... }, ...]
|
|
295
|
+
RelayGrid.client.segments.get(7) # includes a live "recipient_count"
|
|
296
|
+
RelayGrid.client.segments.update(7, name: "Renamed")
|
|
297
|
+
RelayGrid.client.segments.delete(7)
|
|
298
|
+
|
|
299
|
+
RelayGrid.client.segments.preview(rules: segment["rules"])
|
|
300
|
+
# => { "count" => 4210, "sample" => [{ "id" => 1, "first_name" => "Ada", ... }, ...] }
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
`preview` checks rules without saving a segment -- what a rule-builder UI calls
|
|
304
|
+
as the caller edits conditions, capped at 5 sample recipients.
|
|
305
|
+
|
|
185
306
|
## Checking delivery status
|
|
186
307
|
|
|
187
308
|
```ruby
|
|
@@ -313,7 +434,8 @@ suffices. Faraday exceptions never escape the gem.
|
|
|
313
434
|
| `ConnectionError` | The request never produced a response |
|
|
314
435
|
| `TimeoutError` | A timeout (subclass of `ConnectionError`) |
|
|
315
436
|
| `AuthenticationError` | 401/403 — key invalid, inactive, expired, or account suspended |
|
|
316
|
-
| `
|
|
437
|
+
| `PermissionDeniedError` | 403 naming a permission the key lacks (subclass of `AuthenticationError`); `#permission` is the name, e.g. `"messages:read"` |
|
|
438
|
+
| `LimitExceededError` | 402 — monthly notification limit spent, or the account lacks a gated feature (`#body` carries a `feature_key`, e.g. `user_segmentation`) |
|
|
317
439
|
| `NotFoundError` | 404 |
|
|
318
440
|
| `TemplateNotFoundError` | 404 naming a template (subclass of `NotFoundError`) |
|
|
319
441
|
| `UserNotFoundError` | 404 naming a recipient (subclass of `NotFoundError`) |
|
|
@@ -329,6 +451,8 @@ begin
|
|
|
329
451
|
RelayGrid.client.notify(user: user, template: "order_shipped")
|
|
330
452
|
rescue RelayGrid::LimitExceededError
|
|
331
453
|
# out of notifications this month
|
|
454
|
+
rescue RelayGrid::PermissionDeniedError => e
|
|
455
|
+
Rails.logger.error("API key lacks #{e.permission}")
|
|
332
456
|
rescue RelayGrid::TemplateNotFoundError => e
|
|
333
457
|
Rails.logger.error(e.error_message)
|
|
334
458
|
end
|
|
@@ -340,9 +464,10 @@ GETs retry automatically (3 attempts by default, jittered exponential backoff)
|
|
|
340
464
|
on 429, 5xx, and transport failures.
|
|
341
465
|
|
|
342
466
|
**`notify` is never retried.** A blind retry would send the recipient a second
|
|
343
|
-
real notification.
|
|
344
|
-
|
|
345
|
-
|
|
467
|
+
real notification. The same goes for `broadcasts.create`, where a retry would
|
|
468
|
+
fan the whole segment out twice. If either fails, deciding whether to re-send is
|
|
469
|
+
yours to make. Server-side `Idempotency-Key` support is planned so retries can
|
|
470
|
+
be made safe.
|
|
346
471
|
|
|
347
472
|
## Development
|
|
348
473
|
|
data/lib/relaygrid/client.rb
CHANGED
|
@@ -16,7 +16,9 @@ module RelayGrid
|
|
|
16
16
|
class Client
|
|
17
17
|
# Requests that may be replayed without changing server state. `notify` is
|
|
18
18
|
# deliberately absent: a blind retry sends the recipient a second real
|
|
19
|
-
# notification.
|
|
19
|
+
# notification. `POST /api/v1/broadcasts` (behind `broadcasts.create`) is
|
|
20
|
+
# equally non-idempotent -- a retry fans the segment out twice. See README
|
|
21
|
+
# ("Retries and idempotency").
|
|
20
22
|
IDEMPOTENT_METHODS = %i[get head options].freeze
|
|
21
23
|
|
|
22
24
|
RETRIABLE_STATUSES = [429, 500, 502, 503, 504].freeze
|
|
@@ -71,6 +73,14 @@ module RelayGrid
|
|
|
71
73
|
resource(:webhook_endpoints) { Resources::WebhookEndpoints.new(self) }
|
|
72
74
|
end
|
|
73
75
|
|
|
76
|
+
def segments
|
|
77
|
+
resource(:segments) { Resources::Segments.new(self) }
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
def broadcasts
|
|
81
|
+
resource(:broadcasts) { Resources::Broadcasts.new(self) }
|
|
82
|
+
end
|
|
83
|
+
|
|
74
84
|
# Send a notification -- the one call the whole gem exists for.
|
|
75
85
|
# See Resources::Notifications#notify.
|
|
76
86
|
def notify(**kwargs)
|
data/lib/relaygrid/errors.rb
CHANGED
|
@@ -38,7 +38,8 @@ module RelayGrid
|
|
|
38
38
|
def self.from_response(status, body)
|
|
39
39
|
klass =
|
|
40
40
|
case status
|
|
41
|
-
when 401
|
|
41
|
+
when 401 then AuthenticationError
|
|
42
|
+
when 403 then permission_denied?(body) ? PermissionDeniedError : AuthenticationError
|
|
42
43
|
when 402 then LimitExceededError
|
|
43
44
|
when 404 then not_found_class(body)
|
|
44
45
|
when 422 then ValidationError
|
|
@@ -61,6 +62,11 @@ module RelayGrid
|
|
|
61
62
|
end
|
|
62
63
|
private_class_method :not_found_class
|
|
63
64
|
|
|
65
|
+
def self.permission_denied?(body)
|
|
66
|
+
body.is_a?(Hash) && !body["permission"].to_s.empty?
|
|
67
|
+
end
|
|
68
|
+
private_class_method :permission_denied?
|
|
69
|
+
|
|
64
70
|
private
|
|
65
71
|
|
|
66
72
|
def default_message
|
|
@@ -70,9 +76,17 @@ module RelayGrid
|
|
|
70
76
|
end
|
|
71
77
|
|
|
72
78
|
# 401/403 -- the API key is missing, invalid, inactive, expired, or its
|
|
73
|
-
# account is suspended.
|
|
79
|
+
# account is suspended. A 403 for a restricted key that lacks a permission is
|
|
80
|
+
# the PermissionDeniedError subclass instead, so a key that must be rotated
|
|
81
|
+
# can be told apart from one that is merely scoped too narrowly.
|
|
74
82
|
class AuthenticationError < APIError; end
|
|
75
83
|
|
|
84
|
+
class PermissionDeniedError < AuthenticationError
|
|
85
|
+
def permission
|
|
86
|
+
body["permission"]
|
|
87
|
+
end
|
|
88
|
+
end
|
|
89
|
+
|
|
76
90
|
# 402 -- the account's monthly notification limit is exhausted.
|
|
77
91
|
class LimitExceededError < APIError; end
|
|
78
92
|
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module RelayGrid
|
|
4
|
+
module Resources
|
|
5
|
+
# Broadcasting fans one template out to every recipient a segment matches.
|
|
6
|
+
# Resolution and delivery happen in a background job, so `create` returns
|
|
7
|
+
# the broadcast row as soon as it's enqueued -- there is no message id or
|
|
8
|
+
# deliveries to report yet; poll `get` for the status.
|
|
9
|
+
#
|
|
10
|
+
# broadcast = client.broadcasts.create(
|
|
11
|
+
# segment: "Recent signups",
|
|
12
|
+
# template: "spring_sale",
|
|
13
|
+
# attributes: { discount: "20%" }
|
|
14
|
+
# )
|
|
15
|
+
# broadcast # => { "id" => 3, "segment_id" => 7, "recipient_count" => 4210, "status" => "pending" }
|
|
16
|
+
#
|
|
17
|
+
# Creating a broadcast requires the `user_segmentation` feature; an account
|
|
18
|
+
# without it gets a 402 (`LimitExceededError`). `list` and `get` stay
|
|
19
|
+
# readable either way, so past broadcasts survive the feature being turned
|
|
20
|
+
# off.
|
|
21
|
+
class Broadcasts
|
|
22
|
+
include SendPayload
|
|
23
|
+
|
|
24
|
+
PATH = "/api/v1/broadcasts"
|
|
25
|
+
|
|
26
|
+
def initialize(client)
|
|
27
|
+
@client = client
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
# @return [Array<Hash>] every broadcast in the account, newest first
|
|
31
|
+
def list
|
|
32
|
+
Array(@client.get(PATH)["broadcasts"])
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# @param id [Integer]
|
|
36
|
+
# @return [Hash] the broadcast, including "status" and
|
|
37
|
+
# "created_message_count" once it has finished
|
|
38
|
+
# @raise [RelayGrid::NotFoundError]
|
|
39
|
+
def get(id)
|
|
40
|
+
@client.get("#{PATH}/#{id}")["broadcast"]
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# @param segment [String, Integer] the segment to broadcast to. An
|
|
44
|
+
# Integer is the segment's id; a String is its name, which is unique
|
|
45
|
+
# among the account's live segments -- the same way `template:` names a
|
|
46
|
+
# message template rather than carrying its id.
|
|
47
|
+
# @param template [String] the message template's name
|
|
48
|
+
# @param attributes [Hash] values for the template's `{{placeholders}}`
|
|
49
|
+
# @param scheduled_at [Time, DateTime, ActiveSupport::TimeWithZone, String, nil]
|
|
50
|
+
# when to deliver instead of immediately; serialized exactly like
|
|
51
|
+
# `Notifications#notify`'s. The deferral lands on each fanned-out
|
|
52
|
+
# message, so a scheduled broadcast is undone by cancelling each
|
|
53
|
+
# message's schedule -- there is no broadcast-level cancel.
|
|
54
|
+
# @return [Hash] the broadcast (`{ "id", "segment_id", "recipient_count",
|
|
55
|
+
# "status" }`), still "pending" while resolution runs
|
|
56
|
+
#
|
|
57
|
+
# @raise [RelayGrid::TemplateNotFoundError] no such template in the account
|
|
58
|
+
# @raise [RelayGrid::NotFoundError] no such segment in the account
|
|
59
|
+
# @raise [RelayGrid::LimitExceededError] the monthly notification limit is
|
|
60
|
+
# spent, or the account lacks the `user_segmentation` feature
|
|
61
|
+
# @raise [RelayGrid::ValidationError] the payload was rejected, e.g. an
|
|
62
|
+
# unconditioned segment without `match_all`
|
|
63
|
+
# @raise [ArgumentError] `scheduled_at` is a bare `Date`, which has no instant
|
|
64
|
+
def create(segment:, template:, attributes: {}, scheduled_at: nil)
|
|
65
|
+
broadcast = {
|
|
66
|
+
message_template_name: template.to_s,
|
|
67
|
+
message_attributes_attributes: format_attributes(attributes),
|
|
68
|
+
}
|
|
69
|
+
broadcast.merge!(segment_params(segment))
|
|
70
|
+
broadcast[:scheduled_at] = serialize_scheduled_at(scheduled_at) unless scheduled_at.nil?
|
|
71
|
+
|
|
72
|
+
@client.post(PATH, body: { broadcast: broadcast })["broadcast"]
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
private
|
|
76
|
+
|
|
77
|
+
def segment_params(segment)
|
|
78
|
+
return { segment_id: segment } if segment.is_a?(Integer)
|
|
79
|
+
|
|
80
|
+
{ segment_name: segment.to_s }
|
|
81
|
+
end
|
|
82
|
+
end
|
|
83
|
+
end
|
|
84
|
+
end
|
|
@@ -1,16 +1,15 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
require "date"
|
|
4
|
-
require "time"
|
|
5
|
-
|
|
6
3
|
module RelayGrid
|
|
7
4
|
module Resources
|
|
8
5
|
# Sending. The developer contract the gem exists for: a user, a template
|
|
9
6
|
# name, and the attributes the template needs.
|
|
10
7
|
class Notifications
|
|
8
|
+
include SendPayload
|
|
9
|
+
|
|
11
10
|
# Recipient details a send may carry alongside the id. `email` becomes the
|
|
12
11
|
# contact email deliveries resolve their recipient through.
|
|
13
|
-
RECIPIENT_ATTRIBUTES = %i[first_name middle_name last_name email].freeze
|
|
12
|
+
RECIPIENT_ATTRIBUTES = %i[first_name middle_name last_name email traits].freeze
|
|
14
13
|
|
|
15
14
|
def initialize(client)
|
|
16
15
|
@client = client
|
|
@@ -19,16 +18,20 @@ module RelayGrid
|
|
|
19
18
|
# Send a notification, creating or updating the recipient on the way.
|
|
20
19
|
#
|
|
21
20
|
# @param user [Hash] `{ id:, first_name:, last_name:, middle_name:,
|
|
22
|
-
# email: }`. `id` is the *your-system* identifier -- it maps to
|
|
23
|
-
# `external_user_id`. RelayGrid's internal ids are never
|
|
24
|
-
# May also be a bare String/Integer id for a recipient
|
|
25
|
-
# exists, in which case nothing about them is sent.
|
|
21
|
+
# email:, traits: }`. `id` is the *your-system* identifier -- it maps to
|
|
22
|
+
# the API's `external_user_id`. RelayGrid's internal ids are never
|
|
23
|
+
# exposed here. May also be a bare String/Integer id for a recipient
|
|
24
|
+
# that already exists, in which case nothing about them is sent.
|
|
26
25
|
#
|
|
27
26
|
# `email` is optional but load-bearing: email deliveries resolve their
|
|
28
27
|
# recipient through the contact stored for that channel type, so a send
|
|
29
28
|
# over an email channel for a user with no email on file produces a
|
|
30
29
|
# delivery that fails with "no contact on file". Push needs no contact.
|
|
31
30
|
# Passing an empty string removes the contact.
|
|
31
|
+
#
|
|
32
|
+
# `traits` is shallow-merged into the recipient's existing traits; a nil
|
|
33
|
+
# value for a key deletes it. It is what segment rules (`traits.<key>`)
|
|
34
|
+
# match against.
|
|
32
35
|
# @param template [String] the message template's name
|
|
33
36
|
# @param attributes [Hash] values for the template's `{{placeholders}}`
|
|
34
37
|
# @param scheduled_at [Time, DateTime, ActiveSupport::TimeWithZone, String, nil]
|
|
@@ -66,31 +69,12 @@ module RelayGrid
|
|
|
66
69
|
message.merge!(recipient_params(user))
|
|
67
70
|
message[:scheduled_at] = serialize_scheduled_at(scheduled_at) unless scheduled_at.nil?
|
|
68
71
|
|
|
69
|
-
|
|
72
|
+
response = @client.post("/api/v1/messages", body: { message: message })
|
|
73
|
+
SendResult.new(response, client: @client)
|
|
70
74
|
end
|
|
71
75
|
|
|
72
76
|
private
|
|
73
77
|
|
|
74
|
-
# A `Date` has a day but no instant, so there's no correct offset to emit
|
|
75
|
-
# -- `DateTime` (which `Date` is a superclass of) is fine, only a bare
|
|
76
|
-
# `Date` is rejected. Everything else that responds to `iso8601` (`Time`,
|
|
77
|
-
# `DateTime`, `ActiveSupport::TimeWithZone`) is serialized with it; a
|
|
78
|
-
# `String` passes through for the server to validate.
|
|
79
|
-
def serialize_scheduled_at(value)
|
|
80
|
-
return value if value.is_a?(String)
|
|
81
|
-
|
|
82
|
-
if value.is_a?(Date) && !value.is_a?(DateTime)
|
|
83
|
-
raise ArgumentError, "scheduled_at must be a Time, DateTime, or TimeWithZone -- " \
|
|
84
|
-
"a Date has no instant, so there is no offset to serialize"
|
|
85
|
-
end
|
|
86
|
-
|
|
87
|
-
unless value.respond_to?(:iso8601)
|
|
88
|
-
raise ArgumentError, "scheduled_at must be a Time, DateTime, TimeWithZone, or ISO 8601 String"
|
|
89
|
-
end
|
|
90
|
-
|
|
91
|
-
value.iso8601
|
|
92
|
-
end
|
|
93
|
-
|
|
94
78
|
# A Hash upserts the recipient server-side (one round trip instead of
|
|
95
79
|
# registering the user first); a bare id is a strict lookup.
|
|
96
80
|
def recipient_params(user)
|
|
@@ -108,38 +92,12 @@ module RelayGrid
|
|
|
108
92
|
# anything absent untouched, so omitting a name doesn't blank it out and
|
|
109
93
|
# omitting an email doesn't drop the contact.
|
|
110
94
|
RECIPIENT_ATTRIBUTES.each do |name|
|
|
111
|
-
|
|
112
|
-
end
|
|
113
|
-
|
|
114
|
-
{ user: nested }
|
|
115
|
-
end
|
|
116
|
-
|
|
117
|
-
# The API takes attributes as [{ name:, value: }], which is awkward to
|
|
118
|
-
# write by hand, so a plain Hash is accepted and converted.
|
|
119
|
-
def format_attributes(attributes)
|
|
120
|
-
return [] if attributes.nil? || attributes.empty?
|
|
95
|
+
next if user[name].nil?
|
|
121
96
|
|
|
122
|
-
|
|
123
|
-
when Hash
|
|
124
|
-
attributes.map { |name, value| { name: name.to_s, value: value.to_s } }
|
|
125
|
-
when Array
|
|
126
|
-
attributes.map do |attribute|
|
|
127
|
-
attribute = normalize_keys(attribute)
|
|
128
|
-
unless attribute.is_a?(Hash) && attribute.key?(:name)
|
|
129
|
-
raise ArgumentError, "array attributes must be hashes with a :name key"
|
|
130
|
-
end
|
|
131
|
-
|
|
132
|
-
{ name: attribute[:name].to_s, value: attribute[:value].to_s }
|
|
133
|
-
end
|
|
134
|
-
else
|
|
135
|
-
raise ArgumentError, "attributes must be a Hash or an Array of {name:, value:} hashes"
|
|
97
|
+
nested[name] = name == :traits ? user[name] : user[name].to_s
|
|
136
98
|
end
|
|
137
|
-
end
|
|
138
99
|
|
|
139
|
-
|
|
140
|
-
return hash unless hash.is_a?(Hash)
|
|
141
|
-
|
|
142
|
-
hash.each_with_object({}) { |(key, value), out| out[key.to_sym] = value }
|
|
100
|
+
{ user: nested }
|
|
143
101
|
end
|
|
144
102
|
end
|
|
145
103
|
end
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module RelayGrid
|
|
4
|
+
module Resources
|
|
5
|
+
# Segments match recipients on their traits (and a few other fields) via a
|
|
6
|
+
# rules DSL, so a send can target a group instead of one recipient --
|
|
7
|
+
# `RelayGrid.client.broadcasts.create(segment: ..., template: ...)` is the
|
|
8
|
+
# send side.
|
|
9
|
+
#
|
|
10
|
+
# segment = client.segments.create(
|
|
11
|
+
# name: "Pro plan",
|
|
12
|
+
# rules: { all: [{ field: "traits.plan", op: "eq", value: "pro" }] }
|
|
13
|
+
# )
|
|
14
|
+
# client.segments.preview(rules: segment["rules"]) # => { "count" => 4210, "sample" => [...] }
|
|
15
|
+
#
|
|
16
|
+
# Rules are `{ all: [{ field:, op:, value: }, ...] }` -- every condition
|
|
17
|
+
# must match (AND-only, no nesting). Fields: `first_name`, `middle_name`,
|
|
18
|
+
# `last_name`, `created_at`, `channel`, `traits.<key>`. Ops: `eq`, `neq`,
|
|
19
|
+
# `contains`, `gt`, `lt`. `channel` only accepts `email`/`sms`.
|
|
20
|
+
#
|
|
21
|
+
# Segments match third-party recipients only; add `include_members: true`
|
|
22
|
+
# to the rules to also reach the account's own members (e.g. a
|
|
23
|
+
# service-outage announcement to the on-call person).
|
|
24
|
+
#
|
|
25
|
+
# An empty rules payload (`{}`) matches every recipient in the account --
|
|
26
|
+
# fine for drafting and for `preview`, but the server refuses to *send* to
|
|
27
|
+
# an unconditioned segment unless its rules carry `match_all: true`.
|
|
28
|
+
class Segments
|
|
29
|
+
PATH = "/api/v1/segments"
|
|
30
|
+
|
|
31
|
+
def initialize(client)
|
|
32
|
+
@client = client
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# @return [Array<Hash>] every segment in the account (rule counts only --
|
|
36
|
+
# see #get for a live recipient_count)
|
|
37
|
+
def list
|
|
38
|
+
Array(@client.get(PATH)["segments"])
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
# @param id [Integer]
|
|
42
|
+
# @return [Hash] the segment, including a live "recipient_count"
|
|
43
|
+
# @raise [RelayGrid::NotFoundError]
|
|
44
|
+
def get(id)
|
|
45
|
+
@client.get("#{PATH}/#{id}")["segment"]
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# @param name [String]
|
|
49
|
+
# @param rules [Hash] the rules DSL, e.g.
|
|
50
|
+
# `{ all: [{ field: "traits.plan", op: "eq", value: "pro" }] }`
|
|
51
|
+
# @return [Hash] the created segment
|
|
52
|
+
# @raise [RelayGrid::ValidationError] an invalid name or malformed/unknown rules
|
|
53
|
+
def create(name:, rules:)
|
|
54
|
+
@client.post(PATH, body: { segment: { name: name, rules: rules } })["segment"]
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# @return [Hash] the updated segment
|
|
58
|
+
def update(id, name: nil, rules: nil)
|
|
59
|
+
attributes = {}
|
|
60
|
+
attributes[:name] = name unless name.nil?
|
|
61
|
+
attributes[:rules] = rules unless rules.nil?
|
|
62
|
+
|
|
63
|
+
@client.patch("#{PATH}/#{id}", body: { segment: attributes })["segment"]
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# Soft-delete the segment.
|
|
67
|
+
#
|
|
68
|
+
# @return [true]
|
|
69
|
+
def delete(id)
|
|
70
|
+
@client.delete("#{PATH}/#{id}")
|
|
71
|
+
true
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# Count and sample the recipients rules would match, without saving a
|
|
75
|
+
# segment -- what a rule-builder UI calls as the caller edits conditions.
|
|
76
|
+
#
|
|
77
|
+
# @param rules [Hash] the rules DSL
|
|
78
|
+
# @return [Hash] `{ "count" => Integer, "sample" => Array<Hash> }` (sample
|
|
79
|
+
# limited to 5 recipients)
|
|
80
|
+
# @raise [RelayGrid::ValidationError] malformed or unknown rules
|
|
81
|
+
def preview(rules:)
|
|
82
|
+
@client.post("#{PATH}/preview", body: { rules: rules })
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
end
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "date"
|
|
4
|
+
require "time"
|
|
5
|
+
|
|
6
|
+
module RelayGrid
|
|
7
|
+
module Resources
|
|
8
|
+
# The payload pieces a single-recipient send and a broadcast build the
|
|
9
|
+
# same way: template attributes as name/value pairs, and a `scheduled_at`
|
|
10
|
+
# serialized so the server can always parse it.
|
|
11
|
+
module SendPayload
|
|
12
|
+
private
|
|
13
|
+
|
|
14
|
+
# A `Date` has a day but no instant, so there's no correct offset to emit
|
|
15
|
+
# -- `DateTime` (which `Date` is a superclass of) is fine, only a bare
|
|
16
|
+
# `Date` is rejected. Everything else that responds to `iso8601` (`Time`,
|
|
17
|
+
# `DateTime`, `ActiveSupport::TimeWithZone`) is serialized with it; a
|
|
18
|
+
# `String` passes through for the server to validate.
|
|
19
|
+
def serialize_scheduled_at(value)
|
|
20
|
+
return value if value.is_a?(String)
|
|
21
|
+
|
|
22
|
+
if value.is_a?(Date) && !value.is_a?(DateTime)
|
|
23
|
+
raise ArgumentError, "scheduled_at must be a Time, DateTime, or TimeWithZone -- " \
|
|
24
|
+
"a Date has no instant, so there is no offset to serialize"
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
unless value.respond_to?(:iso8601)
|
|
28
|
+
raise ArgumentError, "scheduled_at must be a Time, DateTime, TimeWithZone, or ISO 8601 String"
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
value.iso8601
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# The API takes attributes as [{ name:, value: }], which is awkward to
|
|
35
|
+
# write by hand, so a plain Hash is accepted and converted.
|
|
36
|
+
def format_attributes(attributes)
|
|
37
|
+
return [] if attributes.nil? || attributes.empty?
|
|
38
|
+
|
|
39
|
+
case attributes
|
|
40
|
+
when Hash
|
|
41
|
+
attributes.map { |name, value| { name: name.to_s, value: value.to_s } }
|
|
42
|
+
when Array
|
|
43
|
+
attributes.map do |attribute|
|
|
44
|
+
attribute = normalize_keys(attribute)
|
|
45
|
+
unless attribute.is_a?(Hash) && attribute.key?(:name)
|
|
46
|
+
raise ArgumentError, "array attributes must be hashes with a :name key"
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
{ name: attribute[:name].to_s, value: attribute[:value].to_s }
|
|
50
|
+
end
|
|
51
|
+
else
|
|
52
|
+
raise ArgumentError, "attributes must be a Hash or an Array of {name:, value:} hashes"
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def normalize_keys(hash)
|
|
57
|
+
return hash unless hash.is_a?(Hash)
|
|
58
|
+
|
|
59
|
+
hash.each_with_object({}) { |(key, value), out| out[key.to_sym] = value }
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
end
|
|
63
|
+
end
|
|
@@ -26,11 +26,17 @@ module RelayGrid
|
|
|
26
26
|
|
|
27
27
|
# Create the recipient, or update their names if they already exist.
|
|
28
28
|
#
|
|
29
|
+
# @param traits [Hash, nil] free-form targeting data segment rules
|
|
30
|
+
# (`traits.<key>`) match against. Sent here it *replaces* the
|
|
31
|
+
# recipient's whole traits document; the shallow-merge semantic (where
|
|
32
|
+
# a nil value deletes one key) belongs to the nested `user:` payload on
|
|
33
|
+
# `notify`, not to this endpoint.
|
|
29
34
|
# @return [Hash] the notification user
|
|
30
|
-
def upsert(id:, first_name:, last_name:, middle_name: nil)
|
|
35
|
+
def upsert(id:, first_name:, last_name:, middle_name: nil, traits: nil)
|
|
31
36
|
existing = get(id)
|
|
32
37
|
attributes = { first_name: first_name, last_name: last_name }
|
|
33
38
|
attributes[:middle_name] = middle_name unless middle_name.nil?
|
|
39
|
+
attributes[:traits] = traits unless traits.nil?
|
|
34
40
|
|
|
35
41
|
if existing
|
|
36
42
|
body = @client.patch(
|
|
@@ -36,8 +36,10 @@ module RelayGrid
|
|
|
36
36
|
deliveries.map(&:id)
|
|
37
37
|
end
|
|
38
38
|
|
|
39
|
-
# True when the template dispatched over a push channel
|
|
40
|
-
#
|
|
39
|
+
# True when the template dispatched over a push channel and `push_token` came
|
|
40
|
+
# back, so it is worth handing down to the recipient's device. Also false when
|
|
41
|
+
# the template is a push one but the API key lacks the `recipients:token`
|
|
42
|
+
# permission, because the server withholds the token.
|
|
41
43
|
def push?
|
|
42
44
|
!push_token.nil?
|
|
43
45
|
end
|
data/lib/relaygrid/version.rb
CHANGED
data/lib/relaygrid.rb
CHANGED
|
@@ -9,6 +9,7 @@ require_relative "relaygrid/send_result"
|
|
|
9
9
|
require_relative "relaygrid/client"
|
|
10
10
|
require_relative "relaygrid/webhooks"
|
|
11
11
|
require_relative "relaygrid/websocket_client"
|
|
12
|
+
require_relative "relaygrid/resources/send_payload"
|
|
12
13
|
require_relative "relaygrid/resources/notifications"
|
|
13
14
|
require_relative "relaygrid/resources/deliveries"
|
|
14
15
|
require_relative "relaygrid/resources/messages"
|
|
@@ -16,6 +17,8 @@ require_relative "relaygrid/resources/message_templates"
|
|
|
16
17
|
require_relative "relaygrid/resources/users"
|
|
17
18
|
require_relative "relaygrid/resources/channel_tokens"
|
|
18
19
|
require_relative "relaygrid/resources/webhook_endpoints"
|
|
20
|
+
require_relative "relaygrid/resources/segments"
|
|
21
|
+
require_relative "relaygrid/resources/broadcasts"
|
|
19
22
|
|
|
20
23
|
# Ruby client for the RelayGrid / RelayGrid notification API.
|
|
21
24
|
#
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: relaygrid
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.4.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Ali Zand
|
|
@@ -155,11 +155,14 @@ files:
|
|
|
155
155
|
- lib/relaygrid/delivery.rb
|
|
156
156
|
- lib/relaygrid/errors.rb
|
|
157
157
|
- lib/relaygrid/event.rb
|
|
158
|
+
- lib/relaygrid/resources/broadcasts.rb
|
|
158
159
|
- lib/relaygrid/resources/channel_tokens.rb
|
|
159
160
|
- lib/relaygrid/resources/deliveries.rb
|
|
160
161
|
- lib/relaygrid/resources/message_templates.rb
|
|
161
162
|
- lib/relaygrid/resources/messages.rb
|
|
162
163
|
- lib/relaygrid/resources/notifications.rb
|
|
164
|
+
- lib/relaygrid/resources/segments.rb
|
|
165
|
+
- lib/relaygrid/resources/send_payload.rb
|
|
163
166
|
- lib/relaygrid/resources/users.rb
|
|
164
167
|
- lib/relaygrid/resources/webhook_endpoints.rb
|
|
165
168
|
- lib/relaygrid/send_result.rb
|
|
@@ -189,7 +192,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
|
|
|
189
192
|
- !ruby/object:Gem::Version
|
|
190
193
|
version: '0'
|
|
191
194
|
requirements: []
|
|
192
|
-
rubygems_version: 4.0.
|
|
195
|
+
rubygems_version: 4.0.20
|
|
193
196
|
specification_version: 4
|
|
194
197
|
summary: Ruby client for the RelayGrid notification API
|
|
195
198
|
test_files: []
|