skaidb 1.4.1 → 1.5.1

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.4.1"
43
+ VERSION = "1.5.1"
39
44
 
40
45
  # Base class for every error raised by this driver.
41
46
  class Error < StandardError; end
@@ -48,6 +53,35 @@ module Skaidb
48
53
  # stays usable for the next query.
49
54
  class QueryError < Error; end
50
55
 
56
+ # The server refused a COMMIT because another writer changed a row the
57
+ # transaction writes after its BEGIN. Nothing was applied and the
58
+ # transaction is over: the connection is back in autocommit and stays
59
+ # usable, and running the whole transaction again from BEGIN is safe —
60
+ # which is what Connection#transaction does. A QueryError like any other
61
+ # statement error, so +rescue Skaidb::QueryError+ catches it too; the
62
+ # message is the server's.
63
+ class TransactionConflict < QueryError
64
+ # What the server's message starts with (PROTOCOL.md §6 rule 6). Only the
65
+ # prefix is matched: the rest of the text may change.
66
+ PREFIX = "transaction conflict:"
67
+ end
68
+
69
+ # Internal: the error for a server Error frame's message — a
70
+ # TransactionConflict when it starts with the conflict prefix, a QueryError
71
+ # otherwise, the message unchanged either way.
72
+ def self.statement_error(message)
73
+ (message.start_with?(TransactionConflict::PREFIX) ? TransactionConflict : QueryError).new(message)
74
+ end
75
+
76
+ # Internal: the argument checks of Connection#transaction and
77
+ # Pool#transaction, made before anything is sent.
78
+ def self.check_transaction_arguments(attempts, has_block)
79
+ raise ArgumentError, "transaction needs a block" unless has_block
80
+ return if attempts.is_a?(Integer) && attempts >= 1
81
+
82
+ raise ArgumentError, "attempts must be an Integer >= 1, got #{attempts.inspect}"
83
+ end
84
+
51
85
  # Consistency levels — how many replicas must acknowledge/answer.
52
86
  module Consistency
53
87
  ONE = 0
@@ -674,6 +708,40 @@ module Skaidb
674
708
  @nonce_mutex.synchronize { @nonce_counter += 1 }
675
709
  end
676
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
+
677
745
  # A connection to one skaidb node. Modelled on +PG::Connection+.
678
746
  class Connection
679
747
  # @return [Boolean] whether the connection has been closed
@@ -711,12 +779,34 @@ module Skaidb
711
779
  end
712
780
  @mutex = Mutex.new
713
781
  @closed = false
714
- # Transport died; the next statement re-dials (see ensure_live!).
782
+ # Transport died, and its socket is closed (see mark_broken!); the next
783
+ # statement re-dials (see ensure_live!).
715
784
  @broken = false
716
- # A stream is in flight, so the socket sits mid-reply (see stream).
785
+ # A stream is in flight, so the socket sits mid-reply (see stream), and
786
+ # the Fiber it runs in: the transaction helper unwinds a stream its
787
+ # block left open (see abandon_open_stream).
717
788
  @streaming = false
789
+ @stream_fiber = nil
790
+ # The transaction helper is between its BEGIN and its COMMIT/ROLLBACK,
791
+ # so a lost socket must not be re-dialled (see ensure_live!).
792
+ @in_transaction = false
793
+ # Statements prepared on this socket, SQL => [id, nparams]: the ones
794
+ # the driver prepared for exec_params / exec_batch, least recently used
795
+ # first, and the ones prepare_server handed to the application (see
796
+ # prepare_cached).
718
797
  @prepared = {}
798
+ @held = {}
799
+ # Every id prepare_server has handed out => its SQL, kept across
800
+ # re-dials: exec_prepared prepares the statement again when the id is
801
+ # from a socket this connection has since replaced.
802
+ @handles = {}
803
+ @serial = 0
719
804
  @last_prepare_error = nil
