service_mesh_nats 0.7.1 → 0.9.0

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 78b85ee6f66b79299112123dd686fc035341e64d014e4d3ea8e65d51c3adb501
4
- data.tar.gz: e6628c26d3986a64748e139186950833617631bab6c5902885b30b82fe674d2a
3
+ metadata.gz: 45e8d3352cc574ebf97228c0e7a7fccc8e35b8aa5c51a9ad6c807039b60b7b27
4
+ data.tar.gz: 7d236c8f5f5c7a113c01be8902e7023507d94312d05f6105f34b9be701d7e460
5
5
  SHA512:
6
- metadata.gz: ae7c3c84a34f9706df0e487b7de27822c326df44cf7715ddf1507483ad739971555d934dc4302a4bd3e888bafb53ebb6460d63b4ca93792bd62d0c7f76ab8279
7
- data.tar.gz: f0aae96d9e018be5205fa7a8468ec2ed288d7b8dc695b7ef8e8af6c2582ec95583d44a943614280de060369db706e79e298280f2b20c4898910407e3f08f326e
6
+ metadata.gz: 50754880b109a293ec9ccc5f35fe4c3fb15493c2a920affeb714021bd15dca4b884cb51f4f64f73b3b602f83840b293feefac61d13e7583ac9b855c125fb9dc8
7
+ data.tar.gz: 4b4d25551c600b7de8d3db05252b8181a24565f4a2dcabf1410d81de9cf33cc316781296f694c06559d82220f64d072898233bb0890548229d0711a88445e319
data/README.md CHANGED
@@ -1,14 +1,21 @@
1
1
  # service-mesh-nats-ruby
2
2
 
3
+ This library implements the Service Mesh API Specification v0.5.0.
4
+
5
+ This library implements the Service Mesh NATS API Specification v0.3.0.
6
+
3
7
  service-mesh-nats-ruby is the Ruby implementation of the
4
8
  [Service Mesh API Specification](https://github.com/Paymentbox-com/service-mesh-api)
5
- over NATS. It implements the Ruby contract in the `service_mesh` gem, from
9
+ over NATS, following the
10
+ [Service Mesh NATS API Specification](https://github.com/Paymentbox-com/service-mesh-nats-api).
11
+ It implements the Ruby contract in the `service_mesh` gem, from
6
12
  [service-mesh-ruby](https://github.com/Paymentbox-com/service-mesh-ruby), on
7
13
  top of the `nats-pure` client.
8
14
 
9
15
  The `ServiceMeshNats` module provides:
10
16
  * `Client`, which implements the contract's `Client` over one NATS connection
11
17
  * `Runtime`, which implements the contract's `Runtime` on a `Client`'s connection
18
+ * `Receiver`, which inspects an endpoint or subscriber the runtime is running
12
19
  * the configuration keys it reads
13
20
  * the errors it defines
14
21
 
@@ -23,7 +30,7 @@ come from the `service_mesh` gem.
23
30
  gem "service_mesh_nats"
24
31
  ```
25
32
 
26
- Requires Ruby 3.3 or newer and a reachable NATS server. The gem depends on
33
+ The gem needs Ruby 3.3 or newer and a reachable NATS server. It depends on
27
34
  `service_mesh` and `nats-pure`.
28
35
 
29
36
  ## Usage
@@ -68,6 +75,7 @@ builds a client itself and calls `close` when done. `runtime.service_map` and
68
75
  ## Documentation
69
76
 
70
77
  - [Examples](docs/examples.md): a server process, a call-only client process, and consumer groups
71
- - [Public API](docs/public-api.md): every public constant and method in `ServiceMeshNats`
72
- - [Transport Specific Implementation](docs/transport-specific-implementation.md): subjects, configuration, metadata, delivery, handler failure, timeouts, concurrency, lifecycle, and errors
78
+ - [Public API](docs/public-api.md): the constants and methods in `ServiceMeshNats` that applications use
79
+ - [Transport Specific Implementation](docs/transport-specific-implementation.md): subjects, configuration, settings, metadata, delivery, handler failure, timeouts, concurrency, lifecycle, logging, and errors
80
+ - [JetStream](docs/jetstream.md): publishing to streams, consuming through consumers, their options, and inspecting streams and consumers
73
81
  - [Development](docs/development.md): the recipes and the tests
@@ -19,9 +19,12 @@ module ServiceMeshNats
19
19
  @service_map = service_map
20
20
  @lock = Mutex.new
21
21
  @closed = false
22
- @nc = NATS::IO::Client.new
23
- @nc.on_error { |e| logger.warn("service_mesh_nats: #{e.class}: #{e.message}") } if logger
24
- @nc.connect(@settings.connect_options)
22
+ @connection = NATS::IO::Client.new
23
+ if logger
24
+ @connection.on_error { |error| logger.warn(Log.line("connection error", error: "#{error.class}: #{error.message}")) }
25
+ end
26
+ @connection.connect(@settings.connect_options)
27
+ @jetstream = @connection.jetstream
25
28
  end
26
29
 
27
30
  # Closes the connection and marks the client closed. Returns nil.
@@ -30,52 +33,133 @@ module ServiceMeshNats
30
33
  @lock.synchronize do
31
34
  return nil if @closed
32
35
 
33
- @nc.close
36
+ @connection.close
34
37
  @closed = true
35
38
  end
36
39
  nil
37
40
  end
38
41
 
39
- # The NATS::IO::Client this client owns. Used by Runtime. Raises Closed
40
- # after close.
42
+ # The NATS::IO::Client this client owns. Raises Closed after close.
41
43
  def connection
42
44
  raise Closed if @closed
43
45
 
44
- @nc
46
+ @connection
47
+ end
48
+
49
+ # The NATS::JetStream context this client publishes with. Raises Closed
50
+ # after close.
51
+ def jetstream
52
+ raise Closed if @closed
53
+
54
+ @jetstream
55
+ end
56
+
57
+ # The NATS::JetStream::API::StreamInfo of the stream named by +target+'s
58
+ # STREAM_KEY metadata, or nil when it has none, which is so for every
59
+ # route target. It names the stream a publish to +target+ uses when no
60
+ # per-call option overrides it. Raises Closed after close, and nats-pure's
61
+ # error unchanged when the lookup fails.
62
+ def stream_info(target)
63
+ name = target.metadata.to_h[STREAM_KEY].to_s
64
+ return nil if name.empty?
65
+
66
+ jetstream.stream_info(name)
67
+ end
68
+
69
+ # The configured REQUEST_TIMEOUT_KEY in seconds. The runtime bounds the
70
+ # wait for a double ack's confirmation with it.
71
+ def request_timeout
72
+ @settings.request_timeout
45
73
  end
46
74
 
47
75
  # Sends +message+ to a route target and returns the reply.
48
76
  #
49
- # +opts+ may carry REQUEST_TIMEOUT_KEY to override the configured request
50
- # timeout for this call. Expiry raises NATS::Timeout; no receiver raises
77
+ # Settings are read from +options+, then the target's metadata, then the
78
+ # client's config. The request's deadline is REQUEST_TIMEOUT_KEY from
79
+ # now, or +deadline+, a Time, when that comes first. STREAM_KEY, or a
80
+ # REQUEST_TIMEOUT_KEY no more than DEADLINE_OFFSET_KEY, raises
81
+ # InvalidRequest. Expiry raises NATS::Timeout, and no receiver raises
51
82
  # NATS::IO::NoRespondersError.
52
- def request(message, opts = {})
53
- Subject.check_kind!(message.target, :route, "request")
54
- subject = Subject.format(message.target)
55
- timeout = Settings.duration(opts.to_h, REQUEST_TIMEOUT_KEY, @settings.request_timeout)
56
- nc = connection
83
+ #
84
+ # A request whose time left is no more than DEADLINE_OFFSET_KEY, because
85
+ # +deadline+ leaves too little, raises NATS::Timeout without being sent,
86
+ # because its handler's deadline would fall before the request reached
87
+ # it. This happens when a handler passes its own deadline down a chain of
88
+ # requests, after work done before the call, and across retries under one
89
+ # deadline.
90
+ #
91
+ # The request carries ServiceMesh::TIMEOUT_KEY, set to the time left in
92
+ # whole milliseconds, and ServiceMesh::DEADLINE_OFFSET_KEY, set to
93
+ # DEADLINE_OFFSET_KEY. ServiceMesh::MESSAGE_ID_KEY is copied to
94
+ # Nats-Msg-Id.
95
+ def request(message, options = {}, deadline: nil)
96
+ Target.check_kind!(message.target, :route, "request")
97
+ subject = Target.subject(message.target)
98
+ settings = Target.merge_settings(message.target, options)
99
+ unless settings[STREAM_KEY].to_s.empty?
100
+ raise InvalidRequest, "#{STREAM_KEY}=#{settings[STREAM_KEY].inspect} applies to topic targets only"
101
+ end
102
+ timeout = Config.duration(settings, REQUEST_TIMEOUT_KEY, @settings.request_timeout)
103
+ offset = Config.offset(settings, DEADLINE_OFFSET_KEY, @settings.deadline_offset)
104
+ if timeout <= offset
105
+ raise InvalidRequest, "#{REQUEST_TIMEOUT_KEY}=#{ms(timeout)} is no more than #{DEADLINE_OFFSET_KEY}=#{ms(offset)}"
106
+ end
107
+ nats_connection = connection
108
+
109
+ wait = timeout
110
+ wait = (deadline - Time.now).clamp(0, timeout) if deadline
111
+ outgoing = message.with(metadata: message.metadata.merge(
112
+ ServiceMesh::TIMEOUT_KEY => ms(wait).to_s,
113
+ ServiceMesh::DEADLINE_OFFSET_KEY => ms(offset).to_s
114
+ ))
115
+ if outgoing.expired?
116
+ raise NATS::Timeout, "#{ms(wait)}ms left is no more than #{DEADLINE_OFFSET_KEY}=#{ms(offset)}"
117
+ end
57
118
 
58
- reply = nc.request_msg(nats_msg(subject, message), timeout: timeout)
119
+ reply = nats_connection.request_msg(nats_msg(subject, outgoing), timeout: wait)
59
120
  header = reply.header || {}
60
- raise HandlerError.new(header[HANDLER_ERROR_HEADER].to_s) if header.key?(HANDLER_ERROR_HEADER)
121
+ raise HandlerError.new(header[ServiceMesh::HANDLER_ERROR_KEY].to_s) if header.key?(ServiceMesh::HANDLER_ERROR_KEY)
61
122
 
62
123
  ServiceMesh::Message.new(target: message.target, metadata: header, payload: reply.data.to_s)
63
124
  end
64
125
 
65
- # Sends +message+ to a topic target. +opts+ is accepted for the interface
66
- # and not read.
67
- def publish(message, opts = {})
68
- Subject.check_kind!(message.target, :topic, "publish")
69
- subject = Subject.format(message.target)
70
- connection.publish_msg(nats_msg(subject, message))
126
+ # Sends +message+ to a topic target. ServiceMesh::MESSAGE_ID_KEY is copied
127
+ # to Nats-Msg-Id.
128
+ #
129
+ # Settings are read from +options+, then the target's metadata, then the
130
+ # client's config. When they carry STREAM_KEY, the message goes out as a
131
+ # JetStream publish that expects that stream, and publish waits for the
132
+ # stream's ack, bounded by REQUEST_TIMEOUT_KEY. nats-pure's errors pass
133
+ # through unchanged. They include NATS::Timeout on expiry,
134
+ # NATS::JetStream::Error::NoStreamResponse when no stream takes the
135
+ # subject, and NATS::JetStream::Error::APIError when the stream refuses the
136
+ # message.
137
+ def publish(message, options = {})
138
+ Target.check_kind!(message.target, :topic, "publish")
139
+ subject = Target.subject(message.target)
140
+ settings = Target.merge_settings(message.target, options)
141
+ stream = settings[STREAM_KEY].to_s
142
+ msg = nats_msg(subject, message)
143
+ if stream.empty?
144
+ connection.publish_msg(msg)
145
+ return nil
146
+ end
147
+
148
+ timeout = Config.duration(settings, REQUEST_TIMEOUT_KEY, @settings.request_timeout)
149
+ jetstream.publish(subject, msg.data, header: msg.header, stream: stream, timeout: timeout)
71
150
  nil
72
151
  end
73
152
 
74
153
  private
75
154
 
155
+ # +seconds+ in whole milliseconds, rounded down.
156
+ def ms(seconds)
157
+ (seconds * 1000).floor
158
+ end
159
+
160
+ # The NATS message for +message+, with its metadata as the header.
76
161
  def nats_msg(subject, message)
77
- header = message.metadata.empty? ? nil : message.metadata.transform_keys(&:to_s).transform_values(&:to_s)
78
- NATS::Msg.new(subject: subject, data: message.payload, header: header)
162
+ NATS::Msg.new(subject: subject, data: message.payload, header: Header.outgoing_header(message.metadata))
79
163
  end
80
164
  end
81
165
  end
@@ -0,0 +1,194 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "etc"
4
+
5
+ module ServiceMeshNats
6
+ # Configuration keys this transport reads beyond ServiceMesh::DEPLOYMENT_GROUP_KEY.
7
+ # Every value is a string. Durations are whole numbers of milliseconds, such
8
+ # as "5000" or "250".
9
+ # The server URL, or a comma-separated list of them.
10
+ URL_KEY = "url"
11
+ NAME_KEY = "name"
12
+ CONNECT_TIMEOUT_KEY = "connect_timeout"
13
+ REQUEST_TIMEOUT_KEY = "request_timeout"
14
+ # How much earlier than the caller's deadline the handler's deadline falls,
15
+ # in whole milliseconds, or "0". Sent on each request as
16
+ # ServiceMesh::DEADLINE_OFFSET_KEY. Default "0". It must be less than
17
+ # REQUEST_TIMEOUT_KEY. It is also a request setting.
18
+ DEADLINE_OFFSET_KEY = "deadline_offset"
19
+ CONCURRENCY_KEY = "concurrency"
20
+ # The most times one JetStream message is delivered, as a positive integer.
21
+ # In a runtime's config it is the default for subscribers that do not set
22
+ # it. It is also a subscriber setting.
23
+ MAX_DELIVER_KEY = "max_deliver"
24
+
25
+ # JetStream settings, read from an Endpoint's or Subscriber's metadata over
26
+ # its Target's metadata, and from a call's options over its Target's
27
+ # metadata. Every key but STREAM_KEY is read only from a Subscriber that
28
+ # sets STREAM_KEY.
29
+ #
30
+ # The stream name. A Subscriber consumes from a consumer on it, and a
31
+ # publish waits for its ack. On an Endpoint it is BadConfig, and on a
32
+ # request it is InvalidRequest.
33
+ STREAM_KEY = "stream"
34
+ # "true" or "false". "false" leaves a named consumer group's consumer to be
35
+ # created outside the runtime.
36
+ CREATE_CONSUMER_KEY = "create_consumer"
37
+ # "double", "explicit", or "none".
38
+ ACK_POLICY_KEY = "ack_policy"
39
+ # Milliseconds the server waits for an ack before it sends a message again.
40
+ # Ignored when BACKOFF_KEY is set.
41
+ ACK_WAIT_KEY = "ack_wait"
42
+ # Comma-separated milliseconds, one for each delivery in turn, that set how
43
+ # long the server waits for an ack before it sends the message again.
44
+ # Deliveries past the end of the list use its last entry. The server sets
45
+ # the consumer's ack wait to the first entry. MAX_DELIVER_KEY must exceed
46
+ # its length.
47
+ BACKOFF_KEY = "backoff"
48
+ # Milliseconds the server waits before it sends a failed message again.
49
+ NAK_DELAY_KEY = "nak_delay"
50
+ # The most unacked messages the consumer allows at once.
51
+ MAX_ACK_PENDING_KEY = "max_ack_pending"
52
+ # "all" or "new", where a newly created consumer starts.
53
+ DELIVER_POLICY_KEY = "deliver_policy"
54
+ # Milliseconds a consumer outlives its last puller.
55
+ CONSUMER_INACTIVE_THRESHOLD_KEY = "consumer_inactive_threshold"
56
+ # Milliseconds the server keeps a pull open while it has nothing to send. At
57
+ # least 1000. Also a runtime config key, where it is the default for
58
+ # subscribers that do not set it.
59
+ PULL_EXPIRY_KEY = "pull_expiry"
60
+ # Milliseconds between the server's heartbeats on an open pull that has
61
+ # nothing to send. From 500 to 30000, and no more than half of
62
+ # PULL_EXPIRY_KEY. Two missed heartbeats make the subscriber pull again.
63
+ # Also a runtime config key, where it is the default for subscribers that
64
+ # do not set it.
65
+ PULL_HEARTBEAT_KEY = "pull_heartbeat"
66
+
67
+ # Metadata keys the runtime adds to each JetStream delivery it hands to a
68
+ # handler, from the delivery's JetStream metadata.
69
+ STREAM_METADATA_KEY = "Mesh-Nats-Stream"
70
+ CONSUMER_METADATA_KEY = "Mesh-Nats-Consumer"
71
+ STREAM_SEQUENCE_METADATA_KEY = "Mesh-Nats-Stream-Sequence"
72
+ CONSUMER_SEQUENCE_METADATA_KEY = "Mesh-Nats-Consumer-Sequence"
73
+ NUM_PENDING_METADATA_KEY = "Mesh-Nats-Num-Pending"
74
+ TIMESTAMP_METADATA_KEY = "Mesh-Nats-Timestamp"
75
+
76
+ DEFAULT_URL = "nats://127.0.0.1:4222"
77
+ DEFAULT_CONNECT_TIMEOUT = 5.0
78
+ DEFAULT_REQUEST_TIMEOUT = 30.0
79
+ DEFAULT_MAX_DELIVER = 5
80
+ NAMED_INACTIVE_THRESHOLD = 7 * 24 * 60 * 60.0
81
+ ORDERED_INACTIVE_THRESHOLD = 5 * 60.0
82
+ DEFAULT_PULL_EXPIRY = 30.0
83
+
84
+ # Value parsers shared by the settings types.
85
+ module Config
86
+ # The format of every duration value: a whole number of milliseconds
87
+ # above 0, with no sign, unit, or leading zero.
88
+ POSITIVE_MILLISECONDS = /\A[1-9][0-9]*\z/
89
+
90
+ # Reads +key+ as a positive whole number of milliseconds and returns it in
91
+ # seconds, as a Rational, or returns +fallback+ when absent.
92
+ def self.duration(hash, key, fallback)
93
+ return fallback unless hash.key?(key)
94
+
95
+ value = hash[key].to_s
96
+ unless POSITIVE_MILLISECONDS.match?(value)
97
+ raise BadConfig, "#{key}=#{hash[key].inspect} must be a positive whole number of milliseconds such as \"5000\""
98
+ end
99
+
100
+ Rational(value.to_i, 1000)
101
+ end
102
+
103
+ # Reads +key+ as "0" or a positive whole number of milliseconds and
104
+ # returns it in seconds, or returns +fallback+ when absent.
105
+ def self.offset(hash, key, fallback)
106
+ return fallback unless hash.key?(key)
107
+ return 0 if hash[key].to_s == "0"
108
+ return Rational(hash[key].to_s.to_i, 1000) if POSITIVE_MILLISECONDS.match?(hash[key].to_s)
109
+
110
+ raise BadConfig, "#{key}=#{hash[key].inspect} must be a whole number of milliseconds such as \"0\" or \"50\""
111
+ end
112
+
113
+ def self.positive_integer(hash, key, fallback)
114
+ return fallback unless hash.key?(key)
115
+
116
+ value = Integer(hash[key], 10, exception: false)
117
+ raise BadConfig, "#{key}=#{hash[key].inspect} must be a positive integer" if value.nil? || value <= 0
118
+
119
+ value
120
+ end
121
+
122
+ # Reads +key+ as one of the strings in +allowed+, or returns the first of
123
+ # them when absent.
124
+ def self.choice(hash, key, allowed)
125
+ return allowed.first unless hash.key?(key)
126
+ return hash[key] if allowed.include?(hash[key])
127
+
128
+ raise BadConfig, "#{key}=#{hash[key].inspect} must be one of #{allowed.map(&:inspect).join(", ")}"
129
+ end
130
+
131
+ # Reads +key+ as a comma-separated list of positive whole numbers of
132
+ # milliseconds and returns them in seconds, as Rationals, or returns nil
133
+ # when absent.
134
+ def self.durations(hash, key)
135
+ return nil unless hash.key?(key)
136
+
137
+ hash[key].to_s.split(",", -1).map do |part|
138
+ value = part.strip
139
+ unless POSITIVE_MILLISECONDS.match?(value)
140
+ raise BadConfig, "#{key}=#{hash[key].inspect} must be a comma-separated list of positive whole numbers of milliseconds, such as \"1000,5000\""
141
+ end
142
+
143
+ Rational(value.to_i, 1000)
144
+ end
145
+ end
146
+ end
147
+
148
+ # The keys a Client reads. Any other key is ignored.
149
+ ClientSettings = Data.define(:url, :name, :connect_timeout, :request_timeout, :deadline_offset) do
150
+ def self.parse(config)
151
+ config = config.to_h
152
+ request_timeout = Config.duration(config, REQUEST_TIMEOUT_KEY, DEFAULT_REQUEST_TIMEOUT)
153
+ deadline_offset = Config.offset(config, DEADLINE_OFFSET_KEY, 0)
154
+ if deadline_offset >= request_timeout
155
+ raise BadConfig, "#{DEADLINE_OFFSET_KEY}=#{config[DEADLINE_OFFSET_KEY].inspect} must be less than " \
156
+ "#{REQUEST_TIMEOUT_KEY}=#{(request_timeout * 1000).to_i.to_s.inspect}"
157
+ end
158
+ new(
159
+ url: config.fetch(URL_KEY, DEFAULT_URL).then { |url| url.to_s.empty? ? DEFAULT_URL : url },
160
+ name: config[NAME_KEY],
161
+ connect_timeout: Config.duration(config, CONNECT_TIMEOUT_KEY, DEFAULT_CONNECT_TIMEOUT),
162
+ request_timeout: request_timeout,
163
+ deadline_offset: deadline_offset
164
+ )
165
+ end
166
+
167
+ def connect_options
168
+ options = {servers: url.split(",").map(&:strip), connect_timeout: connect_timeout}
169
+ options[:name] = name if name && !name.empty?
170
+ options
171
+ end
172
+ end
173
+
174
+ # The keys a Runtime reads. Connection keys in a runtime's config are
175
+ # ignored, because the runtime's client carries them.
176
+ #
177
+ # +pull_expiry+ and +pull_heartbeat+ are nil when the config does not set
178
+ # them.
179
+ RuntimeSettings = Data.define(:deployment_group, :concurrency, :max_deliver, :pull_expiry, :pull_heartbeat) do
180
+ def self.parse(config)
181
+ config = config.to_h
182
+ deployment_group = config[ServiceMesh::DEPLOYMENT_GROUP_KEY].to_s
183
+ raise ServiceMesh::NoDeploymentGroup if deployment_group.empty?
184
+
185
+ new(
186
+ deployment_group: deployment_group,
187
+ concurrency: Config.positive_integer(config, CONCURRENCY_KEY, Etc.nprocessors),
188
+ max_deliver: Config.positive_integer(config, MAX_DELIVER_KEY, DEFAULT_MAX_DELIVER),
189
+ pull_expiry: Config.duration(config, PULL_EXPIRY_KEY, nil),
190
+ pull_heartbeat: Config.duration(config, PULL_HEARTBEAT_KEY, nil)
191
+ )
192
+ end
193
+ end
194
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ServiceMeshNats
4
+ # A JetStream subscriber's consumer as the server describes it. acks is
5
+ # false for a consumer that acks nothing. ack_wait is seconds, and backoff
6
+ # is a list of seconds or nil. max_deliver is -1 when deliveries are
7
+ # unlimited.
8
+ Consumer = Data.define(:stream, :name, :acks, :ack_wait, :backoff, :max_deliver) do
9
+ # When the server sends a delivery again unless it is acked. That is its
10
+ # arrival plus its backoff entry when the consumer has backoff, and the
11
+ # consumer's ack_wait otherwise. Deliveries past the end of the backoff
12
+ # list use its last entry.
13
+ def deadline(arrival, delivered)
14
+ return arrival + ack_wait unless backoff&.any?
15
+
16
+ arrival + backoff[[delivered - 1, backoff.length - 1].min]
17
+ end
18
+
19
+ # Whether delivery number +delivered+ is the last one the server sends.
20
+ # A max_deliver of -1 means no limit, so no delivery is the last.
21
+ def last_delivery?(delivered)
22
+ max_deliver.positive? && delivered >= max_deliver
23
+ end
24
+ end
25
+ private_constant :Consumer
26
+ end
@@ -0,0 +1,113 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "nats/io/client"
5
+
6
+ module ServiceMeshNats
7
+ # Creates and looks up JetStream consumers with the server's API directly,
8
+ # so durations travel in nanoseconds. nats-pure's own consumer calls take
9
+ # ack_wait and inactive_threshold in whole seconds and read them back
10
+ # rounded down, which would lose fractional settings and make
11
+ # ServiceMesh::DEADLINE_KEY early.
12
+ #
13
+ # The errors are nats-pure's. They are
14
+ # NATS::JetStream::Error::ServiceUnavailable when JetStream does not answer,
15
+ # and the NATS::JetStream::Error::APIError subclass nats-pure raises for each
16
+ # error the server returns.
17
+ module ConsumerAPI
18
+ API_PREFIX = "$JS.API"
19
+ API_TIMEOUT = 5.0
20
+ NANOSECONDS = 1_000_000_000
21
+
22
+ # Creates the consumer +name+ on +stream+ from +config+, a
23
+ # JetStreamSettings#consumer_config, or updates it when +update+ is true
24
+ # and it exists. Returns the Consumer the server reports.
25
+ def self.create(connection, stream, name, config, update:)
26
+ body = {stream_name: stream, config: wire_config(config.merge(name: name))}
27
+ body[:action] = "create" unless update
28
+ subject = "#{API_PREFIX}.CONSUMER.CREATE.#{stream}.#{name}.#{config.fetch(:filter_subject)}"
29
+ consumer(request(connection, subject, body.to_json))
30
+ end
31
+
32
+ # Looks up the consumer +name+ on +stream+.
33
+ def self.info(connection, stream, name)
34
+ consumer(request(connection, "#{API_PREFIX}.CONSUMER.INFO.#{stream}.#{name}", ""))
35
+ end
36
+
37
+ # Deletes +consumer+, a Consumer opened for the subscriber with
38
+ # JetStreamSettings +settings+. Raises ArgumentError unless the
39
+ # subscriber uses an ordered consumer, which belongs to one instance, so
40
+ # a consumer shared by a named group is never deleted.
41
+ def self.delete(connection, consumer, settings)
42
+ raise ArgumentError, "only an ordered consumer is deleted, not #{consumer.name}" unless settings.ordered?
43
+
44
+ request(connection, "#{API_PREFIX}.CONSUMER.DELETE.#{consumer.stream}.#{consumer.name}", "")
45
+ nil
46
+ end
47
+
48
+ # The config as the server takes it, with durations in nanoseconds.
49
+ def self.wire_config(config)
50
+ config.to_h do |key, value|
51
+ case key
52
+ when :ack_wait, :inactive_threshold then [key, nanoseconds(value)]
53
+ when :backoff then [key, value.map { |seconds| nanoseconds(seconds) }]
54
+ else [key, value]
55
+ end
56
+ end
57
+ end
58
+
59
+ def self.nanoseconds(seconds)
60
+ (seconds * NANOSECONDS).round
61
+ end
62
+
63
+ def self.consumer(result)
64
+ config = result.fetch(:config)
65
+ Consumer.new(
66
+ stream: result.fetch(:stream_name),
67
+ name: result.fetch(:name),
68
+ acks: config[:ack_policy] != "none",
69
+ ack_wait: config[:ack_wait] && Rational(config[:ack_wait], NANOSECONDS),
70
+ backoff: config[:backoff]&.map { |duration| Rational(duration, NANOSECONDS) },
71
+ max_deliver: config.fetch(:max_deliver, -1)
72
+ )
73
+ end
74
+
75
+ def self.request(connection, subject, body)
76
+ reply = begin
77
+ connection.request(subject, body, timeout: API_TIMEOUT)
78
+ rescue NATS::IO::NoRespondersError
79
+ raise NATS::JetStream::Error::ServiceUnavailable
80
+ end
81
+ result = JSON.parse(reply.data, symbolize_names: true)
82
+ raise api_error(result[:error]) if result[:error]
83
+
84
+ result
85
+ end
86
+
87
+ # The nats-pure error for an API error, chosen by the same status and
88
+ # error codes nats-pure uses.
89
+ def self.api_error(details)
90
+ errors = NATS::JetStream::Error
91
+ case details[:code]
92
+ when 503 then errors::ServiceUnavailable.new(details)
93
+ when 500 then errors::ServerError.new(details)
94
+ when 404
95
+ case details[:err_code]
96
+ when 10059 then errors::StreamNotFound.new(details)
97
+ when 10014 then errors::ConsumerNotFound.new(details)
98
+ else errors::NotFound.new(details)
99
+ end
100
+ when 400
101
+ case details[:err_code]
102
+ when 10148 then errors::ConsumerAlreadyExists.new(details)
103
+ when 10149 then errors::ConsumerDoesNotExist.new(details)
104
+ else errors::BadRequest.new(details)
105
+ end
106
+ else errors::APIError.new(details)
107
+ end
108
+ end
109
+
110
+ private_class_method :wire_config, :nanoseconds, :consumer, :request, :api_error
111
+ end
112
+ private_constant :ConsumerAPI
113
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ServiceMeshNats
4
+ # A JetStream message on its way from a pull loop to its handler. It is
5
+ # tracked from when the runtime receives it until its handler's result or
6
+ # Runtime#stop settles it, whichever comes first.
7
+ class Delivery
8
+ attr_reader :msg, :subscription, :pull_loop, :arrival
9
+
10
+ def initialize(msg, subscription, pull_loop, arrival)
11
+ @msg = msg
12
+ @subscription = subscription
13
+ @pull_loop = pull_loop
14
+ @arrival = arrival
15
+ @state = :waiting
16
+ @lock = Mutex.new
17
+ end
18
+
19
+ # Marks the handler running, and returns false when stop already
20
+ # settled the delivery.
21
+ def begin
22
+ @lock.synchronize do
23
+ next false if @state == :settled
24
+
25
+ @state = :running
26
+ true
27
+ end
28
+ end
29
+
30
+ # Marks the delivery settled. Returns [running, ok]: ok is false when it
31
+ # already was settled, and running tells whether its handler had begun.
32
+ def settle
33
+ @lock.synchronize do
34
+ next [false, false] if @state == :settled
35
+
36
+ running = @state == :running
37
+ @state = :settled
38
+ [running, true]
39
+ end
40
+ end
41
+ end
42
+ private_constant :Delivery
43
+ end
@@ -7,6 +7,10 @@ module ServiceMeshNats
7
7
 
8
8
  class BadConfig < Error; end
9
9
 
10
+ # Raised by Client#request when the request's settings do not allow it to
11
+ # be sent.
12
+ class InvalidRequest < Error; end
13
+
10
14
  class Closed < Error
11
15
  def initialize(msg = "client has been closed") = super
12
16
  end
@@ -19,6 +23,19 @@ module ServiceMeshNats
19
23
  def initialize(msg = "runtime has been stopped; it is not restartable") = super
20
24
  end
21
25
 
26
+ # Raised by Runtime#start when a JetStream stream covers one of the
27
+ # runtime's endpoint subjects, because the stream would answer requests to
28
+ # it. +subject+ is the endpoint subject, and +stream+ the stream's name.
29
+ class StreamCoversRoute < Error
30
+ attr_reader :subject, :stream
31
+
32
+ def initialize(subject, stream)
33
+ @subject = subject
34
+ @stream = stream
35
+ super("a stream covers an endpoint subject: subject #{subject.inspect}, stream #{stream.inspect}")
36
+ end
37
+ end
38
+
22
39
  # Raised by Client#request when the serving handler raised. +text+ is the
23
40
  # handler's error message as sent by the serving runtime.
24
41
  class HandlerError < Error
@@ -29,8 +46,4 @@ module ServiceMeshNats
29
46
  super("handler failed: #{text}")
30
47
  end
31
48
  end
32
-
33
- # Reply header set when an endpoint handler fails. Application metadata
34
- # should not use this key.
35
- HANDLER_ERROR_HEADER = "Mesh-Handler-Error"
36
49
  end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "nats/io/client"
4
+
5
+ module ServiceMeshNats
6
+ # Converts between message metadata and NATS headers.
7
+ module Header
8
+ # Copies +metadata+ into a NATS header, one string value per key, or nil
9
+ # when it is empty.
10
+ def self.to_header(metadata)
11
+ metadata.empty? ? nil : metadata.transform_keys(&:to_s).transform_values(&:to_s)
12
+ end
13
+
14
+ # to_header for a message being sent. ServiceMesh::MESSAGE_ID_KEY and
15
+ # Nats-Msg-Id are one field, and ServiceMesh::MESSAGE_ID_KEY wins.
16
+ def self.outgoing_header(metadata)
17
+ header = to_header(metadata)
18
+ header[NATS::JetStream::Header::MSG_ID] = header[ServiceMesh::MESSAGE_ID_KEY] if header&.key?(ServiceMesh::MESSAGE_ID_KEY)
19
+ header
20
+ end
21
+
22
+ # The metadata handed to a handler, never nil. Nats-Msg-Id and
23
+ # ServiceMesh::MESSAGE_ID_KEY are one field, and Nats-Msg-Id wins.
24
+ def self.incoming_metadata(header)
25
+ metadata = header.to_h.dup
26
+ message_id = metadata[NATS::JetStream::Header::MSG_ID]
27
+ metadata[ServiceMesh::MESSAGE_ID_KEY] = message_id if message_id
28
+ metadata
29
+ end
30
+ end
31
+ private_constant :Header
32
+ end