Initial import of the public datacenter bingo site
Some checks failed
Build and Deploy to Production / test (push) Failing after 21s
Build and Deploy to Production / build (push) Has been skipped
Build and Deploy to Production / deploy (push) Has been skipped

The bingo card ran inside the asxpio container, dispatched by Host.
Give the public site its own repo, image and deploy so it can be
released and mirrored independently of asxp.io.

Editing stays in the asxp.io admin, which keeps owning the schema and
the photo pipeline; this app only reads the shared bingo tables and the
bingo/ photos, through a read-only DB role and MinIO user. Tests load a
snapshot of the asxpio-built schema (test/schema.sql).

Assisted-by: Claude:opus-5
This commit is contained in:
Sergei Poljanski 2026-10-12 03:48:06 +04:00
commit 062611fa21
Signed by: asxpi
GPG key ID: 4F8851660FA4121B
35 changed files with 2050 additions and 0 deletions

15
.dockerignore Normal file
View file

@ -0,0 +1,15 @@
.env
.gems
.bundle
vendor/bundle
*.log
tmp
flake.nix
flake.lock
CLAUDE.md
README.md
test
Rakefile
bin
.forgejo
.git

9
.env.example Normal file
View file

@ -0,0 +1,9 @@
RACK_ENV=development
BINGO_HOST=localhost
DATABASE_URL=postgres://bingo:change-me@localhost:5432/asxpio
S3_ENDPOINT=http://localhost:9000
S3_REGION=us-east-1
S3_BUCKET=asxpio-invoices
S3_ACCESS_KEY=change-me
S3_SECRET_KEY=change-me
INDEXNOW_KEY=

View file

@ -0,0 +1,159 @@
name: Build and Deploy to Production
on:
push:
branches:
- main
jobs:
# Same job as in test.yaml (which covers non-main branches); duplicated here
# so a red suite blocks the build+deploy — Forgejo has no cross-workflow needs.
test:
runs-on: nix-latest
services:
postgres:
image: postgres:17-alpine
env:
POSTGRES_USER: postgres
POSTGRES_HOST_AUTH_METHOD: trust
POSTGRES_DB: bingo_test
steps:
- name: Prepare container for actions
run: |
echo "experimental-features = nix-command flakes" >> /etc/nix/nix.conf
# node for JS actions (checkout); git-minimal is already in the image
nix-env -iA nixpkgs.nodejs_22
- name: Checkout
uses: actions/checkout@v4
- name: Cache gems
uses: actions/cache@v4
with:
path: .gems
key: gems-${{ hashFiles('Gemfile.lock') }}
- name: Wait for Postgres
run: |
for i in $(seq 1 30); do
nix develop -c pg_isready -h postgres -U postgres && exit 0
sleep 2
done
echo "Postgres service never became ready" >&2
exit 1
- name: Run test suite
env:
TEST_DATABASE_URL: postgres://postgres@postgres:5432/bingo_test
run: nix develop -c bundle exec rake test
build:
runs-on: arch-latest
needs: test
container:
image: gcr.io/kaniko-project/executor:debug
outputs:
image_tag: ${{ steps.build_image.outputs.image_tag }}
steps:
- name: Build and push Docker Image using Kaniko
id: build_image
run: |
# Tags
SHORT_SHA=${GITHUB_SHA::8}
IMAGE_BASE=${{ secrets.FJ_REGISTRY }}/${{ secrets.FJ_USER }}/datacenterbingo
IMAGE_TAG=${IMAGE_BASE}:${SHORT_SHA}
IMAGE_LATEST=${IMAGE_BASE}:latest
# Auth Conf
mkdir -p /kaniko/.docker
echo "{\"auths\":{\"${{ secrets.FJ_REGISTRY }}\":{\"auth\":\"$(echo -n ${{ secrets.FJ_USER }}:${{ secrets.FJ_TOKEN }} | base64)\"}}}" > /kaniko/.docker/config.json
# Build & push
/kaniko/executor \
--context=git://${{ secrets.FJ_REGISTRY }}/${{ github.repository }}.git \
--git=branch=${{ github.ref_name }} \
--destination=$IMAGE_TAG \
--destination=$IMAGE_LATEST
# Output the specific tag for deployment
echo "image_tag=${IMAGE_TAG}" >> $GITHUB_OUTPUT
deploy:
runs-on: arch-latest
needs: build
steps:
- name: Install dependencies
run: |
pacman -Syu --noconfirm nodejs openssh rsync
- name: Checkout code
uses: actions/checkout@v4
- name: Deploy docker-compose.yml
uses: easingthemes/ssh-deploy@v5.1.0
with:
SSH_PRIVATE_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
REMOTE_HOST: ${{ secrets.DEPLOY_IP }}
REMOTE_USER: ${{ secrets.DEPLOY_USER }}
SOURCE: "docker-compose.yml"
TARGET: "/opt/datacenterbingo/"
# Read-only DB role and MinIO user (see CLAUDE.md); the asxp.io admin
# owns writes. BINGO_HOST also feeds the Traefik rule via compose.
- name: Deploy .env from secrets
uses: appleboy/ssh-action@v1.2.3
env:
BINGO_DB_PASSWORD: ${{ secrets.BINGO_DB_PASSWORD }}
BINGO_S3_ACCESS_KEY: ${{ secrets.BINGO_S3_ACCESS_KEY }}
BINGO_S3_SECRET_KEY: ${{ secrets.BINGO_S3_SECRET_KEY }}
INDEXNOW: ${{ secrets.INDEXNOW }}
with:
host: ${{ secrets.DEPLOY_IP }}
username: ${{ secrets.DEPLOY_USER }}
key: ${{ secrets.DEPLOY_SSH_KEY }}
envs: BINGO_DB_PASSWORD,BINGO_S3_ACCESS_KEY,BINGO_S3_SECRET_KEY,INDEXNOW
script_stop: true
script: |
umask 077
mkdir -p /opt/datacenterbingo
cat > /opt/datacenterbingo/.env <<EOF
RACK_ENV=production
BINGO_HOST=datacenterbingo.xyz
DATABASE_URL=postgres://bingo:${BINGO_DB_PASSWORD}@postgres:5432/asxpio
S3_ENDPOINT=http://minio:9000
S3_REGION=us-east-1
S3_BUCKET=asxpio-invoices
S3_ACCESS_KEY=${BINGO_S3_ACCESS_KEY}
S3_SECRET_KEY=${BINGO_S3_SECRET_KEY}
INDEXNOW_KEY=${INDEXNOW}
EOF
chmod 600 /opt/datacenterbingo/.env
- name: Deploy and update container
uses: appleboy/ssh-action@v1.2.3
env:
NEW_IMAGE: ${{ needs.build.outputs.image_tag }}
with:
host: ${{ secrets.DEPLOY_IP }}
username: ${{ secrets.DEPLOY_USER }}
key: ${{ secrets.DEPLOY_SSH_KEY }}
envs: NEW_IMAGE
script: |
cd /opt/datacenterbingo
sed -i "s|image:.*|image: $NEW_IMAGE|" docker-compose.yml
docker pull $NEW_IMAGE
docker compose up -d
for i in $(seq 1 18); do
status=$(docker inspect --format '{{.State.Health.Status}}' datacenterbingo 2>/dev/null || echo missing)
if [ "$status" = "healthy" ]; then
echo "Deployment successful!"
exit 0
fi
sleep 5
done
echo "datacenterbingo never became healthy (last status: $status)" >&2
docker logs --tail 50 datacenterbingo
exit 1

