Skip to content

About

Helping serve the climbing community by providing real-time precipitation data and alternative climbing options for rain sensitive areas.

Resources

Stars

28 stars

Watchers

0 watching

Forks

Latest commit

 

History

845 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

WetRockPolice

test & build

Table of Contents

Overview

Wetrockpolice is an open source project built with the Ruby on Rails framework. The site backed by a Postgresql database and hosted on a DOKS kubernetes cluster (digital ocean's managed cluster offering). The project has three key goals:

  • Highlight the safety and ethics of climbing on wet rock within at-risk areas.
  • Display historical and real-time rain information to help climbers make informed decisions.
  • Help climbers find alternative climbing destinations in the event of poor weather.

Contibutors are welcome! Please visit the issues tab for ideas on how to contribute.

Dependencies

To work with wetrockpolice locally you'll need the following dependencies installed on your system:

  • Docker Compose for running the postgres container locally
  • RVM for managing your local ruby version (http server)
  • NVM for managing your local node version (esbuild/sass asset builds)
  • VSCode or your own preferred IDE

Running Locally with RVM & Docker

The easiest way to work with wetrockpolice locally is to leverage Docker for your persistence layer dependency (postgres) and run your own http server & asset watchers via a native ruby installation (like via RVM)

  1. Install the required ruby version (3.4.10) via RVM's installation docs

    rvm install 3.4.10
    rvm use 3.4.10
    
  2. Install the required node version (20.13.1) via NVM's installation docs

    nvm install 20.13.1
    nvm use 20.13.1
    
  3. Clone the repository

    git clone git@github.com:Syntaf/wetrockpolice.git
    
  4. Copy over the example environment. Note: You shouldn't need to change any configuration from .env.example initially

    cd wetrockpolice
    cp .env.example .env
    
  5. Start up your postgres container to run in the background

    make up
    
  6. Install required gems & packages for running your http server & asset builds

    make install
    
  7. Setup your database, run migrations & seed data

    make reset-db
    
  8. Start your http server & esbuild/sass watchers

    ./bin/dev
    
  9. Visit http://localhost:3001

Running Locally on OSX

This option is similar to the above but assumes you are running your database locally via brew, and you're within an OSX environment.

  1. Install RVM and the required ruby version (3.4.10) via RVM's installation docs

    rvm install 3.4.10
    rvm use 3.4.10
    
  2. Install the required node version (20.13.1) via NVM's installation docs

    nvm install 20.13.1
    nvm use 20.13.1
    
  3. Install & start a local postgres instance via brew

    brew install postgresql@15
    brew services start postgresql@15
    
  4. Clone the repository

    git clone git@github.com:Syntaf/wetrockpolice.git
    
  5. Copy over the example environment, no initial modifications should be required

    cd wetrockpolice
    cp .env.example .env
    
  6. Update your .env to point towards your locally running services

    # .env.example
    
    # Database configuration
    # ------------------------------------
    POSTGRES_PASSWORD=
    POSTGRES_USER=<your-profile-username>
    POSTGRES_DB=wetrockpolice_development
    POSTGRES_TEST_DB=wetrockpolice_test
    POSTGRES_HOST=0.0.0.0
    
  7. Install dependencies

    make install
    
  8. Setup your database

    make init
    
  9. Start your servers

    make dev
    
  10. Visit http://localhost:3001

Contributing

This repository uses Github Actions for continuous integration. Before a pull request can be merged into master it must pass all existing / new tests as well as linting (Rubocop). Using a rubocop extension is highly recommended.

Running the tests

bundle exec rails test          # unit / integration
bundle exec rails test:system   # headless Chrome, requires Chrome installed

rails test does not include test/system, so run both.

System tests drive the real compiled bundle, so build it first (make pcat). They also refuse to run while public/assets/ exists: Propshaft serves that precompiled copy in preference to app/assets/builds, which would silently test whatever assets:precompile last wrote. If you hit that, run bundle exec rails assets:clobber && make pcat.

Using Rubocop on Visual Studio Code:

Download the following extensions which should come pre-configured in the included .vscode/settings.json

Using Rubocop from the command line

If you're opposed to VSCode or prefer using a different editor, you can always run rubocop from the command line inside the project:

~$: cd wetrockpolice
~$: rubocop

By default the configuration files should be detected and used, so no arguments are needed.

Coding Standards

For a full manifesto on coding standards, Rubocop will adhere mostly to the Ruby Style Guide. In short, keep these key things in mind:

  • Keep lines under 80 characters
  • Use standard snake_case for varible and method naming
  • Use do end instead of { } when writing multi-line blocks
  • Keep the length of blocks under 25 lines.
  • Don't put business logic inside controllers. Skinny controllers, fat models

While WRP only supports Red Rock currently, the backend is designed to support multiple areas in the future and that should be kept in mind during development. Make sure any changes made consider a future where there are many active areas that can display precipitation data.

Development Guide

Models Overview

The database is designed to support a site that one day may have many watched areas (Red Rock, Moe's Valley, Etc). Below is an Entity Relationship Diagram that can be used to gain an understanding of the models defined in this project.

ERB via LucidChards

LocalClimbingOrg

A not-for-profit climbing coalition managing one or more watched areas. Watched areas belong to one, and the association is what lets site content credit the coalition responsible for an area.

WatchedArea

Represents an area being monitored for rain. Uses it's slug field to define a unique "microsite" within WRP consisting of a:

  • Landing page (/redrock)
  • Rainy day options page (/redrock/rainy-day-options)
  • FAQ page (/redrock/faq)

Fields like info_bubble_excerpt and park_type_word allow for dynamic content on the landing page depending on the current watched area being rendered.

RainyDayArea

Links a climbing area to a watched area. Does not contain any information itself, just serves to define relationships between climbing areas and a watched area.

ClimbingArea

A climbing crag / area. Does not contain any associations to a watched area so that the same climbing area can be a "rainy day option" for multiple watched areas if needed.

Location

Contains a pair of coodinates in the EPSG:3857 WGS 84 / Pseudo-Mercator system, and an optional zoom attribute.

User

A standard devise-based user model. The one unique thing worth mentioning is the manages attribute, which contains an array of watched area IDs. I.e. user.manages == [1] means the user can manage all db data relating to Red Rock.

Frontend Structure

The asset pipeline is kept very simple intentionally. All assets are compressed, loaded and cached on a users first page visit, meaning there are no page specific JS/SCSS files.

JS code is encapsulated into vanilla "controllers"; each controller is responsible for managing the functionality on a given type of page. Since all of these controllers are loaded globally, you can immeditely use them at the bottom of your view template:

<!-- area/rainy_day_options/index.html.erb -->

<div class="rainy-day-content">
  <!-- ... -->
</div>
<script>
    // All controllers are loaded and in global scope
    var pageController = new RainyDayController({ /* ... */ });
</script>

Weather Data

Precipitation data comes from Synoptic Data. The browser never talks to Synoptic directly: the landing page's Stimulus controller fetches GET /:slug/precipitation, a small Rails proxy (Area::WeatherController) that calls Synoptic with the station id stored on the WatchedArea row, caches each response for 10 minutes, and passes the JSON through unchanged. The API token lives only on the server, read from the SYNOPTIC_API_TOKEN environment variable (in production, via the synoptic.token Helm secret supplied by secrets.yaml).

In development you normally don't need a token at all: with MOCK_WEATHER_DATA=true (the .env.example default) the page serves a bundled fixture response instead of fetching live data.

Alternate rain gauges (CampbellCloud)

A watched area can also have alternate gauges (RainGauge rows, editable by super admins in Rails Admin). When it does, a button under the hero title ("Check the Black Velvet gauge") switches the tiles and chart between gauges, and ?gauge=<slug> opens the page on a given gauge. Each alternate gauge is served by GET /:slug/precipitation/:gauge, which always answers in Synoptic's JSON shape so the chart code is provider-agnostic.

Gauges can be another Synoptic station or a station on CampbellCloud (e.g. SNCC's Black Velvet gauge, on DRI's organization). For CampbellCloud, CampbellCloudPrecipitation logs in with CAMPBELL_CLOUD_USERNAME / CAMPBELL_CLOUD_PASSWORD (password grant; the API has no API keys), finds the datastream for the gauge's datalogger campbell_table/campbell_field, pulls 20 days of datapoints and sums them into hourly totals in inches.

The field is either a per-interval amount (e.g. Rain_30min/Rain_in_Tot) or, with the gauge's cumulative box ticked, a running total (e.g. cum_ppt_in). Black Velvet uses the running total: some of its readings never upload, and a missing per-interval reading loses its rain, while the next running-total reading still includes it. Each interval is the change in the total since the previous reading, so rain from a gap lands on the first reading after it. A drop in the table's record number marks a logger restart, where the total starts over from 0. To see a station's tables and fields:

bin/rails "campbell_cloud:datastreams[<station uuid>]"

In production the credentials come from the campbellCloud.username / campbellCloud.password Helm values (secrets.yaml).

Creating or Updating Hero Images

This repository uses a custom strategy for loading large background images on the client to ensure the first-load experience isn't poor. Without this strategy, the page would load with the large image missing, then slowly load the image top-down as if the page was being printed out.

On page load, the browser will first load and display an extremely small version of the image (20x20 pixels for example) and apply a large gussian blur to distort the pixel borders. In the background, javascript is used to fetch the fully sized background image; once finished the full image will be swapped for the blurred image with a fade-in transition. The end result is a page load that looks like the background image is just being animated into view rather than slowly loaded.

Because of this strategy however, updating landing page images can be a little more involved. Follow these steps for creating or updating hero images:

  1. Create two copies of your desired hero image: One which is the original (high quality) image and another which has had it's size dramatically scaled down (less then 50x50 pixels). Ensure you've maintained the aspect ratio when scaling the image down.

  2. Move your two copies into app/assets/images/watched-area-slug, calling the original image hero-image.jpg and the small image hero-image-small.jpg.

  3. Go to https://www.base64-image.de/ and load your small image to receive a base64 encoded string. Copy that string to your clipboard and open application.html.erb. In the custom style block at the head, add two new SCSS rules:

      /* Watched Area */
      .hero-header.<slug> {
        background: url("data:image/jpeg;base64,/9j/4AAQSkZJ...");
        background-repeat: no-repeat;
        background-position: center center;
        background-size: cover;
      }
      .hero-header.<slug>.hero-header-loaded {
        background-image: url(<%= asset_path 'watchedarea/hero-image.jpg' %>);
      }

    Where <slug> refers to the slug of the watched area, e.g. redrock or castlerock. Since the initial background is a base64 encoded image, the page will almost always load with it already painted (albeit heavily blurred). The second rule will swap the background image while the image has been successfully loaded in the background (avoiding the top-down loading view).

  4. Load the page and ensure your page transitions from the small image to large image. If you're having trouble determing if the small image is loading properly you can comment out imageLoader.load() in views/area/watched_area/index.html.erb, this will cause the page to load with only the small image

Deploying to Kubernetes

Wetrockpolice is hosted on a digital ocean kubernetes cluster, deploying to this cluster (with credentials) is done through Makefile commands and helm. (k9s)[https://k9scli.io/] is a highly recommended tool.

CI is the image source of truth: every push to master that passes the test suite builds Dockerfile.production and publishes syntaf/wetrockpolice:<commit-sha> (see .github/workflows/tests.yml). To deploy, set image.tag in k8s/wetrockpolice/values.yaml to the desired commit sha and run make deploy. (make build/make push still exist as a deprecated escape hatch, but local pushes bypass the test gate.)

make deploy merges the untracked secrets.yaml over values.yaml (helm upgrade -f secrets.yaml); every value the chart ships as an empty placeholder must be set there, or the release deploys broken in ways the templates cannot catch:

  • masterKey — Rails SECRET_KEY_BASE
  • postgresql.auth.postgresPassword — the database password
  • sendgrid.password — outbound mail
  • synoptic.token — the Synoptic API token for the weather proxy. Without it the app still boots and passes its probes, but GET /:slug/precipitation answers 503 and every landing page renders its weather-unavailable state.

On boot the web container runs bin/rails db:prepare_locked from bin/docker-entrypoint: db:prepare wrapped in a Postgres advisory lock (lib/tasks/db_prepare_locked.rake) so concurrent replicas can't race the schema load on a fresh database. Migrations (or schema load on a fresh database) happen automatically at rollout; seeding does not — db/seeds.rb refuses to run in production unless you explicitly seed with ALLOW_PRODUCTION_SEED=1 and SEED_ADMIN_PASSWORD set (see below). Set SKIP_DB_PREPARE=1 on the container to suppress the prepare entirely.

Postgres cutover (Bitnami subchart → in-chart StatefulSet)

The chart now ships its own Postgres 17 StatefulSet (k8s/wetrockpolice/templates/postgresql/) in place of the frozen Bitnami subchart. The StatefulSet is deliberately named wetrockpolice-postgres — not the Bitnami wetrockpolice-postgresql — because a StatefulSet's selector and volume claim template are immutable: reusing the old name would make helm upgrade patch the existing object and be rejected by the API server. Only the Services and the password Secret keep the old wetrockpolice-postgresql name, since that's what the app deployment points at.

The first make deploy after the cutover therefore:

  1. Deletes the Bitnami StatefulSet and its pod (wetrockpolice-postgresql-0). Its PVC (data-wetrockpolice-postgresql-0, 8Gi, Postgres 15) is left behind untouched — take a final pg_dump from it first if you want to migrate data rather than reseed, and delete it manually once you no longer need it.
  2. Creates wetrockpolice-postgres with a fresh, empty PVC (data-wetrockpolice-postgres-0). The container's initdb creates an empty wetrockpolice_production, and the first web pod to boot loads the schema via db:prepare_locked. No data is migrated automatically.

To restore a dump instead of reseeding, the restore must land before the app prepares the fresh database: scale the web Deployment to 0 (or kubectl set env deployment/wetrockpolice SKIP_DB_PREPARE=1), restore the dump, then roll the web pods normally.

To reseed instead (the accepted disaster-recovery path — content and admin only, no user data), run a one-off inside a web pod:

kubectl exec -n wetrockpolice deploy/wetrockpolice -- \
  env ALLOW_PRODUCTION_SEED=1 SEED_ADMIN_PASSWORD='<strong password>' \
  ./bin/rails db:seed

SEED_ADMIN_PASSWORD has no default in production: seeding without it fails rather than creating an admin with a guessable password.

About

Helping serve the climbing community by providing real-time precipitation data and alternative climbing options for rain sensitive areas.

Resources

Stars

28 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages