nonnative 3.19.0 → 3.26.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: 011e40916b32666c33c2a0374ee97c3e96d563cf950f5c68e12b8afa7c18e986
4
- data.tar.gz: 7b21a33ad8fc14077751e679b66a14523c79c0783004934f55fa61ea5608e477
3
+ metadata.gz: 59db521cea52e4a8c1d2aa8d76e79b50e7a9b76876b63ed8be4e46a665614a5d
4
+ data.tar.gz: 45f21fd21830aab99ce440d65d7cb80720449169684320f814a9e767881d8a1f
5
5
  SHA512:
6
- metadata.gz: 0e24fea055ed0e972507bfcb8ebbdf2c604d41e1a6908333a1863f1ba44dd356ea518936d3d6076f73fb37d0c3a9f593b6321ef1392d51d6d1cdf4c145b5ad6d
7
- data.tar.gz: ec70302587120b093bb506d5d324821e880b10e406974822f44e1efa7c3fdee29465847eb8f71466ab3806ddd0eb328f2e0788bca28196066c6b3636ce0edb83
6
+ metadata.gz: 47d05d9b12dc2601470b87af8a880018a0be1808aee7f501f48a703db422b57db37d041b4f93fbb4ebb5afd4545bccf1ed3bf9b15b7a9d9909ca9134dc1d0111
7
+ data.tar.gz: 0d191245bdedd04c73096cfc4c3cd1871966c6aa9b09a1e5295c835a76798afea4633638f2d6f3bc1179d20f683484c6b033a8c655b45c047c9c468d18aa7fca
data/README.md CHANGED
@@ -211,6 +211,15 @@ Nonnative::Token.http_audience('GET', '/v1/things') # => "GET /v1/things"
211
211
  Nonnative::Token.grpc_audience('/health.v1.Health/Check') # => "/health.v1.Health/Check"
212
212
  ```
213
213
 
214
+ By default the time claims are pinned to the current time (`iat`/`nbf` at now, `exp` at `now + expiration`). To write negative auth tests, `generate` accepts optional absolute `Time` overrides — `issued_at`, `not_before`, and `expires_at` — for minting not-yet-valid or clock-skewed tokens:
215
+
216
+ ```ruby
217
+ # a token that is not valid until an hour from now
218
+ token.generate(aud: 'GET /v1/things', sub: 'user-1', not_before: Time.now + 3600)
219
+ ```
220
+
221
+ `ssh` tokens have no `nbf` claim, so passing `not_before` for the `ssh` kind raises `ArgumentError`.
222
+
214
223
  ### 🔁 Lifecycle strategies (Cucumber integration)
215
224
 
216
225
  Nonnative ships Cucumber hooks (when loaded) that support these tags/strategies:
@@ -456,6 +465,30 @@ module Nonnative
456
465
  end
457
466
  ```
458
467
 
468
+ To run multiple Rack services on one managed port, pass a non-empty mount map. Each key must start
469
+ with `/`, and the mounted application receives the remaining `PATH_INFO`:
470
+
471
+ ```ruby
472
+ module Nonnative
473
+ module Features
474
+ class HealthService < Nonnative::HTTPService
475
+ get '/' do
476
+ 'ok'
477
+ end
478
+ end
479
+
480
+ class HTTPServer < Nonnative::HTTPServer
481
+ def initialize(service)
482
+ super({ '/api' => HelloService.new, '/health' => HealthService.new }, service)
483
+ end
484
+ end
485
+ end
486
+ end
487
+ ```
488
+
489
+ The existing single-service form remains supported. Nonnative converts a mount map to a
490
+ `Rack::URLMap` and keeps one server lifecycle and port. An empty mount map raises `ArgumentError`.
491
+
459
492
  Set it up programmatically:
460
493
 
