adding simple checksum role
[gitmo/MooseX-Storage.git] / lib / MooseX / Storage / Engine.pm
1
2 package MooseX::Storage::Engine;
3 use Moose;
4
5 our $VERSION = '0.02';
6
7 # the class marker when 
8 # serializing an object. 
9 our $CLASS_MARKER = '__CLASS__';
10
11 has 'storage' => (
12     is      => 'ro',
13     isa     => 'HashRef',
14     default => sub {{}}
15 );
16
17 has 'seen' => (
18     is      => 'ro',
19     isa     => 'HashRef',
20     default => sub {{}}
21 );
22
23 has 'object' => (is => 'rw', isa => 'Object');
24 has 'class'  => (is => 'rw', isa => 'Str');
25
26 ## this is the API used by other modules ...
27
28 sub collapse_object {
29         my $self = shift;
30
31         # NOTE:
32         # mark the root object as seen ...
33         $self->seen->{$self->object} = undef;
34         
35     $self->map_attributes('collapse_attribute');
36     $self->storage->{$CLASS_MARKER} = $self->object->meta->identifier;    
37         return $self->storage;
38 }
39
40 sub expand_object {
41     my ($self, $data, %options) = @_;
42     
43     $options{check_version}   = 1 unless exists $options{check_version};
44     $options{check_authority} = 1 unless exists $options{check_authority};   
45     
46         # NOTE:
47         # mark the root object as seen ...
48         $self->seen->{$data} = undef;    
49     
50     $self->map_attributes('expand_attribute', $data, \%options);
51         return $self->storage;    
52 }
53
54 ## this is the internal API ...
55
56 sub collapse_attribute {
57     my ($self, $attr)  = @_;
58     $self->storage->{$attr->name} = $self->collapse_attribute_value($attr) || return;
59 }
60
61 sub expand_attribute {
62     my ($self, $attr, $data, $options)  = @_;
63     $self->storage->{$attr->name} = $self->expand_attribute_value($attr, $data->{$attr->name}, $options) || return;
64 }
65
66 sub collapse_attribute_value {
67     my ($self, $attr)  = @_;
68         my $value = $attr->get_value($self->object);
69         
70         # NOTE:
71         # this might not be enough, we might 
72         # need to make it possible for the 
73         # cycle checker to return the value
74     $self->check_for_cycle_in_collapse($attr, $value) 
75         if ref $value;
76         
77     if (defined $value && $attr->has_type_constraint) {
78         my $type_converter = $self->find_type_handler($attr->type_constraint);
79         (defined $type_converter)
80             || confess "Cannot convert " . $attr->type_constraint->name;
81         $value = $type_converter->{collapse}->($value);
82     }
83         return $value;
84 }
85
86 sub expand_attribute_value {
87     my ($self, $attr, $value, $options)  = @_;
88
89         # NOTE:
90         # (see comment in method above ^^)
91     $self->check_for_cycle_in_expansion($attr, $value) 
92         if ref $value;    
93     
94     if (defined $value && $attr->has_type_constraint) {
95         my $type_converter = $self->find_type_handler($attr->type_constraint);
96         $value = $type_converter->{expand}->($value, $options);
97     }
98         return $value;
99 }
100
101 # NOTE:
102 # possibly these two methods will 
103 # be used by a cycle supporting 
104 # engine. However, I am not sure 
105 # if I can make a cycle one work 
106 # anyway.
107
108 sub check_for_cycle_in_collapse {
109     my ($self, $attr, $value) = @_;
110     (!exists $self->seen->{$value})
111         || confess "Basic Engine does not support cycles in class(" 
112                  . ($attr->associated_class->name) . ").attr("
113                  . ($attr->name) . ") with $value";
114     $self->seen->{$value} = undef;
115 }
116
117 sub check_for_cycle_in_expansion {
118     my ($self, $attr, $value) = @_;
119     (!exists $self->seen->{$value})
120     || confess "Basic Engine does not support cycles in class(" 
121              . ($attr->associated_class->name) . ").attr("
122              . ($attr->name) . ") with $value";
123     $self->seen->{$value} = undef;
124 }
125
126 # util methods ...
127
128 sub map_attributes {
129     my ($self, $method_name, @args) = @_;
130     map { 
131         $self->$method_name($_, @args) 
132     } grep {
133         # Skip our special skip attribute :)
134         !$_->isa('MooseX::Storage::Meta::Attribute::DoNotSerialize')
135     } ($self->object || $self->class)->meta->compute_all_applicable_attributes;
136 }
137
138 ## ------------------------------------------------------------------
139 ## This is all the type handler stuff, it is in a state of flux
140 ## right now, so this may change, or it may just continue to be 
141 ## improved upon. Comments and suggestions are welcomed.
142 ## ------------------------------------------------------------------
143
144 # NOTE:
145 # these are needed by the 
146 # ArrayRef and HashRef handlers
147 # below, so I need easy access 
148 my %OBJECT_HANDLERS = (
149     expand => sub {
150         my ($data, $options) = @_;   
151         (exists $data->{$CLASS_MARKER})
152             || confess "Serialized item has no class marker";
153         # check the class more thoroughly here ...
154         my ($class, $version, $authority) = (split '-' => $data->{$CLASS_MARKER});
155         my $meta = eval { $class->meta };
156         confess "Class ($class) is not loaded, cannot unpack" if $@;     
157         
158         if ($options->{check_version}) {
159             my $meta_version = $meta->version;
160             if (defined $meta_version && $version) {            
161                 if ($options->{check_version} eq 'allow_less_than') {
162                     ($meta_version <= $version)
163                         || confess "Class ($class) versions is not less than currently available." 
164                                  . " got=($version) available=($meta_version)";                
165                 }
166                 elsif ($options->{check_version} eq 'allow_greater_than') {
167                     ($meta->version >= $version)
168                         || confess "Class ($class) versions is not greater than currently available." 
169                                  . " got=($version) available=($meta_version)";                
170                 }            
171                 else {
172                     ($meta->version == $version)
173                         || confess "Class ($class) versions don't match." 
174                                  . " got=($version) available=($meta_version)";
175                 }
176             }
177         }
178         
179         if ($options->{check_authority}) {
180             my $meta_authority = $meta->authority;
181             ($meta->authority eq $authority)
182                 || confess "Class ($class) authorities don't match." 
183                          . " got=($authority) available=($meta_authority)"
184                 if defined $meta_authority && defined $authority;            
185         }
186             
187         # all is well ...
188         $class->unpack($data);
189     },
190     collapse => sub {
191         my $obj = shift;
192 #        ($obj->can('does') && $obj->does('MooseX::Storage::Basic'))
193 #            || confess "Bad object ($obj) does not do MooseX::Storage::Basic role";
194         $obj->pack();
195     },
196 );
197
198
199 my %TYPES = (
200     # These are boring ones, so they use the identity function ...
201     'Int'      => { expand => sub { shift }, collapse => sub { shift } },
202     'Num'      => { expand => sub { shift }, collapse => sub { shift } },
203     'Str'      => { expand => sub { shift }, collapse => sub { shift } },
204     # These are the trickier ones, (see notes)
205     # NOTE:
206     # Because we are nice guys, we will check 
207     # your ArrayRef and/or HashRef one level 
208     # down and inflate any objects we find. 
209     # But this is where it ends, it is too
210     # expensive to try and do this any more  
211     # recursively, when it is probably not 
212     # nessecary in most of the use cases.
213     # However, if you need more then this, subtype 
214     # and add a custom handler.    
215     'ArrayRef' => { 
216         expand => sub {
217             my $array = shift;
218             foreach my $i (0 .. $#{$array}) {
219                 next unless ref($array->[$i]) eq 'HASH' 
220                          && exists $array->[$i]->{$CLASS_MARKER};
221                 $array->[$i] = $OBJECT_HANDLERS{expand}->($array->[$i])
222             }
223             $array;
224         }, 
225         collapse => sub { 
226             my $array = shift;   
227             # NOTE:         
228             # we need to make a copy cause
229             # otherwise it will affect the 
230             # other real version.
231             [ map {
232                 blessed($_)
233                     ? $OBJECT_HANDLERS{collapse}->($_)
234                     : $_
235             } @$array ] 
236         } 
237     },
238     'HashRef'  => { 
239         expand   => sub {
240             my $hash = shift;
241             foreach my $k (keys %$hash) {
242                 next unless ref($hash->{$k}) eq 'HASH' 
243                          && exists $hash->{$k}->{$CLASS_MARKER};
244                 $hash->{$k} = $OBJECT_HANDLERS{expand}->($hash->{$k})
245             }
246             $hash;            
247         }, 
248         collapse => sub {
249             my $hash = shift;   
250             # NOTE:         
251             # we need to make a copy cause
252             # otherwise it will affect the 
253             # other real version.
254             +{ map {
255                 blessed($hash->{$_})
256                     ? ($_ => $OBJECT_HANDLERS{collapse}->($hash->{$_}))
257                     : ($_ => $hash->{$_})
258             } keys %$hash }            
259         } 
260     },
261     'Object'   => \%OBJECT_HANDLERS,
262     # NOTE:
263     # The sanity of enabling this feature by 
264     # default is very questionable.
265     # - SL
266     #'CodeRef' => {
267     #    expand   => sub {}, # use eval ...
268     #    collapse => sub {}, # use B::Deparse ...        
269     #} 
270 );
271
272 sub add_custom_type_handler {
273     my ($class, $type_name, %handlers) = @_;
274     (exists $handlers{expand} && exists $handlers{collapse})
275         || confess "Custom type handlers need an expand *and* a collapse method";
276     $TYPES{$type_name} = \%handlers;
277 }
278
279 sub remove_custom_type_handler {
280     my ($class, $type_name) = @_;
281     delete $TYPES{$type_name} if exists $TYPES{$type_name};
282 }
283
284 sub find_type_handler {
285     my ($self, $type_constraint) = @_;
286     
287     # this should handle most type usages
288     # since they they are usually just 
289     # the standard set of built-ins
290     return $TYPES{$type_constraint->name} 
291         if exists $TYPES{$type_constraint->name};
292       
293     # the next possibility is they are 
294     # a subtype of the built-in types, 
295     # in which case this will DWIM in 
296     # most cases. It is probably not 
297     # 100% ideal though, but until I 
298     # come up with a decent test case 
299     # it will do for now.
300     foreach my $type (keys %TYPES) {
301         return $TYPES{$type} 
302             if $type_constraint->is_subtype_of($type);
303     }
304     
305     # NOTE:
306     # the reason the above will work has to 
307     # do with the fact that custom subtypes
308     # are mostly used for validation of 
309     # the guts of a type, and not for some
310     # weird structural thing which would 
311     # need to be accomidated by the serializer.
312     # Of course, mst or phaylon will probably  
313     # do something to throw this assumption 
314     # totally out the door ;)
315     # - SL
316     
317     # NOTE:
318     # if this method hasnt returned by now
319     # then we have no been able to find a 
320     # type constraint handler to match 
321     confess "Cannot handle type constraint (" . $type_constraint->name . ")";    
322 }
323
324 1;
325
326 __END__
327
328 =pod
329
330 =head1 NAME
331
332 MooseX::Storage::Engine - The meta-engine to handle collapsing and expanding objects
333
334 =head1 DESCRIPTION
335
336 No user serviceable parts inside. If you really want to know, read the source :)
337
338 =head1 METHODS
339
340 =head2 Accessors
341
342 =over 4
343
344 =item B<class>
345
346 =item B<object>
347
348 =item B<storage>
349
350 =item B<seen>
351
352 =back
353
354 =head2 API
355
356 =over 4
357
358 =item B<expand_object>
359
360 =item B<collapse_object>
361
362 =back
363
364 =head2 ...
365
366 =over 4
367
368 =item B<collapse_attribute>
369
370 =item B<collapse_attribute_value>
371
372 =item B<expand_attribute>
373
374 =item B<expand_attribute_value>
375
376 =item B<check_for_cycle_in_collapse>
377
378 =item B<check_for_cycle_in_expansion>
379
380 =item B<map_attributes>
381
382 =back
383
384 =head2 Type Constraint Handlers
385
386 =over 4
387
388 =item B<find_type_handler>
389
390 =item B<add_custom_type_handler>
391
392 =item B<remove_custom_type_handler>
393
394 =back
395
396 =head2 Introspection
397
398 =over 4
399
400 =item B<meta>
401
402 =back
403
404 =head1 BUGS
405
406 All complex software has bugs lurking in it, and this module is no 
407 exception. If you find a bug please either email me, or add the bug
408 to cpan-RT.
409
410 =head1 AUTHOR
411
412 Chris Prather E<lt>chris.prather@iinteractive.comE<gt>
413
414 Stevan Little E<lt>stevan.little@iinteractive.comE<gt>
415
416 =head1 COPYRIGHT AND LICENSE
417
418 Copyright 2007 by Infinity Interactive, Inc.
419
420 L<http://www.iinteractive.com>
421
422 This library is free software; you can redistribute it and/or modify
423 it under the same terms as Perl itself.
424
425 =cut
426
427
428