api_recipes 3.0.0.beta5 → 3.0.0.beta7
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/README.md +139 -25
- data/UPGRADING.md +49 -7
- data/lib/api_recipes/cli/convert.rb +37 -14
- data/lib/api_recipes/cli/import.rb +1 -1
- data/lib/api_recipes/cli/recipes/summary.rb +5 -3
- data/lib/api_recipes/cli/upgrade.rb +2 -0
- data/lib/api_recipes/errors.rb +20 -3
- data/lib/api_recipes/internals/context.rb +7 -2
- data/lib/api_recipes/internals/level.rb +6 -1
- data/lib/api_recipes/internals/origins.rb +70 -0
- data/lib/api_recipes/internals/path_template.rb +9 -6
- data/lib/api_recipes/internals/recipe.rb +3 -3
- data/lib/api_recipes/internals/registry.rb +21 -10
- data/lib/api_recipes/internals/request.rb +2 -2
- data/lib/api_recipes/internals/template.rb +32 -2
- data/lib/api_recipes/response.rb +125 -6
- data/lib/api_recipes/version.rb +1 -1
- data/lib/api_recipes.rb +1 -0
- metadata +2 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: e74dee706cb23be6a067db39d719b50541d83183b705739d9a451806bfcc51b9
|
|
4
|
+
data.tar.gz: 91b784da2650e2f7af4a603b6ab1e5190336dd4db845b83ba59579936dd98f51
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: b930031404cff1ef52d916145db794849902b4647aa7d5911a62d69d2310e1a97b6a24609f63f9da314913af39f9e98e2a9747306280538da6ef62d998e886c1
|
|
7
|
+
data.tar.gz: 69a9493844b49deec69eafdc8d7e1e7477d7e5d2cf3ad0d3e514e9597b6646d54991529c1462561f00707c2a1220fa71e94e5d265bdadef28d29a6d820ff08cf
|
data/README.md
CHANGED
|
@@ -220,7 +220,8 @@ stay in the path is written `\:`.
|
|
|
220
220
|
|
|
221
221
|
A `{name}` in a path is a [variable](#variables): a value given once, to a
|
|
222
222
|
chain, an object, a class or the whole application, where a `:name` is an
|
|
223
|
-
argument of each call.
|
|
223
|
+
argument of each call. A `{*name}` is the variable form of `*name`: its value
|
|
224
|
+
can be several segments.
|
|
224
225
|
|
|
225
226
|
### Endpoints that only group others
|
|
226
227
|
|
|
@@ -294,7 +295,8 @@ ApiRecipes.billing.invoices.show(42).url.to_s
|
|
|
294
295
|
|
|
295
296
|
`host` is a plain host name: no scheme, port, path or spaces. Use `protocol` and
|
|
296
297
|
`port` for those. A `base_url` cannot contain a `:name` or `*name` placeholder;
|
|
297
|
-
for a value that changes, use a [variable](#variables)
|
|
298
|
+
for a value that changes, use a [variable](#variables), and `{*name}` for a
|
|
299
|
+
value of several segments, such as a prefix.
|
|
298
300
|
|
|
299
301
|
All options are listed in the [options reference](#options-reference).
|
|
300
302
|
|
|
@@ -451,7 +453,8 @@ Sandbox.sandbox.with(variables: { tenant: 'acme' }).ping.url.to_s
|
|
|
451
453
|
```
|
|
452
454
|
|
|
453
455
|
`config.values` holds, for each API, its `variables` and its credential
|
|
454
|
-
(`authorization` or `basic_auth`, see [Authorization](#authorization))
|
|
456
|
+
(`authorization` or `basic_auth`, see [Authorization](#authorization)), and with
|
|
457
|
+
the credential the other origins it may go to (`credential_origins`). A later
|
|
455
458
|
`configure` that assigns `config.values` replaces them all; one that does not
|
|
456
459
|
keeps them.
|
|
457
460
|
|
|
@@ -522,11 +525,42 @@ an option as it is written. What decides the shape of the tree is read when
|
|
|
522
525
|
the configuration is loaded and takes no variable: `endpoints`, `resource`,
|
|
523
526
|
`route`, the names, `verify_with` and `auth`.
|
|
524
527
|
|
|
528
|
+
A variable written with a star, `{*name}`, in a `base_url` or in a `path`
|
|
529
|
+
takes a value of several segments, as a `*name` placeholder does: the value is
|
|
530
|
+
split on `/`, each segment is encoded and the slashes stay. It lets an
|
|
531
|
+
application move an API under a prefix:
|
|
532
|
+
|
|
533
|
+
```yaml
|
|
534
|
+
rabbitmq:
|
|
535
|
+
variables:
|
|
536
|
+
api_path:
|
|
537
|
+
default: api
|
|
538
|
+
protocol: http
|
|
539
|
+
host: localhost
|
|
540
|
+
port: 15672
|
|
541
|
+
base_url: '{*api_path}'
|
|
542
|
+
endpoints:
|
|
543
|
+
overview:
|
|
544
|
+
```
|
|
545
|
+
|
|
546
|
+
```ruby
|
|
547
|
+
ApiRecipes.rabbitmq.overview.url.to_s
|
|
548
|
+
# => "http://localhost:15672/api/overview"
|
|
549
|
+
|
|
550
|
+
ApiRecipes.rabbitmq.with(variables: { api_path: 'rabbitmq/api' }).overview.url.to_s
|
|
551
|
+
# => "http://localhost:15672/rabbitmq/api/overview"
|
|
552
|
+
```
|
|
553
|
+
|
|
554
|
+
No segment of the value can be empty, `.` or `..`, so the value never climbs
|
|
555
|
+
out of the path: `'a/../b'`, `'/a'` and `'a//b'` raise
|
|
556
|
+
`ApiRecipes::InvalidVariable`. In a header or a parameter `{*name}` is text,
|
|
557
|
+
a `host` refuses it, and `\{*name}` is text in a `path` and in a `base_url`.
|
|
558
|
+
|
|
525
559
|
The value of a variable is a String, a Symbol or a number, and is kept as
|
|
526
560
|
text. A value is checked for the place where it ends up. In a `host` it can contain
|
|
527
561
|
only letters, digits, dots, hyphens and underscores. In a `base_url` and in a
|
|
528
562
|
`path` it is encoded like a path parameter, and it cannot be empty, `.` or
|
|
529
|
-
|
|
563
|
+
`..`; in a `{*name}` it is encoded like the value of a `*name` placeholder. In a header it cannot contain a line break or another control character.
|
|
530
564
|
In a parameter it is encoded like every value of a query string. Anything else
|
|
531
565
|
raises `ApiRecipes::InvalidVariable`.
|
|
532
566
|
A word in braces that is not a variable is written `\{word}` in a path and in
|
|
@@ -1043,11 +1077,19 @@ What the command does:
|
|
|
1043
1077
|
number (`ENV.fetch('NAME', 'text')`, `ENV['NAME'] || 443`) becomes the
|
|
1044
1078
|
default of the variable. A default that a tag gave to a variable the file
|
|
1045
1079
|
declares is given by the application from now on. Only a variable with a
|
|
1046
|
-
default is declared in the recipe.
|
|
1080
|
+
default is declared in the recipe. In the `base_url` and in a `path` the
|
|
1081
|
+
variable is a `{*name}`, since 2.x put the value of the tag there with its
|
|
1082
|
+
slashes. A value of one or more segments goes where 2.x sent it; one that
|
|
1083
|
+
starts or ends with a slash, has two in a row or is empty, which 2.x joined,
|
|
1084
|
+
raises `ApiRecipes::InvalidVariable` at the request: give it without those
|
|
1085
|
+
slashes. The command says so when the default written in the tag is such a
|
|
1086
|
+
value.
|
|
1047
1087
|
- **A word in braces stays text**, as 2.x sent it, unless the file declares a
|
|
1048
1088
|
variable with that name: it is written `\{word}` in a `path` and in the
|
|
1049
1089
|
`base_url`, and a header or a parameter that holds one is given by a
|
|
1050
|
-
variable whose default is its text.
|
|
1090
|
+
variable whose default is its text. With a star, `{*word}` is written
|
|
1091
|
+
`\{*word}` in a `path` and in the `base_url` even when the file declares
|
|
1092
|
+
`word`; in a header or a parameter it stays as it is.
|
|
1051
1093
|
- **`--calls` writes beside each endpoint how it is called in Ruby**, as
|
|
1052
1094
|
`show: # .invoices.show(id)`, after the name of the API. The recipe is the
|
|
1053
1095
|
same with or without them.
|
|
@@ -1162,7 +1204,7 @@ ApiRecipes[:github].users.run
|
|
|
1162
1204
|
|
|
1163
1205
|
```ruby
|
|
1164
1206
|
ApiRecipes.apis.inspect
|
|
1165
|
-
# => "[:github, :billing, :shopify]"
|
|
1207
|
+
# => "[:github, :billing, :shopify, :rabbitmq]"
|
|
1166
1208
|
```
|
|
1167
1209
|
|
|
1168
1210
|
### In your classes
|
|
@@ -1367,8 +1409,9 @@ in a variable, and for an endpoint whose name is already a method (see
|
|
|
1367
1409
|
|
|
1368
1410
|
## Reading the response
|
|
1369
1411
|
|
|
1370
|
-
`run` returns an `ApiRecipes::Response`. It adds `data
|
|
1371
|
-
|
|
1412
|
+
`run` returns an `ApiRecipes::Response`. It adds `data`, and has the status,
|
|
1413
|
+
the headers and the body of the
|
|
1414
|
+
[http.rb response](https://github.com/httprb/http/wiki/Response-Handling):
|
|
1372
1415
|
|
|
1373
1416
|
```ruby
|
|
1374
1417
|
response = ApiRecipes.github.users.show('octocat').run
|
|
@@ -1380,10 +1423,38 @@ response.headers['Content-Type'] # => "application/json; charset=utf-8"
|
|
|
1380
1423
|
response.body.to_s # => "{\"login\":\"octocat\", ...}"
|
|
1381
1424
|
```
|
|
1382
1425
|
|
|
1383
|
-
`data` parses the body according to the `Content-Type` of the response
|
|
1384
|
-
|
|
1385
|
-
`
|
|
1386
|
-
|
|
1426
|
+
`data` parses the body according to the `Content-Type` of the response, with
|
|
1427
|
+
the parser of http.rb, which reads JSON. A type that ends in `+json`, like
|
|
1428
|
+
`application/problem+json`, is read as JSON too, unless your application gave
|
|
1429
|
+
http.rb a parser for it. An empty body gives `nil`, whatever
|
|
1430
|
+
the status and the type: a `204 No Content` needs nothing special. A body of
|
|
1431
|
+
spaces and line breaks counts as empty. A JSON `null` gives `nil` too: read
|
|
1432
|
+
`response.body.to_s` to tell them apart.
|
|
1433
|
+
|
|
1434
|
+
When there is a body that `data` cannot read (no `Content-Type`, a type that is
|
|
1435
|
+
not JSON, JSON that is not valid) it raises `ApiRecipes::UnreadableResponse`.
|
|
1436
|
+
The error has `path` and `response`, and its message gives the status and the
|
|
1437
|
+
type, when there is one, never the body: read `error.response.body.to_s`.
|
|
1438
|
+
`fill`, and a `verify_with` method that reads `data`, raise it as well. If a
|
|
1439
|
+
server sends JSON with the wrong `Content-Type`, set
|
|
1440
|
+
`mime_type: application/json` on the endpoint or on the API.
|
|
1441
|
+
|
|
1442
|
+
`data` raises the same error when the body is no longer there, because it was
|
|
1443
|
+
read with `readpartial` or because reading it failed: then `body.to_s` raises
|
|
1444
|
+
`HTTP::StateError` too.
|
|
1445
|
+
|
|
1446
|
+
`response.parse` reads the body as `data` does: `nil` for an empty body, the
|
|
1447
|
+
same error for one it cannot read. It takes a type, a String or a Symbol, for
|
|
1448
|
+
one response that is to be read with another one, and it reads the body again
|
|
1449
|
+
at every call:
|
|
1450
|
+
|
|
1451
|
+
```ruby
|
|
1452
|
+
response.parse # as data, read again
|
|
1453
|
+
response.parse('application/json') # whatever the Content-Type and mime_type say
|
|
1454
|
+
```
|
|
1455
|
+
|
|
1456
|
+
It is not the `parse` of http.rb, whose error quotes the body: that one is
|
|
1457
|
+
still `response.original_response.parse`.
|
|
1387
1458
|
|
|
1388
1459
|
`response.success?` tells whether the response passed the rule of the endpoint
|
|
1389
1460
|
(see the next section). It is the way to check a response when `on_bad_code` is
|
|
@@ -1486,6 +1557,8 @@ end
|
|
|
1486
1557
|
The method can be private. It is looked up on the caller, so `verify_with` is
|
|
1487
1558
|
meant for APIs used from a class or an instance. An endpoint that has no
|
|
1488
1559
|
`verify_with` of its own looks for one up the tree, as for the other options.
|
|
1560
|
+
`response.data` is `nil` when the body is empty: a rule that reads a key from
|
|
1561
|
+
it checks that first, where an answer without a body is possible.
|
|
1489
1562
|
|
|
1490
1563
|
## Handling errors
|
|
1491
1564
|
|
|
@@ -1512,6 +1585,7 @@ body, a credential or a query string: the body is on `error.response`.
|
|
|
1512
1585
|
| Error | Raised when |
|
|
1513
1586
|
| --- | --- |
|
|
1514
1587
|
| `ApiRecipes::ResponseCodeNotAsExpected` | the response is not a success; has `response`, `path` and `expected_code` |
|
|
1588
|
+
| `ApiRecipes::UnreadableResponse` | `response.data` or `response.parse` cannot read the body; has `response` and `path` |
|
|
1515
1589
|
| `ApiRecipes::PathParamsMismatch` | an endpoint gets the wrong number of path parameters |
|
|
1516
1590
|
| `ApiRecipes::InvalidPathParameter` | a path parameter is `nil`, empty, `.` or `..` |
|
|
1517
1591
|
| `ApiRecipes::NoRouteExists` | `run` is called on an endpoint with `route: no` |
|
|
@@ -1642,6 +1716,37 @@ through it raises the same error instead of sending a credential of the levels
|
|
|
1642
1716
|
to the old origin: ask `ApiRecipes` (or the class, or the object) for the API
|
|
1643
1717
|
again. A `configure` that does not move the origin changes nothing for it.
|
|
1644
1718
|
|
|
1719
|
+
When one credential is meant for several origins, like the nodes of a cluster
|
|
1720
|
+
that a variable selects, say so where the application gives the credential,
|
|
1721
|
+
with `credential_origins` in `config.values`:
|
|
1722
|
+
|
|
1723
|
+
```ruby
|
|
1724
|
+
ApiRecipes.configure do |config|
|
|
1725
|
+
config.values = {
|
|
1726
|
+
broker: {
|
|
1727
|
+
basic_auth: { user: 'me', pass: 'secret' },
|
|
1728
|
+
credential_origins: ['https://node2.example.com:15672', 'https://node3.example.com:15672']
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
end
|
|
1732
|
+
```
|
|
1733
|
+
|
|
1734
|
+
Each entry is a whole origin, `https://host` or `https://host:port`, and
|
|
1735
|
+
nothing else: no path, no user, no variable, no wildcard. An entry can also
|
|
1736
|
+
begin with `http://`: the credential then goes there in clear. The origin the
|
|
1737
|
+
credential was given for needs no entry. `credential_origins: :any` sends the
|
|
1738
|
+
credential wherever the request goes, plain `http` included. Use it only when
|
|
1739
|
+
the host, the port and the protocol that reach `with` and the variables never
|
|
1740
|
+
come from the data of a request: whoever chooses the destination receives the
|
|
1741
|
+
credential.
|
|
1742
|
+
|
|
1743
|
+
`credential_origins` is taken only there, next to `authorization` or
|
|
1744
|
+
`basic_auth`. `api` in a class, `with`, a recipe and `apis_configs` refuse it,
|
|
1745
|
+
and it says nothing of a credential that a class or an object sets for itself.
|
|
1746
|
+
A redirect to another origin still drops the credential. An API kept in a
|
|
1747
|
+
variable across a `configure` that moves it sends the credential to its old
|
|
1748
|
+
origin when that origin is named, or with `:any`.
|
|
1749
|
+
|
|
1645
1750
|
The readers `authorization` and `basic_auth` return the nearest credential that
|
|
1646
1751
|
was assigned. They do not apply that check: only a request does.
|
|
1647
1752
|
|
|
@@ -1706,8 +1811,11 @@ become a method, when the configuration is loaded (see
|
|
|
1706
1811
|
|
|
1707
1812
|
It also warns, once for each endpoint, when the value of a path parameter
|
|
1708
1813
|
contains a `/` (it is sent as `%2F`) or looks already percent-encoded (it is
|
|
1709
|
-
encoded again). The warning names the endpoint and never the value.
|
|
1710
|
-
|
|
1814
|
+
encoded again). The warning names the endpoint and never the value. A value
|
|
1815
|
+
that your code encoded is given decoded; a value that the API gave already
|
|
1816
|
+
encoded, such as an id it returned in that form, is given as it is, and then
|
|
1817
|
+
the warning is expected. `config.upgrade_warnings = false` turns these two
|
|
1818
|
+
warnings off.
|
|
1711
1819
|
|
|
1712
1820
|
## Inspecting an API
|
|
1713
1821
|
|
|
@@ -1943,11 +2051,14 @@ end
|
|
|
1943
2051
|
|
|
1944
2052
|
What ApiRecipes does:
|
|
1945
2053
|
|
|
1946
|
-
- **Path parameters** are encoded one by one. A value cannot add a
|
|
1947
|
-
|
|
2054
|
+
- **Path parameters** are encoded one by one. A value cannot add a query
|
|
2055
|
+
string or a fragment, nor a segment unless the placeholder is a `*name`.
|
|
2056
|
+
`nil`, an empty value, `.` and `..` are refused, and so is an empty, `.` or
|
|
2057
|
+
`..` segment of a `*name`.
|
|
1948
2058
|
- **Variables** are checked for the place where they end up: a host, a path, a
|
|
1949
2059
|
header or a query parameter. In a path a value is one encoded segment, like a
|
|
1950
|
-
path parameter
|
|
2060
|
+
path parameter, or, written `{*name}`, several encoded segments, none of them
|
|
2061
|
+
empty, `.` or `..`.
|
|
1951
2062
|
- **Parameters sent with every request** cannot take the place of the
|
|
1952
2063
|
credential: with `auth.type: query`, `default_params` that name its parameter
|
|
1953
2064
|
are refused, and the credential is always the only parameter with its name.
|
|
@@ -1959,8 +2070,10 @@ What ApiRecipes does:
|
|
|
1959
2070
|
another finds it. A `configure` changes the descriptions and those values in
|
|
1960
2071
|
one step.
|
|
1961
2072
|
- **Credentials** are sent only to the origin they were set for, and a request
|
|
1962
|
-
that would send one elsewhere raises.
|
|
1963
|
-
|
|
2073
|
+
that would send one elsewhere raises. Only the application names other
|
|
2074
|
+
origins for the credential it gives, with `credential_origins` in
|
|
2075
|
+
`config.values`. A value with a control character is refused, so a credential
|
|
2076
|
+
cannot add a header.
|
|
1964
2077
|
- **Redirects.** With `follow`, a redirect to another origin drops the
|
|
1965
2078
|
credentials, the `Cookie` header and the credential query parameter. They are
|
|
1966
2079
|
not sent again if the chain comes back.
|
|
@@ -2054,12 +2167,12 @@ Every protection has an example in [`spec/security`](spec/security); its
|
|
|
2054
2167
|
| `protocol` | `https` | `http` or `https`; can be a `{variable}` |
|
|
2055
2168
|
| `host` | `localhost` | host name, which can contain `{variables}` |
|
|
2056
2169
|
| `port` | port of the protocol | port number; can be a `{variable}` |
|
|
2057
|
-
| `base_url` | none | prefix of every path, for example `api/v1`; can contain `{variables}` |
|
|
2170
|
+
| `base_url` | none | prefix of every path, for example `api/v1`; can contain `{variables}`, and `{*name}` for a value of several segments |
|
|
2058
2171
|
| `timeout` | `3` | seconds allowed for the whole request; can be a `{variable}`, as `on_bad_code` and `mime_type` |
|
|
2059
2172
|
| `default_headers` | none | headers sent with every request; a value can contain `{variables}` |
|
|
2060
2173
|
| `default_params` | none | query parameters sent with every request; a value is text, a number or a boolean, and can contain `{variables}` |
|
|
2061
2174
|
| `on_bad_code` | `raise` | `raise` or `ignore` when the response is not a success |
|
|
2062
|
-
| `mime_type` | from the response | content type used by `response.data` |
|
|
2175
|
+
| `mime_type` | from the response | content type used by `response.data` and `response.parse` |
|
|
2063
2176
|
| `verify_with` | none | method that decides whether a response is a success |
|
|
2064
2177
|
| `auth` | none | where the credential goes: `type` (`none`, `bearer`, `basic`, `header`, `query`) and `name` (for `header` and `query`) |
|
|
2065
2178
|
| `variables` | none | the variables of the API, each with an optional `default` and `description` |
|
|
@@ -2069,13 +2182,13 @@ Every protection has an example in [`spec/security`](spec/security); its
|
|
|
2069
2182
|
|
|
2070
2183
|
| Option | Default | Meaning |
|
|
2071
2184
|
| --- | --- | --- |
|
|
2072
|
-
| `path` | the endpoint name | segment added to the parent path; `''` adds nothing; can contain `:name` and `*name` placeholders and `{
|
|
2185
|
+
| `path` | the endpoint name | segment added to the parent path; `''` adds nothing; can contain `:name` and `*name` placeholders, `{variables}` and `{*name}` |
|
|
2073
2186
|
| `verb` | `get` | HTTP verb; can be a `{variable}`, as `ok_code` (one status), `timeout`, `on_bad_code` and `mime_type` |
|
|
2074
2187
|
| `route` | `yes` | `no` makes the endpoint a group that cannot be called |
|
|
2075
2188
|
| `ok_code` | any 2xx | the status, or the list of statuses, accepted as a success |
|
|
2076
2189
|
| `timeout` | looked for up the tree | seconds allowed for the whole request |
|
|
2077
2190
|
| `on_bad_code` | looked for up the tree | `raise` or `ignore` |
|
|
2078
|
-
| `mime_type` | looked for up the tree | content type used by `response.data` |
|
|
2191
|
+
| `mime_type` | looked for up the tree | content type used by `response.data` and `response.parse` |
|
|
2079
2192
|
| `verify_with` | looked for up the tree | method that decides whether a response is a success |
|
|
2080
2193
|
| `default_headers` | none | headers of this endpoint; a request finds them here when it looks up the tree, before those of the API |
|
|
2081
2194
|
| `default_params` | none | query parameters of this endpoint; a request finds them here when it looks up the tree, before those of the API |
|
|
@@ -2128,7 +2241,8 @@ operation, as its verb does.
|
|
|
2128
2241
|
`ApiNameClashError`, `ConfigurationError`, `CredentialOriginMismatch`,
|
|
2129
2242
|
`InvalidCredential`, `InvalidPathParameter`, `InvalidUrl`, `InvalidVariable`,
|
|
2130
2243
|
`MissingVariable`, `NoRouteExists`, `PathParamsMismatch`, `RecipeFileError`,
|
|
2131
|
-
`ResponseCodeNotAsExpected` and `
|
|
2244
|
+
`ResponseCodeNotAsExpected`, `UnknownEndpoint` and `UnreadableResponse`). If
|
|
2245
|
+
your application has a
|
|
2132
2246
|
class with one of these names, write it with a leading `::` inside the classes
|
|
2133
2247
|
that include `ApiRecipes`, for example `::Response`. The internal classes of
|
|
2134
2248
|
the gem are all under `ApiRecipes::Internals`, so they hide nothing else.
|
data/UPGRADING.md
CHANGED
|
@@ -95,7 +95,10 @@ configuration in place. Four things are worth knowing:
|
|
|
95
95
|
`variables: { template: { default: '{id}' } }` with the header value
|
|
96
96
|
`'{template}'`. Braces around anything else, such as a JSON value, are sent
|
|
97
97
|
as they are. In a path, if you meant a value that changes at every call,
|
|
98
|
-
write a placeholder, `/items/:id`.
|
|
98
|
+
write a placeholder, `/items/:id`. In the `base_url` and in a `path`, a
|
|
99
|
+
word in braces with a star, `{*id}`, is a variable too, whose value spans
|
|
100
|
+
several segments: `api_recipes convert` writes `\{*id}`, whether the file
|
|
101
|
+
declares `id` or not.
|
|
99
102
|
- A recipe that is missing, not valid YAML, not valid UTF-8 or not a recipe
|
|
100
103
|
raises `ApiRecipes::RecipeFileError`, which names the file. A recipe is
|
|
101
104
|
plain YAML: anchors, aliases, tags and the merge key are refused.
|
|
@@ -114,7 +117,10 @@ describes to a recipe in `config/api_recipes`, one after the other:
|
|
|
114
117
|
|
|
115
118
|
- what an `<%= ... %>` tag gave becomes a variable of the recipe, and the code
|
|
116
119
|
of the tag moves, as it is written, to `config.values` in the file that
|
|
117
|
-
calls `ApiRecipes.configure`;
|
|
120
|
+
calls `ApiRecipes.configure`; in the `base_url` and in a `path` it is a
|
|
121
|
+
`{*name}`, which keeps the slashes inside the value as 2.x did, while a
|
|
122
|
+
value that starts or ends with a slash, has two in a row or is empty raises
|
|
123
|
+
`ApiRecipes::InvalidVariable`: set `API_PREFIX=api/v1`, not `/api/v1`;
|
|
118
124
|
- `config.recipes_paths` is added, and `config.apis_files_paths` goes with the
|
|
119
125
|
last description;
|
|
120
126
|
- the old file is deleted, and every change is listed.
|
|
@@ -138,7 +144,8 @@ own raises:
|
|
|
138
144
|
```
|
|
139
145
|
api 'github': the credential is bound to "https://api.github.com" but the request goes to
|
|
140
146
|
"https://ent.example.test". Set the credential at the level that changes the destination,
|
|
141
|
-
or set it to nil to send none
|
|
147
|
+
or set it to nil to send none, or name that origin in credential_origins, next to the
|
|
148
|
+
credential in config.values
|
|
142
149
|
```
|
|
143
150
|
|
|
144
151
|
Give the credential where the class declares the API:
|
|
@@ -150,6 +157,10 @@ class EnterpriseClient
|
|
|
150
157
|
end
|
|
151
158
|
```
|
|
152
159
|
|
|
160
|
+
When the credential of the application is meant for that origin too, name the
|
|
161
|
+
origin with `credential_origins` in `config.values` instead (see
|
|
162
|
+
"Authorization" in the README).
|
|
163
|
+
|
|
153
164
|
### Credentials are given when the application starts
|
|
154
165
|
|
|
155
166
|
In 2.x the usual line was `ApiRecipes.github.authorization = '...'`, and code
|
|
@@ -277,7 +288,8 @@ ApiRecipes.github.users.show('a/b').url.to_s
|
|
|
277
288
|
|
|
278
289
|
- **Values you encoded yourself.** Remove the encoding (`ERB::Util.url_encode`,
|
|
279
290
|
`CGI.escape`): `%2F` would be sent as `%252F`. The gem logs a warning, once for
|
|
280
|
-
each endpoint, when a value looks already encoded.
|
|
291
|
+
each endpoint, when a value looks already encoded. A value that the API gave
|
|
292
|
+
already encoded, such as an id it returned in that form, is given as it is.
|
|
281
293
|
- **A `/` in a value** that was used to cover several segments is now `%2F`. Write
|
|
282
294
|
the placeholder with a `*` instead: each segment is encoded and the slashes stay.
|
|
283
295
|
The gem logs a warning, once for each endpoint, when a value contains a `/`.
|
|
@@ -364,6 +376,33 @@ to the other host. Cookies that a server sets during a chain of redirects are no
|
|
|
364
376
|
carried to the next hop any more (they were with http.rb 5). A page that sets a
|
|
365
377
|
cookie and redirects to itself now ends in the redirect-loop error of http.rb.
|
|
366
378
|
|
|
379
|
+
### `response.data` on an empty body, and on one it cannot read
|
|
380
|
+
|
|
381
|
+
In 2.x `data` passed on whatever http.rb or the JSON parser raised, also for a
|
|
382
|
+
response with no body. Now an empty body gives `nil`, and a body that cannot be
|
|
383
|
+
read (no `Content-Type`, a type that is not JSON, JSON that is not valid) raises
|
|
384
|
+
`ApiRecipes::UnreadableResponse`, whose message never contains the body. The
|
|
385
|
+
body is still on the response:
|
|
386
|
+
|
|
387
|
+
```ruby
|
|
388
|
+
begin
|
|
389
|
+
response.data
|
|
390
|
+
rescue ApiRecipes::UnreadableResponse => e
|
|
391
|
+
e.response.body.to_s
|
|
392
|
+
end
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
A `rescue HTTP::Error` or a `rescue JSON::ParserError` written around `data`
|
|
396
|
+
no longer catches it. The same holds around `fill`, and around a `run` whose
|
|
397
|
+
`verify_with` method reads `data`. Timeouts and connection errors are still
|
|
398
|
+
errors of http.rb. Code that reads a key of `data` after a call that can answer
|
|
399
|
+
without a body gets `nil`: check `response.data.nil?` first.
|
|
400
|
+
|
|
401
|
+
`response.parse` is no longer the method of http.rb. It reads the body as
|
|
402
|
+
`data` does, with the type it is given: `nil` for an empty body,
|
|
403
|
+
`ApiRecipes::UnreadableResponse` for one it cannot read. The method of http.rb
|
|
404
|
+
is `response.original_response.parse`.
|
|
405
|
+
|
|
367
406
|
### `fill`
|
|
368
407
|
|
|
369
408
|
`fill` calls only public writers. It used to call private ones, and it swallowed
|
|
@@ -379,7 +418,8 @@ classes. In 3.0 `Route` and `Settings` are gone, so a top-level `Route` or
|
|
|
379
418
|
`Settings` of yours is found again. `Error`, `Internals`, `VERSION` and the new
|
|
380
419
|
error classes (`ConfigurationError`, `CredentialOriginMismatch`,
|
|
381
420
|
`InvalidCredential`, `InvalidPathParameter`, `InvalidUrl`, `InvalidVariable`,
|
|
382
|
-
`MissingVariable`, `RecipeFileError`, `UnknownEndpoint`)
|
|
421
|
+
`MissingVariable`, `RecipeFileError`, `UnknownEndpoint`, `UnreadableResponse`)
|
|
422
|
+
are new, and hide a
|
|
383
423
|
top-level constant of yours with the same name. Inside the classes that include
|
|
384
424
|
`ApiRecipes`, write it with a leading `::`, for example `::Error`. The
|
|
385
425
|
[README](README.md#good-to-know) lists all the names.
|
|
@@ -396,7 +436,8 @@ top-level constant of yours with the same name. Inside the classes that include
|
|
|
396
436
|
`auth: { type: 'query' }`.
|
|
397
437
|
- `response.request` was removed, because the request holds the credentials that
|
|
398
438
|
were sent. `response.uri` and the other readers stay, and the http.rb response
|
|
399
|
-
is still `response.original_response`.
|
|
439
|
+
is still `response.original_response`. `response.flush` returns the response of
|
|
440
|
+
the gem, not the one of http.rb.
|
|
400
441
|
- `response.to_s` returns the body, as the http.rb response does. In 2.x it was
|
|
401
442
|
the default text of the object.
|
|
402
443
|
- A redirect to a host with non-ASCII characters needs the `addressable` gem;
|
|
@@ -470,7 +511,8 @@ You can adopt these when you are ready. The [README](README.md) describes each o
|
|
|
470
511
|
|
|
471
512
|
- Path parameters are encoded, and `nil`, empty, `.` and `..` are refused.
|
|
472
513
|
- Variables are checked where they end up: host, path or header.
|
|
473
|
-
- A credential is sent only to the origin it was set for,
|
|
514
|
+
- A credential is sent only to the origin it was set for, or to one that the
|
|
515
|
+
application names for it with `credential_origins`, and a value with a
|
|
474
516
|
control character is refused.
|
|
475
517
|
- Redirects to another origin drop the credentials and cookies.
|
|
476
518
|
- Logs, error messages of the gem and `inspect` never show a credential, a
|
|
@@ -86,7 +86,7 @@ module ApiRecipes
|
|
|
86
86
|
refuse('already has the key recipe: rename the file to NAME.recipe.yml and check it') if options.key?('recipe')
|
|
87
87
|
|
|
88
88
|
body = api_options(options)
|
|
89
|
-
body = { 'recipe' => { 'name' => name, 'version' => @version, 'format' => Internals::Recipe::
|
|
89
|
+
body = { 'recipe' => { 'name' => name, 'version' => @version, 'format' => Internals::Recipe::FORMATS.first } }.merge(body)
|
|
90
90
|
# A variable that has no default needs no declaration: the recipe
|
|
91
91
|
# uses it, and that makes it a variable that a value must be given to.
|
|
92
92
|
written = @variables.reject { |_, spec| spec.empty? }
|
|
@@ -267,7 +267,7 @@ module ApiRecipes
|
|
|
267
267
|
when 'verify_with' then left_out(key, value)
|
|
268
268
|
when 'variables' then out[key] = declared_variables(value)
|
|
269
269
|
when 'host' then out[key] = with_variables(value, key, key)
|
|
270
|
-
when 'base_url' then out[key] = with_variables(as_text(value, key), key, key)
|
|
270
|
+
when 'base_url' then out[key] = with_variables(as_text(value, key), key, key, star: true)
|
|
271
271
|
when *OPTION_KEYS then out[key] = option(value, key, key)
|
|
272
272
|
when *SENT then out[key] = sent(value, key)
|
|
273
273
|
when 'endpoints' then out[key] = endpoints(value, key)
|
|
@@ -308,7 +308,7 @@ module ApiRecipes
|
|
|
308
308
|
here = "#{where}.#{key}"
|
|
309
309
|
case key
|
|
310
310
|
when 'verify_with' then left_out(here, value)
|
|
311
|
-
when 'path' then out[key] = with_variables(as_text(value, here), here, "#{name}_path")
|
|
311
|
+
when 'path' then out[key] = with_variables(as_text(value, here), here, "#{name}_path", star: true)
|
|
312
312
|
when *OPTION_KEYS then out[key] = option(value, here, "#{name}_#{key}")
|
|
313
313
|
when *SENT then out[key] = sent(value, here)
|
|
314
314
|
when 'endpoints' then out[key] = endpoints(value, here)
|
|
@@ -351,12 +351,16 @@ module ApiRecipes
|
|
|
351
351
|
# A word in braces that the file does not declare as a variable: 2.x
|
|
352
352
|
# sent it as text, and 3.0 would read it as a variable. In a path and
|
|
353
353
|
# in the base_url a backslash before the brace already keeps it text;
|
|
354
|
-
# a header and a parameter have no such escape.
|
|
355
|
-
|
|
354
|
+
# a header and a parameter have no such escape. With a star, {*word},
|
|
355
|
+
# it was text in every version before, declared or not: in a path and
|
|
356
|
+
# in the base_url 3.0 reads it as a variable of several segments.
|
|
357
|
+
TEXT_IN_BRACES = /(?<!\\)\{(\*?)([A-Za-z_]\w*)\}/
|
|
356
358
|
|
|
357
359
|
def text_in_braces?(value, escaped: true)
|
|
358
|
-
|
|
359
|
-
|
|
360
|
+
return false unless value.is_a?(String)
|
|
361
|
+
return value.scan(Internals::Template::VARIABLE).flatten.any? { |name| @origins[name] != :declared } unless escaped
|
|
362
|
+
|
|
363
|
+
value.scan(TEXT_IN_BRACES).any? { |star, name| !star.empty? || @origins[name] != :declared }
|
|
360
364
|
end
|
|
361
365
|
|
|
362
366
|
# In a path and in the base_url a brace is kept as text with a backslash.
|
|
@@ -364,11 +368,12 @@ module ApiRecipes
|
|
|
364
368
|
return value unless text_in_braces?(value)
|
|
365
369
|
|
|
366
370
|
value.gsub(TEXT_IN_BRACES) do
|
|
367
|
-
name = Regexp.last_match
|
|
368
|
-
next Regexp.last_match(0) if @origins[name] == :declared
|
|
371
|
+
star, name = Regexp.last_match.captures
|
|
372
|
+
next Regexp.last_match(0) if star.empty? && @origins[name] == :declared
|
|
369
373
|
|
|
370
|
-
|
|
371
|
-
"
|
|
374
|
+
word = "{#{star}#{shown(name)}}"
|
|
375
|
+
@changes << "#{shown(where)}: #{word} was text in 2.x and would be a variable: it is written \\#{word}"
|
|
376
|
+
"\\{#{star}#{name}}"
|
|
372
377
|
end
|
|
373
378
|
end
|
|
374
379
|
|
|
@@ -412,18 +417,36 @@ module ApiRecipes
|
|
|
412
417
|
end
|
|
413
418
|
|
|
414
419
|
# A value where a recipe can have a variable.
|
|
415
|
-
|
|
420
|
+
# star: in the base_url and in a path, where 2.x put the value of the
|
|
421
|
+
# tag as it was, slashes included: the variable spans several segments.
|
|
422
|
+
def with_variables(value, where, fallback, star: false)
|
|
416
423
|
return fixed(value, where) unless value.is_a?(String) && @token.match?(value)
|
|
417
424
|
|
|
418
425
|
value.gsub(@token) do
|
|
419
426
|
tag = @tags[Regexp.last_match(1).to_i]
|
|
420
427
|
variable = variable_for(tag, fallback, where, default: true)
|
|
421
428
|
kept = @variables[variable].key?('default') ? ', with the default written in the tag' : ''
|
|
422
|
-
|
|
423
|
-
"{#{
|
|
429
|
+
as_variable = "{#{'*' if star}#{variable}}"
|
|
430
|
+
@changes << "#{shown(where)}: the ERB tag is now the variable #{as_variable}#{kept}"
|
|
431
|
+
refused_default(where, variable) if star
|
|
432
|
+
as_variable
|
|
424
433
|
end
|
|
425
434
|
end
|
|
426
435
|
|
|
436
|
+
# 2.x joined the slashes of a value; a {*name} refuses a value that
|
|
437
|
+
# starts or ends with one, has two in a row or is empty. Said with the
|
|
438
|
+
# place and the name, never with the value.
|
|
439
|
+
def refused_default(where, variable)
|
|
440
|
+
spec = @variables[variable]
|
|
441
|
+
return unless spec.key?('default')
|
|
442
|
+
|
|
443
|
+
Internals::Template.segments(spec['default'], variable, @name)
|
|
444
|
+
rescue InvalidVariable
|
|
445
|
+
@changes << "#{shown(where)}: the default written in the tag is not a value that {*#{variable}} takes: one or more " \
|
|
446
|
+
'segments, with no slash at the start or at the end and no two in a row. Correct it in the recipe ' \
|
|
447
|
+
'and in the code of the tag, which config.values gives'
|
|
448
|
+
end
|
|
449
|
+
|
|
427
450
|
def variable_for(tag, fallback, where, default:)
|
|
428
451
|
# What is named like a credential in the environment has no default either.
|
|
429
452
|
default &&= !CREDENTIAL.match?(tag.env.to_s)
|
|
@@ -36,7 +36,7 @@ module ApiRecipes
|
|
|
36
36
|
tree = Tree.build(document, only: @only, except: @except)
|
|
37
37
|
raise Error, '--version: must be made of digits, letters and dots, such as 1.2.0' unless Internals::Recipe::VERSION.match?(@version.to_s)
|
|
38
38
|
|
|
39
|
-
options = { recipe: { 'name' => name, 'version' => @version, 'format' => Internals::Recipe::
|
|
39
|
+
options = { recipe: { 'name' => name, 'version' => @version, 'format' => Internals::Recipe::FORMATS.first } }.merge(server.options)
|
|
40
40
|
options[:auth] = security.auth if security.auth
|
|
41
41
|
header = "Generated by api_recipes import from #{document.title} #{document.version}"
|
|
42
42
|
text = Writer.new(name: name, options: options, nodes: tree.nodes, header: header).to_yaml
|
|
@@ -72,7 +72,7 @@ module ApiRecipes
|
|
|
72
72
|
def address(fill = false)
|
|
73
73
|
host = fill ? filled(@api.host) : @api.host
|
|
74
74
|
base = @api.base_url.to_s
|
|
75
|
-
base = filled(base) if fill
|
|
75
|
+
base = filled(base, Internals::Template::PATH_VARIABLE) if fill
|
|
76
76
|
path = "/#{base}".gsub(%r{/+}, '/').chomp('/')
|
|
77
77
|
protocol = fill ? filled(@api.protocol.to_s) : @api.protocol
|
|
78
78
|
port = fill && @api.port ? filled(@api.port.to_s) : @api.port
|
|
@@ -216,9 +216,11 @@ module ApiRecipes
|
|
|
216
216
|
found
|
|
217
217
|
end
|
|
218
218
|
|
|
219
|
-
|
|
219
|
+
# The base_url reads {name} and {*name}, with PATH_VARIABLE; the rest
|
|
220
|
+
# reads {name} only. The name is the last group of both.
|
|
221
|
+
def filled(text, pattern = Internals::Template::VARIABLE)
|
|
220
222
|
defaults = @api.variables.transform_values { |spec| spec[:default] }.compact
|
|
221
|
-
text.gsub(
|
|
223
|
+
text.gsub(pattern) { defaults.fetch(Regexp.last_match[-1].to_sym, Regexp.last_match(0)) }
|
|
222
224
|
end
|
|
223
225
|
|
|
224
226
|
# One line for each variable: its default, or that it must be set.
|
|
@@ -101,6 +101,8 @@ module ApiRecipes
|
|
|
101
101
|
'a bare rescue in a file that does not name the gem, around code that calls it somewhere else: it now catches the errors of the gem too',
|
|
102
102
|
'the response body read from the message of a verify_with error: read it from error.response',
|
|
103
103
|
'fill with private setters, or code that relies on swallowed errors: make the setters public, handle the errors',
|
|
104
|
+
'a rescue of HTTP::Error or of JSON::ParserError around response.data, around response.parse, around fill, or ' \
|
|
105
|
+
'around a run whose verify_with reads data: an empty body now gives nil, and a body that cannot be read raises ApiRecipes::UnreadableResponse',
|
|
104
106
|
'cookies set by a server during a redirect chain: they are no longer carried to the next hop',
|
|
105
107
|
'Endpoint#name, #params, #children, #api and Api#name, #configs, #object were removed: use definition (a search cannot tell them from other methods called like that)',
|
|
106
108
|
'an object restored from a serialized form (Marshal, YAML) has no credential: assign it again',
|
data/lib/api_recipes/errors.rb
CHANGED
|
@@ -67,16 +67,19 @@ module ApiRecipes
|
|
|
67
67
|
end
|
|
68
68
|
|
|
69
69
|
class CredentialOriginMismatch < Error
|
|
70
|
-
|
|
70
|
+
# application: the credential is the one of config.values, the only one
|
|
71
|
+
# that credential_origins can send to other origins.
|
|
72
|
+
def initialize(api, credential_origin, request_origin, application: false)
|
|
73
|
+
remedy = application ? ', or name that origin in credential_origins, next to the credential in config.values' : ''
|
|
71
74
|
if credential_origin
|
|
72
75
|
super("api '#{api}': the credential is bound to #{credential_origin.inspect} but the request goes to " \
|
|
73
76
|
"#{request_origin.inspect}. Set the credential at the level that changes the destination, " \
|
|
74
|
-
|
|
77
|
+
"or set it to nil to send none#{remedy}")
|
|
75
78
|
else
|
|
76
79
|
super("api '#{api}': the origin of the credential cannot be determined at the level that holds it " \
|
|
77
80
|
'(for example, a variable of the host has no value there), so it is not sent to ' \
|
|
78
81
|
"#{request_origin.inspect}. Set the credential at the level that sets the destination, " \
|
|
79
|
-
|
|
82
|
+
"or give the level that holds it the values its host needs#{remedy}")
|
|
80
83
|
end
|
|
81
84
|
end
|
|
82
85
|
end
|
|
@@ -122,6 +125,20 @@ module ApiRecipes
|
|
|
122
125
|
end
|
|
123
126
|
end
|
|
124
127
|
|
|
128
|
+
# Raised by Response#data for a body it cannot read. The message has the
|
|
129
|
+
# route, the status and the content type: never the body, which is on
|
|
130
|
+
# response.body.
|
|
131
|
+
class UnreadableResponse < Error
|
|
132
|
+
attr_reader :path, :response
|
|
133
|
+
|
|
134
|
+
def initialize(path, response, reason, advice)
|
|
135
|
+
@path = path
|
|
136
|
+
@response = response
|
|
137
|
+
route = path ? " on route '#{path}'" : ''
|
|
138
|
+
super("cannot read the data of the response#{route} (#{response.code}): #{reason}. #{advice}")
|
|
139
|
+
end
|
|
140
|
+
end
|
|
141
|
+
|
|
125
142
|
class ApiConfigIsNotAnHash < Error
|
|
126
143
|
def initialize(endpoint)
|
|
127
144
|
message = "provided config for endpoint '#{endpoint}' must be an Hash"
|
|
@@ -264,12 +264,17 @@ module ApiRecipes
|
|
|
264
264
|
# The global level uses the global definition, the others the owner's one:
|
|
265
265
|
# every other level of the chain was written through the declaration in
|
|
266
266
|
# use, whose tree that is.
|
|
267
|
+
# The level of the application can name other origins for the
|
|
268
|
+
# credential it holds, with credential_origins: no other level is asked.
|
|
267
269
|
def check_origin(chain, index, destination)
|
|
270
|
+
kind, level = chain[index]
|
|
271
|
+
return if kind == :global && Origins.name?(level.origins, destination)
|
|
272
|
+
|
|
268
273
|
registry = chain.respond_to?(:registry) ? chain.registry : Registry.current
|
|
269
|
-
bound = origin_from(definition_in_force(
|
|
274
|
+
bound = origin_from(definition_in_force(kind, registry), chain, index, with: false)
|
|
270
275
|
return if bound && destination && bound.casecmp?(destination)
|
|
271
276
|
|
|
272
|
-
raise CredentialOriginMismatch.new(@definition.name, bound, destination)
|
|
277
|
+
raise CredentialOriginMismatch.new(@definition.name, bound, destination, application: kind == :global)
|
|
273
278
|
end
|
|
274
279
|
|
|
275
280
|
# The tree a level reads now. An api or an endpoint kept across a
|
|
@@ -4,7 +4,12 @@ module ApiRecipes
|
|
|
4
4
|
module Internals
|
|
5
5
|
# What was assigned to one api at one level: a credential (nil when never
|
|
6
6
|
# assigned, Credential::NONE when removed on purpose) and variable values.
|
|
7
|
-
|
|
7
|
+
# origins is what credential_origins gave with the credential, see
|
|
8
|
+
# Origins: only the level of the application has it, and a level that is
|
|
9
|
+
# written, sealed or read back from a serialized form never does.
|
|
10
|
+
Level = Data.define(:credential, :variables, :origins) do
|
|
11
|
+
def initialize(credential:, variables:, origins: nil) = super
|
|
12
|
+
|
|
8
13
|
def inspect = "#<ApiRecipes::Internals::Level credential=#{credential.inspect} variables=[FILTERED]>"
|
|
9
14
|
|
|
10
15
|
def to_s = inspect
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ApiRecipes
|
|
4
|
+
module Internals
|
|
5
|
+
# The other origins a credential of the application may go to, as
|
|
6
|
+
# credential_origins says in config.values: :any, or a list of whole
|
|
7
|
+
# origins. The origin the credential was given for needs no entry.
|
|
8
|
+
module Origins
|
|
9
|
+
ANY = :any
|
|
10
|
+
KEY = :credential_origins
|
|
11
|
+
# A scheme, a host as the gem takes one and a port: nothing before,
|
|
12
|
+
# nothing after, so no user, no path and no line break. It is matched
|
|
13
|
+
# against ASCII text only: without its case, a letter of another
|
|
14
|
+
# alphabet is taken for one of these.
|
|
15
|
+
ENTRY = %r{\A(https?)://([A-Za-z0-9._-]+)(?::([0-9]{1,5}))?\z}i
|
|
16
|
+
PORTS = (1..65_535)
|
|
17
|
+
WHOLE = "'scheme://host' or 'scheme://host:port', with https or http as the scheme"
|
|
18
|
+
|
|
19
|
+
class << self
|
|
20
|
+
# nil, ANY, or a frozen list of origins written as a request writes
|
|
21
|
+
# its own. An entry that is refused is named by its position, never
|
|
22
|
+
# shown: it can hold a user and a password.
|
|
23
|
+
def from(value, where)
|
|
24
|
+
return nil if value.nil?
|
|
25
|
+
return ANY if ANY.equal?(value)
|
|
26
|
+
unless Array === value && !value.empty?
|
|
27
|
+
raise ConfigurationError.new(["#{where}.#{KEY}: must be :any or a list of origins, each written as #{WHOLE}"])
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
value.each_with_index.map do |entry, index|
|
|
31
|
+
written(entry) || raise(ConfigurationError.new(
|
|
32
|
+
["#{where}.#{KEY}: entry #{index + 1} is not an origin: write it as #{WHOLE}, and nothing else"]
|
|
33
|
+
))
|
|
34
|
+
end.uniq.freeze
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# Whether origins, as from returned them, name destination.
|
|
38
|
+
def name?(origins, destination)
|
|
39
|
+
return true if origins == ANY
|
|
40
|
+
return false if origins.nil? || destination.nil?
|
|
41
|
+
|
|
42
|
+
origins.any? { |origin| origin.casecmp?(destination) }
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
private
|
|
46
|
+
|
|
47
|
+
# entry as Context#address writes an origin: without the default
|
|
48
|
+
# port. nil when it is not a whole origin. What is checked is a copy
|
|
49
|
+
# that is a String and nothing more: an object of a subclass is not
|
|
50
|
+
# asked what it holds.
|
|
51
|
+
def written(entry)
|
|
52
|
+
return nil unless String === entry
|
|
53
|
+
|
|
54
|
+
text = String.new(entry)
|
|
55
|
+
return nil unless text.ascii_only?
|
|
56
|
+
|
|
57
|
+
match = ENTRY.match(text)
|
|
58
|
+
return nil unless match
|
|
59
|
+
|
|
60
|
+
scheme = match[1].downcase
|
|
61
|
+
port = match[3]&.to_i
|
|
62
|
+
return nil unless port.nil? || PORTS.cover?(port)
|
|
63
|
+
|
|
64
|
+
port = nil if port == Context::DEFAULT_PORTS[scheme]
|
|
65
|
+
"#{scheme}://#{match[2]}#{":#{port}" if port}".freeze
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
end
|
|
@@ -10,6 +10,7 @@ module ApiRecipes
|
|
|
10
10
|
FIXED_KEPT = /\A(?:[A-Za-z0-9\-._~!$&'()*+,;=:@\/]|%\h\h)/
|
|
11
11
|
UNRESERVED = /[A-Za-z0-9\-._~]/
|
|
12
12
|
ENCODED_SEQUENCE = /%25\h\h/
|
|
13
|
+
VARIABLE_KINDS = %i[variable segments].freeze
|
|
13
14
|
|
|
14
15
|
# Percent-encodes every byte outside letters, digits and -._~
|
|
15
16
|
def self.escape(string)
|
|
@@ -29,11 +30,11 @@ module ApiRecipes
|
|
|
29
30
|
repeated = names.find { |name| names.count(name) > 1 }
|
|
30
31
|
raise ArgumentError, "placeholder '#{repeated}' is repeated in '#{string}'" if repeated
|
|
31
32
|
@param_names = names.freeze
|
|
32
|
-
@variable_names = @parts.select { |kind, _| kind
|
|
33
|
+
@variable_names = @parts.select { |kind, _| VARIABLE_KINDS.include?(kind) }.map(&:last).uniq.freeze
|
|
33
34
|
end
|
|
34
35
|
|
|
35
36
|
# param_names: the placeholders, which take an argument each, in order.
|
|
36
|
-
# variable_names: the {variables} of the api, each once.
|
|
37
|
+
# variable_names: the {variables} and {*variables} of the api, each once.
|
|
37
38
|
attr_reader :param_names, :variable_names
|
|
38
39
|
|
|
39
40
|
# The block, if given, is called with the name of a parameter, :slash when
|
|
@@ -68,14 +69,15 @@ module ApiRecipes
|
|
|
68
69
|
encoded = encode_splat(remaining.shift, content, endpoint)
|
|
69
70
|
out << encoded
|
|
70
71
|
yield content, :encoded, endpoint if block_given? && encoded.include?('%25') && encoded.match?(ENCODED_SEQUENCE)
|
|
71
|
-
when :variable
|
|
72
|
+
when :variable, :segments
|
|
72
73
|
raise ArgumentError, 'a path with variables needs a context' if context.nil?
|
|
73
74
|
|
|
74
75
|
variables ||= context.variables
|
|
75
76
|
api = context.definition.name
|
|
76
77
|
raise MissingVariable.new(api, content) unless variables.key?(content)
|
|
77
78
|
|
|
78
|
-
|
|
79
|
+
value = variables[content]
|
|
80
|
+
out << (kind == :segments ? Template.segments(value, content, api) : Template.segment(value, content, api))
|
|
79
81
|
end
|
|
80
82
|
end
|
|
81
83
|
out
|
|
@@ -88,6 +90,7 @@ module ApiRecipes
|
|
|
88
90
|
when :param then ":#{content}"
|
|
89
91
|
when :splat then "*#{content}"
|
|
90
92
|
when :variable then "{#{content}}"
|
|
93
|
+
when :segments then "{*#{content}}"
|
|
91
94
|
end
|
|
92
95
|
end.join
|
|
93
96
|
end
|
|
@@ -107,9 +110,9 @@ module ApiRecipes
|
|
|
107
110
|
elsif rest.start_with?('\\{')
|
|
108
111
|
text << '%7B'
|
|
109
112
|
index += 2
|
|
110
|
-
elsif (match = rest.match(/\A\{(#{NAME})\}/o))
|
|
113
|
+
elsif (match = rest.match(/\A\{(\*?)(#{NAME})\}/o))
|
|
111
114
|
flush(parts, text)
|
|
112
|
-
parts << [:variable, match[
|
|
115
|
+
parts << [match[1].empty? ? :variable : :segments, match[2].to_sym]
|
|
113
116
|
index += match[0].length
|
|
114
117
|
elsif (match = rest.match(/\A:(#{NAME})/o))
|
|
115
118
|
flush(parts, text)
|
|
@@ -10,7 +10,7 @@ module ApiRecipes
|
|
|
10
10
|
class Recipe
|
|
11
11
|
MAX_BYTES = 1_048_576
|
|
12
12
|
SUFFIX = '.recipe.yml'
|
|
13
|
-
|
|
13
|
+
FORMATS = [1].freeze
|
|
14
14
|
NAME = /\A[a-z0-9_][a-z0-9_-]{0,63}\z/
|
|
15
15
|
VERSION = /\A[0-9A-Za-z]+(?:\.[0-9A-Za-z]+)*\z/
|
|
16
16
|
MAX_VERSION = 32
|
|
@@ -241,9 +241,9 @@ module ApiRecipes
|
|
|
241
241
|
end
|
|
242
242
|
problems << "recipe.name must be '#{name}', the name of the api" unless recipe['name'] == name
|
|
243
243
|
problems.concat(version_problems(recipe['version']))
|
|
244
|
-
unless recipe['format'].nil? || recipe['format']
|
|
244
|
+
unless recipe['format'].nil? || FORMATS.include?(recipe['format'])
|
|
245
245
|
problems << "recipe.format #{PlainYaml.label(recipe['format'])} is not known to this version of api_recipes " \
|
|
246
|
-
"(it knows #{
|
|
246
|
+
"(it knows #{FORMATS.join(' and ')}): update the gem"
|
|
247
247
|
end
|
|
248
248
|
summary = recipe['summary']
|
|
249
249
|
unless summary.nil? || (summary.is_a?(String) && summary.length <= MAX_TEXT)
|
|
@@ -62,8 +62,8 @@ module ApiRecipes
|
|
|
62
62
|
"#{endpoint}: the value of '#{param}' contains '/' and is now sent as %2F. " \
|
|
63
63
|
"To span several segments use *#{param} in the path."
|
|
64
64
|
else
|
|
65
|
-
"#{endpoint}: the value of '#{param}' looks already percent-encoded. " \
|
|
66
|
-
'
|
|
65
|
+
"#{endpoint}: the value of '#{param}' looks already percent-encoded, and is encoded again. " \
|
|
66
|
+
'If your code encoded it, give it decoded; if the API gave it in this form, give it as it is.'
|
|
67
67
|
end
|
|
68
68
|
warn_once([endpoint, param, kind], message)
|
|
69
69
|
end
|
|
@@ -98,20 +98,25 @@ module ApiRecipes
|
|
|
98
98
|
raise ConfigurationError.new(["values.#{shown}: is not the name of an api"]) unless shown == name.to_s && !shown.empty?
|
|
99
99
|
raise ConfigurationError.new(["values.#{key}: is given twice"]) if levels.key?(key)
|
|
100
100
|
|
|
101
|
-
levels[key] = level_from(given, "values.#{key}")
|
|
101
|
+
levels[key] = level_from(given, "values.#{key}", origins: true)
|
|
102
102
|
end.freeze
|
|
103
103
|
end
|
|
104
104
|
|
|
105
105
|
# The level that given describes: variables, and authorization or
|
|
106
|
-
# basic_auth. A credential given as nil means "send none".
|
|
107
|
-
|
|
106
|
+
# basic_auth. A credential given as nil means "send none". origins:
|
|
107
|
+
# true for the level of the application, the only one that takes
|
|
108
|
+
# credential_origins: the key is taken out here and is no option for
|
|
109
|
+
# the compiler, which refuses it wherever else it is written.
|
|
110
|
+
def level_from(given, where, origins: false)
|
|
108
111
|
raise ConfigurationError.new(["#{where}: must be a Hash"]) unless given.is_a?(Hash)
|
|
109
112
|
|
|
110
113
|
texts = given.keys.map(&:to_s)
|
|
111
|
-
|
|
114
|
+
names = VALUE_KEYS.map(&:to_s)
|
|
115
|
+
names += [Origins::KEY.to_s] if origins
|
|
116
|
+
# What is not one of these names is not shown: a credential
|
|
112
117
|
# written in the wrong place would be.
|
|
113
|
-
unless (texts -
|
|
114
|
-
raise ConfigurationError.new(["#{where}: takes
|
|
118
|
+
unless (texts - names).empty?
|
|
119
|
+
raise ConfigurationError.new(["#{where}: takes #{names[0..-2].join(', ')} and #{names.last}, and nothing else"])
|
|
115
120
|
end
|
|
116
121
|
twice = texts.find { |text| texts.count(text) > 1 }
|
|
117
122
|
raise ConfigurationError.new(["#{where}: #{twice} is given twice"]) if twice
|
|
@@ -121,9 +126,15 @@ module ApiRecipes
|
|
|
121
126
|
raise ConfigurationError.new(["#{where}: takes authorization or basic_auth, not both"])
|
|
122
127
|
end
|
|
123
128
|
|
|
124
|
-
resolved = Compiler.resolve_options(given, :with_api)
|
|
125
129
|
kind = (names & %i[authorization basic_auth]).first
|
|
126
|
-
|
|
130
|
+
about_origins, given = given.partition { |key, _value| key.to_s == Origins::KEY.to_s }.map(&:to_h)
|
|
131
|
+
unless about_origins.values.first.nil? || kind
|
|
132
|
+
raise ConfigurationError.new(["#{where}: #{Origins::KEY} is given with authorization or basic_auth"])
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
resolved = Compiler.resolve_options(given, :with_api)
|
|
136
|
+
Level.new(credential: kind && Credential.from(kind, resolved[kind]), variables: resolved[:variables],
|
|
137
|
+
origins: Origins.from(about_origins.values.first, where))
|
|
127
138
|
rescue ConfigurationError => e
|
|
128
139
|
raise e if e.errors.all? { |problem| problem.start_with?(where) }
|
|
129
140
|
|
|
@@ -285,7 +285,7 @@ module ApiRecipes
|
|
|
285
285
|
mime_type = setting(:mime_type)
|
|
286
286
|
hidden = auth[:type] == :query ? auth[:name] : nil
|
|
287
287
|
success, expected, message = outcome(http_response, mime_type, hidden)
|
|
288
|
-
response = Response.new(http_response, mime_type: mime_type, success: success, hidden_param: hidden)
|
|
288
|
+
response = Response.new(http_response, mime_type: mime_type, success: success, hidden_param: hidden, path: @path)
|
|
289
289
|
if !success && setting(:on_bad_code).to_s == 'raise'
|
|
290
290
|
raise ResponseCodeNotAsExpected.new(@path, expected, response, message: message)
|
|
291
291
|
end
|
|
@@ -298,7 +298,7 @@ module ApiRecipes
|
|
|
298
298
|
verify_with = setting(:verify_with)
|
|
299
299
|
owner = @context.owner
|
|
300
300
|
if verify_with && owner.respond_to?(verify_with, true)
|
|
301
|
-
checked = Response.new(http_response, mime_type: mime_type, hidden_param: hidden)
|
|
301
|
+
checked = Response.new(http_response, mime_type: mime_type, hidden_param: hidden, path: @path)
|
|
302
302
|
valid = owner.send(verify_with, checked) ? true : false
|
|
303
303
|
return [valid, nil, "response for request on route '#{@path}' was not valid. Verified with #{verify_with}."]
|
|
304
304
|
end
|
|
@@ -7,9 +7,16 @@ module ApiRecipes
|
|
|
7
7
|
# How a value is checked depends on the position.
|
|
8
8
|
class Template
|
|
9
9
|
VARIABLE = /\{([A-Za-z_]\w*)\}/
|
|
10
|
+
# A variable whose value spans several segments: read in a base_url and
|
|
11
|
+
# in the path of an endpoint only. Elsewhere it is text.
|
|
12
|
+
SEGMENTS_VARIABLE = /\{\*([A-Za-z_]\w*)\}/
|
|
13
|
+
# What a base_url reads: {name} and {*name}.
|
|
14
|
+
PATH_VARIABLE = /\{(\*?)([A-Za-z_]\w*)\}/
|
|
10
15
|
HOST_VALUE = /\A[A-Za-z0-9._-]+\z/
|
|
11
16
|
CONTROL = /[\x00-\x1F\x7F]/
|
|
12
17
|
POSITIONS = %i[host base_url header param].freeze
|
|
18
|
+
SEGMENTS_RULE = 'must be one or more segments, none of them empty, "." or "..": ' \
|
|
19
|
+
'no slash at the start or at the end, and no two in a row'
|
|
13
20
|
|
|
14
21
|
# value as one segment of a path: what base_url and the path of an
|
|
15
22
|
# endpoint do with the value of a variable.
|
|
@@ -22,12 +29,24 @@ module ApiRecipes
|
|
|
22
29
|
PathTemplate.escape(text)
|
|
23
30
|
end
|
|
24
31
|
|
|
32
|
+
# value as several segments of a path, for a {*name}: split on '/', each
|
|
33
|
+
# piece encoded as one segment, the slashes kept. A piece that is empty,
|
|
34
|
+
# "." or ".." raises, so the value never climbs or leaves the path.
|
|
35
|
+
def self.segments(value, name, api)
|
|
36
|
+
pieces = value.nil? ? [''] : value.to_s.split('/', -1)
|
|
37
|
+
pieces = [''] if pieces.empty?
|
|
38
|
+
raise InvalidVariable.new(api, name, SEGMENTS_RULE) if pieces.any? { |piece| ['', '.', '..'].include?(piece) }
|
|
39
|
+
|
|
40
|
+
pieces.map { |piece| PathTemplate.escape(piece) }.join('/')
|
|
41
|
+
end
|
|
42
|
+
|
|
25
43
|
def initialize(string, position)
|
|
26
44
|
raise ArgumentError, "unknown template position '#{position}'" unless POSITIONS.include?(position)
|
|
27
45
|
|
|
28
46
|
@string = string.to_s.dup.freeze
|
|
29
47
|
@position = position
|
|
30
|
-
@names = @string.scan(
|
|
48
|
+
@names = (position == :base_url ? @string.scan(PATH_VARIABLE).map(&:last) : @string.scan(VARIABLE).flatten)
|
|
49
|
+
.map(&:to_sym).uniq.freeze
|
|
31
50
|
freeze
|
|
32
51
|
end
|
|
33
52
|
|
|
@@ -51,6 +70,8 @@ module ApiRecipes
|
|
|
51
70
|
end
|
|
52
71
|
|
|
53
72
|
def expand(values, api:)
|
|
73
|
+
return expand_path(values, api) if @position == :base_url
|
|
74
|
+
|
|
54
75
|
@string.gsub(VARIABLE) do
|
|
55
76
|
name = Regexp.last_match(1).to_sym
|
|
56
77
|
raise MissingVariable.new(api, name) unless values.key?(name)
|
|
@@ -61,6 +82,16 @@ module ApiRecipes
|
|
|
61
82
|
|
|
62
83
|
private
|
|
63
84
|
|
|
85
|
+
def expand_path(values, api)
|
|
86
|
+
@string.gsub(PATH_VARIABLE) do
|
|
87
|
+
star = !Regexp.last_match(1).empty?
|
|
88
|
+
name = Regexp.last_match(2).to_sym
|
|
89
|
+
raise MissingVariable.new(api, name) unless values.key?(name)
|
|
90
|
+
|
|
91
|
+
star ? self.class.segments(values[name], name, api) : self.class.segment(values[name], name, api)
|
|
92
|
+
end
|
|
93
|
+
end
|
|
94
|
+
|
|
64
95
|
def encode(value, name, api)
|
|
65
96
|
text = value.to_s
|
|
66
97
|
bytes = text.b
|
|
@@ -68,7 +99,6 @@ module ApiRecipes
|
|
|
68
99
|
when :host
|
|
69
100
|
reject(api, name, 'must contain only letters, digits, dots, hyphens and underscores') unless HOST_VALUE.match?(bytes)
|
|
70
101
|
text
|
|
71
|
-
when :base_url then self.class.segment(value, name, api)
|
|
72
102
|
# http.rb encodes the name and the value of a query parameter.
|
|
73
103
|
when :param then text
|
|
74
104
|
else
|
data/lib/api_recipes/response.rb
CHANGED
|
@@ -8,19 +8,31 @@ module ApiRecipes
|
|
|
8
8
|
extend Forwardable
|
|
9
9
|
|
|
10
10
|
KEY_PATTERN = /\A[a-z_][A-Za-z0-9_]*\z/
|
|
11
|
+
BLANK = /\A[ \t\r\n]*\z/
|
|
12
|
+
BLANK_BYTES = " \t\r\n".bytes.freeze
|
|
13
|
+
PLAIN_TYPE = %r{\A[A-Za-z0-9._+/-]+\z}
|
|
14
|
+
TYPE_LIMIT = 100
|
|
15
|
+
TYPE_ADVICE = 'Set mime_type on the endpoint or on the api, or read response.body.to_s'
|
|
16
|
+
JSON_TYPE = 'application/json'
|
|
17
|
+
JSON_SUFFIX = '+json'
|
|
18
|
+
# A type and a subtype in lower case, with the characters of RFC 6838.
|
|
19
|
+
TYPE_NAME = %r{\A[a-z0-9!\#$&^_.+-]+/[a-z0-9!\#$&^_.+-]+\z}
|
|
11
20
|
|
|
12
21
|
attr_reader :original_response
|
|
13
22
|
|
|
14
23
|
# Public instance methods of HTTP::Response (http.rb 6) except request and
|
|
15
|
-
# deconstruct_keys, which would show the request, and uri
|
|
16
|
-
# which are defined here.
|
|
24
|
+
# deconstruct_keys, which would show the request, and uri, inspect, parse
|
|
25
|
+
# and flush, which are defined here.
|
|
17
26
|
def_delegators :@original_response,
|
|
18
27
|
:body, :charset, :chunked?, :code, :connection, :content_length, :content_type,
|
|
19
|
-
:cookies, :deconstruct, :
|
|
28
|
+
:cookies, :deconstruct, :headers, :mime_type, :proxy_headers,
|
|
20
29
|
:readpartial, :reason, :status, :to_a, :to_s, :to_str, :version
|
|
21
30
|
|
|
22
|
-
|
|
31
|
+
# path: the path of the request, for the error of data. Never the address,
|
|
32
|
+
# which can hold a credential in its query string.
|
|
33
|
+
def initialize(http_response, mime_type: nil, success: nil, hidden_param: nil, path: nil)
|
|
23
34
|
@original_response = http_response
|
|
35
|
+
@path = path
|
|
24
36
|
@mime_type = mime_type
|
|
25
37
|
@success = success
|
|
26
38
|
@hidden_param = hidden_param&.to_s
|
|
@@ -30,11 +42,29 @@ module ApiRecipes
|
|
|
30
42
|
def data
|
|
31
43
|
return @data if @parsed
|
|
32
44
|
|
|
33
|
-
@data =
|
|
45
|
+
@data = read(@mime_type)
|
|
34
46
|
@parsed = true
|
|
35
47
|
@data
|
|
36
48
|
end
|
|
37
49
|
|
|
50
|
+
# Reads the body as data does, with the given type when there is one, and
|
|
51
|
+
# keeps nothing. The parse of http.rb is not forwarded: its error quotes
|
|
52
|
+
# the body.
|
|
53
|
+
def parse(type = nil)
|
|
54
|
+
case type
|
|
55
|
+
when NilClass then read(@mime_type)
|
|
56
|
+
when String, Symbol then read(type.empty? ? @mime_type : type)
|
|
57
|
+
else raise ArgumentError, 'the type given to parse must be a String or a Symbol'
|
|
58
|
+
end
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
# Reads the whole body, as the flush of http.rb does, and returns this
|
|
62
|
+
# response: the one of http.rb holds the request.
|
|
63
|
+
def flush
|
|
64
|
+
@original_response.flush
|
|
65
|
+
self
|
|
66
|
+
end
|
|
67
|
+
|
|
38
68
|
def success?
|
|
39
69
|
return @success unless @success.nil?
|
|
40
70
|
|
|
@@ -63,8 +93,10 @@ module ApiRecipes
|
|
|
63
93
|
filled
|
|
64
94
|
end
|
|
65
95
|
|
|
96
|
+
# The type is text of the server, shown as in the error of data.
|
|
66
97
|
def inspect
|
|
67
|
-
|
|
98
|
+
type = server_type
|
|
99
|
+
"#<#{[self.class.name, status, type && shown_type(type, quote: '')].compact.join(' ')}>"
|
|
68
100
|
end
|
|
69
101
|
|
|
70
102
|
# The http.rb response holds the request, with its credential: a Response
|
|
@@ -79,6 +111,93 @@ module ApiRecipes
|
|
|
79
111
|
|
|
80
112
|
private
|
|
81
113
|
|
|
114
|
+
# nil for an empty body, whatever its type. given is the type to read it
|
|
115
|
+
# with, nil for the one of the response. An error of http.rb about the
|
|
116
|
+
# body is not raised as it is, and is not kept as the cause: its message
|
|
117
|
+
# quotes the body.
|
|
118
|
+
def read(given)
|
|
119
|
+
return nil if blank?(body_text)
|
|
120
|
+
|
|
121
|
+
type = given || server_type
|
|
122
|
+
@original_response.parse(parser_type(type) || '')
|
|
123
|
+
rescue HTTP::ParseError => e
|
|
124
|
+
raise unreadable(*parse_problem(e, type)), cause: nil
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
# JSON has one parser in http.rb, under one name: a JSON type that
|
|
128
|
+
# http.rb has no parser for is read with that one. A parser that the
|
|
129
|
+
# application registered for the type, as it is written or in lower
|
|
130
|
+
# case, is left to read it.
|
|
131
|
+
def parser_type(type)
|
|
132
|
+
name = json_name(type)
|
|
133
|
+
return type unless name
|
|
134
|
+
|
|
135
|
+
[type, name].find { |known| parser?(known) } || JSON_TYPE
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
def parser?(type)
|
|
139
|
+
HTTP::MimeType[type]
|
|
140
|
+
true
|
|
141
|
+
rescue HTTP::UnsupportedMimeTypeError
|
|
142
|
+
false
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
# type in lower case when it is application/json or has the +json suffix
|
|
146
|
+
# (application/problem+json), nil otherwise: also for the text http.rb
|
|
147
|
+
# makes of a repeated header, which is not the name of a type.
|
|
148
|
+
def json_name(type)
|
|
149
|
+
return nil unless type.is_a?(String) || type.is_a?(Symbol)
|
|
150
|
+
|
|
151
|
+
name = type.to_s.b.downcase
|
|
152
|
+
name if TYPE_NAME.match?(name) && (name == JSON_TYPE || name.end_with?(JSON_SUFFIX))
|
|
153
|
+
end
|
|
154
|
+
|
|
155
|
+
# The Content-Type of the response as the gem reads it and shows it: each
|
|
156
|
+
# value of the header without its parameters, in lower case, as bytes.
|
|
157
|
+
# nil when there is none. http.rb gives a repeated header, and one with
|
|
158
|
+
# a slash in a parameter, as one text with the parameters in it.
|
|
159
|
+
def server_type
|
|
160
|
+
values = Array(@original_response.headers['Content-Type'])
|
|
161
|
+
.map { |value| value.to_s.b.split(';', 2).first.to_s.strip.downcase }.reject(&:empty?)
|
|
162
|
+
values.empty? ? nil : values.join(', ')
|
|
163
|
+
end
|
|
164
|
+
|
|
165
|
+
# An error of the network while the body arrives is let through. After
|
|
166
|
+
# one, as after readpartial, http.rb no longer gives the body.
|
|
167
|
+
def body_text
|
|
168
|
+
@original_response.body.to_s
|
|
169
|
+
rescue HTTP::StateError
|
|
170
|
+
raise unreadable('the body is no longer available: it was read in parts, or reading it failed',
|
|
171
|
+
'Read data before readpartial'), cause: nil
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
# The first byte is looked at before the bytes are copied: a body that has
|
|
175
|
+
# something to read is not copied.
|
|
176
|
+
def blank?(text)
|
|
177
|
+
text.empty? || (BLANK_BYTES.include?(text.getbyte(0)) && BLANK.match?(text.b))
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
# type is nil when the response names none.
|
|
181
|
+
def parse_problem(error, type)
|
|
182
|
+
return ["the body is not valid #{shown_type(type)}", 'Read response.body.to_s'] unless
|
|
183
|
+
error.cause.is_a?(HTTP::UnsupportedMimeTypeError)
|
|
184
|
+
return ['it has a body and no content type', TYPE_ADVICE] if type.to_s.empty?
|
|
185
|
+
|
|
186
|
+
["the content type #{shown_type(type)} has no parser", TYPE_ADVICE]
|
|
187
|
+
end
|
|
188
|
+
|
|
189
|
+
# The type is text of the server: only its first bytes are shown, as they
|
|
190
|
+
# are when they are the characters of a type, escaped otherwise.
|
|
191
|
+
def shown_type(type, quote: "'")
|
|
192
|
+
bytes = type.to_s.b
|
|
193
|
+
bytes = "#{bytes[0, TYPE_LIMIT]}..." if bytes.bytesize > TYPE_LIMIT
|
|
194
|
+
PLAIN_TYPE.match?(bytes) ? "#{quote}#{bytes}#{quote}" : bytes.inspect
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
def unreadable(reason, advice)
|
|
198
|
+
UnreadableResponse.new(@path, self, reason, advice)
|
|
199
|
+
end
|
|
200
|
+
|
|
82
201
|
def hidden_pair?(pair)
|
|
83
202
|
name = pair.split('=', 2).first.to_s
|
|
84
203
|
name == @hidden_param || URI.decode_www_form_component(name) == @hidden_param
|
data/lib/api_recipes/version.rb
CHANGED
data/lib/api_recipes.rb
CHANGED
|
@@ -6,6 +6,7 @@ require 'api_recipes/version'
|
|
|
6
6
|
require 'api_recipes/errors'
|
|
7
7
|
require 'api_recipes/internals/credential'
|
|
8
8
|
require 'api_recipes/internals/level'
|
|
9
|
+
require 'api_recipes/internals/origins'
|
|
9
10
|
require 'api_recipes/internals/path_template'
|
|
10
11
|
require 'api_recipes/internals/template'
|
|
11
12
|
require 'api_recipes/internals/option_value'
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: api_recipes
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 3.0.0.
|
|
4
|
+
version: 3.0.0.beta7
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Alessandro Verlato
|
|
@@ -91,6 +91,7 @@ files:
|
|
|
91
91
|
- lib/api_recipes/internals/handles.rb
|
|
92
92
|
- lib/api_recipes/internals/level.rb
|
|
93
93
|
- lib/api_recipes/internals/option_value.rb
|
|
94
|
+
- lib/api_recipes/internals/origins.rb
|
|
94
95
|
- lib/api_recipes/internals/path_template.rb
|
|
95
96
|
- lib/api_recipes/internals/plain_yaml.rb
|
|
96
97
|
- lib/api_recipes/internals/recipe.rb
|