Cache:...::Safe(3pm)

πŸ’– Cache::Memcached::Fast::Safe β€” the manual, but make it cute πŸ’–

okay bestie so this is Cache::Memcached::Fast::Safe, a User Contributed Perl Documentation page, and it's literally Cache::Memcached::Fast but with sanitizing keys and fork-safe energy. iykyk. πŸ¦‹


✨ NAME ✨

Cache::Memcached::Fast::Safe β€” it's Cache::Memcached::Fast with sanitizing keys and fork-safe vibes. no cap. πŸ’…


🌸 SYNOPSIS 🌸

use Cache::Memcached::Fast::Safe;

my $memd = Cache::Memcached::Fast::Safe->new({
  servers => [..]
});

#This module supports all method that Cache::Memcached::Fast has.

the way that it supports all the methods that Cache::Memcached::Fast has?? iconic. every single one. periodt. πŸ‘‘


πŸŽ€ DESCRIPTION πŸŽ€

So Cache::Memcached::Fast::Safe is a subclass of Cache::Memcached::Fast. 🧚

And it does two main character things:

  • it sanitizes all requested keys so you don't get got by the memcached injection problem πŸ’€
  • it calls disconnect_all automatically after fork, for that fork-safe lifestyle πŸ“

⭐ ADDITIONAL METHOD ⭐

get_or_set($key:Str, $callback:CodeRef [,$expires:Num])

okay so this one is the move. you give it a $key, and if that key is already cached, you get the cache value back. simple. slay.

But if it can not retrieve cache values, then it runs your $callback and caches the result with $expires seconds. 🫢

$memd->get_or_set('key:941',sub {
  DB->retrieve(941)
},10);

and here's the cute part β€” the callback can also return expires sec. so you can hand back both the value and the TTL together:

$memd->get_or_set('key:941',sub {
  my $val = DB->retrieve(941);
  return ($val, 10)
});

obsessed, honestly. ✨


πŸ¦‹ CUSTOMIZE Sanitizer πŸ¦‹

This module allows you to change the sanitizing behavior through $Cache::Memcached::Fast::Safe::SANITIZE_METHOD. 🌈

The default sanitizer is literally this:

use bytes;
my %escapes = map { chr($_) => sprintf('%%%02X', $_) } (0x00..0x20, 0x7f..0xff);
local $Cache::Memcached::Fast::Safe::SANITIZE_METHOD = sub {
    my $key = shift;
    $key =~ s/([\x00-\x20\x7f-\xff])/$escapes{$1}/ge;
    if ( length $key > 200 ) {
        $key = sha1_hex($key);
    }
    $key;
};

so yeah. it escapes the spooky byte ranges, and if your key gets longer than 200 it just sha1_hexes it and moves on. πŸ’…


πŸ’œ AUTHOR πŸ’œ

Masahiro Nagano <kazeburo {at} gmail.com>

(ty king 🫢)


🌈 SEE ALSO 🌈


πŸ‘‘ LICENSE πŸ‘‘

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. fr fr. πŸŽ€


lowkey a whole vibe, highkey a whole module. ✨

k bye bestie β€” this was the Cache:...::Safe(3pm) page from perl v5.36.0, dated 2023-02-03. πŸ’–πŸŒΈπŸ¦‹πŸ’…

πŸ“¦ where this page comes from