Module: Quicsilver

Defined in:
lib/quicsilver.rb,
lib/quicsilver/version.rb,
lib/quicsilver/client/client.rb,
lib/quicsilver/server/server.rb,
lib/quicsilver/client/request.rb,
lib/rackup/handler/quicsilver.rb,
lib/quicsilver/protocol/frames.rb,
lib/quicsilver/protocol/adapter.rb,
lib/quicsilver/transport/stream.rb,
lib/quicsilver/protocol/priority.rb,
lib/quicsilver/server/listener_data.rb,
lib/quicsilver/transport/connection.rb,
lib/quicsilver/transport/event_loop.rb,
lib/quicsilver/protocol/frame_parser.rb,
lib/quicsilver/protocol/frame_reader.rb,
lib/quicsilver/protocol/stream_input.rb,
lib/quicsilver/client/connection_pool.rb,
lib/quicsilver/protocol/qpack/decoder.rb,
lib/quicsilver/protocol/qpack/encoder.rb,
lib/quicsilver/protocol/qpack/huffman.rb,
lib/quicsilver/protocol/stream_output.rb,
lib/quicsilver/server/request_handler.rb,
lib/quicsilver/transport/stream_event.rb,
lib/quicsilver/protocol/request_parser.rb,
lib/quicsilver/server/request_registry.rb,
lib/quicsilver/transport/configuration.rb,
lib/quicsilver/protocol/request_encoder.rb,
lib/quicsilver/protocol/response_parser.rb,
lib/quicsilver/transport/inbound_stream.rb,
lib/quicsilver/protocol/response_encoder.rb,
lib/quicsilver/protocol/control_stream_parser.rb,
lib/quicsilver/protocol/qpack/header_block_decoder.rb,
ext/quicsilver/quicsilver.c

Defined Under Namespace

Modules: Protocol, RackHandler, Transport Classes: Client, ConnectionError, Error, Server, ServerConfigurationError, ServerError, ServerIsRunningError, ServerListenerError, TimeoutError

Constant Summary collapse

VERSION =
"0.4.0"

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.loggerObject



63
64
65
# File 'lib/quicsilver.rb', line 63

def logger
  @logger ||= default_logger
end

Class Method Details

.close_configuration(config_handle) ⇒ Object

Close a QUIC configuration



952
953
954
955
956
957
958
959
960
961
962
# File 'ext/quicsilver/quicsilver.c', line 952

static VALUE
quicsilver_close_configuration(VALUE self, VALUE config_handle)
{
    if (MsQuic == NULL) {
        return Qnil;
    }
    
    HQUIC Configuration = (HQUIC)(uintptr_t)NUM2ULL(config_handle);
    MsQuic->ConfigurationClose(Configuration);
    return Qnil;
}

.close_connectionObject



964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
# File 'ext/quicsilver/quicsilver.c', line 964

static VALUE
quicsilver_close(VALUE self)
{
    if (MsQuic != NULL) {
        if (Registration != NULL) {
            MsQuic->RegistrationClose(Registration);
            Registration = NULL;
        }

        if (ExecContext != NULL) {
            MsQuic->ExecutionDelete(1, &ExecContext);
            ExecContext = NULL;
        }

        MsQuicClose(MsQuic);
        MsQuic = NULL;
    }

#if __linux__
    if (WakeFd != -1) {
        close(WakeFd);
        WakeFd = -1;
    }
#endif
    if (EventQ != -1) {
        close(EventQ);
        EventQ = -1;
    }

    return Qnil;
}

.close_connection_handle(connection_data) ⇒ Object

Close a QUIC connection and free context



887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
# File 'ext/quicsilver/quicsilver.c', line 887

static VALUE
quicsilver_close_connection_handle(VALUE self, VALUE connection_data)
{
    if (MsQuic == NULL) {
        return Qnil;
    }

    // Extract connection handle and context from array
    VALUE connection_handle = rb_ary_entry(connection_data, 0);
    VALUE context_handle = rb_ary_entry(connection_data, 1);

    HQUIC Connection = (HQUIC)(uintptr_t)NUM2ULL(connection_handle);
    (void)context_handle; // ctx freed by SHUTDOWN_COMPLETE, not here

    if (Connection != NULL) {
        MsQuic->ConnectionClose(Connection);
    }

    // Don't free ctx here — ConnectionClose is async and SHUTDOWN_COMPLETE
    // will fire on the next event loop poll, which still needs ctx.
    // SHUTDOWN_COMPLETE handles cleanup for both client and server.

    return Qnil;
}

.close_listener(listener_data) ⇒ Object

Close listener



1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
# File 'ext/quicsilver/quicsilver.c', line 1092

static VALUE
quicsilver_close_listener(VALUE self, VALUE listener_data)
{
    if (MsQuic == NULL) {
        return Qnil;
    }
    
    VALUE listener_handle = rb_ary_entry(listener_data, 0);
    VALUE context_handle = rb_ary_entry(listener_data, 1);
    
    HQUIC Listener = (HQUIC)(uintptr_t)NUM2ULL(listener_handle);
    ListenerContext* ctx = (ListenerContext*)(uintptr_t)NUM2ULL(context_handle);
    
    MsQuic->ListenerClose(Listener);
    
    if (ctx != NULL) {
        free(ctx);
    }
    
    return Qnil;
}

