maxmind-db-rust 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/README.md CHANGED
@@ -40,8 +40,8 @@ gem install maxmind-db-rust
40
40
 
41
41
  ## Requirements
42
42
 
43
- - Ruby 3.2 or higher
44
- - Rust toolchain (for building from source)
43
+ - Ruby 3.3 or higher
44
+ - Rust 1.85 or higher (for building from source)
45
45
 
46
46
  ## Usage
47
47
 
@@ -161,6 +161,12 @@ modified or truncated while the reader is alive. To refresh a database, write
161
161
  the replacement to a new file and atomically rename it over the old path. Use
162
162
  `MODE_MEMORY` if the file lifecycle cannot be controlled this way.
163
163
 
164
+ `MODE_MEMORY` reads the file without holding Ruby's global VM lock, so other
165
+ threads keep running while a large database loads. The read cannot be
166
+ interrupted, so a path that never finishes reading, such as a hung network
167
+ mount, blocks the opening thread (and `Timeout` or `Thread#kill` on it) until
168
+ the read returns.
169
+
164
170
  ### Accessing Metadata
165
171
 
166
172
  ```ruby
@@ -224,15 +230,15 @@ Create a new Reader instance.
224
230
 
225
231
  **Parameters:**
226
232
 
227
- - `database` (String): Path to the MaxMind DB file, or database bytes when using `:MODE_PARAM_IS_BUFFER`
228
- - `options` (Hash): Optional configuration
233
+ - `database` (String or Pathname): Path to the MaxMind DB file, or database bytes when using `:MODE_PARAM_IS_BUFFER`. Any object that responds to `to_path` is accepted as a path.
234
+ - `options` (Hash): Optional configuration, passed as keywords or as a positional Hash
229
235
  - `:mode` (Symbol): One of `:MODE_AUTO`, `:MODE_FILE`, `:MODE_MEMORY`, `:MODE_MMAP`, or `:MODE_PARAM_IS_BUFFER`
230
236
 
231
- **Returns:** Reader instance
237
+ **Returns:** Reader instance. `Reader` can be subclassed, and `new` calls the subclass's `initialize`.
232
238
 
233
239
  **Raises:**
234
240
 
235
- - `Errno::ENOENT`: If the database file does not exist
241
+ - `SystemCallError`: If the database file cannot be opened, for example `Errno::ENOENT`, `Errno::EACCES` or `Errno::EISDIR`
236
242
  - `MaxMind::DB::Rust::InvalidDatabaseError`: If the file is not a valid MaxMind DB
237
243
 
238
244
  #### `get(ip_address)`
@@ -241,12 +247,13 @@ Look up an IP address in the database.
241
247
 
242
248
  **Parameters:**
243
249
 
244
- - `ip_address` (String or IPAddr): The IP address to look up
250
+ - `ip_address` (String or IPAddr): The IP address to look up. Strings are parsed like `IPAddr.new`, so CIDR strings such as `"1.2.3.4/32"` and scoped IPv6 addresses such as `"fe80::1%eth0"` are accepted.
245
251
 
246
252
  **Returns:** Hash with the record data, or `nil` if not found
247
253
 
248
254
  **Raises:**
249
255
 
256
+ - `IPAddr::InvalidAddressError`: If the IP address is invalid (a subclass of `ArgumentError`)
250
257
  - `ArgumentError`: If looking up IPv6 in an IPv4-only database
251
258
  - `MaxMind::DB::Rust::InvalidDatabaseError`: If the database is corrupt
252
259
 
@@ -294,7 +301,7 @@ Look up one path for multiple IP addresses.
294
301
 
295
302
  #### `metadata()`
296
303
 
297
- Get metadata about the database.
304
+ Get metadata about the database. Like the official gem, this still works after `close`.
298
305
 
299
306
  **Returns:** `MaxMind::DB::Rust::Metadata` instance
300
307
 
@@ -306,6 +313,11 @@ entire database and may use memory proportional to the number of distinct
306
313
  referenced values, so it is intended for explicit integrity checks rather than
307
314
  the lookup hot path.
308
315
 
316
+ Verification runs without holding Ruby's global VM lock, so other Ruby threads
317
+ keep running while it works. It cannot be cancelled part way through:
318
+ `Thread#raise`, `Timeout`, and signals such as Ctrl-C take effect once
319
+ verification finishes.
320
+
309
321
  **Returns:** `true` when the database passes verification
310
322
 
311
323
  **Raises:** `MaxMind::DB::Rust::InvalidDatabaseError` when verification fails