View file

@ -0,0 +1,56 @@
name: Tests
# main is covered by the test job inside deploy.yaml (which gates the build);
# this workflow covers every other branch.
on:
push:
branches-ignore:
- main
jobs:
test:
runs-on: nix-latest
services:
# CI stand-in for bin/test's ephemeral Postgres: the nix container runs
# as root and initdb refuses to run as root, so the DB lives in a
# service container instead and the suite connects via TEST_DATABASE_URL.
# Job and service share the per-workflow bridge network (the runner's
# container.network must stay "" — with "host" the service network is
# never created and services fail to start).
postgres:
image: postgres:17-alpine
env:
POSTGRES_USER: postgres
POSTGRES_HOST_AUTH_METHOD: trust
POSTGRES_DB: bingo_test
steps:
- name: Prepare container for actions
run: |
echo "experimental-features = nix-command flakes" >> /etc/nix/nix.conf
# node for JS actions (checkout); git-minimal is already in the image
nix-env -iA nixpkgs.nodejs_22
- name: Checkout
uses: actions/checkout@v4
# The nix closure persists in the runner's nix-store volume; gems live
# in the workspace (.gems via the flake's BUNDLE_PATH), so cache those.
- name: Cache gems
uses: actions/cache@v4
with:
path: .gems
key: gems-${{ hashFiles('Gemfile.lock') }}
- name: Wait for Postgres
run: |
for i in $(seq 1 30); do
nix develop -c pg_isready -h postgres -U postgres && exit 0
sleep 2
done
echo "Postgres service never became ready" >&2
exit 1
- name: Run test suite
env:
TEST_DATABASE_URL: postgres://postgres@postgres:5432/bingo_test
run: nix develop -c bundle exec rake test

6
.gitignore vendored Normal file
View file

@ -0,0 +1,6 @@
.env
.gems/
.bundle/
vendor/bundle/
*.log
tmp/

64
CLAUDE.md Normal file
View file

