// Transaction ownership over a scripted PostgreSQL wire server. Native only // (the interpreter has no sockets); run with LOUISE_NET_TESTS=1. import postgres as pg import std/bytes import std/ffi.{type Resource} import std/list import std/net.{type TcpListener, type TcpStream} import std/option import std/os import std/process.{type Subject, type proc} import std/random.{type random} import std/result import std/string import std/test.{assert, assert_equal} import binary import config.{type Config, Config, Disable} import protocol fn enabled :: -> Bool / { option.is_some (os.env "LOUISE_NET_TESTS") } @derive Eq type Behavior { CommitOk, CommitAmbiguous, CommitFailed, CommitRetry, BeginFailedOnce } type Command { Begin, Commit, Rollback } type Event { Connected(Int), Closed(Int), RolledBack(Int) } type ServerState { ServerState( behavior: Behavior , statements: List<(String, Command)> , in_tx: Bool , begin_failed: Bool ) } @test fn commit_errors_release_the_checkout_without_reusing_the_connection :: -> () / { if enabled () { // COMMIT's success frame arrives, then EOF before Sync's ReadyForQuery: // the transaction may have committed, but the connection is unusable. commit_error_gets_a_fresh_connection CommitAmbiguous None // An ErrorResponse without CommandComplete must not strand it either. commit_error_gets_a_fresh_connection CommitFailed (Some("XX000")) } } fn commit_error_gets_a_fresh_connection :: behavior: Behavior code: Option -> () / { let events = process.subject () let attempts = process.subject () let pool = result.expect (pg.start_pool (test_config (server behavior events)) 1) "pool" match pg.transaction_retry pool 1 fn { process.send attempts () Ok(1) } { Ok(_) -> panic "the scripted COMMIT must fail" , Error(e) -> assert_equal (pg.sqlstate e) code } // Neither disconnects nor XX000 are transient: no retry is allowed. assert_equal (drain_attempts attempts 0) 1 // The old code times out here with the sole connection still checked out. assert_equal (result.expect (pg.transaction pool fn { Ok(42) }) "next transaction") 42 assert_first_connection_replaced events } @test fn transaction_retry_uses_a_fresh_connection_and_reruns_only_on_transient_errors :: -> () / { if enabled () { let events = process.subject () let attempts = process.subject () let pool = result.expect (pg.start_pool (test_config (server CommitRetry events)) 1) "pool" assert_equal ( result.expect ( pg.transaction_retry pool 1 fn { process.send attempts () Ok(42) } ) "serialized transaction" ) 42 assert_equal (drain_attempts attempts 0) 2 assert_first_connection_replaced events } } fn assert_first_connection_replaced :: events: Subject -> () / { let observed = [next_event events, next_event events, next_event events] assert (has_connected observed 2) "the next transaction uses a fresh connection" assert (has_closed observed 1) "the failed-COMMIT connection was closed" } fn drain_attempts :: attempts: Subject<()> count: Int -> Int / { match process.receive attempts 0 { Some(()) -> drain_attempts attempts (count + 1), None -> count } } @test fn other_transaction_outcomes_keep_their_release_semantics :: -> () / { if enabled () { let events = process.subject () let pool = result.expect (pg.start_pool (test_config (server BeginFailedOnce events)) 1) "pool" match pg.transaction pool fn { Ok(()) } { Ok(_) -> panic "the scripted BEGIN must fail" , Error(e) -> assert_equal (pg.sqlstate e) Some("XX100") } // BEGIN failed before opening a transaction, so this connection is safe // to reuse. A normal COMMIT still releases it too. assert_equal (result.expect (pg.transaction pool fn { Ok(42) }) "commit") 42 match pg.transaction pool fn { Error(pg.driver ("body failed")) } { Ok(_) -> panic "the callback must fail" , Error(e) -> assert_equal (pg.error_message e) "body failed" } // The callback error rolled back and released the same live connection. assert_equal (result.expect (pg.transaction pool fn { Ok(43) }) "after rollback") 43 match (next_event events, next_event events) { (Connected(1), RolledBack(1)) -> () , _ -> panic "BEGIN failure and COMMIT must reuse connection 1" } match process.receive events 100 { None -> (), Some(_) -> panic "an unexpected connection event" } } } fn has_connected :: events: List id: Int -> Bool { list.any events fn event { match event { Connected(n) -> n == id, _ -> False } } } fn has_closed :: events: List id: Int -> Bool { list.any events fn event { match event { Closed(n) -> n == id, _ -> False } } } fn next_event :: events: Subject -> Event / { match process.receive events 2000 { Some(event) -> event , None -> panic "timed out waiting for the wire server" } } fn test_config :: port: Int -> Config { Config(..pg.config_defaults (), host: "127.0.0.1", port: port, tls: Disable) } // ---- the scripted wire server --------------------------------------------------- fn server :: first: Behavior events: Subject -> Int / { let listener = result.expect (net.listen "127.0.0.1" 0) "listen" let port = net.port listener let _ = process.spawn fn { accept_next listener first events 1 } port } fn accept_next :: listener: Resource first: Behavior events: Subject id: Int -> () / { match net.accept listener { Error(_) -> () , Ok(conn) -> { let behavior = if id == 1 { first } else { CommitOk } process.send events Connected(id) let _ = process.spawn fn { serve_socket conn id behavior events } accept_next listener first events (id + 1) } } } fn serve_socket :: conn: Resource id: Int behavior: Behavior events: Subject -> () / { match startup_message conn (bytes.empty ()) { None -> net.close conn , Some(_) -> { result.expect ( net.write conn (bytes.concat_all [message 82 (binary.be32 0), ready False]) ) "handshake" serve conn id events ServerState(behavior, [], False, False) } } } fn serve :: conn: Resource id: Int events: Subject state: ServerState -> () / { match exchange_message conn (bytes.empty ()) { None -> close_server_connection conn id events , Some(data) -> if bytes.read_u8 data 0 == 88 // Terminate { close_server_connection conn id events } else { match bytes.read_u8 data 0 { 80 -> // Parse + DescribeStatement + Sync { let (name, _) = string_at data 5 let command = command_in data result.expect ( net.write conn ( bytes.concat_all [ message 49 (bytes.empty ()) , message 116 (binary.be16 0) , message 110 (bytes.empty ()) , ready state.in_tx ] ) ) "prepare" serve conn id events ServerState( ..state , statements: [(name, command), ..state.statements] ) } , 66 -> // Bind + DescribePortal + Execute + Sync { let (_, at) = string_at data 5 let (name, _) = string_at data at let (state, response, close) = execute id events state (statement state.statements name) result.expect (net.write conn response) "execute" if close { close_server_connection conn id events } else { serve conn id events state } } , _ -> panic "unexpected frontend message" } } } } fn execute :: id: Int events: Subject state: ServerState command: Command -> (ServerState, Bytes, Bool) / { match command { Begin -> if state.behavior == BeginFailedOnce && !state.begin_failed { ( ServerState(..state, begin_failed: True) , bytes.concat_all [server_error "XX100" "begin failed", ready False] , False ) } else { ( ServerState(..state, in_tx: True) , bytes.concat_all [command_complete "BEGIN", ready True] , False ) } , Rollback -> { process.send events RolledBack(id) ( ServerState(..state, in_tx: False) , bytes.concat_all [command_complete "ROLLBACK", ready False] , False ) } , Commit -> match state.behavior { CommitAmbiguous -> ( ServerState(..state, in_tx: False) , command_complete "COMMIT" , True // Close before ReadyForQuery: a genuinely ambiguous commit. ) , CommitFailed -> ( ServerState(..state, in_tx: False) , bytes.concat_all [server_error "XX000" "commit failed", ready False] , False ) , CommitRetry -> ( ServerState(..state, in_tx: False) , bytes.concat_all [server_error "40001" "serialization failure", ready False] , False ) , _ -> ( ServerState(..state, in_tx: False) , bytes.concat_all [command_complete "COMMIT", ready False] , False ) } } } fn close_server_connection :: conn: Resource id: Int events: Subject -> () / { process.send events Closed(id) net.close conn } fn statement :: statements: List<(String, Command)> name: String -> Command { match statements { [] -> panic "Execute for an unknown prepared statement" , [(prepared, command), ..] if prepared == name -> command , [_, ..rest] -> statement rest name } } fn string_at :: data: Bytes at: Int -> (String, Int) { let end = string_end data at let text = result.expect (bytes.to_string (bytes.slice data at end)) "statement name" (text, end + 1) } fn string_end :: data: Bytes at: Int -> Int { if bytes.read_u8 data at == 0 { at } else { string_end data (at + 1) } } fn command_in :: data: Bytes -> Command { let text = bytes.to_string_lossy data if string.contains text "begin" { Begin } else if string.contains text "commit" { Commit } else if string.contains text "rollback" { Rollback } else { panic "unexpected SQL in the transaction test" } } fn startup_message :: conn: Resource have: Bytes -> Option / { if bytes.length have >= 4 && bytes.length have >= bytes.read_u32be have 0 { Some(have) } else { match net.read conn 65536 { Ok(more) if bytes.length more > 0 -> startup_message conn (bytes.concat have more) , _ -> None } } } fn exchange_message :: conn: Resource have: Bytes -> Option / { let n = bytes.length have let sync = protocol.encode protocol.Sync if n >= 5 && bytes.slice have (n - 5) n == sync || n == 5 && bytes.length have > 0 && bytes.read_u8 have 0 == 88 { Some(have) } else { match net.read conn 65536 { Ok(more) if bytes.length more > 0 -> exchange_message conn (bytes.concat have more) , _ -> None } } } fn command_complete :: tag: String -> Bytes { message 67 (c_string tag) } fn server_error :: code: String text: String -> Bytes { message 69 ( bytes.concat_all [ bytes.concat (bytes.from_list [83]) (c_string "ERROR") , bytes.concat (bytes.from_list [67]) (c_string code) , bytes.concat (bytes.from_list [77]) (c_string text) , bytes.from_list [0] ] ) } fn ready :: in_tx: Bool -> Bytes { message 90 (bytes.from_list [if in_tx { 84 } else { 73 }]) } fn c_string :: text: String -> Bytes { bytes.concat (bytes.from_string text) (bytes.from_list [0]) } fn message :: tag: Int payload: Bytes -> Bytes { bytes.concat_all [bytes.from_list [tag], binary.be32 (bytes.length payload + 4), payload] }