461
494
  ```ruby
@@ -508,6 +541,8 @@ end
508
541
 
509
542
  The system allows you to define an in-process HTTP forward proxy server for external systems, e.g. `api.github.com`. This is a server implementation, not a fault-injection service proxy.
510
543
 
544
+ The proxy preserves the upstream status, body, and safe end-to-end response headers such as `Content-Type`, `ETag`, and application-specific metadata. It removes hop-by-hop, connection-nominated, proxy-authentication, and framing headers; `Set-Cookie`, `Location`, and `Content-Encoding` are not forwarded.
545
+
511
546
  Define your server:
512
547
 
513
548
  ```ruby
@@ -594,6 +629,30 @@ module Nonnative
594
629
  end
595
630
  ```
596
631
 
632
+ To serve multiple gRPC services on one managed port, pass a non-empty array of handler classes or
633
+ instances:
634
+
635
+ ```ruby
636
+ module Nonnative
637
+ module Features
638
+ class HealthService < Grpc::Health::V1::Health::Service
639
+ def check(_request, _call)
640
+ Grpc::Health::V1::HealthCheckResponse.new(status: :SERVING)
641
+ end
642
+ end
643
+
644
+ class GRPCServer < Nonnative::GRPCServer
645
+ def initialize(service)
646
+ super([Greeter.new, HealthService.new], service)
647
+ end
648
+ end
649
+ end
650
+ end
651
+ ```
652
+
653
+ The existing single-handler form remains supported. Nonnative registers each handler before the
654
+ server starts, so application and standard health handlers can share one lifecycle and endpoint.
655
+
597
656
  Set it up programmatically:
598
657
 
599
658
  ```ruby
@@ -789,9 +848,10 @@ Clients connect to the service `host`/`port`, while the proxy forwards traffic t
789
848
 
790
849
  - `close_all` - Closes the socket as soon as it connects.
791
850
  - `reset_peer` - Resets the socket as soon as it connects, so clients observe a TCP reset (`Errno::ECONNRESET`) rather than the graceful close performed by `close_all`.
792
- - `delay` - Delays traffic on the connection. Defaults to 2 seconds and can be configured through options.
851
+ - `delay` - Delays traffic on the connection. Defaults to 2 seconds and can be configured through `options.delay`. An optional `options.jitter` (seconds) adds a random offset in `-jitter..jitter` to each delay (a negative value uses its magnitude), so clients see variable, tail-latency-like timing instead of a flat value.
793
852
  - `timeout` - Accepts the connection and stalls traffic until reset or stop closes the connection, so clients exercise their own read timeout behavior.
794
853
  - `invalid_data` - Forwards client requests unchanged, then corrupts upstream responses before they reach the client.
854
+ - `bandwidth` - Throttles forwarded throughput to `options.rate` kilobytes per second (1 KB = 1024 bytes) by sleeping in proportion to the bytes read, in both directions, so clients see a slow-but-alive dependency. When `rate` is absent or not positive, traffic forwards at full speed.
795
855
 
796
856
  ###### 🧩 Fault Injection Services
797
857
 
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Nonnative
4
+ # Socket-pair variant used by the fault-injection proxy to simulate a bandwidth-limited link.
5
+ #
6
+ # When active, each forwarded read is throttled so throughput does not exceed
7
+ # `proxy.options[:rate]` kilobytes per second (1 KB = 1024 bytes), by sleeping in proportion to the
8
+ # bytes read. Both directions are throttled, so a client under test sees a slow-but-alive
9
+ # dependency. When `rate` is absent or not positive the connection forwards at full speed.
10
+ #
11
+ # This behavior is enabled by calling {Nonnative::FaultInjectionProxy#bandwidth}.
12
+ #
13
+ # @see Nonnative::FaultInjectionProxy
14
+ # @see Nonnative::SocketPairFactory
15
+ # @see Nonnative::SocketPair
16
+ class BandwidthSocketPair < SocketPair
17
+ # One kilobyte in bytes; `proxy.options[:rate]` is expressed in KB/s.
18
+ KILOBYTE = 1024
19
+
20
+ # Reads from the socket, then sleeps so the forwarded throughput stays within the configured rate.
21
+ #
22
+ # @param socket [IO] the socket to read from
23
+ # @return [String] the bytes read from the socket
24
+ def read(socket)
25
+ super.tap { |data| throttle(data.bytesize) }
26
+ end
27
+
28
+ private
29
+
30
+ # Sleeps in proportion to the bytes read so throughput does not exceed `rate` KB/s. A missing or
31
+ # non-positive rate (or an empty read) forwards at full speed.
32
+ #
33
+ # @param bytes [Integer] the number of bytes just read
34
+ # @return [void]
35
+ def throttle(bytes)
36
+ rate = proxy.options[:rate]
37
+ return if rate.nil? || rate <= 0 || bytes.zero?
38
+
39
+ sleep(bytes / (rate * KILOBYTE.to_f))
40
+ end
41
+ end
42
+ end
@@ -59,6 +59,7 @@ module Nonnative
59
59
  'delay' => :delay,
