cs_comments_service/app.rb

193 строки
5.2 KiB
Ruby
Исходник Обычный вид История

2012-06-21 02:25:35 +04:00
require 'rubygems'
require 'bundler'
2012-09-03 22:10:35 +04:00
require 'erb'
Bundler.setup
Bundler.require
2012-06-21 02:25:35 +04:00
env_index = ARGV.index("-e")
env_arg = ARGV[env_index + 1] if env_index
2012-07-27 03:58:39 +04:00
environment = env_arg || ENV["SINATRA_ENV"] || "development"
2012-08-18 00:34:53 +04:00
RACK_ENV = environment
module CommentService
class << self
attr_accessor :config
attr_accessor :blocked_hashes
end
API_VERSION = 'v1'
API_PREFIX = "/api/#{API_VERSION}"
end
if ENV["ENABLE_GC_PROFILER"]
GC::Profiler.enable
end
2012-09-03 22:10:35 +04:00
application_yaml = ERB.new(File.read("config/application.yml")).result()
CommentService.config = YAML.load(application_yaml).with_indifferent_access
2012-08-22 04:23:47 +04:00
Tire.configure do
url CommentService.config[:elasticsearch_server]
logger STDERR if ENV["ENABLE_ELASTICSEARCH_DEBUGGING"]
2012-08-22 04:23:47 +04:00
end
2012-08-02 03:43:17 +04:00
Mongoid.load!("config/mongoid.yml", environment)
Mongoid.logger.level = Logger::INFO
2015-07-28 01:26:16 +03:00
Mongo::Logger.logger.level = ENV["ENABLE_MONGO_DEBUGGING"] ? Logger::DEBUG : Logger::INFO
# set up i18n
I18n.load_path += Dir[File.join(File.dirname(__FILE__), 'locale', '*.yml').to_s]
I18n.default_locale = CommentService.config[:default_locale]
2015-07-28 01:26:16 +03:00
I18n.enforce_available_locales = false
I18n::Backend::Simple.send(:include, I18n::Backend::Fallbacks)
use Rack::Locale
helpers do
def t(*args)
I18n.t(*args)
end
end
2012-07-24 00:15:44 +04:00
Dir[File.dirname(__FILE__) + '/lib/**/*.rb'].each {|file| require file}
2012-07-31 01:36:52 +04:00
Dir[File.dirname(__FILE__) + '/models/*.rb'].each {|file| require file}
Dir[File.dirname(__FILE__) + '/presenters/*.rb'].each {|file| require file}
2012-08-04 23:25:46 +04:00
# Ensure elasticsearch index mappings exist.
Comment.put_search_index_mapping
CommentThread.put_search_index_mapping
2013-05-13 01:54:17 +04:00
# Comment out observers until notifications are actually set up properly.
#Dir[File.dirname(__FILE__) + '/models/observers/*.rb'].each {|file| require file}
#Mongoid.observers = PostReplyObserver, PostTopicObserver, AtUserObserver
#Mongoid.instantiate_observers
2012-08-15 05:32:59 +04:00
APIPREFIX = CommentService::API_PREFIX
DEFAULT_PAGE = 1
DEFAULT_PER_PAGE = 20
before do
pass if request.path_info == '/heartbeat'
api_key = CommentService.config[:api_key]
error 401 unless params[:api_key] == api_key or env["HTTP_X_EDX_API_KEY"] == api_key
2012-08-22 00:22:27 +04:00
end
before do
content_type "application/json"
end
2013-12-18 23:56:49 +04:00
# use yajl implementation for to_json.
# https://github.com/brianmario/yajl-ruby#json-gem-compatibility-api
#
# In addition to performance advantages over the standard JSON gem,
# this avoids a bug with non-BMP characters. For more info see:
# https://github.com/rails/rails/issues/3727
require 'yajl/json_gem'
# patch json serialization of ObjectIds to work properly with yajl.
# See https://groups.google.com/forum/#!topic/mongoid/MaXFVw7D_4s
2015-07-28 01:26:16 +03:00
# Note that BSON was moved from Moped::BSON::ObjectId to BSON::ObjectId
module BSON
class ObjectId
def to_json
self.to_s.to_json
2013-12-18 23:56:49 +04:00
end
end
end
2015-07-28 01:26:16 +03:00
# Patch json serialization of Time Objects
class Time
# Returns a hash, that will be turned into a JSON object and represent this
# object.
# Note that this was done to prevent milliseconds from showing up in the JSON response thus breaking
# API compatibility for downstream clients.
def to_json(*)
'"' + utc().strftime("%Y-%m-%dT%H:%M:%SZ") + '"'
end
end
2013-12-18 23:56:49 +04:00
2013-05-12 14:32:20 +04:00
# these files must be required in order
2012-08-15 22:32:28 +04:00
require './api/search'
require './api/commentables'
require './api/comment_threads'
require './api/comments'
require './api/users'
require './api/votes'
2012-11-21 01:59:58 +04:00
require './api/flags'
2013-03-14 02:40:21 +04:00
require './api/pins'
2012-08-15 22:32:28 +04:00
require './api/notifications_and_subscriptions'
require './api/notifications'
2012-08-18 00:34:53 +04:00
if RACK_ENV.to_s == "development"
2012-08-15 05:32:59 +04:00
get "#{APIPREFIX}/clean" do
2012-08-16 23:13:44 +04:00
[Delayed::Backend::Mongoid::Job, Comment, CommentThread, User, Notification, Subscription, Activity].each(&:delete_all).each(&:remove_indexes).each(&:create_indexes)
2012-06-21 02:25:35 +04:00
{}.to_json
end
end
2012-07-17 03:35:34 +04:00
2015-07-28 01:26:16 +03:00
error Mongo::Error::InvalidDocument do
error 400, [t(:requested_object_not_found)].to_json
2012-07-27 03:58:39 +04:00
end
2012-07-27 04:17:19 +04:00
error Mongoid::Errors::DocumentNotFound do
error 400, [t(:requested_object_not_found)].to_json
2012-07-17 03:35:34 +04:00
end
2012-07-31 01:36:52 +04:00
error ArgumentError do
error 400, [env['sinatra.error'].message].to_json
end
2015-07-28 01:26:16 +03:00
CommentService.blocked_hashes = Content.mongo_client[:blocked_hash].find(nil, projection: {hash: 1}).map {|d| d["hash"]}
def get_db_is_master
2015-07-28 01:26:16 +03:00
Mongoid::Clients.default.command(isMaster: 1)
end
def get_es_status
res = Tire::Configuration.client.get Tire::Configuration.url
JSON.parse res.body
end
2014-03-19 22:30:30 +04:00
get '/heartbeat' do
2014-03-19 22:30:30 +04:00
# mongo is reachable and ready to handle requests
db_ok = false
begin
res = get_db_is_master
2015-07-28 01:26:16 +03:00
db_ok = res.ok? && res.documents.first['ismaster'] == true
rescue
2014-03-19 22:30:30 +04:00
end
error 500, JSON.generate({"OK" => false, "check" => "db"}) unless db_ok
2014-03-19 22:30:30 +04:00
# E_S is reachable and ready to handle requests
es_ok = false
begin
es_status = get_es_status
es_ok = es_status["status"] == 200
rescue
2014-03-19 22:30:30 +04:00
end
error 500, JSON.generate({"OK" => false, "check" => "es"}) unless es_ok
2014-03-19 22:30:30 +04:00
JSON.generate({"OK" => true})
2014-03-19 22:30:30 +04:00
end
get '/selftest' do
begin
t1 = Time.now
status = {
"db" => get_db_is_master,
"es" => get_es_status,
"last_post_created" => (Content.last.created_at rescue nil),
"total_posts" => Content.count,
"total_users" => User.count,
"elapsed_time" => Time.now - t1
}
JSON.generate(status)
rescue => ex
[ 500,
{'Content-Type' => 'text/plain'},
"#{ex.backtrace.first}: #{ex.message} (#{ex.class})\n\t#{ex.backtrace[1..-1].join("\n\t")}"
]
end
2015-07-28 01:26:16 +03:00
end