quicsilver 0.5.0 → 0.6.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: 9f3ec155af92a08642dd37953aa75728a021f9868c964c0240a61b98399f72be
4
- data.tar.gz: 6c5effb85af855cfd60761fc7aef9bdf0cc6901df1c56b478d22557705c55925
3
+ metadata.gz: aa8cd857ef19c8c001b5225ae781060746b0618bec8a47ef0d1db0905693ed76
4
+ data.tar.gz: fd556e29cfb26c55dbc5c5b390e47483a71a52696b4fd5a36e77b2afea25e621
5
5
  SHA512:
6
- metadata.gz: 26490f0003dc3424abb07afaddd5fa9057d36a3cb2e974be2ea46b740069dc4114f95a46afa8d43e8f48c2d8dcc0a294187e6c9852806a97ae83f6841e01c9d9
7
- data.tar.gz: 793d530b463494c8df0e6a0268686f0cd3588246300f1ef1763462f770949bbe0c04b20ef55599046486c3fb1383cf7207c9f317d8a0002a7c579b61f95d668a
6
+ metadata.gz: d5afc00d3a0161e8a97350c0adcaafba830b2747b75280e316d857edbab80f847c2a45e3ef862164797296cfed3c9ce0b8fd0eda25efc6164092c06e220f6028
7
+ data.tar.gz: 409871e32a581317834bab07e7998868365cf8fd79b22230b59bbd6e45deaab3fdec3a463e5cbdbc3f0ad90720d7179cf7aa36995d65a9eb0f1ef0cdb9a8eb77
@@ -31,6 +31,13 @@ jobs:
31
31
  allow-failure: false
32
32
  - ruby-version: "head"
33
33
  allow-failure: true
34
+ # Ubuntu's curl has no HTTP/3, so until the step below the 22 tests in
35
+ # curl_http3_test.rb skipped on every CI run. That changes the timing
36
+ # of the whole suite, and two races only ever showed up in the skipped
37
+ # configuration. Keep one job running it on purpose.
38
+ - ruby-version: "4.0"
39
+ allow-failure: false
40
+ skip-curl-http3: true
34
41
 
35
42
  steps:
36
43
  - uses: actions/checkout@v4
@@ -40,10 +47,33 @@ jobs:
40
47
  uses: ruby/setup-ruby@v1
41
48
  with:
42
49
  ruby-version: ${{ matrix.ruby-version }}
50
+ # The Bundler paired with ruby-head still references Pathname::SEPARATOR_PAT,
51
+ # which trunk removed, so setup failed before a single test ran. A
52
+ # permanently red allow-failure job warns about nothing.
53
+ bundler: ${{ matrix.ruby-version == 'head' && 'latest' || 'default' }}
43
54
  bundler-cache: true # runs 'bundle install' and caches installed gems automatically
55
+ # Ubuntu ships curl built without HTTP/3. Drop in a static build that has
56
+ # it, at the path test/integration/integration_helper.rb already probes.
57
+ - name: Install curl with HTTP/3
58
+ if: ${{ !matrix.skip-curl-http3 }}
59
+ env:
60
+ CURL_VERSION: 8.23.0-1
61
+ run: |
62
+ set -euo pipefail
63
+ sudo mkdir -p /usr/local/opt/curl/bin
64
+ curl -fsSL -o /tmp/static-curl.tar.xz \
65
+ "https://github.com/stunnel/static-curl/releases/download/${CURL_VERSION}/curl-linux-x86_64-musl-${CURL_VERSION}.tar.xz"
66
+ tar -xJf /tmp/static-curl.tar.xz -C /tmp curl
67
+ sudo install -m 0755 /tmp/curl /usr/local/opt/curl/bin/curl
68
+ # The helper decides by grepping --version for HTTP3; fail loudly here
69
+ # rather than silently skipping 22 tests again.
70
+ /usr/local/opt/curl/bin/curl --version
71
+ /usr/local/opt/curl/bin/curl --version | grep -q HTTP3
44
72
  - name: Build MSQUIC
45
73
  run: bundle exec rake build_msquic
46
74
  - name: Compile
47
75
  run: bundle exec rake compile
48
76
  - name: Run tests
77
+ env:
78
+ FORCE_NO_CURL_HTTP3: ${{ matrix.skip-curl-http3 && '1' || '' }}
49
79
  run: bundle exec rake
@@ -89,7 +89,7 @@ jobs:
89
89
  - name: "Setup Ruby"
90
90
  uses: "ruby/setup-ruby@v1"
91
91
  with:
92
- ruby-version: "4.0.0"
92
+ ruby-version: "4.0"
93
93
  - name: "Download platform gems"
94
94
  uses: "actions/download-artifact@v5"
95
95
  with:
@@ -110,7 +110,7 @@ jobs:
110
110
  - name: "Setup Ruby"
111
111
  uses: "ruby/setup-ruby@v1"
112
112
  with:
113
- ruby-version: "4.0.0"
113
+ ruby-version: "4.0"
114
114
  - name: "Run cibuildgem"
115
115
  uses: "shopify/cibuildgem/.github/actions/cibuildgem@main"
116
116
  with:
