quicopt 0.3.0 → 0.5.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: 370fa0c8906d43f509f9262406805bdc0e1357248e8271125b6b76a096a2fd6f
4
- data.tar.gz: 0df9e60f7456ae1b0ecae3a9d3ffb668490c684a095e71f4ebfb614f522c15f0
3
+ metadata.gz: 0ec5a814d8cb2cb2f79dc7361dd714fb102de6887b1d1070e71919fb503eaaf5
4
+ data.tar.gz: 3b6d2794c026ac7838cddf7e052dbe1099a2670809b67b0e445b4b30496d45a3
5
5
  SHA512:
6
- metadata.gz: d4d0c6ef70c1f502da08557c366f31695293a52886b72bc6f214d89c902eedb21862dbe3a14223184adaa3eb64873dccf52a54609ce836e4363f92f77ef9344b
7
- data.tar.gz: e1d1ac282698f36bbe968c9099029db5f3e12bbbe6fcb7fded6dd83dfe1e49b66bdba22e267ca64845deb12cfd6d93adc24b434066470417dfbad162deeeb40f
6
+ metadata.gz: fbe0c96463681f0d74d8fc33bbd684ff2411898fc367b239f0d664f186959ac20abada83ce39afbd5ea3341e40586e8d1fb5930ae223f94e12021f2ac5db40d8
7
+ data.tar.gz: 395d4f06288ec8cee8c840097aaf8d2f304cbb6d0f2c36bc4fe280b9967ae535394d083bac8000a01e519a90509b04ce8d12f96ccdc1417f6b70d49a423ef781
data/README.md CHANGED
@@ -26,7 +26,7 @@ There is no solver on your machine. The service does the solving.
26
26
  variables, constraints, objective.
