summaryrefslogtreecommitdiffstats
path: root/Spline/Data.pm
diff options
context:
space:
mode:
Diffstat (limited to 'Spline/Data.pm')
-rw-r--r--Spline/Data.pm157
1 files changed, 157 insertions, 0 deletions
diff --git a/Spline/Data.pm b/Spline/Data.pm
new file mode 100644
index 0000000..beae3fa
--- /dev/null
+++ b/Spline/Data.pm
@@ -0,0 +1,157 @@
+#!/usr/bin/perl
+=pod
+
+=head1 NAME
+
+Spline::Data - Per Message data
+
+=head1 SYNOPSIS
+
+ use Spline::Data;
+
+ my $data = Spline::Data->new($ctx);
+ my $value = $data->get($key);
+ $data->set($key, $value);
+
+ my $data = Spline::Data->load($ctx);
+
+=head1 DESCRIPTION
+
+=cut
+
+package Spline::Data;
+
+use strict;
+use warnings;
+
+use Spline::Log qw(set_log_context);
+use Data::Dumper;
+
+use base 'Exporter';
+our @EXPORT = qw();
+our @EXPORT_OK = qw();
+
+=head2 _generate_id
+
+ my $id = _gernerate_id();
+
+Generate a random string to tag interleaving log lines belonging to
+the same message.
+
+=cut
+
+sub _generate_id() {
+ my @chars = ('A'..'Z', 'a'..'z', '0'..'9');
+ my $id = '';
+ $id .= $chars[rand @chars] for 1..10;
+
+ return $id;
+};
+
+=head2 new
+
+ my $data = Spline::Data::new($ctx);
+
+=cut
+
+sub new {
+ my $class = shift;
+ my $ctx = shift;
+
+ my $id = _generate_id();
+ my $self = {
+ ctx => $ctx,
+ data => {
+ log_ctx => $id,
+ }
+ };
+ set_log_context($id);
+
+ return bless $self, $class;
+}
+
+=head2 get
+
+ my $value = $data->get($key);
+
+Get the matching value for the supplied key as scalar. If there is no
+such key in the data, return undef.
+
+=cut
+
+sub get($$) {
+ my $self = shift;
+ my $key = shift;
+
+ return $self->{data}->{$key} if defined $self->{data}->{$key};
+ return undef;
+}
+
+=head2 set
+
+ $data->set($key, $value);
+
+Set the supplied value for the key and save the data in the Milter
+context. This method will silently create new keys and overwrite
+possible existent values.
+
+=cut
+
+sub set($$$) {
+ my $self = shift;
+ my ($key, $value) = @_;
+
+ $self->{data}->{$key} = $value;
+ $self->_save();
+}
+
+=head2 _save
+
+ $data->_save();
+
+Save the data in the Milter context.
+
+=cut
+
+sub _save($) {
+ my $self = shift;
+
+ $self->{ctx}->setpriv($self->{data});
+}
+
+=head2 load
+
+ my $data = Spline::Data->load($ctx);
+
+Get the data from the Milter context and return a Spline::Data object.
+The data is saved again after receiving it, so that it will persist
+even if no value is changed.
+
+=cut
+
+sub load {
+ my $class = shift;
+ my $ctx = shift;
+
+ my $self = {
+ ctx => $ctx,
+ data => {},
+ };
+ $self->{data} = $ctx->getpriv();
+ _save($self);
+
+ if (defined $self->{data}->{log_ctx}) {
+ set_log_context($self->{data}->{log_ctx});
+ }
+
+ return bless $self, $class;
+}
+
+=head1 AUTHOR
+
+Alexander Sulfrian <alex@spline.inf.fu-berlin.de>
+
+=cut
+
+1;
+# vim: set et tabstop=4 tw=70: