zrip 0.2.2 → 0.3.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 +4 -4
- data/CHANGELOG.md +15 -0
- data/Cargo.lock +1 -1
- data/README.md +17 -0
- data/ext/zrip/Cargo.toml +1 -1
- data/ext/zrip/src/adaptive.rs +150 -0
- data/ext/zrip/src/lib.rs +132 -18
- data/ext/zrip/src/rb.rs +33 -0
- data/lib/zrip/adaptive_level.rb +56 -0
- data/lib/zrip/block_codec.rb +18 -0
- data/lib/zrip/frame_codec.rb +18 -0
- data/lib/zrip/version.rb +1 -1
- data/lib/zrip.rb +1 -0
- metadata +3 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 7d15447bc566dfc7a7043bd366103ca041245cc7e8c62adf4968414c8ad196a1
|
|
4
|
+
data.tar.gz: fe0f8ed6916f89ef2663f828a5f21e108d03005e1f9dfa5b090af40def53b9f6
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 263643a0dfbbb4a7000c308ebd37f71727e25c25dbdfba0828e50c450bf5e2dfb3a18f591e2bbd71d7facefae81bf53394a1f32bfd88a49f4ff37972a3892c4f
|
|
7
|
+
data.tar.gz: 37beca4c7901d474ee31713ceb0ef7a414a87f6623afa9c56acdc8216395a0166ca5768de6679385e872945282c3a80e39b4ac128874879b346dab307a850921
|
data/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,21 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [0.3.0] - 2026-11-26
|
|
6
|
+
|
|
7
|
+
- `FrameCodec#level=` and `BlockCodec#level=` switch later frames to a new
|
|
8
|
+
level. A dictionary stays loaded; zrip prepares it again for the level.
|
|
9
|
+
- `FrameCodec#take_stats` and `BlockCodec#take_stats` return the bytes in
|
|
10
|
+
and out and the time spent compressing since the last call. The time is
|
|
11
|
+
measured natively around each compression, so it leaves out waits for the
|
|
12
|
+
GVL and the codec lock.
|
|
13
|
+
- `Zrip::AdaptiveLevel.new(range, start: -1)` wraps zrip's adaptive level:
|
|
14
|
+
`#update(plain:, compressed:, busy:, bottleneck: nil)` takes one window's
|
|
15
|
+
stats and what limited the sender, and returns the next level.
|
|
16
|
+
- `FrameCodec#decompress` and `BlockCodec#decompress` decode into a new
|
|
17
|
+
buffer per call. The codec kept a buffer the size of its largest frame
|
|
18
|
+
for its lifetime, and copied each frame out of it.
|
|
19
|
+
|
|
5
20
|
## [0.2.2] - 2026-11-26
|
|
6
21
|
|
|
7
22
|
- Update the `zrip` crate dependency to 0.8.29. Levels are retuned, so
|
data/Cargo.lock
CHANGED
data/README.md
CHANGED
|
@@ -59,6 +59,23 @@ original = codec.decompress(compressed)
|
|
|
59
59
|
```ruby
|
|
60
60
|
fast = Zrip::FrameCodec.new(level: -3) # negative = faster
|
|
61
61
|
strong = Zrip::FrameCodec.new(level: 4) # highest supported level
|
|
62
|
+
fast.level = 1 # later frames; a dictionary stays loaded
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### Adaptive level
|
|
66
|
+
|
|
67
|
+
`AdaptiveLevel` walks the levels of a range, one step per window of work,
|
|
68
|
+
toward ratio when output stalls or the CPU idles and toward speed when the CPU
|
|
69
|
+
is the limit. `#take_stats` reports a codec's work since the last call, with
|
|
70
|
+
the compression time measured natively, so waits for the GVL don't count.
|
|
71
|
+
|
|
72
|
+
```ruby
|
|
73
|
+
codec = Zrip::FrameCodec.new(level: -1)
|
|
74
|
+
adaptive = Zrip::AdaptiveLevel.new(-7..4, start: -1)
|
|
75
|
+
|
|
76
|
+
# once per window, e.g. every 100 ms
|
|
77
|
+
stats = codec.take_stats #=> {plain: 1048576, compressed: 312000, busy: 0.004}
|
|
78
|
+
codec.level = adaptive.update(**stats, bottleneck: :output) # or :cpu, :input, nil
|
|
62
79
|
```
|
|
63
80
|
|
|
64
81
|
### Bounded decompression
|
data/ext/zrip/Cargo.toml
CHANGED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
//! `Zrip::AdaptiveLevel`: zrip's hill climb over compression levels.
|
|
2
|
+
|
|
3
|
+
use std::ffi::c_void;
|
|
4
|
+
use std::panic::{catch_unwind, AssertUnwindSafe};
|
|
5
|
+
use std::sync::{Mutex, OnceLock};
|
|
6
|
+
use std::time::Duration;
|
|
7
|
+
|
|
8
|
+
use rb_sys::{rb_data_type_struct__bindgen_ty_1, rb_data_type_t, size_t, VALUE};
|
|
9
|
+
use zstd::adaptive::{AdaptiveLevel, Bottleneck, CompressStats};
|
|
10
|
+
|
|
11
|
+
use crate::rb::{self, RbResult, RubyErr};
|
|
12
|
+
|
|
13
|
+
/// Lowest and highest level `AdaptiveLevel` accepts in a range: -8 runs as
|
|
14
|
+
/// -7, and 0 as the default level.
|
|
15
|
+
const RANGE_MIN: i32 = -8;
|
|
16
|
+
const RANGE_MAX: i32 = 4;
|
|
17
|
+
|
|
18
|
+
struct NativeDataType(rb_data_type_t);
|
|
19
|
+
|
|
20
|
+
unsafe impl Send for NativeDataType {}
|
|
21
|
+
unsafe impl Sync for NativeDataType {}
|
|
22
|
+
|
|
23
|
+
static DATA_TYPE: OnceLock<NativeDataType> = OnceLock::new();
|
|
24
|
+
|
|
25
|
+
fn data_type() -> *const rb_data_type_t {
|
|
26
|
+
&DATA_TYPE
|
|
27
|
+
.get_or_init(|| {
|
|
28
|
+
NativeDataType(rb_data_type_t {
|
|
29
|
+
wrap_struct_name: c"zrip_adaptive_level".as_ptr(),
|
|
30
|
+
function: rb_data_type_struct__bindgen_ty_1 {
|
|
31
|
+
dmark: None,
|
|
32
|
+
dfree: Some(free),
|
|
33
|
+
dsize: Some(native_size),
|
|
34
|
+
dcompact: None,
|
|
35
|
+
reserved: [std::ptr::null_mut(); 1],
|
|
36
|
+
},
|
|
37
|
+
parent: std::ptr::null(),
|
|
38
|
+
data: std::ptr::null_mut(),
|
|
39
|
+
flags: 1,
|
|
40
|
+
})
|
|
41
|
+
})
|
|
42
|
+
.0
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/// The controller. Ruby calls hold the GVL, so the mutex never waits.
|
|
46
|
+
struct RbAdaptiveLevel(Mutex<AdaptiveLevel>);
|
|
47
|
+
|
|
48
|
+
unsafe extern "C" fn free(ptr: *mut c_void) {
|
|
49
|
+
if ptr.is_null() {
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
let _ = catch_unwind(AssertUnwindSafe(|| unsafe {
|
|
54
|
+
drop(Box::from_raw(ptr as *mut RbAdaptiveLevel));
|
|
55
|
+
}));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
unsafe extern "C" fn native_size(_ptr: *const c_void) -> size_t {
|
|
59
|
+
std::mem::size_of::<RbAdaptiveLevel>() as size_t
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
unsafe fn adaptive_ref(value: VALUE) -> RbResult<&'static RbAdaptiveLevel> {
|
|
63
|
+
unsafe { rb::typed_data_ref(value, data_type(), "Zrip::AdaptiveLevel") }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
fn with_level<R>(rb_self: VALUE, func: impl FnOnce(&mut AdaptiveLevel) -> R) -> RbResult<R> {
|
|
67
|
+
let rb_self = unsafe { adaptive_ref(rb_self)? };
|
|
68
|
+
let mut guard = rb_self
|
|
69
|
+
.0
|
|
70
|
+
.lock()
|
|
71
|
+
.map_err(|_| RubyErr::runtime("AdaptiveLevel mutex poisoned"))?;
|
|
72
|
+
Ok(func(&mut guard))
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
fn new_impl(class: VALUE, min: VALUE, max: VALUE, start: VALUE) -> RbResult<VALUE> {
|
|
76
|
+
let min = rb::value_to_i32(min)?;
|
|
77
|
+
let max = rb::value_to_i32(max)?;
|
|
78
|
+
let start = rb::value_to_i32(start)?;
|
|
79
|
+
if min > max || max < RANGE_MIN || min > RANGE_MAX {
|
|
80
|
+
return Err(RubyErr::arg(format!(
|
|
81
|
+
"{min}..{max} holds no zrip level ({RANGE_MIN}..{RANGE_MAX})"
|
|
82
|
+
)));
|
|
83
|
+
}
|
|
84
|
+
let level = AdaptiveLevel::new(min..=max, start);
|
|
85
|
+
unsafe {
|
|
86
|
+
rb::wrap_typed_data(
|
|
87
|
+
class,
|
|
88
|
+
Box::new(RbAdaptiveLevel(Mutex::new(level))),
|
|
89
|
+
data_type(),
|
|
90
|
+
)
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/// `bottleneck` is -1 (none), 0 (output), 1 (CPU) or 2 (input).
|
|
95
|
+
fn update_impl(
|
|
96
|
+
rb_self: VALUE,
|
|
97
|
+
plain: VALUE,
|
|
98
|
+
compressed: VALUE,
|
|
99
|
+
busy_ns: VALUE,
|
|
100
|
+
bottleneck: VALUE,
|
|
101
|
+
) -> RbResult<VALUE> {
|
|
102
|
+
let stats = CompressStats {
|
|
103
|
+
plain: rb::value_to_u64(plain)?,
|
|
104
|
+
compressed: rb::value_to_u64(compressed)?,
|
|
105
|
+
busy: Duration::from_nanos(rb::value_to_u64(busy_ns)?),
|
|
106
|
+
};
|
|
107
|
+
let bottleneck = match rb::value_to_i32(bottleneck)? {
|
|
108
|
+
-1 => None,
|
|
109
|
+
0 => Some(Bottleneck::Output),
|
|
110
|
+
1 => Some(Bottleneck::Cpu),
|
|
111
|
+
2 => Some(Bottleneck::Input),
|
|
112
|
+
code => return Err(RubyErr::arg(format!("unknown bottleneck code {code}"))),
|
|
113
|
+
};
|
|
114
|
+
let level = with_level(rb_self, |level| level.update(stats, bottleneck))?;
|
|
115
|
+
Ok(rb::i32_value(level))
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
fn level_impl(rb_self: VALUE) -> RbResult<VALUE> {
|
|
119
|
+
Ok(rb::i32_value(with_level(rb_self, |level| level.level())?))
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
unsafe extern "C" fn adaptive_new(class: VALUE, min: VALUE, max: VALUE, start: VALUE) -> VALUE {
|
|
123
|
+
rb::wrap(|| new_impl(class, min, max, start))
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
unsafe extern "C" fn adaptive_update(
|
|
127
|
+
rb_self: VALUE,
|
|
128
|
+
plain: VALUE,
|
|
129
|
+
compressed: VALUE,
|
|
130
|
+
busy_ns: VALUE,
|
|
131
|
+
bottleneck: VALUE,
|
|
132
|
+
) -> VALUE {
|
|
133
|
+
rb::wrap(|| update_impl(rb_self, plain, compressed, busy_ns, bottleneck))
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
unsafe extern "C" fn adaptive_level(rb_self: VALUE) -> VALUE {
|
|
137
|
+
rb::wrap(|| level_impl(rb_self))
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/// Defines `Zrip::AdaptiveLevel` under `module`.
|
|
141
|
+
pub fn define(module: VALUE) -> RbResult<()> {
|
|
142
|
+
let class = unsafe { rb::define_class_under(module, c"AdaptiveLevel", rb_sys::rb_cObject)? };
|
|
143
|
+
unsafe {
|
|
144
|
+
rb::undef_alloc_func(class)?;
|
|
145
|
+
rb::define_singleton_method_3(class, c"_native_new", adaptive_new)?;
|
|
146
|
+
rb::define_method_4(class, c"_update", adaptive_update)?;
|
|
147
|
+
rb::define_method_0(class, c"level", adaptive_level)?;
|
|
148
|
+
}
|
|
149
|
+
Ok(())
|
|
150
|
+
}
|
data/ext/zrip/src/lib.rs
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
|
+
mod adaptive;
|
|
1
2
|
mod rb;
|
|
2
3
|
|
|
3
4
|
use std::ffi::c_void;
|
|
4
5
|
use std::panic::{catch_unwind, AssertUnwindSafe};
|
|
6
|
+
use std::sync::atomic::{AtomicI32, AtomicU64, Ordering};
|
|
5
7
|
use std::sync::{Mutex, OnceLock, TryLockError};
|
|
8
|
+
use std::time::{Duration, Instant};
|
|
6
9
|
|
|
7
10
|
use rb_sys::{rb_data_type_struct__bindgen_ty_1, rb_data_type_t, size_t, VALUE};
|
|
8
11
|
use zstd::dict::fastcover::FastCoverParams;
|
|
@@ -86,6 +89,76 @@ where
|
|
|
86
89
|
}
|
|
87
90
|
}
|
|
88
91
|
|
|
92
|
+
/// Compression work since the last `#take_stats`. `busy` is measured around
|
|
93
|
+
/// the compression itself, so it leaves out waits for the GVL and the lock.
|
|
94
|
+
#[derive(Default)]
|
|
95
|
+
struct CompressStats {
|
|
96
|
+
plain: AtomicU64,
|
|
97
|
+
compressed: AtomicU64,
|
|
98
|
+
busy_ns: AtomicU64,
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
impl CompressStats {
|
|
102
|
+
fn record(&self, plain: usize, compressed: usize, busy: Duration) {
|
|
103
|
+
self.plain.fetch_add(plain as u64, Ordering::Relaxed);
|
|
104
|
+
self.compressed
|
|
105
|
+
.fetch_add(compressed as u64, Ordering::Relaxed);
|
|
106
|
+
let busy_ns = u64::try_from(busy.as_nanos()).unwrap_or(u64::MAX);
|
|
107
|
+
self.busy_ns.fetch_add(busy_ns, Ordering::Relaxed);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/// Returns `[plain, compressed, busy_ns]` and resets them.
|
|
111
|
+
fn take(&self) -> RbResult<VALUE> {
|
|
112
|
+
rb::new_array(&[
|
|
113
|
+
rb::u64_value(self.plain.swap(0, Ordering::Relaxed))?,
|
|
114
|
+
rb::u64_value(self.compressed.swap(0, Ordering::Relaxed))?,
|
|
115
|
+
rb::u64_value(self.busy_ns.swap(0, Ordering::Relaxed))?,
|
|
116
|
+
])
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/// Compresses `input` and records the work in `stats`.
|
|
121
|
+
fn compress_recorded(
|
|
122
|
+
cctx: &mut CompressContext,
|
|
123
|
+
stats: &CompressStats,
|
|
124
|
+
input: &[u8],
|
|
125
|
+
) -> RbResult<Vec<u8>> {
|
|
126
|
+
let start = Instant::now();
|
|
127
|
+
let frame = cctx
|
|
128
|
+
.compress(input)
|
|
129
|
+
.map_err(|e| RubyErr::new(compress_error(), format!("zstd compress failed: {e}")))?;
|
|
130
|
+
let busy = start.elapsed();
|
|
131
|
+
stats.record(input.len(), frame.len(), busy);
|
|
132
|
+
Ok(frame.into_owned())
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/// Switches `cctx` to `rb_level` for later frames. A dictionary stays loaded;
|
|
136
|
+
/// zrip prepares it again for the new level.
|
|
137
|
+
fn set_level(
|
|
138
|
+
cctx: &Mutex<CompressContext>,
|
|
139
|
+
level: &AtomicI32,
|
|
140
|
+
rb_level: VALUE,
|
|
141
|
+
name: &str,
|
|
142
|
+
) -> RbResult<VALUE> {
|
|
143
|
+
let new_level = rb::value_to_i32(rb_level)?;
|
|
144
|
+
let apply = |cctx: &mut CompressContext| {
|
|
145
|
+
cctx.set_level(new_level)
|
|
146
|
+
.map_err(|e| RubyErr::arg(format!("zrip level {new_level}: {e}")))
|
|
147
|
+
};
|
|
148
|
+
let poisoned = || RubyErr::runtime(format!("{name} mutex poisoned"));
|
|
149
|
+
match cctx.try_lock() {
|
|
150
|
+
Ok(mut guard) => apply(&mut guard)?,
|
|
151
|
+
// A compression holds it without the GVL: wait without it as well.
|
|
152
|
+
Err(TryLockError::WouldBlock) => rb::maybe_without_gvl(true, || {
|
|
153
|
+
let mut guard = cctx.lock().map_err(|_| poisoned())?;
|
|
154
|
+
apply(&mut guard)
|
|
155
|
+
})??,
|
|
156
|
+
Err(TryLockError::Poisoned(_)) => return Err(poisoned()),
|
|
157
|
+
}
|
|
158
|
+
level.store(new_level, Ordering::Relaxed);
|
|
159
|
+
Ok(rb::i32_value(new_level))
|
|
160
|
+
}
|
|
161
|
+
|
|
89
162
|
// ---------- frame header parsing ----------
|
|
90
163
|
|
|
91
164
|
const ZSTD_FRAME_MAGIC: [u8; 4] = [0x28, 0xB5, 0x2F, 0xFD];
|
|
@@ -116,8 +189,11 @@ fn decompress_bounded(
|
|
|
116
189
|
}
|
|
117
190
|
|
|
118
191
|
let limit = max_output.unwrap_or(usize::MAX);
|
|
119
|
-
|
|
120
|
-
|
|
192
|
+
// A fresh buffer per frame: the context's own one would keep the largest
|
|
193
|
+
// frame's size for the codec's lifetime.
|
|
194
|
+
let mut out = Vec::new();
|
|
195
|
+
dctx.decompress_into_with_limit(compressed, &mut out, limit)
|
|
196
|
+
.map(|_| out)
|
|
121
197
|
.map_err(|err| match err {
|
|
122
198
|
zstd::DecompressError::OutputTooSmall => BoundedError::OutputSizeLimit {
|
|
123
199
|
limit: limit as u64,
|
|
@@ -296,9 +372,10 @@ unsafe fn dict_trainer_ref(value: VALUE) -> RbResult<&'static RbDictTrainer> {
|
|
|
296
372
|
struct FrameCodec {
|
|
297
373
|
dict_len: usize,
|
|
298
374
|
dict_id: Option<u32>,
|
|
299
|
-
level:
|
|
375
|
+
level: AtomicI32,
|
|
300
376
|
cctx: Mutex<CompressContext>,
|
|
301
377
|
dctx: Mutex<DecompressContext>,
|
|
378
|
+
stats: CompressStats,
|
|
302
379
|
}
|
|
303
380
|
|
|
304
381
|
unsafe impl Send for FrameCodec {}
|
|
@@ -338,9 +415,10 @@ fn frame_codec_new_impl(class: VALUE, rb_dict: VALUE, id: VALUE, level: VALUE) -
|
|
|
338
415
|
Box::new(FrameCodec {
|
|
339
416
|
dict_len,
|
|
340
417
|
dict_id,
|
|
341
|
-
level,
|
|
418
|
+
level: AtomicI32::new(level),
|
|
342
419
|
cctx: Mutex::new(cctx),
|
|
343
420
|
dctx: Mutex::new(dctx),
|
|
421
|
+
stats: CompressStats::default(),
|
|
344
422
|
}),
|
|
345
423
|
frame_codec_data_type(),
|
|
346
424
|
)?
|
|
@@ -358,11 +436,7 @@ fn frame_codec_compress_impl(rb_self: VALUE, rb_input: VALUE) -> RbResult<VALUE>
|
|
|
358
436
|
release_gvl,
|
|
359
437
|
"FrameCodec CCtx",
|
|
360
438
|
&mut input,
|
|
361
|
-
|cctx, input|
|
|
362
|
-
cctx.compress(input)
|
|
363
|
-
.map(|out| out.into_owned())
|
|
364
|
-
.map_err(|e| RubyErr::new(compress_error(), format!("zstd compress failed: {e}")))
|
|
365
|
-
},
|
|
439
|
+
|cctx, input| compress_recorded(cctx, &rb_self.stats, input),
|
|
366
440
|
)?;
|
|
367
441
|
rb::new_binary_string(&out)
|
|
368
442
|
}
|
|
@@ -409,7 +483,7 @@ fn frame_codec_id_impl(rb_self: VALUE) -> RbResult<VALUE> {
|
|
|
409
483
|
|
|
410
484
|
fn frame_codec_level_impl(rb_self: VALUE) -> RbResult<VALUE> {
|
|
411
485
|
let rb_self = unsafe { frame_codec_ref(rb_self)? };
|
|
412
|
-
Ok(rb::i32_value(rb_self.level))
|
|
486
|
+
Ok(rb::i32_value(rb_self.level.load(Ordering::Relaxed)))
|
|
413
487
|
}
|
|
414
488
|
|
|
415
489
|
fn frame_codec_get_frame_content_size_impl(rb_input: VALUE) -> RbResult<VALUE> {
|
|
@@ -457,6 +531,24 @@ unsafe extern "C" fn frame_codec_id(rb_self: VALUE) -> VALUE {
|
|
|
457
531
|
rb::wrap(|| frame_codec_id_impl(rb_self))
|
|
458
532
|
}
|
|
459
533
|
|
|
534
|
+
fn frame_codec_set_level_impl(rb_self: VALUE, rb_level: VALUE) -> RbResult<VALUE> {
|
|
535
|
+
let rb_self = unsafe { frame_codec_ref(rb_self)? };
|
|
536
|
+
set_level(&rb_self.cctx, &rb_self.level, rb_level, "FrameCodec CCtx")
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
fn frame_codec_take_stats_impl(rb_self: VALUE) -> RbResult<VALUE> {
|
|
540
|
+
let rb_self = unsafe { frame_codec_ref(rb_self)? };
|
|
541
|
+
rb_self.stats.take()
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
unsafe extern "C" fn frame_codec_set_level(rb_self: VALUE, rb_level: VALUE) -> VALUE {
|
|
545
|
+
rb::wrap(|| frame_codec_set_level_impl(rb_self, rb_level))
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
unsafe extern "C" fn frame_codec_take_stats(rb_self: VALUE) -> VALUE {
|
|
549
|
+
rb::wrap(|| frame_codec_take_stats_impl(rb_self))
|
|
550
|
+
}
|
|
551
|
+
|
|
460
552
|
unsafe extern "C" fn frame_codec_level(rb_self: VALUE) -> VALUE {
|
|
461
553
|
rb::wrap(|| frame_codec_level_impl(rb_self))
|
|
462
554
|
}
|
|
@@ -470,9 +562,10 @@ unsafe extern "C" fn frame_codec_get_frame_content_size(_class: VALUE, rb_input:
|
|
|
470
562
|
struct BlockCodec {
|
|
471
563
|
dict_len: usize,
|
|
472
564
|
dict_id: Option<u32>,
|
|
473
|
-
level:
|
|
565
|
+
level: AtomicI32,
|
|
474
566
|
cctx: Mutex<CompressContext>,
|
|
475
567
|
dctx: Mutex<DecompressContext>,
|
|
568
|
+
stats: CompressStats,
|
|
476
569
|
}
|
|
477
570
|
|
|
478
571
|
fn block_codec_new_impl(class: VALUE, rb_dict: VALUE, id: VALUE, level: VALUE) -> RbResult<VALUE> {
|
|
@@ -509,9 +602,10 @@ fn block_codec_new_impl(class: VALUE, rb_dict: VALUE, id: VALUE, level: VALUE) -
|
|
|
509
602
|
Box::new(BlockCodec {
|
|
510
603
|
dict_len,
|
|
511
604
|
dict_id,
|
|
512
|
-
level,
|
|
605
|
+
level: AtomicI32::new(level),
|
|
513
606
|
cctx: Mutex::new(cctx),
|
|
514
607
|
dctx: Mutex::new(dctx),
|
|
608
|
+
stats: CompressStats::default(),
|
|
515
609
|
}),
|
|
516
610
|
block_codec_data_type(),
|
|
517
611
|
)
|
|
@@ -527,11 +621,7 @@ fn block_codec_compress_impl(rb_self: VALUE, rb_input: VALUE) -> RbResult<VALUE>
|
|
|
527
621
|
release_gvl,
|
|
528
622
|
"BlockCodec CCtx",
|
|
529
623
|
&mut input,
|
|
530
|
-
|cctx, input|
|
|
531
|
-
cctx.compress(input)
|
|
532
|
-
.map(|out| out.into_owned())
|
|
533
|
-
.map_err(|e| RubyErr::new(compress_error(), format!("zstd compress failed: {e}")))
|
|
534
|
-
},
|
|
624
|
+
|cctx, input| compress_recorded(cctx, &rb_self.stats, input),
|
|
535
625
|
)?;
|
|
536
626
|
rb::new_binary_string(&out)
|
|
537
627
|
}
|
|
@@ -569,7 +659,7 @@ fn block_codec_has_dict_impl(rb_self: VALUE) -> RbResult<VALUE> {
|
|
|
569
659
|
|
|
570
660
|
fn block_codec_level_impl(rb_self: VALUE) -> RbResult<VALUE> {
|
|
571
661
|
let rb_self = unsafe { block_codec_ref(rb_self)? };
|
|
572
|
-
Ok(rb::i32_value(rb_self.level))
|
|
662
|
+
Ok(rb::i32_value(rb_self.level.load(Ordering::Relaxed)))
|
|
573
663
|
}
|
|
574
664
|
|
|
575
665
|
unsafe extern "C" fn block_codec_new(
|
|
@@ -601,6 +691,24 @@ unsafe extern "C" fn block_codec_has_dict(rb_self: VALUE) -> VALUE {
|
|
|
601
691
|
rb::wrap(|| block_codec_has_dict_impl(rb_self))
|
|
602
692
|
}
|
|
603
693
|
|
|
694
|
+
fn block_codec_set_level_impl(rb_self: VALUE, rb_level: VALUE) -> RbResult<VALUE> {
|
|
695
|
+
let rb_self = unsafe { block_codec_ref(rb_self)? };
|
|
696
|
+
set_level(&rb_self.cctx, &rb_self.level, rb_level, "BlockCodec CCtx")
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
fn block_codec_take_stats_impl(rb_self: VALUE) -> RbResult<VALUE> {
|
|
700
|
+
let rb_self = unsafe { block_codec_ref(rb_self)? };
|
|
701
|
+
rb_self.stats.take()
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
unsafe extern "C" fn block_codec_set_level(rb_self: VALUE, rb_level: VALUE) -> VALUE {
|
|
705
|
+
rb::wrap(|| block_codec_set_level_impl(rb_self, rb_level))
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
unsafe extern "C" fn block_codec_take_stats(rb_self: VALUE) -> VALUE {
|
|
709
|
+
rb::wrap(|| block_codec_take_stats_impl(rb_self))
|
|
710
|
+
}
|
|
711
|
+
|
|
604
712
|
unsafe extern "C" fn block_codec_level(rb_self: VALUE) -> VALUE {
|
|
605
713
|
rb::wrap(|| block_codec_level_impl(rb_self))
|
|
606
714
|
}
|
|
@@ -812,6 +920,8 @@ fn init() -> RbResult<()> {
|
|
|
812
920
|
rb::define_method_0(frame_codec_class, c"has_dict?", frame_codec_has_dict)?;
|
|
813
921
|
rb::define_method_0(frame_codec_class, c"id", frame_codec_id)?;
|
|
814
922
|
rb::define_method_0(frame_codec_class, c"level", frame_codec_level)?;
|
|
923
|
+
rb::define_method_1(frame_codec_class, c"level=", frame_codec_set_level)?;
|
|
924
|
+
rb::define_method_0(frame_codec_class, c"_take_stats", frame_codec_take_stats)?;
|
|
815
925
|
}
|
|
816
926
|
|
|
817
927
|
let block_codec_class =
|
|
@@ -828,8 +938,12 @@ fn init() -> RbResult<()> {
|
|
|
828
938
|
rb::define_method_0(block_codec_class, c"size", block_codec_size)?;
|
|
829
939
|
rb::define_method_0(block_codec_class, c"has_dict?", block_codec_has_dict)?;
|
|
830
940
|
rb::define_method_0(block_codec_class, c"level", block_codec_level)?;
|
|
941
|
+
rb::define_method_1(block_codec_class, c"level=", block_codec_set_level)?;
|
|
942
|
+
rb::define_method_0(block_codec_class, c"_take_stats", block_codec_take_stats)?;
|
|
831
943
|
}
|
|
832
944
|
|
|
945
|
+
adaptive::define(module)?;
|
|
946
|
+
|
|
833
947
|
let trainer_class =
|
|
834
948
|
unsafe { rb::define_class_under(module, c"DictTrainer", rb_sys::rb_cObject)? };
|
|
835
949
|
unsafe {
|
data/ext/zrip/src/rb.rs
CHANGED
|
@@ -427,6 +427,18 @@ pub fn value_to_i32(value: VALUE) -> RbResult<i32> {
|
|
|
427
427
|
i32::try_from(out).map_err(|_| RubyErr::arg("integer too large"))
|
|
428
428
|
}
|
|
429
429
|
|
|
430
|
+
pub fn value_to_u64(value: VALUE) -> RbResult<u64> {
|
|
431
|
+
Ok(value_to_usize(value)? as u64)
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
pub fn u64_value(value: u64) -> RbResult<VALUE> {
|
|
435
|
+
protect_value(|| unsafe { rb_sys::rb_ull2inum(value) })
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
pub fn new_array(values: &[VALUE]) -> RbResult<VALUE> {
|
|
439
|
+
protect_value(|| unsafe { rb_sys::rb_ary_new_from_values(values.len() as _, values.as_ptr()) })
|
|
440
|
+
}
|
|
441
|
+
|
|
430
442
|
pub fn usize_value(value: usize) -> RbResult<VALUE> {
|
|
431
443
|
protect_value(|| unsafe { rb_sys::rb_ull2inum(value as u64) })
|
|
432
444
|
}
|
|
@@ -587,6 +599,27 @@ pub unsafe fn define_method_2(
|
|
|
587
599
|
})
|
|
588
600
|
}
|
|
589
601
|
|
|
602
|
+
pub unsafe fn define_method_4(
|
|
603
|
+
class: VALUE,
|
|
604
|
+
name: &CStr,
|
|
605
|
+
func: unsafe extern "C" fn(VALUE, VALUE, VALUE, VALUE, VALUE) -> VALUE,
|
|
606
|
+
) -> RbResult<()> {
|
|
607
|
+
protect_unit(|| unsafe {
|
|
608
|
+
rb_sys::rb_define_method(class, name.as_ptr(), Some(transmute_4(func)), 4)
|
|
609
|
+
})
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
unsafe fn transmute_4(
|
|
613
|
+
func: unsafe extern "C" fn(VALUE, VALUE, VALUE, VALUE, VALUE) -> VALUE,
|
|
614
|
+
) -> unsafe extern "C" fn() -> VALUE {
|
|
615
|
+
unsafe {
|
|
616
|
+
std::mem::transmute::<
|
|
617
|
+
unsafe extern "C" fn(VALUE, VALUE, VALUE, VALUE, VALUE) -> VALUE,
|
|
618
|
+
unsafe extern "C" fn() -> VALUE,
|
|
619
|
+
>(func)
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
|
|
590
623
|
unsafe fn transmute_0(
|
|
591
624
|
func: unsafe extern "C" fn(VALUE) -> VALUE,
|
|
592
625
|
) -> unsafe extern "C" fn() -> VALUE {
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Zrip
|
|
4
|
+
# Picks a compression level per window of work: zrip's hill climb over the
|
|
5
|
+
# levels of a range. Feed it each window's stats (see `FrameCodec#take_stats`)
|
|
6
|
+
# and what limited the sender, and compress at the level it returns.
|
|
7
|
+
#
|
|
8
|
+
# Not Ractor-shareable: use one per connection.
|
|
9
|
+
#
|
|
10
|
+
# @!method level
|
|
11
|
+
# @return [Integer] the level to compress at
|
|
12
|
+
class AdaptiveLevel
|
|
13
|
+
BOTTLENECKS = { output: 0, cpu: 1, input: 2 }.freeze
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
# @param range [Range<Integer>] levels to walk, within -8..4
|
|
17
|
+
# @param start [Integer] start at the first level of the range not below
|
|
18
|
+
# it; -1 by default, as omq.rs
|
|
19
|
+
# @raise [ArgumentError] if the range holds no zrip level
|
|
20
|
+
def self.new(range, start: -1)
|
|
21
|
+
unless Range === range && Integer === range.begin && Integer === range.end
|
|
22
|
+
raise ArgumentError, "range must be a Range of Integers, got #{range.inspect}"
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
min = range.min
|
|
26
|
+
max = range.max
|
|
27
|
+
raise ArgumentError, "#{range.inspect} is empty" if min.nil?
|
|
28
|
+
|
|
29
|
+
_native_new(min, max, Integer(start))
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# Records one window at the current level and returns the next level.
|
|
34
|
+
#
|
|
35
|
+
# @param plain [Integer] input bytes compressed in the window
|
|
36
|
+
# @param compressed [Integer] compressed bytes
|
|
37
|
+
# @param busy [Float] seconds spent compressing
|
|
38
|
+
# @param bottleneck [Symbol, nil] `:output` (writes stalled), `:cpu`
|
|
39
|
+
# (input waited while output kept up), `:input` (nothing waited), or nil
|
|
40
|
+
# (the default) when unclear; the level then holds
|
|
41
|
+
# @return [Integer]
|
|
42
|
+
# @raise [ArgumentError] on an unknown bottleneck
|
|
43
|
+
def update(plain:, compressed:, busy:, bottleneck: nil)
|
|
44
|
+
code = if bottleneck.nil?
|
|
45
|
+
-1
|
|
46
|
+
else
|
|
47
|
+
BOTTLENECKS.fetch(bottleneck) do
|
|
48
|
+
raise ArgumentError, "bottleneck must be :output, :cpu, :input or nil, got #{bottleneck.inspect}"
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
_update(Integer(plain), Integer(compressed), (Float(busy) * 1e9).round, code)
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
end
|
|
56
|
+
end
|
data/lib/zrip/block_codec.rb
CHANGED
|
@@ -28,6 +28,12 @@ module Zrip
|
|
|
28
28
|
# @return [String]
|
|
29
29
|
# @raise [CompressError]
|
|
30
30
|
#
|
|
31
|
+
# @!method level=(level)
|
|
32
|
+
# Compress later frames at `level`. A dictionary stays loaded.
|
|
33
|
+
# @param level [Integer] compression level
|
|
34
|
+
# @return [Integer]
|
|
35
|
+
# @raise [ArgumentError] for a level zrip lacks
|
|
36
|
+
#
|
|
31
37
|
# @!method decompress(bytes, max_output_size: nil)
|
|
32
38
|
# Decompress a Zstandard frame.
|
|
33
39
|
# @param bytes [String] compressed Zstandard frame
|
|
@@ -71,5 +77,17 @@ module Zrip
|
|
|
71
77
|
def decompress(bytes, max_output_size: nil)
|
|
72
78
|
_native_decompress(bytes, max_output_size && Integer(max_output_size))
|
|
73
79
|
end
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# Returns the compression work since the last call and resets it.
|
|
83
|
+
# `busy` is the time spent compressing, measured natively, so it leaves
|
|
84
|
+
# out waits for the GVL.
|
|
85
|
+
#
|
|
86
|
+
# @return [Hash{Symbol => Numeric}] `{plain:, compressed:, busy:}` in
|
|
87
|
+
# bytes and seconds
|
|
88
|
+
def take_stats
|
|
89
|
+
plain, compressed, busy_ns = _take_stats
|
|
90
|
+
{ plain: plain, compressed: compressed, busy: busy_ns / 1e9 }
|
|
91
|
+
end
|
|
74
92
|
end
|
|
75
93
|
end
|
data/lib/zrip/frame_codec.rb
CHANGED
|
@@ -34,6 +34,12 @@ module Zrip
|
|
|
34
34
|
# @return [String]
|
|
35
35
|
# @raise [CompressError]
|
|
36
36
|
#
|
|
37
|
+
# @!method level=(level)
|
|
38
|
+
# Compress later frames at `level`. A dictionary stays loaded.
|
|
39
|
+
# @param level [Integer] compression level
|
|
40
|
+
# @return [Integer]
|
|
41
|
+
# @raise [ArgumentError] for a level zrip lacks
|
|
42
|
+
#
|
|
37
43
|
# @!method decompress(bytes, max_output_size: nil)
|
|
38
44
|
# Decompress a Zstandard frame.
|
|
39
45
|
# @param bytes [String] compressed Zstandard frame
|
|
@@ -80,5 +86,17 @@ module Zrip
|
|
|
80
86
|
def decompress(bytes, max_output_size: nil)
|
|
81
87
|
_native_decompress(bytes, max_output_size && Integer(max_output_size))
|
|
82
88
|
end
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# Returns the compression work since the last call and resets it.
|
|
92
|
+
# `busy` is the time spent compressing, measured natively, so it leaves
|
|
93
|
+
# out waits for the GVL.
|
|
94
|
+
#
|
|
95
|
+
# @return [Hash{Symbol => Numeric}] `{plain:, compressed:, busy:}` in
|
|
96
|
+
# bytes and seconds
|
|
97
|
+
def take_stats
|
|
98
|
+
plain, compressed, busy_ns = _take_stats
|
|
99
|
+
{ plain: plain, compressed: compressed, busy: busy_ns / 1e9 }
|
|
100
|
+
end
|
|
83
101
|
end
|
|
84
102
|
end
|
data/lib/zrip/version.rb
CHANGED
data/lib/zrip.rb
CHANGED
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: zrip
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.3.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Patrik Wenger
|
|
@@ -47,9 +47,11 @@ files:
|
|
|
47
47
|
- ext/zrip/Cargo.toml
|
|
48
48
|
- ext/zrip/build.rs
|
|
49
49
|
- ext/zrip/extconf.rb
|
|
50
|
+
- ext/zrip/src/adaptive.rs
|
|
50
51
|
- ext/zrip/src/lib.rs
|
|
51
52
|
- ext/zrip/src/rb.rs
|
|
52
53
|
- lib/zrip.rb
|
|
54
|
+
- lib/zrip/adaptive_level.rb
|
|
53
55
|
- lib/zrip/block_codec.rb
|
|
54
56
|
- lib/zrip/dict_trainer.rb
|
|
55
57
|
- lib/zrip/dictionary.rb
|