poli-page 0.9.1 → 0.13.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 +298 -1
- data/MIGRATION.md +258 -6
- data/README.md +139 -79
- data/SECURITY.md +4 -2
- data/lib/poli_page/client.rb +34 -16
- data/lib/poli_page/documents.rb +36 -66
- data/lib/poli_page/errors.rb +139 -51
- data/lib/poli_page/inputs/render_input.rb +39 -0
- data/lib/poli_page/inputs/thumbnail_options.rb +7 -4
- data/lib/poli_page/internal/constants.rb +22 -1
- data/lib/poli_page/internal/http.rb +44 -26
- data/lib/poli_page/internal/presigned_fetch.rb +119 -43
- data/lib/poli_page/internal/transport.rb +145 -34
- data/lib/poli_page/internal/uuid.rb +1 -1
- data/lib/poli_page/internal/watchdog.rb +70 -0
- data/lib/poli_page/internal/wire.rb +30 -24
- data/lib/poli_page/models/document_descriptor.rb +21 -4
- data/lib/poli_page/models/document_preview_result.rb +3 -4
- data/lib/poli_page/models/page_format.rb +4 -3
- data/lib/poli_page/render.rb +46 -80
- data/lib/poli_page/render_to_file.rb +97 -21
- data/lib/poli_page/retry_event.rb +1 -1
- data/lib/poli_page/version.rb +1 -1
- data/lib/poli_page.rb +1 -3
- data/sig/poli_page/errors.rbs +40 -18
- data/sig/poli_page/models.rbs +8 -29
- data/sig/poli_page/render.rbs +4 -10
- metadata +3 -4
- data/lib/poli_page/inputs/inline_mode_input.rb +0 -31
- data/lib/poli_page/inputs/project_mode_input.rb +0 -38
- data/lib/poli_page/models/preview_result.rb +0 -9
data/README.md
CHANGED
|
@@ -32,12 +32,17 @@ gem install poli-page
|
|
|
32
32
|
|
|
33
33
|
Requires Ruby **>= 3.2**.
|
|
34
34
|
|
|
35
|
-
The gem
|
|
36
|
-
|
|
35
|
+
The gem's one runtime dependency is `base64` (a bundled gem since Ruby
|
|
36
|
+
3.4, used to decode thumbnail data); everything else is the stdlib
|
|
37
|
+
(`net/http`, `json`, `uri`, `securerandom`, `logger`, `openssl`).
|
|
37
38
|
|
|
38
39
|
## Quick start
|
|
39
40
|
|
|
40
|
-
###
|
|
41
|
+
### Render a template by slug
|
|
42
|
+
|
|
43
|
+
Set `POLI_PAGE_API_KEY` to a `sandbox` key of a fresh organization
|
|
44
|
+
(`pp_sandbox_…`, see [Authentication & environments](#authentication--environments)),
|
|
45
|
+
then:
|
|
41
46
|
|
|
42
47
|
```ruby
|
|
43
48
|
require "poli_page"
|
|
@@ -47,58 +52,57 @@ client = PoliPage::Client.new(api_key: ENV.fetch("POLI_PAGE_API_KEY"))
|
|
|
47
52
|
pdf = client.render.pdf(
|
|
48
53
|
project: "getting-started",
|
|
49
54
|
template: "welcome",
|
|
50
|
-
|
|
51
|
-
data: { name: "World" }
|
|
55
|
+
data: { name: "SDK Demo" }
|
|
52
56
|
)
|
|
53
57
|
# pdf is a binary-encoded String
|
|
54
58
|
```
|
|
55
59
|
|
|
56
|
-
Every
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
+
Every organization gets a `getting-started` project, published into its
|
|
61
|
+
`sandbox` environment when the organization is created, with a `welcome`
|
|
62
|
+
template. A sandbox key renders it with no setup, so the snippet above runs
|
|
63
|
+
as-is on a fresh organization. It is a normal, editable project: in an
|
|
64
|
+
organization that renamed it, deleted it or removed it from `sandbox`, the
|
|
65
|
+
API answers `404 PROJECT_NOT_FOUND` or `404 PROJECT_NOT_IN_ENVIRONMENT`, so
|
|
66
|
+
use a fresh organization to follow along.
|
|
67
|
+
|
|
68
|
+
There is no version to pick: a render uses the project's copy published in
|
|
69
|
+
the API key's environment. For your own templates, publish the project to
|
|
70
|
+
the environment of the key you render with, then swap the slugs:
|
|
60
71
|
|
|
61
72
|
```ruby
|
|
62
73
|
pdf = client.render.pdf(
|
|
63
74
|
project: "billing",
|
|
64
75
|
template: "invoice",
|
|
65
|
-
|
|
66
|
-
data: { invoice_number: "INV-001", total: 1280 }
|
|
67
|
-
)
|
|
68
|
-
```
|
|
69
|
-
|
|
70
|
-
### Preview inline HTML
|
|
71
|
-
|
|
72
|
-
`render.preview` accepts raw HTML for live editing and visual inspection
|
|
73
|
-
without producing a stored document. Use this for editor previews or
|
|
74
|
-
layout tests.
|
|
75
|
-
|
|
76
|
-
```ruby
|
|
77
|
-
result = client.render.preview(
|
|
78
|
-
template: "<h1>Hello {{ name }}</h1>",
|
|
79
|
-
data: { name: "World" }
|
|
76
|
+
data: { invoiceNumber: "INV-001", total: 1280 }
|
|
80
77
|
)
|
|
81
|
-
puts "Rendered #{result.total_pages} page(s) in #{result.environment} mode"
|
|
82
78
|
```
|
|
83
79
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
accepted by `render.preview`.
|
|
80
|
+
To preview a template or render inline HTML while you design it, use the
|
|
81
|
+
playground: <https://play.poli.page>. The API and this SDK render published
|
|
82
|
+
templates only.
|
|
88
83
|
|
|
89
84
|
### Write a PDF to disk
|
|
90
85
|
|
|
91
86
|
```ruby
|
|
92
87
|
client.render_to_file(
|
|
93
88
|
"./welcome.pdf",
|
|
94
|
-
project: "getting-started", template: "welcome",
|
|
95
|
-
data: { name: "
|
|
89
|
+
project: "getting-started", template: "welcome",
|
|
90
|
+
data: { name: "SDK Demo" }
|
|
96
91
|
)
|
|
97
92
|
```
|
|
98
93
|
|
|
99
|
-
`render_to_file` streams the response bytes
|
|
94
|
+
`render_to_file` streams the response bytes to disk via
|
|
100
95
|
`render.pdf_stream` — bounded memory regardless of PDF size. Parent
|
|
101
|
-
directories are created on the fly.
|
|
96
|
+
directories are created on the fly. The PDF goes to a temporary file next
|
|
97
|
+
to the target, renamed over it once complete, so a failed render, download
|
|
98
|
+
or write leaves the target as it was. This needs write permission on the
|
|
99
|
+
target's directory, and a replaced file is a new file (your process owns
|
|
100
|
+
it; a hard link to the old one keeps the old content). A symbolic link is
|
|
101
|
+
followed: the file it points to gets the PDF. A target that is not a
|
|
102
|
+
regular file (a directory, a FIFO, a device) fails before any render with
|
|
103
|
+
`Failed to write PDF: <path>: not a regular file`. A file that cannot be written raises
|
|
104
|
+
`PoliPage::FileWriteError` (code `io_error`, message
|
|
105
|
+
`Failed to write PDF: <reason>`, the Ruby error as `cause`).
|
|
102
106
|
|
|
103
107
|
### Try it locally — runnable demo
|
|
104
108
|
|
|
@@ -106,18 +110,25 @@ directories are created on the fly.
|
|
|
106
110
|
ruby examples/demo.rb
|
|
107
111
|
```
|
|
108
112
|
|
|
109
|
-
The demo walks every public method
|
|
110
|
-
`examples/output/`. First run prompts
|
|
111
|
-
|
|
112
|
-
env var wins over
|
|
113
|
+
The demo renders `getting-started`/`welcome`, walks every public method
|
|
114
|
+
end-to-end and writes the results to `examples/output/`. First run prompts
|
|
115
|
+
for a `sandbox` key (`pp_sandbox_…`) and saves it to `.env` at the project
|
|
116
|
+
root. Subsequent runs are silent. The `POLI_PAGE_API_KEY` env var wins over
|
|
117
|
+
the file when set; `POLI_PAGE_BASE_URL` (optional) overrides the API host.
|
|
118
|
+
|
|
119
|
+
It walks nine steps: `render.pdf` → `render.pdf_stream` → `render_to_file`
|
|
120
|
+
→ `render.document` → `documents.get` → `documents.thumbnails` →
|
|
121
|
+
`documents.preview` → `documents.delete` → `not-found` (a render of a
|
|
122
|
+
template that does not exist, caught as `PoliPage::NotFoundError` with code
|
|
123
|
+
`TEMPLATE_NOT_FOUND`).
|
|
113
124
|
|
|
114
125
|
### Stream — for large PDFs or piping to S3 / HTTP responses
|
|
115
126
|
|
|
116
127
|
```ruby
|
|
117
128
|
File.open("invoice.pdf", "wb") do |io|
|
|
118
129
|
client.render.pdf_stream(
|
|
119
|
-
project: "billing", template: "invoice",
|
|
120
|
-
data: {
|
|
130
|
+
project: "billing", template: "invoice",
|
|
131
|
+
data: { invoiceNumber: "INV-001" }
|
|
121
132
|
) do |chunk|
|
|
122
133
|
io.write(chunk)
|
|
123
134
|
end
|
|
@@ -128,7 +139,7 @@ Without a block, `pdf_stream` returns an `Enumerator` that composes with
|
|
|
128
139
|
`Enumerable`:
|
|
129
140
|
|
|
130
141
|
```ruby
|
|
131
|
-
enum = client.render.pdf_stream(project: "billing", template: "invoice",
|
|
142
|
+
enum = client.render.pdf_stream(project: "billing", template: "invoice", data: data)
|
|
132
143
|
enum.each { |chunk| s3.upload_part(part_number: n += 1, body: chunk) }
|
|
133
144
|
```
|
|
134
145
|
|
|
@@ -145,11 +156,12 @@ when you'll fetch the bytes later).
|
|
|
145
156
|
doc = client.render.document(
|
|
146
157
|
project: "billing",
|
|
147
158
|
template: "invoice",
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
metadata: { customer_id: "cust_123" } # your own audit data
|
|
159
|
+
data: { invoiceNumber: "INV-001" },
|
|
160
|
+
metadata: { customerId: "cust_123" } # your own audit data
|
|
151
161
|
)
|
|
152
|
-
# doc.document_id, doc.page_count, doc.size_bytes, doc.presigned_pdf_url,
|
|
162
|
+
# doc.document_id, doc.page_count, doc.size_bytes, doc.presigned_pdf_url, ...
|
|
163
|
+
# doc.metadata is returned as stored: { "customerId" => "cust_123" }
|
|
164
|
+
# The keys of data: and metadata: are sent exactly as written (no renaming).
|
|
153
165
|
|
|
154
166
|
# 2. Persist doc.document_id in your database
|
|
155
167
|
db.invoices.update(id: "INV-001", document_id: doc.document_id)
|
|
@@ -167,20 +179,40 @@ client.documents.delete(doc.document_id)
|
|
|
167
179
|
|
|
168
180
|
The presigned URL has a 15-minute TTL. If `download_pdf` raises
|
|
169
181
|
`PoliPage::DownloadError` with `status: 403` from S3, call
|
|
170
|
-
`documents.get(id)` to refresh and retry.
|
|
182
|
+
`documents.get(id)` to refresh and retry. The client's `timeout:` also
|
|
183
|
+
bounds the download: the whole download for `download_pdf` and
|
|
184
|
+
`render.pdf`, and the wait for the first byte, then each wait for the next
|
|
185
|
+
chunk, for `render.pdf_stream` and `render_to_file`. Past it, `DownloadError` has the message
|
|
186
|
+
`Failed to download PDF: timeout`.
|
|
171
187
|
|
|
172
188
|
## Authentication & environments
|
|
173
189
|
|
|
174
|
-
|
|
190
|
+
An API key belongs to exactly one environment of your organization, and its
|
|
191
|
+
text names that environment: a key is `pp_{env}_{32 lowercase hex}`, matching
|
|
192
|
+
|
|
193
|
+
```text
|
|
194
|
+
^pp_(?=[a-z][a-z0-9-]{0,19}_)[a-z][a-z0-9]*(?:-[a-z0-9]+)*_[0-9a-f]{32}$
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
The API resolves the environment from the key and renders the project's
|
|
198
|
+
copy published there; the SDK never sends an environment.
|
|
199
|
+
|
|
200
|
+
| Environment | Key | Watermark | Counted |
|
|
201
|
+
| ------------------------------------- | -------------- | --------- | ------- |
|
|
202
|
+
| `sandbox` (every org) | `pp_sandbox_…` | yes | no |
|
|
203
|
+
| `live` (every org, deletable on Pro+) | `pp_live_…` | no | yes |
|
|
204
|
+
| created on Pro+ (e.g. `staging`) | `pp_staging_…` | no | yes |
|
|
175
205
|
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
206
|
+
"Counted" means the render counts toward the organization's monthly PDF
|
|
207
|
+
quota. `sandbox` renders are watermarked, are not counted, and their
|
|
208
|
+
documents expire 30 days after creation. There is no watermark option: a
|
|
209
|
+
template that wants a watermark outside `sandbox` uses the `poli-watermark`
|
|
210
|
+
class.
|
|
180
211
|
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
212
|
+
Standard and service keys share this one format. Every key hits the same
|
|
213
|
+
endpoint, `https://api.poli.page` by default or whatever you pass as
|
|
214
|
+
`base_url:` (see [Configuration](#configuration)). The SDK passes the key
|
|
215
|
+
through as a `Bearer` token and does not check its format.
|
|
184
216
|
|
|
185
217
|
## Methods
|
|
186
218
|
|
|
@@ -188,23 +220,22 @@ pick whichever fits your deploy model.
|
|
|
188
220
|
| ----------------------------------------------- | ---------------------------------- | --------------------------------------------------- |
|
|
189
221
|
| `client.render.pdf(**input)` | `String` (binary bytes) | Render a PDF, return bytes |
|
|
190
222
|
| `client.render.pdf_stream(**input) { \|c\| … }` | `Enumerator` or yields chunks | Render and stream the response |
|
|
191
|
-
| `client.render.preview(**input)` | `PoliPage::PreviewResult` | Paginated HTML preview |
|
|
192
223
|
| `client.render.document(**input)` | `PoliPage::DocumentDescriptor` | Render and return descriptor (skip auto-download) |
|
|
193
224
|
| `client.documents.get(id)` | `PoliPage::DocumentDescriptor` | Retrieve a stored document |
|
|
194
225
|
| `client.documents.preview(id)` | `PoliPage::DocumentPreviewResult` | Stored document's paginated HTML |
|
|
195
|
-
| `client.documents.thumbnails(id, **opts)` | `Array<PoliPage::Thumbnail>` | Page thumbnails (PNG/
|
|
196
|
-
| `client.documents.delete(id)` | `nil` | Soft-delete a stored document
|
|
226
|
+
| `client.documents.thumbnails(id, **opts)` | `Array<PoliPage::Thumbnail>` | Page thumbnails (JPEG/PNG/WebP, base64) |
|
|
227
|
+
| `client.documents.delete(id)` | `nil` | Soft-delete a stored document (idempotent) |
|
|
197
228
|
| `client.render_to_file(path, **input)` | `nil` | Render and stream to disk |
|
|
198
229
|
|
|
199
230
|
## Configuration
|
|
200
231
|
|
|
201
232
|
| Option | Type | Default | Description |
|
|
202
233
|
| ------------- | -------------------------- | -------------------------- | -------------------------------------------- |
|
|
203
|
-
| `api_key:` | `String` | (required) |
|
|
234
|
+
| `api_key:` | `String` | (required) | API key of one environment (`pp_{env}_…`) |
|
|
204
235
|
| `base_url:` | `String` | `"https://api.poli.page"` | API base URL |
|
|
205
236
|
| `max_retries:`| `Integer` | `2` | Max retry attempts on retryable errors |
|
|
206
237
|
| `retry_delay:`| `Numeric` (seconds) | `0.5` | Base delay before the first retry |
|
|
207
|
-
| `timeout:` | `Numeric` (seconds) | `60` | Per-
|
|
238
|
+
| `timeout:` | `Numeric` (seconds) | `60` | Per-attempt timeout, body included; also bounds the PDF download |
|
|
208
239
|
| `logger:` | `Logger` (any duck type) | `nil` | Hook errors and DEBUG events here |
|
|
209
240
|
| `on_retry:` | `#call(PoliPage::RetryEvent)`| `nil` | Called when a retry is scheduled |
|
|
210
241
|
| `on_error:` | `#call(PoliPage::Error)` | `nil` | Called when a call terminates in error |
|
|
@@ -226,7 +257,7 @@ Errors are dispatched by class — the rescue-friendly path:
|
|
|
226
257
|
require "poli_page"
|
|
227
258
|
|
|
228
259
|
begin
|
|
229
|
-
client.render.pdf(project: "billing", template: "invoice",
|
|
260
|
+
client.render.pdf(project: "billing", template: "invoice", data: data)
|
|
230
261
|
rescue PoliPage::AuthenticationError, PoliPage::PermissionDeniedError => e
|
|
231
262
|
refresh_credentials(e)
|
|
232
263
|
rescue PoliPage::RateLimitError => e
|
|
@@ -241,7 +272,10 @@ end
|
|
|
241
272
|
```
|
|
242
273
|
|
|
243
274
|
Predicate helpers on the base class are kept for callers who prefer a
|
|
244
|
-
single `rescue PoliPage::Error => e` clause
|
|
275
|
+
single `rescue PoliPage::Error => e` clause. They read `status` and `code`
|
|
276
|
+
(`auth_error?` is 401/403, `rate_limit_error?` 429, `validation_error?` 400,
|
|
277
|
+
`network_error?` `network_error`/`timeout`), so a `DownloadError` with a
|
|
278
|
+
storage 403 is an `auth_error?`:
|
|
245
279
|
|
|
246
280
|
```ruby
|
|
247
281
|
rescue PoliPage::Error => e
|
|
@@ -258,11 +292,11 @@ rather than treating them as opaque:
|
|
|
258
292
|
```ruby
|
|
259
293
|
rescue PoliPage::Error => e
|
|
260
294
|
case e.code
|
|
261
|
-
when "
|
|
262
|
-
when "ORGANIZATION_CANCELLED"
|
|
263
|
-
when "ORGANIZATION_PURGED"
|
|
264
|
-
when "DOCUMENT_NOT_FOUND"
|
|
265
|
-
when "
|
|
295
|
+
when "ORGANIZATION_PAYMENT_GRACE" then show_banner("Subscription has unpaid invoices.")
|
|
296
|
+
when "ORGANIZATION_CANCELLED" then show_banner("Subscription cancelled — service is read-only.")
|
|
297
|
+
when "ORGANIZATION_PURGED" then show_banner("Organization has been purged.")
|
|
298
|
+
when "DOCUMENT_NOT_FOUND" then render_404
|
|
299
|
+
when "DOCUMENT_GONE" then render_410 # deleted, or a sandbox document past 30 days
|
|
266
300
|
else
|
|
267
301
|
raise
|
|
268
302
|
end
|
|
@@ -272,6 +306,24 @@ end
|
|
|
272
306
|
The full list of known API codes lives in `PoliPage::ErrorCodes` (see
|
|
273
307
|
`lib/poli_page/errors.rb`).
|
|
274
308
|
|
|
309
|
+
A 2xx answer whose body is not JSON, which comes from something between
|
|
310
|
+
your app and the API (a proxy, a captive portal), raises
|
|
311
|
+
`PoliPage::InvalidResponseError` (code `invalid_response`, message
|
|
312
|
+
`Invalid response: HTTP <status> body is not JSON`) with the real 2xx as
|
|
313
|
+
`status`. It is not retried.
|
|
314
|
+
|
|
315
|
+
For framework integrations, `e.to_payload` returns the HTTP body to answer
|
|
316
|
+
with: exactly the keys `code:`, `message:`, `status:` and `requestId:`, the
|
|
317
|
+
same JSON in every Poli Page SDK. Its `status:` is the API status, 503 for
|
|
318
|
+
`network_error`, 504 for `timeout` and 502 for `invalid_response`.
|
|
319
|
+
|
|
320
|
+
```ruby
|
|
321
|
+
rescue PoliPage::Error => e
|
|
322
|
+
payload = e.to_payload
|
|
323
|
+
render json: payload, status: payload[:status] || 500
|
|
324
|
+
end
|
|
325
|
+
```
|
|
326
|
+
|
|
275
327
|
→ Full error reference: <https://poli-page.github.io/sdk-ruby/reference/errors/>
|
|
276
328
|
|
|
277
329
|
## Cancellation
|
|
@@ -315,39 +367,47 @@ render. The injected `logger:` works with any `Logger`-compatible object
|
|
|
315
367
|
|
|
316
368
|
## Retries & idempotency
|
|
317
369
|
|
|
318
|
-
The SDK retries on **5xx**, **429**, **network errors**, and **timeouts
|
|
370
|
+
The SDK retries on **5xx**, **429**, **network errors**, and **timeouts**,
|
|
371
|
+
except `QUOTA_EXCEEDED`, `OVERAGE_CAP_EXCEEDED` and `STORAGE_ACCESS_DENIED`,
|
|
372
|
+
which wait cannot fix. The presigned-URL download is never retried.
|
|
319
373
|
Backoff is exponential (`retry_delay * 2**(attempt - 1)`) with jitter in
|
|
320
|
-
`[0.5, 1.5)`,
|
|
321
|
-
(integer seconds or HTTP-date;
|
|
374
|
+
`[0.5, 1.5)`, replaced by `Retry-After` when the server provides it
|
|
375
|
+
(integer seconds or HTTP-date; clamped to 0–30 s). `timeout:` bounds each
|
|
376
|
+
attempt, body included, and every resend is one of these counted retries:
|
|
377
|
+
`Net::HTTP` never sends a request again on its own.
|
|
322
378
|
|
|
323
|
-
Every POST sends an auto-generated `Idempotency-Key` (UUID v4)
|
|
324
|
-
`idempotency_key:` to override.
|
|
379
|
+
Every POST sends an auto-generated `Idempotency-Key` (UUID v4), the same on
|
|
380
|
+
every retry of one call; pass `idempotency_key:` to override. The API does
|
|
381
|
+
not deduplicate on it: a render retried after a late 5xx, a `timeout` or a
|
|
382
|
+
`network_error` can store a second document.
|
|
325
383
|
|
|
326
384
|
```ruby
|
|
327
|
-
client.render.pdf(project: "billing", template: "invoice",
|
|
385
|
+
client.render.pdf(project: "billing", template: "invoice",
|
|
328
386
|
data: data, idempotency_key: "render-INV-001-2026-05")
|
|
329
387
|
```
|
|
330
388
|
|
|
331
389
|
## Type system
|
|
332
390
|
|
|
333
391
|
The gem ships RBS signatures under `sig/`. Steep checks them against the
|
|
334
|
-
implementation in CI.
|
|
335
|
-
|
|
336
|
-
|
|
392
|
+
implementation in CI. The render methods take keyword arguments, so Ruby
|
|
393
|
+
checks them at call time — `Client#render.pdf` raises `ArgumentError`
|
|
394
|
+
before any request if `project:`, `template:`, or `data:` is omitted, or if
|
|
395
|
+
an unknown keyword (such as the removed `version:`) is passed.
|
|
337
396
|
|
|
338
397
|
For Sorbet users: `.rbi` shipping is a post-1.0 enhancement.
|
|
339
398
|
|
|
340
399
|
## Concurrency & thread-safety
|
|
341
400
|
|
|
342
401
|
A single `PoliPage::Client` instance is safe to share across threads.
|
|
343
|
-
Configuration is immutable after `#initialize`; each
|
|
344
|
-
own `Net::HTTP` connection
|
|
402
|
+
Configuration is immutable after `#initialize`; each attempt opens its
|
|
403
|
+
own `Net::HTTP` connection (no pool or cache to size), plus a short-lived
|
|
404
|
+
thread that enforces `timeout:`.
|
|
345
405
|
|
|
346
406
|
```ruby
|
|
347
407
|
CLIENT = PoliPage::Client.new(api_key: ENV.fetch("POLI_PAGE_API_KEY")).freeze
|
|
348
408
|
|
|
349
409
|
pdfs = ids.map do |id|
|
|
350
|
-
Thread.new { CLIENT.render.pdf(project: "billing", template: "invoice",
|
|
410
|
+
Thread.new { CLIENT.render.pdf(project: "billing", template: "invoice", data: { invoiceNumber: id }) }
|
|
351
411
|
end.map(&:value)
|
|
352
412
|
```
|
|
353
413
|
|
|
@@ -355,9 +415,9 @@ Build the client once at boot. Don't construct a new client per request.
|
|
|
355
415
|
|
|
356
416
|
## Runtime support
|
|
357
417
|
|
|
358
|
-
- Ruby 3.
|
|
418
|
+
- Ruby 3.2+ (CRuby/MRI).
|
|
359
419
|
- JRuby 9.4+ on a best-effort basis.
|
|
360
|
-
- Linux
|
|
420
|
+
- Linux, macOS and Windows (see [Requirements](#requirements) for the CI matrix).
|
|
361
421
|
|
|
362
422
|
## Requirements
|
|
363
423
|
|
data/SECURITY.md
CHANGED
|
@@ -81,8 +81,10 @@ updates. Older minors do not receive backports — please upgrade.
|
|
|
81
81
|
is pinned to a 40-character SHA, not a floating tag.
|
|
82
82
|
- **Dependabot** — weekly updates for `bundler` and `github-actions`.
|
|
83
83
|
- **MFA-required publishing** — the gemspec declares
|
|
84
|
-
`rubygems_mfa_required: "true"
|
|
85
|
-
|
|
84
|
+
`rubygems_mfa_required: "true"`. Releases are published by the tag-triggered
|
|
85
|
+
release workflow via RubyGems Trusted Publishing (OIDC), behind the
|
|
86
|
+
`rubygems-release` environment's required-reviewer approval; no RubyGems
|
|
87
|
+
API key is stored anywhere.
|
|
86
88
|
- **Restricted workflow permissions** — every workflow declares the
|
|
87
89
|
minimum `permissions:` block (most are `contents: read`).
|
|
88
90
|
|
data/lib/poli_page/client.rb
CHANGED
|
@@ -20,8 +20,9 @@ module PoliPage
|
|
|
20
20
|
# execution back through it.
|
|
21
21
|
#
|
|
22
22
|
# Thread-safety: configuration is immutable after `#initialize`; each
|
|
23
|
-
#
|
|
24
|
-
#
|
|
23
|
+
# attempt opens its own `Net::HTTP` connection, so the client keeps no
|
|
24
|
+
# connection pool or other per-call cache. A single `Client` may be safely
|
|
25
|
+
# shared across threads — build one at boot and reuse it.
|
|
25
26
|
#
|
|
26
27
|
# @example Construct with defaults
|
|
27
28
|
# client = PoliPage::Client.new(api_key: ENV.fetch("POLI_PAGE_API_KEY"))
|
|
@@ -56,7 +57,7 @@ module PoliPage
|
|
|
56
57
|
logger: nil, on_request: nil, on_response: nil,
|
|
57
58
|
on_retry: nil, on_error: nil,
|
|
58
59
|
proxy: nil, ca_file: nil, ca_path: nil)
|
|
59
|
-
raise InvalidOptionsError,
|
|
60
|
+
raise InvalidOptionsError, Internal::Constants::MESSAGE_INVALID_OPTIONS if api_key.nil? || api_key.empty?
|
|
60
61
|
|
|
61
62
|
@api_key = api_key
|
|
62
63
|
@base_url = base_url
|
|
@@ -76,19 +77,20 @@ module PoliPage
|
|
|
76
77
|
|
|
77
78
|
# Redacted `#inspect`. Ruby's default would dump `@api_key` into any
|
|
78
79
|
# `puts client` or exception backtrace — that's how secrets end up in
|
|
79
|
-
# logs
|
|
80
|
+
# logs.
|
|
80
81
|
def inspect
|
|
81
82
|
"#<PoliPage::Client base_url=#{@base_url.inspect} timeout=#{@timeout} max_retries=#{@max_retries}>"
|
|
82
83
|
end
|
|
83
84
|
alias to_s inspect
|
|
84
85
|
|
|
85
86
|
# Execute a POST request against `path` with `body` (snake_case hash;
|
|
86
|
-
# caller's responsibility to compact nils).
|
|
87
|
+
# caller's responsibility to compact nils). The SDK's field names are
|
|
88
|
+
# camelized; the values of `data` and `metadata` are sent as given. Returns the parsed
|
|
87
89
|
# snake_case-symbol-keyed Hash on 2xx, or raises a `PoliPage::Error`.
|
|
88
90
|
#
|
|
89
91
|
# @api private
|
|
90
92
|
def execute_post(path, body:, idempotency_key: nil)
|
|
91
|
-
wire_body = JSON.generate(Internal::Wire.to_wire(body))
|
|
93
|
+
wire_body = JSON.generate(Internal::Wire.to_wire(body, Internal::Wire::PAYLOAD_KEYS))
|
|
92
94
|
response = run_with_retry(method: :post, path: path, body: wire_body,
|
|
93
95
|
idempotency_key: idempotency_key || Internal::UUID.generate)
|
|
94
96
|
parse_json_response(response)
|
|
@@ -158,12 +160,12 @@ module PoliPage
|
|
|
158
160
|
fire_hook(@on_retry,
|
|
159
161
|
RetryEvent.new(attempt: attempt + 1, delay_ms: (delay * 1000).round,
|
|
160
162
|
reason: state[:last_error]))
|
|
161
|
-
|
|
163
|
+
Internal::HTTP.sleep_at_least(delay)
|
|
162
164
|
end
|
|
163
165
|
|
|
164
166
|
def raise_terminal(error)
|
|
165
167
|
fire_hook(@on_error, error)
|
|
166
|
-
raise error
|
|
168
|
+
raise error, cause: error.cause
|
|
167
169
|
end
|
|
168
170
|
|
|
169
171
|
def send_once(method:, path:, body:, idempotency_key:, attempt:)
|
|
@@ -173,7 +175,7 @@ module PoliPage
|
|
|
173
175
|
RequestEvent.new(method: method.to_s.upcase, url: url, attempt: attempt))
|
|
174
176
|
started_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
175
177
|
response = @transport.execute(method: method, path: path, headers: headers, body: body)
|
|
176
|
-
return success_result(response, started_at) if (200..299).cover?(response.status)
|
|
178
|
+
return success_result(response, started_at) if response.body_error.nil? && (200..299).cover?(response.status)
|
|
177
179
|
|
|
178
180
|
build_error_result(response)
|
|
179
181
|
rescue PoliPage::TimeoutError, PoliPage::ConnectionError => e
|
|
@@ -199,22 +201,38 @@ module PoliPage
|
|
|
199
201
|
{ ok: true, response: response }
|
|
200
202
|
end
|
|
201
203
|
|
|
204
|
+
# A non-2xx answer. One whose body could not be read is handled as a body
|
|
205
|
+
# that is not JSON (`INTERNAL_ERROR`, `HTTP <status>`), keeping the real
|
|
206
|
+
# status and request id, and is retried by its status like any other.
|
|
202
207
|
def build_error_result(response)
|
|
203
208
|
status = response.status
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
209
|
+
code, message = if response.body_error
|
|
210
|
+
["INTERNAL_ERROR", "HTTP #{status}"]
|
|
211
|
+
else
|
|
212
|
+
Internal::HTTP.parse_error_body(response.body.to_s, status)
|
|
213
|
+
end
|
|
214
|
+
error = Internal::HTTP.classify(status: status, code: code, message: message,
|
|
215
|
+
request_id: response.headers[Internal::Constants::HEADER_REQUEST_ID],
|
|
216
|
+
cause: response.body_error)
|
|
217
|
+
retryable = error.retryable?
|
|
208
218
|
retry_after_header = response.headers[Internal::Constants::HEADER_RETRY_AFTER]
|
|
209
219
|
retry_after = retryable ? Internal::HTTP.parse_retry_after(retry_after_header) : nil
|
|
210
220
|
{ ok: false, error: error, retry_after: retry_after, retryable: retryable }
|
|
211
221
|
end
|
|
212
222
|
|
|
223
|
+
# A 2xx whose body is not JSON (an empty body included) raises
|
|
224
|
+
# `invalid_response` with the real status and the answer's request id; a
|
|
225
|
+
# JSON value that is not an object raises `INTERNAL_ERROR`. Neither is
|
|
226
|
+
# retried, and both go through `on_error` like any error the SDK is about
|
|
227
|
+
# to raise.
|
|
213
228
|
def parse_json_response(response)
|
|
214
|
-
parsed = JSON.parse(response.body)
|
|
215
|
-
Internal::Wire.from_wire(parsed)
|
|
229
|
+
parsed = JSON.parse(response.body.to_s)
|
|
230
|
+
return Internal::Wire.from_wire(parsed, Internal::Wire::PAYLOAD_KEYS) if parsed.is_a?(Hash)
|
|
231
|
+
|
|
232
|
+
raise_terminal(PoliPage::InternalError.new("response body was not a JSON object", status: response.status))
|
|
216
233
|
rescue JSON::ParserError => e
|
|
217
|
-
|
|
234
|
+
request_id = response.headers[Internal::Constants::HEADER_REQUEST_ID]
|
|
235
|
+
raise_terminal(PoliPage::InvalidResponseError.new(status: response.status, request_id: request_id, cause: e))
|
|
218
236
|
end
|
|
219
237
|
|
|
220
238
|
def fire_hook(hook, event)
|