#!/usr/bin/env perl6 use JSON::Fast ; sub MAIN( :$server='0.0.0.0', :$port=3333, :$dbfile='db' ) { my %db; my %index; my $dbdata = slurp "$dbfile.json" ; my $indexdata = slurp "{$dbfile}_index.json" ; %db = from-json($dbdata) if $dbdata ; %index = from-json($indexdata) if $indexdata ; react { whenever IO::Socket::Async.listen( $server , $port ) -> $conn { whenever $conn.Supply.lines -> $line { my %response = 'status' => '' ; my $msg = from-json $line ; say $msg.perl ; given $msg { when 'set' { %db{ $msg } = $msg ; %response = 'ok' ; %index = $msg ; for %index.keys -> $key { if $msg{$key} { %index{ $key }{ $msg{$key} } = $msg ; %index{ $key }{ $msg{$key} }{ $msg } = 1 ; } } spurt "$dbfile.json", to-json(%db); spurt "{$dbfile}_index.json", to-json(%index); } when 'get' { %response = $msg ; %response = %db{ $msg } ; %response = 'ok' ; } when 'dump' { %response{'data'} = %db ; %response = 'ok' ; } when 'dumpindex' { %response{'data'} = %index ; %response = 'ok' ; } when 'delete' { %db{ $msg }:delete; %response = 'ok' ; spurt "$dbfile.json", to-json(%db); reindex(); } when 'addindex' { %response = 'ok' ; %index{ $msg} =1 ; reindex(); } when 'reportlast' { %response{'data'} = %db{%index} ; %response = 'ok' ; } when 'reportlastindex' { %response = $msg ; for %index{$msg}.keys -> $value { #%response{'data'}.push: %db{ %index{ $msg }{ $value } } ; %response{'data'}{$value} = %db{ %index{ $msg }{ $value } } ; } %response = 'ok' ; } when 'reportindex' { %response = 'ok' ; for %index{$msg}.keys.sort -> $value { for %index{ $msg }{ $value }.keys.sort -> $topic { %response.push: %db{ $topic } ; #%response{$value} = %db{ $topic } ; } } } when 'commit' { spurt "$dbfile.json", to-json(%db); spurt "{$dbfile}_index.json", to-json(%index); %response = 'ok' ; } default { %response = 'error'; %response = 'no function or not supported'; } } $conn.print( to-json(%response, :!pretty) ~ "\n" ) ; LAST { $conn.close ; } QUIT { default { $conn.close ; say "oh no, $_";}} CATCH { default { say .^name, ': ', .Str , " handled in $?LINE";}} } } } sub reindex { %index:delete; for %db.keys -> $topic { my $msg = %db{$topic} ; for %index.keys -> $key { if $msg{$key} { %index{ $key }{ $msg{$key} }{ $topic } = 1 ; } } } spurt "{$dbfile}_index.json", to-json(%index) ; } }