60
60
  'timeout' => :timeout,
61
61
  'invalid_data' => :invalid_data,
62
+ 'bandwidth' => :bandwidth,
62
63
  'reset' => :reset
63
64
  }.freeze
64
65
 
@@ -5,7 +5,11 @@ module Nonnative
5
5
  #
6
6
  # When active, reads from the socket are delayed by a configured duration before being forwarded.
7
7
  #
8
- # The delay duration is controlled by `proxy.options[:delay]` and defaults to 2 seconds.
8
+ # The delay duration is controlled by `proxy.options[:delay]` and defaults to 2 seconds. An
9
+ # optional `proxy.options[:jitter]` (seconds) adds a random offset in `-jitter..jitter` to each
10
+ # delay so clients see variable, tail-latency-like timing instead of a flat value; a negative
11
+ # jitter uses its magnitude and the resulting delay is never negative. When `jitter` is absent the
12
+ # delay is the flat duration.
9
13
  #
10
14
  # This behavior is enabled by calling {Nonnative::FaultInjectionProxy#delay}.
11
15
  #
@@ -20,10 +24,22 @@ module Nonnative
20
24
  def read(socket)
21
25
  Nonnative.logger.info "delaying socket '#{socket.inspect}' for 'delay' pair"
22
26
 
23
- duration = proxy.options[:delay] || 2
24
- sleep duration
27
+ sleep delay_duration
25
28
 
26
29
  super
27
30
  end
31
+
32
+ private
33
+
34
+ # The delay applied before a read, optionally jittered by `proxy.options[:jitter]`.
35
+ #
36
+ # @return [Numeric] seconds to sleep (never negative)
37
+ def delay_duration
38
+ duration = proxy.options[:delay] || 2
39
+ jitter = proxy.options[:jitter]&.abs
40
+ return duration unless jitter
41
+
42
+ [duration + rand(-jitter..jitter), 0].max
43
+ end
28
44
  end
29
45
  end
@@ -14,6 +14,7 @@ module Nonnative
14
14
  # - {#delay}: delay reads by a configured duration (default: 2 seconds)
15
15
  # - {#timeout}: accept connections and keep them silent until clients time out
16
16
  # - {#invalid_data}: forward requests unchanged and mutate upstream responses before they reach clients
17
+ # - {#bandwidth}: throttle forwarded throughput to a configured rate (KB/s)
17
18
  # - {#reset}: return to healthy pass-through behavior
18
19
  #
19
20
  # State changes terminate any active connections so new connections observe the new behavior.
@@ -33,6 +34,8 @@ module Nonnative
33
34
  # - `wait`: sleep interval (seconds) applied after state changes
34
35
  # - `options`:
35
36
  # - `delay`: delay duration in seconds used by {#delay}
37
+ # - `jitter`: optional random offset (seconds) added in `-jitter..jitter` to each `delay` (a
38
+ # negative value uses its magnitude), so clients see variable latency instead of a flat value
36
39
  #
37
40
  # @see Nonnative::Proxy
38
41
  # @see Nonnative::SocketPairFactory
@@ -137,6 +140,16 @@ module Nonnative
137
140
  apply_state :invalid_data
138
141
  end
139
142
 