@ -0,0 +1,64 @@
# datacenterbingo
Public site for datacenterbingo.xyz: a 5×5 bingo card of Russia's largest
datacenters, crossed out on publicly sourced incidents. Ruby/Sinatra,
read-only. Primary repo `git.czsk.it/asxpi/datacenterbingo` (Forgejo, CI and
deploy); `github.com/asxpi/datacenterbingo` is a push mirror.
## Shared with asxpio
Content is edited in the asxp.io admin (`/admin/bingo`, repo `asxpio`:
`lib/bingo.rb`, `lib/bingo_admin.rb`). Both apps use the same Postgres tables
(`bingo_datacenters`, `bingo_incidents`) and the photos under `bingo/` in
asxpio's MinIO bucket.
- **asxpio owns the schema.** Migrations live there. After it adds a
bingo migration, refresh `test/schema.sql` (instructions in its header)
and update the models here.
- `lib/bingo.rb` here is the read side of asxpio's: models, `Board`,
`PROVIDERS`, the `T` UI strings, and photo/IndexNow key reading. The
admin side (writes, photo upload and resizing, IndexNow pings, ranking,
seeding, `guess_provider`) stays in asxpio. Keep shared parts in step:
`PROVIDERS`, `Board`, and model methods.
- Prod uses a read-only DB role `bingo` (SELECT on the two tables) and a
MinIO user limited to `s3:GetObject` on `asxpio-invoices/bingo/*`. Both
are provisioned by the `storage` repo (`init/`), from the same
`BINGO_*` secrets set on both repos.
## Layout
- `app.rb`: `BingoWeb`. Routes: `/` (redirect by Accept-Language), `/ru|en|uk`
(card; `?view=all`, `?p[]=provider`), `/:locale/dc/:slug`, `/sitemap.xml`,
`/robots.txt`, `/p/:file` (photo proxy, immutable), `/<indexnow-key>.txt`,
icons, `/healthz`.
- `config.ru`: `www.` → `BINGO_HOST` 301.
- `views/`: `layout.erb` (CSS and SEO head), `index.erb` (card, provider
filter, dialogs), `dc.erb`, partials. `assets/`: icons.
- Card rules: always 5×5. The bare locale URL is the operational card
(indexed). `?view=all` and provider-filtered URLs are noindex, with
canonical pointing to the bare page.
## Dev and tests
`nix develop`, then `bin/test`. That provisions an ephemeral Postgres and
loads `test/schema.sql`. Run `cp .env.example .env` for a local server
(`rackup`), pointing it at a DB that has the bingo tables.
## Deploy
On push to `main`, `.forgejo/workflows/deploy.yaml` tests, builds with kaniko
to `$FJ_REGISTRY/$FJ_USER/datacenterbingo`, then over SSH writes
`/opt/datacenterbingo/{docker-compose.yml,.env}` and runs
`docker compose up -d`. The container is on the `traefik` and `storage`
networks, and the Traefik router `datacenterbingo` takes `BINGO_HOST` and
`www.`.
Secrets:
| Secret | Purpose |
|---|---|
| `FJ_REGISTRY`, `FJ_USER`, `FJ_TOKEN` | kaniko clone + push (`write:package`, `read:repository`); Forgejo reserves the `FORGEJO_` prefix |
| `DEPLOY_IP`, `DEPLOY_USER`, `DEPLOY_SSH_KEY` | SSH to prod |
| `BINGO_DB_PASSWORD` | read-only Postgres role `bingo` |
| `BINGO_S3_ACCESS_KEY`, `BINGO_S3_SECRET_KEY` | read-only MinIO user |
| `INDEXNOW` | same key as asxpio's `INDEXNOW` (served here, pinged from there) |

32
Dockerfile Normal file
View file

