From e16bfaf435d697181be2d6d68484130dc5d5598c Mon Sep 17 00:00:00 2001 From: Andrey Novikov Date: Tue, 20 Jun 2023 23:09:37 +0900 Subject: [PATCH] Example Rails application to showcase how to use the client --- examples/rails_app/.dockerdev/.bashrc | 1 + examples/rails_app/.dockerdev/Aptfile | 3 + examples/rails_app/.dockerdev/Dockerfile | 67 ++++++ examples/rails_app/.dockerdev/README.md | 84 ++++++++ examples/rails_app/.dockerdev/compose.yml | 89 ++++++++ examples/rails_app/.dockerdev/nats.conf | 6 + examples/rails_app/.gitattributes | 7 + examples/rails_app/.gitignore | 29 +++ examples/rails_app/.ruby-version | 1 + examples/rails_app/Gemfile | 30 +++ examples/rails_app/Gemfile.lock | 194 ++++++++++++++++++ examples/rails_app/README.md | 47 +++++ examples/rails_app/Rakefile | 6 + .../rails_app/app/assets/config/manifest.js | 2 + examples/rails_app/app/assets/images/.keep | 0 .../app/assets/stylesheets/application.css | 15 ++ .../app/controllers/application_controller.rb | 2 + .../rails_app/app/controllers/concerns/.keep | 0 .../app/controllers/test_controller.rb | 10 + .../app/helpers/application_helper.rb | 2 + examples/rails_app/app/helpers/test_helper.rb | 2 + .../app/models/application_record.rb | 3 + examples/rails_app/app/models/concerns/.keep | 0 examples/rails_app/app/models/message.rb | 2 + .../app/views/layouts/application.html.erb | 15 ++ .../rails_app/app/views/test/index.html.erb | 15 ++ examples/rails_app/bin/bundle | 109 ++++++++++ examples/rails_app/bin/nats-listener | 43 ++++ examples/rails_app/bin/rails | 4 + examples/rails_app/bin/rake | 4 + examples/rails_app/bin/setup | 33 +++ examples/rails_app/config.ru | 6 + examples/rails_app/config/application.rb | 38 ++++ examples/rails_app/config/boot.rb | 3 + examples/rails_app/config/credentials.yml.enc | 1 + examples/rails_app/config/database.yml | 25 +++ examples/rails_app/config/environment.rb | 5 + .../config/environments/development.rb | 62 ++++++ .../config/environments/production.rb | 75 +++++++ .../rails_app/config/environments/test.rb | 50 +++++ .../rails_app/config/initializers/assets.rb | 12 ++ .../initializers/filter_parameter_logging.rb | 8 + .../rails_app/config/initializers/nats.rb | 12 ++ examples/rails_app/config/puma.rb | 43 ++++ examples/rails_app/config/routes.rb | 6 + .../migrate/20230620121736_create_messages.rb | 9 + examples/rails_app/db/schema.rb | 20 ++ examples/rails_app/db/seeds.rb | 7 + examples/rails_app/dip.yml | 59 ++++++ examples/rails_app/lib/assets/.keep | 0 examples/rails_app/lib/tasks/.keep | 0 examples/rails_app/log/.keep | 0 examples/rails_app/public/404.html | 67 ++++++ examples/rails_app/public/422.html | 67 ++++++ examples/rails_app/public/500.html | 66 ++++++ .../public/apple-touch-icon-precomposed.png | 0 .../rails_app/public/apple-touch-icon.png | 0 examples/rails_app/public/favicon.ico | 0 examples/rails_app/public/robots.txt | 1 + examples/rails_app/tmp/.keep | 0 examples/rails_app/tmp/pids/.keep | 0 61 files changed, 1467 insertions(+) create mode 100644 examples/rails_app/.dockerdev/.bashrc create mode 100644 examples/rails_app/.dockerdev/Aptfile create mode 100644 examples/rails_app/.dockerdev/Dockerfile create mode 100644 examples/rails_app/.dockerdev/README.md create mode 100644 examples/rails_app/.dockerdev/compose.yml create mode 100644 examples/rails_app/.dockerdev/nats.conf create mode 100644 examples/rails_app/.gitattributes create mode 100644 examples/rails_app/.gitignore create mode 100644 examples/rails_app/.ruby-version create mode 100644 examples/rails_app/Gemfile create mode 100644 examples/rails_app/Gemfile.lock create mode 100644 examples/rails_app/README.md create mode 100644 examples/rails_app/Rakefile create mode 100644 examples/rails_app/app/assets/config/manifest.js create mode 100644 examples/rails_app/app/assets/images/.keep create mode 100644 examples/rails_app/app/assets/stylesheets/application.css create mode 100644 examples/rails_app/app/controllers/application_controller.rb create mode 100644 examples/rails_app/app/controllers/concerns/.keep create mode 100644 examples/rails_app/app/controllers/test_controller.rb create mode 100644 examples/rails_app/app/helpers/application_helper.rb create mode 100644 examples/rails_app/app/helpers/test_helper.rb create mode 100644 examples/rails_app/app/models/application_record.rb create mode 100644 examples/rails_app/app/models/concerns/.keep create mode 100644 examples/rails_app/app/models/message.rb create mode 100644 examples/rails_app/app/views/layouts/application.html.erb create mode 100644 examples/rails_app/app/views/test/index.html.erb create mode 100755 examples/rails_app/bin/bundle create mode 100755 examples/rails_app/bin/nats-listener create mode 100755 examples/rails_app/bin/rails create mode 100755 examples/rails_app/bin/rake create mode 100755 examples/rails_app/bin/setup create mode 100644 examples/rails_app/config.ru create mode 100644 examples/rails_app/config/application.rb create mode 100644 examples/rails_app/config/boot.rb create mode 100644 examples/rails_app/config/credentials.yml.enc create mode 100644 examples/rails_app/config/database.yml create mode 100644 examples/rails_app/config/environment.rb create mode 100644 examples/rails_app/config/environments/development.rb create mode 100644 examples/rails_app/config/environments/production.rb create mode 100644 examples/rails_app/config/environments/test.rb create mode 100644 examples/rails_app/config/initializers/assets.rb create mode 100644 examples/rails_app/config/initializers/filter_parameter_logging.rb create mode 100644 examples/rails_app/config/initializers/nats.rb create mode 100644 examples/rails_app/config/puma.rb create mode 100644 examples/rails_app/config/routes.rb create mode 100644 examples/rails_app/db/migrate/20230620121736_create_messages.rb create mode 100644 examples/rails_app/db/schema.rb create mode 100644 examples/rails_app/db/seeds.rb create mode 100644 examples/rails_app/dip.yml create mode 100644 examples/rails_app/lib/assets/.keep create mode 100644 examples/rails_app/lib/tasks/.keep create mode 100644 examples/rails_app/log/.keep create mode 100644 examples/rails_app/public/404.html create mode 100644 examples/rails_app/public/422.html create mode 100644 examples/rails_app/public/500.html create mode 100644 examples/rails_app/public/apple-touch-icon-precomposed.png create mode 100644 examples/rails_app/public/apple-touch-icon.png create mode 100644 examples/rails_app/public/favicon.ico create mode 100644 examples/rails_app/public/robots.txt create mode 100644 examples/rails_app/tmp/.keep create mode 100644 examples/rails_app/tmp/pids/.keep diff --git a/examples/rails_app/.dockerdev/.bashrc b/examples/rails_app/.dockerdev/.bashrc new file mode 100644 index 0000000..4f233c5 --- /dev/null +++ b/examples/rails_app/.dockerdev/.bashrc @@ -0,0 +1 @@ +alias be="bundle exec" diff --git a/examples/rails_app/.dockerdev/Aptfile b/examples/rails_app/.dockerdev/Aptfile new file mode 100644 index 0000000..bd0c4bc --- /dev/null +++ b/examples/rails_app/.dockerdev/Aptfile @@ -0,0 +1,3 @@ +# An editor to work with credentials +vim + diff --git a/examples/rails_app/.dockerdev/Dockerfile b/examples/rails_app/.dockerdev/Dockerfile new file mode 100644 index 0000000..89ff125 --- /dev/null +++ b/examples/rails_app/.dockerdev/Dockerfile @@ -0,0 +1,67 @@ +# syntax=docker/dockerfile:1 + +ARG RUBY_VERSION +ARG DISTRO_NAME=bullseye + +FROM ruby:$RUBY_VERSION-slim-$DISTRO_NAME + +ARG DISTRO_NAME + +# Common dependencies +# Using --mount to speed up build with caching, see https://github.com/moby/buildkit/blob/master/frontend/dockerfile/docs/reference.md#run---mount +RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \ + --mount=type=cache,target=/var/lib/apt,sharing=locked \ + --mount=type=tmpfs,target=/var/log \ + rm -f /etc/apt/apt.conf.d/docker-clean; \ + echo 'Binary::apt::APT::Keep-Downloaded-Packages "true";' > /etc/apt/apt.conf.d/keep-cache; \ + apt-get update -qq && \ + DEBIAN_FRONTEND=noninteractive apt-get -yq dist-upgrade && \ + DEBIAN_FRONTEND=noninteractive apt-get install -yq --no-install-recommends \ + build-essential \ + gnupg2 \ + curl \ + less \ + git + +ARG NODE_MAJOR +RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \ + --mount=type=cache,target=/var/lib/apt,sharing=locked \ + --mount=type=tmpfs,target=/var/log \ + curl -sL https://deb.nodesource.com/setup_$NODE_MAJOR.x | bash - && \ + DEBIAN_FRONTEND=noninteractive apt-get install -yq --no-install-recommends \ + nodejs + +RUN npm install -g yarn + +# Application dependencies +# We use an external Aptfile for this, stay tuned +RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \ + --mount=type=cache,target=/var/lib/apt,sharing=locked \ + --mount=type=tmpfs,target=/var/log \ + --mount=type=bind,source=Aptfile,target=/tmp/Aptfile \ + DEBIAN_FRONTEND=noninteractive apt-get install -yq --no-install-recommends \ + $(grep -Ev '^\s*#' /tmp/Aptfile | xargs) + +# Configure bundler +ENV LANG=C.UTF-8 \ + BUNDLE_JOBS=4 \ + BUNDLE_RETRY=3 + +# Store Bundler settings in the project's root +ENV BUNDLE_APP_CONFIG=.bundle + +# Uncomment this line if you want to run binstubs without prefixing with `bin/` or `bundle exec` +# ENV PATH /app/bin:$PATH + +# Upgrade RubyGems and install the latest Bundler version +RUN gem update --system && \ + gem install bundler + +# Create a directory for the app code +RUN mkdir -p /app +WORKDIR /app + +# Document that we're going to expose port 3000 +EXPOSE 3000 +# Use Bash as the default command +CMD ["/usr/bin/bash"] diff --git a/examples/rails_app/.dockerdev/README.md b/examples/rails_app/.dockerdev/README.md new file mode 100644 index 0000000..2904081 --- /dev/null +++ b/examples/rails_app/.dockerdev/README.md @@ -0,0 +1,84 @@ +# Docker for Development + +Source: [Ruby on Whales: Dockerizing Ruby and Rails development](https://evilmartians.com/chronicles/ruby-on-whales-docker-for-ruby-rails-development). + +## Installation + +- Docker installed. + +For MacOS just use the [official app](https://docs.docker.com/engine/installation/mac/). + +- [`dip`](https://github.com/bibendi/dip) installed. + +You can install `dip` as Ruby gem: + +```sh +gem install dip +``` + +## Provisioning + +When using Dip it could be done with a single command: + +```sh +dip provision +``` + +## Running + +```sh +dip rails s +``` + +## Developing with Dip + +### Useful commands + +```sh +# run rails console +dip rails c + +# run rails server with debugging capabilities (i.e., `debugger` would work) +dip rails s + +# or run the while web app (with all the dependencies) +dip up web + +# run migrations +dip rails db:migrate + +# pass env variables into application +dip VERSION=20100905201547 rails db:migrate:down + +# simply launch bash within app directory (with dependencies up) +dip runner + +# execute an arbitrary command via Bash +dip bash -c 'ls -al tmp/cache' + +# Additional commands + +# update gems or packages +dip bundle install +dip yarn install + +# run tests +# TIP: `dip rails test` is already auto prefixed with `RAILS_ENV=test` +dip rails test + +# shutdown all containers +dip down +``` + +### Development flow + +Another way is to run `dip ` for every interaction. If you prefer this way and use ZSH, you can reduce the typing +by integrating `dip` into your session: + +```sh +$ dip console | source /dev/stdin +# no `dip` prefix is required anymore! +$ rails c +Loading development environment (Rails 7.0.1) +pry> +``` diff --git a/examples/rails_app/.dockerdev/compose.yml b/examples/rails_app/.dockerdev/compose.yml new file mode 100644 index 0000000..7ff22b6 --- /dev/null +++ b/examples/rails_app/.dockerdev/compose.yml @@ -0,0 +1,89 @@ +x-app: &app + build: + context: . + args: + RUBY_VERSION: '3.2.2' + NODE_MAJOR: '18' + image: railsapp-dev:1.0.0 + environment: &env + NODE_ENV: ${NODE_ENV:-development} + RAILS_ENV: ${RAILS_ENV:-development} + tmpfs: + - /tmp + - /app/tmp/pids + +x-backend: &backend + <<: *app + stdin_open: true + tty: true + volumes: + - ..:/app:cached + - bundle:/usr/local/bundle + - rails_cache:/app/tmp/cache + - assets:/app/public/assets + - node_modules:/app/node_modules + - history:/usr/local/hist + - ./.bashrc:/root/.bashrc:ro + environment: &backend_environment + <<: *env + MALLOC_ARENA_MAX: 2 + WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2} + BOOTSNAP_CACHE_DIR: /usr/local/bundle/_bootsnap + XDG_DATA_HOME: /app/tmp/cache + YARN_CACHE_FOLDER: /app/node_modules/.yarn-cache + HISTFILE: /usr/local/hist/.bash_history + IRB_HISTFILE: /usr/local/hist/.irb_history + EDITOR: vi + TZ: ${TZ:-UTC} + NATS_URL: "nats://nats:4222" + depends_on: + - nats + - redis + +services: + rails: + <<: *backend + command: bundle exec rails + + web: + <<: *backend + command: bundle exec rails server -b 0.0.0.0 + ports: + - '3000:3000' + stdin_open: true + tty: true + + listener: + <<: *backend + command: bin/nats-listener + + sidekiq: + <<: *backend + command: bundle exec sidekiq + environment: + <<: *backend_environment + SIDEKIQ_CONCURRENCY: 5 + + nats: + image: nats:2.9.18 + command: -c /etc/nats.conf -js -sd=/data + ports: + - '4222:4222' + - '8080:8080' + volumes: + - ./nats.conf:/etc/nats.conf:ro + - nats_data:/data + + redis: + image: redis:6.2.5 + ports: + - '6379:6379' + +volumes: + bundle: + node_modules: + history: + rails_cache: + assets: + nats_data: + diff --git a/examples/rails_app/.dockerdev/nats.conf b/examples/rails_app/.dockerdev/nats.conf new file mode 100644 index 0000000..3fbd77d --- /dev/null +++ b/examples/rails_app/.dockerdev/nats.conf @@ -0,0 +1,6 @@ +port 4222 + +websocket { + port: 8080 + no_tls: true +} diff --git a/examples/rails_app/.gitattributes b/examples/rails_app/.gitattributes new file mode 100644 index 0000000..31eeee0 --- /dev/null +++ b/examples/rails_app/.gitattributes @@ -0,0 +1,7 @@ +# See https://git-scm.com/docs/gitattributes for more about git attribute files. + +# Mark the database schema as having been generated. +db/schema.rb linguist-generated + +# Mark any vendored files as having been vendored. +vendor/* linguist-vendored diff --git a/examples/rails_app/.gitignore b/examples/rails_app/.gitignore new file mode 100644 index 0000000..4857d33 --- /dev/null +++ b/examples/rails_app/.gitignore @@ -0,0 +1,29 @@ +# 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 + + +/public/assets + +# Ignore master key for decrypting credentials and more. +/config/master.key diff --git a/examples/rails_app/.ruby-version b/examples/rails_app/.ruby-version new file mode 100644 index 0000000..9e79f6c --- /dev/null +++ b/examples/rails_app/.ruby-version @@ -0,0 +1 @@ +ruby-3.2.2 diff --git a/examples/rails_app/Gemfile b/examples/rails_app/Gemfile new file mode 100644 index 0000000..50ec0dd --- /dev/null +++ b/examples/rails_app/Gemfile @@ -0,0 +1,30 @@ +source "https://rubygems.org" +git_source(:github) { |repo| "https://github.com/#{repo}.git" } + +ruby "3.2.2" + +# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" +gem "rails", "~> 7.0.5" + +# The original asset pipeline for Rails [https://github.com/rails/sprockets-rails] +gem "sprockets-rails" + +# Use sqlite3 as the database for Active Record +gem "sqlite3", "~> 1.4" + +# Use the Puma web server [https://github.com/puma/puma] +gem "puma", "~> 5.0" + +# Background jobs +gem "sidekiq", "~> 7.1" + +# NATS for inter-component messaging +gem "nats-pure", "~> 2.3", github: "Envek/nats-pure.rb", branch: "fix/auto-connect-after-code-reload", require: "nats/client" + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem "tzinfo-data", platforms: %i[ mingw mswin x64_mingw jruby ] + +group :development, :test do + # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem + gem "debug", platforms: %i[ mri mingw x64_mingw ] +end diff --git a/examples/rails_app/Gemfile.lock b/examples/rails_app/Gemfile.lock new file mode 100644 index 0000000..d91760e --- /dev/null +++ b/examples/rails_app/Gemfile.lock @@ -0,0 +1,194 @@ +GIT + remote: https://github.com/Envek/nats-pure.rb.git + revision: 69dc397e8dacf6cc40ebfa7747a50cbb027f2f97 + branch: fix/auto-connect-after-code-reload + specs: + nats-pure (2.3.0) + concurrent-ruby (~> 1.0) + +GEM + remote: https://rubygems.org/ + specs: + actioncable (7.0.5) + actionpack (= 7.0.5) + activesupport (= 7.0.5) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + actionmailbox (7.0.5) + actionpack (= 7.0.5) + activejob (= 7.0.5) + activerecord (= 7.0.5) + activestorage (= 7.0.5) + activesupport (= 7.0.5) + mail (>= 2.7.1) + net-imap + net-pop + net-smtp + actionmailer (7.0.5) + actionpack (= 7.0.5) + actionview (= 7.0.5) + activejob (= 7.0.5) + activesupport (= 7.0.5) + mail (~> 2.5, >= 2.5.4) + net-imap + net-pop + net-smtp + rails-dom-testing (~> 2.0) + actionpack (7.0.5) + actionview (= 7.0.5) + activesupport (= 7.0.5) + rack (~> 2.0, >= 2.2.4) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.0, >= 1.2.0) + actiontext (7.0.5) + actionpack (= 7.0.5) + activerecord (= 7.0.5) + activestorage (= 7.0.5) + activesupport (= 7.0.5) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (7.0.5) + activesupport (= 7.0.5) + builder (~> 3.1) + erubi (~> 1.4) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.1, >= 1.2.0) + activejob (7.0.5) + activesupport (= 7.0.5) + globalid (>= 0.3.6) + activemodel (7.0.5) + activesupport (= 7.0.5) + activerecord (7.0.5) + activemodel (= 7.0.5) + activesupport (= 7.0.5) + activestorage (7.0.5) + actionpack (= 7.0.5) + activejob (= 7.0.5) + activerecord (= 7.0.5) + activesupport (= 7.0.5) + marcel (~> 1.0) + mini_mime (>= 1.1.0) + activesupport (7.0.5) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (>= 1.6, < 2) + minitest (>= 5.1) + tzinfo (~> 2.0) + builder (3.2.4) + concurrent-ruby (1.2.2) + connection_pool (2.4.1) + crass (1.0.6) + date (3.3.3) + debug (1.8.0) + irb (>= 1.5.0) + reline (>= 0.3.1) + erubi (1.12.0) + globalid (1.1.0) + activesupport (>= 5.0) + i18n (1.14.1) + concurrent-ruby (~> 1.0) + io-console (0.6.0) + irb (1.7.0) + reline (>= 0.3.0) + loofah (2.21.3) + crass (~> 1.0.2) + nokogiri (>= 1.12.0) + mail (2.8.1) + mini_mime (>= 0.1.1) + net-imap + net-pop + net-smtp + marcel (1.0.2) + method_source (1.0.0) + mini_mime (1.1.2) + minitest (5.18.1) + net-imap (0.3.6) + date + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.2.1) + timeout + net-smtp (0.3.3) + net-protocol + nio4r (2.5.9) + nokogiri (1.15.2-x86_64-linux) + racc (~> 1.4) + puma (5.6.5) + nio4r (~> 2.0) + racc (1.7.1) + rack (2.2.7) + rack-test (2.1.0) + rack (>= 1.3) + rails (7.0.5) + actioncable (= 7.0.5) + actionmailbox (= 7.0.5) + actionmailer (= 7.0.5) + actionpack (= 7.0.5) + actiontext (= 7.0.5) + actionview (= 7.0.5) + activejob (= 7.0.5) + activemodel (= 7.0.5) + activerecord (= 7.0.5) + activestorage (= 7.0.5) + activesupport (= 7.0.5) + bundler (>= 1.15.0) + railties (= 7.0.5) + rails-dom-testing (2.0.3) + activesupport (>= 4.2.0) + nokogiri (>= 1.6) + rails-html-sanitizer (1.6.0) + loofah (~> 2.21) + nokogiri (~> 1.14) + railties (7.0.5) + actionpack (= 7.0.5) + activesupport (= 7.0.5) + method_source + rake (>= 12.2) + thor (~> 1.0) + zeitwerk (~> 2.5) + rake (13.0.6) + redis-client (0.14.1) + connection_pool + reline (0.3.5) + io-console (~> 0.5) + sidekiq (7.1.2) + concurrent-ruby (< 2) + connection_pool (>= 2.3.0) + rack (>= 2.2.4) + redis-client (>= 0.14.0) + sprockets (4.2.0) + concurrent-ruby (~> 1.0) + rack (>= 2.2.4, < 4) + sprockets-rails (3.4.2) + actionpack (>= 5.2) + activesupport (>= 5.2) + sprockets (>= 3.0.0) + sqlite3 (1.6.3-x86_64-linux) + thor (1.2.2) + timeout (0.3.2) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + websocket-driver (0.7.5) + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + zeitwerk (2.6.8) + +PLATFORMS + x86_64-linux + +DEPENDENCIES + debug + nats-pure (~> 2.3)! + puma (~> 5.0) + rails (~> 7.0.5) + sidekiq (~> 7.1) + sprockets-rails + sqlite3 (~> 1.4) + tzinfo-data + +RUBY VERSION + ruby 3.2.2p53 + +BUNDLED WITH + 2.4.14 diff --git a/examples/rails_app/README.md b/examples/rails_app/README.md new file mode 100644 index 0000000..bef1c91 --- /dev/null +++ b/examples/rails_app/README.md @@ -0,0 +1,47 @@ +# Example Rails application for NATS Ruby client + +This is a simple Rails application that demonstrates how to use NATS Ruby client withing Rails application. + +Files of interest: + + - [`config/initializers/nats.rb`](./config/initializers/nats.rb) — initialization of the NATS client early using lazy connection. + - [`app/controllers/test_controller.rb`](./app/controllers/test_controller.rb) — example of the controller. + - [`bin/nats-listener`](./bin/nats-listener()) — example of the separate standalone process. + +Main client features shown in the example: + + - Thread-safety and fork handling: it is totally fine to use “global” NATS client instance without any connection pooling. + - Rails development mode code reloading and resource handling: no more server restarts on changes and leaked database connections. + +A (somewhat artificial) distributed workflow: + + - User fills the form and submits it. + - The form is broadcasted via NATS using “global” NATS client instantiated in the web application server “master” process, but usable in worker processes. + - Special long running process (listener) subscribes to the broadcasted messages and saves them to the database. + - User will eventually see saved messages on the page with the form. + +## Installation + +This app has a Docker-first configuration based one the [Ruby on Whales post](https://evilmartians.com/chronicles/ruby-on-whales-docker-for-ruby-rails-development). + +You need: + +- Docker installed. For MacOS just use [official app](https://docs.docker.com/engine/installation/mac/). + +- [Dip](https://github.com/bibendi/dip) installed. + +Run the following command to build images and provision the application: + +```sh +dip provision +``` + +## Running + +You can start Rails server along with AnyCable by running: + +```sh +dip up web listener +``` + +Then go to [http://localhost:3000/](http://localhost:3000/) and see the application in action. diff --git a/examples/rails_app/Rakefile b/examples/rails_app/Rakefile new file mode 100644 index 0000000..9a5ea73 --- /dev/null +++ b/examples/rails_app/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/examples/rails_app/app/assets/config/manifest.js b/examples/rails_app/app/assets/config/manifest.js new file mode 100644 index 0000000..5918193 --- /dev/null +++ b/examples/rails_app/app/assets/config/manifest.js @@ -0,0 +1,2 @@ +//= link_tree ../images +//= link_directory ../stylesheets .css diff --git a/examples/rails_app/app/assets/images/.keep b/examples/rails_app/app/assets/images/.keep new file mode 100644 index 0000000..e69de29 diff --git a/examples/rails_app/app/assets/stylesheets/application.css b/examples/rails_app/app/assets/stylesheets/application.css new file mode 100644 index 0000000..288b9ab --- /dev/null +++ b/examples/rails_app/app/assets/stylesheets/application.css @@ -0,0 +1,15 @@ +/* + * This is a manifest file that'll be compiled into application.css, which will include all the files + * listed below. + * + * Any CSS (and SCSS, if configured) file within this directory, lib/assets/stylesheets, or any plugin's + * vendor/assets/stylesheets directory can be referenced here using a relative path. + * + * You're free to add application-wide styles to this file and they'll appear at the bottom of the + * compiled file so the styles you add here take precedence over styles defined in any other CSS + * files in this directory. Styles in this file should be added after the last require_* statement. + * It is generally better to create a new file per style scope. + * + *= require_tree . + *= require_self + */ diff --git a/examples/rails_app/app/controllers/application_controller.rb b/examples/rails_app/app/controllers/application_controller.rb new file mode 100644 index 0000000..09705d1 --- /dev/null +++ b/examples/rails_app/app/controllers/application_controller.rb @@ -0,0 +1,2 @@ +class ApplicationController < ActionController::Base +end diff --git a/examples/rails_app/app/controllers/concerns/.keep b/examples/rails_app/app/controllers/concerns/.keep new file mode 100644 index 0000000..e69de29 diff --git a/examples/rails_app/app/controllers/test_controller.rb b/examples/rails_app/app/controllers/test_controller.rb new file mode 100644 index 0000000..13c9b1f --- /dev/null +++ b/examples/rails_app/app/controllers/test_controller.rb @@ -0,0 +1,10 @@ +class TestController < ApplicationController + def index + @messages = Message.all + end + + def publish + $nats.publish('messages', params.require(:message)) + redirect_back fallback_location: root_path + end +end diff --git a/examples/rails_app/app/helpers/application_helper.rb b/examples/rails_app/app/helpers/application_helper.rb new file mode 100644 index 0000000..de6be79 --- /dev/null +++ b/examples/rails_app/app/helpers/application_helper.rb @@ -0,0 +1,2 @@ +module ApplicationHelper +end diff --git a/examples/rails_app/app/helpers/test_helper.rb b/examples/rails_app/app/helpers/test_helper.rb new file mode 100644 index 0000000..09b6d50 --- /dev/null +++ b/examples/rails_app/app/helpers/test_helper.rb @@ -0,0 +1,2 @@ +module TestHelper +end diff --git a/examples/rails_app/app/models/application_record.rb b/examples/rails_app/app/models/application_record.rb new file mode 100644 index 0000000..b63caeb --- /dev/null +++ b/examples/rails_app/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + primary_abstract_class +end diff --git a/examples/rails_app/app/models/concerns/.keep b/examples/rails_app/app/models/concerns/.keep new file mode 100644 index 0000000..e69de29 diff --git a/examples/rails_app/app/models/message.rb b/examples/rails_app/app/models/message.rb new file mode 100644 index 0000000..28bdd9d --- /dev/null +++ b/examples/rails_app/app/models/message.rb @@ -0,0 +1,2 @@ +class Message < ApplicationRecord +end diff --git a/examples/rails_app/app/views/layouts/application.html.erb b/examples/rails_app/app/views/layouts/application.html.erb new file mode 100644 index 0000000..d10b8b4 --- /dev/null +++ b/examples/rails_app/app/views/layouts/application.html.erb @@ -0,0 +1,15 @@ + + + + RailsApp + + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + + <%= stylesheet_link_tag "application" %> + + + + <%= yield %> + + diff --git a/examples/rails_app/app/views/test/index.html.erb b/examples/rails_app/app/views/test/index.html.erb new file mode 100644 index 0000000..156f4af --- /dev/null +++ b/examples/rails_app/app/views/test/index.html.erb @@ -0,0 +1,15 @@ +

