cronwatch 0.14.3 → 0.15.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: d78436fcdc58bdb265650a95d09bfc6300133aa0d24434cfb575fe3f726bb846
4
- data.tar.gz: 1c52f21a7b4a2c724c8cfa75932e38b56eade9198f53602718c4d5be78eebe24
3
+ metadata.gz: 67c52ce623dee0c1de4fdceb487bb8fa8b7000a112a570a0af5b379023afe17e
4
+ data.tar.gz: 58f3f1afed359d10dab68dce39e1c95eb45e5203e68b268f4ea5d9d26c6dc394
5
5
  SHA512:
6
- metadata.gz: 554b274bd8e3058755b2459778d4addcc6de0d2ab39fef01d47c15837d3dee796837333df8c019eaba223b63505cfe6f7c9ef331d0d0fd8d8bcae0ed1c5d46c1
7
- data.tar.gz: d199b491b1260aea57e40852d36827455c69f3aec205fec3b33b0df631b432dcabce27e75b5a3d605e72f1c3e63531af2620e71e50726e524467f63664e4cdd3
6
+ metadata.gz: 58521649648233549054d5486adbf87523b0b208acfa7d887bc4bb8cbc16d6d00598bef0f9e65abe7ccd06bb3f3074f631260f009173bc381925d748e37c0ffb
7
+ data.tar.gz: 897f0fae36f8cf655f0d343e39ff874fc0495e32bcde489ee9cc382e0863d385d03115d398624637825e7c85f07ebacf56cfa3d507a65feef5a1209bc7dea39b
data/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 Jon C. Phillips
3
+ Copyright (c) 2026 CronWatch.dev
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
data/README.md CHANGED
@@ -51,7 +51,7 @@ end
51
51
  CW.start_checking # checks for missed and stuck runs every minute, in a background thread
52
52
  ```
53
53
 
54
- `run` returns what the block returns and raises what it raises, after the run is recorded. A script run from crontab exits when it is done, so instead of `start_checking`, add a second crontab line that declares the jobs and calls `CW.check` every five minutes.
54
+ `run` returns what the block returns and raises what it raises, after the run is recorded. A block left early by `return`, `break`, or `throw` is recorded too, as a run that returned nothing. A script run from crontab exits when it is done, so instead of `start_checking`, add a second crontab line that declares the jobs and calls `CW.check` every five minutes.
55
55
 
56
56
  A run that starts in one call and ends in another (a job that hands work to a queue, a webhook that reports back later) is one run too:
57
57
 
@@ -169,7 +169,7 @@ Rails.application.routes.draw do
169
169
  end
170
170
  ```
171
171
 
