service_mesh_nats 0.7.1 → 0.8.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: c7d47cf27e0ff8d0e54d505b7c59403458afb435e8160f78412817c21eda1a34
4
+ data.tar.gz: 9ea7182672a1a1647aebd0eea30ffde78ff61b7f4f6bd20573a3ec2f6da18423
5
5
  SHA512:
6
- metadata.gz: ae7c3c84a34f9706df0e487b7de27822c326df44cf7715ddf1507483ad739971555d934dc4302a4bd3e888bafb53ebb6460d63b4ca93792bd62d0c7f76ab8279
7
- data.tar.gz: f0aae96d9e018be5205fa7a8468ec2ed288d7b8dc695b7ef8e8af6c2582ec95583d44a943614280de060369db706e79e298280f2b20c4898910407e3f08f326e
6
+ metadata.gz: bdf3079c3f4abd4faf07b4918d28a781d19d20c22013f870b3a5db48bfbfb10689cc787caa09c68f132791ac7b3939832234324aa38f4fcc2ac4a20b7892049a
7
+ data.tar.gz: 746c42c2edefa1b947ff86e78df780979699672dd393c85f6550b541b99b2a77cf9b9ef109b5739a7c5b6ecd4328a22c046075b2a0219be4bae31c62f4d78fba
data/README.md CHANGED
@@ -9,6 +9,7 @@ top of the `nats-pure` client.
9
9
  The `ServiceMeshNats` module provides:
10
10
  * `Client`, which implements the contract's `Client` over one NATS connection
11
11
  * `Runtime`, which implements the contract's `Runtime` on a `Client`'s connection
12
+ * `Receiver`, which inspects an endpoint or subscriber the runtime is running
12
13
  * the configuration keys it reads
13
14
  * the errors it defines
14
15
 
@@ -23,7 +24,7 @@ come from the `service_mesh` gem.
23
24
  gem "service_mesh_nats"