.close_server_connection(connection_handle) ⇒ Object

Close a server-side connection handle (context already freed in C callback)



913
914
915
916
917
918
919
920
921
922
923
# File 'ext/quicsilver/quicsilver.c', line 913

static VALUE
quicsilver_close_server_connection(VALUE self, VALUE connection_handle)
{
    if (MsQuic == NULL) return Qnil;

    HQUIC Connection = (HQUIC)(uintptr_t)NUM2ULL(connection_handle);
    if (Connection != NULL) {
        MsQuic->ConnectionClose(Connection);
    }
    return Qnil;
}

.connection_shutdown(connection_handle, error_code, silent) ⇒ Object

silent = false: graceful shutdown with CONNECTION_CLOSE frame



928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
# File 'ext/quicsilver/quicsilver.c', line 928

static VALUE
quicsilver_connection_shutdown(VALUE self, VALUE connection_handle, VALUE error_code, VALUE silent)
{
    if (MsQuic == NULL) {
        rb_raise(rb_eRuntimeError, "MSQUIC not initialized.");
        return Qnil;
    }

    HQUIC Connection = (HQUIC)(uintptr_t)NUM2ULL(connection_handle);
    uint64_t ErrorCode = NUM2ULL(error_code);

    if (Connection != NULL) {
        QUIC_CONNECTION_SHUTDOWN_FLAGS flags = RTEST(silent)
            ? QUIC_CONNECTION_SHUTDOWN_FLAG_SILENT
            : QUIC_CONNECTION_SHUTDOWN_FLAG_NONE;

        MsQuic->ConnectionShutdown(Connection, flags, ErrorCode);
        wake_event_loop();
    }

    return Qtrue;
}

.connection_status(context_handle) ⇒ Object

Check connection status



869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
# File 'ext/quicsilver/quicsilver.c', line 869

static VALUE
quicsilver_connection_status(VALUE self, VALUE context_handle)
{
    ConnectionContext* ctx = (ConnectionContext*)(uintptr_t)NUM2ULL(context_handle);
    
    VALUE status = rb_hash_new();
    rb_hash_aset(status, rb_str_new_cstr("connected"), ctx->connected ? Qtrue : Qfalse);
    rb_hash_aset(status, rb_str_new_cstr("failed"), ctx->failed ? Qtrue : Qfalse);
    
    if (ctx->failed) {
        rb_hash_aset(status, rb_str_new_cstr("error_status"), ULL2NUM(ctx->error_status));
        rb_hash_aset(status, rb_str_new_cstr("error_code"), ULL2NUM(ctx->error_code));
    }
    
    return status;
}

.create_configuration(unsecure) ⇒ Object

Create a QUIC configuration (for client connections)



599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
# File 'ext/quicsilver/quicsilver.c', line 599

static VALUE
quicsilver_create_configuration(VALUE self, VALUE unsecure)
{
    if (MsQuic == NULL) {
        rb_raise(rb_eRuntimeError, "MSQUIC not initialized. Call Quicsilver.open_connection first.");
        return Qnil;
    }
    
    QUIC_STATUS Status;
    HQUIC Configuration = NULL;
    
    // Basic settings
    QUIC_SETTINGS Settings = {0};
    Settings.IdleTimeoutMs = 10000; // 10 second idle timeout to match server
    Settings.IsSet.IdleTimeoutMs = TRUE;
    
    // Simple ALPN for now - Ruby can customize this later
    QUIC_BUFFER Alpn = { sizeof("h3") - 1, (uint8_t*)"h3" };
    
    // Create configuration
    if (QUIC_FAILED(Status = MsQuic->ConfigurationOpen(Registration, &Alpn, 1, &Settings, sizeof(Settings), NULL, &Configuration))) {
        rb_raise(rb_eRuntimeError, "ConfigurationOpen failed, 0x%x!", Status);
        return Qnil;
    }
    
    // Set up credentials
    QUIC_CREDENTIAL_CONFIG CredConfig = {0};
    CredConfig.Type = QUIC_CREDENTIAL_TYPE_NONE;
    CredConfig.Flags = QUIC_CREDENTIAL_FLAG_CLIENT;
    
    if (RTEST(unsecure)) {
        CredConfig.Flags |= QUIC_CREDENTIAL_FLAG_NO_CERTIFICATE_VALIDATION;
    }
    
    if (QUIC_FAILED(Status = MsQuic->ConfigurationLoadCredential(Configuration, &CredConfig))) {
        MsQuic->ConfigurationClose(Configuration);
        rb_raise(rb_eRuntimeError, "ConfigurationLoadCredential failed, 0x%x!", Status);
        return Qnil;
    }

    // Return the configuration handle as a Ruby integer (pointer)
    return ULL2NUM((uintptr_t)Configuration);
}

