├── .dockerignore ├── .gitattributes ├── .gitignore ├── .ruby-version ├── Dockerfile ├── Gemfile ├── Gemfile.lock ├── Rakefile ├── app ├── assets │ ├── config │ │ └── manifest.js │ ├── images │ │ ├── .keep │ │ ├── Falcon.png │ │ ├── flappy-background.png │ │ ├── flappy-bird.png │ │ └── flappy-pipe.png │ └── stylesheets │ │ ├── application.css │ │ └── flappy.css ├── channels │ └── application_cable │ │ ├── channel.rb │ │ └── connection.rb ├── controllers │ ├── application_controller.rb │ ├── chat_controller.rb │ ├── concerns │ │ └── .keep │ ├── flappy_controller.rb │ ├── game_controller.rb │ ├── job_controller.rb │ ├── ollama_controller.rb │ ├── sse_controller.rb │ ├── streaming_controller.rb │ └── welcome_controller.rb ├── helpers │ ├── application_helper.rb │ ├── chat_helper.rb │ ├── flappy_helper.rb │ ├── game_helper.rb │ ├── job_helper.rb │ ├── ollama_helper.rb │ ├── sse_helper.rb │ ├── streaming_helper.rb │ └── welcome_helper.rb ├── javascript │ ├── application.js │ ├── controllers │ │ ├── application.js │ │ └── index.js │ └── live.js ├── jobs │ ├── application_job.rb │ └── my_job.rb ├── mailers │ └── application_mailer.rb ├── models │ ├── application_record.rb │ ├── concerns │ │ └── .keep │ ├── conversation.rb │ ├── conversation_message.rb │ ├── highscore.rb │ └── job_execution.rb └── views │ ├── chat │ └── index.html.erb │ ├── flappy │ └── index.html.erb │ ├── game │ └── index.html.erb │ ├── job │ └── index.html.erb │ ├── job_executions │ └── _job_execution.html.erb │ ├── layouts │ ├── application.html.erb │ ├── mailer.html.erb │ └── mailer.text.erb │ ├── ollama │ └── index.html.erb │ ├── sse │ └── index.html.erb │ └── welcome │ └── index.html.erb ├── bin ├── bundle ├── docker-entrypoint ├── importmap ├── rails ├── rake └── setup ├── config.ru ├── config ├── application.rb ├── boot.rb ├── cable.yml ├── credentials.yml.enc ├── database.yml ├── environment.rb ├── environments │ ├── development.rb │ ├── production.rb │ └── test.rb ├── importmap.rb ├── initializers │ ├── assets.rb │ ├── async_job.rb │ ├── content_security_policy.rb │ ├── filter_parameter_logging.rb │ ├── inflections.rb │ └── permissions_policy.rb ├── locales │ └── en.yml ├── puma.rb ├── routes.rb └── storage.yml ├── db ├── migrate │ ├── 20240225111326_create_job_executions.rb │ ├── 20240411023610_create_conversations.rb │ ├── 20240411023621_create_conversation_messages.rb │ └── 20240414035057_create_highscores.rb ├── schema.rb └── seeds.rb ├── lib ├── assets │ └── .keep ├── chat.rb ├── flappy_tag.rb ├── game_tag.rb ├── messages.rb ├── ollama_tag.rb └── tasks │ └── .keep ├── log └── .keep ├── public ├── 404.html ├── 422.html ├── 500.html ├── apple-touch-icon-precomposed.png ├── apple-touch-icon.png ├── chat │ └── client.js ├── favicon.ico └── robots.txt ├── readme.md ├── storage └── .keep ├── test ├── application_system_test_case.rb ├── channels │ └── application_cable │ │ └── connection_test.rb ├── controllers │ ├── .keep │ ├── chat_controller_test.rb │ ├── flappy_controller_test.rb │ ├── job_controller_test.rb │ ├── ollama_controller_test.rb │ ├── sse_controller_test.rb │ ├── stock_controller_test.rb │ ├── streaming_controller_test.rb │ └── welcome_controller_test.rb ├── fixtures │ ├── conversation_messages.yml │ ├── conversations.yml │ ├── files │ │ └── .keep │ └── highscores.yml ├── helpers │ └── .keep ├── integration │ └── .keep ├── mailers │ └── .keep ├── models │ ├── .keep │ ├── conversation_message_test.rb │ ├── conversation_test.rb │ └── highscore_test.rb ├── system │ └── .keep └── test_helper.rb ├── tmp ├── .keep ├── pids │ └── .keep └── storage │ └── .keep └── vendor ├── .keep └── javascript ├── .keep ├── @socketry--live.js └── morphdom.js /.dockerignore: -------------------------------------------------------------------------------- 1 | # See https://docs.docker.com/engine/reference/builder/#dockerignore-file for more about ignoring files. 2 | 3 | # Ignore git directory. 4 | /.git/ 5 | 6 | # Ignore bundler config. 7 | /.bundle 8 | 9 | # Ignore all environment files (except templates). 10 | /.env* 11 | !/.env*.erb 12 | 13 | # Ignore all default key files. 14 | /config/master.key 15 | /config/credentials/*.key 16 | 17 | # Ignore all logfiles and tempfiles. 18 | /log/* 19 | /tmp/* 20 | !/log/.keep 21 | !/tmp/.keep 22 | 23 | # Ignore pidfiles, but keep the directory. 24 | /tmp/pids/* 25 | !/tmp/pids/.keep 26 | 27 | # Ignore storage (uploaded files in development and any SQLite databases). 28 | /storage/* 29 | !/storage/.keep 30 | /tmp/storage/* 31 | !/tmp/storage/.keep 32 | 33 | # Ignore assets. 34 | /node_modules/ 35 | /app/assets/builds/* 36 | !/app/assets/builds/.keep 37 | /public/assets 38 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # See https://git-scm.com/docs/gitattributes for more about git attribute files. 2 | 3 | # Mark the database schema as having been generated. 4 | db/schema.rb linguist-generated 5 | 6 | # Mark any vendored files as having been vendored. 7 | vendor/* linguist-vendored 8 | config/credentials/*.yml.enc diff=rails_credentials 9 | config/credentials.yml.enc diff=rails_credentials 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files for more about ignoring files. 2 | # 3 | # If you find yourself ignoring temporary files generated by your text editor 4 | # or operating system, you probably want to add a global ignore instead: 5 | # git config --global core.excludesfile '~/.gitignore_global' 6 | 7 | # Ignore bundler config. 8 | /.bundle 9 | 10 | # Ignore all environment files (except templates). 11 | /.env* 12 | !/.env*.erb 13 | 14 | # Ignore all logfiles and tempfiles. 15 | /log/* 16 | /tmp/* 17 | !/log/.keep 18 | !/tmp/.keep 19 | 20 | # Ignore pidfiles, but keep the directory. 21 | /tmp/pids/* 22 | !/tmp/pids/ 23 | !/tmp/pids/.keep 24 | 25 | # Ignore storage (uploaded files in development and any SQLite databases). 26 | /storage/* 27 | !/storage/.keep 28 | /tmp/storage/* 29 | !/tmp/storage/ 30 | !/tmp/storage/.keep 31 | 32 | /public/assets 33 | 34 | # Ignore master key for decrypting credentials and more. 35 | /config/master.key 36 | -------------------------------------------------------------------------------- /.ruby-version: -------------------------------------------------------------------------------- 1 | ruby-3.3.0 2 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # syntax = docker/dockerfile:1 2 | 3 | # Make sure RUBY_VERSION matches the Ruby version in .ruby-version and Gemfile 4 | ARG RUBY_VERSION=3.3.0 5 | FROM registry.docker.com/library/ruby:$RUBY_VERSION-slim as base 6 | 7 | # Rails app lives here 8 | WORKDIR /rails 9 | 10 | # Set production environment 11 | ENV RAILS_ENV="production" \ 12 | BUNDLE_DEPLOYMENT="1" \ 13 | BUNDLE_PATH="/usr/local/bundle" \ 14 | BUNDLE_WITHOUT="development" 15 | 16 | 17 | # Throw-away build stage to reduce size of final image 18 | FROM base as build 19 | 20 | # Install packages needed to build gems 21 | RUN apt-get update -qq && \ 22 | apt-get install --no-install-recommends -y build-essential git libvips pkg-config 23 | 24 | # Install application gems 25 | COPY Gemfile Gemfile.lock ./ 26 | RUN bundle install && \ 27 | rm -rf ~/.bundle/ "${BUNDLE_PATH}"/ruby/*/cache "${BUNDLE_PATH}"/ruby/*/bundler/gems/*/.git && \ 28 | bundle exec bootsnap precompile --gemfile 29 | 30 | # Copy application code 31 | COPY . . 32 | 33 | # Precompile bootsnap code for faster boot times 34 | RUN bundle exec bootsnap precompile app/ lib/ 35 | 36 | # Precompiling assets for production without requiring secret RAILS_MASTER_KEY 37 | RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile 38 | 39 | 40 | # Final stage for app image 41 | FROM base 42 | 43 | # Install packages needed for deployment 44 | RUN apt-get update -qq && \ 45 | apt-get install --no-install-recommends -y curl libsqlite3-0 libvips && \ 46 | rm -rf /var/lib/apt/lists /var/cache/apt/archives 47 | 48 | # Copy built artifacts: gems, application 49 | COPY --from=build /usr/local/bundle /usr/local/bundle 50 | COPY --from=build /rails /rails 51 | 52 | # Run and own only the runtime files as a non-root user for security 53 | RUN useradd rails --create-home --shell /bin/bash && \ 54 | chown -R rails:rails db log storage tmp 55 | USER rails:rails 56 | 57 | # Entrypoint prepares the database. 58 | ENTRYPOINT ["/rails/bin/docker-entrypoint"] 59 | 60 | # Start the server by default, this can be overwritten at runtime 61 | EXPOSE 3000 62 | CMD ["./bin/rails", "server"] 63 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | 3 | # Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" 4 | # gem "rails", "~> 7.1" 5 | gem "rails", git: "https://github.com/rails/rails" 6 | 7 | # The original asset pipeline for Rails [https://github.com/rails/sprockets-rails] 8 | gem "sprockets-rails" 9 | 10 | # Use sqlite3 as the database for Active Record 11 | gem "sqlite3", "~> 1.4" 12 | 13 | # Use the Falcon web server [https://github.com/socketry/falcon] 14 | gem 'falcon' 15 | gem 'puma', "~> 6.1.0" 16 | 17 | # Use the async-job job server 18 | gem "async-job", "~> 0.5" 19 | gem "async-job-adapter-active_job", "~> 0.7" 20 | 21 | gem "async-ollama" 22 | 23 | # Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails] 24 | gem "importmap-rails" 25 | 26 | # Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev] 27 | gem "turbo-rails" 28 | 29 | # Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev] 30 | gem "stimulus-rails" 31 | 32 | # Build JSON APIs with ease [https://github.com/rails/jbuilder] 33 | gem "jbuilder" 34 | 35 | # Use Redis adapter to run Action Cable in production 36 | gem "redis", ">= 4.0.1" 37 | 38 | # Use Kredis to get higher-level data types in Redis [https://github.com/rails/kredis] 39 | # gem "kredis" 40 | 41 | # Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword] 42 | # gem "bcrypt", "~> 3.1.7" 43 | 44 | # Windows does not include zoneinfo files, so bundle the tzinfo-data gem 45 | gem "tzinfo-data", platforms: %i[ windows jruby ] 46 | 47 | # Reduces boot times through caching; required in config/boot.rb 48 | gem "bootsnap", require: false 49 | 50 | # Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images] 51 | # gem "image_processing", "~> 1.2" 52 | 53 | group :development, :test do 54 | # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem 55 | # gem "debug", platforms: %i[ mri windows ] 56 | end 57 | 58 | group :development do 59 | # Use console on exceptions pages [https://github.com/rails/web-console] 60 | gem "web-console" 61 | 62 | # Add speed badges [https://github.com/MiniProfiler/rack-mini-profiler] 63 | # gem "rack-mini-profiler" 64 | 65 | # Speed up commands on slow machines / big apps [https://github.com/rails/spring] 66 | # gem "spring" 67 | 68 | end 69 | 70 | group :test do 71 | # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing] 72 | gem "capybara" 73 | gem "selenium-webdriver" 74 | end 75 | 76 | gem "console-adapter-rails", "~> 0.3.4" 77 | 78 | gem "console-output-datadog", "~> 0.3.0" 79 | gem "traces-backend-datadog", "~> 0.5.0" 80 | 81 | gem "async-redis", "~> 0.8.0" 82 | gem "thread-local", "~> 1.1" 83 | gem "async-websocket", "~> 0.26.1" 84 | 85 | gem "live", "~> 0.5.0" 86 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | GIT 2 | remote: https://github.com/rails/rails 3 | revision: 793ff00442723b2ff9ed7b7fb39cae2f5608cc2b 4 | specs: 5 | actioncable (7.2.0.alpha) 6 | actionpack (= 7.2.0.alpha) 7 | activesupport (= 7.2.0.alpha) 8 | nio4r (~> 2.0) 9 | websocket-driver (>= 0.6.1) 10 | zeitwerk (~> 2.6) 11 | actionmailbox (7.2.0.alpha) 12 | actionpack (= 7.2.0.alpha) 13 | activejob (= 7.2.0.alpha) 14 | activerecord (= 7.2.0.alpha) 15 | activestorage (= 7.2.0.alpha) 16 | activesupport (= 7.2.0.alpha) 17 | mail (>= 2.8.0) 18 | actionmailer (7.2.0.alpha) 19 | actionpack (= 7.2.0.alpha) 20 | actionview (= 7.2.0.alpha) 21 | activejob (= 7.2.0.alpha) 22 | activesupport (= 7.2.0.alpha) 23 | mail (>= 2.8.0) 24 | rails-dom-testing (~> 2.2) 25 | actionpack (7.2.0.alpha) 26 | actionview (= 7.2.0.alpha) 27 | activesupport (= 7.2.0.alpha) 28 | nokogiri (>= 1.8.5) 29 | racc 30 | rack (>= 2.2.4) 31 | rack-session (>= 1.0.1) 32 | rack-test (>= 0.6.3) 33 | rails-dom-testing (~> 2.2) 34 | rails-html-sanitizer (~> 1.6) 35 | useragent (~> 0.16) 36 | actiontext (7.2.0.alpha) 37 | actionpack (= 7.2.0.alpha) 38 | activerecord (= 7.2.0.alpha) 39 | activestorage (= 7.2.0.alpha) 40 | activesupport (= 7.2.0.alpha) 41 | globalid (>= 0.6.0) 42 | nokogiri (>= 1.8.5) 43 | actionview (7.2.0.alpha) 44 | activesupport (= 7.2.0.alpha) 45 | builder (~> 3.1) 46 | erubi (~> 1.11) 47 | rails-dom-testing (~> 2.2) 48 | rails-html-sanitizer (~> 1.6) 49 | activejob (7.2.0.alpha) 50 | activesupport (= 7.2.0.alpha) 51 | globalid (>= 0.3.6) 52 | activemodel (7.2.0.alpha) 53 | activesupport (= 7.2.0.alpha) 54 | activerecord (7.2.0.alpha) 55 | activemodel (= 7.2.0.alpha) 56 | activesupport (= 7.2.0.alpha) 57 | timeout (>= 0.4.0) 58 | activestorage (7.2.0.alpha) 59 | actionpack (= 7.2.0.alpha) 60 | activejob (= 7.2.0.alpha) 61 | activerecord (= 7.2.0.alpha) 62 | activesupport (= 7.2.0.alpha) 63 | marcel (~> 1.0) 64 | activesupport (7.2.0.alpha) 65 | base64 66 | bigdecimal 67 | concurrent-ruby (~> 1.0, >= 1.0.2) 68 | connection_pool (>= 2.2.5) 69 | drb 70 | i18n (>= 1.6, < 2) 71 | minitest (>= 5.1, < 5.22.0) 72 | tzinfo (~> 2.0, >= 2.0.5) 73 | rails (7.2.0.alpha) 74 | actioncable (= 7.2.0.alpha) 75 | actionmailbox (= 7.2.0.alpha) 76 | actionmailer (= 7.2.0.alpha) 77 | actionpack (= 7.2.0.alpha) 78 | actiontext (= 7.2.0.alpha) 79 | actionview (= 7.2.0.alpha) 80 | activejob (= 7.2.0.alpha) 81 | activemodel (= 7.2.0.alpha) 82 | activerecord (= 7.2.0.alpha) 83 | activestorage (= 7.2.0.alpha) 84 | activesupport (= 7.2.0.alpha) 85 | bundler (>= 1.15.0) 86 | railties (= 7.2.0.alpha) 87 | railties (7.2.0.alpha) 88 | actionpack (= 7.2.0.alpha) 89 | activesupport (= 7.2.0.alpha) 90 | irb (~> 1.13) 91 | rackup (>= 1.0.0) 92 | rake (>= 12.2) 93 | thor (~> 1.0, >= 1.2.2) 94 | zeitwerk (~> 2.6) 95 | 96 | GEM 97 | remote: https://rubygems.org/ 98 | specs: 99 | addressable (2.8.6) 100 | public_suffix (>= 2.0.2, < 6.0) 101 | async (2.10.2) 102 | console (~> 1.10) 103 | fiber-annotation 104 | io-event (~> 1.5, >= 1.5.1) 105 | timers (~> 4.1) 106 | async-container (0.18.2) 107 | async (~> 2.10) 108 | async-http (0.66.2) 109 | async (>= 2.10.2) 110 | async-pool (>= 0.6.1) 111 | io-endpoint (~> 0.10) 112 | io-stream (~> 0.4) 113 | protocol-http (~> 0.26.0) 114 | protocol-http1 (~> 0.19.0) 115 | protocol-http2 (~> 0.17.0) 116 | traces (>= 0.10.0) 117 | async-http-cache (0.4.3) 118 | async-http (~> 0.56) 119 | async-job (0.5.0) 120 | async (~> 2.9) 121 | async-redis 122 | async-job-adapter-active_job (0.7.0) 123 | async-job (~> 0.5) 124 | async-service (~> 0.12) 125 | thread-local 126 | async-ollama (0.1.0) 127 | async 128 | async-rest (~> 0.13.0) 129 | async-pool (0.6.1) 130 | async (>= 1.25) 131 | async-redis (0.8.1) 132 | async (>= 1.8, < 3.0) 133 | async-pool (~> 0.2) 134 | io-endpoint (~> 0.10) 135 | io-stream (~> 0.4) 136 | protocol-redis (~> 0.8.0) 137 | async-rest (0.13.0) 138 | async-http (~> 0.42) 139 | protocol-http (~> 0.7) 140 | async-service (0.12.0) 141 | async 142 | async-container (~> 0.16) 143 | async-websocket (0.26.1) 144 | async-http (~> 0.54) 145 | protocol-rack (~> 0.5) 146 | protocol-websocket (~> 0.11) 147 | base64 (0.2.0) 148 | bigdecimal (3.1.7) 149 | bindex (0.8.1) 150 | bootsnap (1.18.3) 151 | msgpack (~> 1.2) 152 | builder (3.2.4) 153 | capybara (3.40.0) 154 | addressable 155 | matrix 156 | mini_mime (>= 0.1.3) 157 | nokogiri (~> 1.11) 158 | rack (>= 1.6.0) 159 | rack-test (>= 0.6.3) 160 | regexp_parser (>= 1.5, < 3.0) 161 | xpath (~> 3.2) 162 | concurrent-ruby (1.2.3) 163 | connection_pool (2.4.1) 164 | console (1.25.1) 165 | fiber-annotation 166 | fiber-local (~> 1.1) 167 | json 168 | console-adapter-rails (0.3.4) 169 | console (~> 1.21) 170 | fiber-storage (~> 0.1) 171 | rails (>= 6.1) 172 | console-output-datadog (0.3.0) 173 | console 174 | ddtrace (~> 1.0) 175 | crass (1.0.6) 176 | datadog-ci (0.8.3) 177 | msgpack 178 | date (3.3.4) 179 | ddtrace (1.22.0) 180 | datadog-ci (~> 0.8.1) 181 | debase-ruby_core_source (= 3.3.1) 182 | libdatadog (~> 7.0.0.1.0) 183 | libddwaf (~> 1.14.0.0.0) 184 | msgpack 185 | debase-ruby_core_source (3.3.1) 186 | drb (2.2.1) 187 | erubi (1.12.0) 188 | falcon (0.47.1) 189 | async 190 | async-container (~> 0.18) 191 | async-http (~> 0.66, >= 0.66.2) 192 | async-http-cache (~> 0.4.0) 193 | async-service (~> 0.10) 194 | bundler 195 | localhost (~> 1.1) 196 | openssl (~> 3.0) 197 | process-metrics (~> 0.2.0) 198 | protocol-rack (~> 0.5) 199 | samovar (~> 2.3) 200 | ffi (1.16.3) 201 | fiber-annotation (0.2.0) 202 | fiber-local (1.1.0) 203 | fiber-storage 204 | fiber-storage (0.1.0) 205 | globalid (1.2.1) 206 | activesupport (>= 6.1) 207 | i18n (1.14.4) 208 | concurrent-ruby (~> 1.0) 209 | importmap-rails (2.0.1) 210 | actionpack (>= 6.0.0) 211 | activesupport (>= 6.0.0) 212 | railties (>= 6.0.0) 213 | io-console (0.7.2) 214 | io-endpoint (0.10.2) 215 | io-event (1.5.1) 216 | io-stream (0.4.0) 217 | irb (1.13.0) 218 | rdoc (>= 4.0.0) 219 | reline (>= 0.4.2) 220 | jbuilder (2.12.0) 221 | actionview (>= 5.0.0) 222 | activesupport (>= 5.0.0) 223 | json (2.7.2) 224 | libdatadog (7.0.0.1.0) 225 | libdatadog (7.0.0.1.0-aarch64-linux) 226 | libdatadog (7.0.0.1.0-x86_64-linux) 227 | libddwaf (1.14.0.0.0) 228 | ffi (~> 1.0) 229 | libddwaf (1.14.0.0.0-aarch64-linux) 230 | ffi (~> 1.0) 231 | libddwaf (1.14.0.0.0-arm64-darwin) 232 | ffi (~> 1.0) 233 | libddwaf (1.14.0.0.0-x86_64-darwin) 234 | ffi (~> 1.0) 235 | libddwaf (1.14.0.0.0-x86_64-linux) 236 | ffi (~> 1.0) 237 | live (0.5.1) 238 | async-websocket (~> 0.23) 239 | trenni 240 | localhost (1.3.1) 241 | loofah (2.22.0) 242 | crass (~> 1.0.2) 243 | nokogiri (>= 1.12.0) 244 | mail (2.8.1) 245 | mini_mime (>= 0.1.1) 246 | net-imap 247 | net-pop 248 | net-smtp 249 | mapping (1.1.1) 250 | marcel (1.0.4) 251 | matrix (0.4.2) 252 | mini_mime (1.1.5) 253 | minitest (5.21.2) 254 | msgpack (1.7.2) 255 | net-imap (0.4.10) 256 | date 257 | net-protocol 258 | net-pop (0.1.2) 259 | net-protocol 260 | net-protocol (0.2.2) 261 | timeout 262 | net-smtp (0.5.0) 263 | net-protocol 264 | nio4r (2.7.1) 265 | nokogiri (1.16.4-aarch64-linux) 266 | racc (~> 1.4) 267 | nokogiri (1.16.4-arm-linux) 268 | racc (~> 1.4) 269 | nokogiri (1.16.4-arm64-darwin) 270 | racc (~> 1.4) 271 | nokogiri (1.16.4-x86-linux) 272 | racc (~> 1.4) 273 | nokogiri (1.16.4-x86_64-darwin) 274 | racc (~> 1.4) 275 | nokogiri (1.16.4-x86_64-linux) 276 | racc (~> 1.4) 277 | openssl (3.2.0) 278 | process-metrics (0.2.1) 279 | console (~> 1.8) 280 | samovar (~> 2.1) 281 | protocol-hpack (1.4.3) 282 | protocol-http (0.26.4) 283 | protocol-http1 (0.19.1) 284 | protocol-http (~> 0.22) 285 | protocol-http2 (0.17.0) 286 | protocol-hpack (~> 1.4) 287 | protocol-http (~> 0.18) 288 | protocol-rack (0.5.1) 289 | protocol-http (~> 0.23) 290 | rack (>= 1.0) 291 | protocol-redis (0.8.1) 292 | protocol-websocket (0.12.1) 293 | protocol-http (~> 0.2) 294 | psych (5.1.2) 295 | stringio 296 | public_suffix (5.0.5) 297 | puma (6.1.1) 298 | nio4r (~> 2.0) 299 | racc (1.7.3) 300 | rack (3.0.10) 301 | rack-session (2.0.0) 302 | rack (>= 3.0.0) 303 | rack-test (2.1.0) 304 | rack (>= 1.3) 305 | rackup (2.1.0) 306 | rack (>= 3) 307 | webrick (~> 1.8) 308 | rails-dom-testing (2.2.0) 309 | activesupport (>= 5.0.0) 310 | minitest 311 | nokogiri (>= 1.6) 312 | rails-html-sanitizer (1.6.0) 313 | loofah (~> 2.21) 314 | nokogiri (~> 1.14) 315 | rake (13.2.1) 316 | rdoc (6.6.3.1) 317 | psych (>= 4.0.0) 318 | redis (5.2.0) 319 | redis-client (>= 0.22.0) 320 | redis-client (0.22.1) 321 | connection_pool 322 | regexp_parser (2.9.0) 323 | reline (0.5.5) 324 | io-console (~> 0.5) 325 | rexml (3.2.6) 326 | rubyzip (2.3.2) 327 | samovar (2.3.0) 328 | console (~> 1.0) 329 | mapping (~> 1.0) 330 | selenium-webdriver (4.20.1) 331 | base64 (~> 0.2) 332 | rexml (~> 3.2, >= 3.2.5) 333 | rubyzip (>= 1.2.2, < 3.0) 334 | websocket (~> 1.0) 335 | sprockets (4.2.1) 336 | concurrent-ruby (~> 1.0) 337 | rack (>= 2.2.4, < 4) 338 | sprockets-rails (3.4.2) 339 | actionpack (>= 5.2) 340 | activesupport (>= 5.2) 341 | sprockets (>= 3.0.0) 342 | sqlite3 (1.7.3-aarch64-linux) 343 | sqlite3 (1.7.3-arm-linux) 344 | sqlite3 (1.7.3-arm64-darwin) 345 | sqlite3 (1.7.3-x86-linux) 346 | sqlite3 (1.7.3-x86_64-darwin) 347 | sqlite3 (1.7.3-x86_64-linux) 348 | stimulus-rails (1.3.3) 349 | railties (>= 6.0.0) 350 | stringio (3.1.0) 351 | thor (1.3.1) 352 | thread-local (1.1.0) 353 | timeout (0.4.1) 354 | timers (4.3.5) 355 | traces (0.11.1) 356 | traces-backend-datadog (0.5.0) 357 | ddtrace (~> 1.2) 358 | traces (~> 0.10) 359 | trenni (3.14.0) 360 | turbo-rails (2.0.5) 361 | actionpack (>= 6.0.0) 362 | activejob (>= 6.0.0) 363 | railties (>= 6.0.0) 364 | tzinfo (2.0.6) 365 | concurrent-ruby (~> 1.0) 366 | useragent (0.16.10) 367 | web-console (4.2.1) 368 | actionview (>= 6.0.0) 369 | activemodel (>= 6.0.0) 370 | bindex (>= 0.4.0) 371 | railties (>= 6.0.0) 372 | webrick (1.8.1) 373 | websocket (1.2.10) 374 | websocket-driver (0.7.6) 375 | websocket-extensions (>= 0.1.0) 376 | websocket-extensions (0.1.5) 377 | xpath (3.2.0) 378 | nokogiri (~> 1.8) 379 | zeitwerk (2.6.13) 380 | 381 | PLATFORMS 382 | aarch64-linux 383 | arm-linux 384 | arm64-darwin 385 | x86-linux 386 | x86_64-darwin 387 | x86_64-linux 388 | 389 | DEPENDENCIES 390 | async-job (~> 0.5) 391 | async-job-adapter-active_job (~> 0.7) 392 | async-ollama 393 | async-redis (~> 0.8.0) 394 | async-websocket (~> 0.26.1) 395 | bootsnap 396 | capybara 397 | console-adapter-rails (~> 0.3.4) 398 | console-output-datadog (~> 0.3.0) 399 | falcon 400 | importmap-rails 401 | jbuilder 402 | live (~> 0.5.0) 403 | puma (~> 6.1.0) 404 | rails! 405 | redis (>= 4.0.1) 406 | selenium-webdriver 407 | sprockets-rails 408 | sqlite3 (~> 1.4) 409 | stimulus-rails 410 | thread-local (~> 1.1) 411 | traces-backend-datadog (~> 0.5.0) 412 | turbo-rails 413 | tzinfo-data 414 | web-console 415 | 416 | BUNDLED WITH 417 | 2.4.12 418 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | # Add your own tasks in files placed in lib/tasks ending in .rake, 2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 3 | 4 | require_relative "config/application" 5 | 6 | Rails.application.load_tasks 7 | -------------------------------------------------------------------------------- /app/assets/config/manifest.js: -------------------------------------------------------------------------------- 1 | //= link_tree ../images 2 | //= link_directory ../stylesheets .css 3 | //= link_tree ../../javascript .js 4 | //= link_tree ../../../vendor/javascript .js 5 | -------------------------------------------------------------------------------- /app/assets/images/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/app/assets/images/.keep -------------------------------------------------------------------------------- /app/assets/images/Falcon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/app/assets/images/Falcon.png -------------------------------------------------------------------------------- /app/assets/images/flappy-background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/app/assets/images/flappy-background.png -------------------------------------------------------------------------------- /app/assets/images/flappy-bird.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/app/assets/images/flappy-bird.png -------------------------------------------------------------------------------- /app/assets/images/flappy-pipe.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/app/assets/images/flappy-pipe.png -------------------------------------------------------------------------------- /app/assets/stylesheets/application.css: -------------------------------------------------------------------------------- 1 | /* 2 | * This is a manifest file that'll be compiled into application.css, which will include all the files 3 | * listed below. 4 | * 5 | * Any CSS (and SCSS, if configured) file within this directory, lib/assets/stylesheets, or any plugin's 6 | * vendor/assets/stylesheets directory can be referenced here using a relative path. 7 | * 8 | * You're free to add application-wide styles to this file and they'll appear at the bottom of the 9 | * compiled file so the styles you add here take precedence over styles defined in any other CSS 10 | * files in this directory. Styles in this file should be added after the last require_* statement. 11 | * It is generally better to create a new file per style scope. 12 | * 13 | *= require_tree . 14 | *= require_self 15 | */ 16 | 17 | html { 18 | font-family: "PT Sans", Verdana, Helvetica, Arial, sans-serif; 19 | font-size: 16px; 20 | } 21 | 22 | pre { 23 | tab-size: 2; 24 | } 25 | 26 | @media (min-width: 40em) { 27 | html { 28 | font-size: 18px; 29 | } 30 | 31 | pre { 32 | tab-size: 4; 33 | } 34 | } 35 | 36 | @media (min-width: 80em) { 37 | html { 38 | font-size: 20px; 39 | } 40 | 41 | pre { 42 | tab-size: 4; 43 | } 44 | } 45 | 46 | body { 47 | padding: 0; 48 | margin: 0; 49 | 50 | background-color: #fafafa; 51 | } 52 | 53 | nav { 54 | font-size: 0.8rem; 55 | text-align: right; 56 | margin: 0.5rem; 57 | } 58 | 59 | main, footer { 60 | max-width: 48rem; 61 | padding: 1rem; 62 | margin: auto; 63 | } 64 | 65 | body > header { 66 | margin: 0.5rem 0; 67 | 68 | background: white; 69 | 70 | box-shadow: 0 0 20px rgba(0, 0, 0, 0.1); 71 | } 72 | 73 | body > header img { 74 | display: block; 75 | margin: auto; 76 | height: 6rem; 77 | } 78 | 79 | p, ul, ol { 80 | color: #555; 81 | } 82 | 83 | p strong { 84 | color: #222; 85 | } 86 | 87 | h1, h2, h3, h4, h5, h6 { 88 | margin: 2rem 1rem 1rem 1rem; 89 | color: #54401d; 90 | } 91 | 92 | h1 { 93 | margin: 4rem 0; 94 | } 95 | 96 | h2 { 97 | margin-top: 6rem; 98 | } 99 | 100 | img { 101 | border: none; 102 | } 103 | 104 | a, mark { 105 | color: #2d8c46; 106 | } 107 | 108 | mark { 109 | background-color: inherit; 110 | } 111 | 112 | a.action { 113 | text-decoration: none; 114 | } 115 | 116 | a:hover { 117 | color: #55c; 118 | } 119 | 120 | p, ul, ol, dl, h3 { 121 | margin: 2rem; 122 | } 123 | 124 | li { 125 | margin: 0.2rem; 126 | } 127 | 128 | li > ul, li > ol { 129 | margin: 0; 130 | } 131 | 132 | pre { 133 | overflow: auto; 134 | 135 | padding: 1rem 2rem; 136 | font-size: 0.8rem; 137 | 138 | border-top: 1px solid #ccc; 139 | border-bottom: 1px solid #ccc; 140 | 141 | background-color: #eee; 142 | } 143 | 144 | h3 { 145 | border-bottom: 1px solid #ccf; 146 | } 147 | 148 | ul { 149 | margin-bottom: 1rem; 150 | } 151 | 152 | h2, h3, h4, h5, h6 { 153 | font-weight: normal; 154 | } 155 | 156 | body.front h1 { 157 | font-weight: normal; 158 | font-size: 300%; 159 | color: #4caf50; 160 | 161 | text-align: center; 162 | } 163 | 164 | footer { 165 | margin-top: 5rem; 166 | text-align: center; 167 | font-size: 0.65rem; 168 | color: #aaa; 169 | } 170 | 171 | section.features { 172 | display: flex; 173 | flex-wrap: wrap; 174 | justify-content: space-around; 175 | 176 | margin: 1rem 0; 177 | } 178 | 179 | section.features > div { 180 | box-sizing: border-box; 181 | 182 | flex-basis: 20rem; 183 | flex-grow: 1; 184 | 185 | color: #171e42; 186 | margin: 1rem; 187 | padding: 1rem; 188 | 189 | padding-left: 3rem; 190 | 191 | position: relative; 192 | } 193 | 194 | section.features > div i { 195 | position: absolute; 196 | left: 0rem; 197 | 198 | font-size: 1.5rem; 199 | text-align: center; 200 | 201 | width: 3rem; 202 | color: #fafafa; 203 | text-shadow: 0px 0px 1px #000; 204 | } 205 | 206 | section.features div > * { 207 | margin: 0; 208 | maring-bottom: 1rem; 209 | font-size: 80%; 210 | } 211 | 212 | section.features h2 { 213 | margin: 0; 214 | font-size: 90%; 215 | padding: 0; 216 | } 217 | 218 | a.register.button { 219 | font-size: 120%; 220 | 221 | background-color: #d8e6db; 222 | border-radius: 1rem; 223 | padding: 1rem; 224 | 225 | text-decoration: none; 226 | 227 | display: inline-block; /* Ensures the element respects padding and margin */ 228 | margin: 0.5rem; /* Adds space around the button */ 229 | box-sizing: border-box; /* Ensures padding and border are included in the element's total width and height */ 230 | text-align: center; /* Centers the text inside the button */ 231 | white-space: nowrap; /* Prevents the text from wrapping */ 232 | } 233 | 234 | dl { 235 | display: flex; 236 | flex-wrap: wrap; 237 | margin: 1rem; 238 | } 239 | 240 | dt { 241 | width: 25%; 242 | text-align: right; 243 | font-weight: bold; 244 | margin-top: 1rem; 245 | } 246 | 247 | dd { 248 | margin-top: 1rem; 249 | margin-left: auto; 250 | width: 66%; 251 | } 252 | 253 | .game .board { 254 | margin: auto; 255 | } 256 | 257 | .game .board { 258 | border-collapse: collapse; 259 | } 260 | 261 | .game .board td { 262 | text-align: center; 263 | vertical-align: middle; 264 | 265 | width: 4ch; 266 | height: 4ch; 267 | } 268 | 269 | .game .message { 270 | text-align: center; 271 | } 272 | -------------------------------------------------------------------------------- /app/assets/stylesheets/flappy.css: -------------------------------------------------------------------------------- 1 | .flappy { 2 | background-image: url('/assets/flappy-background.png'); 3 | width: 420px; 4 | height: 640px; 5 | margin: auto; 6 | 7 | position: relative; 8 | overflow: hidden; 9 | } 10 | 11 | .flappy .score { 12 | z-index: 10; 13 | padding: 1rem; 14 | color: white; 15 | background-color: rgba(0, 0, 0, 0.5); 16 | position: relative; 17 | } 18 | 19 | .flappy .highscores { 20 | color: white; 21 | } 22 | 23 | .flappy .prompt { 24 | z-index: 20; 25 | padding: 1rem; 26 | color: white; 27 | background-color: rgba(0, 0, 0, 0.5); 28 | 29 | position: absolute; 30 | left: 0; 31 | right: 0; 32 | top: 0; 33 | bottom: 0; 34 | 35 | text-align: center; 36 | } 37 | 38 | .flappy .bird { 39 | z-index: 1; 40 | background-image: url('/assets/flappy-bird.png'); 41 | position: absolute; 42 | background-size: contain; 43 | 44 | transition: all 0.05s linear 0s; 45 | } 46 | 47 | .flappy .pipe { 48 | z-index: 5; 49 | background-image: url('/assets/flappy-pipe.png'); 50 | position: absolute; 51 | background-size: contain; 52 | 53 | transition: all 0.05s linear 0s; 54 | } 55 | -------------------------------------------------------------------------------- /app/channels/application_cable/channel.rb: -------------------------------------------------------------------------------- 1 | module ApplicationCable 2 | class Channel < ActionCable::Channel::Base 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/channels/application_cable/connection.rb: -------------------------------------------------------------------------------- 1 | module ApplicationCable 2 | class Connection < ActionCable::Connection::Base 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::Base 2 | end 3 | -------------------------------------------------------------------------------- /app/controllers/chat_controller.rb: -------------------------------------------------------------------------------- 1 | require 'chat' 2 | require 'async/websocket/adapters/rails' 3 | 4 | class ChatController < ApplicationController 5 | def index 6 | end 7 | 8 | skip_before_action :verify_authenticity_token, only: :connect 9 | 10 | def connect 11 | channel = params.fetch(:channel, 'chat.general') 12 | 13 | self.response = Async::WebSocket::Adapters::Rails.open(request) do |connection| 14 | Sync do 15 | client = Chat::Redis.instance 16 | subscription_task = Async do 17 | # Subscribe to the channel and broadcast incoming messages: 18 | client.subscribe(channel) do |context| 19 | while true 20 | type, name, message = context.listen 21 | 22 | # The message is text, but contains JSON. 23 | connection.send_text(message) 24 | connection.flush 25 | end 26 | end 27 | end 28 | 29 | # Perpetually read incoming messages and publish them to Redis: 30 | while message = connection.read 31 | client.publish(channel, message.buffer) 32 | end 33 | rescue Protocol::WebSocket::ClosedError 34 | # Ignore. 35 | ensure 36 | subscription_task&.stop 37 | end 38 | end 39 | end 40 | end 41 | -------------------------------------------------------------------------------- /app/controllers/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/app/controllers/concerns/.keep -------------------------------------------------------------------------------- /app/controllers/flappy_controller.rb: -------------------------------------------------------------------------------- 1 | require 'async/websocket/adapters/rails' 2 | 3 | class FlappyController < ApplicationController 4 | RESOLVER = Live::Resolver.allow(FlappyTag) 5 | 6 | def index 7 | @tag = FlappyTag.new('flappy') 8 | end 9 | 10 | skip_before_action :verify_authenticity_token, only: :live 11 | 12 | def live 13 | self.response = Async::WebSocket::Adapters::Rails.open(request) do |connection| 14 | Live::Page.new(RESOLVER).run(connection) 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /app/controllers/game_controller.rb: -------------------------------------------------------------------------------- 1 | require 'async/websocket/adapters/rails' 2 | 3 | class GameController < ApplicationController 4 | RESOLVER = Live::Resolver.allow(GameTag) 5 | 6 | def index 7 | @tag = GameTag.new('game') 8 | end 9 | 10 | skip_before_action :verify_authenticity_token, only: :live 11 | 12 | def live 13 | self.response = Async::WebSocket::Adapters::Rails.open(request) do |connection| 14 | Live::Page.new(RESOLVER).run(connection) 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /app/controllers/job_controller.rb: -------------------------------------------------------------------------------- 1 | class JobController < ApplicationController 2 | def index 3 | @job_executions = JobExecution.all 4 | end 5 | 6 | def execute 7 | job = MyJob 8 | 9 | if queue = params[:queue] 10 | job = job.set(queue: queue) 11 | end 12 | 13 | job.perform_later(queued_to: queue) 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /app/controllers/ollama_controller.rb: -------------------------------------------------------------------------------- 1 | require 'async/websocket/adapters/rails' 2 | 3 | class OllamaController < ApplicationController 4 | RESOLVER = Live::Resolver.allow(OllamaTag) 5 | 6 | def index 7 | if id = params[:id] 8 | @conversation = Conversation.find(id) 9 | else 10 | @conversation = Conversation.create!(model: 'llama2:13b') 11 | end 12 | 13 | @tag = OllamaTag.new('ollama', conversation_id: @conversation.id) 14 | end 15 | 16 | skip_before_action :verify_authenticity_token, only: :live 17 | 18 | def live 19 | self.response = Async::WebSocket::Adapters::Rails.open(request) do |connection| 20 | Live::Page.new(RESOLVER).run(connection) 21 | end 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /app/controllers/sse_controller.rb: -------------------------------------------------------------------------------- 1 | class SseController < ApplicationController 2 | def index 3 | end 4 | 5 | EVENT_STREAM_HEADERS = { 6 | 'content-type' => 'text/event-stream', 7 | } 8 | 9 | def events 10 | Highscore.with_connection(prevent_permanent_checkout: true) do 11 | highscore_id = Highscore.last.id 12 | end 13 | 14 | body = proc do |stream| 15 | while true 16 | Console.info(self, "Connection Pool Stat", stats: Highscore.connection_pool.stat) 17 | stream.write("data: #{Time.now}\n\n") 18 | sleep 1 19 | end 20 | end 21 | 22 | self.response = Rack::Response[200, EVENT_STREAM_HEADERS.dup, body] 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /app/controllers/streaming_controller.rb: -------------------------------------------------------------------------------- 1 | class StreamingController < ApplicationController 2 | PREFIX = (("." * 1024) + "\n").freeze 3 | 4 | def index 5 | body = proc do |stream| 6 | # This gets the browser to start rendering interactively: 7 | stream.write(PREFIX) 8 | 9 | 10.downto(1) do |i| 10 | stream.write "#{i} bottles of beer on the wall\n" 11 | sleep 1 12 | stream.write "#{i} bottles of beer\n" 13 | sleep 1 14 | stream.write "Take one down, pass it around\n" 15 | sleep 1 16 | stream.write "#{i - 1} bottles of beer on the wall\n" 17 | sleep 1 18 | end 19 | end 20 | 21 | # Works, puma, falcon, Rails 7.1 22 | self.response = Rack::Response[200, {"content-type" => "text/plain"}, body] 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /app/controllers/welcome_controller.rb: -------------------------------------------------------------------------------- 1 | class WelcomeController < ApplicationController 2 | def index 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/helpers/application_helper.rb: -------------------------------------------------------------------------------- 1 | module ApplicationHelper 2 | end 3 | -------------------------------------------------------------------------------- /app/helpers/chat_helper.rb: -------------------------------------------------------------------------------- 1 | module ChatHelper 2 | end 3 | -------------------------------------------------------------------------------- /app/helpers/flappy_helper.rb: -------------------------------------------------------------------------------- 1 | module FlappyHelper 2 | end 3 | -------------------------------------------------------------------------------- /app/helpers/game_helper.rb: -------------------------------------------------------------------------------- 1 | module GameHelper 2 | end 3 | -------------------------------------------------------------------------------- /app/helpers/job_helper.rb: -------------------------------------------------------------------------------- 1 | module JobHelper 2 | end 3 | -------------------------------------------------------------------------------- /app/helpers/ollama_helper.rb: -------------------------------------------------------------------------------- 1 | module OllamaHelper 2 | end 3 | -------------------------------------------------------------------------------- /app/helpers/sse_helper.rb: -------------------------------------------------------------------------------- 1 | module SseHelper 2 | end 3 | -------------------------------------------------------------------------------- /app/helpers/streaming_helper.rb: -------------------------------------------------------------------------------- 1 | module StreamingHelper 2 | end 3 | -------------------------------------------------------------------------------- /app/helpers/welcome_helper.rb: -------------------------------------------------------------------------------- 1 | module WelcomeHelper 2 | end 3 | -------------------------------------------------------------------------------- /app/javascript/application.js: -------------------------------------------------------------------------------- 1 | // Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails 2 | import "@hotwired/turbo-rails" 3 | import "controllers" 4 | -------------------------------------------------------------------------------- /app/javascript/controllers/application.js: -------------------------------------------------------------------------------- 1 | import { Application } from "@hotwired/stimulus" 2 | 3 | const application = Application.start() 4 | 5 | // Configure Stimulus development experience 6 | application.debug = false 7 | window.Stimulus = application 8 | 9 | export { application } 10 | -------------------------------------------------------------------------------- /app/javascript/controllers/index.js: -------------------------------------------------------------------------------- 1 | // Import and register all your controllers from the importmap under controllers/* 2 | 3 | import { application } from "controllers/application" 4 | 5 | // Eager load all controllers defined in the import map under controllers/**/*_controller 6 | import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading" 7 | eagerLoadControllersFrom("controllers", application) 8 | 9 | // Lazy load controllers as they appear in the DOM (remember not to preload controllers in import map!) 10 | // import { lazyLoadControllersFrom } from "@hotwired/stimulus-loading" 11 | // lazyLoadControllersFrom("controllers", application) 12 | -------------------------------------------------------------------------------- /app/javascript/live.js: -------------------------------------------------------------------------------- 1 | import {Live} from "@socketry/live" 2 | window.live = Live.start() 3 | -------------------------------------------------------------------------------- /app/jobs/application_job.rb: -------------------------------------------------------------------------------- 1 | class ApplicationJob < ActiveJob::Base 2 | # Automatically retry jobs that encountered a deadlock 3 | # retry_on ActiveRecord::Deadlocked 4 | 5 | # Most jobs are safe to ignore if the underlying records are no longer available 6 | # discard_on ActiveJob::DeserializationError 7 | end 8 | -------------------------------------------------------------------------------- /app/jobs/my_job.rb: -------------------------------------------------------------------------------- 1 | class MyJob < ApplicationJob 2 | queue_as "default" 3 | 4 | def perform(*arguments) 5 | JobExecution.create!(name: self.class.name, data: { 6 | arguments: arguments, 7 | }) 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /app/mailers/application_mailer.rb: -------------------------------------------------------------------------------- 1 | class ApplicationMailer < ActionMailer::Base 2 | default from: "from@example.com" 3 | layout "mailer" 4 | end 5 | -------------------------------------------------------------------------------- /app/models/application_record.rb: -------------------------------------------------------------------------------- 1 | class ApplicationRecord < ActiveRecord::Base 2 | primary_abstract_class 3 | end 4 | -------------------------------------------------------------------------------- /app/models/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/app/models/concerns/.keep -------------------------------------------------------------------------------- /app/models/conversation.rb: -------------------------------------------------------------------------------- 1 | class Conversation < ApplicationRecord 2 | has_many :conversation_messages 3 | end 4 | -------------------------------------------------------------------------------- /app/models/conversation_message.rb: -------------------------------------------------------------------------------- 1 | class ConversationMessage < ApplicationRecord 2 | end 3 | -------------------------------------------------------------------------------- /app/models/highscore.rb: -------------------------------------------------------------------------------- 1 | class Highscore < ApplicationRecord 2 | end 3 | -------------------------------------------------------------------------------- /app/models/job_execution.rb: -------------------------------------------------------------------------------- 1 | class JobExecution < ApplicationRecord 2 | # broadcasts_refreshes 3 | after_create_commit -> { broadcast_append_to "job_executions" } 4 | end 5 | -------------------------------------------------------------------------------- /app/views/chat/index.html.erb: -------------------------------------------------------------------------------- 1 |

Chat

2 | 3 | 4 |
5 | 6 |
7 | 8 |
-------------------------------------------------------------------------------- /app/views/flappy/index.html.erb: -------------------------------------------------------------------------------- 1 |

Flappy

2 | 3 | <%= javascript_import_module_tag "live" %> 4 | <%= stylesheet_link_tag "flappy" %> 5 | 6 | <%= raw @tag.to_html %> 7 | -------------------------------------------------------------------------------- /app/views/game/index.html.erb: -------------------------------------------------------------------------------- 1 |

Robot Finds Kitten

2 | 3 | <%= javascript_import_module_tag "live" %> 4 | 5 |

To play the game, use the arrow keys (or WSAD). Click on the board to give it focus.

6 | 7 | <%= raw @tag.to_html %> 8 | -------------------------------------------------------------------------------- /app/views/job/index.html.erb: -------------------------------------------------------------------------------- 1 |

Async Job

2 | 3 |
4 | 9 | 10 |
11 | 12 |

Job Executions

13 | <%= turbo_stream_from "job_executions" %> 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | <%= render @job_executions %> 25 | 26 |
IDNameData
27 | -------------------------------------------------------------------------------- /app/views/job_executions/_job_execution.html.erb: -------------------------------------------------------------------------------- 1 | 2 | <%= job_execution.id %> 3 | <%= job_execution.name %> 4 | <%= job_execution.data %> 5 | -------------------------------------------------------------------------------- /app/views/layouts/application.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Falcon Examples 5 | 6 | <%= csrf_meta_tags %> 7 | <%= csp_meta_tag %> 8 | 9 | <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %> 10 | <%= javascript_importmap_tags %> 11 | 12 | 13 | 14 |
15 | <%= image_tag "Falcon.png", alt: "Falcon Logo", id: 'logo' %> 16 |
17 | 18 |
19 | <%= yield %> 20 |
21 | 22 | 23 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 8 | 9 | 10 | 11 | <%= yield %> 12 | 13 | 14 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.text.erb: -------------------------------------------------------------------------------- 1 | <%= yield %> 2 | -------------------------------------------------------------------------------- /app/views/ollama/index.html.erb: -------------------------------------------------------------------------------- 1 |

Ollama

2 | 3 | <%= javascript_import_module_tag "live" %> 4 | 5 | <%= raw @tag.to_html %> 6 | -------------------------------------------------------------------------------- /app/views/sse/index.html.erb: -------------------------------------------------------------------------------- 1 |

SSE Events

2 | 3 |
4 | -------------------------------------------------------------------------------- /app/views/welcome/index.html.erb: -------------------------------------------------------------------------------- 1 |

Ruby on Rails on Falcon

2 | 3 |

Welcome to the Ruby on Rails on Falcon demo application.

4 | 5 |

Examples

6 | 7 | 16 | -------------------------------------------------------------------------------- /bin/bundle: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | # 5 | # This file was generated by Bundler. 6 | # 7 | # The application 'bundle' is installed as part of a gem, and 8 | # this file is here to facilitate running it. 9 | # 10 | 11 | require "rubygems" 12 | 13 | m = Module.new do 14 | module_function 15 | 16 | def invoked_as_script? 17 | File.expand_path($0) == File.expand_path(__FILE__) 18 | end 19 | 20 | def env_var_version 21 | ENV["BUNDLER_VERSION"] 22 | end 23 | 24 | def cli_arg_version 25 | return unless invoked_as_script? # don't want to hijack other binstubs 26 | return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update` 27 | bundler_version = nil 28 | update_index = nil 29 | ARGV.each_with_index do |a, i| 30 | if update_index && update_index.succ == i && a.match?(Gem::Version::ANCHORED_VERSION_PATTERN) 31 | bundler_version = a 32 | end 33 | next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/ 34 | bundler_version = $1 35 | update_index = i 36 | end 37 | bundler_version 38 | end 39 | 40 | def gemfile 41 | gemfile = ENV["BUNDLE_GEMFILE"] 42 | return gemfile if gemfile && !gemfile.empty? 43 | 44 | File.expand_path("../Gemfile", __dir__) 45 | end 46 | 47 | def lockfile 48 | lockfile = 49 | case File.basename(gemfile) 50 | when "gems.rb" then gemfile.sub(/\.rb$/, ".locked") 51 | else "#{gemfile}.lock" 52 | end 53 | File.expand_path(lockfile) 54 | end 55 | 56 | def lockfile_version 57 | return unless File.file?(lockfile) 58 | lockfile_contents = File.read(lockfile) 59 | return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/ 60 | Regexp.last_match(1) 61 | end 62 | 63 | def bundler_requirement 64 | @bundler_requirement ||= 65 | env_var_version || 66 | cli_arg_version || 67 | bundler_requirement_for(lockfile_version) 68 | end 69 | 70 | def bundler_requirement_for(version) 71 | return "#{Gem::Requirement.default}.a" unless version 72 | 73 | bundler_gem_version = Gem::Version.new(version) 74 | 75 | bundler_gem_version.approximate_recommendation 76 | end 77 | 78 | def load_bundler! 79 | ENV["BUNDLE_GEMFILE"] ||= gemfile 80 | 81 | activate_bundler 82 | end 83 | 84 | def activate_bundler 85 | gem_error = activation_error_handling do 86 | gem "bundler", bundler_requirement 87 | end 88 | return if gem_error.nil? 89 | require_error = activation_error_handling do 90 | require "bundler/version" 91 | end 92 | return if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION)) 93 | 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}'`" 94 | exit 42 95 | end 96 | 97 | def activation_error_handling 98 | yield 99 | nil 100 | rescue StandardError, LoadError => e 101 | e 102 | end 103 | end 104 | 105 | m.load_bundler! 106 | 107 | if m.invoked_as_script? 108 | load Gem.bin_path("bundler", "bundle") 109 | end 110 | -------------------------------------------------------------------------------- /bin/docker-entrypoint: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | 3 | # If running the rails server then create or migrate existing database 4 | if [ "${1}" == "./bin/rails" ] && [ "${2}" == "server" ]; then 5 | ./bin/rails db:prepare 6 | fi 7 | 8 | exec "${@}" 9 | -------------------------------------------------------------------------------- /bin/importmap: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | require_relative "../config/application" 4 | require "importmap/commands" 5 | -------------------------------------------------------------------------------- /bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | APP_PATH = File.expand_path("../config/application", __dir__) 3 | require_relative "../config/boot" 4 | require "rails/commands" 5 | -------------------------------------------------------------------------------- /bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require_relative "../config/boot" 3 | require "rake" 4 | Rake.application.run 5 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require "fileutils" 3 | 4 | # path to your application root. 5 | APP_ROOT = File.expand_path("..", __dir__) 6 | 7 | def system!(*args) 8 | system(*args, exception: true) 9 | end 10 | 11 | FileUtils.chdir APP_ROOT do 12 | # This script is a way to set up or update your development environment automatically. 13 | # This script is idempotent, so that you can run it at any time and get an expectable outcome. 14 | # Add necessary setup steps to this file. 15 | 16 | puts "== Installing dependencies ==" 17 | system! "gem install bundler --conservative" 18 | system("bundle check") || system!("bundle install") 19 | 20 | # puts "\n== Copying sample files ==" 21 | # unless File.exist?("config/database.yml") 22 | # FileUtils.cp "config/database.yml.sample", "config/database.yml" 23 | # end 24 | 25 | puts "\n== Preparing database ==" 26 | system! "bin/rails db:prepare" 27 | 28 | puts "\n== Removing old logs and tempfiles ==" 29 | system! "bin/rails log:clear tmp:clear" 30 | 31 | puts "\n== Restarting application server ==" 32 | system! "bin/rails restart" 33 | end 34 | -------------------------------------------------------------------------------- /config.ru: -------------------------------------------------------------------------------- 1 | # This file is used by Rack-based servers to start the application. 2 | 3 | require_relative "config/environment" 4 | 5 | run Rails.application 6 | Rails.application.load_server 7 | -------------------------------------------------------------------------------- /config/application.rb: -------------------------------------------------------------------------------- 1 | require_relative "boot" 2 | 3 | require "rails/all" 4 | 5 | # Require the gems listed in Gemfile, including any gems 6 | # you've limited to :test, :development, or :production. 7 | Bundler.require(*Rails.groups) 8 | 9 | module Example 10 | class Application < Rails::Application 11 | # Initialize configuration defaults for originally generated Rails version. 12 | config.load_defaults 7.1 13 | 14 | # Please, add to the `ignore` list any other `lib` subdirectories that do 15 | # not contain `.rb` files, or that should not be reloaded or eager loaded. 16 | # Common ones are `templates`, `generators`, or `middleware`, for example. 17 | config.autoload_lib(ignore: %w(assets tasks)) 18 | 19 | # Configuration for the application, engines, and railties goes here. 20 | # 21 | # These settings can be overridden in specific environments using the files 22 | # in config/environments, which are processed later. 23 | # 24 | # config.time_zone = "Central Time (US & Canada)" 25 | # config.eager_load_paths << Rails.root.join("extras") 26 | 27 | # Disallow permanent checkout of activerecord connections (request scope): 28 | config.active_record.permanent_connection_checkout = :disallowed 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /config/boot.rb: -------------------------------------------------------------------------------- 1 | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) 2 | 3 | require "bundler/setup" # Set up gems listed in the Gemfile. 4 | require "bootsnap/setup" # Speed up boot time by caching expensive operations. 5 | -------------------------------------------------------------------------------- /config/cable.yml: -------------------------------------------------------------------------------- 1 | development: 2 | adapter: redis 3 | url: redis://localhost:6379/1 4 | 5 | test: 6 | adapter: test 7 | 8 | production: 9 | adapter: redis 10 | url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> 11 | channel_prefix: example_production 12 | -------------------------------------------------------------------------------- /config/credentials.yml.enc: -------------------------------------------------------------------------------- 1 | 1inyjp7w8IupChyIs0yI1Bpi2HJB99JBymXnFt9lSeAWOjDWgF7WPQiWR1PvDWMB6M8v1B2DLTEIN28/YYKQ1p4y0RUbrvAjoy/OY7VqgwWzaeJ5xhvpg4+LjcapJLXzYjL3NBGiiIvAkEwxgsuKgqtt15B7qAFPpqBHgpFLue63dLIcE0U1idabYGqUL2f8uwAa2j7qLtNKTF0lQese5Ia2y7kFhL/8zLL9cY5B0TYIIzOy3BkOBhQoRuquYIq7nOYBPQ1PaQ1GzWf7ERxHw0c7Q4iJ+vwhwzgUDmyAjWhAjv4EqLi936D9sx2rTecp+QLWTYN7A3HVcPotcGd5LyMIab5u6o2RGYLerIJRtHlUr8Yz3AlWvsHm4Gebv/bV+zktXvIzyejBw7rpMZ2D36pj0ohQ--S5SpB2BE7Th+GpZE--gPTz2YeZbwb8zuv/Ay1p2g== -------------------------------------------------------------------------------- /config/database.yml: -------------------------------------------------------------------------------- 1 | # SQLite. Versions 3.8.0 and up are supported. 2 | # gem install sqlite3 3 | # 4 | # Ensure the SQLite 3 gem is defined in your Gemfile 5 | # gem "sqlite3" 6 | # 7 | default: &default 8 | adapter: sqlite3 9 | pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> 10 | timeout: 5000 11 | 12 | development: 13 | <<: *default 14 | database: storage/development.sqlite3 15 | 16 | # Warning: The database defined as "test" will be erased and 17 | # re-generated from your development database when you run "rake". 18 | # Do not set this db to the same as development or production. 19 | test: 20 | <<: *default 21 | database: storage/test.sqlite3 22 | 23 | production: 24 | <<: *default 25 | database: storage/production.sqlite3 26 | -------------------------------------------------------------------------------- /config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the Rails application. 2 | require_relative "application" 3 | 4 | require 'console/adapter/rails' 5 | Console::Adapter::Rails.apply! 6 | 7 | # Initialize the Rails application. 8 | Rails.application.initialize! 9 | -------------------------------------------------------------------------------- /config/environments/development.rb: -------------------------------------------------------------------------------- 1 | require "active_support/core_ext/integer/time" 2 | 3 | Rails.application.configure do 4 | # Settings specified here will take precedence over those in config/application.rb. 5 | 6 | # In the development environment your application's code is reloaded any time 7 | # it changes. This slows down response time but is perfect for development 8 | # since you don't have to restart the web server when you make code changes. 9 | config.enable_reloading = true 10 | 11 | # Do not eager load code on boot. 12 | config.eager_load = false 13 | 14 | # Show full error reports. 15 | config.consider_all_requests_local = true 16 | 17 | # Enable server timing 18 | config.server_timing = true 19 | 20 | # Enable/disable caching. By default caching is disabled. 21 | # Run rails dev:cache to toggle caching. 22 | if Rails.root.join("tmp/caching-dev.txt").exist? 23 | config.action_controller.perform_caching = true 24 | config.action_controller.enable_fragment_cache_logging = true 25 | 26 | config.cache_store = :memory_store 27 | config.public_file_server.headers = { 28 | "Cache-Control" => "public, max-age=#{2.days.to_i}" 29 | } 30 | else 31 | config.action_controller.perform_caching = false 32 | 33 | config.cache_store = :null_store 34 | end 35 | 36 | # Store uploaded files on the local file system (see config/storage.yml for options). 37 | config.active_storage.service = :local 38 | 39 | # Don't care if the mailer can't send. 40 | config.action_mailer.raise_delivery_errors = false 41 | 42 | config.action_mailer.perform_caching = false 43 | 44 | # Print deprecation notices to the Rails logger. 45 | config.active_support.deprecation = :log 46 | 47 | # Raise exceptions for disallowed deprecations. 48 | config.active_support.disallowed_deprecation = :raise 49 | 50 | # Tell Active Support which deprecation messages to disallow. 51 | config.active_support.disallowed_deprecation_warnings = [] 52 | 53 | # Raise an error on page load if there are pending migrations. 54 | config.active_record.migration_error = :page_load 55 | 56 | # Highlight code that triggered database queries in logs. 57 | config.active_record.verbose_query_logs = true 58 | 59 | # Highlight code that enqueued background job in logs. 60 | config.active_job.verbose_enqueue_logs = true 61 | 62 | # Suppress logger output for asset requests. 63 | config.assets.quiet = true 64 | 65 | # Raises error for missing translations. 66 | # config.i18n.raise_on_missing_translations = true 67 | 68 | # Annotate rendered view with file names. 69 | # config.action_view.annotate_rendered_view_with_filenames = true 70 | 71 | # Uncomment if you wish to allow Action Cable access from any origin. 72 | # config.action_cable.disable_request_forgery_protection = true 73 | 74 | # Raise error when a before_action's only/except options reference missing actions 75 | config.action_controller.raise_on_missing_callback_actions = true 76 | end 77 | -------------------------------------------------------------------------------- /config/environments/production.rb: -------------------------------------------------------------------------------- 1 | require "active_support/core_ext/integer/time" 2 | 3 | Rails.application.configure do 4 | # Settings specified here will take precedence over those in config/application.rb. 5 | 6 | # Code is not reloaded between requests. 7 | config.enable_reloading = false 8 | 9 | # Eager load code on boot. This eager loads most of Rails and 10 | # your application in memory, allowing both threaded web servers 11 | # and those relying on copy on write to perform better. 12 | # Rake tasks automatically ignore this option for performance. 13 | config.eager_load = true 14 | 15 | # Full error reports are disabled and caching is turned on. 16 | config.consider_all_requests_local = false 17 | config.action_controller.perform_caching = true 18 | 19 | # Ensures that a master key has been made available in ENV["RAILS_MASTER_KEY"], config/master.key, or an environment 20 | # key such as config/credentials/production.key. This key is used to decrypt credentials (and other encrypted files). 21 | # config.require_master_key = true 22 | 23 | # Disable serving static files from `public/`, relying on NGINX/Apache to do so instead. 24 | # config.public_file_server.enabled = false 25 | 26 | # Compress CSS using a preprocessor. 27 | # config.assets.css_compressor = :sass 28 | 29 | # Do not fall back to assets pipeline if a precompiled asset is missed. 30 | config.assets.compile = false 31 | 32 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 33 | # config.asset_host = "http://assets.example.com" 34 | 35 | # Specifies the header that your server uses for sending files. 36 | # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache 37 | # config.action_dispatch.x_sendfile_header = "X-Accel-Redirect" # for NGINX 38 | 39 | # Store uploaded files on the local file system (see config/storage.yml for options). 40 | config.active_storage.service = :local 41 | 42 | # Mount Action Cable outside main process or domain. 43 | # config.action_cable.mount_path = nil 44 | # config.action_cable.url = "wss://example.com/cable" 45 | # config.action_cable.allowed_request_origins = [ "http://example.com", /http:\/\/example.*/ ] 46 | 47 | # Assume all access to the app is happening through a SSL-terminating reverse proxy. 48 | # Can be used together with config.force_ssl for Strict-Transport-Security and secure cookies. 49 | # config.assume_ssl = true 50 | 51 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 52 | config.force_ssl = true 53 | 54 | # Log to STDOUT by default 55 | config.logger = ActiveSupport::Logger.new(STDOUT) 56 | .tap { |logger| logger.formatter = ::Logger::Formatter.new } 57 | .then { |logger| ActiveSupport::TaggedLogging.new(logger) } 58 | 59 | # Prepend all log lines with the following tags. 60 | config.log_tags = [ :request_id ] 61 | 62 | # "info" includes generic and useful information about system operation, but avoids logging too much 63 | # information to avoid inadvertent exposure of personally identifiable information (PII). If you 64 | # want to log everything, set the level to "debug". 65 | config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info") 66 | 67 | # Use a different cache store in production. 68 | # config.cache_store = :mem_cache_store 69 | 70 | # Use a real queuing backend for Active Job (and separate queues per environment). 71 | # config.active_job.queue_adapter = :resque 72 | # config.active_job.queue_name_prefix = "async_job_test_production" 73 | 74 | config.action_mailer.perform_caching = false 75 | 76 | # Ignore bad email addresses and do not raise email delivery errors. 77 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 78 | # config.action_mailer.raise_delivery_errors = false 79 | 80 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 81 | # the I18n.default_locale when a translation cannot be found). 82 | config.i18n.fallbacks = true 83 | 84 | # Don't log any deprecations. 85 | config.active_support.report_deprecations = false 86 | 87 | # Do not dump schema after migrations. 88 | config.active_record.dump_schema_after_migration = false 89 | 90 | # Enable DNS rebinding protection and other `Host` header attacks. 91 | # config.hosts = [ 92 | # "example.com", # Allow requests from example.com 93 | # /.*\.example\.com/ # Allow requests from subdomains like `www.example.com` 94 | # ] 95 | # Skip DNS rebinding protection for the default health check endpoint. 96 | # config.host_authorization = { exclude: ->(request) { request.path == "/up" } } 97 | end 98 | -------------------------------------------------------------------------------- /config/environments/test.rb: -------------------------------------------------------------------------------- 1 | require "active_support/core_ext/integer/time" 2 | 3 | # The test environment is used exclusively to run your application's 4 | # test suite. You never need to work with it otherwise. Remember that 5 | # your test database is "scratch space" for the test suite and is wiped 6 | # and recreated between test runs. Don't rely on the data there! 7 | 8 | Rails.application.configure do 9 | # Settings specified here will take precedence over those in config/application.rb. 10 | 11 | # While tests run files are not watched, reloading is not necessary. 12 | config.enable_reloading = false 13 | 14 | # Eager loading loads your entire application. When running a single test locally, 15 | # this is usually not necessary, and can slow down your test suite. However, it's 16 | # recommended that you enable it in continuous integration systems to ensure eager 17 | # loading is working properly before deploying your code. 18 | config.eager_load = ENV["CI"].present? 19 | 20 | # Configure public file server for tests with Cache-Control for performance. 21 | config.public_file_server.enabled = true 22 | config.public_file_server.headers = { 23 | "Cache-Control" => "public, max-age=#{1.hour.to_i}" 24 | } 25 | 26 | # Show full error reports and disable caching. 27 | config.consider_all_requests_local = true 28 | config.action_controller.perform_caching = false 29 | config.cache_store = :null_store 30 | 31 | # Render exception templates for rescuable exceptions and raise for other exceptions. 32 | config.action_dispatch.show_exceptions = :rescuable 33 | 34 | # Disable request forgery protection in test environment. 35 | config.action_controller.allow_forgery_protection = false 36 | 37 | # Store uploaded files on the local file system in a temporary directory. 38 | config.active_storage.service = :test 39 | 40 | config.action_mailer.perform_caching = false 41 | 42 | # Tell Action Mailer not to deliver emails to the real world. 43 | # The :test delivery method accumulates sent emails in the 44 | # ActionMailer::Base.deliveries array. 45 | config.action_mailer.delivery_method = :test 46 | 47 | # Print deprecation notices to the stderr. 48 | config.active_support.deprecation = :stderr 49 | 50 | # Raise exceptions for disallowed deprecations. 51 | config.active_support.disallowed_deprecation = :raise 52 | 53 | # Tell Active Support which deprecation messages to disallow. 54 | config.active_support.disallowed_deprecation_warnings = [] 55 | 56 | # Raises error for missing translations. 57 | # config.i18n.raise_on_missing_translations = true 58 | 59 | # Annotate rendered view with file names. 60 | # config.action_view.annotate_rendered_view_with_filenames = true 61 | 62 | # Raise error when a before_action's only/except options reference missing actions 63 | config.action_controller.raise_on_missing_callback_actions = true 64 | end 65 | -------------------------------------------------------------------------------- /config/importmap.rb: -------------------------------------------------------------------------------- 1 | # Pin npm packages by running ./bin/importmap 2 | 3 | pin "application", preload: true 4 | 5 | pin "@hotwired/turbo-rails", to: "turbo.min.js", preload: true 6 | pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true 7 | pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true 8 | pin_all_from "app/javascript/controllers", under: "controllers" 9 | 10 | pin "morphdom" # @2.7.2 11 | pin "@socketry/live", to: "@socketry--live.js" # @0.13.0 12 | pin "live" 13 | -------------------------------------------------------------------------------- /config/initializers/assets.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Version of your assets, change this if you want to expire all your assets. 4 | Rails.application.config.assets.version = "1.0" 5 | 6 | # Add additional assets to the asset load path. 7 | # Rails.application.config.assets.paths << Emoji.images_path 8 | 9 | # Precompile additional assets. 10 | # application.js, application.css, and all non-JS/CSS in the app/assets 11 | # folder are already added. 12 | # Rails.application.config.assets.precompile += %w( admin.js admin.css ) 13 | -------------------------------------------------------------------------------- /config/initializers/async_job.rb: -------------------------------------------------------------------------------- 1 | 2 | require 'async/job' 3 | require 'async/job/backend/redis' 4 | require 'async/job/backend/inline' 5 | 6 | Rails.application.configure do 7 | config.async_job.backend_for "default" do 8 | queue Async::Job::Backend::Redis 9 | end 10 | 11 | config.async_job.backend_for "local" do 12 | queue Async::Job::Backend::Inline 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /config/initializers/content_security_policy.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Define an application-wide content security policy. 4 | # See the Securing Rails Applications Guide for more information: 5 | # https://guides.rubyonrails.org/security.html#content-security-policy-header 6 | 7 | # Rails.application.configure do 8 | # config.content_security_policy do |policy| 9 | # policy.default_src :self, :https 10 | # policy.font_src :self, :https, :data 11 | # policy.img_src :self, :https, :data 12 | # policy.object_src :none 13 | # policy.script_src :self, :https 14 | # policy.style_src :self, :https 15 | # # Specify URI for violation reports 16 | # # policy.report_uri "/csp-violation-report-endpoint" 17 | # end 18 | # 19 | # # Generate session nonces for permitted importmap, inline scripts, and inline styles. 20 | # config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s } 21 | # config.content_security_policy_nonce_directives = %w(script-src style-src) 22 | # 23 | # # Report violations without enforcing the policy. 24 | # # config.content_security_policy_report_only = true 25 | # end 26 | -------------------------------------------------------------------------------- /config/initializers/filter_parameter_logging.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Configure parameters to be partially matched (e.g. passw matches password) and filtered from the log file. 4 | # Use this to limit dissemination of sensitive information. 5 | # See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors. 6 | Rails.application.config.filter_parameters += [ 7 | :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn 8 | ] 9 | -------------------------------------------------------------------------------- /config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new inflection rules using the following format. Inflections 4 | # are locale specific, and you may define rules for as many different 5 | # locales as you wish. All of these examples are active by default: 6 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 7 | # inflect.plural /^(ox)$/i, "\\1en" 8 | # inflect.singular /^(ox)en/i, "\\1" 9 | # inflect.irregular "person", "people" 10 | # inflect.uncountable %w( fish sheep ) 11 | # end 12 | 13 | # These inflection rules are supported but not enabled by default: 14 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 15 | # inflect.acronym "RESTful" 16 | # end 17 | -------------------------------------------------------------------------------- /config/initializers/permissions_policy.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Define an application-wide HTTP permissions policy. For further 4 | # information see: https://developers.google.com/web/updates/2018/06/feature-policy 5 | 6 | # Rails.application.config.permissions_policy do |policy| 7 | # policy.camera :none 8 | # policy.gyroscope :none 9 | # policy.microphone :none 10 | # policy.usb :none 11 | # policy.fullscreen :self 12 | # policy.payment :self, "https://secure.example.com" 13 | # end 14 | -------------------------------------------------------------------------------- /config/locales/en.yml: -------------------------------------------------------------------------------- 1 | # Files in the config/locales directory are used for internationalization and 2 | # are automatically loaded by Rails. If you want to use locales other than 3 | # English, add the necessary files in this directory. 4 | # 5 | # To use the locales, use `I18n.t`: 6 | # 7 | # I18n.t "hello" 8 | # 9 | # In views, this is aliased to just `t`: 10 | # 11 | # <%= t("hello") %> 12 | # 13 | # To use a different locale, set it with `I18n.locale`: 14 | # 15 | # I18n.locale = :es 16 | # 17 | # This would use the information in config/locales/es.yml. 18 | # 19 | # To learn more about the API, please read the Rails Internationalization guide 20 | # at https://guides.rubyonrails.org/i18n.html. 21 | # 22 | # Be aware that YAML interprets the following case-insensitive strings as 23 | # booleans: `true`, `false`, `on`, `off`, `yes`, `no`. Therefore, these strings 24 | # must be quoted to be interpreted as strings. For example: 25 | # 26 | # en: 27 | # "yes": yup 28 | # enabled: "ON" 29 | 30 | en: 31 | hello: "Hello world" 32 | -------------------------------------------------------------------------------- /config/puma.rb: -------------------------------------------------------------------------------- 1 | # This configuration file will be evaluated by Puma. The top-level methods that 2 | # are invoked here are part of Puma's configuration DSL. For more information 3 | # about methods provided by the DSL, see https://puma.io/puma/Puma/DSL.html. 4 | 5 | # Puma can serve each request in a thread from an internal thread pool. 6 | # The `threads` method setting takes two numbers: a minimum and maximum. 7 | # Any libraries that use thread pools should be configured to match 8 | # the maximum value specified for Puma. Default is set to 5 threads for minimum 9 | # and maximum; this matches the default thread size of Active Record. 10 | max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } 11 | min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count } 12 | threads min_threads_count, max_threads_count 13 | 14 | # Specifies that the worker count should equal the number of processors in production. 15 | if ENV["RAILS_ENV"] == "production" 16 | require "concurrent-ruby" 17 | worker_count = Integer(ENV.fetch("WEB_CONCURRENCY") { Concurrent.physical_processor_count }) 18 | workers worker_count if worker_count > 1 19 | end 20 | 21 | # Specifies the `worker_timeout` threshold that Puma will use to wait before 22 | # terminating a worker in development environments. 23 | worker_timeout 3600 if ENV.fetch("RAILS_ENV", "development") == "development" 24 | 25 | # Specifies the `port` that Puma will listen on to receive requests; default is 3000. 26 | port ENV.fetch("PORT") { 3000 } 27 | 28 | # Specifies the `environment` that Puma will run in. 29 | environment ENV.fetch("RAILS_ENV") { "development" } 30 | 31 | # Specifies the `pidfile` that Puma will use. 32 | pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } 33 | 34 | # Allow puma to be restarted by `bin/rails restart` command. 35 | plugin :tmp_restart 36 | -------------------------------------------------------------------------------- /config/routes.rb: -------------------------------------------------------------------------------- 1 | Rails.application.routes.draw do 2 | # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html 3 | root "welcome#index" 4 | 5 | # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500. 6 | # Can be used by load balancers and uptime monitors to verify that the app is live. 7 | get "up" => "rails/health#show", as: :rails_health_check 8 | 9 | # Streaming Example: 10 | get 'streaming/index' 11 | 12 | # Chat Example: 13 | get "chat/index" 14 | match "chat/connect", via: [:get, :connect] 15 | 16 | # Game Example: 17 | get "game/index" 18 | match "game/live", via: [:get, :connect] 19 | 20 | # Job Example: 21 | get "job/index" 22 | post "job/execute" 23 | 24 | # Ollama Example: 25 | get "ollama/index" 26 | match "ollama/live", via: [:get, :connect] 27 | 28 | # Flappy Example: 29 | get "flappy/index" 30 | match "flappy/live", via: [:get, :connect] 31 | 32 | # SSE Example: 33 | get 'sse/index' 34 | get 'sse/events' 35 | end 36 | -------------------------------------------------------------------------------- /config/storage.yml: -------------------------------------------------------------------------------- 1 | test: 2 | service: Disk 3 | root: <%= Rails.root.join("tmp/storage") %> 4 | 5 | local: 6 | service: Disk 7 | root: <%= Rails.root.join("storage") %> 8 | 9 | # Use bin/rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) 10 | # amazon: 11 | # service: S3 12 | # access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> 13 | # secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> 14 | # region: us-east-1 15 | # bucket: your_own_bucket-<%= Rails.env %> 16 | 17 | # Remember not to checkin your GCS keyfile to a repository 18 | # google: 19 | # service: GCS 20 | # project: your_project 21 | # credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> 22 | # bucket: your_own_bucket-<%= Rails.env %> 23 | 24 | # Use bin/rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) 25 | # microsoft: 26 | # service: AzureStorage 27 | # storage_account_name: your_account_name 28 | # storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> 29 | # container: your_container_name-<%= Rails.env %> 30 | 31 | # mirror: 32 | # service: Mirror 33 | # primary: local 34 | # mirrors: [ amazon, google, microsoft ] 35 | -------------------------------------------------------------------------------- /db/migrate/20240225111326_create_job_executions.rb: -------------------------------------------------------------------------------- 1 | class CreateJobExecutions < ActiveRecord::Migration[7.1] 2 | def change 3 | create_table :job_executions do |t| 4 | t.string :name 5 | t.json :data 6 | 7 | t.timestamps 8 | end 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /db/migrate/20240411023610_create_conversations.rb: -------------------------------------------------------------------------------- 1 | class CreateConversations < ActiveRecord::Migration[7.1] 2 | def change 3 | create_table :conversations do |t| 4 | t.string "model", null: false 5 | t.timestamps 6 | end 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /db/migrate/20240411023621_create_conversation_messages.rb: -------------------------------------------------------------------------------- 1 | class CreateConversationMessages < ActiveRecord::Migration[7.1] 2 | def change 3 | create_table :conversation_messages do |t| 4 | t.belongs_to :conversation, null: false, foreign_key: true 5 | 6 | t.json :context 7 | t.text :prompt 8 | t.text :response 9 | t.timestamps 10 | end 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /db/migrate/20240414035057_create_highscores.rb: -------------------------------------------------------------------------------- 1 | class CreateHighscores < ActiveRecord::Migration[7.1] 2 | def change 3 | create_table :highscores do |t| 4 | t.string :name 5 | t.integer :score 6 | t.timestamps 7 | end 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /db/schema.rb: -------------------------------------------------------------------------------- 1 | # This file is auto-generated from the current state of the database. Instead 2 | # of editing this file, please use the migrations feature of Active Record to 3 | # incrementally modify your database, and then regenerate this schema definition. 4 | # 5 | # This file is the source Rails uses to define your schema when running `bin/rails 6 | # db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to 7 | # be faster and is potentially less error prone than running all of your 8 | # migrations from scratch. Old migrations may fail to apply correctly if those 9 | # migrations use external dependencies or application code. 10 | # 11 | # It's strongly recommended that you check this file into your version control system. 12 | 13 | ActiveRecord::Schema[7.1].define(version: 2024_04_14_035057) do 14 | create_table "conversation_messages", force: :cascade do |t| 15 | t.integer "conversation_id", null: false 16 | t.json "context" 17 | t.text "prompt" 18 | t.text "response" 19 | t.datetime "created_at", null: false 20 | t.datetime "updated_at", null: false 21 | t.index ["conversation_id"], name: "index_conversation_messages_on_conversation_id" 22 | end 23 | 24 | create_table "conversations", force: :cascade do |t| 25 | t.string "model", null: false 26 | t.datetime "created_at", null: false 27 | t.datetime "updated_at", null: false 28 | end 29 | 30 | create_table "highscores", force: :cascade do |t| 31 | t.string "name" 32 | t.integer "score" 33 | t.datetime "created_at", null: false 34 | t.datetime "updated_at", null: false 35 | end 36 | 37 | create_table "job_executions", force: :cascade do |t| 38 | t.string "name" 39 | t.json "data" 40 | t.datetime "created_at", null: false 41 | t.datetime "updated_at", null: false 42 | end 43 | 44 | add_foreign_key "conversation_messages", "conversations" 45 | end 46 | -------------------------------------------------------------------------------- /db/seeds.rb: -------------------------------------------------------------------------------- 1 | # This file should ensure the existence of records required to run the application in every environment (production, 2 | # development, test). The code here should be idempotent so that it can be executed at any point in every environment. 3 | # The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). 4 | # 5 | # Example: 6 | # 7 | # ["Action", "Comedy", "Drama", "Horror"].each do |genre_name| 8 | # MovieGenre.find_or_create_by!(name: genre_name) 9 | # end 10 | -------------------------------------------------------------------------------- /lib/assets/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/lib/assets/.keep -------------------------------------------------------------------------------- /lib/chat.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Released under the MIT License. 4 | # Copyright, 2023, by Samuel Williams. 5 | 6 | require 'async/redis' 7 | require 'thread/local' 8 | 9 | module Chat 10 | module Redis 11 | extend Thread::Local 12 | 13 | def self.local 14 | endpoint = Async::Redis.local_endpoint 15 | client = Async::Redis::Client.new(endpoint) 16 | end 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /lib/flappy_tag.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Released under the MIT License. 4 | # Copyright, 2023, by Samuel Williams. 5 | 6 | require 'live' 7 | require 'async/ollama' 8 | 9 | class FlappyTag < Live::View 10 | WIDTH = 420 11 | HEIGHT = 640 12 | GRAVITY = -9.8 * 50.0 13 | 14 | class BoundingBox 15 | def initialize(x, y, width, height) 16 | @x = x 17 | @y = y 18 | @width = width 19 | @height = height 20 | end 21 | 22 | attr :x 23 | attr :y 24 | 25 | attr :width 26 | attr :height 27 | 28 | def right 29 | @x + @width 30 | end 31 | 32 | def top 33 | @y + @height 34 | end 35 | 36 | def intersect?(other) 37 | !( 38 | self.right < other.x || 39 | self.x > other.right || 40 | self.top < other.y || 41 | self.y > other.top 42 | ) 43 | end 44 | 45 | def to_s 46 | "#<#{self.class} (#{@x}, #{@y}, #{@width}, #{@height}>" 47 | end 48 | end 49 | 50 | class Bird < BoundingBox 51 | def initialize(x = 30, y = HEIGHT / 2, width: 34, height: 24) 52 | super(x, y, width, height) 53 | @velocity = 0.0 54 | end 55 | 56 | def step(dt) 57 | @velocity += GRAVITY * dt 58 | @y += @velocity * dt 59 | 60 | if @y > HEIGHT 61 | @y = HEIGHT 62 | @velocity = 0.0 63 | end 64 | end 65 | 66 | def jump 67 | @velocity = 300.0 68 | end 69 | 70 | def render(builder) 71 | rotation = (@velocity / 20.0).clamp(-40.0, 40.0) 72 | rotate = "rotate(#{-rotation}deg)"; 73 | 74 | builder.inline_tag(:div, class: 'bird', style: "left: #{@x}px; bottom: #{@y}px; width: #{@width}px; height: #{@height}px; transform: #{rotate};") 75 | end 76 | end 77 | 78 | class Pipe 79 | def initialize(x, y, offset = 100, width: 44, height: 700) 80 | @x = x 81 | @y = y 82 | @offset = offset 83 | 84 | @width = width 85 | @height = height 86 | @difficulty = 0.0 87 | @scored = false 88 | end 89 | 90 | attr_accessor :x 91 | attr_accessor :y 92 | attr_accessor :offset 93 | 94 | # Whether the bird has passed through the pipe. 95 | attr_accessor :scored 96 | 97 | def scaled_random 98 | rand(-1.0..1.0) * [@difficulty, 1.0].min 99 | end 100 | 101 | def reset! 102 | @x = WIDTH + (rand * 10) 103 | @y = HEIGHT/2 + (HEIGHT/2 * scaled_random) 104 | 105 | if @offset > 50 106 | @offset -= (@difficulty * 10) 107 | end 108 | 109 | @difficulty += 0.1 110 | @scored = false 111 | end 112 | 113 | def step(dt) 114 | @x -= 100 * dt 115 | 116 | if self.right < 0 117 | reset! 118 | end 119 | end 120 | 121 | def right 122 | @x + @width 123 | end 124 | 125 | def top 126 | @y + @offset 127 | end 128 | 129 | def bottom 130 | (@y - @offset) - @height 131 | end 132 | 133 | def lower_bounding_box 134 | BoundingBox.new(@x, self.bottom, @width, @height) 135 | end 136 | 137 | def upper_bounding_box 138 | BoundingBox.new(@x, self.top, @width, @height) 139 | end 140 | 141 | def intersect?(other) 142 | lower_bounding_box.intersect?(other) || upper_bounding_box.intersect?(other) 143 | end 144 | 145 | def render(builder) 146 | display = "display: none;" if @x > WIDTH 147 | 148 | builder.inline_tag(:div, class: 'pipe', style: "left: #{@x}px; bottom: #{self.bottom}px; width: #{@width}px; height: #{@height}px; #{display}") 149 | builder.inline_tag(:div, class: 'pipe', style: "left: #{@x}px; bottom: #{self.top}px; width: #{@width}px; height: #{@height}px; #{display}") 150 | end 151 | end 152 | 153 | def initialize(...) 154 | super 155 | 156 | @game = nil 157 | @bird = nil 158 | @pipes = nil 159 | 160 | # Defaults: 161 | @score = 0 162 | @prompt = "Press Space to Start" 163 | end 164 | 165 | def handle(event) 166 | case event[:type] 167 | when "keypress" 168 | details = event[:details] 169 | 170 | if @game.nil? 171 | start_game! 172 | elsif details[:key] == " " 173 | @bird&.jump 174 | end 175 | end 176 | end 177 | 178 | def forward_keypress 179 | "live.forward(#{JSON.dump(@id)}, event, {value: event.target.value, key: event.key})" 180 | end 181 | 182 | def reset! 183 | @bird = Bird.new 184 | @pipes = [ 185 | Pipe.new(WIDTH * 1/2, HEIGHT/2), 186 | Pipe.new(WIDTH * 2/2, HEIGHT/2) 187 | ] 188 | @score = 0 189 | end 190 | 191 | def game_over! 192 | Highscore.connection_pool.with_connection do 193 | Highscore.create!(name: "Anonymous", score: @score) 194 | end 195 | 196 | @prompt = "Game Over! Score: #{@score}. Press Space to Restart" 197 | @game = nil 198 | replace! 199 | raise Async::Stop 200 | end 201 | 202 | def start_game! 203 | if @game 204 | @game.stop 205 | @game = nil 206 | end 207 | 208 | self.reset! 209 | @game = self.run! 210 | end 211 | 212 | def step(dt) 213 | @bird.step(dt) 214 | @pipes.each do |pipe| 215 | pipe.step(dt) 216 | 217 | if pipe.right < @bird.x && !pipe.scored 218 | @score += 1 219 | pipe.scored = true 220 | end 221 | 222 | if pipe.intersect?(@bird) 223 | return game_over! 224 | end 225 | end 226 | 227 | if @bird.top < 0 228 | return game_over! 229 | end 230 | end 231 | 232 | def run!(dt = 1.0/20.0) 233 | Console.info(self, "run!") 234 | 235 | Async do 236 | while true 237 | self.step(dt) 238 | 239 | replace! 240 | sleep(dt) 241 | end 242 | end 243 | end 244 | 245 | def render(builder) 246 | builder.tag(:div, class: "flappy", tabIndex: 0, onKeyPress: forward_keypress) do 247 | if @game 248 | builder.inline_tag(:div, class: "score") do 249 | builder.text(@score) 250 | end 251 | else 252 | builder.inline_tag(:div, class: "prompt") do 253 | builder.text(@prompt) 254 | 255 | builder.inline_tag(:ol, class: "highscores") do 256 | Highscore.connection_pool.with_connection do 257 | Highscore.order(score: :desc).limit(10).each do |highscore| 258 | builder.inline_tag(:li) do 259 | builder.text("#{highscore.name}: #{highscore.score}") 260 | end 261 | end 262 | end 263 | end 264 | end 265 | end 266 | 267 | @bird&.render(builder) 268 | 269 | @pipes&.each do |pipe| 270 | pipe.render(builder) 271 | end 272 | end 273 | end 274 | end 275 | -------------------------------------------------------------------------------- /lib/game_tag.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Released under the MIT License. 4 | # Copyright, 2023, by Samuel Williams. 5 | 6 | require 'live' 7 | require_relative 'messages' 8 | 9 | class GameTag < Live::View 10 | ROBOT = "🤖" 11 | KITTEN = "🐱" 12 | 13 | SYMBOLS = [ 14 | "🌳", 15 | "🌲", 16 | "🌴", 17 | "🌵", 18 | "🌾", 19 | "🌿", 20 | "🍀", 21 | "🍁", 22 | "🍂", 23 | "🍃", 24 | "🍄", 25 | "🌰", 26 | "🐚", 27 | "🌱", 28 | "🌼", 29 | "🌻", 30 | "🌺", 31 | "🌹", 32 | "🌷", 33 | "🌸", 34 | "💐", 35 | "🔨", 36 | "🔧", 37 | "🔩", 38 | "🔫", 39 | "🔪", 40 | "🔬", 41 | "🔭", 42 | "📡", 43 | "💉", 44 | "💊", 45 | "🔮", 46 | "🔑", 47 | "🔺", 48 | "🔻", 49 | "🔳", 50 | "🔲", 51 | "🔴", 52 | "🔵", 53 | "🔷", 54 | "🔶", 55 | "🔹", 56 | "🔸", 57 | "🔘", 58 | ] 59 | 60 | class Board 61 | def initialize(width, height) 62 | @width = width 63 | @height = height 64 | @data = Array.new(@width) do |x| 65 | Array.new(@height) 66 | end 67 | end 68 | 69 | attr :width 70 | attr :height 71 | attr :data 72 | 73 | def generate(seed, density: 0.1) 74 | count = (@width * @height * density).to_i 75 | random = Random.new(seed) 76 | 77 | count.times do 78 | x = random.rand(@width) 79 | y = random.rand(@height) 80 | symbol = SYMBOLS[random.rand(SYMBOLS.size)] 81 | message = MESSAGES[random.rand(MESSAGES.size)] 82 | 83 | @data[x][y] = [symbol, message] 84 | end 85 | 86 | x = random.rand(@width) 87 | y = random.rand(@height) 88 | 89 | @data[x][y] = [KITTEN, "A kitten!"] 90 | end 91 | end 92 | 93 | def initialize(...) 94 | super 95 | 96 | # Defaults: 97 | @data[:seed] ||= Random.new_seed 98 | @data[:width] ||= 10 99 | @data[:height] ||= 10 100 | @data[:x] ||= @data[:width].to_i / 2 101 | @data[:y] ||= @data[:height].to_i / 2 102 | end 103 | 104 | def board 105 | @board ||= Board.new(@data[:width].to_i, @data[:height].to_i).tap do |board| 106 | board.generate(@data[:seed].to_i) 107 | end 108 | end 109 | 110 | def bind(page) 111 | super(page) 112 | 113 | # run! 114 | end 115 | 116 | def handle(event) 117 | # Console.info(self, "handle", event: event.inspect) 118 | 119 | if event[:type] == "keyup" 120 | details = event[:details] 121 | case details[:code] 122 | when "KeyW", "ArrowUp" 123 | @data[:y] = (@data[:y].to_i - 1) % board.height 124 | when "KeyS", "ArrowDown" 125 | @data[:y] = (@data[:y].to_i + 1) % board.height 126 | when "KeyA", "ArrowLeft" 127 | @data[:x] = (@data[:x].to_i - 1) % board.width 128 | when "KeyD", "ArrowRight" 129 | @data[:x] = (@data[:x].to_i + 1) % board.width 130 | end 131 | 132 | # Redraw the game: 133 | replace! 134 | end 135 | end 136 | 137 | def forward_keypress 138 | "live.forward(#{JSON.dump(@id)}, event, {code: event.code})" 139 | end 140 | 141 | def render(builder) 142 | builder.tag(:div, class: "game", tabIndex: 0, onkeyup: forward_keypress) do 143 | builder.tag(:table, class: "board") do 144 | board.height.times do |y| 145 | builder.tag(:tr) do 146 | board.width.times do |x| 147 | builder.tag(:td, class: "cell") do 148 | symbol, message = board.data[x][y] 149 | 150 | if x == @data[:x].to_i and y == @data[:y].to_i 151 | builder.text(ROBOT) 152 | else 153 | builder.text(symbol) 154 | end 155 | end 156 | end 157 | end 158 | end 159 | end 160 | 161 | builder.tag(:div, class: "message") do 162 | symbol, message = board.data[@data[:x].to_i][@data[:y].to_i] 163 | 164 | if message 165 | builder.text(message) 166 | end 167 | end 168 | end 169 | end 170 | end 171 | -------------------------------------------------------------------------------- /lib/messages.rb: -------------------------------------------------------------------------------- 1 | MESSAGES = [ 2 | "A red balloon that insists on floating away every time you grab it.", 3 | "A vintage pocket watch that's always fashionably late.", 4 | "A treasure map with a 'You are here' sticker in the middle of the ocean.", 5 | "A love letter with more typos than actual words.", 6 | "A kaleidoscope that insists on only showing shades of beige.", 7 | "A pirate chest with a 'Sorry, out of treasure' sign inside.", 8 | "A sparkling gemstone that moonwalks when no one is looking.", 9 | "A book that whispers the endings of movies that you haven't seen yet.", 10 | "A Zen garden where the sand refuses to stay raked.", 11 | "A steampunk gadget that only communicates in Morse code.", 12 | "A unicorn figurine that demands to be ridden to the grocery store.", 13 | "A collector's stamp that insists it's the last one you need for your collection.", 14 | "A vinyl record that plays songs in reverse and predicts your breakfast choices.", 15 | "An ancient artifact that claims to be the first-ever selfie stick.", 16 | "A seashell collection that tells sea stories at midnight.", 17 | "A crystal chandelier that disco dances to its own light.", 18 | "A wooden treasure chest that hoards socks and mismatched gloves.", 19 | "A fairy tale book that rewrites itself with surprise plot twists.", 20 | "A meditation cushion that whispers motivational quotes.", 21 | "A bouquet of roses that insists on serenading you with love songs.", 22 | "A diamond tiara that confuses you for royalty and demands curtsies.", 23 | "A locked diary that giggles every time you try to open it.", 24 | "A pair of wings that encourages impromptu interpretive dance sessions.", 25 | "An underwater coral reef that throws underwater tea parties.", 26 | "A crystal ball that predicts which sock will go missing in the laundry.", 27 | "A forest waterfall that applauds your hiking skills.", 28 | "A flying broomstick that offers 'Flying 101' lessons on Tuesdays.", 29 | "An ancient scroll that unfolds into a 'How to Train Your Dragon' manual.", 30 | "An antique telescope that claims it can spot the tooth fairy's castle.", 31 | "A snow-capped mountain that challenges you to a snowball fight.", 32 | "A hot air balloon that has a fear of heights and clings to the ground.", 33 | "A treasure trove that challenges you to a game of hide and seek.", 34 | "A fairy wand that turns vegetables into chocolate, but only in your dreams.", 35 | "A mermaid's pearl that offers advice on underwater fashion trends.", 36 | "A dragon egg that hatches into a tiny dragon comedian.", 37 | "A cave entrance that claims to be a portal to Narnia, but it's actually a coat closet.", 38 | "An enchanted rose that serenades passersby with love songs.", 39 | "A pirate's telescope that only sees treasure chests, everywhere.", 40 | "A genie's lamp that grants wishes for endless chocolate chip cookies.", 41 | "An alien artifact that plays catchy tunes from another galaxy.", 42 | "A time-traveling spaceship that keeps getting lost in the 80s.", 43 | "A wizard's staff that moonlights as a drumstick in a rock band.", 44 | "A crystal skull that tells jokes in ancient hieroglyphics.", 45 | "An adventurer's backpack that spontaneously packs and unpacks itself.", 46 | "An ancient city ruin that plays hide-and-seek with curious explorers.", 47 | "A treasure hunter's shovel that challenges you to a digging contest.", 48 | "A forgotten Mayan temple that turns into a bounce house on weekends.", 49 | "A Viking longship that insists on being named 'Boaty McBoatface II'.", 50 | "A medieval sword that insists on challenging you to a duel.", 51 | "A Roman coliseum that hosts chariot races with rubber ducks.", 52 | "An adventurer's map that insists on taking the scenic route.", 53 | "A pirate's compass that has a great sense of humor but a terrible sense of direction.", 54 | 55 | "A mischievous Ruby gem that insists on hiding in your code.", 56 | "A database migration file that insists on 'migrating' to a tropical island.", 57 | "A nested route that leads to a secret underground dance club.", 58 | "A RESTful API endpoint that claims it's the most relaxing API in town.", 59 | "A CSRF token that throws surprise parties for your web forms.", 60 | "A code editor shortcut that insists on making shortcuts to your shortcuts.", 61 | "A Rails model association that insists on introducing your models to its friends.", 62 | "A well-documented API that doubles as a bedtime storybook.", 63 | "A Bootstrap stylesheet that insists on dressing up your website for every holiday.", 64 | "A Git repository that hosts 'Git-togethers' with other repositories.", 65 | "A Rails scaffold that builds actual scaffolds for your website.", 66 | "A rake task that insists on 'raking up' the leaves in your codebase.", 67 | "A Rails console session that tells 'Rails jokes' to lighten the mood.", 68 | "A Docker container that claims to contain the universe.", 69 | "A TDD (Test-Driven Development) test case that challenges your code to a test duel.", 70 | "A PostgreSQL database that insists on speaking in Postgres puns.", 71 | "A CSS flexbox layout that flexes its muscles during web design workouts.", 72 | "A Ruby on Rails meetup that turns into an impromptu karaoke night.", 73 | "A GitHub pull request that sends 'pulling your leg' jokes.", 74 | "A database index that claims to be the 'index of all indices.'", 75 | "A gemfile.lock that insists on locking all the gems in a vault.", 76 | "A bundle install command that summons a 'bundle of joy.'", 77 | "A Sass stylesheet that insists on 'sassing up' your web design.", 78 | "A continuous integration (CI) pipeline that organizes CI-themed parties.", 79 | "A Git merge conflict that insists on 'merging' coffee and code.", 80 | "A Rails partial view that insists on 'partying' with other views.", 81 | "A Rails generator that generates 'electricity' for your application.", 82 | "A secure login page that requires a secret handshake to enter.", 83 | "A Rails validation error that insists it's 'valid' in its own unique way.", 84 | "A Ruby on Rails tutorial that comes with a 'Rails-to-trails' hiking guide.", 85 | "A NoSQL database that 'queries' your life choices in a non-judgmental way.", 86 | "A version control system that insists on being the 'boss' of your code.", 87 | "A RESTful URL route that enjoys 'scenic routes' during road trips.", 88 | "A Rails gemfile that contains hidden 'gemstones' waiting to be discovered.", 89 | "A Ruby gem documentation that tells developer jokes in the footnotes.", 90 | "A coverage framework which promises to help you reach Nirvana.", 91 | "A Git pull request review that insists on 'pulling' hilarious pranks.", 92 | "A JavaScript promise that promises to 'promise' things properly.", 93 | "A secure password reset feature that requires a 'password-reset dance-off.'", 94 | "A CI/CD tool that throws 'continuous celebration' parties.", 95 | "A database backup script that insists on 'backing up' jokes.", 96 | "A Rails model validation that validates your 'model citizen' status.", 97 | "A GraphQL request that queries the meaning of life.", 98 | "A RESTful JSON response that responds with 'REST-aurant recommendations.'", 99 | "A long lost JavaScript library for left-padding strings.", 100 | ] 101 | -------------------------------------------------------------------------------- /lib/ollama_tag.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Released under the MIT License. 4 | # Copyright, 2023, by Samuel Williams. 5 | 6 | require 'live' 7 | require 'async/ollama' 8 | 9 | class OllamaTag < Live::View 10 | def initialize(...) 11 | super 12 | 13 | # Defaults: 14 | @data[:prompt] ||= "" 15 | @data[:context] ||= nil 16 | end 17 | 18 | def conversation 19 | @conversation ||= Conversation.find_by(id: @data[:conversation_id]) 20 | end 21 | 22 | def update_conversation(prompt) 23 | Console.info(self, "update_conversation", prompt: prompt) 24 | 25 | Async::Ollama::Client.open do |client| 26 | conversation_message = conversation.conversation_messages.build(prompt: prompt, response: String.new) 27 | 28 | generate = client.generate(prompt) do |response| 29 | response.body.each do |token| 30 | conversation_message.response += token 31 | replace! 32 | end 33 | end 34 | 35 | conversation_message.response = generate.response 36 | conversation_message.context = generate.context 37 | conversation_message.save! 38 | 39 | @data[:context] = generate.context 40 | 41 | replace! 42 | end 43 | end 44 | 45 | def handle(event) 46 | case event[:type] 47 | when "keypress" 48 | details = event[:details] 49 | @data[:prompt] = details[:value] 50 | 51 | if details[:key] == "Enter" 52 | prompt = @data[:prompt] 53 | @data[:prompt] = "" 54 | update_conversation(prompt) 55 | 56 | replace! 57 | end 58 | end 59 | end 60 | 61 | def forward_keypress 62 | "live.forward(#{JSON.dump(@id)}, event, {value: event.target.value, key: event.key})" 63 | end 64 | 65 | def render_message(builder, message) 66 | builder.tag(:p, class: "message") do 67 | builder.text(message.prompt) 68 | end 69 | 70 | builder.tag(:p, class: "response") do 71 | builder.text(message.response) 72 | end 73 | end 74 | 75 | def render(builder) 76 | builder.tag(:div, class: "conversation") do 77 | conversation.conversation_messages.each do |message| 78 | render_message(builder, message) 79 | end 80 | 81 | builder.tag(:input, type: "text", value: @data[:prompt], style: "width: 100%", onkeypress: forward_keypress, placeholder: "Type here...") 82 | end 83 | end 84 | end 85 | -------------------------------------------------------------------------------- /lib/tasks/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/lib/tasks/.keep -------------------------------------------------------------------------------- /log/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/log/.keep -------------------------------------------------------------------------------- /public/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The page you were looking for doesn't exist (404) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The page you were looking for doesn't exist.

62 |

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

63 |
64 |

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

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /public/422.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The change you wanted was rejected (422) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The change you wanted was rejected.

62 |

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

63 |
64 |

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

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /public/500.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | We're sorry, but something went wrong (500) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

We're sorry, but something went wrong.

62 |
63 |

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

64 |
65 | 66 | 67 | -------------------------------------------------------------------------------- /public/apple-touch-icon-precomposed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/public/apple-touch-icon-precomposed.png -------------------------------------------------------------------------------- /public/apple-touch-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/public/apple-touch-icon.png -------------------------------------------------------------------------------- /public/chat/client.js: -------------------------------------------------------------------------------- 1 | function connectToChatServer(url) { 2 | console.log("WebSocket Connecting...", url); 3 | var server = new WebSocket(url.href); 4 | 5 | server.onopen = function(event) { 6 | console.log("WebSocket Connected:", server); 7 | chat.disabled = false; 8 | 9 | chat.onkeypress = function(event) { 10 | if (event.keyCode == 13) { 11 | server.send(JSON.stringify({text: chat.value})); 12 | 13 | chat.value = ""; 14 | } 15 | } 16 | }; 17 | 18 | server.onmessage = function(event) { 19 | console.log("WebSocket Message:", event); 20 | 21 | var message = JSON.parse(event.data); 22 | 23 | var pre = document.createElement('pre'); 24 | pre.innerText = message.text; 25 | 26 | response.appendChild(pre); 27 | }; 28 | 29 | server.onerror = function(event) { 30 | console.log("WebSocket Error:", event); 31 | chat.disabled = true; 32 | server.close(); 33 | }; 34 | 35 | server.onclose = function(event) { 36 | console.log("WebSocket Close:", event); 37 | 38 | setTimeout(function() { 39 | connectToChatServer(url); 40 | }, 1000); 41 | }; 42 | } 43 | 44 | var url = new URL('/chat/connect', window.location.href); 45 | url.protocol = url.protocol.replace('http', 'ws'); 46 | 47 | connectToChatServer(url); 48 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/public/favicon.ico -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file 2 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Falcon Rails Example 2 | 3 | This repository contains an example Rails application that uses Falcon as the web server. It also demonstrates how to use the `console` gem for logging, and how to use the `traces` gem for request tracing. 4 | 5 | ## Usage 6 | 7 | Migrate the database: 8 | 9 | ``` 10 | > bin/rails db:migrate 11 | ``` 12 | 13 | `redis-server` should be running on localhost for all the examples to work. 14 | 15 | Then start the server using `falcon` directly: 16 | 17 | ``` 18 | > bundle exec falcon serve 19 | ``` 20 | 21 | This will bind to HTTPS / port 443. 22 | -------------------------------------------------------------------------------- /storage/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/storage/.keep -------------------------------------------------------------------------------- /test/application_system_test_case.rb: -------------------------------------------------------------------------------- 1 | require "test_helper" 2 | 3 | class ApplicationSystemTestCase < ActionDispatch::SystemTestCase 4 | driven_by :selenium, using: :chrome, screen_size: [1400, 1400] 5 | end 6 | -------------------------------------------------------------------------------- /test/channels/application_cable/connection_test.rb: -------------------------------------------------------------------------------- 1 | require "test_helper" 2 | 3 | module ApplicationCable 4 | class ConnectionTest < ActionCable::Connection::TestCase 5 | # test "connects with cookies" do 6 | # cookies.signed[:user_id] = 42 7 | # 8 | # connect 9 | # 10 | # assert_equal connection.user_id, "42" 11 | # end 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /test/controllers/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/test/controllers/.keep -------------------------------------------------------------------------------- /test/controllers/chat_controller_test.rb: -------------------------------------------------------------------------------- 1 | require "test_helper" 2 | 3 | class ChatControllerTest < ActionDispatch::IntegrationTest 4 | # test "the truth" do 5 | # assert true 6 | # end 7 | end 8 | -------------------------------------------------------------------------------- /test/controllers/flappy_controller_test.rb: -------------------------------------------------------------------------------- 1 | require "test_helper" 2 | 3 | class FlappyControllerTest < ActionDispatch::IntegrationTest 4 | test "should get index" do 5 | get flappy_index_url 6 | assert_response :success 7 | end 8 | 9 | test "should get live" do 10 | get flappy_live_url 11 | assert_response :success 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /test/controllers/job_controller_test.rb: -------------------------------------------------------------------------------- 1 | require "test_helper" 2 | 3 | class HomeControllerTest < ActionDispatch::IntegrationTest 4 | test "should get index" do 5 | get home_index_url 6 | assert_response :success 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /test/controllers/ollama_controller_test.rb: -------------------------------------------------------------------------------- 1 | require "test_helper" 2 | 3 | class OllamaControllerTest < ActionDispatch::IntegrationTest 4 | test "should get index" do 5 | get ollama_index_url 6 | assert_response :success 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /test/controllers/sse_controller_test.rb: -------------------------------------------------------------------------------- 1 | require "test_helper" 2 | 3 | class SseControllerTest < ActionDispatch::IntegrationTest 4 | test "should get index" do 5 | get sse_index_url 6 | assert_response :success 7 | end 8 | 9 | test "should get events" do 10 | get sse_events_url 11 | assert_response :success 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /test/controllers/stock_controller_test.rb: -------------------------------------------------------------------------------- 1 | require "test_helper" 2 | 3 | class StockControllerTest < ActionDispatch::IntegrationTest 4 | # test "the truth" do 5 | # assert true 6 | # end 7 | end 8 | -------------------------------------------------------------------------------- /test/controllers/streaming_controller_test.rb: -------------------------------------------------------------------------------- 1 | require "test_helper" 2 | 3 | class StreamingControllerTest < ActionDispatch::IntegrationTest 4 | test "should get simple" do 5 | get streaming_simple_url 6 | assert_response :success 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /test/controllers/welcome_controller_test.rb: -------------------------------------------------------------------------------- 1 | require "test_helper" 2 | 3 | class WelcomeControllerTest < ActionDispatch::IntegrationTest 4 | test "should get index" do 5 | get welcome_index_url 6 | assert_response :success 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /test/fixtures/conversation_messages.yml: -------------------------------------------------------------------------------- 1 | # Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html 2 | 3 | # This model initially had no columns defined. If you add columns to the 4 | # model remove the "{}" from the fixture names and add the columns immediately 5 | # below each fixture, per the syntax in the comments below 6 | # 7 | one: {} 8 | # column: value 9 | # 10 | two: {} 11 | # column: value 12 | -------------------------------------------------------------------------------- /test/fixtures/conversations.yml: -------------------------------------------------------------------------------- 1 | # Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html 2 | 3 | # This model initially had no columns defined. If you add columns to the 4 | # model remove the "{}" from the fixture names and add the columns immediately 5 | # below each fixture, per the syntax in the comments below 6 | # 7 | one: {} 8 | # column: value 9 | # 10 | two: {} 11 | # column: value 12 | -------------------------------------------------------------------------------- /test/fixtures/files/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/test/fixtures/files/.keep -------------------------------------------------------------------------------- /test/fixtures/highscores.yml: -------------------------------------------------------------------------------- 1 | # Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html 2 | 3 | # This model initially had no columns defined. If you add columns to the 4 | # model remove the "{}" from the fixture names and add the columns immediately 5 | # below each fixture, per the syntax in the comments below 6 | # 7 | one: {} 8 | # column: value 9 | # 10 | two: {} 11 | # column: value 12 | -------------------------------------------------------------------------------- /test/helpers/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/test/helpers/.keep -------------------------------------------------------------------------------- /test/integration/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/test/integration/.keep -------------------------------------------------------------------------------- /test/mailers/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/test/mailers/.keep -------------------------------------------------------------------------------- /test/models/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/test/models/.keep -------------------------------------------------------------------------------- /test/models/conversation_message_test.rb: -------------------------------------------------------------------------------- 1 | require "test_helper" 2 | 3 | class ConversationMessageTest < ActiveSupport::TestCase 4 | # test "the truth" do 5 | # assert true 6 | # end 7 | end 8 | -------------------------------------------------------------------------------- /test/models/conversation_test.rb: -------------------------------------------------------------------------------- 1 | require "test_helper" 2 | 3 | class ConversationTest < ActiveSupport::TestCase 4 | # test "the truth" do 5 | # assert true 6 | # end 7 | end 8 | -------------------------------------------------------------------------------- /test/models/highscore_test.rb: -------------------------------------------------------------------------------- 1 | require "test_helper" 2 | 3 | class HighscoreTest < ActiveSupport::TestCase 4 | # test "the truth" do 5 | # assert true 6 | # end 7 | end 8 | -------------------------------------------------------------------------------- /test/system/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/test/system/.keep -------------------------------------------------------------------------------- /test/test_helper.rb: -------------------------------------------------------------------------------- 1 | ENV["RAILS_ENV"] ||= "test" 2 | require_relative "../config/environment" 3 | require "rails/test_help" 4 | 5 | module ActiveSupport 6 | class TestCase 7 | # Run tests in parallel with specified workers 8 | parallelize(workers: :number_of_processors) 9 | 10 | # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. 11 | fixtures :all 12 | 13 | # Add more helper methods to be used by all tests here... 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /tmp/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/tmp/.keep -------------------------------------------------------------------------------- /tmp/pids/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/tmp/pids/.keep -------------------------------------------------------------------------------- /tmp/storage/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/tmp/storage/.keep -------------------------------------------------------------------------------- /vendor/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/vendor/.keep -------------------------------------------------------------------------------- /vendor/javascript/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/socketry/falcon-rails-example/da81085b62670c7e500da84e415b8dddb4067a64/vendor/javascript/.keep -------------------------------------------------------------------------------- /vendor/javascript/@socketry--live.js: -------------------------------------------------------------------------------- 1 | import e from"morphdom";class Live{#e;#t;#i;#s;#r;#n;static start(e={}){let t=e.window||globalThis;let i=e.path||"live";let s=e.base||t.location.href;let r=new URL(i,s);r.protocol=r.protocol.replace("http","ws");return new this(t,r)}constructor(e,t){this.#e=e;this.#t=e.document;this.url=t;this.#i=null;this.#s=[];this.#r=0;this.#n=null;this.#t.addEventListener("visibilitychange",(()=>this.#o()));this.#o();const i=this.#e.Node.ELEMENT_NODE;this.observer=new this.#e.MutationObserver(((e,t)=>{for(let t of e)if(t.type==="childList"){for(let e of t.removedNodes)if(e.nodeType===i){e.classList?.contains("live")&&this.#l(e);for(let t of e.getElementsByClassName("live"))this.#l(t)}for(let e of t.addedNodes)if(e.nodeType===i){e.classList.contains("live")&&this.#h(e);for(let t of e.getElementsByClassName("live"))this.#h(t)}}}));this.observer.observe(this.#t.body,{childList:true,subtree:true})}connect(){if(this.#i)return this.#i;let e=this.#i=new this.#e.WebSocket(this.url);if(this.#n){clearTimeout(this.#n);this.#n=null}e.onopen=()=>{this.#r=0;this.#c();this.#a()};e.onmessage=e=>{const[t,...i]=JSON.parse(e.data);this[t](...i)};e.addEventListener("error",(()=>{this.#r+=1}));e.addEventListener("close",(()=>{if(this.#i&&!this.#n){const e=Math.max(100*(this.#r+1)**2,6e4);this.#n=setTimeout((()=>{this.#n=null;this.connect()}),e)}this.#i===e&&(this.#i=null)}));return e}disconnect(){if(this.#i){const e=this.#i;this.#i=null;e.close()}if(this.#n){clearTimeout(this.#n);this.#n=null}}#d(e){if(this.#i)try{return this.#i.send(e)}catch(e){}this.#s.push(e)}#c(){if(this.#s.length===0)return;let e=this.#s;this.#s=[];for(var t of e)this.#d(t)}#o(){this.#t.hidden?this.disconnect():this.connect()}#h(e){console.log("bind",e.id,e.dataset);this.#d(JSON.stringify(["bind",e.id,e.dataset]))}#l(e){console.log("unbind",e.id,e.dataset);this.#i&&this.#d(JSON.stringify(["unbind",e.id]))}#a(){for(let e of this.#t.getElementsByClassName("live"))this.#h(e)}#u(e){return this.#t.createRange().createContextualFragment(e)}#m(e,...t){e?.reply&&this.#d(JSON.stringify(["reply",e.reply,...t]))}script(e,t,i){let s=this.#t.getElementById(e);try{let e=this.#e.Function(t).call(s);this.#m(i,e)}catch(e){this.#m(i,null,{name:e.name,message:e.message,stack:e.stack})}}update(t,i,s){let r=this.#t.getElementById(t);let n=this.#u(i);e(r,n);this.#m(s)}replace(t,i,s){let r=this.#t.querySelectorAll(t);let n=this.#u(i);r.forEach((t=>e(t,n.cloneNode(true))));this.#m(s)}prepend(e,t,i){let s=this.#t.querySelectorAll(e);let r=this.#u(t);s.forEach((e=>e.prepend(r.cloneNode(true))));this.#m(i)}append(e,t,i){let s=this.#t.querySelectorAll(e);let r=this.#u(t);s.forEach((e=>e.append(r.cloneNode(true))));this.#m(i)}remove(e,t){let i=this.#t.querySelectorAll(e);i.forEach((e=>e.remove()));this.#m(t)}dispatchEvent(e,t,i){let s=this.#t.querySelectorAll(e);s.forEach((e=>e.dispatchEvent(new this.#e.CustomEvent(t,i))));this.#m(i)}error(e){console.error("Live.error",...arguments)}forward(e,t){this.connect();this.#d(JSON.stringify(["event",e,t]))}forwardEvent(e,t,i,s=false){s&&t.preventDefault();this.forward(e,{type:t.type,detail:i})}forwardFormEvent(e,t,i,s=true){s&&t.preventDefault();let r=t.form;let n=new FormData(r);this.forward(e,{type:t.type,detail:i,formData:[...n]})}}export{Live}; 2 | 3 | -------------------------------------------------------------------------------- /vendor/javascript/morphdom.js: -------------------------------------------------------------------------------- 1 | var e=11;function morphAttrs(r,t){var a=t.attributes;var n;var o;var i;var d;var l;if(t.nodeType!==e&&r.nodeType!==e){for(var u=a.length-1;u>=0;u--){n=a[u];o=n.name;i=n.namespaceURI;d=n.value;if(i){o=n.localName||o;l=r.getAttributeNS(i,o);if(l!==d){n.prefix==="xmlns"&&(o=n.name);r.setAttributeNS(i,o,d)}}else{l=r.getAttribute(o);l!==d&&r.setAttribute(o,d)}}var f=r.attributes;for(var v=f.length-1;v>=0;v--){n=f[v];o=n.name;i=n.namespaceURI;if(i){o=n.localName||o;t.hasAttributeNS(i,o)||r.removeAttributeNS(i,o)}else t.hasAttribute(o)||r.removeAttribute(o)}}}var r;var t="http://www.w3.org/1999/xhtml";var a=typeof document==="undefined"?void 0:document;var n=!!a&&"content"in a.createElement("template");var o=!!a&&a.createRange&&"createContextualFragment"in a.createRange();function createFragmentFromTemplate(e){var r=a.createElement("template");r.innerHTML=e;return r.content.childNodes[0]}function createFragmentFromRange(e){if(!r){r=a.createRange();r.selectNode(a.body)}var t=r.createContextualFragment(e);return t.childNodes[0]}function createFragmentFromWrap(e){var r=a.createElement("body");r.innerHTML=e;return r.childNodes[0]} 2 | /** 3 | * This is about the same 4 | * var html = new DOMParser().parseFromString(str, 'text/html'); 5 | * return html.body.firstChild; 6 | * 7 | * @method toElement 8 | * @param {String} str 9 | */function toElement(e){e=e.trim();return n?createFragmentFromTemplate(e):o?createFragmentFromRange(e):createFragmentFromWrap(e)} 10 | /** 11 | * Returns true if two node's names are the same. 12 | * 13 | * NOTE: We don't bother checking `namespaceURI` because you will never find two HTML elements with the same 14 | * nodeName and different namespace URIs. 15 | * 16 | * @param {Element} a 17 | * @param {Element} b The target element 18 | * @return {boolean} 19 | */function compareNodeNames(e,r){var t=e.nodeName;var a=r.nodeName;var n,o;if(t===a)return true;n=t.charCodeAt(0);o=a.charCodeAt(0);return n<=90&&o>=97?t===a.toUpperCase():o<=90&&n>=97&&a===t.toUpperCase()} 20 | /** 21 | * Create an element, optionally with a known namespace URI. 22 | * 23 | * @param {string} name the element name, e.g. 'div' or 'svg' 24 | * @param {string} [namespaceURI] the element's namespace URI, i.e. the value of 25 | * its `xmlns` attribute or its inferred namespace. 26 | * 27 | * @return {Element} 28 | */function createElementNS(e,r){return r&&r!==t?a.createElementNS(r,e):a.createElement(e)}function moveChildren(e,r){var t=e.firstChild;while(t){var a=t.nextSibling;r.appendChild(t);t=a}return r}function syncBooleanAttrProp(e,r,t){if(e[t]!==r[t]){e[t]=r[t];e[t]?e.setAttribute(t,""):e.removeAttribute(t)}}var i={OPTION:function(e,r){var t=e.parentNode;if(t){var a=t.nodeName.toUpperCase();if(a==="OPTGROUP"){t=t.parentNode;a=t&&t.nodeName.toUpperCase()}if(a==="SELECT"&&!t.hasAttribute("multiple")){if(e.hasAttribute("selected")&&!r.selected){e.setAttribute("selected","selected");e.removeAttribute("selected")}t.selectedIndex=-1}}syncBooleanAttrProp(e,r,"selected")},INPUT:function(e,r){syncBooleanAttrProp(e,r,"checked");syncBooleanAttrProp(e,r,"disabled");e.value!==r.value&&(e.value=r.value);r.hasAttribute("value")||e.removeAttribute("value")},TEXTAREA:function(e,r){var t=r.value;e.value!==t&&(e.value=t);var a=e.firstChild;if(a){var n=a.nodeValue;if(n==t||!t&&n==e.placeholder)return;a.nodeValue=t}},SELECT:function(e,r){if(!r.hasAttribute("multiple")){var t=-1;var a=0;var n=e.firstChild;var o;var i;while(n){i=n.nodeName&&n.nodeName.toUpperCase();if(i==="OPTGROUP"){o=n;n=o.firstChild}else{if(i==="OPTION"){if(n.hasAttribute("selected")){t=a;break}a++}n=n.nextSibling;if(!n&&o){n=o.nextSibling;o=null}}}e.selectedIndex=t}}};var d=1;var l=11;var u=3;var f=8;function noop(){}function defaultGetNodeKey(e){if(e)return e.getAttribute&&e.getAttribute("id")||e.id}function morphdomFactory(e){return function morphdom(r,t,n){n||(n={});if(typeof t==="string")if(r.nodeName==="#document"||r.nodeName==="HTML"||r.nodeName==="BODY"){var o=t;t=a.createElement("html");t.innerHTML=o}else t=toElement(t);else t.nodeType===l&&(t=t.firstElementChild);var v=n.getNodeKey||defaultGetNodeKey;var m=n.onBeforeNodeAdded||noop;var c=n.onNodeAdded||noop;var s=n.onBeforeElUpdated||noop;var p=n.onElUpdated||noop;var h=n.onBeforeNodeDiscarded||noop;var N=n.onNodeDiscarded||noop;var A=n.onBeforeElChildrenUpdated||noop;var C=n.skipFromChildren||noop;var b=n.addChild||function(e,r){return e.appendChild(r)};var g=n.childrenOnly===true;var T=Object.create(null);var E=[];function addKeyedRemoval(e){E.push(e)}function walkDiscardedChildNodes(e,r){if(e.nodeType===d){var t=e.firstChild;while(t){var a=void 0;if(r&&(a=v(t)))addKeyedRemoval(a);else{N(t);t.firstChild&&walkDiscardedChildNodes(t,r)}t=t.nextSibling}}} 29 | /** 30 | * Removes a DOM node out of the original DOM 31 | * 32 | * @param {Node} node The node to remove 33 | * @param {Node} parentNode The nodes parent 34 | * @param {Boolean} skipKeyedNodes If true then elements with keys will be skipped and not discarded. 35 | * @return {undefined} 36 | */function removeNode(e,r,t){if(h(e)!==false){r&&r.removeChild(e);N(e);walkDiscardedChildNodes(e,t)}}function indexTree(e){if(e.nodeType===d||e.nodeType===l){var r=e.firstChild;while(r){var t=v(r);t&&(T[t]=r);indexTree(r);r=r.nextSibling}}}indexTree(r);function handleNodeAdded(e){c(e);var r=e.firstChild;while(r){var t=r.nextSibling;var a=v(r);if(a){var n=T[a];if(n&&compareNodeNames(r,n)){r.parentNode.replaceChild(n,r);morphEl(n,r)}else handleNodeAdded(r)}else handleNodeAdded(r);r=t}}function cleanupFromEl(e,r,t){while(r){var a=r.nextSibling;(t=v(r))?addKeyedRemoval(t):removeNode(r,e,true);r=a}}function morphEl(r,t,a){var n=v(t);n&&delete T[n];if(!a){if(s(r,t)===false)return;e(r,t);p(r);if(A(r,t)===false)return}r.nodeName!=="TEXTAREA"?morphChildren(r,t):i.TEXTAREA(r,t)}function morphChildren(e,r){var t=C(e,r);var n=r.firstChild;var o=e.firstChild;var l;var c;var s;var p;var h;e:while(n){p=n.nextSibling;l=v(n);while(!t&&o){s=o.nextSibling;if(n.isSameNode&&n.isSameNode(o)){n=p;o=s;continue e}c=v(o);var N=o.nodeType;var A=void 0;if(N===n.nodeType)if(N===d){if(l){if(l!==c)if(h=T[l])if(s===h)A=false;else{e.insertBefore(h,o);c?addKeyedRemoval(c):removeNode(o,e,true);o=h;c=v(o)}else A=false}else c&&(A=false);A=A!==false&&compareNodeNames(o,n);A&&morphEl(o,n)}else if(N===u||N==f){A=true;o.nodeValue!==n.nodeValue&&(o.nodeValue=n.nodeValue)}if(A){n=p;o=s;continue e}c?addKeyedRemoval(c):removeNode(o,e,true);o=s}if(l&&(h=T[l])&&compareNodeNames(h,n)){t||b(e,h);morphEl(h,n)}else{var g=m(n);if(g!==false){g&&(n=g);n.actualize&&(n=n.actualize(e.ownerDocument||a));b(e,n);handleNodeAdded(n)}}n=p;o=s}cleanupFromEl(e,o,c);var E=i[e.nodeName];E&&E(e,r)}var y=r;var S=y.nodeType;var x=t.nodeType;if(!g)if(S===d)if(x===d){if(!compareNodeNames(r,t)){N(r);y=moveChildren(r,createElementNS(t.nodeName,t.namespaceURI))}}else y=t;else if(S===u||S===f){if(x===S){y.nodeValue!==t.nodeValue&&(y.nodeValue=t.nodeValue);return y}y=t}if(y===t)N(r);else{if(t.isSameNode&&t.isSameNode(y))return;morphEl(y,t,g);if(E)for(var F=0,R=E.length;F