27
27
  - [`Quicopt::Permutation`](https://quicopt.github.io/quicopt-ruby/Quicopt/Permutation.html)
28
28
  and [`Quicopt::LookupTable`](https://quicopt.github.io/quicopt-ruby/Quicopt/LookupTable.html) —
29
- orders as decisions, and data read along them.
29
+ orderings as decisions, and data read along them.
30
30
  - [`Quicopt::Client`](https://quicopt.github.io/quicopt-ruby/Quicopt/Client.html) —
31
31
  sending a model, API keys, long-running jobs, errors.
32
32
  - [`Quicopt::Result`](https://quicopt.github.io/quicopt-ruby/Quicopt/Result.html) —
@@ -60,10 +60,12 @@ z = m.num_var(0, 10, "z")
60
60
  m.maximize(3 * x + 2 * y + z)
61
61
  m.add(x + y <= 5)
62
62
 
63
- result = Quicopt::Client.new.solve(m)
63
+ result = Quicopt::Client.new(api_key: "…").solve(m) # the key from your sign-up email
64
64
  puts result.display
65
65
  ```
66
66
 
67
+ The service needs an API key. Register at https://quicopt.com/signup and the key arrives by email. Without a key, the call fails with a message that links to the sign-up page.
68
+
67
69
  `result.display` is rendered by the service and ready to print — the same summary
68
70
  for every kind of model. The structured fields are there too:
69
71
 
@@ -152,7 +154,7 @@ m.minimize(suppliers.sum { |s| cart_value[s] + ship_fee[s] * (use[s] - free[s])
152
154
  Now all we have to do is to send this to the Quicopt API service:
153
155
  ```ruby
154
156
  # get the results from the API service
155
- result = Quicopt::Client.new.solve(m)
157
+ result = Quicopt::Client.new(api_key: "…").solve(m)
156
158
 
157
159
  # inspect the result
158
160
  puts result.display
@@ -243,9 +245,9 @@ Two consequences of that, both deliberate:
243
245
 
244
246
  Chained comparisons (`1 <= x <= 5`) are not a thing in Ruby. Add two rows.
245
247
 
246
- ## Choosing an order
248
+ ## Choosing an ordering
247
249
 
248
- Some decisions are orders: the route a van drives through its stops, or the sequence in which a machine works through its jobs. Declare such an order with `permutation`, and read data along it with a lookup table. Here are five stops along a road; find the shortest route through all of them that visits stop 3 before stop 0:
250
+ Some decisions are orderings: the route a van drives through its stops, or the sequence in which a machine works through its jobs. Declare such an ordering with `permutation`, and read data along it with a lookup table. Here are five stops along a road; find the shortest route through all of them that visits stop 3 before stop 0:
249
251
 
250
252
  ```ruby
251
253
  position = [0, 3, 1, 4, 2] # km along the road, stops 0 to 4
@@ -256,19 +258,19 @@ route = m.permutation("route", 5)
256
258
  route.precede(3, 0) # stop 3 is visited before stop 0
257
259
  m.minimize((0...4).sum { |k| dist[route.item_at(k), route.item_at(k + 1)] })
258
260
 
259
- result = Quicopt::Client.new.solve(m)
261
+ result = Quicopt::Client.new(api_key: "…").solve(m)
260
262
  result.objective # 4.0
261
263
  result.structures["route"].item_at # [3, 1, 4, 2, 0]: the stops in the order visited
262
264
  ```
263
265
 
264
- A permutation places `n` items in `n` slots, one item per slot, both counted from 0. Here the items are the stops and the slots are the visits, so slot 0 holds the first stop visited:
266
+ A permutation places items in as many slots, one item per slot, both counted from 0. Here the items are the stops and the slots are the visits, so slot 0 holds the first stop visited:
265
267
 
266
268
  - `route.item_at(k)` is the stop in slot `k`: `route.item_at(0)` is the first stop visited.
267
269
  - `route.slot_of(i)` is the slot of stop `i`: when it is visited.
268
270
  - `route.precede(a, b)` requires stop `a` to be visited before stop `b`. Every solution meets every such requirement.
269
- - `start:` gives the order the service's search starts from: `m.permutation("route", 5, start: [4, 3, 2, 1, 0])` starts with stop 0 in slot 4, stop 1 in slot 3, and so on.
271
+ - `start:` gives the ordering the service's search starts from: `m.permutation("route", 5, start: [4, 3, 2, 1, 0])` starts with stop 0 in slot 4, stop 1 in slot 3, and so on.
270
272
 
271
- The result holds each permutation's order both ways round, again counted from 0: `item_at`, the item in each slot, and `slot_of`, the slot of each item. Orders are found by a search, which cannot prove that no better order exists, so a model with a permutation comes back with the status `"heuristic"`.
273
+ The result holds each permutation's ordering both ways round, again counted from 0: `item_at`, the item in each slot, and `slot_of`, the slot of each item. Orderings are found by a search, which cannot prove that no better ordering exists, so a model with a permutation comes back with the status `"heuristic"`.
272
274
 
273
275
  A Ruby array cannot be indexed by a decision the service has not made yet, such as which stop comes first; a lookup table can. `dist[route.item_at(k), route.item_at(k + 1)]` is the length of the leg from the `k`-th stop to the next, whichever stops those turn out to be. A table is a vector, indexed `table[i]`, or a matrix, indexed `table[i, j]`. Indexed by whole numbers only, it gives the entry itself (`dist[0, 1]` is `3.0`). It can also be indexed by an integer variable, to read the entry the service picks:
274
276
 
@@ -278,7 +280,7 @@ price = m.lookup_table("price", [3.0, 1.0, 4.0, 1.5])
278
280
  choice = m.int_var(0, 3, "choice")
279
281
  m.minimize(price[choice])
280
282
 
281
- result = Quicopt::Client.new.solve(m)
283
+ result = Quicopt::Client.new(api_key: "…").solve(m)
282
284
  result.solution # {"choice" => 1.0}: option 1 is the cheapest
283
285
  result.objective # 1.0
284
286
  ```
@@ -307,7 +309,7 @@ m.minimize(
307
309
  (0...3).sum { |w| opening[w] * Quicopt.holds(ship[w].sum >= 1) } # opening fee
308
310
  )
309
311
 
310
- result = Quicopt::Client.new.solve(m)
312
+ result = Quicopt::Client.new(api_key: "…").solve(m)
311
313
  result.objective # 300.0
312
314
  result.solution.select { |_, units| units > 0 }.sort.to_h
313
315
  # {"ship_0_0" => 25.0, "ship_0_1" => 10.0, "ship_2_0" => 15.0, "ship_2_1" => 20.0, "ship_2_2" => 20.0}
@@ -315,7 +317,7 @@ result.solution.select { |_, units| units > 0 }.sort.to_h
315
317
 
316
318
  Warehouse 1 stays closed. Warehouse 0 sends its full 25 units to customer 0 and the minimum of 10 to customer 1; warehouse 2 covers the rest. `Quicopt.holds` takes `<=`, `>=`, `<`, `>`, `==` and `!=`, and `tol:` lets a comparison miss by that much and still count: `Quicopt.holds(spend >= 300, tol: 0.01)`. `Quicopt.min` and `Quicopt.max` give the smallest and the largest of several expressions.
317
319
 
318
- `m.partition` splits items into groups the way `permutation` orders them. Six players of strengths 7, 5, 4, 3, 2 and 1 form a team of four and a team of two, as evenly matched as possible:
320
+ `m.partition` makes a split of items into groups a decision, the way `permutation` makes an ordering one. Six players of strengths 7, 5, 4, 3, 2 and 1 form a team of four and a team of two, as evenly matched as possible:
319
321
 
320
322
  ```ruby
321
323
  strength = [7, 5, 4, 3, 2, 1] # of players 0 to 5
@@ -325,7 +327,7 @@ total = (0...2).map { |t| (0...6).sum { |p| strength[p] * Quicopt.holds(teams.pa
325
327
  m.add(teams.size_of(0) == 4) # team 0 has four players
326
328
  m.minimize(Quicopt.max(total[0], total[1]))
327
329
 
328
- result = Quicopt::Client.new.solve(m)
330
+ result = Quicopt::Client.new(api_key: "…").solve(m)
329
331
  result.objective # 11.0
330
332
  result.structures["teams"].part_of # [1, 0, 1, 0, 0, 0]: players 0 and 2 form team 1
331
333
  result.structures["teams"].size_of # [4, 2]
@@ -343,7 +345,7 @@ bytes = m.encode # the message itself: protobuf bytes, ready to POST
343
345
  program = m.to_program # the same content as a structured object you can read
344
346
  Quicopt.decode(bytes) # bytes back into that object
345
347
 
346
- Quicopt::Client.new.solve(bytes) # solve an already-encoded model
348
+ Quicopt::Client.new(api_key: "…").solve(bytes) # solve an already-encoded model
347
349
  ```
348
350
 
349
351
  The message format is a [protobuf](https://protobuf.dev) schema,
@@ -359,22 +361,12 @@ Compare decoded models, never the raw bytes.
359
361
  ## The client
360
362
 
361
363
  ```ruby
362
- client = Quicopt::Client.new # the public free tier
363
- client = Quicopt::Client.new("http://localhost:8137")
364
- client = Quicopt::Client.new(url, "my-api-key", timeout: 120)
364
+ client = Quicopt::Client.new(api_key: "…") # the Quicopt service
365
+ client = Quicopt::Client.new("http://localhost:8137", api_key: "…")
366
+ client = Quicopt::Client.new(api_key: "…", timeout: 120)
365
367
  ```
366
368
 
367
- **Keys.** The first call without a key mints one, cached at
368
- `$XDG_CACHE_HOME/quicopt/free_key` (`~/.cache/…` by default) and replayed as a
369
- bearer token on every later call — including from later runs, so you keep one key
370
- without doing anything. A key you passed in is used as-is, never cached and never
371
- overwritten; `Quicopt::Client.new(url, cache: false)` keeps the minted key in
372
- memory only.
373
-
374
- Where the home directory does not survive the run (CI, containers), the cache is
375
- wiped between sessions and each run mints a new key. Set `QUICOPT_KEY_PATH` to a
376
- durable location — or `Client.new(url, key_path: …)` — to keep one key across
377
- sessions.
369
+ **Keys.** Register at https://quicopt.com/signup and the key arrives by email. Pass it as `api_key:`. To keep the key out of your code, set the environment variable `QUICOPT_API_KEY` instead and create the client as `Quicopt::Client.new`.
378
370
 
379
371
  **Per-project tagging.** `solve(model, project: "atlas")` tags the call so usage on
380
372
  one key can be attributed per project. It rides the query string and is never
@@ -382,7 +374,13 @@ baked into the model.
382
374
 
383
375
  **Large models.** `solve(model, gzip: true)` compresses the request body.
384
376
 
385
- **Time limit.** The service chooses how long a solve may run. `time_limit:` sets that time instead, in seconds. A solver that proves its answer sooner still stops sooner; a search, which cannot prove it is done, runs for all of it:
377
+ **Connections.** A client keeps its connection to the service open between
378
+ requests, so a run of solves sets up a connection once instead of once per
379
+ request. Threads may share one client: each request in flight uses a connection
380
+ of its own. `client.close` closes the open connections, and the client stays
381
+ usable.
382
+
383
+ **Time limit.** The service chooses how long a solve may run. `time_limit:` sets that time instead, in seconds. A solver that proves its answer sooner still stops sooner; a search, which cannot prove it is done, may stop sooner too, once it stops finding better answers:
386
384
 
387
385
  ```ruby
388
386
  result = client.solve(m, time_limit: 30)
@@ -15,11 +15,11 @@ require "zlib"
15
15
  # out over stdlib +net/http+, so the gem's only runtime dependency stays
16
16
  # +google-protobuf+. The request body is the encoded model; the response is the
17
17
  # service's result JSON (+status+ / +objective+ / +solution+ / a ready-to-print
18
- # +display+ / …). The first keyless call mints an API key, returned
19
- # in the +X-Quicopt-Api-Key+ response header; it is cached at
20
- # +$XDG_CACHE_HOME/quicopt/free_key+ and replayed as +Authorization: Bearer+ on
21
- # every later call — including from a later *process*, so one caller keeps one key
22
- # rather than minting a fresh one per run.
18
+ # +display+ / …). Every request carries your API key as
19
+ # <tt>Authorization: Bearer</tt>. Register at https://quicopt.com/signup to
20
+ # receive one by email. A client keeps its connection open between requests, so
21
+ # only the first one waits for the connection to be set up; +Client#close+
22
+ # closes it.
23
23
  #
24
24
  # Two entry points mirror the two service endpoints:
25
25
  #
@@ -35,10 +35,9 @@ require "zlib"
35
35
  # warns when it granted less, and waits on the socket (or polls) long enough for
36
36
  # the time it asked for.
37
37
  module Quicopt
38
- # The public Quicopt free-tier endpoint a +Client+ targets when no +base_url+
39
- # is given. Mirrors the Python and Julia clients' default, so every client
40
- # reaches the same server out of the box.
41
- DEFAULT_BASE_URL = "https://try.quicoptapi.pgi.fz-juelich.de"
38
+ # The Quicopt service a +Client+ targets when no +base_url+ is given. The
39
+ # Python, Julia and R clients default to the same address.
40
+ DEFAULT_BASE_URL = "https://quicoptapi.pgi.fz-juelich.de"
42
41
 
43
42
  # The modelling library a model was written in, sent as the +source_language+
44
43
  # call tag. It names the *library*, not the programming language — the service
@@ -124,8 +123,9 @@ module Quicopt
124
123
  self
125
124
  end
126
125
 
127
- # The kind of model the service recognised (+LP+/+MILP+/+QUBO+/…), or +nil+
128
- # if it did not report one.
126
+ # The kind of model the service recognised
127
+ # (<tt>LP</tt>/<tt>MILP</tt>/<tt>QUBO</tt>/…), or +nil+ if it did not report
128
+ # one.
129
129
  #
130
130
  # @return [String, nil]
131
131
  def model_class
@@ -135,7 +135,7 @@ module Quicopt
135
135
 
136
136
  # A non-2xx service response.
137
137
  #
138
- # +reason+ is the service's stable snake_case code (+size_exceeded+,
138
+ # +reason+ is the service's stable snake_case code (<tt>size_exceeded</tt>,
139
139
  # +unsupported_model+, +quota_exhausted+, +not_done+, +too_many_inflight+,
140
140
  # +queue_full+, +parse_error+, …) — match on it, not on the message. +display+
141
141
  # is the framed text to print; +status_code+ the HTTP status.
@@ -158,23 +158,27 @@ module Quicopt
158
158
  end
159
159
  end
160
160
 
161
- # Environment variable overriding where the free key is cached. Point it at
162
- # durable storage in an environment whose home directory does not survive the
163
- # run (CI, containers), where the default location is wiped between sessions
164
- # and every run would otherwise mint a fresh key.
161
+ # Environment variable a +Client+ reads its API key from when none is passed.
162
+ # It keeps the key out of your code.
163
+ API_KEY_ENV = "QUICOPT_API_KEY"
164
+
165
+ # Environment variable overriding where the client saves a key the server
166
+ # issued itself. A server that gives a caller without a key a new one on the
167
+ # first call has the client save that key and reuse it in later runs. Point the
168
+ # variable at durable storage where the home directory does not survive the
169
+ # run (CI, containers).
165
170
  KEY_PATH_ENV = "QUICOPT_KEY_PATH"
166
171
 
167
- # A connection to a Quicopt service at +base_url+ — the public free tier
168
- # (+DEFAULT_BASE_URL+) unless another URL is given.
172
+ # A connection to a Quicopt service at +base_url+, by default
173
+ # <tt>DEFAULT_BASE_URL</tt>.
169
174
  #
170
- # The client holds the API key: pass a known one, or let the first keyless call
171
- # mint one — which is then cached on disk and reused by later runs, so one
172
- # caller keeps one key.
175
+ # The client holds your API key: the one passed as +api_key:+, else the one in
176
+ # the environment variable <tt>QUICOPT_API_KEY</tt>. Register at
177
+ # https://quicopt.com/signup to receive a key by email.
173
178
  #
174
- # client = Quicopt::Client.new
179
+ # client = Quicopt::Client.new(api_key: "…") # the key from your sign-up email
175
180
  # result = client.solve(model)
176
181
  # puts result.display
177
- # client.api_key # => the key the first call minted (and cached)
178
182
  class Client
179
183
  # The HTTP methods this client issues, and the request class for each.
180
184
  REQUESTS = {
@@ -186,38 +190,56 @@ module Quicopt
186
190
  # The content type of a request body: an encoded model is opaque binary.
187
191
  OCTET_STREAM = "application/octet-stream"
188
192
 
193
+ # Seconds an open connection may sit unused and still carry the next
194
+ # request. Servers and proxies close idle connections after their own
195
+ # timeout, commonly a minute or more; one closed sooner is noticed before
196
+ # the next request and replaced.
197
+ KEEP_ALIVE = 30.0
198
+
189
199
  # @return [String] the service base URL, without a trailing slash
190
200
  attr_reader :base_url
191
- # @return [String, nil] the API key in use; set on the first mint
201
+ # @return [String, nil] the API key in use
192
202
  attr_accessor :api_key
193
203
  # @return [Float] the per-request socket timeout, in seconds
194
204
  attr_accessor :timeout
195
- # @return [Pathname] where the free key is cached
205
+ # @return [Pathname] where a key the server issued is saved
196
206
  attr_reader :key_path
197
207
 
198
208
  # Bind a client to a service endpoint.
199
209
  #
200
210
  # @param base_url [String] the service base URL; a trailing slash is stripped
201
- # @param api_key [String, nil] a known API key, or +nil+ to reuse the cached
202
- # free key (minting one on the first keyless call). A key passed here is
203
- # used as-is and never written to the cache, so authenticating with a key
204
- # you already hold cannot clobber the free key of whoever runs the code.
211
+ # @param key [String, nil] your API key, given as the second argument; the
212
+ # same as +api_key:+
213
+ # @param api_key [String, nil] your API key. When +nil+, the client reads the
214
+ # key from the environment variable <tt>QUICOPT_API_KEY</tt>, and failing
215
+ # that uses a key saved by an earlier run (see +key_path:+). A key passed
216
+ # here or read from the environment is used as-is and never saved.
205
217
  # @param timeout [Numeric] the per-request socket timeout, in seconds
206
- # @param key_path [String, Pathname, nil] where to cache the free key;
207
- # defaults to +Client.default_key_path+
208
- # @param cache [Boolean] +false+ keeps the key in memory only, neither
209
- # reading nor writing the cache file
210
- def initialize(base_url = DEFAULT_BASE_URL, api_key = nil, timeout: 60.0,
211
- key_path: nil, cache: true)
218
+ # @param key_path [String, Pathname, nil] where to save a key the server
219
+ # issued itself, on a first call without a key; defaults to
220
+ # +Client.default_key_path+
221
+ # @param cache [Boolean] +false+ keeps an issued key in memory only, neither
222
+ # reading nor writing the file
223
+ def initialize(base_url = DEFAULT_BASE_URL, key = nil, api_key: key,
224
+ timeout: 60.0, key_path: nil, cache: true)
212
225
  @base_url = base_url.to_s.sub(%r{/+\z}, "")
213
226
  @timeout = timeout
214
227
  @key_path = Pathname(key_path || Client.default_key_path).expand_path
215
228
  @cache = cache
229
+ api_key = Client.env_key if api_key.nil?
230
+ # A key the caller holds — passed, or set in the environment — is never
231
+ # written to the cache, so it cannot clobber the issued key of whoever runs
232
+ # the code, and is never discarded on a 401.
216
233
  @explicit = !api_key.nil?
217
234
  @api_key = @explicit ? api_key : (cache ? Client.read_key(@key_path) : nil)
218
235
  # Only a key that came off disk may be discarded and re-minted on a 401 —
219
236
  # see +request_raw+, which relies on this to bound re-minting to one per run.
220
237
  @from_cache = !@api_key.nil? && !@explicit
238
+ # Open connections between requests, each used by one request at a time
239
+ # (see +connected+), and the process they belong to (see +idle+).
240
+ @idle = []
241
+ @idle_pid = Process.pid
242
+ @idle_lock = Mutex.new
221
243
  end
222
244
 
223
245
  # Solve +model+ synchronously, blocking until the result returns.
@@ -230,10 +252,11 @@ module Quicopt
230
252
  # model.
231
253
  # @param time_limit [Numeric, nil] how many seconds the solve may run, in
232
254
  # place of the time the service would choose. A solver that proves its
233
- # answer sooner stops sooner; a search, which cannot prove it is done, runs
234
- # for all of it. The service grants at most its maximum (120 s on the free
235
- # tier), and a warning says so when it granted less. The client waits for
236
- # the answer at least this long plus a minute.
255
+ # answer sooner stops sooner; a search, which cannot prove it is done, may
256
+ # stop sooner too, once it stops finding better answers. The service grants
257
+ # at most its maximum (120 s on the free tier), and a warning says so when
258
+ # it granted less. The client waits for the answer at least this long plus
259
+ # a minute.
237
260
  # @param config [Hash, nil] optional service parameters, sent as the query
238
261
  # string
239
262
  # @param gzip [Boolean] gzip-compress the request body
@@ -342,7 +365,7 @@ module Quicopt
342
365
  end
343
366
  req["Authorization"] = "Bearer #{@api_key}" if @api_key
344
367
 
345
- resp = http(uri, timeout || @timeout).start { |conn| conn.request(req) }
368
+ resp = connected(uri, timeout || @timeout) { |conn| conn.request(req) }
346
369
  capture_key(resp) # a 502/504 on a first call still minted a key
347
370
  raise QuicoptError.new(resp.code.to_i, Client.decode(resp.body)) unless resp.is_a?(Net::HTTPSuccess)
348
371
 
@@ -361,11 +384,12 @@ module Quicopt
361
384
 
362
385
  # Render a config mapping as a URL query-string suffix.
363
386
  #
364
- # Escapes per RFC 3986, so a space becomes +%20+ and never +'+'+ — the form
365
- # the service's query parser round-trips unambiguously, and the form the
366
- # other clients send. Ruby's stock helpers (+URI.encode_www_form+,
367
- # +CGI.escape+, +URI.encode_www_form_component+) all emit +'+'+ here, so none
368
- # of them can be used.
387
+ # Escapes per RFC 3986, so a space becomes +%20+ and never <tt>'+'</tt> —
388
+ # the form the service's query parser round-trips unambiguously, and the
389
+ # form the other clients send. Ruby's stock helpers
390
+ # (<tt>URI.encode_www_form</tt>, +CGI.escape+,
391
+ # +URI.encode_www_form_component+) all emit <tt>'+'</tt> here, so none of
392
+ # them can be used.
369
393
  #
370
394
  # @param config [Hash, nil]
371
395
  # @return [String] +"?k=v&…"+ if +config+ is non-empty, else +""+
@@ -413,6 +437,15 @@ module Quicopt
413
437
  { "error" => text }
414
438
  end
415
439
 
440
+ # The API key set in the environment variable +API_KEY_ENV+, stripped of
441
+ # surrounding whitespace; +nil+ when the variable is unset or blank.
442
+ #
443
+ # @return [String, nil]
444
+ def self.env_key
445
+ key = ENV.fetch(API_KEY_ENV, "").strip
446
+ key.empty? ? nil : key
447
+ end
448
+
416
449
  # The default location of the cached free key:
417
450
  # +$XDG_CACHE_HOME/quicopt/free_key+, falling back to +~/.cache+ when the
418
451
  # variable is unset, unless +KEY_PATH_ENV+ overrides the whole path.
@@ -457,17 +490,65 @@ module Quicopt
457
490
  tmp&.unlink if tmp&.exist?
458
491
  end
459
492
 
493
+ # Close the connections the client keeps open between requests. The client
494
+ # stays usable: its next request opens a new one.
495
+ #
496
+ # @return [nil]
497
+ def close
498
+ @idle_lock.synchronize { idle.slice!(0..) }.each { |conn| conn.finish if conn.started? }
499
+ nil
500
+ end
501
+
460
502
  private
461
503
 
462
504
  def http(uri, timeout)
463
505
  conn = Net::HTTP.new(uri.host, uri.port)
464
506
  conn.use_ssl = uri.scheme == "https"
507
+ conn.keep_alive_timeout = KEEP_ALIVE
465
508
  conn.open_timeout = timeout
466
509
  conn.read_timeout = timeout
467
510
  conn.write_timeout = timeout
468
511
  conn
469
512
  end
470
513
 
514
+ # Run the block with an open connection to the service, then keep the
515
+ # connection open for a later request.
516
+ #
517
+ # A new connection costs a TCP and a TLS handshake, two round trips before
518
+ # the request goes out, so a solve that submits, polls and fetches would pay
519
+ # them on every request. Each request takes an idle connection, or opens
520
+ # one, and gives it back when its response has been read: threads sharing a
521
+ # client never share a connection. A connection the server has closed is
522
+ # reopened before it is written to (+Net::HTTP+ checks), and one whose
523
+ # request failed is closed, not kept.
524
+ def connected(uri, timeout)
525
+ conn = @idle_lock.synchronize { idle.pop } || http(uri, timeout).tap(&:start)
526
+ conn.read_timeout = timeout
527
+ conn.write_timeout = timeout
528
+ done = false
529
+ result = yield conn
530
+ done = true
531
+ result
532
+ ensure
533
+ if done
534
+ @idle_lock.synchronize { idle.push(conn) }
535
+ elsif conn&.started?
536
+ conn.finish
537
+ end
538
+ end
539
+
540
+ # The idle connections of this process. A process forked from the one that
541
+ # opened them shares their sockets, so it starts with none and leaves them
542
+ # to that process, neither writing to nor closing them. Called under
543
+ # +@idle_lock+.
544
+ def idle
545
+ unless @idle_pid == Process.pid
546
+ @idle = []
547
+ @idle_pid = Process.pid
548
+ end
549
+ @idle
550
+ end
551
+
471
552
  # Coerce to encoded bytes: bytes pass through, a +Program+ is encoded, and a
472
553
  # +Model+ becomes a +Program+ and is encoded — so a caller solves the *model*,
473
554
  # never a hand-built +Program+.
@@ -558,8 +639,9 @@ module Quicopt
558
639
 
559
640
  # Fetch the job's metadata and framed log tail.
560
641
  #
561
- # @return [Hash] the job state (+queued+/+running+/+done+/+failed+) and its
562
- # log tail, as returned by the service
642
+ # @return [Hash] the job state
643
+ # (<tt>queued</tt>/<tt>running</tt>/<tt>done</tt>/<tt>failed</tt>) and
644
+ # its log tail, as returned by the service
563
645
  def status
564
646
  @client.request("GET", "/v1/jobs/#{@job_id}")
565
647
  end
@@ -573,7 +655,7 @@ module Quicopt
573
655
  # @param poll [Numeric] delay between polls, in seconds
574
656
  # @return [Result]
575
657
  # @raise [QuicoptError] if +wait+ is false and the job is not yet done, on any
576
- # non-+not_done+ error, or once +timeout+ elapses
658
+ # non-<tt>not_done</tt> error, or once +timeout+ elapses
577
659
  def result(wait: true, timeout: nil, poll: 0.5)
578
660
  timeout ||= @time_limit.nil? ? 120.0 : [120.0, @time_limit + WAIT_MARGIN].max
579
661
  deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
@@ -37,8 +37,8 @@ module Quicopt
37
37
  # @param comparison [Constraint] built with +<=+, +>=+, +<+, +>+, +==+ or
38
38
  # +!=+ between expressions, such as +shipped >= 60+
39
39
  # @param tol [Numeric] how far a comparison may miss and still count as
40
- # holding: +a >= b+ holds from +a = b − tol+ on, +a > b+ from +a > b + tol+.
41
- # Non-negative.
40
+ # holding: +a >= b+ holds from +a = b − tol+ on, +a > b+ from
41
+ # <tt>a > b + tol</tt>. Non-negative.
42
42
  # @return [Expression] a 0/1 expression; a number when the comparison
43
43
  # involves no decision
44
44
  # @raise [TypeError] if +comparison+ is not a comparison — often one Ruby
@@ -55,8 +55,8 @@ module Quicopt
55
55
  end
56
56
 
57
57
  # The smallest of the given expressions, as an expression the service
58
- # evaluates. +fee * Quicopt.min(1, a.active + b.active)+ is a fee that is due
59
- # once, however many of +a+ and +b+ are in use.
58
+ # evaluates. <tt>fee * Quicopt.min(1, a.active + b.active)</tt> is a fee
59
+ # that is due once, however many of +a+ and +b+ are in use.
60
60
  #
61
61
  # @param args [Array<Expression, Variable, Numeric>] at least two
62
62
  # @return [Expression] a number when every argument is one
@@ -101,7 +101,7 @@ module Quicopt
101
101
  end
102
102
  end
103
103
 
104
- # Whether a comparison between two numbers (+value = lhs − rhs+) holds.
104
+ # Whether a comparison between two numbers (<tt>value = lhs − rhs</tt>) holds.
105
105
  def truth(value, sense, tol)
106
106
  case sense
107
107
  when :le then -value + tol >= 0
@@ -172,8 +172,8 @@ module Quicopt
172
172
  @argument.variables
173
173
  end
174
174
 
175
- # @return [String] the term as sent, e.g. +step(x + y - 1)+; the indicator of
176
- # a bare variable reads +x.active+
175
+ # @return [String] the term as sent, e.g. <tt>step(x + y - 1)</tt>; the
176
+ # indicator of a bare variable reads +x.active+
177
177
  def to_s
178
178
  bare = @argument.constant.zero? && @argument.quadratic.empty? && @argument.linear.size == 1 &&
179
179
  @argument.linear.first[0].is_a?(Variable) && @argument.linear.first[1] == 1.0
@@ -227,7 +227,8 @@ module Quicopt
227
227
  @args.flat_map(&:variables).uniq
228
228
  end
229
229
 
230
- # @return [String] the term as written, e.g. +min(1, a.active + b.active)+
230
+ # @return [String] the term as written, e.g.
231
+ # <tt>min(1, a.active + b.active)</tt>
231
232
  def to_s
232
233
  "#{@op}(#{@args.join(', ')})"
233
234
  end