143
+ # Throttles forwarded throughput to a configured rate.
144
+ #
145
+ # The rate is controlled by `service.proxy.options[:rate]` (kilobytes per second); when it is
146
+ # absent or not positive the connection forwards at full speed.
147
+ #
148
+ # @return [void]
149
+ def bandwidth
150
+ apply_state :bandwidth
151
+ end
152
+
140
153
  # Resets the proxy back to healthy pass-through behavior.
141
154
  #
142
155
  # @return [void]
@@ -12,13 +12,18 @@ module Nonnative
12
12
  #
13
13
  # @see Nonnative::Server
14
14
  class GRPCServer < Nonnative::Server
15
- # Creates a gRPC server and registers the provided service handler.
15
+ # Creates a gRPC server and registers the provided service handler(s).
16
16
  #
17
- # @param svc [Object] a gRPC service implementation (typically a `...::Service` subclass instance)
17
+ # @param svc [Object, Array<Object>] a gRPC service implementation or a non-empty array of
18
+ # implementations (typically `...::Service` subclasses or instances)
18
19
  # @param service [Nonnative::ConfigurationServer] server configuration
20
+ # @raise [ArgumentError] if `svc` is an empty array
19
21
  def initialize(svc, service)
20
22
  @server = GRPC::RpcServer.new
21
- server.handle(svc)
23
+ handlers = svc.is_a?(Array) ? svc : [svc]
24
+ raise ArgumentError, 'gRPC server requires at least one service handler' if handlers.empty?
25
+
26
+ handlers.each { |handler| server.handle(handler) }
22
27
 
23
28
  # Unfortunately gRPC has only one logger so the first server wins.
24
29
  GRPC.define_singleton_method(:logger) do
@@ -80,6 +80,18 @@ module Nonnative
80
80
  end
81
81
  end
82
82
 
83
+ # Performs a PATCH request.
84
+ #
85
+ # @param pathname [String] path relative to `host`
86
+ # @param payload [Object] request payload
87
+ # @param opts [Hash] RestClient request options
88
+ # @return [RestClient::Response, String] response for non-2xx errors, otherwise the RestClient result
89
+ def patch(pathname, payload, opts = {})
90
+ with_exception do
91
+ resource(pathname, opts).patch(payload)
92
+ end
93
+ end
94
+
83
95
  # Creates a RestClient resource for a relative path.
84
96
  #
85
97
  # @param pathname [String] path relative to `host`
@@ -3,7 +3,8 @@
3
3
  # Sinatra-based HTTP forward proxy server used as an in-process Nonnative server.
4
4
  #
5
5
  # The proxy receives inbound HTTP requests and forwards them to an upstream host over HTTPS, returning
6
- # the upstream response status and body.
6
+ # the upstream response status, body, and safe end-to-end response headers. Hop-by-hop,
7
+ # connection-nominated, proxy-authentication, framing, and deferred response headers are not forwarded.
7
8
  #
8
9
  # This file defines two classes:
9
10
  #
@@ -23,7 +24,25 @@ module Nonnative
23
24
  #
24
25
  # Supported HTTP verbs: GET, POST, PUT, PATCH, DELETE.
25
26
  class HTTPProxy < Nonnative::HTTPService
