skaidb 1.5.1 → 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
@@ -40,7 +40,7 @@ end
40
40
  module Skaidb
41
41
  # The package version — the single source of truth. The gemspec reads it,
42
42
  # and it is what the driver reports to the server in the Hello frame.
43
- VERSION = "1.5.1"
43
+ VERSION = "1.5.2"
44
44
 
45
45
  # Base class for every error raised by this driver.
46
46
  class Error < StandardError; end
@@ -778,6 +778,9 @@ module Skaidb
778
778
  "(tls_client_cert: and tls_client_key:)"
779
779
  end
780
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
781
784
  @closed = false
782
785
  # Transport died, and its socket is closed (see mark_broken!); the next
783
786
  # statement re-dials (see ensure_live!).
@@ -790,6 +793,11 @@ module Skaidb
790
793
  # The transaction helper is between its BEGIN and its COMMIT/ROLLBACK,
791
794
  # so a lost socket must not be re-dialled (see ensure_live!).
792
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
793
801
  # Statements prepared on this socket, SQL => [id, nparams]: the ones
794
802
  # the driver prepared for exec_params / exec_batch, least recently used
795
803
  # first, and the ones prepare_server handed to the application (see
@@ -804,22 +812,46 @@ module Skaidb
804
812
  @last_prepare_error = nil
805
813
  # The session database, as the USE target every dial re-enters: the one
806
814
  # 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).
815
+ # — a USE statement the server accepted moves it (see following).
808
816
  @dial_use = database.to_s.empty? ? nil : %("#{database.to_s.gsub('"', '""')}")
809
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
810
830
  # Retained so a reconnect repeats the original connect exactly.
811
831
  @dial_args = { host: host, port: port, user: user, password: password,
812
832
  timeout: timeout, database: database, tls: tls, tls_ca: tls_ca,
813
833
  tls_insecure: tls_insecure, tls_server_name: tls_server_name,
814
834
  seeds: seeds, tls_client_cert: tls_client_cert,
815
835
  tls_client_key: tls_client_key, endpoints: endpoints }
816
- 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
817
847
  end
818
848
 
819
- # Connect, authenticate and enter the session database. Used for the first
849
+ # Connect, authenticate and restore the session. Used for the first
820
850
  # connect and for every reconnect, so a recovered connection is
821
- # indistinguishable from a fresh one.
822
- 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)
823
855
  @serial = Skaidb.next_dial_serial
824
856
  host = @dial_args[:host]
825
857
  port = @dial_args[:port]
@@ -862,6 +894,10 @@ module Skaidb
862
894
  handshake(user.to_s, password.to_s)
863
895
  end
864
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
865
901
  last = nil
866
902
  break
867
903
  rescue StandardError => e
@@ -882,11 +918,41 @@ module Skaidb
882
918
  "no reachable endpoint in #{endpoints.map { |(h, q)| "#{h}:#{q}" }.join(', ')}: #{last.message}"
883
919
  end
884
920
  send_hello
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
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))
890
956
  end
891
957
 
892
958
  # Best-effort self-identification: fills the server's +drivers+ table
@@ -1060,6 +1126,13 @@ module Skaidb
1060
1126
  # Interrupt, a Timeout): the reply is still on its way, so nothing more
1061
1127
  # is written to that socket. Either way the socket is closed at once,
1062
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.
1063
1136
  # - A stream the block leaves open — an Enumerator from +stream+ advanced
1064
1137
  # with +next+ or +peek+ and not read to its end — sits in the middle of
1065
1138
  # its reply, so neither COMMIT nor ROLLBACK can be sent. The socket is
@@ -1080,11 +1153,37 @@ module Skaidb
1080
1153
  Skaidb.check_transaction_arguments(attempts, block_given?)
1081
1154
 
1082
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
1083
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
1084
1177
  begin
1085
1178
  attempt += 1
1086
1179
  committing = false
1087
- 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
1088
1187
  @in_transaction = true
1089
1188
  finished = false
1090
1189
  begin
@@ -1092,14 +1191,20 @@ module Skaidb
1092
1191
  finished = true
1093
1192
  ensure
1094
1193
  abandoned = abandon_open_stream
1095
- rollback_quietly unless finished
1194
+ over = true if !finished && rollback_quietly
1096
1195
  end
1097
1196
  if abandoned
1098
1197
  raise ConnectionError, "a stream opened inside the transaction was left open, so COMMIT could not " \
1099
1198
  "be sent: its session was dropped and nothing was committed"
1100
1199
  end
1101
1200
  committing = true
1102
- 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
1103
1208
  value
1104
1209
  rescue TransactionConflict
