maxmind-db-rust 0.6.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.
@@ -1,5 +1,7 @@
1
1
  use crate::{
2
+ convert::{try_convert_array, try_convert_hash, try_convert_optional},
2
3
  decoder::RubyDecodedValue,
4
+ gvl::without_gvl,
3
5
  metadata::Metadata,
4
6
  path::{
5
7
  parse_path_array, path_array, path_cache_hash, path_elements_from_owned_path,
@@ -11,8 +13,17 @@ use ::maxminddb as maxminddb_crate;
11
13
  use arc_swap::{ArcSwapOption, Guard};
12
14
  use ipnetwork::IpNetwork;
13
15
  use magnus::{
14
- error::Error, prelude::*, scan_args::get_kwargs, scan_args::scan_args, typed_data::Obj,
15
- ExceptionClass, IntoValue, RArray, RClass, RModule, RString, Symbol, Value,
16
+ block::Proc,
17
+ error::{Error, ErrorType},
18
+ gc,
19
+ prelude::*,
20
+ rb_sys::{catch_unwind, protect, resume_error, AsRawValue, FromRawValue},
21
+ scan_args::get_kwargs,
22
+ scan_args::scan_args,
23
+ typed_data::Obj,
24
+ value::Opaque,
25
+ DataTypeFunctions, Exception, ExceptionClass, IntoValue, RArray, RClass, RHash, RModule,
26
+ RString, Symbol, TypedData, Value,
16
27
  };
17
28
  use maxminddb_crate::{MaxMindDbError, PathElement, Reader as MaxMindReader, Within};
18
29
  use memmap2::Mmap;
@@ -21,9 +32,13 @@ use std::{
21
32
  fs::File,
22
33
  io::Read as IoRead,
23
34
  net::{IpAddr, Ipv4Addr, Ipv6Addr},
24
- path::Path,
35
+ panic::AssertUnwindSafe,
36
+ path::{Path, PathBuf},
25
37
  str::FromStr,
26
- sync::{Arc, Mutex},
38
+ sync::{
39
+ atomic::{AtomicBool, AtomicU16, Ordering},
40
+ Arc, Mutex,
41
+ },
27
42
  };
28
43
 
29
44
  const ERR_CLOSED_DB: &str = "Attempt to read from a closed MaxMind DB.";
@@ -147,6 +162,92 @@ impl ReaderWithin<'_> {
147
162
  }
148
163
  }
149
164
 
165
+ self_cell::self_cell!(
166
+ /// A `ReaderWithin` together with the `ReaderSource` it borrows from.
167
+ struct OwnedWithin {
168
+ owner: Arc<ReaderSource>,
169
+
170
+ #[covariant]
171
+ dependent: ReaderWithin,
172
+ }
173
+ );
174
+
175
+ /// Iteration state for `Reader#each`, owned by a Ruby object.
176
+ ///
177
+ /// An external enumerator runs `each` in a Fiber. When the caller stops early,
178
+ /// Ruby frees the Fiber without unwinding its native stack, so anything Rust
179
+ /// owns on that stack is never dropped. Keeping the database handle and the
180
+ /// iterator in a Ruby object lets the garbage collector drop them instead.
181
+ /// When `each` returns normally, by `break` or by an exception, it releases
182
+ /// the state right away so `close` still frees the database at once.
183
+ #[magnus::wrap(class = "MaxMind::DB::Rust::ReaderNetworkIterator", free_immediately)]
184
+ struct NetworkIterator {
185
+ iter: Mutex<Option<OwnedWithin>>,
186
+ }
187
+
188
+ /// Releases a `NetworkIterator`'s state when `each` leaves its loop.
189
+ struct ReleaseOnExit<'a>(&'a NetworkIterator);
190
+
191
+ impl Drop for ReleaseOnExit<'_> {
192
+ fn drop(&mut self) {
193
+ self.0.release();
194
+ }
195
+ }
196
+
197
+ impl NetworkIterator {
198
+ fn new(source: Arc<ReaderSource>, network: IpNetwork) -> Result<Self, MaxMindDbError> {
199
+ let iter = OwnedWithin::try_new(source, |source| source.within(network))?;
200
+ Ok(Self {
201
+ iter: Mutex::new(Some(iter)),
202
+ })
203
+ }
204
+
205
+ /// Drops the iterator and its database handle.
206
+ fn release(&self) {
207
+ let iter = match self.iter.lock() {
208
+ Ok(mut iter) => iter.take(),
209
+ Err(poisoned) => poisoned.into_inner().take(),
210
+ };
211
+ drop(iter);
212
+ }
213
+
214
+ /// Advances one network. The lock is released before calling into Ruby.
215
+ fn next_entry(
216
+ &self,
217
+ ruby: &magnus::Ruby,
218
+ ipaddr_class: RClass,
219
+ ) -> Result<Option<(Value, Value)>, Error> {
220
+ let result = {
221
+ let mut iter = self.iter.lock().map_err(|_| {
222
+ Error::new(
223
+ ruby.exception_runtime_error(),
224
+ "Database iteration failed: iterator lock poisoned",
225
+ )
226
+ })?;
227
+ match iter.as_mut() {
228
+ Some(iter) => iter.with_dependent_mut(|_, iter| iter.next()),
229
+ None => None,
230
+ }
231
+ };
232
+
233
+ match result {
234
+ None => Ok(None),
235
+ Some(Ok((network, data))) => {
236
+ let ipaddr = ipaddr_class.funcall::<_, _, Value>("new", (network.to_string(),))?;
237
+ Ok(Some((ipaddr, data.into_value())))
238
+ }
239
+ Some(Err(MaxMindDbError::InvalidDatabase { .. }))
240
+ | Some(Err(MaxMindDbError::Decoding { .. }))
241
+ | Some(Err(MaxMindDbError::ResourceLimit { .. }))
242
+ | Some(Err(MaxMindDbError::Io(_))) => Err(invalid_database_exception(ERR_BAD_DATA)),
243
+ Some(Err(e)) => Err(Error::new(
244
+ ruby.exception_runtime_error(),
245
+ format!("Database iteration failed: {}", e),
246
+ )),
247
+ }
248
+ }
249
+ }
250
+
150
251
  #[inline]
151
252
  // prefix_len_for_ip_network uses 0 as a sentinel for ip.is_ipv4() && network.is_ipv6().
152
253
  // In this case, 0 is not a real prefix length; it signals an IPv4-in-IPv6 mapping path,
@@ -183,148 +284,235 @@ fn next_within_result<S: AsRef<[u8]>>(
183
284
  }
184
285
 
185
286
  /// A Ruby wrapper around the MaxMind DB reader
287
+ ///
288
+ /// The class has an allocator and an `initialize` method, like a Ruby class,
289
+ /// so `Reader.new` returns an instance of the receiver and subclasses can
290
+ /// override `initialize` and call `super`. An allocated reader that was never
291
+ /// initialized behaves like a closed reader.
186
292
  #[magnus::wrap(class = "MaxMind::DB::Rust::Reader")]
187
293
  struct Reader {
188
294
  reader: ArcSwapOption<ReaderSource>,
295
+ // Kept separately from `reader` so `metadata` still works after `close`,
296
+ // as it does in the official gem.
297
+ metadata: ArcSwapOption<Metadata>,
189
298
  path_cache: Mutex<VecDeque<CachedPath>>,
190
- ip_version: u16,
299
+ ip_version: AtomicU16,
300
+ // Set by the first `initialize` call before it runs any Ruby code, and
301
+ // cleared again if that call fails.
302
+ initialized: AtomicBool,
303
+ }
304
+
305
+ impl Default for Reader {
306
+ fn default() -> Self {
307
+ Reader {
308
+ reader: ArcSwapOption::empty(),
309
+ metadata: ArcSwapOption::empty(),
310
+ path_cache: Mutex::new(VecDeque::with_capacity(PATH_CACHE_MAX_ENTRIES)),
311
+ ip_version: AtomicU16::new(0),
312
+ initialized: AtomicBool::new(false),
313
+ }
314
+ }
191
315
  }
192
316
 
193
317
  impl Reader {
194
- fn new(args: &[Value]) -> Result<Self, Error> {
318
+ fn initialize(&self, args: &[Value]) -> Result<(), Error> {
195
319
  let ruby = magnus::Ruby::get().expect("Ruby VM should be available in Ruby method");
196
320
 
197
- let args = scan_args::<(Value,), (), (), (), _, ()>(args)?;
321
+ // The source, metadata and IP version are stored separately, so
322
+ // swapping them on a reader that is in use could let a lookup see a
323
+ // mix of two databases. Only allow initializing a fresh reader. The
324
+ // flag is claimed before any Ruby code runs (`dup`, `to_path`), so a
325
+ // reentrant or concurrent call is rejected too.
326
+ if self
327
+ .initialized
328
+ .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
329
+ .is_err()
330
+ {
331
+ return Err(Error::new(
332
+ ruby.exception_runtime_error(),
333
+ "MaxMind::DB::Rust::Reader is already initialized",
334
+ ));
335
+ }
336
+
337
+ let result = self.open(&ruby, args);
338
+ if result.is_err() {
339
+ self.initialized.store(false, Ordering::Release);
340
+ }
341
+ result.map_err(|err| err.into_error(&ruby))
342
+ }
343
+
344
+ fn open(&self, ruby: &magnus::Ruby, args: &[Value]) -> Result<(), OpenError> {
345
+ // Accept the options both as keywords and as a positional Hash, like
346
+ // the official gem's `initialize(database, options = {})`.
347
+ let args = scan_args::<(Value,), (Option<Value>,), (), (), RHash, ()>(args)?;
198
348
  let (database,) = args.required;
199
- let kw = get_kwargs::<_, (), (Option<Symbol>,), ()>(args.keywords, &[], &["mode"])?;
349
+ let (positional_options,) = args.optional;
350
+ let options = match positional_options {
351
+ Some(_) if !args.keywords.is_empty() => {
352
+ return Err(OpenError::Ruby(Error::new(
353
+ ruby.exception_arg_error(),
354
+ "wrong number of arguments (given 3, expected 1..2)",
355
+ )));
356
+ }
357
+ // `get_kwargs` removes the keys it reads, so work on a copy rather
358
+ // than emptying the caller's Hash.
359
+ Some(options) => {
360
+ let Some(options) = try_convert_hash(options, ruby)? else {
361
+ return Err(OpenError::Ruby(Error::new(
362
+ ruby.exception_type_error(),
363
+ "options must be a Hash",
364
+ )));
365
+ };
366
+ // Check the result without naming its class (see try_convert_hash).
367
+ let copy = options.funcall::<_, _, Value>("dup", ())?;
368
+ RHash::from_value(copy).ok_or_else(|| {
369
+ Error::new(ruby.exception_type_error(), "options.dup must be a Hash")
370
+ })?
371
+ }
372
+ None => args.keywords,
373
+ };
374
+ let kw = get_kwargs::<_, (), (Option<Symbol>,), ()>(options, &[], &["mode"])?;
200
375
  let (mode,) = kw.optional;
201
376
 
202
377
  // Parse mode from options hash
203
378
  let mode: Symbol = mode.unwrap_or_else(|| ruby.to_symbol("MODE_AUTO"));
204
379
 
205
- let open_mode = OpenMode::from_symbol(mode, &ruby)?;
380
+ let open_mode = OpenMode::from_symbol(mode, ruby)?;
206
381
 
207
382
  // Open database with appropriate mode
208
- match open_mode {
209
- OpenMode::Mmap => open_database_mmap(&database_path(database)?),
210
- OpenMode::Memory => open_database_memory(&database_path(database)?),
211
- OpenMode::Buffer => open_database_buffer(database_buffer(database)?),
212
- }
383
+ let source = match open_mode {
384
+ OpenMode::Mmap => open_database_mmap(&database_path(database, ruby)?)?,
385
+ OpenMode::Memory => open_database_memory(&database_path(database, ruby)?)?,
386
+ OpenMode::Buffer => open_database_buffer(database_buffer(database)?)?,
387
+ };
388
+
389
+ let meta = source.metadata();
390
+ self.ip_version.store(meta.ip_version, Ordering::Relaxed);
391
+ self.metadata
392
+ .store(Some(Arc::new(Metadata::from_maxmind(meta))));
393
+ self.reader.store(Some(Arc::new(source)));
394
+ Ok(())
395
+ }
396
+
397
+ fn initialize_copy(&self, _other: Value) -> Result<(), Error> {
398
+ let ruby = magnus::Ruby::get().expect("Ruby VM should be available in Ruby method");
399
+ Err(Error::new(
400
+ ruby.exception_type_error(),
401
+ "can't copy MaxMind::DB::Rust::Reader",
402
+ ))
213
403
  }
214
404
 
215
405
  #[inline]
216
406
  fn get(&self, ip_address: Value) -> Result<Value, Error> {
217
407
  let ruby = magnus::Ruby::get().expect("Ruby VM should be available in Ruby method");
218
408
 
219
- let guard = self.get_reader(&ruby)?;
220
- let reader_option = guard.as_ref();
221
- let reader = reader_option.as_ref().unwrap();
222
-
223
- let parsed_ip = self.parse_lookup_ip(ip_address, &ruby)?;
224
-
225
- lookup_result_to_value(&ruby, reader.lookup(parsed_ip), "Database lookup failed")
409
+ self.lookup_ip_value(&ruby, ip_address)
226
410
  }
227
411
 
228
412
  #[inline]
229
413
  fn get_path(&self, ip_address: Value, path: Value) -> Result<Value, Error> {
230
414
  let ruby = magnus::Ruby::get().expect("Ruby VM should be available in Ruby method");
231
415
 
232
- let guard = self.get_reader(&ruby)?;
233
- let reader_option = guard.as_ref();
234
- let reader = reader_option.as_ref().unwrap();
235
-
236
416
  let parsed_ip = self.parse_lookup_ip(ip_address, &ruby)?;
237
417
  let owned_path = self.parse_path(path, &ruby)?;
238
418
  let path_elements = path_elements_from_owned_path(owned_path.as_ref());
239
419
 
240
- lookup_result_to_value(
241
- &ruby,
242
- reader.lookup_path(parsed_ip, &path_elements),
243
- "Database lookup failed",
244
- )
420
+ self.lookup_path_value(&ruby, parsed_ip, &path_elements)
245
421
  }
246
422
 
247
423
  #[inline]
248
424
  fn get_with_prefix_length(&self, ip_address: Value) -> Result<RArray, Error> {
249
425
  let ruby = magnus::Ruby::get().expect("Ruby VM should be available in Ruby method");
250
426
 
251
- let guard = self.get_reader(&ruby)?;
252
- let reader_option = guard.as_ref();
253
- let reader = reader_option.as_ref().unwrap();
254
-
255
427
  let parsed_ip = self.parse_lookup_ip(ip_address, &ruby)?;
256
428
 
257
- // Perform lookup with prefix
258
- lookup_prefix_result_to_array(
259
- &ruby,
260
- reader.lookup_prefix(parsed_ip),
261
- "Database lookup failed",
262
- )
429
+ let result = {
430
+ let guard = self.get_reader(&ruby)?;
431
+ guard.as_ref().as_ref().unwrap().lookup_prefix(parsed_ip)
432
+ };
433
+ lookup_prefix_result_to_array(&ruby, result, "Database lookup failed")
263
434
  }
264
435
 
265
- fn get_many(&self, ips: Value) -> Result<RArray, Error> {
436
+ fn get_many(rb_self: Obj<Self>, ips: Value) -> Result<RArray, Error> {
266
437
  let ruby = magnus::Ruby::get().expect("Ruby VM should be available in Ruby method");
438
+ rb_self.get_reader(&ruby)?;
267
439
 
268
- let guard = self.get_reader(&ruby)?;
269
- let reader_option = guard.as_ref();
270
- let reader = reader_option.as_ref().unwrap();
271
-
272
- if let Ok(ip_array) = RArray::try_convert(ips) {
273
- return ruby.ary_try_from_iter((0..ip_array.len()).map(|index| {
274
- let ip = ip_array.entry::<Value>(index as isize)?;
275
- self.lookup_ip_value(&ruby, reader, ip)
276
- }));
440
+ if let Some(ip_array) = try_convert_array(ips, &ruby)? {
441
+ let results = lookup_array(&ruby, ip_array, |ip| rb_self.lookup_ip_value(&ruby, ip));
442
+ gc_guard(&rb_self);
443
+ return results;
277
444
  }
278
445
 
279
- ensure_enumerable(ips, &ruby, "ips must be an Array or Enumerable")?;
280
- ruby.ary_try_from_iter(
281
- ips.enumeratorize("each", ())
282
- .map(|ip| self.lookup_ip_value(&ruby, reader, ip?)),
283
- )
446
+ collect_each(&ruby, rb_self, ips, None)
284
447
  }
285
448
 
286
- fn get_many_path(&self, ips: Value, path: Value) -> Result<RArray, Error> {
449
+ fn get_many_path(rb_self: Obj<Self>, ips: Value, path: Value) -> Result<RArray, Error> {
287
450
  let ruby = magnus::Ruby::get().expect("Ruby VM should be available in Ruby method");
451
+ rb_self.get_reader(&ruby)?;
452
+
453
+ let owned_path = rb_self.parse_path(path, &ruby)?;
454
+ let path = PathWithElements::new(owned_path, |path| path_elements_from_owned_path(path));
455
+
456
+ if let Some(ip_array) = RArray::from_value(ips) {
457
+ // A plain String lookup can't abandon this stack, so the path stays on
458
+ // it until another kind of address needs Ruby code.
459
+ let mut stack_path = Some(path);
460
+ let mut batch_path = None;
461
+ let results = lookup_array(&ruby, ip_array, |ip| {
462
+ if let Some(path) = &stack_path {
463
+ if let Some(parsed_ip) = rb_self.parse_plain_lookup_ip(ip) {
464
+ return rb_self.lookup_path_value(
465
+ &ruby,
466
+ parsed_ip,
467
+ path.borrow_dependent(),
468
+ );
469
+ }
470
+ }
471
+ if let Some(path) = stack_path.take() {
472
+ batch_path = Some(ruby.obj_wrap(BatchPath(path)));
473
+ }
474
+ let path: &Obj<BatchPath> = batch_path.as_ref().expect("the path was moved above");
475
+ rb_self.lookup_ip_path_value(&ruby, ip, path.0.borrow_dependent())
476
+ });
477
+ gc_guard(&batch_path);
478
+ gc_guard(&rb_self);
479
+ return results;
480
+ }
288
481
 
289
- let guard = self.get_reader(&ruby)?;
290
- let reader_option = guard.as_ref();
291
- let reader = reader_option.as_ref().unwrap();
292
-
293
- let owned_path = self.parse_path(path, &ruby)?;
294
- let path_elements = path_elements_from_owned_path(owned_path.as_ref());
295
-
296
- if let Ok(ip_array) = RArray::try_convert(ips) {
297
- return ruby.ary_try_from_iter((0..ip_array.len()).map(|index| {
298
- let ip = ip_array.entry::<Value>(index as isize)?;
299
- self.lookup_ip_path_value(&ruby, reader, ip, &path_elements)
300
- }));
482
+ // Otherwise the garbage collector owns the path (see NetworkIterator).
483
+ let path = ruby.obj_wrap(BatchPath(path));
484
+ if let Some(ip_array) = try_convert_array(ips, &ruby)? {
485
+ let results = lookup_array(&ruby, ip_array, |ip| {
486
+ rb_self.lookup_ip_path_value(&ruby, ip, path.0.borrow_dependent())
487
+ });
488
+ gc_guard(&path);
489
+ gc_guard(&rb_self);
490
+ return results;
301
491
  }
302
492
 
303
- ensure_enumerable(ips, &ruby, "ips must be an Array or Enumerable")?;
304
- ruby.ary_try_from_iter(
305
- ips.enumeratorize("each", ())
306
- .map(|ip| self.lookup_ip_path_value(&ruby, reader, ip?, &path_elements)),
307
- )
493
+ collect_each(&ruby, rb_self, ips, Some(path))
308
494
  }
309
495
 
310
496
  fn metadata(&self) -> Result<Metadata, Error> {
311
497
  let ruby = magnus::Ruby::get().expect("Ruby VM should be available in Ruby method");
312
498
 
313
- let guard = self.get_reader(&ruby)?;
314
- let reader_option = guard.as_ref();
315
- let reader = reader_option.as_ref().unwrap();
316
- let meta = reader.metadata();
317
-
318
- Ok(Metadata::from_maxmind(meta))
499
+ match self.metadata.load().as_ref() {
500
+ Some(meta) => Ok(Metadata::clone(meta)),
501
+ None => Err(Error::new(ruby.exception_runtime_error(), ERR_CLOSED_DB)),
502
+ }
319
503
  }
320
504
 
321
505
  fn verify(&self) -> Result<bool, Error> {
322
506
  let ruby = magnus::Ruby::get().expect("Ruby VM should be available in Ruby method");
323
- let guard = self.get_reader(&ruby)?;
324
- let reader_option = guard.as_ref();
325
- let reader = reader_option.as_ref().unwrap();
326
-
327
- reader.verify().map_err(|err| {
507
+ // Own a reference to the reader so a concurrent `close` cannot free it
508
+ // while verification runs without the GVL.
509
+ let reader = self
510
+ .reader
511
+ .load_full()
512
+ .ok_or_else(|| Error::new(ruby.exception_runtime_error(), ERR_CLOSED_DB))?;
513
+
514
+ // Verification only decodes in Rust, so other Ruby threads can run.
515
+ without_gvl(|| reader.verify())?.map_err(|err| {
328
516
  invalid_database_exception(&format!("Database verification failed: {err}"))
329
517
  })?;
330
518
  Ok(true)
@@ -338,182 +526,111 @@ impl Reader {
338
526
  self.reader.load().is_none()
339
527
  }
340
528
 
341
- fn inspect(&self) -> String {
529
+ fn inspect(rb_self: Obj<Self>) -> String {
530
+ let reader_self = &*rb_self;
342
531
  format!(
343
- "#<MaxMind::DB::Rust::Reader:0x{:x} @closed={} @ip_version={}>",
344
- self as *const Self as usize,
345
- self.closed(),
346
- self.ip_version,
532
+ "#<{}:0x{:x} @closed={} @ip_version={}>",
533
+ // SAFETY: the name is copied before Ruby code can run.
534
+ unsafe { rb_self.classname() },
535
+ reader_self as *const Self as usize,
536
+ reader_self.closed(),
537
+ reader_self.ip_version.load(Ordering::Relaxed),
347
538
  )
348
539
  }
349
540
 
350
541
  fn each(ruby: &magnus::Ruby, rb_self: Obj<Self>, args: &[Value]) -> Result<Value, Error> {
351
542
  let reader_self = &*rb_self;
352
543
 
353
- let guard = reader_self.get_reader(ruby)?;
354
- let reader_option = guard.as_ref();
355
- let reader = reader_option.as_ref().unwrap();
544
+ // Check for a closed reader now, but don't hold it while the network
545
+ // argument below calls into Ruby.
546
+ reader_self.get_reader(ruby)?;
356
547
 
357
- // If no block given, return enumerator
548
+ // Check the arguments before returning an enumerator, so a bad network
549
+ // fails here and not when iteration starts.
550
+ let network = reader_self.parse_each_network(ruby, args)?;
551
+
552
+ // If no block given, return enumerator. It gets the parsed network, not
553
+ // the original argument, so iterating does not convert it again.
358
554
  if !ruby.block_given() {
359
- return Ok(rb_self.enumeratorize("each", args).as_value());
555
+ let enumerator = match network {
556
+ Some(network) => rb_self.enumeratorize("each", (network.to_string(),)),
557
+ None => rb_self.enumeratorize("each", ()),
558
+ };
559
+ return Ok(enumerator.as_value());
360
560
  }
361
561
 
362
- let ip_version = reader.metadata().ip_version;
363
-
364
- // Determine the network to iterate over
365
- let network_str = if args.is_empty() {
366
- // No argument: use default (full database)
367
- if ip_version == 4 {
368
- "0.0.0.0/0".to_string()
562
+ let network = network.unwrap_or_else(|| {
563
+ if reader_self.ip_version.load(Ordering::Relaxed) == 4 {
564
+ IpNetwork::V4(ipnetwork::Ipv4Network::new(Ipv4Addr::UNSPECIFIED, 0).unwrap())
369
565
  } else {
370
- "::/0".to_string()
566
+ IpNetwork::V6(ipnetwork::Ipv6Network::new(Ipv6Addr::UNSPECIFIED, 0).unwrap())
371
567
  }
372
- } else {
373
- // Argument provided: extract network CIDR string
374
- let network_arg = args[0];
375
-
376
- // Try to get string representation
377
- // Accept both String and IPAddr objects
378
- let network_str_val = if let Ok(s) = RString::try_convert(network_arg) {
379
- // It's already a string
380
- s.to_string()?
381
- } else {
382
- // Check if it's an IPAddr object
383
- let ipaddr_class = ruby.class_object().const_get::<_, RClass>("IPAddr")?;
384
- if network_arg.is_kind_of(ipaddr_class) {
385
- // It's an IPAddr - need to get both address and prefix
386
- let ip_str: String = network_arg.funcall("to_s", ())?;
387
-
388
- // Get the prefix length from IPAddr
389
- // IPAddr stores prefix as a netmask, need to convert
390
- let prefix_len: u8 = network_arg.funcall("prefix", ())?;
391
-
392
- // Construct CIDR notation
393
- format!("{}/{}", ip_str, prefix_len)
394
- } else {
395
- // Try to call to_s on it (works for other objects)
396
- let to_s_result: Value = network_arg.funcall("to_s", ())?;
397
- RString::try_convert(to_s_result)
398
- .map_err(|_| {
399
- Error::new(
400
- ruby.exception_arg_error(),
401
- "Network parameter must be a String or IPAddr",
402
- )
403
- })?
404
- .to_string()?
405
- }
406
- };
568
+ });
407
569
 
408
- network_str_val
570
+ let iter = {
571
+ let guard = reader_self.get_reader(ruby)?;
572
+ NetworkIterator::new(Arc::clone(guard.as_ref().as_ref().unwrap()), network)
573
+ .map_err(|e| invalid_database_exception(&format!("Failed to iterate: {}", e)))?
409
574
  };
575
+ let iter = ruby.obj_wrap(iter);
576
+ // Nothing Rust owns may stay on this stack while yielding (see
577
+ // NetworkIterator). The Ruby object above owns the iteration state.
578
+ let _release = ReleaseOnExit(&iter);
410
579
 
411
- let network = IpNetwork::from_str(&network_str).map_err(|e| {
412
- Error::new(
413
- ruby.exception_arg_error(),
414
- format!("Invalid network CIDR '{}': {}", network_str, e),
415
- )
416
- })?;
417
-
418
- // Validate network matches database IP version
419
- // IPv4 in IPv6 DB is OK (IPv4-mapped), IPv6 in IPv6 DB is OK
420
- if let (4, IpNetwork::V6(_)) = (ip_version, network) {
421
- return Err(Error::new(
422
- ruby.exception_arg_error(),
423
- format!(
424
- "Cannot search for IPv6 network '{}' in an IPv4-only database",
425
- network_str
426
- ),
427
- ));
428
- }
429
-
430
- let mut iter = reader
431
- .within(network)
432
- .map_err(|e| invalid_database_exception(&format!("Failed to iterate: {}", e)))?;
433
580
  // Get IPAddr class
434
581
  let ipaddr_class = ruby.class_object().const_get::<_, RClass>("IPAddr")?;
435
582
 
436
- // Iterate over all networks
437
- while let Some(result) = iter.next() {
438
- match result {
439
- Ok((network, data)) => {
440
- // Convert IpNetwork to IPAddr
441
- let ip_str = network.to_string();
442
- let ipaddr = ipaddr_class.funcall::<_, _, Value>("new", (ip_str,))?;
443
-
444
- // Yield [network, data] to block
445
- let values = (ipaddr, data.into_value());
446
- ruby.yield_values::<(Value, Value), Value>(values)?;
447
- }
448
- Err(MaxMindDbError::InvalidDatabase { .. })
449
- | Err(MaxMindDbError::Decoding { .. })
450
- | Err(MaxMindDbError::Io(_)) => {
451
- return Err(invalid_database_exception(ERR_BAD_DATA));
452
- }
453
- Err(e) => {
454
- return Err(Error::new(
455
- ruby.exception_runtime_error(),
456
- format!("Database iteration failed: {}", e),
457
- ));
458
- }
459
- }
583
+ // Iterate over all networks, yielding [network, data] to the block
584
+ while let Some(values) = iter.next_entry(ruby, ipaddr_class)? {
585
+ ruby.yield_values::<(Value, Value), Value>(values)?;
460
586
  }
461
587
 
462
588
  Ok(ruby.qnil().as_value())
463
589
  }
464
590
 
465
- /// Helper method to get the reader from the ArcSwapOption
466
- fn get_reader(&self, ruby: &magnus::Ruby) -> Result<Guard<Option<Arc<ReaderSource>>>, Error> {
467
- let guard = self.reader.load();
468
- if guard.is_none() {
469
- return Err(Error::new(ruby.exception_runtime_error(), ERR_CLOSED_DB));
470
- }
471
- Ok(guard)
591
+ #[inline]
592
+ fn lookup_ip_value(&self, ruby: &magnus::Ruby, ip: Value) -> Result<Value, Error> {
593
+ let parsed_ip = self.parse_lookup_ip(ip, ruby)?;
594
+ let result = {
595
+ let guard = self.get_reader(ruby)?;
596
+ guard.as_ref().as_ref().unwrap().lookup(parsed_ip)
597
+ };
598
+ lookup_result_to_value(ruby, result, "Database lookup failed")
472
599
  }
473
600
 
474
601
  #[inline]
475
602
  fn parse_lookup_ip(&self, ip_address: Value, ruby: &magnus::Ruby) -> Result<IpAddr, Error> {
476
- let parsed_ip = parse_ip_address_fast(ip_address, ruby)?;
477
- self.validate_lookup_ip(parsed_ip, ruby)
478
- }
603
+ // A plain String is parsed without calling Ruby. Everything else can
604
+ // call Ruby, so check for a closed reader first (see get_reader).
605
+ let parsed_ip = match parse_plain_ip(ip_address) {
606
+ Some(parsed_ip) => parsed_ip,
607
+ None => {
608
+ self.get_reader(ruby)?;
609
+ parse_ip_with_ipaddr(ip_address, ruby)?
610
+ }
611
+ };
479
612
 
480
- #[inline]
481
- fn validate_lookup_ip(&self, parsed_ip: IpAddr, ruby: &magnus::Ruby) -> Result<IpAddr, Error> {
482
- if self.ip_version == 4 && matches!(parsed_ip, IpAddr::V6(_)) {
483
- Err(Error::new(
484
- ruby.exception_arg_error(),
485
- ipv6_in_ipv4_error(&parsed_ip),
486
- ))
487
- } else {
488
- Ok(parsed_ip)
613
+ if self.ip_version.load(Ordering::Relaxed) == 4 && parsed_ip.is_ipv6() {
614
+ self.get_reader(ruby)?;
615
+ // Echo the argument as given, like the official gem, rather than
616
+ // the parsed address, which drops an IPv6 zone and normalizes.
617
+ return Err(ipv6_in_ipv4_error(ruby, ip_address));
489
618
  }
619
+ Ok(parsed_ip)
490
620
  }
491
621
 
492
- #[inline]
493
- fn lookup_ip_value(
494
- &self,
495
- ruby: &magnus::Ruby,
496
- reader: &ReaderSource,
497
- ip: Value,
498
- ) -> Result<Value, Error> {
499
- let parsed_ip = self.parse_lookup_ip(ip, ruby)?;
500
- lookup_result_to_value(ruby, reader.lookup(parsed_ip), "Database lookup failed")
501
- }
502
-
503
- #[inline]
504
- fn lookup_ip_path_value(
505
- &self,
506
- ruby: &magnus::Ruby,
507
- reader: &ReaderSource,
508
- ip: Value,
509
- path_elements: &[PathElement<'_>],
510
- ) -> Result<Value, Error> {
511
- let parsed_ip = self.parse_lookup_ip(ip, ruby)?;
512
- lookup_result_to_value(
513
- ruby,
514
- reader.lookup_path(parsed_ip, path_elements),
515
- "Database lookup failed",
516
- )
622
+ /// Helper method to get the reader from the ArcSwapOption
623
+ ///
624
+ /// Parsing arguments can call into Ruby, and no guard may be on the stack
625
+ /// then (see NetworkIterator). So before such a call, methods call this and
626
+ /// drop the guard, which reports a closed reader ahead of a bad argument.
627
+ /// After parsing they call this again for the lookup.
628
+ fn get_reader(&self, ruby: &magnus::Ruby) -> Result<Guard<Option<Arc<ReaderSource>>>, Error> {
629
+ let guard = self.reader.load();
630
+ if guard.is_none() {
631
+ return Err(Error::new(ruby.exception_runtime_error(), ERR_CLOSED_DB));
632
+ }
633
+ Ok(guard)
517
634
  }
518
635
 
519
636
  fn parse_path(
@@ -521,10 +638,18 @@ impl Reader {
521
638
  path: Value,
522
639
  ruby: &magnus::Ruby,
523
640
  ) -> Result<Arc<[OwnedPathElement]>, Error> {
524
- let path = path_array(path, ruby)?;
525
- let hash = path_cache_hash(path, ruby)?;
641
+ // A plain path is hashed without calling Ruby. Anything else can call
642
+ // Ruby or fail, so check for a closed reader first (see get_reader).
643
+ let path = match RArray::from_value(path) {
644
+ Some(path) => path,
645
+ None => {
646
+ self.get_reader(ruby)?;
647
+ path_array(path, ruby)?
648
+ }
649
+ };
650
+ let hash = path_cache_hash(path, ruby, || self.get_reader(ruby).map(drop))?;
526
651
 
527
- if let Some(cached) = self.cached_path(path, hash)? {
652
+ if let Some(cached) = self.cached_path(path, hash, ruby)? {
528
653
  return Ok(cached);
529
654
  }
530
655
 
@@ -537,18 +662,37 @@ impl Reader {
537
662
  &self,
538
663
  path: RArray,
539
664
  hash: u64,
665
+ ruby: &magnus::Ruby,
540
666
  ) -> Result<Option<Arc<[OwnedPathElement]>>, Error> {
541
- let cache = match self.path_cache.lock() {
542
- Ok(cache) => cache,
543
- Err(_) => return Ok(None),
667
+ // Comparing a candidate can call Ruby `to_str` or `to_int` methods,
668
+ // which may reenter this reader or release the GVL. Collect the
669
+ // candidates and release the lock before comparing them so that no
670
+ // Ruby code runs while the mutex is held. The first candidate is kept
671
+ // separately so the usual case does not allocate.
672
+ let (first, rest) = {
673
+ let cache = match self.path_cache.lock() {
674
+ Ok(cache) => cache,
675
+ Err(_) => return Ok(None),
676
+ };
677
+
678
+ let mut first = None;
679
+ let mut rest = Vec::new();
680
+ for entry in cache
681
+ .iter()
682
+ .filter(|entry| entry.hash == hash && entry.elements.len() == path.len())
683
+ {
684
+ if first.is_none() {
685
+ first = Some(entry.elements.clone());
686
+ } else {
687
+ rest.push(entry.elements.clone());
688
+ }
689
+ }
690
+ (first, rest)
544
691
  };
545
692
 
546
- for entry in cache
547
- .iter()
548
- .filter(|entry| entry.hash == hash && entry.elements.len() == path.len())
549
- {
550
- if path_matches_cached(path, entry.elements.as_ref())? {
551
- return Ok(Some(entry.elements.clone()));
693
+ for candidate in first.into_iter().chain(rest) {
694
+ if path_matches_cached(path, candidate.as_ref(), ruby)? {
695
+ return Ok(Some(candidate));
552
696
  }
553
697
  }
554
698
 
@@ -570,6 +714,101 @@ impl Reader {
570
714
  }
571
715
  }
572
716
  }
717
+
718
+ #[inline]
719
+ fn lookup_path_value(
720
+ &self,
721
+ ruby: &magnus::Ruby,
722
+ parsed_ip: IpAddr,
723
+ path_elements: &[PathElement<'_>],
724
+ ) -> Result<Value, Error> {
725
+ let result = {
726
+ let guard = self.get_reader(ruby)?;
727
+ guard
728
+ .as_ref()
729
+ .as_ref()
730
+ .unwrap()
731
+ .lookup_path(parsed_ip, path_elements)
732
+ };
733
+ lookup_result_to_value(ruby, result, "Database lookup failed")
734
+ }
735
+
736
+ /// Parses a plain IP address String that this database can look up. Returns
737
+ /// `None` for anything else. This never calls Ruby.
738
+ #[inline]
739
+ fn parse_plain_lookup_ip(&self, ip: Value) -> Option<IpAddr> {
740
+ parse_plain_ip(ip).filter(|ip| ip.is_ipv4() || self.ip_version.load(Ordering::Relaxed) != 4)
741
+ }
742
+
743
+ #[inline]
744
+ fn lookup_ip_path_value(
745
+ &self,
746
+ ruby: &magnus::Ruby,
747
+ ip: Value,
748
+ path_elements: &[PathElement<'_>],
749
+ ) -> Result<Value, Error> {
750
+ let parsed_ip = self.parse_lookup_ip(ip, ruby)?;
751
+ self.lookup_path_value(ruby, parsed_ip, path_elements)
752
+ }
753
+
754
+ /// Parses the optional network argument to `each`. Returns `None` when the
755
+ /// network is missing or nil, which means the whole database.
756
+ fn parse_each_network(
757
+ &self,
758
+ ruby: &magnus::Ruby,
759
+ args: &[Value],
760
+ ) -> Result<Option<IpNetwork>, Error> {
761
+ let args = scan_args::<(), (Option<Value>,), (), (), (), ()>(args)?;
762
+ let network_arg = match args.optional.0 {
763
+ Some(value) if !value.is_nil() => value,
764
+ _ => return Ok(None),
765
+ };
766
+
767
+ // Accept both String and IPAddr objects
768
+ let network_str = if let Some(s) = try_convert_optional::<RString>(network_arg, ruby)? {
769
+ s.to_string()?
770
+ } else {
771
+ let ipaddr_class = ruby.class_object().const_get::<_, RClass>("IPAddr")?;
772
+ if network_arg.is_kind_of(ipaddr_class) {
773
+ // IPAddr#to_s drops the prefix, so add it back as CIDR notation
774
+ let ip_str: String = network_arg.funcall("to_s", ())?;
775
+ let prefix_len: u8 = network_arg.funcall("prefix", ())?;
776
+ format!("{}/{}", ip_str, prefix_len)
777
+ } else {
778
+ // Try to call to_s on it (works for other objects)
779
+ let to_s_result: Value = network_arg.funcall("to_s", ())?;
780
+ try_convert_optional::<RString>(to_s_result, ruby)?
781
+ .ok_or_else(|| {
782
+ Error::new(
783
+ ruby.exception_arg_error(),
784
+ "Network parameter must be a String or IPAddr",
785
+ )
786
+ })?
787
+ .to_string()?
788
+ }
789
+ };
790
+
791
+ let network = IpNetwork::from_str(&network_str).map_err(|e| {
792
+ Error::new(
793
+ ruby.exception_arg_error(),
794
+ format!("Invalid network CIDR '{}': {}", network_str, e),
795
+ )
796
+ })?;
797
+
798
+ // Validate network matches database IP version
799
+ // IPv4 in IPv6 DB is OK (IPv4-mapped), IPv6 in IPv6 DB is OK
800
+ if let (4, IpNetwork::V6(_)) = (self.ip_version.load(Ordering::Relaxed), network) {
801
+ return Err(Error::new(
802
+ ruby.exception_arg_error(),
803
+ format!(
804
+ "Cannot search for IPv6 network '{}' in an IPv4-only database",
805
+ network_str
806
+ ),
807
+ ));
808
+ }
809
+
810
+ Ok(Some(network))
811
+ }
573
812
  }
574
813
 
575
814
  // SAFETY: Reader does not store Ruby VALUE handles. The database source is
@@ -579,14 +818,180 @@ impl Reader {
579
818
  // while the Ruby VM is active.
580
819
  unsafe impl Send for Reader {}
581
820
 
582
- /// Helper function to create a Reader from a ReaderSource
583
- fn create_reader(source: ReaderSource) -> Reader {
584
- let ip_version = source.metadata().ip_version;
585
- let source = Arc::new(source);
586
- Reader {
587
- reader: ArcSwapOption::from(Some(source)),
588
- path_cache: Mutex::new(VecDeque::with_capacity(PATH_CACHE_MAX_ENTRIES)),
589
- ip_version,
821
+ fn lookup_array(
822
+ ruby: &magnus::Ruby,
823
+ ips: RArray,
824
+ mut lookup: impl FnMut(Value) -> Result<Value, Error>,
825
+ ) -> Result<RArray, Error> {
826
+ ruby.ary_try_from_iter((0..ips.len()).map(|index| lookup(ips.entry(index as isize)?)))
827
+ }
828
+
829
+ type PathElements<'path> = Vec<PathElement<'path>>;
830
+
831
+ self_cell::self_cell!(
832
+ /// A parsed path together with the lookup elements that borrow from it.
833
+ struct PathWithElements {
834
+ owner: Arc<[OwnedPathElement]>,
835
+
836
+ #[covariant]
837
+ dependent: PathElements,
838
+ }
839
+ );
840
+
841
+ /// The path of a `get_many_path` call, owned by a Ruby object so that the
842
+ /// garbage collector frees it if Ruby abandons the call's stack (see
843
+ /// NetworkIterator).
844
+ #[magnus::wrap(class = "MaxMind::DB::Rust::ReaderBatchPath", free_immediately)]
845
+ struct BatchPath(PathWithElements);
846
+
847
+ /// State of a `get_many` or `get_many_path` call whose input is not an Array.
848
+ ///
849
+ /// This is the data of the block that `each` gets. Ruby marks a block's data for
850
+ /// as long as the block can be called. That can be after the call returned, and
851
+ /// also after Ruby abandoned the call's stack.
852
+ #[derive(TypedData)]
853
+ #[magnus(class = "MaxMind::DB::Rust::ReaderBatch", free_immediately, mark)]
854
+ struct Batch {
855
+ /// Not valid when `running` is false. Use `payload` to get it.
856
+ payload: Payload,
857
+ /// Cleared when the call returns.
858
+ running: AtomicBool,
859
+ /// Set when a lookup or a reentry failed, before any Ruby code can run.
860
+ failed: AtomicBool,
861
+ /// Set while the block runs a lookup, and left set if the lookup never
862
+ /// finishes, such as because of a `throw` or a thread kill.
863
+ looking_up: AtomicBool,
864
+ }
865
+
866
+ #[derive(Clone, Copy)]
867
+ struct Payload {
868
+ reader: Opaque<Obj<Reader>>,
869
+ path: Option<Opaque<Obj<BatchPath>>>,
870
+ results: Opaque<RArray>,
871
+ /// Holds the lookup or reentry exception to raise once `each` has unwound.
872
+ error_slot: Opaque<RArray>,
873
+ /// Stops `each` when thrown.
874
+ tag: Opaque<Value>,
875
+ }
876
+
877
+ impl Batch {
878
+ /// Creates the block. This is a Ruby method because a block keeps the receiver
879
+ /// of the method that created it alive, which must not be the Reader.
880
+ fn to_proc(rb_self: Obj<Self>) -> Result<Proc, Error> {
881
+ // SAFETY: `batch_block` has the signature of a block function, and
882
+ // `rb_self` is a live object. Ruby marks it for as long as the block, or a
883
+ // method that was defined from the block, exists.
884
+ let block =
885
+ protect(|| unsafe { rb_sys::rb_proc_new(Some(batch_block), rb_self.as_raw()) })?;
886
+ // SAFETY: `rb_proc_new` returns a live Proc.
887
+ Proc::try_convert(unsafe { Value::from_raw(block) })
888
+ }
889
+
890
+ /// The objects that the block uses, or `None` if the call has returned. The
891
+ /// caller must keep them on its stack, because the call can return later.
892
+ fn payload(&self) -> Option<Payload> {
893
+ self.running.load(Ordering::Acquire).then_some(self.payload)
894
+ }
895
+ }
896
+
897
+ impl DataTypeFunctions for Batch {
898
+ /// Marks, and pins, the payload only while the call runs, so that a block that
899
+ /// `each` kept doesn't keep the reader and the results alive.
900
+ fn mark(&self, marker: &gc::Marker) {
901
+ if let Some(payload) = self.payload() {
902
+ marker.mark(payload.reader);
903
+ if let Some(path) = payload.path {
904
+ marker.mark(path);
905
+ }
906
+ marker.mark(payload.results);
907
+ marker.mark(payload.error_slot);
908
+ marker.mark(payload.tag);
909
+ }
910
+ }
911
+ }
912
+
913
+ const ERR_BATCH_FINISHED: &str =
914
+ "the block that get_many or get_many_path passed to each was called after it returned";
915
+ const ERR_BATCH_REENTERED: &str =
916
+ "the block that get_many or get_many_path passed to each was called before an earlier lookup \
917
+ finished";
918
+ const ERR_BATCH_UNFINISHED: &str =
919
+ "each returned to get_many or get_many_path before a lookup finished";
920
+
921
+ /// Calls `ips.each` with a native block and collects the lookup of each yielded
922
+ /// value.
923
+ ///
924
+ /// Iterating with a block, rather than an external enumerator, lets any
925
+ /// exception from `each`, including `StopIteration`, reach the caller instead
926
+ /// of looking like the end of the input.
927
+ ///
928
+ /// A lookup error stops the iteration with `throw`, which `each` can't rescue,
929
+ /// and is raised after `each` unwinds. A lookup that never finished is an error
930
+ /// too. So the result can't silently come back short.
931
+ fn collect_each(
932
+ ruby: &magnus::Ruby,
933
+ reader: Obj<Reader>,
934
+ ips: Value,
935
+ path: Option<Obj<BatchPath>>,
936
+ ) -> Result<RArray, Error> {
937
+ ensure_enumerable(ips, ruby, "ips must be an Array or Enumerable")?;
938
+
939
+ let results = ruby.ary_new();
940
+ let error_slot = ruby.ary_new();
941
+ let tag: Value = ruby.class_object().new_instance(())?;
942
+ let payload = Payload {
943
+ reader: reader.into(),
944
+ path: path.map(Opaque::from),
945
+ results: results.into(),
946
+ error_slot: error_slot.into(),
947
+ tag: tag.into(),
948
+ };
949
+ let batch = ruby.obj_wrap(Batch {
950
+ payload,
951
+ running: AtomicBool::new(true),
952
+ failed: AtomicBool::new(false),
953
+ looking_up: AtomicBool::new(false),
954
+ });
955
+ // Allocating the Batch can run the garbage collector before the Batch marks
956
+ // the payload.
957
+ gc_guard(&payload);
958
+
959
+ let block: Proc = batch.funcall("to_proc", ())?;
960
+
961
+ // This does not use `proc_from_fn`, because magnus 0.9 frees a closure's data
962
+ // type before Ruby is done with it.
963
+ let each_args = ruby.ary_new_from_values(&[ips, block.as_value()]);
964
+ // SAFETY: `call_each` has the signature of a block function, and all values
965
+ // are live.
966
+ let outcome = protect(|| unsafe {
967
+ rb_sys::rb_catch_obj(tag.as_raw(), Some(call_each), each_args.as_raw())
968
+ });
969
+ gc_guard(&each_args);
970
+
971
+ batch.running.store(false, Ordering::Release);
972
+ match outcome {
973
+ // A jump such as `break` or `throw` from the input still wins. So does
974
+ // an exception such as Interrupt, SystemExit or Timeout's, because the
975
+ // caller may rescue the lookup error and keep running.
976
+ Err(err) if !err.is_kind_of(ruby.exception_standard_error()) => Err(err),
977
+ // The lookup error wins over a StandardError that `each` raised after
978
+ // it, such as from an `ensure`. An asynchronous StandardError, as from
979
+ // `Timeout.timeout(1, MyError)`, looks the same as one from an
980
+ // `ensure`, so it loses too.
981
+ outcome => match error_slot.entry::<Option<Exception>>(0)? {
982
+ Some(exception) => Err(exception.into()),
983
+ None => {
984
+ outcome?;
985
+ if batch.looking_up.load(Ordering::Acquire) || batch.failed.load(Ordering::Acquire)
986
+ {
987
+ return Err(Error::new(
988
+ ruby.exception_runtime_error(),
989
+ ERR_BATCH_UNFINISHED,
990
+ ));
991
+ }
992
+ Ok(results)
993
+ }
994
+ },
590
995
  }
591
996
  }
592
997
 
@@ -601,63 +1006,242 @@ fn ensure_enumerable(value: Value, ruby: &magnus::Ruby, error_message: &str) ->
601
1006
  }
602
1007
  }
603
1008
 
604
- /// Parse IP address from Ruby value (String or IPAddr) - optimized version
605
- #[inline(always)]
606
- fn parse_ip_address_fast(value: Value, ruby: &magnus::Ruby) -> Result<IpAddr, Error> {
607
- // Fast path: Try as RString first (most common case) - zero-copy
608
- if let Some(rstring) = RString::from_value(value) {
609
- // SAFETY: as_str() returns a &str that's valid as long as the Ruby string isn't modified
610
- // We use it immediately for parsing, so this is safe
611
- let ip_str = unsafe { rstring.as_str() }.map_err(|e| {
612
- Error::new(
613
- ruby.exception_arg_error(),
614
- format!("Invalid UTF-8 in IP address string: {}", e),
615
- )
616
- })?;
1009
+ /// The body of the `catch` in `collect_each`. `each_args` is an Array of the
1010
+ /// input and the block.
1011
+ unsafe extern "C" fn call_each(
1012
+ _tag: rb_sys::VALUE,
1013
+ each_args: rb_sys::VALUE,
1014
+ _argc: std::ffi::c_int,
1015
+ _argv: *const rb_sys::VALUE,
1016
+ _block: rb_sys::VALUE,
1017
+ ) -> rb_sys::VALUE {
1018
+ let result = catch_unwind(AssertUnwindSafe(|| -> Result<Value, Error> {
1019
+ // SAFETY: `collect_each` keeps the Array alive.
1020
+ let each_args = RArray::try_convert(unsafe { Value::from_raw(each_args) })?;
1021
+ let ips = each_args.entry::<Value>(0)?;
1022
+ let block = each_args.entry::<Proc>(1)?;
1023
+ ips.funcall_with_block::<_, _, Value>("each", (), block)
1024
+ }));
1025
+ match result.and_then(|result| result) {
1026
+ Ok(value) => value.as_raw(),
1027
+ // SAFETY: nothing on this stack needs to be dropped.
1028
+ Err(err) => unsafe { resume_error(err) },
1029
+ }
1030
+ }
1031
+
1032
+ /// The block that `collect_each` passes to `each`. `batch` is a `Batch`.
1033
+ unsafe extern "C" fn batch_block(
1034
+ _yielded: rb_sys::VALUE,
1035
+ batch: rb_sys::VALUE,
1036
+ argc: std::ffi::c_int,
1037
+ argv: *const rb_sys::VALUE,
1038
+ _block: rb_sys::VALUE,
1039
+ ) -> rb_sys::VALUE {
1040
+ let result = catch_unwind(AssertUnwindSafe(|| -> Result<Value, Error> {
1041
+ // SAFETY: Ruby calls blocks with the GVL held, and passes `argc` live
1042
+ // values and the data that the block was created with.
1043
+ let (ruby, batch) = unsafe { (magnus::Ruby::get_unchecked(), Value::from_raw(batch)) };
1044
+ // Match Enumerator#next: no values yield nil, several yield an Array.
1045
+ let ip = match argc {
1046
+ 0 => ruby.qnil().as_value(),
1047
+ // SAFETY: as above.
1048
+ 1 => unsafe { Value::from_raw(*argv) },
1049
+ _ => {
1050
+ let values = ruby.ary_new_capa(argc as usize);
1051
+ for index in 0..argc as usize {
1052
+ // SAFETY: as above.
1053
+ values.push(unsafe { Value::from_raw(*argv.add(index)) })?;
1054
+ }
1055
+ values.as_value()
1056
+ }
1057
+ };
1058
+ collect_yielded(&ruby, Obj::try_convert(batch)?, ip)
1059
+ }));
1060
+ match result.and_then(|result| result) {
1061
+ Ok(value) => value.as_raw(),
1062
+ // SAFETY: nothing on this stack needs to be dropped.
1063
+ Err(err) => unsafe { resume_error(err) },
1064
+ }
1065
+ }
1066
+
1067
+ /// Looks up a value that `each` yielded and adds it to the results.
1068
+ fn collect_yielded(ruby: &magnus::Ruby, batch: Obj<Batch>, ip: Value) -> Result<Value, Error> {
1069
+ let Some(payload) = batch.payload() else {
1070
+ return Err(Error::new(
1071
+ ruby.exception_runtime_error(),
1072
+ ERR_BATCH_FINISHED,
1073
+ ));
1074
+ };
1075
+ let result = look_up_yielded(ruby, &batch, &payload, ip);
1076
+ // The call can return while the lookup runs Ruby code. After that, only this
1077
+ // stack keeps these alive and in place.
1078
+ gc_guard(&payload);
1079
+ gc_guard(&batch);
1080
+ result
1081
+ }
1082
+
1083
+ fn look_up_yielded(
1084
+ ruby: &magnus::Ruby,
1085
+ batch: &Batch,
1086
+ payload: &Payload,
1087
+ ip: Value,
1088
+ ) -> Result<Value, Error> {
1089
+ // An earlier lookup failed and `each` kept going. Skip the work; the batch
1090
+ // already fails.
1091
+ if !ruby.get_inner(payload.error_slot).is_empty() {
1092
+ return stop_each(ruby, payload);
1093
+ }
1094
+ // A failed batch may not have stored its error yet (see fail_batch).
1095
+ if batch.failed.load(Ordering::Acquire) || batch.looking_up.swap(true, Ordering::AcqRel) {
1096
+ let err = Error::new(ruby.exception_runtime_error(), ERR_BATCH_REENTERED);
1097
+ return fail_batch(ruby, batch, payload, err);
1098
+ }
1099
+
1100
+ // Each lookup loads the reader itself so no guard is held while calling
1101
+ // into Ruby (see NetworkIterator).
1102
+ let reader = ruby.get_inner(payload.reader);
1103
+ let result = match payload.path {
1104
+ Some(path) => {
1105
+ let path = ruby.get_inner(path);
1106
+ reader.lookup_ip_path_value(ruby, ip, path.0.borrow_dependent())
1107
+ }
1108
+ None => reader.lookup_ip_value(ruby, ip),
1109
+ };
1110
+
1111
+ // The lookup can run Ruby code, so check again. Nothing between this check
1112
+ // and the push below can end the batch.
1113
+ if !batch.running.load(Ordering::Acquire) {
1114
+ // Don't drop an error, which may be a thread kill or Interrupt.
1115
+ result?;
1116
+ return Err(Error::new(
1117
+ ruby.exception_runtime_error(),
1118
+ ERR_BATCH_FINISHED,
1119
+ ));
1120
+ }
1121
+ match result {
1122
+ Ok(value) => {
1123
+ batch.looking_up.store(false, Ordering::Release);
1124
+ ruby.get_inner(payload.results).push(value)?;
1125
+ Ok(ruby.qnil().as_value())
1126
+ }
1127
+ Err(err) => fail_batch(ruby, batch, payload, err),
1128
+ }
1129
+ }
617
1130
 
618
- return parse_ip_string(ip_str, ruby);
619
- }
620
-
621
- // Slow path: Try as IPAddr object
622
- if let Ok(ipaddr_class) = ruby.class_object().const_get::<_, RClass>("IPAddr") {
623
- if value.is_kind_of(ipaddr_class) {
624
- let address: u128 = value.funcall("to_i", ())?;
625
- let is_ipv4: bool = value.funcall("ipv4?", ())?;
626
- if is_ipv4 {
627
- let address = u32::try_from(address).map_err(|_| {
628
- Error::new(
629
- ruby.exception_arg_error(),
630
- format!("'{}' does not appear to be an IPv4 address", value),
631
- )
632
- })?;
633
- return Ok(IpAddr::V4(Ipv4Addr::from(address)));
1131
+ /// Stores the error, so that `each` can't hide it by rescuing, and stops `each`.
1132
+ /// The first error wins, except that one such as Interrupt or SystemExit
1133
+ /// replaces a StandardError.
1134
+ fn fail_batch(
1135
+ ruby: &magnus::Ruby,
1136
+ batch: &Batch,
1137
+ payload: &Payload,
1138
+ err: Error,
1139
+ ) -> Result<Value, Error> {
1140
+ // Creating the exception can run Ruby code and let `each` return first. Then
1141
+ // this alone makes the batch fail.
1142
+ batch.failed.store(true, Ordering::Release);
1143
+ let exception = match err.error_type() {
1144
+ // A jump such as `break` or `throw` isn't an exception, and `each` can't
1145
+ // rescue it, so let it continue. If `each` catches it, the batch fails.
1146
+ ErrorType::Jump(_) => return Err(err),
1147
+ ErrorType::Error(class, message) => class.new_instance((message.as_ref(),))?,
1148
+ ErrorType::Exception(exception) => *exception,
1149
+ };
1150
+ let error_slot = ruby.get_inner(payload.error_slot);
1151
+ if error_slot.is_empty() || !exception.is_kind_of(ruby.exception_standard_error()) {
1152
+ error_slot.store(0, exception)?;
1153
+ }
1154
+ stop_each(ruby, payload)
1155
+ }
1156
+
1157
+ /// Throws to the `catch` in `collect_each`. On another thread or fiber, where
1158
+ /// that isn't possible, returns the stored error.
1159
+ fn stop_each(ruby: &magnus::Ruby, payload: &Payload) -> Result<Value, Error> {
1160
+ let tag = ruby.get_inner(payload.tag);
1161
+ let thrown = ruby.module_kernel().funcall::<_, _, Value>("throw", (tag,));
1162
+ match thrown {
1163
+ Err(err) if err.value().is_some() => {
1164
+ let uncaught_throw = ruby
1165
+ .class_object()
1166
+ .const_get::<_, ExceptionClass>("UncaughtThrowError")?;
1167
+ let stored = ruby
1168
+ .get_inner(payload.error_slot)
1169
+ .entry::<Option<Exception>>(0)?;
1170
+ match stored {
1171
+ Some(stored) if err.is_kind_of(uncaught_throw) => Err(stored.into()),
1172
+ _ => Err(err),
634
1173
  }
635
- return Ok(IpAddr::V6(Ipv6Addr::from(address)));
636
1174
  }
1175
+ thrown => thrown,
637
1176
  }
1177
+ }
638
1178
 
639
- if let Ok(ipaddr_obj) = value.funcall::<_, _, String>("to_s", ()) {
640
- return parse_ip_string(&ipaddr_obj, ruby);
1179
+ /// Keeps `value` in this frame's memory up to this point, like Ruby's
1180
+ /// `RB_GC_GUARD`, so the garbage collector's stack scan finds it.
1181
+ #[inline(always)]
1182
+ fn gc_guard<T: Copy>(value: &T) {
1183
+ // SAFETY: `value` is a valid reference to an initialized `T`.
1184
+ unsafe {
1185
+ std::ptr::read_volatile(value);
641
1186
  }
1187
+ }
642
1188
 
643
- Err(Error::new(
644
- ruby.exception_arg_error(),
645
- format!("'{}' does not appear to be an IPv4 or IPv6 address", value),
646
- ))
1189
+ /// Parse a plain IPv4 or IPv6 String without calling Ruby. Returns `None` for
1190
+ /// anything else.
1191
+ #[inline(always)]
1192
+ fn parse_plain_ip(value: Value) -> Option<IpAddr> {
1193
+ let rstring = RString::from_value(value)?;
1194
+ // SAFETY: the &str is only used for parsing before any Ruby code can run
1195
+ // and modify the string. An invalidly encoded string is not a plain IP.
1196
+ unsafe { rstring.test_as_str() }.and_then(parse_ip_string)
1197
+ }
1198
+
1199
+ /// Parse an IP address that is not a plain String with `IPAddr`
1200
+ ///
1201
+ /// Anything that is not an `IPAddr` is handed to `IPAddr.new`, as the official
1202
+ /// gem does, so CIDR strings, scoped IPv6 addresses and the
1203
+ /// `IPAddr::InvalidAddressError` raised for invalid input all match it.
1204
+ fn parse_ip_with_ipaddr(value: Value, ruby: &magnus::Ruby) -> Result<IpAddr, Error> {
1205
+ if value.is_kind_of(ipaddr_class(ruby)?) {
1206
+ return ipaddr_to_ip(value, ruby);
1207
+ }
1208
+
1209
+ ipaddr_to_ip(ipaddr_new(value, ruby)?, ruby)
1210
+ }
1211
+
1212
+ fn ipaddr_class(ruby: &magnus::Ruby) -> Result<RClass, Error> {
1213
+ ruby.class_object().const_get::<_, RClass>("IPAddr")
1214
+ }
1215
+
1216
+ fn ipaddr_new(value: Value, ruby: &magnus::Ruby) -> Result<Value, Error> {
1217
+ ipaddr_class(ruby)?.new_instance((value,))
1218
+ }
1219
+
1220
+ fn ipaddr_to_ip(ipaddr: Value, ruby: &magnus::Ruby) -> Result<IpAddr, Error> {
1221
+ let address: u128 = ipaddr.funcall("to_i", ())?;
1222
+ let is_ipv4: bool = ipaddr.funcall("ipv4?", ())?;
1223
+ if is_ipv4 {
1224
+ let address = u32::try_from(address).map_err(|_| {
1225
+ interpolated_error(
1226
+ ruby,
1227
+ ruby.exception_arg_error(),
1228
+ "'",
1229
+ ipaddr,
1230
+ "' does not appear to be an IPv4 address",
1231
+ )
1232
+ })?;
1233
+ return Ok(IpAddr::V4(Ipv4Addr::from(address)));
1234
+ }
1235
+ Ok(IpAddr::V6(Ipv6Addr::from(address)))
647
1236
  }
648
1237
 
649
1238
  #[inline(always)]
650
- fn parse_ip_string(s: &str, ruby: &magnus::Ruby) -> Result<IpAddr, Error> {
1239
+ fn parse_ip_string(s: &str) -> Option<IpAddr> {
651
1240
  if let Some(ip) = parse_ipv4_string(s.as_bytes()) {
652
- return Ok(IpAddr::V4(ip));
1241
+ return Some(IpAddr::V4(ip));
653
1242
  }
654
1243
 
655
- IpAddr::from_str(s).map_err(|_| {
656
- Error::new(
657
- ruby.exception_arg_error(),
658
- format!("'{}' does not appear to be an IPv4 or IPv6 address", s),
659
- )
660
- })
1244
+ IpAddr::from_str(s).ok()
661
1245
  }
662
1246
 
663
1247
  #[inline(always)]
@@ -739,6 +1323,7 @@ fn lookup_error(ruby: &magnus::Ruby, err: MaxMindDbError, context: &str) -> Erro
739
1323
  match err {
740
1324
  MaxMindDbError::InvalidDatabase { .. }
741
1325
  | MaxMindDbError::Decoding { .. }
1326
+ | MaxMindDbError::ResourceLimit { .. }
742
1327
  | MaxMindDbError::Io(_) => invalid_database_exception(ERR_BAD_DATA),
743
1328
  other => Error::new(
744
1329
  ruby.exception_runtime_error(),
@@ -747,16 +1332,81 @@ fn lookup_error(ruby: &magnus::Ruby, err: MaxMindDbError, context: &str) -> Erro
747
1332
  }
748
1333
  }
749
1334
 
750
- /// Generate error message for IPv6 in IPv4-only database
751
- fn ipv6_in_ipv4_error(ip: &IpAddr) -> String {
752
- format!(
753
- "Error looking up {}. You attempted to look up an IPv6 address in an IPv4-only database.",
754
- ip
1335
+ /// The error for an IPv6 address in an IPv4-only database.
1336
+ fn ipv6_in_ipv4_error(ruby: &magnus::Ruby, ip: Value) -> Error {
1337
+ interpolated_error(
1338
+ ruby,
1339
+ ruby.exception_arg_error(),
1340
+ "Error looking up ",
1341
+ ip,
1342
+ ". You attempted to look up an IPv6 address in an IPv4-only database.",
755
1343
  )
756
1344
  }
757
1345
 
758
- fn database_path(database: Value) -> Result<String, Error> {
759
- RString::try_convert(database)?.to_string()
1346
+ /// An exception of `class` whose message is `"#{prefix}#{value}#{suffix}"`.
1347
+ ///
1348
+ /// The message is built the way Ruby string interpolation builds it: a String
1349
+ /// is used as is and anything else goes through `to_s`. So, as in the
1350
+ /// `maxmind-db` gem, an exception or `throw` from `to_s`, or an
1351
+ /// `Encoding::CompatibilityError` from joining the text, is what the caller
1352
+ /// gets. Formatting the `Value` with `{}` would instead ignore those and show
1353
+ /// `#<Class:0x...>`.
1354
+ fn interpolated_error(
1355
+ ruby: &magnus::Ruby,
1356
+ class: ExceptionClass,
1357
+ prefix: &str,
1358
+ value: Value,
1359
+ suffix: &str,
1360
+ ) -> Error {
1361
+ let build = || -> Result<Exception, Error> {
1362
+ let message = ruby.str_new(prefix);
1363
+ message.buf_append(value.to_r_string()?)?;
1364
+ message.cat(suffix);
1365
+ class.new_instance((message,))
1366
+ };
1367
+ match build() {
1368
+ Ok(exception) => exception.into(),
1369
+ Err(err) => err,
1370
+ }
1371
+ }
1372
+
1373
+ /// A database path, and the Ruby String to show it as in error messages. Only
1374
+ /// the String has the encoding.
1375
+ struct DatabasePath {
1376
+ path: PathBuf,
1377
+ name: RString,
1378
+ }
1379
+
1380
+ /// Convert a database path argument the way Ruby's `File.open` does, including
1381
+ /// `to_path`, the encoding and the check for null bytes.
1382
+ fn database_path(database: Value, ruby: &magnus::Ruby) -> Result<DatabasePath, Error> {
1383
+ // SAFETY: `rb_get_path` is called with a live VALUE and returns a String.
1384
+ // `protect` catches anything it raises or throws.
1385
+ let name = unsafe { Value::from_raw(protect(|| rb_sys::rb_get_path(database.as_raw()))?) };
1386
+ let name = RString::try_convert(name)?;
1387
+ Ok(DatabasePath {
1388
+ path: path_from_string(name, ruby)?,
1389
+ name,
1390
+ })
1391
+ }
1392
+
1393
+ #[cfg(unix)]
1394
+ fn path_from_string(path: RString, _ruby: &magnus::Ruby) -> Result<PathBuf, Error> {
1395
+ use std::os::unix::ffi::OsStringExt;
1396
+
1397
+ // macOS file names are UTF-8, and Ruby converts the path before it opens
1398
+ // the file.
1399
+ #[cfg(target_os = "macos")]
1400
+ let path = path.conv_enc(_ruby.utf8_encoding())?;
1401
+
1402
+ // SAFETY: the bytes are copied before Ruby can mutate or free the string.
1403
+ let bytes = unsafe { path.as_slice() }.to_vec();
1404
+ Ok(PathBuf::from(std::ffi::OsString::from_vec(bytes)))
1405
+ }
1406
+
1407
+ #[cfg(not(unix))]
1408
+ fn path_from_string(path: RString, _ruby: &magnus::Ruby) -> Result<PathBuf, Error> {
1409
+ Ok(PathBuf::from(path.to_string()?))
760
1410
  }
761
1411
 
762
1412
  fn database_buffer(database: Value) -> Result<Vec<u8>, Error> {
@@ -767,104 +1417,158 @@ fn database_buffer(database: Value) -> Result<Vec<u8>, Error> {
767
1417
  }
768
1418
 
769
1419
  /// Open a MaxMind DB using memory-mapped I/O (MODE_MMAP)
770
- fn open_database_mmap(path: &str) -> Result<Reader, Error> {
771
- let ruby = magnus::Ruby::get().expect("Ruby VM should be available in Ruby context");
772
- let file = open_database_file(path, &ruby)?;
773
-
774
- // SAFETY: the mapping is read-only, and MODE_MMAP's documented contract
775
- // requires callers not to modify or truncate the mapped file while this
776
- // reader is alive. Database updates should atomically replace the path.
777
- let mmap = unsafe { Mmap::map(&file) }.map_err(|e| {
778
- Error::new(
779
- ruby.exception_io_error(),
780
- format!("Failed to memory-map database file: {}", e),
781
- )
782
- })?;
783
- let reader = MaxMindReader::from_source(mmap).map_err(|_| {
784
- invalid_database_exception(&format!(
785
- "Error opening database file ({}). Is this a valid MaxMind DB file?",
786
- path
787
- ))
788
- })?;
789
-
790
- Ok(create_reader(ReaderSource::Mmap(reader)))
1420
+ fn open_database_mmap(database: &DatabasePath) -> Result<ReaderSource, OpenError> {
1421
+ let map_file = || {
1422
+ let file = open_database_file(&database.path)?;
1423
+ // SAFETY: the mapping is read-only, and MODE_MMAP's documented contract
1424
+ // requires callers not to modify or truncate the mapped file while this
1425
+ // reader is alive. Database updates should atomically replace the path.
1426
+ unsafe { Mmap::map(&file) }.map_err(FileError::Io)
1427
+ };
1428
+ let mmap = map_file().map_err(|err| OpenError::File(err, database.name))?;
1429
+ let reader =
1430
+ MaxMindReader::from_source(mmap).map_err(|_| OpenError::InvalidDatabase(database.name))?;
1431
+
1432
+ Ok(ReaderSource::Mmap(reader))
791
1433
  }
792
1434
 
793
1435
  /// Open a MaxMind DB by loading entire file into memory (MODE_MEMORY)
794
- fn open_database_memory(path: &str) -> Result<Reader, Error> {
795
- let ruby = magnus::Ruby::get().expect("Ruby VM should be available in Ruby context");
796
- let mut file = open_database_file(path, &ruby)?;
1436
+ fn open_database_memory(database: &DatabasePath) -> Result<ReaderSource, OpenError> {
1437
+ // Opening and reading the file can block for a long time, so do it
1438
+ // without the GVL and build any Ruby exception afterwards.
1439
+ let path = database.path.as_path();
1440
+ let buffer = without_gvl(|| {
1441
+ let mut file = open_database_file(path)?;
1442
+ let mut buffer = Vec::new();
1443
+ file.read_to_end(&mut buffer).map_err(FileError::Io)?;
1444
+ Ok(buffer)
1445
+ })?
1446
+ .map_err(|err| OpenError::File(err, database.name))?;
1447
+ let reader = MaxMindReader::from_source(buffer)
1448
+ .map_err(|_| OpenError::InvalidDatabase(database.name))?;
797
1449
 
798
- let mut buffer = Vec::new();
799
- file.read_to_end(&mut buffer).map_err(|e| {
800
- Error::new(
801
- ruby.exception_io_error(),
802
- format!("Failed to read database file: {}", e),
1450
+ Ok(ReaderSource::Memory(reader))
1451
+ }
1452
+
1453
+ fn open_database_buffer(buffer: Vec<u8>) -> Result<ReaderSource, Error> {
1454
+ let reader = MaxMindReader::from_source(buffer).map_err(|_| {
1455
+ invalid_database_exception(
1456
+ "Error opening database from buffer. Is this a valid MaxMind DB file?",
803
1457
  )
804
1458
  })?;
805
1459
 
806
- reader_from_buffer(
807
- buffer,
808
- format!(
809
- "Error opening database file ({}). Is this a valid MaxMind DB file?",
810
- path
811
- ),
812
- )
1460
+ Ok(ReaderSource::Memory(reader))
813
1461
  }
814
1462
 
815
- fn open_database_buffer(buffer: Vec<u8>) -> Result<Reader, Error> {
816
- reader_from_buffer(
817
- buffer,
818
- "Error opening database from buffer. Is this a valid MaxMind DB file?".to_owned(),
819
- )
1463
+ /// Opens the file without calling Ruby, so this can run without the GVL.
1464
+ fn open_database_file(path: &Path) -> Result<File, FileError> {
1465
+ let file = File::open(path).map_err(FileError::Io)?;
1466
+ // Opening a directory succeeds on Unix, and the error only shows up later
1467
+ // as an unhelpful mmap or read failure. Raise Errno::EISDIR up front, as
1468
+ // the official gem does.
1469
+ if file.metadata().map_err(FileError::Io)?.is_dir() {
1470
+ return Err(FileError::IsDirectory);
1471
+ }
1472
+ Ok(file)
820
1473
  }
821
1474
 
822
- fn reader_from_buffer(buffer: Vec<u8>, invalid_message: String) -> Result<Reader, Error> {
823
- let reader = MaxMindReader::from_source(buffer)
824
- .map_err(|_| invalid_database_exception(invalid_message.as_str()))?;
1475
+ enum FileError {
1476
+ Io(std::io::Error),
1477
+ IsDirectory,
1478
+ }
825
1479
 
826
- Ok(create_reader(ReaderSource::Memory(reader)))
1480
+ /// Why opening a database failed, with the String to show the path as.
1481
+ ///
1482
+ /// Creating an exception can call Ruby, which can abandon the stack. So this
1483
+ /// waits until the file is closed and the reader can be initialized again.
1484
+ enum OpenError {
1485
+ Ruby(Error),
1486
+ File(FileError, RString),
1487
+ InvalidDatabase(RString),
827
1488
  }
828
1489
 
829
- fn open_database_file(path: &str, ruby: &magnus::Ruby) -> Result<File, Error> {
830
- File::open(Path::new(path)).map_err(|e| {
831
- if e.kind() == std::io::ErrorKind::NotFound {
832
- open_not_found_error(ruby, e)
833
- } else {
834
- Error::new(ruby.exception_io_error(), e.to_string())
1490
+ impl From<Error> for OpenError {
1491
+ fn from(err: Error) -> Self {
1492
+ Self::Ruby(err)
1493
+ }
1494
+ }
1495
+
1496
+ impl OpenError {
1497
+ fn into_error(self, ruby: &magnus::Ruby) -> Error {
1498
+ match self {
1499
+ Self::Ruby(err) => err,
1500
+ Self::File(FileError::Io(err), name) => io_error(ruby, &err, name),
1501
+ Self::File(FileError::IsDirectory, name) => errno_error(ruby, "EISDIR", name),
1502
+ Self::InvalidDatabase(name) => interpolated_error(
1503
+ ruby,
1504
+ invalid_database_class(),
1505
+ "Error opening database file (",
1506
+ name.as_value(),
1507
+ "). Is this a valid MaxMind DB file?",
1508
+ ),
835
1509
  }
836
- })
1510
+ }
837
1511
  }
838
1512
 
839
- fn open_not_found_error(ruby: &magnus::Ruby, err: std::io::Error) -> Error {
840
- let errno = ruby
1513
+ /// Convert an I/O error into the matching `Errno` exception, so callers that
1514
+ /// rescue `SystemCallError` see the same classes as with the official gem.
1515
+ /// Errors without an OS error code fall back to `IOError`.
1516
+ fn io_error(ruby: &magnus::Ruby, err: &std::io::Error, name: RString) -> Error {
1517
+ let Some(code) = err.raw_os_error() else {
1518
+ return interpolated_error(
1519
+ ruby,
1520
+ ruby.exception_io_error(),
1521
+ &format!("{err} - "),
1522
+ name.as_value(),
1523
+ "",
1524
+ );
1525
+ };
1526
+ // Ruby turns this into the `Errno` subclass for the code.
1527
+ let exception = ruby
1528
+ .exception_system_call_error()
1529
+ .new_instance((name, errno_from_os_error(code)));
1530
+ match exception {
1531
+ Ok(exception) => Error::from(exception),
1532
+ Err(error) => error,
1533
+ }
1534
+ }
1535
+
1536
+ #[cfg(not(windows))]
1537
+ fn errno_from_os_error(code: i32) -> i32 {
1538
+ code
1539
+ }
1540
+
1541
+ /// Map a Win32 error code to an errno with the function Ruby itself uses.
1542
+ #[cfg(windows)]
1543
+ fn errno_from_os_error(code: i32) -> i32 {
1544
+ extern "C" {
1545
+ fn rb_w32_map_errno(code: u32) -> std::ffi::c_int;
1546
+ }
1547
+ // SAFETY: Ruby exports this function on Windows. It only reads a table.
1548
+ unsafe { rb_w32_map_errno(code as u32) }
1549
+ }
1550
+
1551
+ fn errno_error(ruby: &magnus::Ruby, errno_name: &str, name: RString) -> Error {
1552
+ let class = ruby
841
1553
  .class_object()
842
1554
  .const_get::<_, RModule>("Errno")
843
- .expect("Errno module should exist");
844
- let enoent = errno
845
- .const_get::<_, RClass>("ENOENT")
846
- .expect("Errno::ENOENT should exist");
847
- Error::new(
848
- ExceptionClass::from_value(enoent.as_value())
849
- .expect("ENOENT should convert to ExceptionClass"),
850
- err.to_string(),
851
- )
1555
+ .and_then(|errno| errno.const_get::<_, ExceptionClass>(errno_name));
1556
+ match class.and_then(|class| class.new_instance((name,))) {
1557
+ Ok(exception) => Error::from(exception),
1558
+ Err(error) => error,
1559
+ }
852
1560
  }
853
1561
 
854
1562
  /// Get the InvalidDatabaseError class
855
- fn invalid_database_error() -> RClass {
1563
+ fn invalid_database_class() -> ExceptionClass {
856
1564
  let ruby = magnus::Ruby::get().expect("Ruby VM should be available in Ruby context");
857
- let rust = rust_module(&ruby);
858
- rust.const_get::<_, RClass>("InvalidDatabaseError")
1565
+ rust_module(&ruby)
1566
+ .const_get::<_, ExceptionClass>("InvalidDatabaseError")
859
1567
  .expect("InvalidDatabaseError class should exist")
860
1568
  }
861
1569
 
862
1570
  fn invalid_database_exception(message: &str) -> Error {
863
- Error::new(
864
- ExceptionClass::from_value(invalid_database_error().as_value())
865
- .expect("InvalidDatabaseError should convert to ExceptionClass"),
866
- message.to_owned(),
867
- )
1571
+ Error::new(invalid_database_class(), message.to_owned())
868
1572
  }
869
1573
 
870
1574
  pub(crate) fn define(ruby: &magnus::Ruby, rust: RModule) -> Result<(), Error> {
@@ -872,7 +1576,12 @@ pub(crate) fn define(ruby: &magnus::Ruby, rust: RModule) -> Result<(), Error> {
872
1576
  rust.define_error("InvalidDatabaseError", runtime_error)?;
873
1577
 
874
1578
  let reader_class = rust.define_class("Reader", ruby.class_object())?;
875
- reader_class.define_singleton_method("new", magnus::function!(Reader::new, -1))?;
1579
+ reader_class.define_alloc_func::<Reader>();
1580
+ reader_class.define_method("initialize", magnus::method!(Reader::initialize, -1))?;
1581
+ reader_class.define_method(
1582
+ "initialize_copy",
1583
+ magnus::method!(Reader::initialize_copy, 1),
1584
+ )?;
876
1585
  reader_class.define_method("get", magnus::method!(Reader::get, 1))?;
877
1586
  reader_class.define_method("get_path", magnus::method!(Reader::get_path, 2))?;
878
1587
  reader_class.define_method(
@@ -888,6 +1597,17 @@ pub(crate) fn define(ruby: &magnus::Ruby, rust: RModule) -> Result<(), Error> {
888
1597
  reader_class.define_method("inspect", magnus::method!(Reader::inspect, 0))?;
889
1598
  reader_class.define_method("each", magnus::method!(Reader::each, -1))?;
890
1599
 
1600
+ // Internal holders for iteration and batch lookup state; not meant to be used
1601
+ // directly. A constant of Reader would hide a top-level constant of the same
1602
+ // name in every subclass, so these are not under Reader.
1603
+ let iterator_class = rust.define_class("ReaderNetworkIterator", ruby.class_object())?;
1604
+ iterator_class.undef_default_alloc_func();
1605
+ let batch_class = rust.define_class("ReaderBatch", ruby.class_object())?;
1606
+ batch_class.undef_default_alloc_func();
1607
+ batch_class.define_method("to_proc", magnus::method!(Batch::to_proc, 0))?;
1608
+ let batch_path_class = rust.define_class("ReaderBatchPath", ruby.class_object())?;
1609
+ batch_path_class.undef_default_alloc_func();
1610
+
891
1611
  let enumerable = ruby.class_object().const_get::<_, RModule>("Enumerable")?;
892
1612
  reader_class.include_module(enumerable)?;
893
1613