Created
November 18, 2016 11:22
-
-
Save sleekweasel/b3e2661858932bd5ab80eb4dbdc7ea50 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'socket' | |
# Crappy REDIS for the Linux agents, to avoid having to install redis everywhere. | |
# Would have been better had I realised the manual mode wasn't the standard. | |
# NB: | |
# env.LC_ALL en_US.UTF-8 | |
class SkankyRedis | |
def initialize | |
@db = {} | |
@db_mutex = Mutex.new | |
@server = nil | |
end | |
def stop | |
@server.close if @server | |
@server = nil | |
end | |
# rubocop:disable Style/PerlBackrefs | |
def start | |
@server = TCPServer.new('127.0.0.1', 0) # Default is normally 6379 | |
@port = @server.addr[1] | |
Thread.start do | |
puts "Starting hacky redis server on #{@port}" | |
loop do | |
Thread.start(@server.accept) do |client| | |
begin | |
# puts "new #{client}" | |
while client && (line = client.gets) | |
line.chomp! | |
if line =~ /^\*(\d+)$/ | |
array = [] | |
array_len = $1.to_i | |
# puts "Array[#{$1} = #{array_len}]" | |
array_len.times do | |
line = client.gets.chomp | |
length = line[1..-1].to_i | |
# puts "A[#{array.size}]=#{line}=#{line[1..-1]} = #{length}" | |
data = '' | |
while data.size < length | |
line = client.gets | |
data += line | |
end | |
array << data.chomp | |
end | |
line = array.join(' ') | |
# puts array, line | |
end | |
begin | |
# puts "Respond to #{line}" | |
response = | |
case line.chomp | |
when /^(?i)llen\s+(\S+)$/ | |
llen($1) | |
when /^(?i)rpop\s+(\S+)$/ | |
rpop($1) | |
when /^(?i)lpush\s+(\S+)\s+(.*)$/ | |
lpush($1, $2) | |
when /^quit/ | |
client.close | |
client = nil | |
break | |
else | |
"-Don't know #{line.chomp}" | |
end | |
rescue => e | |
response = "Threw: #{e}" | |
end | |
# puts "Skanky : #{response}" | |
client.puts("#{response}\r") unless response.empty? | |
client.flush if client | |
end | |
client.close if client | |
rescue StandardError => e | |
puts e, caller | |
end | |
end | |
# puts "lost #{client}" | |
end | |
end | |
"redis://localhost:#{@port},skanky" | |
end | |
def lpush(k, vv) | |
@db_mutex.synchronize do | |
vv.split(' ').each do |v| | |
(@db[k] ||= []).push(v =~ /^("?)(.*)\1$/ ? "$#{$2.length}\r\n#{$2}" : v) | |
end | |
":#{@db.fetch(k, []).size}" | |
end | |
end | |
def rpop(k) | |
@db_mutex.synchronize do | |
l = @db.fetch(k, []) | |
l.empty? ? '$-1' : l.shift | |
end | |
end | |
def llen(k) | |
@db_mutex.synchronize do | |
":#{@db.fetch(k, []).size}" | |
end | |
end | |
end | |
# SkankyRedis.new.start.join |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment