flow_machines 0.1.4 → 0.3.4

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: '0529f4715082ccdafa6f35703baacbf89390cb0f0bd4dc240d6c0d4b39af3419'
4
- data.tar.gz: 4ea905f876d495f69cd3e7618c3df4070b97762a325b1fc600feb7213a172348
3
+ metadata.gz: e97250f799c4ee590cdbb63df339149ea68d2786c1b7dd747389fd1856fb57d2
4
+ data.tar.gz: 9b33ae7ff3be0ed93a6b61305e613623c74128766112c5fed34d80e38d5861d5
5
5
  SHA512:
6
- metadata.gz: e7e983fa7ea9e44351963adcaaad11bc7228a5f538772489b6edf15b4bcd2fbb87491b78a552135d078a1388010c2031c8766a55d70481e87cf581be7749be65
7
- data.tar.gz: 34075606adf5898fe2d81d08fd1bc6b9460c2adc37bc6546ed880132673352b543f573393251a8e023b45424cb0934c9aeb931631cd8473c8b3c14d8cdca5d36
6
+ metadata.gz: c6af092982fc55b458cd7721247b504115b20c7b1d190766ee8edfd70ecef74761843e4d992553114587fe256ee3bba23ff14a6081e6dfbaeb4e11779389c98e
7
+ data.tar.gz: a6b302a89d3f5f45a9b695a56e5efcb8ebc9bc5c8aacea7e47a02fe97596ecad0d7283c92958120094426e4e0b660aa11e726a9ca3d80a70e548b138d1965220
data/CHANGELOG.md CHANGED
@@ -1,5 +1,62 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.3.4](https://github.com/seuros/flow_machines/compare/flow_machines/v0.3.3...flow_machines/v0.3.4) (2026-11-16)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * fix wrapped classes at load so building a value runs no Ruby ([978a8ce](https://github.com/seuros/flow_machines/commit/978a8cef9bcdc9925e94453cb5ff421b6f93b012))
9
+
10
+ ## [0.3.3](https://github.com/seuros/flow_machines/compare/flow_machines/v0.3.2...flow_machines/v0.3.3) (2026-11-16)
11
+
12
+
13
+ ### Bug Fixes
14
+
15
+ * build against matryona-machines 0.5 ([1cc6fee](https://github.com/seuros/flow_machines/commit/1cc6fee61c7e4d08626af5f4fd3319b133292d47))
16
+
17
+ ## [0.3.2](https://github.com/seuros/flow_machines/compare/flow_machines/v0.3.1...flow_machines/v0.3.2) (2026-11-14)
18
+
19
+
20
+ ### Bug Fixes
21
+
22
+ * **deps:** require matryona-machines >= 0.4 ([40763b7](https://github.com/seuros/flow_machines/commit/40763b7164a56dcc37442e6820f870448924d7f4))
23
+
24
+ ## [0.3.1](https://github.com/seuros/flow_machines/compare/flow_machines/v0.3.0...flow_machines/v0.3.1) (2026-11-14)
25
+
26
+
27
+ ### Bug Fixes
28
+
29
+ * **deps:** require matryona-machines >= 0.3 with a names_only refusal table and symbols! tables ([3230754](https://github.com/seuros/flow_machines/commit/3230754ffbe7ee763b01d597e96d8feec0a68b9d))
30
+
31
+ ## [0.3.0](https://github.com/seuros/flow_machines/compare/flow_machines/v0.2.1...flow_machines/v0.3.0) (2026-11-14)
32
+
33
+
34
+ ### ⚠ BREAKING CHANGES
35
+
36
+ * adopt matryona-machines 0.2 (shared converters, frozen-first)
37
+
38
+ ### Features
39
+
40
+ * adopt matryona-machines 0.2 (shared converters, frozen-first) ([63ccf35](https://github.com/seuros/flow_machines/commit/63ccf3565543bdf6634015c188ceb6eda1e09af0))
41
+
42
+ ## [0.2.1](https://github.com/seuros/flow_machines/compare/flow_machines/v0.2.0...flow_machines/v0.2.1) (2026-11-14)
43
+
44
+
45
+ ### Bug Fixes
46
+
47
+ * name the offending argument in every raised message and undefine allocate on native classes ([ebf4d13](https://github.com/seuros/flow_machines/commit/ebf4d13bdb180fbc58112ea7a78fd82d18345fc8))
48
+
49
+ ## [0.2.0](https://github.com/seuros/flow_machines/compare/flow_machines/v0.1.4...flow_machines/v0.2.0) (2026-11-13)
50
+
51
+
52
+ ### ⚠ BREAKING CHANGES
53
+
54
+ * converted to the fleet conventions. One exhaustive Refusal per crate, Result from every operation that can refuse, a refusal changes nothing, provable idempotent repeats are honoured, Ruby mirrors the core. No compatibility aliases. try_acquire and release return Result<(), Refusal>; in Ruby they answer symbols, which are all truthy.
55
+
56
+ ### Features
57
+
58
+ * answer credit refusals as Refusal, exhaustive enums, positional Ruby constructors ([7f96f70](https://github.com/seuros/flow_machines/commit/7f96f70933ea1e07dc00c1c160f670c03423fef2))
59
+
3
60
  ## [0.1.4](https://github.com/seuros/flow_machines/compare/flow_machines/v0.1.3...flow_machines/v0.1.4) (2026-11-06)
4
61
 
5
62
 
data/Cargo.lock ADDED
@@ -0,0 +1,307 @@
1
+ # This file is automatically @generated by Cargo.
2
+ # It is not intended for manual editing.
3
+ version = 4
4
+
5
+ [[package]]
6
+ name = "aho-corasick"
7
+ version = "1.1.5"
8
+ source = "registry+https://github.com/rust-lang/crates.io-index"
9
+ checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
10
+ dependencies = [
11
+ "memchr",
12
+ ]
13
+
14
+ [[package]]
15
+ name = "bindgen"
16
+ version = "0.72.1"
17
+ source = "registry+https://github.com/rust-lang/crates.io-index"
18
+ checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"
19
+ dependencies = [
20
+ "bitflags",
21
+ "cexpr",
22
+ "clang-sys",
23
+ "itertools",
24
+ "proc-macro2",
25
+ "quote",
26
+ "regex",
27
+ "rustc-hash",
28
+ "shlex",
29
+ "syn",
30
+ ]
31
+
32
+ [[package]]
33
+ name = "bitflags"
34
+ version = "2.13.2"
35
+ source = "registry+https://github.com/rust-lang/crates.io-index"
36
+ checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
37
+
38
+ [[package]]
39
+ name = "bytes"
40
+ version = "1.12.1"
41
+ source = "registry+https://github.com/rust-lang/crates.io-index"
42
+ checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
43
+
44
+ [[package]]
45
+ name = "cexpr"
46
+ version = "0.6.0"
47
+ source = "registry+https://github.com/rust-lang/crates.io-index"
48
+ checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
49
+ dependencies = [
50
+ "nom",
51
+ ]
52
+
53
+ [[package]]
54
+ name = "cfg-if"
55
+ version = "1.0.5"
56
+ source = "registry+https://github.com/rust-lang/crates.io-index"
57
+ checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
58
+
59
+ [[package]]
60
+ name = "clang-sys"
61
+ version = "1.9.1"
62
+ source = "registry+https://github.com/rust-lang/crates.io-index"
63
+ checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"
64
+ dependencies = [
65
+ "glob",
66
+ "libc",
67
+ "libloading",
68
+ ]
69
+
70
+ [[package]]
71
+ name = "either"
72
+ version = "1.19.0"
73
+ source = "registry+https://github.com/rust-lang/crates.io-index"
74
+ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
75
+
76
+ [[package]]
77
+ name = "flow-machines"
78
+ version = "0.4.1"
79
+ dependencies = [
80
+ "matryona-machines",
81
+ ]
82
+
83
+ [[package]]
84
+ name = "flow_machines_native"
85
+ version = "0.1.7"
86
+ dependencies = [
87
+ "flow-machines",
88
+ "magnus",
89
+ "matryona-machines",
90
+ "rb-sys",
91
+ ]
92
+
93
+ [[package]]
94
+ name = "glob"
95
+ version = "0.3.4"
96
+ source = "registry+https://github.com/rust-lang/crates.io-index"
97
+ checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
98
+
99
+ [[package]]
100
+ name = "itertools"
101
+ version = "0.13.0"
102
+ source = "registry+https://github.com/rust-lang/crates.io-index"
103
+ checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
104
+ dependencies = [
105
+ "either",
106
+ ]
107
+
108
+ [[package]]
109
+ name = "lazy_static"
110
+ version = "1.5.1"
111
+ source = "registry+https://github.com/rust-lang/crates.io-index"
112
+ checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
113
+
114
+ [[package]]
115
+ name = "libc"
116
+ version = "0.2.191"
117
+ source = "registry+https://github.com/rust-lang/crates.io-index"
118
+ checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
119
+
120
+ [[package]]
121
+ name = "libloading"
122
+ version = "0.8.9"
123
+ source = "registry+https://github.com/rust-lang/crates.io-index"
124
+ checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
125
+ dependencies = [
126
+ "cfg-if",
127
+ "windows-link",
128
+ ]
129
+
130
+ [[package]]
131
+ name = "magnus"
132
+ version = "0.9.3"
133
+ source = "registry+https://github.com/rust-lang/crates.io-index"
134
+ checksum = "40ef424404d166cbb71c8b8d19c9c589c748c4547c1afa1928c5504299f6c713"
135
+ dependencies = [
136
+ "bytes",
137
+ "magnus-macros",
138
+ "rb-sys",
139
+ "rb-sys-env",
140
+ "seq-macro",
141
+ ]
142
+
143
+ [[package]]
144
+ name = "magnus-macros"
145
+ version = "0.9.1"
146
+ source = "registry+https://github.com/rust-lang/crates.io-index"
147
+ checksum = "9dafde2eeb66f090e0f326112323eb8324b12cb32b5d1210e541d3df6b0ce77e"
148
+ dependencies = [
149
+ "proc-macro2",
150
+ "quote",
151
+ "syn",
152
+ ]
153
+
154
+ [[package]]
155
+ name = "matryona-machines"
156
+ version = "0.6.0"
157
+ source = "registry+https://github.com/rust-lang/crates.io-index"
158
+ checksum = "cf8a06ab02efd767270815a1f515a40bbf3bfc77038e9360676ebe8d47833b07"
159
+ dependencies = [
160
+ "magnus",
161
+ ]
162
+
163
+ [[package]]
164
+ name = "memchr"
165
+ version = "2.8.3"
166
+ source = "registry+https://github.com/rust-lang/crates.io-index"
167
+ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
168
+
169
+ [[package]]
170
+ name = "minimal-lexical"
171
+ version = "0.2.1"
172
+ source = "registry+https://github.com/rust-lang/crates.io-index"
173
+ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
174
+
175
+ [[package]]
176
+ name = "nom"
177
+ version = "7.1.3"
178
+ source = "registry+https://github.com/rust-lang/crates.io-index"
179
+ checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
180
+ dependencies = [
181
+ "memchr",
182
+ "minimal-lexical",
183
+ ]
184
+
185
+ [[package]]
186
+ name = "proc-macro2"
187
+ version = "1.0.107"
188
+ source = "registry+https://github.com/rust-lang/crates.io-index"
189
+ checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
190
+ dependencies = [
191
+ "unicode-ident",
192
+ ]
193
+
194
+ [[package]]
195
+ name = "quote"
196
+ version = "1.0.47"
197
+ source = "registry+https://github.com/rust-lang/crates.io-index"
198
+ checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
199
+ dependencies = [
200
+ "proc-macro2",
201
+ ]
202
+
203
+ [[package]]
204
+ name = "rb-sys"
205
+ version = "0.9.130"
206
+ source = "registry+https://github.com/rust-lang/crates.io-index"
207
+ checksum = "02faf625bb10ba893e3ae620f19c9fb1b5f8fcae0fe4eb86bb3f2230fad75edb"
208
+ dependencies = [
209
+ "rb-sys-build",
210
+ ]
211
+
212
+ [[package]]
213
+ name = "rb-sys-build"
214
+ version = "0.9.130"
215
+ source = "registry+https://github.com/rust-lang/crates.io-index"
216
+ checksum = "05be6f9c86fe5482808162826f6c047d093b3670582296c770de1d94f8066694"
217
+ dependencies = [
218
+ "bindgen",
219
+ "lazy_static",
220
+ "proc-macro2",
221
+ "quote",
222
+ "regex",
223
+ "shell-words",
224
+ "syn",
225
+ ]
226
+
227
+ [[package]]
228
+ name = "rb-sys-env"
229
+ version = "0.2.3"
230
+ source = "registry+https://github.com/rust-lang/crates.io-index"
231
+ checksum = "cca7ad6a7e21e72151d56fe2495a259b5670e204c3adac41ee7ef676ea08117a"
232
+
233
+ [[package]]
234
+ name = "regex"
235
+ version = "1.13.1"
236
+ source = "registry+https://github.com/rust-lang/crates.io-index"
237
+ checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
238
+ dependencies = [
239
+ "aho-corasick",
240
+ "memchr",
241
+ "regex-automata",
242
+ "regex-syntax",
243
+ ]
244
+
245
+ [[package]]
246
+ name = "regex-automata"
247
+ version = "0.4.18"
248
+ source = "registry+https://github.com/rust-lang/crates.io-index"
249
+ checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
250
+ dependencies = [
251
+ "aho-corasick",
252
+ "memchr",
253
+ "regex-syntax",
254
+ ]
255
+
256
+ [[package]]
257
+ name = "regex-syntax"
258
+ version = "0.8.11"
259
+ source = "registry+https://github.com/rust-lang/crates.io-index"
260
+ checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
261
+
262
+ [[package]]
263
+ name = "rustc-hash"
264
+ version = "2.1.3"
265
+ source = "registry+https://github.com/rust-lang/crates.io-index"
266
+ checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
267
+
268
+ [[package]]
269
+ name = "seq-macro"
270
+ version = "0.3.6"
271
+ source = "registry+https://github.com/rust-lang/crates.io-index"
272
+ checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc"
273
+
274
+ [[package]]
275
+ name = "shell-words"
276
+ version = "1.1.1"
277
+ source = "registry+https://github.com/rust-lang/crates.io-index"
278
+ checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77"
279
+
280
+ [[package]]
281
+ name = "shlex"
282
+ version = "1.3.0"
283
+ source = "registry+https://github.com/rust-lang/crates.io-index"
284
+ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
285
+
286
+ [[package]]
287
+ name = "syn"
288
+ version = "2.0.119"
289
+ source = "registry+https://github.com/rust-lang/crates.io-index"
290
+ checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
291
+ dependencies = [
292
+ "proc-macro2",
293
+ "quote",
294
+ "unicode-ident",
295
+ ]
296
+
297
+ [[package]]
298
+ name = "unicode-ident"
299
+ version = "1.0.27"
300
+ source = "registry+https://github.com/rust-lang/crates.io-index"
301
+ checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
302
+
303
+ [[package]]
304
+ name = "windows-link"
305
+ version = "0.2.1"
306
+ source = "registry+https://github.com/rust-lang/crates.io-index"
307
+ checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
data/Cargo.toml CHANGED
@@ -10,6 +10,7 @@ license = "MIT"
10
10
 
11
11
  [workspace.dependencies]
12
12
  flow-machines = { path = "ext/flow_machines_native/core" }
13
+ matryona-machines = { version = ">=0.6", default-features = false }
13
14
  magnus = { version = "0.9.3", default-features = false }
14
15
  rb-sys = { version = "0.9.130", default-features = false, features = ["stable-api-compiled-fallback"] }
15
16
 
data/README.md CHANGED
@@ -11,12 +11,12 @@ gem 'flow_machines'
11
11
  ```
12
12
 
13
13
  ```ruby
14
- window = FlowMachines::CreditWindow.new(capacity: 100)
15
- control = FlowMachines::Watermarks.new(low: 20, high: 80)
14
+ window = FlowMachines::CreditWindow.new(100)
15
+ control = FlowMachines::Watermarks.new(20, 80)
16
16
 
17
17
  # Producer side: ask before you enqueue.
18
18
  def enqueue(job)
19
- return false unless window.try_acquire(1)
19
+ return false unless window.try_acquire(1) == :acquired
20
20
  queue << job
21
21
  producer.pause if control.observe(queue.length) == :pause
22
22
  true
@@ -85,32 +85,32 @@ sequenceDiagram
85
85
  participant C as Consumer
86
86
 
87
87
  P->>W: try_acquire(1)
88
- W-->>P: true (1 in flight)
88
+ W-->>P: acquired (1 in flight)
89
89
  P->>M: observe(1)
90
90
  M-->>P: unchanged
91
91
 
92
92
  P->>W: try_acquire(1)
93
- W-->>P: true (2 in flight)
93
+ W-->>P: acquired (2 in flight)
94
94
  P->>M: observe(2)
95
95
  M-->>P: unchanged
96
96
 
97
97
  P->>W: try_acquire(1)
98
- W-->>P: true (3 in flight)
98
+ W-->>P: acquired (3 in flight)
99
99
  P->>M: observe(3)
100
100
  M-->>P: pause
101
101
  Note over P: stops producing
102
102
 
103
103
  P->>W: try_acquire(1)
104
- W-->>P: false (window full)
104
+ W-->>P: insufficient (window full)
105
105
 
106
106
  C->>W: release(1)
107
- W-->>C: true (2 in flight)
107
+ W-->>C: released (2 in flight)
108
108
  C->>M: observe(2)
109
109
  M-->>C: unchanged
110
110
  Note over P: still paused, no flapping
111
111
 
112
112
  C->>W: release(1)
113
- W-->>C: true (1 in flight)
113
+ W-->>C: released (1 in flight)
114
114
  C->>M: observe(1)
115
115
  M-->>C: resume
116
116
  Note over P: starts producing again
@@ -121,41 +121,41 @@ sequenceDiagram
121
121
  A window has a capacity. Acquiring takes units out of it, releasing puts them back. Both are all-or-nothing.
122
122
 
123
123
  ```ruby
124
- window = FlowMachines::CreditWindow.new(capacity: 3)
124
+ window = FlowMachines::CreditWindow.new(3)
125
125
  window.capacity # => 3
126
126
  window.in_flight # => 0
127
127
  window.available # => 3
128
128
 
129
- window.try_acquire(2) # => true
130
- window.try_acquire(2) # => false, only 1 left and we asked for 2
129
+ window.try_acquire(2) # => :acquired
130
+ window.try_acquire(2) # => :insufficient, only 1 left and we asked for 2
131
131
  window.in_flight # => 2
132
132
  window.available # => 1
133
133
  ```
134
134
 
135
- A refused acquire takes nothing. There is no partial grant, so you never have to figure out how much you actually got.
135
+ A refused acquire takes nothing. There is no partial grant, so you never have to figure out how much you actually got. Both answers are symbols, and both are truthy: compare against `:acquired`, don't write `if window.try_acquire(1)`.
136
136
 
137
137
  Release is the same deal in reverse:
138
138
 
139
139
  ```ruby
140
- window.release(3) # => false, only 2 are out
141
- window.release(2) # => true
142
- window.release(1) # => false, nothing is out
140
+ window.release(3) # => :exceeds_in_flight, only 2 are out
141
+ window.release(2) # => :released
142
+ window.release(1) # => :exceeds_in_flight, nothing is out
143
143
  window.available # => 3
144
144
  ```
145
145
 
146
- The window is a count, not a ledger. It doesn't know who acquired what. If your code acquires on enqueue and forgets to release on a cancelled job, the window will slowly fill with ghosts. Release every unit you acquire exactly once, including on the error path.
146
+ The window is a count, not a ledger. It doesn't know who acquired what, so it cannot tell a repeated release from a legitimate one: release the same job twice and the second call answers `:released` too, as long as anything is still out, and quietly hands back somebody else's credit. Only when nothing is left does it answer `:exceeds_in_flight`. If your code acquires on enqueue and forgets to release on a cancelled job, the window will slowly fill with ghosts. Release every unit you acquire exactly once, including on the error path.
147
147
 
148
148
  ## The Watermarks
149
149
 
150
150
  A watermarks controller starts running. Feed it the current occupancy after every change and it answers with one of three words.
151
151
 
152
152
  ```ruby
153
- control = FlowMachines::Watermarks.new(low: 2, high: 5)
153
+ control = FlowMachines::Watermarks.new(2, 5)
154
154
  control.state # => :running
155
155
 
156
156
  control.observe(4) # => :unchanged
157
157
  control.observe(5) # => :pause
158
- control.paused? # => true
158
+ control.state # => :paused
159
159
  control.observe(5) # => :unchanged, already paused
160
160
  control.observe(3) # => :unchanged, above low, stay paused
161
161
  control.observe(2) # => :resume
@@ -164,7 +164,7 @@ control.observe(0) # => :unchanged
164
164
 
165
165
  The gap between `low` and `high` is the whole point. A controller that paused at 5 and resumed at 4 would flap every time one job finished. This one pauses at 5 and won't resume until the queue drains to 2. That's hysteresis, and it's why your producer doesn't get whiplash.
166
166
 
167
- `:pause` and `:resume` are edges. You get each one once per crossing. If a producer connects late and missed the edge, ask `state` or `paused?` instead of waiting for a signal that already went by.
167
+ `:pause` and `:resume` are edges. You get each one once per crossing. If a producer connects late and missed the edge, ask `state` instead of waiting for a signal that already went by.
168
168
 
169
169
  Occupancy is whatever you want to measure. Queue length is the obvious choice. Bytes buffered, open connections, or outstanding requests all work just as well, as long as you measure the same thing every time.
170
170
 
@@ -173,8 +173,8 @@ Occupancy is whatever you want to measure. Queue length is the obvious choice. B
173
173
  The window and the controller don't know about each other. You wire them around your queue. Here's a cancellation path, the one everyone forgets:
174
174
 
175
175
  ```ruby
176
- window = FlowMachines::CreditWindow.new(capacity: 4)
177
- control = FlowMachines::Watermarks.new(low: 1, high: 3)
176
+ window = FlowMachines::CreditWindow.new(4)
177
+ control = FlowMachines::Watermarks.new(1, 3)
178
178
  queue = []
179
179
 
180
180
  3.times do |id|
@@ -182,28 +182,48 @@ queue = []
182
182
  queue << id
183
183
  control.observe(queue.length) # :unchanged, :unchanged, :pause
184
184
  end
185
- control.paused? # => true
185
+ control.state # => :paused
186
186
 
187
187
  # A job is cancelled before it ever ran. Still a release.
188
188
  queue.pop
189
- window.release(1) # => true
189
+ window.release(1) # => :released
190
190
  control.observe(queue.length) # => :unchanged, 2 is above low
191
191
 
192
192
  # One finishes normally.
193
193
  queue.shift
194
- window.release(1) # => true
194
+ window.release(1) # => :released
195
195
  control.observe(queue.length) # => :resume
196
196
  window.in_flight # => 1, same as queue.length
197
197
  ```
198
198
 
199
199
  If the cancelled job hadn't released its credit, `in_flight` would read 2 while the queue held 1, and the window would be one berth short forever.
200
200
 
201
+ ### Every answer
202
+
203
+ A call that is honoured answers with a value. A call that is not honoured answers with one of the refusal symbols below, and only those, and changes nothing. Each refusal is the snake_case of one core `Refusal` variant; there is no catch-all symbol, and a refusal never raises.
204
+
205
+ | Call | Honoured | Refusals |
206
+ | --- | --- | --- |
207
+ | `CreditWindow#try_acquire(units)` | `:acquired` | `:insufficient` (`units` is more than `available`) |
208
+ | `CreditWindow#release(units)` | `:released` | `:exceeds_in_flight` (`units` is more than `in_flight`) |
209
+ | `Watermarks#observe(occupancy)` | `:pause`, `:resume`, `:unchanged` | none |
210
+
211
+ `CreditWindow.new(capacity)`, `capacity`, `in_flight`, `available` and `Watermarks#state` (`:running` or `:paused`) never refuse. `Watermarks.new(low, high)` answers a controller or raises `RangeError` unless `low < high`.
212
+
213
+ No answer records a clock: neither object takes one, so every answer depends only on the counts.
214
+
201
215
  ## The Rules of the Escort
202
216
 
203
- - **Counts are Integers** in `0..4_294_967_295`. Capacity, acquire, and release units must be at least 1. Floats and strings raise `TypeError`, zero raises `ArgumentError`, negatives and anything past the range raise `RangeError`.
204
- - **Thresholds obey `0 <= low < high`.** Equal thresholds or a reversed pair raise `ArgumentError`. A `low` of zero is fine: resume only when fully drained.
205
- - **Keywords only.** `CreditWindow.new(3)` and `Watermarks.new(1, 2)` raise `ArgumentError`. So does an unknown keyword.
206
- - **A rejected observation changes nothing.** Pass the controller a float and it raises, but its state is exactly what it was before.
217
+ - **Counts are Integers** in `0..4_294_967_295`. Capacity, acquire and release units, and `high` must be at least 1. Floats and strings raise `TypeError`; zero where 1 is the minimum, negatives and anything past the range raise `RangeError`.
218
+ - **Thresholds obey `0 <= low < high`.** Equal thresholds or a reversed pair raise `RangeError`. A `low` of zero is fine: resume only when fully drained.
219
+ - **Positional, like the core.** `CreditWindow.new(capacity)` and `Watermarks.new(low, high)`, in that order. There are no keywords and no defaults. Pass a Hash where a count belongs and the `TypeError` names the argument: `capacity must be an Integer`.
220
+ - **Exceptions are two.** Wrong type is `TypeError`, a value the core does not accept is `RangeError`, and both messages name the argument. `ArgumentError` only ever comes from Ruby itself, for arity.
221
+ - **Conversions come first.** Every argument is checked before the core is called, and after it the binding only turns the core's answer into a symbol, so a raise never costs a credit.
222
+ - **A refusal is a symbol, and nothing changed.** `:insufficient` and `:exceeds_in_flight` leave `in_flight` and `available` exactly as they were. Nothing is granted or returned in part.
223
+ - **No repeat is recognised.** Credits are an aggregate count with no owner, so the window cannot prove that a release, or an acquire, is a replay of an earlier one. Every call is counted. Releasing each unit exactly once is yours to get right.
224
+ - **`:unchanged` is an answer, not a refusal.** `observe` accepts every reading. `:pause` and `:resume` moved the state; `:unchanged` left it alone.
225
+ - **No clock, no handles.** Neither object reads time or issues ids, so there is nothing to scope and nothing to resume after a restart: rebuild the window and re-acquire what is still in flight.
226
+ - **Malformed input changes nothing.** Pass the controller a float and it raises, but its state is exactly what it was before.
207
227
  - **No copies.** `dup` and `clone` raise `TypeError`. Live accounting isn't something you want two of.
208
228
  - **Frozen means frozen.** `freeze` either object and every mutation raises `FrozenError`.
209
229
 
@@ -1,5 +1,41 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.4.1](https://github.com/seuros/flow_machines/compare/flow-machines-v0.4.0...flow-machines-v0.4.1) (2026-11-16)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * build against matryona-machines 0.5 ([1cc6fee](https://github.com/seuros/flow_machines/commit/1cc6fee61c7e4d08626af5f4fd3319b133292d47))
9
+
10
+ ## [0.4.0](https://github.com/seuros/flow_machines/compare/flow-machines-v0.3.1...flow-machines-v0.4.0) (2026-11-14)
11
+
12
+
13
+ ### ⚠ BREAKING CHANGES
14
+
15
+ * adopt matryona-machines 0.2 (shared converters, frozen-first)
16
+
17
+ ### Features
18
+
19
+ * adopt matryona-machines 0.2 (shared converters, frozen-first) ([63ccf35](https://github.com/seuros/flow_machines/commit/63ccf3565543bdf6634015c188ceb6eda1e09af0))
20
+
21
+ ## [0.3.1](https://github.com/seuros/flow_machines/compare/flow-machines-v0.3.0...flow-machines-v0.3.1) (2026-11-14)
22
+
23
+
24
+ ### Bug Fixes
25
+
26
+ * name the offending argument in every raised message and undefine allocate on native classes ([ebf4d13](https://github.com/seuros/flow_machines/commit/ebf4d13bdb180fbc58112ea7a78fd82d18345fc8))
27
+
28
+ ## [0.3.0](https://github.com/seuros/flow_machines/compare/flow-machines-v0.2.2...flow-machines-v0.3.0) (2026-11-13)
29
+
30
+
31
+ ### ⚠ BREAKING CHANGES
32
+
33
+ * converted to the fleet conventions. One exhaustive Refusal per crate, Result from every operation that can refuse, a refusal changes nothing, provable idempotent repeats are honoured, Ruby mirrors the core. No compatibility aliases. try_acquire and release return Result<(), Refusal>; in Ruby they answer symbols, which are all truthy.
34
+
35
+ ### Features
36
+
37
+ * answer credit refusals as Refusal, exhaustive enums, positional Ruby constructors ([7f96f70](https://github.com/seuros/flow_machines/commit/7f96f70933ea1e07dc00c1c160f670c03423fef2))
38
+
3
39
  ## [0.2.2](https://github.com/seuros/flow_machines/compare/flow-machines-v0.2.1...flow-machines-v0.2.2) (2026-11-06)
4
40
 
5
41
 
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "flow-machines"
3
- version = "0.2.2"
3
+ version = "0.4.1"
4
4
  edition.workspace = true
5
5
  rust-version.workspace = true
6
6
  license.workspace = true
@@ -8,6 +8,8 @@ description = "Allocation-free capacity credits and hysteretic backpressure deci
8
8
  keywords = ["backpressure", "flow-control", "credits", "watermark", "no-std"]
9
9
  categories = ["no-std", "algorithms"]
10
10
  readme = "README.md"
11
- exclude = ["src/**/tests.rs", "tests/"]
11
+ exclude = ["src/**/tests.rs", "src/tests/", "tests/", "src/test_support.rs"]
12
+ [dev-dependencies]
13
+ matryona-machines = { workspace = true, features = ["testing"] }
12
14
  [lints]
13
15
  workspace = true
@@ -10,28 +10,35 @@ Decision-only flow control with no runtime, I/O, allocator, or dependencies.
10
10
 
11
11
  ```rust
12
12
  use core::num::NonZeroU32;
13
- use flow_machines::CreditWindow;
13
+ use flow_machines::{CreditWindow, Refusal};
14
14
 
15
15
  # fn example() -> Option<()> {
16
16
  let mut window = CreditWindow::new(NonZeroU32::new(2)?);
17
- assert!(window.try_acquire(NonZeroU32::MIN));
18
- assert!(window.try_acquire(NonZeroU32::MIN));
19
- assert!(!window.try_acquire(NonZeroU32::MIN));
20
- assert!(window.release(NonZeroU32::MIN));
17
+ assert_eq!(window.try_acquire(NonZeroU32::MIN), Ok(()));
18
+ assert_eq!(window.try_acquire(NonZeroU32::MIN), Ok(()));
19
+ assert_eq!(
20
+ window.try_acquire(NonZeroU32::MIN),
21
+ Err(Refusal::Insufficient { available: 0 }),
22
+ );
23
+ assert_eq!(window.release(NonZeroU32::MIN), Ok(()));
21
24
  assert_eq!(window.available(), 1);
25
+ assert_eq!(
26
+ window.release(NonZeroU32::new(2)?),
27
+ Err(Refusal::ExceedsInFlight { in_flight: 1 }),
28
+ );
22
29
  # Some(())
23
30
  # }
24
31
  # assert_eq!(example(), Some(()));
25
32
  ```
26
33
 
27
- Acquisition and release are all-or-nothing. Failed operations leave state
34
+ Acquisition and release are all-or-nothing. A refused operation leaves state
28
35
  unchanged; capacity never overflows. Units can be requests, messages, or bytes,
29
36
  but must be consistent within a window.
30
37
 
31
38
  This is **aggregate accounting**, not an owned-permit API. The adapter must return
32
39
  each acquired credit exactly once, including on cancellation and failure.
33
- A release larger than the outstanding balance is rejected, but repeated releases
34
- cannot always be distinguished from legitimate completions. Credits are local
40
+ A release larger than the outstanding balance is refused, but a repeated release
41
+ cannot be distinguished from a legitimate completion. Credits are local
35
42
  state, not authenticated distributed permissions.
36
43
 
37
44
  ## High/Low Watermarks
@@ -57,3 +64,28 @@ Newly attached producers should inspect `state()` as well as future signals.
57
64
 
58
65
  Watermarks do not enforce capacity. Combine them with credits: producers should
59
66
  honor the signals, while credit acquisition remains the hard admission boundary.
67
+
68
+ ## Contract
69
+
70
+ - **Refusals.** `Refusal` is the crate's only refusal type. `try_acquire`
71
+ answers `Err(Refusal::Insufficient { available })` when `units` exceeds
72
+ `available()`; `release` answers `Err(Refusal::ExceedsInFlight { in_flight })`
73
+ when `units` exceeds `in_flight()`. Each carries the balance that was
74
+ compared against. A refused call changes nothing: the window equals a clone
75
+ taken before the call.
76
+ - **Honoured outcomes.** `Ok(())` from `try_acquire` and `release` means all
77
+ `units` moved. `Watermarks::observe` never refuses: `Signal::Pause` and
78
+ `Signal::Resume` are the two edges, `Signal::Unchanged` changed nothing.
79
+ - **Repeats.** None is recognised. Credits are an aggregate count with no
80
+ owner or handle, so the window cannot prove that a call replays an earlier
81
+ one. A repeated `release` is honoured while units remain in flight and
82
+ refused with `ExceedsInFlight` once they do not.
83
+ - **Construction.** `CreditWindow::new` cannot fail. `Watermarks::new` answers
84
+ `None` unless `low < high`.
85
+ - **Scopes and restarts.** The crate issues no ids and holds no handles, so
86
+ there is no scope and nothing to resume. After a restart, build a new window
87
+ and re-acquire what is still in flight.
88
+ - **Time.** No call takes or reads a clock. Every number is a count in the
89
+ caller's unit.
90
+ - **Exhaustive.** `Refusal`, `FlowState` and `Signal` are exhaustive: a new
91
+ variant is a breaking change every `match` must handle.
@@ -1,5 +1,7 @@
1
1
  use core::num::NonZeroU32;
2
2
 
3
+ use crate::Refusal;
4
+
3
5
  /// Aggregate capacity accounting for caller-owned work.
4
6
  ///
5
7
  /// The caller must serialize this state with admission and return every acquired
@@ -20,26 +22,40 @@ impl CreditWindow {
20
22
  }
21
23
  }
22
24
 
23
- /// Acquire all requested units, or return `false` without changing state.
24
- #[must_use]
25
- pub const fn try_acquire(&mut self, units: NonZeroU32) -> bool {
26
- if units.get() > self.available() {
27
- return false;
25
+ /// Acquire all requested units.
26
+ ///
27
+ /// # Errors
28
+ ///
29
+ /// [`Refusal::Insufficient`] when `units` exceeds [`Self::available`]:
30
+ /// there is no partial grant and nothing changes.
31
+ pub const fn try_acquire(&mut self, units: NonZeroU32) -> Result<(), Refusal> {
32
+ let available = self.available();
33
+ if units.get() > available {
34
+ return Err(Refusal::Insufficient { available });
28
35
  }
29
36
  self.in_flight += units.get();
30
- true
37
+ Ok(())
31
38
  }
32
39
 
33
- /// Return all requested units, or return `false` if that exceeds the balance.
40
+ /// Return all requested units.
34
41
  ///
35
- /// A successful return does not prove that this particular work owned credits.
36
- #[must_use]
37
- pub const fn release(&mut self, units: NonZeroU32) -> bool {
42
+ /// The window counts units, not permits: an honoured release does not
43
+ /// prove that this particular work owned credits, so a repeated release
44
+ /// cannot be recognised as a repeat. It is honoured while units remain in
45
+ /// flight and refused once they do not.
46
+ ///
47
+ /// # Errors
48
+ ///
49
+ /// [`Refusal::ExceedsInFlight`] when `units` exceeds [`Self::in_flight`]:
50
+ /// there is no partial return and nothing changes.
51
+ pub const fn release(&mut self, units: NonZeroU32) -> Result<(), Refusal> {
38
52
  if units.get() > self.in_flight {
39
- return false;
53
+ return Err(Refusal::ExceedsInFlight {
54
+ in_flight: self.in_flight,
55
+ });
40
56
  }
41
57
  self.in_flight -= units.get();
42
- true
58
+ Ok(())
43
59
  }
44
60
 
45
61
  /// Maximum outstanding units.
@@ -57,6 +73,7 @@ impl CreditWindow {
57
73
  /// Units still available for acquisition.
58
74
  #[must_use]
59
75
  pub const fn available(&self) -> u32 {
76
+ // in_flight <= capacity: `try_acquire` grants at most `available()`.
60
77
  self.capacity.get() - self.in_flight
61
78
  }
62
79
  }
@@ -1,8 +1,13 @@
1
1
  #![no_std]
2
+ #![cfg_attr(not(test), deny(clippy::indexing_slicing))]
2
3
  #![doc = include_str!("../README.md")]
3
4
 
4
5
  mod credits;
6
+ mod refusal;
7
+ #[cfg(test)]
8
+ mod test_support;
5
9
  mod watermarks;
6
10
 
7
11
  pub use credits::CreditWindow;
12
+ pub use refusal::Refusal;
8
13
  pub use watermarks::{FlowState, Signal, Watermarks};
@@ -0,0 +1,31 @@
1
+ use core::fmt;
2
+
3
+ /// Why a call was not honoured. A refused call changes nothing.
4
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
5
+ pub enum Refusal {
6
+ /// The acquisition asks for more units than the window has available.
7
+ Insufficient {
8
+ /// Units the window could still grant.
9
+ available: u32,
10
+ },
11
+ /// The release returns more units than the window accounts as in flight.
12
+ ExceedsInFlight {
13
+ /// Units the window accounts as outstanding.
14
+ in_flight: u32,
15
+ },
16
+ }
17
+
18
+ impl fmt::Display for Refusal {
19
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20
+ match self {
21
+ Self::Insufficient { available } => {
22
+ write!(f, "more units asked for than the {available} available")
23
+ }
24
+ Self::ExceedsInFlight { in_flight } => {
25
+ write!(f, "more units returned than the {in_flight} in flight")
26
+ }
27
+ }
28
+ }
29
+ }
30
+
31
+ impl core::error::Error for Refusal {}
@@ -0,0 +1,21 @@
1
+ //! Helpers shared by the crate's test modules.
2
+
3
+ use core::num::NonZeroU32;
4
+
5
+ use matryona_machines::testing::XorShift64;
6
+
7
+ /// A positive test amount; zero is a broken test assumption.
8
+ pub fn nonzero(value: u32) -> NonZeroU32 {
9
+ let Some(value) = NonZeroU32::new(value) else {
10
+ panic!("test amounts are positive");
11
+ };
12
+ value
13
+ }
14
+
15
+ /// The next draw of `rng`, in `0..bound`.
16
+ pub fn below(rng: &mut XorShift64, bound: u32) -> u32 {
17
+ let Ok(draw) = u32::try_from(rng.below(u64::from(bound))) else {
18
+ panic!("a draw below a u32 fits a u32");
19
+ };
20
+ draw
21
+ }
@@ -2,7 +2,6 @@ use core::num::NonZeroU32;
2
2
 
3
3
  /// Whether a producer should currently run.
4
4
  #[derive(Debug, Clone, Copy, PartialEq, Eq)]
5
- #[non_exhaustive]
6
5
  pub enum FlowState {
7
6
  /// The producer may attempt admission.
8
7
  Running,
@@ -12,7 +11,6 @@ pub enum FlowState {
12
11
 
13
12
  /// A state transition to propagate to a producer.
14
13
  #[derive(Debug, Clone, Copy, PartialEq, Eq)]
15
- #[non_exhaustive]
16
14
  pub enum Signal {
17
15
  /// Stop producing until resumed.
18
16
  Pause,
@@ -45,18 +43,28 @@ impl Watermarks {
45
43
  }
46
44
 
47
45
  /// Observe occupancy and emit a pause/resume edge when a threshold is crossed.
46
+ ///
47
+ /// Never refuses: every `u32` is a valid reading and every answer is
48
+ /// honoured. [`Signal::Unchanged`] changed nothing.
48
49
  #[must_use]
49
50
  pub const fn observe(&mut self, occupancy: u32) -> Signal {
50
51
  match self.state {
51
- FlowState::Running if occupancy >= self.high.get() => {
52
- self.state = FlowState::Paused;
53
- Signal::Pause
52
+ FlowState::Running => {
53
+ if occupancy >= self.high.get() {
54
+ self.state = FlowState::Paused;
55
+ Signal::Pause
56
+ } else {
57
+ Signal::Unchanged
58
+ }
54
59
  }
55
- FlowState::Paused if occupancy <= self.low => {
56
- self.state = FlowState::Running;
57
- Signal::Resume
60
+ FlowState::Paused => {
61
+ if occupancy <= self.low {
62
+ self.state = FlowState::Running;
63
+ Signal::Resume
64
+ } else {
65
+ Signal::Unchanged
66
+ }
58
67
  }
59
- _ => Signal::Unchanged,
60
68
  }
61
69
  }
62
70
 
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "flow_machines_native"
3
- version = "0.1.3"
3
+ version = "0.1.7"
4
4
  edition.workspace = true
5
5
  rust-version.workspace = true
6
6
  license.workspace = true
@@ -17,6 +17,7 @@ flow-machines.workspace = true
17
17
  magnus.workspace = true
18
18
  # Supplies the stable Ruby API when generated bindings lag a Ruby release.
19
19
  rb-sys.workspace = true
20
+ matryona-machines = { workspace = true, features = ["ruby"] }
20
21
 
21
22
  [lints]
22
23
  workspace = true
@@ -1,37 +1,47 @@
1
1
  //! `FlowMachines::CreditWindow`: aggregate counts, not individually owned permits.
2
2
 
3
3
  use std::cell::RefCell;
4
+ use std::num::NonZeroU32;
4
5
 
5
- use flow_machines::CreditWindow;
6
- use magnus::scan_args::{get_kwargs, scan_args};
6
+ use flow_machines::{CreditWindow, Refusal};
7
7
  use magnus::typed_data::Obj;
8
- use magnus::{Error, RHash, RModule, Ruby, Value, function, method, prelude::*};
8
+ use magnus::{Error, RModule, Ruby, Symbol, Value, function, method, prelude::*};
9
+ use matryona_machines::ruby::{Class, SymbolNames, positive, symbol};
9
10
 
10
- use crate::{Count, positive};
11
+ use crate::Refusals;
11
12
 
12
13
  #[magnus::wrap(class = "FlowMachines::CreditWindow", free_immediately, size)]
13
14
  struct Wrapper(RefCell<CreditWindow>);
14
15
 
15
16
  impl Wrapper {
16
- fn new(ruby: &Ruby, args: &[Value]) -> Result<Self, Error> {
17
- let args = scan_args::<(), (), (), (), RHash, ()>(args)?;
18
- let (capacity,) =
19
- get_kwargs::<_, (Count,), (), ()>(args.keywords, &["capacity"], &[])?.required;
20
- Ok(Self(RefCell::new(CreditWindow::new(positive(
21
- ruby, capacity,
22
- )?))))
17
+ fn new(capacity: Value) -> Result<Self, Error> {
18
+ let capacity = positive(capacity, "capacity")?;
19
+ Ok(Self(RefCell::new(CreditWindow::new(capacity))))
23
20
  }
24
21
 
25
- fn try_acquire(ruby: &Ruby, rb_self: Obj<Self>, units: Count) -> Result<bool, Error> {
26
- rb_self.check_frozen()?;
27
- let units = positive(ruby, units)?;
28
- Ok(rb_self.0.borrow_mut().try_acquire(units))
22
+ fn try_acquire(ruby: &Ruby, rb_self: Obj<Self>, units: Value) -> Result<Symbol, Error> {
23
+ Self::apply(ruby, rb_self, units, CreditWindow::try_acquire, "acquired")
24
+ }
25
+
26
+ fn release(ruby: &Ruby, rb_self: Obj<Self>, units: Value) -> Result<Symbol, Error> {
27
+ Self::apply(ruby, rb_self, units, CreditWindow::release, "released")
29
28
  }
30
29
 
31
- fn release(ruby: &Ruby, rb_self: Obj<Self>, units: Count) -> Result<bool, Error> {
30
+ /// Check and convert everything that can raise, then call the core once.
31
+ fn apply(
32
+ ruby: &Ruby,
33
+ rb_self: Obj<Self>,
34
+ units: Value,
35
+ operation: fn(&mut CreditWindow, NonZeroU32) -> Result<(), Refusal>,
36
+ honoured: &'static str,
37
+ ) -> Result<Symbol, Error> {
32
38
  rb_self.check_frozen()?;
33
- let units = positive(ruby, units)?;
34
- Ok(rb_self.0.borrow_mut().release(units))
39
+ let units = positive(units, "units")?;
40
+ let outcome = operation(&mut rb_self.0.borrow_mut(), units);
41
+ Ok(symbol(
42
+ ruby,
43
+ outcome.map_or_else(|refused| Refusals::name(&refused), |()| honoured),
44
+ ))
35
45
  }
36
46
 
37
47
  fn capacity(&self) -> u32 {
@@ -45,26 +55,19 @@ impl Wrapper {
45
55
  fn available(&self) -> u32 {
46
56
  self.0.borrow().available()
47
57
  }
48
-
49
- fn inspect(&self) -> String {
50
- let window = self.0.borrow();
51
- format!(
52
- "#<FlowMachines::CreditWindow capacity={} in_flight={} available={}>",
53
- window.capacity(),
54
- window.in_flight(),
55
- window.available()
56
- )
57
- }
58
58
  }
59
59
 
60
60
  /// Register the credit-window class under the gem namespace.
61
61
  pub fn define(ruby: &Ruby, module: RModule) -> Result<(), Error> {
62
62
  let class = module.define_class("CreditWindow", ruby.class_object())?;
63
- class.define_singleton_method("new", function!(Wrapper::new, -1))?;
63
+ class.undef_default_alloc_func();
64
+ class.define_singleton_method("new", function!(Wrapper::new, 1))?;
64
65
  class.define_method("try_acquire", method!(Wrapper::try_acquire, 1))?;
65
66
  class.define_method("release", method!(Wrapper::release, 1))?;
66
67
  class.define_method("capacity", method!(Wrapper::capacity, 0))?;
67
68
  class.define_method("in_flight", method!(Wrapper::in_flight, 0))?;
68
69
  class.define_method("available", method!(Wrapper::available, 0))?;
69
- class.define_method("inspect", method!(Wrapper::inspect, 0))
70
+ // `new` answers a CreditWindow: its class is fixed now, so building one
71
+ // never runs `Object.const_get`.
72
+ Class::pin_wrapped::<Wrapper>(ruby, class).map(drop)
70
73
  }
@@ -4,28 +4,13 @@ mod credits;
4
4
  mod init;
5
5
  mod watermarks;
6
6
 
7
- use std::num::NonZeroU32;
7
+ use flow_machines::Refusal;
8
8
 
9
- use magnus::{Error, Integer, Ruby, TryConvert, Value};
10
-
11
- /// Counts must be Ruby Integers: Magnus otherwise permits truncating Floats.
12
- #[derive(Clone, Copy)]
13
- pub(crate) struct Count(pub(crate) u32);
14
-
15
- impl TryConvert for Count {
16
- fn try_convert(value: Value) -> Result<Self, Error> {
17
- if Integer::from_value(value).is_none() {
18
- let ruby = Ruby::get_with(value);
19
- return Err(Error::new(
20
- ruby.exception_type_error(),
21
- "count must be an Integer",
22
- ));
23
- }
24
- u32::try_convert(value).map(Self)
9
+ matryona_machines::symbols! {
10
+ /// One symbol per core variant, the snake case of its name; the counts
11
+ /// a variant carries stay in Rust.
12
+ pub(crate) Refusals for Refusal as "a refusal" => names_only {
13
+ Insufficient { .. } => "insufficient",
14
+ ExceedsInFlight { .. } => "exceeds_in_flight",
25
15
  }
26
16
  }
27
-
28
- pub(crate) fn positive(ruby: &Ruby, count: Count) -> Result<NonZeroU32, Error> {
29
- NonZeroU32::new(count.0)
30
- .ok_or_else(|| Error::new(ruby.exception_arg_error(), "count must be positive"))
31
- }
@@ -3,64 +3,60 @@
3
3
  use std::cell::RefCell;
4
4
 
5
5
  use flow_machines::{FlowState, Signal, Watermarks};
6
- use magnus::scan_args::{get_kwargs, scan_args};
7
6
  use magnus::typed_data::Obj;
8
- use magnus::{Error, RHash, RModule, Ruby, Symbol, Value, function, method, prelude::*};
7
+ use magnus::{Error, RModule, Ruby, Symbol, Value, function, method, prelude::*};
8
+ use matryona_machines::ruby::{Class, Symbols, integer, positive};
9
+
10
+ matryona_machines::symbols! {
11
+ /// What an observation tells the producer.
12
+ Signals for Signal as "a signal" {
13
+ Pause => "pause",
14
+ Resume => "resume",
15
+ Unchanged => "unchanged",
16
+ }
17
+ }
9
18
 
10
- use crate::{Count, positive};
19
+ matryona_machines::symbols! {
20
+ /// Whether the producer runs.
21
+ States for FlowState as "a state" {
22
+ Running => "running",
23
+ Paused => "paused",
24
+ }
25
+ }
11
26
 
12
27
  #[magnus::wrap(class = "FlowMachines::Watermarks", free_immediately, size)]
13
28
  struct Wrapper(RefCell<Watermarks>);
14
29
 
15
30
  impl Wrapper {
16
- fn new(ruby: &Ruby, args: &[Value]) -> Result<Self, Error> {
17
- let args = scan_args::<(), (), (), (), RHash, ()>(args)?;
18
- let (Count(low), high) =
19
- get_kwargs::<_, (Count, Count), (), ()>(args.keywords, &["low", "high"], &[])?.required;
20
- let control = Watermarks::new(low, positive(ruby, high)?)
21
- .ok_or_else(|| Error::new(ruby.exception_arg_error(), "low must be less than high"))?;
31
+ fn new(ruby: &Ruby, low: Value, high: Value) -> Result<Self, Error> {
32
+ let low = integer(low, "low")?;
33
+ let control = Watermarks::new(low, positive(high, "high")?)
34
+ .ok_or_else(|| Error::new(ruby.exception_range_error(), "low must be below high"))?;
22
35
  Ok(Self(RefCell::new(control)))
23
36
  }
24
37
 
25
- fn observe(ruby: &Ruby, rb_self: Obj<Self>, occupancy: Count) -> Result<Symbol, Error> {
38
+ fn observe(ruby: &Ruby, rb_self: Obj<Self>, occupancy: Value) -> Result<Symbol, Error> {
26
39
  rb_self.check_frozen()?;
27
- let signal = rb_self.0.borrow_mut().observe(occupancy.0);
40
+ let occupancy = integer(occupancy, "occupancy")?;
41
+ let signal = rb_self.0.borrow_mut().observe(occupancy);
28
42
  // Finish the mutable borrow before allocating a Ruby value.
29
- let name = match signal {
30
- Signal::Pause => "pause",
31
- Signal::Resume => "resume",
32
- _ => "unchanged",
33
- };
34
- Ok(ruby.to_symbol(name))
43
+ Ok(Signals::symbol(ruby, signal))
35
44
  }
36
45
 
37
46
  fn state(ruby: &Ruby, rb_self: &Self) -> Symbol {
38
47
  let state = rb_self.0.borrow().state();
39
- ruby.to_symbol(if state == FlowState::Paused {
40
- "paused"
41
- } else {
42
- "running"
43
- })
44
- }
45
-
46
- fn paused(&self) -> bool {
47
- self.0.borrow().state() == FlowState::Paused
48
- }
49
-
50
- fn inspect(&self) -> String {
51
- format!(
52
- "#<FlowMachines::Watermarks state={}>",
53
- if self.paused() { "paused" } else { "running" }
54
- )
48
+ States::symbol(ruby, state)
55
49
  }
56
50
  }
57
51
 
58
52
  /// Register the watermark controller under the gem namespace.
59
53
  pub fn define(ruby: &Ruby, module: RModule) -> Result<(), Error> {
60
54
  let class = module.define_class("Watermarks", ruby.class_object())?;
61
- class.define_singleton_method("new", function!(Wrapper::new, -1))?;
55
+ class.undef_default_alloc_func();
56
+ class.define_singleton_method("new", function!(Wrapper::new, 2))?;
62
57
  class.define_method("observe", method!(Wrapper::observe, 1))?;
63
58
  class.define_method("state", method!(Wrapper::state, 0))?;
64
- class.define_method("paused?", method!(Wrapper::paused, 0))?;
65
- class.define_method("inspect", method!(Wrapper::inspect, 0))
59
+ // `new` answers a Watermarks: its class is fixed now, so building one
60
+ // never runs `Object.const_get`.
61
+ Class::pin_wrapped::<Wrapper>(ruby, class).map(drop)
66
62
  }
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module FlowMachines
4
- VERSION = '0.1.4'
4
+ VERSION = '0.3.4'
5
5
  end
@@ -1,4 +1,10 @@
1
1
  # Native policy decisions only. The caller owns queues and enforces the results.
2
+ #
3
+ # Counts are Integers in 0..2**32-1: TypeError for anything else, RangeError
4
+ # outside the range, and RangeError for zero where the core takes a NonZeroU32
5
+ # (capacity, units, high). Both messages name the argument. A frozen object
6
+ # raises FrozenError on try_acquire, release and observe. Refusals are
7
+ # symbols, one per core `Refusal` variant, and a refused call changes nothing.
2
8
  module FlowMachines
3
9
  VERSION: String
4
10
 
@@ -7,21 +13,26 @@ module FlowMachines
7
13
 
8
14
  # Aggregate accounting, not a semaphore or a per-work-item permit ledger.
9
15
  class CreditWindow
10
- def self.new: (capacity: Integer) -> instance
11
- def try_acquire: (Integer units) -> bool
12
- def release: (Integer units) -> bool
16
+ # Positional, like the core. Never refuses.
17
+ def self.new: (Integer capacity) -> instance
18
+ # Honoured: :acquired, all `units` are now in flight.
19
+ # Refused: :insufficient, `units` is more than `available`.
20
+ def try_acquire: (Integer units) -> (:acquired | :insufficient)
21
+ # Honoured: :released, all `units` are available again.
22
+ # Refused: :exceeds_in_flight, `units` is more than `in_flight`.
23
+ # The window cannot recognise a repeated release: see the README.
24
+ def release: (Integer units) -> (:released | :exceeds_in_flight)
13
25
  def capacity: () -> Integer
14
26
  def in_flight: () -> Integer
15
27
  def available: () -> Integer
16
- def inspect: () -> String
17
28
  end
18
29
 
19
30
  # Starts running; pauses at occupancy >= high and resumes at occupancy <= low.
20
31
  class Watermarks
21
- def self.new: (low: Integer, high: Integer) -> instance
32
+ # Positional, like the core. RangeError unless low < high.
33
+ def self.new: (Integer low, Integer high) -> instance
34
+ # Never refuses. :pause and :resume are edges; :unchanged changed nothing.
22
35
  def observe: (Integer occupancy) -> signal
23
36
  def state: () -> state
24
- def paused?: () -> bool
25
- def inspect: () -> String
26
37
  end
27
38
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: flow_machines
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.4
4
+ version: 0.3.4
5
5
  platform: ruby
6
6
  authors:
7
7
  - Abdelkader Boudih
@@ -40,6 +40,7 @@ extensions:
40
40
  extra_rdoc_files: []
41
41
  files:
42
42
  - CHANGELOG.md
43
+ - Cargo.lock
43
44
  - Cargo.toml
44
45
  - LICENSE.txt
45
46
  - README.md
@@ -48,6 +49,8 @@ files:
48
49
  - ext/flow_machines_native/core/README.md
49
50
  - ext/flow_machines_native/core/src/credits.rs
50
51
  - ext/flow_machines_native/core/src/lib.rs
52
+ - ext/flow_machines_native/core/src/refusal.rs
53
+ - ext/flow_machines_native/core/src/test_support.rs
51
54
  - ext/flow_machines_native/core/src/watermarks.rs
52
55
  - ext/flow_machines_native/extconf.rb
53
56
  - ext/flow_machines_native/ffi/Cargo.toml