.create_connection(client_obj) ⇒ Object

Create a QUIC connection with context



768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
# File 'ext/quicsilver/quicsilver.c', line 768

static VALUE
quicsilver_create_connection(VALUE self, VALUE client_obj)
{
    if (MsQuic == NULL) {
        rb_raise(rb_eRuntimeError, "MSQUIC not initialized. Call Quicsilver.open_connection first.");
        return Qnil;
    }

    QUIC_STATUS Status;
    HQUIC Connection = NULL;

    // Allocate and initialize connection context
    ConnectionContext* ctx = (ConnectionContext*)malloc(sizeof(ConnectionContext));
    if (ctx == NULL) {
        rb_raise(rb_eRuntimeError, "Failed to allocate connection context");
        return Qnil;
    }

    ctx->connected = 0;
    ctx->failed = 0;
    ctx->error_status = QUIC_STATUS_SUCCESS;
    ctx->error_code = 0;
    ctx->client_obj = client_obj;  // Store Ruby client object (Qnil for server)

    // Protect from GC if it's a Ruby object
    if (!NIL_P(client_obj)) {
        rb_gc_register_address(&ctx->client_obj);
    }

    // Create connection with enhanced callback and context
    if (QUIC_FAILED(Status = MsQuic->ConnectionOpen(Registration, ConnectionCallback, ctx, &Connection))) {
        if (!NIL_P(client_obj)) {
            rb_gc_unregister_address(&ctx->client_obj);
        }
        free(ctx);
        rb_raise(rb_eRuntimeError, "ConnectionOpen failed, 0x%x!", Status);
        return Qnil;
    }

    // Return both the connection handle and context as an array
    VALUE result = rb_ary_new2(2);
    rb_ary_push(result, ULL2NUM((uintptr_t)Connection));
    rb_ary_push(result, ULL2NUM((uintptr_t)ctx));
    return result;
}

.create_listener(config_handle) ⇒ Object

Create a QUIC listener



997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
# File 'ext/quicsilver/quicsilver.c', line 997

static VALUE
quicsilver_create_listener(VALUE self, VALUE config_handle)
{
    if (MsQuic == NULL) {
        rb_raise(rb_eRuntimeError, "MSQUIC not initialized.");
        return Qnil;
    }
    
    HQUIC Configuration = (HQUIC)(uintptr_t)NUM2ULL(config_handle);
    HQUIC Listener = NULL;
    QUIC_STATUS Status;
    
    // Create listener context
    ListenerContext* ctx = (ListenerContext*)malloc(sizeof(ListenerContext));
    if (ctx == NULL) {
        rb_raise(rb_eRuntimeError, "Failed to allocate listener context");
        return Qnil;
    }
    
    ctx->started = 0;
    ctx->stopped = 0;
    ctx->failed = 0;
    ctx->error_status = QUIC_STATUS_SUCCESS;
    ctx->Configuration = Configuration;
    
    // Create listener
    if (QUIC_FAILED(Status = MsQuic->ListenerOpen(Registration, ListenerCallback, ctx, &Listener))) {
        free(ctx);
        rb_raise(rb_eRuntimeError, "ListenerOpen failed, 0x%x!", Status);
        return Qnil;
    }
    
    // Return listener handle and context
    VALUE result = rb_ary_new2(2);
    rb_ary_push(result, ULL2NUM((uintptr_t)Listener));
    rb_ary_push(result, ULL2NUM((uintptr_t)ctx));
    return result;
}

.create_server_configuration(config_hash) ⇒ Object

Create a QUIC server configuration



644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
# File 'ext/quicsilver/quicsilver.c', line 644

