omq-zstd 0.5.1 → 0.6.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: b89a980846b992e85790911f5dd512cc774f7b278ac5f649ecf840dedba9e4a2
4
- data.tar.gz: 554cfe7d3eaff541a544c5e9162361a7e87015d4cdb6d3fc819ffaa5750c6c6e
3
+ metadata.gz: 9ba7286375bada19c382e8ef3114174a8e8b7c4491dfd9466564d2a647fe1ba3
4
+ data.tar.gz: abca6dd024f7e637efba7af8576dae7e9efd5457460b9f94ad77f60ef15094fc
5
5
  SHA512:
6
- metadata.gz: 34a1e9f44b2dfe53b7ec2554dd57f98727088511809a8aa6baffa80a8a146baf23c5025677d11e5d1105e58e5b7fed8c9e89a1f72705d9b05e1a3311d67c34bc
7
- data.tar.gz: fccd26832773fb751b93e18e6616c027789e2cd4978d8f13e1e9993fec8ed61aa3767f0d6513b3ac57910a552a050254a3a9b21923ef5c83bf60dd7725dbbb19
6
+ metadata.gz: b62d2f153273ed13e38f425102b5714088b0a134d6f8bf04133e35e60acb895bf1cb474af9c0adee17e9169f7cd829605d80bcf02f85a2602fcb05f183b691d3
7
+ data.tar.gz: f88f5cb10c9c3484956af1e252d54e80c9765052cb2cacf48312b301ef370f7e83f28c37bdad0e7ccb0c4fe203e3045cc5a08d23594726508aba9b85b42144f3
data/README.md CHANGED
@@ -65,15 +65,37 @@ a `zstd+tcp://` peer. They speak different transports.
65
65
 
66
66
  ### Compression level
67
67
 