data/CHANGELOG.md CHANGED
@@ -7,6 +7,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.6.0] - 2026-11-17
11
+
12
+ ### Added
13
+
14
+ - `Server#shutdown_timeout=` sets how long a signal-initiated graceful shutdown may take (default 30s). A process manager's own grace period needs it to be shorter: foreman kills after 5s.
15
+ - A DEBUG line for each finished request stream, the counterpart of the `HTTP/3 request` line: `HTTP/3 response stream=916 GET /boards/1 200 length=18322 duration=15.2ms`. It records what happened to the response after the application returned it — sent, skipped because the client cancelled (`cancelled`), or failed (`500 (error)`, `timeout (no stream handle)`) — on both the buffered and streaming dispatch paths. `duration` is the time until the response is handed to MsQuic, not until the last byte is acknowledged; `length` is the content-length, or `-` when the body's length is unknown.
16
+
17
+ ### Changed
18
+
19
+ - Graceful shutdown winds WebTransport sessions down instead of resetting them. Open sessions are sent `WT_DRAIN_SESSION` with the first GOAWAY (draft-ietf-webtrans-http3-16 §4.7); any still open after the request drain and a grace period of up to 1s are closed with a `WT_CLOSE_SESSION` capsule (code 0, "server shutting down"). Previously the client only learned the session was over when the connection was shut down beneath it, and its streams were reset with `WT_SESSION_GONE`. A session the peer closes in response keeps the peer's code and reason.
20
+ - A second INT or TERM during a graceful shutdown stops the server at once, without waiting for queued requests. It was ignored, so a process manager that escalates from INT to TERM (foreman does when another process exits) had to SIGKILL the server.
21
+ - `content-length` on a request no longer reaches Rack as `HTTP_CONTENT_LENGTH`, which `Rack::Lint` rejects — every POST to a Lint-wrapped app returned 500. The length still reaches the application as `CONTENT_LENGTH`, carried by the request body.
22
+ Apps that read `env["HTTP_CONTENT_LENGTH"]` should read `CONTENT_LENGTH`.
23
+
24
+ ### Fixed
25
+
26
+ - Graceful shutdown no longer drains the work queue twice. `shutdown(timeout:)` drained within its timeout and then called `stop`, which drained again with its own 5s default, so a shutdown with requests still queued took up to 5s longer than its timeout.
27
+ - Crash when a connection handle outlives its native context. `Client#disconnect` reads the resumption ticket after an idle timeout or a peer-initiated close, by which point the dispatcher has freed the `ConnectionContext` — a segfault in `dispatch_events` and a bus error in `Quicsilver.get_resumption_ticket`. Contexts are now registered in a token-keyed table under the same lock as streams, and `connection_status`, `wait_for_connection`, `get_resumption_ticket` and `open_stream` resolve the handle instead of dereferencing it. Opening a stream on a closed connection raises `IOError` rather than reusing freed memory.
28
+
10
29
  ## [0.5.0] - 2026-11-02
11
30
 
12
31
  ### Added
@@ -47,7 +66,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
47
66
  - WebTransport child streams have bounded receive queues, and a child that fills its buffer now pauses instead of losing its stream. `accept!` takes `receive_buffer_bytes` (default 1 MiB), `receive_buffer_chunks` (default 1024), `receive_overflow_code` and `receive_backpressure` (default `true`); delivery stops until the application reads. A reader that never drains leaves its stream paused indefinitely, and a paused stream holds connection credit, so it can stall its siblings. `receive_backpressure: false` restores the previous policy: an overflowing child is sent `STOP_SENDING` with `receive_overflow_code`, its queued input is discarded and its pending reads fail, while its write side stays open. Limits apply to each child's queued Ruby input, not to native buffers or the whole connection. `WebTransportStream#initialize` now requires these four options rather than defaulting them, so the defaults have a single home in `WebTransportSession::DEFAULT_RECEIVE_OPTIONS`.
48
67
  - WebTransport stream resets are directional. `RESET_STREAM` closes only the read side and invokes the new `on_peer_reset`; `STOP_SENDING` closes only the write side and invokes the new `on_peer_stop_sending`. `on_close` fires once both directions are closed. Previously either signal tore down the whole stream and both reported through `on_reset`, which is removed — the `peer_` prefix distinguishes these inbound events from the outbound `reset` and `abort` methods.
49
68
  - WebTransport CONNECT waits for peer SETTINGS before reaching Rack, including when headers arrive with FIN. The `webtransport-h3` token requires `WT_ENABLED=1` and `H3_DATAGRAM=1`; the legacy `webtransport` token requires `H3_DATAGRAM=1`. Waiting is limited to one CONNECT and 64 KiB of body data per connection, with cleanup on cancellation or connection closure.
50
- - WebTransport permits one active session per QUIC connection until session flow control is implemented. Additional CONNECT requests are rejected with `H3_REQUEST_REJECTED`; closing a session allows another. SETTINGS no longer advertise session flow-control credit, and the legacy session limit is one.
69
+ - WebTransport permits one active session per QUIC connection. Additional CONNECT requests are rejected with `H3_REQUEST_REJECTED`; closing a session allows another. Session flow control (above) permits more (draft-ietf-webtrans-http3-16 §5.1), but sharing one connection between sessions is a separate change, so the legacy `SETTINGS_WT_MAX_SESSIONS` stays at one.
51
70
  - WebTransport `close(code:, reason:)` rejects invalid UTF-8 and codes outside the unsigned 32-bit range before changing session state. Valid UTF-8 binary strings remain supported; long valid reasons are truncated at a UTF-8 character boundary.
52
71
  - Connection pool default mode is `:shared` (multiplexed) — `:exclusive` available as opt-in
53
72
  - `open_stream` wraps C extension errors into typed `StreamFailedToOpenError` / `TransportError`
data/Gemfile.lock CHANGED
@@ -1,7 +1,7 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- quicsilver (0.5.0)
4
+ quicsilver (0.6.0)
5
5
  console
6
6
  localhost (~> 1.6)
7
7
  logger
data/Rakefile CHANGED
@@ -3,24 +3,57 @@ require "bundler/gem_tasks"
3
3
  require "rake/testtask"
4
4
  require "rake/extensiontask"
5
5
  require_relative "ext/quicsilver/msquic_patch"