static VALUE
quicsilver_create_server_configuration(VALUE self, VALUE config_hash)
{
    if (MsQuic == NULL) {
        rb_raise(rb_eRuntimeError, "MSQUIC not initialized. Call Quicsilver.open_connection first.");
        return Qnil;
    }
    VALUE cert_file_val = rb_hash_aref(config_hash, ID2SYM(rb_intern("cert_file")));
    VALUE key_file_val = rb_hash_aref(config_hash, ID2SYM(rb_intern("key_file")));
    VALUE idle_timeout_val = rb_hash_aref(config_hash, ID2SYM(rb_intern("idle_timeout_ms")));
    VALUE server_resumption_level_val = rb_hash_aref(config_hash, ID2SYM(rb_intern("server_resumption_level")));
    VALUE max_concurrent_requests_val = rb_hash_aref(config_hash, ID2SYM(rb_intern("max_concurrent_requests")));
    VALUE max_unidirectional_streams_val = rb_hash_aref(config_hash, ID2SYM(rb_intern("max_unidirectional_streams")));
    VALUE alpn_val = rb_hash_aref(config_hash, ID2SYM(rb_intern("alpn")));
    VALUE stream_receive_window_val = rb_hash_aref(config_hash, ID2SYM(rb_intern("stream_receive_window")));
    VALUE stream_receive_buffer_val = rb_hash_aref(config_hash, ID2SYM(rb_intern("stream_receive_buffer")));
    VALUE connection_flow_control_window_val = rb_hash_aref(config_hash, ID2SYM(rb_intern("connection_flow_control_window")));
    VALUE pacing_enabled_val = rb_hash_aref(config_hash, ID2SYM(rb_intern("pacing_enabled")));
    VALUE send_buffering_enabled_val = rb_hash_aref(config_hash, ID2SYM(rb_intern("send_buffering_enabled")));
    VALUE initial_rtt_ms_val = rb_hash_aref(config_hash, ID2SYM(rb_intern("initial_rtt_ms")));
    VALUE initial_window_packets_val = rb_hash_aref(config_hash, ID2SYM(rb_intern("initial_window_packets")));
    VALUE max_ack_delay_ms_val = rb_hash_aref(config_hash, ID2SYM(rb_intern("max_ack_delay_ms")));
    VALUE keep_alive_interval_ms_val = rb_hash_aref(config_hash, ID2SYM(rb_intern("keep_alive_interval_ms")));
    VALUE congestion_control_val = rb_hash_aref(config_hash, ID2SYM(rb_intern("congestion_control_algorithm")));
    VALUE migration_enabled_val = rb_hash_aref(config_hash, ID2SYM(rb_intern("migration_enabled")));
    VALUE disconnect_timeout_ms_val = rb_hash_aref(config_hash, ID2SYM(rb_intern("disconnect_timeout_ms")));
    VALUE handshake_idle_timeout_ms_val = rb_hash_aref(config_hash, ID2SYM(rb_intern("handshake_idle_timeout_ms")));

    QUIC_STATUS Status;
    HQUIC Configuration = NULL;

    const char* cert_path = StringValueCStr(cert_file_val);
    const char* key_path = StringValueCStr(key_file_val);
    uint32_t idle_timeout_ms = NUM2INT(idle_timeout_val);
    uint32_t server_resumption_level = NUM2INT(server_resumption_level_val);
    uint32_t max_concurrent_requests = NUM2INT(max_concurrent_requests_val);
    uint32_t max_unidirectional_streams = NUM2INT(max_unidirectional_streams_val);
    const char* alpn_str = StringValueCStr(alpn_val);
    uint32_t stream_receive_window = NUM2UINT(stream_receive_window_val);
    uint32_t stream_receive_buffer = NUM2UINT(stream_receive_buffer_val);
    uint32_t connection_flow_control_window = NUM2UINT(connection_flow_control_window_val);
    uint8_t pacing_enabled = (uint8_t)NUM2INT(pacing_enabled_val);
    uint8_t send_buffering_enabled = (uint8_t)NUM2INT(send_buffering_enabled_val);
    uint32_t initial_rtt_ms = NUM2UINT(initial_rtt_ms_val);
    uint32_t initial_window_packets = NUM2UINT(initial_window_packets_val);
    uint32_t max_ack_delay_ms = NUM2UINT(max_ack_delay_ms_val);
    uint32_t keep_alive_interval_ms = NUM2UINT(keep_alive_interval_ms_val);
    uint16_t congestion_control = (uint16_t)NUM2INT(congestion_control_val);
    uint8_t migration_enabled = (uint8_t)NUM2INT(migration_enabled_val);
    uint32_t disconnect_timeout_ms = NUM2UINT(disconnect_timeout_ms_val);
    uint64_t handshake_idle_timeout_ms = NUM2ULL(handshake_idle_timeout_ms_val);

    QUIC_SETTINGS Settings = {0};
    Settings.IdleTimeoutMs = idle_timeout_ms;
    Settings.IsSet.IdleTimeoutMs = TRUE;
    Settings.ServerResumptionLevel = server_resumption_level;
    Settings.IsSet.ServerResumptionLevel = TRUE;
    Settings.PeerBidiStreamCount = max_concurrent_requests;
    Settings.IsSet.PeerBidiStreamCount = TRUE;
    Settings.PeerUnidiStreamCount = max_unidirectional_streams;
    Settings.IsSet.PeerUnidiStreamCount = TRUE;

    // Flow control / backpressure settings
    Settings.StreamRecvWindowDefault = stream_receive_window;
    Settings.IsSet.StreamRecvWindowDefault = TRUE;
    Settings.StreamRecvBufferDefault = stream_receive_buffer;
    Settings.IsSet.StreamRecvBufferDefault = TRUE;
    Settings.ConnFlowControlWindow = connection_flow_control_window;
    Settings.IsSet.ConnFlowControlWindow = TRUE;

    // Throughput settings
    Settings.PacingEnabled = pacing_enabled;
    Settings.IsSet.PacingEnabled = TRUE;
    Settings.SendBufferingEnabled = send_buffering_enabled;
    Settings.IsSet.SendBufferingEnabled = TRUE;
    Settings.InitialRttMs = initial_rtt_ms;
    Settings.IsSet.InitialRttMs = TRUE;
    Settings.InitialWindowPackets = initial_window_packets;
    Settings.IsSet.InitialWindowPackets = TRUE;
    Settings.MaxAckDelayMs = max_ack_delay_ms;
    Settings.IsSet.MaxAckDelayMs = TRUE;

    // Connection management
    Settings.KeepAliveIntervalMs = keep_alive_interval_ms;
    Settings.IsSet.KeepAliveIntervalMs = TRUE;
    Settings.CongestionControlAlgorithm = congestion_control;
    Settings.IsSet.CongestionControlAlgorithm = TRUE;
    Settings.MigrationEnabled = migration_enabled;
    Settings.IsSet.MigrationEnabled = TRUE;
    Settings.DisconnectTimeoutMs = disconnect_timeout_ms;
    Settings.IsSet.DisconnectTimeoutMs = TRUE;
    Settings.HandshakeIdleTimeoutMs = handshake_idle_timeout_ms;
    Settings.IsSet.HandshakeIdleTimeoutMs = TRUE;

    QUIC_BUFFER Alpn = { (uint32_t)strlen(alpn_str), (uint8_t*)alpn_str };
    
    // Create configuration
    if (QUIC_FAILED(Status = MsQuic->ConfigurationOpen(Registration, &Alpn, 1, &Settings, sizeof(Settings), NULL, &Configuration))) {
        rb_raise(rb_eRuntimeError, "Server ConfigurationOpen failed, 0x%x!", Status);
        return Qnil;
    }
    
    // Set up server credentials with certificate files
    QUIC_CREDENTIAL_CONFIG CredConfig = {0};
    QUIC_CERTIFICATE_FILE CertFile = {0};
    
    CertFile.CertificateFile = cert_path;
    CertFile.PrivateKeyFile = key_path;
    
    CredConfig.Type = QUIC_CREDENTIAL_TYPE_CERTIFICATE_FILE;
    CredConfig.CertificateFile = &CertFile;
    CredConfig.Flags = QUIC_CREDENTIAL_FLAG_NO_CERTIFICATE_VALIDATION;
    
    if (QUIC_FAILED(Status = MsQuic->ConfigurationLoadCredential(Configuration, &CredConfig))) {
        MsQuic->ConfigurationClose(Configuration);
        rb_raise(rb_eRuntimeError, "Server ConfigurationLoadCredential failed, 0x%x!", Status);
        return Qnil;
    }
    
    // Return the configuration handle as a Ruby integer (pointer)
    return ULL2NUM((uintptr_t)Configuration);
}

.event_loopObject



35
36
37
# File 'lib/quicsilver/transport/event_loop.rb', line 35

def self.event_loop
  @event_loop ||= Transport::EventLoop.new.tap(&:start)
end

.open_connectionObject

Initialize MSQUIC



519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
# File 'ext/quicsilver/quicsilver.c', line 519

static VALUE
quicsilver_open(VALUE self)
{
    QUIC_STATUS Status;
    
    // Check if already initialized
    if (MsQuic != NULL) {
        return Qtrue;
    }
    
    // Open a handle to the library and get the API function table
    if (QUIC_FAILED(Status = MsQuicOpenVersion(2, (const void**)&MsQuic))) {
        rb_raise(rb_eRuntimeError, "MsQuicOpenVersion failed, 0x%x!", Status);
        return Qfalse;
    }

    // Custom execution MUST be set up BEFORE RegistrationOpen.
    // RegistrationOpen triggers MsQuic lazy init (LazyInitComplete=TRUE),
    // after which ExecutionCreate returns QUIC_STATUS_INVALID_STATE.
#if __linux__
    EventQ = epoll_create1(0);
#elif __APPLE__ || __FreeBSD__
    EventQ = kqueue();
#endif
    if (EventQ == -1) {
        MsQuicClose(MsQuic);
        MsQuic = NULL;
        rb_raise(rb_eRuntimeError, "Failed to create event queue for custom execution");
        return Qfalse;
    }

    QUIC_EXECUTION_CONFIG exec_config = { 0, &EventQ };
    Status = MsQuic->ExecutionCreate(
        QUIC_GLOBAL_EXECUTION_CONFIG_FLAG_NONE,
        0,      // PollingIdleTimeoutUs
        1,      // 1 execution context
        &exec_config,
        &ExecContext
    );
    if (QUIC_FAILED(Status)) {
        close(EventQ);
        EventQ = -1;
        MsQuicClose(MsQuic);
        MsQuic = NULL;
        rb_raise(rb_eRuntimeError, "ExecutionCreate failed, 0x%x!", Status);
        return Qfalse;
    }

    // Now open registration — MsQuic lazy init will see the custom execution
    // context and skip spawning its own worker threads.
    if (QUIC_FAILED(Status = MsQuic->RegistrationOpen(&RegConfig, &Registration))) {
        MsQuic->ExecutionDelete(1, &ExecContext);
        ExecContext = NULL;
        close(EventQ);
        EventQ = -1;
        MsQuicClose(MsQuic);
        MsQuic = NULL;
        rb_raise(rb_eRuntimeError, "RegistrationOpen failed, 0x%x!", Status);
        return Qfalse;
    }

    // Register wake source — Ruby threads can unblock the event loop
#if __linux__
    WakeFd = eventfd(0, EFD_NONBLOCK);
    if (WakeFd != -1) {
        struct epoll_event ev = { .events = EPOLLIN, .data.ptr = NULL };
        epoll_ctl(EventQ, EPOLL_CTL_ADD, WakeFd, &ev);
    }
#elif __APPLE__ || __FreeBSD__
    {
        struct kevent kev;
        EV_SET(&kev, WAKE_IDENT, EVFILT_USER, EV_ADD | EV_CLEAR, 0, 0, NULL);
        kevent(EventQ, &kev, 1, NULL, 0, NULL);
    }
#endif

    return Qtrue;
}

.open_stream(connection_data, unidirectional) ⇒ Object

Works uniformly for both client and server



1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
# File 'ext/quicsilver/quicsilver.c', line 1117

static VALUE
quicsilver_open_stream(VALUE self, VALUE connection_data, VALUE unidirectional)
{
    if (MsQuic == NULL) {
        rb_raise(rb_eRuntimeError, "MSQUIC not initialized.");
        return Qnil;
    }

    // Extract connection handle and context from array
    VALUE connection_handle = rb_ary_entry(connection_data, 0);
    VALUE context_handle = rb_ary_entry(connection_data, 1);

    HQUIC Connection = (HQUIC)(uintptr_t)NUM2ULL(connection_handle);
    ConnectionContext* conn_ctx = (ConnectionContext*)(uintptr_t)NUM2ULL(context_handle);
    HQUIC Stream = NULL;

    StreamContext* ctx = (StreamContext*)malloc(sizeof(StreamContext));
    if (ctx == NULL) {
        rb_raise(rb_eRuntimeError, "Failed to allocate stream context");
        return Qnil;
    }

    ctx->connection = Connection;
    ctx->connection_ctx = conn_ctx;  // Store connection context pointer
    ctx->client_obj = conn_ctx ? conn_ctx->client_obj : Qnil;
    ctx->started = 1;
    ctx->shutdown = 0;
    ctx->early_data = 0;
    ctx->error_status = QUIC_STATUS_SUCCESS;

    // Use flag based on parameter
    QUIC_STREAM_OPEN_FLAGS flags = RTEST(unidirectional)
        ? QUIC_STREAM_OPEN_FLAG_UNIDIRECTIONAL
        : QUIC_STREAM_OPEN_FLAG_NONE;

    // Create stream
    QUIC_STATUS Status = MsQuic->StreamOpen(Connection, flags, StreamCallback, ctx, &Stream);
    if (QUIC_FAILED(Status)) {
        free(ctx);
        rb_raise(rb_eRuntimeError, "StreamOpen failed, 0x%x!", Status);
        return Qnil;
    }
    
    // Start the stream
    Status = MsQuic->StreamStart(Stream, QUIC_STREAM_START_FLAG_NONE);
    if (QUIC_FAILED(Status)) {
        // StreamClose fires SHUTDOWN_COMPLETE synchronously which frees ctx
        MsQuic->StreamClose(Stream);
        rb_raise(rb_eRuntimeError, "StreamStart failed, 0x%x!", Status);
        return Qnil;
    }

    wake_event_loop();
    return ULL2NUM((uintptr_t)Stream);
}

.pollObject

Callbacks (StreamCallback, ConnectionCallback) fire HERE on the Ruby thread.



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'ext/quicsilver/quicsilver.c', line 198

static VALUE
quicsilver_poll(VALUE self)
{
    if (ExecContext == NULL) return INT2NUM(0);

    // 1. ExecutionPoll — process MsQuic timers/state, may fire callbacks (has GVL)
    uint32_t wait_ms = MsQuic->ExecutionPoll(ExecContext);

    // 2. Wait for I/O completions (releases GVL)
    struct poll_args args;
    args.eq = EventQ;
    args.max_events = 64;
    // With wake_event_loop(), Ruby threads instantly unblock us when work is
    // queued. Cap at 1s as a safety net for shutdown responsiveness.
    uint32_t actual_wait = (wait_ms == UINT32_MAX) ? 1000 : wait_ms;
    args.timeout_ms = (int)actual_wait;
    args.count = 0;

    rb_thread_call_without_gvl(eventq_wait_nogvl, &args, RUBY_UBF_IO, NULL);

    // 3. Fire completions — MsQuic callbacks run here (has GVL)
    for (int i = 0; i < args.count; i++) {
#if __linux__
        if (args.events[i].data.ptr == NULL) {
            uint64_t val;
            read(WakeFd, &val, sizeof(val));  // drain eventfd
            continue;
        }
#elif __APPLE__ || __FreeBSD__
        if (args.events[i].filter == EVFILT_USER && args.events[i].ident == WAKE_IDENT) continue;
#endif
        QUIC_SQE* sqe = cqe_get_sqe(&args.events[i]);
        if (sqe && sqe->Completion) {
            sqe->Completion(&args.events[i]);
        }
    }

    return INT2NUM(args.count);
}