@@ -326,7 +338,7 @@ Iterate over networks in the database.
326
338
 
327
339
  **Parameters:**
328
340
 
329
- - `network` (String or IPAddr, optional): Network CIDR to iterate within (e.g., "192.168.0.0/16"). If omitted, iterates over all networks in the database.
341
+ - `network` (String or IPAddr, optional): Network CIDR to iterate within (e.g., "192.168.0.0/16"). If omitted or `nil`, iterates over all networks in the database.
330
342
 
331
343
  **Yields:** IPAddr network and Hash data for each entry
332
344
 
@@ -334,7 +346,7 @@ Iterate over networks in the database.
334
346
 
335
347
  **Raises:**
336
348
 
337
- - `ArgumentError`: If network CIDR is invalid or IPv6 network specified for IPv4-only database
349
+ - `ArgumentError`: If network CIDR is invalid, IPv6 network specified for IPv4-only database, or more than one argument is given. These are raised even when no block is given.
338
350
 
339
351
  ### `MaxMind::DB::Rust::Metadata`
340
352
 
@@ -379,6 +391,12 @@ Metadata attributes:
379
391
  | Iterator support | ✗ | ✓ |
380
392
  | Thread-safe | ✓ | ✓ |
381
393
 
394
+ Known differences from the official gem:
395
+
396
+ - Lookups on a closed reader raise `RuntimeError` rather than `IOError`.
397
+ - Unknown options raise `ArgumentError`. The official gem ignores them.
398
+ - Readers cannot be copied with `dup` or `clone`.
399
+
382
400
  ## Performance
383
401
 
384
402
  Lookup performance depends on hardware, Ruby version, database, and workload.
@@ -2,6 +2,7 @@
2
2
  name = "maxmind_db_rust"
3
3
  version = "0.1.0"
4
4
  edition = "2021"
5
+ rust-version = "1.85"
5
6
  authors = ["Gregory Oschwald <oschwald@gmail.com>"]
6
7
  description = "Rust-based Ruby binding for MaxMind DB - high-performance alternative to maxmind-db"
7
8
  license = "ISC"
@@ -14,8 +15,10 @@ crate-type = ["cdylib"]
14
15
  [dependencies]
15
16
  arc-swap = "1.9"
16
17
  ipnetwork = "0.21"
17
- magnus = "0.8"
18
- maxminddb = "0.32.0"
18
+ magnus = { version = "0.9", features = ["rb-sys"] }
19
+ maxminddb = "0.33.0"
19
20
  memmap2 = "0.9"
21
+ rb-sys = { version = "0.9", default-features = false }
20
22
  rustc-hash = "2.1"
23
+ self_cell = "1.3"
21
24
  serde = "1.0"
@@ -3,4 +3,7 @@
3
3
  require 'mkmf'
4
4
  require 'rb_sys/mkmf'
5
5
 
6
- create_rust_makefile('maxmind/db/maxmind_db_rust')
6
+ create_rust_makefile('maxmind/db/maxmind_db_rust') do |r|
7
+ # Build with the dependency versions in the shipped Cargo.lock.
8
+ r.extra_cargo_args += ['--locked']
9
+ end
@@ -0,0 +1,61 @@
1
+ //! Converting Ruby arguments that may be one of several types.
2
+
3
+ use magnus::{
4
+ error::Error,
5
+ rb_sys::{protect, AsRawValue, FromRawValue},
6
+ RArray, RHash, TryConvert, Value,
7
+ };
8
+
9
+ /// Converts `value`, or returns `None` if it is not convertible to `T`.
10
+ ///
11
+ /// Conversion can call Ruby methods such as `to_str`. Only a `TypeError` means
12
+ /// "not convertible". Any other error must reach the caller: dropping a pending
13
+ /// `throw` or thread kill and then calling Ruby again crashes the interpreter,
14
+ /// and dropping `Interrupt` would ignore Ctrl-C.
15
+ ///
16
+ /// Use `try_convert_array` and `try_convert_hash` for those types.
17
+ #[inline]
18
+ pub(crate) fn try_convert_optional<T: TryConvert>(
19
+ value: Value,
20
+ ruby: &magnus::Ruby,
21
+ ) -> Result<Option<T>, Error> {
22
+ none_if_type_error(T::try_convert(value), ruby)
23
+ }
24
+
25
+ /// Like `try_convert_optional` for an Array.
26
+ ///
27
+ /// The error from magnus's `RArray::try_convert` names the class of `value`. It
28
+ /// calls the class's `to_s` for that and drops anything `to_s` throws.
29
+ #[inline]
30
+ pub(crate) fn try_convert_array(
31
+ value: Value,
32
+ ruby: &magnus::Ruby,
33
+ ) -> Result<Option<RArray>, Error> {
34
+ if let Some(array) = RArray::from_value(value) {
35
+ return Ok(Some(array));
36
+ }
37
+ // SAFETY: `value` is live, and `protect` catches anything that is raised or
38
+ // thrown. The result is an Array or nil.
39
+ let converted = protect(|| unsafe { rb_sys::rb_check_array_type(value.as_raw()) });
40
+ let converted = none_if_type_error(converted, ruby)?;
41
+ Ok(converted.and_then(|raw| RArray::from_value(unsafe { Value::from_raw(raw) })))
42
+ }
43
+
44
+ /// Like `try_convert_array` for a Hash, where magnus has the same problem.
45
+ pub(crate) fn try_convert_hash(value: Value, ruby: &magnus::Ruby) -> Result<Option<RHash>, Error> {
46
+ // SAFETY: as in `try_convert_array`. The result is a Hash or nil.
47
+ let converted = protect(|| unsafe { rb_sys::rb_check_hash_type(value.as_raw()) });
48
+ let converted = none_if_type_error(converted, ruby)?;
49
+ Ok(converted.and_then(|raw| RHash::from_value(unsafe { Value::from_raw(raw) })))
50
+ }
51
+
52
+ fn none_if_type_error<T>(
53
+ result: Result<T, Error>,
54
+ ruby: &magnus::Ruby,
55
+ ) -> Result<Option<T>, Error> {
56
+ match result {
57
+ Ok(converted) => Ok(Some(converted)),
58
+ Err(err) if err.is_kind_of(ruby.exception_type_error()) => Ok(None),
59
+ Err(err) => Err(err),
60
+ }
61
+ }
@@ -0,0 +1,76 @@
1
+ //! Running pure Rust work without holding Ruby's Global VM Lock (GVL).
2
+
3
+ use magnus::error::Error;
4
+ use std::{
5
+ ffi::c_void,
6
+ panic::{self, AssertUnwindSafe},
7
+ ptr,
8
+ };
9
+
10
+ struct Call<F, R> {
11
+ func: Option<F>,
12
+ result: Option<std::thread::Result<R>>,
13
+ }
14
+
15
+ /// Runs `func` with the GVL released so other Ruby threads can run.
16
+ ///
17
+ /// `func` must not touch any Ruby object or call any Ruby API, including
18
+ /// creating exceptions. Return plain Rust data and convert it to Ruby values
19
+ /// after this function returns.
20
+ ///
21
+ /// No unblocking function is registered, so `func` always runs to the end.
22
+ /// `Thread#raise`, `Timeout` and signals such as Ctrl-C take effect once it
23
+ /// returns, and are returned here as an `Err` so they can propagate normally.
24
+ pub(crate) fn without_gvl<F, R>(func: F) -> Result<R, Error>
25
+ where
26
+ F: FnOnce() -> R,
27
+ {
28
+ let mut call = Call {
29
+ func: Some(func),
30
+ result: None,
31
+ };
32
+ let data: *mut c_void = (&mut call as *mut Call<F, R>).cast();
33
+
34
+ // `rb_thread_call_without_gvl` checks for pending interrupts after the
35
+ // callback returns and may raise. `protect` catches that raise so it does
36
+ // not unwind over Rust frames; `call` lives outside the closure and is
37
+ // dropped normally.
38
+ let protected = magnus::rb_sys::protect(|| {
39
+ // SAFETY: the trampoline matches the callback signature, `call`
40
+ // outlives the call, and the caller guarantees `func` does not use
41
+ // the Ruby API.
42
+ unsafe {
43
+ rb_sys::rb_thread_call_without_gvl(
44
+ Some(call_trampoline::<F, R>),
45
+ data,
46
+ None,
47
+ ptr::null_mut(),
48
+ );
49
+ }
50
+ rb_sys::Qnil as rb_sys::VALUE
51
+ });
52
+
53
+ match call.result.take() {
54
+ Some(Ok(value)) => protected.map(|_| value),
55
+ Some(Err(payload)) => panic::resume_unwind(payload),
56
+ None => {
57
+ protected?;
58
+ unreachable!("rb_thread_call_without_gvl returned without running the callback")
59
+ }
60
+ }
61
+ }
62
+
63
+ unsafe extern "C" fn call_trampoline<F, R>(data: *mut c_void) -> *mut c_void
64
+ where
65
+ F: FnOnce() -> R,
66
+ {
67
+ // SAFETY: `data` is the `Call<F, R>` that `without_gvl` passed in, and it
68
+ // stays borrowed until `rb_thread_call_without_gvl` returns.
69
+ let call = unsafe { &mut *data.cast::<Call<F, R>>() };
70
+ if let Some(func) = call.func.take() {
71
+ // A panic must not unwind across the C frame, so catch it here and
72
+ // resume it once the GVL is held again.
73
+ call.result = Some(panic::catch_unwind(AssertUnwindSafe(func)));
74
+ }
75
+ ptr::null_mut()
76
+ }
@@ -1,5 +1,10 @@
1
1
  use crate::{metadata, reader, STRING_CACHE_MAX, STRING_CACHE_ROOTS_CONST};
2
- use magnus::{error::Error, prelude::*, RModule, Value};
2
+ use magnus::{
3
+ error::Error,
4
+ prelude::*,
5
+ rb_sys::{protect, AsRawId, AsRawValue, FromRawValue},
6
+ RModule, Value,
7
+ };
3
8
 
4
9
  const MAP_KEY_ROOTS_CONST: &str = "__MAP_KEY_ROOTS__";
5
10
 
@@ -9,12 +14,11 @@ pub(crate) fn initialize(ruby: &magnus::Ruby) -> Result<(), Error> {
9
14
  let maxmind = ruby.define_module("MaxMind")?;
10
15
 
11
16
  // Try to get or define DB - it might be a Class (official gem) or Module (ours)
12
- let db_value = maxmind.const_get::<_, Value>("DB");
13
- let rust = match db_value {
14
- Ok(existing) if existing.is_kind_of(ruby.class_class()) => {
17
+ let rust = match own_constant(maxmind.as_value(), "DB")? {
18
+ Some(existing) if existing.is_kind_of(ruby.class_class()) => {
15
19
  // MaxMind::DB exists as a Class (official gem loaded first)
16
20
  // Reuse existing Rust constant if present to avoid replacing classes.
17
- if let Ok(rust_value) = existing.funcall::<_, _, Value>("const_get", ("Rust", false)) {
21
+ if let Some(rust_value) = own_constant(existing, "Rust")? {
18
22
  RModule::from_value(rust_value).ok_or_else(|| {
19
23
  Error::new(
20
24
  ruby.exception_type_error(),
@@ -34,38 +38,46 @@ pub(crate) fn initialize(ruby: &magnus::Ruby) -> Result<(), Error> {
34
38
  rust_mod
35
39
  }
36
40
  }
37
- Ok(existing) => {
41
+ Some(existing) => {
38
42
  // MaxMind::DB exists as a Module (our gem loaded first)
39
43
  let db_mod = RModule::from_value(existing).ok_or_else(|| {
40
44
  Error::new(ruby.exception_type_error(), "MaxMind::DB is not a module")
41
45
  })?;
42
46
  db_mod.define_module("Rust")?
43
47
  }
44
- Err(_) => {
48
+ None => {
45
49
  // MaxMind::DB doesn't exist, define it as a module
46
50
  let db = maxmind.define_module("DB")?;
47
51
  db.define_module("Rust")?
48
52
  }
49
53
  };
50
54
 
51
- if rust
52
- .const_get::<_, Value>(STRING_CACHE_ROOTS_CONST)
53
- .is_err()
54
- {
55
- let roots = ruby.ary_new_capa(STRING_CACHE_MAX);
56
- for _ in 0..STRING_CACHE_MAX {
57
- roots.push(ruby.qnil().as_value())?;
55
+ let roots = match own_constant(rust.as_value(), STRING_CACHE_ROOTS_CONST)? {
56
+ Some(existing) => existing,
57
+ None => {
58
+ let roots = ruby.ary_new_capa(STRING_CACHE_MAX);
59
+ for _ in 0..STRING_CACHE_MAX {
60
+ roots.push(ruby.qnil().as_value())?;
61
+ }
62
+ rust.const_set(STRING_CACHE_ROOTS_CONST, roots)?;
63
+ roots.as_value()
58
64
  }
59
- rust.const_set(STRING_CACHE_ROOTS_CONST, roots)?;
60
- }
65
+ };
66
+ // Decoder threads keep this array's handle in a Rust thread-local that Ruby
67
+ // cannot see or update. Registering it as a permanent mark object pins it,
68
+ // so GC compaction can never move it and leave that handle stale. The
69
+ // constant only makes it reachable from Ruby. Register on every load, since
70
+ // an existing array may come from an earlier build that did not pin it;
71
+ // registering the same object again is harmless.
72
+ ruby.gc_register_mark_object(roots);
61
73
 
62
- if rust.const_get::<_, Value>(MAP_KEY_ROOTS_CONST).is_ok() {
74
+ if own_constant(rust.as_value(), MAP_KEY_ROOTS_CONST)?.is_some() {
63
75
  let _ = rust.funcall::<_, _, Value>("send", ("remove_const", MAP_KEY_ROOTS_CONST))?;
64
76
  }
65
77
 
66
78
  // The extension can be loaded more than once from different paths.
67
79
  // Reusing previously defined classes avoids typed-data incompatibilities.
68
- if rust.const_get::<_, Value>("Reader").is_ok() {
80
+ if own_constant(rust.as_value(), "Reader")?.is_some() {
69
81
  return Ok(());
70
82
  }
71
83
 
@@ -73,3 +85,32 @@ pub(crate) fn initialize(ruby: &magnus::Ruby) -> Result<(), Error> {
73
85
  metadata::define(ruby, rust)?;
74
86
  Ok(())
75
87
  }
88
+
89
+ /// Returns the constant `name` defined in `module` itself, if any.
90
+ ///
91
+ /// A plain `const_get` on a module also finds top-level constants, such as an
92
+ /// application's own `DB`. Its error can also come from an autoload.
93
+ fn own_constant(module: Value, name: &str) -> Result<Option<Value>, Error> {
94
+ let ruby = magnus::Ruby::get_with(module);
95
+ let id = ruby.intern(name).as_raw();
96
+ let module = module.as_raw();
97
+ let mut defined = false;
98
+ // SAFETY: `module` is a live Module or Class, `id` is an interned symbol,
99
+ // and `protect` catches anything that an autoload raises or throws.
100
+ let constant = protect(|| unsafe {
101
+ // Run an autoload first. It may not define the constant, and then
102
+ // getting the constant would call `const_missing`.
103
+ rb_sys::rb_autoload_load(module, id);
104
+ defined = rb_sys::rb_const_defined_at(module, id) != 0;
105
+ if defined {
106
+ rb_sys::rb_const_get_at(module, id)
107
+ } else {
108
+ rb_sys::Qnil as rb_sys::VALUE
109
+ }
110
+ })?;
111
+ if !defined {
112
+ return Ok(None);
113
+ }
114
+ // SAFETY: `constant` is the live value of the constant.
115
+ Ok(Some(unsafe { Value::from_raw(constant) }))
116
+ }
@@ -1,4 +1,6 @@
1
+ mod convert;
1
2
  mod decoder;
3
+ mod gvl;
2
4
  mod initialization;
3
5
  mod metadata;
4
6
  mod path;
@@ -83,8 +83,8 @@ impl Metadata {
83
83
  self.record_size / 4
84
84
  }
85
85
 
86
- fn search_tree_size(&self) -> u32 {
87
- self.node_count * (self.record_size as u32 / 4)
86
+ fn search_tree_size(&self) -> u64 {
87
+ u64::from(self.node_count) * u64::from(self.record_size / 4)
88
88
  }
89
89
  }
90
90
 
@@ -121,3 +121,36 @@ pub(crate) fn define(ruby: &magnus::Ruby, rust: RModule) -> Result<(), Error> {
121
121
  )?;
122
122
  Ok(())
123
123
  }
124
+
125
+ #[cfg(test)]
126
+ mod tests {
127
+ use super::Metadata;
128
+ use std::collections::BTreeMap;
129
+
130
+ fn metadata(node_count: u32, record_size: u16) -> Metadata {
131
+ Metadata {
132
+ binary_format_major_version: 2,
133
+ binary_format_minor_version: 0,
134
+ build_epoch: 0,
135
+ database_type: String::new(),
136
+ description_map: BTreeMap::new(),
137
+ ip_version: 6,
138
+ languages_list: Vec::new(),
139
+ node_count,
140
+ record_size,
141
+ }
142
+ }
143
+
144
+ #[test]
145
+ fn search_tree_size_does_not_wrap_at_4_gib() {
146
+ assert_eq!(metadata(536_870_912, 32).search_tree_size(), 4_294_967_296);
147
+ }
148
+
149
+ #[test]
150
+ fn search_tree_size_handles_maximum_node_count() {
151
+ assert_eq!(
152
+ metadata(u32::MAX, 32).search_tree_size(),
153
+ u64::from(u32::MAX) * 8
154
+ );
155
+ }
156
+ }