26
- NON_FORWARDABLE_HEADERS = %w[
27
+ NON_FORWARDABLE_RESPONSE_HEADERS = %w[
28
+ connection
29
+ content-encoding
30
+ content-length
31
+ keep-alive
32
+ location
33
+ proxy-authenticate
34
+ proxy-authorization
35
+ proxy-authentication-info
36
+ proxy-connection
37
+ set-cookie
38
+ status
39
+ te
40
+ trailer
41
+ transfer-encoding
42
+ upgrade
43
+ ].freeze
44
+
45
+ NON_FORWARDABLE_REQUEST_HEADERS = %w[
27
46
  Host
28
47
  Accept-Encoding
29
48
  Version
@@ -37,14 +56,14 @@ module Nonnative
37
56
  #
38
57
  # @param request [Sinatra::Request] the incoming request
39
58
  # @return [Hash{String=>String}] headers to forward to the upstream
40
- def retrieve_headers(request)
59
+ def forward_request_headers(request)
41
60
  headers = request.env.each_with_object({}) do |(header, value), result|
42
- next unless forward_header?(header)
61
+ next unless forward_request_header?(header)
43
62
 
44
- result[normalized_header_name(header)] = value
63
+ result[normalized_request_header_name(header)] = value
45
64
  end
46
65
 
47
- headers.except(*NON_FORWARDABLE_HEADERS)
66
+ headers.except(*NON_FORWARDABLE_REQUEST_HEADERS)
48
67
  end
49
68
 
50
69
  # Builds the upstream URL for the given request.
@@ -86,11 +105,43 @@ module Nonnative
86
105
 
87
106
  private
88
107
 
89
- def forward_header?(header)
108
+ def forward_response_headers(response)
109
+ raw_headers = response.raw_headers
110
+ connection_headers = response_connection_headers(raw_headers)
111
+
112
+ raw_headers.each_with_object({}) do |(header, value), result|
113
+ normalized_header = normalized_response_header_name(header)
114
+ next unless forward_response_header?(normalized_header, connection_headers)
115
+
116
+ result[normalized_header] = Array(value).join(', ')
117
+ end
118
+ end
119
+
120
+ def response_connection_headers(raw_headers)
121
+ connection_headers = raw_headers.each_with_object([]) do |(header, values), result|
122
+ next unless normalized_response_header_name(header) == 'connection'
123
+
124
+ Array(values).each { |value| result.concat(value.to_s.split(',')) }
125
+ end
126
+
127
+ connection_headers.map { |header| normalized_response_header_name(header) }
128
+ end
129
+
130
+ def forward_response_header?(header, connection_headers)
131
+ !NON_FORWARDABLE_RESPONSE_HEADERS.include?(header) &&
132
+ !connection_headers.include?(header) &&
133
+ !header.start_with?('rack.')
134
+ end
135
+
136
+ def normalized_response_header_name(header)
137
+ header.to_s.strip.downcase
138
+ end
139
+
140
+ def forward_request_header?(header)
90
141
  header.start_with?('HTTP_') || %w[CONTENT_TYPE CONTENT_LENGTH].include?(header)
91
142
  end
92
143
 
93
- def normalized_header_name(header)
144
+ def normalized_request_header_name(header)
94
145
  header.delete_prefix('HTTP_').split('_').map(&:capitalize).join('-')
95
146
  end
96
147
 
@@ -99,10 +150,11 @@ module Nonnative
99
150
  res = api_response(
100
151
  method: verb.to_sym,
101
152
  url: build_url(request, settings),
102
- headers: retrieve_headers(request),
153
+ headers: forward_request_headers(request),
103
154
  payload: retrieve_payload(request, verb)
104
155
  )
105
156
 
157
+ headers(forward_response_headers(res))
106
158
  status res.code
107
159
  res.body
108
160
  end
@@ -36,9 +36,16 @@ module Nonnative
36
36
  class HTTPServer < Nonnative::Server
37
37
  # Creates a Puma server for the given HTTP service and runner configuration.
38
38
  #
39
- # @param http_service [#call] an HTTP service instance
39
+ # @param http_service [#call, Hash<String, #call>] an HTTP service instance or mount map
40
40
  # @param service [Nonnative::ConfigurationServer] server configuration
41
+ # @raise [ArgumentError] if `http_service` is an empty mount map
41
42
  def initialize(http_service, service)
43
+ if http_service.is_a?(Hash)
44
+ raise ArgumentError, 'HTTP server requires at least one service mount' if http_service.empty?
45
+
46
+ http_service = Rack::URLMap.new(http_service)
47
+ end
48
+
42
49
  # Keep the log IO so the server lifecycle can release Puma's file handle on stop.
43
50
  @log = File.open(service.log, 'a')
44
51
  options = {
@@ -27,16 +27,19 @@ module Nonnative
27
27
  #
28
28
  # @param aud [String] the `aud` claim (for example `"GET /v1/things"` or a gRPC full method)
29
29
  # @param sub [String] the `sub` claim
30
+ # @param issued_at [Time, nil] overrides the `iat` claim (default: now)
31
+ # @param not_before [Time, nil] overrides the `nbf` claim (default: `issued_at`)
32
+ # @param expires_at [Time, nil] overrides the `exp` claim (default: `issued_at` plus `expiration`)
30
33
  # @return [String] the signed JWT
31
- def generate(aud:, sub:)
32
- now = Time.now.to_i
34
+ def generate(aud:, sub:, issued_at: nil, not_before: nil, expires_at: nil)
35
+ now = issued_at || Time.now
33
36
  payload = {
34
37
  iss: @issuer,
35
38
  aud: aud,
36
39
  sub: sub,
37
- iat: now,
38
- nbf: now,
39
- exp: now + @expiration,
40
+ iat: now.to_i,
41
+ nbf: (not_before || now).to_i,
42
+ exp: (expires_at || (now + @expiration)).to_i,
40
43
  jti: SecureRandom.uuid
41
44
  }
42
45
 
@@ -28,18 +28,21 @@ module Nonnative
28
28
  #
29
29
  # @param aud [String] the `aud` claim (for example `"GET /v1/things"` or a gRPC full method)
30
30
  # @param sub [String] the `sub` claim
31
+ # @param issued_at [Time, nil] overrides the `iat` claim (default: now)
32
+ # @param not_before [Time, nil] overrides the `nbf` claim (default: `issued_at`)
33
+ # @param expires_at [Time, nil] overrides the `exp` claim (default: `issued_at` plus `expiration`)
31
34
  # @return [String] the signed PASETO token
32
- def generate(aud:, sub:)
35
+ def generate(aud:, sub:, issued_at: nil, not_before: nil, expires_at: nil)
33
36
  load_dependencies!
34
37
 
35
- now = Time.now.utc
38
+ now = (issued_at || Time.now).utc
36
39
  claims = {
37
40
  'iss' => @issuer,
38
41
  'aud' => aud,
39
42
  'sub' => sub,
40
43
  'iat' => now.iso8601,
41
- 'nbf' => now.iso8601,
42
- 'exp' => (now + @expiration).iso8601,
44
+ 'nbf' => (not_before || now).utc.iso8601,
45
+ 'exp' => (expires_at || (now + @expiration)).utc.iso8601,
43
46
  'jti' => SecureRandom.uuid
44
47
  }
45
48
 
@@ -23,17 +23,14 @@ module Nonnative
23
23
  @processes = nil
24
24
  end
25
25
 
26
- # Starts all configured runners and yields results for each process/server.
26
+ # Starts all configured runners and collects lifecycle and readiness errors.
27
27
  #
28
28
  # Services are started first (proxy-only) and checked for opt-in readiness, then servers and processes are
29
- # started and checked for readiness.
29
+ # started and checked for readiness. Each readiness failure is described with the runner and, for a process
30
+ # that exited early, its termination detail.
30
31
  #
31
- # @yieldparam name [String, nil] runner name
32
- # @yieldparam values [Object] runner-specific return value from `start` (e.g. `[pid, running]` for processes)
33
- # @yieldparam result [Boolean] result of the port readiness check (`true` if ready in time)
34
- # @yieldparam port [Nonnative::Ports] checked port group
35
32
  # @return [Array<String>] lifecycle and readiness-check errors collected while starting
36
- def start(&)
33
+ def start
37
34
  errors = []
38
35
 
39
36
  errors.concat(service_lifecycle(services, :start, :start))
@@ -41,24 +38,20 @@ module Nonnative
41
38
  errors.concat(service_readiness_errors)
42
39
  return errors if service_readiness_errors.any?
43
40
 
44
- [servers, processes].each { |runners| errors.concat(run_lifecycle_checks(runners, :start, :open?, :start, &)) }
41
+ [servers, processes].each { |runners| errors.concat(run_lifecycle_checks(runners, :start, :open?, :start)) }
45
42
 
46
43
  errors
47
44
  end
48
45
 
49
- # Stops all configured runners and yields results for each process/server.
46
+ # Stops all configured runners and collects lifecycle and shutdown errors.
50
47
  #
51
48
  # Processes and servers are stopped first and checked for shutdown, then services are stopped (proxy-only).
52
49
  #
53
- # @yieldparam name [String, nil] runner name
54
- # @yieldparam id [Object] runner-specific identifier returned by `stop` (e.g. pid or object_id)
55
- # @yieldparam result [Boolean] result of the port shutdown check (`true` if closed in time)
56
- # @yieldparam port [Nonnative::Ports] checked port group
57
50
  # @return [Array<String>] lifecycle and shutdown-check errors collected while stopping
58
- def stop(&)
51
+ def stop
59
52
  errors = []
60
53
 
61
- [processes, servers].each { |runners| errors.concat(run_lifecycle_checks(runners, :stop, :closed?, :stop, &)) }
54
+ [processes, servers].each { |runners| errors.concat(run_lifecycle_checks(runners, :stop, :closed?, :stop)) }
62
55
  errors.concat(service_lifecycle(services, :stop, :stop))
63
56
 
64
57
  errors
@@ -69,16 +62,12 @@ module Nonnative
69
62
  # This is used to rollback partial startup after a failed {#start} without constructing new runner
70
63
  # wrappers as a side effect.
71
64
  #
72
- # @yieldparam name [String, nil] runner name
73
- # @yieldparam id [Object] runner-specific identifier returned by `stop`
74
- # @yieldparam result [Boolean] result of the port shutdown check (`true` if closed in time)
75
- # @yieldparam port [Nonnative::Ports] checked port group
76
65
  # @return [Array<String>] lifecycle and shutdown-check errors collected while rolling back
77
- def rollback(&)
66
+ def rollback
78
67
  errors = []
79
68
 
80
69
  [existing_processes, existing_servers].each do |runners|
81
- errors.concat(run_lifecycle_checks(runners, :stop, :closed?, :stop, &))
70
+ errors.concat(run_lifecycle_checks(runners, :stop, :closed?, :rollback))
82
71
  end
83
72
  errors.concat(service_lifecycle(existing_services, :stop, :stop))
84
73
 
@@ -196,7 +185,8 @@ module Nonnative
196
185
  end
197
186
  end
198
187
 
199
- def run_lifecycle_checks(runners, lifecycle_method, port_method, action, &)
188
+ def run_lifecycle_checks(runners, lifecycle_method, port_method, phase)
189
+ action = phase == :start ? :start : :stop
200
190
  checks = []
201
191
  errors = []
202
192
 
@@ -207,7 +197,7 @@ module Nonnative
207
197
  errors << lifecycle_error(action, runner, e)
208
198
  end
209
199
 
210
- errors.concat(yield_results(checks, action, &))
200
+ errors.concat(lifecycle_results(checks, phase, action))
211
201
  end
212
202
 
213
203
  def check_port(port, port_method)
@@ -216,17 +206,50 @@ module Nonnative
216
206
  { error: e }
217
207
  end
218
208
 
219
- def yield_results(checks, action, &)
220
- checks.each_with_object([]) do |(type, values, port, thread), errors|
209
+ def lifecycle_results(checks, phase, action)
210
+ checks.each_with_object([]) do |(runner, values, port, thread), errors|
221
211
  result = thread.value
222
212
  if result[:error]
223
- errors << port_error(action, type, result[:error])
224
- elsif block_given?
225
- yield type.name, values, result[:result], port
213
+ errors << port_error(action, runner, result[:error])
214
+ else
215
+ errors.concat(readiness_errors(phase, runner, values, result[:result], port))
226
216
  end
227
217
  end
228
218
  end
229
219
 
220
+ def readiness_errors(phase, runner, values, ready, port)
221
+ case phase
222
+ when :start then start_errors(runner, values, ready, port)
223
+ when :stop then stop_errors(runner, values, ready, port)
224
+ else rollback_errors(runner, values, ready, port)
225
+ end
226
+ end
227
+
228
+ def start_errors(runner, values, ready, port)
229
+ id, started = values
230
+ return [] if started && ready
231
+
232
+ message = "Started #{runner.name} with id #{id}, though did not respond in time for #{port.description}"
233
+ detail = runner.termination
234
+ [detail ? "#{message}; #{detail}" : message]
235
+ end
236
+
237
+ def stop_errors(runner, values, ready, port)
238
+ id, stopped = Array(values).then { |v| [v.first, v.fetch(1, true)] }
239
+ errors = []
240
+ errors << "Stopped #{runner.name} with id #{id}, though did not respond in time for #{port.description}" unless ready
241
+ errors << "Stopped #{runner.name} with id #{id}, though the process did not exit in time" unless stopped
242
+ errors
243
+ end
244
+
245
+ def rollback_errors(runner, values, ready, port)
246
+ id, stopped = Array(values).then { |v| [v.first, v.fetch(1, true)] }
247
+ errors = []
248
+ errors << "Rollback failed for #{runner.name} with id #{id}, because it did not stop in time for #{port.description}" unless ready
249
+ errors << "Rollback failed for #{runner.name} with id #{id}, because the process did not exit in time" unless stopped
250
+ errors
251
+ end
252
+
230
253
  def lifecycle_error(action, type, error)
231
254
  "#{action.to_s.capitalize} failed for #{runner_name(type)}: #{error.class} - #{error.message}"
232
255
  end
@@ -37,7 +37,10 @@ module Nonnative
37
37
  wait_start
38
38
  end
39
39
 
40
- [pid, ::Process.waitpid2(pid, ::Process::WNOHANG).nil?]
40
+ # Retain the reaped status for this lifecycle so startup diagnostics can report it.
41
+ status = ::Process.waitpid2(pid, ::Process::WNOHANG)
42
+ @status = status&.last
43
+ [pid, status.nil?]
41
44
  end
42
45
 
43
46
  # Stops the process if it is running.
@@ -62,6 +65,20 @@ module Nonnative
62
65
  @memory = nil
63
66
  end
64
67
 
68
+ # Describes how the process terminated when it exited before becoming ready.
69
+ #
70
+ # Returns `nil` while the process is still running, so callers can distinguish an early exit
71
+ # from a live process that merely missed its readiness window. The check is non-blocking and
72
+ # reuses the status captured during {#start} when available.
73
+ #
74
+ # @return [String, nil] termination detail (exit status or terminating signal), or `nil`
75
+ def termination
76
+ status = captured_status
77
+ return if status.nil?
78
+
79
+ terminated_description(status)
80
+ end
81
+
65
82
  protected
66
83
 
67
84
  def wait_stop
@@ -74,6 +91,28 @@ module Nonnative
74
91
 
75
92
  attr_reader :pid, :timeout
76
93
 
94
+ def captured_status
95
+ return @status unless @status.nil?
96
+ return if pid.nil?
97
+
98
+ # A process that exited during the readiness window has not been reaped yet.
99
+ @status = ::Process.waitpid2(pid, ::Process::WNOHANG)&.last
100
+ rescue Errno::ECHILD, Errno::ESRCH
101
+ nil
102
+ end
103
+
104
+ def terminated_description(status)
105
+ return "process exited before readiness with exit status #{status.exitstatus}" if status.exited?
106
+ return "process exited before readiness after being killed by signal #{signal_description(status.termsig)}" if status.signaled?
107
+
108
+ "process exited before readiness (#{status})"
109
+ end
110
+
111
+ def signal_description(signal)
112
+ name = Signal.signame(signal)
113
+ name ? "SIG#{name} (#{signal})" : signal.to_s
114
+ end
115
+
77
116
  def process_kill
78
117
  signal = Signal.list[service.signal || 'INT'] || Signal.list['INT']
79
118
  ::Process.kill(signal, pid)