Skip to content

Instantly share code, notes, and snippets.

@adityashedge
Created January 20, 2017 16:09
Show Gist options
  • Save adityashedge/ebbd31daf5cfa59c2c5bc150b644e94f to your computer and use it in GitHub Desktop.
Save adityashedge/ebbd31daf5cfa59c2c5bc150b644e94f to your computer and use it in GitHub Desktop.
Key Server πŸ”‘
require 'sinatra'
require 'json'
BLOCKING_TIME = 60
EXPIRY_TIME = 300
all_keys = {}
blocked_keys = []
available_keys = []
# Generate a key
post '/keys' do
headers 'Content-Type' => 'application/json'
now = Time.now
key = now.to_f.to_s.split(".").join
all_keys[key] = now.to_i
available_keys << key
status 200
end
# Serve an existing available key
get '/key' do
headers 'Content-Type' => 'application/json'
data = {}
if available_keys.count == 0
status 404
else
now = Time.now
key = available_keys.sample
blocked_keys << key
available_keys.delete(key)
all_keys[key] = now.to_i
status 200
data = {key: key, expires_at: (now.to_i + BLOCKING_TIME)}
end
body data.to_json
end
# Delete a key
delete '/keys/:id' do
headers 'Content-Type' => 'application/json'
status(404) and return unless all_keys[params[:id]]
all_keys.delete(params[:id])
available_keys.delete(params[:id])
blocked_keys.delete(params[:id])
status 200
end
# Unblock a key
get '/keys/:id/unblock' do
headers 'Content-Type' => 'application/json'
status(404) and return unless all_keys[params[:id]]
blocked_keys.delete(params[:id])
available_keys << params[:id]
status 200
end
# Status
get '/' do
headers 'Content-Type' => 'application/json'
status 200
data = {all: all_keys, available: available_keys, blocked: blocked_keys}
body data.to_json
end
# Refresh a key
get '/keys/:id/refresh' do
headers 'Content-Type' => 'application/json'
now = Time.now
data = {}
if all_keys[params[:id]]
all_keys[params[:id]] = now.to_i
status 200
data = {key: params[:id], expires_at: (now.to_i + BLOCKING_TIME)}
else
status 404
end
body data.to_json
end
Thread.new do
while true
for key, assignment_time in all_keys do
now = Time.now
# unblock after 60 seconds
if (now.to_i - assignment_time) >= BLOCKING_TIME && blocked_keys.include?(key)
blocked_keys.delete(key)
available_keys << key
end
# delete after 300 seconds
if (now.to_i - assignment_time) >= EXPIRY_TIME
blocked_keys.delete(key)
available_keys.delete(key)
all_keys.delete(key)
end
end
sleep(1)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment