skaidb 1.5.0 → 1.5.2

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.
data/lib/skaidb.rb CHANGED
@@ -31,11 +31,16 @@ require "socket"
31
31
  require "openssl"
32
32
  require "securerandom"
33
33
  require "bigdecimal"
34
+ begin
35
+ require "fiber" # Fiber.current, before Ruby 3.1 made it core
36
+ rescue LoadError
37
+ nil
38
+ end
34
39
 
35
40
  module Skaidb
36
41
  # The package version — the single source of truth. The gemspec reads it,
37
42
  # and it is what the driver reports to the server in the Hello frame.
38
- VERSION = "1.5.0"
43
+ VERSION = "1.5.2"
39
44
 
40
45
  # Base class for every error raised by this driver.
41
46
  class Error < StandardError; end
@@ -703,6 +708,40 @@ module Skaidb
703
708
  @nonce_mutex.synchronize { @nonce_counter += 1 }
704
709
  end
705
710
 
711
+ @stream_locks = {}.compare_by_identity
712
+
713
+ # Internal: the locks of the connections that have a stream in flight,
714
+ # held here from the stream's first row frame to its end.
715
+ #
716
+ # A stream read by external iteration (e = conn.stream(sql); e.next) runs
717
+ # in the Enumerator's Fiber, inside the connection's lock. Dropped
718
+ # half-read, that Fiber never runs again: it is collected still owning
719
+ # the lock. Ruby (3.3.8 measured) does not survive the lock then being
720
+ # freed AFTER the Fiber that owns it — a segfault or an abort at that
721
+ # collection or at exit, or a spin at exit. A lock that is referenced from
722
+ # here is not freed while the process runs, and at exit the interpreter
723
+ # releases a thread's locks before it frees anything. So the lock of an
724
+ # abandoned stream stays here for good: one small object per stream left
725
+ # that way, in exchange for the process.
726
+ def self.keep_stream_lock(lock)
727
+ @nonce_mutex.synchronize { @stream_locks[lock] = true }
728
+ end
729
+
730
+ # Internal: the stream ended (its ensure ran): its lock is the
731
+ # connection's own again.
732
+ def self.release_stream_lock(lock)
733
+ @nonce_mutex.synchronize { @stream_locks.delete(lock) }
734
+ end
735
+
736
+ @dial_counter = 0
737
+
738
+ # Internal: a process-wide number for each socket a connection dials. It
739
+ # is the upper half of the prepared-statement ids that socket's
740
+ # connection hands out, so an id says which socket issued it.
741
+ def self.next_dial_serial
742
+ @nonce_mutex.synchronize { @dial_counter += 1 }
743
+ end
744
+
706
745
  # A connection to one skaidb node. Modelled on +PG::Connection+.
707
746
  class Connection
708
747
  # @return [Boolean] whether the connection has been closed
@@ -739,35 +778,86 @@ module Skaidb
739
778
  "(tls_client_cert: and tls_client_key:)"
740
779
  end
741
780
  @mutex = Mutex.new
781
+ # Assigned before the first dial reads it: a dial whose first endpoint
782
+ # does not connect closes "the socket" it never had.
783
+ @sock = nil
742
784
  @closed = false
743
- # Transport died; the next statement re-dials (see ensure_live!).
785
+ # Transport died, and its socket is closed (see mark_broken!); the next
786
+ # statement re-dials (see ensure_live!).
744
787
  @broken = false
745
- # A stream is in flight, so the socket sits mid-reply (see stream).
788
+ # A stream is in flight, so the socket sits mid-reply (see stream), and
789
+ # the Fiber it runs in: the transaction helper unwinds a stream its
790
+ # block left open (see abandon_open_stream).
746
791
  @streaming = false
792
+ @stream_fiber = nil
747
793
  # The transaction helper is between its BEGIN and its COMMIT/ROLLBACK,
748
794
  # so a lost socket must not be re-dialled (see ensure_live!).
749
795
  @in_transaction = false
796
+ # A transaction is open on this session: the server accepted a BEGIN,
797
+ # the helper's or one the application sent itself, and no COMMIT or
798
+ # ROLLBACK has ended it (see following). A lost socket is not
799
+ # re-dialled under it either.
800
+ @transaction = false
801
+ # Statements prepared on this socket, SQL => [id, nparams]: the ones
802
+ # the driver prepared for exec_params / exec_batch, least recently used
803
+ # first, and the ones prepare_server handed to the application (see
804
+ # prepare_cached).
750
805
  @prepared = {}
806
+ @held = {}
807
+ # Every id prepare_server has handed out => its SQL, kept across
808
+ # re-dials: exec_prepared prepares the statement again when the id is
809
+ # from a socket this connection has since replaced.
810
+ @handles = {}
811
+ @serial = 0
751
812
  @last_prepare_error = nil
813
+ # The session database, as the USE target every dial re-enters: the one
814
+ # the connection was opened in (+database:+), and the one it is in now
815
+ # — a USE statement the server accepted moves it (see following).
816
+ @dial_use = database.to_s.empty? ? nil : %("#{database.to_s.gsub('"', '""')}")
817
+ @session_use = @dial_use
818
+ # The session's settings, as the statements every dial sends again
819
+ # after the database: the last SET CONSISTENCY and the last SET SCAN
820
+ # BUDGET the server accepted, nil when none is in force (never set, or
821
+ # cleared with DEFAULT). They live on the server's session like the
822
+ # database does: a new connection starts without them.
823
+ @session_consistency = nil
824
+ @session_scan_budget = nil
825
+ # The socket was dialled for a USE statement, without entering the
826
+ # noted database first (see restore_session): until that USE is
827
+ # accepted its session is in the default database, not in the one
828
+ # the notes name, and carries nothing but a USE.
829
+ @unentered = false
752
830
  # Retained so a reconnect repeats the original connect exactly.
753
831
  @dial_args = { host: host, port: port, user: user, password: password,
754
832
  timeout: timeout, database: database, tls: tls, tls_ca: tls_ca,
755
833
  tls_insecure: tls_insecure, tls_server_name: tls_server_name,
756
834
  seeds: seeds, tls_client_cert: tls_client_cert,
757
835
  tls_client_key: tls_client_key, endpoints: endpoints }
758
- dial!
836
+ # A first dial that does not finish — the database refused after the
837
+ # handshake, or the connect cut short — raises out of here, and the
838
+ # caller gets no connection to close. Its socket is closed now: left
839
+ # to the collector, the server would hold the session until then.
840
+ dialled = false
841
+ begin
842
+ dial!
843
+ dialled = true
844
+ ensure
845
+ mark_broken! unless dialled
846
+ end
759
847
  end
760
848
 
761
- # Connect, authenticate and enter the session database. Used for the first
849
+ # Connect, authenticate and restore the session. Used for the first
762
850
  # connect and for every reconnect, so a recovered connection is
763
- # indistinguishable from a fresh one.
764
- def dial!
851
+ # indistinguishable from a fresh one. +enter+ is false for the one dial
852
+ # that does not enter the session database: the re-dial a USE statement
853
+ # causes (see restore_session).
854
+ def dial!(enter: true)
855
+ @serial = Skaidb.next_dial_serial
765
856
  host = @dial_args[:host]
766
857
  port = @dial_args[:port]
767
858
  user = @dial_args[:user]
768
859
  password = @dial_args[:password]
769
860
  timeout = @dial_args[:timeout]
770
- database = @dial_args[:database]
771
861
  tls = @dial_args[:tls]
772
862
  tls_ca = @dial_args[:tls_ca]
773
863
  tls_insecure = @dial_args[:tls_insecure]
@@ -804,6 +894,10 @@ module Skaidb
804
894
  handshake(user.to_s, password.to_s)
805
895
  end
806
896
  @endpoint = "#{h}:#{prt}"
897
+ # A handshake that failed on an endpoint tried before this one
898
+ # marked the connection broken where its read or write failed.
899
+ # That was said of a socket that is gone; this one answered.
900
+ @broken = false
807
901
  last = nil
808
902
  break
809
903
  rescue StandardError => e
@@ -818,13 +912,47 @@ module Skaidb
818
912
  end
819
913
  end
820
914
  if last
821
- @closed = true
915
+ # Not closed: this is also how a re-dial fails while the members are
916
+ # down, and the next statement dials again (see ensure_live!).
822
917
  raise ConnectionError,
823
918
  "no reachable endpoint in #{endpoints.map { |(h, q)| "#{h}:#{q}" }.join(', ')}: #{last.message}"
824
919
  end
825
920
  send_hello
826
- # USE is per-connection session state, so it runs on every dial.
827
- exec(%(USE "#{database.to_s.gsub('"', '""')}")) if database && !database.to_s.empty?
921
+ restore_session(enter)
922
+ end
923
+
924
+ # What a session is besides its socket, put back on a new one before
925
+ # anything else is sent: the database the session was last in, then the
926
+ # consistency override, then the scan budget — each only when one is
927
+ # noted (see following). A new connection starts in the default database
928
+ # with neither setting, so without this the statement that follows a
929
+ # member's restart would read another database's table of the same
930
+ # name, at the request's own consistency, with the scan limit the
931
+ # application had set silently gone.
932
+ #
933
+ # If the server refuses one of them the dial has failed, and its error
934
+ # is the statement's: nothing runs in another database, or under other
935
+ # settings than the application set.
936
+ #
937
+ # With one exception. When the statement that caused the re-dial is
938
+ # itself a USE (+enter_database+ false), the database it leaves is not
939
+ # entered first. That database may be gone — dropped while the
940
+ # connection was down — and every statement then fails at this USE, as
941
+ # it must; a USE of another database is the application's way out, and
942
+ # must not fail at it too. The settings are put back, the USE is sent,
943
+ # and its answer decides the session database as usual (see following).
944
+ def restore_session(enter_database)
945
+ @unentered = !enter_database && !@session_use.nil?
946
+ session_statement("USE #{@session_use}") if @session_use && enter_database
947
+ session_statement(@session_consistency) if @session_consistency
948
+ session_statement(@session_scan_budget) if @session_scan_budget
949
+ end
950
+
951
+ # One statement of a dial's own, on the socket just dialled: sent as it
952
+ # is, with nothing looked at before it and nothing noted after it.
953
+ def session_statement(sql)
954
+ sql_bytes = sql.dup.force_encoding("UTF-8").b
955
+ parse_response(request([1, @consistency].pack("CC") + [sql_bytes.bytesize].pack("V") + sql_bytes))
828
956
  end
829
957
 
830
958
  # Best-effort self-identification: fills the server's +drivers+ table
@@ -901,7 +1029,7 @@ module Skaidb
901
1029
  # and Hashes have no SQL literal form. $N is rewritten to the
902
1030
  # positional ? the server expects.
903
1031
  qsql, order = Skaidb.to_qmark(sql.to_s, params)
904
- prep = prepare_server(qsql)
1032
+ prep = prepare_cached(qsql)
905
1033
  unless prep.nil?
906
1034
  id, nparams = prep
907
1035
  if nparams != order.length
@@ -934,7 +1062,7 @@ module Skaidb
934
1062
 
935
1063
  level = consistency.nil? ? @consistency : Consistency.resolve(consistency)
936
1064
  qsql, = Skaidb.to_qmark(sql.to_s, rows.first)
937
- prep = prepare_server(qsql)
1065
+ prep = prepare_cached(qsql)
938
1066
  raise QueryError, "statement cannot be prepared, so it cannot be batched" if prep.nil?
939
1067
 
940
1068
  id, nparams = prep
@@ -944,7 +1072,7 @@ module Skaidb
944
1072
  end
945
1073
  raise ConnectionError, "connection is closed" if @closed
946
1074
 
947
- req = +([7, level].pack("CC") + [id].pack("V") + [ordered.length].pack("V"))
1075
+ req = +([7, level].pack("CC") + [id & WIRE_ID].pack("V") + [ordered.length].pack("V"))
948
1076
  ordered.each do |r|
949
1077
  req << [r.length].pack("v")
950
1078
  r.each do |v|
@@ -996,7 +1124,26 @@ module Skaidb
996
1124
  # ConnectionError instead of autocommitting on a new session. The same
997
1125
  # goes for a block cut short in the middle of a round trip (an
998
1126
  # Interrupt, a Timeout): the reply is still on its way, so nothing more
999
- # is written to that socket.
1127
+ # is written to that socket. Either way the socket is closed at once,
1128
+ # and the server drops the transaction with it.
1129
+ # - Such an exception can also land between two statements — just after
1130
+ # the opening statement's reply, or with the block done and COMMIT not
1131
+ # yet written — where no round trip is under way. The helper is never
1132
+ # left with a transaction open on a usable connection: unless the
1133
+ # server has answered a ROLLBACK or the COMMIT, the socket is closed,
1134
+ # the server drops the transaction with it, and the next statement
1135
+ # re-dials.
1136
+ # - A stream the block leaves open — an Enumerator from +stream+ advanced
1137
+ # with +next+ or +peek+ and not read to its end — sits in the middle of
1138
+ # its reply, so neither COMMIT nor ROLLBACK can be sent. The socket is
1139
+ # closed instead and the server drops the transaction with it:
1140
+ # ConnectionError is raised, unless the block was itself leaving with
1141
+ # an exception, +break+ or +throw+, which carries on. The stream is
1142
+ # ended with it, so the connection is what it is after any lost
1143
+ # connection (the next statement re-dials), and the Enumerator starts
1144
+ # its statement again if it is advanced again. Read a stream to its
1145
+ # end, or give +stream+ a block, before the transaction's block
1146
+ # returns.
1000
1147
  #
1001
1148
  # The whole transaction runs on this one connection, so no other thread
1002
1149
  # may use it meanwhile. +attempts+ below 1, or no block, is an
@@ -1006,21 +1153,58 @@ module Skaidb
1006
1153
  Skaidb.check_transaction_arguments(attempts, block_given?)
1007
1154
 
1008
1155
  enclosing = @in_transaction
1156
+ # A transaction already noted on this session when the helper is
1157
+ # called (a hand-written BEGIN, an enclosing helper's): the helper's
1158
+ # own BEGIN and COMMIT are noted like any other, and whatever way it
1159
+ # is left, the note is back to this one — a helper that lost its
1160
+ # connection has reported that, and leaves nothing for the
1161
+ # application to end.
1162
+ outer = @transaction
1009
1163
  attempt = 0
1164
+ # Whether the transaction is over, by what the server answered: the
1165
+ # opening statement refused, a ROLLBACK or the COMMIT answered. False
1166
+ # from the moment the opening statement is handed over, and whenever
1167
+ # the helper is left with it still false the session goes (see the
1168
+ # ensure). Most ways out with it false have lost the socket already;
1169
+ # the one that has not is an exception no statement raised — a
1170
+ # Timeout, an Interrupt — that lands between two statements: just
1171
+ # after the opening statement's reply, or with the block done and
1172
+ # COMMIT not yet written. No round trip is under way there, so the
1173
+ # connection is in order, and the server holds a transaction that
1174
+ # nothing will end: left usable, the connection would run its next
1175
+ # statements inside it, uncommitted.
1176
+ over = true
1010
1177
  begin
1011
1178
  attempt += 1
1012
1179
  committing = false
1013
- exec(opening)
1180
+ over = false
1181
+ begin
1182
+ exec(opening)
1183
+ rescue QueryError
1184
+ over = true # refused — or a re-dial's own statement was: nothing is open
1185
+ raise
1186
+ end
1014
1187
  @in_transaction = true
1015
1188
  finished = false
1016
1189
  begin
1017
1190
  value = yield self
1018
1191
  finished = true
1019
1192
  ensure
1020
- rollback_quietly unless finished
1193
+ abandoned = abandon_open_stream
1194
+ over = true if !finished && rollback_quietly
1195
+ end
1196
+ if abandoned
1197
+ raise ConnectionError, "a stream opened inside the transaction was left open, so COMMIT could not " \
1198
+ "be sent: its session was dropped and nothing was committed"
1021
1199
  end
1022
1200
  committing = true
1023
- exec("COMMIT")
1201
+ begin
1202
+ exec("COMMIT")
1203
+ rescue QueryError
1204
+ over = true # a COMMIT the server refuses has ended the transaction
1205
+ raise
1206
+ end
1207
+ over = true
1024
1208
  value
1025
1209
  rescue TransactionConflict
1026
1210
  # Only a refused COMMIT is run again; a conflict the block raised
@@ -1031,6 +1215,12 @@ module Skaidb
1031
1215
  retry
1032
1216
  ensure
1033
1217
  @in_transaction = enclosing
1218
+ # Not known to be over: the socket is closed, and the server drops
1219
+ # the transaction with the session. (Not a ROLLBACK from here: what
1220
+ # is unwinding may be a timeout, and whether the opening statement
1221
+ # was sent at all is not known.)
1222
+ mark_broken! unless over
1223
+ @transaction = outer
1034
1224
  end
1035
1225
  end
1036
1226
 
@@ -1061,7 +1251,10 @@ module Skaidb
1061
1251
  # sending so the connection sits at a request boundary again. When it
1062
1252
  # cannot (dead socket, a frame that makes no sense mid-stream) the
1063
1253
  # connection is marked broken instead, so +usable?+ turns false and Pool
1064
- # drops it rather than handing out a desynced socket.
1254
+ # drops it rather than handing out a desynced socket. So it is when the
1255
+ # stream is cut short while it waits for a frame (Timeout.timeout, an
1256
+ # Interrupt, Thread#kill): nothing is drained, and the exception
1257
+ # propagates at once.
1065
1258
  #
1066
1259
  # Draining is not free and there is no cancel opcode: breaking out of a
1067
1260
  # million-row scan still transfers the rest of it before the connection
@@ -1100,90 +1293,148 @@ module Skaidb
1100
1293
  # Built before anything touches the socket, so a parameter that cannot
1101
1294
  # be bound is refused without a round trip (or a re-dial).
1102
1295
  req = stream_request(sql, params, level)
1103
- ensure_live!
1296
+ # A statement that changes the session (USE, SET CONSISTENCY, SET
1297
+ # SCAN BUDGET, BEGIN, COMMIT, ROLLBACK) is followed here as it is
1298
+ # from exec. One with parameters is none.
1299
+ change = params.empty? ? session_change(sql.to_s) : nil
1300
+ ended = end_lost_transaction(change)
1301
+ return ended if ended
1302
+
1303
+ ensure_live!(entering: !change.nil? && change[0] == :use)
1104
1304
 
1105
1305
  live = false
1106
1306
  summary = nil
1107
1307
  sets = nil
1108
- @mutex.synchronize do
1109
- started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
1110
- begin
1111
- r = Reader.new(round_trip(req))
1112
- rescue ConnectionError
1113
- observe_failure
1114
- raise
1115
- end
1116
- @observer&.note_round_trip(self, Process.clock_gettime(Process::CLOCK_MONOTONIC) - started)
1117
- tag = r.u8
1118
- note_statement(sql) unless tag == 3
1119
- case tag
1120
- when 3
1121
- msg = r.text
1122
- if msg.include?("unknown opcode")
1123
- what = params.empty? ? "streaming" : "parameterised streaming (skaidb >= 0.330)"
1124
- raise QueryError, "server does not support #{what}: #{msg}"
1125
- end
1126
- raise Skaidb.statement_error(msg)
1127
- when 1
1128
- return Result.new(fields: [], rows: [], cmd_tuples: r.u64, kind: :mutation) # not row-producing
1129
- when 2
1130
- return Result.new(fields: [], rows: [], cmd_tuples: 0, kind: :ddl)
1131
- when 8
1132
- # ResultSets: a CALL whose body EMITted is answered with every set
1133
- # in ONE frame, streamed or not — the frame exec receives, decoded
1134
- # by the same code. Nothing follows it, so the rows are yielded
1135
- # below, with the connection free.
1136
- sets = parse_result_sets(r)
1137
- when 5
1138
- # The server has already committed to a row stream, so from here
1139
- # the socket carries frames this call owns — mark it BEFORE
1140
- # parsing the header, not after. `Reader#take` raises on a
1141
- # truncated or absurd column count, and a raise between the
1142
- # commitment and the flag skips the drain entirely: nothing sets
1143
- # `@broken`, `usable?` stays true, and the pool files a socket
1144
- # parked mid-reply back for the next caller, who reads a leftover
1145
- # chunk and gets "unknown response tag 6". That is the very
1146
- # desync the ensure below exists to prevent, reachable through a
1147
- # two-line window.
1148
- live = true
1149
- @streaming = true
1150
- cols = Array.new(r.u32) { r.text }
1151
- summary = Result.new(fields: cols, rows: [], cmd_tuples: 0, kind: :stream)
1308
+ plain = nil # the Result of a statement that answered with no rows to stream
1309
+ # Whether the reply is accounted for: read to its end (a reply of one
1310
+ # frame), or in the hands of the row loop below, whose ensure drains
1311
+ # it or retires the socket. Leaving before that — an Interrupt or a
1312
+ # Timeout that lands between the header frame and the loop — would
1313
+ # leave the rest of a row stream on a connection that looks idle, for
1314
+ # the next statement to read as its reply. So the connection is
1315
+ # marked broken on every way out that has not placed the reply.
1316
+ placed = false
1317
+ following(change) do
1318
+ @mutex.synchronize do
1319
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
1152
1320
  begin
1153
- while live
1154
- fr = Reader.new(read_frame)
1155
- case fr.u8
1156
- when 6
1157
- fr.u32.times do
1158
- ncells = fr.u32
1159
- cells = Array.new(ncells) { Skaidb.decode_value(Reader.new(fr.blob)) }
1160
- yield cols.zip(cells).to_h
1321
+ r = Reader.new(round_trip(req))
1322
+ rescue ConnectionError
1323
+ observe_failure
1324
+ raise
1325
+ end
1326
+ @observer&.note_round_trip(self, Process.clock_gettime(Process::CLOCK_MONOTONIC) - started)
1327
+ tag = reading_reply { r.u8 }
1328
+ placed = tag != 5 # every other reply is this one frame (an unknown one is retired below)
1329
+ note_statement(sql) unless tag == 3
1330
+ case tag
1331
+ when 3
1332
+ msg = reading_reply { r.text }
1333
+ if msg.include?("unknown opcode")
1334
+ what = params.empty? ? "streaming" : "parameterised streaming (skaidb >= 0.330)"
1335
+ raise QueryError, "server does not support #{what}: #{msg}"
1336
+ end
1337
+ raise Skaidb.statement_error(msg)
1338
+ when 1
1339
+ affected = reading_reply { r.u64 }
1340
+ plain = Result.new(fields: [], rows: [], cmd_tuples: affected, kind: :mutation) # not row-producing
1341
+ when 2
1342
+ plain = Result.new(fields: [], rows: [], cmd_tuples: 0, kind: :ddl)
1343
+ when 8
1344
+ # ResultSets: a CALL whose body EMITted is answered with every set
1345
+ # in ONE frame, streamed or not — the frame exec receives, decoded
1346
+ # by the same code. Nothing follows it, so the rows are yielded
1347
+ # below, with the connection free.
1348
+ sets = reading_reply { parse_result_sets(r) }
1349
+ when 5
1350
+ # The server has already committed to a row stream, so from here
1351
+ # the socket carries frames this call owns — mark it BEFORE
1352
+ # parsing the header, not after. `Reader#take` raises on a
1353
+ # truncated or absurd column count, and a raise between the
1354
+ # commitment and the flag skips the drain entirely: nothing sets
1355
+ # `@broken`, `usable?` stays true, and the pool files a socket
1356
+ # parked mid-reply back for the next caller, who reads a leftover
1357
+ # chunk and gets "unknown response tag 6". That is the very
1358
+ # desync the ensure below exists to prevent.
1359
+ live = true
1360
+ reading = false
1361
+ begin
1362
+ # Inside the begin, flags and header alike: from its first line
1363
+ # the ensure below answers for the socket (+placed+), and a
1364
+ # header that cannot be read leaves through it like every other
1365
+ # way out of the stream.
1366
+ placed = true
1367
+ @streaming = true
1368
+ @stream_fiber = Fiber.current
1369
+ Skaidb.keep_stream_lock(@mutex)
1370
+ cols = reading_reply { Array.new(r.u32) { r.text } }
1371
+ summary = Result.new(fields: cols, rows: [], cmd_tuples: 0, kind: :stream)
1372
+ while live
1373
+ reading = true
1374
+ frame = read_frame
1375
+ reading = false
1376
+ fr = Reader.new(frame)
1377
+ case reading_reply { fr.u8 }
1378
+ when 6
1379
+ reading_reply { fr.u32 }.times do
1380
+ cells = reading_reply { Array.new(fr.u32) { Skaidb.decode_value(Reader.new(fr.blob)) } }
1381
+ yield cols.zip(cells).to_h
1382
+ end
1383
+ when 7
1384
+ live = false
1385
+ when 3
1386
+ msg = reading_reply { fr.text }
1387
+ live = false
1388
+ raise Skaidb.statement_error(msg)
1389
+ else
1390
+ # Mid-stream the server sends only RowsChunk, RowsEnd or Error.
1391
+ # Anything else means we no longer know where the reply ends, so
1392
+ # there is no draining back to a request boundary: retire it.
1393
+ live = false
1394
+ mark_broken!
1395
+ raise QueryError, "unexpected frame in stream"
1161
1396
  end
1162
- when 7
1163
- live = false
1164
- when 3
1165
- live = false
1166
- raise Skaidb.statement_error(fr.text)
1167
- else
1168
- # Mid-stream the server sends only RowsChunk, RowsEnd or Error.
1169
- # Anything else means we no longer know where the reply ends, so
1170
- # there is no draining back to a request boundary: retire it.
1171
- live = false
1172
- @broken = true
1173
- raise QueryError, "unexpected frame in stream"
1397
+ end
1398
+ ensure
1399
+ begin
1400
+ if reading
1401
+ # Left while a frame was being read — the transport failed,
1402
+ # or a Timeout, an Interrupt or Thread#kill cut the read
1403
+ # short. The socket is not at a frame boundary (part of that
1404
+ # frame may be consumed), so there is nothing to drain from;
1405
+ # and draining would hold back the exception until the
1406
+ # server had sent the rest of the stream, which a stalled
1407
+ # server never does.
1408
+ mark_broken!
1409
+ elsif live && !@broken
1410
+ # (A frame that could not be read has retired the socket
1411
+ # already: there is no drain after it.)
1412
+ drain_stream!
1413
+ end
1414
+ ensure
1415
+ # Cleared last: until this point the connection is mid-reply,
1416
+ # and a caller who never unwinds here (an abandoned Enumerator
1417
+ # Fiber) leaves it set, so usable? keeps reporting the truth.
1418
+ # In an ensure of its own: a drain that is itself cut short
1419
+ # has retired the socket, and the connection the next
1420
+ # statement re-dials is not in the middle of any stream.
1421
+ @streaming = false
1422
+ @stream_fiber = nil
1423
+ Skaidb.release_stream_lock(@mutex)
1174
1424
  end
1175
1425
  end
1176
- ensure
1177
- drain_stream! if live
1178
- # Cleared last: until this point the connection is mid-reply, and a
1179
- # caller who never unwinds here (an abandoned Enumerator Fiber)
1180
- # leaves it set, so usable? keeps reporting the truth.
1181
- @streaming = false
1426
+ else
1427
+ # Not a reply to a stream request: whether more frames follow it,
1428
+ # and how many, cannot be told.
1429
+ mark_broken!
1430
+ raise QueryError, "unexpected response tag #{tag} to stream request"
1182
1431
  end
1183
- else
1184
- raise QueryError, "unexpected response tag #{tag} to stream request"
1432
+ ensure
1433
+ mark_broken! unless placed
1185
1434
  end
1186
1435
  end
1436
+ return plain if plain
1437
+
1187
1438
  if sets
1188
1439
  # What exec's Result yields (the call's final result, the LAST set),
1189
1440
  # and that same Result back, every set under +result_sets+.
@@ -1194,45 +1445,37 @@ module Skaidb
1194
1445
  end
1195
1446
 
1196
1447
  # Prepare +sql+ on the SERVER, returning [id, nparams], or nil when the
1197
- # server declines the statement kind (DDL, session statements) so the
1198
- # caller falls back to text binding. Cached per connection.
1448
+ # server declines the statement kind (DDL, session statements). The id is
1449
+ # the caller's to keep for exec_prepared: the driver's cache never closes
1450
+ # a statement handed out here (exec_params and exec_batch with the same
1451
+ # SQL use it too). A server whose statement table is full refuses with
1452
+ # QueryError.
1199
1453
  def prepare_server(sql)
1200
- raise ConnectionError, "connection is closed" if @closed
1201
- # Before the cache is read: a re-dial empties it, and a cached id must
1202
- # not send a statement down a socket that is broken.
1203
- ensure_live!
1204
- hit = @prepared[sql]
1205
- return hit if hit
1206
-
1207
- sql_bytes = sql.dup.force_encoding("UTF-8").b
1208
- req = [2].pack("C") + [sql_bytes.bytesize].pack("V") + sql_bytes
1209
- reader = request(req)
1210
- tag = reader.u8
1211
- case tag
1212
- when 4
1213
- id = reader.u32
1214
- nparams = reader.u16
1215
- v = [id, nparams]
1216
- @prepared[sql] = v if @prepared.length < 240
1217
- v
1218
- when 3
1219
- # Refused: DDL/session statements cannot be prepared, and an old
1220
- # server answers "unknown opcode". Kept for the caller's error message.
1221
- @last_prepare_error = reader.text
1222
- nil
1223
- else
1224
- raise QueryError, "unexpected prepare response tag #{tag}"
1225
- end
1226
- end
1227
-
1228
- # Execute a prepared statement with TYPED parameters. The id belongs to
1229
- # the socket that prepared it, so a broken connection is not re-dialled
1230
- # here: prepare_server does that, and hands out a new id.
1454
+ prepare_cached(sql, hold: true)
1455
+ end
1456
+
1457
+ # The server holds at most 256 prepared statements per connection
1458
+ # (PROTOCOL.md §3.3). The driver keeps under it with room to spare.
1459
+ PREPARED_LIMIT = 240
1460
+ private_constant :PREPARED_LIMIT
1461
+
1462
+ # The lower half of an id is the server's statement number, the upper
1463
+ # half the socket that issued it (see Skaidb.next_dial_serial).
1464
+ WIRE_ID = 0xFFFF_FFFF
1465
+ private_constant :WIRE_ID
1466
+
1467
+ # Execute a prepared statement with TYPED parameters, by the id
1468
+ # prepare_server returned. An id is a number on the socket that issued
1469
+ # it; on another socket the same number is unknown, or names a different
1470
+ # statement prepared there since. So an id from a socket this connection
1471
+ # has since replaced is not sent: its statement is prepared again on the
1472
+ # current socket first (a broken connection re-dials for it, as for any
1473
+ # statement). An id another connection issued is refused with QueryError.
1231
1474
  def exec_prepared(id, params, consistency)
1232
1475
  raise ConnectionError, "connection is closed" if @closed
1233
- raise ConnectionError, "connection is broken; prepare the statement again" if @broken
1234
1476
 
1235
- req = +([3, consistency].pack("CC") + [id].pack("V") + [params.length].pack("v"))
1477
+ id = current_id(id)
1478
+ req = +([3, consistency].pack("CC") + [id & WIRE_ID].pack("V") + [params.length].pack("v"))
1236
1479
  params.each do |p|
1237
1480
  v = Skaidb.encode_value(p)
1238
1481
  req << [v.bytesize].pack("V") << v
@@ -1241,7 +1484,6 @@ module Skaidb
1241
1484
  parse_response(reader)
1242
1485
  end
1243
1486
 
1244
- # Close the connection. Idempotent.
1245
1487
  # Yield a stream's events as they arrive, forever.
1246
1488
  #
1247
1489
  # A dependency-free helper over the stream's log: pages it with the
@@ -1282,6 +1524,7 @@ module Skaidb
1282
1524
  !@closed && !@broken && !@streaming
1283
1525
  end
1284
1526
 
1527
+ # Close the connection. Idempotent.
1285
1528
  def close
1286
1529
  return if @closed
1287
1530
 
@@ -1301,6 +1544,68 @@ module Skaidb
1301
1544
  @closed
1302
1545
  end
1303
1546
 
1547
+ # Whether this connection was lost while it sat idle: the peer has closed
1548
+ # it, reset it, or written to it unasked. One peek at the socket, which
1549
+ # does not wait — no round trip.
1550
+ #
1551
+ # A server closes its idle connections when it restarts, fails over or
1552
+ # times them out. The next request then finds a dead socket — and over a
1553
+ # real network WRITING to it succeeds (the reset has not come back yet);
1554
+ # only the read of the reply fails, by which time the statement cannot
1555
+ # be sent again, since for all the driver knows it ran. So the look
1556
+ # comes first: on an idle connection the server sends nothing, and
1557
+ # anything there is to read — end-of-file, a reset, bytes nobody asked
1558
+ # for — means the connection carries no further statement.
1559
+ #
1560
+ # Under TLS the TCP socket is what is looked at, not the decrypted
1561
+ # stream: a peer that is gone ends the TCP connection whether or not it
1562
+ # said a TLS goodbye first. (What the TLS layer has already decrypted
1563
+ # and nobody asked for counts as stray bytes too; see peer_gone?.) A
1564
+ # connection with a stream in flight is not idle — the frames on its
1565
+ # socket are that stream's — and is not looked at; nor is one in the
1566
+ # middle of another thread's round trip, which the look waits out (it
1567
+ # takes the connection's lock).
1568
+ #
1569
+ # Internal: ensure_live! asks before every statement, and Pool before it
1570
+ # hands an idle connection out.
1571
+ def lost_while_idle?
1572
+ return false if @closed || @broken || @streaming || @sock.nil?
1573
+
1574
+ @mutex.synchronize { !@broken && !@streaming && peer_gone? }
1575
+ end
1576
+
1577
+ # Internal, for Pool: the connection comes back from a borrower, and the
1578
+ # next one must find it as a new connection would be — no transaction
1579
+ # open, in the database it was opened in (+database:+, or +default+,
1580
+ # where every session starts), with no scan budget and no consistency
1581
+ # override. What the notes say the borrower changed is put back, in
1582
+ # that order, and only that: a borrower that changed nothing costs no
1583
+ # round trip. The notes are back to the dial's own with it, so a re-dial
1584
+ # under the next borrower restores this state and not the last
1585
+ # borrower's.
1586
+ #
1587
+ # Returns whether the session is in that state. False when it could not
1588
+ # be put there — a statement refused (a server before 0.349 has no SET
1589
+ # CONSISTENCY DEFAULT), the connection gone — and the pool then closes
1590
+ # the connection instead of keeping it. A connection found lost is not
1591
+ # dialled again for this: there is nothing on a new one to put back.
1592
+ def reset_session
1593
+ return false unless usable?
1594
+ return true unless @transaction || @session_use != @dial_use || @session_scan_budget || @session_consistency
1595
+ return false if lost_while_idle?
1596
+
1597
+ exec("ROLLBACK") if @transaction
1598
+ if @session_use != @dial_use
1599
+ exec("USE #{@dial_use || 'default'}")
1600
+ @session_use = @dial_use
1601
+ end
1602
+ exec("SET SCAN BUDGET DEFAULT") if @session_scan_budget
1603
+ exec("SET CONSISTENCY DEFAULT") if @session_consistency
1604
+ usable?
1605
+ rescue Error
1606
+ false
1607
+ end
1608
+
1304
1609
  private
1305
1610
 
1306
1611
  # -- framing --
@@ -1309,39 +1614,109 @@ module Skaidb
1309
1614
  payload = payload.b
1310
1615
  @sock.write([payload.bytesize].pack("N") + payload) # length is BE
1311
1616
  rescue StandardError => e
1312
- @broken = true
1617
+ mark_broken!
1313
1618
  raise ConnectionError, "write failed: #{e.message}"
1314
1619
  end
1315
1620
 
1316
- # Re-dial if the transport died since the last statement, BEFORE anything
1317
- # is prepared on it.
1621
+ # This socket carries no further statement: its transport failed, or it
1622
+ # was left in the middle of a reply. usable? turns false and the next
1623
+ # statement re-dials — and the socket is closed HERE, not when that
1624
+ # statement comes. The server keeps a session for as long as its socket
1625
+ # is open, and with it the transaction left open on it; a connection that
1626
+ # timed out inside a transaction and is not used again would hold that
1627
+ # transaction until it is closed or collected. The TCP socket is closed
1628
+ # as it is, with no TLS goodbye written first: nothing more is written
1629
+ # to a socket in this state.
1630
+ def mark_broken!
1631
+ @broken = true
1632
+ @sock&.to_io&.close
1633
+ rescue StandardError
1634
+ nil
1635
+ end
1636
+
1637
+ # The look of lost_while_idle? (the caller holds @mutex): whether the
1638
+ # socket has anything to read, asked with one peek that does not wait.
1639
+ # Nothing there is a socket that is alive; end-of-file or data is one
1640
+ # that is not, and so is an error from the call (a reset; bytes Ruby
1641
+ # had already read ahead of a reply).
1642
+ #
1643
+ # The peek is not preceded by IO.select with a zero timeout: when the
1644
+ # calling thread has an interrupt pending — another thread waiting for
1645
+ # the interpreter lock is enough — Ruby returns from that select
1646
+ # without having polled, and a socket at end-of-file is reported as
1647
+ # having nothing to read (seen on Ruby 3.2, in the test suite).
1648
+ #
1649
+ # Under TLS there is one more place for bytes nobody asked for: sent in
1650
+ # the same TLS record as a reply, they were decrypted with it and wait
1651
+ # in the TLS layer's buffer, where the TCP socket shows nothing. So
1652
+ # when the TCP socket is quiet the TLS layer is asked too, without
1653
+ # waiting: data or end-of-file there is a connection that is gone as
1654
+ # well.
1655
+ def peer_gone?
1656
+ io = @sock.to_io # under TLS, the TCP socket beneath it
1657
+ return true unless io.recv_nonblock(1, Socket::MSG_PEEK, exception: false) == :wait_readable
1658
+ return false if io.equal?(@sock)
1659
+
1660
+ !%i[wait_readable wait_writable].include?(@sock.read_nonblock(1, exception: false))
1661
+ rescue StandardError
1662
+ true
1663
+ end
1664
+
1665
+ # Re-dial if the transport died since the last statement — or while the
1666
+ # connection sat idle, which is looked for here (lost_while_idle?) —
1667
+ # BEFORE anything is written or prepared on it. +entering+ says the
1668
+ # statement about to be sent is a USE: a re-dial for it does not enter
1669
+ # the database the session is leaving (see restore_session).
1318
1670
  #
1319
1671
  # The prepared-statement cache MUST be cleared: an id is only valid on the
1320
1672
  # connection that created it, so carrying one across a reconnect would run
1321
1673
  # a different statement (or fail obscurely).
1322
- def ensure_live!
1674
+ def ensure_live!(entering: false)
1323
1675
  raise ConnectionError, "connection is closed" if @closed
1676
+ # Found dead before the request is written: exactly as after a failed
1677
+ # write, except that nothing was sent — so nothing is reported, and
1678
+ # the statement goes out on the connection dialled below.
1679
+ mark_broken! if lost_while_idle?
1680
+ # A socket dialled for a USE that then never reached it (the call was
1681
+ # cut short in between) is in the default database: only a USE may
1682
+ # use it, and anything else dials again.
1683
+ mark_broken! if @unentered && !entering
1324
1684
  return unless @broken
1325
1685
  # A transaction lives on the socket that carried its BEGIN. Re-dialling
1326
1686
  # inside the helper would run the rest of the block, and the COMMIT, on
1327
1687
  # a new session with no transaction open: each statement autocommitted.
1328
1688
  raise ConnectionError, "connection lost inside a transaction; not re-dialling until it ends" if @in_transaction
1689
+ # The same for a transaction the application opened itself: its
1690
+ # statements, and its COMMIT, would each autocommit on a new session.
1691
+ # It ends the transaction with ROLLBACK or COMMIT, neither of which is
1692
+ # sent (see end_lost_transaction); then the connection re-dials.
1693
+ if @transaction
1694
+ raise ConnectionError, "connection lost inside a transaction: nothing of it was committed, and no " \
1695
+ "statement is sent until ROLLBACK (or COMMIT, which fails) ends it"
1696
+ end
1329
1697
 
1330
1698
  @prepared.clear
1699
+ @held.clear
1331
1700
  begin
1332
1701
  @sock&.close
1333
1702
  rescue StandardError
1334
1703
  nil
1335
1704
  end
1336
1705
  @sock = nil
1337
- # Cleared BEFORE dialling: dial! issues USE, which runs a statement and
1338
- # would otherwise re-enter this method forever.
1706
+ # Cleared before dialling: it was said of the socket that is gone.
1707
+ # (An endpoint that fails its handshake sets it again; the one that
1708
+ # answers clears it, see dial!.)
1339
1709
  @broken = false
1710
+ dialled = false
1340
1711
  begin
1341
- dial!
1342
- rescue StandardError => e
1343
- @broken = true # still down; the next statement retries
1344
- raise e
1712
+ dial!(enter: !entering)
1713
+ dialled = true
1714
+ ensure
1715
+ # Still down, so the next statement retries — or the dial was cut
1716
+ # short (an Interrupt, a Timeout) with the handshake's or Hello's
1717
+ # reply outstanding on the new socket, which the next statement
1718
+ # would read as its own.
1719
+ mark_broken! unless dialled
1345
1720
  end
1346
1721
  end
1347
1722
 
@@ -1352,38 +1727,43 @@ module Skaidb
1352
1727
  end
1353
1728
 
1354
1729
  # Read out the frames left over from a stream the caller walked away from,
1355
- # so the connection is positioned at a request boundary again. Deliberately
1730
+ # so the connection is positioned at a request boundary again.
1731
+ #
1356
1732
  # Runs from an ensure, where an exception would replace whatever the
1357
1733
  # caller's block was already unwinding with — so an ordinary failure
1358
1734
  # marks the connection broken rather than raising. usable? then fails
1359
1735
  # and ensure_live! re-dials before the next statement.
1360
1736
  #
1361
- # Not exception-PROOF, and the difference matters: the rescue below
1362
- # catches StandardError, so Interrupt, SignalException and
1363
- # NoMemoryError still escape. They also skip the `@streaming = false`
1364
- # in the caller's ensure, which leaves the connection permanently
1365
- # unusable — safe, but only because "unusable" is the failing
1366
- # direction. Rescuing Exception here would hide a Ctrl-C, which is a
1367
- # worse trade than retiring one connection.
1737
+ # An Interrupt, a Timeout or Thread#kill is not an ordinary failure: the
1738
+ # rescue below catches StandardError only, so those still leave through
1739
+ # here (rescuing Exception would hide a Ctrl-C). They leave the rest of
1740
+ # the stream on the socket, so the ensure marks the connection broken on
1741
+ # EVERY exit that did not reach the end of the stream. Left unmarked,
1742
+ # the next statements on the connection read the leftover chunks as
1743
+ # their replies, and after those the replies of the statements before
1744
+ # them.
1368
1745
  #
1369
- # There is also no read DEADLINE. A peer that is alive but silent
1370
- # blocks the drain forever, holding @mutex — the same as every other
1371
- # read in this driver, and `close` deliberately does not take @mutex
1372
- # so another thread can break it. A genuinely dead socket (EOF, RST)
1373
- # exits correctly.
1746
+ # There is no read DEADLINE. A peer that is alive but silent blocks the
1747
+ # drain forever, holding @mutex — the same as every other read in this
1748
+ # driver, and `close` deliberately does not take @mutex so another
1749
+ # thread can break it. A genuinely dead socket (EOF, RST) exits
1750
+ # correctly.
1374
1751
  def drain_stream!
1752
+ drained = false
1375
1753
  loop do
1376
1754
  tag = Reader.new(read_frame).u8
1377
- break if tag == 7 || tag == 3 # RowsEnd, or an Error that ended the stream
1378
- next if tag == 6 # RowsChunk: more to come
1755
+ next if tag == 6 # RowsChunk: more to come
1379
1756
 
1380
- @broken = true
1757
+ # RowsEnd, or an Error that ended the stream: at a request boundary.
1758
+ # Anything else: where the reply ends is no longer known.
1759
+ drained = [7, 3].include?(tag)
1381
1760
  break
1382
1761
  end
1383
1762
  rescue StandardError
1384
- # An I/O failure already set @broken in read_exact; set it for the rest
1385
- # (a truncated frame, say) so the socket is never reused mid-reply.
1386
- @broken = true
1763
+ # An I/O failure, or a frame too short to carry a tag: not drained.
1764
+ nil
1765
+ ensure
1766
+ mark_broken! unless drained
1387
1767
  end
1388
1768
 
1389
1769
  def read_exact(n)
@@ -1394,11 +1774,11 @@ module Skaidb
1394
1774
  chunk = begin
1395
1775
  @sock.read(n - buf.bytesize)
1396
1776
  rescue StandardError => e
1397
- @broken = true
1777
+ mark_broken!
1398
1778
  raise ConnectionError, "read failed: #{e.message}"
1399
1779
  end
1400
1780
  if chunk.nil? || chunk.empty?
1401
- @broken = true
1781
+ mark_broken!
1402
1782
  raise ConnectionError, "connection closed by server"
1403
1783
  end
1404
1784
 
@@ -1454,6 +1834,84 @@ module Skaidb
1454
1834
 
1455
1835
  # -- query --
1456
1836
 
1837
+ # prepare_server's work, and how exec_params and exec_batch prepare: [id,
1838
+ # nparams] for +sql+, from this socket's statements or prepared now; nil
1839
+ # when the server declines the statement kind, so the caller falls back
1840
+ # to text binding.
1841
+ #
1842
+ # Statements prepared here on the driver's own account are a cache, least
1843
+ # recently used first. Before a new statement would take the count to
1844
+ # PREPARED_LIMIT the oldest of them is closed on the server (OP_CLOSE),
1845
+ # so the server's table (256 per connection) never fills however many
1846
+ # distinct statements a connection runs. Statements handed to the
1847
+ # application (+hold+) are never closed: it still holds their ids.
1848
+ #
1849
+ # A server that refuses because its table is full all the same — the
1850
+ # application holds that many — is a statement error, QueryError. It is
1851
+ # NOT answered with the text fallback: that would send the values as
1852
+ # literals, a Time as a number and bytes as a hex string, without a word.
1853
+ def prepare_cached(sql, hold: false)
1854
+ raise ConnectionError, "connection is closed" if @closed
1855
+ # Before the cache is read: a re-dial empties it, and a cached id must
1856
+ # not send a statement down a socket that is broken.
1857
+ ensure_live!
1858
+ hit = @held[sql]
1859
+ return hit if hit
1860
+
1861
+ if (hit = @prepared.delete(sql))
1862
+ (hold ? @held : @prepared)[sql] = hit # held from now on, or most recently used
1863
+ @handles[hit[0]] = sql if hold
1864
+ return hit
1865
+ end
1866
+
1867
+ close_prepared(@prepared.shift[1][0]) while @held.length + @prepared.length >= PREPARED_LIMIT && !@prepared.empty?
1868
+ sql_bytes = sql.dup.force_encoding("UTF-8").b
1869
+ req = [2].pack("C") + [sql_bytes.bytesize].pack("V") + sql_bytes
1870
+ reader = request(req)
1871
+ tag = reading_reply { reader.u8 }
1872
+ case tag
1873
+ when 4
1874
+ number, nparams = reading_reply { [reader.u32, reader.u16] }
1875
+ id = (@serial << 32) | number
1876
+ @handles[id] = sql if hold
1877
+ (hold ? @held : @prepared)[sql] = [id, nparams]
1878
+ when 3
1879
+ msg = reading_reply { reader.text }
1880
+ raise Skaidb.statement_error(msg) if msg.start_with?("too many prepared statements")
1881
+
1882
+ # Refused: DDL/session statements cannot be prepared, and an old
1883
+ # server answers "unknown opcode". Kept for the caller's error message.
1884
+ @last_prepare_error = msg
1885
+ nil
1886
+ else
1887
+ mark_broken! # not a reply to a prepare: what follows it cannot be placed
1888
+ raise QueryError, "unexpected prepare response tag #{tag}"
1889
+ end
1890
+ end
1891
+
1892
+ # Free a prepared statement's slot on the server (OP_CLOSE). What it
1893
+ # answers does not matter: the id is forgotten here either way.
1894
+ def close_prepared(id)
1895
+ request([4].pack("C") + [id & WIRE_ID].pack("V"))
1896
+ nil
1897
+ end
1898
+
1899
+ # exec_prepared's id as the current socket knows it: the id itself when
1900
+ # this socket issued it; otherwise the id of the same statement prepared
1901
+ # here again — never a number another socket gave out.
1902
+ def current_id(id)
1903
+ ensure_live!
1904
+ return id if id >> 32 == @serial
1905
+
1906
+ sql = @handles[id]
1907
+ raise QueryError, "prepared statement id #{id} was not issued by this connection" if sql.nil?
1908
+
1909
+ entry = prepare_cached(sql, hold: true)
1910
+ raise QueryError, "the statement could not be prepared again: #{@last_prepare_error}" if entry.nil?
1911
+
1912
+ entry[0]
1913
+ end
1914
+
1457
1915
  # The transaction helper's clean-up after a block that did not run to its
1458
1916
  # end. It runs while something else is unwinding, so it never raises: a
1459
1917
  # ROLLBACK the server refuses (one before 0.347 answers "no transaction in
@@ -1461,22 +1919,222 @@ module Skaidb
1461
1919
  # replace what the block left with. Not sent on a connection that is not
1462
1920
  # usable — its socket died, or was left in the middle of a reply: the
1463
1921
  # transaction goes with the socket.
1922
+ #
1923
+ # Returns whether the server answered it: the transaction is over then,
1924
+ # also when the answer was an error.
1464
1925
  def rollback_quietly
1465
- exec("ROLLBACK") if usable?
1926
+ return false unless usable?
1927
+
1928
+ exec("ROLLBACK")
1929
+ true
1930
+ rescue QueryError
1931
+ true
1466
1932
  rescue StandardError
1467
- nil
1933
+ false
1934
+ end
1935
+
1936
+ # Internal: raised into the Fiber of a stream the transaction helper's
1937
+ # block left open, to unwind it. Not a StandardError, so nothing between
1938
+ # the stream and the top of that Fiber takes it for an ordinary failure.
1939
+ class StreamAbandoned < Exception; end # rubocop:disable Lint/InheritException
1940
+ private_constant :StreamAbandoned
1941
+
1942
+ # The transaction helper's check once its block is done: is a stream the
1943
+ # block opened still in flight? That is an Enumerator from +stream+
1944
+ # advanced with +next+ and not read to its end: its Fiber holds the
1945
+ # socket in the middle of the reply (and the connection's lock), so
1946
+ # neither COMMIT nor ROLLBACK can be sent, and the transaction would stay
1947
+ # open on a live session — where a statement sent after the stream was
1948
+ # read to its end would run inside it, uncommitted.
1949
+ #
1950
+ # So the session goes: the connection is marked broken, which closes the
1951
+ # socket, and the server drops the transaction with it. Then the stream
1952
+ # is unwound — an exception raised into its Fiber runs the stream's
1953
+ # ensure, which finds nothing to drain, clears the busy flag and releases
1954
+ # the lock — so the connection is what it is after any lost connection:
1955
+ # the next statement re-dials. The Fiber must not be left where it is:
1956
+ # it owns the lock, and an Enumerator dropped in that state takes the
1957
+ # lock's owner with it when it is collected (which Ruby 3.3 does not
1958
+ # survive).
1959
+ #
1960
+ # A stream whose Fiber cannot be reached (it runs in another thread)
1961
+ # leaves the connection closed for good instead: a re-dial would hand
1962
+ # that Fiber, when it is resumed, a new socket to read its old reply
1963
+ # from. Returns whether a stream was in flight.
1964
+ def abandon_open_stream
1965
+ return false unless @streaming
1966
+
1967
+ fiber = @stream_fiber
1968
+ mark_broken!
1969
+ begin
1970
+ fiber.raise(StreamAbandoned) if fiber&.alive? && !fiber.equal?(Fiber.current)
1971
+ rescue StreamAbandoned, StandardError
1972
+ nil # unwound; or not reachable (FiberError), which the next line sees
1973
+ end
1974
+ close if @streaming
1975
+ true
1468
1976
  end
1469
1977
 
1470
1978
  def run(sql, consistency)
1471
1979
  raise ConnectionError, "connection is closed" if @closed
1472
- ensure_live!
1980
+ change = session_change(sql)
1981
+ ended = end_lost_transaction(change)
1982
+ return ended if ended
1473
1983
 
1984
+ ensure_live!(entering: !change.nil? && change[0] == :use)
1474
1985
  sql_bytes = sql.dup.force_encoding("UTF-8").b
1475
1986
  req = [1, consistency].pack("CC") + [sql_bytes.bytesize].pack("V") + sql_bytes
1476
- reader = request(req)
1477
- res = parse_response(reader)
1478
- note_statement(sql)
1479
- res
1987
+ following(change) do
1988
+ res = parse_response(request(req))
1989
+ note_statement(sql)
1990
+ res
1991
+ end
1992
+ end
1993
+
1994
+ # +USE [DATABASE] <name>+ with an optional +;+ — the name bare, or in
1995
+ # double quotes with "" for a quote inside.
1996
+ USE_STATEMENT = /\A\s*USE\s+(?:DATABASE\s+)?("(?:[^"]|"")+"|[[:alpha:]_][[:alnum:]_]*)\s*;?\s*\z/i.freeze
1997
+ # A statement whose first word is BEGIN: +BEGIN+, +BEGIN TRANSACTION+,
1998
+ # +BEGIN ATOMIC …+.
1999
+ BEGIN_STATEMENT = /\A\s*BEGIN(?![[:alnum:]_])/i.freeze
2000
+ # Exactly +COMMIT [TRANSACTION]+ or +ROLLBACK [TRANSACTION]+, with an
2001
+ # optional +;+.
2002
+ END_STATEMENT = /\A\s*(COMMIT|ROLLBACK)(?:\s+TRANSACTION)?\s*;?\s*\z/i.freeze
2003
+ # One statement whose first words are +SET CONSISTENCY+, or +SET SCAN
2004
+ # BUDGET+, with an optional +;+ (a second +;+ would be a second
2005
+ # statement). What follows the keywords is the server's to read — but
2006
+ # for +DEFAULT+, which clears the setting.
2007
+ SET_STATEMENT = /\A\s*(SET\s+(CONSISTENCY|SCAN\s+BUDGET)(?![[:alnum:]_])[^;]*?)\s*;?\s*\z/i.freeze
2008
+ SET_DEFAULT = /\ASET\s+(?:CONSISTENCY|SCAN\s+BUDGET)\s+DEFAULT(?![[:alnum:]_])/i.freeze
2009
+ # A +--+ comment, which the server skips to the end of its line — or a
2010
+ # double-quoted name or single-quoted string, inside which two dashes are
2011
+ # not a comment (an unclosed quote runs to the end of the text).
2012
+ COMMENT_OR_QUOTED = /"[^"]*(?:"|\z)|'[^']*(?:'|\z)|--[^\n]*/.freeze
2013
+ private_constant :USE_STATEMENT, :BEGIN_STATEMENT, :END_STATEMENT, :SET_STATEMENT, :SET_DEFAULT,
2014
+ :COMMENT_OR_QUOTED
2015
+
2016
+ # What +sql+ changes of the session state the driver keeps a note of,
2017
+ # as [kind, value] — or nil, for every other statement and for text
2018
+ # that is not exactly one statement the driver can read:
2019
+ #
2020
+ # - [:use, name] — +USE [DATABASE] <name>+: the session moves to that
2021
+ # database. The name is kept as it was written.
2022
+ # - [:consistency, statement], [:scan_budget, statement] — +SET
2023
+ # CONSISTENCY …+, +SET SCAN BUDGET …+: the statement is the setting in
2024
+ # force from now on, kept as written without its comments; nil when
2025
+ # it is +… DEFAULT+, which clears the setting.
2026
+ # - [:begin, nil] — a statement whose first word is +BEGIN+: a
2027
+ # transaction opens.
2028
+ # - [:commit, nil], [:rollback, nil] — it ends.
2029
+ #
2030
+ # Comments are skipped as the server skips them (+USE app -- the app
2031
+ # database+). The note itself is taken once the server has answered
2032
+ # (see following).
2033
+ def session_change(sql)
2034
+ text = sql.gsub(COMMENT_OR_QUOTED) { |part| part.start_with?("--") ? "" : part }
2035
+ if (m = USE_STATEMENT.match(text)) then [:use, m[1]]
2036
+ elsif (m = SET_STATEMENT.match(text))
2037
+ [m[2].casecmp?("CONSISTENCY") ? :consistency : :scan_budget, SET_DEFAULT.match?(m[1]) ? nil : m[1]]
2038
+ elsif BEGIN_STATEMENT.match?(text) then [:begin, nil]
2039
+ elsif (m = END_STATEMENT.match(text)) then [m[1].downcase.to_sym, nil]
2040
+ end
2041
+ rescue ArgumentError, EncodingError
2042
+ nil # bytes the patterns cannot read
2043
+ end
2044
+
2045
+ # Runs the block — the round trip of a statement, and the reading of its
2046
+ # reply — and brings the driver's notes in line with what the server
2047
+ # answered. +change+ is what session_change read from the statement; nil
2048
+ # is every ordinary statement, for which the block is simply run.
2049
+ #
2050
+ # - Success: the change is noted. After USE the session is in that
2051
+ # database, and a re-dial must put it back there (a new session starts
2052
+ # in the default database, where a table of the same name is another
2053
+ # table); after a SET it has that setting, and a re-dial sends it
2054
+ # again (see restore_session). One note per kind: the last statement
2055
+ # the server accepted. After BEGIN a transaction is open, and until it
2056
+ # ends a lost connection is not replaced: PROTOCOL.md §6 rule 7 holds
2057
+ # for a transaction the application writes itself exactly as inside
2058
+ # the helper. After COMMIT or ROLLBACK it is over.
2059
+ # - An Error from the server (QueryError): a USE, a SET or a BEGIN it
2060
+ # refused changed nothing. (A USE refused on a socket dialled for it
2061
+ # leaves that socket in no database the driver noted: it is retired,
2062
+ # and the next statement dials into the noted one again.) A COMMIT it
2063
+ # refused has ended the transaction all the same, and so has a
2064
+ # ROLLBACK.
2065
+ # - No answer the driver could read — the connection lost under the
2066
+ # statement, a reply that makes no sense, or an exception no statement
2067
+ # raised (a Timeout, an Interrupt) anywhere in between: whether the
2068
+ # server took the change is not known, so the notes cannot be trusted
2069
+ # to describe that session any more. The connection is marked broken:
2070
+ # the next statement re-dials into the state the notes do describe. A
2071
+ # COMMIT or ROLLBACK that ends this way has ended the transaction for
2072
+ # the driver — the server drops it with the socket — and a COMMIT
2073
+ # lost in transport says that its outcome is not known: the server may
2074
+ # have applied it before its reply went missing.
2075
+ def following(change)
2076
+ return yield if change.nil?
2077
+
2078
+ kind, value = change
2079
+ ending = kind == :commit || kind == :rollback
2080
+ settled = false
2081
+ begin
2082
+ result = yield
2083
+ case kind
2084
+ when :use
2085
+ @session_use = value
2086
+ @unentered = false
2087
+ when :consistency then @session_consistency = value
2088
+ when :scan_budget then @session_scan_budget = value
2089
+ when :begin then @transaction = true
2090
+ else @transaction = false
2091
+ end
2092
+ settled = true
2093
+ result
2094
+ rescue QueryError
2095
+ @transaction = false if ending
2096
+ # A USE the server refused, on a socket that was dialled for it
2097
+ # without entering the noted database: its session is in the
2098
+ # default database, where nothing the application sends belongs.
2099
+ mark_broken! if @unentered
2100
+ settled = true
2101
+ raise
2102
+ rescue ConnectionError => e
2103
+ raise unless kind == :commit
2104
+
2105
+ raise ConnectionError, "connection lost under COMMIT: whether the transaction was committed is " \
2106
+ "not known (#{e.message})"
2107
+ ensure
2108
+ unless settled
2109
+ mark_broken!
2110
+ @transaction = false if ending
2111
+ end
2112
+ end
2113
+ end
2114
+
2115
+ # The application ends a transaction whose connection is gone: its
2116
+ # ROLLBACK is answered with success and its COMMIT with an error, and
2117
+ # neither is sent — there is nothing to send them to. The server
2118
+ # discarded the transaction with the connection, so nothing of it was
2119
+ # committed (a COMMIT lost in flight is another matter, and following's).
2120
+ # Either one clears the note; the next statement re-dials as after any
2121
+ # lost connection. The connection is looked at first (lost_while_idle?):
2122
+ # one found dead here is a lost transaction like any other.
2123
+ #
2124
+ # Returns nil when +change+ is no COMMIT or ROLLBACK, when no transaction
2125
+ # is noted, or when its connection is alive: the statement is then sent.
2126
+ def end_lost_transaction(change)
2127
+ return nil unless @transaction && change && (change[0] == :commit || change[0] == :rollback)
2128
+
2129
+ mark_broken! if lost_while_idle?
2130
+ return nil unless @broken
2131
+
2132
+ @transaction = false
2133
+ if change[0] == :commit
2134
+ raise ConnectionError, "connection lost inside a transaction: COMMIT was not sent and nothing was committed"
2135
+ end
2136
+
2137
+ Result.new(fields: [], rows: [], cmd_tuples: 0, kind: :ddl)
1480
2138
  end
1481
2139
 
1482
2140
  # The request +stream+ sends. Without parameters: OP_QUERY_STREAM with
@@ -1523,8 +2181,8 @@ module Skaidb
1523
2181
  # Interrupt, a Timeout or Thread#kill, which no rescue here sees — means
1524
2182
  # the reply is still on its way: the socket no longer sits at a request
1525
2183
  # boundary, and the next statement would read this one's reply as its
1526
- # own. So the connection is marked broken: usable? turns false, a pool
1527
- # drops it, and the next statement re-dials.
2184
+ # own. So the connection is marked broken and its socket closed: usable?
2185
+ # turns false, a pool drops it, and the next statement re-dials.
1528
2186
  def round_trip(req)
1529
2187
  answered = false
1530
2188
  write_frame(req)
@@ -1532,7 +2190,7 @@ module Skaidb
1532
2190
  answered = true
1533
2191
  frame
1534
2192
  ensure
1535
- @broken = true unless answered
2193
+ mark_broken! unless answered
1536
2194
  end
1537
2195
 
1538
2196
  def observe_failure
@@ -1546,21 +2204,40 @@ module Skaidb
1546
2204
  end
1547
2205
 
1548
2206
  def parse_response(r)
1549
- tag = r.u8
1550
- case tag
1551
- when 0 # Rows
1552
- parse_rows(r)
1553
- when 8 # ResultSets: a CALL whose body EMITted
1554
- parse_result_sets(r)
1555
- when 1 # Mutation
1556
- Result.new(fields: [], rows: [], cmd_tuples: r.u64, kind: :mutation)
1557
- when 2 # Ddl
1558
- Result.new(fields: [], rows: [], cmd_tuples: 0, kind: :ddl)
1559
- when 3 # Error — a statement error, connection stays usable
1560
- raise Skaidb.statement_error(r.text)
1561
- else
1562
- raise ConnectionError, "unknown response tag #{tag}"
2207
+ message = nil
2208
+ result = reading_reply do
2209
+ tag = r.u8
2210
+ case tag
2211
+ when 0 # Rows
2212
+ parse_rows(r)
2213
+ when 8 # ResultSets: a CALL whose body EMITted
2214
+ parse_result_sets(r)
2215
+ when 1 # Mutation
2216
+ Result.new(fields: [], rows: [], cmd_tuples: r.u64, kind: :mutation)
2217
+ when 2 # Ddl
2218
+ Result.new(fields: [], rows: [], cmd_tuples: 0, kind: :ddl)
2219
+ when 3 # Error — a statement error, connection stays usable
2220
+ message = r.text
2221
+ else
2222
+ raise ConnectionError, "unknown response tag #{tag}"
2223
+ end
1563
2224
  end
2225
+ raise Skaidb.statement_error(message) if message
2226
+
2227
+ result
2228
+ end
2229
+
2230
+ # Runs the block that reads a reply's fields. A reply that cannot be
2231
+ # read — a tag the protocol does not have, a message shorter than its
2232
+ # own fields say, a value of an unknown type — is a ConnectionError, and
2233
+ # the connection is marked broken with it: the peer is not speaking the
2234
+ # protocol, so where its reply ends, and what the next bytes on the
2235
+ # socket belong to, cannot be told. The next statement re-dials.
2236
+ def reading_reply
2237
+ yield
2238
+ rescue ConnectionError
2239
+ mark_broken!
2240
+ raise
1564
2241
  end
1565
2242
 
1566
2243
  # A Rows body (PROTOCOL.md §3.2), also one set of ResultSets; +r+ sits
@@ -1676,6 +2353,12 @@ module Skaidb
1676
2353
  # starting members, and the rest (TLS, the session database, ...) apply to
1677
2354
  # every connection.
1678
2355
  #
2356
+ # Every borrower gets the pool's own session state: the pool's database
2357
+ # (+database:+, or +default+ when it names none), no transaction open, no
2358
+ # consistency override and no scan budget of an earlier borrower. What a
2359
+ # borrower changed is put back when the connection is returned (see
2360
+ # checkin), and a connection that cannot be put back is closed.
2361
+ #
1679
2362
  # Load balancing (PROTOCOL.md §6.1, the same in every skaidb driver; see
1680
2363
  # docs/pooling.md):
1681
2364
  #
@@ -1842,9 +2525,10 @@ module Skaidb
1842
2525
  close_quietly(conn)
1843
2526
  next
1844
2527
  end
1845
- elsif !conn.usable?
1846
- # A connection the server closed while it sat idle still looks
1847
- # fine locally, so check before handing it out.
2528
+ elsif !conn.usable? || conn.lost_while_idle?
2529
+ # A connection the server closed while it sat idle is not handed
2530
+ # out as a live one: the look finds it (no round trip), and the
2531
+ # borrower gets another idle connection or a new one.
1848
2532
  close_quietly(conn)
1849
2533
  next
1850
2534
  end
@@ -1860,21 +2544,31 @@ module Skaidb
1860
2544
 
1861
2545
  # Return a connection, closing it if it is broken, its member is ejected
1862
2546
  # or gone, or the pool is full.
2547
+ #
2548
+ # A connection the pool keeps is first put back in the pool's own
2549
+ # session state (Connection#reset_session): whatever its borrower left
2550
+ # — a transaction open, another database, a scan budget, a consistency
2551
+ # override — the next borrower gets a session in the pool's database
2552
+ # with none of it. That takes round trips only when the borrower
2553
+ # changed something, and a connection that cannot be put back is closed.
1863
2554
  def checkin(conn)
1864
- keep = @mutex.synchronize do
2555
+ keep = false
2556
+ wanted = @mutex.synchronize do
1865
2557
  if conn.pool_out
1866
2558
  conn.pool_out = false
1867
2559
  counted = @members[conn.pool_member]
1868
2560
  counted.in_use -= 1 if counted && counted.in_use.positive?
1869
2561
  end
1870
- m = @members[conn.pool_member]
1871
- if !@closed && conn.usable? && m && usable?(m) && @idle.length < @maxsize
1872
- @idle.push(conn)
1873
- true
1874
- else
1875
- false
1876
- end
2562
+ keepable?(conn)
1877
2563
  end
2564
+ # Outside the pool's lock: these are round trips. (One the pool would
2565
+ # close anyway is closed as it is.)
2566
+ return unless wanted && conn.reset_session
2567
+
2568
+ keep = @mutex.synchronize do
2569
+ @idle.push(conn) if keepable?(conn)
2570
+ end
2571
+ ensure
1878
2572
  close_quietly(conn) unless keep
1879
2573
  end
1880
2574
 
@@ -2044,6 +2738,14 @@ module Skaidb
2044
2738
  nil
2045
2739
  end
2046
2740
 
2741
+ # Whether a returned connection would join the idle set (the caller
2742
+ # holds @mutex): the pool is open and has room, the connection is in
2743
+ # order, and its member still takes connections.
2744
+ def keepable?(conn)
2745
+ m = @members[conn.pool_member]
2746
+ !@closed && conn.usable? && !m.nil? && usable?(m) && @idle.length < @maxsize
2747
+ end
2748
+
2047
2749
  def log(message)
2048
2750
  @logger&.warn("skaidb pool: #{message}")
2049
2751
  end