jonswar's Journal jonswar's use Perl Journal en-us use Perl; is Copyright 1998-2006, Chris Nandor. Stories, comments, journals, and other submissions posted on use Perl; are Copyright their respective owners. 2012-01-25T02:39:56+00:00 pudge Technology hourly 1 1970-01-01T00:00+00:00 jonswar's Journal Leaving use.perl for This blog has been moved to <a href=""></a>. Hope to see you there! jonswar 2009-06-26T13:57:45+00:00 journal Auto-wrapping subclass methods <p>Back in Feb I asked on various lists how I could auto-wrap CHI driver methods, but didn't get any completely satisfying answers:</p><p><div class="quote"><p>CHI drivers implement methods like remove() and clear(). If you call $cache-&gt;remove(), it goes directly to the driver subclass.</p><p>The problem is that there are now legitimate reasons to "wrap" these methods at the CHI/ superclass level (meaning, do something before and/or after the method). For example, I want to add an optional generic size-awareness feature (the cache can keep track of its own size), which means that we have to adjust size whenever remove() and clear() are called. And I want to log remove() calls the way we currently log get() and set().</p><p>So one solution is to define remove() and clear() in CHI/, and have them call _remove() and _clear() in the driver subclasses. But this kind of change makes me uneasy for several reasons:</p><ul> <li>It changes the driver API, i.e. all existing drivers out there have to modified. And we might have to change it again as we identify new methods to wrap.</li><li>The list of 'normal' versus 'underscore' methods becomes rather arbitrary - it's "whatever we've needed to wrap so far".</li></ul></div><p>I thought about using regular wrapping modules, like Sub::Prepend or Hook::LexWrap. But this fails when you have subclasses more than one level deep. e.g.:</p><blockquote><div><p><small> <tt>CHI::Driver -&gt; CHI::Driver::Foo -&gt; CHI::Driver::Foo::Bar</tt></small></p></div> </blockquote><p> Now if you call CHI::Driver::Foo::Bar::remove(), the wrapping code will get called twice, once for each subclass. I only want it to be called once regardless of how deep the subclass is. </p><p>Here's how I solved this in CHI-0.2. When each CHI driver is used for the first time, e.g. CHI::Driver::Memory:</p><blockquote><div><p><small> <tt>my $cache = CHI-&gt;new('Memory');</tt></small></p></div> </blockquote><p>CHI autogenerates a new class called CHI::Wrapped::CHI::Driver::Memory, which inherits from</p><blockquote><div><p><small> <tt>('CHI::Driver::Wrapper', 'CHI::Driver::Memory')</tt></small></p></div> </blockquote><p>then blesses the actual cache object (and future cache objects of this driver) as CHI::Wrapped::CHI::Driver::Memory.</p><p>Now, when someone calls a method like $cache-&gt;get() or $cache-&gt;remove(), CHI::Driver::Wrapper has an opportunity to handle it first, and then pass control to CHI::Driver::Memory. If not, it goes directly to CHI::Driver::Memory.</p><p>I was unable to find this solution on CPAN, even though I feel like I must be reinventing the wheel. If someone knows of a distribution that encapsulates this technique, please let me know.</p><p>Here's the code from <a href="">CHI::Driver::Wrapper</a> that creates the wrapper class:</p><blockquote><div><p><small> <tt>sub create_wrapped_driver_class {<br>&nbsp; &nbsp; my ( $proto, $driver_class ) = @_;<br>&nbsp; &nbsp; carp "internal class method" if ref($proto);<br> <br>&nbsp; &nbsp; if ( !$wrapped_driver_classes{$driver_class} ) {<br>&nbsp; &nbsp; &nbsp; &nbsp; my $wrapped_driver_class&nbsp; &nbsp; &nbsp; = "CHI::Wrapped::$driver_class";<br>&nbsp; &nbsp; &nbsp; &nbsp; my $wrapped_driver_class_decl = join( "\n",<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "package $wrapped_driver_class;",<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "use strict;",<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "use warnings;",<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "use base qw(CHI::Driver::Wrapper $driver_class);",<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "sub driver_class { '$driver_class' }",<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "1;" );<br>&nbsp; &nbsp; &nbsp; &nbsp; eval($wrapped_driver_class_decl);&nbsp; &nbsp; ## no critic ProhibitStringyEval<br>&nbsp; &nbsp; &nbsp; &nbsp; die $@ if $@;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ## no critic RequireCarping<br>&nbsp; &nbsp; &nbsp; &nbsp; $wrapped_driver_classes{$driver_class} = $wrapped_driver_class;<br>&nbsp; &nbsp; }<br>&nbsp; &nbsp; return $wrapped_driver_classes{$driver_class};<br>}</tt></small></p></div> </blockquote><p>And here's the first application of auto-wrapping: when certain methods are called on a cache, automatically call them on the <a href="">subcaches</a>, if any.</p><blockquote><div><p><small> <tt># Call these methods first on the main cache, then on any subcaches.<br>#<br>foreach my $method (qw(remove expire expire_if clear purge)) {<br>&nbsp; &nbsp; no strict 'refs';<br>&nbsp; &nbsp; *{ __PACKAGE__ . "::$method" } = sub {<br>&nbsp; &nbsp; &nbsp; &nbsp; my $self = shift;<br>&nbsp; &nbsp; &nbsp; &nbsp; my $retval = $self-&gt;call_native_driver( $method, @_ );<br>&nbsp; &nbsp; &nbsp; &nbsp; $self-&gt;call_method_on_subcaches( $method, @_ );<br>&nbsp; &nbsp; &nbsp; &nbsp; return $retval;<br>&nbsp; &nbsp; };<br>}<br> <br># Call the specified $method on the native driver class, e.g. CHI::Driver::Memory.&nbsp; SUPER<br># cannot be used because it refers to the superclass(es) of the current package and not to<br># the superclass(es) of the object - see perlobj.<br>#<br>sub call_native_driver {<br>&nbsp; &nbsp; my $self&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;= shift;<br>&nbsp; &nbsp; my $method&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;= shift;<br>&nbsp; &nbsp; my $native_driver_method = join( "::", $self-&gt;driver_class, $method );<br>&nbsp; &nbsp; $self-&gt;$native_driver_method(@_);<br>}</tt></small></p></div> </blockquote> jonswar 2009-04-27T02:45:18+00:00 journal CHI 0.2 - Subcaches <p>I've just released CHI 0.2. The main visible change is that multi-level caches have been fleshed out and made easier to use.</p><p>There are two kinds of multi-level relationships that I wanted to be able to express easily with CHI:</p><ul> <li>L1 (level 1) cache: Sits in front of the primary cache in order faster access for commonly accessed cache entries. i.e. a cache for your cache.</li><li><p> Mirror cache: Sits behind the primary cache and, over time, mirrors its contents. Useful for migrating from one cache to another without a sudden performance hit.</p></li> </ul><p>Initially CHI had a Multilevel driver that would let you place two or more caches inside a container cache object. The problem was that adding an L1 to an existing cache required changing it to a Multilevel cache, causing existing driver-specific calls to fail. (e.g. If I change a File cache to a Multilevel cache, File-specific methods will no longer get handled right.)</p><p>In 0.2 I switched to a primary cache / subcache model, which seems more appropriate. Now the File cache has an L1 subcache, and File-specific methods (as well as many ancillary methods on which the L1 relationship has no clear meaning) simply go to the primary cache.</p><p>The usage is also simpler. Here we place an in-process Memory cache in front a Memcached cache:</p><blockquote><div><p> <tt>&nbsp; &nbsp; my $cache = CHI-&gt;new(<br>&nbsp; &nbsp; &nbsp; &nbsp; driver&nbsp; &nbsp;=&gt; 'Memcached',<br>&nbsp; &nbsp; &nbsp; &nbsp; servers&nbsp; =&gt; [ "", "" ],<br>&nbsp; &nbsp; &nbsp; &nbsp; l1_cache =&gt; { driver =&gt; 'Memory' }<br>&nbsp; &nbsp; );</tt></p></div> </blockquote><p>Note that there isn't a way yet to specify a size limit for the memory cache, which would make this a lot more self-maintaining.<nobr> <wbr></nobr>:) That's coming soon. In the meantime, I'm planning to use this for an unlimited request-based cache, clearing it manually at the end of each web request:</p><blockquote><div><p> <tt>&nbsp; &nbsp; $cache-&gt;l1_cache-&gt;clear();</tt></p></div> </blockquote><p>Here we prepare to migrate from an old to a new cache directory:</p><blockquote><div><p> <tt>&nbsp; &nbsp; my $cache = CHI-&gt;new(<br>&nbsp; &nbsp; &nbsp; &nbsp; driver&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; =&gt; 'File',<br>&nbsp; &nbsp; &nbsp; &nbsp; root_dir&nbsp; &nbsp; &nbsp; &nbsp; =&gt; '/old/cache/root',<br>&nbsp; &nbsp; &nbsp; &nbsp; mirror_cache =&gt; { driver =&gt; 'File', root_dir =&gt; '/new/cache/root' },<br>&nbsp; &nbsp; );</tt></p></div> </blockquote><p>We leave this running for a few hours (or as needed), then replace it with</p><blockquote><div><p> <tt>&nbsp; &nbsp; my $cache = CHI-&gt;new(<br>&nbsp; &nbsp; &nbsp; &nbsp; driver&nbsp; &nbsp;=&gt; 'File',<br>&nbsp; &nbsp; &nbsp; &nbsp; root_dir =&gt; '/new/cache/root'<br>&nbsp; &nbsp; );</tt></p></div> </blockquote><p>More details in the Subcaches section of the CHI 0.2 documentation.</p> jonswar 2009-04-26T04:19:03+00:00 journal 2 problems with typical perl cache usage (and 5 solutions) A typical cache usage pattern looks like this:<blockquote><div><p> <tt>&nbsp; &nbsp;# Try to get the value from the cache<br>&nbsp; &nbsp;my $result = $cache-&gt;get('key');<br> <br>&nbsp; &nbsp;# If it isn't there, compute and set in the cache<br>&nbsp; &nbsp;if (!defined($result)) {<br>&nbsp; &nbsp; &nbsp; my $result = do_something_to_compute_result();<br>&nbsp; &nbsp; &nbsp; $cache-&gt;set('key', $result, $expiration_time);<br>&nbsp; &nbsp;}</tt></p></div> </blockquote><p>This pattern is popular because it is easy to wrap around existing code, and easy to understand.</p><p>Unfortunately, it suffers from two problems:</p><ul> <li> <p> <b>Miss Stampedes</b>: When a cache item expires at the specified time, any processes trying to get it will start to recompute it. If it is a popular cache item and if recomputation is expensive, you may get many recomputations for the same item, which is at best wasteful and at worst can bog down a server.</p><p>I originally recognized this problem while working on Mason's <a href="">busy locking</a>, but am obviously not alone in experiencing it. The term "miss stampede" comes from this <a href="">memcached list discussion</a> - definitely worth a read.</p></li><li> <p> <b>Recomputation Latency</b>: When a cache item is recomputed, the client (whether that be a browser, command-line, whatever) has to wait for the computation to complete. Since caching keeps average latencies down, there is a tendency to ignore the unfortunate customer that gets stuck with one or more cache misses.</p></li></ul><p> Here are some ways of tweaking the usage pattern above to address one or both of these problems. I've added the initials of the problems that each one addresses, and mentioned relevant features from <a href=";mode=all">CHI</a>, if any. </p><ul> <li> <b>Probabilistic expiration (MS)</b><p>Instead of specifying a single expiration time, specify a range of time during which expiration might occur. Then each cache <tt>get</tt> makes an independent probabilistic decision as to whether the item has expired. The probability starts out low at the beginning of the range and increases to 1.0 at the end of the range. What this means for popular cache items is that only one or a handful of <tt>get</tt>s will most likely expire at the same time.</p><p>CHI supports this with the <a href="">expires_variance</a> parameter. It may be passed to individual <tt>set</tt> commands or as a default for all <tt>set</tt>s. Personally, I plan to default it to 0.2 or so in almost all my caches.</p><p>Drawbacks: Since this is probabilistic, you get no guarantee of how well stampedes will be avoided (if at all), and you have to try to guess the right variance to use.</p></li><li> <b>Busy locks (MS)</b><p>When a cache item expires, flag the item for a short time, either by upping its expiration time or by setting an associated value in the cache. Subsequent misses will see the flag and return the old value instead of duplicating the recompute effort.</p><p>CHI supports this with the <a href="">busy_lock</a> parameter, stolen from Mason. It works by temporarily setting the expiration time forward by the specified amount of time.</p><p>Drawbacks: Setting a busy lock involves a separate write. If you use this feature liberally, you'll double the number of write operations you do. Some backends will suffer from a race condition, a small window of time in which many processes may decide to recompute, before the first lock has been successfully set.</p></li><li> <b>Background recomputation (RL)</b><p>When a cache item expires, return the old value immediately, then kick off a recomputation in the background. This spares the client from the cost of the recompute.</p><p>This requires a non-traditional usage pattern, since the get and set are effectively happening as part of one operation. In CHI it will look like this:</p><blockquote><div><p> <tt>&nbsp; &nbsp; my $result =<br>&nbsp; &nbsp; &nbsp; $cache-&gt;compute( 'key', sub { do_something_to_compute_result() },<br>&nbsp; &nbsp; &nbsp; &nbsp; $expiration_time );</tt></p></div> </blockquote><p>CHI already has a working <a href="">compute</a> API, but doesn't yet know how to run things in the background. Coming soon.</p><p>Drawbacks: Requires a non-traditional and somewhat ugly code pattern; background processes are harder to track and debug.</p></li> <li> <b>External recomputation (MS + RL)</b><p>Recompute cache items entirely from an external process, either when change events occur or when items approach their expiration time. Items never actually expire as the result of a client request. This is the most efficient and client-friendly solution, if you can manage it.</p><p>Drawbacks: Requires extra external processes (more moving parts). Code to recompute caches must be available from the external process, which can result in some unwanted code separation, API contortions, or repetition. It is also difficult to know which items to keep repopulating, and when exactly to recompute them.</p></li><li> <b>Externally initiated recomputation (MS + RL)</b><p>Use a periodic external process to trigger events that will naturally utilize your caches (e.g. write a cron job that hits common pages on your website), but pass a special flag making items more likely to expire. This makes it less likely that expiration will occur during a real client request.</p><p>This is not yet supported in CHI, but the idea would be to add some kind of easily-accessible lever to temporarily view all expiration times as reduced. e.g.</p><blockquote><div><p> <tt>&nbsp; &nbsp; # Reduction ends when $lex goes out of scope<br>&nbsp; &nbsp; my $lex = CHI-&gt;reduced_expirations(0.5);</tt></p></div> </blockquote><p>Drawbacks: Requires extra external processes (more moving parts). Triggers and their run frequencies must be carefully chosen.</p></li></ul><p>What other techniques have you used, and what success/failures have you had with them?</p> jonswar 2008-02-05T01:43:46+00:00 journal CHI: Cache Interface for Perl CHI, a module I've been working on for a few months, has made it to <a href=";mode=all">CPAN</a>:<blockquote><div><p> <tt>&nbsp; &nbsp;file: $CPAN/authors/id/J/JS/JSWARTZ/CHI-0.03.tar.gz<br>&nbsp; &nbsp;size: 62313 bytes<br>&nbsp; &nbsp; md5: ec828f2466ba266e11cd6d1dd5ca2913</tt></p></div> </blockquote><p>CHI provides a unified caching API, designed to assist a developer in persisting data for a specified period of time. It is intended as an evolution of DeWitt Clinton's Cache::Cache package, adhering to the basic Cache API but adding new features and addressing limitations in the Cache::Cache implementation.</p><p>You might think of it as a fledgling "DBI for caching".</p><p>Driver classes already exist for in-process memory, plain files, memory mapped files and memcached. Other drivers such as BerkeleyDB and DBI will be coming soon. Fortunately, implementing drivers is fairly easy, on the order of creating a TIE interface to your data store.</p><p>Special thanks to the <a href="">Hearst Digital Media group</a>, where CHI was first designed and developed, for blessing the open source release of this code.</p><p>There's lots more in store for this module, so stay tuned! Feedback welcome here or on the <a href="">Perl cache mailing list.</a></p> jonswar 2008-01-23T23:57:50+00:00 journal A standard logging API It seems as if every CPAN module has its own way of logging debug information and error conditions. For example:<ul> <li>LWP - activate by use'ing LWP::Debug; outputs to STDERR</li> <li>DBI - activate by calling DBI-&gt;trace(); outputs to STDERR or a file</li> <li>Rose::DB - activate by setting various $Debug package variables; outputs to STDERR</li> <li>Encode::* - activate by modifying various DEBUG subroutines to return 1; outputs using warn()</li> <li>Apache::* - activate by setting the Apache log level and restarting; outputs to the Apache logs</li> </ul><p> In addition, there must be CPAN modules that have interesting things to say but choose not to log at all, because they don't want to invent another logging mechanism or become dependent on an existing one.</p><p> This situation is pretty much the opposite of what I want when developing a large application. I want a single way to turn logging on and off, and to control where logs get sent, for all of the modules I'm using.</p><p> This being Perl, there are many fine logging frameworks available: Log::Log4perl, Log::Dispatch, Log::Handler, Log::Agent, Log::Trivial, etc. So why do CPAN modules eschew the use of these and invent their own mechanisms that are almost guaranteed to be less powerful?</p><ul> <li>The very existence of so many logging modules means that there is no one standard that a CPAN author would feel comfortable binding their users to. As usual, TMTOWTDI is a double-edged sword.</li> <li>A logging framework can be a significant dependency for a module to have, easily dwarfing the size of the module itself. For small modules that want to minimize dependencies, depending on Log4perl (for example) is a non-starter.</li> </ul><p> <b>A Common Log API</b> </p><p> One thing to notice is that while the logging frameworks all differ in their configuration and activation API, and the set of features they support, the API to log messages is generally quite simple. At its core it consists of</p><ul> <li>A set of valid log levels, e.g. debug, info, warn, error, fatal</li> <li>Methods to log a message at a particular level, e.g. $log-&gt;debug()</li> <li>Methods to determine if a particular level is activated, e.g. $log-&gt;is_debug()</li> </ul><p> I expect most CPAN modules would happily stick to this API, and let the application worry about configuring what's getting logged and where it's going. Therefore...</p><p> <b>Proposed Module: Log::Any</b> </p><p> I propose a small module called Log::Any that provides this API, with no dependencies and no logging implementation of its own. Log::Any would be designed to be linked by the main application to an existing logging framework.</p><p> A CPAN module would use it like this:</p><blockquote><div><p> <tt>&nbsp; &nbsp; package Foo;<br>&nbsp; &nbsp; use Log::Any;<br>&nbsp; &nbsp; my $log = Log::Any-&gt;get_logger(category =&gt; __PACKAGE__);<br> <br>&nbsp; &nbsp; $log-&gt;error("an error occurred");<br> <br>&nbsp; &nbsp; $log-&gt;debug("arguments are: " . Dumper(\@_))<br>&nbsp; &nbsp; &nbsp; &nbsp; if $log-&gt;is_debug();</tt></p></div> </blockquote><p>By default, methods like $log-&gt;debug would be no-ops, and methods like $log-&gt;is_debug() would return false.</p><p> As a convenient shorthand, you can use</p><blockquote><div><p> <tt>&nbsp; &nbsp; package Foo;<br>&nbsp; &nbsp; use Log::Any qw($log);</tt></p></div> </blockquote><p>to create the logger, which is equivalent to the first example except that $log is (necessarily) a package-scoped rather than lexical variable.</p><p> How does an application activate logging? The low-level way is to call Log::Any-&gt;set_logger_factory (better name pending) with a single argument: a subroutine that takes a log category and returns a logger object implementing the standard logging API above. The log category is typically the class doing the logging, and it may be ignored.</p><p> For example, to link with Log::Log4perl:</p><blockquote><div><p> <tt>&nbsp; &nbsp; use Log::Any;<br>&nbsp; &nbsp; use Log::Log4perl;<br> <br>&nbsp; &nbsp; Log::Log4perl-&gt;init("log.conf");<br>&nbsp; &nbsp; Log::Any-&gt;set_logger_factory<br>&nbsp; &nbsp; &nbsp; &nbsp;(sub { Log::Log4perl-&gt;get_logger(@_) });</tt></p></div> </blockquote><p>To link with Log::Dispatch, with all categories going to the screen:</p><blockquote><div><p> <tt>&nbsp; &nbsp; use Log::Any;<br>&nbsp; &nbsp; use Log::Dispatch;<br> <br>&nbsp; &nbsp; my $dispatcher = Log::Dispatch::Screen-&gt;new(...);<br>&nbsp; &nbsp; Log::Any-&gt;set_logger_factory(sub { $dispatcher });</tt></p></div> </blockquote><p>To link with Log::Dispatch, with different categories going to different dispatchers:</p><blockquote><div><p> <tt>&nbsp; &nbsp; use Log::Any;<br>&nbsp; &nbsp; use Log::Dispatch;<br> <br>&nbsp; &nbsp; my $dispatcher_screen = Log::Dispatch::Screen-&gt;new(...);<br>&nbsp; &nbsp; my $dispatcher_file&nbsp; &nbsp;= Log::Dispatch::File-&gt;new(...);<br> <br>&nbsp; &nbsp; sub choose_dispatcher {<br>&nbsp; &nbsp; &nbsp; &nbsp; my $category = shift;<br>&nbsp; &nbsp; &nbsp; &nbsp; $category =~<nobr> <wbr></nobr>/DBI|LWP/ ? $dispatcher_file : $dispatcher_screen;<br>&nbsp; &nbsp; }<br>&nbsp; &nbsp; Log::Any-&gt;set_logger_factory(\&amp;choose_dispatcher);</tt></p></div> </blockquote><p>This API is a little awkward for the average user. One solution is for logging frameworks themselves to provide more convenient mixins, e.g.:</p><blockquote><div><p> <tt>&nbsp; &nbsp;use Log::Dispatch;&nbsp; &nbsp;# this also defines Log::Any::use_log_dispatch<br>&nbsp; &nbsp;my $d = Log::Dispatch::File-&gt;new(...);<br>&nbsp; &nbsp;Log::Any-&gt;use_log_dispatch($d);&nbsp; # calls set_logger_factory for you<br> <br>&nbsp; &nbsp;use Log::Log4perl;&nbsp; &nbsp;# this also defines Log::Any::use_log4perl<br>&nbsp; &nbsp;Log::Any-&gt;use_log4perl();&nbsp; &nbsp; &nbsp; &nbsp; # calls set_logger_factory for you</tt></p></div> </blockquote><p>set_logger_factory would be implemented so as to take effect on all existing as well as future loggers. Any $log objects already created inside modules will automatically be switched when set_logger_factory is called. (i.e. $log will probably be a thin proxy object.) This means that Log::Any need not be initialized by the time it is used in CPAN modules, and it allows set_logger_factory to be called more than once per application.</p><p> <b>Promoting Use</b> </p><p> For Log::Any to be useful, a substantial number of modules - especially major modules - would have to adopt its use. Fortunately, with its minimal footprint and standalone nature, authors should not find Log::Any a difficult dependency to add. Existing logging mechanisms, such as LWP::Debug and $DBI::tfh, could easily be converted to write *both* to their existing output streams and to Log::Any. This would preserve backward compatibility for existing applications, but allow new applications to benefit from more powerful logging. I would be willing to submit such patches to major module authors to get things going.</p><p> Feedback welcome. Thanks!</p> jonswar 2007-09-06T21:52:13+00:00 journal