From d8413dbe9eb4acf8a8ae34c2b7438ffbd084687e Mon Sep 17 00:00:00 2001 From: Joe Anderson Date: Thu, 25 Mar 2021 21:07:18 +0000 Subject: [PATCH] Initial commit --- .github/workflows/main.yml | 14 +- .gitignore | 29 +++- .ruby-version | 1 + Dockerfile | 17 ++- Gemfile | 41 +++++- Gemfile.lock | 124 +++++++++++++++--- LICENSE | 24 ---- README.md | 79 ++--------- Rakefile | 6 + app.rb | 64 --------- app/controllers/application_controller.rb | 2 + .../controllers/concerns/.keep | 0 app/controllers/hits_controller.rb | 57 ++++++++ app/javascript/.keep | 0 app/models/app.rb | 3 + app/models/application_record.rb | 3 + app/models/concerns/.keep | 0 app/models/hit.rb | 3 + app/models/nonce.rb | 11 ++ bin/bundle | 114 ++++++++++++++++ bin/rails | 4 + bin/rake | 4 + bin/setup | 33 +++++ conf/apps | 1 - config.ru | 7 +- config/application.rb | 40 ++++++ config/boot.rb | 3 + config/credentials.yml.enc | 1 + config/database.yml | 86 ++++++++++++ config/environment.rb | 5 + config/environments/development.rb | 58 ++++++++ config/environments/production.rb | 96 ++++++++++++++ config/environments/test.rb | 49 +++++++ .../application_controller_renderer.rb | 8 ++ config/initializers/backtrace_silencers.rb | 8 ++ config/initializers/cors.rb | 16 +++ .../initializers/filter_parameter_logging.rb | 6 + config/initializers/inflections.rb | 16 +++ config/initializers/mime_types.rb | 4 + config/initializers/wrap_parameters.rb | 14 ++ config/locales/en.yml | 33 +++++ config/puma.rb | 43 ++++++ config/routes.rb | 5 + db/migrate/20210325164906_create_apps.rb | 10 ++ db/migrate/20210325171139_create_hits.rb | 12 ++ db/migrate/20210325182747_create_nonces.rb | 8 ++ db/schema.rb | 37 ++++++ db/seeds.rb | 7 + docker-compose.yml | 23 ++++ docker/entrypoint-web.sh | 15 +++ lib/tasks/.keep | 0 log/.keep | 0 public/robots.txt | 1 + tmp/.keep | 0 tmp/pids/.keep | 0 vendor/.keep | 0 56 files changed, 1058 insertions(+), 187 deletions(-) create mode 100644 .ruby-version delete mode 100644 LICENSE create mode 100644 Rakefile delete mode 100644 app.rb create mode 100644 app/controllers/application_controller.rb rename db/.deleteme => app/controllers/concerns/.keep (100%) create mode 100644 app/controllers/hits_controller.rb create mode 100644 app/javascript/.keep create mode 100644 app/models/app.rb create mode 100644 app/models/application_record.rb create mode 100644 app/models/concerns/.keep create mode 100644 app/models/hit.rb create mode 100644 app/models/nonce.rb create mode 100755 bin/bundle create mode 100755 bin/rails create mode 100755 bin/rake create mode 100755 bin/setup delete mode 100644 conf/apps create mode 100644 config/application.rb create mode 100644 config/boot.rb create mode 100644 config/credentials.yml.enc create mode 100644 config/database.yml create mode 100644 config/environment.rb create mode 100644 config/environments/development.rb create mode 100644 config/environments/production.rb create mode 100644 config/environments/test.rb create mode 100644 config/initializers/application_controller_renderer.rb create mode 100644 config/initializers/backtrace_silencers.rb create mode 100644 config/initializers/cors.rb create mode 100644 config/initializers/filter_parameter_logging.rb create mode 100644 config/initializers/inflections.rb create mode 100644 config/initializers/mime_types.rb create mode 100644 config/initializers/wrap_parameters.rb create mode 100644 config/locales/en.yml create mode 100644 config/puma.rb create mode 100644 config/routes.rb create mode 100644 db/migrate/20210325164906_create_apps.rb create mode 100644 db/migrate/20210325171139_create_hits.rb create mode 100644 db/migrate/20210325182747_create_nonces.rb create mode 100644 db/schema.rb create mode 100644 db/seeds.rb create mode 100644 docker-compose.yml create mode 100755 docker/entrypoint-web.sh create mode 100644 lib/tasks/.keep create mode 100644 log/.keep create mode 100644 public/robots.txt create mode 100644 tmp/.keep create mode 100644 tmp/pids/.keep create mode 100644 vendor/.keep diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index ea7b7ef..aebabc9 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -2,7 +2,7 @@ name: ci on: push: - branches: master + branches: main jobs: main: @@ -17,6 +17,14 @@ jobs: - name: Set up Docker Buildx uses: docker/setup-buildx-action@v1 + - + name: Cache Docker layers + uses: actions/cache@v2 + with: + path: /tmp/.buildx-cache + key: ${{ runner.os }}-buildx-${{ github.sha }} + restore-keys: | + ${{ runner.os }}-buildx- - name: Login to registry uses: docker/login-action@v1 @@ -31,7 +39,9 @@ jobs: context: . file: ./Dockerfile push: true - tags: ${{ secrets.REGISTRY_URL }}/not-analytics:latest + tags: ${{ secrets.REGISTRY_URL }}/not-analytics-2:latest + cache-from: type=local,src=/tmp/.buildx-cache + cache-to: type=local,dest=/tmp/.buildx-cache - name: Image digest run: echo ${{ steps.docker_build.outputs.digest }} diff --git a/.gitignore b/.gitignore index 4c9bcea..c9cfef5 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,28 @@ -db/*.yml +# See https://help.github.com/articles/ignoring-files for more about ignoring files. +# +# If you find yourself ignoring temporary files generated by your text editor +# or operating system, you probably want to add a global ignore instead: +# git config --global core.excludesfile '~/.gitignore_global' + +# Ignore bundler config. +/.bundle + +# Ignore the default SQLite database. +/db/*.sqlite3 +/db/*.sqlite3-* + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +# Ignore pidfiles, but keep the directory. +/tmp/pids/* +!/tmp/pids/ +!/tmp/pids/.keep + +.byebug_history + +# Ignore master key for decrypting credentials and more. +/config/master.key diff --git a/.ruby-version b/.ruby-version new file mode 100644 index 0000000..4a36342 --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +3.0.0 diff --git a/Dockerfile b/Dockerfile index 3c5d490..01b15cc 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,9 +1,18 @@ -FROM ruby:2.7.1 +FROM ruby:3.0.0-alpine + +RUN apk add --update --no-cache bash build-base tzdata postgresql-dev git WORKDIR /code -COPY . /code + +COPY Gemfile Gemfile.lock /code/ RUN bundle install -EXPOSE 8080 +COPY . /code/ + +COPY docker/entrypoint-web.sh /usr/bin/ +RUN chmod +x /usr/bin/entrypoint-web.sh +ENTRYPOINT ["entrypoint-web.sh"] + +EXPOSE 3000 -CMD ["bundle", "exec", "rackup", "--host", "0.0.0.0", "-p", "8080"] +CMD ["bundle", "exec", "rails", "server", "-b", "0.0.0.0", "-p", "3000"] diff --git a/Gemfile b/Gemfile index c8aa7b2..78feff8 100644 --- a/Gemfile +++ b/Gemfile @@ -1,7 +1,38 @@ -# frozen_string_literal: true +source 'https://rubygems.org' +git_source(:github) { |repo| "https://github.com/#{repo}.git" } -source "https://rubygems.org" +ruby '3.0.0' -gem "rack" -gem "yaml" -gem "activesupport" +# Rails +gem 'activesupport' +gem 'actionpack' +gem 'actionview' +gem 'activemodel' +gem 'activerecord' +gem 'railties' + +# Use postgresql as the database for Active Record +gem 'pg', '~> 1.1' + +# Use Puma as the app server +gem 'puma', '~> 5.0' + +# Use Active Model has_secure_password +# gem 'bcrypt', '~> 3.1.7' + +# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible +# gem 'rack-cors' + +gem 'not_analytics_client', '~> 0.2.0', github: '12joan/not-analytics-client', branch: 'main' + +group :development, :test do + # Call 'byebug' anywhere in the code to stop execution and get a debugger console + gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] +end + +group :development do + gem 'listen', '~> 3.3' +end + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] diff --git a/Gemfile.lock b/Gemfile.lock index 60b93f1..0a71b7a 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,30 +1,120 @@ +GIT + remote: https://github.com/12joan/not-analytics-client.git + revision: 0fbe42e65dd54c4f0c3614fb32d260b67451833d + branch: main + specs: + not_analytics_client (0.2.0) + base64 (~> 0.1) + json (~> 2.5) + net-http (~> 0.1.1) + openssl (~> 2.2) + securerandom (~> 0.1) + GEM remote: https://rubygems.org/ specs: - activesupport (6.0.3.3) + actionpack (6.1.3) + actionview (= 6.1.3) + activesupport (= 6.1.3) + rack (~> 2.0, >= 2.0.9) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.0, >= 1.2.0) + actionview (6.1.3) + activesupport (= 6.1.3) + builder (~> 3.1) + erubi (~> 1.4) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.1, >= 1.2.0) + activemodel (6.1.3) + activesupport (= 6.1.3) + activerecord (6.1.3) + activemodel (= 6.1.3) + activesupport (= 6.1.3) + activesupport (6.1.3) concurrent-ruby (~> 1.0, >= 1.0.2) - i18n (>= 0.7, < 2) - minitest (~> 5.1) - tzinfo (~> 1.1) - zeitwerk (~> 2.2, >= 2.2.2) - concurrent-ruby (1.1.7) - i18n (1.8.5) + i18n (>= 1.6, < 2) + minitest (>= 5.1) + tzinfo (~> 2.0) + zeitwerk (~> 2.3) + base64 (0.1.0) + builder (3.2.4) + byebug (11.1.3) + concurrent-ruby (1.1.8) + crass (1.0.6) + erubi (1.10.0) + ffi (1.15.0) + i18n (1.8.9) concurrent-ruby (~> 1.0) - minitest (5.14.2) + io-wait (0.1.0) + json (2.5.1) + listen (3.5.0) + rb-fsevent (~> 0.10, >= 0.10.3) + rb-inotify (~> 0.9, >= 0.9.10) + loofah (2.9.0) + crass (~> 1.0.2) + nokogiri (>= 1.5.9) + method_source (1.0.0) + minitest (5.14.4) + net-http (0.1.1) + net-protocol + uri + net-protocol (0.1.0) + io-wait + timeout + nio4r (2.5.7) + nokogiri (1.11.2-x86_64-linux) + racc (~> 1.4) + openssl (2.2.0) + pg (1.2.3) + puma (5.2.2) + nio4r (~> 2.0) + racc (1.5.2) rack (2.2.3) - thread_safe (0.3.6) - tzinfo (1.2.7) - thread_safe (~> 0.1) - yaml (0.1.0) - zeitwerk (2.4.0) + rack-test (1.1.0) + rack (>= 1.0, < 3) + rails-dom-testing (2.0.3) + activesupport (>= 4.2.0) + nokogiri (>= 1.6) + rails-html-sanitizer (1.3.0) + loofah (~> 2.3) + railties (6.1.3) + actionpack (= 6.1.3) + activesupport (= 6.1.3) + method_source + rake (>= 0.8.7) + thor (~> 1.0) + rake (13.0.3) + rb-fsevent (0.10.4) + rb-inotify (0.10.1) + ffi (~> 1.0) + securerandom (0.1.0) + thor (1.1.0) + timeout (0.1.1) + tzinfo (2.0.4) + concurrent-ruby (~> 1.0) + uri (0.10.1) + zeitwerk (2.4.2) PLATFORMS - ruby + x86_64-linux DEPENDENCIES + actionpack + actionview + activemodel + activerecord activesupport - rack - yaml + byebug + listen (~> 3.3) + not_analytics_client (~> 0.2.0)! + pg (~> 1.1) + puma (~> 5.0) + railties + tzinfo-data + +RUBY VERSION + ruby 3.0.0p0 BUNDLED WITH - 2.1.4 + 2.2.3 diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 3c577b0..0000000 --- a/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -This is free and unencumbered software released into the public domain. - -Anyone is free to copy, modify, publish, use, compile, sell, or -distribute this software, either in source code form or as a compiled -binary, for any purpose, commercial or non-commercial, and by any -means. - -In jurisdictions that recognize copyright laws, the author or authors -of this software dedicate any and all copyright interest in the -software to the public domain. We make this dedication for the benefit -of the public at large and to the detriment of our heirs and -successors. We intend this dedication to be an overt act of -relinquishment in perpetuity of all present and future rights to this -software under copyright law. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR -OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. - -For more information, please refer to \ No newline at end of file diff --git a/README.md b/README.md index 49e38bb..7db80e4 100644 --- a/README.md +++ b/README.md @@ -1,77 +1,24 @@ -# not Analytics +# README -don't be creepy. +This README would normally document whatever steps are necessary to get the +application up and running. -## Quick start +Things you may want to cover: -```sh -git clone https://github.com/12joan/not-analytics.git && -cd not-analytics && -bundle install && -echo && -echo "Your app id is..." && -cat /dev/urandom | tr -dc 'a-f0-9' | fold -w 32 | head -n 1 | tee conf/apps && # <-- Generate a random app id -echo && -rm db/.deleteme && -rackup --host 0.0.0.0 -p 8080 -``` +* Ruby version -`conf/apps` should contain a list of allowed app ids, one per line. +* System dependencies -## Docker +* Configuration -``` -git clone https://github.com/12joan/not-analytics.git && -docker build --tag not-analytics not-analytics && -mkdir -p $HOME/not-analytics/{db,conf} && -echo && -echo "Your app id is..." && -cat /dev/urandom | tr -dc 'a-f0-9' | fold -w 32 | head -n 1 | tee $HOME/not-analytics/conf/apps && # <-- Generate a random app id -echo && -docker run \ - --rm \ - -d \ - -p 8080:8080 \ - -v $HOME/not-analytics/db:/code/db \ - -v $HOME/not-analytics/conf:/code/conf \ - --name not-analytics \ - not-analytics -``` +* Database creation -## Recording hits +* Database initialization -For every hit you want to track, send a request to the metrics server. +* How to run the test suite -``` -https://metricsserver.com/app_id/path -``` +* Services (job queues, cache servers, search engines, etc.) -For example, to register a hit to `/12joan/not-analytics`, send the following request. - -``` -https://metricsserver.com/14b6a51577c125505e0524226783c895/12joan/not-analytics -``` - -**Please filter out query parameters before pinging the metrics server.** - -## Perusing data - -Hits are logged to `db/app_id.yml` with a resolution of one hour - -```yaml -$ cat db/14b6a51577c125505e0524226783c895.yml ---- -Wed 6 Nov 2019 09:00: - "/about/us": 12 - "/": 31 -Wed 6 Nov 2019 10:00: - "/": 11 -Wed 6 Nov 2019 11:00: - "/": 2 - "/about/us": 2 -``` - -## Privacy - -Consider linking to this GitHub repo in your privacy policy, so that users can see for themselves how their data is collected. +* Deployment instructions +* ... diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..9a5ea73 --- /dev/null +++ b/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative "config/application" + +Rails.application.load_tasks diff --git a/app.rb b/app.rb deleted file mode 100644 index 6a05ec5..0000000 --- a/app.rb +++ /dev/null @@ -1,64 +0,0 @@ -require "yaml/store" -require "active_support/security_utils" - -class App - - attr_reader :request - - def call(env) - @request = Rack::Request.new(env) - - begin - [ 200, {}, [ get ] ] - rescue StandardError => e - puts "Runtime error: #{e}" - puts e.backtrace.join("\n\t") - [ 500, {}, [ "500 error occurred" ] ] - end - end - - attr_reader :app_id, :path, :log_db - - def get - @app_id, @path = request.path.match(/\/([^\/]+)(\/.*)/)&.captures || [nil, nil] - return "invalid app id" unless app_id_valid? - set_log_db - log_request - "ok" - end - - private - - def log_request - log_db.transaction do - log_db[time] ||= {} - log_db[time][path] ||= 0 - log_db[time][path] += 1 - end - end - - def time - Time.now.strftime("%a %e %b %Y %H:00") - end - - def app_id_valid? - whitelisted_ids.any? { |x| ActiveSupport::SecurityUtils.secure_compare(x, app_id) } - end - - def whitelisted_ids - File.readlines(app_id_whitelist_path).map(&:strip).select { |x| x.length > 0 } - end - - def set_log_db - @log_db = YAML::Store.new(db_path, true) - end - - def db_path - File.join("db", app_id + ".yml") - end - - def app_id_whitelist_path - File.join("conf", "apps") - end - -end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb new file mode 100644 index 0000000..4ac8823 --- /dev/null +++ b/app/controllers/application_controller.rb @@ -0,0 +1,2 @@ +class ApplicationController < ActionController::API +end diff --git a/db/.deleteme b/app/controllers/concerns/.keep similarity index 100% rename from db/.deleteme rename to app/controllers/concerns/.keep diff --git a/app/controllers/hits_controller.rb b/app/controllers/hits_controller.rb new file mode 100644 index 0000000..4bf7a3e --- /dev/null +++ b/app/controllers/hits_controller.rb @@ -0,0 +1,57 @@ +class HitsController < ApplicationController + before_action :set_app + before_action :verify_signature + before_action :verify_nonce + + def create + @hit = @app.hits.find_or_create_by( + time: DateTime.now.beginning_of_hour, + event: hit_params[:event], + ) + + Hit.increment_counter(:count, @hit.id) + + render json: { ok: true } + end + + private + + def set_app + @app = App.find(hit_params[:app_id]) + end + + def verify_signature + if @app.key.present? + expected = NotAnalyticsClient::MessageEncryptor.new(@app.key).decrypt_and_verify( + hit_params[:signature], + iv: hit_params[:iv], + auth_tag: hit_params[:auth_tag], + ) + + actual = "#{hit_params[:nonce]}:#{hit_params[:event]}" + + unless expected == actual + render json: { ok: false, error: 'Invalid signature' } + end + end + end + + def verify_nonce + if @app.key.present? + unless Nonce.remember(hit_params[:nonce]) + render json: { ok: false, error: 'Invalid nonce' } + end + end + end + + def hit_params + params.require(:hit).permit( + :app_id, + :event, + :signature, + :iv, + :auth_tag, + :nonce, + ) + end +end diff --git a/app/javascript/.keep b/app/javascript/.keep new file mode 100644 index 0000000..e69de29 diff --git a/app/models/app.rb b/app/models/app.rb new file mode 100644 index 0000000..a0530eb --- /dev/null +++ b/app/models/app.rb @@ -0,0 +1,3 @@ +class App < ApplicationRecord + has_many :hits +end diff --git a/app/models/application_record.rb b/app/models/application_record.rb new file mode 100644 index 0000000..10a4cba --- /dev/null +++ b/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + self.abstract_class = true +end diff --git a/app/models/concerns/.keep b/app/models/concerns/.keep new file mode 100644 index 0000000..e69de29 diff --git a/app/models/hit.rb b/app/models/hit.rb new file mode 100644 index 0000000..e1eecf9 --- /dev/null +++ b/app/models/hit.rb @@ -0,0 +1,3 @@ +class Hit < ApplicationRecord + belongs_to :app +end diff --git a/app/models/nonce.rb b/app/models/nonce.rb new file mode 100644 index 0000000..2c58fc6 --- /dev/null +++ b/app/models/nonce.rb @@ -0,0 +1,11 @@ +class Nonce < ApplicationRecord + def self.remember(id) + nonce = find_or_initialize_by(id: id) + + if nonce.new_record? + nonce.save! + else + return false + end + end +end diff --git a/bin/bundle b/bin/bundle new file mode 100755 index 0000000..a71368e --- /dev/null +++ b/bin/bundle @@ -0,0 +1,114 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'bundle' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require "rubygems" + +m = Module.new do + module_function + + def invoked_as_script? + File.expand_path($0) == File.expand_path(__FILE__) + end + + def env_var_version + ENV["BUNDLER_VERSION"] + end + + def cli_arg_version + return unless invoked_as_script? # don't want to hijack other binstubs + return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update` + bundler_version = nil + update_index = nil + ARGV.each_with_index do |a, i| + if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN + bundler_version = a + end + next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/ + bundler_version = $1 + update_index = i + end + bundler_version + end + + def gemfile + gemfile = ENV["BUNDLE_GEMFILE"] + return gemfile if gemfile && !gemfile.empty? + + File.expand_path("../../Gemfile", __FILE__) + end + + def lockfile + lockfile = + case File.basename(gemfile) + when "gems.rb" then gemfile.sub(/\.rb$/, gemfile) + else "#{gemfile}.lock" + end + File.expand_path(lockfile) + end + + def lockfile_version + return unless File.file?(lockfile) + lockfile_contents = File.read(lockfile) + return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/ + Regexp.last_match(1) + end + + def bundler_version + @bundler_version ||= + env_var_version || cli_arg_version || + lockfile_version + end + + def bundler_requirement + return "#{Gem::Requirement.default}.a" unless bundler_version + + bundler_gem_version = Gem::Version.new(bundler_version) + + requirement = bundler_gem_version.approximate_recommendation + + return requirement unless Gem::Version.new(Gem::VERSION) < Gem::Version.new("2.7.0") + + requirement += ".a" if bundler_gem_version.prerelease? + + requirement + end + + def load_bundler! + ENV["BUNDLE_GEMFILE"] ||= gemfile + + activate_bundler + end + + def activate_bundler + gem_error = activation_error_handling do + gem "bundler", bundler_requirement + end + return if gem_error.nil? + require_error = activation_error_handling do + require "bundler/version" + end + return if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION)) + warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`" + exit 42 + end + + def activation_error_handling + yield + nil + rescue StandardError, LoadError => e + e + end +end + +m.load_bundler! + +if m.invoked_as_script? + load Gem.bin_path("bundler", "bundle") +end diff --git a/bin/rails b/bin/rails new file mode 100755 index 0000000..6fb4e40 --- /dev/null +++ b/bin/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path('../config/application', __dir__) +require_relative "../config/boot" +require "rails/commands" diff --git a/bin/rake b/bin/rake new file mode 100755 index 0000000..4fbf10b --- /dev/null +++ b/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "rake" +Rake.application.run diff --git a/bin/setup b/bin/setup new file mode 100755 index 0000000..5792302 --- /dev/null +++ b/bin/setup @@ -0,0 +1,33 @@ +#!/usr/bin/env ruby +require "fileutils" + +# path to your application root. +APP_ROOT = File.expand_path('..', __dir__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +FileUtils.chdir APP_ROOT do + # This script is a way to set up or update your development environment automatically. + # This script is idempotent, so that you can run it at any time and get an expectable outcome. + # Add necessary setup steps to this file. + + puts '== Installing dependencies ==' + system! 'gem install bundler --conservative' + system('bundle check') || system!('bundle install') + + # puts "\n== Copying sample files ==" + # unless File.exist?('config/database.yml') + # FileUtils.cp 'config/database.yml.sample', 'config/database.yml' + # end + + puts "\n== Preparing database ==" + system! 'bin/rails db:prepare' + + puts "\n== Removing old logs and tempfiles ==" + system! 'bin/rails log:clear tmp:clear' + + puts "\n== Restarting application server ==" + system! 'bin/rails restart' +end diff --git a/conf/apps b/conf/apps deleted file mode 100644 index 3513c74..0000000 --- a/conf/apps +++ /dev/null @@ -1 +0,0 @@ -14b6a51577c125505e0524226783c895 diff --git a/config.ru b/config.ru index fa6acfc..4a3c09a 100644 --- a/config.ru +++ b/config.ru @@ -1,5 +1,6 @@ -require_relative 'app' +# This file is used by Rack-based servers to start the application. -use Rack::ContentLength +require_relative "config/environment" -run App.new +run Rails.application +Rails.application.load_server diff --git a/config/application.rb b/config/application.rb new file mode 100644 index 0000000..3ce07ae --- /dev/null +++ b/config/application.rb @@ -0,0 +1,40 @@ +require_relative "boot" + +require "rails" +# Pick the frameworks you want: +require "active_model/railtie" +# require "active_job/railtie" +require "active_record/railtie" +# require "active_storage/engine" +require "action_controller/railtie" +# require "action_mailer/railtie" +# require "action_mailbox/engine" +# require "action_text/engine" +require "action_view/railtie" +# require "action_cable/engine" +# require "sprockets/railtie" +# require "rails/test_unit/railtie" + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module NotAnalytics + class Application < Rails::Application + # Initialize configuration defaults for originally generated Rails version. + config.load_defaults 6.1 + + # Configuration for the application, engines, and railties goes here. + # + # These settings can be overridden in specific environments using the files + # in config/environments, which are processed later. + # + # config.time_zone = "Central Time (US & Canada)" + # config.eager_load_paths << Rails.root.join("extras") + + # Only loads a smaller set of middleware suitable for API only apps. + # Middleware like session, flash, cookies can be added back manually. + # Skip views, helpers and assets when generating a new resource. + config.api_only = true + end +end diff --git a/config/boot.rb b/config/boot.rb new file mode 100644 index 0000000..d69bd27 --- /dev/null +++ b/config/boot.rb @@ -0,0 +1,3 @@ +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) + +require "bundler/setup" # Set up gems listed in the Gemfile. diff --git a/config/credentials.yml.enc b/config/credentials.yml.enc new file mode 100644 index 0000000..0c59c8b --- /dev/null +++ b/config/credentials.yml.enc @@ -0,0 +1 @@ +c7z6MAMX8mtSNIi5lhlIbnNoA6JQtacgaoQuzqrPeSHYKW4zR7vsx+MTniE/pP1D+pNaR2gyRMrMwHeDpqnm+klORuIXzozuzBlFXiU3bYvqosqF35TYBEYZ2fUJMPwQWgcmpqnapVrN7YAPbpL4qI7Ai8xhPohj6gOcPE35mvtmFK2Xm18WTJETk66of/s/DUiOAVyrpVzytxoMyUKCfPRNq2Ld8lUi1INrwB9nkbjTKjXmLBpeCzAhZaRYhjaQ1bnTExCLSUAtOwuZ0Sg7x9uiyLcZYFv2hjOXNoPaotFRVkDDW7gsKR4U/8Oum6lqkSPPf8xKcBIT0Bd7vdaulR0HsJgMt/cZPjgGNbVFjCVEg2gUJHiSbiIQT/+Cmyv7EzternPCrU0EU6J6ASG5R9e+dJ2aBxR53S9u--fJs3b1i70cVo4kzz--xS9B8JC36h7Dedy8WS5lRQ== \ No newline at end of file diff --git a/config/database.yml b/config/database.yml new file mode 100644 index 0000000..1e810d5 --- /dev/null +++ b/config/database.yml @@ -0,0 +1,86 @@ +# PostgreSQL. Versions 9.3 and up are supported. +# +# Install the pg driver: +# gem install pg +# On macOS with Homebrew: +# gem install pg -- --with-pg-config=/usr/local/bin/pg_config +# On macOS with MacPorts: +# gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config +# On Windows: +# gem install pg +# Choose the win32 build. +# Install PostgreSQL and put its /bin directory on your path. +# +# Configure Using Gemfile +# gem 'pg' +# +default: &default + adapter: postgresql + encoding: unicode + # For details on connection pooling, see Rails configuration guide + # https://guides.rubyonrails.org/configuring.html#database-pooling + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + +development: + <<: *default + database: not_analytics_development + + # The specified database role being used to connect to postgres. + # To create additional roles in postgres see `$ createuser --help`. + # When left blank, postgres will use the default role. This is + # the same name as the operating system user running Rails. + #username: not_analytics + + # The password associated with the postgres role (username). + #password: + + # Connect on a TCP socket. Omitted by default since the client uses a + # domain socket that doesn't need configuration. Windows does not have + # domain sockets, so uncomment these lines. + #host: localhost + + # The TCP port the server listens on. Defaults to 5432. + # If your server runs on a different port number, change accordingly. + #port: 5432 + + # Schema search path. The server defaults to $user,public + #schema_search_path: myapp,sharedapp,public + + # Minimum log levels, in increasing order: + # debug5, debug4, debug3, debug2, debug1, + # log, notice, warning, error, fatal, and panic + # Defaults to warning. + #min_messages: notice + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *default + database: not_analytics_test + +# As with config/credentials.yml, you never want to store sensitive information, +# like your database password, in your source code. If your source code is +# ever seen by anyone, they now have access to your database. +# +# Instead, provide the password or a full connection URL as an environment +# variable when you boot the app. For example: +# +# DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" +# +# If the connection URL is provided in the special DATABASE_URL environment +# variable, Rails will automatically merge its configuration values on top of +# the values provided in this file. Alternatively, you can specify a connection +# URL environment variable explicitly: +# +# production: +# url: <%= ENV['MY_APP_DATABASE_URL'] %> +# +# Read https://guides.rubyonrails.org/configuring.html#configuring-a-database +# for a full overview on how database connection configuration can be specified. +# +production: + <<: *default + database: not_analytics_production + username: not_analytics + password: <%= ENV['TRIANGLES_DATABASE_PASSWORD'] %> diff --git a/config/environment.rb b/config/environment.rb new file mode 100644 index 0000000..cac5315 --- /dev/null +++ b/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative "application" + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/config/environments/development.rb b/config/environments/development.rb new file mode 100644 index 0000000..7db25d6 --- /dev/null +++ b/config/environments/development.rb @@ -0,0 +1,58 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded any time + # it changes. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.cache_classes = false + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable/disable caching. By default caching is disabled. + # Run rails dev:cache to toggle caching. + if Rails.root.join('tmp', 'caching-dev.txt').exist? + config.cache_store = :memory_store + config.public_file_server.headers = { + 'Cache-Control' => "public, max-age=#{2.days.to_i}" + } + else + config.action_controller.perform_caching = false + + config.cache_store = :null_store + end + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + # Highlight code that triggered database queries in logs. + config.active_record.verbose_query_logs = true + + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true + + # Use an evented file watcher to asynchronously detect changes in source code, + # routes, locales, etc. This feature depends on the listen gem. + config.file_watcher = ActiveSupport::EventedFileUpdateChecker + + # Uncomment if you wish to allow Action Cable access from any origin. + # config.action_cable.disable_request_forgery_protection = true +end diff --git a/config/environments/production.rb b/config/environments/production.rb new file mode 100644 index 0000000..3dea1b3 --- /dev/null +++ b/config/environments/production.rb @@ -0,0 +1,96 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.cache_classes = true + + # Eager load code on boot. This eager loads most of Rails and + # your application in memory, allowing both threaded web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. + config.consider_all_requests_local = false + + # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] + # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). + # config.require_master_key = true + + # Disable serving static files from the `/public` folder by default since + # Apache or NGINX already handles this. + config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.asset_host = 'http://assets.example.com' + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache + # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true + + # Include generic and useful information about system operation, but avoid logging too much + # information to avoid inadvertent exposure of personally identifiable information (PII). + config.log_level = :info + + # Prepend all log lines with the following tags. + config.log_tags = [ :request_id ] + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Send deprecation notices to registered listeners. + config.active_support.deprecation = :notify + + # Log disallowed deprecations. + config.active_support.disallowed_deprecation = :log + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # Use default logging formatter so that PID and timestamp are not suppressed. + config.log_formatter = ::Logger::Formatter.new + + # Use a different logger for distributed setups. + # require "syslog/logger" + # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') + + if ENV["RAILS_LOG_TO_STDOUT"].present? + logger = ActiveSupport::Logger.new(STDOUT) + logger.formatter = config.log_formatter + config.logger = ActiveSupport::TaggedLogging.new(logger) + end + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false + + # Inserts middleware to perform automatic connection switching. + # The `database_selector` hash is used to pass options to the DatabaseSelector + # middleware. The `delay` is used to determine how long to wait after a write + # to send a subsequent read to the primary. + # + # The `database_resolver` class is used by the middleware to determine which + # database is appropriate to use based on the time delay. + # + # The `database_resolver_context` class is used by the middleware to set + # timestamps for the last write to the primary. The resolver uses the context + # class timestamps to determine how long to wait before reading from the + # replica. + # + # By default Rails will store a last write timestamp in the session. The + # DatabaseSelector middleware is designed as such you can define your own + # strategy for connection switching and pass that into the middleware through + # these configuration options. + # config.active_record.database_selector = { delay: 2.seconds } + # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver + # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session +end diff --git a/config/environments/test.rb b/config/environments/test.rb new file mode 100644 index 0000000..9fa79dd --- /dev/null +++ b/config/environments/test.rb @@ -0,0 +1,49 @@ +require "active_support/core_ext/integer/time" + +# The test environment is used exclusively to run your application's +# test suite. You never need to work with it otherwise. Remember that +# your test database is "scratch space" for the test suite and is wiped +# and recreated between test runs. Don't rely on the data there! + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + config.cache_classes = true + + # Do not eager load code on boot. This avoids loading your whole application + # just for the purpose of running a single test. If you are using a tool that + # preloads Rails for running tests, you may have to set it to true. + config.eager_load = false + + # Configure public file server for tests with Cache-Control for performance. + config.public_file_server.enabled = true + config.public_file_server.headers = { + 'Cache-Control' => "public, max-age=#{1.hour.to_i}" + } + + # Show full error reports and disable caching. + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + config.cache_store = :null_store + + # Raise exceptions instead of rendering exception templates. + config.action_dispatch.show_exceptions = false + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true +end diff --git a/config/initializers/application_controller_renderer.rb b/config/initializers/application_controller_renderer.rb new file mode 100644 index 0000000..89d2efa --- /dev/null +++ b/config/initializers/application_controller_renderer.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +# ActiveSupport::Reloader.to_prepare do +# ApplicationController.renderer.defaults.merge!( +# http_host: 'example.org', +# https: false +# ) +# end diff --git a/config/initializers/backtrace_silencers.rb b/config/initializers/backtrace_silencers.rb new file mode 100644 index 0000000..33699c3 --- /dev/null +++ b/config/initializers/backtrace_silencers.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. +# Rails.backtrace_cleaner.add_silencer { |line| /my_noisy_library/.match?(line) } + +# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code +# by setting BACKTRACE=1 before calling your invocation, like "BACKTRACE=1 ./bin/rails runner 'MyClass.perform'". +Rails.backtrace_cleaner.remove_silencers! if ENV["BACKTRACE"] diff --git a/config/initializers/cors.rb b/config/initializers/cors.rb new file mode 100644 index 0000000..3b1c1b5 --- /dev/null +++ b/config/initializers/cors.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Avoid CORS issues when API is called from the frontend app. +# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests. + +# Read more: https://github.com/cyu/rack-cors + +# Rails.application.config.middleware.insert_before 0, Rack::Cors do +# allow do +# origins 'example.com' +# +# resource '*', +# headers: :any, +# methods: [:get, :post, :put, :patch, :delete, :options, :head] +# end +# end diff --git a/config/initializers/filter_parameter_logging.rb b/config/initializers/filter_parameter_logging.rb new file mode 100644 index 0000000..4b34a03 --- /dev/null +++ b/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,6 @@ +# Be sure to restart your server when you modify this file. + +# Configure sensitive parameters which will be filtered from the log file. +Rails.application.config.filter_parameters += [ + :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn +] diff --git a/config/initializers/inflections.rb b/config/initializers/inflections.rb new file mode 100644 index 0000000..ac033bf --- /dev/null +++ b/config/initializers/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, '\1en' +# inflect.singular /^(ox)en/i, '\1' +# inflect.irregular 'person', 'people' +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym 'RESTful' +# end diff --git a/config/initializers/mime_types.rb b/config/initializers/mime_types.rb new file mode 100644 index 0000000..dc18996 --- /dev/null +++ b/config/initializers/mime_types.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Add new mime types for use in respond_to blocks: +# Mime::Type.register "text/richtext", :rtf diff --git a/config/initializers/wrap_parameters.rb b/config/initializers/wrap_parameters.rb new file mode 100644 index 0000000..bbfc396 --- /dev/null +++ b/config/initializers/wrap_parameters.rb @@ -0,0 +1,14 @@ +# Be sure to restart your server when you modify this file. + +# This file contains settings for ActionController::ParamsWrapper which +# is enabled by default. + +# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. +ActiveSupport.on_load(:action_controller) do + wrap_parameters format: [:json] +end + +# To enable root element in JSON for ActiveRecord objects. +# ActiveSupport.on_load(:active_record) do +# self.include_root_in_json = true +# end diff --git a/config/locales/en.yml b/config/locales/en.yml new file mode 100644 index 0000000..cf9b342 --- /dev/null +++ b/config/locales/en.yml @@ -0,0 +1,33 @@ +# Files in the config/locales directory are used for internationalization +# and are automatically loaded by Rails. If you want to use locales other +# than English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t 'hello' +# +# In views, this is aliased to just `t`: +# +# <%= t('hello') %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# The following keys must be escaped otherwise they will not be retrieved by +# the default I18n backend: +# +# true, false, on, off, yes, no +# +# Instead, surround them with single quotes. +# +# en: +# 'true': 'foo' +# +# To learn more, please read the Rails Internationalization guide +# available at https://guides.rubyonrails.org/i18n.html. + +en: + hello: "Hello world" diff --git a/config/puma.rb b/config/puma.rb new file mode 100644 index 0000000..d9b3e83 --- /dev/null +++ b/config/puma.rb @@ -0,0 +1,43 @@ +# Puma can serve each request in a thread from an internal thread pool. +# The `threads` method setting takes two numbers: a minimum and maximum. +# Any libraries that use thread pools should be configured to match +# the maximum value specified for Puma. Default is set to 5 threads for minimum +# and maximum; this matches the default thread size of Active Record. +# +max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } +min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count } +threads min_threads_count, max_threads_count + +# Specifies the `worker_timeout` threshold that Puma will use to wait before +# terminating a worker in development environments. +# +worker_timeout 3600 if ENV.fetch("RAILS_ENV", "development") == "development" + +# Specifies the `port` that Puma will listen on to receive requests; default is 3000. +# +port ENV.fetch("PORT") { 3000 } + +# Specifies the `environment` that Puma will run in. +# +environment ENV.fetch("RAILS_ENV") { "development" } + +# Specifies the `pidfile` that Puma will use. +pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } + +# Specifies the number of `workers` to boot in clustered mode. +# Workers are forked web server processes. If using threads and workers together +# the concurrency of the application would be max `threads` * `workers`. +# Workers do not work on JRuby or Windows (both of which do not support +# processes). +# +# workers ENV.fetch("WEB_CONCURRENCY") { 2 } + +# Use the `preload_app!` method when specifying a `workers` number. +# This directive tells Puma to first boot the application and load code +# before forking the application. This takes advantage of Copy On Write +# process behavior so workers use less memory. +# +# preload_app! + +# Allow puma to be restarted by `rails restart` command. +plugin :tmp_restart diff --git a/config/routes.rb b/config/routes.rb new file mode 100644 index 0000000..a751670 --- /dev/null +++ b/config/routes.rb @@ -0,0 +1,5 @@ +Rails.application.routes.draw do + # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html + + post '/', to: 'hits#create' +end diff --git a/db/migrate/20210325164906_create_apps.rb b/db/migrate/20210325164906_create_apps.rb new file mode 100644 index 0000000..3d39fa2 --- /dev/null +++ b/db/migrate/20210325164906_create_apps.rb @@ -0,0 +1,10 @@ +class CreateApps < ActiveRecord::Migration[6.1] + def change + create_table :apps, id: :string do |t| + t.string :name + t.string :key + + t.timestamps + end + end +end diff --git a/db/migrate/20210325171139_create_hits.rb b/db/migrate/20210325171139_create_hits.rb new file mode 100644 index 0000000..20142cd --- /dev/null +++ b/db/migrate/20210325171139_create_hits.rb @@ -0,0 +1,12 @@ +class CreateHits < ActiveRecord::Migration[6.1] + def change + create_table :hits do |t| + t.references :app, type: :string, null: false, foreign_key: true + t.datetime :time, null: false + t.string :event + t.integer :count, default: 0 + end + + Hit.record_timestamps = false + end +end diff --git a/db/migrate/20210325182747_create_nonces.rb b/db/migrate/20210325182747_create_nonces.rb new file mode 100644 index 0000000..5cafd13 --- /dev/null +++ b/db/migrate/20210325182747_create_nonces.rb @@ -0,0 +1,8 @@ +class CreateNonces < ActiveRecord::Migration[6.1] + def change + create_table :nonces, id: :string do |t| + end + + Nonce.record_timestamps = false + end +end diff --git a/db/schema.rb b/db/schema.rb new file mode 100644 index 0000000..250f232 --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,37 @@ +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# This file is the source Rails uses to define your schema when running `bin/rails +# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to +# be faster and is potentially less error prone than running all of your +# migrations from scratch. Old migrations may fail to apply correctly if those +# migrations use external dependencies or application code. +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema.define(version: 2021_03_25_182747) do + + # These are extensions that must be enabled in order to support this database + enable_extension "plpgsql" + + create_table "apps", id: :string, force: :cascade do |t| + t.string "name" + t.string "key" + t.datetime "created_at", precision: 6, null: false + t.datetime "updated_at", precision: 6, null: false + end + + create_table "hits", force: :cascade do |t| + t.string "app_id", null: false + t.datetime "time", null: false + t.string "event" + t.integer "count", default: 0 + t.index ["app_id"], name: "index_hits_on_app_id" + end + + create_table "nonces", id: :string, force: :cascade do |t| + end + + add_foreign_key "hits", "apps" +end diff --git a/db/seeds.rb b/db/seeds.rb new file mode 100644 index 0000000..f3a0480 --- /dev/null +++ b/db/seeds.rb @@ -0,0 +1,7 @@ +# This file should contain all the record creation needed to seed the database with its default values. +# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). +# +# Examples: +# +# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) +# Character.create(name: 'Luke', movie: movies.first) diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..54ee1a3 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,23 @@ +version: '3' + +services: + db: + image: postgres + environment: + POSTGRES_HOST_AUTH_METHOD: trust + volumes: + - pgdata:/var/lib/postgresql/data + + web: + build: . + environment: + DATABASE_URL: postgres://postgres@db + ports: + - "3000:3000" + volumes: + - .:/code + depends_on: + - db + +volumes: + pgdata: diff --git a/docker/entrypoint-web.sh b/docker/entrypoint-web.sh new file mode 100755 index 0000000..bbc8095 --- /dev/null +++ b/docker/entrypoint-web.sh @@ -0,0 +1,15 @@ +#!/bin/bash +set -e + +export TZ="Europe/London" + +rm -f /code/tmp/pids/server.pid + +bundle exec rails db:create +bundle exec rails db:migrate + +if [ "$RAILS_ENV" = "production" ]; then + bundle exec rails assets:precompile +fi + +exec "$@" diff --git a/lib/tasks/.keep b/lib/tasks/.keep new file mode 100644 index 0000000..e69de29 diff --git a/log/.keep b/log/.keep new file mode 100644 index 0000000..e69de29 diff --git a/public/robots.txt b/public/robots.txt new file mode 100644 index 0000000..c19f78a --- /dev/null +++ b/public/robots.txt @@ -0,0 +1 @@ +# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file diff --git a/tmp/.keep b/tmp/.keep new file mode 100644 index 0000000..e69de29 diff --git a/tmp/pids/.keep b/tmp/pids/.keep new file mode 100644 index 0000000..e69de29 diff --git a/vendor/.keep b/vendor/.keep new file mode 100644 index 0000000..e69de29