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.
@@ -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,183 +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::ResourceLimit { .. })
451
- | Err(MaxMindDbError::Io(_)) => {
452
- return Err(invalid_database_exception(ERR_BAD_DATA));
453
- }
454
- Err(e) => {
455
- return Err(Error::new(
456
- ruby.exception_runtime_error(),
457
- format!("Database iteration failed: {}", e),
458
- ));
459
- }
460
- }
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)?;
461
586
  }
462
587
 
463
588
  Ok(ruby.qnil().as_value())
464
589
  }
465
590
 
466
- /// Helper method to get the reader from the ArcSwapOption
467
- fn get_reader(&self, ruby: &magnus::Ruby) -> Result<Guard<Option<Arc<ReaderSource>>>, Error> {
468
- let guard = self.reader.load();
469
- if guard.is_none() {
470
- return Err(Error::new(ruby.exception_runtime_error(), ERR_CLOSED_DB));
471
- }
472
- 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")
473
599
  }
474
600
 
475
601
  #[inline]
476
602
  fn parse_lookup_ip(&self, ip_address: Value, ruby: &magnus::Ruby) -> Result<IpAddr, Error> {
477
- let parsed_ip = parse_ip_address_fast(ip_address, ruby)?;
478
- self.validate_lookup_ip(parsed_ip, ruby)
479
- }
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
+ };
480
612
 
481
- #[inline]
482
- fn validate_lookup_ip(&self, parsed_ip: IpAddr, ruby: &magnus::Ruby) -> Result<IpAddr, Error> {
483
- if self.ip_version == 4 && matches!(parsed_ip, IpAddr::V6(_)) {
484
- Err(Error::new(
485
- ruby.exception_arg_error(),
486
- ipv6_in_ipv4_error(&parsed_ip),
487
- ))
488
- } else {
489
- 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));
490
618
  }
619
+ Ok(parsed_ip)
491
620
  }
492
621
 
493
- #[inline]
494
- fn lookup_ip_value(
495
- &self,
496
- ruby: &magnus::Ruby,
497
- reader: &ReaderSource,
498
- ip: Value,
499
- ) -> Result<Value, Error> {
500
- let parsed_ip = self.parse_lookup_ip(ip, ruby)?;
501
- lookup_result_to_value(ruby, reader.lookup(parsed_ip), "Database lookup failed")
502
- }
503
-
504
- #[inline]
505
- fn lookup_ip_path_value(
506
- &self,
507
- ruby: &magnus::Ruby,
508
- reader: &ReaderSource,
509
- ip: Value,
510
- path_elements: &[PathElement<'_>],
511
- ) -> Result<Value, Error> {
512
- let parsed_ip = self.parse_lookup_ip(ip, ruby)?;
513
- lookup_result_to_value(
514
- ruby,
515
- reader.lookup_path(parsed_ip, path_elements),
516
- "Database lookup failed",
517
- )
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)
518
634
  }
519
635
 
520
636
  fn parse_path(
@@ -522,10 +638,18 @@ impl Reader {
522
638
  path: Value,
523
639
  ruby: &magnus::Ruby,
524
640
  ) -> Result<Arc<[OwnedPathElement]>, Error> {
525
- let path = path_array(path, ruby)?;
526
- 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))?;
527
651
 
528
- if let Some(cached) = self.cached_path(path, hash)? {
652
+ if let Some(cached) = self.cached_path(path, hash, ruby)? {
529
653
  return Ok(cached);
530
654
  }
531
655
 
@@ -538,18 +662,37 @@ impl Reader {
538
662
  &self,
539
663
  path: RArray,
540
664
  hash: u64,
665
+ ruby: &magnus::Ruby,
541
666
  ) -> Result<Option<Arc<[OwnedPathElement]>>, Error> {
542
- let cache = match self.path_cache.lock() {
543
- Ok(cache) => cache,
544
- 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)
545
691
  };
546
692
 
547
- for entry in cache
548
- .iter()
549
- .filter(|entry| entry.hash == hash && entry.elements.len() == path.len())
550
- {
551
- if path_matches_cached(path, entry.elements.as_ref())? {
552
- 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));
553
696
  }
554
697
  }
555
698
 
@@ -571,6 +714,101 @@ impl Reader {
571
714
  }
572
715
  }
573
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
+ }
574
812
  }
575
813
 
576
814
  // SAFETY: Reader does not store Ruby VALUE handles. The database source is
@@ -580,14 +818,180 @@ impl Reader {
580
818
  // while the Ruby VM is active.
581
819
  unsafe impl Send for Reader {}
582
820
 
583
- /// Helper function to create a Reader from a ReaderSource
584
- fn create_reader(source: ReaderSource) -> Reader {
585
- let ip_version = source.metadata().ip_version;
586
- let source = Arc::new(source);
587
- Reader {
588
- reader: ArcSwapOption::from(Some(source)),
589
- path_cache: Mutex::new(VecDeque::with_capacity(PATH_CACHE_MAX_ENTRIES)),
590
- 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
+ },
591
995
  }
592
996
  }
593
997
 
@@ -602,63 +1006,242 @@ fn ensure_enumerable(value: Value, ruby: &magnus::Ruby, error_message: &str) ->
602
1006
  }
603
1007
  }
604
1008
 
605
- /// Parse IP address from Ruby value (String or IPAddr) - optimized version
606
- #[inline(always)]
607
- fn parse_ip_address_fast(value: Value, ruby: &magnus::Ruby) -> Result<IpAddr, Error> {
608
- // Fast path: Try as RString first (most common case) - zero-copy
609
- if let Some(rstring) = RString::from_value(value) {
610
- // SAFETY: as_str() returns a &str that's valid as long as the Ruby string isn't modified
611
- // We use it immediately for parsing, so this is safe
612
- let ip_str = unsafe { rstring.as_str() }.map_err(|e| {
613
- Error::new(
614
- ruby.exception_arg_error(),
615
- format!("Invalid UTF-8 in IP address string: {}", e),
616
- )
617
- })?;
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
+ }
618
1130
 
619
- return parse_ip_string(ip_str, ruby);
620
- }
621
-
622
- // Slow path: Try as IPAddr object
623
- if let Ok(ipaddr_class) = ruby.class_object().const_get::<_, RClass>("IPAddr") {
624
- if value.is_kind_of(ipaddr_class) {
625
- let address: u128 = value.funcall("to_i", ())?;
626
- let is_ipv4: bool = value.funcall("ipv4?", ())?;
627
- if is_ipv4 {
628
- let address = u32::try_from(address).map_err(|_| {
629
- Error::new(
630
- ruby.exception_arg_error(),
631
- format!("'{}' does not appear to be an IPv4 address", value),
632
- )
633
- })?;
634
- 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),
635
1173
  }
636
- return Ok(IpAddr::V6(Ipv6Addr::from(address)));
637
1174
  }
1175
+ thrown => thrown,
638
1176
  }
1177
+ }
639
1178
 
640
- if let Ok(ipaddr_obj) = value.funcall::<_, _, String>("to_s", ()) {
641
- 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);
642
1186
  }
1187
+ }
643
1188
 
644
- Err(Error::new(
645
- ruby.exception_arg_error(),
646
- format!("'{}' does not appear to be an IPv4 or IPv6 address", value),
647
- ))
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)))
648
1236
  }
649
1237
 
650
1238
  #[inline(always)]
651
- fn parse_ip_string(s: &str, ruby: &magnus::Ruby) -> Result<IpAddr, Error> {
1239
+ fn parse_ip_string(s: &str) -> Option<IpAddr> {
652
1240
  if let Some(ip) = parse_ipv4_string(s.as_bytes()) {
653
- return Ok(IpAddr::V4(ip));
1241
+ return Some(IpAddr::V4(ip));
654
1242
  }
655
1243
 
656
- IpAddr::from_str(s).map_err(|_| {
657
- Error::new(
658
- ruby.exception_arg_error(),
659
- format!("'{}' does not appear to be an IPv4 or IPv6 address", s),
660
- )
661
- })
1244
+ IpAddr::from_str(s).ok()
662
1245
  }
663
1246
 
664
1247
  #[inline(always)]
@@ -749,16 +1332,81 @@ fn lookup_error(ruby: &magnus::Ruby, err: MaxMindDbError, context: &str) -> Erro
749
1332
  }
750
1333
  }
751
1334
 
752
- /// Generate error message for IPv6 in IPv4-only database
753
- fn ipv6_in_ipv4_error(ip: &IpAddr) -> String {
754
- format!(
755
- "Error looking up {}. You attempted to look up an IPv6 address in an IPv4-only database.",
756
- 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.",
757
1343
  )
758
1344
  }
759
1345
 
760
- fn database_path(database: Value) -> Result<String, Error> {
761
- 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()?))
762
1410
  }
763
1411
 
764
1412
  fn database_buffer(database: Value) -> Result<Vec<u8>, Error> {
@@ -769,104 +1417,158 @@ fn database_buffer(database: Value) -> Result<Vec<u8>, Error> {
769
1417
  }
770
1418
 
771
1419
  /// Open a MaxMind DB using memory-mapped I/O (MODE_MMAP)
772
- fn open_database_mmap(path: &str) -> Result<Reader, Error> {
773
- let ruby = magnus::Ruby::get().expect("Ruby VM should be available in Ruby context");
774
- let file = open_database_file(path, &ruby)?;
775
-
776
- // SAFETY: the mapping is read-only, and MODE_MMAP's documented contract
777
- // requires callers not to modify or truncate the mapped file while this
778
- // reader is alive. Database updates should atomically replace the path.
779
- let mmap = unsafe { Mmap::map(&file) }.map_err(|e| {
780
- Error::new(
781
- ruby.exception_io_error(),
782
- format!("Failed to memory-map database file: {}", e),
783
- )
784
- })?;
785
- let reader = MaxMindReader::from_source(mmap).map_err(|_| {
786
- invalid_database_exception(&format!(
787
- "Error opening database file ({}). Is this a valid MaxMind DB file?",
788
- path
789
- ))
790
- })?;
791
-
792
- 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))
793
1433
  }
794
1434
 
795
1435
  /// Open a MaxMind DB by loading entire file into memory (MODE_MEMORY)
796
- fn open_database_memory(path: &str) -> Result<Reader, Error> {
797
- let ruby = magnus::Ruby::get().expect("Ruby VM should be available in Ruby context");
798
- 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))?;
799
1449
 
800
- let mut buffer = Vec::new();
801
- file.read_to_end(&mut buffer).map_err(|e| {
802
- Error::new(
803
- ruby.exception_io_error(),
804
- 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?",
805
1457
  )
806
1458
  })?;
807
1459
 
808
- reader_from_buffer(
809
- buffer,
810
- format!(
811
- "Error opening database file ({}). Is this a valid MaxMind DB file?",
812
- path
813
- ),
814
- )
1460
+ Ok(ReaderSource::Memory(reader))
815
1461
  }
816
1462
 
817
- fn open_database_buffer(buffer: Vec<u8>) -> Result<Reader, Error> {
818
- reader_from_buffer(
819
- buffer,
820
- "Error opening database from buffer. Is this a valid MaxMind DB file?".to_owned(),
821
- )
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)
822
1473
  }
823
1474
 
824
- fn reader_from_buffer(buffer: Vec<u8>, invalid_message: String) -> Result<Reader, Error> {
825
- let reader = MaxMindReader::from_source(buffer)
826
- .map_err(|_| invalid_database_exception(invalid_message.as_str()))?;
1475
+ enum FileError {
1476
+ Io(std::io::Error),
1477
+ IsDirectory,
1478
+ }
827
1479
 
828
- 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),
829
1488
  }
830
1489
 
831
- fn open_database_file(path: &str, ruby: &magnus::Ruby) -> Result<File, Error> {
832
- File::open(Path::new(path)).map_err(|e| {
833
- if e.kind() == std::io::ErrorKind::NotFound {
834
- open_not_found_error(ruby, e)
835
- } else {
836
- 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
+ ),
837
1509
  }
838
- })
1510
+ }
839
1511
  }
840
1512
 
841
- fn open_not_found_error(ruby: &magnus::Ruby, err: std::io::Error) -> Error {
842
- 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
843
1553
  .class_object()
844
1554
  .const_get::<_, RModule>("Errno")
845
- .expect("Errno module should exist");
846
- let enoent = errno
847
- .const_get::<_, RClass>("ENOENT")
848
- .expect("Errno::ENOENT should exist");
849
- Error::new(
850
- ExceptionClass::from_value(enoent.as_value())
851
- .expect("ENOENT should convert to ExceptionClass"),
852
- err.to_string(),
853
- )
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
+ }
854
1560
  }
855
1561
 
856
1562
  /// Get the InvalidDatabaseError class
857
- fn invalid_database_error() -> RClass {
1563
+ fn invalid_database_class() -> ExceptionClass {
858
1564
  let ruby = magnus::Ruby::get().expect("Ruby VM should be available in Ruby context");
859
- let rust = rust_module(&ruby);
860
- rust.const_get::<_, RClass>("InvalidDatabaseError")
1565
+ rust_module(&ruby)
1566
+ .const_get::<_, ExceptionClass>("InvalidDatabaseError")
861
1567
  .expect("InvalidDatabaseError class should exist")
862
1568
  }
863
1569
 
864
1570
  fn invalid_database_exception(message: &str) -> Error {
865
- Error::new(
866
- ExceptionClass::from_value(invalid_database_error().as_value())
867
- .expect("InvalidDatabaseError should convert to ExceptionClass"),
868
- message.to_owned(),
869
- )
1571
+ Error::new(invalid_database_class(), message.to_owned())
870
1572
  }
871
1573
 
872
1574
  pub(crate) fn define(ruby: &magnus::Ruby, rust: RModule) -> Result<(), Error> {
@@ -874,7 +1576,12 @@ pub(crate) fn define(ruby: &magnus::Ruby, rust: RModule) -> Result<(), Error> {
874
1576
  rust.define_error("InvalidDatabaseError", runtime_error)?;
875
1577
 
876
1578
  let reader_class = rust.define_class("Reader", ruby.class_object())?;
877
- 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
+ )?;
878
1585
  reader_class.define_method("get", magnus::method!(Reader::get, 1))?;
879
1586
  reader_class.define_method("get_path", magnus::method!(Reader::get_path, 2))?;
880
1587
  reader_class.define_method(
@@ -890,6 +1597,17 @@ pub(crate) fn define(ruby: &magnus::Ruby, rust: RModule) -> Result<(), Error> {
890
1597
  reader_class.define_method("inspect", magnus::method!(Reader::inspect, 0))?;
891
1598
  reader_class.define_method("each", magnus::method!(Reader::each, -1))?;
892
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
+
893
1611
  let enumerable = ruby.class_object().const_get::<_, RModule>("Enumerable")?;
894
1612
  reader_class.include_module(enumerable)?;
895
1613