6
-
7
- Rake::ExtensionTask.new('quicsilver') do |ext|
8
- ext.lib_dir = 'lib/quicsilver'
6
+ require_relative "lib/quicsilver/extension"
7
+
8
+ # Installed under the ABI version that built it, which is the path lib/quicsilver.rb already looks
9
+ # for first. A single shared lib/quicsilver/quicsilver.bundle is owned by whichever Ruby ran compile
10
+ # last, so switching Rubies between checkouts silently leaves a binary the next one cannot load —
11
+ # and `rake compile` considers itself up to date, so it does not rebuild. Version-scoped builds
12
+ # coexist instead, and each Ruby loads its own.
13
+ Rake::ExtensionTask.new("quicsilver") do |ext|
14
+ ext.lib_dir = "lib/quicsilver/#{Quicsilver::Extension::DIR}"
9
15
  end
10
16
 
11
17
  # Keep `rake compile` useful in source checkouts, but let cibuildgem own
12
18
  # extension compilation after the workflow has built and bundled MsQuic.
13
- task :compile => [:build_msquic, :bundle_msquic] unless ENV["CIBUILDGEM"]
19
+ #
20
+ # bundle_msquic rewrites the rpath of the compiled extension, so it has to run
21
+ # *after* compile, not as a prerequisite of it. As a prerequisite on a clean
22
+ # checkout it patched whatever stale bundle was lying around and rake-compiler
23
+ # then overwrote it with an unsigned, rpath-less one.
24
+ unless ENV["CIBUILDGEM"]
25
+ task :compile => :build_msquic
26
+ Rake::Task[:compile].enhance { Rake::Task[:bundle_msquic].invoke }
27
+ end
28
+
29
+ # Where rake-compiler installed the extension for this Ruby's ABI. The flat
30
+ # path is only what a released gem ships; a build left there by a different
31
+ # Ruby gets picked up by the fallback require and fails inside dyld.
32
+ def extension_path
33
+ versioned = "lib/quicsilver/#{Quicsilver::Extension::DIR}/quicsilver.bundle"
34
+ File.exist?(versioned) ? versioned : 'lib/quicsilver/quicsilver.bundle'
35
+ end
14
36
 
15
37
  # Copy MsQuic dylib next to the compiled extension for gem packaging
16
38
  task :bundle_msquic do
17
39
  lib_dir = 'lib/quicsilver'
18
40
  if RUBY_PLATFORM =~ /darwin/
19
41
  dylib = 'vendor/msquic/build/bin/Release/libmsquic.2.dylib'
42
+ bundle = extension_path
20
43
  if File.exist?(dylib)
21
44
  cp dylib, "#{lib_dir}/libmsquic.2.dylib"
22
- # Update rpath so the bundle finds the dylib in the same directory
23
- sh "install_name_tool -add_rpath @loader_path #{lib_dir}/quicsilver.bundle 2>/dev/null || true"
45
+ if File.exist?(bundle)
46
+ # Update rpath so the bundle finds the dylib. @loader_path covers a flat
47
+ # install; @loader_path/.. covers the versioned subdirectory. Both are
48
+ # errors when already present, hence the `|| true`.
49
+ sh "install_name_tool -add_rpath @loader_path #{bundle} 2>/dev/null || true"
50
+ sh "install_name_tool -add_rpath @loader_path/.. #{bundle} 2>/dev/null || true"
51
+ # install_name_tool invalidates the signature, and macOS then SIGKILLs
52
+ # the process with no message at all. Re-sign ad-hoc.
53
+ sh "codesign -f -s - #{bundle} #{lib_dir}/libmsquic.2.dylib"
54
+ else
55
+ warn "bundle_msquic: no compiled extension at #{bundle}; run `rake compile`"
56
+ end
24
57
  end
25
58
  elsif RUBY_PLATFORM =~ /linux/
26
59
  so = 'vendor/msquic/build/bin/Release/libmsquic.so.2'
@@ -39,7 +72,19 @@ task :setup do
39
72
  end
40
73
 
41
74
  task :build_msquic => :setup do
42
- MsquicPatch.apply!(File.expand_path("vendor/msquic", __dir__))
75
+ source = File.expand_path("vendor/msquic", __dir__)
76
+ built_library = Dir[File.join(source, "build/bin/Release/libmsquic.{2.dylib,so.2}")].first
77
+
78
+ # Reconfiguring picks up whatever toolchain is live, which is how a working
79
+ # checkout starts failing to build gtest under a different shell. If the
80
+ # patches are unchanged and the library is there, there is nothing to do.
81
+ if MsquicPatch.built?(source) && built_library
82
+ puts "MsQuic already built for the current patch set (#{built_library}); skipping."
83
+ puts "Force a rebuild with: rm -rf vendor/msquic/build"
84
+ next
85
+ end
86
+
87
+ MsquicPatch.apply!(source)
43
88
  cmake_args = ['-B build', '-DCMAKE_BUILD_TYPE=Release', '-DQUIC_TLS_LIB=quictls', '-DQUIC_LINUX_IOURING_ENABLED=OFF']
44
89
  if RUBY_PLATFORM =~ /darwin/
45
90
  cmake_args << '-DCMAKE_EXE_LINKER_FLAGS="-framework CoreServices"'
@@ -62,6 +62,10 @@ static const QUIC_REGISTRATION_CONFIG RegConfig = { "quicsilver", QUIC_EXECUTION
62
62
 
63
63
  // Connection state tracking
64
64
  typedef struct {
65
+ // Opaque handle Ruby holds. Never the pointer: a freed context's address
66
+ // gets handed straight back by malloc, and a stale handle would then
67
+ // resolve to a live but unrelated connection. Tokens are never reused.
68
+ uint64_t token;
65
69
  int connected;
66
70
  int failed;
67
71
  QUIC_STATUS error_status;
@@ -162,6 +166,12 @@ static pthread_mutex_t StateLock = PTHREAD_MUTEX_INITIALIZER;
162
166
  // block. Inserting one of those between find_stream and the MsQuic call it
163
167
  // guards is a use-after-free.
164
168
  static st_table* LiveStreams;
169
+ // Every ConnectionContext handed to Ruby as an integer handle. A connection
170
+ // is freed on the dispatcher when Ruby has seen CONNECTION_CLOSED, but Ruby
171
+ // can still be holding the handle (Client#disconnect reads the resumption
172
+ // ticket after an idle timeout or a peer-initiated close). Dereferencing the
173
+ // raw pointer then is a use-after-free; look it up here instead.
174
+ static st_table* LiveConnections;
165
175
 
166
176
  typedef enum {
167
177
  RELEASE_NONE = 0,
@@ -472,6 +482,48 @@ forget_connection_streams(HQUIC connection)
472
482
  STATE_UNLOCK();
473
483
  }
474
484
 
485
+ static uint64_t NextConnectionToken = 1;
486
+
487
+ // Mints the handle under the same lock that inserts it, as register_stream
488
+ // does: connections are opened from Ruby threads and accepted on the poll
489
+ // thread, and neither holds the GVL against the other.
490
+ static uint64_t
491
+ register_connection(ConnectionContext* ctx)
492
+ {
493
+ if (ctx == NULL) return 0;
494
+ STATE_LOCK();
495
+ ctx->token = NextConnectionToken++;
496
+ st_insert(LiveConnections, (st_data_t)ctx->token, (st_data_t)ctx);
497
+ STATE_UNLOCK();
498
+ return ctx->token;
499
+ }
500
+
501
+ static void
502
+ unregister_connection(ConnectionContext* ctx)
503
+ {
504
+ if (ctx == NULL || ctx->token == 0) return;
505
+ st_data_t key = (st_data_t)ctx->token;
506
+ STATE_LOCK();
507
+ st_delete(LiveConnections, &key, NULL);
508
+ STATE_UNLOCK();
509
+ }
510
+
511
+ // Resolve a Ruby-held context handle to a context that is still alive.
512
+ // Returns NULL once the dispatcher has released it.
513
+ static ConnectionContext*
514
+ find_connection(VALUE context_handle)
515
+ {
516
+ if (NIL_P(context_handle)) return NULL;
517
+ uint64_t token = NUM2ULL(context_handle);
518
+ if (token == 0) return NULL;
519
+
520
+ st_data_t entry;
521
+ STATE_LOCK();
522
+ int found = st_lookup(LiveConnections, (st_data_t)token, &entry);
523
+ STATE_UNLOCK();
524
+ return found ? (ConnectionContext*)entry : NULL;
525
+ }
526
+
475
527
 
476
528
  // rb_protect wrapper — catches Ruby exceptions so they don't longjmp
477
529
  // through MsQuic callback frames (which would corrupt MsQuic state).
@@ -533,7 +585,7 @@ dispatch_ruby_body(VALUE arg)
533
585
  ConnectionContext* conn_ctx = (ConnectionContext*)a->connection_ctx;
534
586
  VALUE connection_data = rb_ary_new2(3);
535
587
  rb_ary_push(connection_data, ULL2NUM((uintptr_t)a->connection));
536
- rb_ary_push(connection_data, ULL2NUM((uintptr_t)a->connection_ctx));
588
+ rb_ary_push(connection_data, ULL2NUM(conn_ctx ? conn_ctx->token : 0));
537
589
  rb_ary_push(connection_data, conn_ctx && conn_ctx->session_resumed ? Qtrue : Qfalse);
538
590
  VALUE argv[5] = {
539
591
  connection_data,
@@ -877,6 +929,7 @@ perform_release(RubyEvent* ev)
877
929
  case RELEASE_CONNECTION: {
878
930
  ConnectionContext* ctx = (ConnectionContext*)ev->release_ptr;
879
931
  forget_connection_streams(ev->connection);
932
+ unregister_connection(ctx);
880
933
  if (!NIL_P(ctx->client_obj)) rb_gc_unregister_address(&ctx->client_obj);
881
934
  free(ctx->resumption_ticket);
882
935
  free(ctx);
@@ -1278,12 +1331,15 @@ ListenerCallback(HQUIC Listener, void* Context, QUIC_LISTENER_EVENT* Event)
1278
1331
  conn_ctx->dropped_datagrams = 0;
1279
1332
  conn_ctx->resumption_ticket_length = 0;
1280
1333
 
1334
+ register_connection(conn_ctx);
1335
+
1281
1336
  // Set the connection callback
1282
1337
  MsQuic->SetCallbackHandler(Event->NEW_CONNECTION.Connection, (void*)ConnectionCallback, conn_ctx);
1283
1338
 
1284
1339
  // Accept the new connection with the server configuration
1285
1340
  QUIC_STATUS Status = MsQuic->ConnectionSetConfiguration(Event->NEW_CONNECTION.Connection, ctx->Configuration);
1286
1341
  if (QUIC_FAILED(Status)) {
1342
+ unregister_connection(conn_ctx);
1287
1343
  free(conn_ctx);
1288
1344
  return Status;
1289
1345
  }
@@ -1643,11 +1699,14 @@ quicsilver_create_connection(VALUE self, VALUE client_obj)
1643
1699
  rb_gc_register_address(&ctx->client_obj);
1644
1700
  }
1645
1701
 
1702
+ register_connection(ctx);
1703
+
1646
1704
  // Create connection with enhanced callback and context
1647
1705
  if (QUIC_FAILED(Status = MsQuic->ConnectionOpen(Registration, ConnectionCallback, ctx, &Connection))) {
1648
1706
  if (!NIL_P(client_obj)) {
1649
1707
  rb_gc_unregister_address(&ctx->client_obj);
1650
1708
  }
1709
+ unregister_connection(ctx);
1651
1710
  free(ctx);
1652
1711
  rb_raise(rb_eRuntimeError, "ConnectionOpen failed, 0x%x!", Status);
1653
1712
  return Qnil;
@@ -1656,7 +1715,7 @@ quicsilver_create_connection(VALUE self, VALUE client_obj)
1656
1715
  // Return both the connection handle and context as an array
1657
1716
  VALUE result = rb_ary_new2(2);
1658
1717
  rb_ary_push(result, ULL2NUM((uintptr_t)Connection));
1659
- rb_ary_push(result, ULL2NUM((uintptr_t)ctx));
1718
+ rb_ary_push(result, ULL2NUM(ctx->token));
1660
1719
  return result;
1661
1720
  }
1662
1721
 
@@ -1698,7 +1757,14 @@ static void* sleep_nogvl(void* arg) {
1698
1757
  static VALUE
1699
1758
  quicsilver_wait_for_connection(VALUE self, VALUE context_handle, VALUE timeout_ms)
1700
1759
  {
1701
- ConnectionContext* ctx = (ConnectionContext*)(uintptr_t)NUM2ULL(context_handle);
1760
+ ConnectionContext* ctx = find_connection(context_handle);
1761
+ if (ctx == NULL) {
1762
+ VALUE gone = rb_hash_new();
1763
+ rb_hash_aset(gone, rb_str_new_cstr("error"), Qtrue);
1764
+ rb_hash_aset(gone, rb_str_new_cstr("status"), ULL2NUM(0));
1765
+ rb_hash_aset(gone, rb_str_new_cstr("code"), ULL2NUM(0));
1766
+ return gone;
1767
+ }
1702
1768
  int timeout = NUM2INT(timeout_ms);
1703
1769
  int elapsed = 0;
1704
1770
  const int sleep_interval = 1; // 1ms
@@ -1729,9 +1795,15 @@ quicsilver_wait_for_connection(VALUE self, VALUE context_handle, VALUE timeout_m
1729
1795
  static VALUE
1730
1796
  quicsilver_connection_status(VALUE self, VALUE context_handle)
1731
1797
  {
1732
- ConnectionContext* ctx = (ConnectionContext*)(uintptr_t)NUM2ULL(context_handle);
1733
-
1798
+ ConnectionContext* ctx = find_connection(context_handle);
1799
+
1734
1800
  VALUE status = rb_hash_new();
1801
+ if (ctx == NULL) {
1802
+ rb_hash_aset(status, rb_str_new_cstr("connected"), Qfalse);
1803
+ rb_hash_aset(status, rb_str_new_cstr("failed"), Qtrue);
1804
+ return status;
1805
+ }
1806
+
1735
1807
  rb_hash_aset(status, rb_str_new_cstr("connected"), ctx->connected ? Qtrue : Qfalse);
1736
1808
  rb_hash_aset(status, rb_str_new_cstr("failed"), ctx->failed ? Qtrue : Qfalse);
1737
1809
 
@@ -1900,7 +1972,7 @@ quicsilver_transport_counters(VALUE self)
1900
1972
  static VALUE
1901
1973
  quicsilver_get_resumption_ticket(VALUE self, VALUE context_handle_val)
1902
1974
  {
1903
- ConnectionContext* ctx = (ConnectionContext*)(uintptr_t)NUM2ULL(context_handle_val);
1975
+ ConnectionContext* ctx = find_connection(context_handle_val);
1904
1976
  if (ctx == NULL || ctx->resumption_ticket == NULL || ctx->resumption_ticket_length == 0) {
1905
1977
  return Qnil;
1906
1978
  }
@@ -2136,6 +2208,7 @@ quicsilver_close(VALUE self)
2136
2208
  {
2137
2209
  if (MsQuic != NULL) {
2138
2210
  st_clear(LiveStreams);
2211
+ st_clear(LiveConnections);
2139
2212
  if (Registration != NULL) {
2140
2213
  MsQuic->RegistrationClose(Registration);
2141
2214
  Registration = NULL;
@@ -2425,7 +2498,14 @@ quicsilver_open_stream(VALUE self, VALUE connection_data, VALUE unidirectional)
2425
2498
  VALUE context_handle = rb_ary_entry(connection_data, 1);
2426
2499
 
2427
2500
  HQUIC Connection = (HQUIC)(uintptr_t)NUM2ULL(connection_handle);
2428
- ConnectionContext* conn_ctx = (ConnectionContext*)(uintptr_t)NUM2ULL(context_handle);
2501
+ ConnectionContext* conn_ctx = find_connection(context_handle);
2502
+ if (conn_ctx == NULL) {
2503
+ // The context is released once Ruby has seen CONNECTION_CLOSED, so
2504
+ // the HQUIC above is closed too. Opening a stream on it is a
2505
+ // use-after-free, not a recoverable no-op.
2506
+ rb_raise(rb_eIOError, "QUIC connection is closed");
2507
+ return Qnil;
2508
+ }
2429
2509
  HQUIC Stream = NULL;
2430
2510
 
2431
2511
  StreamContext* ctx = (StreamContext*)malloc(sizeof(StreamContext));
@@ -2436,7 +2516,7 @@ quicsilver_open_stream(VALUE self, VALUE connection_data, VALUE unidirectional)
2436
2516
 
2437
2517
  ctx->connection = Connection;
2438
2518
  ctx->connection_ctx = conn_ctx; // Store connection context pointer
2439
- ctx->client_obj = conn_ctx ? conn_ctx->client_obj : Qnil;
2519
+ ctx->client_obj = conn_ctx->client_obj;
2440
2520
  ctx->stream_id = UINT64_MAX; // Sentinel: lazily resolved on first callback
2441
2521
  ctx->started = 1;
2442
2522
  ctx->shutdown = 0;
@@ -2681,6 +2761,7 @@ Init_quicsilver(void)
2681
2761
  {
2682
2762
  mQuicsilver = rb_define_module("Quicsilver");
2683
2763
  LiveStreams = st_init_numtable();
2764
+ LiveConnections = st_init_numtable();
2684
2765
  LiveSends = st_init_numtable();
2685
2766
  LiveSendsRoot = TypedData_Wrap_Struct(rb_cObject, &live_sends_type, &LiveSendsRootData);
2686
2767
  rb_gc_register_mark_object(LiveSendsRoot);
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "rbconfig"
5
+
6
+ module Quicsilver
7
+ # Where a locally built C extension lives, shared by lib/quicsilver.rb and the
8
+ # Rakefile so the build and the require cannot disagree.
9
+ #
10
+ # Keying on the ABI version alone is not enough in a source checkout. Ruby
11
+ # 4.0.7 under nix and 4.0.9 under mise both answer "4.0", but an extension
12
+ # linked against one install's libruby will not load under the other:
13
+ #
14
+ # linked to incompatible /nix/store/.../libruby.4.0.dylib - quicsilver.bundle
15
+ #
16
+ # The install prefix distinguishes them, so builds from different Rubies
17
+ # coexist instead of overwriting each other. Released gems are unaffected:
18
+ # extconf.rb installs flat, and REQUIRE_PATHS still falls back to that.
19
+ module Extension
20
+ ABI = RUBY_VERSION[/\d+\.\d+/]
21
+
22
+ # Short digest of the install prefix. Two Rubies reporting the same version
23
+ # from different prefixes get different directories.
24
+ INSTALL_TAG = Digest::SHA256.hexdigest(RbConfig::CONFIG["prefix"].to_s)[0, 8]
25
+
26
+ # Directory a local `rake compile` installs into, relative to lib/quicsilver.
27
+ DIR = "#{ABI}-#{INSTALL_TAG}"
28
+
29
+ # Tried in order: this exact Ruby install, then any build for this ABI
30
+ # (older checkouts), then the flat path a released gem ships.
31
+ REQUIRE_PATHS = [
32
+ "quicsilver/#{DIR}/quicsilver",
33
+ "quicsilver/#{ABI}/quicsilver",
34
+ "quicsilver/quicsilver"
35
+ ].freeze
36
+ end
37
+ end
Binary file
@@ -66,6 +66,12 @@ module Quicsilver
66
66
  protocol_headers = ::Protocol::HTTP::Headers.new
67
67
  headers.each do |name, value|
68
68
  next if name.start_with?(":")
69
+ # content-length rides on the body, which carries the length read
70
+ # above. Left in the header list it reaches Rack as
71
+ # HTTP_CONTENT_LENGTH, which Rack::Lint rejects outright — every
72
+ # POST to a Lint-wrapped app 500s. Bodyless requests have no body to
73
+ # carry it, and Rack allows CONTENT_LENGTH to be absent there.
74
+ next if name == "content-length"
69
75
  protocol_headers.add(name, value)
70
76
  end
71
77
 
@@ -16,12 +16,13 @@ module Quicsilver
16
16
  end
17
17
 
18
18
  def call(connection, stream, early_data: false)
19
+ started_at = ResponseLog.now
19
20
  request = parse_request(connection, stream, early_data: early_data)
20
21
  return unless request
21
22
 
22
23
  response = @adapter.call(request)
23
24
 
24
- send_response(connection, stream, request, response)
25
+ send_response(connection, stream, request, response, started_at)
25
26
  rescue Server::DrainTimeoutError
26
27
  Quicsilver.logger.debug("Request interrupted by drain: stream #{stream.stream_id}")
27
28
  rescue Protocol::FrameError => e
@@ -34,6 +35,7 @@ module Quicsilver
34
35
  Quicsilver.logger.error("Error handling request: #{e.class} - #{e.message}")
35
36
  Quicsilver.logger.debug(e.backtrace.first(5).join("\n"))
36
37
  connection.send_error(stream, 500, "Internal Server Error") if stream.writable?
38
+ log_response(stream, request, "500 (error)", started_at) if request
37
39
  ensure
38
40
  @request_registry.complete(stream.stream_id, connection.handle)
39
41
  @cancelled_mutex.synchronize { @cancelled_streams.delete([connection.handle, stream.stream_id]) }
@@ -99,9 +101,10 @@ module Quicsilver
99
101
  request
100
102
  end
101
103
 
102
- def send_response(connection, stream, request, response)
104
+ def send_response(connection, stream, request, response, started_at)
103
105
  if cancelled_stream?(stream.stream_id, connection.handle)
104
106
  Quicsilver.logger.debug("Skipping response for cancelled stream #{stream.stream_id}")
107
+ log_response(stream, request, "cancelled", started_at)
105
108
  return
106
109
  end
107
110
 
@@ -137,10 +140,16 @@ module Quicsilver
137
140
  body = response.body || []
138
141
  connection.send_response(stream, response.status, response_headers, body,
139
142
  head_request: request.head?, trailers: trailers)
143
+ log_response(stream, request, response.status, started_at, response_headers)
140
144
  @request_registry.complete(stream.stream_id, connection.handle)
141
145
  connection.remove_stream(stream.stream_id)
142
146
  end
143
147
 
148
+ def log_response(stream, request, outcome, started_at, headers = nil)
149
+ ResponseLog.record(stream_id: stream.stream_id, method: request.method, path: request.path,
150
+ outcome: outcome, started_at: started_at, headers: headers)
151
+ end
152
+
144
153
  def cancelled_stream?(stream_id, connection_handle)
145
154
  @cancelled_mutex.synchronize { @cancelled_streams.include?([connection_handle, stream_id]) }
146
155
  end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Quicsilver
4
+ class Server
5
+ # One DEBUG line per request stream when it finishes, the counterpart of the "HTTP/3 request"
6
+ # line: what happened to the response, as far as the transport can tell.
7
+ #
8
+ # HTTP/3 response stream=916 GET /boards/1 200 length=18322 duration=15.2ms
9
+ #
10
+ # The application's own log says the request completed; this says whether the response then
11
+ # went out, was skipped because the client cancelled, or failed. duration is the time from the
12
+ # handler picking the stream up to the response being handed to MsQuic, not to the last byte
13
+ # being acknowledged. length is the content-length, or "-" for a body of unknown length.
14
+ module ResponseLog
15
+ module_function
16
+
17
+ def now
18
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
19
+ end
20
+
21
+ def record(stream_id:, method:, path:, outcome:, started_at:, headers: nil)
22
+ Quicsilver.logger.debug do
23
+ elapsed = ((now - started_at) * 1000).round(1)
24
+ "HTTP/3 response stream=#{stream_id} #{method} #{path} #{outcome} " \
25
+ "length=#{content_length(headers) || "-"} duration=#{elapsed}ms"
26
+ end
27
+ end
28
+
29
+ def content_length(headers)
30
+ headers&.find { |name, _| name == "content-length" }&.last
31
+ end
32
+ end
33
+ end
34
+ end
@@ -10,6 +10,15 @@ module Quicsilver
10
10
  class Server
11
11
  attr_reader :address, :port, :server_configuration, :running, :connections, :request_registry, :shutting_down, :max_queue_size, :max_connections, :scheduler
12
12
 
13
+ # How long a signal-initiated graceful shutdown may take (default 30s). A process manager with
14
+ # its own grace period (foreman gives 5s) needs this to be shorter, or the shutdown is killed
15
+ # before it finishes.
16
+ attr_accessor :shutdown_timeout
17
+
18
+ # How long open WebTransport sessions get, after being asked to drain, to close themselves
19
+ # before the server closes them.
20
+ WEBTRANSPORT_CLOSE_GRACE = 1.0
21
+
13
22
  DEFAULT_THREAD_POOL_SIZE = 5
14
23
  DEFAULT_QUEUE_MULTIPLIER = 4
15
24
  DEFAULT_MAX_CONNECTIONS = 100
@@ -219,10 +228,11 @@ module Quicsilver
219
228
  raise ServerError, "Server start failed: #{error_msg}"
220
229
  end
221
230
 
222
- def stop
231
+ # drain_timeout bounds the wait for queued requests; 0 stops without waiting.
232
+ def stop(drain_timeout: 5)
223
233
  return unless @running
224
234
 
225
- drain
235
+ drain(timeout: drain_timeout)
226
236
 
227
237
  if @listener_data && @listener_data.listener_handle
228
238
  Quicsilver.stop_listener(@listener_data.listener_handle)
@@ -317,9 +327,19 @@ module Quicsilver
317
327
  # Phase 1: Send GOAWAY - tell clients to stop sending new requests
318
328
  @connections.each_value { |c| c.send_goaway(Protocol::MAX_STREAM_ID) }
319
329
 
330
+ # Phase 1b: Ask open WebTransport sessions to wind down (draft-16 §4.7). A session never
331
+ # finishes the way a request does, so without this the client only learns it is over when
332
+ # the connection is shut down underneath it.
333
+ sessions = @webtransport.sessions.select(&:open?)
334
+ sessions.each(&:drain!)
335
+
320
336
  # Phase 2: Drain in-flight requests
321
337
  drain(timeout: timeout)
322
338
 
339
+ # Phase 2a: Close the sessions that did not close themselves, with a CLOSE capsule rather
340
+ # than the reset a connection shutdown would give them.
341
+ wind_down_webtransport_sessions(sessions, grace: [WEBTRANSPORT_CLOSE_GRACE, timeout * 0.1].min)
342
+
323
343
  # Phase 2b: Send final GOAWAY with actual last processed stream ID (RFC 9114 §5.2)
324
344
  @connections.each_value do |c|
325
345
  c.send_goaway
@@ -343,8 +363,9 @@ module Quicsilver
343
363
  @connections.each_value(&:shutdown)
344
364
  sleep [0.1, timeout * 0.05].min
345
365
 
346
- # Phase 4: Hard stop
347
- stop
366
+ # Phase 4: Hard stop. The queue was drained in phase 2, within this shutdown's timeout;
367
+ # draining again would add stop's own default on top of it.
368
+ stop(drain_timeout: 0)
348
369
  @shutting_down = false
349
370
 
350
371
  Quicsilver.logger.info("Graceful shutdown complete")
@@ -558,7 +579,31 @@ module Quicsilver
558
579
 
559
580
  def setup_signal_handlers
560
581
  %w[INT TERM].each do |signal|
561
- trap(signal) { Thread.new { shutdown } }
582
+ trap(signal) { handle_signal }
583
+ end
584
+ end
585
+
586
+ # The first INT or TERM starts a graceful shutdown. A second one while it runs means "now":
587
+ # process managers send TERM after INT when the grace period they allow is running out, and
588
+ # ignoring it only gets the process killed.
589
+ def handle_signal # :nodoc:
590
+ if @shutting_down
591
+ Thread.new { stop(drain_timeout: 0) }
592
+ else
593
+ Thread.new { shutdown(timeout: @shutdown_timeout || 30) }
594
+ end
595
+ end
596
+
597
+ def wind_down_webtransport_sessions(sessions, grace:)
598
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + grace
599
+ until sessions.all?(&:closed?) || Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
600
+ sleep 0.02
601
+ end
602
+
603
+ sessions.reject(&:closed?).each do |session|
604
+ session.close(code: 0, reason: "server shutting down")
605
+ rescue => e
606
+ Quicsilver.logger.debug("WebTransport close during shutdown failed: #{e.message}")
562
607
  end
563
608
  end
564
609
 
@@ -904,16 +949,21 @@ module Quicsilver
904
949
  end
905
950
 
906
951
  def handle_streaming_request(pending)
952
+ started_at = ResponseLog.now
907
953
  response = @request_handler.adapter.call(pending.request)
908
954
 
909
955
  # Wait for RECEIVE_FIN to provide the stream handle
910
956
  stream_handle = pending.wait_for_handle(timeout: 30)
911
957
  unless stream_handle
912
958
  Quicsilver.logger.error("Timed out waiting for stream handle on stream #{pending.stream_id}")
959
+ log_streaming_response(pending, "timeout (no stream handle)", started_at)
913
960
  return
914
961
  end
915
962
 
916
- return if cancelled_stream?(pending.stream_id, pending.connection.handle)
963
+ if cancelled_stream?(pending.stream_id, pending.connection.handle)
964
+ log_streaming_response(pending, "cancelled", started_at)
965
+ return
966
+ end
917
967
 
918
968
  headers = response.headers
919
969
 
@@ -941,9 +991,11 @@ module Quicsilver
941
991
  pending.connection.apply_stream_priority(stream, pending.priority)
942
992
  pending.connection.send_response(stream, response.status, response_headers, response.body,
943
993
  head_request: pending.request.method == "HEAD", trailers: trailers)
994
+ log_streaming_response(pending, response.status, started_at, response_headers)
944
995
  @request_registry.complete(pending.stream_id, pending.connection.handle)
945
996
  rescue => e
946
997
  Quicsilver.logger.error("Streaming request error: #{e.class} - #{e.message}")
998
+ log_streaming_response(pending, "500 (error)", started_at)
947
999
  if pending.stream_handle
948
1000
  stream = Transport::InboundStream.new(pending.stream_id)
949
1001
  stream.stream_handle = pending.stream_handle
@@ -956,6 +1008,11 @@ module Quicsilver
956
1008
  pending.connection.remove_stream(pending.stream_id)
957
1009
  end
958
1010
 
1011
+ def log_streaming_response(pending, outcome, started_at, headers = nil)
1012
+ ResponseLog.record(stream_id: pending.stream_id, method: pending.request.method,
1013
+ path: pending.request.path, outcome: outcome, started_at: started_at, headers: headers)
1014
+ end
1015
+
959
1016
  # Drain buffered body frames, failing the connection if the peer sends a
960
1017
  # frame type that is not allowed on a request stream.
961
1018
  def drain_pending_frames(pending)
@@ -32,6 +32,11 @@ module Quicsilver
32
32
  manager.sessions
33
33
  end
34
34
 
35
+ # Every session on every connection.
36
+ def sessions
37
+ @mutex.synchronize { @managers.values.flat_map(&:sessions) }
38
+ end
39
+
35
40
  def connection_count
36
41
  @mutex.synchronize { @managers.size }
37
42
  end
@@ -1,3 +1,3 @@
1
1
  module Quicsilver
2
- VERSION = "0.5.0"
2
+ VERSION = "0.6.0"
3
3
  end
data/lib/quicsilver.rb CHANGED
@@ -39,6 +39,7 @@ require_relative "quicsilver/transport/connection_stats"
39
39
  # Server
40
40
  require_relative "quicsilver/server/listener_data"
41
41
  require_relative "quicsilver/server/request_registry"
42
+ require_relative "quicsilver/server/response_log"
42
43
  require_relative "quicsilver/server/request_handler"
43
44
  require_relative "quicsilver/server/rack_adapter"
44
45
  require_relative "quicsilver/server/web_transport_flow_control"
@@ -50,12 +51,34 @@ require_relative "quicsilver/client/request"
50
51
  require_relative "quicsilver/client/connection_pool"
51
52
  require_relative "quicsilver/client/client"
52
53
 
53
- # C extension
54
- begin
55
- ruby_version = /(\d+\.\d+)/.match(RUBY_VERSION)
56
- require "quicsilver/#{ruby_version}/quicsilver"
57
- rescue LoadError
58
- require "quicsilver/quicsilver"
54
+ # C extension. Quicsilver::Extension::REQUIRE_PATHS is ordered most to least specific: a build made
55
+ # by this exact Ruby install, then any build for this ABI, then the flat path a released gem ships.
56
+ #
57
+ # Every candidate can fail for two different reasons — absent, or present but linked against another
58
+ # Ruby — and dyld reports the second from deep inside Bundler with a message that names no fix. Keep
59
+ # trying the rest, then re-raise with every reason listed.
60
+ require_relative "quicsilver/extension"
61
+
62
+ extension_errors = []
63
+ Quicsilver::Extension::REQUIRE_PATHS.each do |candidate|
64
+ begin
65
+ require candidate
66
+ extension_errors.clear
67
+ break
68
+ rescue LoadError => error
69
+ extension_errors << "#{candidate}: #{error.message}"
70
+ end
71
+ end
72
+
73
+ unless extension_errors.empty?
74
+ raise LoadError, <<~MESSAGE.strip
75
+ quicsilver has no usable C extension for Ruby #{RUBY_VERSION} (#{RbConfig::CONFIG["prefix"]}).
76
+
77
+ Build one with: rake compile
78
+
79
+ Tried:
80
+ #{extension_errors.join("\n")}
81
+ MESSAGE
59
82
  end
60
83
 
61
84
  # Rackup handler
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: quicsilver
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.5.0
4
+ version: 0.6.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Haroon Ahmed
@@ -281,7 +281,8 @@ files:
281
281
  - lib/quicsilver/client/connection_pool.rb
282
282
  - lib/quicsilver/client/request.rb
283
283
  - lib/quicsilver/errors.rb
284
- - lib/quicsilver/libmsquic.2.dylib
284
+ - lib/quicsilver/extension.rb
285
+ - lib/quicsilver/libmsquic.so.2
285
286
  - lib/quicsilver/protocol/adapter.rb
286
287
  - lib/quicsilver/protocol/capsule.rb
287
288
  - lib/quicsilver/protocol/connect_stream_decoder.rb
@@ -310,6 +311,7 @@ files:
310
311
  - lib/quicsilver/server/receive_queue.rb
311
312
  - lib/quicsilver/server/request_handler.rb
312
313
  - lib/quicsilver/server/request_registry.rb
314
+ - lib/quicsilver/server/response_log.rb
313
315
  - lib/quicsilver/server/scheduler.rb
314
316
  - lib/quicsilver/server/schedulers/fiber_scheduler.rb
315
317
  - lib/quicsilver/server/schedulers/thread_scheduler.rb
Binary file