172
- Set `CRONWATCH_TOKEN` to a long random string and open `/cronwatch?token=<it>` once; the browser keeps a cookie. The token and `CRON_SECRET` are trimmed of the whitespace around them, so one read from a file with a trailing newline still works. Without a token, while the environment (the first of `CRONWATCH_ENV`, `APP_ENV`, then `Rails.env` (when Rails is loaded), `RAILS_ENV`, or `RACK_ENV` that holds more than spaces, trimmed and lowercased) is `development`, `dev`, or `local` (not `test` or `testing`: a test run or CI needs a token, as production does), it makes a token of its own and prints a sign-in link to standard output on its first request (open it once; unless `origin:` is set or the request's host is loopback, the link leaves the host out, since a client chooses it); anywhere else it answers 503. Puma, Unicorn, Thin, and rackup set `RACK_ENV` to `development` when nothing names an environment, production included, so under one of them `RACK_ENV=development` alone does not count: `CRONWATCH_ENV`, `APP_ENV`, `Rails.env`, or `RAILS_ENV` must say development (or `RACK_ENV` say `dev` or `local`). To rely on the app's own sign in, mount it behind that (Devise's `authenticate` block, or a routing constraint) and pass `token: nil`. The URLs, JSON shapes, headers, and CSRF rules are the SDK's, so the MCP server reads it unchanged. The request's origin, which the CSRF check compares against, is the request's own scheme and `Host`. Behind a proxy, pass `trust_proxy: true` to read the first `X-Forwarded-Proto` and `X-Forwarded-Host` instead (only when the proxy sets or overwrites both, since a client can send them too), or `origin: "https://app.example.com"` to pin it. Under Rails `trust_proxy` defaults to true, as Rails itself trusts those headers; anywhere else it defaults to false, as in the SDK. `GET /cronwatch/api/check` with a bearer (the token or `CRON_SECRET`) runs the check, for an outside cron.
172
+ Set `CRONWATCH_TOKEN` to a long random string and open `/cronwatch?token=<it>` once; the browser keeps a cookie. The token and `CRON_SECRET` are trimmed of the whitespace around them, so one read from a file with a trailing newline still works. Without a token, while the environment (the first of `CRONWATCH_ENV`, `APP_ENV`, then `Rails.env` (when Rails is loaded), `RAILS_ENV`, or `RACK_ENV` that holds more than spaces, trimmed and lowercased) is `development`, `dev`, or `local` (not `test` or `testing`: a test run or CI needs a token, as production does), it makes a token of its own and prints a sign-in link to standard output on its first request (open it once; unless `origin:` is set or the request's host is loopback, the link leaves the host out, since a client chooses it; the token is the client's, so it stays the same when Rails reloads `config/routes.rb` and the browser stays signed in until the server restarts); anywhere else it answers 503. Puma, Unicorn, Thin, and rackup set `RACK_ENV` to `development` when nothing names an environment, production included, so under one of them `RACK_ENV=development` alone does not count: `CRONWATCH_ENV`, `APP_ENV`, `Rails.env`, or `RAILS_ENV` must say development (or `RACK_ENV` say `dev` or `local`). To rely on the app's own sign in, mount it behind that (Devise's `authenticate` block, or a routing constraint) and pass `token: nil`. The URLs, JSON shapes, headers, and CSRF rules are the SDK's, so the MCP server reads it unchanged. The request's origin, which the CSRF check compares against, is the request's own scheme and `Host`. Behind a proxy, pass `trust_proxy: true` to read the first `X-Forwarded-Proto` and `X-Forwarded-Host` instead (only when the proxy sets or overwrites both, since a client can send them too), or `origin: "https://app.example.com"` to pin it. Under Rails `trust_proxy` defaults to true, as Rails itself trusts those headers; anywhere else it defaults to false, as in the SDK. `GET /cronwatch/api/check` with a bearer (the token or `CRON_SECRET`) runs the check, for an outside cron.
173
173
 
174
174
  There is no `handler()` as in the TypeScript SDK: for a job triggered over HTTP, wrap the controller action's body in `CW.job(...).run` (declared once, at boot) and check the bearer in the controller.
175
175
 
@@ -197,6 +197,8 @@ These still work through every 1.x release and go in 2.0, each with a warning in
197
197
 
198
198
  Finished runs older than `retention` (default `"30d"`) are pruned by the check; each job's newest run is kept.
199
199
 
200
+ A store that hangs does not hold a job back where the gem can leave the write behind: with the memory store or the ActiveRecord store on Postgres, `run` waits five seconds for the start to be recorded, then reports it to `on_error` and runs the job unrecorded, finishing the run over the late row if it lands. On SQLite the store writes through the caller's own connection, so the wait is SQLite's busy timeout and the pool's checkout timeout instead. A store of your own gets the five seconds when it answers true to `abandonable?`.
201
+
200
202
  ## Alerts
201
203
 
202
204
  ```ruby
@@ -214,7 +216,7 @@ Cronwatch::Alerts::Custom.new("pagerduty") do |alert|
214
216
  end
215
217
  ```
216
218
 
217
- Every alert goes to every channel. A channel that raises, or takes longer than 15 seconds, goes to `on_error` and never blocks the others, and the alert is kept for that channel alone: each check retries it there, and only there, until it takes it. Each condition alerts once when it opens and once more when a clean run closes it; there are no repeat alerts. The webhook's body is the alert's JSON with `"schema": 1` first (its [JSON Schema](https://cronwatch.dev/schemas/webhook/1.json)); parse the fields, not `title` and `message`, whose wording may change. It signs the body with `X-CronWatch-Signature: sha256=<hex>`, the HMAC-SHA256 of the raw body, and sends `X-CronWatch-Timestamp` (unix seconds) with `X-CronWatch-Timestamp-Signature: sha256=<hex>`, the HMAC-SHA256 of `<timestamp>.<raw body>`. A receiver checks the second with `Rack::Utils.secure_compare("sha256=#{Cronwatch::Alerts::Webhook.signature(secret, "#{timestamp}.#{raw_body}")}", header)` and refuses a timestamp more than five minutes from its own clock, so a captured alert cannot be sent again later.
219
+ Every alert goes to every channel. A channel that raises, or takes longer than 15 seconds, goes to `on_error` and never blocks the others, and the alert is kept for that channel alone: each check retries it there, and only there, until it takes it. Each condition alerts once when it opens and once more when a clean run closes it; there are no repeat alerts. Stuck stays open until a run finishes ok, so a job that hangs on every run alerts once, not at every timeout. The webhook's body is the alert's JSON with `"schema": 1` first (its [JSON Schema](https://cronwatch.dev/schemas/webhook/1.json)); parse the fields, not `title` and `message`, whose wording may change. It signs the body with `X-CronWatch-Signature: sha256=<hex>`, the HMAC-SHA256 of the raw body, and sends `X-CronWatch-Timestamp` (unix seconds) with `X-CronWatch-Timestamp-Signature: sha256=<hex>`, the HMAC-SHA256 of `<timestamp>.<raw body>`. A receiver checks the second with `Rack::Utils.secure_compare("sha256=#{Cronwatch::Alerts::Webhook.signature(secret, "#{timestamp}.#{raw_body}")}", header)` and refuses a timestamp more than five minutes from its own clock, so a captured alert cannot be sent again later.
218
220
 
219
221
  ## Triage
220
222
 
@@ -231,7 +233,7 @@ Cronwatch.configure do |c|
231
233
  end
232
234
  ```
233
235
 
234
- Adds two to four sentences from Claude (likely cause, first thing to check) to every alert except recoveries. Needs the `anthropic` gem and `ANTHROPIC_API_KEY`. It runs only when an alert is sent, never per run, and the alert goes out without it after 25 seconds. Options: `model` (default `"claude-opus-5"`), `effort` (`"medium"`), `max_tokens` (`800`), `context`, `fallbacks` (`true`), `api_key`, `client`.
236
+ Adds two to four sentences from Claude (likely cause, first thing to check) to every alert except recoveries. Needs the `anthropic` gem and `ANTHROPIC_API_KEY`. It runs only when an alert is sent, never per run, and the alert goes out without it after 25 seconds. Options: `model` (default `"claude-opus-5"`), `effort` (`"medium"`), `max_tokens` (`4096`: the model's thinking counts toward it, and a reply that reaches it before any diagnosis is written is reported to `on_error`), `context`, `fallbacks` (`true`), `api_key`, `client`.
235
237
 
236
238
  ## Sharing a database with a Node app
237
239
 
@@ -29,6 +29,12 @@ module Cronwatch
29
29
  # Wall-clock time one check spends retrying undelivered alerts, across
30
30
  # every job. Once it is spent the rest wait for the next check.
31
31
  RETRY_BUDGET_MS = 20_000
32
+ # How long run waits for the store to record a run's start (the job's
33
+ # declaration and the run's row) before running the job without it. A
34
+ # store that fails does so sooner; this is for one that hangs. Only a
35
+ # store whose calls can be left behind in another thread is waited on
36
+ # this way (see record_execute_start).
37
+ START_DEADLINE_MS = 5_000
32
38
  # Reads and writes of one job's state before an update gives up on a store that keeps changing under it.
33
39
  STATE_ATTEMPTS = 10
34
40
  # Runs read for a baseline, and the most read when failures crowd out the successes.
@@ -51,12 +57,31 @@ module Cronwatch
51
57
  STRANDED_ERROR = "Imported, but its finish was never written; marked as timed out"
52
58
  private_constant :CHANNEL_TIMEOUT_MS, :DEFAULT_OPTIONS, :FORK_LOCK, :HISTORY_MAX, :HISTORY_PAGE, :MAX_RUN_ID,
53
59
  :PRUNE_INTERVAL_MS, :RESERVED_RUN_ID_PREFIX, :RETRY_BUDGET_MS, :RUN_STATUSES, :SILENCE_OPTIONS,
54
- :STATE_ATTEMPTS, :STRANDED_ERROR, :TRIAGE_TIMEOUT_MS
60
+ :START_DEADLINE_MS, :STATE_ATTEMPTS, :STRANDED_ERROR, :TRIAGE_TIMEOUT_MS
55
61
 
56
62
  # What execute returns: the recorded run, and the block's own outcome.
57
63
  #
58
64
  # @api private
59
65
  ExecuteResult = Struct.new(:run, :result, :error, :threw, keyword_init: true)
66
+ # A start write that execute gave up waiting for, still under way in its
67
+ # own thread, and what the two sides tell each other under `lock`:
68
+ # `landed` once the write is in the store, `concluded` once the finish
69
+ # has been recorded or has failed to be, with the finished `run` and
70
+ # whether to `judge` it.
71
+ #
72
+ # @api private
73
+ class StartWrite
74
+ attr_reader :lock
75
+ attr_accessor :abandoned, :landed, :concluded, :run, :judge
76
+
77
+ def initialize
78
+ @lock = Mutex.new
79
+ @abandoned = false
80
+ @landed = false
81
+ @concluded = false
82
+ @judge = true
83
+ end
84
+ end
60
85
  # What a channel's call receives with each alert (the SDK's ChannelContext).
61
86
  # on_error(error) reports a problem that did not stop the alert going
62
87
  # out, such as one of several recipients refusing it, to the client's on_error.
@@ -153,6 +178,7 @@ module Cronwatch
153
178
  @channel_timeout_ms = CHANNEL_TIMEOUT_MS
154
179
  @triage_timeout_ms = TRIAGE_TIMEOUT_MS
155
180
  @retry_budget_ms = RETRY_BUDGET_MS
181
+ @start_deadline_ms = START_DEADLINE_MS
156
182
  @warned_deferred_start = false
157
183
  reset_process_state
158
184
  end
@@ -224,7 +250,9 @@ module Cronwatch
224
250
  # outcome. A StandardError from the block is not raised; see `threw`. An
225
251
  # exception outside StandardError (Interrupt, SystemExit, Sidekiq::Shutdown,
226
252
  # a Timeout, NotImplementedError) is recorded as a failed run and then
227
- # raised again, so the run is never left running.
253
+ # raised again, so the run is never left running. A block left by a
254
+ # `return` from the method around it, a `break`, or a `throw` is recorded
255
+ # as a run that returned nil, and the jump carries on.
228
256
  #
229
257
  # `failure` is an optional callable that turns the block's result into an
230
258
  # error message, or nil when the result is fine: an HTTP handler uses it to
@@ -244,15 +272,15 @@ module Cronwatch
244
272
  run = Run.new(id: SecureRandom.uuid, job: name, status: :running, started_at: started_at, finished_at: nil,
245
273
  duration_ms: nil, error: nil, output: nil, metrics: {}, trigger: trigger)
246
274
  recorded = false
275
+ # The start write, when it was given up on and is still under way.
276
+ start = nil
247
277
  begin
248
- sync(definition, confirm: true)
249
- @store.insert_run(run.dup)
250
- recorded = true
278
+ recorded, start = record_execute_start(definition, run)
251
279
  rescue StandardError => e
252
280
  report(e, "recording #{name}")
253
281
  end
254
- # The SDK closes missed and stuck beside the running job; here it is done
255
- # just before the block runs. The result is the same.
282
+ # The SDK closes missed beside the running job; here it is done just
283
+ # before the block runs. The result is the same.
256
284
  if recorded
257
285
  begin
258
286
  update_state(name) { |before| [Evaluate.hold_run(Evaluate.on_run_start(definition, run, before, now), run.id), nil] }
@@ -265,30 +293,32 @@ module Cronwatch
265
293
  result = nil
266
294
  error = nil
267
295
  threw = false
296
+ returned = false
268
297
  begin
269
298
  result = yield(recorder.context)
299
+ returned = true
270
300
  rescue Exception => e # rubocop:disable Lint/RescueException -- recorded, then raised again below
271
301
  error = e
272
302
  threw = true
273
303
  ensure
274
304
  recorder.signal.settle!
305
+ # The block left without returning or raising: a `return` from the
306
+ # method around it, a `break`, or a `throw`. The run is over all the
307
+ # same, so it is finished here, as one that returned nil, and the
308
+ # jump carries on to where it was going. A thread being killed is
309
+ # left alone: it has no time to write and send, and the stuck check
310
+ # reports its run.
311
+ if !returned && !threw && Thread.current.status != "aborting"
312
+ begin
313
+ finish_execution(definition, run, recorder, recorded, start, nil, nil, false, failure, requeued_on_shutdown)
314
+ rescue StandardError => e
315
+ # Raised from here it would replace the jump.
316
+ report(e, "recording #{name}")
317
+ end
318
+ end
275
319
  end
276
320
 
277
- finished_at = now
278
- run.finished_at = finished_at
279
- run.duration_ms = Evaluate.run_duration(started_at, finished_at)
280
- run.metrics = recorder.metrics
281
- returned = result.is_a?(String) ? Output.utf8(result) : nil
282
- run.output = recorder.output || returned
283
-
284
- conclude(definition, run, result, error, threw, recorder.expect_text || returned, failure: failure)
285
- begin
286
- judge = !(requeued_on_shutdown && threw && Client.shutdown?(error))
287
- ignored = record_finish(definition, run, recorded, finished_at, judge: judge)
288
- report(RuntimeError.new("run #{run.id} of #{name} #{ignored}; ignored"), "finishing #{name}") if ignored
289
- rescue StandardError => e
290
- report(e, "recording #{name}")
291
- end
321
+ finish_execution(definition, run, recorder, recorded, start, result, error, threw, failure, requeued_on_shutdown)
292
322
 
293
323
  raise error if threw && interrupted?(error)
294
324
 
@@ -498,7 +528,7 @@ module Cronwatch
498
528
  def job_summary(name)
499
529
  ensure_ready
500
530
  definition = @registry.synchronize { @definitions[name] }
501
- sync(definition, confirm: true) if definition
531
+ sync(definition, confirm: true, running: false) if definition
502
532
  stored = @store.get_job(name)
503
533
  return nil unless stored
504
534
 
@@ -609,6 +639,14 @@ module Cronwatch
609
639
  Web.build(self, **options)
610
640
  end
611
641
 
642
+ # The development token every dashboard built for this client shares, and
643
+ # the sign-in lines printed for it (Web::DevelopmentSignIn).
644
+ #
645
+ # @api private For Cronwatch::Web, not apps.
646
+ def development_sign_in
647
+ @registry.synchronize { @development_sign_in ||= Web::DevelopmentSignIn.new }
648
+ end
649
+
612
650
  # Stop the checks start_checking began.
613
651
  def stop
614
652
  stop_ticker
@@ -649,6 +687,128 @@ module Cronwatch
649
687
 
650
688
  private
651
689
 
690
+ # The start of execute: the job's declaration and the run's row, written
691
+ # before the block runs. Returns `[recorded, start]`. Raises what the
692
+ # store raises.
693
+ #
694
+ # A store that hangs must not hold the job back, so a store whose calls
695
+ # can be left behind (`abandonable?`: the memory store, and the
696
+ # ActiveRecord store on Postgres, which writes through a pool of its own)
697
+ # is written to from a thread of its own and given START_DEADLINE_MS.
698
+ # Past that the job runs as one whose start was never written, and
699
+ # `start` is the write still under way: it may land later, leaving a
700
+ # running row. One that lands before the finish is finished over as
701
+ # usual; one that lands after it is finished then (late_finish), so no
702
+ # row is left running to be called stuck.
703
+ #
704
+ # Any other store is written to here, on the caller's thread, with no
705
+ # deadline: the ActiveRecord store on SQLite uses the caller's own
706
+ # connection and joins its transaction, which a write made from another
707
+ # thread would not, and a store of the app's own may be bound to its
708
+ # thread the same way. A blocking call cannot be given up on from the
709
+ # thread that makes it (Timeout would cut it off part way through a
710
+ # driver call), so there the wait is the store's own: its busy and pool
711
+ # checkout timeouts.
712
+ def record_execute_start(definition, run)
713
+ unless abandonable_store?
714
+ sync(definition, confirm: true)
715
+ @store.insert_run(run.dup)
716
+ return [true, nil]
717
+ end
718
+
719
+ # The run as it starts: what the start write holds, however late it lands.
720
+ begun = run.dup
721
+ start = StartWrite.new
722
+ thread = Thread.new do
723
+ Thread.current.report_on_exception = false
724
+ sync(definition, confirm: true)
725
+ @store.insert_run(begun)
726
+ # A finish that was recorded, or failed to be, before this landed has no finish coming.
727
+ late = start.lock.synchronize do
728
+ start.landed = true
729
+ start.abandoned && start.concluded
730
+ end
731
+ late_finish(definition, start) if late
732
+ nil
733
+ # Handed to the caller, which raises it as the write's failure.
734
+ rescue Exception => e # rubocop:disable Lint/RescueException
735
+ e
736
+ end
737
+
738
+ if thread.join(@start_deadline_ms / 1000.0)
739
+ failure = thread.value
740
+ raise(failure.is_a?(StandardError) ? failure : RuntimeError.new("#{failure.class}: #{failure.message}")) if failure
741
+
742
+ return [true, nil]
743
+ end
744
+ # It may have landed just as the wait ended.
745
+ landed = start.lock.synchronize do
746
+ start.abandoned = true unless start.landed
747
+ start.landed
748
+ end
749
+ return [true, nil] if landed
750
+
751
+ name = definition.name
752
+ report(RuntimeError.new("the store took longer than #{Duration.format(@start_deadline_ms)} to record the start of #{name}; " \
753
+ "running it unrecorded"), "recording #{name}")
754
+ [false, start]
755
+ end
756
+
757
+ # Whether the store's calls may be made from, and left behind in, a thread other than the caller's.
758
+ def abandonable_store?
759
+ @store.respond_to?(:abandonable?) && @store.abandonable? ? true : false
760
+ rescue StandardError
761
+ false
762
+ end
763
+
764
+ # A start write that landed after its run's finish was concluded without
765
+ # being recorded: the run is finished over the row now, and judged, so
766
+ # it is not left running.
767
+ def late_finish(definition, start)
768
+ run = start.run
769
+ record_finish(definition, run, true, run.finished_at, judge: start.judge)
770
+ nil
771
+ rescue StandardError => e
772
+ report(e, "recording #{definition.name}")
773
+ end
774
+
775
+ # The end of execute: the run as it finished, judged and recorded. Store
776
+ # failures are reported, never raised. `start` is the start write execute
777
+ # gave up waiting for, if it did (record_execute_start).
778
+ def finish_execution(definition, run, recorder, recorded, start, result, error, threw, failure, requeued_on_shutdown)
779
+ name = definition.name
780
+ finished_at = now
781
+ run.finished_at = finished_at
782
+ run.duration_ms = Evaluate.run_duration(run.started_at, finished_at)
783
+ run.metrics = recorder.metrics
784
+ returned = result.is_a?(String) ? Output.utf8(result) : nil
785
+ run.output = recorder.output || returned
786
+
787
+ conclude(definition, run, result, error, threw, recorder.expect_text || returned, failure: failure)
788
+ judge = !(requeued_on_shutdown && threw && Client.shutdown?(error))
789
+ # A start that has landed since is finished over, as one recorded in time.
790
+ recorded ||= start.lock.synchronize { start.landed } if start
791
+ written = false
792
+ begin
793
+ ignored = record_finish(definition, run, recorded, finished_at, judge: judge)
794
+ report(RuntimeError.new("run #{run.id} of #{name} #{ignored}; ignored"), "finishing #{name}") if ignored
795
+ written = true
796
+ rescue StandardError => e
797
+ report(e, "recording #{name}")
798
+ end
799
+ return if start.nil?
800
+
801
+ # From here a start that lands finishes the run itself. One that
802
+ # landed while the finish above was failing is finished now.
803
+ late = start.lock.synchronize do
804
+ start.run = run
805
+ start.judge = judge
806
+ start.concluded = true
807
+ !written && !recorded && start.landed
808
+ end
809
+ late_finish(definition, start) if late
810
+ end
811
+
652
812
  # Stops the interval thread and returns it, or nil when there was none.
653
813
  def stop_ticker
654
814
  after_fork_check
@@ -799,8 +959,8 @@ module Cronwatch
799
959
 
800
960
  # Writes the declaration of `definition`'s name as it stands, unless the
801
961
  # store has it. A handle kept from an earlier declaration writes the one
802
- # that replaced it, never its own over it, and one forgotten since writes
803
- # its own. The writes of one name take turns (the name's lock in
962
+ # that replaced it, never its own over it, and one forgotten since
963
+ # declares the job again as it was last declared here. The writes of one name take turns (the name's lock in
804
964
  # @syncing, held across the write), so one still under way cannot land
805
965
  # after a later one; and a name declared again while its write was under
806
966
  # way is still to be written. A name is marked as written only while
@@ -810,8 +970,11 @@ module Cronwatch
810
970
  #
811
971
  # With `confirm`, as a run starts, a name already written is read back:
812
972
  # another process may have forgotten the job since, and a job still
813
- # declared here comes back on its next run.
814
- def sync(definition, confirm: false)
973
+ # declared here comes back on its next run. `running` says the write is
974
+ # for a run (by default, whenever `confirm` is): a name forgotten here is
975
+ # then declared again, where a check or a dashboard read, whose loop may
976
+ # have picked the name up just before the forget, leaves it forgotten.
977
+ def sync(definition, confirm: false, running: confirm)
815
978
  ensure_ready
816
979
  name = definition.name
817
980
  if @registry.synchronize { @synced.include?(name) }
@@ -823,7 +986,23 @@ module Cronwatch
823
986
  after_fork_check
824
987
  turn = @registry.synchronize { @syncing[name] ||= Mutex.new }
825
988
  turn.synchronize do
826
- standing = @registry.synchronize { @synced.include?(name) ? nil : @definitions.fetch(name, definition) }
989
+ standing = @registry.synchronize do
990
+ next nil if @synced.include?(name)
991
+
992
+ unless @definitions.key?(name)
993
+ # Forgotten here since this write was asked for. A check or a
994
+ # dashboard read that was on its way to write it leaves it
995
+ # forgotten: only a run brings a forgotten job back.
996
+ next nil unless running
997
+
998
+ # A handle kept from before the forget: its run declares the job
999
+ # again, as run by name does (declared), so the name is marked as
1000
+ # written once more and the checks keep it declared.
1001
+ forgotten = @forgotten.delete(name)
1002
+ @definitions[name] = forgotten if forgotten
1003
+ end
1004
+ @definitions.fetch(name, definition)
1005
+ end
827
1006
  next if standing.nil?
828
1007
 
829
1008
  @store.upsert_job(Serialize.to_stored(standing), now)
@@ -1055,7 +1234,7 @@ module Cronwatch
1055
1234
  def record_finish(definition, run, recorded, finished_at, judge: true)
1056
1235
  unless recorded
1057
1236
  # The start was never written; the store may be back by now.
1058
- sync(definition)
1237
+ sync(definition, running: true)
1059
1238
  begin
1060
1239
  @store.insert_run(run)
1061
1240
  finish_run(Serialize.to_stored(definition), run, finished_at) if judge
@@ -1091,9 +1270,9 @@ module Cronwatch
1091
1270
  defined?(::Sidekiq::Shutdown) && error.is_a?(::Sidekiq::Shutdown) ? true : false
1092
1271
  end
1093
1272
 
1094
- # The start of execute without the block: the run is inserted and missed
1095
- # and stuck close (on_run_start). A store that fails is reported and the
1096
- # handle inserts the finished run instead, as execute does.
1273
+ # The start of execute without the block or the deadline: the run is
1274
+ # inserted and missed closes (on_run_start). A store that fails is
1275
+ # reported and the handle inserts the finished run instead, as execute does.
1097
1276
  def record_start(definition, trigger, id)
1098
1277
  name = definition.name
1099
1278
  unless id.nil?
@@ -1151,10 +1330,15 @@ module Cronwatch
1151
1330
  # `started` is true for a handle whose run this process inserted.
1152
1331
  def run_handle(definition, id, base, recorded, inactive, started: false)
1153
1332
  name = definition.name
1333
+ # The lines this handle last flushed, as logged (:raw) and as they
1334
+ # stand at the end of the stored output (:redacted), or nil before the
1335
+ # first flush. See append_redacted. The handle's flushes and its
1336
+ # finish take turns, so nothing else reads it meanwhile.
1337
+ flushed = [nil]
1154
1338
  RunHandle.new(
1155
1339
  id: id, job: name, started_at: base&.started_at, inactive: inactive,
1156
- finish: ->(recorder, outcome, head) { finish_handle(definition, id, base, recorded, recorder, outcome, head, started) },
1157
- flush: recorded ? ->(lines, metrics) { flush_handle(name, id, lines, metrics) } : nil,
1340
+ finish: ->(recorder, outcome, head) { finish_handle(definition, id, base, recorded, recorder, outcome, head, started, flushed) },
1341
+ flush: recorded ? ->(lines, metrics) { flush_handle(name, id, lines, metrics, flushed) } : nil,
1158
1342
  ignored: ->(why) { ignore_finish(id, name, why) },
1159
1343
  )
1160
1344
  end
@@ -1171,7 +1355,7 @@ module Cronwatch
1171
1355
  # Returns the run as recorded, or nil when nothing was. A store that
1172
1356
  # fails is reported and raises RunHandle::Retry, which leaves the handle
1173
1357
  # active to be finished again.
1174
- def finish_handle(definition, id, base, recorded, recorder, outcome, head = nil, started = false)
1358
+ def finish_handle(definition, id, base, recorded, recorder, outcome, head = nil, started = false, flushed = [nil])
1175
1359
  name = definition.name
1176
1360
  from = base
1177
1361
  if recorded
@@ -1204,7 +1388,7 @@ module Cronwatch
1204
1388
  run.duration_ms = Evaluate.run_duration(from.started_at, finished_at)
1205
1389
  run.error = nil
1206
1390
  # Capped by conclude, after it is redacted.
1207
- run.output = join_lines(from.output, added)
1391
+ run.output = added.nil? ? from.output : append_redacted(from.output, added, flushed[0])[0]
1208
1392
  run.metrics = (from.metrics || {}).merge(recorder.metrics)
1209
1393
  expect_text = join_lines(head, join_lines(from.output, recorder.expect_text || returned))
1210
1394
  conclude(definition, run, result, error, failed, expect_text)
@@ -1230,7 +1414,7 @@ module Cronwatch
1230
1414
  # running, so a flush never undoes a finish. True once written; false
1231
1415
  # when the handle should keep them for finish (the run is not running or
1232
1416
  # is another job's, or the store failed).
1233
- def flush_handle(name, id, lines, metrics)
1417
+ def flush_handle(name, id, lines, metrics, flushed = [nil])
1234
1418
  stored = @store.get_run(id)
1235
1419
  # Not running: the lines stay in the handle for finish, which reports why it cannot record them.
1236
1420
  return false if stored.nil? || stored.status != :running
@@ -1241,14 +1425,48 @@ module Cronwatch
1241
1425
  end
1242
1426
 
1243
1427
  updated = stored.dup
1244
- updated.output = join_output(stored.output, Output.redact_and_cap(lines, @redact)) unless lines.nil?
1428
+ output, tail = lines.nil? ? [stored.output, nil] : append_redacted(stored.output, lines, flushed[0])
1429
+ output = Output.cap(output) unless lines.nil? || output.nil?
1430
+ updated.output = output
1245
1431
  updated.metrics = (stored.metrics || {}).merge(metrics)
1246
- write_run_if(updated, [:running])
1432
+ return false unless write_run_if(updated, [:running])
1433
+
1434
+ # Remembered only while the stored output still ends with it (the cap did not cut into it).
1435
+ flushed[0] = tail && output&.end_with?(tail[:redacted]) ? tail : nil unless lines.nil?
1436
+ true
1247
1437
  rescue StandardError => e
1248
1438
  report(e, "flushing #{name}")
1249
1439
  false
1250
1440
  end
1251
1441
 
1442
+ # `lines` added to the stored output, redacted. While the output still
1443
+ # ends with what the handle flushed last (`flushed`), that tail is
1444
+ # redacted again with the new lines after it and replaced, so a secret
1445
+ # that began in one flush and ends in the next (a private key logged a
1446
+ # line at a time, a label and then its value) is blanked whole, where
1447
+ # redacting each flush alone would store its second half. Otherwise (the
1448
+ # first flush, or another process has written since) the lines are
1449
+ # redacted alone and appended. Returns `[output, tail]`: the tail is what
1450
+ # to remember once the write lands, at most Output::CAP of the raw text,
1451
+ # from the start of a line, and only while its redaction is still the
1452
+ # end of what was written.
1453
+ def append_redacted(stored, lines, flushed)
1454
+ added = Output.strip_nul(Output.utf8(lines))
1455
+ joins = !flushed.nil? && !stored.nil? && stored.end_with?(flushed[:redacted])
1456
+ raw = joins ? "#{flushed[:raw]}\n#{added}" : added
1457
+ redacted = Output.redact_and_cap(raw, @redact)
1458
+ output = joins ? stored[0, stored.length - flushed[:redacted].length] + redacted : join_lines(stored, redacted)
1459
+ return [output, { raw: raw, redacted: redacted }] if JS.length16(raw) <= Output::CAP
1460
+
1461
+ kept_raw = JS.tail16(raw, Output::CAP)
1462
+ cut = kept_raw.index("\n")
1463
+ return [output, nil] if cut.nil?
1464
+
1465
+ kept_raw = kept_raw[(cut + 1)..]
1466
+ kept = Output.redact_and_cap(kept_raw, @redact)
1467
+ [output, redacted.end_with?(kept) ? { raw: kept_raw, redacted: kept } : nil]
1468
+ end
1469
+
1252
1470
  # Raises for a run id no store could hold, or one reserved for the pg_cron source.
1253
1471
  def check_run_id(job, id, method)
1254
1472
  unless id.is_a?(String) && !id.empty? && JS.length16(id) <= MAX_RUN_ID
@@ -1271,12 +1489,6 @@ module Cronwatch
1271
1489
  "#{before}\n#{after}"
1272
1490
  end
1273
1491
 
1274
- # Output appended to stored output, capped like any run's.
1275
- def join_output(before, after)
1276
- joined = join_lines(before, after)
1277
- joined && Output.cap(joined)
1278
- end
1279
-
1280
1492
  # Runs the job's state still holds as pending (Evaluate.hold_run) whose
1281
1493
  # finish was written but never evaluated: the process that finished them
1282
1494
  # stopped, or its state write failed, between the two writes. Each one
@@ -1388,11 +1600,23 @@ module Cronwatch
1388
1600
  next if run.nil? || run.status != :running || run.job != listed.job
1389
1601
 
1390
1602
  run.status = :timeout
1391
- if stranded
1392
- # Its own status was never written; a late finish of it is judged
1393
- # as one after a timeout, so a success still recovers.
1603
+ if stranded && !run.error.nil?
1604
+ # The placeholder of a finished import keeps the run's own error,
1605
+ # and only a run that failed has one: it is closed as the failure
1606
+ # it was, with its own times, and alerts as failed. A later
1607
+ # import of the same run finds it finished and changes nothing.
1608
+ run.status = :failed
1609
+ if run.duration_ms.nil?
1610
+ run.duration_ms = Evaluate.run_duration(run.started_at, run.finished_at)
1611
+ else
1612
+ run.finished_at = run.started_at + run.duration_ms
1613
+ end
1614
+ elsif stranded
1615
+ # Its own status was never written and nothing says it failed; a
1616
+ # late finish of it is judged as one after a timeout, so a success
1617
+ # still recovers.
1394
1618
  run.duration_ms = Evaluate.run_duration(run.started_at, run.finished_at) if run.duration_ms.nil?
1395
- run.error = run.error.nil? ? STRANDED_ERROR : "#{STRANDED_ERROR}\n#{run.error}"
1619
+ run.error = STRANDED_ERROR
1396
1620
  else
1397
1621
  run.finished_at = at
1398
1622
  run.duration_ms = Evaluate.run_duration(run.started_at, at)
@@ -563,14 +563,17 @@ module Cronwatch
563
563
  end
564
564
 
565
565
  # Called when a run starts, or when a run a source reports is recorded.
566
- # Missed and stuck are about the absence of a run, so a run starting
567
- # closes them without an alert; the recovered message waits for a
568
- # successful finish. Missed closes only when the run catches the schedule
569
- # up (catches_up?), which a run starting now always does.
566
+ # Missed is about the absence of a run, so a run starting closes it
567
+ # without an alert; the recovered message waits for a successful finish.
568
+ # It closes only when the run catches the schedule up (catches_up?),
569
+ # which a run starting now always does. Nothing else closes here. Stuck
570
+ # in particular stays open: a run that has only started may hang as the
571
+ # last one did, and closing stuck for it would open it, and alert, again
572
+ # at every timeout of a job that hangs every time. Only a run that
573
+ # finishes ok closes stuck.
570
574
  def on_run_start(definition, run, state, now)
571
575
  next_state = clone_state(state)
572
576
  close_condition(next_state, :missed) if catches_up?(definition, run, now)
573
- close_condition(next_state, :stuck)
574
577
  next_state
575
578
  end
576
579
 
@@ -89,7 +89,8 @@ module Cronwatch
89
89
  # one from http_proxy or https_proxy, which fetch never reads, so an
90
90
  # alert (and the credentials in it) reaches only the channel's own host.
91
91
  def connection(uri)
92
- http = Net::HTTP.new(uri.host, uri.port, nil)
92
+ # hostname, not host: an IPv6 literal without its brackets, which the name lookup refuses.
93
+ http = Net::HTTP.new(uri.hostname, uri.port, nil)
93
94
  http.use_ssl = uri.scheme == "https"
94
95
  http.open_timeout = @timeout
95
96
  http.read_timeout = @timeout
data/lib/cronwatch/js.rb CHANGED
@@ -156,12 +156,22 @@ module Cronwatch
156
156
  when Numeric then json(value.to_f)
157
157
  else
158
158
  if value.respond_to?(:as_json) && !value.is_a?(Struct) then json(value.as_json)
159
- elsif value.respond_to?(:to_h) then json(value.to_h)
159
+ elsif value.respond_to?(:to_h) then json(hash_of(value))
160
160
  else quote(value.to_s)
161
161
  end
162
162
  end
163
163
  end
164
164
 
165
+ # to_h, or the value's text where it has a to_h that cannot make a Hash
166
+ # of it: every Enumerable has one, and a Range's, a Set's, or an
167
+ # Enumerator's raises unless its elements are pairs.
168
+ def hash_of(value)
169
+ hash = value.to_h
170
+ hash.is_a?(Hash) ? hash : value.to_s
171
+ rescue StandardError
172
+ value.to_s
173
+ end
174
+
165
175
  def quote(text)
166
176
  if text.encoding == Encoding::UTF_8 && !text.valid_encoding? && text.b.match?(LONE)
167
177
  # A lone surrogate (see lone_surrogate), written as JSON.stringify writes one.
@@ -97,12 +97,27 @@ module Cronwatch
97
97
  config = ::ActiveRecord::DatabaseConfigurations::HashConfig.new(
98
98
  db_config.env_name, "#{db_config.name}_cronwatch", db_config.configuration_hash,
99
99
  )
100
- ::ActiveRecord::Base.connected_to(role: ::ActiveRecord.writing_role) { klass.establish_connection(config) }
100
+ # What klass.establish_connection does, but on the default shard
101
+ # whichever shard the app has swapped to when the store is first used.
102
+ klass.connection_specification_name = klass.name
103
+ klass.connection_handler.establish_connection(config, owner_name: klass, role: ::ActiveRecord.writing_role,
104
+ shard: klass.default_shard)
101
105
  klass
102
106
  end
103
107
  end
104
108
  end
105
109
 
110
+ # The store's own pool for `db_config`. It is on the default shard
111
+ # alone, so it is asked for by name: connection_pool would look for it
112
+ # on the shard the app has swapped to (connected_to(shard:), Rails'
113
+ # ShardSelector), where it is not.
114
+ def self.own_pool(db_config)
115
+ own = own_connection_class(db_config)
116
+ own.connection_handler.retrieve_connection_pool(
117
+ own.connection_specification_name, role: ::ActiveRecord.writing_role, shard: own.default_shard, strict: true,
118
+ )
119
+ end
120
+
106
121
  # The SDK's schema, character for character (sql.ts `schema`).
107
122
  def self.schema(dialect, prefix = DEFAULT_PREFIX)
108
123
  p = table_prefix(prefix)
@@ -277,6 +292,20 @@ module Cronwatch
277
292
  write(:prune, [before])
278
293
  end
279
294
 
295
+ # Whether a call may be made from, and left behind in, a thread other
296
+ # than the caller's (Client#record_execute_start): on Postgres, where
297
+ # the store has a pool of its own. On SQLite it uses the caller's
298
+ # connection and joins its transaction, which another thread would not.
299
+ def abandonable?
300
+ return @abandonable unless @abandonable.nil?
301
+
302
+ source = connection_class
303
+ found = source.connection_handler.retrieve_connection_pool(
304
+ source.connection_specification_name, role: ::ActiveRecord.writing_role, shard: source.default_shard,
305
+ ) || source.connection_pool
306
+ @abandonable = self.class.dialect(found.db_config.adapter) == :postgres
307
+ end
308
+
280
309
  # The pool belongs to the app; there is nothing to close.
281
310
  def close
282
311
  nil
@@ -298,7 +327,7 @@ module Cronwatch
298
327
  ) || source.connection_pool
299
328
  return found if self.class.dialect(found.db_config.adapter) == :sqlite
300
329
 
301
- self.class.own_connection_class(found.db_config).connection_pool
330
+ self.class.own_pool(found.db_config)
302
331
  end
303
332
 
304
333
  # Every call runs on the writing role, even inside the app's
@@ -10,8 +10,12 @@ module Cronwatch
10
10
  # get_job, list_jobs, delete_job, insert_run, update_run, update_run_if
11
11
  # (optional: without it the client reads the run, then writes it), get_run,
12
12
  # list_runs, last_run, running_runs, get_state, set_state, compare_and_set_state
13
- # (optional: without it the client falls back to set_state), prune, and close
14
- # (optional). They take and return the types in types.rb.
13
+ # (optional: without it the client falls back to set_state), prune, close
14
+ # (optional), and abandonable? (optional: true when a call may be made
15
+ # from, and left behind in, a thread other than the caller's, which lets
16
+ # run give up on a start write that hangs; without it the client calls
17
+ # the store on the caller's thread and waits). They take and return the
18
+ # types in types.rb.
15
19
  class Memory
16
20
  def initialize
17
21
  @jobs = {}
@@ -22,6 +26,12 @@ module Cronwatch
22
26
  @lock = Mutex.new
23
27
  end
24
28
 
29
+ # Nothing here belongs to the thread that calls it, so a call may be
30
+ # made from, and left behind in, another (Client#record_execute_start).
31
+ def abandonable?
32
+ true
33
+ end
34
+
25
35
  def upsert_job(definition, now)
26
36
  definition = JobDefinition.from_h(definition)
27
37
  sync do
@@ -21,7 +21,8 @@ module Cronwatch
21
21
  # gives it 25 seconds and moves on without a diagnosis if it takes longer.
22
22
  class Anthropic
23
23
  DEFAULT_MODEL = "claude-opus-5"
24
- DEFAULT_MAX_TOKENS = 800
24
+ # Room for the model's thinking as well as the paragraph it writes after it.
25
+ DEFAULT_MAX_TOKENS = 4096
25
26
  DEFAULT_EFFORT = "medium"
26
27
  FALLBACK_BETA = "server-side-fallback-2026-07-01"
27
28
  # Under the client's 25 second wait, so the request ends on its own first.
@@ -46,7 +47,10 @@ module Cronwatch
46
47
  # client: bring a configured Anthropic::Client instead.
47
48
  # model: default "claude-opus-5".
48
49
  # effort: how hard the model thinks: "low", "medium" (the default) or "high".
49
- # max_tokens: default 800. A diagnosis is a paragraph.
50
+ # max_tokens: default 4096. A diagnosis is a paragraph, but the model thinks first
51
+ # (thinking is on by default on current models) and that thinking counts
52
+ # toward this limit, so one sized for the paragraph alone can be used up
53
+ # before any of it is written.
50
54
  # fallbacks: route a policy refusal to Anthropic's default fallback model inside
51
55
  # the same request, so a diagnosis still comes back. On by default;
52
56
  # turn off if your account or gateway rejects the beta.
@@ -69,6 +73,14 @@ module Cronwatch
69
73
  return nil if response.stop_reason.to_s == "refusal"
70
74
 
71
75
  text = JS.trim((response.content || []).select { |block| block.type.to_s == "text" }.map(&:text).join("\n"))
76
+ # The limit ran out before any of the diagnosis was written (on its
77
+ # thinking, say): raised, so the client reports it to on_error rather
78
+ # than the alert going out with no diagnosis and no word of why. The
79
+ # text is the SDK's, its option name included.
80
+ if text.empty? && response.stop_reason.to_s == "max_tokens"
81
+ raise "triage: the model reached max_tokens (#{@max_tokens}) before writing a diagnosis; raise maxTokens or lower effort"
82
+ end
83
+
72
84
  text.empty? ? nil : text
73
85
  end
74
86
 
@@ -2,5 +2,5 @@
2
2
 
3
3
  module Cronwatch
4
4
  # Kept in step with @cronwatch/sdk.
5
- VERSION = "0.14.3"
5
+ VERSION = "0.15.0"
6
6
  end
@@ -32,7 +32,9 @@ module Cronwatch
32
32
  # With no token while Cronwatch::Environment is development
33
33
  # (Environment.stated_development?: under Puma, Unicorn,
34
34
  # Thin, or rackup, which set RACK_ENV=development by default,
35
- # RACK_ENV alone does not count), the app makes a random one and
35
+ # RACK_ENV alone does not count), the client makes a random one
36
+ # (kept for every app built for it, so a Rails reload of
37
+ # config/routes.rb does not sign the browser out) and the app
36
38
  # prints a sign-in link to stdout on its first request; with no
37
39
  # token otherwise it answers 503. Pass `token: nil` to opt out and serve it open everywhere,
38
40
  # for example behind your own auth. /api/check also accepts the
@@ -125,7 +127,11 @@ module Cronwatch
125
127
  # alike), so development gets a token too: made here, and shown only in
126
128
  # the server log.
127
129
  @generated = @token.nil? && !@opted_out && Environment.stated_development?
128
- @token = Web.development_token if @generated
130
+ # The client's, so that an app built again for the same client (Rails
131
+ # builds one each time it reloads config/routes.rb, after any change to
132
+ # the app's code) keeps the token a browser has already signed in with.
133
+ @sign_in = (client ? client.development_sign_in : DevelopmentSignIn.new) if @generated
134
+ @token = @sign_in.token if @generated
129
135
  Web.warn_short_token(@token) unless @generated
130
136
  @announced = false
131
137
  @announce_lock = Mutex.new
@@ -146,8 +152,33 @@ module Cronwatch
146
152
  "such as the output of `ruby -rsecurerandom -e 'puts SecureRandom.urlsafe_base64(32)'`"
147
153
  end
148
154
 
149
- # A token for one app in development, when none is configured: 32 random
150
- # bytes, base64url (43 characters).
155
+ # The development token of one client, and the sign-in lines printed for
156
+ # it: every app built for the client shares them (Client#development_sign_in),
157
+ # so the token outlives the app and a line is printed once, however many
158
+ # times the app is built again.
159
+ #
160
+ # @api private
161
+ class DevelopmentSignIn
162
+ attr_reader :token
163
+
164
+ def initialize
165
+ @token = Web.development_token
166
+ @printed = {}
167
+ @lock = Mutex.new
168
+ end
169
+
170
+ # Whether `line` has not been printed for this client before.
171
+ def first?(line)
172
+ @lock.synchronize do
173
+ next false if @printed[line]
174
+
175
+ @printed[line] = true
176
+ end
177
+ end
178
+ end
179
+
180
+ # A token for one client in development, when none is configured: 32
181
+ # random bytes, base64url (43 characters).
151
182
  def self.development_token
152
183
  Base64.urlsafe_encode64(SecureRandom.random_bytes(32), padding: false)
153
184
  end
@@ -444,7 +475,8 @@ module Cronwatch
444
475
  end
445
476
  end
446
477
 
447
- # Prints the development sign-in link, once per app.
478
+ # Prints the development sign-in link on the app's first request, unless
479
+ # an earlier app of the same client printed the same line.
448
480
  def announce(request, base)
449
481
  first = @announce_lock.synchronize do
450
482
  next false if @announced
@@ -455,7 +487,10 @@ module Cronwatch
455
487
 
456
488
  own = request_origin(request)
457
489
  shown = @origin || (Web.loopback_origin?(own) ? own : nil)
458
- $stdout.puts(Web.development_sign_in_line(shown, base, @token))
490
+ line = Web.development_sign_in_line(shown, base, @token)
491
+ return unless @sign_in.first?(line)
492
+
493
+ $stdout.puts(line)
459
494
  $stdout.flush
460
495
  end
461
496
 
@@ -708,10 +743,15 @@ module Cronwatch
708
743
  "/#{out.join("/")}"
709
744
  end
710
745
 
746
+ # A header's value as valid UTF-8, or nil. A server hands the bytes
747
+ # over as they came (Puma as ASCII-8BIT), and a cookie or an
748
+ # Authorization header may hold any: bytes that are not UTF-8 become
749
+ # U+FFFD, so nothing that reads the value can raise on its encoding.
711
750
  def header(name)
712
751
  key = name.tr("-", "_").upcase
713
752
  key = "HTTP_#{key}" unless %w[CONTENT_TYPE CONTENT_LENGTH].include?(key)
714
- @env[key]
753
+ value = @env[key]
754
+ value.nil? ? nil : Output.utf8(value)
715
755
  end
716
756
 
717
757
  # scheme://host[:port], the page's origin as the request URL gives it
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: cronwatch
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.14.3
4
+ version: 0.15.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Jon C. Phillips