1105
1210
  # Only a refused COMMIT is run again; a conflict the block raised
@@ -1110,6 +1215,12 @@ module Skaidb
1110
1215
  retry
1111
1216
  ensure
1112
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
1113
1224
  end
1114
1225
  end
1115
1226
 
@@ -1182,116 +1293,148 @@ module Skaidb
1182
1293
  # Built before anything touches the socket, so a parameter that cannot
1183
1294
  # be bound is refused without a round trip (or a re-dial).
1184
1295
  req = stream_request(sql, params, level)
1185
- 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)
1186
1304
 
1187
1305
  live = false
1188
1306
  summary = nil
1189
1307
  sets = nil
1190
- @mutex.synchronize do
1191
- started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
1192
- begin
1193
- r = Reader.new(round_trip(req))
1194
- rescue ConnectionError
1195
- observe_failure
1196
- raise
1197
- end
1198
- @observer&.note_round_trip(self, Process.clock_gettime(Process::CLOCK_MONOTONIC) - started)
1199
- tag = r.u8
1200
- note_statement(sql) unless tag == 3
1201
- case tag
1202
- when 3
1203
- msg = r.text
1204
- if msg.include?("unknown opcode")
1205
- what = params.empty? ? "streaming" : "parameterised streaming (skaidb >= 0.330)"
1206
- raise QueryError, "server does not support #{what}: #{msg}"
1207
- end
1208
- raise Skaidb.statement_error(msg)
1209
- when 1
1210
- return Result.new(fields: [], rows: [], cmd_tuples: r.u64, kind: :mutation) # not row-producing
1211
- when 2
1212
- note_use(sql.to_s) if params.empty?
1213
- return Result.new(fields: [], rows: [], cmd_tuples: 0, kind: :ddl)
1214
- when 8
1215
- # ResultSets: a CALL whose body EMITted is answered with every set
1216
- # in ONE frame, streamed or not — the frame exec receives, decoded
1217
- # by the same code. Nothing follows it, so the rows are yielded
1218
- # below, with the connection free.
1219
- sets = parse_result_sets(r)
1220
- when 5
1221
- # The server has already committed to a row stream, so from here
1222
- # the socket carries frames this call owns — mark it BEFORE
1223
- # parsing the header, not after. `Reader#take` raises on a
1224
- # truncated or absurd column count, and a raise between the
1225
- # commitment and the flag skips the drain entirely: nothing sets
1226
- # `@broken`, `usable?` stays true, and the pool files a socket
1227
- # parked mid-reply back for the next caller, who reads a leftover
1228
- # chunk and gets "unknown response tag 6". That is the very
1229
- # desync the ensure below exists to prevent, reachable through a
1230
- # two-line window.
1231
- live = true
1232
- @streaming = true
1233
- @stream_fiber = Fiber.current
1234
- Skaidb.keep_stream_lock(@mutex)
1235
- cols = Array.new(r.u32) { r.text }
1236
- summary = Result.new(fields: cols, rows: [], cmd_tuples: 0, kind: :stream)
1237
- reading = false
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)
1238
1320
  begin
1239
- while live
1240
- reading = true
1241
- frame = read_frame
1242
- reading = false
1243
- fr = Reader.new(frame)
1244
- case fr.u8
1245
- when 6
1246
- fr.u32.times do
1247
- ncells = fr.u32
1248
- cells = Array.new(ncells) { Skaidb.decode_value(Reader.new(fr.blob)) }
1249
- yield cols.zip(cells).to_h
1250
- end
1251
- when 7
1252
- live = false
1253
- when 3
1254
- live = false
1255
- raise Skaidb.statement_error(fr.text)
1256
- else
1257
- # Mid-stream the server sends only RowsChunk, RowsEnd or Error.
1258
- # Anything else means we no longer know where the reply ends, so
1259
- # there is no draining back to a request boundary: retire it.
1260
- live = false
1261
- mark_broken!
1262
- raise QueryError, "unexpected frame in stream"
1263
- end
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}"
1264
1336
  end
1265
- ensure
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
1266
1361
  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!
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"
1396
+ end
1278
1397
  end
1279
1398
  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)
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)
1424
+ end
1289
1425
  end
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"
1290
1431
  end
1291
- else
1292
- raise QueryError, "unexpected response tag #{tag} to stream request"
1432
+ ensure
1433
+ mark_broken! unless placed
1293
1434
  end
1294
1435
  end
1436
+ return plain if plain
1437
+
1295
1438
  if sets
1296
1439
  # What exec's Result yields (the call's final result, the LAST set),
1297
1440
  # and that same Result back, every set under +result_sets+.
@@ -1341,7 +1484,6 @@ module Skaidb
1341
1484
  parse_response(reader)
1342
1485
  end
1343
1486
 
1344
- # Close the connection. Idempotent.
1345
1487
  # Yield a stream's events as they arrive, forever.
1346
1488
  #
1347
1489
  # A dependency-free helper over the stream's log: pages it with the
@@ -1382,6 +1524,7 @@ module Skaidb
1382
1524
  !@closed && !@broken && !@streaming
1383
1525
  end
1384
1526
 
1527
+ # Close the connection. Idempotent.
1385
1528
  def close
1386
1529
  return if @closed
1387
1530
 
@@ -1401,11 +1544,66 @@ module Skaidb
1401
1544
  @closed
1402
1545
  end
1403
1546
 
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
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
1409
1607
  end
1410
1608
 
1411
1609
  private
@@ -1436,19 +1634,66 @@ module Skaidb
1436
1634
  nil
1437
1635
  end
1438
1636
 
1439
- # Re-dial if the transport died since the last statement, BEFORE anything
1440
- # is prepared on it.
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).
1441
1670
  #
1442
1671
  # The prepared-statement cache MUST be cleared: an id is only valid on the
1443
1672
  # connection that created it, so carrying one across a reconnect would run
1444
1673
  # a different statement (or fail obscurely).
1445
- def ensure_live!
1674
+ def ensure_live!(entering: false)
1446
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
1447
1684
  return unless @broken
1448
1685
  # A transaction lives on the socket that carried its BEGIN. Re-dialling
1449
1686
  # inside the helper would run the rest of the block, and the COMMIT, on
1450
1687
  # a new session with no transaction open: each statement autocommitted.
1451
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
1452
1697
 
1453
1698
  @prepared.clear
1454
1699
  @held.clear
@@ -1458,12 +1703,13 @@ module Skaidb
1458
1703
  nil
1459
1704
  end
1460
1705
  @sock = nil
1461
- # Cleared BEFORE dialling: dial! issues USE, which runs a statement and
1462
- # 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!.)
1463
1709
  @broken = false
1464
1710
  dialled = false
1465
1711
  begin
1466
- dial!
1712
+ dial!(enter: !entering)
1467
1713
  dialled = true
1468
1714
  ensure
1469
1715
  # Still down, so the next statement retries — or the dial was cut
@@ -1622,15 +1868,15 @@ module Skaidb
1622
1868
  sql_bytes = sql.dup.force_encoding("UTF-8").b
1623
1869
  req = [2].pack("C") + [sql_bytes.bytesize].pack("V") + sql_bytes
1624
1870
  reader = request(req)
1625
- tag = reader.u8
1871
+ tag = reading_reply { reader.u8 }
1626
1872
  case tag
1627
1873
  when 4
1628
- id = (@serial << 32) | reader.u32
1629
- nparams = reader.u16
1874
+ number, nparams = reading_reply { [reader.u32, reader.u16] }
1875
+ id = (@serial << 32) | number
1630
1876
  @handles[id] = sql if hold
1631
1877
  (hold ? @held : @prepared)[sql] = [id, nparams]
1632
1878
  when 3
1633
- msg = reader.text
1879
+ msg = reading_reply { reader.text }
1634
1880
  raise Skaidb.statement_error(msg) if msg.start_with?("too many prepared statements")
1635
1881
 
1636
1882
  # Refused: DDL/session statements cannot be prepared, and an old
@@ -1638,6 +1884,7 @@ module Skaidb
1638
1884
  @last_prepare_error = msg
1639
1885
  nil
1640
1886
  else
1887
+ mark_broken! # not a reply to a prepare: what follows it cannot be placed
1641
1888
  raise QueryError, "unexpected prepare response tag #{tag}"
1642
1889
  end
1643
1890
  end
@@ -1672,10 +1919,18 @@ module Skaidb
1672
1919
  # replace what the block left with. Not sent on a connection that is not
1673
1920
  # usable — its socket died, or was left in the middle of a reply: the
1674
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.
1675
1925
  def rollback_quietly
1676
- exec("ROLLBACK") if usable?
1926
+ return false unless usable?
1927
+
1928
+ exec("ROLLBACK")
1929
+ true
1930
+ rescue QueryError
1931
+ true
1677
1932
  rescue StandardError
1678
- nil
1933
+ false
1679
1934
  end
1680
1935
 
1681
1936
  # Internal: raised into the Fiber of a stream the transaction helper's
@@ -1722,39 +1977,164 @@ module Skaidb
1722
1977
 
1723
1978
  def run(sql, consistency)
1724
1979
  raise ConnectionError, "connection is closed" if @closed
1725
- ensure_live!
1980
+ change = session_change(sql)
1981
+ ended = end_lost_transaction(change)
1982
+ return ended if ended
1726
1983
 
1984
+ ensure_live!(entering: !change.nil? && change[0] == :use)
1727
1985
  sql_bytes = sql.dup.force_encoding("UTF-8").b
1728
1986
  req = [1, consistency].pack("CC") + [sql_bytes.bytesize].pack("V") + sql_bytes
1729
- reader = request(req)
1730
- res = parse_response(reader)
1731
- note_statement(sql)
1732
- note_use(sql)
1733
- res
1987
+ following(change) do
1988
+ res = parse_response(request(req))
1989
+ note_statement(sql)
1990
+ res
1991
+ end
1734
1992
  end
1735
1993
 
1736
1994
  # +USE [DATABASE] <name>+ with an optional +;+ — the name bare, or in
1737
1995
  # double quotes with "" for a quote inside.
1738
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
1739
2009
  # A +--+ comment, which the server skips to the end of its line — or a
1740
2010
  # double-quoted name or single-quoted string, inside which two dashes are
1741
2011
  # not a comment (an unclosed quote runs to the end of the text).
1742
2012
  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)
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)
1753
2034
  text = sql.gsub(COMMENT_OR_QUOTED) { |part| part.start_with?("--") ? "" : part }
1754
- m = USE_STATEMENT.match(text)
1755
- @session_use = m[1] if m
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
1756
2041
  rescue ArgumentError, EncodingError
1757
- nil # bytes the pattern cannot read
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)
1758
2138
  end
1759
2139
 
1760
2140
  # The request +stream+ sends. Without parameters: OP_QUERY_STREAM with
@@ -1824,21 +2204,40 @@ module Skaidb
1824
2204
  end
1825
2205
 
1826
2206
  def parse_response(r)
1827
- tag = r.u8
1828
- case tag
1829
- when 0 # Rows
1830
- parse_rows(r)
1831
- when 8 # ResultSets: a CALL whose body EMITted
1832
- parse_result_sets(r)
1833
- when 1 # Mutation
1834
- Result.new(fields: [], rows: [], cmd_tuples: r.u64, kind: :mutation)
1835
- when 2 # Ddl
1836
- Result.new(fields: [], rows: [], cmd_tuples: 0, kind: :ddl)
1837
- when 3 # Error — a statement error, connection stays usable
1838
- raise Skaidb.statement_error(r.text)
1839
- else
1840
- 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
1841
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
1842
2241
  end
1843
2242
 
1844
2243
  # A Rows body (PROTOCOL.md §3.2), also one set of ResultSets; +r+ sits
@@ -1954,6 +2353,12 @@ module Skaidb
1954
2353
  # starting members, and the rest (TLS, the session database, ...) apply to
1955
2354
  # every connection.
1956
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
+ #
1957
2362
  # Load balancing (PROTOCOL.md §6.1, the same in every skaidb driver; see
1958
2363
  # docs/pooling.md):
1959
2364
  #
@@ -2120,12 +2525,10 @@ module Skaidb
2120
2525
  close_quietly(conn)
2121
2526
  next
2122
2527
  end
2123
- elsif !conn.usable?
2124
- # A connection the server closed while it sat idle still looks
2125
- # fine locally, so check before handing it out.
2126
- close_quietly(conn)
2127
- next
2128
- elsif !in_pool_database?(conn)
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.
2129
2532
  close_quietly(conn)
2130
2533
  next
2131
2534
  end
@@ -2141,21 +2544,31 @@ module Skaidb
2141
2544
 
2142
2545
  # Return a connection, closing it if it is broken, its member is ejected
2143
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.
2144
2554
  def checkin(conn)
2145
- keep = @mutex.synchronize do
2555
+ keep = false
2556
+ wanted = @mutex.synchronize do
2146
2557
  if conn.pool_out
2147
2558
  conn.pool_out = false
2148
2559
  counted = @members[conn.pool_member]
2149
2560
  counted.in_use -= 1 if counted && counted.in_use.positive?
2150
2561
  end
2151
- m = @members[conn.pool_member]
2152
- if !@closed && conn.usable? && m && usable?(m) && @idle.length < @maxsize
2153
- @idle.push(conn)
2154
- true
2155
- else
2156
- false
2157
- end
2562
+ keepable?(conn)
2158
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
2159
2572
  close_quietly(conn) unless keep
2160
2573
  end
2161
2574
 
@@ -2325,15 +2738,12 @@ module Skaidb
2325
2738
  nil
2326
2739
  end
2327
2740
 
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
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
2337
2747
  end
2338
2748
 
2339
2749
  def log(message)