Greetings, stranger!

+

How do you greet in your language?

+ +<%= form_with url: test_publish_url do |f| %> + <%= f.text_field :message %> + <%= f.submit "Greet" %> +<% end %> + + + +

Please note that greeting sometimes may not appear immediately, because of the long way they need to make through our systems

\ No newline at end of file diff --git a/examples/rails_app/bin/bundle b/examples/rails_app/bin/bundle new file mode 100755 index 0000000..42c7fd7 --- /dev/null +++ b/examples/rails_app/bin/bundle @@ -0,0 +1,109 @@ +#!/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", __dir__) + end + + def lockfile + lockfile = + case File.basename(gemfile) + when "gems.rb" then gemfile.sub(/\.rb$/, ".locked") + 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_requirement + @bundler_requirement ||= + env_var_version || + cli_arg_version || + bundler_requirement_for(lockfile_version) + end + + def bundler_requirement_for(version) + return "#{Gem::Requirement.default}.a" unless version + + bundler_gem_version = Gem::Version.new(version) + + bundler_gem_version.approximate_recommendation + 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/examples/rails_app/bin/nats-listener b/examples/rails_app/bin/nats-listener new file mode 100755 index 0000000..614face --- /dev/null +++ b/examples/rails_app/bin/nats-listener @@ -0,0 +1,43 @@ +#!/usr/bin/env ruby + +# Load application +APP_PATH = File.expand_path('../config/application', __dir__) +require_relative '../config/boot' +require_relative '../config/environment' + +# NOTE: This code is NOT automatically reloaded in development environment. +# Restart the process after you made changes to the code below. + +puts "Connecting to NATS…" +$nats.connect + +puts "Setting up NATS listeners…" +$nats.subscribe('messages') do |msg, _reply, sub| + puts "Received on '#{sub}': '#{msg}'" + # Subscription block is executed in a separate thread, so invoking model methods + # will check out a connection from the database connection pool. + text = msg.force_encoding("UTF-8") # NATS payload is binary, but we sure that it is UTF-8 here + Message.create!(text: text) + # But after block has finished executing, the connection is returned to the pool. +end + +$nats.on_error do |e| + Rails.logger.error e +end + +$nats.flush +puts "Ready to receive messages!" + +shutting_down = false +Signal.trap("INT") do + puts "Shutting down NATS client…" + shutting_down = true +end + +# run process forever +loop do + sleep 1 + + break if $nats.closed? + $nats.drain if shutting_down +end diff --git a/examples/rails_app/bin/rails b/examples/rails_app/bin/rails new file mode 100755 index 0000000..efc0377 --- /dev/null +++ b/examples/rails_app/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/examples/rails_app/bin/rake b/examples/rails_app/bin/rake new file mode 100755 index 0000000..4fbf10b --- /dev/null +++ b/examples/rails_app/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "rake" +Rake.application.run diff --git a/examples/rails_app/bin/setup b/examples/rails_app/bin/setup new file mode 100755 index 0000000..ec47b79 --- /dev/null +++ b/examples/rails_app/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/examples/rails_app/config.ru b/examples/rails_app/config.ru new file mode 100644 index 0000000..4a3c09a --- /dev/null +++ b/examples/rails_app/config.ru @@ -0,0 +1,6 @@ +# This file is used by Rack-based servers to start the application. + +require_relative "config/environment" + +run Rails.application +Rails.application.load_server diff --git a/examples/rails_app/config/application.rb b/examples/rails_app/config/application.rb new file mode 100644 index 0000000..847a8c2 --- /dev/null +++ b/examples/rails_app/config/application.rb @@ -0,0 +1,38 @@ +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 "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 RailsApp + class Application < Rails::Application + # Initialize configuration defaults for originally generated Rails version. + config.load_defaults 7.0 + + # 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") + config.time_zone = ENV["TZ"].presence || "UTC" + + # Don't generate system test files. + config.generators.system_tests = nil + end +end diff --git a/examples/rails_app/config/boot.rb b/examples/rails_app/config/boot.rb new file mode 100644 index 0000000..2820116 --- /dev/null +++ b/examples/rails_app/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/examples/rails_app/config/credentials.yml.enc b/examples/rails_app/config/credentials.yml.enc new file mode 100644 index 0000000..974815f --- /dev/null +++ b/examples/rails_app/config/credentials.yml.enc @@ -0,0 +1 @@ +1O08grR4L0thQR8xgL1Th4MCth/G5nHL1gCia9xxjHE2mX2K+ilBOCCFmfqzbNLI9b7h7R9tCnfIooGkcSr9QJ4wYzgzs0pjq2sEzqyTSddLITiOQ7nugIuIDt/wD1vagZs8A7wWf6DVGul5AwLF4D0+J6t2lO4dJoIabY9sj3MvGxbW71QeEoyS7+ipuwPb6Zdh0Vnlqkqx05NdMSDdg1WsuH95vIRcjFswcQRGAXQz94NEXF3boyKi1v/DwOeZzBYbYwd/Fh0KuuWX+0gmosqhv7N8HYpw/iiKcNV/EcyirrqhfApMcf8Fi7StlIGdiagchofSqMJE2SUWEmW/VjCxFRKB9+Sx3oIn8aUAujaXR2SNyyPZuMFXQF90Duf0O47LWniSu54VcaZARlF7hXn4G7/80QiiYrr3--Uwxr06ktGdGZyGlV--FLc8VjupsIDAwAIUw6mPnQ== \ No newline at end of file diff --git a/examples/rails_app/config/database.yml b/examples/rails_app/config/database.yml new file mode 100644 index 0000000..fcba57f --- /dev/null +++ b/examples/rails_app/config/database.yml @@ -0,0 +1,25 @@ +# SQLite. Versions 3.8.0 and up are supported. +# gem install sqlite3 +# +# Ensure the SQLite 3 gem is defined in your Gemfile +# gem "sqlite3" +# +default: &default + adapter: sqlite3 + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + timeout: 5000 + +development: + <<: *default + database: db/development.sqlite3 + +# 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: db/test.sqlite3 + +production: + <<: *default + database: db/production.sqlite3 diff --git a/examples/rails_app/config/environment.rb b/examples/rails_app/config/environment.rb new file mode 100644 index 0000000..cac5315 --- /dev/null +++ b/examples/rails_app/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative "application" + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/examples/rails_app/config/environments/development.rb b/examples/rails_app/config/environments/development.rb new file mode 100644 index 0000000..5ab2549 --- /dev/null +++ b/examples/rails_app/config/environments/development.rb @@ -0,0 +1,62 @@ +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 server timing + config.server_timing = 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.action_controller.perform_caching = true + config.action_controller.enable_fragment_cache_logging = true + + 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 + + # Suppress logger output for asset requests. + config.assets.quiet = 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 + + # Uncomment if you wish to allow Action Cable access from any origin. + # config.action_cable.disable_request_forgery_protection = true +end diff --git a/examples/rails_app/config/environments/production.rb b/examples/rails_app/config/environments/production.rb new file mode 100644 index 0000000..ac46ed4 --- /dev/null +++ b/examples/rails_app/config/environments/production.rb @@ -0,0 +1,75 @@ +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 + config.action_controller.perform_caching = true + + # 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? + + # Compress CSS using a preprocessor. + # config.assets.css_compressor = :sass + + # Do not fallback to assets pipeline if a precompiled asset is missed. + config.assets.compile = false + + # 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 + + # Don't log any deprecations. + config.active_support.report_deprecations = false + + # 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 +end diff --git a/examples/rails_app/config/environments/test.rb b/examples/rails_app/config/environments/test.rb new file mode 100644 index 0000000..eb2f171 --- /dev/null +++ b/examples/rails_app/config/environments/test.rb @@ -0,0 +1,50 @@ +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. + + # Turn false under Spring and add config.action_view.cache_template_loading = true. + config.cache_classes = true + + # Eager loading loads your whole application. When running a single test locally, + # this probably isn't necessary. It's a good idea to do in a continuous integration + # system, or in some way before deploying your code. + config.eager_load = ENV["CI"].present? + + # 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/examples/rails_app/config/initializers/assets.rb b/examples/rails_app/config/initializers/assets.rb new file mode 100644 index 0000000..2eeef96 --- /dev/null +++ b/examples/rails_app/config/initializers/assets.rb @@ -0,0 +1,12 @@ +# Be sure to restart your server when you modify this file. + +# Version of your assets, change this if you want to expire all your assets. +Rails.application.config.assets.version = "1.0" + +# Add additional assets to the asset load path. +# Rails.application.config.assets.paths << Emoji.images_path + +# Precompile additional assets. +# application.js, application.css, and all non-JS/CSS in the app/assets +# folder are already added. +# Rails.application.config.assets.precompile += %w( admin.js admin.css ) diff --git a/examples/rails_app/config/initializers/filter_parameter_logging.rb b/examples/rails_app/config/initializers/filter_parameter_logging.rb new file mode 100644 index 0000000..adc6568 --- /dev/null +++ b/examples/rails_app/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +# Configure parameters to be filtered from the log file. Use this to limit dissemination of +# sensitive information. See the ActiveSupport::ParameterFilter documentation for supported +# notations and behaviors. +Rails.application.config.filter_parameters += [ + :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn +] diff --git a/examples/rails_app/config/initializers/nats.rb b/examples/rails_app/config/initializers/nats.rb new file mode 100644 index 0000000..bda663d --- /dev/null +++ b/examples/rails_app/config/initializers/nats.rb @@ -0,0 +1,12 @@ +nats_url = ENV.fetch("NATS_URL", "nats://localhost:4222") + +# Connection won't be established until the client is used for the first time +# Connection most probably will be made after the fork of the Puma web server. +$nats = NATS::Client.new(nats_url) + +# Hint: don't do subscriptions in the initializer as they will be run in +# the app server master process which you probably don't want. +# Do them in a special dedicated processes, see bin/nats-listener script for an example. + +# NATS client does request/response and subscription multiplexing from different callers, +# so connection pooling isn't necessary – you can use a single instance for the whole app. diff --git a/examples/rails_app/config/puma.rb b/examples/rails_app/config/puma.rb new file mode 100644 index 0000000..3df8fce --- /dev/null +++ b/examples/rails_app/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 `bin/rails restart` command. +plugin :tmp_restart diff --git a/examples/rails_app/config/routes.rb b/examples/rails_app/config/routes.rb new file mode 100644 index 0000000..9ad1811 --- /dev/null +++ b/examples/rails_app/config/routes.rb @@ -0,0 +1,6 @@ +Rails.application.routes.draw do + # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html + + root "test#index" + post "test/publish" => "test#publish", as: :test_publish +end diff --git a/examples/rails_app/db/migrate/20230620121736_create_messages.rb b/examples/rails_app/db/migrate/20230620121736_create_messages.rb new file mode 100644 index 0000000..7429d5b --- /dev/null +++ b/examples/rails_app/db/migrate/20230620121736_create_messages.rb @@ -0,0 +1,9 @@ +class CreateMessages < ActiveRecord::Migration[7.0] + def change + create_table :messages do |t| + t.text :text + + t.timestamps + end + end +end diff --git a/examples/rails_app/db/schema.rb b/examples/rails_app/db/schema.rb new file mode 100644 index 0000000..7e9e1d1 --- /dev/null +++ b/examples/rails_app/db/schema.rb @@ -0,0 +1,20 @@ +# 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[7.0].define(version: 2023_06_20_121736) do + create_table "messages", force: :cascade do |t| + t.text "text" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + +end diff --git a/examples/rails_app/db/seeds.rb b/examples/rails_app/db/seeds.rb new file mode 100644 index 0000000..bc25fce --- /dev/null +++ b/examples/rails_app/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/examples/rails_app/dip.yml b/examples/rails_app/dip.yml new file mode 100644 index 0000000..d2b8b93 --- /dev/null +++ b/examples/rails_app/dip.yml @@ -0,0 +1,59 @@ +version: '7.1' + +# Define default environment variables to pass +# to Docker Compose +environment: + RAILS_ENV: development + +compose: + files: + - .dockerdev/compose.yml + project_name: railsapp + +interaction: + # This command spins up a Rails container with the required dependencies (such as databases), + # and opens a terminal within it. + runner: + description: Open a Bash shell within a Rails container (with dependencies up) + service: rails + command: /bin/bash + + # Run a Rails container without any dependent services (useful for non-Rails scripts) + bash: + description: Run an arbitrary script within a container (or open a shell without deps) + service: rails + command: /bin/bash + compose_run_options: [ no-deps ] + + # A shortcut to run Bundler commands + bundle: + description: Run Bundler commands + service: rails + command: bundle + compose_run_options: [ no-deps ] + + rails: + description: Run Rails commands + service: rails + command: bundle exec rails + subcommands: + s: + description: Run Rails server at http://localhost:3000 + service: web + compose: + run_options: [ service-ports, use-aliases ] + test: + description: Run unit tests + service: rails + command: bundle exec rails test + environment: + RAILS_ENV: test + + yarn: + description: Run Yarn commands + service: rails + command: yarn + compose_run_options: [ no-deps ] + +provision: + - dip bash -c bin/setup diff --git a/examples/rails_app/lib/assets/.keep b/examples/rails_app/lib/assets/.keep new file mode 100644 index 0000000..e69de29 diff --git a/examples/rails_app/lib/tasks/.keep b/examples/rails_app/lib/tasks/.keep new file mode 100644 index 0000000..e69de29 diff --git a/examples/rails_app/log/.keep b/examples/rails_app/log/.keep new file mode 100644 index 0000000..e69de29 diff --git a/examples/rails_app/public/404.html b/examples/rails_app/public/404.html new file mode 100644 index 0000000..2be3af2 --- /dev/null +++ b/examples/rails_app/public/404.html @@ -0,0 +1,67 @@ + + + + The page you were looking for doesn't exist (404) + + + + + + +
+
+

