Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 20 additions & 4 deletions DEPLOYMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ Settle ships as two images built from `docker/Dockerfile`, run with Docker Compo
- `ghcr.io/ame180/settle-php` (`prod` target): PHP-FPM with the app, vendor dependencies and the built frontend. Applies migrations on start.
- `ghcr.io/ame180/settle-web` (`web` target): nginx serving `public/` and passing PHP requests to the `php` service.

`deploy/compose.yaml` runs both with MariaDB. TLS and the public hostname come from a reverse proxy in front of `web`.
`deploy/compose.yaml` runs both with MariaDB, plus a `scheduler` service on the php image (see [Scheduled jobs](#scheduled-jobs)). TLS and the public hostname come from a reverse proxy in front of `web`.

| Environment | Deployed by | Image tag |
| --- | --- | --- |
Expand Down Expand Up @@ -137,6 +137,8 @@ On the server, point `IMAGE_TAG` in `.env` at an earlier tag and restart:
cd ~/settle-staging && sed -i 's/^IMAGE_TAG=.*/IMAGE_TAG=v0.1.0/' .env && docker compose up -d --wait
```

v0.1.0 has no `scheduler`, so it restarts in a loop on that image. When rolling back to it, add `--scale scheduler=0` to the `up` command above and to any later `up` until the next deploy.

Rolling back code does not roll back the database. Migrations run on every start of `php`, so they must stay backward-compatible: the previous release has to work against the newer schema. A failing migration keeps `php` restarting (and `web` waiting) until it is fixed or rolled back.

## Backups
Expand All @@ -152,14 +154,28 @@ docker compose exec -T mariadb sh -c 'mariadb-dump -uroot -p"$MARIADB_ROOT_PASSW
To restore a dump (from that command or the nightly backups), stop the app so nothing writes, empty the database, load the dump and start again:

```bash
docker compose stop web php
docker compose stop web scheduler php
docker compose exec -T mariadb sh -c 'mariadb -uroot -p"$MARIADB_ROOT_PASSWORD" -e "DROP DATABASE \`$MARIADB_DATABASE\`; CREATE DATABASE \`$MARIADB_DATABASE\`"'
gunzip -c <dump>.sql.gz | docker compose exec -T mariadb sh -c 'mariadb -uroot -p"$MARIADB_ROOT_PASSWORD" "$MARIADB_DATABASE"'
docker compose start php web
docker compose start php scheduler web
```

On start, `php` applies any migrations newer than the dump, as on a deploy.

## Scheduled jobs

The `scheduler` service creates repeating expenses when they fall due. It runs `bin/console app:recurring:run` once on start, then `messenger:consume scheduler_default`, which runs the same job every hour. Each run creates every occurrence that is due, including ones missed while the service was down, each dated on its own schedule date, so stopping it only delays them. It doesn't run migrations; it starts once `php` is healthy.

Dates follow the container's timezone, UTC, so an occurrence due on a given day appears within an hour after midnight UTC.

To use a host cron instead, remove the service and run the job from the environment's directory, hourly or more often:

```bash
docker compose exec -T php bin/console app:recurring:run
```

Runs are safe to overlap, so a manual run alongside the service creates nothing twice.

## Adding users

Sign-up claims the account of anyone a user added as a contact by email, without checking that the email belongs to the person signing up. So public sign-up is off unless enabled: `POST /api/register` answers 403 and the app hides its sign-up link. Set `APP_REGISTRATION_ENABLED=1` in the server's `.env` only where that's acceptable, such as a private staging host.
Expand All @@ -176,7 +192,7 @@ If someone already added them as a contact, this claims that account, so their s

All commands run in the environment's directory.

- Status and logs: `docker compose ps`, `docker compose logs -f php`
- Status and logs: `docker compose ps`, `docker compose logs -f php` (`scheduler` for repeating expenses)
- Stop and start (e.g. staging between test sessions): `docker compose stop`, `docker compose start`
- Reset the staging database (after a branch's migrations left it out of step):

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Expense sharing for ad-hoc groups of friends. Symfony 7.4 JSON API plus a React

1. Copy `.env.example` to `.env` and fill in the values.
2. `docker login ghcr.io -u <username> -p <token>` (nginx/mariadb images live there).
3. `docker compose up -d` starts PHP, nginx (port `NGINX_PORT`, default 80) and the database. The PHP container installs Composer dependencies and runs migrations on start.
3. `docker compose up -d` starts PHP, nginx (port `NGINX_PORT`, default 80), the database and the `scheduler` that creates repeating expenses. The PHP container installs Composer dependencies and runs migrations on start; restart `scheduler` to pick up code changes.
4. Create a user: `docker compose exec php bin/console app:user:create <email> <password>`.
5. Frontend: `cd frontend && npm install && npm run dev`, then open http://localhost:5173. The Vite dev server proxies `/api` to nginx (override with `VITE_API_PROXY`).

Expand Down
22 changes: 22 additions & 0 deletions compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,32 @@ services:
- .:/app
env_file: .env
entrypoint: docker/entrypoint.sh
# php-fpm only listens once dependencies are installed and migrations have run.
healthcheck:
test: ["CMD", "php", "-r", "exit(@fsockopen('127.0.0.1', 9000) ? 0 : 1);"]
start_period: 300s
interval: 10s
timeout: 5s
retries: 3
depends_on:
mysql:
condition: service_healthy

# Long-running: restart it to pick up code changes.
scheduler:
build:
context: .
dockerfile: docker/Dockerfile
target: base
volumes:
- .:/app
env_file: .env
entrypoint: ["sh", "-c", "bin/console app:recurring:run && exec bin/console messenger:consume scheduler_default --memory-limit=128M"]
restart: unless-stopped
depends_on:
php:
condition: service_healthy

nginx:
image: ghcr.io/ame180/nginx-php:latest
environment:
Expand Down
2 changes: 2 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"doctrine/orm": "^3.8.0",
"phpdocumentor/reflection-docblock": "^5.6.7",
"phpstan/phpdoc-parser": "^2.4.1",
"symfony/clock": "7.4.*",
"symfony/console": "7.4.*",
"symfony/doctrine-messenger": "7.4.*",
"symfony/dotenv": "7.4.*",
Expand All @@ -31,6 +32,7 @@
"symfony/property-info": "7.4.*",
"symfony/rate-limiter": "7.4.*",
"symfony/runtime": "7.4.*",
"symfony/scheduler": "7.4.*",
"symfony/security-bundle": "7.4.*",
"symfony/serializer": "7.4.*",
"symfony/string": "7.4.*",
Expand Down
88 changes: 87 additions & 1 deletion composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion config/packages/messenger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ framework:
default_bus: messenger.bus.default

buses:
messenger.bus.default: []
# The scheduler worker idles between hourly ticks, long enough for the DB to drop the connection.
messenger.bus.default:
middleware:
- doctrine_ping_connection

routing:
Symfony\Component\Mailer\Messenger\SendEmailMessage: async
Expand Down
2 changes: 1 addition & 1 deletion config/reference.php
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,7 @@
* }>,
* },
* scheduler?: bool|array{ // Scheduler configuration
* enabled?: bool|Param, // Default: false
* enabled?: bool|Param, // Default: true
* },
* disallow_search_engine_index?: bool|Param, // Enabled by default when debug is enabled. // Default: true
* http_client?: bool|array{ // HTTP Client configuration
Expand Down
14 changes: 12 additions & 2 deletions deploy/compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ services:
php:
image: ghcr.io/ame180/settle-php:${IMAGE_TAG:?set IMAGE_TAG}
# Explicit list rather than env_file, so the DB root password never reaches the app.
environment:
environment: &php-environment
APP_SECRET: ${APP_SECRET:?set APP_SECRET}
MYSQL_HOST: mariadb
MYSQL_PORT: 3306
MYSQL_DATABASE: ${MYSQL_DATABASE:?set MYSQL_DATABASE}
MYSQL_USER: ${MYSQL_USER:?set MYSQL_USER}
MYSQL_PASSWORD: ${MYSQL_PASSWORD:?set MYSQL_PASSWORD}
SYMFONY_TRUSTED_PROXIES: private_ranges
# Required by the messenger and mailer config, though nothing sends messages or mail yet.
# Required by the messenger and mailer config, though nothing queues messages or sends mail yet.
MESSENGER_TRANSPORT_DSN: doctrine://default?auto_setup=0
MAILER_DSN: null://null
APP_REGISTRATION_ENABLED: ${APP_REGISTRATION_ENABLED:-}
Expand All @@ -29,6 +29,16 @@ services:
mariadb:
condition: service_healthy

# Skips the image's entrypoint, so only `php` runs migrations.
scheduler:
image: ghcr.io/ame180/settle-php:${IMAGE_TAG:?set IMAGE_TAG}
environment: *php-environment
entrypoint: ["sh", "-c", "bin/console app:recurring:run && exec bin/console messenger:consume scheduler_default --memory-limit=128M"]
restart: unless-stopped
depends_on:
php:
condition: service_healthy

web:
image: ghcr.io/ame180/settle-web:${IMAGE_TAG:?set IMAGE_TAG}
environment:
Expand Down
32 changes: 32 additions & 0 deletions migrations/Version20261126221928.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

declare(strict_types=1);

namespace DoctrineMigrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

final class Version20261126221928 extends AbstractMigration
{
public function getDescription(): string
{
return 'Add recurring_series and link expenses to it';
}

public function up(Schema $schema): void
{
$this->addSql("CREATE TABLE recurring_series (id INT AUTO_INCREMENT NOT NULL, unit VARCHAR(8) NOT NULL, every SMALLINT NOT NULL, anchor_on DATE NOT NULL COMMENT '(DC2Type:date_immutable)', next_run_on DATE NOT NULL COMMENT '(DC2Type:date_immutable)', active TINYINT(1) NOT NULL, created_at DATETIME NOT NULL COMMENT '(DC2Type:datetime_immutable)', updated_at DATETIME NOT NULL COMMENT '(DC2Type:datetime_immutable)', INDEX idx_recurring_series_due (active, next_run_on), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB");
$this->addSql('ALTER TABLE expense ADD series_id INT DEFAULT NULL');
$this->addSql('ALTER TABLE expense ADD CONSTRAINT FK_2D3A8DA65278319C FOREIGN KEY (series_id) REFERENCES recurring_series (id)');
$this->addSql('CREATE INDEX IDX_2D3A8DA65278319C ON expense (series_id)');
}

public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE expense DROP FOREIGN KEY FK_2D3A8DA65278319C');
$this->addSql('DROP INDEX IDX_2D3A8DA65278319C ON expense');
$this->addSql('ALTER TABLE expense DROP series_id');
$this->addSql('DROP TABLE recurring_series');
}
}
34 changes: 34 additions & 0 deletions src/Command/RecurringRunCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

namespace App\Command;

use App\Services\RecurringExpenseRunner;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(
name: 'app:recurring:run',
description: 'Creates the repeating expenses that are due',
)]
final class RecurringRunCommand extends Command
{
public function __construct(
private readonly RecurringExpenseRunner $runner,
) {
parent::__construct();
}

protected function execute(InputInterface $input, OutputInterface $output): int
{
$created = $this->runner->run();

(new SymfonyStyle($input, $output))->success(sprintf('Created %d repeating expense(s).', $created));

return Command::SUCCESS;
}
}
5 changes: 4 additions & 1 deletion src/Controller/Api/ExpenseApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,9 @@ private function toResponse(User $viewer, Expense $expense): ExpenseResponse
$participants[] = $debt->getPayer();
}

return ExpenseResponse::fromExpense($expense, $this->personRefFactory->createMany($viewer, $participants));
$series = $expense->getSeries();
$seriesLatestId = null === $series ? null : $this->expenseRepository->findLatestIdInSeries($series);

return ExpenseResponse::fromExpense($expense, $this->personRefFactory->createMany($viewer, $participants), $seriesLatestId);
}
}
1 change: 1 addition & 0 deletions src/Dto/ActivityItem.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public function __construct(
public PersonRef $payee,
public ?PersonRef $payer,
public ?ExpenseCategory $category,
public bool $recurring = false,
) {
}
}
3 changes: 3 additions & 0 deletions src/Dto/ExpenseRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ public function __construct(
public ExpenseCategory $category = ExpenseCategory::General,

public ?string $description = null,

#[Assert\Valid]
public ?RepeatRequest $repeat = null,
) {
}
}
8 changes: 7 additions & 1 deletion src/Dto/ExpenseResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,18 @@ public function __construct(
public SplitType $splitType,
public ExpenseCategory $category,
public array $debts,
public ?RepeatResponse $repeat,
public ?SeriesResponse $series,
) {
}

/**
* @param array<int, PersonRef> $people keyed by user id, must cover the payee and every debtor
*/
public static function fromExpense(Expense $expense, array $people): self
public static function fromExpense(Expense $expense, array $people, ?int $seriesLatestId): self
{
$series = $expense->getSeries();

$debts = array_map(
fn ($debt) => new ExpenseDebtResponse(
payer: $people[$debt->getPayer()->getId()],
Expand All @@ -52,6 +56,8 @@ public static function fromExpense(Expense $expense, array $people): self
splitType: $expense->getSplitType(),
category: $expense->getCategory(),
debts: array_values($debts),
repeat: null === $series ? null : RepeatResponse::fromSeries($series),
series: null === $seriesLatestId ? null : new SeriesResponse($seriesLatestId, $seriesLatestId === $expense->getId()),
);
}
}
Loading