--- /dev/null
+package Newslash::Plugin::Statics;
+use Mojo::Base 'Mojolicious::Plugin';
+
+use constant KEY_PREFIX => "newslash_statics:";
+use constant KEY_REQUEST_COUNTER => "req_count";
+use constant REQUEST_COUNTER_BASE_TIME_FIELD => "base_time";
+
+sub register {
+ my ($self, $app, $conf) = @_;
+ $conf ||= {};
+ $self->{app} = $app;
+ $self->{kvs} = $app->kvs;
+ $self->{options} = $conf->{options} || {};
+
+ $app->hook(after_dispatch=> sub {
+ my $c = shift;
+ my $method = $c->req->method;
+ my $code = $c->res->code;
+ if (!$method || !$code) {
+ $app->log->error("Plugin::Statics: update_request_counter error. method: $method, code: $code");
+ return;
+ }
+ my $rs = $self->update_request_counter($method, $code);
+ if (!defined $rs) {
+ $app->log->error("Plugin::Statics: update_request_counter error. method: $method, code: $code");
+ }
+ #else {
+ # $app->log->info("Plugin::Statics: update_request_counter done. method: $method, code: $code");
+ #}
+ });
+}
+
+sub update_request_counter {
+ my ($self, $method, $code) = @_;
+ my $key = KEY_PREFIX . KEY_REQUEST_COUNTER;
+ my $field_base_time = REQUEST_COUNTER_BASE_TIME_FIELD;
+ my $field = uc($method);
+ return if !$field || !$key;
+
+ my $kvs = $self->{kvs};
+ $kvs->start_transaction;
+
+ if (!$kvs->hexists($key, $field_base_time)) {
+ my $time = $kvs->time;
+ $kvs->hset($key, $field_base_time, $time->[0]);
+ }
+ $kvs->hincrby($key, $field, 1);
+ $kvs->commit;
+ return 1;
+}
+
+
+1;