@ -0,0 +1,32 @@
FROM ruby:3.4-slim-bookworm
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential \
libpq-dev \
&& rm -rf /var/lib/apt/lists/*
RUN groupadd -g 11000 bingo \
&& useradd -d /app -u 21000 -g 11000 -m -s /bin/bash bingo
WORKDIR /app
USER bingo
ENV GEM_HOME=/app/bundle
ENV PATH="${GEM_HOME}/bin:${PATH}"
COPY --chown=bingo Gemfile Gemfile.lock* ./
ENV BUNDLE_FROZEN=true
RUN bundle install --without development:test
COPY --chown=bingo . .
ENV PUMA_PORT=3000
ENV PUMA_THREADS="4:16"
ENV RACK_ENV=production
EXPOSE 3000
# Slim image has no curl; ruby is right there.
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
CMD ruby -rnet/http -e 'port = ENV.fetch("PUMA_PORT", "3000"); exit(Net::HTTP.get_response(URI("http://127.0.0.1:#{port}/healthz")).code == "200" ? 0 : 1)'
CMD ["sh", "-c", "exec puma -b tcp://0.0.0.0:${PUMA_PORT} -t ${PUMA_THREADS} --preload"]

27
Gemfile Normal file
View file

@ -0,0 +1,27 @@
source 'https://rubygems.org'
ruby '>= 3.1'
gem 'sinatra', '~> 4.2'
gem 'puma', '~> 6.6'
gem 'rack', '~> 3.2'
gem 'rack-protection', '~> 4.2'
gem 'rackup', '~> 2.3'
gem 'erubi', '~> 1.13'
gem 'dotenv', '~> 3.1'
gem 'pg', '~> 1.5'
gem 'sequel', '~> 5.86'
gem 'aws-sdk-s3', '~> 1.170'
# aws-sdk-core needs an XML parser; rexml stopped being a default gem in
# Ruby 3.4, so it must be declared or S3 calls raise at first use.
gem 'rexml', '~> 3.4'
group :development do
gem 'rerun', '~> 0.14'
end
group :test do
gem 'minitest', '~> 5.25'
gem 'rack-test', '~> 2.2'
gem 'rake', '~> 13.2'
end

120
Gemfile.lock Normal file
View file

@ -0,0 +1,120 @@
GEM
remote: https://rubygems.org/
specs:
aws-eventstream (1.4.0)
aws-partitions (1.1253.0)
aws-sdk-core (3.249.0)
aws-eventstream (~> 1, >= 1.3.0)
aws-partitions (~> 1, >= 1.992.0)
aws-sigv4 (~> 1.9)
base64
bigdecimal
jmespath (~> 1, >= 1.6.1)
logger
aws-sdk-kms (1.128.0)
aws-sdk-core (~> 3, >= 3.248.0)
aws-sigv4 (~> 1.5)
aws-sdk-s3 (1.224.0)
aws-sdk-core (~> 3, >= 3.248.0)
aws-sdk-kms (~> 1)
aws-sigv4 (~> 1.5)
aws-sigv4 (1.12.1)
aws-eventstream (~> 1, >= 1.0.2)
base64 (0.3.0)
bigdecimal (3.3.1)
dotenv (3.2.0)
erubi (1.13.1)
ffi (1.17.4)
ffi (1.17.4-aarch64-linux-gnu)
ffi (1.17.4-aarch64-linux-musl)
ffi (1.17.4-arm-linux-gnu)
ffi (1.17.4-arm-linux-musl)
ffi (1.17.4-arm64-darwin)
ffi (1.17.4-x86-linux-gnu)
ffi (1.17.4-x86-linux-musl)
ffi (1.17.4-x86_64-darwin)
ffi (1.17.4-x86_64-linux-gnu)
ffi (1.17.4-x86_64-linux-musl)
jmespath (1.6.2)
listen (3.10.0)
logger
rb-fsevent (~> 0.10, >= 0.10.3)
rb-inotify (~> 0.9, >= 0.9.10)
logger (1.7.0)
minitest (5.27.0)
mustermann (3.1.1)
nio4r (2.7.5)
pg (1.6.3)
pg (1.6.3-aarch64-linux)
pg (1.6.3-aarch64-linux-musl)
pg (1.6.3-arm64-darwin)
pg (1.6.3-x86_64-darwin)
pg (1.6.3-x86_64-linux)
pg (1.6.3-x86_64-linux-musl)
puma (6.6.1)
nio4r (~> 2.0)
rack (3.2.6)
rack-protection (4.2.1)
base64 (>= 0.1.0)
logger (>= 1.6.0)
rack (>= 3.0.0, < 4)
rack-session (2.1.2)
base64 (>= 0.1.0)
rack (>= 3.0.0)
rack-test (2.2.0)
rack (>= 1.3)
rackup (2.3.1)
rack (>= 3)
rake (13.4.2)
rb-fsevent (0.11.2)
rb-inotify (0.11.1)
ffi (~> 1.0)
rerun (0.14.0)
listen (~> 3.0)
rexml (3.4.4)
sequel (5.104.0)
bigdecimal
sinatra (4.2.1)
logger (>= 1.6.0)
mustermann (~> 3.0)
rack (>= 3.0.0, < 4)
rack-protection (= 4.2.1)
rack-session (>= 2.0.0, < 3)
tilt (~> 2.0)
tilt (2.7.0)
PLATFORMS
aarch64-linux-gnu
aarch64-linux-musl
arm-linux-gnu
arm-linux-musl
arm64-darwin
ruby
x86-linux-gnu
x86-linux-musl
x86_64-darwin
x86_64-linux-gnu
x86_64-linux-musl
DEPENDENCIES
aws-sdk-s3 (~> 1.170)
dotenv (~> 3.1)
erubi (~> 1.13)
minitest (~> 5.25)
pg (~> 1.5)
puma (~> 6.6)
rack (~> 3.2)
rack-protection (~> 4.2)
rack-test (~> 2.2)
rackup (~> 2.3)
rake (~> 13.2)
rerun (~> 0.14)
rexml (~> 3.4)
sequel (~> 5.86)
sinatra (~> 4.2)
RUBY VERSION
ruby 3.4.9p82
BUNDLED WITH
2.6.9

16
README.md Normal file
View file

@ -0,0 +1,16 @@
# Datacenter Bingo
https://datacenterbingo.xyz: a 5×5 bingo card of Russia's largest
datacenters. A cell is crossed out once a drone strike, fire or outage
there is reported by a public source. Available in Ukrainian, English and
Russian.
This repo is the public site (Ruby/Sinatra). Content is managed from a
separate admin app that shares the database.
Data comes from open sources. It was collected and verified with the help
of Claude (Anthropic). Part of the list came from the
[hackyourmom datacenter map](https://hackyourmom.com/en/karta-data-czentriv-na-rasii/)
(data by Cat Eyes OSINT), and each entry was re-verified.
Development: `nix develop`, then `bin/test`. See `CLAUDE.md`.

9
Rakefile Normal file
View file

@ -0,0 +1,9 @@
require 'rake/testtask'
Rake::TestTask.new(:test) do |t|
t.libs << 'test'
t.pattern = 'test/*_test.rb'
t.warning = false
end
task default: :test

264
app.rb Normal file
View file

@ -0,0 +1,264 @@
require 'logger'
require 'json'
require 'sinatra/base'
require 'erubi'
begin
require 'dotenv'
Dotenv.load unless ENV['RACK_ENV'] == 'test'
rescue LoadError
end
$root = __dir__
$logger = Logger.new($stdout)
$env = ENV.fetch('RACK_ENV', 'development')
require_relative 'lib/db'
if ENV['DATABASE_URL']
DB.connect!
require_relative 'lib/bingo'
else
$logger.warn('DATABASE_URL not set — every page answers 503')
end
# Public datacenter bingo on BINGO_HOST. Read-only: no session, no CSRF.
# Content is managed from asxp.io/admin/bingo (asxpio repo), which shares the
# database and photo bucket.
class BingoWeb < Sinatra::Base
HOSTS = [ENV['BINGO_HOST'], ENV['BINGO_ALT_HOST']].compact.reject(&:empty?).freeze
configure do
set :root, $root
set :erb, layout: :layout, escape_html: true
set :static, false # icons have explicit routes below
set :show_exceptions, $env == 'development'
# HSTS (1 year, this host only); http:// already 308s at the edge.
set :protection, use: %i[strict_transport]
set :host_authorization,
{ permitted_hosts: $env == 'production' ? [*HOSTS, '127.0.0.1'] : [] } # 127.0.0.1: HEALTHCHECK
end
helpers do
def t(key) = Bingo::T[@locale][key]
def kind_label(kind) = Bingo::T[@locale][:kinds][kind] || Bingo::T[@locale][:kinds]['other']
def kind_icon(kind) = Bingo::ICONS[kind] || Bingo::ICONS['other']
def photo_path(dc, width = nil) = dc.photo_file(width) && "/p/#{dc.photo_file(width)}"
# Path for a locale/view combination; the default view (operational)
# keeps a bare URL, the full list is ?view=all.
# Path for a locale/view/provider selection; the default (operational,
# every provider) keeps a bare URL.
def card_path(locale = @locale, view = @view, providers = @providers)
q = []
q << 'view=all' if view == 'all'
Array(providers).each { |p| q << "p[]=#{Rack::Utils.escape(p)}" }
q.empty? ? "/#{locale}" : "/#{locale}?#{q.join('&')}"
end
def selected_providers
Array(params[:p]).flat_map { |v| v.to_s.split(',') }.select { |p| Bingo::PROVIDERS.key?(p) }.uniq
end
def dc_path(dc, locale = @locale) = "/#{locale}/dc/#{dc.slug}"
def base_url = "https://#{ENV.fetch('BINGO_HOST', request.host)}"
# WebSite + ItemList of the card's datacenters, for rich results.
def json_ld(board, desc)
url = "#{base_url}/#{@locale}"
JSON.generate(
'@context' => 'https://schema.org',
'@graph' => [
{ '@type' => 'WebSite', '@id' => "#{base_url}/#website", 'url' => "#{base_url}/",
'name' => t(:title), 'inLanguage' => Bingo::LOCALES,
'publisher' => { '@type' => 'Person', 'name' => 'asxpi', 'url' => 'https://asxp.io' } },
{ '@type' => 'ItemList', 'url' => url, 'name' => t(:seo_title), 'description' => desc,
'inLanguage' => @locale, 'numberOfItems' => board.cells.size,
'dateModified' => board.updated_on&.utc&.iso8601,
'itemListElement' => board.cells.each_with_index.map do |dc, i|
{ '@type' => 'ListItem', 'position' => i + 1, 'item' => ld_place(dc) }
end }.compact
]
).gsub('</', '<\/')
end
# The info_url describes the datacenter (operator page, news), it isn't
# the datacenter's own identity, so subjectOf rather than sameAs.
# Incidents are Events at the place.
def ld_place(dc)
address = { '@type' => 'PostalAddress', 'addressLocality' => dc.l(:city, @locale), 'addressCountry' => 'RU' }
url = "#{base_url}#{dc_path(dc)}"
place = { '@type' => 'Place', '@id' => "#{url}#place", 'url' => url, 'name' => dc.l(:name, @locale), 'address' => address }
place['image'] = "#{base_url}#{photo_path(dc, 1200)}" if dc.photo_key
place['subjectOf'] = { '@type' => 'CreativeWork', 'url' => dc.info_url } if dc.info_url
events = dc.incidents.map do |i|
{ '@type' => 'Event', 'name' => "#{kind_label(i.kind)}: #{i.l(:title, @locale)}",
'startDate' => i.occurred_on.iso8601, 'url' => i.url,
'location' => { '@type' => 'Place', 'name' => place['name'], 'address' => address } }.compact
end
place['event'] = events if events.any?
place
end
# Datacenter page: the Place plus a breadcrumb back to the card.
def dc_json_ld(dc)
JSON.generate(
'@context' => 'https://schema.org',
'@graph' => [
ld_place(dc),
{ '@type' => 'BreadcrumbList', 'itemListElement' => [
{ '@type' => 'ListItem', 'position' => 1, 'name' => t(:title), 'item' => "#{base_url}/#{@locale}" },
{ '@type' => 'ListItem', 'position' => 2, 'name' => dc.l(:name, @locale), 'item' => "#{base_url}#{dc_path(dc)}" }
] }
]
).gsub('</', '<\/')
end
# Plain-language facts for the datacenter page and its meta description.
def dc_facts(dc)
[format(t(:dc_intro), name: dc.l(:name, @locale), city: dc.l(:city, @locale), operator: dc.operator),
(format(t(:dc_capacity), mw: mw_prose(dc)) if mw(dc)),
{ 'building' => t(:dc_building), 'planned' => t(:dc_planned) }[dc.status] || (dc.year && format(t(:dc_since), dc.year)),
format(t(:dc_rank), pos: dc.position)].compact
end
def dc_latest(dc)
i = dc.incidents.first or return t(:no_incidents)
format(t(:dc_latest), date: fmt_date(i.occurred_on), title: i.l(:title, @locale))
end
# Cut at a word boundary to fit a search snippet.
def snippet(text, max = 160)
text.length <= max ? text : "#{text[0, max - 1][/\A.*(?=\s)/m] || text[0, max - 1]}…"
end
# Preview image: the most recent hit with a photo, else the first photo.
def og_dc(board)
board.incidents.map(&:datacenter).find(&:photo_key) || board.cells.find(&:photo_key)
end
def fmt_date(d) = d.strftime('%d.%m.%Y')
# "64 MW", "64 MW · design", "17 MVA" (MVA is a unit, not a tag).
def mw(dc, tag: true)
return if dc.mw.to_s.strip.empty?
return "#{dc.mw} #{t(:mva)}" if dc.mw_type == 'mva'
tag &&= t(:mw_types)[dc.mw_type]
["#{dc.mw} #{t(:mw)}", tag || nil].compact.join(' · ')
end
# "63 MW (design)": the dialog's " · design" tag reads badly in a sentence.
def mw_prose(dc)
tag = dc.mw_type != 'mva' && t(:mw_types)[dc.mw_type]
tag ? "#{mw(dc, tag: false)} (#{tag})" : mw(dc)
end
# Badge for anything not yet in service.
def status_label(dc)
{ 'building' => t(:building), 'planned' => t(:planned) }[dc.status]
end
def preferred_locale
langs = request.env['HTTP_ACCEPT_LANGUAGE'].to_s.downcase.scan(/([a-z]{2})(?:-[a-z]+)?(?:;q=([\d.]+))?/)
langs.sort_by { |_, q| -(q || '1').to_f }.map(&:first).find { |l| Bingo::LOCALES.include?(l) } || 'en'
end
end
get '/healthz' do
halt 503, 'no database' unless defined?(Bingo::Datacenter)
DB.connection.test_connection
'ok'
end
before do
halt 503, 'Bingo not configured (DATABASE_URL missing).' unless defined?(Bingo::Datacenter)
end
get '/' do
headers 'Vary' => 'Accept-Language'
redirect "/#{preferred_locale}", 302
end
get '/robots.txt' do
content_type 'text/plain'
"User-agent: *\nAllow: /\n\nSitemap: #{base_url}/sitemap.xml\n"
end
# The card and every datacenter page (reserve included), each with its
# language alternates.
get '/sitemap.xml' do
content_type 'application/xml'
cache_control :public, max_age: 3600
dcs = Bingo::Datacenter.order(:position, :id).eager(:incidents).all
@entries = [[->(l) { "/#{l}" }, Bingo::Board.load.updated_on, '/']] +
dcs.map { |dc| [->(l) { dc_path(dc, l) }, [dc.updated_at, *dc.incidents.map(&:updated_at)].compact.max] }
erb :sitemap, layout: false
end
# One URL per page: /en/ is a duplicate of /en.
get %r{/((?:ru|en|uk)(?:/dc/[a-z0-9-]+)?)/} do |path|
qs = request.query_string
redirect "/#{path}#{"?#{qs}" unless qs.empty?}", 301
end
get %r{/(ru|en|uk)} do |locale|
@locale = locale
@view = params[:view] == 'all' ? 'all' : Bingo::VIEWS.first
@providers = selected_providers
@board = Bingo::Board.load(@view, providers: @providers)
@title = t(:seo_title)
@desc = format(t(:seo_desc), hit: @board.hit.count(true), total: @board.cells.size)
@noindex = !@board.operational_only? || @board.filtered? # variants of the bare page
@path_for = ->(l) { "/#{l}" }
@x_default = '/'
@og = og_dc(@board)
@ld = json_ld(@board, @desc)
cache_control :public, max_age: 60
erb :index
end
get %r{/(ru|en|uk)/dc/([a-z0-9-]+)} do |locale, slug|
@locale = locale
@dc = Bingo::Datacenter.where(slug: slug).eager(:incidents).first or halt 404
@prev, @next = [-1, 1].map { |d| Bingo::Datacenter.first(position: @dc.position + d) }
name, city = @dc.l(:name, locale), @dc.l(:city, locale)
hit = @dc.incidents.first
@title = hit ? format(t(:dc_title_hit), name: name, city: city, kind: kind_label(hit.kind), date: fmt_date(hit.occurred_on))
: format(t(:dc_title), name: name, city: city)
@desc = snippet([*dc_facts(@dc).first(2), dc_latest(@dc)].join(' '))
@path_for = ->(l) { dc_path(@dc, l) }
@og = @dc if @dc.photo_key
@ld = dc_json_ld(@dc)
cache_control :public, max_age: 60
erb :dc
end
# IndexNow key file: proves to the engines that pings come from us.
get %r{/([A-Za-z0-9-]{8,128})\.txt} do |name|
halt 404 unless name == Bingo::IndexNow.key
content_type 'text/plain'
name
end
# Icons from assets/. Search engines want
# a crawlable favicon URL; a data: URI doesn't count.
ICONS = { 'favicon.svg' => 'image/svg+xml', 'favicon.ico' => 'image/x-icon',
'apple-touch-icon.png' => 'image/png' }.freeze
get %r{/(favicon\.svg|favicon\.ico|apple-touch-icon\.png)} do |name|
cache_control :public, max_age: 86_400
send_file File.join(settings.root, 'assets', name), type: ICONS[name]
end
# Photos are immutable per key (a new upload gets a new key).
get '/p/:file' do
bytes, type = Bingo::Photo.read(params[:file])
content_type type
cache_control :public, :immutable, max_age: 31_536_000
bytes
rescue Bingo::Photo::Error, Aws::S3::Errors::NoSuchKey, Aws::S3::Errors::NotFound
halt 404
end
not_found do
'Not found'
end
end

BIN
assets/apple-touch-icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

BIN
assets/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

1
assets/favicon.svg Normal file
View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="12" fill="#121212"/><rect x="5" y="5" width="10" height="10" rx="1.5" fill="#ff6a4d"/><rect x="16" y="5" width="10" height="10" rx="1.5" fill="#ece7dc"/><rect x="27" y="5" width="10" height="10" rx="1.5" fill="#ece7dc"/><rect x="38" y="5" width="10" height="10" rx="1.5" fill="#ece7dc"/><rect x="49" y="5" width="10" height="10" rx="1.5" fill="#ece7dc"/><rect x="5" y="16" width="10" height="10" rx="1.5" fill="#ece7dc"/><rect x="16" y="16" width="10" height="10" rx="1.5" fill="#ff6a4d"/><rect x="27" y="16" width="10" height="10" rx="1.5" fill="#ece7dc"/><rect x="38" y="16" width="10" height="10" rx="1.5" fill="#ece7dc"/><rect x="49" y="16" width="10" height="10" rx="1.5" fill="#ece7dc"/><rect x="5" y="27" width="10" height="10" rx="1.5" fill="#ece7dc"/><rect x="16" y="27" width="10" height="10" rx="1.5" fill="#ece7dc"/><rect x="27" y="27" width="10" height="10" rx="1.5" fill="#ff6a4d"/><rect x="38" y="27" width="10" height="10" rx="1.5" fill="#ece7dc"/><rect x="49" y="27" width="10" height="10" rx="1.5" fill="#ece7dc"/><rect x="5" y="38" width="10" height="10" rx="1.5" fill="#ece7dc"/><rect x="16" y="38" width="10" height="10" rx="1.5" fill="#ece7dc"/><rect x="27" y="38" width="10" height="10" rx="1.5" fill="#ece7dc"/><rect x="38" y="38" width="10" height="10" rx="1.5" fill="#ff6a4d"/><rect x="49" y="38" width="10" height="10" rx="1.5" fill="#ece7dc"/><rect x="5" y="49" width="10" height="10" rx="1.5" fill="#ece7dc"/><rect x="16" y="49" width="10" height="10" rx="1.5" fill="#ece7dc"/><rect x="27" y="49" width="10" height="10" rx="1.5" fill="#ece7dc"/><rect x="38" y="49" width="10" height="10" rx="1.5" fill="#ece7dc"/><rect x="49" y="49" width="10" height="10" rx="1.5" fill="#ff6a4d"/></svg>

After

Width:  |  Height:  |  Size: 1.8 KiB

View file

@ -0,0 +1 @@
img

19
bin/test Executable file
View file

@ -0,0 +1,19 @@
#!/usr/bin/env bash
# Full test suite against an ephemeral Postgres. Run inside `nix develop`
# (needs initdb/pg_ctl from the dev shell). Without a database you can still
# run `bundle exec rake test` — DB-backed tests skip.
set -euo pipefail
cd "$(dirname "$0")/.."
PORT="${TEST_PG_PORT:-54329}"
TMP="$(mktemp -d)"
trap 'pg_ctl -D "$TMP/pg" stop -m immediate >/dev/null 2>&1 || true; rm -rf "$TMP"' EXIT
initdb -D "$TMP/pg" -A trust -U postgres >/dev/null
printf "unix_socket_directories = ''\nlisten_addresses = '127.0.0.1'\nport = %s\n" "$PORT" \
>> "$TMP/pg/postgresql.conf"
pg_ctl -D "$TMP/pg" -l "$TMP/pg.log" start >/dev/null
createdb -h 127.0.0.1 -p "$PORT" -U postgres bingo_test
TEST_DATABASE_URL="postgres://postgres@127.0.0.1:$PORT/bingo_test" \
bundle exec rake test "$@"

14
config.ru Normal file
View file

@ -0,0 +1,14 @@
require_relative 'app'
# www. redirects to the canonical BINGO_HOST; everything else is the card.
bingo_host = ENV['BINGO_HOST']
bingo = BingoWeb.new
run lambda { |env|
req = Rack::Request.new(env)
if bingo_host && req.host == "www.#{bingo_host}"
[301, { 'location' => "https://#{bingo_host}#{req.fullpath}" }, []]
else
bingo.call(env)
end
}

27
docker-compose.yml Normal file
View file

@ -0,0 +1,27 @@
services:
bingo:
# Image is set by the deploy workflow (registry/user/datacenterbingo:sha).
build: .
image: datacenterbingo:latest
container_name: datacenterbingo
restart: unless-stopped
env_file: .env
networks:
- traefik
- storage # postgres + minio
labels:
- "traefik.enable=true"
# Priority beats the old asxpio-bingo router while both exist.
- "traefik.http.routers.datacenterbingo.rule=Host(`${BINGO_HOST}`) || Host(`www.${BINGO_HOST}`)"
- "traefik.http.routers.datacenterbingo.priority=1000"
- "traefik.http.routers.datacenterbingo.entrypoints=websecure"
- "traefik.http.routers.datacenterbingo.tls=true"
- "traefik.http.routers.datacenterbingo.tls.certresolver=letsencrypt"
- "traefik.http.routers.datacenterbingo.service=datacenterbingo"
- "traefik.http.services.datacenterbingo.loadbalancer.server.port=3000"
networks:
traefik:
external: true
storage:
external: true

27
flake.lock generated Normal file
View file

@ -0,0 +1,27 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1777578337,
"narHash": "sha256-Ad49moKWeXtKBJNy2ebiTQUEgdLyvGmTeykAQ9xM+Z4=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "15f4ee454b1dce334612fa6843b3e05cf546efab",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}

Some files were not shown because too many files have changed in this diff Show more