24
25
  ```
25
26
 
26
- Requires Ruby 3.3 or newer and a reachable NATS server. The gem depends on
27
+ The gem needs Ruby 3.3 or newer and a reachable NATS server. It depends on
27
28
  `service_mesh` and `nats-pure`.
28
29
 
29
30
  ## Usage
@@ -68,6 +69,7 @@ builds a client itself and calls `close` when done. `runtime.service_map` and
68
69
  ## Documentation
69
70
 
70
71
  - [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
72
+ - [Public API](docs/public-api.md): the constants and methods in `ServiceMeshNats` that applications use
73
+ - [Transport Specific Implementation](docs/transport-specific-implementation.md): subjects, configuration, settings, metadata, delivery, handler failure, timeouts, concurrency, lifecycle, logging, and errors
74
+ - [JetStream](docs/jetstream.md): publishing to streams, consuming through consumers, their options, and inspecting streams and consumers
73
75
  - [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,106 @@ 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. REQUEST_TIMEOUT_KEY bounds the call. STREAM_KEY raises
79
+ # BadConfig. Expiry raises NATS::Timeout, and no receiver raises
51
80
  # 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
81
+ #
82
+ # The request carries ServiceMesh::TIMEOUT_KEY, set to the request timeout
83
+ # in whole milliseconds. ServiceMesh::MESSAGE_ID_KEY is copied to
84
+ # Nats-Msg-Id.
85
+ def request(message, options = {})
86
+ Target.check_kind!(message.target, :route, "request")
87
+ subject = Target.subject(message.target)
88
+ settings = Target.merge_settings(message.target, options)
89
+ unless settings[STREAM_KEY].to_s.empty?
90
+ raise BadConfig, "#{STREAM_KEY}=#{settings[STREAM_KEY].inspect} applies to topic targets only"
91
+ end
92
+ timeout = Config.duration(settings, REQUEST_TIMEOUT_KEY, @settings.request_timeout)
93
+ nats_connection = connection
57
94
 
58
- reply = nc.request_msg(nats_msg(subject, message), timeout: timeout)
95
+ msg = nats_msg(subject, message)
96
+ msg.header = (msg.header || {}).merge(ServiceMesh::TIMEOUT_KEY => (timeout * 1000).floor.to_s)
97
+ reply = nats_connection.request_msg(msg, timeout: timeout)
59
98
  header = reply.header || {}
60
- raise HandlerError.new(header[HANDLER_ERROR_HEADER].to_s) if header.key?(HANDLER_ERROR_HEADER)
99
+ raise HandlerError.new(header[ServiceMesh::HANDLER_ERROR_KEY].to_s) if header.key?(ServiceMesh::HANDLER_ERROR_KEY)
61
100
 
62
101
  ServiceMesh::Message.new(target: message.target, metadata: header, payload: reply.data.to_s)
63
102
  end
64
103
 
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))
104
+ # Sends +message+ to a topic target. ServiceMesh::MESSAGE_ID_KEY is copied
105
+ # to Nats-Msg-Id.
106
+ #
107
+ # Settings are read from +options+, then the target's metadata, then the
108
+ # client's config. When they carry STREAM_KEY, the message goes out as a
109
+ # JetStream publish that expects that stream, and publish waits for the
110
+ # stream's ack, bounded by REQUEST_TIMEOUT_KEY. nats-pure's errors pass
111
+ # through unchanged. They include NATS::Timeout on expiry,
112
+ # NATS::JetStream::Error::NoStreamResponse when no stream takes the
113
+ # subject, and NATS::JetStream::Error::APIError when the stream refuses the
114
+ # message.
115
+ def publish(message, options = {})
116
+ Target.check_kind!(message.target, :topic, "publish")
117
+ subject = Target.subject(message.target)
118
+ settings = Target.merge_settings(message.target, options)
119
+ stream = settings[STREAM_KEY].to_s
120
+ msg = nats_msg(subject, message)
121
+ if stream.empty?
122
+ connection.publish_msg(msg)
123
+ return nil
124
+ end
125
+
126
+ timeout = Config.duration(settings, REQUEST_TIMEOUT_KEY, @settings.request_timeout)
127
+ jetstream.publish(subject, msg.data, header: msg.header, stream: stream, timeout: timeout)
71
128
  nil
72
129
  end
73
130
 
74
131
  private
75
132
 
133
+ # The NATS message for +message+, with its metadata as the header.
76
134
  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)
135
+ NATS::Msg.new(subject: subject, data: message.payload, header: Header.outgoing_header(message.metadata))
79
136
  end
80
137
  end
81
138
  end
@@ -0,0 +1,162 @@
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 seconds, such as "5" or "0.25".
8
+ URL_KEY = "url"
9
+ NAME_KEY = "name"
10
+ CONNECT_TIMEOUT_KEY = "connect_timeout"
11
+ REQUEST_TIMEOUT_KEY = "request_timeout"
12
+ CONCURRENCY_KEY = "concurrency"
13
+ # The most times one JetStream message is delivered, as a positive integer.
14
+ # In a runtime's config it is the default for subscribers that do not set
15
+ # it. It is also a subscriber setting.
16
+ MAX_DELIVER_KEY = "max_deliver"
17
+
18
+ # JetStream settings, read from an Endpoint's or Subscriber's metadata over
19
+ # its Target's metadata, and from a call's options over its Target's
20
+ # metadata. Every key but STREAM_KEY is read only from a Subscriber that
21
+ # sets STREAM_KEY.
22
+ #
23
+ # The stream name. A Subscriber consumes from a consumer on it, and a
24
+ # publish waits for its ack. On an Endpoint or a request it is BadConfig.
25
+ STREAM_KEY = "stream"
26
+ # "true" or "false". "false" leaves a named consumer group's consumer to be
27
+ # created outside the runtime.
28
+ CREATE_CONSUMER_KEY = "create_consumer"
29
+ # "double", "explicit", or "none".
30
+ ACK_POLICY_KEY = "ack_policy"
31
+ # Seconds the server waits for an ack before it sends a message again.
32
+ # Ignored when BACKOFF_KEY is set.
33
+ ACK_WAIT_KEY = "ack_wait"
34
+ # Comma-separated seconds, one for each delivery in turn, that set how long
35
+ # the server waits for an ack before it sends the message again. Deliveries
36
+ # past the end of the list use its last entry. The server sets the
37
+ # consumer's ack wait to the first entry. MAX_DELIVER_KEY must exceed its
38
+ # length.
39
+ BACKOFF_KEY = "backoff"
40
+ # Seconds the server waits before it sends a failed message again.
41
+ NAK_DELAY_KEY = "nak_delay"
42
+ # The most unacked messages the consumer allows at once.
43
+ MAX_ACK_PENDING_KEY = "max_ack_pending"
44
+ # "all" or "new", where a newly created consumer starts.
45
+ DELIVER_POLICY_KEY = "deliver_policy"
46
+ # Seconds a consumer outlives its last puller.
47
+ CONSUMER_INACTIVE_THRESHOLD_KEY = "consumer_inactive_threshold"
48
+ # Seconds the server keeps a pull open while it has nothing to send. At
49
+ # least 1. Also a runtime config key, where it is the default for
50
+ # subscribers that do not set it.
51
+ PULL_EXPIRY_KEY = "pull_expiry"
52
+ # Seconds between the server's heartbeats on an open pull that has nothing
53
+ # to send. From 0.5 to 30, and no more than half of PULL_EXPIRY_KEY. Two
54
+ # missed heartbeats make the subscriber pull again. Also a
55
+ # runtime config key, where it is the default for subscribers that do not
56
+ # set it.
57
+ PULL_HEARTBEAT_KEY = "pull_heartbeat"
58
+
59
+ # Metadata keys the runtime adds to each JetStream delivery it hands to a
60
+ # handler, from the delivery's JetStream metadata.
61
+ STREAM_METADATA_KEY = "Mesh-Nats-Stream"
62
+ CONSUMER_METADATA_KEY = "Mesh-Nats-Consumer"
63
+ STREAM_SEQUENCE_METADATA_KEY = "Mesh-Nats-Stream-Sequence"
64
+ CONSUMER_SEQUENCE_METADATA_KEY = "Mesh-Nats-Consumer-Sequence"
65
+ NUM_PENDING_METADATA_KEY = "Mesh-Nats-Num-Pending"
66
+ TIMESTAMP_METADATA_KEY = "Mesh-Nats-Timestamp"
67
+
68
+ DEFAULT_URL = "nats://127.0.0.1:4222"
69
+ DEFAULT_CONNECT_TIMEOUT = 5.0
70
+ DEFAULT_REQUEST_TIMEOUT = 30.0
71
+ DEFAULT_MAX_DELIVER = 5
72
+ NAMED_INACTIVE_THRESHOLD = 7 * 24 * 60 * 60.0
73
+ ORDERED_INACTIVE_THRESHOLD = 5 * 60.0
74
+ DEFAULT_PULL_EXPIRY = 30.0
75
+
76
+ # Value parsers shared by the settings types.
77
+ module Config
78
+ # Reads +key+ as a positive number of seconds, or returns +fallback+ when
79
+ # absent.
80
+ def self.duration(hash, key, fallback)
81
+ return fallback unless hash.key?(key)
82
+
83
+ value = Float(hash[key], exception: false)
84
+ raise BadConfig, "#{key}=#{hash[key].inspect} must be a positive number of seconds" if value.nil? || value <= 0
85
+
86
+ value
87
+ end
88
+
89
+ def self.positive_integer(hash, key, fallback)
90
+ return fallback unless hash.key?(key)
91
+
92
+ value = Integer(hash[key], 10, exception: false)
93
+ raise BadConfig, "#{key}=#{hash[key].inspect} must be a positive integer" if value.nil? || value <= 0
94
+
95
+ value
96
+ end
97
+
98
+ # Reads +key+ as one of the strings in +allowed+, or returns the first of
99
+ # them when absent.
100
+ def self.choice(hash, key, allowed)
101
+ return allowed.first unless hash.key?(key)
102
+ return hash[key] if allowed.include?(hash[key])
103
+
104
+ raise BadConfig, "#{key}=#{hash[key].inspect} must be one of #{allowed.map(&:inspect).join(", ")}"
105
+ end
106
+
107
+ # Reads +key+ as a comma-separated list of positive numbers of seconds,
108
+ # or returns nil when absent.
109
+ def self.durations(hash, key)
110
+ return nil unless hash.key?(key)
111
+
112
+ hash[key].to_s.split(",", -1).map do |part|
113
+ value = Float(part.strip, exception: false)
114
+ if value.nil? || value <= 0
115
+ raise BadConfig, "#{key}=#{hash[key].inspect} must be a comma-separated list of positive numbers of seconds, such as \"1,5\""
116
+ end
117
+
118
+ value
119
+ end
120
+ end
121
+ end
122
+
123
+ # The keys a Client reads. Any other key is ignored.
124
+ ClientSettings = Data.define(:url, :name, :connect_timeout, :request_timeout) do
125
+ def self.parse(config)
126
+ config = config.to_h
127
+ new(
128
+ url: config.fetch(URL_KEY, DEFAULT_URL).then { |url| url.to_s.empty? ? DEFAULT_URL : url },
129
+ name: config[NAME_KEY],
130
+ connect_timeout: Config.duration(config, CONNECT_TIMEOUT_KEY, DEFAULT_CONNECT_TIMEOUT),
131
+ request_timeout: Config.duration(config, REQUEST_TIMEOUT_KEY, DEFAULT_REQUEST_TIMEOUT)
132
+ )
133
+ end
134
+
135
+ def connect_options
136
+ options = {servers: [url], connect_timeout: connect_timeout}
137
+ options[:name] = name if name && !name.empty?
138
+ options
139
+ end
140
+ end
141
+
142
+ # The keys a Runtime reads. Connection keys in a runtime's config are
143
+ # ignored, because the runtime's client carries them.
144
+ #
145
+ # +pull_expiry+ and +pull_heartbeat+ are nil when the config does not set
146
+ # them.
147
+ RuntimeSettings = Data.define(:deployment_group, :concurrency, :max_deliver, :pull_expiry, :pull_heartbeat) do
148
+ def self.parse(config)
149
+ config = config.to_h
150
+ deployment_group = config[ServiceMesh::DEPLOYMENT_GROUP_KEY].to_s
151
+ raise ServiceMesh::NoDeploymentGroup if deployment_group.empty?
152
+
153
+ new(
154
+ deployment_group: deployment_group,
155
+ concurrency: Config.positive_integer(config, CONCURRENCY_KEY, Etc.nprocessors),
156
+ max_deliver: Config.positive_integer(config, MAX_DELIVER_KEY, DEFAULT_MAX_DELIVER),
157
+ pull_expiry: Config.duration(config, PULL_EXPIRY_KEY, nil),
158
+ pull_heartbeat: Config.duration(config, PULL_HEARTBEAT_KEY, nil)
159
+ )
160
+ end
161
+ end
162
+ 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
@@ -19,6 +19,19 @@ module ServiceMeshNats
19
19
  def initialize(msg = "runtime has been stopped; it is not restartable") = super
20
20
  end
21
21
 
22
+ # Raised by Runtime#start when a JetStream stream covers one of the
23
+ # runtime's endpoint subjects, because the stream would answer requests to
24
+ # it. +subject+ is the endpoint subject, and +stream+ the stream's name.
25
+ class StreamCoversRoute < Error
26
+ attr_reader :subject, :stream
27
+
28
+ def initialize(subject, stream)
29
+ @subject = subject
30
+ @stream = stream
31
+ super("a stream covers an endpoint subject: subject #{subject.inspect}, stream #{stream.inspect}")
32
+ end
33
+ end
34
+
22
35
  # Raised by Client#request when the serving handler raised. +text+ is the
23
36
  # handler's error message as sent by the serving runtime.
24
37
  class HandlerError < Error
@@ -29,8 +42,4 @@ module ServiceMeshNats
29
42
  super("handler failed: #{text}")
30
43
  end
31
44
  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
45
  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