|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +module Mongo |
| 4 | + module Operation |
| 5 | + # Defines the behavior of operations that have the default timeout |
| 6 | + # behavior described by the client-side operation timeouts (CSOT) |
| 7 | + # spec. |
| 8 | + # |
| 9 | + # @api private |
| 10 | + module Timed |
| 11 | + # If a timeout is active (as defined by the current context), and it has |
| 12 | + # not yet expired, add :maxTimeMS to the spec. |
| 13 | + # |
| 14 | + # @param [ Hash ] spec The spec to modify |
| 15 | + # @param [ Connection ] connection The connection that will be used to |
| 16 | + # execute the operation |
| 17 | + # |
| 18 | + # @return [ Hash ] the spec |
| 19 | + # |
| 20 | + # @raises [ Mongo::Error::TimeoutError ] if the current timeout has |
| 21 | + # expired. |
| 22 | + def apply_relevant_timeouts_to(spec, connection) |
| 23 | + with_max_time(connection) do |max_time_sec| |
| 24 | + return spec if max_time_sec.nil? |
| 25 | + |
| 26 | + spec.tap { spec[:maxTimeMS] = (max_time_sec * 1_000).to_i } |
| 27 | + end |
| 28 | + end |
| 29 | + |
| 30 | + # A helper method that computes the remaining timeout (in seconds) and |
| 31 | + # yields it to the associated block. If no timeout is present, yields |
| 32 | + # nil. If the timeout has expired, raises Mongo::Error::TimeoutError. |
| 33 | + # |
| 34 | + # @param [ Connection ] connection The connection that will be used to |
| 35 | + # execute the operation |
| 36 | + # |
| 37 | + # @return [ Hash ] the result of yielding to the block (which must be |
| 38 | + # a Hash) |
| 39 | + def with_max_time(connection) |
| 40 | + if context&.has_timeout? |
| 41 | + max_time_sec = context.remaining_timeout_sec - connection.server.minimum_round_trip_time |
| 42 | + raise Mongo::Error::TimeoutError if max_time_sec <= 0 |
| 43 | + |
| 44 | + yield max_time_sec |
| 45 | + else |
| 46 | + yield nil |
| 47 | + end |
| 48 | + end |
| 49 | + end |
| 50 | + end |
| 51 | +end |
0 commit comments