.send_stream(stream_handle, data, send_fin) ⇒ Object

Send data on a QUIC stream



1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
# File 'ext/quicsilver/quicsilver.c', line 1174

static VALUE
quicsilver_send_stream(VALUE self, VALUE stream_handle, VALUE data, VALUE send_fin)
{
    if (MsQuic == NULL) {
        rb_raise(rb_eRuntimeError, "MSQUIC not initialized.");
        return Qnil;
    }

    HQUIC Stream = (HQUIC)(uintptr_t)NUM2ULL(stream_handle);
    // Use StringValuePtr and RSTRING_LEN for binary data with null bytes
    const char* data_str = RSTRING_PTR(data);
    uint32_t data_len = (uint32_t)RSTRING_LEN(data);
    
    void* SendBufferRaw = malloc(sizeof(QUIC_BUFFER) + data_len);
    if (SendBufferRaw == NULL) {
        rb_raise(rb_eRuntimeError, "SendBuffer allocation failed!");
        return Qnil;
    }

    QUIC_BUFFER* SendBuffer = (QUIC_BUFFER*)SendBufferRaw;
    SendBuffer->Buffer = (uint8_t*)SendBufferRaw + sizeof(QUIC_BUFFER);
    SendBuffer->Length = data_len;

    memcpy(SendBuffer->Buffer, data_str, data_len);

    // Use flag based on parameter (default to FIN for backwards compat)
    QUIC_SEND_FLAGS flags = (NIL_P(send_fin) || RTEST(send_fin))
        ? QUIC_SEND_FLAG_FIN
        : QUIC_SEND_FLAG_NONE;
    
    QUIC_STATUS Status = MsQuic->StreamSend(Stream, SendBuffer, 1, flags, SendBufferRaw);
    if (QUIC_FAILED(Status)) {
        free(SendBufferRaw);
        rb_raise(rb_eRuntimeError, "StreamSend failed, 0x%x!", Status);
        return Qfalse;
    }

    wake_event_loop();
    return Qtrue;
}

.set_stream_priority(stream_handle, priority) ⇒ Object

priority. The actual SetParam happens on the MsQuic event thread in StreamCallback.



1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
# File 'ext/quicsilver/quicsilver.c', line 1237

static VALUE
quicsilver_set_stream_priority(VALUE self, VALUE stream_handle, VALUE priority)
{
    if (MsQuic == NULL) return Qnil;

    HQUIC Stream = (HQUIC)(uintptr_t)NUM2ULL(stream_handle);
    if (Stream == NULL) return Qnil;

    if (PendingPriorityCount >= MAX_PENDING_PRIORITIES) return Qfalse;

    uint16_t Priority = (uint16_t)NUM2UINT(priority);
    PendingPriorities[PendingPriorityCount].stream = Stream;
    PendingPriorities[PendingPriorityCount].priority_plus_one = Priority + 1;
    PendingPriorityCount++;

    wake_event_loop();
    return Qtrue;
}

.start_connection(connection_handle, config_handle, hostname, port) ⇒ Object

Start a QUIC connection



815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
# File 'ext/quicsilver/quicsilver.c', line 815

static VALUE
quicsilver_start_connection(VALUE self, VALUE connection_handle, VALUE config_handle, VALUE hostname, VALUE port)
{
    if (MsQuic == NULL) {
        rb_raise(rb_eRuntimeError, "MSQUIC not initialized.");
        return Qfalse;
    }
    
    HQUIC Connection = (HQUIC)(uintptr_t)NUM2ULL(connection_handle);
    HQUIC Configuration = (HQUIC)(uintptr_t)NUM2ULL(config_handle);
    const char* Target = StringValueCStr(hostname);
    uint16_t Port = (uint16_t)NUM2INT(port);
    
    QUIC_STATUS Status;
    if (QUIC_FAILED(Status = MsQuic->ConnectionStart(Connection, Configuration, QUIC_ADDRESS_FAMILY_UNSPEC, Target, Port))) {
        rb_raise(rb_eRuntimeError, "ConnectionStart failed, 0x%x!", Status);
        return Qfalse;
    }

    wake_event_loop();
    return Qtrue;
}

.start_listener(listener_handle, address, port, alpn) ⇒ Object

Start listener on specific address and port



1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
# File 'ext/quicsilver/quicsilver.c', line 1037

static VALUE
quicsilver_start_listener(VALUE self, VALUE listener_handle, VALUE address, VALUE port, VALUE alpn)
{
    if (MsQuic == NULL) {
        rb_raise(rb_eRuntimeError, "MSQUIC not initialized.");
        return Qfalse;
    }

    HQUIC Listener = (HQUIC)(uintptr_t)NUM2ULL(listener_handle);
    uint16_t Port = (uint16_t)NUM2INT(port);
    const char* alpn_str = StringValueCStr(alpn);

    // Setup address - properly initialize the entire structure
    QUIC_ADDR Address;
    memset(&Address, 0, sizeof(Address));

    // Parse address string to determine family
    const char* addr_str = StringValueCStr(address);
    if (strchr(addr_str, ':') != NULL) {
        // IPv6 address (contains ':')
        QuicAddrSetFamily(&Address, QUIC_ADDRESS_FAMILY_INET6);
    } else {
        // IPv4 address or unspecified - use UNSPEC for dual-stack
        QuicAddrSetFamily(&Address, QUIC_ADDRESS_FAMILY_UNSPEC);
    }
    QuicAddrSetPort(&Address, Port);

    QUIC_STATUS Status;

    QUIC_BUFFER AlpnBuffer = { (uint32_t)strlen(alpn_str), (uint8_t*)alpn_str };

    if (QUIC_FAILED(Status = MsQuic->ListenerStart(Listener, &AlpnBuffer, 1, &Address))) {
        rb_raise(rb_eRuntimeError, "ListenerStart failed, 0x%x!", Status);
        return Qfalse;
    }

    wake_event_loop();
    return Qtrue;
}

.stop_listener(listener_handle) ⇒ Object

Stop listener



1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
# File 'ext/quicsilver/quicsilver.c', line 1078

static VALUE
quicsilver_stop_listener(VALUE self, VALUE listener_handle)
{
    if (MsQuic == NULL) {
        return Qfalse;
    }

    HQUIC Listener = (HQUIC)(uintptr_t)NUM2ULL(listener_handle);
    MsQuic->ListenerStop(Listener);
    wake_event_loop();
    return Qtrue;
}

.stream_reset(stream_handle, error_code) ⇒ Object

Reset a QUIC stream (RESET_STREAM frame - abruptly terminates sending)



1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
# File 'ext/quicsilver/quicsilver.c', line 1216

static VALUE
quicsilver_stream_reset(VALUE self, VALUE stream_handle, VALUE error_code)
{
    if (MsQuic == NULL) {
        rb_raise(rb_eRuntimeError, "MSQUIC not initialized.");
        return Qnil;
    }

    HQUIC Stream = (HQUIC)(uintptr_t)NUM2ULL(stream_handle);
    if (Stream == NULL) return Qnil;

    uint64_t ErrorCode = NUM2ULL(error_code);

    MsQuic->StreamShutdown(Stream, QUIC_STREAM_SHUTDOWN_FLAG_ABORT_SEND, ErrorCode);

    wake_event_loop();
    return Qtrue;
}

.stream_stop_sending(stream_handle, error_code) ⇒ Object

Stop sending on a QUIC stream (STOP_SENDING frame - requests peer to stop)



1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
# File 'ext/quicsilver/quicsilver.c', line 1257

static VALUE
quicsilver_stream_stop_sending(VALUE self, VALUE stream_handle, VALUE error_code)
{
    if (MsQuic == NULL) {
        rb_raise(rb_eRuntimeError, "MSQUIC not initialized.");
        return Qnil;
    }

    HQUIC Stream = (HQUIC)(uintptr_t)NUM2ULL(stream_handle);
    if (Stream == NULL) return Qnil;

    uint64_t ErrorCode = NUM2ULL(error_code);

    MsQuic->StreamShutdown(Stream, QUIC_STREAM_SHUTDOWN_FLAG_ABORT_RECEIVE, ErrorCode);

    wake_event_loop();
    return Qtrue;
}

.wait_for_connection(context_handle, timeout_ms) ⇒ Object

Wait for connection to complete (connected or failed)



839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
# File 'ext/quicsilver/quicsilver.c', line 839

static VALUE
quicsilver_wait_for_connection(VALUE self, VALUE context_handle, VALUE timeout_ms)
{
    ConnectionContext* ctx = (ConnectionContext*)(uintptr_t)NUM2ULL(context_handle);
    int timeout = NUM2INT(timeout_ms);
    int elapsed = 0;
    const int sleep_interval = 10; // 10ms
    
    while (elapsed < timeout && !ctx->connected && !ctx->failed) {
        poll_inline(sleep_interval);  // Drive MsQuic execution while waiting
        elapsed += sleep_interval;
    }
    
    if (ctx->connected) {
        return rb_hash_new();
    } else if (ctx->failed) {
        VALUE error_info = rb_hash_new();
        rb_hash_aset(error_info, rb_str_new_cstr("error"), Qtrue);
        rb_hash_aset(error_info, rb_str_new_cstr("status"), ULL2NUM(ctx->error_status));
        rb_hash_aset(error_info, rb_str_new_cstr("code"), ULL2NUM(ctx->error_code));
        
        return error_info;
    } else {
        VALUE timeout_info = rb_hash_new();
        rb_hash_aset(timeout_info, rb_str_new_cstr("timeout"), Qtrue);
        return timeout_info;
    }
}

.wakeObject



1276
1277
1278
1279
1280
1281
# File 'ext/quicsilver/quicsilver.c', line 1276

static VALUE
quicsilver_wake(VALUE self)
{
    wake_event_loop();
    return Qnil;
}