68
- Default is **`-3`** (negative = Zstd's fast strategy). Override at bind/connect:
68
+ By default each connection adapts its send level within -7..4, starting at
69
+ -1, as omq.rs does. Every window of at least 100 ms and 256 KiB of input, it
70
+ steps toward ratio when writes stall or the sender idles, and toward speed
71
+ when compression keeps the send queue full (zrip's `AdaptiveLevel`). An
72
+ Integer fixes the level; a Range adapts within it:
69
73
 
70
74
  ```ruby
71
- pull.bind("zstd+tcp://127.0.0.1:0", level: 3)
72
- push.connect("zstd+tcp://127.0.0.1:5555", level: 9)
75
+ pull.bind("zstd+tcp://127.0.0.1:0", level: 3) # fixed
76
+ push.connect("zstd+tcp://127.0.0.1:5555", level: -5..2) # adapts within -5..2
73
77
  ```
74
78
 
79
+ Fan-out sockets (PUB, XPUB, RADIO) compress each message once for all
80
+ subscribers, so they keep a fixed level: -1, or the end of the range nearest
81
+ it. An adaptive connection has its own Zstd compressor; a fixed level shares
82
+ one per socket.
83
+
75
84
  Per-direction, per-side: each side picks its own send level. Receiving works
76
- at any level the peer chose.
85
+ at any level the peer chose. Unknown options raise `ArgumentError`.
86
+
87
+ PUSH to PULL, 4 KiB messages, receiver and link in other processes
88
+ (`bench/adaptive.rb`, YJIT, x86_64), plaintext MB/s with `level: -3` (the
89
+ old default) and adaptive:
90
+
91
+ | Messages | Unlimited link | 10 MB/s link | 2 MB/s link |
92
+ |---|---|---|---|
93
+ | JSON records | 212 / 259 | 64.0 / 69.8 | 13.9 / 14.6 |
94
+ | Silesia dickens | 274 / 487 | 17.4 / 20.2 | 3.6 / 4.3 |
95
+ | Silesia xml | 240 / 304 | 59.2 / 63.8 | 12.5 / 13.8 |
96
+
97
+ On an unlimited link the level drops to -7; on slow links it climbs as far
98
+ as a higher level compresses better (to 3 on xml).
77
99
 
78
100
  ### Dictionaries
79
101
 
@@ -129,9 +151,9 @@ cap is rejected on the offending part.
129
151
  pull.max_message_size = 1_048_576 # 1 MiB cap on the total message
130
152
  ```
131
153
 
132
- If `max_message_size` is `nil` (OMQ's default, unlimited), there is no
133
- ceiling on decompressed message size. Set a value that matches what
134
- your application would tolerate over plain `tcp://`.
154
+ If `max_message_size` is `nil` (OMQ's default), a message may decode to
155
+ just under 1 GiB, plaintext parts included, as in omq.rs. Set a value
156
+ that matches what your application would tolerate over plain `tcp://`.
135
157
 
136
158
  Independent of the message-size knob, the dictionary itself is capped at
137
159
  8 KiB. A peer attempting to ship a larger dictionary, or send a message
@@ -162,7 +184,7 @@ transport layer. They are not delivered to the application.
162
184
  | Uncompressed sentinel | `00 00 00 00` |
163
185
  | Zstd frame sentinel | `28 B5 2F FD` (Zstandard frame magic) |
164
186
  | Dictionary sentinel | `37 A4 30 EC` |
165
- | Default level | -3 |
187
+ | Default level | adapts within -7..4 from -1 |
166
188
  | Min compress, no dict | 512 B |
167
189
  | Min compress, with dict | 64 B |
168
190
  | Max dictionary size | 8 KiB |
@@ -196,7 +218,8 @@ It is **not** worth it for:
196
218
  `require "omq/zstd"` registers the `zstd+tcp` scheme on
197
219
  `OMQ::Engine.transports`. A `zstd+tcp` socket builds a per-engine
198
220
  `Codec` (one Zstd dictionary instance shared across all the socket's
199
- connections. Fan-out compresses each part exactly once). Each accepted
221
+ connections. Fan-out compresses each part exactly once; an adaptive
222
+ connection compresses with its own codec at its own level). Each accepted
200
223
  or dialed TCP connection is wrapped in `ZstdConnection`, a
201
224
  `SimpleDelegator` over the underlying ZMTP connection that intercepts
202
225
  `#send_message` / `#write_message` / `#receive_message`. Message parts
@@ -0,0 +1,150 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "async/clock"
4
+
5
+ require_relative "bottleneck"
6
+
7
+ module OMQ
8
+ module Transport
9
+ module ZstdTcp
10
+ # One connection's adaptive compression level: its own frame codec and
11
+ # `Zrip::AdaptiveLevel`, and the counts of the current window. The
12
+ # socket's {Codec} keeps the dictionary and its training.
13
+ #
14
+ class AdaptiveSender
15
+ # A window closes after at least this long...
16
+ WINDOW_SECONDS = 0.1
17
+
18
+ # ...and this much input, as in omq.rs (zrip's `MIN_WINDOW_BYTES`).
19
+ WINDOW_BYTES = 256 * 1024
20
+
21
+ # A write that takes longer than this waited on the link; the time
22
+ # beyond it counts as stalled. Copying a batch into the kernel takes
23
+ # well under it, and counting that made CPU-bound windows unclear.
24
+ WRITE_GRACE = 0.001
25
+
26
+ # The send pump's batch limits (`Routing::RoundRobin`). A batch that
27
+ # reaches one with input still queued overflowed.
28
+ BATCH_MSG_CAP = Routing::RoundRobin::BATCH_MSG_CAP
29
+ BATCH_BYTE_CAP = Routing::RoundRobin::BATCH_BYTE_CAP
30
+
31
+
32
+ # @return [Codec] the socket's codec
33
+ attr_reader :codec
34
+
35
+ # @return [Float] when the current window started
36
+ attr_reader :window_started
37
+
38
+
39
+ # @param codec [Codec] the socket's codec, with the level range
40
+ # @param send_hwm [Integer, nil] the socket's send HWM. A batch this
41
+ # large was taken from a full queue.
42
+ # @param queued [#call, nil] whether the socket has messages queued
43
+ # to send, asked as each batch is written. Nil counts no batch as
44
+ # backlogged.
45
+ def initialize(codec, send_hwm:, queued:)
46
+ @codec = codec
47
+ @send_hwm = send_hwm if send_hwm&.positive?
48
+ @queued = queued
49
+ @adaptive = Zrip::AdaptiveLevel.new(codec.level_range, start: START_LEVEL)
50
+ @dict = codec.send_dict_bytes
51
+ @frame_codec = codec.build_frame_codec(@adaptive.level)
52
+ start_window(Async::Clock.now)
53
+ end
54
+
55
+
56
+ # The codec to compress with. It follows the socket's dictionary once
57
+ # training installs one, at the current level.
58
+ #
59
+ # @return [Zrip::FrameCodec]
60
+ def frame_codec
61
+ unless @codec.send_dict_bytes.equal?(@dict)
62
+ record(@frame_codec.take_stats)
63
+ @dict = @codec.send_dict_bytes
64
+ @frame_codec = @codec.build_frame_codec(@frame_codec.level)
65
+ end
66
+
67
+ @frame_codec
68
+ end
69
+
70
+
71
+ # Counts one written batch of messages.
72
+ #
73
+ # @param messages [Array<Array<String>>]
74
+ # @return [void]
75
+ def note_batch(messages)
76
+ bytes = 0
77
+ messages.each { |parts| parts.each { |part| bytes += part.bytesize } }
78
+
79
+ # A batch that reaches a limit can still be all there was: one
80
+ # large message reaches the byte limit alone.
81
+ capped = messages.size >= BATCH_MSG_CAP || bytes >= BATCH_BYTE_CAP
82
+ left = @queued&.call
83
+
84
+ @batches += 1
85
+ @backlogged += 1 if left
86
+ @overflowed += 1 if left && capped
87
+ @input_full += 1 if @send_hwm && messages.size >= @send_hwm
88
+ end
89
+
90
+
91
+ # @param seconds [Float] time a write or flush took
92
+ # @return [void]
93
+ def note_write(seconds)
94
+ @blocked += seconds - WRITE_GRACE if seconds > WRITE_GRACE
95
+ end
96
+
97
+
98
+ # Closes the window if it is long and large enough, and moves the
99
+ # level.
100
+ #
101
+ # @param now [Float]
102
+ # @return [void]
103
+ def maybe_adapt(now = Async::Clock.now)
104
+ elapsed = now - @window_started
105
+ return if elapsed < WINDOW_SECONDS
106
+
107
+ record(@frame_codec.take_stats)
108
+ return if @plain < WINDOW_BYTES
109
+
110
+ bottleneck = Bottleneck.classify(
111
+ elapsed: elapsed,
112
+ blocked: @blocked,
113
+ batches: @batches,
114
+ backlogged: @backlogged,
115
+ overflowed: @overflowed,
116
+ input_full: @input_full,
117
+ )
118
+ level = @adaptive.update(plain: @plain, compressed: @compressed, busy: @busy, bottleneck: bottleneck)
119
+ @frame_codec.level = level unless level == @frame_codec.level
120
+
121
+ start_window(now)
122
+ end
123
+
124
+
125
+ private
126
+
127
+
128
+ def record(stats)
129
+ @plain += stats[:plain]
130
+ @compressed += stats[:compressed]
131
+ @busy += stats[:busy]
132
+ end
133
+
134
+
135
+ def start_window(now)
136
+ @window_started = now
137
+ @plain = 0
138
+ @compressed = 0
139
+ @busy = 0.0
140
+ @blocked = 0.0
141
+ @batches = 0
142
+ @backlogged = 0
143
+ @overflowed = 0
144
+ @input_full = 0
145
+ end
146
+
147
+ end
148
+ end
149
+ end
150
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OMQ
4
+ module Transport
5
+ module ZstdTcp
6
+ # Names what limited a sender during one adaptation window, as omq.rs
7
+ # does (omq-proto `transform/adaptive.rs`). `Zrip::AdaptiveLevel` then
8
+ # walks the level toward ratio (`:output`, `:input`) or speed (`:cpu`).
9
+ #
10
+ # One reactor thread compresses for every connection, and compression
11
+ # below 64 KiB holds the GVL, so peers that are all busy all read as
12
+ # `:cpu`. That is what they are.
13
+ #
14
+ module Bottleneck
15
+ module_function
16
+
17
+
18
+ # @param elapsed [Float] seconds the window covers
19
+ # @param blocked [Float] seconds writes stalled
20
+ # @param batches [Integer] batches written
21
+ # @param backlogged [Integer] batches that left input queued
22
+ # @param overflowed [Integer] backlogged batches that stopped at a
23
+ # batch limit
24
+ # @param input_full [Integer] batches taken from a full send queue
25
+ # @return [Symbol, nil] `:output`, `:cpu`, `:input`, or nil when no
26
+ # bottleneck is clear
27
+ def classify(elapsed:, blocked:, batches:, backlogged:, overflowed:, input_full:)
28
+ return nil if elapsed <= 0 || batches.zero?
29
+
30
+ # Writes stalled for at least 1/16 of the window.
31
+ return :output if blocked > 0 && blocked * 16 >= elapsed
32
+
33
+ # The send queue filled, or more than 1/8 of the batches stopped
34
+ # at their limit with input left. A shorter backlog only grows the
35
+ # batches.
36
+ if input_full > 0 || overflowed * 8 > batches
37
+ return blocked * 64 < elapsed ? :cpu : nil
38
+ end
39
+
40
+ backlogged.zero? ? :input : nil
41
+ end
42
+ end
43
+ end
44
+ end
45
+ end
@@ -22,12 +22,31 @@ module OMQ
22
22
 
23
23
  USER_DICT_ID_RANGE = (32_768..(2**31 - 1)).freeze
24
24
 
25
+ # omq.rs decoders refuse a frame of 1 GiB or more, so a larger part
26
+ # goes as plaintext (omq-proto 0.40). The decode budget without a
27
+ # `max_message_size` is the same.
28
+ MAX_COMPRESSED_PART = (1 << 30) - 1
25
29
 
30
+
31
+ # @return [String, nil] the dictionary this socket sends with
32
+ # @return [Integer, nil] the socket's `max_message_size`
26
33
  attr_reader :send_dict_bytes, :max_message_size
27
34
 
35
+ # @return [Integer] the level of the shared codec: fixed, or the start
36
+ # of an adaptive range
37
+ attr_reader :level
38
+
39
+ # @return [Range, nil] the levels each connection adapts within, or
40
+ # nil for a fixed level
41
+ attr_reader :level_range
42
+
43
+ # @return [Zrip::FrameCodec] the shared frame codec
44
+ attr_reader :send_codec
28
45
 
29
- def initialize(level:, dict: nil, max_message_size: nil, auto_dict: nil)
46
+
47
+ def initialize(level:, level_range: nil, dict: nil, max_message_size: nil, auto_dict: nil)
30
48
  @level = level
49
+ @level_range = level_range
31
50
  @max_message_size = max_message_size
32
51
  @dict_capacity = if auto_dict.is_a?(Hash) && auto_dict[:capacity]
33
52
  auto_dict[:capacity]
@@ -54,27 +73,49 @@ module OMQ
54
73
  end
55
74
 
56
75
 
57
- def compress_parts(parts)
58
- return @cached_compressed if parts.equal?(@cached_parts)
76
+ # Compresses one message's parts. Fan-out compresses a message once
77
+ # for every subscriber with the shared codec; a connection that
78
+ # adapts its level passes its own.
79
+ #
80
+ # @param parts [Array<String>]
81
+ # @param frame_codec [Zrip::FrameCodec]
82
+ # @return [Array<String>] wire parts
83
+ def compress_parts(parts, frame_codec = @send_codec)
84
+ shared = frame_codec.equal?(@send_codec)
85
+ return @cached_compressed if shared && parts.equal?(@cached_parts)
59
86
 
60
87
  parts.each { |p| maybe_train!(p) }
61
88
 
62
- compressed = parts.map { |p| compress_or_plain(p) }
63
- @cached_parts = parts
64
- @cached_compressed = compressed.freeze
89
+ compressed = parts.map { |p| compress_or_plain(p, frame_codec) }
90
+ if shared
91
+ @cached_parts = parts
92
+ @cached_compressed = compressed.freeze
93
+ end
65
94
  compressed
66
95
  end
67
96
 
68
97
 
69
- def compress_messages(messages)
98
+ # A frame codec with the socket's dictionary, if any, at `level`.
99
+ #
100
+ # @param level [Integer]
101
+ # @return [Zrip::FrameCodec]
102
+ def build_frame_codec(level)
103
+ Zrip::FrameCodec.new(dict: @send_dict_bytes, level: level)
104
+ end
105
+
106
+
107
+ # @param messages [Array<Array<String>>]
108
+ # @param frame_codec [Zrip::FrameCodec]
109
+ # @return [Array<Array<String>>] wire messages
110
+ def compress_messages(messages, frame_codec = @send_codec)
70
111
  CompressionArena.each_batch(messages, target: ARENA_TARGET_BYTES).map do |batch|
71
112
  if batch.size == 1
72
- compress_parts(batch.first)
113
+ compress_parts(batch.first, frame_codec)
73
114
  else
74
115
  batch.each { |parts| parts.each { |part| maybe_train!(part) } }
75
116
  threshold = @send_dict_bytes ? MIN_COMPRESS_WITH_DICT : MIN_COMPRESS_NO_DICT
76
117
  [CompressionArena.encode(batch, sentinel: ARENA_MAGIC, threshold: threshold) do |data|
77
- @send_codec.compress(data)
118
+ frame_codec.compress(data)
78
119
  end]
79
120
  end
80
121
  end
@@ -192,12 +233,13 @@ module OMQ
192
233
  end
193
234
 
194
235
 
195
- def compress_or_plain(part)
236
+ def compress_or_plain(part, frame_codec = @send_codec)
196
237
  bytes = part.is_a?(String) && part.encoding == Encoding::BINARY ? part : part.to_s.b
197
238
  threshold = @send_dict_bytes ? MIN_COMPRESS_WITH_DICT : MIN_COMPRESS_NO_DICT
198
239
  return plain(bytes) if bytes.bytesize < threshold
240
+ return plain(bytes) if bytes.bytesize > max_compressed_part
199
241
 
200
- compressed = @send_codec.compress(bytes)
242
+ compressed = frame_codec.compress(bytes)
201
243
 
202
244
  return plain(bytes) if compressed.bytesize >= bytes.bytesize - 4
203
245
 
@@ -209,6 +251,11 @@ module OMQ
209
251
  NUL_PREAMBLE + body
210
252
  end
211
253
 
254
+
255
+ def max_compressed_part
256
+ MAX_COMPRESSED_PART
257
+ end
258
+
212
259
  end
213
260
  end
214
261
  end
@@ -11,10 +11,18 @@ module OMQ
11
11
  attr_reader :last_wire_size_in
12
12
 
13
13
 
14
- def initialize(conn, codec)
14
+ # @param conn [Protocol::ZMTP::Connection]
15
+ # @param codec [Codec] the socket's codec
16
+ # @param adaptive [Boolean] adapt the send level on this connection,
17
+ # within the codec's range
18
+ # @param send_hwm [Integer, nil] the socket's send HWM
19
+ # @param queued [#call, nil] whether the socket has messages queued
20
+ # to send
21
+ def initialize(conn, codec, adaptive: false, send_hwm: nil, queued: nil)
15
22
  super(conn, max_message_size: codec.max_message_size,
16
23
  arena_sentinel: Codec::ARENA_MAGIC, protocol_error: ProtocolError)
17
24
  @codec = codec
25
+ @sender = AdaptiveSender.new(codec, send_hwm: send_hwm, queued: queued) if adaptive && codec.level_range
18
26
  @dict_shipped = false
19
27
  # FrameCodec is the decoder. Starts no-dict; when a dict
20
28
  # shipment arrives on this direction, we build a fresh
@@ -27,29 +35,56 @@ module OMQ
27
35
 
28
36
 
29
37
  def send_message(parts)
30
- compressed = @codec.compress_parts(parts)
38
+ compressed = @codec.compress_parts(parts, send_codec)
31
39
  ship_dict!
32
- __getobj__.send_message(compressed)
40
+ timed { __getobj__.send_message(compressed) }
41
+ @sender&.note_batch([parts])
42
+ @sender&.maybe_adapt
33
43
  end
34
44
 
35
45
 
36
46
  def write_message(parts)
37
- compressed = @codec.compress_parts(parts)
47
+ compressed = @codec.compress_parts(parts, send_codec)
38
48
  ship_dict!
39
- __getobj__.write_message(compressed)
49
+ timed { __getobj__.write_message(compressed) }
50
+ @sender&.note_batch([parts])
40
51
  end
41
52
 
42
53
 
43
54
  def write_messages(messages)
44
- compressed = @codec.compress_messages(messages)
55
+ compressed = @codec.compress_messages(messages, send_codec)
45
56
  ship_dict!
46
- __getobj__.write_messages(compressed)
57
+ timed { __getobj__.write_messages(compressed) }
58
+ @sender&.note_batch(messages)
59
+ end
60
+
61
+
62
+ def flush
63
+ timed { __getobj__.flush }
64
+ @sender&.maybe_adapt
47
65
  end
48
66
 
49
67
 
50
68
  private
51
69
 
52
70
 
71
+ def send_codec
72
+ @sender ? @sender.frame_codec : @codec.send_codec
73
+ end
74
+
75
+
76
+ # Counts the time a write takes toward the adaptation window. A write
77
+ # waits on the link when io-stream drains its buffer, past 64 KiB.
78
+ def timed
79
+ return yield unless @sender
80
+
81
+ started = Async::Clock.now
82
+ yield
83
+ ensure
84
+ @sender&.note_write(Async::Clock.now - started) if started
85
+ end
86
+
87
+
53
88
  def decompress_arena(data, size)
54
89
  unless data.start_with?(Codec::ZSTD_MAGIC) && @codec.parse_frame_content_size(data) == size
55
90
  raise ProtocolError, "arena Frame_Content_Size mismatch"
@@ -71,7 +106,7 @@ module OMQ
71
106
 
72
107
 
73
108
  def decode_parts(parts)
74
- budget = @codec.max_message_size
109
+ budget = @decode_budget
75
110
  decoded = []
76
111
  all_dicts = true
77
112
 
@@ -9,6 +9,16 @@ module OMQ
9
9
  module ZstdTcp
10
10
  SCHEME = "zstd+tcp"
11
11
 
12
+ # Levels a connection adapts within by default, as omq.rs.
13
+ DEFAULT_LEVEL_RANGE = (-7..4)
14
+
15
+ # The level an adaptive connection starts at, and fan-out keeps: the
16
+ # end of the range nearest it when the range leaves it out.
17
+ START_LEVEL = -1
18
+
19
+ # Levels zrip accepts: -8 runs as -7, and 0 as its default level.
20
+ LEVELS = (-8..4)
21
+
12
22
 
13
23
  # WeakKeyMap keyed by Engine — the Codec for a socket lives as long
14
24
  # as the Engine (and therefore the socket) lives. When the socket is
@@ -22,21 +32,19 @@ module OMQ
22
32
  #
23
33
  # @param endpoint [String] e.g. "zstd+tcp://127.0.0.1:5555"
24
34
  # @param engine [Engine]
25
- # @param level [Integer] Zstd compression level
35
+ # @param level [Integer, Range, nil] a fixed level (-7..4), or a
36
+ # Range each connection adapts its level within. Nil adapts within
37
+ # -7..4. Fan-out sockets (PUB, XPUB, RADIO) compress a message once
38
+ # for all subscribers, so they keep a fixed level: -1, or the end
39
+ # of the range nearest it.
26
40
  # @param dict [String, nil] user-supplied dictionary bytes
27
41
  # @param auto_dict [true, Hash, nil] enable automatic dictionary
28
42
  # training. Pass `true` for defaults or `{ capacity: N }`.
29
43
  # @return [Listener]
44
+ # @raise [ArgumentError] on an unknown option or a level zrip lacks
30
45
  #
31
- def listener(endpoint, engine, level: -3, dict: nil, auto_dict: nil, **)
32
- validate_security!(engine)
33
- validate_auto_dict!(auto_dict, dict)
34
- codec = codec_for(
35
- engine,
36
- level: level,
37
- dict: dict,
38
- auto_dict: normalize_auto_dict(auto_dict),
39
- )
46
+ def listener(endpoint, engine, level: nil, dict: nil, auto_dict: nil)
47
+ codec = codec_for(engine, level: level, dict: dict, auto_dict: auto_dict)
40
48
 
41
49
  host, port = parse_endpoint(endpoint)
42
50
  host = normalize_bind_host(host)
@@ -59,22 +67,15 @@ module OMQ
59
67
  #
60
68
  # @param endpoint [String] e.g. "zstd+tcp://127.0.0.1:5555"
61
69
  # @param engine [Engine]
62
- # @param level [Integer] Zstd compression level
70
+ # @param level [Integer, Range, nil] see {.listener}
63
71
  # @param dict [String, nil] user-supplied dictionary bytes
64
72
  # @param auto_dict [true, Hash, nil] enable automatic dictionary
65
73
  # training. Pass `true` for defaults or `{ capacity: N }`.
66
74
  # @return [Dialer]
75
+ # @raise [ArgumentError] on an unknown option or a level zrip lacks
67
76
  #
68
- def dialer(endpoint, engine, level: -3, dict: nil, auto_dict: nil, **)
69
- validate_security!(engine)
70
- validate_auto_dict!(auto_dict, dict)
71
- codec = codec_for(
72
- engine,
73
- level: level,
74
- dict: dict,
75
- auto_dict: normalize_auto_dict(auto_dict),
76
- )
77
- Dialer.new(endpoint, engine, codec)
77
+ def dialer(endpoint, engine, level: nil, dict: nil, auto_dict: nil)
78
+ Dialer.new(endpoint, engine, codec_for(engine, level: level, dict: dict, auto_dict: auto_dict))
78
79
  end
79
80
 
80
81
 
@@ -104,7 +105,20 @@ module OMQ
104
105
 
105
106
  def connect_timeout(options)
106
107
  ri = options.reconnect_interval
107
- ri.is_a?(Range) ? ri.end : [ri * 10, 30].min
108
+ return ri.end if ri.is_a?(Range) && ri.end&.finite?
109
+
110
+ ri = ri.begin if ri.is_a?(Range) # endless: no cap
111
+ [ri * 10, 30].min
112
+ end
113
+
114
+
115
+ # @param engine [Engine]
116
+ # @return [Proc] whether the socket has messages queued to send
117
+ def queued_probe(engine)
118
+ routing = engine.routing
119
+ return -> { false } unless routing.respond_to?(:send_queues_drained?)
120
+
121
+ -> { !routing.send_queues_drained? }
108
122
  end
109
123
 
110
124
 
@@ -161,13 +175,53 @@ module OMQ
161
175
  end
162
176
 
163
177
 
178
+ # The socket's codec: the first bind or connect sets its options,
179
+ # and each one checks them.
164
180
  def codec_for(engine, level:, dict:, auto_dict:)
165
- @codecs[engine] ||= Codec.new level: level, dict: dict, auto_dict: auto_dict,
166
- max_message_size: engine.options.max_message_size
167
-
181
+ validate_security!(engine)
182
+ validate_auto_dict!(auto_dict, dict)
183
+ level_range(level)
184
+ @codecs[engine] ||= build_codec(engine, level, dict, normalize_auto_dict(auto_dict))
168
185
  rescue Ractor::IsolationError
169
- Codec.new level: level, dict: dict, auto_dict: auto_dict,
170
- max_message_size: engine.options.max_message_size
186
+ build_codec(engine, level, dict, normalize_auto_dict(auto_dict))
187
+ end
188
+
189
+
190
+ def build_codec(engine, level, dict, auto_dict)
191
+ range = level_range(level)
192
+ start = range ? Zrip::AdaptiveLevel.new(range, start: START_LEVEL).level : level
193
+ range = nil if fan_out?(engine.routing)
194
+ Codec.new(level: start, level_range: range, dict: dict, auto_dict: auto_dict,
195
+ max_message_size: engine.options.max_message_size)
196
+ end
197
+
198
+
199
+ # PUB, XPUB and RADIO compress each message once for all peers.
200
+ # RADIO is a draft type, loaded only by `require "omq/radio_dish"`.
201
+ def fan_out?(routing)
202
+ return true if routing.is_a?(Routing::FanOut)
203
+
204
+ return false unless defined?(Routing::Radio)
205
+
206
+ routing.is_a?(Routing::Radio)
207
+ end
208
+
209
+
210
+ # @return [Range, nil] the range to adapt within, nil for a fixed level
211
+ # @raise [ArgumentError] on a level or range zrip lacks
212
+ def level_range(level)
213
+ case level
214
+ when nil
215
+ DEFAULT_LEVEL_RANGE
216
+ when Range
217
+ Zrip::AdaptiveLevel.new(level, start: START_LEVEL) # validates the range
218
+ level
219
+ when Integer
220
+ raise ArgumentError, "level #{level} is outside #{LEVELS}" unless LEVELS.cover?(level)
221
+ nil
222
+ else
223
+ raise ArgumentError, "level must be an Integer or a Range, got #{level.inspect}"
224
+ end
171
225
  end
172
226
  end
173
227
 
@@ -218,7 +272,8 @@ module OMQ
218
272
  # @return [ZstdConnection]
219
273
  #
220
274
  def wrap_connection(conn)
221
- ZstdConnection.new(conn, @codec)
275
+ ZstdConnection.new(conn, @codec, adaptive: true, send_hwm: @engine.options.send_hwm,
276
+ queued: ZstdTcp.queued_probe(@engine))
222
277
  end
223
278
 
224
279
  end
@@ -259,7 +314,8 @@ module OMQ
259
314
  # @return [ZstdConnection]
260
315
  #
261
316
  def wrap_connection(conn)
262
- ZstdConnection.new(conn, @codec)
317
+ ZstdConnection.new(conn, @codec, adaptive: true, send_hwm: @engine.options.send_hwm,
318
+ queued: ZstdTcp.queued_probe(@engine))
263
319
  end
264
320
 
265
321
 
@@ -281,6 +337,9 @@ module OMQ
281
337
 
282
338
  on_accepted.call stream
283
339
  end
340
+ rescue *AcceptLoop::RECOVERABLE_ERRORS => error
341
+ client&.close rescue nil
342
+ AcceptLoop.recover(error, @engine, @endpoint)
284
343
  end
285
344
  rescue Async::Stop
286
345
  rescue IOError
@@ -6,12 +6,14 @@
6
6
  # require "omq/zstd"
7
7
  #
8
8
  # push = OMQ::PUSH.new
9
- # push.connect("zstd+tcp://127.0.0.1:5555", level: -3)
9
+ # push.connect("zstd+tcp://127.0.0.1:5555") # adapts in -7..4
10
+ # push.connect("zstd+tcp://127.0.0.1:5555", level: -3) # fixed level
10
11
 
11
12
  require "omq"
12
13
  require "zrip"
13
14
 
14
15
  require_relative "zstd_tcp/codec"
16
+ require_relative "zstd_tcp/adaptive_sender"
15
17
  require_relative "zstd_tcp/connection"
16
18
  require_relative "zstd_tcp/transport"
17
19
 
@@ -2,6 +2,6 @@
2
2
 
3
3
  module OMQ
4
4
  module Zstd
5
- VERSION = "0.5.1"
5
+ VERSION = "0.6.0"
6
6
  end
7
7
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: omq-zstd
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.5.1
4
+ version: 0.6.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Patrik Wenger
@@ -15,28 +15,28 @@ dependencies:
15
15
  requirements:
16
16
  - - "~>"
17
17
  - !ruby/object:Gem::Version
18
- version: '0.29'
18
+ version: '0.30'
19
19
  type: :runtime
20
20
  prerelease: false
21
21
  version_requirements: !ruby/object:Gem::Requirement
22
22
  requirements:
23
23
  - - "~>"
24
24
  - !ruby/object:Gem::Version
25
- version: '0.29'
25
+ version: '0.30'
26
26
  - !ruby/object:Gem::Dependency
27
27
  name: zrip
28
28
  requirement: !ruby/object:Gem::Requirement
29
29
  requirements:
30
30
  - - "~>"
31
31
  - !ruby/object:Gem::Version
32
- version: 0.2.2
32
+ version: 0.3.0
33
33
  type: :runtime
34
34
  prerelease: false
35
35
  version_requirements: !ruby/object:Gem::Requirement
36
36
  requirements:
37
37
  - - "~>"
38
38
  - !ruby/object:Gem::Version
39
- version: 0.2.2
39
+ version: 0.3.0
40
40
  description: Experimental zstd+tcp:// endpoint support for OMQ with per-frame Zstd
41
41
  compression, bounded decompression, in-band dictionary shipping, and sender-side
42
42
  dictionary training.
@@ -51,6 +51,8 @@ files:
51
51
  - README.md
52
52
  - RFC.md
53
53
  - lib/omq/transport/zstd_tcp.rb
54
+ - lib/omq/transport/zstd_tcp/adaptive_sender.rb
55
+ - lib/omq/transport/zstd_tcp/bottleneck.rb
54
56
  - lib/omq/transport/zstd_tcp/codec.rb
55
57
  - lib/omq/transport/zstd_tcp/connection.rb
56
58
  - lib/omq/transport/zstd_tcp/transport.rb