pool_machines 0.1.3 → 0.5.3

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.
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "pool_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
@@ -15,6 +15,7 @@ doctest = false
15
15
  pool-machines.workspace = true
16
16
  magnus.workspace = true
17
17
  rb-sys.workspace = true
18
+ matryona-machines = { workspace = true, features = ["ruby"] }
18
19
 
19
20
  [lints]
20
21
  workspace = true
@@ -1,28 +1,3 @@
1
1
  //! Native resource roster. Ruby resources are not retained or operated here.
2
2
  mod init;
3
3
  mod pool;
4
-
5
- use std::time::Duration;
6
-
7
- use magnus::{Error, Integer, Ruby, TryConvert, Value};
8
-
9
- #[derive(Clone, Copy)]
10
- struct Count(u64);
11
-
12
- impl TryConvert for Count {
13
- fn try_convert(value: Value) -> Result<Self, Error> {
14
- if Integer::from_value(value).is_none() {
15
- return Err(Error::new(
16
- Ruby::get_with(value).exception_type_error(),
17
- "slot/time must be an unsigned 64-bit Integer (time in nanoseconds)",
18
- ));
19
- }
20
- u64::try_convert(value).map(Self)
21
- }
22
- }
23
-
24
- impl Count {
25
- const fn duration(self) -> Duration {
26
- Duration::from_nanos(self.0)
27
- }
28
- }
@@ -1,116 +1,239 @@
1
- use std::{cell::RefCell, sync::Arc};
1
+ use std::cell::RefCell;
2
2
 
3
- use magnus::{Error, RModule, Ruby, function, method, prelude::*, typed_data::Obj};
4
- use pool_machines::{Handle, Pool, Returned};
3
+ use magnus::{Error, RModule, Ruby, Value, function, method, prelude::*, typed_data::Obj};
4
+ use matryona_machines::ruby::{
5
+ Class, Registry, Symbols, class_name, duration, exact_typed_with, integer, keep,
6
+ };
7
+ use pool_machines::{DrainBegin, Handle, Refusal, Registration, Returned};
5
8
 
6
- use crate::Count;
9
+ const CAPACITY: usize = 32;
7
10
 
8
- #[magnus::wrap(class = "PoolMachines::Handle", free_immediately, size)]
9
- struct Lease {
10
- // Shared native identity survives pool GC; addresses cannot be recycled
11
- // while a handle exists. No Ruby values need marking.
12
- owner: Arc<()>,
13
- handle: Handle,
11
+ type Core = pool_machines::Pool<CAPACITY>;
12
+
13
+ matryona_machines::symbols! {
14
+ /// The core's refusals as Symbols: the snake case of each variant.
15
+ Refusals for Refusal as "a refusal" {
16
+ Draining => "draining",
17
+ TimeRegression => "time_regression",
18
+ UnknownSlot => "unknown_slot",
19
+ Busy => "busy",
20
+ Exhausted => "exhausted",
21
+ Stale => "stale",
22
+ }
23
+ }
24
+
25
+ matryona_machines::symbols! {
26
+ /// The core's honoured `register` answers as Symbols.
27
+ Registrations for Registration as "a registration" {
28
+ Registered => "registered",
29
+ AlreadyIdle => "already_idle",
30
+ }
31
+ }
32
+
33
+ matryona_machines::symbols! {
34
+ /// The core's honoured `checkin` answers as Symbols.
35
+ Returns for Returned as "a return" {
36
+ Idle => "idle",
37
+ Retire => "retire",
38
+ }
39
+ }
40
+
41
+ matryona_machines::symbols! {
42
+ /// The core's `begin_drain` answers as Symbols.
43
+ DrainBegins for DrainBegin as "a drain" {
44
+ Begun => "begun",
45
+ AlreadyDraining => "already_draining",
46
+ }
47
+ }
48
+
49
+ fn refused(ruby: &Ruby, refused: Refusal) -> Value {
50
+ Refusals::symbol(ruby, refused).as_value()
14
51
  }
15
52
 
16
- impl Lease {
53
+ /// `PoolMachines::Handle`: the core's `Handle`. It carries the scope of the
54
+ /// pool that issued it; the core refuses it anywhere else.
55
+ #[magnus::wrap(class = "PoolMachines::Handle", free_immediately, size)]
56
+ struct Issued(Handle);
57
+
58
+ impl Issued {
17
59
  const fn slot(&self) -> usize {
18
- self.handle.slot()
60
+ self.0.slot()
61
+ }
62
+
63
+ const fn scope(&self) -> u16 {
64
+ self.0.scope()
19
65
  }
20
66
  }
21
67
 
68
+ /// `PoolMachines::Handle`, the class defined at init and pinned there: a
69
+ /// constant reassigned later neither receives a handle nor passes for one.
70
+ struct Classes {
71
+ handle: Class,
72
+ }
73
+
74
+ static CLASSES: Registry<Classes> = Registry::new("pool_machines");
75
+
76
+ /// `value` when it is exactly a `PoolMachines::Handle`: `TypeError` naming
77
+ /// the class received for anything else, a subclass included. Only the
78
+ /// binding builds one, from a handle the core issued, so its contents need
79
+ /// no further check.
80
+ fn issued(ruby: &Ruby, value: Value) -> Result<Handle, Error> {
81
+ let class = CLASSES.get(ruby)?.handle.get(ruby);
82
+ let handle = exact_typed_with::<Issued>(ruby, value, class, || {
83
+ format!(
84
+ "handle must be a PoolMachines::Handle, not {}",
85
+ class_name(value)
86
+ )
87
+ })?;
88
+ Ok(handle.0)
89
+ }
90
+
22
91
  #[magnus::wrap(class = "PoolMachines::Pool", free_immediately, size)]
23
- struct Wrapper {
24
- owner: Arc<()>,
25
- pool: RefCell<Pool<32>>,
92
+ struct Pool {
93
+ core: RefCell<Core>,
26
94
  }
27
95
 
28
- impl Wrapper {
29
- fn new(ruby: &Ruby) -> Result<Self, Error> {
30
- let pool = Pool::new()
31
- .ok_or_else(|| Error::new(ruby.exception_runtime_error(), "invalid native capacity"))?;
32
- Ok(Self {
33
- owner: Arc::new(()),
34
- pool: RefCell::new(pool),
96
+ impl Pool {
97
+ fn build(ruby: &Ruby, core: Option<Core>, why: &'static str) -> Result<Self, Error> {
98
+ core.map(|core| Self {
99
+ core: RefCell::new(core),
35
100
  })
101
+ .ok_or_else(|| Error::new(ruby.exception_range_error(), why))
36
102
  }
37
103
 
38
- fn register(ruby: &Ruby, this: Obj<Self>, slot: Count, now: Count) -> Result<bool, Error> {
39
- this.check_frozen()?;
40
- if slot.0 >= 32 {
41
- return Err(Error::new(
42
- ruby.exception_range_error(),
43
- "slot must be in 0...32",
44
- ));
45
- }
46
- let slot = usize::try_from(slot.0)
47
- .map_err(|_| Error::new(ruby.exception_range_error(), "slot overflow"))?;
48
- let now = now.duration();
49
- Ok(this.pool.borrow_mut().register(slot, now))
50
- }
51
-
52
- fn checkout(this: Obj<Self>, now: Count) -> Result<Option<Lease>, Error> {
104
+ fn new(ruby: &Ruby) -> Result<Self, Error> {
105
+ Self::build(ruby, Core::new(), "invalid native capacity")
106
+ }
107
+
108
+ fn with_scope(ruby: &Ruby, scope: Value) -> Result<Self, Error> {
109
+ let scope = integer(scope, "scope")?;
110
+ Self::build(ruby, Core::with_scope(scope), "invalid native capacity")
111
+ }
112
+
113
+ fn resumed(ruby: &Ruby, scope: Value, issued: Value) -> Result<Self, Error> {
114
+ let (scope, issued) = (integer(scope, "scope")?, integer(issued, "issued")?);
115
+ Self::build(
116
+ ruby,
117
+ Core::resumed(scope, issued),
118
+ "issued is past the last sequence of a scope (2**48 - 1)",
119
+ )
120
+ }
121
+
122
+ fn scope(&self) -> u16 {
123
+ self.core.borrow().scope()
124
+ }
125
+
126
+ fn issued(&self) -> u64 {
127
+ self.core.borrow().issued()
128
+ }
129
+
130
+ fn capacity(&self) -> usize {
131
+ self.core.borrow().capacity()
132
+ }
133
+
134
+ fn checked_out(&self) -> u32 {
135
+ self.core.borrow().checked_out()
136
+ }
137
+
138
+ fn is_draining(&self) -> bool {
139
+ self.core.borrow().is_draining()
140
+ }
141
+
142
+ fn register(ruby: &Ruby, this: Obj<Self>, slot: Value, now: Value) -> Result<Value, Error> {
53
143
  this.check_frozen()?;
54
- let handle = this.pool.borrow_mut().checkout(now.duration());
55
- Ok(handle.map(|handle| Lease {
56
- owner: Arc::clone(&this.owner),
57
- handle,
58
- }))
144
+ let (slot, now) = (integer(slot, "slot")?, duration(now, "now")?);
145
+ let outcome = this.core.borrow_mut().register(slot, now);
146
+ Ok(match outcome {
147
+ Ok(registration) => Registrations::symbol(ruby, registration).as_value(),
148
+ Err(refusal) => refused(ruby, refusal),
149
+ })
59
150
  }
60
151
 
61
- fn checkin(
62
- ruby: &Ruby,
63
- this: Obj<Self>,
64
- lease: &Lease,
65
- now: Count,
66
- ) -> Result<&'static str, Error> {
152
+ fn checkout(ruby: &Ruby, this: Obj<Self>, now: Value) -> Result<Value, Error> {
67
153
  this.check_frozen()?;
68
- if !Arc::ptr_eq(&this.owner, &lease.owner) {
69
- return Err(Error::new(
70
- ruby.exception_arg_error(),
71
- "handle belongs to another pool",
72
- ));
73
- }
74
- let returned = this.pool.borrow_mut().checkin(lease.handle, now.duration());
75
- match returned {
76
- Returned::Idle => Ok("idle"),
77
- Returned::Retire => Ok("retire"),
78
- _ => Err(Error::new(
79
- ruby.exception_arg_error(),
80
- "stale handle or backwards clock",
81
- )),
82
- }
83
- }
84
-
85
- fn begin_drain(this: Obj<Self>) -> Result<(), Error> {
154
+ let now = duration(now, "now")?;
155
+ // Look the class up before the core issues a handle: a failure here
156
+ // must not leave a checkout behind that Ruby never received.
157
+ let class = CLASSES.get(ruby)?.handle.get(ruby);
158
+ // Clone-then-keep: the core decides on a copy, kept only once the
159
+ // answer exists and the pool is still unfrozen and unchanged.
160
+ keep(
161
+ ruby,
162
+ this,
163
+ &this.core,
164
+ |core| core.checkout(now),
165
+ |checkout| {
166
+ Ok(match checkout {
167
+ Ok(Some(handle)) => ruby.obj_wrap_as(Issued(handle), class).as_value(),
168
+ Ok(None) => ruby.qnil().as_value(),
169
+ Err(refusal) => refused(ruby, refusal),
170
+ })
171
+ },
172
+ )
173
+ }
174
+
175
+ fn checkin(ruby: &Ruby, this: Obj<Self>, handle: Value, now: Value) -> Result<Value, Error> {
86
176
  this.check_frozen()?;
87
- this.pool.borrow_mut().begin_drain();
88
- Ok(())
177
+ let handle = issued(ruby, handle)?;
178
+ let now = duration(now, "now")?;
179
+ let outcome = this.core.borrow_mut().checkin(handle, now);
180
+ Ok(match outcome {
181
+ Ok(returned) => Returns::symbol(ruby, returned).as_value(),
182
+ Err(refusal) => refused(ruby, refusal),
183
+ })
89
184
  }
90
185
 
91
- fn retire_idle(this: Obj<Self>, now: Count, idle_for: Count) -> Result<Option<usize>, Error> {
186
+ fn begin_drain(ruby: &Ruby, this: Obj<Self>) -> Result<Value, Error> {
92
187
  this.check_frozen()?;
93
- let now = now.duration();
94
- let idle_for = idle_for.duration();
95
- let slot = this.pool.borrow_mut().retire_idle(now, idle_for);
96
- Ok(slot)
188
+ let outcome = this.core.borrow_mut().begin_drain();
189
+ Ok(DrainBegins::symbol(ruby, outcome).as_value())
97
190
  }
98
191
 
99
- fn checked_out(&self) -> u32 {
100
- self.pool.borrow().checked_out()
192
+ fn retire_idle(
193
+ ruby: &Ruby,
194
+ this: Obj<Self>,
195
+ now: Value,
196
+ idle_for: Value,
197
+ ) -> Result<Value, Error> {
198
+ this.check_frozen()?;
199
+ let (now, idle_for) = (duration(now, "now")?, duration(idle_for, "idle_for")?);
200
+ let outcome = this.core.borrow_mut().retire_idle(now, idle_for);
201
+ Ok(match outcome {
202
+ Ok(Some(slot)) => ruby.integer_from_u64(slot as u64).as_value(),
203
+ Ok(None) => ruby.qnil().as_value(),
204
+ Err(refusal) => refused(ruby, refusal),
205
+ })
101
206
  }
102
207
  }
103
208
 
104
209
  pub fn define(ruby: &Ruby, module: RModule) -> Result<(), Error> {
105
210
  let handle = module.define_class("Handle", ruby.class_object())?;
106
211
  handle.undef_default_alloc_func();
107
- handle.define_method("slot", method!(Lease::slot, 0))?;
212
+ handle.define_method("slot", method!(Issued::slot, 0))?;
213
+ handle.define_method("scope", method!(Issued::scope, 0))?;
214
+ // Fixes magnus's class for each wrapped type now: building a Handle or a
215
+ // Pool never runs `Object.const_get` later.
216
+ CLASSES.set(
217
+ ruby,
218
+ Classes {
219
+ handle: Class::pin_wrapped::<Issued>(ruby, handle)?,
220
+ },
221
+ )?;
108
222
  let class = module.define_class("Pool", ruby.class_object())?;
109
- class.define_singleton_method("new", function!(Wrapper::new, 0))?;
110
- class.define_method("register", method!(Wrapper::register, 2))?;
111
- class.define_method("checkout", method!(Wrapper::checkout, 1))?;
112
- class.define_method("checkin", method!(Wrapper::checkin, 2))?;
113
- class.define_method("begin_drain", method!(Wrapper::begin_drain, 0))?;
114
- class.define_method("retire_idle", method!(Wrapper::retire_idle, 2))?;
115
- class.define_method("checked_out", method!(Wrapper::checked_out, 0))
223
+ class.undef_default_alloc_func();
224
+ class.const_set("CAPACITY", CAPACITY)?;
225
+ class.define_singleton_method("new", function!(Pool::new, 0))?;
226
+ class.define_singleton_method("with_scope", function!(Pool::with_scope, 1))?;
227
+ class.define_singleton_method("resumed", function!(Pool::resumed, 2))?;
228
+ class.define_method("scope", method!(Pool::scope, 0))?;
229
+ class.define_method("issued", method!(Pool::issued, 0))?;
230
+ class.define_method("capacity", method!(Pool::capacity, 0))?;
231
+ class.define_method("checked_out", method!(Pool::checked_out, 0))?;
232
+ class.define_method("draining?", method!(Pool::is_draining, 0))?;
233
+ class.define_method("register", method!(Pool::register, 2))?;
234
+ class.define_method("checkout", method!(Pool::checkout, 1))?;
235
+ class.define_method("checkin", method!(Pool::checkin, 2))?;
236
+ class.define_method("begin_drain", method!(Pool::begin_drain, 0))?;
237
+ class.define_method("retire_idle", method!(Pool::retire_idle, 2))?;
238
+ Class::pin_wrapped::<Pool>(ruby, class).map(drop)
116
239
  }
@@ -1,4 +1,4 @@
1
1
  # frozen_string_literal: true
2
2
  module PoolMachines
3
- VERSION = '0.1.3'
3
+ VERSION = '0.5.3'
4
4
  end
data/lib/pool_machines.rb CHANGED
@@ -1,3 +1,10 @@
1
1
  # frozen_string_literal: true
2
2
  require_relative 'pool_machines/version'
3
3
  require 'pool_machines_native/pool_machines_native'
4
+
5
+ module PoolMachines
6
+ # Sealed: only the pool builds a Handle. No subclass, no `allocate`, and
7
+ # the pool accepts nothing but an instance of exactly this class.
8
+ Handle.singleton_class.undef_method(:allocate)
9
+ Handle.define_singleton_method(:inherited) { |_| raise TypeError, "#{Handle} cannot be subclassed" }
10
+ end
@@ -1,16 +1,63 @@
1
+ # Slots are Integers a `usize` holds; times, durations and `issued` are
2
+ # Integers in 0..2**64-1 (nanoseconds for times and durations); scopes are
3
+ # Integers in 0..65535. TypeError for anything else, RangeError outside the
4
+ # range, and every message names the argument.
1
5
  module PoolMachines
2
6
  VERSION: String
3
- # Opaque checkout result; direct construction is unsupported.
7
+
8
+ # Refusals: the call was not honoured and changed nothing, the observed
9
+ # clock included. Every reason has its own symbol; there is no catch-all.
10
+ type refusal = :draining | :time_regression | :unknown_slot | :busy | :exhausted | :stale
11
+
12
+ # Mirrors the core's `Handle`: names one checkout on the pool that issued it
13
+ # and carries that pool's scope. Opaque and sealed (subclassing raises
14
+ # TypeError, no `allocate`); it cannot be built, copied or marshalled by
15
+ # hand. A pool in another scope answers :stale to it.
4
16
  class Handle
17
+ # The slot to fetch from your own storage.
5
18
  def slot: () -> Integer
19
+ # The scope of the pool that issued it, 0..65535.
20
+ def scope: () -> Integer
6
21
  end
22
+
7
23
  class Pool
8
- def self.new: () -> instance
9
- def register: (Integer slot, Integer now_ns) -> bool
10
- def checkout: (Integer now_ns) -> Handle?
11
- def checkin: (Handle handle, Integer now_ns) -> String
12
- def begin_drain: () -> nil
13
- def retire_idle: (Integer now_ns, Integer idle_for_ns) -> Integer?
24
+ CAPACITY: Integer
25
+
26
+ # Scope zero, every slot vacant, nothing issued.
27
+ def self.new: () -> Pool
28
+ # `scope` is an Integer in 0..65535: TypeError otherwise, RangeError
29
+ # outside the range.
30
+ def self.with_scope: (Integer scope) -> Pool
31
+ # Continues `scope` after a restart from a saved `issued` count. Restores
32
+ # only the handle sequence: every slot is vacant. RangeError when `issued`
33
+ # is above 2**48 - 1.
34
+ def self.resumed: (Integer scope, Integer issued) -> Pool
35
+ # The scope carried by every Handle this pool issues.
36
+ def scope: () -> Integer
37
+ # Handles issued in this scope so far: the count to save for `resumed`.
38
+ def issued: () -> Integer
39
+ def capacity: () -> Integer
14
40
  def checked_out: () -> Integer
41
+ def draining?: () -> bool
42
+
43
+ # Times are Integer nanoseconds of a monotonic clock, instants and spans.
44
+ # Honoured: :registered, or :already_idle for a slot that already holds an
45
+ # idle resource (a repeat that changes nothing). Only :registered records
46
+ # `now`. Refused: :draining, :time_regression, :unknown_slot, :busy.
47
+ def register: (Integer slot, Integer now)
48
+ -> (:registered | :already_idle | :draining | :time_regression | :unknown_slot | :busy)
49
+ # Honoured: a Handle, or nil when nothing is idle (both record `now`).
50
+ # Refused: :draining, :time_regression, :exhausted.
51
+ def checkout: (Integer now) -> (Handle | nil | :draining | :time_regression | :exhausted)
52
+ # Honoured: :idle (keep the resource; records `now`) or :retire (destroy
53
+ # it, the pool is draining; records no clock). Refused: :stale, a repeat
54
+ # and a Handle of another scope included, and :time_regression. TypeError
55
+ # for anything that is not exactly a Handle, a subclass included.
56
+ def checkin: (Handle handle, Integer now) -> (:idle | :retire | :stale | :time_regression)
57
+ # Never refuses. :already_draining is a repeat that changes nothing.
58
+ def begin_drain: () -> (:begun | :already_draining)
59
+ # Honoured: the retired slot, or nil when nothing is old enough (both
60
+ # record `now`). Refused: :time_regression.
61
+ def retire_idle: (Integer now, Integer idle_for) -> (Integer | nil | :time_regression)
15
62
  end
16
63
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: pool_machines
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.3
4
+ version: 0.5.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - Abdelkader Boudih
@@ -29,8 +29,9 @@ dependencies:
29
29
  - - ">="
30
30
  - !ruby/object:Gem::Version
31
31
  version: 0.9.130
32
- description: Initial native roster model with draining and retirement. Caller owns
33
- resources and execution. Local sibling Rust checkout required.
32
+ description: 'Keeps the roster of a resource pool: which slot is busy or idle, which
33
+ idle slots are old enough to retire, and whether a returned handle is stale. The
34
+ caller owns the resources and their lifecycle.'
34
35
  email:
35
36
  - oss@seuros.com
36
37
  executables: []
@@ -39,6 +40,7 @@ extensions:
39
40
  extra_rdoc_files: []
40
41
  files:
41
42
  - CHANGELOG.md
43
+ - Cargo.lock
42
44
  - Cargo.toml
43
45
  - LICENSE.txt
44
46
  - README.md
@@ -46,6 +48,7 @@ files:
46
48
  - ext/pool_machines_native/core/Cargo.toml
47
49
  - ext/pool_machines_native/core/README.md
48
50
  - ext/pool_machines_native/core/src/lib.rs
51
+ - ext/pool_machines_native/core/src/refusal.rs
49
52
  - ext/pool_machines_native/extconf.rb
50
53
  - ext/pool_machines_native/ffi/Cargo.toml
51
54
  - ext/pool_machines_native/ffi/extconf.rb
@@ -79,5 +82,5 @@ required_rubygems_version: !ruby/object:Gem::Requirement
79
82
  requirements: []
80
83
  rubygems_version: 4.0.20
81
84
  specification_version: 4
82
- summary: Native generation-checked resource-slot policy for Ruby
85
+ summary: Generation-checked resource-slot checkout, recycling and draining for Ruby
83
86
  test_files: []