805
+ # The session database, as the USE target every dial re-enters: the one
806
+ # the connection was opened in (+database:+), and the one it is in now
807
+ # — a USE statement the server accepted moves it (see note_use).
808
+ @dial_use = database.to_s.empty? ? nil : %("#{database.to_s.gsub('"', '""')}")
809
+ @session_use = @dial_use
720
810
  # Retained so a reconnect repeats the original connect exactly.
721
811
  @dial_args = { host: host, port: port, user: user, password: password,
722
812
  timeout: timeout, database: database, tls: tls, tls_ca: tls_ca,
@@ -730,12 +820,12 @@ module Skaidb
730
820
  # connect and for every reconnect, so a recovered connection is
731
821
  # indistinguishable from a fresh one.
732
822
  def dial!
823
+ @serial = Skaidb.next_dial_serial
733
824
  host = @dial_args[:host]
734
825
  port = @dial_args[:port]
735
826
  user = @dial_args[:user]
736
827
  password = @dial_args[:password]
737
828
  timeout = @dial_args[:timeout]
738
- database = @dial_args[:database]
739
829
  tls = @dial_args[:tls]
740
830
  tls_ca = @dial_args[:tls_ca]
741
831
  tls_insecure = @dial_args[:tls_insecure]
@@ -786,13 +876,17 @@ module Skaidb
786
876
  end
787
877
  end
788
878
  if last
789
- @closed = true
879
+ # Not closed: this is also how a re-dial fails while the members are
880
+ # down, and the next statement dials again (see ensure_live!).
790
881
  raise ConnectionError,
791
882
  "no reachable endpoint in #{endpoints.map { |(h, q)| "#{h}:#{q}" }.join(', ')}: #{last.message}"
792
883
  end
793
884
  send_hello
794
- # USE is per-connection session state, so it runs on every dial.
795
- exec(%(USE "#{database.to_s.gsub('"', '""')}")) if database && !database.to_s.empty?
885
+ # The database is per-connection session state, so it is entered on
886
+ # every dial — the one the session was last in, before anything else
887
+ # is sent. If the server refuses, the dial has failed and its error is
888
+ # the statement's: nothing runs in another database.
889
+ exec("USE #{@session_use}") if @session_use
796
890
  end
797
891
 
798
892
  # Best-effort self-identification: fills the server's +drivers+ table
@@ -869,7 +963,7 @@ module Skaidb
869
963
  # and Hashes have no SQL literal form. $N is rewritten to the
870
964
  # positional ? the server expects.
871
965
  qsql, order = Skaidb.to_qmark(sql.to_s, params)
872
- prep = prepare_server(qsql)
966
+ prep = prepare_cached(qsql)
873
967
  unless prep.nil?
874
968
  id, nparams = prep
875
969
  if nparams != order.length
@@ -902,7 +996,7 @@ module Skaidb
902
996
 
903
997
  level = consistency.nil? ? @consistency : Consistency.resolve(consistency)
904
998
  qsql, = Skaidb.to_qmark(sql.to_s, rows.first)
905
- prep = prepare_server(qsql)
999
+ prep = prepare_cached(qsql)
906
1000
  raise QueryError, "statement cannot be prepared, so it cannot be batched" if prep.nil?
907
1001
 
908
1002
  id, nparams = prep
@@ -912,7 +1006,7 @@ module Skaidb
912
1006
  end
913
1007
  raise ConnectionError, "connection is closed" if @closed
914
1008
 
915
- req = +([7, level].pack("CC") + [id].pack("V") + [ordered.length].pack("V"))
1009
+ req = +([7, level].pack("CC") + [id & WIRE_ID].pack("V") + [ordered.length].pack("V"))
916
1010
  ordered.each do |r|
917
1011
  req << [r.length].pack("v")
918
1012
  r.each do |v|
@@ -926,6 +1020,99 @@ module Skaidb
926
1020
  n
927
1021
  end
928
1022
 
1023
+ # Run the block inside a transaction on this connection and return the
1024
+ # block's value: +begin+, the block (handed the connection), COMMIT.
1025
+ #
1026
+ # conn.transaction do |c|
1027
+ # c.exec_params("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [10, 1])
1028
+ # c.exec_params("UPDATE accounts SET balance = balance + $1 WHERE id = $2", [10, 2])
1029
+ # end
1030
+ #
1031
+ # A COMMIT the server refuses with TransactionConflict (another writer
1032
+ # changed a row the transaction writes; nothing was applied) starts the
1033
+ # whole thing again from +begin+ — up to +attempts+ runs in all, with no
1034
+ # pause between them: the other writer has already finished, and the next
1035
+ # run reads the rows as they are now. So the block may run MORE THAN
1036
+ # ONCE: it must be safe to repeat, and should do nothing outside the
1037
+ # database that a repeat would do twice. The conflict of the last attempt
1038
+ # is raised.
1039
+ #
1040
+ # +begin+ is the opening statement, sent as given: "BEGIN" on a
1041
+ # standalone server, "BEGIN ATOMIC" or "BEGIN ATOMIC PARTITION (col =
1042
+ # lit)" on a cluster.
1043
+ #
1044
+ # - +begin+ refused: its error is raised, the block never runs and
1045
+ # nothing else is sent (the block's statements would autocommit one by
1046
+ # one).
1047
+ # - The block does not run to its end — an exception of any class,
1048
+ # +break+, +throw+ or a +return+ out of it: ROLLBACK is sent, and what
1049
+ # the block was leaving with carries on unchanged whatever the ROLLBACK
1050
+ # itself answers. Nothing is retried, a TransactionConflict raised in
1051
+ # the block included.
1052
+ # - Any other COMMIT error is raised as it is. A failed COMMIT has ended
1053
+ # the transaction, so no ROLLBACK follows and nothing is retried.
1054
+ # - A transport failure is the usual ConnectionError and is not retried.
1055
+ # The transaction lived on the socket that died, so until the helper
1056
+ # returns the connection does not re-dial: no ROLLBACK is sent, and a
1057
+ # statement the block still runs after rescuing the failure raises
1058
+ # ConnectionError instead of autocommitting on a new session. The same
1059
+ # goes for a block cut short in the middle of a round trip (an
1060
+ # Interrupt, a Timeout): the reply is still on its way, so nothing more
1061
+ # is written to that socket. Either way the socket is closed at once,
1062
+ # and the server drops the transaction with it.
1063
+ # - A stream the block leaves open — an Enumerator from +stream+ advanced
1064
+ # with +next+ or +peek+ and not read to its end — sits in the middle of
1065
+ # its reply, so neither COMMIT nor ROLLBACK can be sent. The socket is
1066
+ # closed instead and the server drops the transaction with it:
1067
+ # ConnectionError is raised, unless the block was itself leaving with
1068
+ # an exception, +break+ or +throw+, which carries on. The stream is
1069
+ # ended with it, so the connection is what it is after any lost
1070
+ # connection (the next statement re-dials), and the Enumerator starts
1071
+ # its statement again if it is advanced again. Read a stream to its
1072
+ # end, or give +stream+ a block, before the transaction's block
1073
+ # returns.
1074
+ #
1075
+ # The whole transaction runs on this one connection, so no other thread
1076
+ # may use it meanwhile. +attempts+ below 1, or no block, is an
1077
+ # ArgumentError raised before anything is sent.
1078
+ def transaction(attempts: 3, begin: "BEGIN")
1079
+ opening = binding.local_variable_get(:begin) # +begin+ is a keyword, so the local has no other name
1080
+ Skaidb.check_transaction_arguments(attempts, block_given?)
1081
+
1082
+ enclosing = @in_transaction
1083
+ attempt = 0
1084
+ begin
1085
+ attempt += 1
1086
+ committing = false
1087
+ exec(opening)
1088
+ @in_transaction = true
1089
+ finished = false
1090
+ begin
1091
+ value = yield self
1092
+ finished = true
1093
+ ensure
1094
+ abandoned = abandon_open_stream
1095
+ rollback_quietly unless finished
1096
+ end
1097
+ if abandoned
1098
+ raise ConnectionError, "a stream opened inside the transaction was left open, so COMMIT could not " \
1099
+ "be sent: its session was dropped and nothing was committed"
1100
+ end
1101
+ committing = true
1102
+ exec("COMMIT")
1103
+ value
1104
+ rescue TransactionConflict
1105
+ # Only a refused COMMIT is run again; a conflict the block raised
1106
+ # was rolled back above, and one from +begin+ opened nothing.
1107
+ raise unless committing && attempt < attempts
1108
+
1109
+ @in_transaction = enclosing
1110
+ retry
1111
+ ensure
1112
+ @in_transaction = enclosing
1113
+ end
1114
+ end
1115
+
929
1116
  # Stream a result set: yields one row Hash at a time while holding a
930
1117
  # single chunk, instead of buffering the whole result. For exports and
931
1118
  # large scans.
@@ -953,7 +1140,10 @@ module Skaidb
953
1140
  # sending so the connection sits at a request boundary again. When it
954
1141
  # cannot (dead socket, a frame that makes no sense mid-stream) the
955
1142
  # connection is marked broken instead, so +usable?+ turns false and Pool
956
- # drops it rather than handing out a desynced socket.
1143
+ # drops it rather than handing out a desynced socket. So it is when the
1144
+ # stream is cut short while it waits for a frame (Timeout.timeout, an
1145
+ # Interrupt, Thread#kill): nothing is drained, and the exception
1146
+ # propagates at once.
957
1147
  #
958
1148
  # Draining is not free and there is no cancel opcode: breaking out of a
959
1149
  # million-row scan still transfers the rest of it before the connection
@@ -1000,8 +1190,7 @@ module Skaidb
1000
1190
  @mutex.synchronize do
1001
1191
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
1002
1192
  begin
1003
- write_frame(req)
1004
- r = Reader.new(read_frame)
1193
+ r = Reader.new(round_trip(req))
1005
1194
  rescue ConnectionError
1006
1195
  observe_failure
1007
1196
  raise
@@ -1016,10 +1205,11 @@ module Skaidb
1016
1205
  what = params.empty? ? "streaming" : "parameterised streaming (skaidb >= 0.330)"
1017
1206
  raise QueryError, "server does not support #{what}: #{msg}"
1018
1207
  end
1019
- raise QueryError, msg
1208
+ raise Skaidb.statement_error(msg)
1020
1209
  when 1
1021
1210
  return Result.new(fields: [], rows: [], cmd_tuples: r.u64, kind: :mutation) # not row-producing
1022
1211
  when 2
1212
+ note_use(sql.to_s) if params.empty?
1023
1213
  return Result.new(fields: [], rows: [], cmd_tuples: 0, kind: :ddl)
1024
1214
  when 8
1025
1215
  # ResultSets: a CALL whose body EMITted is answered with every set
@@ -1040,11 +1230,17 @@ module Skaidb
1040
1230
  # two-line window.
1041
1231
  live = true
1042
1232
  @streaming = true
1233
+ @stream_fiber = Fiber.current
1234
+ Skaidb.keep_stream_lock(@mutex)
1043
1235
  cols = Array.new(r.u32) { r.text }
1044
1236
  summary = Result.new(fields: cols, rows: [], cmd_tuples: 0, kind: :stream)
1237
+ reading = false
1045
1238
  begin
1046
1239
  while live
1047
- fr = Reader.new(read_frame)
1240
+ reading = true
1241
+ frame = read_frame
1242
+ reading = false
1243
+ fr = Reader.new(frame)
1048
1244
  case fr.u8
1049
1245
  when 6
1050
1246
  fr.u32.times do
@@ -1056,22 +1252,41 @@ module Skaidb
1056
1252
  live = false
1057
1253
  when 3
1058
1254
  live = false
1059
- raise QueryError, fr.text
1255
+ raise Skaidb.statement_error(fr.text)
1060
1256
  else
1061
1257
  # Mid-stream the server sends only RowsChunk, RowsEnd or Error.
1062
1258
  # Anything else means we no longer know where the reply ends, so
1063
1259
  # there is no draining back to a request boundary: retire it.
1064
1260
  live = false
1065
- @broken = true
1261
+ mark_broken!
1066
1262
  raise QueryError, "unexpected frame in stream"
1067
1263
  end
1068
1264
  end
1069
1265
  ensure
1070
- drain_stream! if live
1071
- # Cleared last: until this point the connection is mid-reply, and a
1072
- # caller who never unwinds here (an abandoned Enumerator Fiber)
1073
- # leaves it set, so usable? keeps reporting the truth.
1074
- @streaming = false
1266
+ begin
1267
+ if reading
1268
+ # Left while a frame was being read — the transport failed,
1269
+ # or a Timeout, an Interrupt or Thread#kill cut the read
1270
+ # short. The socket is not at a frame boundary (part of that
1271
+ # frame may be consumed), so there is nothing to drain from;
1272
+ # and draining would hold back the exception until the
1273
+ # server had sent the rest of the stream, which a stalled
1274
+ # server never does.
1275
+ mark_broken!
1276
+ elsif live
1277
+ drain_stream!
1278
+ end
1279
+ ensure
1280
+ # Cleared last: until this point the connection is mid-reply,
1281
+ # and a caller who never unwinds here (an abandoned Enumerator
1282
+ # Fiber) leaves it set, so usable? keeps reporting the truth.
1283
+ # In an ensure of its own: a drain that is itself cut short
1284
+ # has retired the socket, and the connection the next
1285
+ # statement re-dials is not in the middle of any stream.
1286
+ @streaming = false
1287
+ @stream_fiber = nil
1288
+ Skaidb.release_stream_lock(@mutex)
1289
+ end
1075
1290
  end
1076
1291
  else
1077
1292
  raise QueryError, "unexpected response tag #{tag} to stream request"
@@ -1087,40 +1302,37 @@ module Skaidb
1087
1302
  end
1088
1303
 
1089
1304
  # Prepare +sql+ on the SERVER, returning [id, nparams], or nil when the
1090
- # server declines the statement kind (DDL, session statements) so the
1091
- # caller falls back to text binding. Cached per connection.
1305
+ # server declines the statement kind (DDL, session statements). The id is
1306
+ # the caller's to keep for exec_prepared: the driver's cache never closes
1307
+ # a statement handed out here (exec_params and exec_batch with the same
1308
+ # SQL use it too). A server whose statement table is full refuses with
1309
+ # QueryError.
1092
1310
  def prepare_server(sql)
1093
- hit = @prepared[sql]
1094
- return hit if hit
1095
- raise ConnectionError, "connection is closed" if @closed
1096
- ensure_live!
1097
-
1098
- sql_bytes = sql.dup.force_encoding("UTF-8").b
1099
- req = [2].pack("C") + [sql_bytes.bytesize].pack("V") + sql_bytes
1100
- reader = request(req)
1101
- tag = reader.u8
1102
- case tag
1103
- when 4
1104
- id = reader.u32
1105
- nparams = reader.u16
1106
- v = [id, nparams]
1107
- @prepared[sql] = v if @prepared.length < 240
1108
- v
1109
- when 3
1110
- # Refused: DDL/session statements cannot be prepared, and an old
1111
- # server answers "unknown opcode". Kept for the caller's error message.
1112
- @last_prepare_error = reader.text
1113
- nil
1114
- else
1115
- raise QueryError, "unexpected prepare response tag #{tag}"
1116
- end
1117
- end
1118
-
1119
- # Execute a prepared statement with TYPED parameters.
1311
+ prepare_cached(sql, hold: true)
1312
+ end
1313
+
1314
+ # The server holds at most 256 prepared statements per connection
1315
+ # (PROTOCOL.md §3.3). The driver keeps under it with room to spare.
1316
+ PREPARED_LIMIT = 240
1317
+ private_constant :PREPARED_LIMIT
1318
+
1319
+ # The lower half of an id is the server's statement number, the upper
1320
+ # half the socket that issued it (see Skaidb.next_dial_serial).
1321
+ WIRE_ID = 0xFFFF_FFFF
1322
+ private_constant :WIRE_ID
1323
+
1324
+ # Execute a prepared statement with TYPED parameters, by the id
1325
+ # prepare_server returned. An id is a number on the socket that issued
1326
+ # it; on another socket the same number is unknown, or names a different
1327
+ # statement prepared there since. So an id from a socket this connection
1328
+ # has since replaced is not sent: its statement is prepared again on the
1329
+ # current socket first (a broken connection re-dials for it, as for any
1330
+ # statement). An id another connection issued is refused with QueryError.
1120
1331
  def exec_prepared(id, params, consistency)
1121
1332
  raise ConnectionError, "connection is closed" if @closed
1122
1333
 
1123
- req = +([3, consistency].pack("CC") + [id].pack("V") + [params.length].pack("v"))
1334
+ id = current_id(id)
1335
+ req = +([3, consistency].pack("CC") + [id & WIRE_ID].pack("V") + [params.length].pack("v"))
1124
1336
  params.each do |p|
1125
1337
  v = Skaidb.encode_value(p)
1126
1338
  req << [v.bytesize].pack("V") << v
@@ -1189,6 +1401,13 @@ module Skaidb
1189
1401
  @closed
1190
1402
  end
1191
1403
 
1404
+ # Internal, for Pool: put the session back in the database the connection
1405
+ # was opened in (+database:+) when a USE statement has moved it since.
1406
+ # One round trip, and none when there is nothing to put back.
1407
+ def reenter_dial_database
1408
+ exec("USE #{@dial_use}") if @dial_use && @session_use != @dial_use
1409
+ end
1410
+
1192
1411
  private
1193
1412
 
1194
1413
  # -- framing --
@@ -1197,10 +1416,26 @@ module Skaidb
1197
1416
  payload = payload.b
1198
1417
  @sock.write([payload.bytesize].pack("N") + payload) # length is BE
1199
1418
  rescue StandardError => e
1200
- @broken = true
1419
+ mark_broken!
1201
1420
  raise ConnectionError, "write failed: #{e.message}"
1202
1421
  end
1203
1422
 
1423
+ # This socket carries no further statement: its transport failed, or it
1424
+ # was left in the middle of a reply. usable? turns false and the next
1425
+ # statement re-dials — and the socket is closed HERE, not when that
1426
+ # statement comes. The server keeps a session for as long as its socket
1427
+ # is open, and with it the transaction left open on it; a connection that
1428
+ # timed out inside a transaction and is not used again would hold that
1429
+ # transaction until it is closed or collected. The TCP socket is closed
1430
+ # as it is, with no TLS goodbye written first: nothing more is written
1431
+ # to a socket in this state.
1432
+ def mark_broken!
1433
+ @broken = true
1434
+ @sock&.to_io&.close
1435
+ rescue StandardError
1436
+ nil
1437
+ end
1438
+
1204
1439
  # Re-dial if the transport died since the last statement, BEFORE anything
1205
1440
  # is prepared on it.
1206
1441
  #
@@ -1210,8 +1445,13 @@ module Skaidb
1210
1445
  def ensure_live!
1211
1446
  raise ConnectionError, "connection is closed" if @closed
1212
1447
  return unless @broken
1448
+ # A transaction lives on the socket that carried its BEGIN. Re-dialling
1449
+ # inside the helper would run the rest of the block, and the COMMIT, on
1450
+ # a new session with no transaction open: each statement autocommitted.
1451
+ raise ConnectionError, "connection lost inside a transaction; not re-dialling until it ends" if @in_transaction
1213
1452
 
1214
1453
  @prepared.clear
1454
+ @held.clear
1215
1455
  begin
1216
1456
  @sock&.close
1217
1457
  rescue StandardError
@@ -1221,11 +1461,16 @@ module Skaidb
1221
1461
  # Cleared BEFORE dialling: dial! issues USE, which runs a statement and
1222
1462
  # would otherwise re-enter this method forever.
1223
1463
  @broken = false
1464
+ dialled = false
1224
1465
  begin
1225
1466
  dial!
1226
- rescue StandardError => e
1227
- @broken = true # still down; the next statement retries
1228
- raise e
1467
+ dialled = true
1468
+ ensure
1469
+ # Still down, so the next statement retries — or the dial was cut
1470
+ # short (an Interrupt, a Timeout) with the handshake's or Hello's
1471
+ # reply outstanding on the new socket, which the next statement
1472
+ # would read as its own.
1473
+ mark_broken! unless dialled
1229
1474
  end
1230
1475
  end
1231
1476
 
@@ -1236,38 +1481,43 @@ module Skaidb
1236
1481
  end
1237
1482
 
1238
1483
  # Read out the frames left over from a stream the caller walked away from,
1239
- # so the connection is positioned at a request boundary again. Deliberately
1484
+ # so the connection is positioned at a request boundary again.
1485
+ #
1240
1486
  # Runs from an ensure, where an exception would replace whatever the
1241
1487
  # caller's block was already unwinding with — so an ordinary failure
1242
1488
  # marks the connection broken rather than raising. usable? then fails
1243
1489
  # and ensure_live! re-dials before the next statement.
1244
1490
  #
1245
- # Not exception-PROOF, and the difference matters: the rescue below
1246
- # catches StandardError, so Interrupt, SignalException and
1247
- # NoMemoryError still escape. They also skip the `@streaming = false`
1248
- # in the caller's ensure, which leaves the connection permanently
1249
- # unusable — safe, but only because "unusable" is the failing
1250
- # direction. Rescuing Exception here would hide a Ctrl-C, which is a
1251
- # worse trade than retiring one connection.
1491
+ # An Interrupt, a Timeout or Thread#kill is not an ordinary failure: the
1492
+ # rescue below catches StandardError only, so those still leave through
1493
+ # here (rescuing Exception would hide a Ctrl-C). They leave the rest of
1494
+ # the stream on the socket, so the ensure marks the connection broken on
1495
+ # EVERY exit that did not reach the end of the stream. Left unmarked,
1496
+ # the next statements on the connection read the leftover chunks as
1497
+ # their replies, and after those the replies of the statements before
1498
+ # them.
1252
1499
  #
1253
- # There is also no read DEADLINE. A peer that is alive but silent
1254
- # blocks the drain forever, holding @mutex — the same as every other
1255
- # read in this driver, and `close` deliberately does not take @mutex
1256
- # so another thread can break it. A genuinely dead socket (EOF, RST)
1257
- # exits correctly.
1500
+ # There is no read DEADLINE. A peer that is alive but silent blocks the
1501
+ # drain forever, holding @mutex — the same as every other read in this
1502
+ # driver, and `close` deliberately does not take @mutex so another
1503
+ # thread can break it. A genuinely dead socket (EOF, RST) exits
1504
+ # correctly.
1258
1505
  def drain_stream!
1506
+ drained = false
1259
1507
  loop do
1260
1508
  tag = Reader.new(read_frame).u8
1261
- break if tag == 7 || tag == 3 # RowsEnd, or an Error that ended the stream
1262
- next if tag == 6 # RowsChunk: more to come
1509
+ next if tag == 6 # RowsChunk: more to come
1263
1510
 
1264
- @broken = true
1511
+ # RowsEnd, or an Error that ended the stream: at a request boundary.
1512
+ # Anything else: where the reply ends is no longer known.
1513
+ drained = [7, 3].include?(tag)
1265
1514
  break
1266
1515
  end
1267
1516
  rescue StandardError
1268
- # An I/O failure already set @broken in read_exact; set it for the rest
1269
- # (a truncated frame, say) so the socket is never reused mid-reply.
1270
- @broken = true
1517
+ # An I/O failure, or a frame too short to carry a tag: not drained.
1518
+ nil
1519
+ ensure
1520
+ mark_broken! unless drained
1271
1521
  end
1272
1522
 
1273
1523
  def read_exact(n)
@@ -1278,11 +1528,11 @@ module Skaidb
1278
1528
  chunk = begin
1279
1529
  @sock.read(n - buf.bytesize)
1280
1530
  rescue StandardError => e
1281
- @broken = true
1531
+ mark_broken!
1282
1532
  raise ConnectionError, "read failed: #{e.message}"
1283
1533
  end
1284
1534
  if chunk.nil? || chunk.empty?
1285
- @broken = true
1535
+ mark_broken!
1286
1536
  raise ConnectionError, "connection closed by server"
1287
1537
  end
1288
1538
 
@@ -1338,6 +1588,138 @@ module Skaidb
1338
1588
 
1339
1589
  # -- query --
1340
1590
 
1591
+ # prepare_server's work, and how exec_params and exec_batch prepare: [id,
1592
+ # nparams] for +sql+, from this socket's statements or prepared now; nil
1593
+ # when the server declines the statement kind, so the caller falls back
1594
+ # to text binding.
1595
+ #
1596
+ # Statements prepared here on the driver's own account are a cache, least
1597
+ # recently used first. Before a new statement would take the count to
1598
+ # PREPARED_LIMIT the oldest of them is closed on the server (OP_CLOSE),
1599
+ # so the server's table (256 per connection) never fills however many
1600
+ # distinct statements a connection runs. Statements handed to the
1601
+ # application (+hold+) are never closed: it still holds their ids.
1602
+ #
1603
+ # A server that refuses because its table is full all the same — the
1604
+ # application holds that many — is a statement error, QueryError. It is
1605
+ # NOT answered with the text fallback: that would send the values as
1606
+ # literals, a Time as a number and bytes as a hex string, without a word.
1607
+ def prepare_cached(sql, hold: false)
1608
+ raise ConnectionError, "connection is closed" if @closed
1609
+ # Before the cache is read: a re-dial empties it, and a cached id must
1610
+ # not send a statement down a socket that is broken.
1611
+ ensure_live!
1612
+ hit = @held[sql]
1613
+ return hit if hit
1614
+
1615
+ if (hit = @prepared.delete(sql))
1616
+ (hold ? @held : @prepared)[sql] = hit # held from now on, or most recently used
1617
+ @handles[hit[0]] = sql if hold
1618
+ return hit
1619
+ end
1620
+
1621
+ close_prepared(@prepared.shift[1][0]) while @held.length + @prepared.length >= PREPARED_LIMIT && !@prepared.empty?
1622
+ sql_bytes = sql.dup.force_encoding("UTF-8").b
1623
+ req = [2].pack("C") + [sql_bytes.bytesize].pack("V") + sql_bytes
1624
+ reader = request(req)
1625
+ tag = reader.u8
1626
+ case tag
1627
+ when 4
1628
+ id = (@serial << 32) | reader.u32
1629
+ nparams = reader.u16
1630
+ @handles[id] = sql if hold
1631
+ (hold ? @held : @prepared)[sql] = [id, nparams]
1632
+ when 3
1633
+ msg = reader.text
1634
+ raise Skaidb.statement_error(msg) if msg.start_with?("too many prepared statements")
1635
+
1636
+ # Refused: DDL/session statements cannot be prepared, and an old
1637
+ # server answers "unknown opcode". Kept for the caller's error message.
1638
+ @last_prepare_error = msg
1639
+ nil
1640
+ else
1641
+ raise QueryError, "unexpected prepare response tag #{tag}"
1642
+ end
1643
+ end
1644
+
1645
+ # Free a prepared statement's slot on the server (OP_CLOSE). What it
1646
+ # answers does not matter: the id is forgotten here either way.
1647
+ def close_prepared(id)
1648
+ request([4].pack("C") + [id & WIRE_ID].pack("V"))
1649
+ nil
1650
+ end
1651
+
1652
+ # exec_prepared's id as the current socket knows it: the id itself when
1653
+ # this socket issued it; otherwise the id of the same statement prepared
1654
+ # here again — never a number another socket gave out.
1655
+ def current_id(id)
1656
+ ensure_live!
1657
+ return id if id >> 32 == @serial
1658
+
1659
+ sql = @handles[id]
1660
+ raise QueryError, "prepared statement id #{id} was not issued by this connection" if sql.nil?
1661
+
1662
+ entry = prepare_cached(sql, hold: true)
1663
+ raise QueryError, "the statement could not be prepared again: #{@last_prepare_error}" if entry.nil?
1664
+
1665
+ entry[0]
1666
+ end
1667
+
1668
+ # The transaction helper's clean-up after a block that did not run to its
1669
+ # end. It runs while something else is unwinding, so it never raises: a
1670
+ # ROLLBACK the server refuses (one before 0.347 answers "no transaction in
1671
+ # progress" when nothing is open) or that dies in transport must not
1672
+ # replace what the block left with. Not sent on a connection that is not
1673
+ # usable — its socket died, or was left in the middle of a reply: the
1674
+ # transaction goes with the socket.
1675
+ def rollback_quietly
1676
+ exec("ROLLBACK") if usable?
1677
+ rescue StandardError
1678
+ nil
1679
+ end
1680
+
1681
+ # Internal: raised into the Fiber of a stream the transaction helper's
1682
+ # block left open, to unwind it. Not a StandardError, so nothing between
1683
+ # the stream and the top of that Fiber takes it for an ordinary failure.
1684
+ class StreamAbandoned < Exception; end # rubocop:disable Lint/InheritException
1685
+ private_constant :StreamAbandoned
1686
+
1687
+ # The transaction helper's check once its block is done: is a stream the
1688
+ # block opened still in flight? That is an Enumerator from +stream+
1689
+ # advanced with +next+ and not read to its end: its Fiber holds the
1690
+ # socket in the middle of the reply (and the connection's lock), so
1691
+ # neither COMMIT nor ROLLBACK can be sent, and the transaction would stay
1692
+ # open on a live session — where a statement sent after the stream was
1693
+ # read to its end would run inside it, uncommitted.
1694
+ #
1695
+ # So the session goes: the connection is marked broken, which closes the
1696
+ # socket, and the server drops the transaction with it. Then the stream
1697
+ # is unwound — an exception raised into its Fiber runs the stream's
1698
+ # ensure, which finds nothing to drain, clears the busy flag and releases
1699
+ # the lock — so the connection is what it is after any lost connection:
1700
+ # the next statement re-dials. The Fiber must not be left where it is:
1701
+ # it owns the lock, and an Enumerator dropped in that state takes the
1702
+ # lock's owner with it when it is collected (which Ruby 3.3 does not
1703
+ # survive).
1704
+ #
1705
+ # A stream whose Fiber cannot be reached (it runs in another thread)
1706
+ # leaves the connection closed for good instead: a re-dial would hand
1707
+ # that Fiber, when it is resumed, a new socket to read its old reply
1708
+ # from. Returns whether a stream was in flight.
1709
+ def abandon_open_stream
1710
+ return false unless @streaming
1711
+
1712
+ fiber = @stream_fiber
1713
+ mark_broken!
1714
+ begin
1715
+ fiber.raise(StreamAbandoned) if fiber&.alive? && !fiber.equal?(Fiber.current)
1716
+ rescue StreamAbandoned, StandardError
1717
+ nil # unwound; or not reachable (FiberError), which the next line sees
1718
+ end
1719
+ close if @streaming
1720
+ true
1721
+ end
1722
+
1341
1723
  def run(sql, consistency)
1342
1724
  raise ConnectionError, "connection is closed" if @closed
1343
1725
  ensure_live!
@@ -1347,9 +1729,34 @@ module Skaidb
1347
1729
  reader = request(req)
1348
1730
  res = parse_response(reader)
1349
1731
  note_statement(sql)
1732
+ note_use(sql)
1350
1733
  res
1351
1734
  end
1352
1735
 
1736
+ # +USE [DATABASE] <name>+ with an optional +;+ — the name bare, or in
1737
+ # double quotes with "" for a quote inside.
1738
+ USE_STATEMENT = /\A\s*USE\s+(?:DATABASE\s+)?("(?:[^"]|"")+"|[[:alpha:]_][[:alnum:]_]*)\s*;?\s*\z/i.freeze
1739
+ # A +--+ comment, which the server skips to the end of its line — or a
1740
+ # double-quoted name or single-quoted string, inside which two dashes are
1741
+ # not a comment (an unclosed quote runs to the end of the text).
1742
+ COMMENT_OR_QUOTED = /"[^"]*(?:"|\z)|'[^']*(?:'|\z)|--[^\n]*/.freeze
1743
+ private_constant :USE_STATEMENT, :COMMENT_OR_QUOTED
1744
+
1745
+ # A statement the server answered with success: when it is a USE, the
1746
+ # session is in that database now, and a re-dial must put it back there
1747
+ # (a new session starts in the default database, where a table of the
1748
+ # same name is another table). Comments are skipped as the server skips
1749
+ # them (+USE app -- the app database+). The name is kept as it was
1750
+ # written and sent again the same way, in a USE of its own. Text that is
1751
+ # not exactly one such statement is left alone.
1752
+ def note_use(sql)
1753
+ text = sql.gsub(COMMENT_OR_QUOTED) { |part| part.start_with?("--") ? "" : part }
1754
+ m = USE_STATEMENT.match(text)
1755
+ @session_use = m[1] if m
1756
+ rescue ArgumentError, EncodingError
1757
+ nil # bytes the pattern cannot read
1758
+ end
1759
+
1353
1760
  # The request +stream+ sends. Without parameters: OP_QUERY_STREAM with
1354
1761
  # the SQL as given, byte for byte what every server understands. With
1355
1762
  # them: OP_QUERY_STREAM_PARAMS (server >= 0.330), $N rewritten to the
@@ -1380,10 +1787,7 @@ module Skaidb
1380
1787
  def request(req)
1381
1788
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
1382
1789
  frame = begin
1383
- @mutex.synchronize do
1384
- write_frame(req)
1385
- read_frame
1386
- end
1790
+ @mutex.synchronize { round_trip(req) }
1387
1791
  rescue ConnectionError
1388
1792
  observe_failure
1389
1793
  raise
@@ -1392,6 +1796,23 @@ module Skaidb
1392
1796
  Reader.new(frame)
1393
1797
  end
1394
1798
 
1799
+ # Write a request and read the first frame of its reply (the caller holds
1800
+ # @mutex). Leaving in between — on a transport error, but also on an
1801
+ # Interrupt, a Timeout or Thread#kill, which no rescue here sees — means
1802
+ # the reply is still on its way: the socket no longer sits at a request
1803
+ # boundary, and the next statement would read this one's reply as its
1804
+ # own. So the connection is marked broken and its socket closed: usable?
1805
+ # turns false, a pool drops it, and the next statement re-dials.
1806
+ def round_trip(req)
1807
+ answered = false
1808
+ write_frame(req)
1809
+ frame = read_frame
1810
+ answered = true
1811
+ frame
1812
+ ensure
1813
+ mark_broken! unless answered
1814
+ end
1815
+
1395
1816
  def observe_failure
1396
1817
  @observer.note_failure(@endpoint) if @observer && @endpoint
1397
1818
  end
@@ -1414,7 +1835,7 @@ module Skaidb
1414
1835
  when 2 # Ddl
1415
1836
  Result.new(fields: [], rows: [], cmd_tuples: 0, kind: :ddl)
1416
1837
  when 3 # Error — a statement error, connection stays usable
1417
- raise QueryError, r.text
1838
+ raise Skaidb.statement_error(r.text)
1418
1839
  else
1419
1840
  raise ConnectionError, "unknown response tag #{tag}"
1420
1841
  end
@@ -1704,6 +2125,9 @@ module Skaidb
1704
2125
  # fine locally, so check before handing it out.
1705
2126
  close_quietly(conn)
1706
2127
  next
2128
+ elsif !in_pool_database?(conn)
2129
+ close_quietly(conn)
2130
+ next
1707
2131
  end
1708
2132
  @mutex.synchronize do
1709
2133
  m = @members[conn.pool_member]
@@ -1746,6 +2170,20 @@ module Skaidb
1746
2170
  end
1747
2171
  end
1748
2172
 
2173
+ # Run the block inside a transaction on ONE checked-out connection and
2174
+ # return the block's value: Connection#transaction, with the same
2175
+ # +attempts+ and +begin+, on a connection held for the whole transaction
2176
+ # — every attempt included — and returned afterwards. +affinity+ scopes
2177
+ # read-your-writes, as in +with+.
2178
+ #
2179
+ # pool.transaction { |conn| conn.exec_params("UPDATE … WHERE id = $1", [id]) }
2180
+ def transaction(attempts: 3, begin: "BEGIN", affinity: nil, &block)
2181
+ opening = binding.local_variable_get(:begin) # +begin+ is a keyword, so the local has no other name
2182
+ Skaidb.check_transaction_arguments(attempts, block_given?)
2183
+
2184
+ with(affinity: affinity) { |conn| conn.transaction(attempts: attempts, begin: opening, &block) }
2185
+ end
2186
+
1749
2187
  # The members as the pool sees them, for monitoring: one Hash each with
1750
2188
  # +:endpoint+ (what the pool dials), +:canonical+ (the member's own name,
1751
2189
  # once discovered), +:state+ (+:ready+, +:ejected+, +:resyncing+,
@@ -1887,6 +2325,17 @@ module Skaidb
1887
2325
  nil
1888
2326
  end
1889
2327
 
2328
+ # An idle connection its last borrower moved with a USE statement goes
2329
+ # back to the pool's +database:+ before it is handed out again; false
2330
+ # when that fails (the connection is then dropped). A pool without
2331
+ # +database:+ has no database to put it back in.
2332
+ def in_pool_database?(conn)
2333
+ conn.reenter_dial_database
2334
+ true
2335
+ rescue Error
2336
+ false
2337
+ end
2338
+
1890
2339
  def log(message)
1891
2340
  @logger&.warn("skaidb pool: #{message}")
1892
2341
  end