The page you were looking for doesn't exist.

+

You may have mistyped the address or the page may have moved.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/examples/rails_app/public/422.html b/examples/rails_app/public/422.html new file mode 100644 index 0000000..c08eac0 --- /dev/null +++ b/examples/rails_app/public/422.html @@ -0,0 +1,67 @@ + + + + The change you wanted was rejected (422) + + + + + + +
+
+

The change you wanted was rejected.

+

Maybe you tried to change something you didn't have access to.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/examples/rails_app/public/500.html b/examples/rails_app/public/500.html new file mode 100644 index 0000000..78a030a --- /dev/null +++ b/examples/rails_app/public/500.html @@ -0,0 +1,66 @@ + + + + We're sorry, but something went wrong (500) + + + + + + +
+
+

We're sorry, but something went wrong.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/examples/rails_app/public/apple-touch-icon-precomposed.png b/examples/rails_app/public/apple-touch-icon-precomposed.png new file mode 100644 index 0000000..e69de29 diff --git a/examples/rails_app/public/apple-touch-icon.png b/examples/rails_app/public/apple-touch-icon.png new file mode 100644 index 0000000..e69de29 diff --git a/examples/rails_app/public/favicon.ico b/examples/rails_app/public/favicon.ico new file mode 100644 index 0000000..e69de29 diff --git a/examples/rails_app/public/robots.txt b/examples/rails_app/public/robots.txt new file mode 100644 index 0000000..c19f78a --- /dev/null +++ b/examples/rails_app/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/examples/rails_app/tmp/.keep b/examples/rails_app/tmp/.keep new file mode 100644 index 0000000..e69de29 diff --git a/examples/rails_app/tmp/pids/.keep b/examples/rails_app/tmp/pids/.keep new file mode 100644 index 0000000..e69de29