http_resource 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 6d9fe8b0aeb930b24273f354fa958c855392cbc7169178aff012fc55c9349bc0
4
- data.tar.gz: c59a5d2b61d6b759f494fc15619b14a26f1040425c6d1d9eb43c90a67218e2d8
3
+ metadata.gz: 54121171e391d5c93c206858ee6f2f6e6436ed46bcec2f3c53c68f5afc42cd8a
4
+ data.tar.gz: b172e10720457ff5f4e9d0ad61c63f473dc23c548e28364a95ca4c9a0628d7a6
5
5
  SHA512:
6
- metadata.gz: 882a09948d72787115e9dde41bf305269355f16bc431e929e2b13d7d28372a48fbaa695682b0e73be030412d1e402cde6fe339d946db1991317e3e19be4e16d7
7
- data.tar.gz: e12dcb9fbb52ea78a319a1fa19c27f906a88c66079e03f0ec3f97dc358e7dafc48772a329509934c24cc9475809d58915d81614c8c06a10e75af886b9a672868
6
+ metadata.gz: cfce40b735fd7044d8e82a891f5c0de4e805270a98dc3b411a4ed7e25c66ffbb9705eb5142b69f2a39cb08dbb1a4ec7b74a0eb09029f1a240a967fa49a7792f0
7
+ data.tar.gz: 57f180da78e05ed7c28a1337b3d77e9c1f68a00d1a57d93612435ee06c6de146aead46b0a88d76ded3932af4edc3cd6aa378354d70dde665eb3cc60eabdbe3b7
data/README.md CHANGED
@@ -8,8 +8,8 @@ with a **typed error hierarchy**, Rails-style **bang/non-bang resources**,
8
8
  **pluggable auth**, **per-call timeouts**, and **escape-safe URL building** so
9
9
  untrusted path segments can never escape the protocol.
10
10
 
11
- It is the generic core extracted from Skiftet's `mejla_api_client`: a small set
12
- of proven patterns you would otherwise hand-roll (and get subtly wrong) in every
11
+ It is the generic core extracted from an in-house API client: a small set of
12
+ proven patterns you would otherwise hand-roll (and get subtly wrong) in every
13
13
  service-to-service client.
14
14
 
15
15
  ## Why
@@ -159,6 +159,258 @@ than silently dropping a write.
159
159
  missing keys to `nil`. Guarding `data && Contact.from(data)` means an empty 2xx
160
160
  yields `nil`, not a ghost value object.
161
161
 
162
+ ## Simulation mode (test without a backend)
163
+
164
+ Opt-in, in-memory stand-in for the transport: your resource proxies, value
165
+ objects and error handling run **unchanged** against seeded state — no server,
166
+ no WebMock stubs. Nothing is loaded unless you ask:
167
+ `require "http_resource"` never pulls simulation in; the `simulation:` kwarg does.
168
+
169
+ ```ruby
170
+ # 1. In your client gem: subclass the backend and register path handlers on it.
171
+ class MyGem::Simulation::Backend < HttpResource::Simulation::Backend; end
172
+
173
+ class ContactsHandler
174
+ def initialize(store) = @store = store
175
+
176
+ def call(verb, segments, payload:, params:)
177
+ contact = @store[:contacts].find { _1["id"].to_s == segments.first }
178
+ raise HttpResource::ApiError.for_status("not found", status: 404, body: nil) unless contact
179
+
180
+ contact
181
+ end
182
+ end
183
+ MyGem::Simulation::Backend.register("api/contacts", ContactsHandler)
184
+
185
+ # 2. Build a simulated client — or inject a prepared backend instance.
186
+ client = HttpResource::Client.new(base_url: "https://irrelevant.test", simulation: true)
187
+ client.simulation.seed(contacts: [{ id: 1, email: "anna@example.com" }])
188
+
189
+ client.get(["api", "contacts", 1]) # => { "id" => 1, "email" => "anna@example.com" } — no network
190
+ client.get(["api", "contacts", 9]) # => raises NotFoundError (from your handler)
191
+
192
+ # 3. Inject failures to exercise error paths.
193
+ client.simulation.fail_next(status: 422, body: '{"errors":["bad"]}', on: "contacts")
194
+ ```
195
+
196
+ The pieces:
197
+
198
+ - **`Simulation::Backend`** — same verb surface as `Client` (signatures,
199
+ `params:`/`form:`/timeouts) and the same deterministic-bug guards: blank/dot
200
+ path segments, URI-invalid String paths, payload+`form:` together, and
201
+ unserializable payloads raise exactly as they would in production, so
202
+ simulation can't mask a caller bug. Handlers see **what a real server sees**:
203
+ JSON payloads parsed (string keys), form bodies and query params as decoded
204
+ string pairs (`params: {}` converges to `nil`, as on the wire). Responses
205
+ come back as **fresh parsed-JSON copies** — mutating one can't corrupt the
206
+ store. An unhandled path raises a loud 501 `ServerError` (never `nil`).
207
+ - **Per-subclass registry** — `register(prefix, handler_class)` stores on the
208
+ receiving subclass; lookup walks the inheritance chain (nearest class with a
209
+ match wins, longest whole-segment prefix within it). Two client gems can
210
+ never leak handlers into each other. Handlers are `HandlerClass.new(store)`,
211
+ memoized per backend instance.
212
+ - **`Simulation::Store`** — collection-agnostic: `store[:anything]`
213
+ auto-vivifies, `next_id(:collection)` allocates per-collection Integer ids
214
+ (seeding an explicit id reserves it; duplicates raise), `deep_stringify` is
215
+ public for handlers building records from payloads.
216
+ - **`fail_next(status:, body:, on:)`** — FIFO one-shot failure injection,
217
+ checked before handler lookup; `on:` scopes it to paths containing the
218
+ (slash-normalized) fragment. `reset!` clears store + injections + handlers.
219
+ - **Client seam** — `simulation: true` instantiates
220
+ `self.class.simulation_backend_class` (override in your Client subclass);
221
+ `simulation: backend_instance` injects a prepared one. `client.simulation`
222
+ returns the backend (`nil` in real mode).
223
+
224
+ ## ETag conditional caching (opt-in)
225
+
226
+ Transparent revalidation: inject a cache store and `get` stays `get` — no new
227
+ method, no ETag in any signature. With a store attached, a GET sends
228
+ `If-None-Match` from the stored ETag; a **304 returns the cached value** (the
229
+ caller never sees the 304 or the ETag), a 200 stores the new `{etag, value}`.
230
+ This is pure *revalidation*, not a freshness cache: every call still hits the
231
+ network; the win is that a 304 carries no body. Without `cache:`, behavior is
232
+ byte-for-byte unchanged.
233
+
234
+ ```ruby
235
+ class MyEtagStore
236
+ Entry = Struct.new(:etag, :value)
237
+ def initialize = (@h = {}; @m = Mutex.new)
238
+ def read(key) = @m.synchronize { @h[key] }
239
+ def write(key, etag, value) = @m.synchronize { @h[key] = Entry.new(etag, value) }
240
+ end
241
+
242
+ client = HttpResource::Client.new(
243
+ base_url: "https://api.example.org",
244
+ auth: HttpResource::Auth.bearer(token),
245
+ cache: MyEtagStore.new,
246
+ logger: Rails.logger # optional: receives cache-write warnings
247
+ )
248
+
249
+ client.get(["api", "permissions"]) # 200 -> stored; later calls: 304 -> cached value
250
+ ```
251
+
252
+ The store is duck-typed (like auth strategies): `read(key)` returns `nil` or an
253
+ entry responding to `.etag`/`.value`; `write(key, etag, value)` is called only
254
+ on a 2xx GET carrying an ETag. Notes:
255
+
256
+ - **Frozen results** — a cached value is deep-frozen once at store time; the
257
+ caller gets the same frozen object (mutation raises `FrozenError` instead of
258
+ silently poisoning the cache — `dup` to mutate).
259
+ - **Identity-safe keys** — keys are namespaced by a SHA-256 fingerprint of the
260
+ headers the auth strategy sets, so one store shared across clients with
261
+ different credentials can never leak a response across identities. The raw
262
+ credential never enters a key.
263
+ - **Write failures warn, never fail** — a store-write error on a successful
264
+ response logs a warning (`logger:`, falling back to `Kernel#warn`) and
265
+ returns the value uncached. Store *reads* stay unguarded on purpose.
266
+ - **GET-only**; errors are untouched (a failure never clobbers a cached
267
+ value); weak ETags (`W/"…"`) round-trip verbatim; an *unsolicited* 304
268
+ still raises `RedirectError` exactly as before.
269
+ - **Inert in simulation** — with `simulation:`, the backend replaces the
270
+ transport before any conditional logic runs; the store is never touched.
271
+ - Also wireable via `HttpResource.configure` (`c.cache = …`, `c.logger = …`).
272
+
273
+ ## Safe fetch of untrusted URLs (opt-in)
274
+
275
+ For a URL someone else gave you (a pasted link, an address found on another page,
276
+ a user's webhook target), `HttpResource::SafeFetch` GETs it under one strict
277
+ rule, and `HttpResource::PublicAddress` is that address rule alone (for a link
278
+ checker or a sender that makes its own request). Both are opt-in beside the
279
+ unchanged `Client`, stdlib only, and load only when named (0.4.0 and later).
280
+
281
+ ```ruby
282
+ fetch = HttpResource::SafeFetch.new(user_agent: "fetch/1.0")
283
+ response = fetch.get("https://www.example.com/page", max_bytes: 3_000_000, deadline: 12)
284
+ response.body # => a binary String; response is the Net::HTTPSuccess
285
+ fetch.redirect_target("https://www.example.org/s/1") # => the URI its one 3xx names, not asked itself
286
+
287
+ HttpResource::PublicAddress.public?("93.184.216.34") # => true
288
+ HttpResource::PublicAddress.connectable?("172.20.1.2", inside: true) # => true
289
+ HttpResource::PublicAddress.address("127.0.0.1/0") # => nil, a range is no address
290
+ ```
291
+
292
+ **The address rule, on every hop.** Before each request, the first and every
293
+ redirect, the host is resolved (an IP literal is its own address; a decimal or
294
+ hex spelling is looked up) and the request is refused, unsent, unless EVERY
295
+ address is public: an allow rule, so anything not shown public is refused.
296
+ `PublicAddress.address(value)` is the reading `public?` and `connectable?` judge
297
+ by: an `IPAddr` when `value` (an `IPAddr` or a String) is one address, nil when
298
+ it is none. A range (`127.0.0.1/0`; a full prefix is one address), a String
299
+ that is not ASCII only, a host name and a decimal or hex spelling are none, and
300
+ for them `public?` and `connectable?` answer false.
301
+
302
+ | Not public | RFC |
303
+ |---|---|
304
+ | 0.0.0.0/8; 127.0.0.0/8 | 1122 |
305
+ | 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 (see inside hosts) | 1918 |
306
+ | 100.64.0.0/10 | 6598 |
307
+ | 169.254.0.0/16, the cloud metadata address 169.254.169.254 among it | 3927 |
308
+ | 192.0.0.0/24 | 6890 |
309
+ | 192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24 | 5737 |
310
+ | 192.88.99.0/24 | 3068, 7526 |
311
+ | 198.18.0.0/15 | 2544 |
312
+ | 224.0.0.0/4; 240.0.0.0/4 with 255.255.255.255 | 5771; 1112, 919 |
313
+ | all IPv6 outside 2000::/3 | 4291 §2.4 |
314
+ | 2001::/23 (Teredo, benchmarking, ORCHIDv2) | 2928, 4380, 5180, 7343 |
315
+ | 2001:db8::/32; 3fff::/20 | 3849; 9637 |
316
+ | 2002::/16, 6to4 whole | 3056 |
317
+ | ::ffff:0:0/96 and 64:ff9b::/96: judged by the IPv4 address they carry | 4291 §2.5.5.2, 6052 |
318
+
319
+ **Inside hosts.** `inside_hosts: ["intranet.example.org"]` names the hosts on
320
+ your private network, each a name in exactly this form: lower-case labels of
321
+ a-z, 0-9 and hyphen joined by dots, at most 253 characters, no label empty, over
322
+ 63 or with a hyphen at an end, the last beginning with a letter (`intranet` is
323
+ one). Anything else (capitals, a trailing dot, an address in any spelling such
324
+ as `10.0.5` or `::1`) is an `ArgumentError` when the fetch is built. A request
325
+ whose host, lower-cased with one trailing dot dropped, is such a name equal to an
326
+ entry may also connect to an RFC 1918 IPv4 address; to no other address that is
327
+ not public, nor for a subdomain. Anyone who can hand your app a URL can reach a
328
+ listed host, directly or by a redirect: list only hosts that may be read so.
329
+
330
+ **The connection** goes to the address that was checked (the first IPv4 one,
331
+ else the first; one lookup per hop), never through an environment proxy
332
+ (`https_proxy` is ignored); TLS verifies the URL's host by Net::HTTP's defaults,
333
+ which the gem never changes. Each hop is its own connection, no retry; no cookie
334
+ or other answer header reaches the next hop. Every hop, one to another host too,
335
+ is sent the call's `headers:` and `user_agent` (it replaces theirs), so a secret
336
+ header belongs only in a call with `follow_redirects: false` or an `allow` that
337
+ keeps every hop on that host. The gem adds no header to Net::HTTP's defaults.
338
+
339
+ **Scheme and redirects.** https only: `plain_http: :refuse` (the default) refuses
340
+ `http:`, `:upgrade` asks the same URL over https (its port kept), `:allow` asks
341
+ it as written; the same holds for every redirect target. The port is the URL's
342
+ own (a Location's, an inside host's too): check it first, and in `allow`, if only
343
+ 443 will do. A URL with userinfo (`https://user:pw@www.example.com/`) is refused unsent, first or hop,
344
+ so `allow` never sees one. The first URL must be ASCII: it is read as written,
345
+ and one with a byte outside ASCII is refused unsent. `SafeFetch.wire_url(url)`
346
+ makes a pasted link so: it percent-encodes each byte outside ASCII
347
+ (`https://www.example.com/café` becomes `https://www.example.com/caf%C3%A9`) and
348
+ repairs nothing else (a raw space is still refused), and the fetch puts every
349
+ Location through it. A host outside ASCII must arrive in its xn-- form
350
+ (`xn--bcher-kva.example.com`, not `bücher.example.com`); `wire_url` makes none.
351
+ At most `max_redirects` hops (default 3, 1-10). `allow:` is asked of
352
+ every hop's target (a String), never of the first URL; false refuses it unrequested, and
353
+ what it raises reaches you as it is. `follow_redirects: false` makes a 3xx an error.
354
+
355
+ **Bounds, always on.** `max_bytes:` (default 10 MiB) counts body bytes as read,
356
+ after inflation: a Content-Length over it is refused before a body byte is read
357
+ and a longer body is cut as it arrives. `deadline:` (default 60 s) is wall-clock
358
+ over all hops: every lookup (at most `RESOLVE_TIMEOUT`, 4 s), connect, handshake,
359
+ head and body runs under `Timeout` for what is left. `open_timeout:` (the
360
+ connect) and `read_timeout:` (each read) default to 10 s, cut to what is left.
361
+ The head holds `HEAD_BYTES` (64 KiB) in all, 1xx heads included, and no line (a
362
+ chunk size, a trailer) may reach it before its end. The three times are finite
363
+ positive numbers and `max_bytes:` a positive Integer, with no upper limit; `nil`
364
+ or anything else is an `ArgumentError`, as is any keyword off its form.
365
+
366
+ **Type.** `accept_type: ->(type) { type.start_with?("image/") }` is asked of a
367
+ 2xx with the lower-cased type/subtype (or nil), after its declared length and
368
+ before its body; falsy refuses it with the body unread. What it raises reaches
369
+ you as it is, unless its class is in one of the two lists below.
370
+
371
+ **Errors.** Every refusal is a `HttpResource::SafeFetch::Error` (an
372
+ `HttpResource::Error`) with `#reason`, and `#status` for the answer that ended it:
373
+
374
+ | `reason` | When |
375
+ |---|---|
376
+ | `:address` | not an http(s) URL with a host; a URL that is not ASCII (a pasted link goes through `wire_url` first; a host outside ASCII arrives in its xn-- form); a URL with userinfo; an address not allowed |
377
+ | `:scheme` | plain http under `:refuse` |
378
+ | `:redirect_off_allow` | a hop's Location unreadable, not http(s), with userinfo, plain http under `:refuse`, or not allowed |
379
+ | `:status` | an answer neither 2xx nor 3xx, or a 3xx with `follow_redirects: false` (`status` its code); a 3xx without Location, too many redirects, `redirect_target` answered 2xx (`status` nil) |
380
+ | `:type` | `accept_type` said no |
381
+ | `:too_large` | over `max_bytes`; `SafeFetch::HeadTooLarge` for the head |
382
+ | `:truncated` | the stream ended before the body did: short of its Content-Length, a chunked body before its last chunk, or over TLS a connection cut without its closing message (close_notify) while the body is read, a body the close would end among them; whatever the transport raised for it (`EOFError`, or OpenSSL's "unexpected eof while reading"); no part of it is returned, by `get` or `read_body` |
383
+ | `:timeout` | the deadline, or one of `TIMEOUT_ERRORS` |
384
+ | `:network` | no address, or any other of `NETWORK_ERRORS` (a reset, bad TLS, a broken answer or compressed stream, a connection that ended before an answer) |
385
+
386
+ A message carries the URL as it was asked, query string included (a URL that
387
+ could not be read is not repeated, and a failure while the body is read names
388
+ what failed, not the URL); each piece the far end wrote is cut to 200
389
+ bytes, so a message is valid UTF-8. A wire failure's `cause` is its own, uncut.
390
+
391
+ **Testing your code.** Hand in `resolver: ->(host) { ["93.184.216.34"] }` (the
392
+ default, `SYSTEM_RESOLVER`, asks `Addrinfo.getaddrinfo`), and stub
393
+ `PublicAddress.connectable?` or `SafeFetch.monotonic_now`: the fetch asks both
394
+ through those singleton methods. These steer the address check (and
395
+ `monotonic_now` the clock), never the wire: the request still goes to the address
396
+ the resolver answered, so a suite stubs the wire too, one of two ways. A stub of
397
+ Net::HTTP such as WebMock's (`stub_request(:get, "https://www.example.com/page")`)
398
+ matches the URL's host whatever the resolver answers, and opens no connection. Or
399
+ the suite runs its own server on 127.0.0.1, the resolver answers `["127.0.0.1"]`,
400
+ `connectable?` is stubbed to allow it, and the URL names the server's port (plain
401
+ http with `plain_http: :allow`, or TLS the suite trusts). The gem's own suite does
402
+ both and reaches no other machine.
403
+
404
+ **Your own API client's requests.** The wire pieces are public:
405
+ `SafeFetch.connection(host, port)` (a `Net::HTTP` with no proxy and the head
406
+ bound; you set TLS, `ipaddr`, timeouts, retries), `SafeFetch.read_body(response,
407
+ max_bytes:, ends_at:)` (inside `request`'s block; what the wire raises while it
408
+ reads is a `SafeFetch::Error` by the table above), `wire_url`, `media_type`,
409
+ `monotonic_now`, and the lists `TIMEOUT_ERRORS` and `NETWORK_ERRORS`.
410
+
411
+ **It does not** send anything but GET, keep cookies, retry, follow more than 10
412
+ redirects, take a proxy, or offer a switch to allow every address.
413
+
162
414
  ## Error hierarchy
163
415
 
164
416
  Every failure is an `HttpResource::ApiError` carrying `#status` (an `Integer`, or
@@ -247,6 +499,30 @@ adversarial spec (`spec/escape_safety_spec.rb`).
247
499
 
248
500
  ## Changelog
249
501
 
502
+ ### 0.4.0
503
+
504
+ - Add opt-in **ETag conditional caching**: a duck-typed `cache:` store on
505
+ `Client` (+ `logger:` for cache-write warnings, both also on
506
+ `HttpResource.configure`). GETs transparently revalidate with
507
+ `If-None-Match`; a 304 returns the cached value invisibly. Cached values are
508
+ deep-frozen; keys are namespaced per auth identity. No `cache:` → behavior
509
+ unchanged.
510
+ - Add opt-in **safe fetch of untrusted URLs**: `HttpResource::SafeFetch` GETs a
511
+ URL someone else gave you under one address rule, checked before every hop
512
+ (https only by default, bounded size and time, every refusal a
513
+ `SafeFetch::Error` with `#reason`), and `HttpResource::PublicAddress` is that
514
+ address rule alone. The wire pieces (`SafeFetch.connection`,
515
+ `SafeFetch.read_body`, the error lists) are public for your own API client's
516
+ requests. Stdlib only, loaded only when named; `Client` is unchanged.
517
+
518
+ ### 0.3.0
519
+
520
+ - Add opt-in **simulation mode**: `HttpResource::Simulation::Backend`/`Store` +
521
+ a `simulation:` kwarg on `Client` — exercise a client with no live backend
522
+ and no stubs. Per-subclass handler registries, collection-agnostic seeded
523
+ store, FIFO failure injection, full transport parity (same guards, same
524
+ typed errors). Lazy-loaded: plain `require "http_resource"` is unchanged.
525
+
250
526
  ### 0.2.0
251
527
 
252
528
  - Add a `form:` keyword to `post`/`put`/`patch` for `application/x-www-form-urlencoded`
@@ -32,14 +32,33 @@ module HttpResource
32
32
 
33
33
  attr_reader :base_url
34
34
 
35
+ # The simulation backend when built with simulation:; nil in real mode.
36
+ attr_reader :simulation
37
+
38
+ # The Backend class `simulation: true` instantiates. Client-gem subclasses
39
+ # override this to point at their own Backend subclass (with its own
40
+ # registered handlers). Only called after the lazy require, so the
41
+ # constant resolves.
42
+ def self.simulation_backend_class
43
+ Simulation::Backend
44
+ end
45
+
46
+ # cache: opts into transparent ETag revalidation on GET (see
47
+ # ConditionalCache for the store contract); logger: receives cache-write
48
+ # warnings (falls back to Kernel#warn). Inert in simulation mode — the
49
+ # backend replaces the transport before any conditional logic runs.
35
50
  def initialize(base_url:, auth: nil, username: nil, password: nil,
36
- open_timeout: DEFAULT_OPEN_TIMEOUT, read_timeout: DEFAULT_READ_TIMEOUT)
51
+ open_timeout: DEFAULT_OPEN_TIMEOUT, read_timeout: DEFAULT_READ_TIMEOUT,
52
+ simulation: nil, cache: nil, logger: nil)
37
53
  raise ConfigurationError, "base_url is required" if blank?(base_url)
38
54
 
39
55
  @base_url = base_url.to_s.sub(%r{/+\z}, "")
40
56
  @auth = auth || default_auth(username, password)
41
57
  @open_timeout = open_timeout
42
58
  @read_timeout = read_timeout
59
+ @simulation = setup_simulation(simulation)
60
+ @conditional_cache = cache && ConditionalCache.new(store: cache, auth: @auth, base_url: @base_url,
61
+ logger:)
43
62
  end
44
63
 
45
64
  # Low-level REST verbs. `path` may be a String ("/api/foo") sent verbatim, or
@@ -78,16 +97,26 @@ module HttpResource
78
97
  private
79
98
 
80
99
  def request(method, path, body: nil, form: nil, params: nil, open_timeout: nil, read_timeout: nil)
100
+ # In simulation the verb call is handed to the backend BEFORE any URI
101
+ # build or network I/O — the backend enforces the same deterministic-bug
102
+ # guards, so a call that raises in production raises identically here.
103
+ return simulate(method, path, body:, form:, params:) if @simulation
104
+
81
105
  # Build the URI + request OUTSIDE the network rescue: a URI::InvalidURIError
82
106
  # (bad path), JSON::GeneratorError (un-serializable payload, e.g. a NaN
83
107
  # amount) or an ArgumentError (both a JSON and a form body) is a
84
108
  # deterministic caller bug, and must NOT be masked as a retryable
85
109
  # TransportError — that would have a worker retry it forever.
86
110
  uri = build_uri(path, params)
87
- req = build_request(method, uri, body, form)
111
+ # GET-only: with a cache attached, read the store ONCE into a carrier
112
+ # (deterministic side, like uri/req — a broken store read surfaces
113
+ # honestly). handle() never re-reads, so an eviction between request
114
+ # and response can't turn a solicited 304 into a RedirectError.
115
+ cond = @conditional_cache && method == :get ? @conditional_cache.conditional_for(uri) : nil
116
+ req = build_request(method, uri, body, form, cond)
88
117
  connection = http(uri, open_timeout:, read_timeout:)
89
118
  begin
90
- handle(connection.request(req))
119
+ handle(connection.request(req), cond)
91
120
  rescue ApiError
92
121
  raise
93
122
  rescue Timeout::Error, Errno::ETIMEDOUT => e # Net::Open/ReadTimeout subclass Timeout::Error
@@ -131,7 +160,7 @@ module HttpResource
131
160
  ERB::Util.url_encode(str)
132
161
  end
133
162
 
134
- def build_request(method, uri, body, form = nil)
163
+ def build_request(method, uri, body, form = nil, cond = nil)
135
164
  klass = {
136
165
  get: Net::HTTP::Get, post: Net::HTTP::Post, put: Net::HTTP::Put,
137
166
  patch: Net::HTTP::Patch, delete: Net::HTTP::Delete
@@ -139,6 +168,9 @@ module HttpResource
139
168
  request = klass.new(uri)
140
169
  @auth&.apply(request)
141
170
  request["Accept"] = "application/json"
171
+ # The stored validator is replayed VERBATIM (quotes, any W/ prefix):
172
+ # RFC 7232 gives If-None-Match weak comparison; the server owns the match.
173
+ request["If-None-Match"] = cond.etag if cond&.etag
142
174
  apply_body(request, body, form)
143
175
  request
144
176
  end
@@ -167,12 +199,23 @@ module HttpResource
167
199
  http
168
200
  end
169
201
 
170
- def handle(response)
202
+ def handle(response, cond = nil)
171
203
  status = response.code.to_i
204
+ # Solicited 304: return the value carried from request time — the caller
205
+ # never sees the 304 or the ETag. MUST sit above the body read (a 304
206
+ # has no body; reading it can raise) and above for_status (which maps
207
+ # 3xx to RedirectError). An UNSOLICITED 304 (no If-None-Match sent)
208
+ # still falls through and raises, exactly as without a cache.
209
+ return @conditional_cache.freeze_value(cond.value) if cond&.etag && status == 304
210
+
172
211
  body = response.body.to_s
173
212
  parsed = body.empty? ? nil : parse_json(body)
174
- return parsed if status.between?(200, 299)
213
+ if status.between?(200, 299)
214
+ parsed = @conditional_cache.store_response(cond, response, parsed) if cond
215
+ return parsed
216
+ end
175
217
 
218
+ # A failure never touches the store: a cached value survives an outage.
176
219
  raise ApiError.for_status("HTTP request returned #{status}", status:, body:)
177
220
  end
178
221
 
@@ -182,6 +225,27 @@ module HttpResource
182
225
  body
183
226
  end
184
227
 
228
+ def simulate(method, path, body:, form:, params:)
229
+ # The public verbs only pass params: on get; reaching this with params
230
+ # on another verb means private-seam misuse — fail loud, don't drop it.
231
+ raise ArgumentError, "params: is only supported on get in simulation" if params && method != :get
232
+
233
+ case method
234
+ when :get then @simulation.get(path, params:)
235
+ when :delete then @simulation.delete(path)
236
+ else @simulation.public_send(method, path, body, form:)
237
+ end
238
+ end
239
+
240
+ # Lazy: the simulation machinery is test-facing and never loaded unless
241
+ # asked for — plain `require "http_resource"` must not pull it in.
242
+ def setup_simulation(simulation)
243
+ return nil unless simulation
244
+
245
+ require "http_resource/simulation"
246
+ simulation == true ? self.class.simulation_backend_class.new : simulation
247
+ end
248
+
185
249
  def default_auth(username, password)
186
250
  return nil if blank?(username) && blank?(password)
187
251
 
@@ -0,0 +1,135 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "uri"
5
+ require "openssl"
6
+
7
+ module HttpResource
8
+ # Transparent ETag revalidation for a Client (opt-in via the cache: kwarg).
9
+ # Pure REVALIDATION, not a freshness cache: every GET still hits the network;
10
+ # the win is that a 304 carries no body — the caller gets the cached value
11
+ # back and never sees the 304, the ETag, or any new method.
12
+ #
13
+ # The injected store is duck-typed (like Auth strategies):
14
+ #
15
+ # read(key) -> entry | nil # entry responds to .etag/.value
16
+ # write(key, etag, value) -> (ignored) # called only on a 2xx GET with an ETag
17
+ #
18
+ # The Client reads `.etag`/`.value` — never hash keys — so a store may hand
19
+ # back a Struct, an OpenStruct, or a deserialized object. The OUTER nil from
20
+ # read is the only "missing" signal; a stored value may itself be nil (a
21
+ # cached 204). Store thread-safety is the store's responsibility.
22
+ class ConditionalCache
23
+ # Read ONCE per GET, at request time, and threaded through the request:
24
+ # the 304 path returns the carried value and never re-reads the store, so
25
+ # an eviction between request and response can't break revalidation.
26
+ Conditional = Struct.new(:key, :etag, :value)
27
+
28
+ def initialize(store:, auth:, base_url:, logger: nil)
29
+ @store = store
30
+ @auth = auth
31
+ @base_url = base_url
32
+ @logger = logger
33
+ end
34
+
35
+ # A carrier for EVERY GET — etag/value are nil on a miss (or an entry with
36
+ # a blank etag), which means: send a plain GET, but still store the 200.
37
+ def conditional_for(uri)
38
+ key = cache_key(uri)
39
+ entry = @store.read(key)
40
+ Conditional.new(key, presence(entry&.etag), entry&.value)
41
+ end
42
+
43
+ # Store a fresh 2xx GET body when the response carries a validator. The
44
+ # value is deep-frozen FIRST (parsed JSON is only Hash/Array/String/
45
+ # Numeric/bool/nil, so the freeze is total) — both the store and the
46
+ # caller get the same frozen object, so a caller mutation can't poison
47
+ # the cache: it raises FrozenError instead. Returns the value to hand the
48
+ # caller (frozen when cached, untouched when there was no ETag).
49
+ def store_response(conditional, response, parsed)
50
+ etag = presence(response["ETag"]&.strip)
51
+ return parsed unless etag
52
+
53
+ frozen = deep_freeze(parsed)
54
+ begin
55
+ @store.write(conditional.key, etag, frozen)
56
+ rescue StandardError => e
57
+ # A cache-write failure must not fail a SUCCESSFUL response — warn and
58
+ # return the value uncached. Reads stay unguarded: a broken read is a
59
+ # deterministic bug that should surface, not hide.
60
+ warn_failure(e)
61
+ end
62
+ frozen
63
+ end
64
+
65
+ # Public for the Client's 304 path: an in-memory store hands back the
66
+ # already-frozen object (no-op), but a SERIALIZING store (Rails.cache,
67
+ # Redis…) returns fresh unfrozen copies — freeze them too, so the
68
+ # "results are read-only" guarantee is uniform across 200 and 304.
69
+ def freeze_value(value)
70
+ deep_freeze(value)
71
+ end
72
+
73
+ private
74
+
75
+ # NUL separator: cannot appear in a URI or a percent-encoded segment, so
76
+ # distinct tuples can never alias. request_uri = path + "?" + query, so
77
+ # different params are different entries (different representations).
78
+ def cache_key(uri)
79
+ [identity, uri.scheme, uri.host, uri.port, uri.request_uri].join("\0")
80
+ end
81
+
82
+ # Namespace the key by WHO is asking, so one store shared across clients
83
+ # with different credentials can never leak a representation across
84
+ # identities. Fingerprint = SHA-256 of ONLY the headers the auth strategy
85
+ # sets/changes (the delta against an un-applied probe — Net::HTTP's
86
+ # defaults like User-Agent are excluded, so a persistent store survives a
87
+ # Ruby upgrade). Uses the existing #apply duck — no new Auth API; the raw
88
+ # credential never enters a key. Lazy + memoized: a throwing custom auth
89
+ # surfaces on first request, not at construction.
90
+ def identity
91
+ @identity ||=
92
+ if @auth.nil?
93
+ "anon"
94
+ else
95
+ baseline = Net::HTTP::Get.new(URI(@base_url)).to_hash
96
+ probe = Net::HTTP::Get.new(URI(@base_url))
97
+ @auth.apply(probe)
98
+ delta = probe.to_hash.reject { |name, value| baseline[name] == value }
99
+ "h:#{OpenSSL::Digest::SHA256.hexdigest(delta.sort.to_s)}"
100
+ end
101
+ end
102
+
103
+ def presence(string)
104
+ string unless string.nil? || string.empty?
105
+ end
106
+
107
+ def deep_freeze(value)
108
+ case value
109
+ when Hash
110
+ value.each do |key, val|
111
+ deep_freeze(key)
112
+ deep_freeze(val)
113
+ end
114
+ when Array
115
+ value.each { deep_freeze(_1) }
116
+ end
117
+ value.freeze
118
+ end
119
+
120
+ # Best-effort by design: warning about a cache hiccup must never be the
121
+ # thing that fails a SUCCESSFUL response — a raising logger degrades to
122
+ # Kernel#warn, and even a closed stderr is swallowed.
123
+ def warn_failure(error)
124
+ message = "http_resource: cache write failed (#{error.class}: #{error.message}); " \
125
+ "response served uncached"
126
+ @logger ? @logger.warn(message) : Kernel.warn(message)
127
+ rescue StandardError
128
+ begin
129
+ Kernel.warn(message)
130
+ rescue StandardError
131
+ nil
132
+ end
133
+ end
134
+ end
135
+ end
@@ -10,13 +10,17 @@ module HttpResource
10
10
  # c.auth = HttpResource::Auth.bearer(ENV.fetch("API_TOKEN"))
11
11
  # end
12
12
  class Configuration
13
- attr_accessor :base_url, :auth, :open_timeout, :read_timeout
13
+ # cache: an ETag store opting the default client into conditional caching
14
+ # (see ConditionalCache); logger: receives cache-write warnings.
15
+ attr_accessor :base_url, :auth, :open_timeout, :read_timeout, :cache, :logger
14
16
 
15
17
  def initialize
16
18
  @base_url = nil
17
19
  @auth = nil
18
20
  @open_timeout = Client::DEFAULT_OPEN_TIMEOUT
19
21
  @read_timeout = Client::DEFAULT_READ_TIMEOUT
22
+ @cache = nil
23
+ @logger = nil
20
24
  end
21
25
  end
22
26
  end