relaygrid 0.2.1 → 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 +65 -0
- data/QUICKSTART.md +31 -1
- data/README.md +180 -4
- data/lib/relaygrid/client.rb +11 -1
- data/lib/relaygrid/delivery.rb +15 -2
- data/lib/relaygrid/errors.rb +16 -2
- data/lib/relaygrid/resources/broadcasts.rb +84 -0
- data/lib/relaygrid/resources/messages.rb +12 -0
- data/lib/relaygrid/resources/notifications.rb +33 -37
- 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 +31 -4
- data/lib/relaygrid/version.rb +1 -1
- data/lib/relaygrid.rb +3 -0
- metadata +19 -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,71 @@ 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
|
+
|
|
48
|
+
## [0.3.0] - 2026-08-26
|
|
49
|
+
|
|
50
|
+
### Added
|
|
51
|
+
|
|
52
|
+
- **Scheduled deliveries.** `notify` accepts `scheduled_at:` to deliver later
|
|
53
|
+
instead of immediately. A `Time`, `DateTime`, or `ActiveSupport::TimeWithZone`
|
|
54
|
+
is serialized with `.iso8601`, which always emits a UTC offset; a `String` is
|
|
55
|
+
passed through untouched for the server to validate. **The server requires an
|
|
56
|
+
explicit UTC offset and returns a 422 on a naive or malformed timestamp** —
|
|
57
|
+
it never assumes a timezone, so a client that serializes naively would
|
|
58
|
+
otherwise turn into a 422 the caller can't diagnose. A bare `Date` raises
|
|
59
|
+
`ArgumentError` locally, since a date has no instant.
|
|
60
|
+
- `messages.cancel_schedule(id)` withdraws a scheduled send before it
|
|
61
|
+
dispatches (`DELETE /api/v1/messages/:id/schedule`). Raises `ValidationError`
|
|
62
|
+
if the message has already dispatched or been canceled.
|
|
63
|
+
- `SendResult#scheduled?` and `#scheduled_at`, read off the created message.
|
|
64
|
+
- **`wait_for_deliveries` returns immediately for a scheduled send**, without
|
|
65
|
+
polling. A `scheduled` delivery is never terminal — nothing has been handed
|
|
66
|
+
to a provider yet — so without this a caller who scheduled and then waited
|
|
67
|
+
would block for the full `timeout`.
|
|
68
|
+
- Note for integrators: a `201` at schedule time is not a delivery guarantee.
|
|
69
|
+
A scheduled send can still end in `delivery.failed` if the account's
|
|
70
|
+
monthly quota is spent by dispatch time. `push?`/`push_token` are unaffected
|
|
71
|
+
by scheduling — the token is for the device to subscribe now, independent
|
|
72
|
+
of when the message dispatches, because the server reads the template's
|
|
73
|
+
live channels rather than the deliveries.
|
|
74
|
+
|
|
10
75
|
## [0.2.1] - 2026-08-21
|
|
11
76
|
|
|
12
77
|
### Fixed
|
data/QUICKSTART.md
CHANGED
|
@@ -74,6 +74,33 @@ them when you want status. Don't block a web request waiting — see
|
|
|
74
74
|
`wait_for_deliveries` in the README for when that helper is and isn't
|
|
75
75
|
appropriate.
|
|
76
76
|
|
|
77
|
+
## 6a. Schedule for later (optional)
|
|
78
|
+
|
|
79
|
+
Pass `scheduled_at` instead of sending immediately:
|
|
80
|
+
|
|
81
|
+
```ruby
|
|
82
|
+
RelayGrid.client.notify(
|
|
83
|
+
user: current_user.id, template: "order_shipped",
|
|
84
|
+
scheduled_at: Time.now + 1.day # or an ISO 8601 String like "2026-09-01T09:00:00-07:00"
|
|
85
|
+
)
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
**The timestamp must carry an explicit UTC offset.** A `Time`/`DateTime`/
|
|
89
|
+
`ActiveSupport::TimeWithZone` is serialized with `.iso8601` for you, which
|
|
90
|
+
always includes one; a naive `String` (no offset) is rejected by the server
|
|
91
|
+
with a 422 rather than assumed to mean UTC. A bare `Date` raises
|
|
92
|
+
`ArgumentError` locally — it has no instant to schedule.
|
|
93
|
+
|
|
94
|
+
A `201` here means the schedule was accepted, not that the message will
|
|
95
|
+
successfully send: a scheduled delivery can still end in `delivery.failed`
|
|
96
|
+
if the account's quota is spent by dispatch time. Withdraw it beforehand with:
|
|
97
|
+
|
|
98
|
+
```ruby
|
|
99
|
+
RelayGrid.client.messages.cancel_schedule(result.message_id)
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
See the [README](README.md#scheduling-a-send) for the full behavior.
|
|
103
|
+
|
|
77
104
|
## 7. Receive (optional)
|
|
78
105
|
|
|
79
106
|
If your template has a push channel, the send hands you a token for the
|
|
@@ -99,11 +126,14 @@ ws.connect
|
|
|
99
126
|
|---|---|
|
|
100
127
|
| `ConfigurationError: api_key is required` | `RELAYGRID_API_KEY` isn't set in this environment. |
|
|
101
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`. |
|
|
102
130
|
| `TemplateNotFoundError` | Template name doesn't match, or the template is soft-deleted. |
|
|
103
131
|
| `LimitExceededError` | Monthly notification limit spent — check Usage in the dashboard. |
|
|
104
|
-
| `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`. |
|
|
105
133
|
| Delivery stuck at `queued` | The delivery job hasn't run yet; poll again shortly. |
|
|
106
134
|
| Delivery `failed` | Read `delivery.friendly_error_message` — usually channel credentials. |
|
|
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. |
|
|
136
|
+
| A scheduled send ends in `delivery.failed` | Quota was spent between scheduling and dispatch. The `201` at schedule time isn't a delivery guarantee. |
|
|
107
137
|
|
|
108
138
|
## Next steps
|
|
109
139
|
|
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
|
|
@@ -123,8 +153,53 @@ result.rendered_subject # => "Hi Ada"
|
|
|
123
153
|
result.push_token # => "eyJf..." or nil
|
|
124
154
|
result.push_token_expires_at # => 2026-07-28 11:00:00 +0000
|
|
125
155
|
result.push? # => true when a push channel was dispatched
|
|
156
|
+
result.scheduled? # => true when scheduled_at was set
|
|
157
|
+
result.scheduled_at # => 2026-09-01 16:00:00 +0000, or nil for an immediate send
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
### Scheduling a send
|
|
161
|
+
|
|
162
|
+
Pass `scheduled_at` to deliver later instead of immediately:
|
|
163
|
+
|
|
164
|
+
```ruby
|
|
165
|
+
RelayGrid.client.notify(
|
|
166
|
+
user: "user-123", template: "order_shipped",
|
|
167
|
+
scheduled_at: Time.now + 3600 # or a DateTime, an ActiveSupport::TimeWithZone, or an ISO 8601 String
|
|
168
|
+
)
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
A `Time`, `DateTime`, or `ActiveSupport::TimeWithZone` is serialized with
|
|
172
|
+
`.iso8601`, which always emits a UTC offset. A `String` is passed through
|
|
173
|
+
untouched for the server to validate. **The server requires an explicit UTC
|
|
174
|
+
offset and returns a 422 (`RelayGrid::ValidationError`) on a naive or
|
|
175
|
+
malformed timestamp** — it never guesses what timezone you meant, so
|
|
176
|
+
`"2026-09-01T09:00:00"` (no offset) is rejected rather than silently treated
|
|
177
|
+
as UTC. A bare `Date` raises `ArgumentError` locally, before any request is
|
|
178
|
+
made — a date has no instant, so there's no correct offset to send.
|
|
179
|
+
|
|
180
|
+
The message is created immediately with status-`scheduled` deliveries, and
|
|
181
|
+
returns a `201` right away; nothing has reached a channel provider yet. A
|
|
182
|
+
scheduled send can still end in `delivery.failed` at dispatch time if the
|
|
183
|
+
account's monthly quota is spent by then — the `201` at schedule time is not
|
|
184
|
+
a guarantee of delivery, only that the schedule was accepted.
|
|
185
|
+
|
|
186
|
+
The push token, when present, is unaffected by scheduling: it authenticates
|
|
187
|
+
the recipient's device to subscribe *now*, independent of when the message
|
|
188
|
+
actually dispatches. `push?`/`push_token` work exactly as they do for an
|
|
189
|
+
immediate send, because the server reads the template's live channels, not
|
|
190
|
+
the deliveries.
|
|
191
|
+
|
|
192
|
+
Withdraw a scheduled send before it dispatches:
|
|
193
|
+
|
|
194
|
+
```ruby
|
|
195
|
+
RelayGrid.client.messages.cancel_schedule(message_id)
|
|
126
196
|
```
|
|
127
197
|
|
|
198
|
+
Only pending messages can be withdrawn. Once dispatch has claimed the row,
|
|
199
|
+
sends may already be going out, and the call raises `ValidationError` (422) —
|
|
200
|
+
there is a small window where a well-timed cancel can lose the race to the
|
|
201
|
+
dispatch sweep.
|
|
202
|
+
|
|
128
203
|
### The push token
|
|
129
204
|
|
|
130
205
|
When the template has a live push channel, the send response carries a token
|
|
@@ -137,6 +212,97 @@ RelayGrid.client.channel_tokens.create(user_id: "user-123")
|
|
|
137
212
|
# => { token: "eyJf...", expires_in: 3600, expires_at: 2026-07-28 11:00:00 +0000 }
|
|
138
213
|
```
|
|
139
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
|
+
|
|
140
306
|
## Checking delivery status
|
|
141
307
|
|
|
142
308
|
```ruby
|
|
@@ -165,6 +331,12 @@ It returns once every delivery is **terminal** — successful or not — so chec
|
|
|
165
331
|
`success?` yourself rather than treating a return as a win. A delivery the server
|
|
166
332
|
is still retrying reads `retrying`, which is why `failed` means final.
|
|
167
333
|
|
|
334
|
+
For a scheduled send (`result.scheduled?`), this returns `deliveries`
|
|
335
|
+
immediately — still reading `status: "scheduled"` — instead of polling. A
|
|
336
|
+
`scheduled` delivery is never terminal, since nothing has been handed to a
|
|
337
|
+
provider yet, so polling it would otherwise just block for the full `timeout`
|
|
338
|
+
waiting on a state change that isn't coming until dispatch.
|
|
339
|
+
|
|
168
340
|
> **This blocks the calling thread.** Use it in a background job, a rake task, or
|
|
169
341
|
> a script — never inside a web request, where it would pin a request thread for
|
|
170
342
|
> up to `timeout` seconds. In a request, return `delivery_ids` and let the
|
|
@@ -262,7 +434,8 @@ suffices. Faraday exceptions never escape the gem.
|
|
|
262
434
|
| `ConnectionError` | The request never produced a response |
|
|
263
435
|
| `TimeoutError` | A timeout (subclass of `ConnectionError`) |
|
|
264
436
|
| `AuthenticationError` | 401/403 — key invalid, inactive, expired, or account suspended |
|
|
265
|
-
| `
|
|
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`) |
|
|
266
439
|
| `NotFoundError` | 404 |
|
|
267
440
|
| `TemplateNotFoundError` | 404 naming a template (subclass of `NotFoundError`) |
|
|
268
441
|
| `UserNotFoundError` | 404 naming a recipient (subclass of `NotFoundError`) |
|
|
@@ -278,6 +451,8 @@ begin
|
|
|
278
451
|
RelayGrid.client.notify(user: user, template: "order_shipped")
|
|
279
452
|
rescue RelayGrid::LimitExceededError
|
|
280
453
|
# out of notifications this month
|
|
454
|
+
rescue RelayGrid::PermissionDeniedError => e
|
|
455
|
+
Rails.logger.error("API key lacks #{e.permission}")
|
|
281
456
|
rescue RelayGrid::TemplateNotFoundError => e
|
|
282
457
|
Rails.logger.error(e.error_message)
|
|
283
458
|
end
|
|
@@ -289,9 +464,10 @@ GETs retry automatically (3 attempts by default, jittered exponential backoff)
|
|
|
289
464
|
on 429, 5xx, and transport failures.
|
|
290
465
|
|
|
291
466
|
**`notify` is never retried.** A blind retry would send the recipient a second
|
|
292
|
-
real notification.
|
|
293
|
-
|
|
294
|
-
|
|
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.
|
|
295
471
|
|
|
296
472
|
## Development
|
|
297
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/delivery.rb
CHANGED
|
@@ -15,11 +15,16 @@ module RelayGrid
|
|
|
15
15
|
FAILED = "failed"
|
|
16
16
|
BOUNCED = "bounced"
|
|
17
17
|
OPENED = "opened"
|
|
18
|
+
SCHEDULED = "scheduled"
|
|
19
|
+
CANCELED = "canceled"
|
|
18
20
|
|
|
19
21
|
SUCCESS_STATUSES = [DELIVERED, OPENED].freeze
|
|
20
22
|
|
|
21
|
-
# States the server will not move away from on its own.
|
|
22
|
-
|
|
23
|
+
# States the server will not move away from on its own. `scheduled` is
|
|
24
|
+
# deliberately absent -- only the sweep moves it, which can be well past
|
|
25
|
+
# any reasonable poll timeout. `canceled` is terminal; the server never
|
|
26
|
+
# revives a canceled delivery.
|
|
27
|
+
TERMINAL_STATUSES = (SUCCESS_STATUSES + [FAILED, BOUNCED, CANCELED]).freeze
|
|
23
28
|
|
|
24
29
|
attr_reader :id, :message_id, :status, :channel_id, :channel_name, :channel_type,
|
|
25
30
|
:error_message, :friendly_error_message,
|
|
@@ -79,6 +84,14 @@ module RelayGrid
|
|
|
79
84
|
status == OPENED
|
|
80
85
|
end
|
|
81
86
|
|
|
87
|
+
def scheduled?
|
|
88
|
+
status == SCHEDULED
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
def canceled?
|
|
92
|
+
status == CANCELED
|
|
93
|
+
end
|
|
94
|
+
|
|
82
95
|
# Reached a state the server considers final and successful.
|
|
83
96
|
def success?
|
|
84
97
|
SUCCESS_STATUSES.include?(status)
|
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
|
|
@@ -58,6 +58,18 @@ module RelayGrid
|
|
|
58
58
|
def render(id)
|
|
59
59
|
@client.get("/api/v1/messages/#{id}/render_message")
|
|
60
60
|
end
|
|
61
|
+
|
|
62
|
+
# Withdraw a scheduled send before it dispatches. Only pending messages
|
|
63
|
+
# can be withdrawn -- once dispatch has claimed the row, channel sends
|
|
64
|
+
# may already be going out, and there's nothing left to cancel.
|
|
65
|
+
#
|
|
66
|
+
# @return [Hash] the message, with `schedule_canceled_reason: "requested"`
|
|
67
|
+
# @raise [RelayGrid::ValidationError] the message already dispatched or
|
|
68
|
+
# was already canceled (the sweep won the race)
|
|
69
|
+
# @raise [RelayGrid::NotFoundError] no such message
|
|
70
|
+
def cancel_schedule(id)
|
|
71
|
+
@client.delete("/api/v1/messages/#{id}/schedule")["message"]
|
|
72
|
+
end
|
|
61
73
|
end
|
|
62
74
|
end
|
|
63
75
|
end
|
|
@@ -5,9 +5,11 @@ module RelayGrid
|
|
|
5
5
|
# Sending. The developer contract the gem exists for: a user, a template
|
|
6
6
|
# name, and the attributes the template needs.
|
|
7
7
|
class Notifications
|
|
8
|
+
include SendPayload
|
|
9
|
+
|
|
8
10
|
# Recipient details a send may carry alongside the id. `email` becomes the
|
|
9
11
|
# contact email deliveries resolve their recipient through.
|
|
10
|
-
RECIPIENT_ATTRIBUTES = %i[first_name middle_name last_name email].freeze
|
|
12
|
+
RECIPIENT_ATTRIBUTES = %i[first_name middle_name last_name email traits].freeze
|
|
11
13
|
|
|
12
14
|
def initialize(client)
|
|
13
15
|
@client = client
|
|
@@ -16,23 +18,35 @@ module RelayGrid
|
|
|
16
18
|
# Send a notification, creating or updating the recipient on the way.
|
|
17
19
|
#
|
|
18
20
|
# @param user [Hash] `{ id:, first_name:, last_name:, middle_name:,
|
|
19
|
-
# email: }`. `id` is the *your-system* identifier -- it maps to
|
|
20
|
-
# `external_user_id`. RelayGrid's internal ids are never
|
|
21
|
-
# May also be a bare String/Integer id for a recipient
|
|
22
|
-
# 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.
|
|
23
25
|
#
|
|
24
26
|
# `email` is optional but load-bearing: email deliveries resolve their
|
|
25
27
|
# recipient through the contact stored for that channel type, so a send
|
|
26
28
|
# over an email channel for a user with no email on file produces a
|
|
27
29
|
# delivery that fails with "no contact on file". Push needs no contact.
|
|
28
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.
|
|
29
35
|
# @param template [String] the message template's name
|
|
30
36
|
# @param attributes [Hash] values for the template's `{{placeholders}}`
|
|
37
|
+
# @param scheduled_at [Time, DateTime, ActiveSupport::TimeWithZone, String, nil]
|
|
38
|
+
# when to deliver instead of immediately. A `Time`/`DateTime`/`TimeWithZone`
|
|
39
|
+
# is serialized with `.iso8601`, which always emits a UTC offset; a
|
|
40
|
+
# `String` is passed through untouched for the server to validate. The
|
|
41
|
+
# server rejects a naive or malformed timestamp with a 422 -- it never
|
|
42
|
+
# guesses a timezone. `nil` (the default) sends immediately.
|
|
31
43
|
# @return [RelayGrid::SendResult]
|
|
32
44
|
#
|
|
33
45
|
# @raise [RelayGrid::TemplateNotFoundError] no such template in the account
|
|
34
46
|
# @raise [RelayGrid::LimitExceededError] the monthly notification limit is spent
|
|
35
|
-
# @raise [RelayGrid::ValidationError] the payload was rejected
|
|
47
|
+
# @raise [RelayGrid::ValidationError] the payload was rejected, e.g. a
|
|
48
|
+
# `scheduled_at` with no UTC offset
|
|
49
|
+
# @raise [ArgumentError] `scheduled_at` is a bare `Date`, which has no instant
|
|
36
50
|
#
|
|
37
51
|
# @example
|
|
38
52
|
# result = RelayGrid.client.notify(
|
|
@@ -41,14 +55,22 @@ module RelayGrid
|
|
|
41
55
|
# attributes: { order_number: "1042", eta: "tomorrow" }
|
|
42
56
|
# )
|
|
43
57
|
# result.delivery_ids # => [201, 202]
|
|
44
|
-
|
|
58
|
+
#
|
|
59
|
+
# @example Scheduling a send
|
|
60
|
+
# RelayGrid.client.notify(
|
|
61
|
+
# user: "user-123", template: "order_shipped",
|
|
62
|
+
# scheduled_at: Time.now + 3600 # or "2026-09-01T09:00:00-07:00"
|
|
63
|
+
# )
|
|
64
|
+
def notify(user:, template:, attributes: {}, scheduled_at: nil)
|
|
45
65
|
message = {
|
|
46
66
|
message_template_name: template.to_s,
|
|
47
67
|
message_attributes_attributes: format_attributes(attributes),
|
|
48
68
|
}
|
|
49
69
|
message.merge!(recipient_params(user))
|
|
70
|
+
message[:scheduled_at] = serialize_scheduled_at(scheduled_at) unless scheduled_at.nil?
|
|
50
71
|
|
|
51
|
-
|
|
72
|
+
response = @client.post("/api/v1/messages", body: { message: message })
|
|
73
|
+
SendResult.new(response, client: @client)
|
|
52
74
|
end
|
|
53
75
|
|
|
54
76
|
private
|
|
@@ -70,38 +92,12 @@ module RelayGrid
|
|
|
70
92
|
# anything absent untouched, so omitting a name doesn't blank it out and
|
|
71
93
|
# omitting an email doesn't drop the contact.
|
|
72
94
|
RECIPIENT_ATTRIBUTES.each do |name|
|
|
73
|
-
|
|
74
|
-
end
|
|
95
|
+
next if user[name].nil?
|
|
75
96
|
|
|
76
|
-
|
|
77
|
-
end
|
|
78
|
-
|
|
79
|
-
# The API takes attributes as [{ name:, value: }], which is awkward to
|
|
80
|
-
# write by hand, so a plain Hash is accepted and converted.
|
|
81
|
-
def format_attributes(attributes)
|
|
82
|
-
return [] if attributes.nil? || attributes.empty?
|
|
83
|
-
|
|
84
|
-
case attributes
|
|
85
|
-
when Hash
|
|
86
|
-
attributes.map { |name, value| { name: name.to_s, value: value.to_s } }
|
|
87
|
-
when Array
|
|
88
|
-
attributes.map do |attribute|
|
|
89
|
-
attribute = normalize_keys(attribute)
|
|
90
|
-
unless attribute.is_a?(Hash) && attribute.key?(:name)
|
|
91
|
-
raise ArgumentError, "array attributes must be hashes with a :name key"
|
|
92
|
-
end
|
|
93
|
-
|
|
94
|
-
{ name: attribute[:name].to_s, value: attribute[:value].to_s }
|
|
95
|
-
end
|
|
96
|
-
else
|
|
97
|
-
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
|
|
98
98
|
end
|
|
99
|
-
end
|
|
100
|
-
|
|
101
|
-
def normalize_keys(hash)
|
|
102
|
-
return hash unless hash.is_a?(Hash)
|
|
103
99
|
|
|
104
|
-
|
|
100
|
+
{ user: nested }
|
|
105
101
|
end
|
|
106
102
|
end
|
|
107
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(
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require "time"
|
|
4
|
+
|
|
3
5
|
module RelayGrid
|
|
4
6
|
# What `RelayGrid.client.notify` hands back: the message that was created, the
|
|
5
7
|
# deliveries queued for it, and -- when the template has a live push channel
|
|
@@ -7,7 +9,7 @@ module RelayGrid
|
|
|
7
9
|
# realtime channel.
|
|
8
10
|
class SendResult
|
|
9
11
|
attr_reader :message_id, :push_token, :push_token_expires_at, :deliveries,
|
|
10
|
-
:rendered_subject, :rendered_body, :raw
|
|
12
|
+
:rendered_subject, :rendered_body, :scheduled_at, :raw
|
|
11
13
|
|
|
12
14
|
def initialize(body, client:)
|
|
13
15
|
@raw = body
|
|
@@ -17,6 +19,7 @@ module RelayGrid
|
|
|
17
19
|
@message_id = message["id"]
|
|
18
20
|
@rendered_subject = message["rendered_subject"]
|
|
19
21
|
@rendered_body = message["rendered_body"]
|
|
22
|
+
@scheduled_at = parse_time(message["scheduled_at"])
|
|
20
23
|
|
|
21
24
|
@push_token = body["push_token"]
|
|
22
25
|
expires_in = body["push_token_expires_in"]
|
|
@@ -33,8 +36,10 @@ module RelayGrid
|
|
|
33
36
|
deliveries.map(&:id)
|
|
34
37
|
end
|
|
35
38
|
|
|
36
|
-
# True when the template dispatched over a push channel
|
|
37
|
-
#
|
|
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.
|
|
38
43
|
def push?
|
|
39
44
|
!push_token.nil?
|
|
40
45
|
end
|
|
@@ -43,16 +48,28 @@ module RelayGrid
|
|
|
43
48
|
deliveries.find { |delivery| delivery.channel_type == channel_type.to_s }
|
|
44
49
|
end
|
|
45
50
|
|
|
51
|
+
# True when this send was scheduled for later rather than sent immediately.
|
|
52
|
+
def scheduled?
|
|
53
|
+
!scheduled_at.nil?
|
|
54
|
+
end
|
|
55
|
+
|
|
46
56
|
# Poll until every delivery reaches a terminal state, or `timeout` seconds
|
|
47
57
|
# elapse. A delivery the server is still retrying reads `retrying`.
|
|
48
58
|
#
|
|
59
|
+
# A `scheduled` delivery is never terminal -- nothing has been handed to a
|
|
60
|
+
# provider yet, so there is nothing to settle -- and polling it would just
|
|
61
|
+
# burn the full `timeout` waiting for a state change that isn't coming
|
|
62
|
+
# until dispatch. When `scheduled?` is true, this returns `deliveries`
|
|
63
|
+
# (each still reading `status: "scheduled"`) immediately without calling
|
|
64
|
+
# the API at all.
|
|
65
|
+
#
|
|
49
66
|
# @param timeout [Numeric] seconds to keep polling
|
|
50
67
|
# @param interval [Numeric] seconds between polls
|
|
51
68
|
# @param raise_on_timeout [Boolean] raise TimeoutWaitingForDeliveries
|
|
52
69
|
# instead of returning the last-seen deliveries
|
|
53
70
|
# @return [Array<RelayGrid::Delivery>] deliveries as last seen
|
|
54
71
|
def wait_for_deliveries(timeout: 30, interval: 2, raise_on_timeout: false)
|
|
55
|
-
return deliveries if deliveries.empty?
|
|
72
|
+
return deliveries if deliveries.empty? || scheduled?
|
|
56
73
|
|
|
57
74
|
@client.deliveries.wait_for(
|
|
58
75
|
delivery_ids,
|
|
@@ -70,5 +87,15 @@ module RelayGrid
|
|
|
70
87
|
"#<RelayGrid::SendResult message_id: #{message_id.inspect}, " \
|
|
71
88
|
"delivery_ids: #{delivery_ids.inspect}, push: #{push?}>"
|
|
72
89
|
end
|
|
90
|
+
|
|
91
|
+
private
|
|
92
|
+
|
|
93
|
+
def parse_time(value)
|
|
94
|
+
return nil if value.nil? || value.to_s.empty?
|
|
95
|
+
|
|
96
|
+
Time.parse(value.to_s)
|
|
97
|
+
rescue ArgumentError
|
|
98
|
+
nil
|
|
99
|
+
end
|
|
73
100
|
end
|
|
74
101
|
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
|
|
@@ -51,6 +51,20 @@ dependencies:
|
|
|
51
51
|
- - "~>"
|
|
52
52
|
- !ruby/object:Gem::Version
|
|
53
53
|
version: '0.6'
|
|
54
|
+
- !ruby/object:Gem::Dependency
|
|
55
|
+
name: activesupport
|
|
56
|
+
requirement: !ruby/object:Gem::Requirement
|
|
57
|
+
requirements:
|
|
58
|
+
- - ">="
|
|
59
|
+
- !ruby/object:Gem::Version
|
|
60
|
+
version: '7.1'
|
|
61
|
+
type: :development
|
|
62
|
+
prerelease: false
|
|
63
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
64
|
+
requirements:
|
|
65
|
+
- - ">="
|
|
66
|
+
- !ruby/object:Gem::Version
|
|
67
|
+
version: '7.1'
|
|
54
68
|
- !ruby/object:Gem::Dependency
|
|
55
69
|
name: rspec
|
|
56
70
|
requirement: !ruby/object:Gem::Requirement
|
|
@@ -141,11 +155,14 @@ files:
|
|
|
141
155
|
- lib/relaygrid/delivery.rb
|
|
142
156
|
- lib/relaygrid/errors.rb
|
|
143
157
|
- lib/relaygrid/event.rb
|
|
158
|
+
- lib/relaygrid/resources/broadcasts.rb
|
|
144
159
|
- lib/relaygrid/resources/channel_tokens.rb
|
|
145
160
|
- lib/relaygrid/resources/deliveries.rb
|
|
146
161
|
- lib/relaygrid/resources/message_templates.rb
|
|
147
162
|
- lib/relaygrid/resources/messages.rb
|
|
148
163
|
- lib/relaygrid/resources/notifications.rb
|
|
164
|
+
- lib/relaygrid/resources/segments.rb
|
|
165
|
+
- lib/relaygrid/resources/send_payload.rb
|
|
149
166
|
- lib/relaygrid/resources/users.rb
|
|
150
167
|
- lib/relaygrid/resources/webhook_endpoints.rb
|
|
151
168
|
- lib/relaygrid/send_result.rb
|
|
@@ -175,7 +192,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
|
|
|
175
192
|
- !ruby/object:Gem::Version
|
|
176
193
|
version: '0'
|
|
177
194
|
requirements: []
|
|
178
|
-
rubygems_version: 4.0.
|
|
195
|
+
rubygems_version: 4.0.20
|
|
179
196
|
specification_version: 4
|
|
180
197
|
summary: Ruby client for the RelayGrid notification API
|
|
181
198
|
test_files: []
|