Compare commits
43 Commits
v0.1.4
...
1340418a2b
| Author | SHA1 | Date | |
|---|---|---|---|
| 1340418a2b | |||
| 6d409fb4bd | |||
| dc1f1f11f9 | |||
| 0f1ef9e622 | |||
| 6beef58dbf | |||
| f0c10210eb | |||
| f9436a7423 | |||
| 65dd22f974 | |||
| 35c5237dfc | |||
| 28eb5e07a0 | |||
| 22ce15c707 | |||
| 00677148e2 | |||
| 87fcd0277b | |||
| 7b2caf4c01 | |||
| 761a2f0bc2 | |||
| f236a8086a | |||
| 44df38e555 | |||
| 9aaa1e9426 | |||
| bb276101d2 | |||
| 67dc07435d | |||
| 9684ffd37f | |||
| eba4d6dd56 | |||
| d5e3aa7a44 | |||
| c372a02357 | |||
| 07f1eb2148 | |||
| 4b6a0a3b74 | |||
| 42fb4aa82a | |||
| c4cfd3fc74 | |||
| 004283fc0a | |||
| 063a13b1c9 | |||
| 1fc282f796 | |||
| c8b22d13a2 | |||
| f2f3bdf784 | |||
| 980ae15249 | |||
| a8564035d3 | |||
| 1a52fdce6f | |||
| 29fd0e494c | |||
| 8b1e5abf68 | |||
| 04557f610d | |||
| bb68cb6602 | |||
| e51bc28b05 | |||
| 0382978af0 | |||
| a6c38d3e96 |
@@ -2,7 +2,12 @@
|
|||||||
|
|
||||||
`distributor` validates manifested report bundles and publishes selected source or generated artifacts to configured destinations.
|
`distributor` validates manifested report bundles and publishes selected source or generated artifacts to configured destinations.
|
||||||
|
|
||||||
It is a local-first CLI with SSH/SFTP and S3-compatible storage support: source bundles can be read from local or remote storage, destinations can be local directories or remote paths, and Markdown files can be rendered to HTML sidecars.
|
It is a local-first CLI with SSH/SFTP, S3-compatible storage, and HTTP upload
|
||||||
|
support: source bundles can be read from local or remote storage, pushed to the
|
||||||
|
upload API, published to local directories or remote paths, and rendered from
|
||||||
|
Markdown to HTML sidecars or `index.html`.
|
||||||
|
|
||||||
|
Go producers can use `gitea.maximumdirect.net/eric/distributor/pkg/bundle` to build, write, parse, and validate complete local source bundles with the same manifest contract used by `distributor`.
|
||||||
|
|
||||||
Run the local example pipeline:
|
Run the local example pipeline:
|
||||||
|
|
||||||
@@ -10,4 +15,4 @@ Run the local example pipeline:
|
|||||||
go run ./cmd/distributor run --config examples/local-publish.yml
|
go run ./cmd/distributor run --config examples/local-publish.yml
|
||||||
```
|
```
|
||||||
|
|
||||||
See [docs/cli.md](docs/cli.md), [docs/config.md](docs/config.md), [docs/operations.md](docs/operations.md), and [docs/troubleshooting.md](docs/troubleshooting.md) for the implemented CLI, configuration, operating notes, and common failure modes. Planning material lives under `docs/roadmap/`.
|
See [docs/cli.md](docs/cli.md), [docs/config.md](docs/config.md), [docs/operations.md](docs/operations.md), and [docs/troubleshooting.md](docs/troubleshooting.md) for the implemented CLI, configuration, operating notes, and common failure modes. Future and deferred work lives under `docs/roadmap/`.
|
||||||
|
|||||||
148
docs/cli.md
148
docs/cli.md
@@ -12,18 +12,24 @@ This discovers the example source bundle and publishes source files to `workspac
|
|||||||
|
|
||||||
```sh
|
```sh
|
||||||
distributor [--help]
|
distributor [--help]
|
||||||
distributor version
|
distributor version [--format text|json]
|
||||||
distributor run [--config <path>] [--dry-run] [--force]
|
distributor run [--config <path>] [--dry-run] [--force] [--format text|json]
|
||||||
distributor validate <path>
|
distributor serve [--config <path>]
|
||||||
distributor inspect <path>
|
distributor validate [--format text|json] <path>
|
||||||
|
distributor validate --config <path> --pipeline <id> [--bundle <path>] [--format text|json]
|
||||||
|
distributor inspect [--format text|json] <path>
|
||||||
|
distributor inspect --config <path> --pipeline <id> [--bundle <path>] [--format text|json]
|
||||||
|
distributor manifest create <bundle-path> --id <bundle-id> [options]
|
||||||
```
|
```
|
||||||
|
|
||||||
- `version`: prints the application name and version. Development builds print `distributor dev`.
|
- `version`: prints the application name and version. Development builds print `distributor dev`.
|
||||||
- `run`: loads a YAML config, discovers source bundles, plans each configured destination, writes selected outputs unless `--dry-run` is set, and prints a final status summary.
|
- `run`: loads a YAML config, discovers source bundles, plans each configured destination, writes selected outputs unless `--dry-run` is set, and prints a final status summary.
|
||||||
- `validate`: validates a local source bundle directory or a local tree containing source bundles.
|
- `serve`: loads a YAML config, resolves HTTP upload bearer tokens, and runs the HTTP upload API.
|
||||||
- `inspect`: validates local source bundles and prints normalized bundle metadata.
|
- `validate`: validates a local source bundle directory, a local source bundle tree, or one configured pipeline source.
|
||||||
|
- `inspect`: validates source bundles and prints normalized bundle metadata for a local path or one configured pipeline source.
|
||||||
|
- `manifest create`: creates `manifest.json` for a local source bundle directory.
|
||||||
|
|
||||||
`validate` and `inspect` accept local paths only. `run` executes `local`, `ssh`, and `s3` backends.
|
`validate` and `inspect` have two mutually exclusive modes: a local path shortcut, or configured source mode with `--config <path> --pipeline <id>`. Configured source mode opens only the selected pipeline source and supports configured `local`, `ssh`, and `s3` sources. It does not open destinations. `run` executes configured `local`, `ssh`, and `s3` sources and destinations. `serve` executes configured `http_upload` sources through the upload API and normal destination fan-out.
|
||||||
|
|
||||||
## Flag reference
|
## Flag reference
|
||||||
|
|
||||||
@@ -35,13 +41,34 @@ All subcommands:
|
|||||||
|
|
||||||
- `--help`, `-h`: print command-specific help.
|
- `--help`, `-h`: print command-specific help.
|
||||||
|
|
||||||
|
Output-producing subcommands:
|
||||||
|
|
||||||
|
- `--format text|json`: output format. `text` is the default. Help and usage output are always text.
|
||||||
|
|
||||||
`run` flags:
|
`run` flags:
|
||||||
|
|
||||||
- `--config <path>`: config file to load. If omitted, `run` uses `/usr/local/etc/distributor/config.yml`.
|
- `--config <path>`: config file to load. If omitted, `run` uses `/usr/local/etc/distributor/config.yml`.
|
||||||
- `--dry-run`: load config, discover bundles, inspect destination state, print planned actions and final status, and do not write output files, destination state, or SSH `known_hosts` entries.
|
- `--dry-run`: load config, discover bundles, inspect destination state, print planned actions and final status, and do not write output files, destination state, or SSH `known_hosts` entries.
|
||||||
- `--force`: allow explicit destructive replacement for supported conflict cases in this run only.
|
- `--force`: allow explicit destructive replacement for supported conflict cases in this run only.
|
||||||
|
|
||||||
`run` does not accept positional arguments. `validate` and `inspect` accept at most one path; omitting the path returns a required-path error.
|
`serve` flags:
|
||||||
|
|
||||||
|
- `--config <path>`: config file to load. If omitted, `serve` uses `/usr/local/etc/distributor/config.yml`.
|
||||||
|
|
||||||
|
`validate` and `inspect` configured source flags:
|
||||||
|
|
||||||
|
- `--config <path>`: config file to load for source validation or inspection. Required in configured source mode.
|
||||||
|
- `--pipeline <id>`: pipeline source to validate or inspect. Required in configured source mode.
|
||||||
|
- `--bundle <path>`: source-root-relative bundle directory to validate or inspect instead of discovering every bundle under the source root.
|
||||||
|
|
||||||
|
`manifest create` flags:
|
||||||
|
|
||||||
|
- `--id <bundle-id>`: source bundle id. Required.
|
||||||
|
- `--file <path>`: bundle-relative file to include. Repeatable. If omitted, files are scanned recursively.
|
||||||
|
- `--created <time>`: RFC3339 source created timestamp. If omitted, the current UTC time is used.
|
||||||
|
- `--overwrite`: replace an existing `manifest.json`.
|
||||||
|
|
||||||
|
`run` does not accept positional arguments. `validate` and `inspect` accept at most one path in local mode. Local paths cannot be combined with `--config`, `--pipeline`, or `--bundle`.
|
||||||
|
|
||||||
## Common workflows
|
## Common workflows
|
||||||
|
|
||||||
@@ -57,6 +84,37 @@ Inspect a source bundle:
|
|||||||
go run ./cmd/distributor inspect examples/source-bundle
|
go run ./cmd/distributor inspect examples/source-bundle
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Validate a configured source without opening destinations:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/distributor validate --config examples/local-publish.yml --pipeline example-source-bundle
|
||||||
|
```
|
||||||
|
|
||||||
|
Inspect one configured source bundle:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/distributor inspect \
|
||||||
|
--config <config-path> \
|
||||||
|
--pipeline <pipeline-id> \
|
||||||
|
--bundle daily/2026-06-01
|
||||||
|
```
|
||||||
|
|
||||||
|
Create a manifest for a local producer bundle:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/distributor manifest create <bundle-path> --id <bundle-id>
|
||||||
|
```
|
||||||
|
|
||||||
|
Create a manifest with explicit file order:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/distributor manifest create <bundle-path> \
|
||||||
|
--id <bundle-id> \
|
||||||
|
--created 2026-06-01T11:00:00Z \
|
||||||
|
--file report.md \
|
||||||
|
--file summary.txt
|
||||||
|
```
|
||||||
|
|
||||||
Preview local publication without writing:
|
Preview local publication without writing:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
@@ -75,12 +133,52 @@ Publish the local HTML example:
|
|||||||
go run ./cmd/distributor run --config examples/local-html.yml
|
go run ./cmd/distributor run --config examples/local-html.yml
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Start the HTTP upload API:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
DISTRIBUTOR_EXAMPLE_UPLOAD_TOKEN=<token> \
|
||||||
|
go run ./cmd/distributor serve --config examples/http-upload-local.yml
|
||||||
|
```
|
||||||
|
|
||||||
|
Upload an archive to the configured `http_upload` pipeline associated with a bearer token:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -X POST http://127.0.0.1:8080/upload \
|
||||||
|
-H "Authorization: Bearer $DISTRIBUTOR_EXAMPLE_UPLOAD_TOKEN" \
|
||||||
|
-H "Content-Type: application/gzip" \
|
||||||
|
--data-binary @bundle.tar.gz
|
||||||
|
```
|
||||||
|
|
||||||
|
The upload response is accepted asynchronously:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"run_id":"reports.20260603T120000Z.abcdef12","status":"accepted"}
|
||||||
|
```
|
||||||
|
|
||||||
|
Check upload status:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl http://127.0.0.1:8080/runs/<run-id>
|
||||||
|
```
|
||||||
|
|
||||||
|
Check server readiness:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl http://127.0.0.1:8080/healthz
|
||||||
|
```
|
||||||
|
|
||||||
Preview local fan-out publication:
|
Preview local fan-out publication:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
go run ./cmd/distributor run --config examples/fan-out.yml --dry-run
|
go run ./cmd/distributor run --config examples/fan-out.yml --dry-run
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Preview local archive-plus-latest publication:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/distributor run --config examples/archive-and-latest.yml --dry-run
|
||||||
|
```
|
||||||
|
|
||||||
Preview a forced replacement before publishing:
|
Preview a forced replacement before publishing:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
@@ -89,7 +187,9 @@ go run ./cmd/distributor run --config <config-path> --dry-run --force
|
|||||||
|
|
||||||
## Output
|
## Output
|
||||||
|
|
||||||
`run` prints the number of configured pipelines, one line per pipeline, one line per planned destination action, and a final status line. Destination action lines include the bundle path, destination id, destination backend, action, outputs, and reason. Actions include:
|
Text output is the default and is intended for humans.
|
||||||
|
|
||||||
|
`run` text output prints the number of configured pipelines, one line per pipeline, one line per planned destination action, and a final status line. Destination action lines include the source bundle path, destination id, destination backend, action, outputs, and reason. Fixed path destinations also print `path_mapping=fixed target=.` to show that the selected bundle targets the destination backend root. Actions include:
|
||||||
|
|
||||||
- `publish_new`: destination has no managed state and is empty.
|
- `publish_new`: destination has no managed state and is empty.
|
||||||
- `replace_older`: destination state is older than the source manifest.
|
- `replace_older`: destination state is older than the source manifest.
|
||||||
@@ -100,10 +200,36 @@ go run ./cmd/distributor run --config <config-path> --dry-run --force
|
|||||||
|
|
||||||
The command exits non-zero if any destination fails. Independent later destinations are still attempted.
|
The command exits non-zero if any destination fails. Independent later destinations are still attempted.
|
||||||
|
|
||||||
The final status line includes counters for `publish_new`, `replace_older`, `force_replace`, skipped destinations, failures, and whether the run was a dry run.
|
Dry-run output for fixed path destinations prints a warning with the candidate count and selected source bundle. If a fixed path dry run plans a destructive replacement, it prints an additional warning that the destination root would be replaced.
|
||||||
|
|
||||||
|
The final status line includes counters for `publish_new`, `replace_older`, `force_replace`, skipped destinations, failures, whether the run was a dry run, and fixed path destinations.
|
||||||
|
|
||||||
|
JSON output writes exactly one JSON document to stdout:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"schema_version": 1,
|
||||||
|
"command": "inspect",
|
||||||
|
"ok": true,
|
||||||
|
"warnings": [],
|
||||||
|
"result": {}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Warnings are objects in the top-level `warnings` array and are not printed again as text. Fatal setup errors, such as a missing config file or invalid arguments, write no JSON document and return a non-zero exit code with a text error on stderr.
|
||||||
|
|
||||||
|
`run --format json` returns partial results when destination failures occur after planning or execution begins. In that case stdout contains `ok: false`, a `result` with pipeline summaries, destination actions, final counters, and a top-level `errors` array; the process still exits non-zero.
|
||||||
|
|
||||||
|
Command-specific JSON results:
|
||||||
|
|
||||||
|
- `version`: application name and version.
|
||||||
|
- `validate`: bundle count and discovered bundle identifiers. Configured source results also include pipeline id and source backend.
|
||||||
|
- `inspect`: bundle path, id, created timestamp, digest, file count, total size, and manifest file records. Configured source results also include pipeline id and source backend.
|
||||||
|
- `manifest create`: manifest path, bundle root, id, created timestamp, digest, file count, and file records.
|
||||||
|
- `run`: dry-run status, pipeline summaries, destination action records, destination bundle paths, path mapping markers, optional primary URLs, output records with optional URLs, final counters, warnings, and partial failure records.
|
||||||
|
|
||||||
## Diagnostics
|
## Diagnostics
|
||||||
|
|
||||||
Use `validate` before publication when a producer has written a new bundle. Use `inspect` to confirm normalized ids, timestamps, digests, file paths, and file sizes.
|
Use `manifest create` when a local producer has written bundle files but not `manifest.json`. Use `validate` before publication when a producer has written a new bundle; use configured source mode when the bundle is already on an SSH or S3 source. Use `inspect` to confirm normalized ids, timestamps, digests, file paths, and file sizes.
|
||||||
|
|
||||||
For symptom-oriented recovery steps, see [troubleshooting](troubleshooting.md). For destination state and retry behavior, see [operations](operations.md). For config fields and defaults, see [configuration](config.md).
|
For symptom-oriented recovery steps, see [troubleshooting](troubleshooting.md). For destination state and retry behavior, see [operations](operations.md). For config fields and defaults, see [configuration](config.md).
|
||||||
|
|||||||
222
docs/config.md
222
docs/config.md
@@ -2,15 +2,18 @@
|
|||||||
|
|
||||||
## Config File Location
|
## Config File Location
|
||||||
|
|
||||||
`distributor run --config <path>` loads the YAML config at the provided path.
|
`distributor run --config <path>` and `distributor serve --config <path>` load
|
||||||
|
the YAML config at the provided path.
|
||||||
|
|
||||||
If `--config` is omitted, `run` uses:
|
If `--config` is omitted, both commands use:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
/usr/local/etc/distributor/config.yml
|
/usr/local/etc/distributor/config.yml
|
||||||
```
|
```
|
||||||
|
|
||||||
Config parsing rejects unknown YAML fields. The executable backends are `local`, `ssh`, and `s3`.
|
Config parsing rejects unknown YAML fields. The executable `run` backends are
|
||||||
|
`local`, `ssh`, and `s3`. The `serve` command executes `http_upload` sources
|
||||||
|
through the HTTP upload API and normal destination fan-out.
|
||||||
|
|
||||||
## Minimal Local Config
|
## Minimal Local Config
|
||||||
|
|
||||||
@@ -31,6 +34,14 @@ This publishes source files only. It uses the default validation and transfer po
|
|||||||
## Production-Oriented Local Config
|
## Production-Oriented Local Config
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
|
server:
|
||||||
|
http:
|
||||||
|
bind: 127.0.0.1:8080
|
||||||
|
staging_root: /var/spool/distributor
|
||||||
|
max_upload_size: 20MB
|
||||||
|
queue_size: 16
|
||||||
|
max_concurrency: 1
|
||||||
|
retention: 24h
|
||||||
pipelines:
|
pipelines:
|
||||||
- id: reports
|
- id: reports
|
||||||
source:
|
source:
|
||||||
@@ -52,9 +63,87 @@ pipelines:
|
|||||||
on_conflict: fail
|
on_conflict: fail
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## HTTP Upload Source Configuration
|
||||||
|
|
||||||
|
HTTP upload sources are configured as pipeline sources only. They are not valid
|
||||||
|
destination backends. `distributor serve` maps each configured upload token to
|
||||||
|
exactly one `http_upload` pipeline.
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
server:
|
||||||
|
http:
|
||||||
|
bind: 127.0.0.1:8080
|
||||||
|
staging_root: /var/spool/distributor
|
||||||
|
max_upload_size: 20MB
|
||||||
|
queue_size: 16
|
||||||
|
max_concurrency: 1
|
||||||
|
retention: 24h
|
||||||
|
pipelines:
|
||||||
|
- id: weather-daily
|
||||||
|
source:
|
||||||
|
backend: http_upload
|
||||||
|
token_env: WEATHER_DAILY_UPLOAD_TOKEN
|
||||||
|
staging_path: /var/spool/distributor/weather-daily
|
||||||
|
max_upload_size: 20MB
|
||||||
|
destinations:
|
||||||
|
- id: archive
|
||||||
|
backend: local
|
||||||
|
path: /srv/reports/archive
|
||||||
|
```
|
||||||
|
|
||||||
|
`source.token_env` is required and names the environment variable or `secrets.directory` file that provides the bearer token. Literal upload tokens are not supported in YAML.
|
||||||
|
|
||||||
|
`source.staging_path` is optional. When omitted, it defaults to `<server.http.staging_root>/<pipeline id>`.
|
||||||
|
|
||||||
|
`source.max_upload_size` is optional. When omitted, it defaults to `server.http.max_upload_size`.
|
||||||
|
|
||||||
|
The server resolves each `token_env` through the real process environment and
|
||||||
|
the configured `secrets.directory` resolver. Startup fails if any configured
|
||||||
|
upload token is missing, empty, or resolves to the same value as another upload
|
||||||
|
pipeline. Token values are not read from YAML and are not printed in API
|
||||||
|
responses.
|
||||||
|
|
||||||
|
## HTTP Upload API
|
||||||
|
|
||||||
|
`distributor serve` binds to `server.http.bind`, which defaults to
|
||||||
|
`127.0.0.1:8080`.
|
||||||
|
|
||||||
|
Routes:
|
||||||
|
|
||||||
|
- `GET /healthz`: returns readiness status after config and upload tokens load.
|
||||||
|
- `POST /upload`: accepts one tar or tar.gz source bundle archive.
|
||||||
|
- `GET /runs/<run_id>`: returns an in-memory upload status record, or `404` if the run id is unknown or expired.
|
||||||
|
|
||||||
|
`POST /upload` authenticates with:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Authorization: Bearer <token>
|
||||||
|
```
|
||||||
|
|
||||||
|
The token selects the configured `http_upload` pipeline. Producers do not send a
|
||||||
|
pipeline id. Requests with a submitted `pipeline` or `pipeline_id` query value
|
||||||
|
are rejected.
|
||||||
|
|
||||||
|
Accepted upload content types:
|
||||||
|
|
||||||
|
- `application/x-tar`
|
||||||
|
- `application/gzip`
|
||||||
|
- `application/x-gzip`
|
||||||
|
|
||||||
|
Accepted uploads return:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"run_id":"<id>","status":"accepted"}
|
||||||
|
```
|
||||||
|
|
||||||
|
The run id can be queried through `GET /runs/<run_id>` while the status record
|
||||||
|
is retained in memory. Completed records expire after `server.http.retention`;
|
||||||
|
expiration also removes committed staged bundle directories for completed
|
||||||
|
uploads.
|
||||||
|
|
||||||
## HTML Publication
|
## HTML Publication
|
||||||
|
|
||||||
To publish generated HTML from Markdown files:
|
To publish generated sidecar HTML from Markdown files:
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
publish:
|
publish:
|
||||||
@@ -68,10 +157,87 @@ transform:
|
|||||||
|
|
||||||
Sidecar generation writes `report.html` for `report.md`. It does not mutate the source bundle.
|
Sidecar generation writes `report.html` for `report.md`. It does not mutate the source bundle.
|
||||||
|
|
||||||
|
To publish a single Markdown file as `index.html`:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
publish:
|
||||||
|
source: false
|
||||||
|
html: true
|
||||||
|
transform:
|
||||||
|
markdown_to_html:
|
||||||
|
enabled: true
|
||||||
|
mode: index
|
||||||
|
input: report.md
|
||||||
|
```
|
||||||
|
|
||||||
|
When `mode: index` omits `input`, the source manifest must list exactly one Markdown file.
|
||||||
|
|
||||||
|
## Destination Path Mapping
|
||||||
|
|
||||||
|
Each destination chooses how source bundle paths map into that destination:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
path_mapping:
|
||||||
|
mode: preserve_relative
|
||||||
|
```
|
||||||
|
|
||||||
|
`preserve_relative` is the default. It publishes each discovered source bundle at the same path relative to the destination backend root. A source bundle at `daily/2026-06-01` publishes below `daily/2026-06-01` for that destination.
|
||||||
|
|
||||||
|
`fixed` publishes one selected source bundle directly at the destination backend root:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
destinations:
|
||||||
|
- id: latest-html
|
||||||
|
backend: local
|
||||||
|
path: /srv/www/reports/latest
|
||||||
|
path_mapping:
|
||||||
|
mode: fixed
|
||||||
|
publish:
|
||||||
|
source: false
|
||||||
|
html: true
|
||||||
|
transform:
|
||||||
|
markdown_to_html:
|
||||||
|
enabled: true
|
||||||
|
mode: index
|
||||||
|
input: report.md
|
||||||
|
```
|
||||||
|
|
||||||
|
Fixed destinations select the newest discovered source bundle by manifest `created` timestamp. If multiple candidates have the same timestamp, the source-root-relative bundle path in ascending order wins. Older candidates are not planned or written for that destination.
|
||||||
|
|
||||||
|
Fixed mapping is useful for stable latest-style paths. It is more destructive than archive-style publication because successive source bundles target the same destination root. Preview fixed destinations with `run --dry-run`, especially before using `--force`.
|
||||||
|
|
||||||
|
## Destination Links
|
||||||
|
|
||||||
|
Destinations can record public URLs for published outputs:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
links:
|
||||||
|
base_url: https://reports.example.com/archive
|
||||||
|
primary: auto
|
||||||
|
```
|
||||||
|
|
||||||
|
`links.base_url` is an absolute `http` or `https` URL corresponding to the destination backend root. It may include a path prefix, but it must not include a query string or fragment. Distributor does not infer public URLs from backend config.
|
||||||
|
|
||||||
|
`links.primary` selects the top-level primary URL stored in destination state:
|
||||||
|
|
||||||
|
- `auto`: prefer `index.html`, then generated HTML, then source outputs.
|
||||||
|
- `html`: use the first generated HTML output.
|
||||||
|
- `source`: use the first copied source output.
|
||||||
|
|
||||||
|
If a destination has no `links` block, no URL metadata is generated. If a primary policy has no matching output, per-output URLs are still recorded and the top-level primary URL is omitted.
|
||||||
|
|
||||||
|
Output URLs are built from `links.base_url`, the destination bundle path, and the output path using URL path semantics. `index.html` outputs produce directory-style URLs that omit the filename.
|
||||||
|
|
||||||
## Reference
|
## Reference
|
||||||
|
|
||||||
Top level:
|
Top level:
|
||||||
|
|
||||||
|
- `server.http.bind`: optional HTTP bind address; defaults to `127.0.0.1:8080`.
|
||||||
|
- `server.http.staging_root`: optional root for default HTTP upload staging paths; defaults to `/var/spool/distributor`.
|
||||||
|
- `server.http.max_upload_size`: optional default upload size limit; defaults to `20MB`.
|
||||||
|
- `server.http.queue_size`: optional HTTP upload admission queue size; defaults to `16`.
|
||||||
|
- `server.http.max_concurrency`: optional HTTP upload worker concurrency; defaults to `1`.
|
||||||
|
- `server.http.retention`: optional completed upload retention duration; defaults to `24h`.
|
||||||
- `secrets.directory`: optional credential secrets directory.
|
- `secrets.directory`: optional credential secrets directory.
|
||||||
- `pipelines`: required non-empty list.
|
- `pipelines`: required non-empty list.
|
||||||
|
|
||||||
@@ -99,6 +265,9 @@ Source backend:
|
|||||||
- `force_path_style`: optional for `s3`; defaults to `true`. Set `false` only for services that require virtual-host addressing.
|
- `force_path_style`: optional for `s3`; defaults to `true`. Set `false` only for services that require virtual-host addressing.
|
||||||
- `credentials.access_key_id_env`: optional S3 credential environment variable name.
|
- `credentials.access_key_id_env`: optional S3 credential environment variable name.
|
||||||
- `credentials.secret_access_key_env`: optional S3 credential environment variable name.
|
- `credentials.secret_access_key_env`: optional S3 credential environment variable name.
|
||||||
|
- `token_env`: required for `http_upload`; names the token environment variable or secret-file name.
|
||||||
|
- `staging_path`: optional for `http_upload`; defaults below `server.http.staging_root` using the pipeline id.
|
||||||
|
- `max_upload_size`: optional for `http_upload`; defaults to `server.http.max_upload_size`.
|
||||||
|
|
||||||
Destination:
|
Destination:
|
||||||
|
|
||||||
@@ -106,6 +275,9 @@ Destination:
|
|||||||
- Backend fields: same accepted shape as source backends, with destination fields at the destination level.
|
- Backend fields: same accepted shape as source backends, with destination fields at the destination level.
|
||||||
- `publish`: optional; defaults to source-only publication.
|
- `publish`: optional; defaults to source-only publication.
|
||||||
- `transform`: required only for generated HTML publication.
|
- `transform`: required only for generated HTML publication.
|
||||||
|
- `path_mapping.mode`: optional; defaults to `preserve_relative`. Accepted values are `preserve_relative` and `fixed`.
|
||||||
|
- `links.base_url`: optional links block; when present, `base_url` is required and must be an absolute HTTP or HTTPS URL without query string or fragment.
|
||||||
|
- `links.primary`: optional; defaults to `auto`. Accepted values are `auto`, `html`, and `source`.
|
||||||
- `transfer`: optional; defaults described below.
|
- `transfer`: optional; defaults described below.
|
||||||
|
|
||||||
Accepted backend names:
|
Accepted backend names:
|
||||||
@@ -113,6 +285,20 @@ Accepted backend names:
|
|||||||
- `local`: executable; requires `path`.
|
- `local`: executable; requires `path`.
|
||||||
- `ssh`: executable; requires `host` and `path`.
|
- `ssh`: executable; requires `host` and `path`.
|
||||||
- `s3`: executable; requires `endpoint` and `bucket`.
|
- `s3`: executable; requires `endpoint` and `bucket`.
|
||||||
|
- `http_upload`: source-only configuration; requires `token_env`.
|
||||||
|
|
||||||
|
## Size And Duration Values
|
||||||
|
|
||||||
|
Upload size fields use an integer plus one of the supported binary-size suffixes:
|
||||||
|
|
||||||
|
- `B`
|
||||||
|
- `KB`
|
||||||
|
- `MB`
|
||||||
|
- `GB`
|
||||||
|
|
||||||
|
Suffix multipliers use powers of 1024. Size values must be greater than zero after defaults are applied.
|
||||||
|
|
||||||
|
HTTP retention uses Go-style duration strings such as `24h`, `90m`, or `168h`. Retention must be greater than zero after defaults are applied.
|
||||||
|
|
||||||
## SSH Backend
|
## SSH Backend
|
||||||
|
|
||||||
@@ -164,7 +350,15 @@ Publish policy:
|
|||||||
- `publish.source`: publish source artifacts.
|
- `publish.source`: publish source artifacts.
|
||||||
- `publish.html`: publish generated HTML artifacts from Markdown source files.
|
- `publish.html`: publish generated HTML artifacts from Markdown source files.
|
||||||
|
|
||||||
At least one output type must be enabled. When `publish.html` is true, `transform.markdown_to_html.enabled` must be `true` and `transform.markdown_to_html.mode` must be `sidecar`.
|
At least one output type must be enabled. When `publish.html` is true, `transform.markdown_to_html.enabled` must be `true`.
|
||||||
|
|
||||||
|
Markdown-to-HTML transform:
|
||||||
|
|
||||||
|
- `transform.markdown_to_html.enabled`: enables Markdown-to-HTML generation for destinations with `publish.html: true`.
|
||||||
|
- `transform.markdown_to_html.mode`: optional; defaults to `sidecar`. Accepted values are `sidecar` and `index`.
|
||||||
|
- `transform.markdown_to_html.input`: optional source manifest path for `index` mode. It must identify a listed Markdown file.
|
||||||
|
|
||||||
|
`sidecar` mode renders each manifest-listed `.md` file to a same-directory `.html` output. `index` mode renders one selected Markdown file to `index.html` at the destination bundle path. Enabled Markdown-to-HTML config is rejected when `publish.html` is false, and `input` is valid only with `mode: index`.
|
||||||
|
|
||||||
Transfer policy:
|
Transfer policy:
|
||||||
|
|
||||||
@@ -184,8 +378,19 @@ Defaults are applied after YAML decoding and before validation:
|
|||||||
- SSH `host_key_policy: accept-new`
|
- SSH `host_key_policy: accept-new`
|
||||||
- S3 `region: us-east-1`
|
- S3 `region: us-east-1`
|
||||||
- S3 `force_path_style: true`
|
- S3 `force_path_style: true`
|
||||||
|
- `server.http.bind: 127.0.0.1:8080`
|
||||||
|
- `server.http.staging_root: /var/spool/distributor`
|
||||||
|
- `server.http.max_upload_size: 20MB`
|
||||||
|
- `server.http.queue_size: 16`
|
||||||
|
- `server.http.max_concurrency: 1`
|
||||||
|
- `server.http.retention: 24h`
|
||||||
|
- `source.staging_path: /var/spool/distributor/<pipeline id>` for `http_upload`
|
||||||
|
- `source.max_upload_size: server.http.max_upload_size` for `http_upload`
|
||||||
|
- `transform.markdown_to_html.mode: sidecar` when a Markdown-to-HTML transform block is present and mode is omitted
|
||||||
- `publish.source: true`
|
- `publish.source: true`
|
||||||
- `publish.html: false`
|
- `publish.html: false`
|
||||||
|
- `path_mapping.mode: preserve_relative`
|
||||||
|
- `links.primary: auto` when a `links` block is present and `primary` is omitted
|
||||||
- `transfer.on_destination_same: skip`
|
- `transfer.on_destination_same: skip`
|
||||||
- `transfer.on_destination_older: replace`
|
- `transfer.on_destination_older: replace`
|
||||||
- `transfer.on_destination_newer: skip`
|
- `transfer.on_destination_newer: skip`
|
||||||
@@ -209,6 +414,10 @@ S3 credentials may name environment variables:
|
|||||||
- `credentials.access_key_id_env`
|
- `credentials.access_key_id_env`
|
||||||
- `credentials.secret_access_key_env`
|
- `credentials.secret_access_key_env`
|
||||||
|
|
||||||
|
HTTP upload tokens name one environment variable or secret-file name:
|
||||||
|
|
||||||
|
- `source.token_env`
|
||||||
|
|
||||||
## Examples
|
## Examples
|
||||||
|
|
||||||
Maintained examples live under [examples](../examples/):
|
Maintained examples live under [examples](../examples/):
|
||||||
@@ -216,6 +425,9 @@ Maintained examples live under [examples](../examples/):
|
|||||||
- `local-to-local.yml`: minimal local config.
|
- `local-to-local.yml`: minimal local config.
|
||||||
- `local-publish.yml`: runnable local source publication.
|
- `local-publish.yml`: runnable local source publication.
|
||||||
- `local-html.yml`: runnable local HTML publication.
|
- `local-html.yml`: runnable local HTML publication.
|
||||||
|
- `local-index.yml`: runnable local `index.html` publication.
|
||||||
- `fan-out.yml`: runnable local fan-out publication to source and HTML destinations.
|
- `fan-out.yml`: runnable local fan-out publication to source and HTML destinations.
|
||||||
|
- `archive-and-latest.yml`: runnable local fan-out publication to an archive destination and a fixed latest destination.
|
||||||
|
- `http-upload-local.yml`: local HTTP upload server example with a token environment variable reference.
|
||||||
- `ssh-destination.yml`: environment-gated local-to-SSH publication example.
|
- `ssh-destination.yml`: environment-gated local-to-SSH publication example.
|
||||||
- `s3-destination.yml`: environment-gated local-to-S3 publication example.
|
- `s3-destination.yml`: environment-gated local-to-S3 publication example.
|
||||||
|
|||||||
@@ -12,7 +12,12 @@ Rendering uses `github.com/yuin/goldmark`. The exact dependency version is pinne
|
|||||||
|
|
||||||
`internal/transform/markdown.New` constructs the renderer with `goldmark.New()` and no project-specific extensions or renderer options.
|
`internal/transform/markdown.New` constructs the renderer with `goldmark.New()` and no project-specific extensions or renderer options.
|
||||||
|
|
||||||
For each source bundle file ending in `.md`, the transform reads the Markdown source and generates an HTML sidecar in the same logical directory. The output path replaces the `.md` suffix with `.html`, so `report.md` produces `report.html`. Non-Markdown source files produce no Markdown outputs.
|
The transform supports two output modes:
|
||||||
|
|
||||||
|
- `sidecar`: reads each source bundle file ending in `.md` and generates an HTML sidecar in the same logical directory. The output path replaces the `.md` suffix with `.html`, so `report.md` produces `report.html`. Non-Markdown source files produce no Markdown outputs.
|
||||||
|
- `index`: renders one selected Markdown source to `index.html` at the destination bundle path.
|
||||||
|
|
||||||
|
In `index` mode, `transform.markdown_to_html.input` can name the source manifest path to render. If `input` is omitted, the manifest must list exactly one Markdown file. The selected input must be a safe relative source path, must be listed in the source manifest, and must end in `.md`.
|
||||||
|
|
||||||
Raw HTML embedded in Markdown is not passed through by the current renderer behavior. Tests allow Goldmark's disabled-or-escaped raw HTML output forms and reject literal script tags in generated HTML.
|
Raw HTML embedded in Markdown is not passed through by the current renderer behavior. Tests allow Goldmark's disabled-or-escaped raw HTML output forms and reject literal script tags in generated HTML.
|
||||||
|
|
||||||
@@ -42,7 +47,7 @@ Generated outputs record:
|
|||||||
|
|
||||||
Markdown rendering does not mutate source bundles, publish files, write `.distributor.json`, select outputs, or choose transfer actions. Publish planning decides whether generated HTML is selected for a destination.
|
Markdown rendering does not mutate source bundles, publish files, write `.distributor.json`, select outputs, or choose transfer actions. Publish planning decides whether generated HTML is selected for a destination.
|
||||||
|
|
||||||
Only sidecar output mode is supported for current behavior.
|
Publish planning chooses the configured mode and input for each destination. Markdown rendering does not inspect destinations, publish files, write `.distributor.json`, or choose transfer actions.
|
||||||
|
|
||||||
## Tests
|
## Tests
|
||||||
|
|
||||||
@@ -52,4 +57,4 @@ Before changing Markdown renderer behavior, inspect and run:
|
|||||||
go test ./internal/transform/markdown
|
go test ./internal/transform/markdown
|
||||||
```
|
```
|
||||||
|
|
||||||
The tests cover sidecar naming, ignored non-Markdown files, raw HTML handling, deterministic output, digest metadata, and size metadata.
|
The tests cover sidecar naming, index input selection, ignored non-Markdown files, raw HTML handling, deterministic output, digest metadata, and size metadata.
|
||||||
|
|||||||
@@ -2,52 +2,232 @@
|
|||||||
|
|
||||||
## Purpose
|
## Purpose
|
||||||
|
|
||||||
`internal/app` owns top-level use cases for `run`, `validate`, and `inspect`. It wires configuration, storage backends, transforms, publish planning, execution, summaries, and notification handoff.
|
`internal/app` owns the top-level application use cases. It coordinates
|
||||||
|
configuration loading, secret resolution, backend construction, source bundle
|
||||||
|
discovery, destination selection, publish planning, publish execution,
|
||||||
|
notification handoff, run reporting, and in-memory run coordination.
|
||||||
|
|
||||||
## Inputs and outputs
|
The package is the boundary between callers and lower-level domain packages. It
|
||||||
|
does not own manifest validation rules, destination state comparison, storage
|
||||||
|
path rules, output planning, transform rendering, or backend-specific behavior.
|
||||||
|
|
||||||
`Run` accepts a context, optional config path, dry-run flag, force flag, stdout writer, and optional notifier. It loads YAML config, discovers source bundles for each configured pipeline, plans each destination independently, optionally executes publish plans, writes summary output when stdout is supplied, and returns an aggregated error if any destination fails.
|
## Use Cases
|
||||||
|
|
||||||
`Validate` and `Inspect` accept a local path. `Validate` discovers and validates bundles. `Inspect` writes bundle metadata and manifest file entries to stdout when provided.
|
`Run` is the CLI-facing all-pipeline entrypoint. It accepts a context, optional
|
||||||
|
config path, dry-run flag, force flag, stdout writer, output format, and
|
||||||
|
optional notifier. It runs every configured pipeline, builds a `RunReport`, and
|
||||||
|
projects the report to text or JSON when stdout is supplied.
|
||||||
|
|
||||||
## Run flow
|
`RunPipeline` is the app-layer single-pipeline entrypoint. It accepts a context,
|
||||||
|
config path, pipeline ID, dry-run flag, force flag, and optional notifier. It
|
||||||
|
loads the same config as `Run`, narrows execution to exactly one configured
|
||||||
|
pipeline, and returns a `RunReport` without writing command output.
|
||||||
|
|
||||||
The runner:
|
`RunPipelineWithLocalSource` is the app-layer single-pipeline entrypoint for an
|
||||||
|
already prepared local source bundle root. It accepts the same pipeline
|
||||||
|
selection and execution options as `RunPipeline` plus a local source root path.
|
||||||
|
It loads config, selects one configured pipeline, opens the supplied source
|
||||||
|
root as a local backend, validates exactly that root bundle, and then uses the
|
||||||
|
same destination fan-out path as normal runs.
|
||||||
|
|
||||||
|
`Validate` and `Inspect` accept either a local path or one configured pipeline
|
||||||
|
source. They share source backend construction with run workflows and never open
|
||||||
|
destination backends.
|
||||||
|
|
||||||
|
`Serve` is the CLI-facing HTTP upload server entrypoint. It loads config,
|
||||||
|
loads the configured secrets directory, resolves upload bearer tokens for
|
||||||
|
configured `http_upload` sources, creates an `UploadCoordinator`, binds
|
||||||
|
`server.http.bind`, and serves the upload API until its context is cancelled.
|
||||||
|
|
||||||
|
## Run Reports
|
||||||
|
|
||||||
|
`RunReport` is the structured result model for run workflows. It includes
|
||||||
|
dry-run state, pipeline summaries, action records, output metadata, summary
|
||||||
|
counters, warnings, and destination-scoped output errors.
|
||||||
|
|
||||||
|
Text and JSON run output are projections of `RunReport`. JSON tags on report
|
||||||
|
records match the CLI JSON output contract. Text output preserves the CLI
|
||||||
|
summary shape while keeping output rendering outside the core planning and
|
||||||
|
execution loop.
|
||||||
|
|
||||||
|
Destination-scoped failures produce a report plus an aggregated error. Fatal
|
||||||
|
setup failures, such as config loading, source open, or source discovery
|
||||||
|
failures, return before a complete run report is available.
|
||||||
|
|
||||||
|
## Run Flow
|
||||||
|
|
||||||
|
The app runner:
|
||||||
|
|
||||||
1. loads config from the supplied path or `config.DefaultConfigPath`;
|
1. loads config from the supplied path or `config.DefaultConfigPath`;
|
||||||
2. opens the configured source backend;
|
2. loads configured secret files into a config-owned environment resolver;
|
||||||
3. discovers validated bundles from the source root;
|
3. builds the app-level backend factory and transform registry;
|
||||||
4. opens each destination backend independently;
|
4. opens each selected pipeline source backend;
|
||||||
5. builds a publish plan for each bundle and destination;
|
5. discovers validated source bundles from the source root;
|
||||||
6. prints plan lines and records summary counters;
|
6. selects source bundles for each destination according to path mapping;
|
||||||
7. executes publish or replacement plans unless dry-run is enabled;
|
7. opens destination backends independently;
|
||||||
8. invokes the notifier after successful publish or replacement actions.
|
8. builds publish plans for selected bundle and destination combinations;
|
||||||
|
9. records warnings, action records, output metadata, and summary counters;
|
||||||
|
10. executes publish or replacement plans unless dry-run is enabled;
|
||||||
|
11. invokes the notifier after successful publish or replacement actions;
|
||||||
|
12. returns the structured report and any aggregated destination failures.
|
||||||
|
|
||||||
Destination failures are collected while later destinations continue to run. Source open and source discovery failures stop the run because there are no valid bundles to fan out.
|
`RunPipeline` follows the same flow after selecting a single configured
|
||||||
|
pipeline. It uses the same backend factory, secret loading, transform registry,
|
||||||
|
warning generation, destination planning, publish execution, notification
|
||||||
|
behavior, and failure aggregation as `Run`.
|
||||||
|
|
||||||
## Backend and transform wiring
|
`RunPipelineWithLocalSource` follows the same flow after pipeline selection
|
||||||
|
except for source opening and source discovery. It opens the supplied local
|
||||||
|
source root directly, validates the root bundle before opening any destinations,
|
||||||
|
and passes the resulting local source backend and bundle into the same
|
||||||
|
destination planning and execution loop. Destination code receives the normal
|
||||||
|
storage backend and bundle values and does not depend on how the source root was
|
||||||
|
prepared.
|
||||||
|
|
||||||
The app-level backend factory registers local, SSH, and S3 backends for execution. S3 explicit credential references are resolved through the config environment resolver before adapter construction.
|
## Upload Coordination
|
||||||
|
|
||||||
The app-level transform registry registers Markdown-to-HTML using `internal/transform/markdown`. Lower-level publish code receives a resolver and does not import concrete transform implementations.
|
`UploadCoordinator` owns in-memory coordination for asynchronous upload
|
||||||
|
processing. It admits uploads for configured `http_upload` pipelines, generates
|
||||||
|
run IDs, tracks status records, stages accepted archives through
|
||||||
|
`internal/ingest`, and executes the selected pipeline through
|
||||||
|
`RunPipelineWithLocalSource`.
|
||||||
|
|
||||||
## Dry-run behavior
|
Upload run IDs use:
|
||||||
|
|
||||||
Dry-run still loads config, opens backends, discovers bundles, inspects destinations, resolves transforms, and builds publish plans. It does not write destination outputs, write `.distributor.json`, delete managed outputs, perform forced prefix deletion, or notify.
|
```text
|
||||||
|
<pipeline id>.<UTC timestamp>.<random suffix>
|
||||||
|
```
|
||||||
|
|
||||||
## Failure behavior
|
The timestamp uses `YYYYMMDDThhmmssZ` UTC format and the suffix is filesystem
|
||||||
|
safe.
|
||||||
|
|
||||||
`Run` returns immediately for config loading errors, context cancellation before work starts, source open errors, and source discovery errors. Per-destination backend, planning, execution, and notification errors are aggregated into one run error after remaining destinations have been attempted.
|
The coordinator records these statuses:
|
||||||
|
|
||||||
Run diagnostics include pipeline id, destination id, destination backend, and bundle path for destination-scoped failures. Source open and discovery failures include the source backend.
|
- `accepted`
|
||||||
|
- `queued`
|
||||||
|
- `running`
|
||||||
|
- `succeeded`
|
||||||
|
- `failed`
|
||||||
|
- `expired`
|
||||||
|
|
||||||
Stdout write errors are returned immediately because the caller's requested output stream can no longer be trusted.
|
Admission is bounded by `server.http.queue_size`. Full queues are rejected
|
||||||
|
before the upload body is staged. Execution is bounded by
|
||||||
|
`server.http.max_concurrency`, and only one upload for a given pipeline may run
|
||||||
|
at a time. Later uploads for the same pipeline remain queued until the active
|
||||||
|
run finishes.
|
||||||
|
|
||||||
## Boundaries
|
Completed records retain the final run report or error text until
|
||||||
|
`server.http.retention` elapses. Expiration removes completed status records and
|
||||||
|
their committed staged bundle directories. The coordinator is memory-only and
|
||||||
|
does not persist queue state, status records, or run reports.
|
||||||
|
|
||||||
`internal/app` coordinates packages but does not own manifest validation rules, destination state comparison, storage path rules, output planning, transform rendering, or backend-specific filesystem behavior.
|
## HTTP Upload Server
|
||||||
|
|
||||||
`Validate` and `Inspect` are local path commands. Remote execution wiring currently belongs to `Run`.
|
The HTTP upload server is app-layer transport wiring around
|
||||||
|
`UploadCoordinator`. It owns request authentication, route dispatch, HTTP status
|
||||||
|
mapping, and JSON response projection. Bundle staging and publication remain in
|
||||||
|
the coordinator and staged-source run path.
|
||||||
|
|
||||||
|
Server startup resolves every configured `http_upload` source `token_env`
|
||||||
|
through the config-owned environment resolver after `secrets.directory` has
|
||||||
|
been loaded. Startup fails when a token is missing, empty, or duplicates another
|
||||||
|
upload pipeline token. Error messages identify environment variable names and
|
||||||
|
pipeline ids, but not token values.
|
||||||
|
|
||||||
|
Routes:
|
||||||
|
|
||||||
|
- `GET /healthz`: returns `200` after config, secrets, tokens, coordinator, and route setup succeed.
|
||||||
|
- `POST /upload`: accepts authenticated tar and tar.gz archives and returns an accepted run id.
|
||||||
|
- `GET /runs/<run_id>`: returns the current in-memory upload status record or `404`.
|
||||||
|
|
||||||
|
The upload token maps to exactly one configured pipeline. Producers do not
|
||||||
|
submit pipeline ids, and submitted `pipeline` or `pipeline_id` query values are
|
||||||
|
rejected. Full queues are rejected before the request body is read. Oversized
|
||||||
|
uploads, unsupported content types, invalid bearer tokens, full queues, and
|
||||||
|
unknown status records are mapped to stable HTTP status codes without returning
|
||||||
|
secret token values.
|
||||||
|
|
||||||
|
## Coordination
|
||||||
|
|
||||||
|
`PipelineRunCoordinator` wraps `RunPipeline` with in-memory admission control.
|
||||||
|
It allows different pipeline IDs to run concurrently and rejects a second active
|
||||||
|
run for the same pipeline ID.
|
||||||
|
|
||||||
|
Coordinator records contain a run ID, pipeline ID, status, timestamps, completed
|
||||||
|
report, and error text when applicable. Active state is memory-only and is
|
||||||
|
cleared after success, failure, unknown pipeline ID, or context cancellation.
|
||||||
|
|
||||||
|
The admission context is checked before a run is accepted. Once accepted, the
|
||||||
|
run uses the coordinator lifetime context, so caller cancellation can stop
|
||||||
|
waiting for admission without owning the actual run lifetime.
|
||||||
|
|
||||||
|
The coordinator does not queue duplicate runs, persist run records, or define
|
||||||
|
transport endpoints.
|
||||||
|
|
||||||
|
## Errors
|
||||||
|
|
||||||
|
`Run` returns immediately for config loading errors, context cancellation before
|
||||||
|
work starts, source open errors, and source discovery errors.
|
||||||
|
|
||||||
|
`RunPipeline` returns `PipelineNotFoundError` when the requested pipeline ID is
|
||||||
|
not configured. Callers can detect that condition with `IsPipelineNotFound`.
|
||||||
|
|
||||||
|
`RunPipelineWithLocalSource` also returns `PipelineNotFoundError` for an unknown
|
||||||
|
pipeline ID. It returns before destination opening when the supplied local
|
||||||
|
source root is missing, cannot be opened, or does not validate as one complete
|
||||||
|
source bundle.
|
||||||
|
|
||||||
|
Per-destination backend, planning, execution, and notification errors are
|
||||||
|
aggregated into one run error after remaining destinations have been attempted.
|
||||||
|
Destination diagnostics include pipeline ID, destination ID, backend, and
|
||||||
|
bundle path.
|
||||||
|
|
||||||
|
`PipelineRunCoordinator` returns `DuplicatePipelineRunError` when the same
|
||||||
|
pipeline already has an active run. Callers can detect that condition with
|
||||||
|
`IsDuplicatePipelineRun`.
|
||||||
|
|
||||||
|
Stdout write errors are returned immediately because the caller's requested
|
||||||
|
output stream can no longer be trusted.
|
||||||
|
|
||||||
|
## Package Layout
|
||||||
|
|
||||||
|
Run helpers are grouped by responsibility:
|
||||||
|
|
||||||
|
- `run.go`: `Run`, `RunPipeline`, and shared run orchestration.
|
||||||
|
- `run_output.go`: `RunReport`, action/output records, and text/JSON report projection.
|
||||||
|
- `run_summary.go`: summary counters.
|
||||||
|
- `run_failures.go`: destination failure aggregation and partial-result detection.
|
||||||
|
- `run_selection.go`: destination bundle selection, path mapping decisions, and fixed-path warnings.
|
||||||
|
- `run_warnings.go`: secret and SSH warning records.
|
||||||
|
- `run_notify.go`: notification event projection and action filtering.
|
||||||
|
- `run_coordinator.go`: in-memory run admission, run IDs, status records, and duplicate-run errors.
|
||||||
|
- `upload_coordinator.go`: in-memory upload admission, queueing, status tracking, staging handoff, and staged-source execution.
|
||||||
|
- `upload_http.go`: HTTP upload authentication, routes, JSON response projection, and HTTP error mapping.
|
||||||
|
- `serve.go`: config/secrets loading and HTTP server startup.
|
||||||
|
- `backends.go`: app-level backend factory wiring.
|
||||||
|
- `transforms.go`: app-level transform registry wiring.
|
||||||
|
- `source_select.go`: configured-source selection shared by `validate` and `inspect`.
|
||||||
|
|
||||||
|
## Backend And Transform Wiring
|
||||||
|
|
||||||
|
The app-level backend factory registers local, SSH, and S3 backends for runtime
|
||||||
|
execution. Source and destination backend config is converted through a shared
|
||||||
|
app-local open spec before adapter construction.
|
||||||
|
|
||||||
|
Credential references are resolved through the config environment resolver.
|
||||||
|
Production app code must not read backend credential environment variables
|
||||||
|
directly.
|
||||||
|
|
||||||
|
The app-level transform registry registers Markdown-to-HTML through
|
||||||
|
`internal/transform/markdown`. Lower-level publish code receives a resolver and
|
||||||
|
does not import concrete transform implementations.
|
||||||
|
|
||||||
|
## Dry-Run Behavior
|
||||||
|
|
||||||
|
Dry-run loads config, opens backends, discovers bundles, inspects destinations,
|
||||||
|
resolves transforms, and builds publish plans. It does not write destination
|
||||||
|
outputs, write `.distributor.json`, delete managed outputs, perform forced
|
||||||
|
prefix deletion, or invoke notifications.
|
||||||
|
|
||||||
## Tests
|
## Tests
|
||||||
|
|
||||||
@@ -57,10 +237,18 @@ Before changing app orchestration, inspect tests under:
|
|||||||
- `internal/cli`
|
- `internal/cli`
|
||||||
- `internal/publish`
|
- `internal/publish`
|
||||||
|
|
||||||
|
Use focused app tests for report structure, single-pipeline execution,
|
||||||
|
coordinator admission, warning generation, notification behavior, and
|
||||||
|
partial-result aggregation.
|
||||||
|
|
||||||
## Invariants
|
## Invariants
|
||||||
|
|
||||||
- One source fans out to each destination independently.
|
- One source fans out to each destination independently.
|
||||||
- Destination failures do not prevent later destinations from being planned.
|
- Destination failures do not prevent later destinations from being planned.
|
||||||
|
- Destination-scoped failures still produce a structured report plus an aggregated error.
|
||||||
- Dry-run must not mutate destination storage or invoke notifications.
|
- Dry-run must not mutate destination storage or invoke notifications.
|
||||||
|
- `RunPipeline` must use the same run path as `Run` after pipeline selection.
|
||||||
|
- Duplicate in-flight runs are rejected only for the same pipeline ID.
|
||||||
|
- Different pipeline IDs may run concurrently.
|
||||||
- Concrete backend and transform registration stays at the app layer.
|
- Concrete backend and transform registration stays at the app layer.
|
||||||
- The default notifier is `notify.Noop`.
|
- The default notifier is `notify.Noop`.
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
## Purpose
|
## Purpose
|
||||||
|
|
||||||
`internal/bundle` parses, discovers, and validates source bundles through the storage interface.
|
`internal/bundle` discovers and validates source bundles through the storage interface. The source manifest model, manifest parsing, manifest validation, path rules, digest calculation, and producer-side local writer come from `pkg/bundle` so producer-facing APIs and distributor validation share one manifest contract.
|
||||||
|
|
||||||
## Inputs and outputs
|
## Inputs and outputs
|
||||||
|
|
||||||
@@ -20,11 +20,13 @@ The source manifest requires:
|
|||||||
|
|
||||||
Each file requires `path`, `sha256`, and `size`. Digests must use lowercase `sha256:<64 hex>` format. `created` must parse as RFC3339.
|
Each file requires `path`, `sha256`, and `size`. Digests must use lowercase `sha256:<64 hex>` format. `created` must parse as RFC3339.
|
||||||
|
|
||||||
|
`pkg/bundle.ValidateDigest` is the canonical digest format validator for producer-facing and internal code. `internal/bundle.ValidateDigest` delegates to that public validator so source manifests and destination state use the same digest grammar.
|
||||||
|
|
||||||
## Validation
|
## Validation
|
||||||
|
|
||||||
`ValidateManifest` owns normalized source manifest semantics: schema version, id, digest format, timestamp presence, file list presence, source path safety, duplicate file paths, reserved paths, file digest format, non-negative file sizes, and the top-level bundle digest.
|
`pkg/bundle.ValidateManifest` owns normalized source manifest semantics: schema version, id, digest format, timestamp presence, file list presence, source path safety, duplicate file paths, reserved paths, file digest format, non-negative file sizes, and the top-level bundle digest.
|
||||||
|
|
||||||
Storage-backed bundle validation additionally checks file existence, regular-file type, file size, and per-file SHA-256.
|
Storage-backed bundle validation in `internal/bundle` additionally checks file existence, regular-file type, file size, and per-file SHA-256 for configured storage backends.
|
||||||
|
|
||||||
The bundle digest is SHA-256 of a deterministic JSON array of file records in manifest order with fields `path`, `sha256`, and `size`.
|
The bundle digest is SHA-256 of a deterministic JSON array of file records in manifest order with fields `path`, `sha256`, and `size`.
|
||||||
|
|
||||||
@@ -38,11 +40,11 @@ Manifest parsing and validation fail before destination planning. Storage-backed
|
|||||||
|
|
||||||
## Boundaries
|
## Boundaries
|
||||||
|
|
||||||
Bundle code uses `internal/storage` and does not import concrete adapters. CLI local path support is wired in `internal/app`.
|
Internal bundle discovery uses `internal/storage` and does not import concrete adapters. Producer-side local filesystem manifest building, complete bundle writing, and validation belong to `pkg/bundle`. CLI local path support is wired in `internal/app`.
|
||||||
|
|
||||||
## Tests
|
## Tests
|
||||||
|
|
||||||
Before changing bundle behavior, inspect tests under `internal/bundle`.
|
Before changing bundle behavior, inspect tests under `pkg/bundle` and `internal/bundle`.
|
||||||
|
|
||||||
## Invariants
|
## Invariants
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
|
|
||||||
## Inputs and outputs
|
## Inputs and outputs
|
||||||
|
|
||||||
Input is a YAML file containing optional `secrets` and required `pipelines`. Output is a `Config` value with defaults applied and validation completed. Load failures include the config path and whether the failure occurred during file loading, YAML parsing, or validation.
|
Input is a YAML file containing optional `server`, optional `secrets`, and required `pipelines`. Output is a `Config` value with defaults applied and validation completed. Load failures include the config path and whether the failure occurred during file loading, YAML parsing, or validation.
|
||||||
|
|
||||||
## Loading flow
|
## Loading flow
|
||||||
|
|
||||||
@@ -14,16 +14,28 @@ Input is a YAML file containing optional `secrets` and required `pipelines`. Out
|
|||||||
|
|
||||||
Known-field checking rejects misspelled or unknown YAML keys before defaults and validation run.
|
Known-field checking rejects misspelled or unknown YAML keys before defaults and validation run.
|
||||||
|
|
||||||
`LoadFile` does not read secret files. `Run` loads the configured secrets directory after config validation and before backend construction.
|
`LoadFile` does not read secret files. App entrypoints load the configured
|
||||||
|
secrets directory after config validation and before credential-consuming work.
|
||||||
|
|
||||||
## Defaults
|
## Defaults
|
||||||
|
|
||||||
Defaults are applied in `ApplyDefaults`:
|
Defaults are applied in `ApplyDefaults`:
|
||||||
|
|
||||||
|
- HTTP server `bind` defaults to `127.0.0.1:8080`;
|
||||||
|
- HTTP server `staging_root` defaults to `/var/spool/distributor`;
|
||||||
|
- HTTP server `max_upload_size` defaults to `20MB`;
|
||||||
|
- HTTP server `queue_size` defaults to `16`;
|
||||||
|
- HTTP server `max_concurrency` defaults to `1`;
|
||||||
|
- HTTP server `retention` defaults to `24h`;
|
||||||
|
- `http_upload` source `staging_path` defaults to `<server.http.staging_root>/<pipeline id>`;
|
||||||
|
- `http_upload` source `max_upload_size` defaults to `server.http.max_upload_size`;
|
||||||
- pipeline validation defaults `on_digest_mismatch` to `fail`;
|
- pipeline validation defaults `on_digest_mismatch` to `fail`;
|
||||||
- SSH backend `port` defaults to `22`;
|
- SSH backend `port` defaults to `22`;
|
||||||
- SSH backend `host_key_policy` defaults to `accept-new`;
|
- SSH backend `host_key_policy` defaults to `accept-new`;
|
||||||
- destination publish policy defaults to source output only;
|
- destination publish policy defaults to source output only;
|
||||||
|
- Markdown-to-HTML mode defaults to `sidecar` when a transform block is present and mode is omitted;
|
||||||
|
- destination path mapping defaults to `preserve_relative`;
|
||||||
|
- destination link primary policy defaults to `auto` when a `links` block is present;
|
||||||
- `transfer.on_destination_same` defaults to `skip`;
|
- `transfer.on_destination_same` defaults to `skip`;
|
||||||
- `transfer.on_destination_older` defaults to `replace`;
|
- `transfer.on_destination_older` defaults to `replace`;
|
||||||
- `transfer.on_destination_newer` defaults to `skip`;
|
- `transfer.on_destination_newer` defaults to `skip`;
|
||||||
@@ -31,20 +43,30 @@ Defaults are applied in `ApplyDefaults`:
|
|||||||
|
|
||||||
## Validation responsibilities
|
## Validation responsibilities
|
||||||
|
|
||||||
Validation requires at least one pipeline, slug-like unique pipeline ids, one source per pipeline, at least one destination, slug-like unique destination ids within each pipeline, backend-specific required fields, valid validation policy, valid publish and transform combinations, and valid transfer actions.
|
Validation requires positive HTTP server limits and retention, at least one pipeline, slug-like unique pipeline ids, one source per pipeline, at least one destination, slug-like unique destination ids within each pipeline, backend-specific required fields, valid validation policy, valid publish and transform combinations, valid destination path mapping mode, valid destination link config, and valid transfer actions.
|
||||||
|
|
||||||
|
HTTP upload sources require `token_env`, a staging path after defaults, and a positive maximum upload size. Literal token fields are not part of the YAML schema. The `http_upload` backend is accepted only for sources and rejected for destinations.
|
||||||
|
|
||||||
|
Upload size values are parsed from strings with `B`, `KB`, `MB`, or `GB` suffixes using 1024 multipliers. Retention values are parsed with `time.ParseDuration`. Explicit zero values fail validation; omitted values receive defaults before validation.
|
||||||
|
|
||||||
Transfer validation accepts `replace` for `on_destination_newer` and `on_conflict`, but publish planning honors those destructive actions only when the current run explicitly requests force.
|
Transfer validation accepts `replace` for `on_destination_newer` and `on_conflict`, but publish planning honors those destructive actions only when the current run explicitly requests force.
|
||||||
|
|
||||||
`ValidatePublishTransformPolicy` is shared with publish planning so destination policy combinations are checked consistently. Publishing HTML requires an enabled Markdown-to-HTML transform in `sidecar` mode. A publish policy must select source output, HTML output, or both.
|
`ValidatePublishTransformPolicy` is shared with publish planning so destination policy combinations are checked consistently. Publishing HTML requires an enabled Markdown-to-HTML transform in `sidecar` or `index` mode. Enabled Markdown-to-HTML config is rejected when `publish.html` is false. `input` is accepted only for enabled `index` mode. A publish policy must select source output, HTML output, or both.
|
||||||
|
|
||||||
|
Destination path mapping accepts `preserve_relative` and `fixed`. The app layer applies the mapping when it selects destination bundle paths; config owns only YAML shape, defaulting, and validation.
|
||||||
|
|
||||||
|
Destination links are optional. When a `links` block is present, `base_url` is required, must use `http` or `https`, and must not include a query string or fragment. `primary` accepts `auto`, `html`, and `source`.
|
||||||
|
|
||||||
## Executable support boundary
|
## Executable support boundary
|
||||||
|
|
||||||
Config validation accepts `local`, `ssh`, and `s3` backend shapes. Runtime execution opens all three through `internal/app`.
|
Config validation accepts `local`, `ssh`, `s3`, and source-only `http_upload` backend shapes. Runtime `run`, `validate`, and `inspect` workflows open `local`, `ssh`, and `s3` through `internal/app`. Runtime `serve` workflows execute `http_upload` sources through the app upload coordinator and HTTP server.
|
||||||
|
|
||||||
SSH config uses structured fields: `host`, optional `user`, optional `port`, `path`, optional `ssh_key_file`, optional `known_hosts`, and optional `host_key_policy`. `host_key_policy` accepts YAML booleans and strings and normalizes `true`/`strict`, `accept-new`, and `false`/`off`.
|
SSH config uses structured fields: `host`, optional `user`, optional `port`, `path`, optional `ssh_key_file`, optional `known_hosts`, and optional `host_key_policy`. `host_key_policy` accepts YAML booleans and strings and normalizes `true`/`strict`, `accept-new`, and `false`/`off`.
|
||||||
|
|
||||||
S3 config requires `endpoint` and `bucket`, normalizes optional `prefix`, defaults `region` to `us-east-1`, and defaults omitted `force_path_style` to `true` while preserving explicit `false`.
|
S3 config requires `endpoint` and `bucket`, normalizes optional `prefix`, defaults `region` to `us-east-1`, and defaults omitted `force_path_style` to `true` while preserving explicit `false`.
|
||||||
|
|
||||||
|
HTTP upload config is source-only. Config owns its YAML shape, defaulting, size and duration parsing, and validation. The config package does not authenticate requests, stage uploads, or execute HTTP upload sources. The app layer resolves `token_env` through the config-owned environment resolver before starting the HTTP server.
|
||||||
|
|
||||||
## Secrets and credential resolution
|
## Secrets and credential resolution
|
||||||
|
|
||||||
`secrets.directory` points to a directory of credential files. `LoadSecretEnvironment` reads regular files and symlinks to regular files, rejects invalid filenames, trims exactly one trailing LF or CRLF, and returns an `Environment` resolver plus conflict metadata.
|
`secrets.directory` points to a directory of credential files. `LoadSecretEnvironment` reads regular files and symlinks to regular files, rejects invalid filenames, trims exactly one trailing LF or CRLF, and returns an `Environment` resolver plus conflict metadata.
|
||||||
|
|||||||
43
docs/internal/ingest.md
Normal file
43
docs/internal/ingest.md
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
# Ingestion Internals
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
`internal/ingest` stages uploaded source bundle archives into local per-run directories. It does not authenticate requests, manage upload queues, publish destinations, or start an HTTP server.
|
||||||
|
|
||||||
|
## Archive staging
|
||||||
|
|
||||||
|
`StageArchive` accepts one upload body, content type, pipeline staging path, run id, and explicit size and file-count limits. It writes the request body to temporary storage while enforcing the configured upload size limit, extracts the archive into temporary local storage, validates the extracted source bundle, and then commits the validated bundle to:
|
||||||
|
|
||||||
|
```text
|
||||||
|
<pipeline staging path>/<run id>
|
||||||
|
```
|
||||||
|
|
||||||
|
The returned `StagedBundle.Root` is a local filesystem path to the validated source bundle root.
|
||||||
|
|
||||||
|
## Accepted archive formats
|
||||||
|
|
||||||
|
The package accepts only:
|
||||||
|
|
||||||
|
- `application/x-tar`
|
||||||
|
- `application/gzip`
|
||||||
|
- `application/x-gzip`
|
||||||
|
|
||||||
|
Gzip uploads must contain a tar archive.
|
||||||
|
|
||||||
|
## Extraction rules
|
||||||
|
|
||||||
|
Archive entry paths must be clean relative slash-separated paths. Extraction rejects absolute paths, path traversal, backslash paths, duplicate files, symlinks, hardlinks, devices, sockets, and other special entries.
|
||||||
|
|
||||||
|
The archive must contain exactly one root-level `manifest.json`. Nested manifests are rejected.
|
||||||
|
|
||||||
|
Regular files and directories are the only accepted tar entries. Regular file extraction enforces the explicit maximum extracted byte count and maximum file count supplied by the caller.
|
||||||
|
|
||||||
|
## Bundle validation
|
||||||
|
|
||||||
|
After extraction, the package loads and validates the staged bundle through `pkg/bundle`. Manifest parsing, source path validation, file existence checks, regular-file checks, file sizes, file SHA-256 digests, and bundle digest validation use the existing source bundle contract.
|
||||||
|
|
||||||
|
Validation happens before the staged bundle is committed to its final per-run path.
|
||||||
|
|
||||||
|
## Failure behavior
|
||||||
|
|
||||||
|
Failed staging removes temporary archive and extraction data created by the package. A failed call does not publish anything and does not leave a committed per-run bundle directory.
|
||||||
27
docs/internal/link.md
Normal file
27
docs/internal/link.md
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
# Link URL Policy
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
`internal/link` defines shared validation for configured and persisted HTTP link URLs.
|
||||||
|
|
||||||
|
## Inputs and outputs
|
||||||
|
|
||||||
|
Input is a URL string. Output is either nil for an accepted URL or a concise validation error that callers wrap with field context.
|
||||||
|
|
||||||
|
## Validation behavior
|
||||||
|
|
||||||
|
Accepted URLs must parse successfully, use `http` or `https`, include a host, and omit query strings and fragments.
|
||||||
|
|
||||||
|
## Boundaries
|
||||||
|
|
||||||
|
This package validates URL shape only. It does not construct destination output URLs, choose primary URLs, infer public URLs from backend configuration, or read configuration files.
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
Before changing link URL policy, inspect tests under `internal/link` and callers in `internal/config`, `internal/state`, and `internal/publish`.
|
||||||
|
|
||||||
|
## Invariants
|
||||||
|
|
||||||
|
- Configured `links.base_url`, persisted `links.primary_url`, persisted output `url`, and publish link planning use the same URL policy.
|
||||||
|
- Callers own field-specific error context.
|
||||||
|
- URL path construction remains in `internal/publish`.
|
||||||
@@ -6,9 +6,9 @@
|
|||||||
|
|
||||||
## Inputs and outputs
|
## Inputs and outputs
|
||||||
|
|
||||||
Inputs are a source bundle, source backend, destination backend, pipeline id, destination id, publish policy, transform policy, transformer resolver, transfer policy, destination bundle path, existing destination state, and whether explicit force was requested for the current run.
|
Inputs are a source bundle, source backend, destination backend, pipeline id, destination id, publish policy, transform policy, optional link policy, transformer resolver, transfer policy, path mapping mode, destination bundle path, existing destination state, and whether explicit force was requested for the current run.
|
||||||
|
|
||||||
Output is a plan with an action, reason, and selected source or generated outputs. Execution writes selected source files, generated files, and `.distributor.json` for publish or replacement actions.
|
Output is a plan with an action, reason, optional primary URL, and selected source or generated outputs. Execution writes selected source files, generated files, and `.distributor.json` for publish or replacement actions.
|
||||||
|
|
||||||
## Actions
|
## Actions
|
||||||
|
|
||||||
@@ -22,9 +22,15 @@ Execution fails if a write, delete, state serialization, or context check fails.
|
|||||||
|
|
||||||
## Boundaries
|
## Boundaries
|
||||||
|
|
||||||
The current implementation publishes source files and Markdown-to-HTML sidecar outputs. Backend behavior is supplied through `internal/storage`; app runtime currently supplies local, SSH, and S3 backends.
|
The package publishes source files and Markdown-to-HTML outputs. Markdown sidecar mode writes same-directory `.html` outputs, and Markdown index mode writes `index.html`. Backend behavior is supplied through `internal/storage`; app runtime supplies local, SSH, and S3 backends.
|
||||||
|
|
||||||
The package uses `internal/state` for destination comparison, `internal/storage` for IO, and the shared `internal/config` publish/transform policy helper for request validation. It resolves transforms through a narrow resolver supplied by the caller; concrete transform registration is owned by the app layer. It does not parse CLI flags or load config files.
|
The package uses `internal/state` for destination comparison, `internal/storage` for IO, and the shared `internal/config` publish/transform policy helper for request validation. It resolves transforms through a narrow resolver supplied by the caller; concrete transform registration is owned by the app layer. It does not parse CLI flags, load config files, or choose which source bundles a destination receives.
|
||||||
|
|
||||||
|
The package owns projection from planned publish outputs to destination state output records and managed destination output paths. App JSON results and notification events keep their own schemas, but may use the publish output projection to avoid field-mapping drift.
|
||||||
|
|
||||||
|
The app layer computes the destination bundle path before planning. `preserve_relative` destinations pass the source-root-relative bundle path. `fixed` destinations pass an empty destination bundle path, which means the destination backend root, and pass only the newest selected source bundle for that destination.
|
||||||
|
|
||||||
|
When link config is present, publish planning builds per-output URLs from `links.base_url`, the destination bundle path, and each output path. `index.html` outputs use directory-style URLs. The primary URL is selected from planned outputs according to the destination primary policy.
|
||||||
|
|
||||||
## Safety
|
## Safety
|
||||||
|
|
||||||
@@ -37,6 +43,8 @@ Before changing publish behavior, inspect tests under `internal/publish` and run
|
|||||||
## Invariants
|
## Invariants
|
||||||
|
|
||||||
- Publish planning is deterministic for the same source, destination state, policies, and transform outputs.
|
- Publish planning is deterministic for the same source, destination state, policies, and transform outputs.
|
||||||
|
- Destination bundle paths are caller-supplied and are interpreted relative to the destination backend root.
|
||||||
|
- URL generation uses URL path semantics and does not infer public URLs from backend configuration.
|
||||||
- Normal replacement deletes only managed paths recorded in existing state plus `.distributor.json`.
|
- Normal replacement deletes only managed paths recorded in existing state plus `.distributor.json`.
|
||||||
- Forced replacement is explicit per run and deletes only within the destination bundle path.
|
- Forced replacement is explicit per run and deletes only within the destination bundle path.
|
||||||
- Publish execution writes destination state after selected outputs are written.
|
- Publish execution writes destination state after selected outputs are written.
|
||||||
|
|||||||
@@ -19,13 +19,15 @@ Input is JSON destination state plus the current source manifest, pipeline id, d
|
|||||||
- `source.manifest`
|
- `source.manifest`
|
||||||
- `outputs`
|
- `outputs`
|
||||||
|
|
||||||
`distributor_version` is optional diagnostic metadata. `published_at` parses as RFC3339 and distributor-written state serializes it as RFC3339 UTC.
|
`distributor_version` is optional diagnostic metadata. `links` is optional URL metadata. `published_at` parses as RFC3339 and distributor-written state serializes it as RFC3339 UTC.
|
||||||
|
|
||||||
The embedded `source.manifest` is validated with the same source manifest rules used by `internal/bundle`.
|
The embedded `source.manifest` is validated with the same source manifest rules used by `internal/bundle`.
|
||||||
|
|
||||||
## Outputs
|
## Outputs
|
||||||
|
|
||||||
Each output records `path`, `kind`, `source_path`, `sha256`, and `size`. Supported output kinds are `source` and `generated`. Generated outputs require `transform`.
|
Each output records `path`, `kind`, `source_path`, `sha256`, and `size`. Supported output kinds are `source` and `generated`. Generated outputs require `transform`. Outputs may record `url` when the destination has link generation configured.
|
||||||
|
|
||||||
|
The optional top-level `links.primary_url` records the selected primary URL for the published destination bundle. It is omitted when link generation is not configured or when the destination primary policy has no matching output.
|
||||||
|
|
||||||
## Comparison
|
## Comparison
|
||||||
|
|
||||||
@@ -33,7 +35,7 @@ Comparison outcomes cover absent destination state, unmanaged destination conten
|
|||||||
|
|
||||||
## Failure behavior
|
## Failure behavior
|
||||||
|
|
||||||
Invalid JSON, invalid state schema, invalid embedded source manifests, unsafe output paths, unsupported output kinds, missing generated-output transform names, and mismatched pipeline or destination ids produce comparison outcomes that publish planning can turn into fail actions. Supported identity and source-manifest conflicts can become forced replacement only when publish planning receives explicit force and compatible transfer policy.
|
Invalid JSON, invalid state schema, invalid embedded source manifests, unsafe output paths, invalid stored URLs, unsupported output kinds, missing generated-output transform names, and mismatched pipeline or destination ids produce comparison outcomes that publish planning can turn into fail actions. Supported identity and source-manifest conflicts can become forced replacement only when publish planning receives explicit force and compatible transfer policy.
|
||||||
|
|
||||||
## Boundaries
|
## Boundaries
|
||||||
|
|
||||||
@@ -48,5 +50,6 @@ Before changing destination state behavior, inspect tests under `internal/state`
|
|||||||
- `.distributor.json` is the destination sentinel and state record.
|
- `.distributor.json` is the destination sentinel and state record.
|
||||||
- Embedded source manifests use the same validation rules as source bundles.
|
- Embedded source manifests use the same validation rules as source bundles.
|
||||||
- Generated outputs always record a transform id.
|
- Generated outputs always record a transform id.
|
||||||
|
- Stored URLs are optional and must be absolute HTTP or HTTPS URLs when present.
|
||||||
- Comparison returns outcomes and reasons; it does not mutate storage.
|
- Comparison returns outcomes and reasons; it does not mutate storage.
|
||||||
- `distributor_version` is diagnostic metadata, not a comparison key.
|
- `distributor_version` is diagnostic metadata, not a comparison key.
|
||||||
|
|||||||
@@ -26,6 +26,19 @@ Storage errors use typed categories such as not found, already exists, invalid p
|
|||||||
|
|
||||||
Backends may wrap implementation-specific errors, but callers should receive storage errors where practical. Traversal can stop cleanly with `ErrStopWalk`.
|
Backends may wrap implementation-specific errors, but callers should receive storage errors where practical. Traversal can stop cleanly with `ErrStopWalk`.
|
||||||
|
|
||||||
|
## Traversal helpers
|
||||||
|
|
||||||
|
Backends own their traversal mechanics. The local adapter owns filesystem walking, the SSH adapter owns SFTP directory walking, and the S3 adapter owns object listing and pagination.
|
||||||
|
|
||||||
|
`internal/storage` owns the shared callback emission rules used by backends:
|
||||||
|
|
||||||
|
- context cancellation is checked before callback emission;
|
||||||
|
- `WalkOptions.Limit` bounds the number of emitted entries;
|
||||||
|
- `ErrStopWalk` stops traversal without becoming a caller-visible error;
|
||||||
|
- callback errors are wrapped as storage walk errors.
|
||||||
|
|
||||||
|
`storage.HasAny(ctx, backend, prefix)` provides the shared destination-content check. It calls `Walk` with non-recursive, limit-one traversal and stops after the first emitted entry.
|
||||||
|
|
||||||
## Deletion
|
## Deletion
|
||||||
|
|
||||||
`DeleteManagedBundle` may delete listed managed outputs plus `.distributor.json`.
|
`DeleteManagedBundle` may delete listed managed outputs plus `.distributor.json`.
|
||||||
|
|||||||
@@ -2,11 +2,11 @@
|
|||||||
|
|
||||||
## Purpose
|
## Purpose
|
||||||
|
|
||||||
`internal/transform` defines generated publication artifacts. `internal/transform/markdown` implements Markdown-to-HTML sidecar generation.
|
`internal/transform` defines generated publication artifacts. `internal/transform/markdown` implements Markdown-to-HTML generation.
|
||||||
|
|
||||||
## Inputs and outputs
|
## Inputs and outputs
|
||||||
|
|
||||||
Inputs are a validated source bundle and source backend. Outputs include destination path, source path, transform id, generated bytes, SHA-256, and size.
|
Inputs are a validated source bundle, source backend, and transform options supplied by publish planning. Outputs include destination path, source path, transform id, generated bytes, SHA-256, and size.
|
||||||
|
|
||||||
## Registry
|
## Registry
|
||||||
|
|
||||||
@@ -14,7 +14,7 @@ Inputs are a validated source bundle and source backend. Outputs include destina
|
|||||||
|
|
||||||
## Markdown behavior
|
## Markdown behavior
|
||||||
|
|
||||||
Markdown files ending in `.md` generate `.html` files in the same logical directory. Non-Markdown files do not generate outputs. Raw HTML embedded in Markdown is not passed through by the renderer.
|
Markdown sidecar mode renders files ending in `.md` to `.html` files in the same logical directory. Markdown index mode renders one selected manifest-listed Markdown file to `index.html`. Non-Markdown files do not generate sidecar outputs. Raw HTML embedded in Markdown is not passed through by the renderer.
|
||||||
|
|
||||||
Generated HTML is deterministic for the same source content and transform configuration.
|
Generated HTML is deterministic for the same source content and transform configuration.
|
||||||
|
|
||||||
@@ -22,7 +22,7 @@ See `docs/integrations/markdown.md` for the Goldmark integration contract.
|
|||||||
|
|
||||||
## Failure behavior
|
## Failure behavior
|
||||||
|
|
||||||
Transform resolution fails when a requested transform id is not registered. Markdown rendering fails when the source file cannot be read or rendered. Publish planning fails when HTML output is requested and the selected transform produces no outputs for a bundle.
|
Transform resolution fails when a requested transform id is not registered. Markdown rendering fails when the source file cannot be read or rendered. Index input selection fails when the configured input is unsafe, not listed, not Markdown, or when no configured input can be inferred from exactly one manifest-listed Markdown file. Publish planning fails when HTML output is requested and the selected transform produces no outputs for a bundle.
|
||||||
|
|
||||||
## Boundaries
|
## Boundaries
|
||||||
|
|
||||||
@@ -42,5 +42,6 @@ Before changing transform behavior, inspect tests under:
|
|||||||
- Source bundle files are never mutated by transforms.
|
- Source bundle files are never mutated by transforms.
|
||||||
- Generated outputs record destination path, source path, transform id, SHA-256, and size.
|
- Generated outputs record destination path, source path, transform id, SHA-256, and size.
|
||||||
- Markdown sidecar naming changes only the `.md` extension to `.html`.
|
- Markdown sidecar naming changes only the `.md` extension to `.html`.
|
||||||
|
- Markdown index mode always writes `index.html`.
|
||||||
- Non-Markdown source files do not generate Markdown outputs.
|
- Non-Markdown source files do not generate Markdown outputs.
|
||||||
- Transform registration stays outside publish planning.
|
- Transform registration stays outside publish planning.
|
||||||
|
|||||||
@@ -26,12 +26,30 @@ Run the local HTML publication:
|
|||||||
go run ./cmd/distributor run --config examples/local-html.yml
|
go run ./cmd/distributor run --config examples/local-html.yml
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Run the local `index.html` publication:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/distributor run --config examples/local-index.yml
|
||||||
|
```
|
||||||
|
|
||||||
Preview local fan-out publication:
|
Preview local fan-out publication:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
go run ./cmd/distributor run --config examples/fan-out.yml --dry-run
|
go run ./cmd/distributor run --config examples/fan-out.yml --dry-run
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Preview local archive-plus-latest publication:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/distributor run --config examples/archive-and-latest.yml --dry-run
|
||||||
|
```
|
||||||
|
|
||||||
|
Preview a run for automation:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/distributor run --config examples/fan-out.yml --dry-run --format json
|
||||||
|
```
|
||||||
|
|
||||||
Preview an environment-gated SSH destination config after editing it for an SSH/SFTP endpoint you control:
|
Preview an environment-gated SSH destination config after editing it for an SSH/SFTP endpoint you control:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
@@ -44,11 +62,99 @@ Preview an environment-gated S3 destination config after editing it for an S3-co
|
|||||||
go run ./cmd/distributor run --config examples/s3-destination.yml --dry-run
|
go run ./cmd/distributor run --config examples/s3-destination.yml --dry-run
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Validate one configured source without opening destinations:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/distributor validate --config examples/local-publish.yml --pipeline example-source-bundle
|
||||||
|
```
|
||||||
|
|
||||||
|
## HTTP Upload Workflow
|
||||||
|
|
||||||
|
`distributor serve` runs the HTTP upload API for pipelines whose source backend
|
||||||
|
is `http_upload`. Each upload token maps to one configured pipeline, and each
|
||||||
|
accepted archive is staged, validated, and published through the same
|
||||||
|
destination fan-out path used by local source runs.
|
||||||
|
|
||||||
|
Minimal local HTTP upload configuration:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
server:
|
||||||
|
http:
|
||||||
|
bind: 127.0.0.1:8080
|
||||||
|
staging_root: /var/spool/distributor
|
||||||
|
max_upload_size: 20MB
|
||||||
|
queue_size: 16
|
||||||
|
max_concurrency: 1
|
||||||
|
retention: 24h
|
||||||
|
secrets:
|
||||||
|
directory: /run/secrets/distributor
|
||||||
|
pipelines:
|
||||||
|
- id: reports
|
||||||
|
source:
|
||||||
|
backend: http_upload
|
||||||
|
token_env: DISTRIBUTOR_EXAMPLE_UPLOAD_TOKEN
|
||||||
|
destinations:
|
||||||
|
- id: archive
|
||||||
|
backend: local
|
||||||
|
path: /srv/reports/archive
|
||||||
|
```
|
||||||
|
|
||||||
|
Create `/run/secrets/distributor/DISTRIBUTOR_EXAMPLE_UPLOAD_TOKEN` or set the
|
||||||
|
real process environment variable before starting the server. Distributor does
|
||||||
|
not read literal upload tokens from YAML.
|
||||||
|
|
||||||
|
Start the maintained local example:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
DISTRIBUTOR_EXAMPLE_UPLOAD_TOKEN=<token> \
|
||||||
|
go run ./cmd/distributor serve --config examples/http-upload-local.yml
|
||||||
|
```
|
||||||
|
|
||||||
|
Submit a tar or tar.gz source bundle:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -X POST http://127.0.0.1:8080/upload \
|
||||||
|
-H "Authorization: Bearer $DISTRIBUTOR_EXAMPLE_UPLOAD_TOKEN" \
|
||||||
|
-H "Content-Type: application/gzip" \
|
||||||
|
--data-binary @bundle.tar.gz
|
||||||
|
```
|
||||||
|
|
||||||
|
Successful admission returns a run id:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"run_id":"reports.20260603T120000Z.abcdef12","status":"accepted"}
|
||||||
|
```
|
||||||
|
|
||||||
|
Poll status until it reaches `succeeded` or `failed`:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl http://127.0.0.1:8080/runs/<run-id>
|
||||||
|
```
|
||||||
|
|
||||||
|
The status record includes the completed run report on successful publication
|
||||||
|
or error details on failure. Status is memory-only and expires after
|
||||||
|
`server.http.retention`; completed staged bundle directories are removed on
|
||||||
|
expiry. Restarting the process clears upload status and queue state.
|
||||||
|
|
||||||
|
Use `GET /healthz` for readiness after config and tokens load:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl http://127.0.0.1:8080/healthz
|
||||||
|
```
|
||||||
|
|
||||||
|
The default bind address is private loopback. Put TLS, public routing,
|
||||||
|
rate-limiting, and external access policy in a reverse proxy or deployment
|
||||||
|
layer.
|
||||||
|
|
||||||
## Filesystem Layout
|
## Filesystem Layout
|
||||||
|
|
||||||
Source bundles are discovered beneath the configured source root. Each bundle is a directory containing `manifest.json`.
|
Source bundles are discovered beneath the configured source root. Each bundle is a directory containing `manifest.json`.
|
||||||
|
|
||||||
Destination bundle paths preserve the source bundle path relative to the source root. A source bundle at the source root publishes to the destination root. A source bundle under `daily/` publishes under `daily/` at each destination.
|
Destination bundle paths are configured per destination with `path_mapping.mode`.
|
||||||
|
|
||||||
|
The default mode, `preserve_relative`, preserves the source bundle path relative to the source root. A source bundle at the source root publishes to the destination root. A source bundle under `daily/` publishes under `daily/` at that destination.
|
||||||
|
|
||||||
|
The `fixed` mode publishes one selected source bundle at the destination backend root. A fixed destination with local `path: /srv/www/reports/latest` writes outputs and `.distributor.json` directly under `/srv/www/reports/latest`. Fixed destinations select the newest discovered source bundle by manifest `created` timestamp, with the source-root-relative bundle path as the deterministic tie-breaker.
|
||||||
|
|
||||||
The maintained local examples write under `workspace/`, which is ignored by Git.
|
The maintained local examples write under `workspace/`, which is ignored by Git.
|
||||||
|
|
||||||
@@ -64,19 +170,173 @@ Each published destination bundle contains `.distributor.json`. This file is the
|
|||||||
- publication timestamp;
|
- publication timestamp;
|
||||||
- source manifest used for publication;
|
- source manifest used for publication;
|
||||||
- copied source output metadata;
|
- copied source output metadata;
|
||||||
- generated output metadata.
|
- generated output metadata;
|
||||||
|
- optional public URL metadata when destination links are configured.
|
||||||
|
|
||||||
`manifest.json` from the source bundle is not copied as destination state.
|
`manifest.json` from the source bundle is not copied as destination state.
|
||||||
|
|
||||||
Do not edit `.distributor.json` by hand during normal operation. If it is missing or invalid while destination files remain, `distributor` treats the destination as unmanaged or conflicted.
|
Do not edit `.distributor.json` by hand during normal operation. If it is missing or invalid while destination files remain, `distributor` treats the destination as unmanaged or conflicted.
|
||||||
|
|
||||||
|
## Go Producer Bundles
|
||||||
|
|
||||||
|
Go producer applications can import `gitea.maximumdirect.net/eric/distributor/pkg/bundle` to create complete local source bundles with the same path, digest, timestamp, and validation rules used by `distributor`. The package also exposes digest helpers, including `ValidateDigest`, for producer code that needs to validate lowercase `sha256:<64 hex>` strings before writing manifests.
|
||||||
|
|
||||||
|
Minimal producer-side bundle creation:
|
||||||
|
|
||||||
|
```go
|
||||||
|
manifest, err := bundle.WriteBundle(bundle.WriteBundleOptions{
|
||||||
|
Root: outputDir,
|
||||||
|
ID: "reports.example.2026-05-30",
|
||||||
|
Files: []bundle.BundleFile{
|
||||||
|
{SourcePath: reportPath, Path: "report.md"},
|
||||||
|
{SourcePath: summaryPath, Path: "summary.txt"},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`WriteBundle` copies local producer files into a sibling temporary directory, writes `manifest.json`, validates the result, and promotes the completed bundle into place. It fails if `Root` already exists unless `Overwrite` is true. With overwrite enabled, it builds and validates the replacement before moving the existing root aside.
|
||||||
|
|
||||||
|
Use `BuildManifest` and `WriteManifest` when a producer already wrote all bundle files into the final root. `BuildManifest` can preserve an explicit file order, or `Scan: true` can recursively include regular files under `Root` in deterministic slash-path order. Scan mode includes dotfiles, excludes files named `manifest.json` or `.distributor.json`, and rejects symlinks.
|
||||||
|
|
||||||
|
Shell producers can create the same manifest through the CLI after writing bundle files:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/distributor manifest create <bundle-path> --id reports.example.2026-05-30
|
||||||
|
go run ./cmd/distributor validate <bundle-path>
|
||||||
|
```
|
||||||
|
|
||||||
|
Use repeated `--file` flags to preserve a specific file order. If no `--file` flags are provided, the command scans the bundle directory recursively using the same filtering rules as `pkg/bundle.BuildManifest`.
|
||||||
|
|
||||||
|
## Static HTML Publication
|
||||||
|
|
||||||
|
Markdown-to-HTML publication can write sidecar files or a fixed `index.html`.
|
||||||
|
|
||||||
|
Use sidecar mode when each Markdown source should keep a matching HTML filename:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
publish:
|
||||||
|
source: false
|
||||||
|
html: true
|
||||||
|
transform:
|
||||||
|
markdown_to_html:
|
||||||
|
enabled: true
|
||||||
|
mode: sidecar
|
||||||
|
```
|
||||||
|
|
||||||
|
Use index mode for static-site destinations that should serve a bundle through `index.html`:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
publish:
|
||||||
|
source: false
|
||||||
|
html: true
|
||||||
|
transform:
|
||||||
|
markdown_to_html:
|
||||||
|
enabled: true
|
||||||
|
mode: index
|
||||||
|
input: report.md
|
||||||
|
```
|
||||||
|
|
||||||
|
If `input` is omitted in index mode, the source manifest must list exactly one Markdown file. Generated HTML is recorded in `.distributor.json` with `kind: generated`, `source_path`, `transform: markdown_to_html`, digest, and size metadata.
|
||||||
|
|
||||||
|
## Archive And Latest Fan-Out
|
||||||
|
|
||||||
|
A pipeline can publish the same source to an archive destination and a stable latest destination:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
pipelines:
|
||||||
|
- id: reports
|
||||||
|
source:
|
||||||
|
backend: local
|
||||||
|
path: /var/spool/distributor/reports
|
||||||
|
destinations:
|
||||||
|
- id: archive
|
||||||
|
backend: local
|
||||||
|
path: /srv/reports/archive
|
||||||
|
path_mapping:
|
||||||
|
mode: preserve_relative
|
||||||
|
publish:
|
||||||
|
source: true
|
||||||
|
html: false
|
||||||
|
- id: latest-html
|
||||||
|
backend: local
|
||||||
|
path: /srv/www/reports/latest
|
||||||
|
path_mapping:
|
||||||
|
mode: fixed
|
||||||
|
links:
|
||||||
|
base_url: https://reports.example.com/latest
|
||||||
|
primary: auto
|
||||||
|
publish:
|
||||||
|
source: false
|
||||||
|
html: true
|
||||||
|
transform:
|
||||||
|
markdown_to_html:
|
||||||
|
enabled: true
|
||||||
|
mode: index
|
||||||
|
input: report.md
|
||||||
|
```
|
||||||
|
|
||||||
|
The archive destination plans every discovered source bundle at its source-relative path. The fixed latest destination plans only the newest discovered bundle and writes `index.html` plus `.distributor.json` at its backend root.
|
||||||
|
|
||||||
|
## Static Site URLs
|
||||||
|
|
||||||
|
Use destination `links` when a destination backend root corresponds to a public HTTP or HTTPS URL:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
links:
|
||||||
|
base_url: https://reports.example.com/archive
|
||||||
|
primary: auto
|
||||||
|
```
|
||||||
|
|
||||||
|
Distributor records URLs in `.distributor.json`; it does not publish notifications or infer URLs from local, SSH, or S3 backend fields.
|
||||||
|
|
||||||
|
For archive-style destinations, URLs include the destination bundle path. A source bundle under `daily/brentwood/2026-06-01` with `base_url: https://reports.example.com/archive` can produce:
|
||||||
|
|
||||||
|
```text
|
||||||
|
https://reports.example.com/archive/daily/brentwood/2026-06-01/report.html
|
||||||
|
```
|
||||||
|
|
||||||
|
For fixed destinations, URLs are rooted at `links.base_url`. A fixed HTML index destination with `base_url: https://reports.example.com/latest` records:
|
||||||
|
|
||||||
|
```text
|
||||||
|
https://reports.example.com/latest/
|
||||||
|
```
|
||||||
|
|
||||||
|
`index.html` outputs use directory-style URLs. Other outputs include their filename. The primary URL is selected from the published outputs using the destination `links.primary` policy.
|
||||||
|
|
||||||
|
## Source Validation and Inspection
|
||||||
|
|
||||||
|
`validate` and `inspect` can operate on a local path or on one configured pipeline source. Configured source mode requires both `--config` and `--pipeline`; it loads the normal config, resolves `secrets.directory`, opens only the selected source backend, and does not open any destinations.
|
||||||
|
|
||||||
|
Configured source validation is useful when producers write directly to SSH or S3 storage:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/distributor validate --config <config-path> --pipeline <pipeline-id>
|
||||||
|
go run ./cmd/distributor inspect --config <config-path> --pipeline <pipeline-id>
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `--bundle <path>` to validate or inspect one source-root-relative bundle directory:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/distributor validate \
|
||||||
|
--config <config-path> \
|
||||||
|
--pipeline <pipeline-id> \
|
||||||
|
--bundle daily/2026-06-01
|
||||||
|
```
|
||||||
|
|
||||||
|
For configured SSH sources, host key and authentication behavior matches `run`. For configured S3 sources, endpoint, bucket, prefix, region, path-style, explicit credential environment variables, and `secrets.directory` handling match `run`.
|
||||||
|
|
||||||
## Dry Runs
|
## Dry Runs
|
||||||
|
|
||||||
`--dry-run` loads and validates config, discovers source bundles, inspects destination state, plans outputs, and prints summary lines. It does not write output files, destination state, or SSH `known_hosts` entries.
|
`--dry-run` loads and validates config, discovers source bundles, inspects destination state, plans outputs, and prints summary lines. It does not write output files, destination state, or SSH `known_hosts` entries.
|
||||||
|
|
||||||
Dry-run output is useful before publishing to confirm actions such as `publish_new`, `replace_older`, `force_replace`, `skip_same`, and `skip_destination_newer`.
|
Dry-run output is useful before publishing to confirm actions such as `publish_new`, `replace_older`, `force_replace`, `skip_same`, and `skip_destination_newer`.
|
||||||
|
|
||||||
Destination action lines include the destination backend, so mixed local, SSH, and S3 fan-out runs can be audited before publication.
|
Destination action lines include the destination backend, so mixed local, SSH, and S3 fan-out runs can be audited before publication. Fixed path destinations add `path_mapping=fixed target=.` to planned action lines. Dry-run also prints a warning with the fixed destination candidate count and selected source bundle; destructive fixed replacements print an additional warning that the destination root would be replaced.
|
||||||
|
|
||||||
|
Use `--format json` when another process needs stable run data. JSON output includes warnings, pipeline summaries, destination actions, destination bundle paths, path mapping modes, optional link URLs, output records, final counters, and partial failure records. The summary includes `fixed_path`. If one destination fails after planning or execution begins, JSON output still contains the successful and failed destination records with `ok: false`, and the command exits non-zero.
|
||||||
|
|
||||||
## Retry and Replacement Behavior
|
## Retry and Replacement Behavior
|
||||||
|
|
||||||
@@ -99,7 +359,7 @@ go run ./cmd/distributor run --config <config-path> --force
|
|||||||
|
|
||||||
Forced replacement can overwrite unmanaged non-empty destination paths. Destination state conflicts require `transfer.on_conflict: replace` plus `--force`. Newer destination state requires `transfer.on_destination_newer: replace` plus `--force`.
|
Forced replacement can overwrite unmanaged non-empty destination paths. Destination state conflicts require `transfer.on_conflict: replace` plus `--force`. Newer destination state requires `transfer.on_destination_newer: replace` plus `--force`.
|
||||||
|
|
||||||
Forced replacement deletes the current destination bundle path before writing outputs and state. It does not delete above that bundle path. For S3 destinations, deletion is constrained to the configured bucket and prefix plus the destination bundle prefix. Force is per run only and has no config default.
|
Forced replacement deletes the current destination bundle path before writing outputs and state. It does not delete above that bundle path. For fixed destinations, the destination bundle path is the backend root, so forced replacement may clear that configured root but not its parent path, sibling directories, or anything outside the configured S3 bucket and prefix. Force is per run only and has no config default.
|
||||||
|
|
||||||
## Failure Handling
|
## Failure Handling
|
||||||
|
|
||||||
@@ -107,6 +367,8 @@ If one destination fails in a fan-out run, independent later destinations are st
|
|||||||
|
|
||||||
Errors include the pipeline id, destination id, destination backend, and bundle path where applicable.
|
Errors include the pipeline id, destination id, destination backend, and bundle path where applicable.
|
||||||
|
|
||||||
|
In JSON mode, destination failures after planning or execution begins are reported in the top-level `errors` array and in the run result while preserving a non-zero exit code. Fatal setup errors such as an unreadable config or invalid secrets directory write no JSON document.
|
||||||
|
|
||||||
If a write fails during publication, `distributor` attempts to remove outputs written during that failed attempt so a retry does not see those partial outputs as unmanaged destination content.
|
If a write fails during publication, `distributor` attempts to remove outputs written during that failed attempt so a retry does not see those partial outputs as unmanaged destination content.
|
||||||
|
|
||||||
After a successful publish or replacement, the internal notifier hook runs. The current default notifier is a no-op. Skipped destinations do not invoke it.
|
After a successful publish or replacement, the internal notifier hook runs. The current default notifier is a no-op. Skipped destinations do not invoke it.
|
||||||
@@ -127,7 +389,7 @@ S3 execution uses the AWS SDK for Go v2. Configure `endpoint`, `bucket`, optiona
|
|||||||
|
|
||||||
When explicit credential env names are configured, both variables must resolve to non-empty values through the real process environment or `secrets.directory`. When they are omitted, the AWS SDK default credential chain is used as-is.
|
When explicit credential env names are configured, both variables must resolve to non-empty values through the real process environment or `secrets.directory`. When they are omitted, the AWS SDK default credential chain is used as-is.
|
||||||
|
|
||||||
Normal replacement and failed-write cleanup delete only managed output objects recorded in `.distributor.json` plus the state object. Forced replacement deletes objects under the bounded destination bundle prefix. Distributor does not manage bucket versioning or delete markers.
|
Normal replacement and failed-write cleanup delete only managed output objects recorded in `.distributor.json` plus the state object. Forced replacement deletes objects under the bounded destination bundle prefix. For fixed destinations, that prefix is the configured bucket plus optional `prefix`. Distributor does not manage bucket versioning or delete markers.
|
||||||
|
|
||||||
## Secrets Directory
|
## Secrets Directory
|
||||||
|
|
||||||
@@ -138,9 +400,12 @@ secrets:
|
|||||||
directory: /run/secrets/distributor
|
directory: /run/secrets/distributor
|
||||||
```
|
```
|
||||||
|
|
||||||
The directory is loaded during `run` before any source or destination backend is opened. If the directory is missing, unreadable, or contains an invalid secret filename, the run fails before publication work starts.
|
The directory is loaded during `run`, `serve`, and configured-source `validate`
|
||||||
|
or `inspect` before credential-consuming work starts. If the directory is
|
||||||
|
missing, unreadable, or contains an invalid secret filename, the command fails
|
||||||
|
before storage work starts.
|
||||||
|
|
||||||
Real process environment values take precedence over files with the same name. If the values differ and stdout is enabled, `run` prints a warning naming the ignored secret file variable without printing either value. The process environment is not changed.
|
Real process environment values take precedence over files with the same name. If the values differ and stdout is enabled, `run` and configured-source diagnostics print a warning naming the ignored secret file variable without printing either value. The process environment is not changed.
|
||||||
|
|
||||||
## Caveats
|
## Caveats
|
||||||
|
|
||||||
|
|||||||
@@ -22,19 +22,21 @@ The current core workflow is:
|
|||||||
2. open the source backend;
|
2. open the source backend;
|
||||||
3. discover source bundles beneath the source root;
|
3. discover source bundles beneath the source root;
|
||||||
4. validate each source bundle and its `manifest.json`;
|
4. validate each source bundle and its `manifest.json`;
|
||||||
5. for each configured destination, inspect destination state;
|
5. select the source bundle or bundles for each destination according to that destination's path mapping policy;
|
||||||
6. compare source state to destination state;
|
6. open each destination backend independently;
|
||||||
7. build a publish plan;
|
7. inspect destination state at the resolved destination bundle path;
|
||||||
8. optionally transform Markdown to HTML for that destination;
|
8. compare source state to destination state;
|
||||||
9. publish selected source and generated artifacts;
|
9. build a publish plan that selects source files, generated files, destination paths, and optional public URLs;
|
||||||
10. write `.distributor.json` as the destination sentinel/state file;
|
10. optionally transform Markdown to HTML for that destination;
|
||||||
11. run the notification hook, which is a no-op in the MVP.
|
11. publish selected source and generated artifacts;
|
||||||
|
12. write `.distributor.json` as the destination sentinel/state file;
|
||||||
|
13. run the notification hook, whose default implementation is currently a no-op.
|
||||||
|
|
||||||
## Pipeline Model
|
## Pipeline Model
|
||||||
|
|
||||||
A pipeline has exactly one source and one or more destinations.
|
A pipeline has exactly one source and one or more destinations.
|
||||||
|
|
||||||
The source is discovered and validated once. Each destination has independent backend configuration, publication policy, transform policy, replacement behavior, state, and notification behavior.
|
The source is discovered and validated once. Each destination has independent backend configuration, path mapping, publication policy, transform policy, public link policy, replacement behavior, state, and notification behavior.
|
||||||
|
|
||||||
The pipeline model is fan-out by design:
|
The pipeline model is fan-out by design:
|
||||||
|
|
||||||
@@ -53,7 +55,7 @@ A source bundle is a directory containing `manifest.json`.
|
|||||||
|
|
||||||
`manifest.json` is the sole producer-to-`distributor` contract. `distributor` must not rely on producer-specific work directory layouts, filenames, metadata, or conventions outside the configured source root and the source manifest.
|
`manifest.json` is the sole producer-to-`distributor` contract. `distributor` must not rely on producer-specific work directory layouts, filenames, metadata, or conventions outside the configured source root and the source manifest.
|
||||||
|
|
||||||
The MVP source manifest schema is intentionally minimal:
|
The source manifest schema is intentionally minimal:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -73,7 +75,7 @@ The MVP source manifest schema is intentionally minimal:
|
|||||||
|
|
||||||
Required fields:
|
Required fields:
|
||||||
|
|
||||||
- `schema_version`: source manifest schema version. MVP value: `1`.
|
- `schema_version`: source manifest schema version. Current value: `1`.
|
||||||
- `id`: stable bundle identifier.
|
- `id`: stable bundle identifier.
|
||||||
- `digest`: SHA-256 digest for the listed files.
|
- `digest`: SHA-256 digest for the listed files.
|
||||||
- `created`: RFC3339 timestamp. UTC is preferred; explicit offsets are allowed.
|
- `created`: RFC3339 timestamp. UTC is preferred; explicit offsets are allowed.
|
||||||
@@ -101,6 +103,7 @@ Each destination bundle path is managed by `.distributor.json`. This file is bot
|
|||||||
- the normalized source manifest used for publication;
|
- the normalized source manifest used for publication;
|
||||||
- metadata for copied source outputs;
|
- metadata for copied source outputs;
|
||||||
- metadata for generated outputs, such as HTML files;
|
- metadata for generated outputs, such as HTML files;
|
||||||
|
- optional URL metadata for published outputs;
|
||||||
- any additional metadata required by `distributor`.
|
- any additional metadata required by `distributor`.
|
||||||
|
|
||||||
A representative destination state file is:
|
A representative destination state file is:
|
||||||
@@ -127,14 +130,18 @@ A representative destination state file is:
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"links": {
|
||||||
|
"primary_url": "https://reports.example.com/weather-daily/"
|
||||||
|
},
|
||||||
"outputs": [
|
"outputs": [
|
||||||
{
|
{
|
||||||
"path": "report.html",
|
"path": "index.html",
|
||||||
"kind": "generated",
|
"kind": "generated",
|
||||||
"source_path": "report.md",
|
"source_path": "report.md",
|
||||||
"transform": "markdown_to_html",
|
"transform": "markdown_to_html",
|
||||||
"sha256": "sha256:...",
|
"sha256": "sha256:...",
|
||||||
"size": 23456
|
"size": 23456,
|
||||||
|
"url": "https://reports.example.com/weather-daily/"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -157,6 +164,8 @@ Transforms are configured per destination. A destination may receive source file
|
|||||||
|
|
||||||
The MVP supports only Markdown-to-HTML transformation. HTML generation must not mutate the source bundle. Generated outputs must be deterministic from the source bundle and destination transform configuration, and must be recorded in `.distributor.json`.
|
The MVP supports only Markdown-to-HTML transformation. HTML generation must not mutate the source bundle. Generated outputs must be deterministic from the source bundle and destination transform configuration, and must be recorded in `.distributor.json`.
|
||||||
|
|
||||||
|
Destination path mapping and public link generation are destination behavior. Source manifests do not declare where a bundle is published or which public URLs are recorded.
|
||||||
|
|
||||||
The application should distinguish:
|
The application should distinguish:
|
||||||
|
|
||||||
- transform policy: how derived files are generated;
|
- transform policy: how derived files are generated;
|
||||||
@@ -187,11 +196,13 @@ Avoid dependencies for small conveniences. Do not let external dependency types
|
|||||||
Use this current layout unless the project has a documented reason to differ:
|
Use this current layout unless the project has a documented reason to differ:
|
||||||
|
|
||||||
- `cmd/distributor`: application entrypoint only.
|
- `cmd/distributor`: application entrypoint only.
|
||||||
|
- `pkg/bundle`: public producer-facing source manifest model, digest logic, parsing, manifest building, complete local bundle writing, and local validation helpers.
|
||||||
- `internal/app`: application orchestration and top-level use cases.
|
- `internal/app`: application orchestration and top-level use cases.
|
||||||
- `internal/cli`: CLI command definitions, flags, argument parsing, and command wiring.
|
- `internal/cli`: CLI command definitions, flags, argument parsing, and command wiring.
|
||||||
- `internal/config`: configuration structs, defaults, loading, precedence, and validation.
|
- `internal/config`: configuration structs, defaults, loading, precedence, and validation.
|
||||||
- `internal/bundle`: source manifest parsing, source bundle discovery, source digest validation, and source bundle model.
|
- `internal/bundle`: storage-backed source bundle discovery and validation over the public manifest contract.
|
||||||
- `internal/state`: `.distributor.json` parsing, validation, comparison, and output metadata.
|
- `internal/state`: `.distributor.json` parsing, validation, comparison, and output metadata.
|
||||||
|
- `internal/link`: shared HTTP URL validation for configured and persisted link metadata.
|
||||||
- `internal/storage`: backend interfaces, shared path/resource types, backend registry, and storage errors.
|
- `internal/storage`: backend interfaces, shared path/resource types, backend registry, and storage errors.
|
||||||
- `internal/adapters/local`: local filesystem backend.
|
- `internal/adapters/local`: local filesystem backend.
|
||||||
- `internal/adapters/ssh`: SSH/SFTP backend.
|
- `internal/adapters/ssh`: SSH/SFTP backend.
|
||||||
@@ -228,17 +239,20 @@ Pipeline configuration should express:
|
|||||||
- pipeline id;
|
- pipeline id;
|
||||||
- one source backend;
|
- one source backend;
|
||||||
- one or more destinations;
|
- one or more destinations;
|
||||||
|
- per-destination path mapping;
|
||||||
- per-destination publish policy;
|
- per-destination publish policy;
|
||||||
- per-destination transform policy;
|
- per-destination transform policy;
|
||||||
|
- per-destination public link policy;
|
||||||
- validation behavior;
|
- validation behavior;
|
||||||
- destination conflict/replacement behavior.
|
- destination conflict/replacement behavior.
|
||||||
|
|
||||||
## Modules, Stages, and Registries
|
## Modules and Registries
|
||||||
|
|
||||||
Each major stage should have an explicit input/output contract:
|
Each major workflow step should have an explicit input/output contract:
|
||||||
|
|
||||||
- source discovery;
|
- source discovery;
|
||||||
- source validation;
|
- source validation;
|
||||||
|
- destination bundle selection;
|
||||||
- destination state inspection;
|
- destination state inspection;
|
||||||
- destination comparison;
|
- destination comparison;
|
||||||
- transform planning/execution;
|
- transform planning/execution;
|
||||||
@@ -297,8 +311,10 @@ Important tests include:
|
|||||||
- relative path safety and path traversal rejection;
|
- relative path safety and path traversal rejection;
|
||||||
- destination `.distributor.json` parsing and comparison;
|
- destination `.distributor.json` parsing and comparison;
|
||||||
- same/older/newer/conflict publish decisions;
|
- same/older/newer/conflict publish decisions;
|
||||||
|
- destination bundle path mapping;
|
||||||
- destructive replacement safety checks;
|
- destructive replacement safety checks;
|
||||||
- transform output planning and metadata recording;
|
- transform output planning and metadata recording;
|
||||||
|
- public URL planning and state metadata;
|
||||||
- dry-run output;
|
- dry-run output;
|
||||||
- local backend behavior with temporary directories;
|
- local backend behavior with temporary directories;
|
||||||
- fake backend behavior for storage-facing core logic.
|
- fake backend behavior for storage-facing core logic.
|
||||||
|
|||||||
@@ -6,10 +6,11 @@ Use it with `docs/policy/architecture.md` and `docs/policy/documentation.md`.
|
|||||||
## Repository Layout
|
## Repository Layout
|
||||||
|
|
||||||
- `cmd/distributor`: executable entrypoint only.
|
- `cmd/distributor`: executable entrypoint only.
|
||||||
|
- `pkg/bundle`: public producer-facing source manifest and local bundle writer helpers.
|
||||||
- `internal/app`: top-level use cases for `run`, `validate`, and `inspect`.
|
- `internal/app`: top-level use cases for `run`, `validate`, and `inspect`.
|
||||||
- `internal/cli`: standard-library command parsing, flags, help text, and command wiring.
|
- `internal/cli`: standard-library command parsing, flags, help text, and command wiring.
|
||||||
- `internal/config`: YAML configuration structs, loading, defaults, and validation.
|
- `internal/config`: YAML configuration structs, loading, defaults, and validation.
|
||||||
- `internal/bundle`: source bundle discovery, manifest parsing, digest calculation, and validation.
|
- `internal/bundle`: storage-backed source bundle discovery and validation using the public manifest contract.
|
||||||
- `internal/state`: destination `.distributor.json` parsing, validation, and comparison.
|
- `internal/state`: destination `.distributor.json` parsing, validation, and comparison.
|
||||||
- `internal/storage`: backend interface, registry, logical path rules, typed errors, and shared storage helpers.
|
- `internal/storage`: backend interface, registry, logical path rules, typed errors, and shared storage helpers.
|
||||||
- `internal/adapters/local`: local filesystem backend.
|
- `internal/adapters/local`: local filesystem backend.
|
||||||
@@ -18,15 +19,16 @@ Use it with `docs/policy/architecture.md` and `docs/policy/documentation.md`.
|
|||||||
- `internal/storage/fake`: in-memory backend for tests.
|
- `internal/storage/fake`: in-memory backend for tests.
|
||||||
- `internal/publish`: destination inspection, output planning, reconciliation, execution, managed cleanup, and explicit forced replacement.
|
- `internal/publish`: destination inspection, output planning, reconciliation, execution, managed cleanup, and explicit forced replacement.
|
||||||
- `internal/transform`: transform interface and registry.
|
- `internal/transform`: transform interface and registry.
|
||||||
- `internal/transform/markdown`: Markdown-to-HTML sidecar transform.
|
- `internal/transform/markdown`: Markdown-to-HTML transform.
|
||||||
- `internal/notify`: notification interface and current no-op notifier.
|
- `internal/notify`: notification interface and current no-op notifier.
|
||||||
- `internal/testutil`: shared test fixtures. Production code must not import this package.
|
- `internal/testutil`: shared test fixtures. Production code must not import this package.
|
||||||
- `docs`: current user, operator, policy, internal, and roadmap documentation.
|
- `docs`: current user, operator, policy, internal, and roadmap documentation.
|
||||||
- `examples`: copyable example configs and source bundles.
|
- `examples`: copyable example configs and source bundles.
|
||||||
|
|
||||||
Do not create new top-level package families such as `pkg`, `internal/stage`,
|
Do not create new top-level package families such as public `pkg/...` packages
|
||||||
`internal/modules`, or service-specific adapter directories unless the
|
beyond `pkg/bundle`, generic workflow containers, or service-specific adapter
|
||||||
architecture policy or a current roadmap explicitly calls for them.
|
directories unless the architecture policy or a current roadmap explicitly
|
||||||
|
calls for them.
|
||||||
|
|
||||||
## Common Commands
|
## Common Commands
|
||||||
|
|
||||||
@@ -73,7 +75,7 @@ GOCACHE=/private/tmp/distributor-gocache GOMODCACHE=/private/tmp/distributor-gom
|
|||||||
- Keep adapter packages thin. Backend-specific filesystem or service behavior belongs in adapters; bundle, state, transform, and publish policy belongs outside adapters.
|
- Keep adapter packages thin. Backend-specific filesystem or service behavior belongs in adapters; bundle, state, transform, and publish policy belongs outside adapters.
|
||||||
- Preserve public CLI behavior, config semantics, manifest schema, destination state schema, and implemented backend behavior unless the current task explicitly changes them.
|
- Preserve public CLI behavior, config semantics, manifest schema, destination state schema, and implemented backend behavior unless the current task explicitly changes them.
|
||||||
- Use `storage.DisplayPath`, `storage.StateFileName`, `storage.StatePath`, and `storage.ManagedBundleTargets` instead of duplicating those conventions.
|
- Use `storage.DisplayPath`, `storage.StateFileName`, `storage.StatePath`, and `storage.ManagedBundleTargets` instead of duplicating those conventions.
|
||||||
- Use `bundle.ValidateManifest` for normalized source manifest semantics, including embedded source manifests in destination state.
|
- Use `pkg/bundle` for normalized source manifest semantics. Internal packages should reach those rules through `internal/bundle` when they also need storage-backed bundle discovery or validation.
|
||||||
- Use `config.ValidatePublishTransformPolicy` for publish and transform policy combinations.
|
- Use `config.ValidatePublishTransformPolicy` for publish and transform policy combinations.
|
||||||
- Do not import concrete transform implementations from `internal/publish`; app-level wiring owns transform registration.
|
- Do not import concrete transform implementations from `internal/publish`; app-level wiring owns transform registration.
|
||||||
- Do not import `internal/testutil` from production code.
|
- Do not import `internal/testutil` from production code.
|
||||||
@@ -127,8 +129,9 @@ When adding or changing commands or flags:
|
|||||||
3. Add or update CLI tests in `internal/cli`.
|
3. Add or update CLI tests in `internal/cli`.
|
||||||
4. Update `docs/cli.md` if syntax, flags, output expectations, or workflows change.
|
4. Update `docs/cli.md` if syntax, flags, output expectations, or workflows change.
|
||||||
|
|
||||||
`validate` and `inspect` are local path commands. `run` loads configured
|
`validate` and `inspect` support a local path shortcut and configured
|
||||||
pipelines and executes local, SSH, and S3 backends.
|
source-only diagnostics. `run` loads configured pipelines and executes local,
|
||||||
|
SSH, and S3 backends.
|
||||||
|
|
||||||
## Storage Backends
|
## Storage Backends
|
||||||
|
|
||||||
|
|||||||
@@ -106,7 +106,7 @@ Recommended:
|
|||||||
- `examples/`
|
- `examples/`
|
||||||
- `docs/policy/development.md`
|
- `docs/policy/development.md`
|
||||||
|
|
||||||
### Modular, staged, service-oriented, or orchestration application
|
### Modular, service-oriented, or orchestration application
|
||||||
|
|
||||||
Required:
|
Required:
|
||||||
- `docs/cli.md`, if CLI-based
|
- `docs/cli.md`, if CLI-based
|
||||||
@@ -175,7 +175,7 @@ It should include:
|
|||||||
- dependency policy;
|
- dependency policy;
|
||||||
- how to add config fields;
|
- how to add config fields;
|
||||||
- how to add CLI flags;
|
- how to add CLI flags;
|
||||||
- how to add stages/modules/adapters, if applicable;
|
- how to add modules or adapters, if applicable;
|
||||||
- how to update examples;
|
- how to update examples;
|
||||||
- documentation update expectations.
|
- documentation update expectations.
|
||||||
|
|
||||||
@@ -216,7 +216,7 @@ Explain when commands are useful, not just their syntax.
|
|||||||
|
|
||||||
**Audience:** administrators, operators
|
**Audience:** administrators, operators
|
||||||
|
|
||||||
Required for applications that maintain state, support resume behavior, run multiple stages, write durable artifacts, use remote storage, or require recovery procedures.
|
Required for applications that maintain state, support resume behavior, run multi-step workflows, write durable artifacts, use remote storage, or require recovery procedures.
|
||||||
|
|
||||||
It should cover:
|
It should cover:
|
||||||
|
|
||||||
@@ -248,7 +248,7 @@ Each entry should include:
|
|||||||
|
|
||||||
**Audience:** developers, LLM coding agents
|
**Audience:** developers, LLM coding agents
|
||||||
|
|
||||||
Required for modular, staged, service-oriented, or orchestration projects.
|
Required for modular, service-oriented, or orchestration projects.
|
||||||
|
|
||||||
This directory describes implemented internal components. It is not the roadmap.
|
This directory describes implemented internal components. It is not the roadmap.
|
||||||
|
|
||||||
|
|||||||
592
docs/roadmap/audit.md
Normal file
592
docs/roadmap/audit.md
Normal file
@@ -0,0 +1,592 @@
|
|||||||
|
# Code Quality and Deduplication Audit
|
||||||
|
|
||||||
|
## 1. Executive summary
|
||||||
|
|
||||||
|
Overall code quality is strong. The repository has clear package boundaries, good current-behavior documentation, focused adapter packages, and tests close to most implemented behavior. The most important cleanup opportunities are narrow and behavior-preserving rather than architectural.
|
||||||
|
|
||||||
|
Top three refactoring targets:
|
||||||
|
|
||||||
|
1. HTTP upload admission, body staging, and archive validation are split across `internal/app` and `internal/ingest` in a way that duplicates size and content-type policy and buffers uploads in memory.
|
||||||
|
2. Runtime config loading, default config path selection, secret loading, and warning projection are repeated across app entrypoints.
|
||||||
|
3. Run orchestration mixes destination processing, failure aggregation, warning recording, and report event ordering in one large loop, making future changes harder to review safely.
|
||||||
|
|
||||||
|
The codebase appears ready for a limited cleanup pass. I do not see a major architectural risk that requires a redesign before the next release.
|
||||||
|
|
||||||
|
## 2. Repository map reviewed
|
||||||
|
|
||||||
|
Reviewed policy and current-behavior documentation:
|
||||||
|
|
||||||
|
- `AGENTS.md`
|
||||||
|
- `README.md`
|
||||||
|
- `docs/policy/architecture.md`
|
||||||
|
- `docs/policy/development.md`
|
||||||
|
- `docs/policy/documentation.md`
|
||||||
|
- `docs/config.md`
|
||||||
|
- `docs/cli.md`
|
||||||
|
- `docs/operations.md`
|
||||||
|
- `docs/troubleshooting.md`
|
||||||
|
- `docs/internal/*.md`
|
||||||
|
- `docs/roadmap/http.md`
|
||||||
|
- `docs/roadmap/implementation.md`
|
||||||
|
|
||||||
|
Reviewed implementation areas:
|
||||||
|
|
||||||
|
- `cmd/distributor`: executable entrypoint.
|
||||||
|
- `internal/cli`: root command, `version`, `run`, `serve`, `validate`, `inspect`, and `manifest create` parsing.
|
||||||
|
- `internal/app`: run orchestration, configured source diagnostics, backend factory, manifest creation, CLI output, HTTP upload server, upload coordinator, and pipeline coordinator.
|
||||||
|
- `internal/config`: config structs, defaults, validation, quantity parsing, S3/SSH helpers, and secrets resolver.
|
||||||
|
- `internal/bundle`: storage-backed source discovery and validation.
|
||||||
|
- `pkg/bundle`: public manifest model, digest logic, manifest building, local validation, and local bundle writer.
|
||||||
|
- `internal/storage` and `internal/storage/fake`: backend interface, path helpers, walk helpers, typed errors, and fake backend.
|
||||||
|
- `internal/adapters/local`, `internal/adapters/ssh`, and `internal/adapters/s3`: runtime storage adapters.
|
||||||
|
- `internal/ingest`: HTTP upload archive staging.
|
||||||
|
- `internal/publish`: destination planning, output selection, link projection, state writing, cleanup, and force replacement.
|
||||||
|
- `internal/state`: destination state parsing, validation, comparison, and JSON projection.
|
||||||
|
- `internal/transform` and `internal/transform/markdown`: transform registry and Markdown rendering.
|
||||||
|
- `internal/link`, `internal/notify`, `internal/logging`, and `internal/testutil`.
|
||||||
|
- `examples`, package tests, and package `testdata`.
|
||||||
|
|
||||||
|
Requested areas that are absent as separate packages:
|
||||||
|
|
||||||
|
- `internal/stage`
|
||||||
|
- `internal/modules`
|
||||||
|
- `internal/validators`
|
||||||
|
- `internal/artifacts`
|
||||||
|
- `internal/manifest`
|
||||||
|
- `internal/schema`
|
||||||
|
- `internal/report`
|
||||||
|
- public `pkg` packages other than `pkg/bundle`
|
||||||
|
|
||||||
|
Those absences are consistent with current architecture policy; the corresponding behavior lives in narrower existing packages.
|
||||||
|
|
||||||
|
## 3. High-confidence deduplication opportunities
|
||||||
|
|
||||||
|
### HTTP upload body handling should be owned by ingestion
|
||||||
|
|
||||||
|
Affected files/packages:
|
||||||
|
|
||||||
|
- `internal/app/upload_http.go`
|
||||||
|
- `internal/app/upload_coordinator.go`
|
||||||
|
- `internal/ingest/archive.go`
|
||||||
|
- `internal/app/upload_http_test.go`
|
||||||
|
- `internal/app/upload_http_integration_test.go`
|
||||||
|
- `internal/ingest/archive_test.go`
|
||||||
|
|
||||||
|
Duplicated or near-duplicated behavior:
|
||||||
|
|
||||||
|
- `internal/app/upload_http.go` validates upload content types in `supportedUploadContentType`, while `internal/ingest/archive.go` validates the same content types in `archiveFormat`.
|
||||||
|
- `internal/app/upload_http.go` enforces upload size in `readUploadBody`, while `internal/ingest/archive.go` enforces upload size again in `writeLimited`.
|
||||||
|
- The HTTP handler reads the full upload body into memory before submission, then the coordinator passes a `bytes.Reader` to ingestion.
|
||||||
|
|
||||||
|
Why it matters:
|
||||||
|
|
||||||
|
- The app transport layer now partially owns archive policy that should belong to `internal/ingest`.
|
||||||
|
- Large accepted uploads are buffered in memory even though ingestion already has streaming-to-disk mechanics.
|
||||||
|
- Future archive formats, content types, or upload limit changes would need coordinated edits in multiple packages.
|
||||||
|
|
||||||
|
Recommended refactor:
|
||||||
|
|
||||||
|
- Move supported content-type checking behind an ingestion-owned helper, for example `ingest.ValidateContentType` or `ingest.IsSupportedContentType`.
|
||||||
|
- Change upload admission so the request body is streamed to staging exactly once before the HTTP handler returns `202 Accepted`.
|
||||||
|
- Keep queue-full rejection before reading the body.
|
||||||
|
- Queue a staged local bundle root, not an unread request body. This preserves async distribution while keeping HTTP request lifetime separate from later pipeline execution.
|
||||||
|
- Keep `UploadCoordinator` responsible for queueing, status, per-pipeline serialization, and execution. Keep `internal/ingest` responsible for archive format, size, extraction, cleanup, and source bundle validation.
|
||||||
|
|
||||||
|
Suggested tests:
|
||||||
|
|
||||||
|
- HTTP handler rejects full queues without reading the body.
|
||||||
|
- HTTP handler streams a valid body to ingestion and returns `202` only after staging succeeds.
|
||||||
|
- Unsupported content types are rejected through the ingestion-owned content-type policy.
|
||||||
|
- Oversized uploads are rejected without retaining a staged run.
|
||||||
|
- Accepted upload status still transitions through queued/running/succeeded or failed without depending on an open HTTP request body.
|
||||||
|
|
||||||
|
Risk level:
|
||||||
|
|
||||||
|
- Medium. The behavior change is internal but touches admission timing and async execution boundaries. It should be implemented in a focused prompt with existing HTTP integration tests extended first.
|
||||||
|
|
||||||
|
### Runtime config and secret setup should have one app-level helper
|
||||||
|
|
||||||
|
Affected files/packages:
|
||||||
|
|
||||||
|
- `internal/app/run.go`
|
||||||
|
- `internal/app/source_select.go`
|
||||||
|
- `internal/app/serve.go`
|
||||||
|
- `internal/app/backends.go`
|
||||||
|
- `internal/app/run_warnings.go`
|
||||||
|
- `internal/config`
|
||||||
|
- `internal/app/*_test.go`
|
||||||
|
|
||||||
|
Duplicated or near-duplicated behavior:
|
||||||
|
|
||||||
|
- Defaulting an empty config path to `config.DefaultConfigPath` appears in `Run`, `RunPipeline`, `RunPipelineWithLocalSource`, and `Serve`.
|
||||||
|
- Config loading and secret loading are separate repeated steps in `buildRunReport`, `selectSourceBundlesFromConfig`, and `Serve`.
|
||||||
|
- Secret conflict warnings are projected in run and configured source diagnostics, while serve loads secrets without using or exposing conflict warning metadata.
|
||||||
|
- Backend factory construction from a config environment is repeated through provider plumbing.
|
||||||
|
|
||||||
|
Why it matters:
|
||||||
|
|
||||||
|
- Config and secret precedence is a public operational policy.
|
||||||
|
- A future change to config discovery, secret conflict reporting, or runtime environment construction could drift between `run`, `serve`, `validate`, and `inspect`.
|
||||||
|
- Tests for secrets and credential resolution need to cover several entrypoints today.
|
||||||
|
|
||||||
|
Recommended refactor:
|
||||||
|
|
||||||
|
- Add a small app-level runtime setup helper, for example `loadRuntimeConfig(optionsConfigPath string) (runtimeConfig, error)`.
|
||||||
|
- The helper should own default config path selection, `config.LoadFile`, `config.LoadSecretEnvironment`, and conversion of secret conflicts into `OutputWarning` values.
|
||||||
|
- Keep config parsing and validation in `internal/config`; the helper should not duplicate config policy.
|
||||||
|
- Let `run`, configured `validate`/`inspect`, and `serve` call the helper and then apply command-specific behavior.
|
||||||
|
|
||||||
|
Suggested tests:
|
||||||
|
|
||||||
|
- One focused app test proving default config path selection remains unchanged where injection permits it.
|
||||||
|
- Existing secret conflict JSON/text warning tests for `run`, `validate`, and `inspect`.
|
||||||
|
- Serve startup test proving duplicate and missing upload tokens still fail without leaking values.
|
||||||
|
- S3 explicit credential tests proving the resolver is still used through the helper.
|
||||||
|
|
||||||
|
Risk level:
|
||||||
|
|
||||||
|
- Low to medium. This is a straightforward centralization but touches several command entrypoints.
|
||||||
|
|
||||||
|
### Run destination processing needs a narrow helper boundary
|
||||||
|
|
||||||
|
Affected files/packages:
|
||||||
|
|
||||||
|
- `internal/app/run.go`
|
||||||
|
- `internal/app/run_output.go`
|
||||||
|
- `internal/app/run_failures.go`
|
||||||
|
- `internal/app/run_selection.go`
|
||||||
|
- `internal/publish`
|
||||||
|
- `internal/app/run_test.go`
|
||||||
|
|
||||||
|
Duplicated or near-duplicated behavior:
|
||||||
|
|
||||||
|
- Destination backend open failures and publish planning/execution failures each manually add `runFailures`, record summary failure counts, append `RunActionRecord`, and append pipeline event indexes.
|
||||||
|
- `publish.Build` error handling patches missing `Plan` identity fields inline before converting the plan to a run action.
|
||||||
|
- Fixed-path warning emission is interleaved with destination selection and publish plan handling.
|
||||||
|
|
||||||
|
Why it matters:
|
||||||
|
|
||||||
|
- `run --format json` depends on exact action ordering, warnings, partial failures, and summary counters.
|
||||||
|
- Future changes to actions, links, notifications, or HTTP upload reports could accidentally update one failure path but not another.
|
||||||
|
- The current loop is correct but dense enough that small behavior changes are hard to review.
|
||||||
|
|
||||||
|
Recommended refactor:
|
||||||
|
|
||||||
|
- Extract a narrow `runDestination` or `destinationRunner` helper that processes one destination and returns action records, warnings, summary deltas, and failures.
|
||||||
|
- Add a helper for recording a destination-scoped failure that updates `runFailures`, `runSummary`, `RunReport.Actions`, and pipeline events in one place.
|
||||||
|
- Add a helper that normalizes partial `publish.Plan` identity fields before action projection.
|
||||||
|
- Do not introduce a generic workflow engine or stage abstraction.
|
||||||
|
|
||||||
|
Suggested tests:
|
||||||
|
|
||||||
|
- Preserve existing run text output golden assertions.
|
||||||
|
- Preserve JSON partial-result behavior when planning fails after destination processing begins.
|
||||||
|
- Add one focused test where destination open fails for multiple selected bundles and verify action records, output errors, and summary counters stay aligned.
|
||||||
|
- Add one fixed-path dry-run warning test after extraction to verify event ordering.
|
||||||
|
|
||||||
|
Risk level:
|
||||||
|
|
||||||
|
- Medium. The refactor is behavior-preserving but touches the most important user-facing workflow.
|
||||||
|
|
||||||
|
### Archive path validation duplicates source path policy with a different error surface
|
||||||
|
|
||||||
|
Affected files/packages:
|
||||||
|
|
||||||
|
- `internal/ingest/archive.go`
|
||||||
|
- `pkg/bundle/path.go`
|
||||||
|
- `internal/storage/path.go`
|
||||||
|
- `internal/ingest/archive_test.go`
|
||||||
|
|
||||||
|
Duplicated or near-duplicated behavior:
|
||||||
|
|
||||||
|
- `cleanArchivePath`, `pkg/bundle.ValidateSourcePath`, and `storage.ValidatePath` all enforce clean slash-separated relative paths with no backslashes, no absolute paths, and no dot segments.
|
||||||
|
- Archive staging needs slightly different policy because directories are allowed and `manifest.json` is allowed only at the root, so the duplication is not completely mechanical.
|
||||||
|
|
||||||
|
Why it matters:
|
||||||
|
|
||||||
|
- Path safety is high-risk behavior.
|
||||||
|
- Future changes to source path rules could miss archive extraction, especially around backslashes, reserved names, or dot segments.
|
||||||
|
|
||||||
|
Recommended refactor:
|
||||||
|
|
||||||
|
- Keep archive-specific rules in `internal/ingest`, but use a shared path-checking primitive where possible.
|
||||||
|
- A good shape is an exported `pkg/bundle.ValidatePathSegmented` only if it fits the public producer API, or an internal helper in ingestion that delegates file-entry validation to `pkg/bundle.ValidateSourcePath` for regular files after handling directory-specific exceptions.
|
||||||
|
- Preserve current archive-specific errors and tests.
|
||||||
|
|
||||||
|
Suggested tests:
|
||||||
|
|
||||||
|
- Table tests shared or mirrored across bundle path validation and archive path cleaning for absolute paths, traversal, backslashes, dot segments, empty names, root `manifest.json`, nested `manifest.json`, and `.distributor.json`.
|
||||||
|
- Regression tests proving directories are still accepted in archives but symlinks and hardlinks remain rejected.
|
||||||
|
|
||||||
|
Risk level:
|
||||||
|
|
||||||
|
- Low to medium. Path validation changes need careful tests, but the desired change can be small.
|
||||||
|
|
||||||
|
## 4. Medium-confidence opportunities
|
||||||
|
|
||||||
|
### Source and destination backend config shapes could expose a normalized view
|
||||||
|
|
||||||
|
Affected files/packages:
|
||||||
|
|
||||||
|
- `internal/config/config.go`
|
||||||
|
- `internal/config/defaults.go`
|
||||||
|
- `internal/config/validate.go`
|
||||||
|
- `internal/app/backends.go`
|
||||||
|
- `internal/config/*_test.go`
|
||||||
|
- `internal/app/backends_test.go`
|
||||||
|
|
||||||
|
Duplicated or near-duplicated behavior:
|
||||||
|
|
||||||
|
- `config.Backend` and `config.Destination` duplicate backend fields for local, SSH, S3, and credentials.
|
||||||
|
- Defaults for source backends and destination backends are implemented in separate functions.
|
||||||
|
- App backend opening converts both shapes into `backendOpenSpec`.
|
||||||
|
|
||||||
|
Why it matters:
|
||||||
|
|
||||||
|
- New backend fields must be added to both YAML structs, defaulting paths, validation paths, app open-spec conversion, docs, and tests.
|
||||||
|
- The current pattern is easy to understand but likely to drift as more backend-specific fields are added.
|
||||||
|
|
||||||
|
Recommended refactor:
|
||||||
|
|
||||||
|
- Keep the YAML shape unchanged for compatibility.
|
||||||
|
- Add package-local helpers in `internal/config` that return a normalized backend view for either source or destination.
|
||||||
|
- Use that view for shared backend defaulting and validation where it improves clarity.
|
||||||
|
- Keep destination-only fields such as `publish`, `transfer`, `links`, and `path_mapping` on `Destination`.
|
||||||
|
|
||||||
|
Suggested tests:
|
||||||
|
|
||||||
|
- Existing source and destination backend validation tests should continue to pass.
|
||||||
|
- Add a table test that validates equivalent local, SSH, and S3 source/destination backend field requirements through the shared view.
|
||||||
|
- Add a test that `http_upload` remains source-only.
|
||||||
|
|
||||||
|
Risk level:
|
||||||
|
|
||||||
|
- Medium. This reduces future drift, but the current duplication is understandable and does not need to be the first cleanup.
|
||||||
|
|
||||||
|
### CLI command scaffolding is mostly shared, but manifest create has special parsing
|
||||||
|
|
||||||
|
Affected files/packages:
|
||||||
|
|
||||||
|
- `internal/cli/run.go`
|
||||||
|
- `internal/cli/serve.go`
|
||||||
|
- `internal/cli/source_mode.go`
|
||||||
|
- `internal/cli/manifest.go`
|
||||||
|
- `internal/cli/version.go`
|
||||||
|
- `internal/cli/root_test.go`
|
||||||
|
|
||||||
|
Duplicated or near-duplicated behavior:
|
||||||
|
|
||||||
|
- Several commands repeat `flag.NewFlagSet`, `SetOutput`, help handling, format parsing, and usage exit handling.
|
||||||
|
- `manifest create` uses `splitManifestCreateArgs` to allow a positional bundle path before flags, unlike Go's default `flag` behavior.
|
||||||
|
|
||||||
|
Why it matters:
|
||||||
|
|
||||||
|
- CLI syntax and error behavior are public.
|
||||||
|
- A broad CLI helper could accidentally obscure command-specific parsing, but a narrow helper could reduce repeated setup and invalid-format handling.
|
||||||
|
|
||||||
|
Recommended refactor:
|
||||||
|
|
||||||
|
- Do not introduce a CLI framework.
|
||||||
|
- Consider a tiny helper for common `FlagSet` creation and output-format parsing after higher-value app/config cleanup.
|
||||||
|
- Keep `manifest create` custom parsing local unless another command needs the same interspersed positional behavior.
|
||||||
|
|
||||||
|
Suggested tests:
|
||||||
|
|
||||||
|
- Preserve current CLI usage-error tests.
|
||||||
|
- Add explicit tests for `manifest create <path> --id x`, `manifest create --id x <path>`, and invalid missing flag values before any parser cleanup.
|
||||||
|
|
||||||
|
Risk level:
|
||||||
|
|
||||||
|
- Low if kept narrow; medium if over-generalized.
|
||||||
|
|
||||||
|
### Output DTOs repeat bundle metadata projection
|
||||||
|
|
||||||
|
Affected files/packages:
|
||||||
|
|
||||||
|
- `internal/app/validate.go`
|
||||||
|
- `internal/app/inspect.go`
|
||||||
|
- `internal/app/manifest.go`
|
||||||
|
- `internal/app/run_output.go`
|
||||||
|
- `internal/app/output.go`
|
||||||
|
|
||||||
|
Duplicated or near-duplicated behavior:
|
||||||
|
|
||||||
|
- `inspect` and `manifest create` both project bundle file metadata into command-specific JSON structs.
|
||||||
|
- `validate`, `inspect`, and `manifest create` each define local result types and file record types.
|
||||||
|
- RFC3339 formatting uses both `time.RFC3339` and the equivalent literal layout string.
|
||||||
|
|
||||||
|
Why it matters:
|
||||||
|
|
||||||
|
- JSON output is now a public interface.
|
||||||
|
- Repeated projection can drift in field names, timestamp formatting, or path display rules.
|
||||||
|
|
||||||
|
Recommended refactor:
|
||||||
|
|
||||||
|
- Add a small app-local projection helper for bundle summaries and manifest file records.
|
||||||
|
- Use `time.RFC3339` instead of literal RFC3339 layouts.
|
||||||
|
- Keep command-specific result structs where the command output semantics differ.
|
||||||
|
|
||||||
|
Suggested tests:
|
||||||
|
|
||||||
|
- JSON structural tests for `validate`, `inspect`, and `manifest create` before and after the helper.
|
||||||
|
- A timestamp-format assertion using an offset timestamp to confirm current behavior is preserved.
|
||||||
|
|
||||||
|
Risk level:
|
||||||
|
|
||||||
|
- Low.
|
||||||
|
|
||||||
|
### PipelineRunCoordinator overlaps conceptually with UploadCoordinator
|
||||||
|
|
||||||
|
Affected files/packages:
|
||||||
|
|
||||||
|
- `internal/app/run_coordinator.go`
|
||||||
|
- `internal/app/upload_coordinator.go`
|
||||||
|
- `docs/internal/app.md`
|
||||||
|
- `internal/app/run_coordinator_test.go`
|
||||||
|
- `internal/app/upload_coordinator_test.go`
|
||||||
|
|
||||||
|
Duplicated or near-duplicated behavior:
|
||||||
|
|
||||||
|
- Both coordinators define run records, statuses, timestamps, status transitions, context handling, and active pipeline protection.
|
||||||
|
- The upload coordinator additionally queues, stages, expires status records, and serializes same-pipeline upload execution.
|
||||||
|
|
||||||
|
Why it matters:
|
||||||
|
|
||||||
|
- The concepts are similar enough to confuse future contributors.
|
||||||
|
- However, the behavior is not identical: one rejects duplicate active runs, while the other queues accepted uploads.
|
||||||
|
|
||||||
|
Recommended refactor:
|
||||||
|
|
||||||
|
- Do not merge the coordinators now.
|
||||||
|
- Review whether `PipelineRunCoordinator` is still needed as an exported app-level helper. If it is intended for future transports, document that role clearly. If not, remove it and its tests in a separate dead-code cleanup.
|
||||||
|
- If both remain, extract only tiny shared timestamp/status helpers if a real third coordinator appears.
|
||||||
|
|
||||||
|
Suggested tests:
|
||||||
|
|
||||||
|
- If retained, keep existing duplicate-run tests.
|
||||||
|
- If removed, run `go test ./internal/app ./internal/cli` and verify no current behavior depended on it.
|
||||||
|
|
||||||
|
Risk level:
|
||||||
|
|
||||||
|
- Low for documentation clarification, medium for removal because it is exported from an internal package and documented for maintainers.
|
||||||
|
|
||||||
|
## 5. Boundary and responsibility concerns
|
||||||
|
|
||||||
|
The major boundaries are sound:
|
||||||
|
|
||||||
|
- CLI parsing stays in `internal/cli`.
|
||||||
|
- Config defaults and validation stay in `internal/config`.
|
||||||
|
- Backend-specific filesystem, SFTP, and S3 behavior stays in adapters.
|
||||||
|
- Manifest semantics are centralized in `pkg/bundle`, with `internal/bundle` adding storage-backed discovery and validation.
|
||||||
|
- Destination state comparison stays in `internal/state`.
|
||||||
|
- Publish planning/execution stays in `internal/publish`.
|
||||||
|
- Transform implementation is behind `internal/transform`.
|
||||||
|
|
||||||
|
Concerns worth addressing:
|
||||||
|
|
||||||
|
- HTTP upload request-body staging currently crosses the app/ingest boundary. The app transport layer should not own body buffering and archive size enforcement beyond admission and HTTP status projection.
|
||||||
|
- Runtime config setup is app-layer behavior, but it is repeated rather than named. A runtime setup helper would clarify the boundary between `internal/config` and command-specific execution.
|
||||||
|
- `internal/app/run.go` owns too many destination-loop details. Extracting a destination processing helper would keep orchestration in app while reducing local complexity.
|
||||||
|
|
||||||
|
Recommended homes:
|
||||||
|
|
||||||
|
- Upload archive policy: `internal/ingest`.
|
||||||
|
- HTTP route/auth/status mapping: `internal/app/upload_http.go`.
|
||||||
|
- Queueing/status/execution: `internal/app/upload_coordinator.go`.
|
||||||
|
- Runtime config plus secret setup: a small helper in `internal/app`, using `internal/config`.
|
||||||
|
- Path and state filenames: keep in `internal/storage`.
|
||||||
|
|
||||||
|
## 6. Path, key, and naming construction review
|
||||||
|
|
||||||
|
Centralized and healthy areas:
|
||||||
|
|
||||||
|
- `storage.StateFileName`, `storage.StatePath`, `storage.ManagedBundleTargets`, `storage.Join`, `storage.DisplayPath`, and logical path validation are used in core publication and tests.
|
||||||
|
- S3 object-key mapping is contained in `internal/adapters/s3`.
|
||||||
|
- SSH and local native path conversion stay inside their adapters.
|
||||||
|
- Link URL construction is isolated in `internal/publish/links.go` and URL validation in `internal/link`.
|
||||||
|
- Manifest name and schema version are centralized in `pkg/bundle`, with `internal/bundle` aliases.
|
||||||
|
|
||||||
|
Areas needing cleanup:
|
||||||
|
|
||||||
|
- Archive path cleaning duplicates much of source/storage path policy and should either delegate to a shared primitive or be tightly covered by mirrored tests.
|
||||||
|
- Upload run ID construction is isolated, but the shape is partly policy. Keep tests around `<pipeline_id>.<utc_timestamp>.<random_suffix>` before changing coordinator code.
|
||||||
|
- Some app tests still construct destination state and source paths locally. `internal/testutil` already covers many cases; additional helper use should be opportunistic, not a sweeping test rewrite.
|
||||||
|
|
||||||
|
## 7. Resolution and catalog review
|
||||||
|
|
||||||
|
Named concept resolution is mostly consistent:
|
||||||
|
|
||||||
|
- Backend names are defined in `internal/config/defaults.go`.
|
||||||
|
- Runtime backend construction is app-owned through `backendFactory` and the storage registry.
|
||||||
|
- Transform names are defined in `internal/transform`, and app wiring owns concrete registration.
|
||||||
|
- Publish/transform policy combinations use `config.ValidatePublishTransformPolicy`.
|
||||||
|
- Configured source selection for `validate` and `inspect` is shared in `source_select.go`.
|
||||||
|
|
||||||
|
Potential refinements:
|
||||||
|
|
||||||
|
- A normalized backend config view would make backend field resolution less repetitive across source and destination config.
|
||||||
|
- Transform and backend registries should remain separate; there is no evidence that a generic registry abstraction would help.
|
||||||
|
- No separate catalog package is needed for the current feature set.
|
||||||
|
|
||||||
|
## 8. Config and command-loading review
|
||||||
|
|
||||||
|
Config loading is reliable and strict:
|
||||||
|
|
||||||
|
- YAML known-field checking is enabled.
|
||||||
|
- Defaults are applied before validation.
|
||||||
|
- Validation collects multiple field errors.
|
||||||
|
- Secrets are loaded without mutating `os.Environ`.
|
||||||
|
- Explicit S3 credential references use the config-owned resolver.
|
||||||
|
|
||||||
|
Likely accidental duplication:
|
||||||
|
|
||||||
|
- Default config path selection and `config.LoadFile` are repeated in several app entrypoints.
|
||||||
|
- Secret loading is repeated in run, source diagnostics, and serve.
|
||||||
|
- Secret conflict warning projection is not represented by one runtime setup result.
|
||||||
|
|
||||||
|
Intentional differences:
|
||||||
|
|
||||||
|
- `serve` loads upload tokens and does not produce CLI JSON output.
|
||||||
|
- `validate` and `inspect` support local-path shortcut mode, while `run` and `serve` are config-driven.
|
||||||
|
- `manifest create` is local filesystem producer tooling and does not load app config.
|
||||||
|
|
||||||
|
Recommended cleanup:
|
||||||
|
|
||||||
|
- Centralize runtime config and secret setup in `internal/app`.
|
||||||
|
- Keep CLI flag parsing local to command files.
|
||||||
|
- Keep `manifest create` outside runtime config loading.
|
||||||
|
|
||||||
|
## 9. State, manifest, or progress handling review
|
||||||
|
|
||||||
|
Manifest handling is in good shape:
|
||||||
|
|
||||||
|
- `pkg/bundle` owns manifest parsing, digest grammar, source path validation, canonical bundle digest, local manifest building, and local bundle writing.
|
||||||
|
- `internal/bundle` delegates normalized manifest semantics to `pkg/bundle` and adds storage-backed validation.
|
||||||
|
- Destination state embeds the normalized manifest and validates through `internal/bundle`/`pkg/bundle`.
|
||||||
|
|
||||||
|
State handling is in good shape:
|
||||||
|
|
||||||
|
- `.distributor.json` parsing, validation, JSON projection, and comparison live in `internal/state`.
|
||||||
|
- Publish execution writes destination state only after outputs are written.
|
||||||
|
- Managed replacement deletes only state-listed outputs plus `.distributor.json`; forced replacement is explicit and bounded.
|
||||||
|
|
||||||
|
Progress/status handling:
|
||||||
|
|
||||||
|
- `RunReport` is the core run result model and supports JSON partial-result output.
|
||||||
|
- HTTP upload status is memory-only and documented as such.
|
||||||
|
- `PipelineRunCoordinator` and `UploadCoordinator` overlap conceptually but have different policies. Avoid merging unless product behavior converges.
|
||||||
|
|
||||||
|
Gaps:
|
||||||
|
|
||||||
|
- HTTP upload staging currently stores the request body in memory before queueing. This is both a quality gap and a mismatch with the intended ingestion boundary.
|
||||||
|
- There is no durable upload status, but this is documented as deferred work and should not be addressed in cleanup.
|
||||||
|
|
||||||
|
## 10. Refactors to avoid
|
||||||
|
|
||||||
|
Avoid these changes in the cleanup pass:
|
||||||
|
|
||||||
|
- Do not introduce a generic workflow engine or stage framework. The current explicit workflow is easier to audit.
|
||||||
|
- Do not add a CLI framework. The standard-library CLI is sufficient and policy-approved.
|
||||||
|
- Do not merge local, SSH, S3, and fake adapters behind a shared implementation layer. Their semantics differ enough that generic helpers would likely hide important behavior.
|
||||||
|
- Do not collapse `pkg/bundle` and `internal/bundle`. The public producer API and storage-backed distributor validation have different responsibilities.
|
||||||
|
- Do not move destination state comparison into `publish` or app orchestration.
|
||||||
|
- Do not redesign JSON output envelopes while doing cleanup.
|
||||||
|
- Do not add durable queues, retry workers, HTTP TLS, zstd, or browser UI under the banner of refactoring. These are feature work.
|
||||||
|
- Do not rewrite tests wholesale to use a new fixture system. Add helpers only where they reduce immediate duplication around changed code.
|
||||||
|
|
||||||
|
## 11. Recommended implementation sequence
|
||||||
|
|
||||||
|
1. HTTP upload staging boundary cleanup.
|
||||||
|
- Move supported content-type policy to `internal/ingest`.
|
||||||
|
- Stop buffering accepted uploads in `upload_http.go`.
|
||||||
|
- Queue staged bundle roots rather than request bodies.
|
||||||
|
- Extend HTTP upload tests first.
|
||||||
|
|
||||||
|
2. Runtime config setup helper.
|
||||||
|
- Add an app-level helper for default config path, config load, secret load, environment resolver, and secret warnings.
|
||||||
|
- Use it from `run`, configured `validate`/`inspect`, and `serve` where applicable.
|
||||||
|
- Preserve command-specific behavior.
|
||||||
|
|
||||||
|
3. Run destination processing extraction.
|
||||||
|
- Add small helpers for destination-scoped failure recording and plan identity normalization.
|
||||||
|
- Extract one-destination processing only if the helper remains readable.
|
||||||
|
- Preserve action ordering and report output.
|
||||||
|
|
||||||
|
4. Backend config normalized view.
|
||||||
|
- Add source/destination backend view helpers in `internal/config`.
|
||||||
|
- Use them for defaulting and validation if tests show the shape remains clear.
|
||||||
|
- Keep YAML structs and public config unchanged.
|
||||||
|
|
||||||
|
5. Bundle output projection cleanup.
|
||||||
|
- Add app-local helpers for file record and bundle summary projection.
|
||||||
|
- Use `time.RFC3339` consistently.
|
||||||
|
- Preserve command-specific JSON field names.
|
||||||
|
|
||||||
|
6. Archive/source path validation test alignment.
|
||||||
|
- Add mirrored path safety tests around ingestion and bundle path validation.
|
||||||
|
- Only centralize code if the helper does not blur archive directory semantics.
|
||||||
|
|
||||||
|
7. Coordinator intent cleanup.
|
||||||
|
- Decide whether `PipelineRunCoordinator` is retained for internal future use.
|
||||||
|
- If retained, clarify comments/docs. If removed, do it as a separate dead-code commit.
|
||||||
|
|
||||||
|
8. Test helper cleanup.
|
||||||
|
- Expand `internal/testutil` only for repeated setup touched by the previous refactors.
|
||||||
|
- Avoid moving every test fixture.
|
||||||
|
|
||||||
|
## 12. Test strategy
|
||||||
|
|
||||||
|
Tests to add before refactoring:
|
||||||
|
|
||||||
|
- HTTP upload handler test proving queue-full rejection does not consume the body.
|
||||||
|
- HTTP upload test proving accepted upload staging completes before `202 Accepted`.
|
||||||
|
- Ingestion content-type policy tests exposed through the new helper.
|
||||||
|
- Run report test covering destination open failure for multiple selected bundles.
|
||||||
|
- CLI JSON tests for `inspect` and `manifest create` timestamp formatting before projection cleanup.
|
||||||
|
|
||||||
|
Tests to run with each cleanup stage:
|
||||||
|
|
||||||
|
- HTTP upload cleanup: `go test ./internal/ingest ./internal/app ./internal/cli`
|
||||||
|
- Config setup cleanup: `go test ./internal/config ./internal/app ./internal/cli`
|
||||||
|
- Run processing cleanup: `go test ./internal/app ./internal/publish ./internal/state`
|
||||||
|
- Backend config view cleanup: `go test ./internal/config ./internal/app`
|
||||||
|
- Output projection cleanup: `go test ./internal/app ./internal/cli`
|
||||||
|
- Path validation cleanup: `go test ./pkg/bundle ./internal/bundle ./internal/ingest ./internal/storage`
|
||||||
|
- Final cleanup validation: `go test ./...`
|
||||||
|
|
||||||
|
Useful read-only checks:
|
||||||
|
|
||||||
|
- `rg -n "LoadFile\\(|LoadSecretEnvironment\\(|DefaultConfigPath" internal/app internal/cli`
|
||||||
|
- `rg -n "application/x-tar|application/gzip|application/x-gzip" internal docs`
|
||||||
|
- `rg -n "2006-01-02T15:04:05Z07:00" internal pkg`
|
||||||
|
- `rg -n "manifest.json|\\.distributor.json|StatePath|DisplayPath" internal pkg`
|
||||||
|
|
||||||
|
## 13. Appendix: findings not worth acting on
|
||||||
|
|
||||||
|
Adapter `ReadFile` and `WriteFile` wrappers:
|
||||||
|
|
||||||
|
- Local, SSH, S3, and fake backends each implement byte helpers in terms of stream helpers. This is small duplication but appropriate because each adapter owns error translation and metadata semantics.
|
||||||
|
|
||||||
|
Adapter traversal implementation:
|
||||||
|
|
||||||
|
- Local filesystem walking, SFTP walking, and S3 pagination look similar at the interface level but are semantically different. Keep traversal mechanics in adapters and shared callback behavior in `storage.WalkEmitter`.
|
||||||
|
|
||||||
|
State and manifest raw JSON parsing:
|
||||||
|
|
||||||
|
- `pkg/bundle` and `internal/state` both parse raw JSON with pointer fields to detect missing required fields. The schemas and error contexts differ, so a generic required-field parser would not be worth the complexity.
|
||||||
|
|
||||||
|
CLI help text:
|
||||||
|
|
||||||
|
- Help text repeats command names and flags. This is acceptable in a small hand-written CLI and keeps command files readable.
|
||||||
|
|
||||||
|
Test fixture strings:
|
||||||
|
|
||||||
|
- Some tests inline YAML snippets or expected output strings despite `internal/testutil`. Inline data is often clearer for edge cases. Only centralize fixture setup when tests are already being changed for a behavior-preserving refactor.
|
||||||
|
|
||||||
|
HTTP JSON response helpers:
|
||||||
|
|
||||||
|
- HTTP API responses use simple JSON objects rather than the CLI JSON envelope. This is intentional because HTTP status codes and route-specific responses are not the same public interface as CLI command output.
|
||||||
|
|
||||||
|
Public and internal bundle validation:
|
||||||
|
|
||||||
|
- `pkg/bundle.ValidateBundle` is local-filesystem producer validation; `internal/bundle.Validate` is storage-backed distributor validation. Keep both, with shared manifest semantics delegated through `pkg/bundle`.
|
||||||
400
docs/roadmap/cleanup.md
Normal file
400
docs/roadmap/cleanup.md
Normal file
@@ -0,0 +1,400 @@
|
|||||||
|
# Code Quality Cleanup Roadmap
|
||||||
|
|
||||||
|
## Current Baseline
|
||||||
|
|
||||||
|
The codebase has completed the local, SSH/SFTP, S3, public bundle package,
|
||||||
|
manifest creation, JSON output, path mapping, link generation, and HTTP upload
|
||||||
|
work documented in the current user and internal docs.
|
||||||
|
|
||||||
|
The audit in `docs/roadmap/audit.md` found no major architectural risk. The
|
||||||
|
remaining cleanup work should be narrow, behavior-preserving, and focused on
|
||||||
|
reducing drift in upload staging, runtime config setup, run reporting, backend
|
||||||
|
config handling, output projection, path validation tests, and internal
|
||||||
|
coordination code.
|
||||||
|
|
||||||
|
One intentional behavior change is part of this cleanup roadmap: malformed
|
||||||
|
authenticated upload archives should be rejected before `202 Accepted`, rather
|
||||||
|
than accepted and later marked failed. Valid staged uploads should still run
|
||||||
|
asynchronously after admission.
|
||||||
|
|
||||||
|
## Cleanup Principles
|
||||||
|
|
||||||
|
- Preserve public CLI behavior, config schema, manifest schema, destination
|
||||||
|
state schema, backend behavior, and JSON envelopes unless a stage explicitly
|
||||||
|
says otherwise.
|
||||||
|
- Keep config parsing and validation in `internal/config`.
|
||||||
|
- Keep CLI parsing in `internal/cli`.
|
||||||
|
- Keep upload archive policy in `internal/ingest`; keep HTTP routing,
|
||||||
|
authentication, and status projection in `internal/app`.
|
||||||
|
- Keep backend-specific filesystem, SSH/SFTP, and S3 behavior in adapter
|
||||||
|
packages.
|
||||||
|
- Prefer small package-local helpers over broad abstractions.
|
||||||
|
- Add or strengthen tests before refactoring behavior that affects public
|
||||||
|
output, upload admission, path safety, or run reporting.
|
||||||
|
|
||||||
|
## Active Cleanup Stages
|
||||||
|
|
||||||
|
Implement these stages in order. Each stage should be small enough for one
|
||||||
|
implementation prompt and should leave the repository passing the listed focused
|
||||||
|
tests before moving to the next stage.
|
||||||
|
|
||||||
|
## Stage 1: HTTP Upload Staging Boundary
|
||||||
|
|
||||||
|
Goal:
|
||||||
|
|
||||||
|
Move archive validation and upload body staging fully behind `internal/ingest`,
|
||||||
|
stop app-layer full-body buffering, and reject malformed archives before
|
||||||
|
returning `202 Accepted`.
|
||||||
|
|
||||||
|
Implementation scope:
|
||||||
|
|
||||||
|
- Add an ingestion-owned content-type helper, such as
|
||||||
|
`ValidateContentType(contentType string) error`, and remove duplicated
|
||||||
|
content-type policy from the HTTP handler.
|
||||||
|
- Replace the current handler-side `readUploadBody` buffering with streaming
|
||||||
|
staging through `internal/ingest`.
|
||||||
|
- Introduce a two-step upload coordinator admission model:
|
||||||
|
- reserve a run id and queue slot before consuming the request body;
|
||||||
|
- stage and validate the archive using that reserved run id;
|
||||||
|
- enqueue only a successfully staged local bundle root for async execution.
|
||||||
|
- Keep queue-full rejection before reading the body.
|
||||||
|
- Preserve `401` for missing or invalid bearer tokens, `415` for unsupported
|
||||||
|
content type, `413` for oversized uploads, and `503` for a full queue.
|
||||||
|
- Return a pre-acceptance `400` for malformed tar/gzip content or invalid
|
||||||
|
staged bundles.
|
||||||
|
- Preserve async queued/running/succeeded/failed status after a valid staged
|
||||||
|
bundle is accepted.
|
||||||
|
- Do not add durable queues, idempotency keys, zstd, or new routes.
|
||||||
|
|
||||||
|
Current-behavior documentation updates:
|
||||||
|
|
||||||
|
- Update `docs/cli.md`, `docs/config.md`, `docs/operations.md`,
|
||||||
|
`docs/troubleshooting.md`, `docs/internal/app.md`, and
|
||||||
|
`docs/internal/ingest.md` only as needed to describe the new
|
||||||
|
pre-acceptance failure boundary.
|
||||||
|
|
||||||
|
Tests:
|
||||||
|
|
||||||
|
- `go test ./internal/ingest ./internal/app ./internal/cli`
|
||||||
|
- Queue-full upload rejection does not read the request body.
|
||||||
|
- Unsupported content type is rejected through ingestion-owned policy.
|
||||||
|
- Oversized uploads return `413` and do not retain a staged run.
|
||||||
|
- Malformed tar/gzip content returns `400` before a run id is issued.
|
||||||
|
- Valid tar and tar.gz uploads return `202` after staging and still transition
|
||||||
|
through async status.
|
||||||
|
- HTTP responses and status records do not leak bearer tokens or secret values.
|
||||||
|
|
||||||
|
Completion criteria:
|
||||||
|
|
||||||
|
- `internal/app` no longer buffers the full upload body before staging.
|
||||||
|
- A valid accepted upload has a committed staged bundle root before the `202`
|
||||||
|
response is sent.
|
||||||
|
- Invalid archive content cannot create an accepted run id.
|
||||||
|
|
||||||
|
## Stage 2: Runtime Config And Secret Setup Helper
|
||||||
|
|
||||||
|
Goal:
|
||||||
|
|
||||||
|
Centralize runtime config path resolution, config loading, secret loading,
|
||||||
|
environment resolver creation, and secret-conflict warning projection in one
|
||||||
|
app-layer helper.
|
||||||
|
|
||||||
|
Implementation scope:
|
||||||
|
|
||||||
|
- Add a small `internal/app` runtime setup helper that:
|
||||||
|
- defaults an empty config path to `config.DefaultConfigPath`;
|
||||||
|
- calls `config.LoadFile`;
|
||||||
|
- calls `config.LoadSecretEnvironment`;
|
||||||
|
- exposes the loaded config, config path, `config.Environment`, and
|
||||||
|
`[]OutputWarning` for secret conflicts.
|
||||||
|
- Use the helper from `Run`, `RunPipeline`, `RunPipelineWithLocalSource`,
|
||||||
|
configured `Validate`/`Inspect`, and `Serve` where applicable.
|
||||||
|
- Keep `manifest create` outside runtime config loading.
|
||||||
|
- Keep YAML structs, defaults, validation, and secret-directory parsing in
|
||||||
|
`internal/config`.
|
||||||
|
- Preserve app test injection points for backend factories and upload handler
|
||||||
|
tests.
|
||||||
|
|
||||||
|
Current-behavior documentation updates:
|
||||||
|
|
||||||
|
- Update `docs/internal/app.md` if helper boundaries or flow descriptions
|
||||||
|
change. User-facing docs should not change unless observable behavior changes.
|
||||||
|
|
||||||
|
Tests:
|
||||||
|
|
||||||
|
- `go test ./internal/config ./internal/app ./internal/cli`
|
||||||
|
- Default config path behavior remains unchanged.
|
||||||
|
- Secret conflict warnings still appear in text and JSON output for `run`,
|
||||||
|
configured `validate`, and configured `inspect`.
|
||||||
|
- `serve` still fails startup safely for missing, empty, or duplicate upload
|
||||||
|
tokens without leaking values.
|
||||||
|
- Explicit S3 credential references still resolve through the config-owned
|
||||||
|
environment resolver.
|
||||||
|
|
||||||
|
Completion criteria:
|
||||||
|
|
||||||
|
- Runtime commands no longer repeat config path defaulting and secret loading.
|
||||||
|
- Config policy remains owned by `internal/config`.
|
||||||
|
|
||||||
|
## Stage 3: Run Destination Processing Extraction
|
||||||
|
|
||||||
|
Goal:
|
||||||
|
|
||||||
|
Reduce complexity in the main run loop while preserving run report behavior,
|
||||||
|
warning ordering, action ordering, failure aggregation, and text/JSON output.
|
||||||
|
|
||||||
|
Implementation scope:
|
||||||
|
|
||||||
|
- Extract narrow helpers from `internal/app/run.go` for destination-scoped
|
||||||
|
processing.
|
||||||
|
- Centralize destination-scoped failure recording so one helper updates
|
||||||
|
`runFailures`, `runSummary`, `RunReport.Actions`, and pipeline events.
|
||||||
|
- Centralize normalization of partial `publish.Plan` identity fields before
|
||||||
|
converting plans to run action records.
|
||||||
|
- Keep app orchestration explicit; do not introduce a generic workflow engine,
|
||||||
|
stage framework, or broad runner abstraction.
|
||||||
|
- Preserve independent destination fan-out and partial-result behavior.
|
||||||
|
|
||||||
|
Current-behavior documentation updates:
|
||||||
|
|
||||||
|
- Update `docs/internal/app.md` only if helper names or package layout
|
||||||
|
descriptions materially change.
|
||||||
|
|
||||||
|
Tests:
|
||||||
|
|
||||||
|
- `go test ./internal/app ./internal/publish ./internal/state`
|
||||||
|
- Destination open failures for multiple selected bundles keep action records,
|
||||||
|
output errors, summary counters, and pipeline events aligned.
|
||||||
|
- JSON partial-result output remains unchanged when destination planning or
|
||||||
|
execution fails after a report exists.
|
||||||
|
- Fixed-path dry-run warnings appear in the same order as before.
|
||||||
|
- Existing run text output assertions continue to pass.
|
||||||
|
|
||||||
|
Completion criteria:
|
||||||
|
|
||||||
|
- `run.go` delegates destination-scoped record/failure bookkeeping to helpers.
|
||||||
|
- No public output shape or ordering changes.
|
||||||
|
|
||||||
|
## Stage 4: Backend Config Normalized View
|
||||||
|
|
||||||
|
Goal:
|
||||||
|
|
||||||
|
Reduce source/destination backend config drift while preserving the current YAML
|
||||||
|
schema and public config behavior.
|
||||||
|
|
||||||
|
Implementation scope:
|
||||||
|
|
||||||
|
- Add package-local normalized backend view helpers in `internal/config` for
|
||||||
|
source and destination backend fields.
|
||||||
|
- Use the normalized view to reduce duplication in backend defaulting and
|
||||||
|
validation where it remains clearer than the current paired code.
|
||||||
|
- Keep `config.Backend` and `config.Destination` YAML structs and tags
|
||||||
|
unchanged.
|
||||||
|
- Preserve destination-only policy fields on `Destination`.
|
||||||
|
- Preserve `http_upload` as source-only and invalid for destinations.
|
||||||
|
- Update app backend opening only if the normalized view provides clearer
|
||||||
|
handoff without leaking config internals.
|
||||||
|
|
||||||
|
Current-behavior documentation updates:
|
||||||
|
|
||||||
|
- None expected unless internal docs mention the old paired implementation
|
||||||
|
shape in a way that becomes misleading.
|
||||||
|
|
||||||
|
Tests:
|
||||||
|
|
||||||
|
- `go test ./internal/config ./internal/app`
|
||||||
|
- Equivalent local, SSH, and S3 source/destination validation remains
|
||||||
|
consistent.
|
||||||
|
- Defaults for SSH port/host key policy, S3 region/prefix/force-path-style, and
|
||||||
|
HTTP upload staging fields remain unchanged.
|
||||||
|
- `http_upload` remains valid only for sources.
|
||||||
|
|
||||||
|
Completion criteria:
|
||||||
|
|
||||||
|
- Adding a future backend field has one obvious defaulting/validation path.
|
||||||
|
- Public config files and examples continue to load unchanged.
|
||||||
|
|
||||||
|
## Stage 5: Command Output Projection Cleanup
|
||||||
|
|
||||||
|
Goal:
|
||||||
|
|
||||||
|
Reduce drift in bundle and file metadata projection for app command JSON
|
||||||
|
results.
|
||||||
|
|
||||||
|
Implementation scope:
|
||||||
|
|
||||||
|
- Add small app-local projection helpers for bundle summaries and manifest file
|
||||||
|
records used by `validate`, `inspect`, and `manifest create`.
|
||||||
|
- Use `time.RFC3339` consistently instead of equivalent literal layouts.
|
||||||
|
- Preserve existing JSON envelope fields, command names, command-specific result
|
||||||
|
field names, text output, and fatal error behavior.
|
||||||
|
- Do not redesign CLI JSON output or HTTP JSON responses.
|
||||||
|
|
||||||
|
Current-behavior documentation updates:
|
||||||
|
|
||||||
|
- None expected unless tests reveal current docs are stale.
|
||||||
|
|
||||||
|
Tests:
|
||||||
|
|
||||||
|
- `go test ./internal/app ./internal/cli`
|
||||||
|
- JSON output for `validate`, `inspect`, and `manifest create` remains
|
||||||
|
structurally stable.
|
||||||
|
- RFC3339 timestamps remain unchanged, including offset-preserving source
|
||||||
|
timestamps where current behavior preserves them.
|
||||||
|
- Text output remains unchanged.
|
||||||
|
|
||||||
|
Completion criteria:
|
||||||
|
|
||||||
|
- Bundle/file projection logic is shared where semantics match.
|
||||||
|
- Command-specific result structs remain easy to read.
|
||||||
|
|
||||||
|
## Stage 6: Archive And Source Path Validation Alignment
|
||||||
|
|
||||||
|
Goal:
|
||||||
|
|
||||||
|
Protect path safety by aligning archive path tests with source and storage path
|
||||||
|
policy, without blurring archive-specific rules.
|
||||||
|
|
||||||
|
Implementation scope:
|
||||||
|
|
||||||
|
- Add mirrored path-safety table tests around `internal/ingest`, `pkg/bundle`,
|
||||||
|
`internal/bundle`, and `internal/storage` where useful.
|
||||||
|
- Keep archive-specific directory handling, root-level manifest rules, duplicate
|
||||||
|
file rejection, symlink rejection, hardlink rejection, and special-entry
|
||||||
|
rejection in `internal/ingest`.
|
||||||
|
- Centralize code only if the helper can preserve clear archive semantics and
|
||||||
|
current error behavior.
|
||||||
|
- Do not add new public `pkg/bundle` APIs unless the existing public API cannot
|
||||||
|
safely support the needed shared behavior.
|
||||||
|
|
||||||
|
Current-behavior documentation updates:
|
||||||
|
|
||||||
|
- None expected unless implementation changes error boundaries or internal
|
||||||
|
package descriptions.
|
||||||
|
|
||||||
|
Tests:
|
||||||
|
|
||||||
|
- `go test ./pkg/bundle ./internal/bundle ./internal/ingest ./internal/storage`
|
||||||
|
- Absolute paths, traversal, backslashes, empty paths, dot segments, nested
|
||||||
|
manifests, `.distributor.json` handling, symlinks, hardlinks, devices, and
|
||||||
|
sockets remain covered.
|
||||||
|
- Archive directories remain accepted where safe.
|
||||||
|
|
||||||
|
Completion criteria:
|
||||||
|
|
||||||
|
- Path safety policy has regression coverage across archive staging, source
|
||||||
|
bundle validation, and storage logical path validation.
|
||||||
|
- Any code sharing is smaller and clearer than the duplicated logic it replaces.
|
||||||
|
|
||||||
|
## Stage 7: Pipeline Run Coordinator Removal
|
||||||
|
|
||||||
|
Goal:
|
||||||
|
|
||||||
|
Remove the currently unused internal `PipelineRunCoordinator` to avoid
|
||||||
|
maintaining two similar coordination concepts.
|
||||||
|
|
||||||
|
Implementation scope:
|
||||||
|
|
||||||
|
- Delete `PipelineRunCoordinator`, `PipelineRunRecord`,
|
||||||
|
`DuplicatePipelineRunError`, related helpers, and their tests.
|
||||||
|
- Remove or rewrite `docs/internal/app.md` sections that describe the removed
|
||||||
|
coordinator.
|
||||||
|
- Keep `UploadCoordinator`; do not merge upload queueing with the removed
|
||||||
|
duplicate-run coordinator.
|
||||||
|
- Before deletion, confirm with `rg` that production code does not reference
|
||||||
|
`NewPipelineRunCoordinator`, `PipelineRunCoordinator`, or
|
||||||
|
`DuplicatePipelineRunError`.
|
||||||
|
|
||||||
|
Current-behavior documentation updates:
|
||||||
|
|
||||||
|
- Update `docs/internal/app.md` because it currently documents the coordinator
|
||||||
|
as an internal implemented component.
|
||||||
|
|
||||||
|
Tests:
|
||||||
|
|
||||||
|
- `go test ./internal/app ./internal/cli`
|
||||||
|
- `rg -n "PipelineRunCoordinator|NewPipelineRunCoordinator|DuplicatePipelineRunError" internal docs`
|
||||||
|
should show no stale references after removal.
|
||||||
|
|
||||||
|
Completion criteria:
|
||||||
|
|
||||||
|
- No production, test, or internal documentation references remain for the
|
||||||
|
removed coordinator.
|
||||||
|
- Upload coordination behavior is unchanged.
|
||||||
|
|
||||||
|
## Stage 8: Narrow CLI And Test Helper Cleanup
|
||||||
|
|
||||||
|
Goal:
|
||||||
|
|
||||||
|
Apply only low-risk CLI setup and test fixture cleanup that remains useful after
|
||||||
|
the earlier stages.
|
||||||
|
|
||||||
|
Implementation scope:
|
||||||
|
|
||||||
|
- Add tiny CLI helpers for repeated `flag.FlagSet` setup or output-format
|
||||||
|
parsing only where command behavior remains obvious.
|
||||||
|
- Keep the standard-library CLI; do not introduce a CLI framework.
|
||||||
|
- Keep `manifest create` interspersed positional parsing local unless another
|
||||||
|
command now needs the same parsing behavior.
|
||||||
|
- Expand `internal/testutil` only for repeated setup touched by earlier stages.
|
||||||
|
- Do not rewrite tests wholesale just to use shared helpers.
|
||||||
|
|
||||||
|
Current-behavior documentation updates:
|
||||||
|
|
||||||
|
- None expected unless CLI help or syntax changes. This stage should avoid such
|
||||||
|
changes.
|
||||||
|
|
||||||
|
Tests:
|
||||||
|
|
||||||
|
- `go test ./internal/cli ./internal/app`
|
||||||
|
- CLI usage-error tests remain stable.
|
||||||
|
- `manifest create <path> --id x`, `manifest create --id x <path>`, missing
|
||||||
|
flag values, invalid `--format`, and help output remain covered.
|
||||||
|
|
||||||
|
Completion criteria:
|
||||||
|
|
||||||
|
- Remaining CLI/test cleanup is small, readable, and behavior-preserving.
|
||||||
|
- No public CLI syntax or output changes.
|
||||||
|
|
||||||
|
## Refactors To Avoid
|
||||||
|
|
||||||
|
- Do not introduce a generic workflow engine or stage framework.
|
||||||
|
- Do not add a CLI framework.
|
||||||
|
- Do not merge local, SSH, S3, and fake backend adapter implementations.
|
||||||
|
- Do not collapse `pkg/bundle` and `internal/bundle`.
|
||||||
|
- Do not move destination state comparison into `internal/publish` or
|
||||||
|
`internal/app`.
|
||||||
|
- Do not redesign CLI JSON envelopes.
|
||||||
|
- Do not change HTTP JSON response shapes except where Stage 1 requires
|
||||||
|
pre-acceptance error behavior.
|
||||||
|
- Do not add durable upload queues, retry workers, zstd support, in-app TLS,
|
||||||
|
idempotency keys, browser UI, or other feature work.
|
||||||
|
- Do not rewrite tests wholesale to use new fixture helpers.
|
||||||
|
|
||||||
|
## Validation
|
||||||
|
|
||||||
|
After each implementation stage, run the stage-specific tests listed above.
|
||||||
|
|
||||||
|
After all cleanup stages:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go test ./...
|
||||||
|
```
|
||||||
|
|
||||||
|
Recommended consistency checks:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
rg -n "LoadFile\\(|LoadSecretEnvironment\\(|DefaultConfigPath" internal/app internal/cli
|
||||||
|
rg -n "application/x-tar|application/gzip|application/x-gzip" internal docs
|
||||||
|
rg -n "2006-01-02T15:04:05Z07:00" internal pkg
|
||||||
|
rg -n "PipelineRunCoordinator|NewPipelineRunCoordinator|DuplicatePipelineRunError" internal docs
|
||||||
|
```
|
||||||
|
|
||||||
|
The cleanup is complete when:
|
||||||
|
|
||||||
|
- all staged tests and `go test ./...` pass;
|
||||||
|
- current-behavior docs describe the implemented Stage 1 upload failure
|
||||||
|
boundary;
|
||||||
|
- `docs/roadmap/audit.md` findings have either been addressed or consciously
|
||||||
|
left in place as noted in this cleanup roadmap;
|
||||||
|
- no completed cleanup behavior is documented only as future work.
|
||||||
60
docs/roadmap/http.md
Normal file
60
docs/roadmap/http.md
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
# Roadmap: HTTP Upload Extensions
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
The HTTP upload API is implemented. Current behavior is documented in:
|
||||||
|
|
||||||
|
- [CLI](../cli.md)
|
||||||
|
- [Configuration](../config.md)
|
||||||
|
- [Operations](../operations.md)
|
||||||
|
- [Troubleshooting](../troubleshooting.md)
|
||||||
|
- [Application internals](../internal/app.md)
|
||||||
|
- [Ingestion internals](../internal/ingest.md)
|
||||||
|
|
||||||
|
This roadmap records HTTP upload extensions that are intentionally not part of
|
||||||
|
the current implementation.
|
||||||
|
|
||||||
|
## Deferred Extensions
|
||||||
|
|
||||||
|
### Authentication
|
||||||
|
|
||||||
|
- URL-token authentication for constrained clients.
|
||||||
|
- Additional token lifecycle tooling.
|
||||||
|
- Mutual TLS or other in-app identity mechanisms.
|
||||||
|
|
||||||
|
### Archive Formats
|
||||||
|
|
||||||
|
- Zstandard-compressed tar archives.
|
||||||
|
- Additional content negotiation rules for future archive formats.
|
||||||
|
|
||||||
|
### Status And Queue Durability
|
||||||
|
|
||||||
|
- Durable status persistence across process restarts.
|
||||||
|
- Database-backed queueing.
|
||||||
|
- Recovery semantics for queued or running uploads after a restart.
|
||||||
|
|
||||||
|
### Producer Coordination
|
||||||
|
|
||||||
|
- Producer-supplied idempotency keys.
|
||||||
|
- Run retry endpoints.
|
||||||
|
- Run cancellation endpoints.
|
||||||
|
- Run listing endpoints.
|
||||||
|
|
||||||
|
### Deployment Surface
|
||||||
|
|
||||||
|
- In-app TLS.
|
||||||
|
- Public exposure defaults.
|
||||||
|
- Browser UI.
|
||||||
|
|
||||||
|
## Boundaries
|
||||||
|
|
||||||
|
Current HTTP upload behavior remains intentionally small:
|
||||||
|
|
||||||
|
- `http_upload` is source-only and is not a durable storage backend.
|
||||||
|
- Upload status is memory-only.
|
||||||
|
- Producers submit complete tar or gzip-compressed tar source bundles.
|
||||||
|
- Producers authenticate with `Authorization: Bearer <token>`.
|
||||||
|
- Public access policy, TLS termination, and rate limiting belong outside
|
||||||
|
`distributor` unless a future roadmap explicitly changes that boundary.
|
||||||
|
|
||||||
|
Do not document deferred extensions as available outside `docs/roadmap/`.
|
||||||
@@ -1,62 +1,34 @@
|
|||||||
# Implementation Roadmap
|
# HTTP Upload Deferred Work
|
||||||
|
|
||||||
This roadmap records current implementation status and deferred work for
|
## Purpose
|
||||||
`distributor`. Implemented behavior is documented in the user, operator, and
|
|
||||||
internal documentation listed below.
|
|
||||||
|
|
||||||
Canonical current-behavior docs:
|
HTTP upload behavior is implemented and documented in the current-behavior
|
||||||
|
manuals:
|
||||||
|
|
||||||
- `README.md`
|
- [CLI](../cli.md)
|
||||||
- `docs/cli.md`
|
- [Configuration](../config.md)
|
||||||
- `docs/config.md`
|
- [Operations](../operations.md)
|
||||||
- `docs/operations.md`
|
- [Troubleshooting](../troubleshooting.md)
|
||||||
- `docs/troubleshooting.md`
|
- [Application internals](../internal/app.md)
|
||||||
- `docs/internal/`
|
- [Configuration internals](../internal/config.md)
|
||||||
- `docs/integrations/markdown.md`
|
- [Ingestion internals](../internal/ingest.md)
|
||||||
- `docs/policy/`
|
|
||||||
- `examples/`
|
|
||||||
|
|
||||||
Future, planned, or aspirational behavior belongs under `docs/roadmap/` until
|
This file tracks only HTTP upload work that is not implemented.
|
||||||
it is implemented.
|
|
||||||
|
|
||||||
## Current State
|
|
||||||
|
|
||||||
`distributor` is ready for routine use against producer pipelines using the
|
|
||||||
implemented local, SSH/SFTP, and S3-compatible backends.
|
|
||||||
|
|
||||||
## Active Roadmap
|
|
||||||
|
|
||||||
There are no active implementation items in this roadmap.
|
|
||||||
|
|
||||||
Before implementing new product behavior, add a focused roadmap entry when the
|
|
||||||
work changes storage semantics, config, CLI behavior, state schema, transform
|
|
||||||
behavior, notification behavior, operational safety, or user-visible workflows.
|
|
||||||
Keep those entries out of current-behavior docs until the behavior exists.
|
|
||||||
|
|
||||||
## Deferred Work
|
## Deferred Work
|
||||||
|
|
||||||
These items are not implemented and should stay out of current-behavior docs
|
- URL-token authentication.
|
||||||
until a roadmap entry is selected and implemented:
|
- Zstandard-compressed archive support.
|
||||||
|
- Durable status persistence across process restarts.
|
||||||
|
- Database-backed queueing.
|
||||||
|
- Producer-supplied idempotency keys.
|
||||||
|
- Run listing, cancellation, and retry endpoints.
|
||||||
|
- In-app TLS.
|
||||||
|
- Public network exposure defaults.
|
||||||
|
- Browser UI.
|
||||||
|
|
||||||
- external notification adapters;
|
## Documentation Rule
|
||||||
- warning-only digest mismatch handling;
|
|
||||||
- additional auth mechanisms beyond the implemented SSH and S3 credential
|
|
||||||
paths;
|
|
||||||
- compatibility parsing for legacy SSH URI config;
|
|
||||||
- broad recursive destination deletion outside managed bundle paths;
|
|
||||||
- concurrent fan-out publishing;
|
|
||||||
- streaming, resumable, or multipart S3 uploads;
|
|
||||||
- cloud-provider-specific IAM integration docs;
|
|
||||||
- repository-managed packaging, release, and deployment automation.
|
|
||||||
|
|
||||||
## Roadmap Maintenance
|
Deferred behavior belongs under `docs/roadmap/` until implemented. Current
|
||||||
|
behavior docs must describe only the active HTTP upload API, configuration,
|
||||||
When adding future roadmap work:
|
operation, troubleshooting, and internal package contracts.
|
||||||
|
|
||||||
- describe user-visible behavior and safety boundaries;
|
|
||||||
- define which existing docs must change after implementation;
|
|
||||||
- keep examples secret-free and runnable or clearly environment-gated;
|
|
||||||
- avoid workflow labels in production code, tests, config fields, and user
|
|
||||||
documentation;
|
|
||||||
- run focused tests for the changed behavior and `go test ./...` for
|
|
||||||
cross-package changes.
|
|
||||||
|
|||||||
@@ -26,7 +26,10 @@ Safe fix: compare the file to the reference in [configuration](config.md) and re
|
|||||||
|
|
||||||
## `validate config ... backend ... is unsupported`
|
## `validate config ... backend ... is unsupported`
|
||||||
|
|
||||||
Likely cause: a source or destination uses a backend name other than `local`, `ssh`, or `s3`.
|
Likely cause: a source or destination uses an unsupported backend name, or a
|
||||||
|
command is trying to execute a backend that is valid only for another workflow.
|
||||||
|
`run`, `validate`, and `inspect` execute `local`, `ssh`, and `s3` sources.
|
||||||
|
`serve` executes `http_upload` sources.
|
||||||
|
|
||||||
Diagnostic:
|
Diagnostic:
|
||||||
|
|
||||||
@@ -34,7 +37,188 @@ Diagnostic:
|
|||||||
rg -n "backend:" <config-path>
|
rg -n "backend:" <config-path>
|
||||||
```
|
```
|
||||||
|
|
||||||
Safe fix: use `backend: local`, `backend: ssh`, or `backend: s3` for executable workflows.
|
Safe fix: use `backend: local`, `backend: ssh`, or `backend: s3` for normal
|
||||||
|
source and destination workflows. Use `backend: http_upload` only for sources
|
||||||
|
handled by `distributor serve`.
|
||||||
|
|
||||||
|
## `bind HTTP server ... address already in use`
|
||||||
|
|
||||||
|
Likely cause: another process is already listening on `server.http.bind`.
|
||||||
|
|
||||||
|
Diagnostic:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
ss -ltnp | rg '<port>'
|
||||||
|
```
|
||||||
|
|
||||||
|
Safe fix: stop the conflicting process or configure a different
|
||||||
|
`server.http.bind` value. The default bind address is `127.0.0.1:8080`.
|
||||||
|
|
||||||
|
## `upload token environment variable ... is not set`
|
||||||
|
|
||||||
|
Likely cause: a configured `http_upload` source references `token_env`, but the
|
||||||
|
variable is absent from both the real process environment and
|
||||||
|
`secrets.directory`.
|
||||||
|
|
||||||
|
Diagnostic:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
env | cut -d= -f1 | rg '^<token-variable>$'
|
||||||
|
ls -l <secrets-directory>/<token-variable>
|
||||||
|
```
|
||||||
|
|
||||||
|
Safe fix: set the real environment variable or create a readable
|
||||||
|
secrets-directory file with the same name. Do not place literal token values in
|
||||||
|
YAML.
|
||||||
|
|
||||||
|
## `upload token environment variables ... resolve to the same value`
|
||||||
|
|
||||||
|
Likely cause: two configured `http_upload` pipelines resolve to the same bearer
|
||||||
|
token value.
|
||||||
|
|
||||||
|
Diagnostic:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
rg -n 'token_env:' <config-path>
|
||||||
|
```
|
||||||
|
|
||||||
|
Safe fix: assign a distinct non-empty token value to each `http_upload`
|
||||||
|
pipeline. Distributor does not print the duplicate token value.
|
||||||
|
|
||||||
|
## `POST /upload` returns `401`
|
||||||
|
|
||||||
|
Likely cause: the request is missing `Authorization: Bearer <token>` or the
|
||||||
|
token does not match any configured `http_upload` pipeline.
|
||||||
|
|
||||||
|
Diagnostic:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -i -X POST http://127.0.0.1:8080/upload \
|
||||||
|
-H "Authorization: Bearer $DISTRIBUTOR_UPLOAD_TOKEN" \
|
||||||
|
-H "Content-Type: application/x-tar" \
|
||||||
|
--data-binary @bundle.tar
|
||||||
|
```
|
||||||
|
|
||||||
|
Safe fix: use the token value resolved by the configured `token_env`. Do not
|
||||||
|
include token values in logs or tickets.
|
||||||
|
|
||||||
|
## `POST /upload` returns `413`
|
||||||
|
|
||||||
|
Likely cause: the request body exceeds the selected pipeline's
|
||||||
|
`source.max_upload_size` or the default `server.http.max_upload_size`.
|
||||||
|
|
||||||
|
Diagnostic:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
ls -lh bundle.tar bundle.tar.gz
|
||||||
|
rg -n 'max_upload_size:' <config-path>
|
||||||
|
```
|
||||||
|
|
||||||
|
Safe fix: upload a smaller archive, remove unnecessary files from the source
|
||||||
|
bundle, or raise the configured upload size limit.
|
||||||
|
|
||||||
|
## `POST /upload` returns `415`
|
||||||
|
|
||||||
|
Likely cause: the upload uses an unsupported content type. The server accepts
|
||||||
|
uncompressed tar and gzip-compressed tar archives only.
|
||||||
|
|
||||||
|
Diagnostic:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
file bundle.tar.gz
|
||||||
|
```
|
||||||
|
|
||||||
|
Safe fix: send `Content-Type: application/x-tar`, `application/gzip`, or
|
||||||
|
`application/x-gzip`, matching the archive format.
|
||||||
|
|
||||||
|
## `POST /upload` returns `503`
|
||||||
|
|
||||||
|
Likely cause: the in-memory upload queue is full.
|
||||||
|
|
||||||
|
Diagnostic:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
rg -n 'queue_size|max_concurrency' <config-path>
|
||||||
|
```
|
||||||
|
|
||||||
|
Safe fix: retry after active uploads finish, or increase `server.http.queue_size`
|
||||||
|
for the deployment.
|
||||||
|
|
||||||
|
## `GET /runs/<run_id>` returns `404`
|
||||||
|
|
||||||
|
Likely cause: the run id is wrong, the process restarted, or the completed
|
||||||
|
status record expired after `server.http.retention`.
|
||||||
|
|
||||||
|
Diagnostic:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -i http://127.0.0.1:8080/runs/<run-id>
|
||||||
|
rg -n 'retention:' <config-path>
|
||||||
|
```
|
||||||
|
|
||||||
|
Safe fix: use the exact `run_id` returned by `POST /upload`. If status retention
|
||||||
|
is too short for operators, increase `server.http.retention`.
|
||||||
|
|
||||||
|
## `--format: format must be text or json`
|
||||||
|
|
||||||
|
Likely cause: a command was run with an unsupported output format.
|
||||||
|
|
||||||
|
Diagnostic:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/distributor run --help
|
||||||
|
```
|
||||||
|
|
||||||
|
Safe fix: use `--format text` or `--format json`. Help and usage output are always text.
|
||||||
|
|
||||||
|
## `--format json` wrote no JSON output
|
||||||
|
|
||||||
|
Likely cause: the command failed before it could construct a result, such as a missing config file, invalid arguments, unreadable secrets directory, or source setup failure.
|
||||||
|
|
||||||
|
Diagnostic:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/distributor run --config <config-path> --format json
|
||||||
|
```
|
||||||
|
|
||||||
|
Safe fix: read the stderr error and fix the setup problem. JSON mode writes a document only after the command has enough information to construct a result.
|
||||||
|
|
||||||
|
## `configured source mode requires --pipeline`
|
||||||
|
|
||||||
|
Likely cause: `validate` or `inspect` was run with `--config` but without an explicit pipeline id.
|
||||||
|
|
||||||
|
Diagnostic:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/distributor validate --help
|
||||||
|
go run ./cmd/distributor inspect --help
|
||||||
|
```
|
||||||
|
|
||||||
|
Safe fix: add `--pipeline <pipeline-id>`. Configured source diagnostics require an explicit pipeline even when the config contains one pipeline.
|
||||||
|
|
||||||
|
## `does not accept a local path with --config, --pipeline, or --bundle`
|
||||||
|
|
||||||
|
Likely cause: local-path mode and configured source mode were mixed in one `validate` or `inspect` command.
|
||||||
|
|
||||||
|
Diagnostic:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/distributor inspect --help
|
||||||
|
```
|
||||||
|
|
||||||
|
Safe fix: use either `distributor inspect <local-path>` or `distributor inspect --config <path> --pipeline <id>`, not both.
|
||||||
|
|
||||||
|
## `--format json` exited non-zero with `ok: false`
|
||||||
|
|
||||||
|
Likely cause: `run` began planning or executing destinations, and at least one destination failed while other destination results were still available.
|
||||||
|
|
||||||
|
Diagnostic:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/distributor run --config <config-path> --format json
|
||||||
|
```
|
||||||
|
|
||||||
|
Safe fix: inspect the top-level `errors` array, `result.actions`, and `result.summary`. Fix the failed destination, then preview with `--dry-run --format json` before retrying.
|
||||||
|
|
||||||
## `prefix must be a clean relative slash-separated path`
|
## `prefix must be a clean relative slash-separated path`
|
||||||
|
|
||||||
@@ -198,21 +382,33 @@ ssh-keygen -F <host> -f <known-hosts-path>
|
|||||||
|
|
||||||
Safe fix: verify the server identity out of band before updating `known_hosts`. Do not switch to `host_key_policy: off` to bypass an unexpected changed key.
|
Safe fix: verify the server identity out of band before updating `known_hosts`. Do not switch to `host_key_policy: off` to bypass an unexpected changed key.
|
||||||
|
|
||||||
## `stat ssh ... not_found` or `no bundles found`
|
## `pipeline "<id>" not found`
|
||||||
|
|
||||||
Likely cause: the configured SSH `path` is wrong, unreadable, or does not contain source bundles.
|
Likely cause: configured source validation or inspection requested a pipeline id that is not present in the config file.
|
||||||
|
|
||||||
Diagnostic:
|
Diagnostic:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sftp <user>@<host>
|
rg -n "id:" <config-path>
|
||||||
```
|
```
|
||||||
|
|
||||||
Safe fix: correct the remote root `path`, permissions, or source bundle location.
|
Safe fix: pass an existing pipeline id with `--pipeline`, or update the config.
|
||||||
|
|
||||||
|
## `stat ssh ... not_found`, `stat s3 ... not_found`, or `no bundles found`
|
||||||
|
|
||||||
|
Likely cause: the configured source root is wrong, unreadable, or does not contain source bundles.
|
||||||
|
|
||||||
|
Diagnostic:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go run ./cmd/distributor validate --config <config-path> --pipeline <pipeline-id>
|
||||||
|
```
|
||||||
|
|
||||||
|
Safe fix: correct the configured source root, S3 prefix, permissions, or source bundle location. Use `--bundle <path>` only with a source-root-relative bundle directory that contains `manifest.json`.
|
||||||
|
|
||||||
## `validate command requires a path` or `inspect command requires a path`
|
## `validate command requires a path` or `inspect command requires a path`
|
||||||
|
|
||||||
Likely cause: `validate` or `inspect` was run without a path.
|
Likely cause: `validate` or `inspect` was run without a local path and without configured source mode.
|
||||||
|
|
||||||
Diagnostic:
|
Diagnostic:
|
||||||
|
|
||||||
@@ -221,7 +417,7 @@ go run ./cmd/distributor validate --help
|
|||||||
go run ./cmd/distributor inspect --help
|
go run ./cmd/distributor inspect --help
|
||||||
```
|
```
|
||||||
|
|
||||||
Safe fix: pass a local source bundle directory or a local tree containing source bundles.
|
Safe fix: pass a local source bundle directory or local tree, or pass both `--config <path>` and `--pipeline <id>`.
|
||||||
|
|
||||||
## `no bundles found under "."`
|
## `no bundles found under "."`
|
||||||
|
|
||||||
|
|||||||
29
examples/archive-and-latest.yml
Normal file
29
examples/archive-and-latest.yml
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
pipelines:
|
||||||
|
- id: example-archive-and-latest
|
||||||
|
source:
|
||||||
|
backend: local
|
||||||
|
path: examples/source-bundle
|
||||||
|
destinations:
|
||||||
|
- id: local-source-archive
|
||||||
|
backend: local
|
||||||
|
path: workspace/published/archive-and-latest/archive
|
||||||
|
path_mapping:
|
||||||
|
mode: preserve_relative
|
||||||
|
publish:
|
||||||
|
source: true
|
||||||
|
html: false
|
||||||
|
- id: local-html-latest
|
||||||
|
backend: local
|
||||||
|
path: workspace/published/archive-and-latest/latest
|
||||||
|
path_mapping:
|
||||||
|
mode: fixed
|
||||||
|
links:
|
||||||
|
base_url: https://reports.example.com/latest
|
||||||
|
primary: auto
|
||||||
|
publish:
|
||||||
|
source: false
|
||||||
|
html: true
|
||||||
|
transform:
|
||||||
|
markdown_to_html:
|
||||||
|
enabled: true
|
||||||
|
mode: index
|
||||||
24
examples/http-upload-local.yml
Normal file
24
examples/http-upload-local.yml
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
# Local HTTP upload example.
|
||||||
|
# Set DISTRIBUTOR_EXAMPLE_UPLOAD_TOKEN in the process environment or provide a
|
||||||
|
# secrets-directory file with that name before running `distributor serve`.
|
||||||
|
server:
|
||||||
|
http:
|
||||||
|
bind: 127.0.0.1:8080
|
||||||
|
staging_root: workspace/http-upload/staging
|
||||||
|
max_upload_size: 20MB
|
||||||
|
queue_size: 16
|
||||||
|
max_concurrency: 1
|
||||||
|
retention: 24h
|
||||||
|
pipelines:
|
||||||
|
- id: example-http-upload
|
||||||
|
source:
|
||||||
|
backend: http_upload
|
||||||
|
token_env: DISTRIBUTOR_EXAMPLE_UPLOAD_TOKEN
|
||||||
|
destinations:
|
||||||
|
- id: local-archive
|
||||||
|
backend: local
|
||||||
|
path: workspace/published/http-upload
|
||||||
|
publish:
|
||||||
|
source: true
|
||||||
|
html: false
|
||||||
|
|
||||||
16
examples/local-index.yml
Normal file
16
examples/local-index.yml
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
pipelines:
|
||||||
|
- id: example-index-bundle
|
||||||
|
source:
|
||||||
|
backend: local
|
||||||
|
path: examples/source-bundle
|
||||||
|
destinations:
|
||||||
|
- id: local-index
|
||||||
|
backend: local
|
||||||
|
path: workspace/published/index-bundle
|
||||||
|
publish:
|
||||||
|
source: false
|
||||||
|
html: true
|
||||||
|
transform:
|
||||||
|
markdown_to_html:
|
||||||
|
enabled: true
|
||||||
|
mode: index
|
||||||
@@ -161,31 +161,10 @@ func (b *Backend) Walk(ctx context.Context, prefix string, opts storage.WalkOpti
|
|||||||
}
|
}
|
||||||
return b.translateError(storage.OpWalk, prefix, err)
|
return b.translateError(storage.OpWalk, prefix, err)
|
||||||
}
|
}
|
||||||
visited := 0
|
emitter := storage.NewWalkEmitter(ctx, backendName, opts, fn)
|
||||||
emit := func(entry storage.Entry) error {
|
|
||||||
if err := ctx.Err(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if opts.Limit > 0 && visited >= opts.Limit {
|
|
||||||
return storage.ErrStopWalk
|
|
||||||
}
|
|
||||||
visited++
|
|
||||||
if err := fn(entry); err != nil {
|
|
||||||
if errors.Is(err, storage.ErrStopWalk) {
|
|
||||||
return storage.ErrStopWalk
|
|
||||||
}
|
|
||||||
return storage.NewError(storage.OpWalk, backendName, entry.Path, storage.ErrUnknown, err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if !info.IsDir() {
|
if !info.IsDir() {
|
||||||
if err := emit(entryFromInfo(prefix, info)); errors.Is(err, storage.ErrStopWalk) {
|
return storage.FinishWalk(emitter.Emit(entryFromInfo(prefix, info)))
|
||||||
return nil
|
|
||||||
} else if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
walkErr := filepath.WalkDir(nativePrefix, func(nativePath string, dirEntry fs.DirEntry, err error) error {
|
walkErr := filepath.WalkDir(nativePrefix, func(nativePath string, dirEntry fs.DirEntry, err error) error {
|
||||||
@@ -210,24 +189,13 @@ func (b *Backend) Walk(ctx context.Context, prefix string, opts storage.WalkOpti
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return b.translateError(storage.OpWalk, logicalPath, err)
|
return b.translateError(storage.OpWalk, logicalPath, err)
|
||||||
}
|
}
|
||||||
return emit(entryFromInfo(logicalPath, info))
|
return emitter.Emit(entryFromInfo(logicalPath, info))
|
||||||
})
|
})
|
||||||
if errors.Is(walkErr, storage.ErrStopWalk) {
|
return storage.FinishWalk(walkErr)
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return walkErr
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Backend) HasAny(ctx context.Context, prefix string) (bool, error) {
|
func (b *Backend) HasAny(ctx context.Context, prefix string) (bool, error) {
|
||||||
found := false
|
return storage.HasAny(ctx, b, prefix)
|
||||||
err := b.Walk(ctx, prefix, storage.WalkOptions{Recursive: false, Limit: 1}, func(storage.Entry) error {
|
|
||||||
found = true
|
|
||||||
return storage.ErrStopWalk
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return false, err
|
|
||||||
}
|
|
||||||
return found, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Backend) DeleteManagedBundle(ctx context.Context, bundlePath string, managedOutputPaths []string, opts storage.DeleteOptions) error {
|
func (b *Backend) DeleteManagedBundle(ctx context.Context, bundlePath string, managedOutputPaths []string, opts storage.DeleteOptions) error {
|
||||||
|
|||||||
@@ -183,55 +183,25 @@ func (b *Backend) Walk(ctx context.Context, logicalPrefix string, opts storage.W
|
|||||||
if err := storage.ValidatePrefix(logicalPrefix); err != nil {
|
if err := storage.ValidatePrefix(logicalPrefix); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
visited := 0
|
emitter := storage.NewWalkEmitter(ctx, BackendName, opts, fn)
|
||||||
emit := func(entry storage.Entry) error {
|
|
||||||
if err := ctx.Err(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if opts.Limit > 0 && visited >= opts.Limit {
|
|
||||||
return storage.ErrStopWalk
|
|
||||||
}
|
|
||||||
visited++
|
|
||||||
if err := fn(entry); err != nil {
|
|
||||||
if errors.Is(err, storage.ErrStopWalk) {
|
|
||||||
return storage.ErrStopWalk
|
|
||||||
}
|
|
||||||
return storage.NewError(storage.OpWalk, BackendName, entry.Path, storage.ErrUnknown, err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if logicalPrefix != "" {
|
if logicalPrefix != "" {
|
||||||
entry, err := b.Stat(ctx, logicalPrefix)
|
entry, err := b.Stat(ctx, logicalPrefix)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
if err := emit(entry); errors.Is(err, storage.ErrStopWalk) {
|
if err := emitter.Emit(entry); err != nil {
|
||||||
return nil
|
return storage.FinishWalk(err)
|
||||||
} else if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
}
|
||||||
if opts.Limit > 0 && visited >= opts.Limit {
|
if emitter.LimitReached() {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
} else if !storage.IsNotFound(err) {
|
} else if !storage.IsNotFound(err) {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
err := b.walkObjects(ctx, logicalPrefix, opts, emit)
|
return storage.FinishWalk(b.walkObjects(ctx, logicalPrefix, opts, emitter.Emit))
|
||||||
if errors.Is(err, storage.ErrStopWalk) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Backend) HasAny(ctx context.Context, logicalPrefix string) (bool, error) {
|
func (b *Backend) HasAny(ctx context.Context, logicalPrefix string) (bool, error) {
|
||||||
found := false
|
return storage.HasAny(ctx, b, logicalPrefix)
|
||||||
err := b.Walk(ctx, logicalPrefix, storage.WalkOptions{Recursive: false, Limit: 1}, func(storage.Entry) error {
|
|
||||||
found = true
|
|
||||||
return storage.ErrStopWalk
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return false, err
|
|
||||||
}
|
|
||||||
return found, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Backend) DeleteManagedBundle(ctx context.Context, bundlePath string, managedOutputPaths []string, opts storage.DeleteOptions) error {
|
func (b *Backend) DeleteManagedBundle(ctx context.Context, bundlePath string, managedOutputPaths []string, opts storage.DeleteOptions) error {
|
||||||
|
|||||||
@@ -209,51 +209,17 @@ func (b *Backend) Walk(ctx context.Context, prefix string, opts storage.WalkOpti
|
|||||||
return b.translateError(storage.OpWalk, prefix, err)
|
return b.translateError(storage.OpWalk, prefix, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
visited := 0
|
emitter := storage.NewWalkEmitter(ctx, BackendName, opts, fn)
|
||||||
emit := func(entry storage.Entry) error {
|
|
||||||
if err := ctx.Err(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if opts.Limit > 0 && visited >= opts.Limit {
|
|
||||||
return storage.ErrStopWalk
|
|
||||||
}
|
|
||||||
visited++
|
|
||||||
if err := fn(entry); err != nil {
|
|
||||||
if errors.Is(err, storage.ErrStopWalk) {
|
|
||||||
return storage.ErrStopWalk
|
|
||||||
}
|
|
||||||
return storage.NewError(storage.OpWalk, BackendName, entry.Path, storage.ErrUnknown, err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if !info.IsDir() {
|
if !info.IsDir() {
|
||||||
if err := emit(entryFromInfo(prefix, info)); errors.Is(err, storage.ErrStopWalk) {
|
return storage.FinishWalk(emitter.Emit(entryFromInfo(prefix, info)))
|
||||||
return nil
|
|
||||||
} else if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := b.walkDirectory(ctx, prefix, nativePrefix, opts, emit); errors.Is(err, storage.ErrStopWalk) {
|
return storage.FinishWalk(b.walkDirectory(ctx, prefix, nativePrefix, opts, emitter.Emit))
|
||||||
return nil
|
|
||||||
} else if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Backend) HasAny(ctx context.Context, prefix string) (bool, error) {
|
func (b *Backend) HasAny(ctx context.Context, prefix string) (bool, error) {
|
||||||
found := false
|
return storage.HasAny(ctx, b, prefix)
|
||||||
err := b.Walk(ctx, prefix, storage.WalkOptions{Recursive: false, Limit: 1}, func(storage.Entry) error {
|
|
||||||
found = true
|
|
||||||
return storage.ErrStopWalk
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return false, err
|
|
||||||
}
|
|
||||||
return found, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Backend) DeleteManagedBundle(ctx context.Context, bundlePath string, managedOutputPaths []string, opts storage.DeleteOptions) error {
|
func (b *Backend) DeleteManagedBundle(ctx context.Context, bundlePath string, managedOutputPaths []string, opts storage.DeleteOptions) error {
|
||||||
|
|||||||
@@ -37,6 +37,22 @@ type backendFactory struct {
|
|||||||
readOnlyKnownHosts bool
|
readOnlyKnownHosts bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type backendOpenSpec struct {
|
||||||
|
role string
|
||||||
|
backend string
|
||||||
|
path string
|
||||||
|
host string
|
||||||
|
user string
|
||||||
|
port int
|
||||||
|
ssh config.SSH
|
||||||
|
endpoint string
|
||||||
|
bucket string
|
||||||
|
prefix string
|
||||||
|
region string
|
||||||
|
forcePath *bool
|
||||||
|
credentials config.Credentials
|
||||||
|
}
|
||||||
|
|
||||||
func newBackendFactory() *backendFactory {
|
func newBackendFactory() *backendFactory {
|
||||||
return newBackendFactoryWithEnvironment(config.ProcessEnvironment())
|
return newBackendFactoryWithEnvironment(config.ProcessEnvironment())
|
||||||
}
|
}
|
||||||
@@ -91,25 +107,11 @@ func newBackendFactoryWithEnvironment(environment config.Environment) *backendFa
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (f *backendFactory) openSource(ctx context.Context, source config.Backend) (storage.Backend, error) {
|
func (f *backendFactory) openSource(ctx context.Context, source config.Backend) (storage.Backend, error) {
|
||||||
if source.Backend != config.BackendLocal && source.Backend != config.BackendSSH && source.Backend != config.BackendS3 {
|
return f.openBackend(ctx, backendOpenSpecFromSource(source))
|
||||||
return nil, fmt.Errorf("source backend %s is not implemented for execution", source.Backend)
|
|
||||||
}
|
|
||||||
openConfig, err := f.sourceOpenConfig(source)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return f.registry.Open(ctx, source.Backend, openConfig)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *backendFactory) openDestination(ctx context.Context, destination config.Destination) (storage.Backend, error) {
|
func (f *backendFactory) openDestination(ctx context.Context, destination config.Destination) (storage.Backend, error) {
|
||||||
if destination.Backend != config.BackendLocal && destination.Backend != config.BackendSSH && destination.Backend != config.BackendS3 {
|
return f.openBackend(ctx, backendOpenSpecFromDestination(destination))
|
||||||
return nil, fmt.Errorf("backend %s is not implemented for execution", destination.Backend)
|
|
||||||
}
|
|
||||||
openConfig, err := f.destinationOpenConfig(destination)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return f.registry.Open(ctx, destination.Backend, openConfig)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *backendFactory) openLocalPath(ctx context.Context, path string) (storage.Backend, error) {
|
func (f *backendFactory) openLocalPath(ctx context.Context, path string) (storage.Backend, error) {
|
||||||
@@ -120,40 +122,51 @@ func (f *backendFactory) resolveCredentials(creds config.Credentials) (config.Re
|
|||||||
return f.environment.ResolveCredentials(creds)
|
return f.environment.ResolveCredentials(creds)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *backendFactory) sourceOpenConfig(source config.Backend) (storage.OpenConfig, error) {
|
func (f *backendFactory) openBackend(ctx context.Context, spec backendOpenSpec) (storage.Backend, error) {
|
||||||
cfg := sourceOpenConfig(source)
|
if !backendExecutable(spec.backend) {
|
||||||
if source.Backend == config.BackendS3 {
|
if spec.role == "source" {
|
||||||
if err := f.addS3Config(cfg, source.Endpoint, source.Bucket, source.Prefix, source.Region, source.ForcePath, source.Creds); err != nil {
|
return nil, fmt.Errorf("source backend %s is not implemented for execution", spec.backend)
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("backend %s is not implemented for execution", spec.backend)
|
||||||
|
}
|
||||||
|
openConfig, err := f.openConfig(spec)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return f.registry.Open(ctx, spec.backend, openConfig)
|
||||||
|
}
|
||||||
|
|
||||||
|
func backendExecutable(name string) bool {
|
||||||
|
return name == config.BackendLocal || name == config.BackendSSH || name == config.BackendS3
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *backendFactory) openConfig(spec backendOpenSpec) (storage.OpenConfig, error) {
|
||||||
|
cfg := storage.OpenConfig{storagePathKey: spec.path}
|
||||||
|
switch spec.backend {
|
||||||
|
case config.BackendSSH:
|
||||||
|
cfg[sshHostKey] = spec.host
|
||||||
|
cfg[sshUserKey] = spec.user
|
||||||
|
cfg[sshPortKey] = strconv.Itoa(spec.port)
|
||||||
|
cfg[sshKeyFileKey] = spec.ssh.KeyFile
|
||||||
|
cfg[sshKnownHostsKey] = spec.ssh.KnownHosts
|
||||||
|
cfg[sshHostKeyPolicyKey] = string(spec.ssh.HostKeyPolicy)
|
||||||
|
cfg[sshReadOnlyHostsKey] = strconv.FormatBool(f.readOnlyKnownHosts)
|
||||||
|
case config.BackendS3:
|
||||||
|
if err := f.addS3Config(cfg, spec); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if source.Backend == config.BackendSSH {
|
|
||||||
cfg[sshReadOnlyHostsKey] = strconv.FormatBool(f.readOnlyKnownHosts)
|
|
||||||
}
|
|
||||||
return cfg, nil
|
return cfg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *backendFactory) destinationOpenConfig(destination config.Destination) (storage.OpenConfig, error) {
|
func (f *backendFactory) addS3Config(cfg storage.OpenConfig, spec backendOpenSpec) error {
|
||||||
cfg := destinationOpenConfig(destination)
|
cfg[s3EndpointKey] = spec.endpoint
|
||||||
if destination.Backend == config.BackendS3 {
|
cfg[s3BucketKey] = spec.bucket
|
||||||
if err := f.addS3Config(cfg, destination.Endpoint, destination.Bucket, destination.Prefix, destination.Region, destination.ForcePath, destination.Creds); err != nil {
|
cfg[s3PrefixKey] = spec.prefix
|
||||||
return nil, err
|
cfg[s3RegionKey] = spec.region
|
||||||
}
|
cfg[s3ForcePathStyleKey] = strconv.FormatBool(config.ForcePathStyle(spec.forcePath))
|
||||||
}
|
if spec.credentials.AccessKeyIDEnv != "" || spec.credentials.SecretAccessKeyEnv != "" {
|
||||||
if destination.Backend == config.BackendSSH {
|
resolved, err := f.resolveCredentials(spec.credentials)
|
||||||
cfg[sshReadOnlyHostsKey] = strconv.FormatBool(f.readOnlyKnownHosts)
|
|
||||||
}
|
|
||||||
return cfg, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *backendFactory) addS3Config(cfg storage.OpenConfig, endpoint, bucket, prefix, region string, forcePath *bool, creds config.Credentials) error {
|
|
||||||
cfg[s3EndpointKey] = endpoint
|
|
||||||
cfg[s3BucketKey] = bucket
|
|
||||||
cfg[s3PrefixKey] = prefix
|
|
||||||
cfg[s3RegionKey] = region
|
|
||||||
cfg[s3ForcePathStyleKey] = strconv.FormatBool(config.ForcePathStyle(forcePath))
|
|
||||||
if creds.AccessKeyIDEnv != "" || creds.SecretAccessKeyEnv != "" {
|
|
||||||
resolved, err := f.resolveCredentials(creds)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -163,30 +176,38 @@ func (f *backendFactory) addS3Config(cfg storage.OpenConfig, endpoint, bucket, p
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func sourceOpenConfig(source config.Backend) storage.OpenConfig {
|
func backendOpenSpecFromSource(source config.Backend) backendOpenSpec {
|
||||||
cfg := storage.OpenConfig{storagePathKey: source.Path}
|
return backendOpenSpec{
|
||||||
if source.Backend == config.BackendSSH {
|
role: "source",
|
||||||
cfg[sshHostKey] = source.Host
|
backend: source.Backend,
|
||||||
cfg[sshUserKey] = source.User
|
path: source.Path,
|
||||||
cfg[sshPortKey] = strconv.Itoa(source.Port)
|
host: source.Host,
|
||||||
cfg[sshKeyFileKey] = source.SSH.KeyFile
|
user: source.User,
|
||||||
cfg[sshKnownHostsKey] = source.SSH.KnownHosts
|
port: source.Port,
|
||||||
cfg[sshHostKeyPolicyKey] = string(source.SSH.HostKeyPolicy)
|
ssh: source.SSH,
|
||||||
cfg[sshReadOnlyHostsKey] = "false"
|
endpoint: source.Endpoint,
|
||||||
|
bucket: source.Bucket,
|
||||||
|
prefix: source.Prefix,
|
||||||
|
region: source.Region,
|
||||||
|
forcePath: source.ForcePath,
|
||||||
|
credentials: source.Creds,
|
||||||
}
|
}
|
||||||
return cfg
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func destinationOpenConfig(destination config.Destination) storage.OpenConfig {
|
func backendOpenSpecFromDestination(destination config.Destination) backendOpenSpec {
|
||||||
cfg := storage.OpenConfig{storagePathKey: destination.Path}
|
return backendOpenSpec{
|
||||||
if destination.Backend == config.BackendSSH {
|
role: "destination",
|
||||||
cfg[sshHostKey] = destination.Host
|
backend: destination.Backend,
|
||||||
cfg[sshUserKey] = destination.User
|
path: destination.Path,
|
||||||
cfg[sshPortKey] = strconv.Itoa(destination.Port)
|
host: destination.Host,
|
||||||
cfg[sshKeyFileKey] = destination.SSH.KeyFile
|
user: destination.User,
|
||||||
cfg[sshKnownHostsKey] = destination.SSH.KnownHosts
|
port: destination.Port,
|
||||||
cfg[sshHostKeyPolicyKey] = string(destination.SSH.HostKeyPolicy)
|
ssh: destination.SSH,
|
||||||
cfg[sshReadOnlyHostsKey] = "false"
|
endpoint: destination.Endpoint,
|
||||||
|
bucket: destination.Bucket,
|
||||||
|
prefix: destination.Prefix,
|
||||||
|
region: destination.Region,
|
||||||
|
forcePath: destination.ForcePath,
|
||||||
|
credentials: destination.Creds,
|
||||||
}
|
}
|
||||||
return cfg
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,16 @@
|
|||||||
package app
|
package app
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/distributor/internal/config"
|
"gitea.maximumdirect.net/eric/distributor/internal/config"
|
||||||
"gitea.maximumdirect.net/eric/distributor/internal/storage"
|
"gitea.maximumdirect.net/eric/distributor/internal/storage"
|
||||||
"gitea.maximumdirect.net/eric/distributor/internal/storage/fake"
|
"gitea.maximumdirect.net/eric/distributor/internal/storage/fake"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/testutil"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestBackendFactoryOpensLocalSource(t *testing.T) {
|
func TestBackendFactoryOpensLocalSource(t *testing.T) {
|
||||||
@@ -275,7 +278,8 @@ func TestBackendFactoryResolvesCredentialsThroughEnvironment(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestBackendFactoryBuildsSSHSourceOpenConfig(t *testing.T) {
|
func TestBackendFactoryBuildsSSHSourceOpenConfig(t *testing.T) {
|
||||||
cfg := sourceOpenConfig(config.Backend{
|
factory := &backendFactory{environment: config.NewEnvironment(nil, nil)}
|
||||||
|
cfg, err := factory.openConfig(backendOpenSpecFromSource(config.Backend{
|
||||||
Backend: config.BackendSSH,
|
Backend: config.BackendSSH,
|
||||||
Host: "source.example.com",
|
Host: "source.example.com",
|
||||||
User: "reports",
|
User: "reports",
|
||||||
@@ -286,7 +290,10 @@ func TestBackendFactoryBuildsSSHSourceOpenConfig(t *testing.T) {
|
|||||||
KnownHosts: "/home/reports/.ssh/known_hosts",
|
KnownHosts: "/home/reports/.ssh/known_hosts",
|
||||||
HostKeyPolicy: config.HostKeyPolicyStrict,
|
HostKeyPolicy: config.HostKeyPolicyStrict,
|
||||||
},
|
},
|
||||||
})
|
}))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("openConfig() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
assertOpenConfig(t, cfg, map[string]string{
|
assertOpenConfig(t, cfg, map[string]string{
|
||||||
storagePathKey: "/reports",
|
storagePathKey: "/reports",
|
||||||
@@ -300,7 +307,8 @@ func TestBackendFactoryBuildsSSHSourceOpenConfig(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestBackendFactoryBuildsSSHDestinationOpenConfig(t *testing.T) {
|
func TestBackendFactoryBuildsSSHDestinationOpenConfig(t *testing.T) {
|
||||||
cfg := destinationOpenConfig(config.Destination{
|
factory := &backendFactory{environment: config.NewEnvironment(nil, nil)}
|
||||||
|
cfg, err := factory.openConfig(backendOpenSpecFromDestination(config.Destination{
|
||||||
Backend: config.BackendSSH,
|
Backend: config.BackendSSH,
|
||||||
Host: "destination.example.com",
|
Host: "destination.example.com",
|
||||||
User: "deploy",
|
User: "deploy",
|
||||||
@@ -309,7 +317,10 @@ func TestBackendFactoryBuildsSSHDestinationOpenConfig(t *testing.T) {
|
|||||||
SSH: config.SSH{
|
SSH: config.SSH{
|
||||||
HostKeyPolicy: config.HostKeyPolicyAcceptNew,
|
HostKeyPolicy: config.HostKeyPolicyAcceptNew,
|
||||||
},
|
},
|
||||||
})
|
}))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("openConfig() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
assertOpenConfig(t, cfg, map[string]string{
|
assertOpenConfig(t, cfg, map[string]string{
|
||||||
storagePathKey: "/srv/archive",
|
storagePathKey: "/srv/archive",
|
||||||
@@ -320,6 +331,257 @@ func TestBackendFactoryBuildsSSHDestinationOpenConfig(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestBackendFactoryBuildsEquivalentSourceAndDestinationOpenConfig(t *testing.T) {
|
||||||
|
forcePathStyle := false
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
source config.Backend
|
||||||
|
destination config.Destination
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "local",
|
||||||
|
source: config.Backend{Backend: config.BackendLocal, Path: "/reports"},
|
||||||
|
destination: config.Destination{Backend: config.BackendLocal, Path: "/reports"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "ssh",
|
||||||
|
source: config.Backend{
|
||||||
|
Backend: config.BackendSSH,
|
||||||
|
Host: "reports.example.com",
|
||||||
|
User: "reports",
|
||||||
|
Port: 2222,
|
||||||
|
Path: "/reports",
|
||||||
|
SSH: config.SSH{
|
||||||
|
KeyFile: "/home/reports/.ssh/id_ed25519",
|
||||||
|
KnownHosts: "/home/reports/.ssh/known_hosts",
|
||||||
|
HostKeyPolicy: config.HostKeyPolicyStrict,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
destination: config.Destination{
|
||||||
|
Backend: config.BackendSSH,
|
||||||
|
Host: "reports.example.com",
|
||||||
|
User: "reports",
|
||||||
|
Port: 2222,
|
||||||
|
Path: "/reports",
|
||||||
|
SSH: config.SSH{
|
||||||
|
KeyFile: "/home/reports/.ssh/id_ed25519",
|
||||||
|
KnownHosts: "/home/reports/.ssh/known_hosts",
|
||||||
|
HostKeyPolicy: config.HostKeyPolicyStrict,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "s3",
|
||||||
|
source: config.Backend{
|
||||||
|
Backend: config.BackendS3,
|
||||||
|
Endpoint: "https://s3.example.com",
|
||||||
|
Bucket: "reports",
|
||||||
|
Prefix: "archive",
|
||||||
|
Region: "us-west-2",
|
||||||
|
ForcePath: &forcePathStyle,
|
||||||
|
},
|
||||||
|
destination: config.Destination{
|
||||||
|
Backend: config.BackendS3,
|
||||||
|
Endpoint: "https://s3.example.com",
|
||||||
|
Bucket: "reports",
|
||||||
|
Prefix: "archive",
|
||||||
|
Region: "us-west-2",
|
||||||
|
ForcePath: &forcePathStyle,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "s3 explicit credentials",
|
||||||
|
source: config.Backend{
|
||||||
|
Backend: config.BackendS3,
|
||||||
|
Endpoint: "https://s3.example.com",
|
||||||
|
Bucket: "reports",
|
||||||
|
Region: config.DefaultS3Region,
|
||||||
|
Creds: config.Credentials{
|
||||||
|
AccessKeyIDEnv: "ACCESS_KEY_ID",
|
||||||
|
SecretAccessKeyEnv: "SECRET_ACCESS_KEY",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
destination: config.Destination{
|
||||||
|
Backend: config.BackendS3,
|
||||||
|
Endpoint: "https://s3.example.com",
|
||||||
|
Bucket: "reports",
|
||||||
|
Region: config.DefaultS3Region,
|
||||||
|
Creds: config.Credentials{
|
||||||
|
AccessKeyIDEnv: "ACCESS_KEY_ID",
|
||||||
|
SecretAccessKeyEnv: "SECRET_ACCESS_KEY",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
factory := &backendFactory{
|
||||||
|
environment: config.NewEnvironment(map[string]string{
|
||||||
|
"ACCESS_KEY_ID": "secret-access",
|
||||||
|
"SECRET_ACCESS_KEY": "secret-secret",
|
||||||
|
}, func(string) (string, bool) { return "", false }),
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
sourceConfig, err := factory.openConfig(backendOpenSpecFromSource(tt.source))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("source openConfig() error = %v", err)
|
||||||
|
}
|
||||||
|
destinationConfig, err := factory.openConfig(backendOpenSpecFromDestination(tt.destination))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("destination openConfig() error = %v", err)
|
||||||
|
}
|
||||||
|
if !openConfigEqual(sourceConfig, destinationConfig) {
|
||||||
|
t.Fatalf("source open config = %#v, destination open config = %#v, want equivalent", sourceConfig, destinationConfig)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBackendFactoryBuildsEquivalentDryRunSSHOpenConfig(t *testing.T) {
|
||||||
|
factory := &backendFactory{readOnlyKnownHosts: true}
|
||||||
|
sourceConfig, err := factory.openConfig(backendOpenSpecFromSource(config.Backend{
|
||||||
|
Backend: config.BackendSSH,
|
||||||
|
Host: "reports.example.com",
|
||||||
|
Port: 22,
|
||||||
|
Path: "/reports",
|
||||||
|
SSH: config.SSH{HostKeyPolicy: config.HostKeyPolicyAcceptNew},
|
||||||
|
}))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("source openConfig() error = %v", err)
|
||||||
|
}
|
||||||
|
destinationConfig, err := factory.openConfig(backendOpenSpecFromDestination(config.Destination{
|
||||||
|
Backend: config.BackendSSH,
|
||||||
|
Host: "reports.example.com",
|
||||||
|
Port: 22,
|
||||||
|
Path: "/reports",
|
||||||
|
SSH: config.SSH{HostKeyPolicy: config.HostKeyPolicyAcceptNew},
|
||||||
|
}))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("destination openConfig() error = %v", err)
|
||||||
|
}
|
||||||
|
if !openConfigEqual(sourceConfig, destinationConfig) {
|
||||||
|
t.Fatalf("source open config = %#v, destination open config = %#v, want equivalent", sourceConfig, destinationConfig)
|
||||||
|
}
|
||||||
|
if sourceConfig[sshReadOnlyHostsKey] != "true" {
|
||||||
|
t.Fatalf("open config %s = %q, want true", sshReadOnlyHostsKey, sourceConfig[sshReadOnlyHostsKey])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfiguredSourceValidationAndRunUseEquivalentSourceOpenConfig(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
source config.Backend
|
||||||
|
sourceKey string
|
||||||
|
dest config.Destination
|
||||||
|
destKey string
|
||||||
|
wantFields map[string]string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "s3",
|
||||||
|
source: config.Backend{
|
||||||
|
Backend: config.BackendS3,
|
||||||
|
Endpoint: "https://s3.example.com",
|
||||||
|
Bucket: "source-bucket",
|
||||||
|
Prefix: "source-prefix",
|
||||||
|
Region: config.DefaultS3Region,
|
||||||
|
},
|
||||||
|
sourceKey: "s3:source-bucket",
|
||||||
|
dest: config.Destination{
|
||||||
|
ID: "archive",
|
||||||
|
Backend: config.BackendS3,
|
||||||
|
Endpoint: "https://s3.example.com",
|
||||||
|
Bucket: "destination-bucket",
|
||||||
|
Region: config.DefaultS3Region,
|
||||||
|
},
|
||||||
|
destKey: "s3:destination-bucket",
|
||||||
|
wantFields: map[string]string{
|
||||||
|
s3EndpointKey: "https://s3.example.com",
|
||||||
|
s3BucketKey: "source-bucket",
|
||||||
|
s3PrefixKey: "source-prefix",
|
||||||
|
s3RegionKey: config.DefaultS3Region,
|
||||||
|
s3ForcePathStyleKey: "true",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "ssh",
|
||||||
|
source: config.Backend{
|
||||||
|
Backend: config.BackendSSH,
|
||||||
|
Host: "ssh.example.com",
|
||||||
|
User: "reports",
|
||||||
|
Port: 2222,
|
||||||
|
Path: "/source",
|
||||||
|
SSH: config.SSH{
|
||||||
|
KeyFile: "/home/reports/.ssh/id_ed25519",
|
||||||
|
KnownHosts: "/home/reports/.ssh/known_hosts",
|
||||||
|
HostKeyPolicy: config.HostKeyPolicyStrict,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
sourceKey: "ssh:/source",
|
||||||
|
dest: config.Destination{
|
||||||
|
ID: "archive",
|
||||||
|
Backend: config.BackendSSH,
|
||||||
|
Host: "ssh.example.com",
|
||||||
|
Port: 2222,
|
||||||
|
Path: "/destination",
|
||||||
|
SSH: config.SSH{HostKeyPolicy: config.HostKeyPolicyStrict},
|
||||||
|
},
|
||||||
|
destKey: "ssh:/destination",
|
||||||
|
wantFields: map[string]string{
|
||||||
|
storagePathKey: "/source",
|
||||||
|
sshHostKey: "ssh.example.com",
|
||||||
|
sshUserKey: "reports",
|
||||||
|
sshPortKey: "2222",
|
||||||
|
sshKeyFileKey: "/home/reports/.ssh/id_ed25519",
|
||||||
|
sshKnownHostsKey: "/home/reports/.ssh/known_hosts",
|
||||||
|
sshHostKeyPolicyKey: "strict",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
sourceBackend := fake.New()
|
||||||
|
testutil.WriteFakeSourceBundle(t, sourceBackend, "", testutil.BundleOptions{ID: "reports.source"})
|
||||||
|
destinationBackend := fake.New()
|
||||||
|
var validateSourceConfig storage.OpenConfig
|
||||||
|
var runSourceConfig storage.OpenConfig
|
||||||
|
validateProvider := recordingBackendFactoryProvider(t, map[string]storage.Backend{
|
||||||
|
tt.sourceKey: sourceBackend,
|
||||||
|
tt.destKey: destinationBackend,
|
||||||
|
}, func(cfg storage.OpenConfig) {
|
||||||
|
validateSourceConfig = cfg
|
||||||
|
})
|
||||||
|
runProvider := recordingBackendFactoryProvider(t, map[string]storage.Backend{
|
||||||
|
tt.sourceKey: sourceBackend,
|
||||||
|
tt.destKey: destinationBackend,
|
||||||
|
}, func(cfg storage.OpenConfig) {
|
||||||
|
runSourceConfig = cfg
|
||||||
|
})
|
||||||
|
cfg := config.Config{Pipelines: []config.Pipeline{{
|
||||||
|
ID: "reports",
|
||||||
|
Source: tt.source,
|
||||||
|
Destinations: []config.Destination{tt.dest},
|
||||||
|
}}}
|
||||||
|
config.ApplyDefaults(&cfg)
|
||||||
|
|
||||||
|
var validateOutput bytes.Buffer
|
||||||
|
if err := validateConfigWithBackendFactory(context.Background(), cfg, ValidateOptions{
|
||||||
|
PipelineID: "reports",
|
||||||
|
Stdout: &validateOutput,
|
||||||
|
}, validateProvider); err != nil {
|
||||||
|
t.Fatalf("validateConfigWithBackendFactory() error = %v", err)
|
||||||
|
}
|
||||||
|
if err := runConfigWithBackendFactory(context.Background(), cfg, RunOptions{}, runProvider); err != nil {
|
||||||
|
t.Fatalf("runConfigWithBackendFactory() error = %v", err)
|
||||||
|
}
|
||||||
|
if !openConfigEqual(validateSourceConfig, runSourceConfig) {
|
||||||
|
t.Fatalf("validate source config = %#v, run source config = %#v, want equivalent", validateSourceConfig, runSourceConfig)
|
||||||
|
}
|
||||||
|
assertOpenConfig(t, runSourceConfig, tt.wantFields)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func assertOpenConfig(t *testing.T, got map[string]string, want map[string]string) {
|
func assertOpenConfig(t *testing.T, got map[string]string, want map[string]string) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
for key, wantValue := range want {
|
for key, wantValue := range want {
|
||||||
@@ -328,3 +590,49 @@ func assertOpenConfig(t *testing.T, got map[string]string, want map[string]strin
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func openConfigEqual(left, right storage.OpenConfig) bool {
|
||||||
|
if len(left) != len(right) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for key, leftValue := range left {
|
||||||
|
if right[key] != leftValue {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func recordingBackendFactoryProvider(t *testing.T, remoteBackends map[string]storage.Backend, recordSource func(storage.OpenConfig)) backendFactoryProvider {
|
||||||
|
t.Helper()
|
||||||
|
return func(environment config.Environment) *backendFactory {
|
||||||
|
registry := storage.NewRegistry()
|
||||||
|
if err := registry.Register(config.BackendS3, func(ctx context.Context, cfg storage.OpenConfig) (storage.Backend, error) {
|
||||||
|
if cfg[s3BucketKey] == "source-bucket" {
|
||||||
|
recordSource(cfg)
|
||||||
|
}
|
||||||
|
key := "s3:" + cfg[s3BucketKey]
|
||||||
|
backend := remoteBackends[key]
|
||||||
|
if backend == nil {
|
||||||
|
return nil, fmt.Errorf("missing fake backend for %s", key)
|
||||||
|
}
|
||||||
|
return backend, nil
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("register s3 backend: %v", err)
|
||||||
|
}
|
||||||
|
if err := registry.Register(config.BackendSSH, func(ctx context.Context, cfg storage.OpenConfig) (storage.Backend, error) {
|
||||||
|
if cfg[storagePathKey] == "/source" {
|
||||||
|
recordSource(cfg)
|
||||||
|
}
|
||||||
|
key := "ssh:" + cfg[storagePathKey]
|
||||||
|
backend := remoteBackends[key]
|
||||||
|
if backend == nil {
|
||||||
|
return nil, fmt.Errorf("missing fake backend for %s", key)
|
||||||
|
}
|
||||||
|
return backend, nil
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("register ssh backend: %v", err)
|
||||||
|
}
|
||||||
|
return &backendFactory{registry: registry, environment: environment}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -5,38 +5,130 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/distributor/internal/bundle"
|
"gitea.maximumdirect.net/eric/distributor/internal/config"
|
||||||
"gitea.maximumdirect.net/eric/distributor/internal/storage"
|
"gitea.maximumdirect.net/eric/distributor/internal/storage"
|
||||||
)
|
)
|
||||||
|
|
||||||
type InspectOptions struct {
|
type InspectOptions struct {
|
||||||
Path string
|
Path string
|
||||||
Stdout io.Writer
|
ConfigPath string
|
||||||
|
PipelineID string
|
||||||
|
BundlePath string
|
||||||
|
Stdout io.Writer
|
||||||
|
OutputFormat OutputFormat
|
||||||
}
|
}
|
||||||
|
|
||||||
func Inspect(ctx context.Context, options InspectOptions) error {
|
func Inspect(ctx context.Context, options InspectOptions) error {
|
||||||
if options.Path == "" {
|
return inspectWithBackendFactory(ctx, options, newBackendFactoryWithEnvironment)
|
||||||
return fmt.Errorf("inspect command requires a path")
|
|
||||||
}
|
|
||||||
backend, err := newBackendFactory().openLocalPath(ctx, options.Path)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
bundles, err := bundle.Discover(ctx, backend, "")
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return writeInspection(options.Stdout, bundles)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func writeInspection(w io.Writer, bundles []bundle.Bundle) error {
|
func inspectWithBackendFactory(ctx context.Context, options InspectOptions, provider backendFactoryProvider) error {
|
||||||
|
if err := ValidateOutputFormat(options.OutputFormat); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
selection, err := selectSourceBundles(ctx, sourceCommandOptions{
|
||||||
|
CommandName: "inspect",
|
||||||
|
Path: options.Path,
|
||||||
|
ConfigPath: options.ConfigPath,
|
||||||
|
PipelineID: options.PipelineID,
|
||||||
|
BundlePath: options.BundlePath,
|
||||||
|
}, provider)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return writeInspectResult(options, selection)
|
||||||
|
}
|
||||||
|
|
||||||
|
func inspectConfigWithBackendFactory(ctx context.Context, cfg config.Config, options InspectOptions, provider backendFactoryProvider) error {
|
||||||
|
if err := ValidateOutputFormat(options.OutputFormat); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
selection, err := selectSourceBundlesFromConfig(ctx, cfg, sourceCommandOptions{
|
||||||
|
CommandName: "inspect",
|
||||||
|
PipelineID: options.PipelineID,
|
||||||
|
BundlePath: options.BundlePath,
|
||||||
|
}, provider)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return writeInspectResult(options, selection)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeInspectResult(options InspectOptions, selection sourceSelection) error {
|
||||||
|
if IsJSONOutput(options.OutputFormat) {
|
||||||
|
return WriteJSONEnvelope(options.Stdout, "inspect", true, selection.Warnings, inspectResultFromSelection(selection), nil)
|
||||||
|
}
|
||||||
|
if err := writeWarnings(options.Stdout, selection.Warnings); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return writeInspection(options.Stdout, selection)
|
||||||
|
}
|
||||||
|
|
||||||
|
type inspectResult struct {
|
||||||
|
PipelineID string `json:"pipeline_id,omitempty"`
|
||||||
|
SourceBackend string `json:"source_backend,omitempty"`
|
||||||
|
BundleCount int `json:"bundle_count"`
|
||||||
|
Bundles []inspectBundleResult `json:"bundles"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type inspectBundleResult struct {
|
||||||
|
Path string `json:"path"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
Created string `json:"created"`
|
||||||
|
Digest string `json:"digest"`
|
||||||
|
FileCount int `json:"file_count"`
|
||||||
|
TotalSize int64 `json:"total_size"`
|
||||||
|
Files []inspectFileResult `json:"files"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type inspectFileResult struct {
|
||||||
|
Path string `json:"path"`
|
||||||
|
SHA256 string `json:"sha256"`
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func inspectResultFromSelection(selection sourceSelection) inspectResult {
|
||||||
|
result := inspectResult{
|
||||||
|
PipelineID: selection.PipelineID,
|
||||||
|
SourceBackend: selection.SourceBackend,
|
||||||
|
BundleCount: len(selection.Bundles),
|
||||||
|
Bundles: make([]inspectBundleResult, 0, len(selection.Bundles)),
|
||||||
|
}
|
||||||
|
for _, sourceBundle := range selection.Bundles {
|
||||||
|
bundleResult := inspectBundleResult{
|
||||||
|
Path: storage.DisplayPath(sourceBundle.RootRelativePath),
|
||||||
|
ID: sourceBundle.Manifest.ID,
|
||||||
|
Created: sourceBundle.Manifest.Created.Format("2006-01-02T15:04:05Z07:00"),
|
||||||
|
Digest: sourceBundle.Manifest.Digest,
|
||||||
|
FileCount: len(sourceBundle.Manifest.Files),
|
||||||
|
Files: make([]inspectFileResult, 0, len(sourceBundle.Manifest.Files)),
|
||||||
|
}
|
||||||
|
for _, file := range sourceBundle.Manifest.Files {
|
||||||
|
bundleResult.TotalSize += file.Size
|
||||||
|
bundleResult.Files = append(bundleResult.Files, inspectFileResult{
|
||||||
|
Path: file.Path,
|
||||||
|
SHA256: file.SHA256,
|
||||||
|
Size: file.Size,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
result.Bundles = append(result.Bundles, bundleResult)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeInspection(w io.Writer, selection sourceSelection) error {
|
||||||
if w == nil {
|
if w == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if _, err := fmt.Fprintf(w, "Bundles: %d\n", len(bundles)); err != nil {
|
if selection.ConfigMode {
|
||||||
|
if _, err := fmt.Fprintf(w, "Pipeline: %s\nSource: %s\n", selection.PipelineID, selection.SourceBackend); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := fmt.Fprintf(w, "Bundles: %d\n", len(selection.Bundles)); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
for _, sourceBundle := range bundles {
|
for _, sourceBundle := range selection.Bundles {
|
||||||
if _, err := fmt.Fprintf(
|
if _, err := fmt.Fprintf(
|
||||||
w,
|
w,
|
||||||
"- path=%s id=%s created=%s digest=%s files=%d\n",
|
"- path=%s id=%s created=%s digest=%s files=%d\n",
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/testutil"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestInspectPrintsBundleSummary(t *testing.T) {
|
func TestInspectPrintsBundleSummary(t *testing.T) {
|
||||||
@@ -32,6 +34,57 @@ func TestInspectPrintsBundleSummary(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestInspectConfiguredLocalSource(t *testing.T) {
|
||||||
|
sourceRoot := t.TempDir()
|
||||||
|
destinationRoot := t.TempDir()
|
||||||
|
testutil.WriteSourceBundle(t, sourceRoot, "daily", testutil.BundleOptions{ID: "reports.daily"})
|
||||||
|
var stdout bytes.Buffer
|
||||||
|
|
||||||
|
err := Inspect(context.Background(), InspectOptions{
|
||||||
|
ConfigPath: testutil.WriteMinimalLocalConfig(t, sourceRoot, destinationRoot),
|
||||||
|
PipelineID: "reports",
|
||||||
|
Stdout: &stdout,
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Inspect() configured source error = %v", err)
|
||||||
|
}
|
||||||
|
output := stdout.String()
|
||||||
|
for _, want := range []string{
|
||||||
|
"Pipeline: reports",
|
||||||
|
"Source: local",
|
||||||
|
"Bundles: 1",
|
||||||
|
"path=daily",
|
||||||
|
"id=reports.daily",
|
||||||
|
} {
|
||||||
|
if !strings.Contains(output, want) {
|
||||||
|
t.Fatalf("Inspect() output = %q, want substring %q", output, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInspectConfiguredSourceJSON(t *testing.T) {
|
||||||
|
sourceRoot := t.TempDir()
|
||||||
|
destinationRoot := t.TempDir()
|
||||||
|
testutil.WriteSourceBundle(t, sourceRoot, "", testutil.BundleOptions{ID: "reports.json"})
|
||||||
|
var stdout bytes.Buffer
|
||||||
|
|
||||||
|
err := Inspect(context.Background(), InspectOptions{
|
||||||
|
ConfigPath: testutil.WriteMinimalLocalConfig(t, sourceRoot, destinationRoot),
|
||||||
|
PipelineID: "reports",
|
||||||
|
Stdout: &stdout,
|
||||||
|
OutputFormat: OutputFormatJSON,
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Inspect() configured JSON error = %v", err)
|
||||||
|
}
|
||||||
|
result := decodeAppResult(t, stdout.String())
|
||||||
|
if result["pipeline_id"] != "reports" || result["source_backend"] != "local" || result["bundle_count"] != float64(1) {
|
||||||
|
t.Fatalf("result = %#v, want configured inspect metadata", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestInspectRequiresPath(t *testing.T) {
|
func TestInspectRequiresPath(t *testing.T) {
|
||||||
err := Inspect(context.Background(), InspectOptions{})
|
err := Inspect(context.Background(), InspectOptions{})
|
||||||
if err == nil || !strings.Contains(err.Error(), "requires a path") {
|
if err == nil || !strings.Contains(err.Error(), "requires a path") {
|
||||||
|
|||||||
128
internal/app/manifest.go
Normal file
128
internal/app/manifest.go
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
producerbundle "gitea.maximumdirect.net/eric/distributor/pkg/bundle"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ManifestCreateOptions struct {
|
||||||
|
Root string
|
||||||
|
ID string
|
||||||
|
Created string
|
||||||
|
Files []string
|
||||||
|
Overwrite bool
|
||||||
|
Stdout io.Writer
|
||||||
|
OutputFormat OutputFormat
|
||||||
|
}
|
||||||
|
|
||||||
|
func ManifestCreate(ctx context.Context, options ManifestCreateOptions) error {
|
||||||
|
if err := ValidateOutputFormat(options.OutputFormat); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if options.Root == "" {
|
||||||
|
return fmt.Errorf("manifest create command requires a bundle path")
|
||||||
|
}
|
||||||
|
if options.ID == "" {
|
||||||
|
return fmt.Errorf("manifest create command requires --id")
|
||||||
|
}
|
||||||
|
|
||||||
|
created, err := parseOptionalCreated(options.Created)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
files := normalizeManifestFiles(options.Files)
|
||||||
|
buildOptions := producerbundle.BuildOptions{
|
||||||
|
Root: options.Root,
|
||||||
|
ID: options.ID,
|
||||||
|
Created: created,
|
||||||
|
Files: files,
|
||||||
|
Scan: len(files) == 0,
|
||||||
|
}
|
||||||
|
manifest, err := producerbundle.BuildManifest(buildOptions)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := producerbundle.WriteManifest(options.Root, manifest, producerbundle.WriteManifestOptions{Overwrite: options.Overwrite}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
loaded, err := producerbundle.LoadManifest(options.Root)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := producerbundle.ValidateBundle(options.Root, loaded); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
result := manifestCreateResultFromManifest(options.Root, loaded)
|
||||||
|
if IsJSONOutput(options.OutputFormat) {
|
||||||
|
return WriteJSONEnvelope(options.Stdout, "manifest create", true, nil, result, nil)
|
||||||
|
}
|
||||||
|
if options.Stdout != nil {
|
||||||
|
_, err = fmt.Fprintf(options.Stdout, "created %s\nbundle: %s\nfiles: %d\ndigest: %s\n", producerbundle.ManifestName, result.ID, result.FileCount, result.Digest)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseOptionalCreated(value string) (time.Time, error) {
|
||||||
|
if value == "" {
|
||||||
|
return time.Time{}, nil
|
||||||
|
}
|
||||||
|
created, err := time.Parse(time.RFC3339, value)
|
||||||
|
if err != nil {
|
||||||
|
return time.Time{}, fmt.Errorf("created must be RFC3339: %w", err)
|
||||||
|
}
|
||||||
|
return created, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeManifestFiles(files []string) []string {
|
||||||
|
normalized := make([]string, 0, len(files))
|
||||||
|
for _, file := range files {
|
||||||
|
normalized = append(normalized, filepath.ToSlash(filepath.Clean(strings.ReplaceAll(file, "\\", string(filepath.Separator)))))
|
||||||
|
}
|
||||||
|
return normalized
|
||||||
|
}
|
||||||
|
|
||||||
|
type manifestCreateResult struct {
|
||||||
|
ManifestPath string `json:"manifest_path"`
|
||||||
|
Root string `json:"root"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
Created string `json:"created"`
|
||||||
|
Digest string `json:"digest"`
|
||||||
|
FileCount int `json:"file_count"`
|
||||||
|
Files []manifestCreateFileResult `json:"files"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type manifestCreateFileResult struct {
|
||||||
|
Path string `json:"path"`
|
||||||
|
SHA256 string `json:"sha256"`
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func manifestCreateResultFromManifest(root string, manifest producerbundle.Manifest) manifestCreateResult {
|
||||||
|
result := manifestCreateResult{
|
||||||
|
ManifestPath: filepath.ToSlash(filepath.Join(root, producerbundle.ManifestName)),
|
||||||
|
Root: filepath.ToSlash(root),
|
||||||
|
ID: manifest.ID,
|
||||||
|
Created: manifest.Created.Format(time.RFC3339),
|
||||||
|
Digest: manifest.Digest,
|
||||||
|
FileCount: len(manifest.Files),
|
||||||
|
Files: make([]manifestCreateFileResult, 0, len(manifest.Files)),
|
||||||
|
}
|
||||||
|
for _, file := range manifest.Files {
|
||||||
|
result.Files = append(result.Files, manifestCreateFileResult{
|
||||||
|
Path: file.Path,
|
||||||
|
SHA256: file.SHA256,
|
||||||
|
Size: file.Size,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
76
internal/app/output.go
Normal file
76
internal/app/output.go
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
)
|
||||||
|
|
||||||
|
const outputSchemaVersion = 1
|
||||||
|
|
||||||
|
type OutputFormat string
|
||||||
|
|
||||||
|
const (
|
||||||
|
OutputFormatText OutputFormat = "text"
|
||||||
|
OutputFormatJSON OutputFormat = "json"
|
||||||
|
)
|
||||||
|
|
||||||
|
type OutputWarning struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type OutputError struct {
|
||||||
|
PipelineID string `json:"pipeline_id,omitempty"`
|
||||||
|
DestinationID string `json:"destination_id,omitempty"`
|
||||||
|
Backend string `json:"backend,omitempty"`
|
||||||
|
BundlePath string `json:"bundle_path,omitempty"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type outputEnvelope struct {
|
||||||
|
SchemaVersion int `json:"schema_version"`
|
||||||
|
Command string `json:"command"`
|
||||||
|
OK bool `json:"ok"`
|
||||||
|
Warnings []OutputWarning `json:"warnings"`
|
||||||
|
Result any `json:"result"`
|
||||||
|
Errors []OutputError `json:"errors,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func NormalizeOutputFormat(format OutputFormat) OutputFormat {
|
||||||
|
if format == "" {
|
||||||
|
return OutputFormatText
|
||||||
|
}
|
||||||
|
return format
|
||||||
|
}
|
||||||
|
|
||||||
|
func ValidateOutputFormat(format OutputFormat) error {
|
||||||
|
switch NormalizeOutputFormat(format) {
|
||||||
|
case OutputFormatText, OutputFormatJSON:
|
||||||
|
return nil
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("format must be text or json")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsJSONOutput(format OutputFormat) bool {
|
||||||
|
return NormalizeOutputFormat(format) == OutputFormatJSON
|
||||||
|
}
|
||||||
|
|
||||||
|
func WriteJSONEnvelope(w io.Writer, command string, ok bool, warnings []OutputWarning, result any, errors []OutputError) error {
|
||||||
|
if w == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if warnings == nil {
|
||||||
|
warnings = []OutputWarning{}
|
||||||
|
}
|
||||||
|
envelope := outputEnvelope{
|
||||||
|
SchemaVersion: outputSchemaVersion,
|
||||||
|
Command: command,
|
||||||
|
OK: ok,
|
||||||
|
Warnings: warnings,
|
||||||
|
Result: result,
|
||||||
|
Errors: errors,
|
||||||
|
}
|
||||||
|
encoder := json.NewEncoder(w)
|
||||||
|
return encoder.Encode(envelope)
|
||||||
|
}
|
||||||
@@ -2,10 +2,8 @@ package app
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"strings"
|
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/distributor/internal/bundle"
|
"gitea.maximumdirect.net/eric/distributor/internal/bundle"
|
||||||
"gitea.maximumdirect.net/eric/distributor/internal/config"
|
"gitea.maximumdirect.net/eric/distributor/internal/config"
|
||||||
@@ -15,14 +13,35 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type RunOptions struct {
|
type RunOptions struct {
|
||||||
|
ConfigPath string
|
||||||
|
DryRun bool
|
||||||
|
Force bool
|
||||||
|
Stdout io.Writer
|
||||||
|
OutputFormat OutputFormat
|
||||||
|
Notifier notify.Notifier
|
||||||
|
}
|
||||||
|
|
||||||
|
type RunPipelineOptions struct {
|
||||||
ConfigPath string
|
ConfigPath string
|
||||||
|
PipelineID string
|
||||||
|
DryRun bool
|
||||||
|
Force bool
|
||||||
|
Notifier notify.Notifier
|
||||||
|
}
|
||||||
|
|
||||||
|
type RunPipelineWithLocalSourceOptions struct {
|
||||||
|
ConfigPath string
|
||||||
|
PipelineID string
|
||||||
|
SourceRoot string
|
||||||
DryRun bool
|
DryRun bool
|
||||||
Force bool
|
Force bool
|
||||||
Stdout io.Writer
|
|
||||||
Notifier notify.Notifier
|
Notifier notify.Notifier
|
||||||
}
|
}
|
||||||
|
|
||||||
func Run(ctx context.Context, options RunOptions) error {
|
func Run(ctx context.Context, options RunOptions) error {
|
||||||
|
if err := ValidateOutputFormat(options.OutputFormat); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
if err := ctx.Err(); err != nil {
|
if err := ctx.Err(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -38,98 +57,224 @@ func Run(ctx context.Context, options RunOptions) error {
|
|||||||
return runConfig(ctx, cfg, options)
|
return runConfig(ctx, cfg, options)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func RunPipeline(ctx context.Context, options RunPipelineOptions) (RunReport, error) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return RunReport{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
configPath := options.ConfigPath
|
||||||
|
if configPath == "" {
|
||||||
|
configPath = config.DefaultConfigPath
|
||||||
|
}
|
||||||
|
cfg, err := config.LoadFile(configPath)
|
||||||
|
if err != nil {
|
||||||
|
return RunReport{}, err
|
||||||
|
}
|
||||||
|
return runPipelineConfig(ctx, cfg, options)
|
||||||
|
}
|
||||||
|
|
||||||
|
func RunPipelineWithLocalSource(ctx context.Context, options RunPipelineWithLocalSourceOptions) (RunReport, error) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return RunReport{}, err
|
||||||
|
}
|
||||||
|
if options.SourceRoot == "" {
|
||||||
|
return RunReport{}, fmt.Errorf("source root is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
configPath := options.ConfigPath
|
||||||
|
if configPath == "" {
|
||||||
|
configPath = config.DefaultConfigPath
|
||||||
|
}
|
||||||
|
cfg, err := config.LoadFile(configPath)
|
||||||
|
if err != nil {
|
||||||
|
return RunReport{}, err
|
||||||
|
}
|
||||||
|
return runPipelineConfigWithLocalSource(ctx, cfg, options)
|
||||||
|
}
|
||||||
|
|
||||||
func runConfig(ctx context.Context, cfg config.Config, options RunOptions) error {
|
func runConfig(ctx context.Context, cfg config.Config, options RunOptions) error {
|
||||||
return runConfigWithBackendFactory(ctx, cfg, options, newBackendFactoryWithEnvironment)
|
return runConfigWithBackendFactory(ctx, cfg, options, newBackendFactoryWithEnvironment)
|
||||||
}
|
}
|
||||||
|
|
||||||
type backendFactoryProvider func(config.Environment) *backendFactory
|
type backendFactoryProvider func(config.Environment) *backendFactory
|
||||||
|
|
||||||
|
func runPipelineConfig(ctx context.Context, cfg config.Config, options RunPipelineOptions) (RunReport, error) {
|
||||||
|
return runPipelineConfigWithBackendFactory(ctx, cfg, options, newBackendFactoryWithEnvironment)
|
||||||
|
}
|
||||||
|
|
||||||
|
func runPipelineConfigWithLocalSource(ctx context.Context, cfg config.Config, options RunPipelineWithLocalSourceOptions) (RunReport, error) {
|
||||||
|
return runPipelineConfigWithLocalSourceAndBackendFactory(ctx, cfg, options, newBackendFactoryWithEnvironment)
|
||||||
|
}
|
||||||
|
|
||||||
|
func runPipelineConfigWithBackendFactory(ctx context.Context, cfg config.Config, options RunPipelineOptions, provider backendFactoryProvider) (RunReport, error) {
|
||||||
|
pipeline, ok := findPipeline(cfg, options.PipelineID)
|
||||||
|
if !ok {
|
||||||
|
return RunReport{}, PipelineNotFoundError{ID: options.PipelineID}
|
||||||
|
}
|
||||||
|
return buildRunReportWithBackendFactory(ctx, config.Config{
|
||||||
|
Server: cfg.Server,
|
||||||
|
Secrets: cfg.Secrets,
|
||||||
|
Pipelines: []config.Pipeline{pipeline},
|
||||||
|
}, RunOptions{
|
||||||
|
DryRun: options.DryRun,
|
||||||
|
Force: options.Force,
|
||||||
|
Notifier: options.Notifier,
|
||||||
|
}, provider)
|
||||||
|
}
|
||||||
|
|
||||||
|
func runPipelineConfigWithLocalSourceAndBackendFactory(ctx context.Context, cfg config.Config, options RunPipelineWithLocalSourceOptions, provider backendFactoryProvider) (RunReport, error) {
|
||||||
|
pipeline, ok := findPipeline(cfg, options.PipelineID)
|
||||||
|
if !ok {
|
||||||
|
return RunReport{}, PipelineNotFoundError{ID: options.PipelineID}
|
||||||
|
}
|
||||||
|
return buildRunReport(ctx, config.Config{
|
||||||
|
Server: cfg.Server,
|
||||||
|
Secrets: cfg.Secrets,
|
||||||
|
Pipelines: []config.Pipeline{pipeline},
|
||||||
|
}, RunOptions{
|
||||||
|
DryRun: options.DryRun,
|
||||||
|
Force: options.Force,
|
||||||
|
Notifier: options.Notifier,
|
||||||
|
}, provider, &localSourceRoot{
|
||||||
|
pipelineID: options.PipelineID,
|
||||||
|
root: options.SourceRoot,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func runConfigWithBackendFactory(ctx context.Context, cfg config.Config, options RunOptions, provider backendFactoryProvider) error {
|
func runConfigWithBackendFactory(ctx context.Context, cfg config.Config, options RunOptions, provider backendFactoryProvider) error {
|
||||||
|
report, err := buildRunReportWithBackendFactory(ctx, cfg, options, provider)
|
||||||
|
if err != nil && !IsPartialResultError(err) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if outputErr := WriteRunReport(options.Stdout, options.OutputFormat, report); outputErr != nil {
|
||||||
|
return outputErr
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildRunReportWithBackendFactory(ctx context.Context, cfg config.Config, options RunOptions, provider backendFactoryProvider) (RunReport, error) {
|
||||||
|
return buildRunReport(ctx, cfg, options, provider, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
type localSourceRoot struct {
|
||||||
|
pipelineID string
|
||||||
|
root string
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildRunReport(ctx context.Context, cfg config.Config, options RunOptions, provider backendFactoryProvider, sourceRoot *localSourceRoot) (RunReport, error) {
|
||||||
notifier := options.Notifier
|
notifier := options.Notifier
|
||||||
if notifier == nil {
|
if notifier == nil {
|
||||||
notifier = notify.Noop{}
|
notifier = notify.Noop{}
|
||||||
}
|
}
|
||||||
summary := runSummary{dryRun: options.DryRun}
|
summary := runSummary{dryRun: options.DryRun}
|
||||||
|
report := RunReport{
|
||||||
|
DryRun: options.DryRun,
|
||||||
|
Pipelines: []RunPipelineSummary{},
|
||||||
|
Actions: []RunActionRecord{},
|
||||||
|
}
|
||||||
var failures runFailures
|
var failures runFailures
|
||||||
secretLoad, err := config.LoadSecretEnvironment(cfg.Secrets.Directory, nil)
|
secretLoad, err := config.LoadSecretEnvironment(cfg.Secrets.Directory, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return report, err
|
||||||
}
|
|
||||||
if options.Stdout != nil {
|
|
||||||
if err := writeSecretConflictWarnings(options.Stdout, secretLoad.Conflicts); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
secretWarnings := secretConflictWarnings(secretLoad.Conflicts)
|
||||||
|
report.PreambleWarnings = append(report.PreambleWarnings, secretWarnings...)
|
||||||
|
report.addWarnings(secretWarnings)
|
||||||
backends := provider(secretLoad.Environment)
|
backends := provider(secretLoad.Environment)
|
||||||
backends.readOnlyKnownHosts = options.DryRun
|
backends.readOnlyKnownHosts = options.DryRun
|
||||||
transforms := newTransformRegistry()
|
transforms := newTransformRegistry()
|
||||||
if options.Stdout != nil {
|
|
||||||
if _, err := fmt.Fprintf(options.Stdout, "Configured pipelines: %d\n", len(cfg.Pipelines)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, pipeline := range cfg.Pipelines {
|
for _, pipeline := range cfg.Pipelines {
|
||||||
if options.Stdout != nil {
|
pipelineWarnings := sshWarnings(pipeline)
|
||||||
if err := writeSSHWarnings(options.Stdout, pipeline); err != nil {
|
report.addWarnings(pipelineWarnings)
|
||||||
return err
|
sourceBackend, bundles, sourceBackendName, err := openPipelineSource(ctx, backends, pipeline, sourceRoot)
|
||||||
}
|
|
||||||
}
|
|
||||||
sourceBackend, err := backends.openSource(ctx, pipeline.Source)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("pipeline %s source backend %s: %w", pipeline.ID, pipeline.Source.Backend, err)
|
return report, err
|
||||||
}
|
}
|
||||||
bundles, err := bundle.Discover(ctx, sourceBackend, "")
|
report.Pipelines = append(report.Pipelines, RunPipelineSummary{
|
||||||
if err != nil {
|
ID: pipeline.ID,
|
||||||
closeBackend(sourceBackend)
|
SourceBackend: sourceBackendName,
|
||||||
return fmt.Errorf("pipeline %s source backend %s discover source bundles: %w", pipeline.ID, pipeline.Source.Backend, err)
|
BundleCount: len(bundles),
|
||||||
}
|
Destinations: destinationIDs(pipeline.Destinations),
|
||||||
if options.Stdout != nil {
|
Warnings: pipelineWarnings,
|
||||||
if _, err := fmt.Fprintf(options.Stdout, "- pipeline=%s source=%s bundles=%d destinations=%s\n", pipeline.ID, pipeline.Source.Backend, len(bundles), destinationSummary(pipeline.Destinations)); err != nil {
|
})
|
||||||
closeBackend(sourceBackend)
|
pipelineIndex := len(report.Pipelines) - 1
|
||||||
return err
|
for _, destination := range pipeline.Destinations {
|
||||||
|
selections := selectDestinationBundles(destination, bundles)
|
||||||
|
if isFixedPathDestination(destination) {
|
||||||
|
summary.recordFixedPath()
|
||||||
|
if options.DryRun {
|
||||||
|
warning := fixedPathSelectionWarning(pipeline.ID, destination.ID, selections, len(bundles))
|
||||||
|
report.addWarning(warning)
|
||||||
|
report.Pipelines[pipelineIndex].events = append(report.Pipelines[pipelineIndex].events, warningEvent(warning))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
if len(selections) == 0 {
|
||||||
for _, sourceBundle := range bundles {
|
continue
|
||||||
for _, destination := range pipeline.Destinations {
|
}
|
||||||
destinationBackend, err := backends.openDestination(ctx, destination)
|
destinationBackend, err := backends.openDestination(ctx, destination)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
failures.add(pipeline.ID, destination.ID, destination.Backend, storage.DisplayPath(sourceBundle.RootRelativePath), err)
|
for _, selection := range selections {
|
||||||
|
failures.add(pipeline.ID, destination.ID, destination.Backend, storage.DisplayPath(selection.SourceBundle.RootRelativePath), err)
|
||||||
summary.recordFailure()
|
summary.recordFailure()
|
||||||
if options.Stdout != nil {
|
report.Actions = append(report.Actions, errorAction(pipeline.ID, destination.ID, destination.Backend, selection.SourceBundle.RootRelativePath, err))
|
||||||
writeErrorLine(options.Stdout, sourceBundle.RootRelativePath, destination.ID, destination.Backend, err)
|
report.Pipelines[pipelineIndex].events = append(report.Pipelines[pipelineIndex].events, actionEvent(len(report.Actions)-1))
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
}
|
||||||
closeDestination := true
|
continue
|
||||||
deferCloseDestination := func() {
|
}
|
||||||
if closeDestination {
|
closeDestination := true
|
||||||
closeBackend(destinationBackend)
|
deferCloseDestination := func() {
|
||||||
closeDestination = false
|
if closeDestination {
|
||||||
}
|
closeBackend(destinationBackend)
|
||||||
|
closeDestination = false
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
for _, selection := range selections {
|
||||||
|
sourceBundle := selection.SourceBundle
|
||||||
req := publish.Request{
|
req := publish.Request{
|
||||||
PipelineID: pipeline.ID,
|
PipelineID: pipeline.ID,
|
||||||
DestinationID: destination.ID,
|
DestinationID: destination.ID,
|
||||||
SourceBundle: sourceBundle,
|
SourceBundle: sourceBundle,
|
||||||
SourceBackend: sourceBackend,
|
SourceBackend: sourceBackend,
|
||||||
DestinationBackend: destinationBackend,
|
DestinationBackend: destinationBackend,
|
||||||
DestinationBundlePath: sourceBundle.RootRelativePath,
|
DestinationBundlePath: selection.DestinationBundlePath,
|
||||||
|
PathMapping: destination.PathMap.Mode,
|
||||||
Publish: *destination.Publish,
|
Publish: *destination.Publish,
|
||||||
Transform: destination.Transform,
|
Transform: destination.Transform,
|
||||||
|
Links: destination.Links,
|
||||||
Transformers: transforms,
|
Transformers: transforms,
|
||||||
Transfer: destination.Transfer,
|
Transfer: destination.Transfer,
|
||||||
DistributorVersion: Version,
|
DistributorVersion: Version,
|
||||||
Force: options.Force,
|
Force: options.Force,
|
||||||
}
|
}
|
||||||
plan, err := publish.Build(ctx, req)
|
plan, err := publish.Build(ctx, req)
|
||||||
if err != nil && plan.DestinationID == "" {
|
|
||||||
plan = publish.Plan{DestinationID: destination.ID, BundlePath: sourceBundle.RootRelativePath}
|
|
||||||
}
|
|
||||||
if options.Stdout != nil {
|
|
||||||
writePlanLine(options.Stdout, destination.Backend, plan, err)
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
deferCloseDestination()
|
if plan.PipelineID == "" {
|
||||||
|
plan.PipelineID = pipeline.ID
|
||||||
|
}
|
||||||
|
if plan.DestinationID == "" {
|
||||||
|
plan.DestinationID = destination.ID
|
||||||
|
}
|
||||||
|
if plan.BundleID == "" {
|
||||||
|
plan.BundleID = sourceBundle.Manifest.ID
|
||||||
|
}
|
||||||
|
if plan.BundlePath == "" {
|
||||||
|
plan.BundlePath = sourceBundle.RootRelativePath
|
||||||
|
}
|
||||||
|
if plan.DestinationBundlePath == "" {
|
||||||
|
plan.DestinationBundlePath = selection.DestinationBundlePath
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if isFixedPathDestination(destination) {
|
||||||
|
plan.PathMapping = config.PathMappingFixed
|
||||||
|
if options.DryRun && isDestructiveFixedPathAction(plan.Action) {
|
||||||
|
warning := fixedPathReplacementWarning(plan)
|
||||||
|
report.addWarning(warning)
|
||||||
|
report.Pipelines[pipelineIndex].events = append(report.Pipelines[pipelineIndex].events, warningEvent(warning))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
report.Actions = append(report.Actions, runActionFromPlan(destination.Backend, plan, err))
|
||||||
|
report.Pipelines[pipelineIndex].events = append(report.Pipelines[pipelineIndex].events, actionEvent(len(report.Actions)-1))
|
||||||
|
if err != nil {
|
||||||
failures.add(pipeline.ID, destination.ID, destination.Backend, storage.DisplayPath(sourceBundle.RootRelativePath), err)
|
failures.add(pipeline.ID, destination.ID, destination.Backend, storage.DisplayPath(sourceBundle.RootRelativePath), err)
|
||||||
summary.recordFailure()
|
summary.recordFailure()
|
||||||
continue
|
continue
|
||||||
@@ -137,34 +282,55 @@ func runConfigWithBackendFactory(ctx context.Context, cfg config.Config, options
|
|||||||
summary.recordPlan(plan.Action)
|
summary.recordPlan(plan.Action)
|
||||||
if !options.DryRun {
|
if !options.DryRun {
|
||||||
if err := publish.Execute(ctx, req, plan); err != nil {
|
if err := publish.Execute(ctx, req, plan); err != nil {
|
||||||
deferCloseDestination()
|
|
||||||
failures.add(pipeline.ID, destination.ID, destination.Backend, storage.DisplayPath(sourceBundle.RootRelativePath), err)
|
failures.add(pipeline.ID, destination.ID, destination.Backend, storage.DisplayPath(sourceBundle.RootRelativePath), err)
|
||||||
summary.recordFailure()
|
summary.recordFailure()
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if shouldNotify(plan.Action) {
|
if shouldNotify(plan.Action) {
|
||||||
if err := notifier.Notify(ctx, notifyEvent(plan)); err != nil {
|
if err := notifier.Notify(ctx, notifyEvent(plan)); err != nil {
|
||||||
deferCloseDestination()
|
|
||||||
failures.add(pipeline.ID, destination.ID, destination.Backend, storage.DisplayPath(sourceBundle.RootRelativePath), err)
|
failures.add(pipeline.ID, destination.ID, destination.Backend, storage.DisplayPath(sourceBundle.RootRelativePath), err)
|
||||||
summary.recordFailure()
|
summary.recordFailure()
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
deferCloseDestination()
|
|
||||||
}
|
}
|
||||||
|
deferCloseDestination()
|
||||||
}
|
}
|
||||||
closeBackend(sourceBackend)
|
closeBackend(sourceBackend)
|
||||||
}
|
}
|
||||||
if options.Stdout != nil {
|
report.Summary = summary.Result()
|
||||||
if _, err := fmt.Fprintln(options.Stdout, summary.Line()); err != nil {
|
report.OutputErrors = failures.outputErrors()
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(failures.items) > 0 {
|
if len(failures.items) > 0 {
|
||||||
return failures
|
return report, failures
|
||||||
}
|
}
|
||||||
return nil
|
return report, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func openPipelineSource(ctx context.Context, backends *backendFactory, pipeline config.Pipeline, sourceRoot *localSourceRoot) (storage.Backend, []bundle.Bundle, string, error) {
|
||||||
|
if sourceRoot != nil && sourceRoot.pipelineID == pipeline.ID {
|
||||||
|
sourceBackend, err := backends.openLocalPath(ctx, sourceRoot.root)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, config.BackendLocal, fmt.Errorf("pipeline %s source backend %s: %w", pipeline.ID, config.BackendLocal, err)
|
||||||
|
}
|
||||||
|
sourceBundle, err := bundle.Validate(ctx, sourceBackend, "")
|
||||||
|
if err != nil {
|
||||||
|
closeBackend(sourceBackend)
|
||||||
|
return nil, nil, config.BackendLocal, fmt.Errorf("pipeline %s source backend %s validate source bundle: %w", pipeline.ID, config.BackendLocal, err)
|
||||||
|
}
|
||||||
|
return sourceBackend, []bundle.Bundle{sourceBundle}, config.BackendLocal, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
sourceBackend, err := backends.openSource(ctx, pipeline.Source)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, pipeline.Source.Backend, fmt.Errorf("pipeline %s source backend %s: %w", pipeline.ID, pipeline.Source.Backend, err)
|
||||||
|
}
|
||||||
|
bundles, err := bundle.Discover(ctx, sourceBackend, "")
|
||||||
|
if err != nil {
|
||||||
|
closeBackend(sourceBackend)
|
||||||
|
return nil, nil, pipeline.Source.Backend, fmt.Errorf("pipeline %s source backend %s discover source bundles: %w", pipeline.ID, pipeline.Source.Backend, err)
|
||||||
|
}
|
||||||
|
return sourceBackend, bundles, pipeline.Source.Backend, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type closeableBackend interface {
|
type closeableBackend interface {
|
||||||
@@ -178,175 +344,3 @@ func closeBackend(backend storage.Backend) {
|
|||||||
}
|
}
|
||||||
_ = closeable.Close()
|
_ = closeable.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
func writePlanLine(w io.Writer, backend string, plan publish.Plan, planErr error) {
|
|
||||||
if w == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if planErr != nil {
|
|
||||||
destinationID := plan.DestinationID
|
|
||||||
if destinationID == "" {
|
|
||||||
destinationID = "unknown"
|
|
||||||
}
|
|
||||||
fmt.Fprintf(w, " - bundle=%s destination=%s backend=%s action=error reason=%q\n", storage.DisplayPath(plan.BundlePath), destinationID, backend, planErr.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
fmt.Fprintf(w, " - bundle=%s destination=%s backend=%s action=%s outputs=%s reason=%q\n", storage.DisplayPath(plan.BundlePath), plan.DestinationID, backend, plan.Action, outputSummary(plan.Outputs), plan.Reason)
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeErrorLine(w io.Writer, bundlePath, destinationID, backend string, err error) {
|
|
||||||
if w == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
fmt.Fprintf(w, " - bundle=%s destination=%s backend=%s action=error reason=%q\n", storage.DisplayPath(bundlePath), destinationID, backend, err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
func outputSummary(outputs []publish.Output) string {
|
|
||||||
if len(outputs) == 0 {
|
|
||||||
return "none"
|
|
||||||
}
|
|
||||||
paths := make([]string, 0, len(outputs))
|
|
||||||
for _, output := range outputs {
|
|
||||||
paths = append(paths, output.DestinationPath)
|
|
||||||
}
|
|
||||||
return strings.Join(paths, ",")
|
|
||||||
}
|
|
||||||
|
|
||||||
func destinationSummary(destinations []config.Destination) string {
|
|
||||||
if len(destinations) == 0 {
|
|
||||||
return "none"
|
|
||||||
}
|
|
||||||
ids := make([]string, 0, len(destinations))
|
|
||||||
for _, destination := range destinations {
|
|
||||||
ids = append(ids, destination.ID)
|
|
||||||
}
|
|
||||||
return strings.Join(ids, ",")
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeSecretConflictWarnings(w io.Writer, conflicts []config.SecretConflict) error {
|
|
||||||
for _, conflict := range conflicts {
|
|
||||||
if _, err := fmt.Fprintf(w, "Warning: secret %s ignored because the real environment already has that variable\n", conflict.Name); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeSSHWarnings(w io.Writer, pipeline config.Pipeline) error {
|
|
||||||
if pipeline.Source.Backend == config.BackendSSH && pipeline.Source.SSH.HostKeyPolicy == config.HostKeyPolicyOff {
|
|
||||||
if _, err := fmt.Fprintf(w, "Warning: pipeline=%s source host_key_policy=off disables SSH host key checking\n", pipeline.ID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, destination := range pipeline.Destinations {
|
|
||||||
if destination.Backend == config.BackendSSH && destination.SSH.HostKeyPolicy == config.HostKeyPolicyOff {
|
|
||||||
if _, err := fmt.Fprintf(w, "Warning: pipeline=%s destination=%s host_key_policy=off disables SSH host key checking\n", pipeline.ID, destination.ID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func shouldNotify(action publish.Action) bool {
|
|
||||||
return action == publish.ActionPublishNew || action == publish.ActionReplaceOlder || action == publish.ActionForceReplace
|
|
||||||
}
|
|
||||||
|
|
||||||
func notifyEvent(plan publish.Plan) notify.Event {
|
|
||||||
outputs := make([]notify.Output, 0, len(plan.Outputs))
|
|
||||||
for _, output := range plan.Outputs {
|
|
||||||
outputs = append(outputs, notify.Output{
|
|
||||||
Path: output.DestinationPath,
|
|
||||||
Kind: output.Kind,
|
|
||||||
SourcePath: output.SourcePath,
|
|
||||||
Transform: output.Transform,
|
|
||||||
SHA256: output.SHA256,
|
|
||||||
Size: output.Size,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return notify.Event{
|
|
||||||
PipelineID: plan.PipelineID,
|
|
||||||
DestinationID: plan.DestinationID,
|
|
||||||
BundleID: plan.BundleID,
|
|
||||||
BundlePath: plan.BundlePath,
|
|
||||||
Action: string(plan.Action),
|
|
||||||
Outputs: outputs,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type runSummary struct {
|
|
||||||
dryRun bool
|
|
||||||
planned int
|
|
||||||
publishNew int
|
|
||||||
replaceOlder int
|
|
||||||
forceReplace int
|
|
||||||
skipped int
|
|
||||||
failures int
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *runSummary) recordPlan(action publish.Action) {
|
|
||||||
s.planned++
|
|
||||||
switch action {
|
|
||||||
case publish.ActionPublishNew:
|
|
||||||
s.publishNew++
|
|
||||||
case publish.ActionReplaceOlder:
|
|
||||||
s.replaceOlder++
|
|
||||||
case publish.ActionForceReplace:
|
|
||||||
s.forceReplace++
|
|
||||||
case publish.ActionSkipSame, publish.ActionSkipDestinationNewer:
|
|
||||||
s.skipped++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *runSummary) recordFailure() {
|
|
||||||
s.failures++
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s runSummary) Line() string {
|
|
||||||
status := "ok"
|
|
||||||
if s.failures > 0 {
|
|
||||||
status = "failed"
|
|
||||||
}
|
|
||||||
return fmt.Sprintf("Final status: %s planned=%d publish_new=%d replace_older=%d force_replace=%d skipped=%d failed=%d dry_run=%t", status, s.planned, s.publishNew, s.replaceOlder, s.forceReplace, s.skipped, s.failures, s.dryRun)
|
|
||||||
}
|
|
||||||
|
|
||||||
type runFailure struct {
|
|
||||||
pipelineID string
|
|
||||||
destinationID string
|
|
||||||
backend string
|
|
||||||
bundlePath string
|
|
||||||
err error
|
|
||||||
}
|
|
||||||
|
|
||||||
type runFailures struct {
|
|
||||||
items []runFailure
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *runFailures) add(pipelineID, destinationID, backend, bundlePath string, err error) {
|
|
||||||
f.items = append(f.items, runFailure{
|
|
||||||
pipelineID: pipelineID,
|
|
||||||
destinationID: destinationID,
|
|
||||||
backend: backend,
|
|
||||||
bundlePath: bundlePath,
|
|
||||||
err: err,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f runFailures) Error() string {
|
|
||||||
if len(f.items) == 0 {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
parts := make([]string, 0, len(f.items))
|
|
||||||
for _, item := range f.items {
|
|
||||||
parts = append(parts, fmt.Sprintf("pipeline %s destination %s backend %s bundle %s: %v", item.pipelineID, item.destinationID, item.backend, item.bundlePath, item.err))
|
|
||||||
}
|
|
||||||
return "run failed: " + strings.Join(parts, "; ")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f runFailures) Unwrap() error {
|
|
||||||
errs := make([]error, 0, len(f.items))
|
|
||||||
for _, item := range f.items {
|
|
||||||
errs = append(errs, item.err)
|
|
||||||
}
|
|
||||||
return errors.Join(errs...)
|
|
||||||
}
|
|
||||||
|
|||||||
131
internal/app/run_coordinator.go
Normal file
131
internal/app/run_coordinator.go
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type PipelineRunID string
|
||||||
|
|
||||||
|
type PipelineRunStatus string
|
||||||
|
|
||||||
|
const (
|
||||||
|
PipelineRunRunning PipelineRunStatus = "running"
|
||||||
|
PipelineRunSucceeded PipelineRunStatus = "succeeded"
|
||||||
|
PipelineRunFailed PipelineRunStatus = "failed"
|
||||||
|
)
|
||||||
|
|
||||||
|
type PipelineRunRecord struct {
|
||||||
|
ID PipelineRunID `json:"id"`
|
||||||
|
PipelineID string `json:"pipeline_id"`
|
||||||
|
Status PipelineRunStatus `json:"status"`
|
||||||
|
StartedAt time.Time `json:"started_at"`
|
||||||
|
FinishedAt *time.Time `json:"finished_at,omitempty"`
|
||||||
|
Report RunReport `json:"report,omitempty"`
|
||||||
|
Error string `json:"error,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type DuplicatePipelineRunError struct {
|
||||||
|
PipelineID string
|
||||||
|
RunID PipelineRunID
|
||||||
|
}
|
||||||
|
|
||||||
|
func (err DuplicatePipelineRunError) Error() string {
|
||||||
|
if err.RunID == "" {
|
||||||
|
return fmt.Sprintf("pipeline %q already has an active run", err.PipelineID)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("pipeline %q already has active run %s", err.PipelineID, err.RunID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsDuplicatePipelineRun(err error) bool {
|
||||||
|
var duplicate DuplicatePipelineRunError
|
||||||
|
return errors.As(err, &duplicate)
|
||||||
|
}
|
||||||
|
|
||||||
|
type PipelineRunCoordinator struct {
|
||||||
|
ctx context.Context
|
||||||
|
run pipelineRunFunc
|
||||||
|
now func() time.Time
|
||||||
|
mu sync.Mutex
|
||||||
|
nextID uint64
|
||||||
|
active map[string]PipelineRunRecord
|
||||||
|
}
|
||||||
|
|
||||||
|
type pipelineRunFunc func(context.Context, RunPipelineOptions) (RunReport, error)
|
||||||
|
|
||||||
|
func NewPipelineRunCoordinator(ctx context.Context) *PipelineRunCoordinator {
|
||||||
|
return newPipelineRunCoordinator(ctx, RunPipeline)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newPipelineRunCoordinator(ctx context.Context, run pipelineRunFunc) *PipelineRunCoordinator {
|
||||||
|
if ctx == nil {
|
||||||
|
ctx = context.Background()
|
||||||
|
}
|
||||||
|
return &PipelineRunCoordinator{
|
||||||
|
ctx: ctx,
|
||||||
|
run: run,
|
||||||
|
now: time.Now,
|
||||||
|
active: map[string]PipelineRunRecord{},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (coordinator *PipelineRunCoordinator) RunPipeline(ctx context.Context, options RunPipelineOptions) (PipelineRunRecord, error) {
|
||||||
|
if ctx == nil {
|
||||||
|
ctx = context.Background()
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return PipelineRunRecord{}, err
|
||||||
|
}
|
||||||
|
record, err := coordinator.admit(options.PipelineID)
|
||||||
|
if err != nil {
|
||||||
|
return PipelineRunRecord{}, err
|
||||||
|
}
|
||||||
|
defer coordinator.clear(options.PipelineID)
|
||||||
|
|
||||||
|
report, runErr := coordinator.run(coordinator.ctx, options)
|
||||||
|
record.Report = report
|
||||||
|
finishedAt := coordinator.now().UTC()
|
||||||
|
record.FinishedAt = &finishedAt
|
||||||
|
if runErr != nil {
|
||||||
|
record.Status = PipelineRunFailed
|
||||||
|
record.Error = runErr.Error()
|
||||||
|
return record, runErr
|
||||||
|
}
|
||||||
|
record.Status = PipelineRunSucceeded
|
||||||
|
return record, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (coordinator *PipelineRunCoordinator) admit(pipelineID string) (PipelineRunRecord, error) {
|
||||||
|
coordinator.mu.Lock()
|
||||||
|
defer coordinator.mu.Unlock()
|
||||||
|
if active, ok := coordinator.active[pipelineID]; ok {
|
||||||
|
return PipelineRunRecord{}, DuplicatePipelineRunError{
|
||||||
|
PipelineID: pipelineID,
|
||||||
|
RunID: active.ID,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
coordinator.nextID++
|
||||||
|
record := PipelineRunRecord{
|
||||||
|
ID: PipelineRunID(fmt.Sprintf("run-%016d", coordinator.nextID)),
|
||||||
|
PipelineID: pipelineID,
|
||||||
|
Status: PipelineRunRunning,
|
||||||
|
StartedAt: coordinator.now().UTC(),
|
||||||
|
}
|
||||||
|
coordinator.active[pipelineID] = record
|
||||||
|
return record, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (coordinator *PipelineRunCoordinator) clear(pipelineID string) {
|
||||||
|
coordinator.mu.Lock()
|
||||||
|
defer coordinator.mu.Unlock()
|
||||||
|
delete(coordinator.active, pipelineID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (coordinator *PipelineRunCoordinator) activeCount() int {
|
||||||
|
coordinator.mu.Lock()
|
||||||
|
defer coordinator.mu.Unlock()
|
||||||
|
return len(coordinator.active)
|
||||||
|
}
|
||||||
223
internal/app/run_coordinator_test.go
Normal file
223
internal/app/run_coordinator_test.go
Normal file
@@ -0,0 +1,223 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPipelineRunCoordinatorRejectsDuplicateActiveRun(t *testing.T) {
|
||||||
|
started := make(chan struct{})
|
||||||
|
release := make(chan struct{})
|
||||||
|
var startedOnce sync.Once
|
||||||
|
coordinator := newPipelineRunCoordinator(context.Background(), func(ctx context.Context, options RunPipelineOptions) (RunReport, error) {
|
||||||
|
startedOnce.Do(func() {
|
||||||
|
close(started)
|
||||||
|
})
|
||||||
|
<-release
|
||||||
|
return RunReport{}, nil
|
||||||
|
})
|
||||||
|
firstResult := make(chan runCoordinatorTestResult, 1)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
record, err := coordinator.RunPipeline(context.Background(), RunPipelineOptions{PipelineID: "reports"})
|
||||||
|
firstResult <- runCoordinatorTestResult{record: record, err: err}
|
||||||
|
}()
|
||||||
|
waitForSignal(t, started, "first run to start")
|
||||||
|
|
||||||
|
_, err := coordinator.RunPipeline(context.Background(), RunPipelineOptions{PipelineID: "reports"})
|
||||||
|
if err == nil || !IsDuplicatePipelineRun(err) {
|
||||||
|
t.Fatalf("RunPipeline() error = %v, want duplicate active run", err)
|
||||||
|
}
|
||||||
|
close(release)
|
||||||
|
result := waitForRunResult(t, firstResult)
|
||||||
|
if result.err != nil {
|
||||||
|
t.Fatalf("first RunPipeline() error = %v", result.err)
|
||||||
|
}
|
||||||
|
if result.record.Status != PipelineRunSucceeded || result.record.ID == "" || result.record.FinishedAt == nil {
|
||||||
|
t.Fatalf("first record = %#v, want succeeded completed record", result.record)
|
||||||
|
}
|
||||||
|
if got := coordinator.activeCount(); got != 0 {
|
||||||
|
t.Fatalf("active count = %d, want 0", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPipelineRunCoordinatorAllowsDifferentActivePipelines(t *testing.T) {
|
||||||
|
started := make(chan string, 2)
|
||||||
|
release := make(chan struct{})
|
||||||
|
coordinator := newPipelineRunCoordinator(context.Background(), func(ctx context.Context, options RunPipelineOptions) (RunReport, error) {
|
||||||
|
started <- options.PipelineID
|
||||||
|
<-release
|
||||||
|
return RunReport{}, nil
|
||||||
|
})
|
||||||
|
firstResult := make(chan runCoordinatorTestResult, 1)
|
||||||
|
secondResult := make(chan runCoordinatorTestResult, 1)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
record, err := coordinator.RunPipeline(context.Background(), RunPipelineOptions{PipelineID: "reports-one"})
|
||||||
|
firstResult <- runCoordinatorTestResult{record: record, err: err}
|
||||||
|
}()
|
||||||
|
go func() {
|
||||||
|
record, err := coordinator.RunPipeline(context.Background(), RunPipelineOptions{PipelineID: "reports-two"})
|
||||||
|
secondResult <- runCoordinatorTestResult{record: record, err: err}
|
||||||
|
}()
|
||||||
|
startedPipelines := map[string]bool{
|
||||||
|
waitForPipelineID(t, started): true,
|
||||||
|
waitForPipelineID(t, started): true,
|
||||||
|
}
|
||||||
|
if !startedPipelines["reports-one"] || !startedPipelines["reports-two"] {
|
||||||
|
t.Fatalf("started pipelines = %#v, want both requested pipelines", startedPipelines)
|
||||||
|
}
|
||||||
|
if got := coordinator.activeCount(); got != 2 {
|
||||||
|
t.Fatalf("active count = %d, want 2", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
close(release)
|
||||||
|
first := waitForRunResult(t, firstResult)
|
||||||
|
second := waitForRunResult(t, secondResult)
|
||||||
|
if first.err != nil || second.err != nil {
|
||||||
|
t.Fatalf("RunPipeline() errors = %v, %v; want nil", first.err, second.err)
|
||||||
|
}
|
||||||
|
if first.record.ID == second.record.ID {
|
||||||
|
t.Fatalf("run IDs matched: %q", first.record.ID)
|
||||||
|
}
|
||||||
|
if got := coordinator.activeCount(); got != 0 {
|
||||||
|
t.Fatalf("active count = %d, want 0", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPipelineRunCoordinatorClearsActiveRunAfterSuccess(t *testing.T) {
|
||||||
|
coordinator := newPipelineRunCoordinator(context.Background(), func(ctx context.Context, options RunPipelineOptions) (RunReport, error) {
|
||||||
|
return RunReport{DryRun: options.DryRun}, nil
|
||||||
|
})
|
||||||
|
|
||||||
|
first, err := coordinator.RunPipeline(context.Background(), RunPipelineOptions{PipelineID: "reports", DryRun: true})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("first RunPipeline() error = %v", err)
|
||||||
|
}
|
||||||
|
second, err := coordinator.RunPipeline(context.Background(), RunPipelineOptions{PipelineID: "reports"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("second RunPipeline() error = %v", err)
|
||||||
|
}
|
||||||
|
if first.Status != PipelineRunSucceeded || second.Status != PipelineRunSucceeded {
|
||||||
|
t.Fatalf("statuses = %s, %s; want succeeded", first.Status, second.Status)
|
||||||
|
}
|
||||||
|
if !first.Report.DryRun {
|
||||||
|
t.Fatalf("first report dry_run = false, want true")
|
||||||
|
}
|
||||||
|
if got := coordinator.activeCount(); got != 0 {
|
||||||
|
t.Fatalf("active count = %d, want 0", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPipelineRunCoordinatorClearsActiveRunAfterFailure(t *testing.T) {
|
||||||
|
runError := errors.New("run failed")
|
||||||
|
attempt := 0
|
||||||
|
coordinator := newPipelineRunCoordinator(context.Background(), func(ctx context.Context, options RunPipelineOptions) (RunReport, error) {
|
||||||
|
attempt++
|
||||||
|
if attempt == 1 {
|
||||||
|
return RunReport{}, runError
|
||||||
|
}
|
||||||
|
return RunReport{}, nil
|
||||||
|
})
|
||||||
|
|
||||||
|
first, err := coordinator.RunPipeline(context.Background(), RunPipelineOptions{PipelineID: "reports"})
|
||||||
|
if !errors.Is(err, runError) {
|
||||||
|
t.Fatalf("first RunPipeline() error = %v, want run failure", err)
|
||||||
|
}
|
||||||
|
if first.Status != PipelineRunFailed || first.Error != runError.Error() || first.FinishedAt == nil {
|
||||||
|
t.Fatalf("first record = %#v, want failed completed record", first)
|
||||||
|
}
|
||||||
|
second, err := coordinator.RunPipeline(context.Background(), RunPipelineOptions{PipelineID: "reports"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("second RunPipeline() error = %v", err)
|
||||||
|
}
|
||||||
|
if second.Status != PipelineRunSucceeded {
|
||||||
|
t.Fatalf("second status = %s, want succeeded", second.Status)
|
||||||
|
}
|
||||||
|
if got := coordinator.activeCount(); got != 0 {
|
||||||
|
t.Fatalf("active count = %d, want 0", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPipelineRunCoordinatorClearsActiveRunAfterCancellation(t *testing.T) {
|
||||||
|
runContext, cancel := context.WithCancel(context.Background())
|
||||||
|
coordinator := newPipelineRunCoordinator(runContext, func(ctx context.Context, options RunPipelineOptions) (RunReport, error) {
|
||||||
|
return RunReport{}, ctx.Err()
|
||||||
|
})
|
||||||
|
cancel()
|
||||||
|
|
||||||
|
record, err := coordinator.RunPipeline(context.Background(), RunPipelineOptions{PipelineID: "reports"})
|
||||||
|
if !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatalf("RunPipeline() error = %v, want context canceled", err)
|
||||||
|
}
|
||||||
|
if record.Status != PipelineRunFailed || record.Error != context.Canceled.Error() {
|
||||||
|
t.Fatalf("record = %#v, want failed cancellation record", record)
|
||||||
|
}
|
||||||
|
_, err = coordinator.RunPipeline(context.Background(), RunPipelineOptions{PipelineID: "reports"})
|
||||||
|
if !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatalf("second RunPipeline() error = %v, want context canceled", err)
|
||||||
|
}
|
||||||
|
if IsDuplicatePipelineRun(err) {
|
||||||
|
t.Fatalf("second RunPipeline() error = %v, want cancellation instead of duplicate", err)
|
||||||
|
}
|
||||||
|
if got := coordinator.activeCount(); got != 0 {
|
||||||
|
t.Fatalf("active count = %d, want 0", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPipelineRunCoordinatorUnknownPipelineDoesNotRemainActive(t *testing.T) {
|
||||||
|
coordinator := newPipelineRunCoordinator(context.Background(), func(ctx context.Context, options RunPipelineOptions) (RunReport, error) {
|
||||||
|
return RunReport{}, PipelineNotFoundError{ID: options.PipelineID}
|
||||||
|
})
|
||||||
|
|
||||||
|
_, err := coordinator.RunPipeline(context.Background(), RunPipelineOptions{PipelineID: "missing"})
|
||||||
|
if err == nil || !IsPipelineNotFound(err) {
|
||||||
|
t.Fatalf("RunPipeline() error = %v, want pipeline not found", err)
|
||||||
|
}
|
||||||
|
_, err = coordinator.RunPipeline(context.Background(), RunPipelineOptions{PipelineID: "missing"})
|
||||||
|
if err == nil || !IsPipelineNotFound(err) || IsDuplicatePipelineRun(err) {
|
||||||
|
t.Fatalf("second RunPipeline() error = %v, want pipeline not found without duplicate", err)
|
||||||
|
}
|
||||||
|
if got := coordinator.activeCount(); got != 0 {
|
||||||
|
t.Fatalf("active count = %d, want 0", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type runCoordinatorTestResult struct {
|
||||||
|
record PipelineRunRecord
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitForSignal(t *testing.T, signal <-chan struct{}, name string) {
|
||||||
|
t.Helper()
|
||||||
|
select {
|
||||||
|
case <-signal:
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatalf("timed out waiting for %s", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitForPipelineID(t *testing.T, pipelineIDs <-chan string) string {
|
||||||
|
t.Helper()
|
||||||
|
select {
|
||||||
|
case pipelineID := <-pipelineIDs:
|
||||||
|
return pipelineID
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatalf("timed out waiting for pipeline start")
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitForRunResult(t *testing.T, results <-chan runCoordinatorTestResult) runCoordinatorTestResult {
|
||||||
|
t.Helper()
|
||||||
|
select {
|
||||||
|
case result := <-results:
|
||||||
|
return result
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatalf("timed out waiting for run result")
|
||||||
|
return runCoordinatorTestResult{}
|
||||||
|
}
|
||||||
|
}
|
||||||
70
internal/app/run_failures.go
Normal file
70
internal/app/run_failures.go
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type runFailure struct {
|
||||||
|
pipelineID string
|
||||||
|
destinationID string
|
||||||
|
backend string
|
||||||
|
bundlePath string
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
type runFailures struct {
|
||||||
|
items []runFailure
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *runFailures) add(pipelineID, destinationID, backend, bundlePath string, err error) {
|
||||||
|
f.items = append(f.items, runFailure{
|
||||||
|
pipelineID: pipelineID,
|
||||||
|
destinationID: destinationID,
|
||||||
|
backend: backend,
|
||||||
|
bundlePath: bundlePath,
|
||||||
|
err: err,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f runFailures) Error() string {
|
||||||
|
if len(f.items) == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
parts := make([]string, 0, len(f.items))
|
||||||
|
for _, item := range f.items {
|
||||||
|
parts = append(parts, fmt.Sprintf("pipeline %s destination %s backend %s bundle %s: %v", item.pipelineID, item.destinationID, item.backend, item.bundlePath, item.err))
|
||||||
|
}
|
||||||
|
return "run failed: " + strings.Join(parts, "; ")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f runFailures) outputErrors() []OutputError {
|
||||||
|
if len(f.items) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
errors := make([]OutputError, 0, len(f.items))
|
||||||
|
for _, item := range f.items {
|
||||||
|
errors = append(errors, OutputError{
|
||||||
|
PipelineID: item.pipelineID,
|
||||||
|
DestinationID: item.destinationID,
|
||||||
|
Backend: item.backend,
|
||||||
|
BundlePath: item.bundlePath,
|
||||||
|
Message: item.err.Error(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return errors
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsPartialResultError(err error) bool {
|
||||||
|
var failures runFailures
|
||||||
|
return errors.As(err, &failures)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f runFailures) Unwrap() error {
|
||||||
|
errs := make([]error, 0, len(f.items))
|
||||||
|
for _, item := range f.items {
|
||||||
|
errs = append(errs, item.err)
|
||||||
|
}
|
||||||
|
return errors.Join(errs...)
|
||||||
|
}
|
||||||
33
internal/app/run_notify.go
Normal file
33
internal/app/run_notify.go
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/notify"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/publish"
|
||||||
|
)
|
||||||
|
|
||||||
|
func shouldNotify(action publish.Action) bool {
|
||||||
|
return action == publish.ActionPublishNew || action == publish.ActionReplaceOlder || action == publish.ActionForceReplace
|
||||||
|
}
|
||||||
|
|
||||||
|
func notifyEvent(plan publish.Plan) notify.Event {
|
||||||
|
outputs := make([]notify.Output, 0, len(plan.Outputs))
|
||||||
|
for _, output := range plan.Outputs {
|
||||||
|
stateOutput := output.StateOutputFile()
|
||||||
|
outputs = append(outputs, notify.Output{
|
||||||
|
Path: stateOutput.Path,
|
||||||
|
Kind: stateOutput.Kind,
|
||||||
|
SourcePath: stateOutput.SourcePath,
|
||||||
|
Transform: stateOutput.Transform,
|
||||||
|
SHA256: stateOutput.SHA256,
|
||||||
|
Size: stateOutput.Size,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return notify.Event{
|
||||||
|
PipelineID: plan.PipelineID,
|
||||||
|
DestinationID: plan.DestinationID,
|
||||||
|
BundleID: plan.BundleID,
|
||||||
|
BundlePath: plan.BundlePath,
|
||||||
|
Action: string(plan.Action),
|
||||||
|
Outputs: outputs,
|
||||||
|
}
|
||||||
|
}
|
||||||
218
internal/app/run_output.go
Normal file
218
internal/app/run_output.go
Normal file
@@ -0,0 +1,218 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/config"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/publish"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/storage"
|
||||||
|
)
|
||||||
|
|
||||||
|
func WriteRunReport(w io.Writer, format OutputFormat, report RunReport) error {
|
||||||
|
if IsJSONOutput(format) {
|
||||||
|
return WriteJSONEnvelope(w, "run", len(report.OutputErrors) == 0, report.Warnings, report, report.OutputErrors)
|
||||||
|
}
|
||||||
|
return writeRunReportText(w, report)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeRunReportText(w io.Writer, report RunReport) error {
|
||||||
|
if w == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err := writeWarnings(w, report.PreambleWarnings); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := fmt.Fprintf(w, "Configured pipelines: %d\n", len(report.Pipelines)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, pipeline := range report.Pipelines {
|
||||||
|
if err := writeWarnings(w, pipeline.Warnings); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := fmt.Fprintf(w, "- pipeline=%s source=%s bundles=%d destinations=%s\n", pipeline.ID, pipeline.SourceBackend, pipeline.BundleCount, destinationIDSummary(pipeline.Destinations)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, event := range pipeline.events {
|
||||||
|
if event.warning != nil {
|
||||||
|
if err := writeWarnings(w, []OutputWarning{*event.warning}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if event.actionIndex < 0 || event.actionIndex >= len(report.Actions) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
writeRunActionLine(w, report.Actions[event.actionIndex])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_, err := fmt.Fprintln(w, report.Summary.Line())
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeRunActionLine(w io.Writer, action RunActionRecord) {
|
||||||
|
if action.Action == "error" {
|
||||||
|
destinationID := action.DestinationID
|
||||||
|
if destinationID == "" {
|
||||||
|
destinationID = "unknown"
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, " - bundle=%s destination=%s backend=%s%s action=error reason=%q\n", action.BundlePath, destinationID, action.Backend, pathMappingRecordSummary(action), action.Reason)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, " - bundle=%s destination=%s backend=%s%s action=%s outputs=%s reason=%q\n", action.BundlePath, action.DestinationID, action.Backend, pathMappingRecordSummary(action), action.Action, outputRecordSummary(action.Outputs), action.Reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
func pathMappingRecordSummary(action RunActionRecord) string {
|
||||||
|
if action.PathMapping != config.PathMappingFixed {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return fmt.Sprintf(" path_mapping=fixed target=%s", action.DestinationPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
func outputRecordSummary(outputs []RunOutputRecord) string {
|
||||||
|
if len(outputs) == 0 {
|
||||||
|
return "none"
|
||||||
|
}
|
||||||
|
paths := make([]string, 0, len(outputs))
|
||||||
|
for _, output := range outputs {
|
||||||
|
paths = append(paths, output.Path)
|
||||||
|
}
|
||||||
|
return strings.Join(paths, ",")
|
||||||
|
}
|
||||||
|
|
||||||
|
func destinationIDSummary(ids []string) string {
|
||||||
|
if len(ids) == 0 {
|
||||||
|
return "none"
|
||||||
|
}
|
||||||
|
return strings.Join(ids, ",")
|
||||||
|
}
|
||||||
|
|
||||||
|
type RunReport struct {
|
||||||
|
DryRun bool `json:"dry_run"`
|
||||||
|
Pipelines []RunPipelineSummary `json:"pipelines"`
|
||||||
|
Actions []RunActionRecord `json:"actions"`
|
||||||
|
Summary RunSummaryCounters `json:"summary"`
|
||||||
|
Warnings []OutputWarning `json:"-"`
|
||||||
|
OutputErrors []OutputError `json:"-"`
|
||||||
|
PreambleWarnings []OutputWarning `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *RunReport) addWarning(warning OutputWarning) {
|
||||||
|
r.Warnings = append(r.Warnings, warning)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *RunReport) addWarnings(warnings []OutputWarning) {
|
||||||
|
r.Warnings = append(r.Warnings, warnings...)
|
||||||
|
}
|
||||||
|
|
||||||
|
type RunPipelineSummary struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
SourceBackend string `json:"source_backend"`
|
||||||
|
BundleCount int `json:"bundle_count"`
|
||||||
|
Destinations []string `json:"destinations"`
|
||||||
|
Warnings []OutputWarning `json:"-"`
|
||||||
|
events []runPipelineEvent
|
||||||
|
}
|
||||||
|
|
||||||
|
type runPipelineEvent struct {
|
||||||
|
warning *OutputWarning
|
||||||
|
actionIndex int
|
||||||
|
}
|
||||||
|
|
||||||
|
func warningEvent(warning OutputWarning) runPipelineEvent {
|
||||||
|
return runPipelineEvent{warning: &warning, actionIndex: -1}
|
||||||
|
}
|
||||||
|
|
||||||
|
func actionEvent(actionIndex int) runPipelineEvent {
|
||||||
|
return runPipelineEvent{actionIndex: actionIndex}
|
||||||
|
}
|
||||||
|
|
||||||
|
type RunActionRecord struct {
|
||||||
|
PipelineID string `json:"pipeline_id,omitempty"`
|
||||||
|
DestinationID string `json:"destination_id"`
|
||||||
|
Backend string `json:"backend"`
|
||||||
|
BundleID string `json:"bundle_id,omitempty"`
|
||||||
|
BundlePath string `json:"bundle_path"`
|
||||||
|
DestinationPath string `json:"destination_path"`
|
||||||
|
PathMapping string `json:"path_mapping,omitempty"`
|
||||||
|
Action string `json:"action"`
|
||||||
|
PrimaryURL string `json:"primary_url,omitempty"`
|
||||||
|
Reason string `json:"reason,omitempty"`
|
||||||
|
Outputs []RunOutputRecord `json:"outputs"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type RunOutputRecord struct {
|
||||||
|
Path string `json:"path"`
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
SourcePath string `json:"source_path,omitempty"`
|
||||||
|
Transform string `json:"transform,omitempty"`
|
||||||
|
URL string `json:"url,omitempty"`
|
||||||
|
SHA256 string `json:"sha256"`
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func runActionFromPlan(backend string, plan publish.Plan, planErr error) RunActionRecord {
|
||||||
|
if planErr != nil {
|
||||||
|
destinationID := plan.DestinationID
|
||||||
|
if destinationID == "" {
|
||||||
|
destinationID = "unknown"
|
||||||
|
}
|
||||||
|
return RunActionRecord{
|
||||||
|
PipelineID: plan.PipelineID,
|
||||||
|
DestinationID: destinationID,
|
||||||
|
Backend: backend,
|
||||||
|
BundleID: plan.BundleID,
|
||||||
|
BundlePath: storage.DisplayPath(plan.BundlePath),
|
||||||
|
DestinationPath: storage.DisplayPath(plan.DestinationBundlePath),
|
||||||
|
PathMapping: plan.PathMapping,
|
||||||
|
Action: "error",
|
||||||
|
PrimaryURL: plan.PrimaryURL,
|
||||||
|
Reason: planErr.Error(),
|
||||||
|
Outputs: []RunOutputRecord{},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return RunActionRecord{
|
||||||
|
PipelineID: plan.PipelineID,
|
||||||
|
DestinationID: plan.DestinationID,
|
||||||
|
Backend: backend,
|
||||||
|
BundleID: plan.BundleID,
|
||||||
|
BundlePath: storage.DisplayPath(plan.BundlePath),
|
||||||
|
DestinationPath: storage.DisplayPath(plan.DestinationBundlePath),
|
||||||
|
PathMapping: plan.PathMapping,
|
||||||
|
Action: string(plan.Action),
|
||||||
|
PrimaryURL: plan.PrimaryURL,
|
||||||
|
Reason: plan.Reason,
|
||||||
|
Outputs: runOutputsFromPlan(plan.Outputs),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func errorAction(pipelineID, destinationID, backend, bundlePath string, err error) RunActionRecord {
|
||||||
|
return RunActionRecord{
|
||||||
|
PipelineID: pipelineID,
|
||||||
|
DestinationID: destinationID,
|
||||||
|
Backend: backend,
|
||||||
|
BundlePath: storage.DisplayPath(bundlePath),
|
||||||
|
DestinationPath: storage.DisplayPath(bundlePath),
|
||||||
|
Action: "error",
|
||||||
|
Reason: err.Error(),
|
||||||
|
Outputs: []RunOutputRecord{},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func runOutputsFromPlan(outputs []publish.Output) []RunOutputRecord {
|
||||||
|
results := make([]RunOutputRecord, 0, len(outputs))
|
||||||
|
for _, output := range outputs {
|
||||||
|
stateOutput := output.StateOutputFile()
|
||||||
|
results = append(results, RunOutputRecord{
|
||||||
|
Path: stateOutput.Path,
|
||||||
|
Kind: stateOutput.Kind,
|
||||||
|
SourcePath: stateOutput.SourcePath,
|
||||||
|
Transform: stateOutput.Transform,
|
||||||
|
URL: stateOutput.URL,
|
||||||
|
SHA256: stateOutput.SHA256,
|
||||||
|
Size: stateOutput.Size,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return results
|
||||||
|
}
|
||||||
79
internal/app/run_selection.go
Normal file
79
internal/app/run_selection.go
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/bundle"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/config"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/publish"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/storage"
|
||||||
|
)
|
||||||
|
|
||||||
|
type destinationBundleSelection struct {
|
||||||
|
SourceBundle bundle.Bundle
|
||||||
|
DestinationBundlePath string
|
||||||
|
}
|
||||||
|
|
||||||
|
func selectDestinationBundles(destination config.Destination, bundles []bundle.Bundle) []destinationBundleSelection {
|
||||||
|
if !isFixedPathDestination(destination) {
|
||||||
|
selections := make([]destinationBundleSelection, 0, len(bundles))
|
||||||
|
for _, sourceBundle := range bundles {
|
||||||
|
selections = append(selections, destinationBundleSelection{
|
||||||
|
SourceBundle: sourceBundle,
|
||||||
|
DestinationBundlePath: sourceBundle.RootRelativePath,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return selections
|
||||||
|
}
|
||||||
|
if len(bundles) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
sourceBundle := newestBundle(bundles)
|
||||||
|
return []destinationBundleSelection{{
|
||||||
|
SourceBundle: sourceBundle,
|
||||||
|
DestinationBundlePath: "",
|
||||||
|
}}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newestBundle(bundles []bundle.Bundle) bundle.Bundle {
|
||||||
|
if len(bundles) == 0 {
|
||||||
|
return bundle.Bundle{}
|
||||||
|
}
|
||||||
|
sorted := append([]bundle.Bundle(nil), bundles...)
|
||||||
|
sort.Slice(sorted, func(i, j int) bool {
|
||||||
|
if sorted[i].Manifest.Created.Equal(sorted[j].Manifest.Created) {
|
||||||
|
return sorted[i].RootRelativePath < sorted[j].RootRelativePath
|
||||||
|
}
|
||||||
|
return sorted[i].Manifest.Created.After(sorted[j].Manifest.Created)
|
||||||
|
})
|
||||||
|
return sorted[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
func isFixedPathDestination(destination config.Destination) bool {
|
||||||
|
return destination.PathMap.Mode == config.PathMappingFixed
|
||||||
|
}
|
||||||
|
|
||||||
|
func fixedPathSelectionWarning(pipelineID, destinationID string, selections []destinationBundleSelection, candidateCount int) OutputWarning {
|
||||||
|
selected := "none"
|
||||||
|
if len(selections) > 0 {
|
||||||
|
selected = storage.DisplayPath(selections[0].SourceBundle.RootRelativePath)
|
||||||
|
}
|
||||||
|
return OutputWarning{Message: fmt.Sprintf("pipeline=%s destination=%s path_mapping=fixed candidates=%d selected_bundle=%s destination_bundle=.", pipelineID, destinationID, candidateCount, selected)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func isDestructiveFixedPathAction(action publish.Action) bool {
|
||||||
|
return action == publish.ActionReplaceOlder || action == publish.ActionForceReplace
|
||||||
|
}
|
||||||
|
|
||||||
|
func fixedPathReplacementWarning(plan publish.Plan) OutputWarning {
|
||||||
|
return OutputWarning{Message: fmt.Sprintf("pipeline=%s destination=%s path_mapping=fixed action=%s replaces destination root for selected_bundle=%s", plan.PipelineID, plan.DestinationID, plan.Action, storage.DisplayPath(plan.BundlePath))}
|
||||||
|
}
|
||||||
|
|
||||||
|
func destinationIDs(destinations []config.Destination) []string {
|
||||||
|
ids := make([]string, 0, len(destinations))
|
||||||
|
for _, destination := range destinations {
|
||||||
|
ids = append(ids, destination.ID)
|
||||||
|
}
|
||||||
|
return ids
|
||||||
|
}
|
||||||
74
internal/app/run_summary.go
Normal file
74
internal/app/run_summary.go
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/publish"
|
||||||
|
)
|
||||||
|
|
||||||
|
type runSummary struct {
|
||||||
|
dryRun bool
|
||||||
|
planned int
|
||||||
|
publishNew int
|
||||||
|
replaceOlder int
|
||||||
|
forceReplace int
|
||||||
|
skipped int
|
||||||
|
failures int
|
||||||
|
fixedPath int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *runSummary) recordPlan(action publish.Action) {
|
||||||
|
s.planned++
|
||||||
|
switch action {
|
||||||
|
case publish.ActionPublishNew:
|
||||||
|
s.publishNew++
|
||||||
|
case publish.ActionReplaceOlder:
|
||||||
|
s.replaceOlder++
|
||||||
|
case publish.ActionForceReplace:
|
||||||
|
s.forceReplace++
|
||||||
|
case publish.ActionSkipSame, publish.ActionSkipDestinationNewer:
|
||||||
|
s.skipped++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *runSummary) recordFailure() {
|
||||||
|
s.failures++
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *runSummary) recordFixedPath() {
|
||||||
|
s.fixedPath++
|
||||||
|
}
|
||||||
|
|
||||||
|
type RunSummaryCounters struct {
|
||||||
|
Status string `json:"status"`
|
||||||
|
Planned int `json:"planned"`
|
||||||
|
PublishNew int `json:"publish_new"`
|
||||||
|
ReplaceOlder int `json:"replace_older"`
|
||||||
|
ForceReplace int `json:"force_replace"`
|
||||||
|
Skipped int `json:"skipped"`
|
||||||
|
Failed int `json:"failed"`
|
||||||
|
DryRun bool `json:"dry_run"`
|
||||||
|
FixedPath int `json:"fixed_path"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s RunSummaryCounters) Line() string {
|
||||||
|
return fmt.Sprintf("Final status: %s planned=%d publish_new=%d replace_older=%d force_replace=%d skipped=%d failed=%d dry_run=%t fixed_path=%d", s.Status, s.Planned, s.PublishNew, s.ReplaceOlder, s.ForceReplace, s.Skipped, s.Failed, s.DryRun, s.FixedPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s runSummary) Result() RunSummaryCounters {
|
||||||
|
status := "ok"
|
||||||
|
if s.failures > 0 {
|
||||||
|
status = "failed"
|
||||||
|
}
|
||||||
|
return RunSummaryCounters{
|
||||||
|
Status: status,
|
||||||
|
Planned: s.planned,
|
||||||
|
PublishNew: s.publishNew,
|
||||||
|
ReplaceOlder: s.replaceOlder,
|
||||||
|
ForceReplace: s.forceReplace,
|
||||||
|
Skipped: s.skipped,
|
||||||
|
Failed: s.failures,
|
||||||
|
DryRun: s.dryRun,
|
||||||
|
FixedPath: s.fixedPath,
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
47
internal/app/run_warnings.go
Normal file
47
internal/app/run_warnings.go
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
func secretConflictWarnings(conflicts []config.SecretConflict) []OutputWarning {
|
||||||
|
warnings := make([]OutputWarning, 0, len(conflicts))
|
||||||
|
for _, conflict := range conflicts {
|
||||||
|
warnings = append(warnings, OutputWarning{
|
||||||
|
Message: fmt.Sprintf("secret %s ignored because the real environment already has that variable", conflict.Name),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return warnings
|
||||||
|
}
|
||||||
|
|
||||||
|
func sshWarnings(pipeline config.Pipeline) []OutputWarning {
|
||||||
|
var warnings []OutputWarning
|
||||||
|
if pipeline.Source.Backend == config.BackendSSH && pipeline.Source.SSH.HostKeyPolicy == config.HostKeyPolicyOff {
|
||||||
|
warnings = append(warnings, OutputWarning{
|
||||||
|
Message: fmt.Sprintf("pipeline=%s source host_key_policy=off disables SSH host key checking", pipeline.ID),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
for _, destination := range pipeline.Destinations {
|
||||||
|
if destination.Backend == config.BackendSSH && destination.SSH.HostKeyPolicy == config.HostKeyPolicyOff {
|
||||||
|
warnings = append(warnings, OutputWarning{
|
||||||
|
Message: fmt.Sprintf("pipeline=%s destination=%s host_key_policy=off disables SSH host key checking", pipeline.ID, destination.ID),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return warnings
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeWarnings(w io.Writer, warnings []OutputWarning) error {
|
||||||
|
if w == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
for _, warning := range warnings {
|
||||||
|
if _, err := fmt.Fprintf(w, "Warning: %s\n", warning.Message); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
62
internal/app/serve.go
Normal file
62
internal/app/serve.go
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ServeOptions struct {
|
||||||
|
ConfigPath string
|
||||||
|
}
|
||||||
|
|
||||||
|
func Serve(ctx context.Context, options ServeOptions) error {
|
||||||
|
if ctx == nil {
|
||||||
|
ctx = context.Background()
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
configPath := options.ConfigPath
|
||||||
|
if configPath == "" {
|
||||||
|
configPath = config.DefaultConfigPath
|
||||||
|
}
|
||||||
|
cfg, err := config.LoadFile(configPath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
secretLoad, err := config.LoadSecretEnvironment(cfg.Secrets.Directory, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
handler, err := newUploadHTTPHandler(ctx, cfg, secretLoad.Environment)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
listener, err := net.Listen("tcp", cfg.Server.HTTP.Bind)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("bind HTTP server %q: %w", cfg.Server.HTTP.Bind, err)
|
||||||
|
}
|
||||||
|
defer listener.Close()
|
||||||
|
|
||||||
|
server := &http.Server{Handler: handler}
|
||||||
|
shutdownDone := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
defer close(shutdownDone)
|
||||||
|
<-ctx.Done()
|
||||||
|
_ = server.Shutdown(context.Background())
|
||||||
|
}()
|
||||||
|
|
||||||
|
err = server.Serve(listener)
|
||||||
|
if errors.Is(err, http.ErrServerClosed) {
|
||||||
|
<-shutdownDone
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
134
internal/app/source_select.go
Normal file
134
internal/app/source_select.go
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/bundle"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/config"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/storage"
|
||||||
|
)
|
||||||
|
|
||||||
|
type PipelineNotFoundError struct {
|
||||||
|
ID string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e PipelineNotFoundError) Error() string {
|
||||||
|
return fmt.Sprintf("pipeline %q not found", e.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsPipelineNotFound(err error) bool {
|
||||||
|
var notFound PipelineNotFoundError
|
||||||
|
return errors.As(err, ¬Found)
|
||||||
|
}
|
||||||
|
|
||||||
|
type sourceCommandOptions struct {
|
||||||
|
CommandName string
|
||||||
|
Path string
|
||||||
|
ConfigPath string
|
||||||
|
PipelineID string
|
||||||
|
BundlePath string
|
||||||
|
}
|
||||||
|
|
||||||
|
type sourceSelection struct {
|
||||||
|
Bundles []bundle.Bundle
|
||||||
|
PipelineID string
|
||||||
|
SourceBackend string
|
||||||
|
ConfigMode bool
|
||||||
|
Warnings []OutputWarning
|
||||||
|
}
|
||||||
|
|
||||||
|
func selectSourceBundles(ctx context.Context, options sourceCommandOptions, provider backendFactoryProvider) (sourceSelection, error) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return sourceSelection{}, err
|
||||||
|
}
|
||||||
|
if options.ConfigPath != "" {
|
||||||
|
cfg, err := config.LoadFile(options.ConfigPath)
|
||||||
|
if err != nil {
|
||||||
|
return sourceSelection{}, err
|
||||||
|
}
|
||||||
|
return selectSourceBundlesFromConfig(ctx, cfg, options, provider)
|
||||||
|
}
|
||||||
|
if options.PipelineID != "" {
|
||||||
|
return sourceSelection{}, fmt.Errorf("configured source mode requires --config")
|
||||||
|
}
|
||||||
|
if options.BundlePath != "" {
|
||||||
|
return sourceSelection{}, fmt.Errorf("configured source mode requires --config")
|
||||||
|
}
|
||||||
|
if options.Path == "" {
|
||||||
|
return sourceSelection{}, fmt.Errorf("%s command requires a path", options.CommandName)
|
||||||
|
}
|
||||||
|
backend, err := newBackendFactory().openLocalPath(ctx, options.Path)
|
||||||
|
if err != nil {
|
||||||
|
return sourceSelection{}, err
|
||||||
|
}
|
||||||
|
defer closeBackend(backend)
|
||||||
|
bundles, err := bundle.Discover(ctx, backend, "")
|
||||||
|
if err != nil {
|
||||||
|
return sourceSelection{}, err
|
||||||
|
}
|
||||||
|
return sourceSelection{Bundles: bundles}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func selectSourceBundlesFromConfig(ctx context.Context, cfg config.Config, options sourceCommandOptions, provider backendFactoryProvider) (sourceSelection, error) {
|
||||||
|
if options.Path != "" {
|
||||||
|
return sourceSelection{}, fmt.Errorf("configured source mode does not accept a local path")
|
||||||
|
}
|
||||||
|
if options.PipelineID == "" {
|
||||||
|
return sourceSelection{}, fmt.Errorf("configured source mode requires --pipeline")
|
||||||
|
}
|
||||||
|
secretLoad, err := config.LoadSecretEnvironment(cfg.Secrets.Directory, nil)
|
||||||
|
if err != nil {
|
||||||
|
return sourceSelection{}, err
|
||||||
|
}
|
||||||
|
pipeline, ok := findPipeline(cfg, options.PipelineID)
|
||||||
|
if !ok {
|
||||||
|
return sourceSelection{}, PipelineNotFoundError{ID: options.PipelineID}
|
||||||
|
}
|
||||||
|
backends := provider(secretLoad.Environment)
|
||||||
|
sourceBackend, err := backends.openSource(ctx, pipeline.Source)
|
||||||
|
if err != nil {
|
||||||
|
return sourceSelection{}, fmt.Errorf("pipeline %s source backend %s: %w", pipeline.ID, pipeline.Source.Backend, err)
|
||||||
|
}
|
||||||
|
defer closeBackend(sourceBackend)
|
||||||
|
|
||||||
|
var bundles []bundle.Bundle
|
||||||
|
if options.BundlePath != "" {
|
||||||
|
sourceBundle, err := bundle.Validate(ctx, sourceBackend, options.BundlePath)
|
||||||
|
if err != nil {
|
||||||
|
return sourceSelection{}, fmt.Errorf("pipeline %s source backend %s bundle %s: %w", pipeline.ID, pipeline.Source.Backend, storage.DisplayPath(options.BundlePath), err)
|
||||||
|
}
|
||||||
|
bundles = []bundle.Bundle{sourceBundle}
|
||||||
|
} else {
|
||||||
|
bundles, err = bundle.Discover(ctx, sourceBackend, "")
|
||||||
|
if err != nil {
|
||||||
|
return sourceSelection{}, fmt.Errorf("pipeline %s source backend %s discover source bundles: %w", pipeline.ID, pipeline.Source.Backend, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sourceSelection{
|
||||||
|
Bundles: bundles,
|
||||||
|
PipelineID: pipeline.ID,
|
||||||
|
SourceBackend: pipeline.Source.Backend,
|
||||||
|
ConfigMode: true,
|
||||||
|
Warnings: append(secretConflictWarnings(secretLoad.Conflicts), sourceSSHWarnings(pipeline)...),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func findPipeline(cfg config.Config, id string) (config.Pipeline, bool) {
|
||||||
|
for _, pipeline := range cfg.Pipelines {
|
||||||
|
if pipeline.ID == id {
|
||||||
|
return pipeline, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return config.Pipeline{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
func sourceSSHWarnings(pipeline config.Pipeline) []OutputWarning {
|
||||||
|
if pipeline.Source.Backend != config.BackendSSH || pipeline.Source.SSH.HostKeyPolicy != config.HostKeyPolicyOff {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return []OutputWarning{{
|
||||||
|
Message: fmt.Sprintf("pipeline=%s source host_key_policy=off disables SSH host key checking", pipeline.ID),
|
||||||
|
}}
|
||||||
|
}
|
||||||
389
internal/app/upload_coordinator.go
Normal file
389
internal/app/upload_coordinator.go
Normal file
@@ -0,0 +1,389 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/config"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/ingest"
|
||||||
|
)
|
||||||
|
|
||||||
|
const DefaultUploadMaxFileCount = 4096
|
||||||
|
|
||||||
|
type UploadRunID string
|
||||||
|
|
||||||
|
type UploadStatus string
|
||||||
|
|
||||||
|
const (
|
||||||
|
UploadStatusAccepted UploadStatus = "accepted"
|
||||||
|
UploadStatusQueued UploadStatus = "queued"
|
||||||
|
UploadStatusRunning UploadStatus = "running"
|
||||||
|
UploadStatusSucceeded UploadStatus = "succeeded"
|
||||||
|
UploadStatusFailed UploadStatus = "failed"
|
||||||
|
UploadStatusExpired UploadStatus = "expired"
|
||||||
|
)
|
||||||
|
|
||||||
|
type UploadRunRecord struct {
|
||||||
|
ID UploadRunID `json:"run_id"`
|
||||||
|
PipelineID string `json:"pipeline_id"`
|
||||||
|
Status UploadStatus `json:"status"`
|
||||||
|
AcceptedAt time.Time `json:"accepted_at"`
|
||||||
|
StartedAt *time.Time `json:"started_at,omitempty"`
|
||||||
|
FinishedAt *time.Time `json:"finished_at,omitempty"`
|
||||||
|
Report *RunReport `json:"report,omitempty"`
|
||||||
|
Error string `json:"error,omitempty"`
|
||||||
|
StagedRoot string `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type UploadRequest struct {
|
||||||
|
PipelineID string
|
||||||
|
ContentType string
|
||||||
|
Body io.Reader
|
||||||
|
DryRun bool
|
||||||
|
Force bool
|
||||||
|
MaxFileCount int
|
||||||
|
}
|
||||||
|
|
||||||
|
type UploadQueueFullError struct {
|
||||||
|
QueueSize int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (err UploadQueueFullError) Error() string {
|
||||||
|
return fmt.Sprintf("upload queue is full with capacity %d", err.QueueSize)
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsUploadQueueFull(err error) bool {
|
||||||
|
var full UploadQueueFullError
|
||||||
|
return errors.As(err, &full)
|
||||||
|
}
|
||||||
|
|
||||||
|
type UploadCoordinator struct {
|
||||||
|
ctx context.Context
|
||||||
|
cfg config.Config
|
||||||
|
stage uploadStageFunc
|
||||||
|
run uploadRunFunc
|
||||||
|
now func() time.Time
|
||||||
|
randomSuffix func() (string, error)
|
||||||
|
retention time.Duration
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
signal chan struct{}
|
||||||
|
queueSize int
|
||||||
|
maxConcurrency int
|
||||||
|
runningCount int
|
||||||
|
activePipeline map[string]bool
|
||||||
|
pending []*uploadJob
|
||||||
|
records map[UploadRunID]UploadRunRecord
|
||||||
|
}
|
||||||
|
|
||||||
|
type uploadStageFunc func(context.Context, ingest.StageOptions) (ingest.StagedBundle, error)
|
||||||
|
|
||||||
|
type uploadRunFunc func(context.Context, config.Config, RunPipelineWithLocalSourceOptions) (RunReport, error)
|
||||||
|
|
||||||
|
type uploadJob struct {
|
||||||
|
recordID UploadRunID
|
||||||
|
request UploadRequest
|
||||||
|
pipeline config.Pipeline
|
||||||
|
}
|
||||||
|
|
||||||
|
type uploadCoordinatorHooks struct {
|
||||||
|
stage uploadStageFunc
|
||||||
|
run uploadRunFunc
|
||||||
|
now func() time.Time
|
||||||
|
randomSuffix func() (string, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUploadCoordinator(ctx context.Context, cfg config.Config) *UploadCoordinator {
|
||||||
|
return newUploadCoordinator(ctx, cfg, uploadCoordinatorHooks{})
|
||||||
|
}
|
||||||
|
|
||||||
|
func newUploadCoordinator(ctx context.Context, cfg config.Config, hooks uploadCoordinatorHooks) *UploadCoordinator {
|
||||||
|
if ctx == nil {
|
||||||
|
ctx = context.Background()
|
||||||
|
}
|
||||||
|
config.ApplyDefaults(&cfg)
|
||||||
|
stage := hooks.stage
|
||||||
|
if stage == nil {
|
||||||
|
stage = ingest.StageArchive
|
||||||
|
}
|
||||||
|
run := hooks.run
|
||||||
|
if run == nil {
|
||||||
|
run = runPipelineConfigWithLocalSource
|
||||||
|
}
|
||||||
|
now := hooks.now
|
||||||
|
if now == nil {
|
||||||
|
now = time.Now
|
||||||
|
}
|
||||||
|
randomSuffix := hooks.randomSuffix
|
||||||
|
if randomSuffix == nil {
|
||||||
|
randomSuffix = randomRunIDSuffix
|
||||||
|
}
|
||||||
|
coordinator := &UploadCoordinator{
|
||||||
|
ctx: ctx,
|
||||||
|
cfg: cfg,
|
||||||
|
stage: stage,
|
||||||
|
run: run,
|
||||||
|
now: now,
|
||||||
|
randomSuffix: randomSuffix,
|
||||||
|
retention: cfg.Server.HTTP.Retention.AsDuration(),
|
||||||
|
signal: make(chan struct{}, 1),
|
||||||
|
queueSize: cfg.Server.HTTP.QueueSize,
|
||||||
|
maxConcurrency: cfg.Server.HTTP.MaxConcurrency,
|
||||||
|
activePipeline: map[string]bool{},
|
||||||
|
records: map[UploadRunID]UploadRunRecord{},
|
||||||
|
}
|
||||||
|
go coordinator.dispatchLoop()
|
||||||
|
return coordinator
|
||||||
|
}
|
||||||
|
|
||||||
|
func (coordinator *UploadCoordinator) Submit(ctx context.Context, request UploadRequest) (UploadRunRecord, error) {
|
||||||
|
if ctx == nil {
|
||||||
|
ctx = context.Background()
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return UploadRunRecord{}, err
|
||||||
|
}
|
||||||
|
if request.Body == nil {
|
||||||
|
return UploadRunRecord{}, fmt.Errorf("upload body is required")
|
||||||
|
}
|
||||||
|
pipeline, ok := findPipeline(coordinator.cfg, request.PipelineID)
|
||||||
|
if !ok {
|
||||||
|
return UploadRunRecord{}, PipelineNotFoundError{ID: request.PipelineID}
|
||||||
|
}
|
||||||
|
if pipeline.Source.Backend != config.BackendHTTPUpload {
|
||||||
|
return UploadRunRecord{}, fmt.Errorf("pipeline %s source backend %s is not configured for uploads", pipeline.ID, pipeline.Source.Backend)
|
||||||
|
}
|
||||||
|
runID, err := coordinator.newRunID(pipeline.ID)
|
||||||
|
if err != nil {
|
||||||
|
return UploadRunRecord{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
coordinator.mu.Lock()
|
||||||
|
defer coordinator.mu.Unlock()
|
||||||
|
coordinator.expireLocked(coordinator.now().UTC())
|
||||||
|
if len(coordinator.pending) >= coordinator.queueSize {
|
||||||
|
return UploadRunRecord{}, UploadQueueFullError{QueueSize: coordinator.queueSize}
|
||||||
|
}
|
||||||
|
record := UploadRunRecord{
|
||||||
|
ID: runID,
|
||||||
|
PipelineID: pipeline.ID,
|
||||||
|
Status: UploadStatusAccepted,
|
||||||
|
AcceptedAt: coordinator.now().UTC(),
|
||||||
|
}
|
||||||
|
coordinator.records[runID] = record
|
||||||
|
coordinator.pending = append(coordinator.pending, &uploadJob{
|
||||||
|
recordID: runID,
|
||||||
|
request: request,
|
||||||
|
pipeline: pipeline,
|
||||||
|
})
|
||||||
|
coordinator.notify()
|
||||||
|
return record, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (coordinator *UploadCoordinator) Status(runID UploadRunID) (UploadRunRecord, bool) {
|
||||||
|
coordinator.mu.Lock()
|
||||||
|
defer coordinator.mu.Unlock()
|
||||||
|
coordinator.expireLocked(coordinator.now().UTC())
|
||||||
|
record, ok := coordinator.records[runID]
|
||||||
|
return record, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func (coordinator *UploadCoordinator) Expire() []UploadRunRecord {
|
||||||
|
coordinator.mu.Lock()
|
||||||
|
defer coordinator.mu.Unlock()
|
||||||
|
return coordinator.expireLocked(coordinator.now().UTC())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (coordinator *UploadCoordinator) CanAccept() bool {
|
||||||
|
coordinator.mu.Lock()
|
||||||
|
defer coordinator.mu.Unlock()
|
||||||
|
coordinator.expireLocked(coordinator.now().UTC())
|
||||||
|
return len(coordinator.pending) < coordinator.queueSize
|
||||||
|
}
|
||||||
|
|
||||||
|
func (coordinator *UploadCoordinator) QueueDepth() int {
|
||||||
|
coordinator.mu.Lock()
|
||||||
|
defer coordinator.mu.Unlock()
|
||||||
|
return len(coordinator.pending)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (coordinator *UploadCoordinator) RunningCount() int {
|
||||||
|
coordinator.mu.Lock()
|
||||||
|
defer coordinator.mu.Unlock()
|
||||||
|
return coordinator.runningCount
|
||||||
|
}
|
||||||
|
|
||||||
|
func (coordinator *UploadCoordinator) newRunID(pipelineID string) (UploadRunID, error) {
|
||||||
|
suffix, err := coordinator.randomSuffix()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
timestamp := coordinator.now().UTC().Format("20060102T150405Z")
|
||||||
|
return UploadRunID(pipelineID + "." + timestamp + "." + suffix), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (coordinator *UploadCoordinator) dispatchLoop() {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-coordinator.ctx.Done():
|
||||||
|
return
|
||||||
|
case <-coordinator.signal:
|
||||||
|
for coordinator.startNext() {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (coordinator *UploadCoordinator) startNext() bool {
|
||||||
|
coordinator.mu.Lock()
|
||||||
|
defer coordinator.mu.Unlock()
|
||||||
|
if coordinator.runningCount >= coordinator.maxConcurrency {
|
||||||
|
coordinator.markPendingQueuedLocked()
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
index := -1
|
||||||
|
for candidateIndex, job := range coordinator.pending {
|
||||||
|
if coordinator.activePipeline[job.pipeline.ID] {
|
||||||
|
record := coordinator.records[job.recordID]
|
||||||
|
if record.Status == UploadStatusAccepted {
|
||||||
|
record.Status = UploadStatusQueued
|
||||||
|
coordinator.records[job.recordID] = record
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
index = candidateIndex
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if index < 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
job := coordinator.pending[index]
|
||||||
|
coordinator.pending = append(coordinator.pending[:index], coordinator.pending[index+1:]...)
|
||||||
|
now := coordinator.now().UTC()
|
||||||
|
record := coordinator.records[job.recordID]
|
||||||
|
record.Status = UploadStatusRunning
|
||||||
|
record.StartedAt = &now
|
||||||
|
coordinator.records[job.recordID] = record
|
||||||
|
coordinator.runningCount++
|
||||||
|
coordinator.activePipeline[job.pipeline.ID] = true
|
||||||
|
|
||||||
|
go coordinator.runJob(job)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (coordinator *UploadCoordinator) markPendingQueuedLocked() {
|
||||||
|
for _, job := range coordinator.pending {
|
||||||
|
record := coordinator.records[job.recordID]
|
||||||
|
if record.Status == UploadStatusAccepted {
|
||||||
|
record.Status = UploadStatusQueued
|
||||||
|
coordinator.records[job.recordID] = record
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (coordinator *UploadCoordinator) runJob(job *uploadJob) {
|
||||||
|
record := coordinator.currentRecord(job.recordID)
|
||||||
|
maxFileCount := job.request.MaxFileCount
|
||||||
|
if maxFileCount <= 0 {
|
||||||
|
maxFileCount = DefaultUploadMaxFileCount
|
||||||
|
}
|
||||||
|
staged, err := coordinator.stage(coordinator.ctx, ingest.StageOptions{
|
||||||
|
Body: job.request.Body,
|
||||||
|
ContentType: job.request.ContentType,
|
||||||
|
PipelineStagingPath: job.pipeline.Source.Upload.StagingPath,
|
||||||
|
RunID: string(record.ID),
|
||||||
|
MaxUploadSize: int64(*job.pipeline.Source.Upload.MaxUploadSize),
|
||||||
|
MaxExtractedSize: int64(*job.pipeline.Source.Upload.MaxUploadSize),
|
||||||
|
MaxFileCount: maxFileCount,
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
coordinator.setStagedRoot(job.recordID, staged.Root)
|
||||||
|
var report RunReport
|
||||||
|
report, err = coordinator.run(coordinator.ctx, coordinator.cfg, RunPipelineWithLocalSourceOptions{
|
||||||
|
PipelineID: job.pipeline.ID,
|
||||||
|
SourceRoot: staged.Root,
|
||||||
|
DryRun: job.request.DryRun,
|
||||||
|
Force: job.request.Force,
|
||||||
|
})
|
||||||
|
coordinator.complete(job, &report, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
coordinator.complete(job, nil, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (coordinator *UploadCoordinator) currentRecord(runID UploadRunID) UploadRunRecord {
|
||||||
|
coordinator.mu.Lock()
|
||||||
|
defer coordinator.mu.Unlock()
|
||||||
|
return coordinator.records[runID]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (coordinator *UploadCoordinator) setStagedRoot(runID UploadRunID, root string) {
|
||||||
|
coordinator.mu.Lock()
|
||||||
|
defer coordinator.mu.Unlock()
|
||||||
|
record := coordinator.records[runID]
|
||||||
|
record.StagedRoot = root
|
||||||
|
coordinator.records[runID] = record
|
||||||
|
}
|
||||||
|
|
||||||
|
func (coordinator *UploadCoordinator) complete(job *uploadJob, report *RunReport, runErr error) {
|
||||||
|
coordinator.mu.Lock()
|
||||||
|
defer coordinator.mu.Unlock()
|
||||||
|
record := coordinator.records[job.recordID]
|
||||||
|
finishedAt := coordinator.now().UTC()
|
||||||
|
record.FinishedAt = &finishedAt
|
||||||
|
record.Report = report
|
||||||
|
if runErr != nil {
|
||||||
|
record.Status = UploadStatusFailed
|
||||||
|
record.Error = runErr.Error()
|
||||||
|
} else {
|
||||||
|
record.Status = UploadStatusSucceeded
|
||||||
|
}
|
||||||
|
coordinator.records[job.recordID] = record
|
||||||
|
coordinator.runningCount--
|
||||||
|
delete(coordinator.activePipeline, job.pipeline.ID)
|
||||||
|
coordinator.notify()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (coordinator *UploadCoordinator) expireLocked(now time.Time) []UploadRunRecord {
|
||||||
|
var expired []UploadRunRecord
|
||||||
|
for runID, record := range coordinator.records {
|
||||||
|
if record.FinishedAt == nil || record.Status == UploadStatusExpired {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if now.Before(record.FinishedAt.Add(coordinator.retention)) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if record.StagedRoot != "" {
|
||||||
|
_ = os.RemoveAll(record.StagedRoot)
|
||||||
|
}
|
||||||
|
record.Status = UploadStatusExpired
|
||||||
|
record.Report = nil
|
||||||
|
record.Error = ""
|
||||||
|
expired = append(expired, record)
|
||||||
|
delete(coordinator.records, runID)
|
||||||
|
}
|
||||||
|
return expired
|
||||||
|
}
|
||||||
|
|
||||||
|
func (coordinator *UploadCoordinator) notify() {
|
||||||
|
select {
|
||||||
|
case coordinator.signal <- struct{}{}:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func randomRunIDSuffix() (string, error) {
|
||||||
|
var data [4]byte
|
||||||
|
if _, err := rand.Read(data[:]); err != nil {
|
||||||
|
return "", fmt.Errorf("generate run id suffix: %w", err)
|
||||||
|
}
|
||||||
|
return hex.EncodeToString(data[:]), nil
|
||||||
|
}
|
||||||
373
internal/app/upload_coordinator_test.go
Normal file
373
internal/app/upload_coordinator_test.go
Normal file
@@ -0,0 +1,373 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/config"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/ingest"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestUploadCoordinatorGeneratesRunIDAndAcceptedStatus(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
clock := newUploadTestClock(time.Date(2026, 6, 3, 12, 0, 0, 0, time.UTC))
|
||||||
|
coordinator := newUploadCoordinator(ctx, uploadCoordinatorConfig(t, uploadCoordinatorConfigOptions{
|
||||||
|
pipelineIDs: []string{"weather-daily"},
|
||||||
|
}), uploadCoordinatorHooks{
|
||||||
|
now: clock.Now,
|
||||||
|
randomSuffix: uploadTestSuffixes("ab12cd34"),
|
||||||
|
stage: successfulUploadStage,
|
||||||
|
run: successfulUploadRun,
|
||||||
|
})
|
||||||
|
|
||||||
|
record, err := coordinator.Submit(context.Background(), UploadRequest{
|
||||||
|
PipelineID: "weather-daily",
|
||||||
|
ContentType: ingest.ContentTypeTar,
|
||||||
|
Body: strings.NewReader("archive"),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Submit() error = %v", err)
|
||||||
|
}
|
||||||
|
if got, want := record.ID, UploadRunID("weather-daily.20260603T120000Z.ab12cd34"); got != want {
|
||||||
|
t.Fatalf("run id = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
if got, want := record.Status, UploadStatusAccepted; got != want {
|
||||||
|
t.Fatalf("initial status = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
waitForUploadStatus(t, coordinator, record.ID, UploadStatusSucceeded)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUploadCoordinatorRejectsFullQueueBeforeReadingBody(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
release := make(chan struct{})
|
||||||
|
var reads atomic.Int64
|
||||||
|
coordinator := newUploadCoordinator(ctx, uploadCoordinatorConfig(t, uploadCoordinatorConfigOptions{
|
||||||
|
pipelineIDs: []string{"reports"},
|
||||||
|
queueSize: 1,
|
||||||
|
maxConcurrency: 1,
|
||||||
|
}), uploadCoordinatorHooks{
|
||||||
|
randomSuffix: uploadTestSuffixes("00000001", "00000002", "00000003"),
|
||||||
|
stage: successfulUploadStage,
|
||||||
|
run: func(ctx context.Context, cfg config.Config, options RunPipelineWithLocalSourceOptions) (RunReport, error) {
|
||||||
|
<-release
|
||||||
|
return RunReport{}, nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
first, err := coordinator.Submit(context.Background(), UploadRequest{
|
||||||
|
PipelineID: "reports",
|
||||||
|
ContentType: ingest.ContentTypeTar,
|
||||||
|
Body: strings.NewReader("first"),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("first Submit() error = %v", err)
|
||||||
|
}
|
||||||
|
waitForUploadStatus(t, coordinator, first.ID, UploadStatusRunning)
|
||||||
|
|
||||||
|
second, err := coordinator.Submit(context.Background(), UploadRequest{
|
||||||
|
PipelineID: "reports",
|
||||||
|
ContentType: ingest.ContentTypeTar,
|
||||||
|
Body: strings.NewReader("second"),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("second Submit() error = %v", err)
|
||||||
|
}
|
||||||
|
waitForUploadStatus(t, coordinator, second.ID, UploadStatusQueued)
|
||||||
|
|
||||||
|
_, err = coordinator.Submit(context.Background(), UploadRequest{
|
||||||
|
PipelineID: "reports",
|
||||||
|
ContentType: ingest.ContentTypeTar,
|
||||||
|
Body: readerFunc(func(data []byte) (int, error) {
|
||||||
|
reads.Add(1)
|
||||||
|
return 0, io.EOF
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
if err == nil || !IsUploadQueueFull(err) {
|
||||||
|
t.Fatalf("third Submit() error = %v, want full queue", err)
|
||||||
|
}
|
||||||
|
if got := reads.Load(); got != 0 {
|
||||||
|
t.Fatalf("rejected body reads = %d, want 0", got)
|
||||||
|
}
|
||||||
|
close(release)
|
||||||
|
waitForUploadStatus(t, coordinator, first.ID, UploadStatusSucceeded)
|
||||||
|
waitForUploadStatus(t, coordinator, second.ID, UploadStatusSucceeded)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUploadCoordinatorSerializesSamePipelineUploads(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
release := make(chan struct{})
|
||||||
|
coordinator := newUploadCoordinator(ctx, uploadCoordinatorConfig(t, uploadCoordinatorConfigOptions{
|
||||||
|
pipelineIDs: []string{"reports"},
|
||||||
|
queueSize: 4,
|
||||||
|
maxConcurrency: 2,
|
||||||
|
}), uploadCoordinatorHooks{
|
||||||
|
randomSuffix: uploadTestSuffixes("00000001", "00000002"),
|
||||||
|
stage: successfulUploadStage,
|
||||||
|
run: func(ctx context.Context, cfg config.Config, options RunPipelineWithLocalSourceOptions) (RunReport, error) {
|
||||||
|
<-release
|
||||||
|
return RunReport{}, nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
first, err := coordinator.Submit(context.Background(), UploadRequest{PipelineID: "reports", ContentType: ingest.ContentTypeTar, Body: strings.NewReader("first")})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("first Submit() error = %v", err)
|
||||||
|
}
|
||||||
|
second, err := coordinator.Submit(context.Background(), UploadRequest{PipelineID: "reports", ContentType: ingest.ContentTypeTar, Body: strings.NewReader("second")})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("second Submit() error = %v", err)
|
||||||
|
}
|
||||||
|
waitForUploadStatus(t, coordinator, first.ID, UploadStatusRunning)
|
||||||
|
waitForUploadStatus(t, coordinator, second.ID, UploadStatusQueued)
|
||||||
|
if got := coordinator.RunningCount(); got != 1 {
|
||||||
|
t.Fatalf("running count = %d, want 1", got)
|
||||||
|
}
|
||||||
|
close(release)
|
||||||
|
waitForUploadStatus(t, coordinator, first.ID, UploadStatusSucceeded)
|
||||||
|
waitForUploadStatus(t, coordinator, second.ID, UploadStatusSucceeded)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUploadCoordinatorRunsDifferentPipelinesConcurrentlyUpToLimit(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
release := make(chan struct{})
|
||||||
|
coordinator := newUploadCoordinator(ctx, uploadCoordinatorConfig(t, uploadCoordinatorConfigOptions{
|
||||||
|
pipelineIDs: []string{"reports-one", "reports-two"},
|
||||||
|
queueSize: 4,
|
||||||
|
maxConcurrency: 2,
|
||||||
|
}), uploadCoordinatorHooks{
|
||||||
|
randomSuffix: uploadTestSuffixes("00000001", "00000002"),
|
||||||
|
stage: successfulUploadStage,
|
||||||
|
run: func(ctx context.Context, cfg config.Config, options RunPipelineWithLocalSourceOptions) (RunReport, error) {
|
||||||
|
<-release
|
||||||
|
return RunReport{}, nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
first, err := coordinator.Submit(context.Background(), UploadRequest{PipelineID: "reports-one", ContentType: ingest.ContentTypeTar, Body: strings.NewReader("first")})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("first Submit() error = %v", err)
|
||||||
|
}
|
||||||
|
second, err := coordinator.Submit(context.Background(), UploadRequest{PipelineID: "reports-two", ContentType: ingest.ContentTypeTar, Body: strings.NewReader("second")})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("second Submit() error = %v", err)
|
||||||
|
}
|
||||||
|
waitForUploadStatus(t, coordinator, first.ID, UploadStatusRunning)
|
||||||
|
waitForUploadStatus(t, coordinator, second.ID, UploadStatusRunning)
|
||||||
|
if got := coordinator.RunningCount(); got != 2 {
|
||||||
|
t.Fatalf("running count = %d, want 2", got)
|
||||||
|
}
|
||||||
|
close(release)
|
||||||
|
waitForUploadStatus(t, coordinator, first.ID, UploadStatusSucceeded)
|
||||||
|
waitForUploadStatus(t, coordinator, second.ID, UploadStatusSucceeded)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUploadCoordinatorRecordsFailureDetails(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
runErr := errors.New("publish failed")
|
||||||
|
coordinator := newUploadCoordinator(ctx, uploadCoordinatorConfig(t, uploadCoordinatorConfigOptions{
|
||||||
|
pipelineIDs: []string{"reports"},
|
||||||
|
}), uploadCoordinatorHooks{
|
||||||
|
randomSuffix: uploadTestSuffixes("00000001"),
|
||||||
|
stage: successfulUploadStage,
|
||||||
|
run: func(ctx context.Context, cfg config.Config, options RunPipelineWithLocalSourceOptions) (RunReport, error) {
|
||||||
|
return RunReport{DryRun: options.DryRun}, runErr
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
record, err := coordinator.Submit(context.Background(), UploadRequest{
|
||||||
|
PipelineID: "reports",
|
||||||
|
ContentType: ingest.ContentTypeTar,
|
||||||
|
Body: strings.NewReader("archive"),
|
||||||
|
DryRun: true,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Submit() error = %v", err)
|
||||||
|
}
|
||||||
|
failed := waitForUploadStatus(t, coordinator, record.ID, UploadStatusFailed)
|
||||||
|
if failed.Error != runErr.Error() {
|
||||||
|
t.Fatalf("error = %q, want %q", failed.Error, runErr.Error())
|
||||||
|
}
|
||||||
|
if failed.Report == nil || !failed.Report.DryRun {
|
||||||
|
t.Fatalf("report = %#v, want retained dry-run report", failed.Report)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUploadCoordinatorExpiresCompletedRecordsAndStagingDirectories(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
clock := newUploadTestClock(time.Date(2026, 6, 3, 12, 0, 0, 0, time.UTC))
|
||||||
|
coordinator := newUploadCoordinator(ctx, uploadCoordinatorConfig(t, uploadCoordinatorConfigOptions{
|
||||||
|
pipelineIDs: []string{"reports"},
|
||||||
|
retention: time.Second,
|
||||||
|
}), uploadCoordinatorHooks{
|
||||||
|
now: clock.Now,
|
||||||
|
randomSuffix: uploadTestSuffixes("00000001"),
|
||||||
|
stage: successfulUploadStage,
|
||||||
|
run: func(ctx context.Context, cfg config.Config, options RunPipelineWithLocalSourceOptions) (RunReport, error) {
|
||||||
|
return RunReport{DryRun: true}, nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
record, err := coordinator.Submit(context.Background(), UploadRequest{
|
||||||
|
PipelineID: "reports",
|
||||||
|
ContentType: ingest.ContentTypeTar,
|
||||||
|
Body: strings.NewReader("archive"),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Submit() error = %v", err)
|
||||||
|
}
|
||||||
|
succeeded := waitForUploadStatus(t, coordinator, record.ID, UploadStatusSucceeded)
|
||||||
|
if succeeded.Report == nil || !succeeded.Report.DryRun {
|
||||||
|
t.Fatalf("report = %#v, want retained dry-run report", succeeded.Report)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(succeeded.StagedRoot); err != nil {
|
||||||
|
t.Fatalf("staged root stat before expiry = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
clock.Advance(2 * time.Second)
|
||||||
|
expired := coordinator.Expire()
|
||||||
|
if got, want := len(expired), 1; got != want {
|
||||||
|
t.Fatalf("expired count = %d, want %d", got, want)
|
||||||
|
}
|
||||||
|
if expired[0].Status != UploadStatusExpired || expired[0].Report != nil || expired[0].Error != "" {
|
||||||
|
t.Fatalf("expired record = %#v, want expired without report/error", expired[0])
|
||||||
|
}
|
||||||
|
if _, ok := coordinator.Status(record.ID); ok {
|
||||||
|
t.Fatal("Status() ok = true after expiry, want removed status")
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(succeeded.StagedRoot); !os.IsNotExist(err) {
|
||||||
|
t.Fatalf("staged root stat after expiry = %v, want not exist", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type readerFunc func([]byte) (int, error)
|
||||||
|
|
||||||
|
func (fn readerFunc) Read(data []byte) (int, error) {
|
||||||
|
return fn(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func successfulUploadStage(ctx context.Context, opts ingest.StageOptions) (ingest.StagedBundle, error) {
|
||||||
|
root := filepath.Join(opts.PipelineStagingPath, opts.RunID)
|
||||||
|
if err := os.MkdirAll(root, 0o755); err != nil {
|
||||||
|
return ingest.StagedBundle{}, err
|
||||||
|
}
|
||||||
|
return ingest.StagedBundle{Root: root}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func successfulUploadRun(ctx context.Context, cfg config.Config, options RunPipelineWithLocalSourceOptions) (RunReport, error) {
|
||||||
|
return RunReport{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type uploadCoordinatorConfigOptions struct {
|
||||||
|
pipelineIDs []string
|
||||||
|
queueSize int
|
||||||
|
maxConcurrency int
|
||||||
|
retention time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func uploadCoordinatorConfig(t *testing.T, opts uploadCoordinatorConfigOptions) config.Config {
|
||||||
|
t.Helper()
|
||||||
|
queueSize := opts.queueSize
|
||||||
|
if queueSize == 0 {
|
||||||
|
queueSize = 4
|
||||||
|
}
|
||||||
|
maxConcurrency := opts.maxConcurrency
|
||||||
|
if maxConcurrency == 0 {
|
||||||
|
maxConcurrency = 1
|
||||||
|
}
|
||||||
|
retentionValue := opts.retention
|
||||||
|
if retentionValue == 0 {
|
||||||
|
retentionValue = time.Minute
|
||||||
|
}
|
||||||
|
retention := config.Duration(retentionValue)
|
||||||
|
maxUploadSize := config.ByteSize(1024)
|
||||||
|
cfg := config.Config{
|
||||||
|
Server: config.Server{HTTP: config.HTTPServer{
|
||||||
|
StagingRoot: t.TempDir(),
|
||||||
|
MaxUploadSize: &maxUploadSize,
|
||||||
|
QueueSize: queueSize,
|
||||||
|
MaxConcurrency: maxConcurrency,
|
||||||
|
Retention: &retention,
|
||||||
|
}},
|
||||||
|
}
|
||||||
|
for _, pipelineID := range opts.pipelineIDs {
|
||||||
|
cfg.Pipelines = append(cfg.Pipelines, config.Pipeline{
|
||||||
|
ID: pipelineID,
|
||||||
|
Source: config.Backend{
|
||||||
|
Backend: config.BackendHTTPUpload,
|
||||||
|
Upload: config.HTTPUpload{TokenEnv: strings.ToUpper(strings.ReplaceAll(pipelineID, "-", "_")) + "_TOKEN"},
|
||||||
|
},
|
||||||
|
Destinations: []config.Destination{{
|
||||||
|
ID: "archive",
|
||||||
|
Backend: config.BackendLocal,
|
||||||
|
Path: t.TempDir(),
|
||||||
|
}},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
type uploadTestClock struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
now time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func newUploadTestClock(now time.Time) *uploadTestClock {
|
||||||
|
return &uploadTestClock{now: now}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (clock *uploadTestClock) Now() time.Time {
|
||||||
|
clock.mu.Lock()
|
||||||
|
defer clock.mu.Unlock()
|
||||||
|
return clock.now
|
||||||
|
}
|
||||||
|
|
||||||
|
func (clock *uploadTestClock) Advance(duration time.Duration) {
|
||||||
|
clock.mu.Lock()
|
||||||
|
defer clock.mu.Unlock()
|
||||||
|
clock.now = clock.now.Add(duration)
|
||||||
|
}
|
||||||
|
|
||||||
|
func uploadTestSuffixes(values ...string) func() (string, error) {
|
||||||
|
var mu sync.Mutex
|
||||||
|
index := 0
|
||||||
|
return func() (string, error) {
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
if index >= len(values) {
|
||||||
|
return fmt.Sprintf("%08d", index+1), nil
|
||||||
|
}
|
||||||
|
value := values[index]
|
||||||
|
index++
|
||||||
|
return value, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitForUploadStatus(t *testing.T, coordinator *UploadCoordinator, runID UploadRunID, status UploadStatus) UploadRunRecord {
|
||||||
|
t.Helper()
|
||||||
|
deadline := time.Now().Add(time.Second)
|
||||||
|
for time.Now().Before(deadline) {
|
||||||
|
record, ok := coordinator.Status(runID)
|
||||||
|
if ok && record.Status == status {
|
||||||
|
return record
|
||||||
|
}
|
||||||
|
time.Sleep(time.Millisecond)
|
||||||
|
}
|
||||||
|
record, ok := coordinator.Status(runID)
|
||||||
|
t.Fatalf("timed out waiting for status %s; latest ok=%t record=%#v", status, ok, record)
|
||||||
|
return UploadRunRecord{}
|
||||||
|
}
|
||||||
209
internal/app/upload_http.go
Normal file
209
internal/app/upload_http.go
Normal file
@@ -0,0 +1,209 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"mime"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/config"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/ingest"
|
||||||
|
)
|
||||||
|
|
||||||
|
type uploadCoordinator interface {
|
||||||
|
CanAccept() bool
|
||||||
|
Submit(context.Context, UploadRequest) (UploadRunRecord, error)
|
||||||
|
Status(UploadRunID) (UploadRunRecord, bool)
|
||||||
|
}
|
||||||
|
|
||||||
|
type uploadHTTPHandler struct {
|
||||||
|
coordinator uploadCoordinator
|
||||||
|
tokens map[string]string
|
||||||
|
limits map[string]int64
|
||||||
|
}
|
||||||
|
|
||||||
|
type uploadAcceptedResponse struct {
|
||||||
|
RunID UploadRunID `json:"run_id"`
|
||||||
|
Status UploadStatus `json:"status"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type httpErrorResponse struct {
|
||||||
|
Error string `json:"error"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func newUploadHTTPHandler(ctx context.Context, cfg config.Config, environment config.Environment) (http.Handler, error) {
|
||||||
|
config.ApplyDefaults(&cfg)
|
||||||
|
tokens, limits, err := resolveUploadTokens(cfg, environment)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return uploadHTTPHandler{
|
||||||
|
coordinator: NewUploadCoordinator(ctx, cfg),
|
||||||
|
tokens: tokens,
|
||||||
|
limits: limits,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveUploadTokens(cfg config.Config, environment config.Environment) (map[string]string, map[string]int64, error) {
|
||||||
|
tokens := make(map[string]string)
|
||||||
|
limits := make(map[string]int64)
|
||||||
|
for _, pipeline := range cfg.Pipelines {
|
||||||
|
if pipeline.Source.Backend != config.BackendHTTPUpload {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
tokenName := pipeline.Source.Upload.TokenEnv
|
||||||
|
token, ok := environment.Lookup(tokenName)
|
||||||
|
if !ok {
|
||||||
|
return nil, nil, fmt.Errorf("upload token environment variable %s is not set", tokenName)
|
||||||
|
}
|
||||||
|
if token == "" {
|
||||||
|
return nil, nil, fmt.Errorf("upload token environment variable %s is empty", tokenName)
|
||||||
|
}
|
||||||
|
if existing, exists := tokens[token]; exists {
|
||||||
|
return nil, nil, fmt.Errorf("upload token environment variables for pipelines %s and %s resolve to the same value", existing, pipeline.ID)
|
||||||
|
}
|
||||||
|
tokens[token] = pipeline.ID
|
||||||
|
limits[pipeline.ID] = int64(*pipeline.Source.Upload.MaxUploadSize)
|
||||||
|
}
|
||||||
|
return tokens, limits, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (handler uploadHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch {
|
||||||
|
case r.Method == http.MethodGet && r.URL.Path == "/healthz":
|
||||||
|
handler.handleHealth(w)
|
||||||
|
case r.Method == http.MethodPost && r.URL.Path == "/upload":
|
||||||
|
handler.handleUpload(w, r)
|
||||||
|
case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/runs/"):
|
||||||
|
handler.handleRunStatus(w, r)
|
||||||
|
default:
|
||||||
|
writeHTTPError(w, http.StatusNotFound, "not found")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (handler uploadHTTPHandler) handleHealth(w http.ResponseWriter) {
|
||||||
|
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (handler uploadHTTPHandler) handleUpload(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.URL.Query().Has("pipeline") || r.URL.Query().Has("pipeline_id") {
|
||||||
|
writeHTTPError(w, http.StatusBadRequest, "pipeline id is not accepted")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
pipelineID, ok := handler.authenticate(r.Header.Get("Authorization"))
|
||||||
|
if !ok {
|
||||||
|
writeHTTPError(w, http.StatusUnauthorized, "unauthorized")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
contentType := r.Header.Get("Content-Type")
|
||||||
|
if !supportedUploadContentType(contentType) {
|
||||||
|
writeHTTPError(w, http.StatusUnsupportedMediaType, "unsupported content type")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !handler.coordinator.CanAccept() {
|
||||||
|
writeHTTPError(w, http.StatusServiceUnavailable, "upload queue is full")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
body, err := readUploadBody(r.Body, handler.limits[pipelineID])
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, ingest.ErrUploadTooLarge) {
|
||||||
|
writeHTTPError(w, http.StatusRequestEntityTooLarge, "upload exceeds maximum size")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeHTTPError(w, http.StatusBadRequest, "read upload body failed")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
record, err := handler.coordinator.Submit(r.Context(), UploadRequest{
|
||||||
|
PipelineID: pipelineID,
|
||||||
|
ContentType: contentType,
|
||||||
|
Body: bytes.NewReader(body),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
writeUploadSubmitError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusAccepted, uploadAcceptedResponse{
|
||||||
|
RunID: record.ID,
|
||||||
|
Status: UploadStatusAccepted,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (handler uploadHTTPHandler) handleRunStatus(w http.ResponseWriter, r *http.Request) {
|
||||||
|
rawRunID := strings.TrimPrefix(r.URL.Path, "/runs/")
|
||||||
|
if rawRunID == "" || strings.Contains(rawRunID, "/") {
|
||||||
|
writeHTTPError(w, http.StatusNotFound, "not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
record, ok := handler.coordinator.Status(UploadRunID(rawRunID))
|
||||||
|
if !ok {
|
||||||
|
writeHTTPError(w, http.StatusNotFound, "run not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, record)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (handler uploadHTTPHandler) authenticate(header string) (string, bool) {
|
||||||
|
const prefix = "Bearer "
|
||||||
|
if !strings.HasPrefix(header, prefix) {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
token := strings.TrimSpace(strings.TrimPrefix(header, prefix))
|
||||||
|
if token == "" {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
pipelineID, ok := handler.tokens[token]
|
||||||
|
return pipelineID, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func supportedUploadContentType(contentType string) bool {
|
||||||
|
mediaType, _, err := mime.ParseMediaType(contentType)
|
||||||
|
if err != nil {
|
||||||
|
mediaType = contentType
|
||||||
|
}
|
||||||
|
switch mediaType {
|
||||||
|
case ingest.ContentTypeTar, ingest.ContentTypeGzip, ingest.ContentTypeXGzip:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func readUploadBody(body io.Reader, maxSize int64) ([]byte, error) {
|
||||||
|
limited := &io.LimitedReader{R: body, N: maxSize + 1}
|
||||||
|
data, err := io.ReadAll(limited)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if int64(len(data)) > maxSize {
|
||||||
|
return nil, ingest.ErrUploadTooLarge
|
||||||
|
}
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeUploadSubmitError(w http.ResponseWriter, err error) {
|
||||||
|
switch {
|
||||||
|
case IsUploadQueueFull(err):
|
||||||
|
writeHTTPError(w, http.StatusServiceUnavailable, "upload queue is full")
|
||||||
|
case errors.Is(err, ingest.ErrUploadTooLarge):
|
||||||
|
writeHTTPError(w, http.StatusRequestEntityTooLarge, "upload exceeds maximum size")
|
||||||
|
case errors.Is(err, ingest.ErrUnsupportedContentType):
|
||||||
|
writeHTTPError(w, http.StatusUnsupportedMediaType, "unsupported content type")
|
||||||
|
default:
|
||||||
|
writeHTTPError(w, http.StatusBadRequest, "upload rejected")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeHTTPError(w http.ResponseWriter, status int, message string) {
|
||||||
|
writeJSON(w, status, httpErrorResponse{Error: message})
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(status)
|
||||||
|
_ = json.NewEncoder(w).Encode(value)
|
||||||
|
}
|
||||||
419
internal/app/upload_http_integration_test.go
Normal file
419
internal/app/upload_http_integration_test.go
Normal file
@@ -0,0 +1,419 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/tar"
|
||||||
|
"bytes"
|
||||||
|
"compress/gzip"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"io/fs"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/config"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/ingest"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/storage"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/testutil"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestHTTPUploadPublishesTarAndGzipFanout(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
compressed bool
|
||||||
|
contentType string
|
||||||
|
}{
|
||||||
|
{name: "tar", contentType: ingest.ContentTypeTar},
|
||||||
|
{name: "gzip", compressed: true, contentType: ingest.ContentTypeGzip},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
firstDestination := t.TempDir()
|
||||||
|
secondDestination := t.TempDir()
|
||||||
|
cfg := httpUploadIntegrationConfig(t, []httpUploadPipelineSpec{{
|
||||||
|
id: "reports",
|
||||||
|
tokenEnv: "REPORTS_TOKEN",
|
||||||
|
stagingPath: filepath.Join(t.TempDir(), "reports"),
|
||||||
|
destinations: []string{firstDestination, secondDestination},
|
||||||
|
}}, 4, 1)
|
||||||
|
handler, err := newUploadHTTPHandler(context.Background(), cfg, uploadHTTPTestEnvironment(map[string]string{
|
||||||
|
"REPORTS_TOKEN": "reports-secret",
|
||||||
|
}))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("newUploadHTTPHandler() error = %v", err)
|
||||||
|
}
|
||||||
|
server := httptest.NewServer(handler)
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
runID := submitHTTPUpload(t, server, "reports-secret", tt.contentType, bundleArchive(t, tt.compressed, testutil.BundleOptions{}))
|
||||||
|
record := waitForHTTPUploadStatus(t, server, runID, UploadStatusSucceeded)
|
||||||
|
|
||||||
|
if record.Report == nil {
|
||||||
|
t.Fatal("completed status report = nil, want run report")
|
||||||
|
}
|
||||||
|
if record.Report.Summary.Status != "ok" {
|
||||||
|
t.Fatalf("summary status = %q, want ok", record.Report.Summary.Status)
|
||||||
|
}
|
||||||
|
if got, want := len(record.Report.Actions), 2; got != want {
|
||||||
|
t.Fatalf("action count = %d, want %d", got, want)
|
||||||
|
}
|
||||||
|
assertPublishedBundle(t, firstDestination)
|
||||||
|
assertPublishedBundle(t, secondDestination)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHTTPUploadInvalidArchiveFailsWithoutPublishing(t *testing.T) {
|
||||||
|
destination := t.TempDir()
|
||||||
|
cfg := httpUploadIntegrationConfig(t, []httpUploadPipelineSpec{{
|
||||||
|
id: "reports",
|
||||||
|
tokenEnv: "REPORTS_TOKEN",
|
||||||
|
stagingPath: filepath.Join(t.TempDir(), "reports"),
|
||||||
|
destinations: []string{destination},
|
||||||
|
}}, 4, 1)
|
||||||
|
handler, err := newUploadHTTPHandler(context.Background(), cfg, uploadHTTPTestEnvironment(map[string]string{
|
||||||
|
"REPORTS_TOKEN": "reports-secret",
|
||||||
|
}))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("newUploadHTTPHandler() error = %v", err)
|
||||||
|
}
|
||||||
|
server := httptest.NewServer(handler)
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
runID := submitHTTPUpload(t, server, "reports-secret", ingest.ContentTypeTar, []byte("not a tar archive"))
|
||||||
|
record := waitForHTTPUploadStatus(t, server, runID, UploadStatusFailed)
|
||||||
|
|
||||||
|
if record.Error == "" {
|
||||||
|
t.Fatal("failed status error is empty")
|
||||||
|
}
|
||||||
|
if record.Report != nil {
|
||||||
|
t.Fatalf("failed staging report = %#v, want nil", record.Report)
|
||||||
|
}
|
||||||
|
assertDirectoryEmpty(t, destination)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHTTPUploadSamePipelineRequestsSerialize(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
release := make(chan struct{})
|
||||||
|
started := make(chan struct{}, 1)
|
||||||
|
coordinator := newUploadCoordinator(ctx, httpUploadIntegrationConfig(t, []httpUploadPipelineSpec{{
|
||||||
|
id: "reports",
|
||||||
|
tokenEnv: "REPORTS_TOKEN",
|
||||||
|
stagingPath: filepath.Join(t.TempDir(), "reports"),
|
||||||
|
destinations: []string{t.TempDir()},
|
||||||
|
}}, 4, 2), uploadCoordinatorHooks{
|
||||||
|
randomSuffix: uploadTestSuffixes("00000001", "00000002"),
|
||||||
|
stage: successfulUploadStage,
|
||||||
|
run: func(ctx context.Context, cfg config.Config, options RunPipelineWithLocalSourceOptions) (RunReport, error) {
|
||||||
|
select {
|
||||||
|
case started <- struct{}{}:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
<-release
|
||||||
|
return RunReport{}, nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
handler := uploadHTTPHandler{
|
||||||
|
coordinator: coordinator,
|
||||||
|
tokens: map[string]string{"reports-secret": "reports"},
|
||||||
|
limits: map[string]int64{"reports": 1024},
|
||||||
|
}
|
||||||
|
server := httptest.NewServer(handler)
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
firstRunID := submitHTTPUpload(t, server, "reports-secret", ingest.ContentTypeTar, []byte("first"))
|
||||||
|
waitForRunStart(t, started)
|
||||||
|
first := waitForHTTPUploadStatus(t, server, firstRunID, UploadStatusRunning)
|
||||||
|
secondRunID := submitHTTPUpload(t, server, "reports-secret", ingest.ContentTypeTar, []byte("second"))
|
||||||
|
second := waitForHTTPUploadStatus(t, server, secondRunID, UploadStatusQueued)
|
||||||
|
|
||||||
|
if first.PipelineID != "reports" || second.PipelineID != "reports" {
|
||||||
|
t.Fatalf("statuses = %#v %#v, want same pipeline", first, second)
|
||||||
|
}
|
||||||
|
if got := coordinator.RunningCount(); got != 1 {
|
||||||
|
t.Fatalf("running count = %d, want 1", got)
|
||||||
|
}
|
||||||
|
close(release)
|
||||||
|
waitForHTTPUploadStatus(t, server, firstRunID, UploadStatusSucceeded)
|
||||||
|
waitForHTTPUploadStatus(t, server, secondRunID, UploadStatusSucceeded)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHTTPUploadDifferentPipelinesRunConcurrently(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
release := make(chan struct{})
|
||||||
|
started := make(chan string, 2)
|
||||||
|
coordinator := newUploadCoordinator(ctx, httpUploadIntegrationConfig(t, []httpUploadPipelineSpec{
|
||||||
|
{
|
||||||
|
id: "reports-one",
|
||||||
|
tokenEnv: "REPORTS_ONE_TOKEN",
|
||||||
|
stagingPath: filepath.Join(t.TempDir(), "reports-one"),
|
||||||
|
destinations: []string{t.TempDir()},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "reports-two",
|
||||||
|
tokenEnv: "REPORTS_TWO_TOKEN",
|
||||||
|
stagingPath: filepath.Join(t.TempDir(), "reports-two"),
|
||||||
|
destinations: []string{t.TempDir()},
|
||||||
|
},
|
||||||
|
}, 4, 2), uploadCoordinatorHooks{
|
||||||
|
randomSuffix: uploadTestSuffixes("00000001", "00000002"),
|
||||||
|
stage: successfulUploadStage,
|
||||||
|
run: func(ctx context.Context, cfg config.Config, options RunPipelineWithLocalSourceOptions) (RunReport, error) {
|
||||||
|
started <- options.PipelineID
|
||||||
|
<-release
|
||||||
|
return RunReport{}, nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
handler := uploadHTTPHandler{
|
||||||
|
coordinator: coordinator,
|
||||||
|
tokens: map[string]string{
|
||||||
|
"one-secret": "reports-one",
|
||||||
|
"two-secret": "reports-two",
|
||||||
|
},
|
||||||
|
limits: map[string]int64{
|
||||||
|
"reports-one": 1024,
|
||||||
|
"reports-two": 1024,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
server := httptest.NewServer(handler)
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
firstRunID := submitHTTPUpload(t, server, "one-secret", ingest.ContentTypeTar, []byte("first"))
|
||||||
|
secondRunID := submitHTTPUpload(t, server, "two-secret", ingest.ContentTypeTar, []byte("second"))
|
||||||
|
waitForStartedPipelines(t, started, "reports-one", "reports-two")
|
||||||
|
waitForHTTPUploadStatus(t, server, firstRunID, UploadStatusRunning)
|
||||||
|
waitForHTTPUploadStatus(t, server, secondRunID, UploadStatusRunning)
|
||||||
|
|
||||||
|
if got := coordinator.RunningCount(); got != 2 {
|
||||||
|
t.Fatalf("running count = %d, want 2", got)
|
||||||
|
}
|
||||||
|
close(release)
|
||||||
|
waitForHTTPUploadStatus(t, server, firstRunID, UploadStatusSucceeded)
|
||||||
|
waitForHTTPUploadStatus(t, server, secondRunID, UploadStatusSucceeded)
|
||||||
|
}
|
||||||
|
|
||||||
|
type httpUploadPipelineSpec struct {
|
||||||
|
id string
|
||||||
|
tokenEnv string
|
||||||
|
stagingPath string
|
||||||
|
destinations []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func httpUploadIntegrationConfig(t *testing.T, pipelines []httpUploadPipelineSpec, queueSize, maxConcurrency int) config.Config {
|
||||||
|
t.Helper()
|
||||||
|
size := config.ByteSize(1024 * 1024)
|
||||||
|
retention := config.Duration(time.Minute)
|
||||||
|
cfg := config.Config{
|
||||||
|
Server: config.Server{HTTP: config.HTTPServer{
|
||||||
|
Bind: config.DefaultHTTPBind,
|
||||||
|
StagingRoot: t.TempDir(),
|
||||||
|
MaxUploadSize: &size,
|
||||||
|
QueueSize: queueSize,
|
||||||
|
MaxConcurrency: maxConcurrency,
|
||||||
|
Retention: &retention,
|
||||||
|
}},
|
||||||
|
}
|
||||||
|
for _, spec := range pipelines {
|
||||||
|
pipeline := config.Pipeline{
|
||||||
|
ID: spec.id,
|
||||||
|
Source: config.Backend{
|
||||||
|
Backend: config.BackendHTTPUpload,
|
||||||
|
Upload: config.HTTPUpload{
|
||||||
|
TokenEnv: spec.tokenEnv,
|
||||||
|
StagingPath: spec.stagingPath,
|
||||||
|
MaxUploadSize: &size,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for index, destination := range spec.destinations {
|
||||||
|
pipeline.Destinations = append(pipeline.Destinations, config.Destination{
|
||||||
|
ID: fmt.Sprintf("archive-%d", index+1),
|
||||||
|
Backend: config.BackendLocal,
|
||||||
|
Path: destination,
|
||||||
|
Publish: &config.PublishPolicy{Source: true},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
cfg.Pipelines = append(cfg.Pipelines, pipeline)
|
||||||
|
}
|
||||||
|
config.ApplyDefaults(&cfg)
|
||||||
|
return cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
func submitHTTPUpload(t *testing.T, server *httptest.Server, token, contentType string, body []byte) UploadRunID {
|
||||||
|
t.Helper()
|
||||||
|
request, err := http.NewRequest(http.MethodPost, server.URL+"/upload", bytes.NewReader(body))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("NewRequest() error = %v", err)
|
||||||
|
}
|
||||||
|
request.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
request.Header.Set("Content-Type", contentType)
|
||||||
|
response, err := server.Client().Do(request)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("POST /upload error = %v", err)
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.StatusCode != http.StatusAccepted {
|
||||||
|
t.Fatalf("POST /upload status = %d, want %d", response.StatusCode, http.StatusAccepted)
|
||||||
|
}
|
||||||
|
var accepted uploadAcceptedResponse
|
||||||
|
if err := json.NewDecoder(response.Body).Decode(&accepted); err != nil {
|
||||||
|
t.Fatalf("decode accepted response: %v", err)
|
||||||
|
}
|
||||||
|
if accepted.RunID == "" || accepted.Status != UploadStatusAccepted {
|
||||||
|
t.Fatalf("accepted response = %#v, want run id and accepted status", accepted)
|
||||||
|
}
|
||||||
|
return accepted.RunID
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitForHTTPUploadStatus(t *testing.T, server *httptest.Server, runID UploadRunID, status UploadStatus) UploadRunRecord {
|
||||||
|
t.Helper()
|
||||||
|
deadline := time.Now().Add(3 * time.Second)
|
||||||
|
var latest UploadRunRecord
|
||||||
|
var latestStatus int
|
||||||
|
for time.Now().Before(deadline) {
|
||||||
|
latest, latestStatus = getHTTPUploadStatus(t, server, runID)
|
||||||
|
if latestStatus == http.StatusOK && latest.Status == status {
|
||||||
|
return latest
|
||||||
|
}
|
||||||
|
time.Sleep(time.Millisecond)
|
||||||
|
}
|
||||||
|
t.Fatalf("timed out waiting for status %s; latest HTTP status=%d record=%#v", status, latestStatus, latest)
|
||||||
|
return UploadRunRecord{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func getHTTPUploadStatus(t *testing.T, server *httptest.Server, runID UploadRunID) (UploadRunRecord, int) {
|
||||||
|
t.Helper()
|
||||||
|
response, err := server.Client().Get(server.URL + "/runs/" + string(runID))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GET /runs error = %v", err)
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.StatusCode != http.StatusOK {
|
||||||
|
return UploadRunRecord{}, response.StatusCode
|
||||||
|
}
|
||||||
|
var record UploadRunRecord
|
||||||
|
if err := json.NewDecoder(response.Body).Decode(&record); err != nil {
|
||||||
|
t.Fatalf("decode run status: %v", err)
|
||||||
|
}
|
||||||
|
return record, response.StatusCode
|
||||||
|
}
|
||||||
|
|
||||||
|
func bundleArchive(t *testing.T, compressed bool, opts testutil.BundleOptions) []byte {
|
||||||
|
t.Helper()
|
||||||
|
root := t.TempDir()
|
||||||
|
testutil.WriteSourceBundle(t, root, "", opts)
|
||||||
|
return tarDirectory(t, root, compressed)
|
||||||
|
}
|
||||||
|
|
||||||
|
func tarDirectory(t *testing.T, root string, compressed bool) []byte {
|
||||||
|
t.Helper()
|
||||||
|
var output bytes.Buffer
|
||||||
|
var writer io.WriteCloser = nopWriteCloser{writer: &output}
|
||||||
|
if compressed {
|
||||||
|
gzipWriter := gzip.NewWriter(&output)
|
||||||
|
writer = gzipWriter
|
||||||
|
}
|
||||||
|
tarWriter := tar.NewWriter(writer)
|
||||||
|
if err := filepath.WalkDir(root, func(filePath string, entry fs.DirEntry, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if entry.IsDir() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
relative, err := filepath.Rel(root, filePath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(filePath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
header := &tar.Header{
|
||||||
|
Name: filepath.ToSlash(relative),
|
||||||
|
Mode: 0o600,
|
||||||
|
Size: int64(len(data)),
|
||||||
|
}
|
||||||
|
if err := tarWriter.WriteHeader(header); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := tarWriter.Write(data); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("walk bundle: %v", err)
|
||||||
|
}
|
||||||
|
if err := tarWriter.Close(); err != nil {
|
||||||
|
t.Fatalf("close tar: %v", err)
|
||||||
|
}
|
||||||
|
if err := writer.Close(); err != nil {
|
||||||
|
t.Fatalf("close archive: %v", err)
|
||||||
|
}
|
||||||
|
return output.Bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
type nopWriteCloser struct {
|
||||||
|
writer io.Writer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (writer nopWriteCloser) Write(data []byte) (int, error) {
|
||||||
|
return writer.writer.Write(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (writer nopWriteCloser) Close() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertPublishedBundle(t *testing.T, destinationRoot string) {
|
||||||
|
t.Helper()
|
||||||
|
testutil.AssertFile(t, filepath.Join(destinationRoot, "report.md"), "# Report\nSunny.\n")
|
||||||
|
testutil.AssertFile(t, filepath.Join(destinationRoot, "summary.txt"), "Summary\n")
|
||||||
|
if _, err := os.Stat(filepath.Join(destinationRoot, storage.StateFileName)); err != nil {
|
||||||
|
t.Fatalf("destination state stat: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertDirectoryEmpty(t *testing.T, root string) {
|
||||||
|
t.Helper()
|
||||||
|
entries, err := os.ReadDir(root)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ReadDir() error = %v", err)
|
||||||
|
}
|
||||||
|
if len(entries) != 0 {
|
||||||
|
t.Fatalf("directory %s has %d entries, want empty", root, len(entries))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitForRunStart(t *testing.T, started <-chan struct{}) {
|
||||||
|
t.Helper()
|
||||||
|
select {
|
||||||
|
case <-started:
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatal("timed out waiting for run start")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitForStartedPipelines(t *testing.T, started <-chan string, want ...string) {
|
||||||
|
t.Helper()
|
||||||
|
remaining := map[string]bool{}
|
||||||
|
for _, pipelineID := range want {
|
||||||
|
remaining[pipelineID] = true
|
||||||
|
}
|
||||||
|
deadline := time.After(time.Second)
|
||||||
|
for len(remaining) > 0 {
|
||||||
|
select {
|
||||||
|
case pipelineID := <-started:
|
||||||
|
delete(remaining, pipelineID)
|
||||||
|
case <-deadline:
|
||||||
|
t.Fatalf("timed out waiting for pipelines to start; remaining=%v", remaining)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
331
internal/app/upload_http_test.go
Normal file
331
internal/app/upload_http_test.go
Normal file
@@ -0,0 +1,331 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
type fakeUploadCoordinator struct {
|
||||||
|
canAccept bool
|
||||||
|
submit func(context.Context, UploadRequest) (UploadRunRecord, error)
|
||||||
|
status func(UploadRunID) (UploadRunRecord, bool)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fake fakeUploadCoordinator) CanAccept() bool {
|
||||||
|
return fake.canAccept
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fake fakeUploadCoordinator) Submit(ctx context.Context, request UploadRequest) (UploadRunRecord, error) {
|
||||||
|
if fake.submit == nil {
|
||||||
|
return UploadRunRecord{}, errors.New("unexpected submit")
|
||||||
|
}
|
||||||
|
return fake.submit(ctx, request)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fake fakeUploadCoordinator) Status(runID UploadRunID) (UploadRunRecord, bool) {
|
||||||
|
if fake.status == nil {
|
||||||
|
return UploadRunRecord{}, false
|
||||||
|
}
|
||||||
|
return fake.status(runID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolveUploadTokensFailsForMissingAndDuplicateTokens(t *testing.T) {
|
||||||
|
cfg := uploadHTTPTestConfig()
|
||||||
|
|
||||||
|
_, _, err := resolveUploadTokens(cfg, config.NewEnvironment(nil, func(string) (string, bool) {
|
||||||
|
return "", false
|
||||||
|
}))
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "UPLOAD_TOKEN") {
|
||||||
|
t.Fatalf("resolveUploadTokens() error = %v, want missing UPLOAD_TOKEN", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg.Pipelines = append(cfg.Pipelines, config.Pipeline{
|
||||||
|
ID: "weekly",
|
||||||
|
Source: config.Backend{
|
||||||
|
Backend: config.BackendHTTPUpload,
|
||||||
|
Upload: config.HTTPUpload{TokenEnv: "OTHER_UPLOAD_TOKEN"},
|
||||||
|
},
|
||||||
|
Destinations: cfg.Pipelines[0].Destinations,
|
||||||
|
})
|
||||||
|
config.ApplyDefaults(&cfg)
|
||||||
|
secret := "super-secret-token"
|
||||||
|
_, _, err = resolveUploadTokens(cfg, uploadHTTPTestEnvironment(map[string]string{
|
||||||
|
"UPLOAD_TOKEN": secret,
|
||||||
|
"OTHER_UPLOAD_TOKEN": secret,
|
||||||
|
}))
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("resolveUploadTokens() error = nil, want duplicate token error")
|
||||||
|
}
|
||||||
|
if strings.Contains(err.Error(), secret) {
|
||||||
|
t.Fatalf("duplicate token error exposed secret value: %q", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewUploadHTTPHandlerAcceptsDefaultedConfig(t *testing.T) {
|
||||||
|
cfg := uploadHTTPTestConfig()
|
||||||
|
cfg.Server.HTTP.Bind = ""
|
||||||
|
cfg.Server.HTTP.StagingRoot = ""
|
||||||
|
cfg.Server.HTTP.MaxUploadSize = nil
|
||||||
|
cfg.Server.HTTP.QueueSize = 0
|
||||||
|
cfg.Server.HTTP.MaxConcurrency = 0
|
||||||
|
cfg.Server.HTTP.Retention = nil
|
||||||
|
cfg.Pipelines[0].Source.Upload.StagingPath = ""
|
||||||
|
cfg.Pipelines[0].Source.Upload.MaxUploadSize = nil
|
||||||
|
|
||||||
|
handler, err := newUploadHTTPHandler(context.Background(), cfg, uploadHTTPTestEnvironment(map[string]string{
|
||||||
|
"UPLOAD_TOKEN": "secret",
|
||||||
|
}))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("newUploadHTTPHandler() error = %v", err)
|
||||||
|
}
|
||||||
|
if handler == nil {
|
||||||
|
t.Fatal("newUploadHTTPHandler() = nil")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUploadHTTPHandlerAuthenticatesAndAcceptsUpload(t *testing.T) {
|
||||||
|
var submitted UploadRequest
|
||||||
|
handler := uploadHTTPHandler{
|
||||||
|
coordinator: fakeUploadCoordinator{
|
||||||
|
canAccept: true,
|
||||||
|
submit: func(_ context.Context, request UploadRequest) (UploadRunRecord, error) {
|
||||||
|
submitted = request
|
||||||
|
body, err := io.ReadAll(request.Body)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read submitted body: %v", err)
|
||||||
|
}
|
||||||
|
if string(body) != "archive" {
|
||||||
|
t.Fatalf("submitted body = %q, want archive", body)
|
||||||
|
}
|
||||||
|
return UploadRunRecord{ID: "reports.20260603T120000Z.abcdef12", Status: UploadStatusAccepted}, nil
|
||||||
|
},
|
||||||
|
},
|
||||||
|
tokens: map[string]string{"valid-token": "reports"},
|
||||||
|
limits: map[string]int64{"reports": 1024},
|
||||||
|
}
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
request := httptest.NewRequest(http.MethodPost, "/upload", strings.NewReader("archive"))
|
||||||
|
request.Header.Set("Authorization", "Bearer valid-token")
|
||||||
|
request.Header.Set("Content-Type", "application/x-tar")
|
||||||
|
|
||||||
|
handler.ServeHTTP(recorder, request)
|
||||||
|
|
||||||
|
if recorder.Code != http.StatusAccepted {
|
||||||
|
t.Fatalf("status = %d, want %d; body = %q", recorder.Code, http.StatusAccepted, recorder.Body.String())
|
||||||
|
}
|
||||||
|
if submitted.PipelineID != "reports" {
|
||||||
|
t.Fatalf("submitted pipeline = %q, want reports", submitted.PipelineID)
|
||||||
|
}
|
||||||
|
var response uploadAcceptedResponse
|
||||||
|
if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
|
||||||
|
t.Fatalf("decode response: %v", err)
|
||||||
|
}
|
||||||
|
if response.RunID != "reports.20260603T120000Z.abcdef12" || response.Status != UploadStatusAccepted {
|
||||||
|
t.Fatalf("response = %#v, want accepted run id", response)
|
||||||
|
}
|
||||||
|
if strings.Contains(recorder.Body.String(), "valid-token") {
|
||||||
|
t.Fatalf("response exposed token: %q", recorder.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUploadHTTPHandlerRejectsUnauthorizedRequests(t *testing.T) {
|
||||||
|
handler := uploadHTTPHandler{
|
||||||
|
coordinator: fakeUploadCoordinator{canAccept: true},
|
||||||
|
tokens: map[string]string{"valid-token": "reports"},
|
||||||
|
limits: map[string]int64{"reports": 1024},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, authHeader := range []string{"", "Bearer wrong-token"} {
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
request := httptest.NewRequest(http.MethodPost, "/upload", strings.NewReader("archive"))
|
||||||
|
request.Header.Set("Authorization", authHeader)
|
||||||
|
request.Header.Set("Content-Type", "application/x-tar")
|
||||||
|
|
||||||
|
handler.ServeHTTP(recorder, request)
|
||||||
|
|
||||||
|
if recorder.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("auth %q status = %d, want %d", authHeader, recorder.Code, http.StatusUnauthorized)
|
||||||
|
}
|
||||||
|
if strings.Contains(recorder.Body.String(), "valid-token") || strings.Contains(recorder.Body.String(), "wrong-token") {
|
||||||
|
t.Fatalf("unauthorized response exposed token: %q", recorder.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUploadHTTPHandlerRejectsUnsupportedOversizedFullQueueAndPipelineID(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
canAccept bool
|
||||||
|
url string
|
||||||
|
contentType string
|
||||||
|
body io.Reader
|
||||||
|
wantStatus int
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "unsupported content type",
|
||||||
|
canAccept: true,
|
||||||
|
url: "/upload",
|
||||||
|
contentType: "application/zip",
|
||||||
|
body: strings.NewReader("archive"),
|
||||||
|
wantStatus: http.StatusUnsupportedMediaType,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "oversized",
|
||||||
|
canAccept: true,
|
||||||
|
url: "/upload",
|
||||||
|
contentType: "application/x-tar",
|
||||||
|
body: strings.NewReader("too-large"),
|
||||||
|
wantStatus: http.StatusRequestEntityTooLarge,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "full queue",
|
||||||
|
canAccept: false,
|
||||||
|
url: "/upload",
|
||||||
|
contentType: "application/x-tar",
|
||||||
|
body: &countingReader{reader: strings.NewReader("archive")},
|
||||||
|
wantStatus: http.StatusServiceUnavailable,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "submitted pipeline id",
|
||||||
|
canAccept: true,
|
||||||
|
url: "/upload?pipeline_id=reports",
|
||||||
|
contentType: "application/x-tar",
|
||||||
|
body: strings.NewReader("archive"),
|
||||||
|
wantStatus: http.StatusBadRequest,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
handler := uploadHTTPHandler{
|
||||||
|
coordinator: fakeUploadCoordinator{
|
||||||
|
canAccept: tt.canAccept,
|
||||||
|
submit: func(context.Context, UploadRequest) (UploadRunRecord, error) {
|
||||||
|
t.Fatal("Submit should not be called")
|
||||||
|
return UploadRunRecord{}, nil
|
||||||
|
},
|
||||||
|
},
|
||||||
|
tokens: map[string]string{"valid-token": "reports"},
|
||||||
|
limits: map[string]int64{"reports": 4},
|
||||||
|
}
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
request := httptest.NewRequest(http.MethodPost, tt.url, tt.body)
|
||||||
|
request.Header.Set("Authorization", "Bearer valid-token")
|
||||||
|
request.Header.Set("Content-Type", tt.contentType)
|
||||||
|
|
||||||
|
handler.ServeHTTP(recorder, request)
|
||||||
|
|
||||||
|
if recorder.Code != tt.wantStatus {
|
||||||
|
t.Fatalf("status = %d, want %d; body = %q", recorder.Code, tt.wantStatus, recorder.Body.String())
|
||||||
|
}
|
||||||
|
if reader, ok := tt.body.(*countingReader); ok && reader.reads != 0 {
|
||||||
|
t.Fatalf("full queue read body %d time(s), want zero", reader.reads)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUploadHTTPHandlerRunStatusAndHealth(t *testing.T) {
|
||||||
|
finishedAt := time.Date(2026, 6, 3, 12, 0, 0, 0, time.UTC)
|
||||||
|
handler := uploadHTTPHandler{
|
||||||
|
coordinator: fakeUploadCoordinator{
|
||||||
|
canAccept: true,
|
||||||
|
status: func(runID UploadRunID) (UploadRunRecord, bool) {
|
||||||
|
if runID != "reports.20260603T120000Z.abcdef12" {
|
||||||
|
return UploadRunRecord{}, false
|
||||||
|
}
|
||||||
|
return UploadRunRecord{
|
||||||
|
ID: runID,
|
||||||
|
PipelineID: "reports",
|
||||||
|
Status: UploadStatusSucceeded,
|
||||||
|
FinishedAt: &finishedAt,
|
||||||
|
}, true
|
||||||
|
},
|
||||||
|
},
|
||||||
|
tokens: map[string]string{"valid-token": "reports"},
|
||||||
|
limits: map[string]int64{"reports": 1024},
|
||||||
|
}
|
||||||
|
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/healthz", nil))
|
||||||
|
if recorder.Code != http.StatusOK {
|
||||||
|
t.Fatalf("health status = %d, want %d", recorder.Code, http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
|
recorder = httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/runs/reports.20260603T120000Z.abcdef12", nil))
|
||||||
|
if recorder.Code != http.StatusOK {
|
||||||
|
t.Fatalf("run status = %d, want %d; body = %q", recorder.Code, http.StatusOK, recorder.Body.String())
|
||||||
|
}
|
||||||
|
var record UploadRunRecord
|
||||||
|
if err := json.Unmarshal(recorder.Body.Bytes(), &record); err != nil {
|
||||||
|
t.Fatalf("decode run status: %v", err)
|
||||||
|
}
|
||||||
|
if record.ID != "reports.20260603T120000Z.abcdef12" || record.Status != UploadStatusSucceeded {
|
||||||
|
t.Fatalf("record = %#v, want succeeded run status", record)
|
||||||
|
}
|
||||||
|
|
||||||
|
recorder = httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/runs/unknown", nil))
|
||||||
|
if recorder.Code != http.StatusNotFound {
|
||||||
|
t.Fatalf("unknown run status = %d, want %d", recorder.Code, http.StatusNotFound)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type countingReader struct {
|
||||||
|
reader io.Reader
|
||||||
|
reads int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (reader *countingReader) Read(data []byte) (int, error) {
|
||||||
|
reader.reads++
|
||||||
|
return reader.reader.Read(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func uploadHTTPTestConfig() config.Config {
|
||||||
|
size := config.ByteSize(1024)
|
||||||
|
retention := config.Duration(24 * time.Hour)
|
||||||
|
cfg := config.Config{
|
||||||
|
Server: config.Server{HTTP: config.HTTPServer{
|
||||||
|
Bind: config.DefaultHTTPBind,
|
||||||
|
StagingRoot: "/tmp/distributor-test",
|
||||||
|
MaxUploadSize: &size,
|
||||||
|
QueueSize: 2,
|
||||||
|
MaxConcurrency: 1,
|
||||||
|
Retention: &retention,
|
||||||
|
}},
|
||||||
|
Pipelines: []config.Pipeline{{
|
||||||
|
ID: "reports",
|
||||||
|
Source: config.Backend{
|
||||||
|
Backend: config.BackendHTTPUpload,
|
||||||
|
Upload: config.HTTPUpload{
|
||||||
|
TokenEnv: "UPLOAD_TOKEN",
|
||||||
|
StagingPath: "/tmp/distributor-test/reports",
|
||||||
|
MaxUploadSize: &size,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Destinations: []config.Destination{{
|
||||||
|
ID: "local",
|
||||||
|
Backend: config.BackendLocal,
|
||||||
|
Path: "/tmp/distributor-output",
|
||||||
|
Publish: &config.PublishPolicy{Source: true},
|
||||||
|
}},
|
||||||
|
}},
|
||||||
|
}
|
||||||
|
config.ApplyDefaults(&cfg)
|
||||||
|
return cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
func uploadHTTPTestEnvironment(values map[string]string) config.Environment {
|
||||||
|
return config.NewEnvironment(values, func(string) (string, bool) {
|
||||||
|
return "", false
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -5,28 +5,97 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/distributor/internal/bundle"
|
"gitea.maximumdirect.net/eric/distributor/internal/config"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/storage"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ValidateOptions struct {
|
type ValidateOptions struct {
|
||||||
Path string
|
Path string
|
||||||
Stdout io.Writer
|
ConfigPath string
|
||||||
|
PipelineID string
|
||||||
|
BundlePath string
|
||||||
|
Stdout io.Writer
|
||||||
|
OutputFormat OutputFormat
|
||||||
}
|
}
|
||||||
|
|
||||||
func Validate(ctx context.Context, options ValidateOptions) error {
|
func Validate(ctx context.Context, options ValidateOptions) error {
|
||||||
if options.Path == "" {
|
return validateWithBackendFactory(ctx, options, newBackendFactoryWithEnvironment)
|
||||||
return fmt.Errorf("validate command requires a path")
|
}
|
||||||
|
|
||||||
|
func validateWithBackendFactory(ctx context.Context, options ValidateOptions, provider backendFactoryProvider) error {
|
||||||
|
if err := ValidateOutputFormat(options.OutputFormat); err != nil {
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
backend, err := newBackendFactory().openLocalPath(ctx, options.Path)
|
selection, err := selectSourceBundles(ctx, sourceCommandOptions{
|
||||||
|
CommandName: "validate",
|
||||||
|
Path: options.Path,
|
||||||
|
ConfigPath: options.ConfigPath,
|
||||||
|
PipelineID: options.PipelineID,
|
||||||
|
BundlePath: options.BundlePath,
|
||||||
|
}, provider)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
bundles, err := bundle.Discover(ctx, backend, "")
|
return writeValidateResult(options, selection)
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateConfigWithBackendFactory(ctx context.Context, cfg config.Config, options ValidateOptions, provider backendFactoryProvider) error {
|
||||||
|
if err := ValidateOutputFormat(options.OutputFormat); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
selection, err := selectSourceBundlesFromConfig(ctx, cfg, sourceCommandOptions{
|
||||||
|
CommandName: "validate",
|
||||||
|
PipelineID: options.PipelineID,
|
||||||
|
BundlePath: options.BundlePath,
|
||||||
|
}, provider)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
return writeValidateResult(options, selection)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeValidateResult(options ValidateOptions, selection sourceSelection) error {
|
||||||
|
if IsJSONOutput(options.OutputFormat) {
|
||||||
|
return WriteJSONEnvelope(options.Stdout, "validate", true, selection.Warnings, validateResultFromSelection(selection), nil)
|
||||||
|
}
|
||||||
|
var err error
|
||||||
if options.Stdout != nil {
|
if options.Stdout != nil {
|
||||||
_, err = fmt.Fprintf(options.Stdout, "Validated %d bundle(s)\n", len(bundles))
|
if err := writeWarnings(options.Stdout, selection.Warnings); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if selection.ConfigMode {
|
||||||
|
_, err = fmt.Fprintf(options.Stdout, "Validated %d bundle(s) for pipeline %s source %s\n", len(selection.Bundles), selection.PipelineID, selection.SourceBackend)
|
||||||
|
} else {
|
||||||
|
_, err = fmt.Fprintf(options.Stdout, "Validated %d bundle(s)\n", len(selection.Bundles))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type validateResult struct {
|
||||||
|
PipelineID string `json:"pipeline_id,omitempty"`
|
||||||
|
SourceBackend string `json:"source_backend,omitempty"`
|
||||||
|
BundleCount int `json:"bundle_count"`
|
||||||
|
Bundles []validateBundleResult `json:"bundles"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type validateBundleResult struct {
|
||||||
|
Path string `json:"path"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateResultFromSelection(selection sourceSelection) validateResult {
|
||||||
|
result := validateResult{
|
||||||
|
PipelineID: selection.PipelineID,
|
||||||
|
SourceBackend: selection.SourceBackend,
|
||||||
|
BundleCount: len(selection.Bundles),
|
||||||
|
Bundles: make([]validateBundleResult, 0, len(selection.Bundles)),
|
||||||
|
}
|
||||||
|
for _, sourceBundle := range selection.Bundles {
|
||||||
|
result.Bundles = append(result.Bundles, validateBundleResult{
|
||||||
|
Path: storage.DisplayPath(sourceBundle.RootRelativePath),
|
||||||
|
ID: sourceBundle.Manifest.ID,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,9 +3,15 @@ package app
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/config"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/storage"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/storage/fake"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/testutil"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestValidateLocalBundle(t *testing.T) {
|
func TestValidateLocalBundle(t *testing.T) {
|
||||||
@@ -31,9 +37,182 @@ func TestValidateExampleSourceBundle(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestValidateConfiguredLocalSource(t *testing.T) {
|
||||||
|
sourceRoot := t.TempDir()
|
||||||
|
destinationRoot := t.TempDir()
|
||||||
|
testutil.WriteSourceBundle(t, sourceRoot, "", testutil.BundleOptions{})
|
||||||
|
var stdout bytes.Buffer
|
||||||
|
|
||||||
|
err := Validate(context.Background(), ValidateOptions{
|
||||||
|
ConfigPath: testutil.WriteMinimalLocalConfig(t, sourceRoot, destinationRoot),
|
||||||
|
PipelineID: "reports",
|
||||||
|
Stdout: &stdout,
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Validate() configured source error = %v", err)
|
||||||
|
}
|
||||||
|
if got, want := stdout.String(), "Validated 1 bundle(s) for pipeline reports source local\n"; got != want {
|
||||||
|
t.Fatalf("stdout = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateConfiguredSourceBundlePath(t *testing.T) {
|
||||||
|
sourceRoot := t.TempDir()
|
||||||
|
destinationRoot := t.TempDir()
|
||||||
|
testutil.WriteSourceBundle(t, sourceRoot, "daily/one", testutil.BundleOptions{ID: "reports.one"})
|
||||||
|
testutil.WriteSourceBundle(t, sourceRoot, "daily/two", testutil.BundleOptions{ID: "reports.two"})
|
||||||
|
var stdout bytes.Buffer
|
||||||
|
|
||||||
|
err := Validate(context.Background(), ValidateOptions{
|
||||||
|
ConfigPath: testutil.WriteMinimalLocalConfig(t, sourceRoot, destinationRoot),
|
||||||
|
PipelineID: "reports",
|
||||||
|
BundlePath: "daily/two",
|
||||||
|
Stdout: &stdout,
|
||||||
|
OutputFormat: OutputFormatJSON,
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Validate() configured bundle error = %v", err)
|
||||||
|
}
|
||||||
|
result := decodeAppResult(t, stdout.String())
|
||||||
|
if result["pipeline_id"] != "reports" || result["source_backend"] != "local" || result["bundle_count"] != float64(1) {
|
||||||
|
t.Fatalf("result = %#v, want configured source summary", result)
|
||||||
|
}
|
||||||
|
bundles, ok := result["bundles"].([]any)
|
||||||
|
if !ok || len(bundles) != 1 {
|
||||||
|
t.Fatalf("bundles = %#v, want one bundle", result["bundles"])
|
||||||
|
}
|
||||||
|
sourceBundle, ok := bundles[0].(map[string]any)
|
||||||
|
if !ok || sourceBundle["path"] != "daily/two" || sourceBundle["id"] != "reports.two" {
|
||||||
|
t.Fatalf("bundle = %#v, want narrowed bundle", sourceBundle)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateConfiguredRemoteSourcesThroughStorageAbstraction(t *testing.T) {
|
||||||
|
s3Source := fake.New()
|
||||||
|
testutil.WriteFakeSourceBundle(t, s3Source, "", testutil.BundleOptions{ID: "reports.s3"})
|
||||||
|
sshSource := fake.New()
|
||||||
|
testutil.WriteFakeSourceBundle(t, sshSource, "daily", testutil.BundleOptions{ID: "reports.ssh"})
|
||||||
|
cfg := config.Config{Pipelines: []config.Pipeline{
|
||||||
|
{
|
||||||
|
ID: "s3-reports",
|
||||||
|
Source: config.Backend{
|
||||||
|
Backend: config.BackendS3,
|
||||||
|
Endpoint: "http://s3.test",
|
||||||
|
Bucket: "source-bucket",
|
||||||
|
},
|
||||||
|
Destinations: []config.Destination{{
|
||||||
|
ID: "archive",
|
||||||
|
Backend: config.BackendLocal,
|
||||||
|
Path: t.TempDir(),
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
ID: "ssh-reports",
|
||||||
|
Source: config.Backend{
|
||||||
|
Backend: config.BackendSSH,
|
||||||
|
Host: "ssh.test",
|
||||||
|
Path: "/source",
|
||||||
|
},
|
||||||
|
Destinations: []config.Destination{{
|
||||||
|
ID: "archive",
|
||||||
|
Backend: config.BackendLocal,
|
||||||
|
Path: t.TempDir(),
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
config.ApplyDefaults(&cfg)
|
||||||
|
provider := fakeBackendFactoryProvider(t, map[string]storage.Backend{
|
||||||
|
"s3:source-bucket": s3Source,
|
||||||
|
"ssh:/source": sshSource,
|
||||||
|
})
|
||||||
|
|
||||||
|
var s3Stdout bytes.Buffer
|
||||||
|
if err := validateConfigWithBackendFactory(context.Background(), cfg, ValidateOptions{
|
||||||
|
PipelineID: "s3-reports",
|
||||||
|
Stdout: &s3Stdout,
|
||||||
|
OutputFormat: OutputFormatJSON,
|
||||||
|
}, provider); err != nil {
|
||||||
|
t.Fatalf("validate s3 source error = %v", err)
|
||||||
|
}
|
||||||
|
s3Result := decodeAppResult(t, s3Stdout.String())
|
||||||
|
if s3Result["source_backend"] != "s3" || s3Result["bundle_count"] != float64(1) {
|
||||||
|
t.Fatalf("s3 result = %#v, want one s3 bundle", s3Result)
|
||||||
|
}
|
||||||
|
|
||||||
|
var sshStdout bytes.Buffer
|
||||||
|
if err := validateConfigWithBackendFactory(context.Background(), cfg, ValidateOptions{
|
||||||
|
PipelineID: "ssh-reports",
|
||||||
|
BundlePath: "daily",
|
||||||
|
Stdout: &sshStdout,
|
||||||
|
}, provider); err != nil {
|
||||||
|
t.Fatalf("validate ssh source error = %v", err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(sshStdout.String(), "pipeline ssh-reports source ssh") {
|
||||||
|
t.Fatalf("ssh stdout = %q, want ssh source summary", sshStdout.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateConfiguredSourceLoadsSecretsBeforeOpeningBackend(t *testing.T) {
|
||||||
|
sourceRoot := filepath.Join(t.TempDir(), "missing-source")
|
||||||
|
destinationRoot := t.TempDir()
|
||||||
|
configPath := writeConfigFile(t, `
|
||||||
|
secrets:
|
||||||
|
directory: `+filepath.Join(t.TempDir(), "missing-secrets")+`
|
||||||
|
pipelines:
|
||||||
|
- id: reports
|
||||||
|
source:
|
||||||
|
backend: local
|
||||||
|
path: `+sourceRoot+`
|
||||||
|
destinations:
|
||||||
|
- id: archive
|
||||||
|
backend: local
|
||||||
|
path: `+destinationRoot+`
|
||||||
|
`)
|
||||||
|
|
||||||
|
err := Validate(context.Background(), ValidateOptions{ConfigPath: configPath, PipelineID: "reports"})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("Validate() error = nil, want secrets directory error")
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "load secrets directory") {
|
||||||
|
t.Fatalf("Validate() error = %v, want secrets directory error", err)
|
||||||
|
}
|
||||||
|
if strings.Contains(err.Error(), "missing-source") {
|
||||||
|
t.Fatalf("Validate() error = %v, opened source before loading secrets", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateConfiguredSourceRequiresPipeline(t *testing.T) {
|
||||||
|
sourceRoot := t.TempDir()
|
||||||
|
destinationRoot := t.TempDir()
|
||||||
|
testutil.WriteSourceBundle(t, sourceRoot, "", testutil.BundleOptions{})
|
||||||
|
|
||||||
|
err := Validate(context.Background(), ValidateOptions{
|
||||||
|
ConfigPath: testutil.WriteMinimalLocalConfig(t, sourceRoot, destinationRoot),
|
||||||
|
})
|
||||||
|
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "requires --pipeline") {
|
||||||
|
t.Fatalf("Validate() error = %v, want required pipeline", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestValidateRequiresPath(t *testing.T) {
|
func TestValidateRequiresPath(t *testing.T) {
|
||||||
err := Validate(context.Background(), ValidateOptions{})
|
err := Validate(context.Background(), ValidateOptions{})
|
||||||
if err == nil || !strings.Contains(err.Error(), "requires a path") {
|
if err == nil || !strings.Contains(err.Error(), "requires a path") {
|
||||||
t.Fatalf("Validate() error = %v, want required path", err)
|
t.Fatalf("Validate() error = %v, want required path", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func decodeAppResult(t *testing.T, output string) map[string]any {
|
||||||
|
t.Helper()
|
||||||
|
var envelope map[string]any
|
||||||
|
if err := json.Unmarshal([]byte(output), &envelope); err != nil {
|
||||||
|
t.Fatalf("decode output: %v; output = %q", err, output)
|
||||||
|
}
|
||||||
|
result, ok := envelope["result"].(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("result = %#v, want object", envelope["result"])
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,49 +1,19 @@
|
|||||||
package bundle
|
package bundle
|
||||||
|
|
||||||
import (
|
import publicbundle "gitea.maximumdirect.net/eric/distributor/pkg/bundle"
|
||||||
"crypto/sha256"
|
|
||||||
"encoding/hex"
|
|
||||||
"fmt"
|
|
||||||
"regexp"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
var digestPattern = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`)
|
|
||||||
|
|
||||||
func ValidateDigest(value string) error {
|
func ValidateDigest(value string) error {
|
||||||
if !digestPattern.MatchString(value) {
|
return publicbundle.ValidateDigest(value)
|
||||||
return fmt.Errorf("must be lowercase sha256:<64 hex>")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func FileDigest(data []byte) string {
|
func FileDigest(data []byte) string {
|
||||||
sum := sha256.Sum256(data)
|
return publicbundle.FileDigest(data)
|
||||||
return "sha256:" + hex.EncodeToString(sum[:])
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func BundleDigest(files []ManifestFile) string {
|
func BundleDigest(files []ManifestFile) string {
|
||||||
canonical := CanonicalFilePayload(files)
|
return publicbundle.BundleDigest(files)
|
||||||
sum := sha256.Sum256([]byte(canonical))
|
|
||||||
return "sha256:" + hex.EncodeToString(sum[:])
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func CanonicalFilePayload(files []ManifestFile) string {
|
func CanonicalFilePayload(files []ManifestFile) string {
|
||||||
var builder strings.Builder
|
return publicbundle.CanonicalFilePayload(files)
|
||||||
builder.WriteByte('[')
|
|
||||||
for index, file := range files {
|
|
||||||
if index > 0 {
|
|
||||||
builder.WriteByte(',')
|
|
||||||
}
|
|
||||||
builder.WriteString(`{"path":`)
|
|
||||||
builder.WriteString(strconv.Quote(file.Path))
|
|
||||||
builder.WriteString(`,"sha256":`)
|
|
||||||
builder.WriteString(strconv.Quote(file.SHA256))
|
|
||||||
builder.WriteString(`,"size":`)
|
|
||||||
builder.WriteString(strconv.FormatInt(file.Size, 10))
|
|
||||||
builder.WriteByte('}')
|
|
||||||
}
|
|
||||||
builder.WriteByte(']')
|
|
||||||
return builder.String()
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,110 +1,32 @@
|
|||||||
package bundle
|
package bundle
|
||||||
|
|
||||||
import (
|
import publicbundle "gitea.maximumdirect.net/eric/distributor/pkg/bundle"
|
||||||
"bytes"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
const ManifestName = "manifest.json"
|
const ManifestName = publicbundle.ManifestName
|
||||||
|
|
||||||
type Manifest struct {
|
const SchemaVersion = publicbundle.SchemaVersion
|
||||||
SchemaVersion int `json:"schema_version"`
|
|
||||||
ID string `json:"id"`
|
|
||||||
Digest string `json:"digest"`
|
|
||||||
Created time.Time `json:"created"`
|
|
||||||
Files []ManifestFile `json:"files"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type ManifestFile struct {
|
type Manifest = publicbundle.Manifest
|
||||||
Path string `json:"path"`
|
|
||||||
SHA256 string `json:"sha256"`
|
type ManifestFile = publicbundle.ManifestFile
|
||||||
Size int64 `json:"size"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type Bundle struct {
|
type Bundle struct {
|
||||||
RootRelativePath string
|
RootRelativePath string
|
||||||
Manifest Manifest
|
Manifest Manifest
|
||||||
}
|
}
|
||||||
|
|
||||||
type rawManifest struct {
|
|
||||||
SchemaVersion *int `json:"schema_version"`
|
|
||||||
ID *string `json:"id"`
|
|
||||||
Digest *string `json:"digest"`
|
|
||||||
Created *string `json:"created"`
|
|
||||||
Files []rawManifestFile `json:"files"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type rawManifestFile struct {
|
|
||||||
Path *string `json:"path"`
|
|
||||||
SHA256 *string `json:"sha256"`
|
|
||||||
Size *int64 `json:"size"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func ParseManifest(data []byte) (Manifest, error) {
|
func ParseManifest(data []byte) (Manifest, error) {
|
||||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
return publicbundle.ParseManifest(data)
|
||||||
var raw rawManifest
|
|
||||||
if err := decoder.Decode(&raw); err != nil {
|
|
||||||
return Manifest{}, fmt.Errorf("parse manifest: %w", err)
|
|
||||||
}
|
|
||||||
var extra any
|
|
||||||
if err := decoder.Decode(&extra); err != io.EOF {
|
|
||||||
return Manifest{}, fmt.Errorf("parse manifest: trailing data")
|
|
||||||
}
|
|
||||||
|
|
||||||
var manifest Manifest
|
|
||||||
if raw.SchemaVersion == nil {
|
|
||||||
return Manifest{}, fmt.Errorf("manifest schema_version is required")
|
|
||||||
}
|
|
||||||
manifest.SchemaVersion = *raw.SchemaVersion
|
|
||||||
if raw.ID == nil || *raw.ID == "" {
|
|
||||||
return Manifest{}, fmt.Errorf("manifest id is required")
|
|
||||||
}
|
|
||||||
manifest.ID = *raw.ID
|
|
||||||
if raw.Digest == nil || *raw.Digest == "" {
|
|
||||||
return Manifest{}, fmt.Errorf("manifest digest is required")
|
|
||||||
}
|
|
||||||
manifest.Digest = *raw.Digest
|
|
||||||
if raw.Created == nil || *raw.Created == "" {
|
|
||||||
return Manifest{}, fmt.Errorf("manifest created is required")
|
|
||||||
}
|
|
||||||
created, err := time.Parse(time.RFC3339, *raw.Created)
|
|
||||||
if err != nil {
|
|
||||||
return Manifest{}, fmt.Errorf("manifest created must be RFC3339: %w", err)
|
|
||||||
}
|
|
||||||
manifest.Created = created
|
|
||||||
if len(raw.Files) == 0 {
|
|
||||||
return Manifest{}, fmt.Errorf("manifest files is required")
|
|
||||||
}
|
|
||||||
|
|
||||||
for index, rawFile := range raw.Files {
|
|
||||||
file, err := parseManifestFile(index, rawFile)
|
|
||||||
if err != nil {
|
|
||||||
return Manifest{}, err
|
|
||||||
}
|
|
||||||
manifest.Files = append(manifest.Files, file)
|
|
||||||
}
|
|
||||||
if err := ValidateManifest(manifest); err != nil {
|
|
||||||
return Manifest{}, fmt.Errorf("manifest %w", err)
|
|
||||||
}
|
|
||||||
return manifest, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseManifestFile(index int, raw rawManifestFile) (ManifestFile, error) {
|
func MarshalManifest(manifest Manifest) ([]byte, error) {
|
||||||
if raw.Path == nil || *raw.Path == "" {
|
return publicbundle.MarshalManifest(manifest)
|
||||||
return ManifestFile{}, fmt.Errorf("manifest files[%d].path is required", index)
|
}
|
||||||
}
|
|
||||||
if raw.SHA256 == nil || *raw.SHA256 == "" {
|
func ValidateManifest(manifest Manifest) error {
|
||||||
return ManifestFile{}, fmt.Errorf("manifest files[%d].sha256 is required", index)
|
return publicbundle.ValidateManifest(manifest)
|
||||||
}
|
}
|
||||||
if raw.Size == nil {
|
|
||||||
return ManifestFile{}, fmt.Errorf("manifest files[%d].size is required", index)
|
func ValidateSourcePath(path string) error {
|
||||||
}
|
return publicbundle.ValidateSourcePath(path)
|
||||||
return ManifestFile{
|
|
||||||
Path: *raw.Path,
|
|
||||||
SHA256: *raw.SHA256,
|
|
||||||
Size: *raw.Size,
|
|
||||||
}, nil
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,55 +7,6 @@ import (
|
|||||||
"gitea.maximumdirect.net/eric/distributor/internal/storage"
|
"gitea.maximumdirect.net/eric/distributor/internal/storage"
|
||||||
)
|
)
|
||||||
|
|
||||||
func ValidateSourcePath(path string) error {
|
|
||||||
if err := storage.ValidatePath(path); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
switch path {
|
|
||||||
case ManifestName, storage.StateFileName:
|
|
||||||
return fmt.Errorf("%q is reserved", path)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func ValidateManifest(manifest Manifest) error {
|
|
||||||
if manifest.SchemaVersion != 1 {
|
|
||||||
return fmt.Errorf("schema_version must be 1")
|
|
||||||
}
|
|
||||||
if manifest.ID == "" {
|
|
||||||
return fmt.Errorf("id is required")
|
|
||||||
}
|
|
||||||
if err := ValidateDigest(manifest.Digest); err != nil {
|
|
||||||
return fmt.Errorf("digest: %w", err)
|
|
||||||
}
|
|
||||||
if manifest.Created.IsZero() {
|
|
||||||
return fmt.Errorf("created is required")
|
|
||||||
}
|
|
||||||
if len(manifest.Files) == 0 {
|
|
||||||
return fmt.Errorf("files is required")
|
|
||||||
}
|
|
||||||
seen := make(map[string]struct{}, len(manifest.Files))
|
|
||||||
for index, file := range manifest.Files {
|
|
||||||
if err := ValidateSourcePath(file.Path); err != nil {
|
|
||||||
return fmt.Errorf("files[%d].path: %w", index, err)
|
|
||||||
}
|
|
||||||
if err := ValidateDigest(file.SHA256); err != nil {
|
|
||||||
return fmt.Errorf("files[%d].sha256: %w", index, err)
|
|
||||||
}
|
|
||||||
if file.Size < 0 {
|
|
||||||
return fmt.Errorf("files[%d].size must be non-negative", index)
|
|
||||||
}
|
|
||||||
if _, exists := seen[file.Path]; exists {
|
|
||||||
return fmt.Errorf("files[%d].path duplicates %q", index, file.Path)
|
|
||||||
}
|
|
||||||
seen[file.Path] = struct{}{}
|
|
||||||
}
|
|
||||||
if actual := BundleDigest(manifest.Files); actual != manifest.Digest {
|
|
||||||
return fmt.Errorf("digest mismatch: got %s want %s", actual, manifest.Digest)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func Validate(ctx context.Context, backend storage.Backend, bundleRoot string) (Bundle, error) {
|
func Validate(ctx context.Context, backend storage.Backend, bundleRoot string) (Bundle, error) {
|
||||||
return validateAt(ctx, backend, bundleRoot, bundleRoot)
|
return validateAt(ctx, backend, bundleRoot, bundleRoot)
|
||||||
}
|
}
|
||||||
|
|||||||
22
internal/cli/format.go
Normal file
22
internal/cli/format.go
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/app"
|
||||||
|
)
|
||||||
|
|
||||||
|
func addFormatFlag(flags *flag.FlagSet) *string {
|
||||||
|
return flags.String("format", string(app.OutputFormatText), "output format: text or json")
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseOutputFormat(stderr io.Writer, command, raw string) (app.OutputFormat, bool) {
|
||||||
|
format := app.OutputFormat(raw)
|
||||||
|
if err := app.ValidateOutputFormat(format); err != nil {
|
||||||
|
fmt.Fprintf(stderr, "%s: %s --format: %s\n", app.Name, command, err)
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return app.NormalizeOutputFormat(format), true
|
||||||
|
}
|
||||||
@@ -13,11 +13,18 @@ func inspectCommand(ctx context.Context, args []string, stdout, stderr io.Writer
|
|||||||
printInspectHelp(stdout)
|
printInspectHelp(stdout)
|
||||||
return exitOK
|
return exitOK
|
||||||
}
|
}
|
||||||
path, ok := parseOptionalPathArg(stderr, "inspect", args)
|
parsed, ok := parseSourceDiagnosticArgs(stderr, "inspect", args)
|
||||||
if !ok {
|
if !ok {
|
||||||
return exitUsage
|
return exitUsage
|
||||||
}
|
}
|
||||||
if err := app.Inspect(ctx, app.InspectOptions{Path: path, Stdout: stdout}); err != nil {
|
if err := app.Inspect(ctx, app.InspectOptions{
|
||||||
|
Path: parsed.Path,
|
||||||
|
ConfigPath: parsed.ConfigPath,
|
||||||
|
PipelineID: parsed.PipelineID,
|
||||||
|
BundlePath: parsed.BundlePath,
|
||||||
|
Stdout: stdout,
|
||||||
|
OutputFormat: parsed.OutputFormat,
|
||||||
|
}); err != nil {
|
||||||
return fail(stderr, err)
|
return fail(stderr, err)
|
||||||
}
|
}
|
||||||
return exitOK
|
return exitOK
|
||||||
@@ -25,8 +32,16 @@ func inspectCommand(ctx context.Context, args []string, stdout, stderr io.Writer
|
|||||||
|
|
||||||
func printInspectHelp(w io.Writer) {
|
func printInspectHelp(w io.Writer) {
|
||||||
fmt.Fprint(w, `Usage:
|
fmt.Fprint(w, `Usage:
|
||||||
distributor inspect <path>
|
distributor inspect [--format text|json] <path>
|
||||||
|
distributor inspect --config <path> --pipeline <id> [--bundle <path>] [--format text|json]
|
||||||
|
|
||||||
Print a normalized summary of local source bundles.
|
Options:
|
||||||
|
--config <path> Path to config file for configured source inspection
|
||||||
|
--pipeline <id> Pipeline id to inspect in config mode
|
||||||
|
--bundle <path> Source-root-relative bundle path to inspect
|
||||||
|
--format text|json Output format
|
||||||
|
|
||||||
|
Print a normalized summary of local source bundles or a configured pipeline
|
||||||
|
source.
|
||||||
`)
|
`)
|
||||||
}
|
}
|
||||||
|
|||||||
139
internal/cli/manifest.go
Normal file
139
internal/cli/manifest.go
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/app"
|
||||||
|
)
|
||||||
|
|
||||||
|
func manifestCommand(ctx context.Context, args []string, stdout, stderr io.Writer) int {
|
||||||
|
if len(args) == 0 || args[0] == "-h" || args[0] == "--help" || args[0] == "help" {
|
||||||
|
printManifestHelp(stdout)
|
||||||
|
return exitOK
|
||||||
|
}
|
||||||
|
switch args[0] {
|
||||||
|
case "create":
|
||||||
|
return manifestCreateCommand(ctx, args[1:], stdout, stderr)
|
||||||
|
default:
|
||||||
|
fmt.Fprintf(stderr, "%s: manifest unknown command %q\n\n", app.Name, args[0])
|
||||||
|
printManifestHelp(stderr)
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func manifestCreateCommand(ctx context.Context, args []string, stdout, stderr io.Writer) int {
|
||||||
|
if hasHelp(args) {
|
||||||
|
printManifestCreateHelp(stdout)
|
||||||
|
return exitOK
|
||||||
|
}
|
||||||
|
flags := flag.NewFlagSet("manifest create", flag.ContinueOnError)
|
||||||
|
flags.SetOutput(stderr)
|
||||||
|
id := flags.String("id", "", "source bundle id")
|
||||||
|
created := flags.String("created", "", "source created timestamp")
|
||||||
|
overwrite := flags.Bool("overwrite", false, "replace an existing manifest.json")
|
||||||
|
formatFlag := addFormatFlag(flags)
|
||||||
|
var files repeatedFlag
|
||||||
|
flags.Var(&files, "file", "bundle-relative file to include")
|
||||||
|
flagArgs, positionalArgs, ok := splitManifestCreateArgs(stderr, args)
|
||||||
|
if !ok {
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
if err := flags.Parse(flagArgs); err != nil {
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
if len(positionalArgs) != 1 {
|
||||||
|
fmt.Fprintf(stderr, "%s: manifest create requires exactly one bundle path\n", app.Name)
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
format, ok := parseOutputFormat(stderr, "manifest create", *formatFlag)
|
||||||
|
if !ok {
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
err := app.ManifestCreate(ctx, app.ManifestCreateOptions{
|
||||||
|
Root: positionalArgs[0],
|
||||||
|
ID: *id,
|
||||||
|
Created: *created,
|
||||||
|
Files: []string(files),
|
||||||
|
Overwrite: *overwrite,
|
||||||
|
Stdout: stdout,
|
||||||
|
OutputFormat: format,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return fail(stderr, err)
|
||||||
|
}
|
||||||
|
return exitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
func splitManifestCreateArgs(stderr io.Writer, args []string) ([]string, []string, bool) {
|
||||||
|
var flagArgs []string
|
||||||
|
var positionalArgs []string
|
||||||
|
for index := 0; index < len(args); index++ {
|
||||||
|
arg := args[index]
|
||||||
|
switch arg {
|
||||||
|
case "--overwrite":
|
||||||
|
flagArgs = append(flagArgs, arg)
|
||||||
|
case "--id", "--created", "--file", "--format":
|
||||||
|
if index+1 >= len(args) {
|
||||||
|
fmt.Fprintf(stderr, "%s: manifest create %s requires a value\n", app.Name, arg)
|
||||||
|
return nil, nil, false
|
||||||
|
}
|
||||||
|
flagArgs = append(flagArgs, arg, args[index+1])
|
||||||
|
index++
|
||||||
|
default:
|
||||||
|
if strings.HasPrefix(arg, "--id=") ||
|
||||||
|
strings.HasPrefix(arg, "--created=") ||
|
||||||
|
strings.HasPrefix(arg, "--file=") ||
|
||||||
|
strings.HasPrefix(arg, "--format=") {
|
||||||
|
flagArgs = append(flagArgs, arg)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(arg, "-") {
|
||||||
|
flagArgs = append(flagArgs, arg)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
positionalArgs = append(positionalArgs, arg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return flagArgs, positionalArgs, true
|
||||||
|
}
|
||||||
|
|
||||||
|
type repeatedFlag []string
|
||||||
|
|
||||||
|
func (f *repeatedFlag) String() string {
|
||||||
|
return fmt.Sprint([]string(*f))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *repeatedFlag) Set(value string) error {
|
||||||
|
*f = append(*f, value)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func printManifestHelp(w io.Writer) {
|
||||||
|
fmt.Fprint(w, `Usage:
|
||||||
|
distributor manifest <command> [options]
|
||||||
|
|
||||||
|
Commands:
|
||||||
|
create Create a source bundle manifest
|
||||||
|
|
||||||
|
Use "distributor manifest <command> --help" for command-specific help.
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
func printManifestCreateHelp(w io.Writer) {
|
||||||
|
fmt.Fprint(w, `Usage:
|
||||||
|
distributor manifest create <bundle-path> --id <bundle-id> [options]
|
||||||
|
|
||||||
|
Options:
|
||||||
|
--id <bundle-id> Source bundle id
|
||||||
|
--file <path> Bundle-relative file to include; repeatable
|
||||||
|
--created <time> RFC3339 source created timestamp
|
||||||
|
--overwrite Replace an existing manifest.json
|
||||||
|
--format text|json Output format
|
||||||
|
|
||||||
|
Create manifest.json for a local source bundle directory.
|
||||||
|
`)
|
||||||
|
}
|
||||||
@@ -29,10 +29,14 @@ func Execute(ctx context.Context, args []string, stdout, stderr io.Writer) int {
|
|||||||
return versionCommand(ctx, args[1:], stdout, stderr)
|
return versionCommand(ctx, args[1:], stdout, stderr)
|
||||||
case "run":
|
case "run":
|
||||||
return runCommand(ctx, args[1:], stdout, stderr)
|
return runCommand(ctx, args[1:], stdout, stderr)
|
||||||
|
case "serve":
|
||||||
|
return serveCommand(ctx, args[1:], stdout, stderr)
|
||||||
case "validate":
|
case "validate":
|
||||||
return validateCommand(ctx, args[1:], stdout, stderr)
|
return validateCommand(ctx, args[1:], stdout, stderr)
|
||||||
case "inspect":
|
case "inspect":
|
||||||
return inspectCommand(ctx, args[1:], stdout, stderr)
|
return inspectCommand(ctx, args[1:], stdout, stderr)
|
||||||
|
case "manifest":
|
||||||
|
return manifestCommand(ctx, args[1:], stdout, stderr)
|
||||||
default:
|
default:
|
||||||
fmt.Fprintf(stderr, "%s: unknown command %q\n\n", app.Name, args[0])
|
fmt.Fprintf(stderr, "%s: unknown command %q\n\n", app.Name, args[0])
|
||||||
printRootHelp(stderr)
|
printRootHelp(stderr)
|
||||||
@@ -49,8 +53,10 @@ Usage:
|
|||||||
Commands:
|
Commands:
|
||||||
version Print version information
|
version Print version information
|
||||||
run Run configured distribution pipelines
|
run Run configured distribution pipelines
|
||||||
|
serve Run the HTTP upload server
|
||||||
validate Validate a source bundle or bundle tree
|
validate Validate a source bundle or bundle tree
|
||||||
inspect Inspect bundles or distributor state
|
inspect Inspect bundles or distributor state
|
||||||
|
manifest Create source bundle manifests
|
||||||
|
|
||||||
Use "%s <command> --help" for command-specific help.
|
Use "%s <command> --help" for command-specific help.
|
||||||
`, app.Name, app.Name, app.Name)
|
`, app.Name, app.Name, app.Name)
|
||||||
|
|||||||
@@ -3,15 +3,43 @@ package cli
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/app"
|
||||||
"gitea.maximumdirect.net/eric/distributor/internal/storage"
|
"gitea.maximumdirect.net/eric/distributor/internal/storage"
|
||||||
"gitea.maximumdirect.net/eric/distributor/internal/testutil"
|
"gitea.maximumdirect.net/eric/distributor/internal/testutil"
|
||||||
|
producerbundle "gitea.maximumdirect.net/eric/distributor/pkg/bundle"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func decodeEnvelope(t *testing.T, stdout *bytes.Buffer) map[string]any {
|
||||||
|
t.Helper()
|
||||||
|
decoder := json.NewDecoder(strings.NewReader(stdout.String()))
|
||||||
|
var envelope map[string]any
|
||||||
|
if err := decoder.Decode(&envelope); err != nil {
|
||||||
|
t.Fatalf("decode JSON envelope: %v; stdout = %q", err, stdout.String())
|
||||||
|
}
|
||||||
|
var extra any
|
||||||
|
if err := decoder.Decode(&extra); err != io.EOF {
|
||||||
|
t.Fatalf("stdout contains more than one JSON document: %q", stdout.String())
|
||||||
|
}
|
||||||
|
return envelope
|
||||||
|
}
|
||||||
|
|
||||||
|
func envelopeResult(t *testing.T, envelope map[string]any) map[string]any {
|
||||||
|
t.Helper()
|
||||||
|
result, ok := envelope["result"].(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("result = %#v, want object", envelope["result"])
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
func TestExecuteRootHelp(t *testing.T) {
|
func TestExecuteRootHelp(t *testing.T) {
|
||||||
var stdout, stderr bytes.Buffer
|
var stdout, stderr bytes.Buffer
|
||||||
|
|
||||||
@@ -44,6 +72,71 @@ func TestExecuteVersion(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestExecuteVersionJSON(t *testing.T) {
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
|
||||||
|
code := Execute(context.Background(), []string{"version", "--format", "json"}, &stdout, &stderr)
|
||||||
|
|
||||||
|
if code != exitOK {
|
||||||
|
t.Fatalf("exit code = %d, want %d; stderr = %q", code, exitOK, stderr.String())
|
||||||
|
}
|
||||||
|
envelope := decodeEnvelope(t, &stdout)
|
||||||
|
if envelope["command"] != "version" || envelope["ok"] != true {
|
||||||
|
t.Fatalf("envelope = %#v, want version ok", envelope)
|
||||||
|
}
|
||||||
|
result := envelopeResult(t, envelope)
|
||||||
|
if result["application"] != "distributor" || result["version"] != "dev" {
|
||||||
|
t.Fatalf("result = %#v, want application/version", result)
|
||||||
|
}
|
||||||
|
if stderr.Len() != 0 {
|
||||||
|
t.Fatalf("stderr = %q, want empty", stderr.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecuteServeParsesConfig(t *testing.T) {
|
||||||
|
originalServeApp := serveApp
|
||||||
|
defer func() {
|
||||||
|
serveApp = originalServeApp
|
||||||
|
}()
|
||||||
|
var gotOptions app.ServeOptions
|
||||||
|
serveApp = func(_ context.Context, options app.ServeOptions) error {
|
||||||
|
gotOptions = options
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
|
||||||
|
code := Execute(context.Background(), []string{"serve", "--config", "config.yml"}, &stdout, &stderr)
|
||||||
|
|
||||||
|
if code != exitOK {
|
||||||
|
t.Fatalf("exit code = %d, want %d; stderr = %q", code, exitOK, stderr.String())
|
||||||
|
}
|
||||||
|
if gotOptions.ConfigPath != "config.yml" {
|
||||||
|
t.Fatalf("ConfigPath = %q, want config.yml", gotOptions.ConfigPath)
|
||||||
|
}
|
||||||
|
if stdout.Len() != 0 {
|
||||||
|
t.Fatalf("stdout = %q, want empty", stdout.String())
|
||||||
|
}
|
||||||
|
if stderr.Len() != 0 {
|
||||||
|
t.Fatalf("stderr = %q, want empty", stderr.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecuteRejectsInvalidFormat(t *testing.T) {
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
|
||||||
|
code := Execute(context.Background(), []string{"version", "--format", "xml"}, &stdout, &stderr)
|
||||||
|
|
||||||
|
if code != exitUsage {
|
||||||
|
t.Fatalf("exit code = %d, want %d", code, exitUsage)
|
||||||
|
}
|
||||||
|
if stdout.Len() != 0 {
|
||||||
|
t.Fatalf("stdout = %q, want empty", stdout.String())
|
||||||
|
}
|
||||||
|
if !strings.Contains(stderr.String(), "format must be text or json") {
|
||||||
|
t.Fatalf("stderr = %q, want invalid format error", stderr.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestExecuteValidate(t *testing.T) {
|
func TestExecuteValidate(t *testing.T) {
|
||||||
var stdout, stderr bytes.Buffer
|
var stdout, stderr bytes.Buffer
|
||||||
|
|
||||||
@@ -57,6 +150,63 @@ func TestExecuteValidate(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestExecuteValidateJSON(t *testing.T) {
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
|
||||||
|
code := Execute(context.Background(), []string{"validate", "--format", "json", filepath.Join("..", "bundle", "testdata", "valid_bundle")}, &stdout, &stderr)
|
||||||
|
|
||||||
|
if code != exitOK {
|
||||||
|
t.Fatalf("exit code = %d, want %d; stderr = %q", code, exitOK, stderr.String())
|
||||||
|
}
|
||||||
|
envelope := decodeEnvelope(t, &stdout)
|
||||||
|
if envelope["command"] != "validate" || envelope["ok"] != true {
|
||||||
|
t.Fatalf("envelope = %#v, want validate ok", envelope)
|
||||||
|
}
|
||||||
|
result := envelopeResult(t, envelope)
|
||||||
|
if result["bundle_count"] != float64(1) {
|
||||||
|
t.Fatalf("result = %#v, want one bundle", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecuteValidateConfiguredSource(t *testing.T) {
|
||||||
|
sourceRoot := t.TempDir()
|
||||||
|
destinationRoot := t.TempDir()
|
||||||
|
testutil.WriteSourceBundle(t, sourceRoot, "", testutil.BundleOptions{})
|
||||||
|
configPath := testutil.WriteMinimalLocalConfig(t, sourceRoot, destinationRoot)
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
|
||||||
|
code := Execute(context.Background(), []string{"validate", "--config", configPath, "--pipeline", "reports"}, &stdout, &stderr)
|
||||||
|
|
||||||
|
if code != exitOK {
|
||||||
|
t.Fatalf("exit code = %d, want %d; stderr = %q", code, exitOK, stderr.String())
|
||||||
|
}
|
||||||
|
if got, want := stdout.String(), "Validated 1 bundle(s) for pipeline reports source local\n"; got != want {
|
||||||
|
t.Fatalf("stdout = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecuteValidateConfiguredSourceJSON(t *testing.T) {
|
||||||
|
sourceRoot := t.TempDir()
|
||||||
|
destinationRoot := t.TempDir()
|
||||||
|
testutil.WriteSourceBundle(t, sourceRoot, "daily", testutil.BundleOptions{ID: "reports.daily"})
|
||||||
|
configPath := testutil.WriteMinimalLocalConfig(t, sourceRoot, destinationRoot)
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
|
||||||
|
code := Execute(context.Background(), []string{"validate", "--config", configPath, "--pipeline", "reports", "--bundle", "daily", "--format", "json"}, &stdout, &stderr)
|
||||||
|
|
||||||
|
if code != exitOK {
|
||||||
|
t.Fatalf("exit code = %d, want %d; stderr = %q", code, exitOK, stderr.String())
|
||||||
|
}
|
||||||
|
envelope := decodeEnvelope(t, &stdout)
|
||||||
|
if envelope["command"] != "validate" || envelope["ok"] != true {
|
||||||
|
t.Fatalf("envelope = %#v, want validate ok", envelope)
|
||||||
|
}
|
||||||
|
result := envelopeResult(t, envelope)
|
||||||
|
if result["pipeline_id"] != "reports" || result["source_backend"] != "local" || result["bundle_count"] != float64(1) {
|
||||||
|
t.Fatalf("result = %#v, want configured source metadata", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestExecuteValidateArgs(t *testing.T) {
|
func TestExecuteValidateArgs(t *testing.T) {
|
||||||
validPath := filepath.Join("..", "bundle", "testdata", "valid_bundle")
|
validPath := filepath.Join("..", "bundle", "testdata", "valid_bundle")
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
@@ -84,6 +234,36 @@ func TestExecuteValidateArgs(t *testing.T) {
|
|||||||
wantCode: exitUsage,
|
wantCode: exitUsage,
|
||||||
wantStderr: "accepts at most one path",
|
wantStderr: "accepts at most one path",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "path plus config",
|
||||||
|
args: []string{"validate", "--config", "config.yml", "--pipeline", "reports", validPath},
|
||||||
|
wantCode: exitUsage,
|
||||||
|
wantStderr: "does not accept a local path",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "pipeline without config",
|
||||||
|
args: []string{"validate", "--pipeline", "reports"},
|
||||||
|
wantCode: exitUsage,
|
||||||
|
wantStderr: "requires --config",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "bundle without config",
|
||||||
|
args: []string{"validate", "--bundle", "daily"},
|
||||||
|
wantCode: exitUsage,
|
||||||
|
wantStderr: "requires --config",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "config without pipeline",
|
||||||
|
args: []string{"validate", "--config", "config.yml"},
|
||||||
|
wantCode: exitUsage,
|
||||||
|
wantStderr: "requires --pipeline",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid format",
|
||||||
|
args: []string{"validate", "--format", "xml", validPath},
|
||||||
|
wantCode: exitUsage,
|
||||||
|
wantStderr: "format must be text or json",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
@@ -115,6 +295,56 @@ func TestExecuteInspect(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestExecuteInspectJSON(t *testing.T) {
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
|
||||||
|
code := Execute(context.Background(), []string{"inspect", "--format", "json", filepath.Join("..", "bundle", "testdata", "valid_bundle")}, &stdout, &stderr)
|
||||||
|
|
||||||
|
if code != exitOK {
|
||||||
|
t.Fatalf("exit code = %d, want %d; stderr = %q", code, exitOK, stderr.String())
|
||||||
|
}
|
||||||
|
envelope := decodeEnvelope(t, &stdout)
|
||||||
|
if envelope["command"] != "inspect" || envelope["ok"] != true {
|
||||||
|
t.Fatalf("envelope = %#v, want inspect ok", envelope)
|
||||||
|
}
|
||||||
|
result := envelopeResult(t, envelope)
|
||||||
|
bundles, ok := result["bundles"].([]any)
|
||||||
|
if !ok || len(bundles) != 1 {
|
||||||
|
t.Fatalf("bundles = %#v, want one bundle", result["bundles"])
|
||||||
|
}
|
||||||
|
bundle, ok := bundles[0].(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("bundle = %#v, want object", bundles[0])
|
||||||
|
}
|
||||||
|
if bundle["id"] != "weather.daily.brentwood.2026-05-30" || bundle["file_count"] != float64(2) || bundle["total_size"] != float64(24) {
|
||||||
|
t.Fatalf("bundle = %#v, want normalized metadata", bundle)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecuteInspectConfiguredSource(t *testing.T) {
|
||||||
|
sourceRoot := t.TempDir()
|
||||||
|
destinationRoot := t.TempDir()
|
||||||
|
testutil.WriteSourceBundle(t, sourceRoot, "daily", testutil.BundleOptions{ID: "reports.daily"})
|
||||||
|
configPath := testutil.WriteMinimalLocalConfig(t, sourceRoot, destinationRoot)
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
|
||||||
|
code := Execute(context.Background(), []string{"inspect", "--config", configPath, "--pipeline", "reports"}, &stdout, &stderr)
|
||||||
|
|
||||||
|
if code != exitOK {
|
||||||
|
t.Fatalf("exit code = %d, want %d; stderr = %q", code, exitOK, stderr.String())
|
||||||
|
}
|
||||||
|
for _, want := range []string{
|
||||||
|
"Pipeline: reports",
|
||||||
|
"Source: local",
|
||||||
|
"path=daily",
|
||||||
|
"id=reports.daily",
|
||||||
|
} {
|
||||||
|
if !strings.Contains(stdout.String(), want) {
|
||||||
|
t.Fatalf("stdout = %q, want substring %q", stdout.String(), want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestExecuteInspectArgs(t *testing.T) {
|
func TestExecuteInspectArgs(t *testing.T) {
|
||||||
validPath := filepath.Join("..", "bundle", "testdata", "valid_bundle")
|
validPath := filepath.Join("..", "bundle", "testdata", "valid_bundle")
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
@@ -142,6 +372,36 @@ func TestExecuteInspectArgs(t *testing.T) {
|
|||||||
wantCode: exitUsage,
|
wantCode: exitUsage,
|
||||||
wantStderr: "accepts at most one path",
|
wantStderr: "accepts at most one path",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "path plus config",
|
||||||
|
args: []string{"inspect", "--config", "config.yml", "--pipeline", "reports", validPath},
|
||||||
|
wantCode: exitUsage,
|
||||||
|
wantStderr: "does not accept a local path",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "pipeline without config",
|
||||||
|
args: []string{"inspect", "--pipeline", "reports"},
|
||||||
|
wantCode: exitUsage,
|
||||||
|
wantStderr: "requires --config",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "bundle without config",
|
||||||
|
args: []string{"inspect", "--bundle", "daily"},
|
||||||
|
wantCode: exitUsage,
|
||||||
|
wantStderr: "requires --config",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "config without pipeline",
|
||||||
|
args: []string{"inspect", "--config", "config.yml"},
|
||||||
|
wantCode: exitUsage,
|
||||||
|
wantStderr: "requires --pipeline",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid format",
|
||||||
|
args: []string{"inspect", "--format", "xml", validPath},
|
||||||
|
wantCode: exitUsage,
|
||||||
|
wantStderr: "format must be text or json",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
@@ -160,6 +420,206 @@ func TestExecuteInspectArgs(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestExecuteManifestCreateExplicitFiles(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
writeCLIFile(t, root, "b.txt", "bravo")
|
||||||
|
writeCLIFile(t, root, "nested/a.txt", "alpha")
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
|
||||||
|
code := Execute(context.Background(), []string{
|
||||||
|
"manifest", "create", root,
|
||||||
|
"--id", "reports.explicit",
|
||||||
|
"--created", "2026-06-01T11:00:00Z",
|
||||||
|
"--file", "b.txt",
|
||||||
|
"--file", "nested/a.txt",
|
||||||
|
}, &stdout, &stderr)
|
||||||
|
|
||||||
|
if code != exitOK {
|
||||||
|
t.Fatalf("exit code = %d, want %d; stderr = %q", code, exitOK, stderr.String())
|
||||||
|
}
|
||||||
|
for _, want := range []string{
|
||||||
|
"created manifest.json",
|
||||||
|
"bundle: reports.explicit",
|
||||||
|
"files: 2",
|
||||||
|
"digest: sha256:",
|
||||||
|
} {
|
||||||
|
if !strings.Contains(stdout.String(), want) {
|
||||||
|
t.Fatalf("stdout = %q, want substring %q", stdout.String(), want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
manifest, err := producerbundle.LoadManifest(root)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("LoadManifest() error = %v", err)
|
||||||
|
}
|
||||||
|
if got, want := manifestPaths(manifest), []string{"b.txt", "nested/a.txt"}; !equalStrings(got, want) {
|
||||||
|
t.Fatalf("manifest paths = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
if err := producerbundle.ValidateBundle(root, manifest); err != nil {
|
||||||
|
t.Fatalf("ValidateBundle() error = %v", err)
|
||||||
|
}
|
||||||
|
var validateStdout, validateStderr bytes.Buffer
|
||||||
|
validateCode := Execute(context.Background(), []string{"validate", root}, &validateStdout, &validateStderr)
|
||||||
|
if validateCode != exitOK {
|
||||||
|
t.Fatalf("validate exit code = %d, want %d; stderr = %q", validateCode, exitOK, validateStderr.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecuteManifestCreateScansBundle(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
writeCLIFile(t, root, "z.txt", "zulu")
|
||||||
|
writeCLIFile(t, root, ".env", "dotfile")
|
||||||
|
writeCLIFile(t, root, "nested/report.md", "# Report\n")
|
||||||
|
writeCLIFile(t, root, storage.StateFileName, "destination state")
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
|
||||||
|
code := Execute(context.Background(), []string{"manifest", "create", root, "--id", "reports.scan"}, &stdout, &stderr)
|
||||||
|
|
||||||
|
if code != exitOK {
|
||||||
|
t.Fatalf("exit code = %d, want %d; stderr = %q", code, exitOK, stderr.String())
|
||||||
|
}
|
||||||
|
manifest, err := producerbundle.LoadManifest(root)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("LoadManifest() error = %v", err)
|
||||||
|
}
|
||||||
|
if got, want := manifestPaths(manifest), []string{".env", "nested/report.md", "z.txt"}; !equalStrings(got, want) {
|
||||||
|
t.Fatalf("manifest paths = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecuteManifestCreateJSON(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
writeCLIFile(t, root, "report.md", "# Report\n")
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
|
||||||
|
code := Execute(context.Background(), []string{"manifest", "create", root, "--id", "reports.json", "--file", "report.md", "--format", "json"}, &stdout, &stderr)
|
||||||
|
|
||||||
|
if code != exitOK {
|
||||||
|
t.Fatalf("exit code = %d, want %d; stderr = %q", code, exitOK, stderr.String())
|
||||||
|
}
|
||||||
|
envelope := decodeEnvelope(t, &stdout)
|
||||||
|
if envelope["command"] != "manifest create" || envelope["ok"] != true {
|
||||||
|
t.Fatalf("envelope = %#v, want manifest create ok", envelope)
|
||||||
|
}
|
||||||
|
result := envelopeResult(t, envelope)
|
||||||
|
if result["id"] != "reports.json" || result["file_count"] != float64(1) {
|
||||||
|
t.Fatalf("result = %#v, want manifest summary", result)
|
||||||
|
}
|
||||||
|
if stderr.Len() != 0 {
|
||||||
|
t.Fatalf("stderr = %q, want empty", stderr.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecuteManifestCreateOverwrite(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
writeCLIFile(t, root, "report.md", "old\n")
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
code := Execute(context.Background(), []string{"manifest", "create", root, "--id", "reports.old", "--file", "report.md"}, &stdout, &stderr)
|
||||||
|
if code != exitOK {
|
||||||
|
t.Fatalf("initial exit code = %d, want %d; stderr = %q", code, exitOK, stderr.String())
|
||||||
|
}
|
||||||
|
writeCLIFile(t, root, "report.md", "new\n")
|
||||||
|
|
||||||
|
stdout.Reset()
|
||||||
|
stderr.Reset()
|
||||||
|
code = Execute(context.Background(), []string{"manifest", "create", root, "--id", "reports.new", "--file", "report.md"}, &stdout, &stderr)
|
||||||
|
if code != exitError {
|
||||||
|
t.Fatalf("overwrite exit code = %d, want %d", code, exitError)
|
||||||
|
}
|
||||||
|
if !strings.Contains(stderr.String(), "write manifest") {
|
||||||
|
t.Fatalf("stderr = %q, want write manifest error", stderr.String())
|
||||||
|
}
|
||||||
|
manifest, err := producerbundle.LoadManifest(root)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("LoadManifest() error = %v", err)
|
||||||
|
}
|
||||||
|
if manifest.ID != "reports.old" {
|
||||||
|
t.Fatalf("manifest id = %q, want reports.old", manifest.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
stdout.Reset()
|
||||||
|
stderr.Reset()
|
||||||
|
code = Execute(context.Background(), []string{"manifest", "create", root, "--id", "reports.new", "--file", "report.md", "--overwrite"}, &stdout, &stderr)
|
||||||
|
if code != exitOK {
|
||||||
|
t.Fatalf("overwrite exit code = %d, want %d; stderr = %q", code, exitOK, stderr.String())
|
||||||
|
}
|
||||||
|
manifest, err = producerbundle.LoadManifest(root)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("LoadManifest() error = %v", err)
|
||||||
|
}
|
||||||
|
if manifest.ID != "reports.new" {
|
||||||
|
t.Fatalf("manifest id = %q, want reports.new", manifest.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecuteManifestCreateRejectsSymlink(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
writeCLIFile(t, root, "target.md", "# Report\n")
|
||||||
|
if err := os.Symlink("target.md", filepath.Join(root, "link.md")); err != nil {
|
||||||
|
t.Skipf("symlink unavailable: %v", err)
|
||||||
|
}
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
|
||||||
|
code := Execute(context.Background(), []string{"manifest", "create", root, "--id", "reports.link", "--file", "link.md"}, &stdout, &stderr)
|
||||||
|
|
||||||
|
if code != exitError {
|
||||||
|
t.Fatalf("exit code = %d, want %d", code, exitError)
|
||||||
|
}
|
||||||
|
if !strings.Contains(stderr.String(), "regular file") {
|
||||||
|
t.Fatalf("stderr = %q, want regular file error", stderr.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecuteManifestCreateArgs(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
writeCLIFile(t, root, "report.md", "# Report\n")
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
args []string
|
||||||
|
wantCode int
|
||||||
|
wantStderr string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "missing path",
|
||||||
|
args: []string{"manifest", "create", "--id", "reports.missing"},
|
||||||
|
wantCode: exitUsage,
|
||||||
|
wantStderr: "requires exactly one bundle path",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "missing id",
|
||||||
|
args: []string{"manifest", "create", root},
|
||||||
|
wantCode: exitError,
|
||||||
|
wantStderr: "requires --id",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "bad created",
|
||||||
|
args: []string{"manifest", "create", root, "--id", "reports.bad", "--created", "June 1"},
|
||||||
|
wantCode: exitError,
|
||||||
|
wantStderr: "created must be RFC3339",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "bad format",
|
||||||
|
args: []string{"manifest", "create", root, "--id", "reports.bad", "--format", "xml"},
|
||||||
|
wantCode: exitUsage,
|
||||||
|
wantStderr: "format must be text or json",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
code := Execute(context.Background(), tt.args, &stdout, &stderr)
|
||||||
|
if code != tt.wantCode {
|
||||||
|
t.Fatalf("exit code = %d, want %d; stderr = %q", code, tt.wantCode, stderr.String())
|
||||||
|
}
|
||||||
|
if stdout.Len() != 0 {
|
||||||
|
t.Fatalf("stdout = %q, want empty", stdout.String())
|
||||||
|
}
|
||||||
|
if !strings.Contains(stderr.String(), tt.wantStderr) {
|
||||||
|
t.Fatalf("stderr = %q, want substring %q", stderr.String(), tt.wantStderr)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestExecuteRunDryRun(t *testing.T) {
|
func TestExecuteRunDryRun(t *testing.T) {
|
||||||
sourceRoot := t.TempDir()
|
sourceRoot := t.TempDir()
|
||||||
testutil.WriteSourceBundle(t, sourceRoot, "", testutil.BundleOptions{})
|
testutil.WriteSourceBundle(t, sourceRoot, "", testutil.BundleOptions{})
|
||||||
@@ -172,14 +632,297 @@ func TestExecuteRunDryRun(t *testing.T) {
|
|||||||
if code != exitOK {
|
if code != exitOK {
|
||||||
t.Fatalf("exit code = %d, want %d; stderr = %q", code, exitOK, stderr.String())
|
t.Fatalf("exit code = %d, want %d; stderr = %q", code, exitOK, stderr.String())
|
||||||
}
|
}
|
||||||
if !strings.Contains(stdout.String(), "action=publish_new") {
|
wantStdout := "Configured pipelines: 1\n" +
|
||||||
t.Fatalf("stdout = %q, want config summary", stdout.String())
|
"- pipeline=reports source=local bundles=1 destinations=archive\n" +
|
||||||
|
" - bundle=. destination=archive backend=local action=publish_new outputs=report.md,summary.txt reason=\"destination state is absent\"\n" +
|
||||||
|
"Final status: ok planned=1 publish_new=1 replace_older=0 force_replace=0 skipped=0 failed=0 dry_run=true fixed_path=0\n"
|
||||||
|
if got := stdout.String(); got != wantStdout {
|
||||||
|
t.Fatalf("stdout = %q, want %q", got, wantStdout)
|
||||||
}
|
}
|
||||||
if stderr.Len() != 0 {
|
if stderr.Len() != 0 {
|
||||||
t.Fatalf("stderr = %q, want empty", stderr.String())
|
t.Fatalf("stderr = %q, want empty", stderr.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestExecuteRunJSONDryRun(t *testing.T) {
|
||||||
|
sourceRoot := t.TempDir()
|
||||||
|
testutil.WriteSourceBundle(t, sourceRoot, "", testutil.BundleOptions{})
|
||||||
|
configPath := testutil.WriteMinimalLocalConfig(t, sourceRoot, t.TempDir())
|
||||||
|
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
|
||||||
|
code := Execute(context.Background(), []string{"run", "--config", configPath, "--dry-run", "--format", "json"}, &stdout, &stderr)
|
||||||
|
|
||||||
|
if code != exitOK {
|
||||||
|
t.Fatalf("exit code = %d, want %d; stderr = %q", code, exitOK, stderr.String())
|
||||||
|
}
|
||||||
|
envelope := decodeEnvelope(t, &stdout)
|
||||||
|
if envelope["command"] != "run" || envelope["ok"] != true {
|
||||||
|
t.Fatalf("envelope = %#v, want run ok", envelope)
|
||||||
|
}
|
||||||
|
result := envelopeResult(t, envelope)
|
||||||
|
if result["dry_run"] != true {
|
||||||
|
t.Fatalf("result = %#v, want dry_run true", result)
|
||||||
|
}
|
||||||
|
pipelines, ok := result["pipelines"].([]any)
|
||||||
|
if !ok || len(pipelines) != 1 {
|
||||||
|
t.Fatalf("pipelines = %#v, want one pipeline", result["pipelines"])
|
||||||
|
}
|
||||||
|
pipeline, ok := pipelines[0].(map[string]any)
|
||||||
|
if !ok || pipeline["id"] != "reports" || pipeline["source_backend"] != "local" || pipeline["bundle_count"] != float64(1) {
|
||||||
|
t.Fatalf("pipeline = %#v, want reports/local summary", pipelines[0])
|
||||||
|
}
|
||||||
|
actions, ok := result["actions"].([]any)
|
||||||
|
if !ok || len(actions) != 1 {
|
||||||
|
t.Fatalf("actions = %#v, want one action", result["actions"])
|
||||||
|
}
|
||||||
|
action, ok := actions[0].(map[string]any)
|
||||||
|
if !ok || action["action"] != "publish_new" {
|
||||||
|
t.Fatalf("action = %#v, want publish_new", actions[0])
|
||||||
|
}
|
||||||
|
outputs, ok := action["outputs"].([]any)
|
||||||
|
if !ok || len(outputs) != 2 {
|
||||||
|
t.Fatalf("outputs = %#v, want source outputs", action["outputs"])
|
||||||
|
}
|
||||||
|
summary, ok := result["summary"].(map[string]any)
|
||||||
|
if !ok || summary["status"] != "ok" || summary["planned"] != float64(1) || summary["publish_new"] != float64(1) || summary["dry_run"] != true {
|
||||||
|
t.Fatalf("summary = %#v, want ok dry-run publish counters", result["summary"])
|
||||||
|
}
|
||||||
|
if stderr.Len() != 0 {
|
||||||
|
t.Fatalf("stderr = %q, want empty", stderr.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecuteRunJSONDryRunReportsFixedPathMapping(t *testing.T) {
|
||||||
|
sourceRoot := t.TempDir()
|
||||||
|
destinationRoot := t.TempDir()
|
||||||
|
testutil.WriteSourceBundle(t, sourceRoot, "", testutil.BundleOptions{})
|
||||||
|
configPath := filepath.Join(t.TempDir(), "config.yml")
|
||||||
|
if err := os.WriteFile(configPath, []byte(`
|
||||||
|
pipelines:
|
||||||
|
- id: reports
|
||||||
|
source:
|
||||||
|
backend: local
|
||||||
|
path: `+sourceRoot+`
|
||||||
|
destinations:
|
||||||
|
- id: latest
|
||||||
|
backend: local
|
||||||
|
path: `+destinationRoot+`
|
||||||
|
path_mapping:
|
||||||
|
mode: fixed
|
||||||
|
`), 0o600); err != nil {
|
||||||
|
t.Fatalf("write config: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
|
||||||
|
code := Execute(context.Background(), []string{"run", "--config", configPath, "--dry-run", "--format", "json"}, &stdout, &stderr)
|
||||||
|
|
||||||
|
if code != exitOK {
|
||||||
|
t.Fatalf("exit code = %d, want %d; stderr = %q", code, exitOK, stderr.String())
|
||||||
|
}
|
||||||
|
envelope := decodeEnvelope(t, &stdout)
|
||||||
|
warnings, ok := envelope["warnings"].([]any)
|
||||||
|
if !ok || len(warnings) != 1 {
|
||||||
|
t.Fatalf("warnings = %#v, want one fixed-path warning", envelope["warnings"])
|
||||||
|
}
|
||||||
|
warning, ok := warnings[0].(map[string]any)
|
||||||
|
if !ok || !strings.Contains(fmt.Sprint(warning["message"]), "path_mapping=fixed candidates=1 selected_bundle=.") {
|
||||||
|
t.Fatalf("warning = %#v, want fixed-path selection warning", warnings[0])
|
||||||
|
}
|
||||||
|
result := envelopeResult(t, envelope)
|
||||||
|
actions, ok := result["actions"].([]any)
|
||||||
|
if !ok || len(actions) != 1 {
|
||||||
|
t.Fatalf("actions = %#v, want one action", result["actions"])
|
||||||
|
}
|
||||||
|
action, ok := actions[0].(map[string]any)
|
||||||
|
if !ok || action["path_mapping"] != "fixed" || action["destination_path"] != "." || action["action"] != "publish_new" {
|
||||||
|
t.Fatalf("action = %#v, want fixed publish_new at root", actions[0])
|
||||||
|
}
|
||||||
|
summary, ok := result["summary"].(map[string]any)
|
||||||
|
if !ok || summary["fixed_path"] != float64(1) {
|
||||||
|
t.Fatalf("summary = %#v, want fixed_path 1", result["summary"])
|
||||||
|
}
|
||||||
|
if stderr.Len() != 0 {
|
||||||
|
t.Fatalf("stderr = %q, want empty", stderr.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecuteRunJSONDryRunReportsLinks(t *testing.T) {
|
||||||
|
sourceRoot := t.TempDir()
|
||||||
|
destinationRoot := t.TempDir()
|
||||||
|
testutil.WriteSourceBundle(t, sourceRoot, "", testutil.BundleOptions{})
|
||||||
|
configPath := filepath.Join(t.TempDir(), "config.yml")
|
||||||
|
if err := os.WriteFile(configPath, []byte(`
|
||||||
|
pipelines:
|
||||||
|
- id: reports
|
||||||
|
source:
|
||||||
|
backend: local
|
||||||
|
path: `+sourceRoot+`
|
||||||
|
destinations:
|
||||||
|
- id: web
|
||||||
|
backend: local
|
||||||
|
path: `+destinationRoot+`
|
||||||
|
links:
|
||||||
|
base_url: https://reports.example.com/archive
|
||||||
|
primary: source
|
||||||
|
`), 0o600); err != nil {
|
||||||
|
t.Fatalf("write config: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
|
||||||
|
code := Execute(context.Background(), []string{"run", "--config", configPath, "--dry-run", "--format", "json"}, &stdout, &stderr)
|
||||||
|
|
||||||
|
if code != exitOK {
|
||||||
|
t.Fatalf("exit code = %d, want %d; stderr = %q", code, exitOK, stderr.String())
|
||||||
|
}
|
||||||
|
envelope := decodeEnvelope(t, &stdout)
|
||||||
|
result := envelopeResult(t, envelope)
|
||||||
|
actions, ok := result["actions"].([]any)
|
||||||
|
if !ok || len(actions) != 1 {
|
||||||
|
t.Fatalf("actions = %#v, want one action", result["actions"])
|
||||||
|
}
|
||||||
|
action, ok := actions[0].(map[string]any)
|
||||||
|
if !ok || action["primary_url"] != "https://reports.example.com/archive/report.md" {
|
||||||
|
t.Fatalf("action = %#v, want primary URL", actions[0])
|
||||||
|
}
|
||||||
|
outputs, ok := action["outputs"].([]any)
|
||||||
|
if !ok || len(outputs) != 2 {
|
||||||
|
t.Fatalf("outputs = %#v, want two outputs", action["outputs"])
|
||||||
|
}
|
||||||
|
output, ok := outputs[0].(map[string]any)
|
||||||
|
if !ok || output["url"] != "https://reports.example.com/archive/report.md" {
|
||||||
|
t.Fatalf("output = %#v, want output URL", outputs[0])
|
||||||
|
}
|
||||||
|
if stderr.Len() != 0 {
|
||||||
|
t.Fatalf("stderr = %q, want empty", stderr.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecuteRunJSONWarningsAreStructured(t *testing.T) {
|
||||||
|
name := "DISTRIBUTOR_TEST_CLI_JSON_SECRET"
|
||||||
|
t.Setenv(name, "process-value")
|
||||||
|
sourceRoot := t.TempDir()
|
||||||
|
destinationRoot := t.TempDir()
|
||||||
|
secretsRoot := t.TempDir()
|
||||||
|
testutil.WriteSourceBundle(t, sourceRoot, "", testutil.BundleOptions{})
|
||||||
|
if err := os.WriteFile(filepath.Join(secretsRoot, name), []byte("secret-value\n"), 0o600); err != nil {
|
||||||
|
t.Fatalf("write secret: %v", err)
|
||||||
|
}
|
||||||
|
configPath := filepath.Join(t.TempDir(), "config.yml")
|
||||||
|
if err := os.WriteFile(configPath, []byte(`
|
||||||
|
secrets:
|
||||||
|
directory: `+secretsRoot+`
|
||||||
|
pipelines:
|
||||||
|
- id: reports
|
||||||
|
source:
|
||||||
|
backend: local
|
||||||
|
path: `+sourceRoot+`
|
||||||
|
destinations:
|
||||||
|
- id: archive
|
||||||
|
backend: local
|
||||||
|
path: `+destinationRoot+`
|
||||||
|
`), 0o600); err != nil {
|
||||||
|
t.Fatalf("write config: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
code := Execute(context.Background(), []string{"run", "--config", configPath, "--dry-run", "--format", "json"}, &stdout, &stderr)
|
||||||
|
|
||||||
|
if code != exitOK {
|
||||||
|
t.Fatalf("exit code = %d, want %d; stderr = %q", code, exitOK, stderr.String())
|
||||||
|
}
|
||||||
|
envelope := decodeEnvelope(t, &stdout)
|
||||||
|
warnings, ok := envelope["warnings"].([]any)
|
||||||
|
if !ok || len(warnings) != 1 {
|
||||||
|
t.Fatalf("warnings = %#v, want one warning", envelope["warnings"])
|
||||||
|
}
|
||||||
|
warning, ok := warnings[0].(map[string]any)
|
||||||
|
if !ok || !strings.Contains(fmt.Sprint(warning["message"]), name) {
|
||||||
|
t.Fatalf("warning = %#v, want secret name", warnings[0])
|
||||||
|
}
|
||||||
|
if strings.Contains(stdout.String(), "Warning:") || strings.Contains(stdout.String(), "process-value") || strings.Contains(stdout.String(), "secret-value") {
|
||||||
|
t.Fatalf("stdout exposed text warning or secret values: %q", stdout.String())
|
||||||
|
}
|
||||||
|
if stderr.Len() != 0 {
|
||||||
|
t.Fatalf("stderr = %q, want empty", stderr.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecuteRunJSONFatalSetupErrorWritesNoJSON(t *testing.T) {
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
|
||||||
|
code := Execute(context.Background(), []string{"run", "--config", filepath.Join(t.TempDir(), "missing.yml"), "--format", "json"}, &stdout, &stderr)
|
||||||
|
|
||||||
|
if code != exitError {
|
||||||
|
t.Fatalf("exit code = %d, want %d", code, exitError)
|
||||||
|
}
|
||||||
|
if stdout.Len() != 0 {
|
||||||
|
t.Fatalf("stdout = %q, want empty", stdout.String())
|
||||||
|
}
|
||||||
|
if !strings.Contains(stderr.String(), "no such file or directory") {
|
||||||
|
t.Fatalf("stderr = %q, want setup error", stderr.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecuteRunJSONPartialFailure(t *testing.T) {
|
||||||
|
sourceRoot := t.TempDir()
|
||||||
|
firstDestination := t.TempDir()
|
||||||
|
secondDestination := t.TempDir()
|
||||||
|
testutil.WriteSourceBundle(t, sourceRoot, "", testutil.BundleOptions{})
|
||||||
|
if err := os.WriteFile(filepath.Join(firstDestination, "unmanaged.txt"), []byte("data"), 0o600); err != nil {
|
||||||
|
t.Fatalf("write unmanaged file: %v", err)
|
||||||
|
}
|
||||||
|
configPath := filepath.Join(t.TempDir(), "config.yml")
|
||||||
|
if err := os.WriteFile(configPath, []byte(`
|
||||||
|
pipelines:
|
||||||
|
- id: reports
|
||||||
|
source:
|
||||||
|
backend: local
|
||||||
|
path: `+sourceRoot+`
|
||||||
|
destinations:
|
||||||
|
- id: archive-one
|
||||||
|
backend: local
|
||||||
|
path: `+firstDestination+`
|
||||||
|
- id: archive-two
|
||||||
|
backend: local
|
||||||
|
path: `+secondDestination+`
|
||||||
|
`), 0o600); err != nil {
|
||||||
|
t.Fatalf("write config: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
code := Execute(context.Background(), []string{"run", "--config", configPath, "--format", "json"}, &stdout, &stderr)
|
||||||
|
|
||||||
|
if code != exitError {
|
||||||
|
t.Fatalf("exit code = %d, want %d; stderr = %q", code, exitError, stderr.String())
|
||||||
|
}
|
||||||
|
if stderr.Len() != 0 {
|
||||||
|
t.Fatalf("stderr = %q, want empty for partial JSON result", stderr.String())
|
||||||
|
}
|
||||||
|
envelope := decodeEnvelope(t, &stdout)
|
||||||
|
if envelope["command"] != "run" || envelope["ok"] != false {
|
||||||
|
t.Fatalf("envelope = %#v, want failed run envelope", envelope)
|
||||||
|
}
|
||||||
|
errors, ok := envelope["errors"].([]any)
|
||||||
|
if !ok || len(errors) != 1 {
|
||||||
|
t.Fatalf("errors = %#v, want one error", envelope["errors"])
|
||||||
|
}
|
||||||
|
result := envelopeResult(t, envelope)
|
||||||
|
summary, ok := result["summary"].(map[string]any)
|
||||||
|
if !ok || summary["status"] != "failed" || summary["failed"] != float64(1) {
|
||||||
|
t.Fatalf("summary = %#v, want failed summary", result["summary"])
|
||||||
|
}
|
||||||
|
actions, ok := result["actions"].([]any)
|
||||||
|
if !ok || len(actions) != 2 {
|
||||||
|
t.Fatalf("actions = %#v, want two actions", result["actions"])
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(secondDestination, storage.StateFileName)); err != nil {
|
||||||
|
t.Fatalf("second destination state stat error = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestExecuteRunForceDryRunReportsWithoutWriting(t *testing.T) {
|
func TestExecuteRunForceDryRunReportsWithoutWriting(t *testing.T) {
|
||||||
sourceRoot := t.TempDir()
|
sourceRoot := t.TempDir()
|
||||||
destinationRoot := t.TempDir()
|
destinationRoot := t.TempDir()
|
||||||
@@ -249,3 +992,34 @@ func TestUnknownCommandIsUsageError(t *testing.T) {
|
|||||||
t.Fatalf("stderr = %q, want unknown command error", stderr.String())
|
t.Fatalf("stderr = %q, want unknown command error", stderr.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func manifestPaths(manifest producerbundle.Manifest) []string {
|
||||||
|
paths := make([]string, 0, len(manifest.Files))
|
||||||
|
for _, file := range manifest.Files {
|
||||||
|
paths = append(paths, file.Path)
|
||||||
|
}
|
||||||
|
return paths
|
||||||
|
}
|
||||||
|
|
||||||
|
func equalStrings(a, b []string) bool {
|
||||||
|
if len(a) != len(b) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for index := range a {
|
||||||
|
if a[index] != b[index] {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeCLIFile(t *testing.T, root, relative, body string) {
|
||||||
|
t.Helper()
|
||||||
|
path := filepath.Join(root, filepath.FromSlash(relative))
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||||
|
t.Fatalf("mkdir %s: %v", filepath.Dir(path), err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
|
||||||
|
t.Fatalf("write %s: %v", path, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -20,19 +20,28 @@ func runCommand(ctx context.Context, args []string, stdout, stderr io.Writer) in
|
|||||||
configPath := flags.String("config", "", "path to config file")
|
configPath := flags.String("config", "", "path to config file")
|
||||||
dryRun := flags.Bool("dry-run", false, "load and validate config without publishing")
|
dryRun := flags.Bool("dry-run", false, "load and validate config without publishing")
|
||||||
force := flags.Bool("force", false, "allow explicit destructive replacement for supported conflicts")
|
force := flags.Bool("force", false, "allow explicit destructive replacement for supported conflicts")
|
||||||
|
formatFlag := addFormatFlag(flags)
|
||||||
if err := flags.Parse(args); err != nil {
|
if err := flags.Parse(args); err != nil {
|
||||||
return exitUsage
|
return exitUsage
|
||||||
}
|
}
|
||||||
if rejectPositionalArgs(stderr, "run", flags.Args()) {
|
if rejectPositionalArgs(stderr, "run", flags.Args()) {
|
||||||
return exitUsage
|
return exitUsage
|
||||||
}
|
}
|
||||||
|
format, ok := parseOutputFormat(stderr, "run", *formatFlag)
|
||||||
|
if !ok {
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
|
||||||
if err := app.Run(ctx, app.RunOptions{
|
if err := app.Run(ctx, app.RunOptions{
|
||||||
ConfigPath: *configPath,
|
ConfigPath: *configPath,
|
||||||
DryRun: *dryRun,
|
DryRun: *dryRun,
|
||||||
Force: *force,
|
Force: *force,
|
||||||
Stdout: stdout,
|
Stdout: stdout,
|
||||||
|
OutputFormat: format,
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
|
if app.IsJSONOutput(format) && app.IsPartialResultError(err) {
|
||||||
|
return exitError
|
||||||
|
}
|
||||||
return fail(stderr, err)
|
return fail(stderr, err)
|
||||||
}
|
}
|
||||||
return exitOK
|
return exitOK
|
||||||
@@ -40,12 +49,14 @@ func runCommand(ctx context.Context, args []string, stdout, stderr io.Writer) in
|
|||||||
|
|
||||||
func printRunHelp(w io.Writer) {
|
func printRunHelp(w io.Writer) {
|
||||||
fmt.Fprint(w, `Usage:
|
fmt.Fprint(w, `Usage:
|
||||||
distributor run --config <path> [--dry-run] [--force]
|
distributor run --config <path> [--dry-run] [--force] [--format text|json]
|
||||||
|
|
||||||
Options:
|
Options:
|
||||||
--config <path> Path to config file
|
--config <path> Path to config file
|
||||||
--dry-run Load and validate config without publishing
|
--dry-run Load and validate config without publishing
|
||||||
--force Allow explicit destructive replacement for supported conflicts
|
--force Allow explicit destructive replacement for supported conflicts
|
||||||
|
--format text|json
|
||||||
|
Output format
|
||||||
|
|
||||||
Run discovers configured source bundles, plans each destination, publishes
|
Run discovers configured source bundles, plans each destination, publishes
|
||||||
selected outputs unless --dry-run is set, and prints a final status summary.
|
selected outputs unless --dry-run is set, and prints a final status summary.
|
||||||
|
|||||||
46
internal/cli/serve.go
Normal file
46
internal/cli/serve.go
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/app"
|
||||||
|
)
|
||||||
|
|
||||||
|
var serveApp = app.Serve
|
||||||
|
|
||||||
|
func serveCommand(ctx context.Context, args []string, stdout, stderr io.Writer) int {
|
||||||
|
if hasHelp(args) {
|
||||||
|
printServeHelp(stdout)
|
||||||
|
return exitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
flags := flag.NewFlagSet("serve", flag.ContinueOnError)
|
||||||
|
flags.SetOutput(stderr)
|
||||||
|
configPath := flags.String("config", "", "path to config file")
|
||||||
|
if err := flags.Parse(args); err != nil {
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
if rejectPositionalArgs(stderr, "serve", flags.Args()) {
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := serveApp(ctx, app.ServeOptions{ConfigPath: *configPath}); err != nil {
|
||||||
|
return fail(stderr, err)
|
||||||
|
}
|
||||||
|
return exitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
func printServeHelp(w io.Writer) {
|
||||||
|
fmt.Fprint(w, `Usage:
|
||||||
|
distributor serve --config <path>
|
||||||
|
|
||||||
|
Options:
|
||||||
|
--config <path> Path to config file
|
||||||
|
|
||||||
|
Serve loads configured HTTP upload sources, resolves upload tokens through the
|
||||||
|
configured secret environment, and starts the HTTP upload API.
|
||||||
|
`)
|
||||||
|
}
|
||||||
67
internal/cli/source_mode.go
Normal file
67
internal/cli/source_mode.go
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/app"
|
||||||
|
)
|
||||||
|
|
||||||
|
type sourceDiagnosticArgs struct {
|
||||||
|
Path string
|
||||||
|
ConfigPath string
|
||||||
|
PipelineID string
|
||||||
|
BundlePath string
|
||||||
|
OutputFormat app.OutputFormat
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseSourceDiagnosticArgs(stderr io.Writer, command string, args []string) (sourceDiagnosticArgs, bool) {
|
||||||
|
flags := flag.NewFlagSet(command, flag.ContinueOnError)
|
||||||
|
flags.SetOutput(stderr)
|
||||||
|
configPath := flags.String("config", "", "path to config file")
|
||||||
|
pipelineID := flags.String("pipeline", "", "pipeline id")
|
||||||
|
bundlePath := flags.String("bundle", "", "source-root-relative bundle path")
|
||||||
|
formatFlag := addFormatFlag(flags)
|
||||||
|
if err := flags.Parse(args); err != nil {
|
||||||
|
return sourceDiagnosticArgs{}, false
|
||||||
|
}
|
||||||
|
format, ok := parseOutputFormat(stderr, command, *formatFlag)
|
||||||
|
if !ok {
|
||||||
|
return sourceDiagnosticArgs{}, false
|
||||||
|
}
|
||||||
|
path, ok := parseOptionalPathArg(stderr, command, flags.Args())
|
||||||
|
if !ok {
|
||||||
|
return sourceDiagnosticArgs{}, false
|
||||||
|
}
|
||||||
|
if !validateInspectModeOK(stderr, command, path, *configPath, *pipelineID, *bundlePath) {
|
||||||
|
return sourceDiagnosticArgs{}, false
|
||||||
|
}
|
||||||
|
return sourceDiagnosticArgs{
|
||||||
|
Path: path,
|
||||||
|
ConfigPath: *configPath,
|
||||||
|
PipelineID: *pipelineID,
|
||||||
|
BundlePath: *bundlePath,
|
||||||
|
OutputFormat: format,
|
||||||
|
}, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateInspectModeOK(stderr io.Writer, command, path, configPath, pipelineID, bundlePath string) bool {
|
||||||
|
configMode := configPath != "" || pipelineID != "" || bundlePath != ""
|
||||||
|
if !configMode {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if path != "" {
|
||||||
|
fmt.Fprintf(stderr, "distributor: %s does not accept a local path with --config, --pipeline, or --bundle\n", command)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if configPath == "" {
|
||||||
|
fmt.Fprintf(stderr, "distributor: %s requires --config when --pipeline or --bundle is set\n", command)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if pipelineID == "" {
|
||||||
|
fmt.Fprintf(stderr, "distributor: %s requires --pipeline in config mode\n", command)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
@@ -13,11 +13,18 @@ func validateCommand(ctx context.Context, args []string, stdout, stderr io.Write
|
|||||||
printValidateHelp(stdout)
|
printValidateHelp(stdout)
|
||||||
return exitOK
|
return exitOK
|
||||||
}
|
}
|
||||||
path, ok := parseOptionalPathArg(stderr, "validate", args)
|
parsed, ok := parseSourceDiagnosticArgs(stderr, "validate", args)
|
||||||
if !ok {
|
if !ok {
|
||||||
return exitUsage
|
return exitUsage
|
||||||
}
|
}
|
||||||
if err := app.Validate(ctx, app.ValidateOptions{Path: path, Stdout: stdout}); err != nil {
|
if err := app.Validate(ctx, app.ValidateOptions{
|
||||||
|
Path: parsed.Path,
|
||||||
|
ConfigPath: parsed.ConfigPath,
|
||||||
|
PipelineID: parsed.PipelineID,
|
||||||
|
BundlePath: parsed.BundlePath,
|
||||||
|
Stdout: stdout,
|
||||||
|
OutputFormat: parsed.OutputFormat,
|
||||||
|
}); err != nil {
|
||||||
return fail(stderr, err)
|
return fail(stderr, err)
|
||||||
}
|
}
|
||||||
return exitOK
|
return exitOK
|
||||||
@@ -25,8 +32,16 @@ func validateCommand(ctx context.Context, args []string, stdout, stderr io.Write
|
|||||||
|
|
||||||
func printValidateHelp(w io.Writer) {
|
func printValidateHelp(w io.Writer) {
|
||||||
fmt.Fprint(w, `Usage:
|
fmt.Fprint(w, `Usage:
|
||||||
distributor validate <path>
|
distributor validate [--format text|json] <path>
|
||||||
|
distributor validate --config <path> --pipeline <id> [--bundle <path>] [--format text|json]
|
||||||
|
|
||||||
Validate a local source bundle directory or a tree containing source bundles.
|
Options:
|
||||||
|
--config <path> Path to config file for configured source validation
|
||||||
|
--pipeline <id> Pipeline id to validate in config mode
|
||||||
|
--bundle <path> Source-root-relative bundle path to validate
|
||||||
|
--format text|json Output format
|
||||||
|
|
||||||
|
Validate a local source bundle directory, a local source bundle tree, or a
|
||||||
|
configured pipeline source.
|
||||||
`)
|
`)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package cli
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
|
||||||
@@ -13,16 +14,44 @@ func versionCommand(_ context.Context, args []string, stdout, stderr io.Writer)
|
|||||||
printVersionHelp(stdout)
|
printVersionHelp(stdout)
|
||||||
return exitOK
|
return exitOK
|
||||||
}
|
}
|
||||||
if rejectExtraArgs(stderr, "version", args) {
|
flags := flag.NewFlagSet("version", flag.ContinueOnError)
|
||||||
|
flags.SetOutput(stderr)
|
||||||
|
formatFlag := addFormatFlag(flags)
|
||||||
|
if err := flags.Parse(args); err != nil {
|
||||||
return exitUsage
|
return exitUsage
|
||||||
}
|
}
|
||||||
|
if rejectExtraArgs(stderr, "version", flags.Args()) {
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
format, ok := parseOutputFormat(stderr, "version", *formatFlag)
|
||||||
|
if !ok {
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
if app.IsJSONOutput(format) {
|
||||||
|
err := app.WriteJSONEnvelope(stdout, "version", true, nil, versionResult{
|
||||||
|
Application: app.Name,
|
||||||
|
Version: app.Version,
|
||||||
|
}, nil)
|
||||||
|
if err != nil {
|
||||||
|
return fail(stderr, err)
|
||||||
|
}
|
||||||
|
return exitOK
|
||||||
|
}
|
||||||
fmt.Fprintln(stdout, app.VersionString())
|
fmt.Fprintln(stdout, app.VersionString())
|
||||||
return exitOK
|
return exitOK
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type versionResult struct {
|
||||||
|
Application string `json:"application"`
|
||||||
|
Version string `json:"version"`
|
||||||
|
}
|
||||||
|
|
||||||
func printVersionHelp(w io.Writer) {
|
func printVersionHelp(w io.Writer) {
|
||||||
fmt.Fprint(w, `Usage:
|
fmt.Fprint(w, `Usage:
|
||||||
distributor version
|
distributor version [--format text|json]
|
||||||
|
|
||||||
|
Options:
|
||||||
|
--format text|json Output format
|
||||||
|
|
||||||
Print version information.
|
Print version information.
|
||||||
`)
|
`)
|
||||||
|
|||||||
@@ -1,10 +1,24 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
|
Server Server `yaml:"server"`
|
||||||
Secrets Secrets `yaml:"secrets"`
|
Secrets Secrets `yaml:"secrets"`
|
||||||
Pipelines []Pipeline `yaml:"pipelines"`
|
Pipelines []Pipeline `yaml:"pipelines"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type Server struct {
|
||||||
|
HTTP HTTPServer `yaml:"http"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type HTTPServer struct {
|
||||||
|
Bind string `yaml:"bind"`
|
||||||
|
StagingRoot string `yaml:"staging_root"`
|
||||||
|
MaxUploadSize *ByteSize `yaml:"max_upload_size"`
|
||||||
|
QueueSize int `yaml:"queue_size"`
|
||||||
|
MaxConcurrency int `yaml:"max_concurrency"`
|
||||||
|
Retention *Duration `yaml:"retention"`
|
||||||
|
}
|
||||||
|
|
||||||
type Secrets struct {
|
type Secrets struct {
|
||||||
Directory string `yaml:"directory"`
|
Directory string `yaml:"directory"`
|
||||||
}
|
}
|
||||||
@@ -32,6 +46,8 @@ type Destination struct {
|
|||||||
SSH SSH `yaml:",inline"`
|
SSH SSH `yaml:",inline"`
|
||||||
Publish *PublishPolicy `yaml:"publish"`
|
Publish *PublishPolicy `yaml:"publish"`
|
||||||
Transform Transform `yaml:"transform"`
|
Transform Transform `yaml:"transform"`
|
||||||
|
PathMap PathMapping `yaml:"path_mapping"`
|
||||||
|
Links *Links `yaml:"links"`
|
||||||
Transfer TransferPolicy `yaml:"transfer"`
|
Transfer TransferPolicy `yaml:"transfer"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,6 +64,13 @@ type Backend struct {
|
|||||||
ForcePath *bool `yaml:"force_path_style"`
|
ForcePath *bool `yaml:"force_path_style"`
|
||||||
Creds Credentials `yaml:"credentials"`
|
Creds Credentials `yaml:"credentials"`
|
||||||
SSH SSH `yaml:",inline"`
|
SSH SSH `yaml:",inline"`
|
||||||
|
Upload HTTPUpload `yaml:",inline"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type HTTPUpload struct {
|
||||||
|
TokenEnv string `yaml:"token_env"`
|
||||||
|
StagingPath string `yaml:"staging_path"`
|
||||||
|
MaxUploadSize *ByteSize `yaml:"max_upload_size"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type SSH struct {
|
type SSH struct {
|
||||||
@@ -77,6 +100,16 @@ type Transform struct {
|
|||||||
type MarkdownToHTML struct {
|
type MarkdownToHTML struct {
|
||||||
Enabled bool `yaml:"enabled"`
|
Enabled bool `yaml:"enabled"`
|
||||||
Mode string `yaml:"mode"`
|
Mode string `yaml:"mode"`
|
||||||
|
Input string `yaml:"input"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PathMapping struct {
|
||||||
|
Mode string `yaml:"mode"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Links struct {
|
||||||
|
BaseURL string `yaml:"base_url"`
|
||||||
|
Primary string `yaml:"primary"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type TransferPolicy struct {
|
type TransferPolicy struct {
|
||||||
|
|||||||
@@ -1,11 +1,19 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"path/filepath"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/transform"
|
||||||
|
)
|
||||||
|
|
||||||
const DefaultConfigPath = "/usr/local/etc/distributor/config.yml"
|
const DefaultConfigPath = "/usr/local/etc/distributor/config.yml"
|
||||||
|
|
||||||
const (
|
const (
|
||||||
BackendLocal = "local"
|
BackendLocal = "local"
|
||||||
BackendSSH = "ssh"
|
BackendSSH = "ssh"
|
||||||
BackendS3 = "s3"
|
BackendS3 = "s3"
|
||||||
|
BackendHTTPUpload = "http_upload"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -19,15 +27,40 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
TransformModeSidecar = "sidecar"
|
TransformModeSidecar = transform.MarkdownModeSidecar
|
||||||
|
TransformModeIndex = transform.MarkdownModeIndex
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
PathMappingPreserveRelative = "preserve_relative"
|
||||||
|
PathMappingFixed = "fixed"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
LinkPrimaryAuto = "auto"
|
||||||
|
LinkPrimaryHTML = "html"
|
||||||
|
LinkPrimarySource = "source"
|
||||||
)
|
)
|
||||||
|
|
||||||
const DefaultS3Region = "us-east-1"
|
const DefaultS3Region = "us-east-1"
|
||||||
|
|
||||||
|
const (
|
||||||
|
DefaultHTTPBind = "127.0.0.1:8080"
|
||||||
|
DefaultHTTPStagingRoot = "/var/spool/distributor"
|
||||||
|
DefaultHTTPMaxUploadSize = ByteSize(20 * 1024 * 1024)
|
||||||
|
DefaultHTTPQueueSize = 16
|
||||||
|
DefaultHTTPMaxConcurrency = 1
|
||||||
|
DefaultHTTPRetention = Duration(24 * time.Hour)
|
||||||
|
)
|
||||||
|
|
||||||
func ApplyDefaults(cfg *Config) {
|
func ApplyDefaults(cfg *Config) {
|
||||||
|
applyHTTPServerDefaults(&cfg.Server.HTTP)
|
||||||
for pipelineIndex := range cfg.Pipelines {
|
for pipelineIndex := range cfg.Pipelines {
|
||||||
pipeline := &cfg.Pipelines[pipelineIndex]
|
pipeline := &cfg.Pipelines[pipelineIndex]
|
||||||
applyBackendDefaults(&pipeline.Source)
|
applyBackendDefaults(&pipeline.Source)
|
||||||
|
if pipeline.Source.Backend == BackendHTTPUpload {
|
||||||
|
applyHTTPUploadDefaults(&pipeline.Source.Upload, pipeline.ID, cfg.Server.HTTP)
|
||||||
|
}
|
||||||
if pipeline.Validation.OnDigestMismatch == "" {
|
if pipeline.Validation.OnDigestMismatch == "" {
|
||||||
pipeline.Validation.OnDigestMismatch = ValidationActionFail
|
pipeline.Validation.OnDigestMismatch = ValidationActionFail
|
||||||
}
|
}
|
||||||
@@ -37,6 +70,15 @@ func ApplyDefaults(cfg *Config) {
|
|||||||
if destination.Publish == nil {
|
if destination.Publish == nil {
|
||||||
destination.Publish = &PublishPolicy{Source: true}
|
destination.Publish = &PublishPolicy{Source: true}
|
||||||
}
|
}
|
||||||
|
if destination.Transform.MarkdownToHTML != nil && destination.Transform.MarkdownToHTML.Mode == "" {
|
||||||
|
destination.Transform.MarkdownToHTML.Mode = TransformModeSidecar
|
||||||
|
}
|
||||||
|
if destination.PathMap.Mode == "" {
|
||||||
|
destination.PathMap.Mode = PathMappingPreserveRelative
|
||||||
|
}
|
||||||
|
if destination.Links != nil && destination.Links.Primary == "" {
|
||||||
|
destination.Links.Primary = LinkPrimaryAuto
|
||||||
|
}
|
||||||
if destination.Transfer.OnDestinationSame == "" {
|
if destination.Transfer.OnDestinationSame == "" {
|
||||||
destination.Transfer.OnDestinationSame = TransferActionSkip
|
destination.Transfer.OnDestinationSame = TransferActionSkip
|
||||||
}
|
}
|
||||||
@@ -53,6 +95,44 @@ func ApplyDefaults(cfg *Config) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func applyHTTPServerDefaults(server *HTTPServer) {
|
||||||
|
if server.Bind == "" {
|
||||||
|
server.Bind = DefaultHTTPBind
|
||||||
|
}
|
||||||
|
if server.StagingRoot == "" {
|
||||||
|
server.StagingRoot = DefaultHTTPStagingRoot
|
||||||
|
}
|
||||||
|
if server.MaxUploadSize == nil {
|
||||||
|
server.MaxUploadSize = byteSize(DefaultHTTPMaxUploadSize)
|
||||||
|
}
|
||||||
|
if server.QueueSize == 0 {
|
||||||
|
server.QueueSize = DefaultHTTPQueueSize
|
||||||
|
}
|
||||||
|
if server.MaxConcurrency == 0 {
|
||||||
|
server.MaxConcurrency = DefaultHTTPMaxConcurrency
|
||||||
|
}
|
||||||
|
if server.Retention == nil {
|
||||||
|
server.Retention = duration(DefaultHTTPRetention)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func applyHTTPUploadDefaults(upload *HTTPUpload, pipelineID string, server HTTPServer) {
|
||||||
|
if upload.StagingPath == "" && pipelineID != "" {
|
||||||
|
upload.StagingPath = filepath.Join(server.StagingRoot, pipelineID)
|
||||||
|
}
|
||||||
|
if upload.MaxUploadSize == nil && server.MaxUploadSize != nil {
|
||||||
|
upload.MaxUploadSize = byteSize(*server.MaxUploadSize)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func byteSize(value ByteSize) *ByteSize {
|
||||||
|
return &value
|
||||||
|
}
|
||||||
|
|
||||||
|
func duration(value Duration) *Duration {
|
||||||
|
return &value
|
||||||
|
}
|
||||||
|
|
||||||
func applyBackendDefaults(backend *Backend) {
|
func applyBackendDefaults(backend *Backend) {
|
||||||
if backend.Backend == BackendSSH {
|
if backend.Backend == BackendSSH {
|
||||||
if backend.Port == 0 {
|
if backend.Port == 0 {
|
||||||
|
|||||||
@@ -94,6 +94,237 @@ pipelines:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestLoadFileValidMarkdownIndexConfig(t *testing.T) {
|
||||||
|
cfg := loadConfig(t, `
|
||||||
|
pipelines:
|
||||||
|
- id: static-site
|
||||||
|
source:
|
||||||
|
backend: local
|
||||||
|
path: /var/spool/reports
|
||||||
|
destinations:
|
||||||
|
- id: web
|
||||||
|
backend: local
|
||||||
|
path: /srv/www/reports
|
||||||
|
publish:
|
||||||
|
source: false
|
||||||
|
html: true
|
||||||
|
transform:
|
||||||
|
markdown_to_html:
|
||||||
|
enabled: true
|
||||||
|
mode: index
|
||||||
|
input: report.md
|
||||||
|
`)
|
||||||
|
|
||||||
|
markdown := cfg.Pipelines[0].Destinations[0].Transform.MarkdownToHTML
|
||||||
|
if markdown == nil || markdown.Mode != TransformModeIndex || markdown.Input != "report.md" {
|
||||||
|
t.Fatalf("markdown config = %#v, want index input", markdown)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadFileDefaultsMarkdownModeToSidecar(t *testing.T) {
|
||||||
|
cfg := loadConfig(t, `
|
||||||
|
pipelines:
|
||||||
|
- id: static-site
|
||||||
|
source:
|
||||||
|
backend: local
|
||||||
|
path: /var/spool/reports
|
||||||
|
destinations:
|
||||||
|
- id: web
|
||||||
|
backend: local
|
||||||
|
path: /srv/www/reports
|
||||||
|
publish:
|
||||||
|
source: false
|
||||||
|
html: true
|
||||||
|
transform:
|
||||||
|
markdown_to_html:
|
||||||
|
enabled: true
|
||||||
|
`)
|
||||||
|
|
||||||
|
markdown := cfg.Pipelines[0].Destinations[0].Transform.MarkdownToHTML
|
||||||
|
if markdown == nil || markdown.Mode != TransformModeSidecar {
|
||||||
|
t.Fatalf("markdown mode = %#v, want sidecar default", markdown)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadFileDefaultsPathMappingToPreserveRelative(t *testing.T) {
|
||||||
|
cfg := loadConfig(t, `
|
||||||
|
pipelines:
|
||||||
|
- id: reports
|
||||||
|
source:
|
||||||
|
backend: local
|
||||||
|
path: /source
|
||||||
|
destinations:
|
||||||
|
- id: archive
|
||||||
|
backend: local
|
||||||
|
path: /destination
|
||||||
|
`)
|
||||||
|
|
||||||
|
if got, want := cfg.Pipelines[0].Destinations[0].PathMap.Mode, PathMappingPreserveRelative; got != want {
|
||||||
|
t.Fatalf("path mapping mode = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadFileAcceptsFixedPathMapping(t *testing.T) {
|
||||||
|
cfg := loadConfig(t, `
|
||||||
|
pipelines:
|
||||||
|
- id: reports
|
||||||
|
source:
|
||||||
|
backend: local
|
||||||
|
path: /source
|
||||||
|
destinations:
|
||||||
|
- id: latest
|
||||||
|
backend: local
|
||||||
|
path: /destination/latest
|
||||||
|
path_mapping:
|
||||||
|
mode: fixed
|
||||||
|
`)
|
||||||
|
|
||||||
|
if got, want := cfg.Pipelines[0].Destinations[0].PathMap.Mode, PathMappingFixed; got != want {
|
||||||
|
t.Fatalf("path mapping mode = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadFileDefaultsLinksPrimaryToAuto(t *testing.T) {
|
||||||
|
cfg := loadConfig(t, `
|
||||||
|
pipelines:
|
||||||
|
- id: reports
|
||||||
|
source:
|
||||||
|
backend: local
|
||||||
|
path: /source
|
||||||
|
destinations:
|
||||||
|
- id: web
|
||||||
|
backend: local
|
||||||
|
path: /destination
|
||||||
|
links:
|
||||||
|
base_url: https://reports.example.com/archive
|
||||||
|
`)
|
||||||
|
|
||||||
|
links := cfg.Pipelines[0].Destinations[0].Links
|
||||||
|
if links == nil {
|
||||||
|
t.Fatal("links = nil, want config")
|
||||||
|
}
|
||||||
|
if links.BaseURL != "https://reports.example.com/archive" || links.Primary != LinkPrimaryAuto {
|
||||||
|
t.Fatalf("links = %#v, want base URL with auto primary", links)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadFileDefaultsHTTPServerConfig(t *testing.T) {
|
||||||
|
cfg := loadConfig(t, `
|
||||||
|
pipelines:
|
||||||
|
- id: reports
|
||||||
|
source:
|
||||||
|
backend: local
|
||||||
|
path: /source
|
||||||
|
destinations:
|
||||||
|
- id: archive
|
||||||
|
backend: local
|
||||||
|
path: /archive
|
||||||
|
`)
|
||||||
|
|
||||||
|
server := cfg.Server.HTTP
|
||||||
|
if got, want := server.Bind, DefaultHTTPBind; got != want {
|
||||||
|
t.Fatalf("server.http.bind = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
if got, want := server.StagingRoot, DefaultHTTPStagingRoot; got != want {
|
||||||
|
t.Fatalf("server.http.staging_root = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
if got, want := *server.MaxUploadSize, DefaultHTTPMaxUploadSize; got != want {
|
||||||
|
t.Fatalf("server.http.max_upload_size = %s, want %s", got, want)
|
||||||
|
}
|
||||||
|
if got, want := server.QueueSize, DefaultHTTPQueueSize; got != want {
|
||||||
|
t.Fatalf("server.http.queue_size = %d, want %d", got, want)
|
||||||
|
}
|
||||||
|
if got, want := server.MaxConcurrency, DefaultHTTPMaxConcurrency; got != want {
|
||||||
|
t.Fatalf("server.http.max_concurrency = %d, want %d", got, want)
|
||||||
|
}
|
||||||
|
if got, want := *server.Retention, DefaultHTTPRetention; got != want {
|
||||||
|
t.Fatalf("server.http.retention = %s, want %s", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadFileAcceptsHTTPUploadSourceConfig(t *testing.T) {
|
||||||
|
cfg := loadConfig(t, `
|
||||||
|
server:
|
||||||
|
http:
|
||||||
|
bind: 127.0.0.1:9090
|
||||||
|
staging_root: /srv/distributor/staging
|
||||||
|
max_upload_size: 64MB
|
||||||
|
queue_size: 32
|
||||||
|
max_concurrency: 2
|
||||||
|
retention: 48h
|
||||||
|
pipelines:
|
||||||
|
- id: weather-daily
|
||||||
|
source:
|
||||||
|
backend: http_upload
|
||||||
|
token_env: WEATHER_DAILY_UPLOAD_TOKEN
|
||||||
|
staging_path: /srv/distributor/staging/weather-daily
|
||||||
|
max_upload_size: 32MB
|
||||||
|
destinations:
|
||||||
|
- id: archive
|
||||||
|
backend: local
|
||||||
|
path: /archive
|
||||||
|
`)
|
||||||
|
|
||||||
|
server := cfg.Server.HTTP
|
||||||
|
if got, want := server.Bind, "127.0.0.1:9090"; got != want {
|
||||||
|
t.Fatalf("server.http.bind = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
if got, want := server.StagingRoot, "/srv/distributor/staging"; got != want {
|
||||||
|
t.Fatalf("server.http.staging_root = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
if got, want := *server.MaxUploadSize, ByteSize(64*1024*1024); got != want {
|
||||||
|
t.Fatalf("server.http.max_upload_size = %s, want %s", got, want)
|
||||||
|
}
|
||||||
|
if got, want := server.QueueSize, 32; got != want {
|
||||||
|
t.Fatalf("server.http.queue_size = %d, want %d", got, want)
|
||||||
|
}
|
||||||
|
if got, want := server.MaxConcurrency, 2; got != want {
|
||||||
|
t.Fatalf("server.http.max_concurrency = %d, want %d", got, want)
|
||||||
|
}
|
||||||
|
if got, want := server.Retention.String(), "48h0m0s"; got != want {
|
||||||
|
t.Fatalf("server.http.retention = %s, want %s", got, want)
|
||||||
|
}
|
||||||
|
|
||||||
|
source := cfg.Pipelines[0].Source
|
||||||
|
if got, want := source.Backend, BackendHTTPUpload; got != want {
|
||||||
|
t.Fatalf("source.backend = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
if got, want := source.Upload.TokenEnv, "WEATHER_DAILY_UPLOAD_TOKEN"; got != want {
|
||||||
|
t.Fatalf("source.token_env = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
if got, want := source.Upload.StagingPath, "/srv/distributor/staging/weather-daily"; got != want {
|
||||||
|
t.Fatalf("source.staging_path = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
if got, want := *source.Upload.MaxUploadSize, ByteSize(32*1024*1024); got != want {
|
||||||
|
t.Fatalf("source.max_upload_size = %s, want %s", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadFileDefaultsHTTPUploadSourceConfig(t *testing.T) {
|
||||||
|
cfg := loadConfig(t, `
|
||||||
|
server:
|
||||||
|
http:
|
||||||
|
max_upload_size: 12MB
|
||||||
|
pipelines:
|
||||||
|
- id: weather-daily
|
||||||
|
source:
|
||||||
|
backend: http_upload
|
||||||
|
token_env: WEATHER_DAILY_UPLOAD_TOKEN
|
||||||
|
destinations:
|
||||||
|
- id: archive
|
||||||
|
backend: local
|
||||||
|
path: /archive
|
||||||
|
`)
|
||||||
|
|
||||||
|
source := cfg.Pipelines[0].Source
|
||||||
|
if got, want := source.Upload.StagingPath, "/var/spool/distributor/weather-daily"; got != want {
|
||||||
|
t.Fatalf("source.staging_path = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
if got, want := *source.Upload.MaxUploadSize, ByteSize(12*1024*1024); got != want {
|
||||||
|
t.Fatalf("source.max_upload_size = %s, want %s", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestLoadFileValidBackendConfigs(t *testing.T) {
|
func TestLoadFileValidBackendConfigs(t *testing.T) {
|
||||||
tests := map[string]string{
|
tests := map[string]string{
|
||||||
"local": `
|
"local": `
|
||||||
@@ -282,6 +513,26 @@ func TestLoadFileRejectsInvalidS3Config(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestLoadFileRejectsInvalidHTTPUploadConfig(t *testing.T) {
|
||||||
|
tests := map[string]string{
|
||||||
|
"server size": `server: {http: {max_upload_size: 20XB}}`,
|
||||||
|
"source size": `pipelines: [{id: reports, source: {backend: http_upload, token_env: UPLOAD_TOKEN, max_upload_size: 20XB}, destinations: [{id: archive, backend: local, path: /archive}]}]`,
|
||||||
|
"zero source size": `pipelines: [{id: reports, source: {backend: http_upload, token_env: UPLOAD_TOKEN, max_upload_size: 0B}, destinations: [{id: archive, backend: local, path: /archive}]}]`,
|
||||||
|
"server duration": `server: {http: {retention: forever}}`,
|
||||||
|
"zero server duration": `server: {http: {retention: 0s}}`,
|
||||||
|
"missing token env": `pipelines: [{id: reports, source: {backend: http_upload}, destinations: [{id: archive, backend: local, path: /archive}]}]`,
|
||||||
|
"destination http upload": `pipelines: [{id: reports, source: {backend: local, path: /source}, destinations: [{id: ingest, backend: http_upload}]}]`,
|
||||||
|
"literal token": `pipelines: [{id: reports, source: {backend: http_upload, token: secret, token_env: UPLOAD_TOKEN}, destinations: [{id: archive, backend: local, path: /archive}]}]`,
|
||||||
|
"unknown server field": `server: {http: {surprise: true}}`,
|
||||||
|
"unknown source field": `pipelines: [{id: reports, source: {backend: http_upload, token_env: UPLOAD_TOKEN, surprise: true}, destinations: [{id: archive, backend: local, path: /archive}]}]`,
|
||||||
|
}
|
||||||
|
for name, body := range tests {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
assertLoadError(t, body, "")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestLoadFileDefaultsSSHConfig(t *testing.T) {
|
func TestLoadFileDefaultsSSHConfig(t *testing.T) {
|
||||||
cfg := loadConfig(t, `
|
cfg := loadConfig(t, `
|
||||||
pipelines:
|
pipelines:
|
||||||
@@ -464,7 +715,10 @@ func TestExampleConfigsLoad(t *testing.T) {
|
|||||||
"../../examples/local-to-local.yml",
|
"../../examples/local-to-local.yml",
|
||||||
"../../examples/local-publish.yml",
|
"../../examples/local-publish.yml",
|
||||||
"../../examples/local-html.yml",
|
"../../examples/local-html.yml",
|
||||||
|
"../../examples/local-index.yml",
|
||||||
"../../examples/fan-out.yml",
|
"../../examples/fan-out.yml",
|
||||||
|
"../../examples/archive-and-latest.yml",
|
||||||
|
"../../examples/http-upload-local.yml",
|
||||||
"../../examples/ssh-destination.yml",
|
"../../examples/ssh-destination.yml",
|
||||||
"../../examples/s3-destination.yml",
|
"../../examples/s3-destination.yml",
|
||||||
} {
|
} {
|
||||||
|
|||||||
117
internal/config/quantity.go
Normal file
117
internal/config/quantity.go
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ByteSize int64
|
||||||
|
|
||||||
|
type Duration time.Duration
|
||||||
|
|
||||||
|
func (size *ByteSize) UnmarshalYAML(value *yaml.Node) error {
|
||||||
|
if value.Kind != yaml.ScalarNode || value.Tag != "!!str" {
|
||||||
|
return fmt.Errorf("size must be a string with B, KB, MB, or GB suffix")
|
||||||
|
}
|
||||||
|
|
||||||
|
var raw string
|
||||||
|
if err := value.Decode(&raw); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
parsed, err := ParseByteSize(raw)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
*size = parsed
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (size ByteSize) String() string {
|
||||||
|
value := int64(size)
|
||||||
|
if value == 0 {
|
||||||
|
return "0B"
|
||||||
|
}
|
||||||
|
units := []struct {
|
||||||
|
suffix string
|
||||||
|
multiplier int64
|
||||||
|
}{
|
||||||
|
{suffix: "GB", multiplier: 1024 * 1024 * 1024},
|
||||||
|
{suffix: "MB", multiplier: 1024 * 1024},
|
||||||
|
{suffix: "KB", multiplier: 1024},
|
||||||
|
{suffix: "B", multiplier: 1},
|
||||||
|
}
|
||||||
|
for _, unit := range units {
|
||||||
|
if value%unit.multiplier == 0 {
|
||||||
|
return strconv.FormatInt(value/unit.multiplier, 10) + unit.suffix
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strconv.FormatInt(value, 10) + "B"
|
||||||
|
}
|
||||||
|
|
||||||
|
func ParseByteSize(raw string) (ByteSize, error) {
|
||||||
|
value := strings.TrimSpace(raw)
|
||||||
|
if value == "" {
|
||||||
|
return 0, fmt.Errorf("size is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
units := []struct {
|
||||||
|
suffix string
|
||||||
|
multiplier int64
|
||||||
|
}{
|
||||||
|
{suffix: "GB", multiplier: 1024 * 1024 * 1024},
|
||||||
|
{suffix: "MB", multiplier: 1024 * 1024},
|
||||||
|
{suffix: "KB", multiplier: 1024},
|
||||||
|
{suffix: "B", multiplier: 1},
|
||||||
|
}
|
||||||
|
for _, unit := range units {
|
||||||
|
number, ok := strings.CutSuffix(value, unit.suffix)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(number) != number || number == "" {
|
||||||
|
return 0, fmt.Errorf("size must be an integer followed by B, KB, MB, or GB")
|
||||||
|
}
|
||||||
|
parsed, err := strconv.ParseInt(number, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("size must be an integer followed by B, KB, MB, or GB")
|
||||||
|
}
|
||||||
|
if parsed < 0 {
|
||||||
|
return 0, fmt.Errorf("size must be non-negative")
|
||||||
|
}
|
||||||
|
const maxInt64 = int64(1<<63 - 1)
|
||||||
|
if parsed > 0 && parsed > maxInt64/unit.multiplier {
|
||||||
|
return 0, fmt.Errorf("size is too large")
|
||||||
|
}
|
||||||
|
return ByteSize(parsed * unit.multiplier), nil
|
||||||
|
}
|
||||||
|
return 0, fmt.Errorf("size must use B, KB, MB, or GB suffix")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (duration *Duration) UnmarshalYAML(value *yaml.Node) error {
|
||||||
|
if value.Kind != yaml.ScalarNode || value.Tag != "!!str" {
|
||||||
|
return fmt.Errorf("duration must be a string duration")
|
||||||
|
}
|
||||||
|
|
||||||
|
var raw string
|
||||||
|
if err := value.Decode(&raw); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
parsed, err := time.ParseDuration(raw)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("duration must be a valid duration: %w", err)
|
||||||
|
}
|
||||||
|
*duration = Duration(parsed)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (duration Duration) String() string {
|
||||||
|
return time.Duration(duration).String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (duration Duration) AsDuration() time.Duration {
|
||||||
|
return time.Duration(duration)
|
||||||
|
}
|
||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/link"
|
||||||
)
|
)
|
||||||
|
|
||||||
var idPattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]*$`)
|
var idPattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]*$`)
|
||||||
@@ -20,6 +22,8 @@ func (e ValidationErrors) Error() string {
|
|||||||
func Validate(cfg Config) error {
|
func Validate(cfg Config) error {
|
||||||
var errs ValidationErrors
|
var errs ValidationErrors
|
||||||
|
|
||||||
|
errs = validateHTTPServer(errs, "server.http", cfg.Server.HTTP)
|
||||||
|
|
||||||
if len(cfg.Pipelines) == 0 {
|
if len(cfg.Pipelines) == 0 {
|
||||||
errs = append(errs, "pipelines is required")
|
errs = append(errs, "pipelines is required")
|
||||||
}
|
}
|
||||||
@@ -58,6 +62,8 @@ func Validate(cfg Config) error {
|
|||||||
|
|
||||||
errs = validateDestinationBackend(errs, destinationContext, destination)
|
errs = validateDestinationBackend(errs, destinationContext, destination)
|
||||||
errs = validatePublishTransformPolicy(errs, destinationContext, destination.Publish, destination.Transform)
|
errs = validatePublishTransformPolicy(errs, destinationContext, destination.Publish, destination.Transform)
|
||||||
|
errs = validatePathMapping(errs, destinationContext+".path_mapping", destination.PathMap)
|
||||||
|
errs = validateLinks(errs, destinationContext+".links", destination.Links)
|
||||||
errs = validateTransferPolicy(errs, destinationContext+".transfer", destination.Transfer)
|
errs = validateTransferPolicy(errs, destinationContext+".transfer", destination.Transfer)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -68,14 +74,56 @@ func Validate(cfg Config) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func validateHTTPServer(errs ValidationErrors, context string, server HTTPServer) ValidationErrors {
|
||||||
|
if server.Bind == "" {
|
||||||
|
errs = append(errs, context+".bind is required")
|
||||||
|
}
|
||||||
|
if server.StagingRoot == "" {
|
||||||
|
errs = append(errs, context+".staging_root is required")
|
||||||
|
}
|
||||||
|
if server.MaxUploadSize == nil || *server.MaxUploadSize <= 0 {
|
||||||
|
errs = append(errs, context+".max_upload_size must be greater than zero")
|
||||||
|
}
|
||||||
|
if server.QueueSize <= 0 {
|
||||||
|
errs = append(errs, context+".queue_size must be greater than zero")
|
||||||
|
}
|
||||||
|
if server.MaxConcurrency <= 0 {
|
||||||
|
errs = append(errs, context+".max_concurrency must be greater than zero")
|
||||||
|
}
|
||||||
|
if server.Retention == nil || *server.Retention <= 0 {
|
||||||
|
errs = append(errs, context+".retention must be greater than zero")
|
||||||
|
}
|
||||||
|
return errs
|
||||||
|
}
|
||||||
|
|
||||||
func validateSourceBackend(errs ValidationErrors, context string, backend Backend) ValidationErrors {
|
func validateSourceBackend(errs ValidationErrors, context string, backend Backend) ValidationErrors {
|
||||||
|
if backend.Backend == BackendHTTPUpload {
|
||||||
|
return validateHTTPUploadSource(errs, context, backend.Upload)
|
||||||
|
}
|
||||||
return validateBackend(errs, context, backend.Backend, backend.Host, backend.Port, backend.Path, backend.Endpoint, backend.Bucket, backend.Prefix, backend.SSH.HostKeyPolicy, backend.Creds)
|
return validateBackend(errs, context, backend.Backend, backend.Host, backend.Port, backend.Path, backend.Endpoint, backend.Bucket, backend.Prefix, backend.SSH.HostKeyPolicy, backend.Creds)
|
||||||
}
|
}
|
||||||
|
|
||||||
func validateDestinationBackend(errs ValidationErrors, context string, destination Destination) ValidationErrors {
|
func validateDestinationBackend(errs ValidationErrors, context string, destination Destination) ValidationErrors {
|
||||||
|
if destination.Backend == BackendHTTPUpload {
|
||||||
|
errs = append(errs, context+".backend "+BackendHTTPUpload+" is only supported for sources")
|
||||||
|
return errs
|
||||||
|
}
|
||||||
return validateBackend(errs, context, destination.Backend, destination.Host, destination.Port, destination.Path, destination.Endpoint, destination.Bucket, destination.Prefix, destination.SSH.HostKeyPolicy, destination.Creds)
|
return validateBackend(errs, context, destination.Backend, destination.Host, destination.Port, destination.Path, destination.Endpoint, destination.Bucket, destination.Prefix, destination.SSH.HostKeyPolicy, destination.Creds)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func validateHTTPUploadSource(errs ValidationErrors, context string, upload HTTPUpload) ValidationErrors {
|
||||||
|
if upload.TokenEnv == "" {
|
||||||
|
errs = append(errs, context+".token_env is required for http_upload backend")
|
||||||
|
}
|
||||||
|
if upload.StagingPath == "" {
|
||||||
|
errs = append(errs, context+".staging_path is required for http_upload backend")
|
||||||
|
}
|
||||||
|
if upload.MaxUploadSize == nil || *upload.MaxUploadSize <= 0 {
|
||||||
|
errs = append(errs, context+".max_upload_size must be greater than zero")
|
||||||
|
}
|
||||||
|
return errs
|
||||||
|
}
|
||||||
|
|
||||||
func validateBackend(errs ValidationErrors, context, backend, host string, port int, path, endpoint, bucket, prefix string, hostKeyPolicy HostKeyPolicy, creds Credentials) ValidationErrors {
|
func validateBackend(errs ValidationErrors, context, backend, host string, port int, path, endpoint, bucket, prefix string, hostKeyPolicy HostKeyPolicy, creds Credentials) ValidationErrors {
|
||||||
switch backend {
|
switch backend {
|
||||||
case "":
|
case "":
|
||||||
@@ -149,21 +197,52 @@ func ValidatePublishTransformPolicy(publish PublishPolicy, transform Transform)
|
|||||||
if transform.MarkdownToHTML == nil {
|
if transform.MarkdownToHTML == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
mode := transform.MarkdownToHTML.Mode
|
||||||
|
if mode == "" {
|
||||||
|
mode = TransformModeSidecar
|
||||||
|
}
|
||||||
|
if mode != TransformModeSidecar && mode != TransformModeIndex {
|
||||||
|
return fmt.Errorf("transform.markdown_to_html.mode must be %s or %s", TransformModeSidecar, TransformModeIndex)
|
||||||
|
}
|
||||||
|
if transform.MarkdownToHTML.Input != "" && !transform.MarkdownToHTML.Enabled {
|
||||||
|
return fmt.Errorf("transform.markdown_to_html.input requires transform.markdown_to_html.enabled to be true")
|
||||||
|
}
|
||||||
|
if transform.MarkdownToHTML.Input != "" && mode != TransformModeIndex {
|
||||||
|
return fmt.Errorf("transform.markdown_to_html.input is only valid when mode is %s", TransformModeIndex)
|
||||||
|
}
|
||||||
|
if transform.MarkdownToHTML.Enabled && !publish.HTML {
|
||||||
|
return fmt.Errorf("transform.markdown_to_html.enabled requires publish.html to be true")
|
||||||
|
}
|
||||||
if publish.HTML && !transform.MarkdownToHTML.Enabled {
|
if publish.HTML && !transform.MarkdownToHTML.Enabled {
|
||||||
return fmt.Errorf("transform.markdown_to_html.enabled must be true when publish.html is true")
|
return fmt.Errorf("transform.markdown_to_html.enabled must be true when publish.html is true")
|
||||||
}
|
}
|
||||||
if publish.HTML && transform.MarkdownToHTML.Mode != TransformModeSidecar {
|
|
||||||
return fmt.Errorf("transform.markdown_to_html.mode must be %s", TransformModeSidecar)
|
|
||||||
}
|
|
||||||
if transform.MarkdownToHTML.Enabled && transform.MarkdownToHTML.Mode != TransformModeSidecar {
|
|
||||||
return fmt.Errorf("transform.markdown_to_html.mode must be %s", TransformModeSidecar)
|
|
||||||
}
|
|
||||||
if !transform.MarkdownToHTML.Enabled && transform.MarkdownToHTML.Mode != "" && transform.MarkdownToHTML.Mode != TransformModeSidecar {
|
|
||||||
return fmt.Errorf("transform.markdown_to_html.mode must be %s", TransformModeSidecar)
|
|
||||||
}
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func validatePathMapping(errs ValidationErrors, context string, mapping PathMapping) ValidationErrors {
|
||||||
|
if mapping.Mode != PathMappingPreserveRelative && mapping.Mode != PathMappingFixed {
|
||||||
|
errs = append(errs, context+".mode must be "+PathMappingPreserveRelative+" or "+PathMappingFixed)
|
||||||
|
}
|
||||||
|
return errs
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateLinks(errs ValidationErrors, context string, links *Links) ValidationErrors {
|
||||||
|
if links == nil {
|
||||||
|
return errs
|
||||||
|
}
|
||||||
|
if links.BaseURL == "" {
|
||||||
|
errs = append(errs, context+".base_url is required")
|
||||||
|
} else if err := link.ValidateHTTPURL(links.BaseURL); err != nil {
|
||||||
|
errs = append(errs, context+".base_url "+err.Error())
|
||||||
|
}
|
||||||
|
switch links.Primary {
|
||||||
|
case LinkPrimaryAuto, LinkPrimaryHTML, LinkPrimarySource:
|
||||||
|
default:
|
||||||
|
errs = append(errs, context+".primary must be "+LinkPrimaryAuto+", "+LinkPrimaryHTML+", or "+LinkPrimarySource)
|
||||||
|
}
|
||||||
|
return errs
|
||||||
|
}
|
||||||
|
|
||||||
func validateTransferPolicy(errs ValidationErrors, context string, policy TransferPolicy) ValidationErrors {
|
func validateTransferPolicy(errs ValidationErrors, context string, policy TransferPolicy) ValidationErrors {
|
||||||
if policy.OnDestinationSame != TransferActionSkip && policy.OnDestinationSame != TransferActionFail {
|
if policy.OnDestinationSame != TransferActionSkip && policy.OnDestinationSame != TransferActionFail {
|
||||||
errs = append(errs, context+".on_destination_same must be skip or fail")
|
errs = append(errs, context+".on_destination_same must be skip or fail")
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import "testing"
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
func TestValidatePublishTransformPolicy(t *testing.T) {
|
func TestValidatePublishTransformPolicy(t *testing.T) {
|
||||||
tests := publishTransformPolicyCases()
|
tests := publishTransformPolicyCases()
|
||||||
@@ -70,6 +73,103 @@ func TestValidateAcceptsForceReplacementTransferActions(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestValidatePathMapping(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
mode string
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{name: "preserve relative", mode: PathMappingPreserveRelative},
|
||||||
|
{name: "fixed", mode: PathMappingFixed},
|
||||||
|
{name: "invalid", mode: "archive", wantErr: true},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
cfg := Config{Pipelines: []Pipeline{{
|
||||||
|
ID: "reports",
|
||||||
|
Source: Backend{Backend: BackendLocal, Path: "/source"},
|
||||||
|
Destinations: []Destination{{
|
||||||
|
ID: "archive",
|
||||||
|
Backend: BackendLocal,
|
||||||
|
Path: "/destination",
|
||||||
|
PathMap: PathMapping{Mode: tt.mode},
|
||||||
|
}},
|
||||||
|
}}}
|
||||||
|
ApplyDefaults(&cfg)
|
||||||
|
err := Validate(cfg)
|
||||||
|
if tt.wantErr && err == nil {
|
||||||
|
t.Fatal("Validate() error = nil, want error")
|
||||||
|
}
|
||||||
|
if !tt.wantErr && err != nil {
|
||||||
|
t.Fatalf("Validate() error = %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateLinks(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
links *Links
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{name: "absent links"},
|
||||||
|
{name: "http", links: &Links{BaseURL: "http://reports.example.com/archive", Primary: LinkPrimaryAuto}},
|
||||||
|
{name: "https", links: &Links{BaseURL: "https://reports.example.com/archive/", Primary: LinkPrimaryHTML}},
|
||||||
|
{name: "source primary", links: &Links{BaseURL: "https://reports.example.com", Primary: LinkPrimarySource}},
|
||||||
|
{name: "missing base", links: &Links{Primary: LinkPrimaryAuto}, wantErr: true},
|
||||||
|
{name: "ftp scheme", links: &Links{BaseURL: "ftp://reports.example.com", Primary: LinkPrimaryAuto}, wantErr: true},
|
||||||
|
{name: "missing host", links: &Links{BaseURL: "https:///archive", Primary: LinkPrimaryAuto}, wantErr: true},
|
||||||
|
{name: "query", links: &Links{BaseURL: "https://reports.example.com/archive?preview=1", Primary: LinkPrimaryAuto}, wantErr: true},
|
||||||
|
{name: "fragment", links: &Links{BaseURL: "https://reports.example.com/archive#top", Primary: LinkPrimaryAuto}, wantErr: true},
|
||||||
|
{name: "invalid primary", links: &Links{BaseURL: "https://reports.example.com", Primary: "document"}, wantErr: true},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
cfg := Config{Pipelines: []Pipeline{{
|
||||||
|
ID: "reports",
|
||||||
|
Source: Backend{Backend: BackendLocal, Path: "/source"},
|
||||||
|
Destinations: []Destination{{
|
||||||
|
ID: "web",
|
||||||
|
Backend: BackendLocal,
|
||||||
|
Path: "/destination",
|
||||||
|
Links: tt.links,
|
||||||
|
}},
|
||||||
|
}}}
|
||||||
|
ApplyDefaults(&cfg)
|
||||||
|
err := Validate(cfg)
|
||||||
|
if tt.wantErr && err == nil {
|
||||||
|
t.Fatal("Validate() error = nil, want error")
|
||||||
|
}
|
||||||
|
if !tt.wantErr && err != nil {
|
||||||
|
t.Fatalf("Validate() error = %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateLinksReportsFieldContext(t *testing.T) {
|
||||||
|
cfg := Config{Pipelines: []Pipeline{{
|
||||||
|
ID: "reports",
|
||||||
|
Source: Backend{Backend: BackendLocal, Path: "/source"},
|
||||||
|
Destinations: []Destination{{
|
||||||
|
ID: "web",
|
||||||
|
Backend: BackendLocal,
|
||||||
|
Path: "/destination",
|
||||||
|
Links: &Links{BaseURL: "https://reports.example.com/archive?preview=1", Primary: LinkPrimaryAuto},
|
||||||
|
}},
|
||||||
|
}}}
|
||||||
|
ApplyDefaults(&cfg)
|
||||||
|
err := Validate(cfg)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("Validate() error = nil, want error")
|
||||||
|
}
|
||||||
|
want := "pipelines[0].destinations[0].links.base_url must not include a query string"
|
||||||
|
if !strings.Contains(err.Error(), want) {
|
||||||
|
t.Fatalf("Validate() error = %q, want %q", err, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
type publishTransformPolicyCase struct {
|
type publishTransformPolicyCase struct {
|
||||||
name string
|
name string
|
||||||
publish PublishPolicy
|
publish PublishPolicy
|
||||||
@@ -91,6 +191,30 @@ func publishTransformPolicyCases() []publishTransformPolicyCase {
|
|||||||
Mode: TransformModeSidecar,
|
Mode: TransformModeSidecar,
|
||||||
}},
|
}},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "html only default mode allowed",
|
||||||
|
publish: PublishPolicy{HTML: true},
|
||||||
|
transform: Transform{MarkdownToHTML: &MarkdownToHTML{
|
||||||
|
Enabled: true,
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "html only index allowed",
|
||||||
|
publish: PublishPolicy{HTML: true},
|
||||||
|
transform: Transform{MarkdownToHTML: &MarkdownToHTML{
|
||||||
|
Enabled: true,
|
||||||
|
Mode: TransformModeIndex,
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "html only index input allowed",
|
||||||
|
publish: PublishPolicy{HTML: true},
|
||||||
|
transform: Transform{MarkdownToHTML: &MarkdownToHTML{
|
||||||
|
Enabled: true,
|
||||||
|
Mode: TransformModeIndex,
|
||||||
|
Input: "report.md",
|
||||||
|
}},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "source and html sidecar allowed",
|
name: "source and html sidecar allowed",
|
||||||
publish: PublishPolicy{Source: true, HTML: true},
|
publish: PublishPolicy{Source: true, HTML: true},
|
||||||
@@ -127,6 +251,15 @@ func publishTransformPolicyCases() []publishTransformPolicyCase {
|
|||||||
}},
|
}},
|
||||||
wantErr: true,
|
wantErr: true,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "source only enabled transform rejected",
|
||||||
|
publish: PublishPolicy{Source: true},
|
||||||
|
transform: Transform{MarkdownToHTML: &MarkdownToHTML{
|
||||||
|
Enabled: true,
|
||||||
|
Mode: TransformModeSidecar,
|
||||||
|
}},
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "enabled markdown wrong mode rejected",
|
name: "enabled markdown wrong mode rejected",
|
||||||
publish: PublishPolicy{Source: true},
|
publish: PublishPolicy{Source: true},
|
||||||
@@ -136,6 +269,16 @@ func publishTransformPolicyCases() []publishTransformPolicyCase {
|
|||||||
}},
|
}},
|
||||||
wantErr: true,
|
wantErr: true,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "sidecar input rejected",
|
||||||
|
publish: PublishPolicy{HTML: true},
|
||||||
|
transform: Transform{MarkdownToHTML: &MarkdownToHTML{
|
||||||
|
Enabled: true,
|
||||||
|
Mode: TransformModeSidecar,
|
||||||
|
Input: "report.md",
|
||||||
|
}},
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "disabled markdown empty mode allowed",
|
name: "disabled markdown empty mode allowed",
|
||||||
publish: PublishPolicy{Source: true},
|
publish: PublishPolicy{Source: true},
|
||||||
@@ -151,6 +294,24 @@ func publishTransformPolicyCases() []publishTransformPolicyCase {
|
|||||||
Mode: TransformModeSidecar,
|
Mode: TransformModeSidecar,
|
||||||
}},
|
}},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "disabled markdown index mode allowed",
|
||||||
|
publish: PublishPolicy{Source: true},
|
||||||
|
transform: Transform{MarkdownToHTML: &MarkdownToHTML{
|
||||||
|
Enabled: false,
|
||||||
|
Mode: TransformModeIndex,
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "disabled markdown input rejected",
|
||||||
|
publish: PublishPolicy{Source: true},
|
||||||
|
transform: Transform{MarkdownToHTML: &MarkdownToHTML{
|
||||||
|
Enabled: false,
|
||||||
|
Mode: TransformModeIndex,
|
||||||
|
Input: "report.md",
|
||||||
|
}},
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "disabled markdown wrong mode rejected",
|
name: "disabled markdown wrong mode rejected",
|
||||||
publish: PublishPolicy{Source: true},
|
publish: PublishPolicy{Source: true},
|
||||||
|
|||||||
346
internal/ingest/archive.go
Normal file
346
internal/ingest/archive.go
Normal file
@@ -0,0 +1,346 @@
|
|||||||
|
package ingest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/tar"
|
||||||
|
"compress/gzip"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"mime"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
sourcebundle "gitea.maximumdirect.net/eric/distributor/pkg/bundle"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
ContentTypeTar = "application/x-tar"
|
||||||
|
ContentTypeGzip = "application/gzip"
|
||||||
|
ContentTypeXGzip = "application/x-gzip"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrUnsupportedContentType = errors.New("unsupported archive content type")
|
||||||
|
ErrUploadTooLarge = errors.New("upload exceeds maximum size")
|
||||||
|
ErrExtractedTooLarge = errors.New("extracted bundle exceeds maximum size")
|
||||||
|
ErrTooManyFiles = errors.New("extracted bundle has too many files")
|
||||||
|
ErrUnsafeArchivePath = errors.New("unsafe archive path")
|
||||||
|
)
|
||||||
|
|
||||||
|
type StageOptions struct {
|
||||||
|
Body io.Reader
|
||||||
|
ContentType string
|
||||||
|
PipelineStagingPath string
|
||||||
|
RunID string
|
||||||
|
MaxUploadSize int64
|
||||||
|
MaxExtractedSize int64
|
||||||
|
MaxFileCount int
|
||||||
|
}
|
||||||
|
|
||||||
|
type StagedBundle struct {
|
||||||
|
Root string
|
||||||
|
Manifest sourcebundle.Manifest
|
||||||
|
}
|
||||||
|
|
||||||
|
func StageArchive(ctx context.Context, opts StageOptions) (StagedBundle, error) {
|
||||||
|
if ctx == nil {
|
||||||
|
ctx = context.Background()
|
||||||
|
}
|
||||||
|
if err := validateStageOptions(opts); err != nil {
|
||||||
|
return StagedBundle{}, err
|
||||||
|
}
|
||||||
|
format, err := archiveFormat(opts.ContentType)
|
||||||
|
if err != nil {
|
||||||
|
return StagedBundle{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := os.MkdirAll(opts.PipelineStagingPath, 0o755); err != nil {
|
||||||
|
return StagedBundle{}, fmt.Errorf("create pipeline staging path: %w", err)
|
||||||
|
}
|
||||||
|
tempDir, err := os.MkdirTemp(opts.PipelineStagingPath, "."+opts.RunID+"-")
|
||||||
|
if err != nil {
|
||||||
|
return StagedBundle{}, fmt.Errorf("create staging temp dir: %w", err)
|
||||||
|
}
|
||||||
|
cleanupTemp := true
|
||||||
|
defer func() {
|
||||||
|
if cleanupTemp {
|
||||||
|
_ = os.RemoveAll(tempDir)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
archivePath := filepath.Join(tempDir, "upload.archive")
|
||||||
|
if err := writeLimited(ctx, archivePath, opts.Body, opts.MaxUploadSize); err != nil {
|
||||||
|
return StagedBundle{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
extractRoot := filepath.Join(tempDir, "bundle")
|
||||||
|
if err := os.Mkdir(extractRoot, 0o755); err != nil {
|
||||||
|
return StagedBundle{}, fmt.Errorf("create extraction root: %w", err)
|
||||||
|
}
|
||||||
|
if err := extractArchive(ctx, archivePath, extractRoot, format, opts.MaxExtractedSize, opts.MaxFileCount); err != nil {
|
||||||
|
return StagedBundle{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
manifest, err := sourcebundle.LoadManifest(extractRoot)
|
||||||
|
if err != nil {
|
||||||
|
return StagedBundle{}, err
|
||||||
|
}
|
||||||
|
if err := sourcebundle.ValidateBundle(extractRoot, manifest); err != nil {
|
||||||
|
return StagedBundle{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
finalRoot := filepath.Join(opts.PipelineStagingPath, opts.RunID)
|
||||||
|
if err := os.Rename(extractRoot, finalRoot); err != nil {
|
||||||
|
return StagedBundle{}, fmt.Errorf("commit staged bundle: %w", err)
|
||||||
|
}
|
||||||
|
cleanupTemp = false
|
||||||
|
if err := os.RemoveAll(tempDir); err != nil {
|
||||||
|
return StagedBundle{}, fmt.Errorf("remove staging temp dir: %w", err)
|
||||||
|
}
|
||||||
|
return StagedBundle{
|
||||||
|
Root: finalRoot,
|
||||||
|
Manifest: manifest,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateStageOptions(opts StageOptions) error {
|
||||||
|
if opts.Body == nil {
|
||||||
|
return fmt.Errorf("body is required")
|
||||||
|
}
|
||||||
|
if opts.PipelineStagingPath == "" {
|
||||||
|
return fmt.Errorf("pipeline staging path is required")
|
||||||
|
}
|
||||||
|
if err := validateRunID(opts.RunID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if opts.MaxUploadSize <= 0 {
|
||||||
|
return fmt.Errorf("max upload size must be greater than zero")
|
||||||
|
}
|
||||||
|
if opts.MaxExtractedSize <= 0 {
|
||||||
|
return fmt.Errorf("max extracted size must be greater than zero")
|
||||||
|
}
|
||||||
|
if opts.MaxFileCount <= 0 {
|
||||||
|
return fmt.Errorf("max file count must be greater than zero")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateRunID(value string) error {
|
||||||
|
if value == "" {
|
||||||
|
return fmt.Errorf("run id is required")
|
||||||
|
}
|
||||||
|
if value == "." || value == ".." || strings.ContainsAny(value, `/\`) {
|
||||||
|
return fmt.Errorf("run id must be a single filesystem path segment")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type archiveKind int
|
||||||
|
|
||||||
|
const (
|
||||||
|
archiveKindTar archiveKind = iota + 1
|
||||||
|
archiveKindGzip
|
||||||
|
)
|
||||||
|
|
||||||
|
func archiveFormat(contentType string) (archiveKind, error) {
|
||||||
|
mediaType, _, err := mime.ParseMediaType(contentType)
|
||||||
|
if err != nil {
|
||||||
|
mediaType = contentType
|
||||||
|
}
|
||||||
|
switch mediaType {
|
||||||
|
case ContentTypeTar:
|
||||||
|
return archiveKindTar, nil
|
||||||
|
case ContentTypeGzip, ContentTypeXGzip:
|
||||||
|
return archiveKindGzip, nil
|
||||||
|
default:
|
||||||
|
return 0, ErrUnsupportedContentType
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeLimited(ctx context.Context, destination string, body io.Reader, maxSize int64) error {
|
||||||
|
file, err := os.OpenFile(destination, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("create upload archive: %w", err)
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
limited := &limitedReader{ctx: ctx, reader: body, limit: maxSize}
|
||||||
|
if _, err := io.Copy(file, limited); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := file.Close(); err != nil {
|
||||||
|
return fmt.Errorf("write upload archive: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type limitedReader struct {
|
||||||
|
ctx context.Context
|
||||||
|
reader io.Reader
|
||||||
|
limit int64
|
||||||
|
read int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *limitedReader) Read(data []byte) (int, error) {
|
||||||
|
if err := r.ctx.Err(); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if r.read == r.limit {
|
||||||
|
var probe [1]byte
|
||||||
|
n, err := r.reader.Read(probe[:])
|
||||||
|
if n > 0 {
|
||||||
|
return 0, ErrUploadTooLarge
|
||||||
|
}
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
remaining := r.limit - r.read
|
||||||
|
if int64(len(data)) > remaining+1 {
|
||||||
|
data = data[:remaining+1]
|
||||||
|
}
|
||||||
|
n, err := r.reader.Read(data)
|
||||||
|
if r.read+int64(n) > r.limit {
|
||||||
|
allowed := int(r.limit - r.read)
|
||||||
|
r.read = r.limit
|
||||||
|
return allowed, ErrUploadTooLarge
|
||||||
|
}
|
||||||
|
r.read += int64(n)
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func extractArchive(ctx context.Context, archivePath, destination string, format archiveKind, maxExtractedSize int64, maxFileCount int) error {
|
||||||
|
file, err := os.Open(archivePath)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("open upload archive: %w", err)
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
var reader io.Reader = file
|
||||||
|
var gzipReader *gzip.Reader
|
||||||
|
if format == archiveKindGzip {
|
||||||
|
gzipReader, err = gzip.NewReader(file)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("open gzip archive: %w", err)
|
||||||
|
}
|
||||||
|
defer gzipReader.Close()
|
||||||
|
reader = gzipReader
|
||||||
|
}
|
||||||
|
|
||||||
|
extractor := archiveExtractor{
|
||||||
|
ctx: ctx,
|
||||||
|
destination: destination,
|
||||||
|
maxExtractedSize: maxExtractedSize,
|
||||||
|
maxFileCount: maxFileCount,
|
||||||
|
}
|
||||||
|
if err := extractor.extract(tar.NewReader(reader)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if extractor.rootManifestCount != 1 {
|
||||||
|
return fmt.Errorf("archive must contain exactly one root-level manifest.json")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type archiveExtractor struct {
|
||||||
|
ctx context.Context
|
||||||
|
destination string
|
||||||
|
maxExtractedSize int64
|
||||||
|
maxFileCount int
|
||||||
|
extractedSize int64
|
||||||
|
fileCount int
|
||||||
|
rootManifestCount int
|
||||||
|
seenFiles map[string]struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *archiveExtractor) extract(reader *tar.Reader) error {
|
||||||
|
e.seenFiles = make(map[string]struct{})
|
||||||
|
for {
|
||||||
|
if err := e.ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
header, err := reader.Next()
|
||||||
|
if errors.Is(err, io.EOF) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("read tar archive: %w", err)
|
||||||
|
}
|
||||||
|
name, err := cleanArchivePath(header.Name)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if path.Base(name) == sourcebundle.ManifestName {
|
||||||
|
if name != sourcebundle.ManifestName {
|
||||||
|
return fmt.Errorf("nested manifest %q is not allowed", name)
|
||||||
|
}
|
||||||
|
e.rootManifestCount++
|
||||||
|
}
|
||||||
|
|
||||||
|
switch header.Typeflag {
|
||||||
|
case tar.TypeDir:
|
||||||
|
if err := os.MkdirAll(filepath.Join(e.destination, filepath.FromSlash(name)), 0o755); err != nil {
|
||||||
|
return fmt.Errorf("create archive directory %q: %w", name, err)
|
||||||
|
}
|
||||||
|
case tar.TypeReg, tar.TypeRegA:
|
||||||
|
if err := e.extractFile(reader, name, header.Size); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("archive entry %q has unsupported type %c", name, header.Typeflag)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *archiveExtractor) extractFile(reader *tar.Reader, name string, size int64) error {
|
||||||
|
if size < 0 {
|
||||||
|
return fmt.Errorf("archive entry %q has invalid size", name)
|
||||||
|
}
|
||||||
|
e.fileCount++
|
||||||
|
if e.fileCount > e.maxFileCount {
|
||||||
|
return ErrTooManyFiles
|
||||||
|
}
|
||||||
|
e.extractedSize += size
|
||||||
|
if e.extractedSize > e.maxExtractedSize {
|
||||||
|
return ErrExtractedTooLarge
|
||||||
|
}
|
||||||
|
if _, exists := e.seenFiles[name]; exists {
|
||||||
|
return fmt.Errorf("archive entry %q is duplicated", name)
|
||||||
|
}
|
||||||
|
e.seenFiles[name] = struct{}{}
|
||||||
|
|
||||||
|
fullPath := filepath.Join(e.destination, filepath.FromSlash(name))
|
||||||
|
if err := os.MkdirAll(filepath.Dir(fullPath), 0o755); err != nil {
|
||||||
|
return fmt.Errorf("create archive parent for %q: %w", name, err)
|
||||||
|
}
|
||||||
|
file, err := os.OpenFile(fullPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("create archive file %q: %w", name, err)
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
if _, err := io.CopyN(file, reader, size); err != nil {
|
||||||
|
return fmt.Errorf("extract archive file %q: %w", name, err)
|
||||||
|
}
|
||||||
|
if err := file.Close(); err != nil {
|
||||||
|
return fmt.Errorf("extract archive file %q: %w", name, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func cleanArchivePath(value string) (string, error) {
|
||||||
|
if value == "" || strings.Contains(value, `\`) || strings.HasPrefix(value, "/") {
|
||||||
|
return "", ErrUnsafeArchivePath
|
||||||
|
}
|
||||||
|
cleaned := path.Clean(value)
|
||||||
|
if cleaned != value {
|
||||||
|
return "", ErrUnsafeArchivePath
|
||||||
|
}
|
||||||
|
for _, segment := range strings.Split(value, "/") {
|
||||||
|
if segment == "" || segment == "." || segment == ".." {
|
||||||
|
return "", ErrUnsafeArchivePath
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return value, nil
|
||||||
|
}
|
||||||
382
internal/ingest/archive_test.go
Normal file
382
internal/ingest/archive_test.go
Normal file
@@ -0,0 +1,382 @@
|
|||||||
|
package ingest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/tar"
|
||||||
|
"bytes"
|
||||||
|
"compress/gzip"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
sourcebundle "gitea.maximumdirect.net/eric/distributor/pkg/bundle"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestStageArchiveAcceptsTar(t *testing.T) {
|
||||||
|
archive := validArchive(t, false)
|
||||||
|
staged := stageArchive(t, archive, ContentTypeTar)
|
||||||
|
|
||||||
|
if got, want := staged.Manifest.ID, "reports.ingest"; got != want {
|
||||||
|
t.Fatalf("manifest id = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
if got := readFile(t, staged.Root, "report.md"); got != "# Report\n" {
|
||||||
|
t.Fatalf("report = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStageArchiveAcceptsGzipTar(t *testing.T) {
|
||||||
|
archive := validArchive(t, true)
|
||||||
|
staged := stageArchive(t, archive, ContentTypeGzip+"; charset=binary")
|
||||||
|
|
||||||
|
if got, want := staged.Manifest.ID, "reports.ingest"; got != want {
|
||||||
|
t.Fatalf("manifest id = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
if got := readFile(t, staged.Root, "summary.txt"); got != "Summary\n" {
|
||||||
|
t.Fatalf("summary = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStageArchiveRejectsUnsupportedContentType(t *testing.T) {
|
||||||
|
err := stageArchiveError(t, validArchive(t, false), "application/zip", nil)
|
||||||
|
if !errors.Is(err, ErrUnsupportedContentType) {
|
||||||
|
t.Fatalf("StageArchive() error = %v, want ErrUnsupportedContentType", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStageArchiveEnforcesMaxUploadSize(t *testing.T) {
|
||||||
|
archive := validArchive(t, false)
|
||||||
|
err := stageArchiveError(t, archive, ContentTypeTar, func(opts *StageOptions) {
|
||||||
|
opts.MaxUploadSize = int64(len(archive) - 1)
|
||||||
|
})
|
||||||
|
if !errors.Is(err, ErrUploadTooLarge) {
|
||||||
|
t.Fatalf("StageArchive() error = %v, want ErrUploadTooLarge", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStageArchiveEnforcesExtractionLimits(t *testing.T) {
|
||||||
|
archive := validArchive(t, false)
|
||||||
|
tests := map[string]struct {
|
||||||
|
mutate func(*StageOptions)
|
||||||
|
wantErr error
|
||||||
|
}{
|
||||||
|
"size": {
|
||||||
|
mutate: func(opts *StageOptions) {
|
||||||
|
opts.MaxExtractedSize = 1
|
||||||
|
},
|
||||||
|
wantErr: ErrExtractedTooLarge,
|
||||||
|
},
|
||||||
|
"files": {
|
||||||
|
mutate: func(opts *StageOptions) {
|
||||||
|
opts.MaxFileCount = 1
|
||||||
|
},
|
||||||
|
wantErr: ErrTooManyFiles,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for name, tt := range tests {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
err := stageArchiveError(t, archive, ContentTypeTar, tt.mutate)
|
||||||
|
if !errors.Is(err, tt.wantErr) {
|
||||||
|
t.Fatalf("StageArchive() error = %v, want %v", err, tt.wantErr)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStageArchiveRejectsUnsafeEntries(t *testing.T) {
|
||||||
|
tests := map[string][]tarEntry{
|
||||||
|
"absolute path": {
|
||||||
|
fileEntry("/report.md", "report"),
|
||||||
|
},
|
||||||
|
"path traversal": {
|
||||||
|
fileEntry("../report.md", "report"),
|
||||||
|
},
|
||||||
|
"backslash path": {
|
||||||
|
fileEntry(`nested\report.md`, "report"),
|
||||||
|
},
|
||||||
|
"symlink": {
|
||||||
|
{name: "link.md", typeflag: tar.TypeSymlink, linkname: "report.md"},
|
||||||
|
},
|
||||||
|
"hardlink": {
|
||||||
|
{name: "link.md", typeflag: tar.TypeLink, linkname: "report.md"},
|
||||||
|
},
|
||||||
|
"device": {
|
||||||
|
{name: "device", typeflag: tar.TypeChar},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for name, entries := range tests {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
err := stageArchiveError(t, makeArchive(t, false, entries...), ContentTypeTar, nil)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("StageArchive() error = nil, want error")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStageArchiveRejectsBundleValidationFailures(t *testing.T) {
|
||||||
|
tests := map[string][]tarEntry{
|
||||||
|
"missing manifest": {
|
||||||
|
fileEntry("report.md", "report"),
|
||||||
|
},
|
||||||
|
"nested manifest": {
|
||||||
|
fileEntry("manifest.json", manifestJSON(t, manifestFor("reports.nested", fileSpec{path: "report.md", body: "report"}))),
|
||||||
|
fileEntry("nested/manifest.json", "{}"),
|
||||||
|
fileEntry("report.md", "report"),
|
||||||
|
},
|
||||||
|
"missing listed file": {
|
||||||
|
fileEntry("manifest.json", manifestJSON(t, manifestFor("reports.missing", fileSpec{path: "missing.md", body: "missing"}))),
|
||||||
|
},
|
||||||
|
"digest mismatch": {
|
||||||
|
fileEntry("manifest.json", manifestJSON(t, manifestFor("reports.digest", fileSpec{path: "report.md", body: "expected"}))),
|
||||||
|
fileEntry("report.md", "actual"),
|
||||||
|
},
|
||||||
|
"non regular listed file": {
|
||||||
|
fileEntry("manifest.json", manifestJSON(t, manifestFor("reports.directory", fileSpec{path: "report.md", body: "report"}))),
|
||||||
|
{name: "report.md", typeflag: tar.TypeDir},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for name, entries := range tests {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
err := stageArchiveError(t, makeArchive(t, false, entries...), ContentTypeTar, nil)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("StageArchive() error = nil, want error")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStageArchiveCleansUpFailedExtraction(t *testing.T) {
|
||||||
|
stagingPath := filepath.Join(t.TempDir(), "staging")
|
||||||
|
archive := makeArchive(t, false, fileEntry("../report.md", "report"))
|
||||||
|
_, err := StageArchive(context.Background(), StageOptions{
|
||||||
|
Body: bytes.NewReader(archive),
|
||||||
|
ContentType: ContentTypeTar,
|
||||||
|
PipelineStagingPath: stagingPath,
|
||||||
|
RunID: "reports.20260603T120000Z.abcd",
|
||||||
|
MaxUploadSize: int64(len(archive)),
|
||||||
|
MaxExtractedSize: 1024 * 1024,
|
||||||
|
MaxFileCount: 10,
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("StageArchive() error = nil, want error")
|
||||||
|
}
|
||||||
|
entries, err := os.ReadDir(stagingPath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ReadDir() error = %v", err)
|
||||||
|
}
|
||||||
|
if len(entries) != 0 {
|
||||||
|
t.Fatalf("staging entries = %d, want cleanup", len(entries))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func stageArchive(t *testing.T, archive []byte, contentType string) StagedBundle {
|
||||||
|
t.Helper()
|
||||||
|
staged, err := StageArchive(context.Background(), defaultStageOptions(t, archive, contentType))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("StageArchive() error = %v", err)
|
||||||
|
}
|
||||||
|
return staged
|
||||||
|
}
|
||||||
|
|
||||||
|
func stageArchiveError(t *testing.T, archive []byte, contentType string, mutate func(*StageOptions)) error {
|
||||||
|
t.Helper()
|
||||||
|
opts := defaultStageOptions(t, archive, contentType)
|
||||||
|
if mutate != nil {
|
||||||
|
mutate(&opts)
|
||||||
|
}
|
||||||
|
_, err := StageArchive(context.Background(), opts)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("StageArchive() error = nil, want error")
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func defaultStageOptions(t *testing.T, archive []byte, contentType string) StageOptions {
|
||||||
|
t.Helper()
|
||||||
|
return StageOptions{
|
||||||
|
Body: bytes.NewReader(archive),
|
||||||
|
ContentType: contentType,
|
||||||
|
PipelineStagingPath: filepath.Join(t.TempDir(), "staging"),
|
||||||
|
RunID: "reports.20260603T120000Z.abcd",
|
||||||
|
MaxUploadSize: int64(len(archive)),
|
||||||
|
MaxExtractedSize: 1024 * 1024,
|
||||||
|
MaxFileCount: 10,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func validArchive(t *testing.T, compressed bool) []byte {
|
||||||
|
t.Helper()
|
||||||
|
root := filepath.Join(t.TempDir(), "bundle")
|
||||||
|
sourceRoot := t.TempDir()
|
||||||
|
writeFile(t, sourceRoot, "report.md", "# Report\n")
|
||||||
|
writeFile(t, sourceRoot, "summary.txt", "Summary\n")
|
||||||
|
_, err := sourcebundle.WriteBundle(sourcebundle.WriteBundleOptions{
|
||||||
|
Root: root,
|
||||||
|
ID: "reports.ingest",
|
||||||
|
Created: time.Date(2026, 6, 3, 12, 0, 0, 0, time.UTC),
|
||||||
|
Files: []sourcebundle.BundleFile{
|
||||||
|
{SourcePath: filepath.Join(sourceRoot, "report.md"), Path: "report.md"},
|
||||||
|
{SourcePath: filepath.Join(sourceRoot, "summary.txt"), Path: "summary.txt"},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("WriteBundle() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var entries []tarEntry
|
||||||
|
if err := filepath.WalkDir(root, func(filePath string, entry fs.DirEntry, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if entry.IsDir() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
relative, err := filepath.Rel(root, filePath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(filePath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
entries = append(entries, fileEntry(filepath.ToSlash(relative), string(data)))
|
||||||
|
return nil
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("walk bundle: %v", err)
|
||||||
|
}
|
||||||
|
return makeArchive(t, compressed, entries...)
|
||||||
|
}
|
||||||
|
|
||||||
|
type tarEntry struct {
|
||||||
|
name string
|
||||||
|
typeflag byte
|
||||||
|
body []byte
|
||||||
|
linkname string
|
||||||
|
}
|
||||||
|
|
||||||
|
func fileEntry(name, body string) tarEntry {
|
||||||
|
return tarEntry{name: name, typeflag: tar.TypeReg, body: []byte(body)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func makeArchive(t *testing.T, compressed bool, entries ...tarEntry) []byte {
|
||||||
|
t.Helper()
|
||||||
|
var output bytes.Buffer
|
||||||
|
var writer *tar.Writer
|
||||||
|
var gzipWriter *gzip.Writer
|
||||||
|
if compressed {
|
||||||
|
gzipWriter = gzip.NewWriter(&output)
|
||||||
|
writer = tar.NewWriter(gzipWriter)
|
||||||
|
} else {
|
||||||
|
writer = tar.NewWriter(&output)
|
||||||
|
}
|
||||||
|
for _, entry := range entries {
|
||||||
|
header := &tar.Header{
|
||||||
|
Name: entry.name,
|
||||||
|
Typeflag: entry.typeflag,
|
||||||
|
Size: int64(len(entry.body)),
|
||||||
|
Mode: 0o644,
|
||||||
|
Linkname: entry.linkname,
|
||||||
|
}
|
||||||
|
if entry.typeflag == tar.TypeDir {
|
||||||
|
header.Size = 0
|
||||||
|
header.Mode = 0o755
|
||||||
|
}
|
||||||
|
if err := writer.WriteHeader(header); err != nil {
|
||||||
|
t.Fatalf("WriteHeader(%q) error = %v", entry.name, err)
|
||||||
|
}
|
||||||
|
if len(entry.body) > 0 {
|
||||||
|
if _, err := writer.Write(entry.body); err != nil {
|
||||||
|
t.Fatalf("Write(%q) error = %v", entry.name, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := writer.Close(); err != nil {
|
||||||
|
t.Fatalf("close tar writer: %v", err)
|
||||||
|
}
|
||||||
|
if gzipWriter != nil {
|
||||||
|
if err := gzipWriter.Close(); err != nil {
|
||||||
|
t.Fatalf("close gzip writer: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return output.Bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
type fileSpec struct {
|
||||||
|
path string
|
||||||
|
body string
|
||||||
|
}
|
||||||
|
|
||||||
|
func manifestFor(id string, files ...fileSpec) sourcebundle.Manifest {
|
||||||
|
manifest := sourcebundle.Manifest{
|
||||||
|
SchemaVersion: sourcebundle.SchemaVersion,
|
||||||
|
ID: id,
|
||||||
|
Created: time.Date(2026, 6, 3, 12, 0, 0, 0, time.UTC),
|
||||||
|
}
|
||||||
|
for _, file := range files {
|
||||||
|
manifest.Files = append(manifest.Files, sourcebundle.ManifestFile{
|
||||||
|
Path: file.path,
|
||||||
|
SHA256: sourcebundle.FileDigest([]byte(file.body)),
|
||||||
|
Size: int64(len(file.body)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
manifest.Digest = sourcebundle.BundleDigest(manifest.Files)
|
||||||
|
return manifest
|
||||||
|
}
|
||||||
|
|
||||||
|
func manifestJSON(t *testing.T, manifest sourcebundle.Manifest) string {
|
||||||
|
t.Helper()
|
||||||
|
data, err := sourcebundle.MarshalManifest(manifest)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("MarshalManifest() error = %v", err)
|
||||||
|
}
|
||||||
|
return string(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeFile(t *testing.T, root, relative, body string) {
|
||||||
|
t.Helper()
|
||||||
|
fullPath := filepath.Join(root, filepath.FromSlash(relative))
|
||||||
|
if err := os.MkdirAll(filepath.Dir(fullPath), 0o755); err != nil {
|
||||||
|
t.Fatalf("MkdirAll() error = %v", err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(fullPath, []byte(body), 0o644); err != nil {
|
||||||
|
t.Fatalf("WriteFile() error = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func readFile(t *testing.T, root, relative string) string {
|
||||||
|
t.Helper()
|
||||||
|
data, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(relative)))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ReadFile() error = %v", err)
|
||||||
|
}
|
||||||
|
return string(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCleanArchivePath(t *testing.T) {
|
||||||
|
tests := map[string]bool{
|
||||||
|
"manifest.json": true,
|
||||||
|
"nested/report.md": true,
|
||||||
|
"": false,
|
||||||
|
"/absolute.md": false,
|
||||||
|
"../escape.md": false,
|
||||||
|
"nested/../report.md": false,
|
||||||
|
`nested\report.md`: false,
|
||||||
|
"./report.md": false,
|
||||||
|
"nested//report.md": false,
|
||||||
|
}
|
||||||
|
for value, wantOK := range tests {
|
||||||
|
t.Run(strings.ReplaceAll(value, "/", "_"), func(t *testing.T) {
|
||||||
|
_, err := cleanArchivePath(value)
|
||||||
|
if wantOK && err != nil {
|
||||||
|
t.Fatalf("cleanArchivePath(%q) error = %v", value, err)
|
||||||
|
}
|
||||||
|
if !wantOK && err == nil {
|
||||||
|
t.Fatalf("cleanArchivePath(%q) error = nil, want error", value)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
26
internal/link/url.go
Normal file
26
internal/link/url.go
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
package link
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/url"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ValidateHTTPURL(value string) error {
|
||||||
|
parsed, err := url.Parse(value)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("must be a valid URL")
|
||||||
|
}
|
||||||
|
if parsed.Scheme != "http" && parsed.Scheme != "https" {
|
||||||
|
return fmt.Errorf("must use http or https")
|
||||||
|
}
|
||||||
|
if parsed.Host == "" {
|
||||||
|
return fmt.Errorf("must include a host")
|
||||||
|
}
|
||||||
|
if parsed.RawQuery != "" {
|
||||||
|
return fmt.Errorf("must not include a query string")
|
||||||
|
}
|
||||||
|
if parsed.Fragment != "" {
|
||||||
|
return fmt.Errorf("must not include a fragment")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
39
internal/link/url_test.go
Normal file
39
internal/link/url_test.go
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
package link
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestValidateHTTPURL(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
value string
|
||||||
|
wantErr string
|
||||||
|
}{
|
||||||
|
{name: "http", value: "http://reports.example.com/archive"},
|
||||||
|
{name: "https", value: "https://reports.example.com/archive"},
|
||||||
|
{name: "missing host", value: "https:///archive", wantErr: "must include a host"},
|
||||||
|
{name: "unsupported scheme", value: "ftp://reports.example.com/archive", wantErr: "must use http or https"},
|
||||||
|
{name: "query string", value: "https://reports.example.com/archive?preview=1", wantErr: "must not include a query string"},
|
||||||
|
{name: "fragment", value: "https://reports.example.com/archive#top", wantErr: "must not include a fragment"},
|
||||||
|
{name: "parse failure", value: "http://[::1", wantErr: "must be a valid URL"},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
err := ValidateHTTPURL(tt.value)
|
||||||
|
if tt.wantErr == "" {
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ValidateHTTPURL() error = %v", err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("ValidateHTTPURL() error = nil, want error")
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), tt.wantErr) {
|
||||||
|
t.Fatalf("ValidateHTTPURL() error = %q, want %q", err, tt.wantErr)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,7 +23,7 @@ func Execute(ctx context.Context, req Request, plan Plan) error {
|
|||||||
if plan.ExistingState == nil {
|
if plan.ExistingState == nil {
|
||||||
return fmt.Errorf("replace requires existing destination state")
|
return fmt.Errorf("replace requires existing destination state")
|
||||||
}
|
}
|
||||||
if err := req.DestinationBackend.DeleteManagedBundle(ctx, req.DestinationBundlePath, existingManagedOutputPaths(*plan.ExistingState), storage.DeleteOptions{IgnoreMissing: true, PruneEmptyDirs: true}); err != nil {
|
if err := req.DestinationBackend.DeleteManagedBundle(ctx, req.DestinationBundlePath, stateOutputManagedPaths(plan.ExistingState.Outputs), storage.DeleteOptions{IgnoreMissing: true, PruneEmptyDirs: true}); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if err := ensureDestinationEmpty(ctx, req.DestinationBackend, req.DestinationBundlePath); err != nil {
|
if err := ensureDestinationEmpty(ctx, req.DestinationBackend, req.DestinationBundlePath); err != nil {
|
||||||
@@ -41,7 +41,7 @@ func Execute(ctx context.Context, req Request, plan Plan) error {
|
|||||||
|
|
||||||
writtenOutputs := make([]Output, 0, len(plan.Outputs))
|
writtenOutputs := make([]Output, 0, len(plan.Outputs))
|
||||||
cleanup := func() {
|
cleanup := func() {
|
||||||
_ = req.DestinationBackend.DeleteManagedBundle(ctx, req.DestinationBundlePath, managedOutputPaths(writtenOutputs), storage.DeleteOptions{IgnoreMissing: true, PruneEmptyDirs: true})
|
_ = req.DestinationBackend.DeleteManagedBundle(ctx, req.DestinationBundlePath, ManagedOutputPaths(writtenOutputs), storage.DeleteOptions{IgnoreMissing: true, PruneEmptyDirs: true})
|
||||||
}
|
}
|
||||||
for _, output := range plan.Outputs {
|
for _, output := range plan.Outputs {
|
||||||
destinationPath, err := storage.Join(req.DestinationBundlePath, output.DestinationPath)
|
destinationPath, err := storage.Join(req.DestinationBundlePath, output.DestinationPath)
|
||||||
@@ -76,7 +76,10 @@ func Execute(ctx context.Context, req Request, plan Plan) error {
|
|||||||
DestinationID: req.DestinationID,
|
DestinationID: req.DestinationID,
|
||||||
PublishedAt: time.Now().UTC(),
|
PublishedAt: time.Now().UTC(),
|
||||||
Source: state.SourceState{Manifest: req.SourceBundle.Manifest},
|
Source: state.SourceState{Manifest: req.SourceBundle.Manifest},
|
||||||
Outputs: stateOutputs(plan.Outputs),
|
Outputs: StateOutputFiles(plan.Outputs),
|
||||||
|
}
|
||||||
|
if plan.PrimaryURL != "" {
|
||||||
|
destinationState.Links = &state.LinkState{PrimaryURL: plan.PrimaryURL}
|
||||||
}
|
}
|
||||||
if err := state.Validate(destinationState); err != nil {
|
if err := state.Validate(destinationState); err != nil {
|
||||||
cleanup()
|
cleanup()
|
||||||
@@ -99,11 +102,3 @@ func Execute(ctx context.Context, req Request, plan Plan) error {
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func existingManagedOutputPaths(destinationState state.DistributorState) []string {
|
|
||||||
paths := make([]string, 0, len(destinationState.Outputs))
|
|
||||||
for _, output := range destinationState.Outputs {
|
|
||||||
paths = append(paths, output.Path)
|
|
||||||
}
|
|
||||||
return paths
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -2,13 +2,11 @@ package publish
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/distributor/internal/bundle"
|
"gitea.maximumdirect.net/eric/distributor/internal/bundle"
|
||||||
"gitea.maximumdirect.net/eric/distributor/internal/config"
|
"gitea.maximumdirect.net/eric/distributor/internal/config"
|
||||||
"gitea.maximumdirect.net/eric/distributor/internal/storage"
|
|
||||||
"gitea.maximumdirect.net/eric/distributor/internal/storage/fake"
|
"gitea.maximumdirect.net/eric/distributor/internal/storage/fake"
|
||||||
"gitea.maximumdirect.net/eric/distributor/internal/testutil"
|
"gitea.maximumdirect.net/eric/distributor/internal/testutil"
|
||||||
)
|
)
|
||||||
@@ -25,7 +23,7 @@ func TestBuildPlansForcedReplacementOnlyWhenExplicit(t *testing.T) {
|
|||||||
name: "unmanaged content",
|
name: "unmanaged content",
|
||||||
prepare: func(t *testing.T, backend *fake.Backend, source bundle.Manifest) {
|
prepare: func(t *testing.T, backend *fake.Backend, source bundle.Manifest) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
writeFakeFile(t, backend, "bundle/old.txt", "old")
|
testutil.WriteFakeFile(t, backend, "bundle/old.txt", "old")
|
||||||
},
|
},
|
||||||
transfer: defaultTransfer(),
|
transfer: defaultTransfer(),
|
||||||
wantReason: "fail_unmanaged",
|
wantReason: "fail_unmanaged",
|
||||||
@@ -37,7 +35,7 @@ func TestBuildPlansForcedReplacementOnlyWhenExplicit(t *testing.T) {
|
|||||||
t.Helper()
|
t.Helper()
|
||||||
conflict := source
|
conflict := source
|
||||||
conflict.ID = "other.source"
|
conflict.ID = "other.source"
|
||||||
writeFakeDestinationState(t, backend, "bundle", conflict, testutil.DestinationStateOptions{})
|
testutil.WriteFakeDestinationState(t, backend, "bundle", conflict, testutil.DestinationStateOptions{})
|
||||||
},
|
},
|
||||||
transfer: conflictReplaceTransfer(),
|
transfer: conflictReplaceTransfer(),
|
||||||
wantReason: "requires --force",
|
wantReason: "requires --force",
|
||||||
@@ -48,7 +46,7 @@ func TestBuildPlansForcedReplacementOnlyWhenExplicit(t *testing.T) {
|
|||||||
prepare: func(t *testing.T, backend *fake.Backend, source bundle.Manifest) {
|
prepare: func(t *testing.T, backend *fake.Backend, source bundle.Manifest) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
conflict := testutil.ValidManifest(testutil.BundleOptions{Files: []testutil.SourceFile{{Path: "report.md", Data: "# Different\n"}}})
|
conflict := testutil.ValidManifest(testutil.BundleOptions{Files: []testutil.SourceFile{{Path: "report.md", Data: "# Different\n"}}})
|
||||||
writeFakeDestinationState(t, backend, "bundle", conflict, testutil.DestinationStateOptions{})
|
testutil.WriteFakeDestinationState(t, backend, "bundle", conflict, testutil.DestinationStateOptions{})
|
||||||
},
|
},
|
||||||
transfer: conflictReplaceTransfer(),
|
transfer: conflictReplaceTransfer(),
|
||||||
wantReason: "requires --force",
|
wantReason: "requires --force",
|
||||||
@@ -58,7 +56,7 @@ func TestBuildPlansForcedReplacementOnlyWhenExplicit(t *testing.T) {
|
|||||||
name: "pipeline mismatch",
|
name: "pipeline mismatch",
|
||||||
prepare: func(t *testing.T, backend *fake.Backend, source bundle.Manifest) {
|
prepare: func(t *testing.T, backend *fake.Backend, source bundle.Manifest) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
writeFakeDestinationState(t, backend, "bundle", source, testutil.DestinationStateOptions{PipelineID: "other-pipeline"})
|
testutil.WriteFakeDestinationState(t, backend, "bundle", source, testutil.DestinationStateOptions{PipelineID: "other-pipeline"})
|
||||||
},
|
},
|
||||||
transfer: conflictReplaceTransfer(),
|
transfer: conflictReplaceTransfer(),
|
||||||
wantReason: "requires --force",
|
wantReason: "requires --force",
|
||||||
@@ -68,7 +66,7 @@ func TestBuildPlansForcedReplacementOnlyWhenExplicit(t *testing.T) {
|
|||||||
name: "destination mismatch",
|
name: "destination mismatch",
|
||||||
prepare: func(t *testing.T, backend *fake.Backend, source bundle.Manifest) {
|
prepare: func(t *testing.T, backend *fake.Backend, source bundle.Manifest) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
writeFakeDestinationState(t, backend, "bundle", source, testutil.DestinationStateOptions{DestinationID: "other-destination"})
|
testutil.WriteFakeDestinationState(t, backend, "bundle", source, testutil.DestinationStateOptions{DestinationID: "other-destination"})
|
||||||
},
|
},
|
||||||
transfer: conflictReplaceTransfer(),
|
transfer: conflictReplaceTransfer(),
|
||||||
wantReason: "requires --force",
|
wantReason: "requires --force",
|
||||||
@@ -80,7 +78,7 @@ func TestBuildPlansForcedReplacementOnlyWhenExplicit(t *testing.T) {
|
|||||||
t.Helper()
|
t.Helper()
|
||||||
newer := source
|
newer := source
|
||||||
newer.Created = newer.Created.AddDate(0, 0, 1)
|
newer.Created = newer.Created.AddDate(0, 0, 1)
|
||||||
writeFakeDestinationState(t, backend, "bundle", newer, testutil.DestinationStateOptions{})
|
testutil.WriteFakeDestinationState(t, backend, "bundle", newer, testutil.DestinationStateOptions{})
|
||||||
},
|
},
|
||||||
transfer: newerReplaceTransfer(),
|
transfer: newerReplaceTransfer(),
|
||||||
wantReason: "requires --force",
|
wantReason: "requires --force",
|
||||||
@@ -121,7 +119,7 @@ func TestBuildRequiresConflictPolicyForStateConflicts(t *testing.T) {
|
|||||||
destinationBackend := fake.New()
|
destinationBackend := fake.New()
|
||||||
conflict := sourceBundle.Manifest
|
conflict := sourceBundle.Manifest
|
||||||
conflict.ID = "other.source"
|
conflict.ID = "other.source"
|
||||||
writeFakeDestinationState(t, destinationBackend, "bundle", conflict, testutil.DestinationStateOptions{})
|
testutil.WriteFakeDestinationState(t, destinationBackend, "bundle", conflict, testutil.DestinationStateOptions{})
|
||||||
|
|
||||||
req := forceRequest(sourceBackend, destinationBackend, sourceBundle, defaultTransfer())
|
req := forceRequest(sourceBackend, destinationBackend, sourceBundle, defaultTransfer())
|
||||||
req.Force = true
|
req.Force = true
|
||||||
@@ -135,10 +133,10 @@ func TestExecuteForcedReplacementDeletesOnlyBundlePath(t *testing.T) {
|
|||||||
sourceBackend := fake.New()
|
sourceBackend := fake.New()
|
||||||
sourceBundle := testutil.WriteFakeSourceBundle(t, sourceBackend, "bundle", testutil.BundleOptions{})
|
sourceBundle := testutil.WriteFakeSourceBundle(t, sourceBackend, "bundle", testutil.BundleOptions{})
|
||||||
destinationBackend := fake.New()
|
destinationBackend := fake.New()
|
||||||
writeFakeFile(t, destinationBackend, "bundle/old.txt", "old")
|
testutil.WriteFakeFile(t, destinationBackend, "bundle/old.txt", "old")
|
||||||
writeFakeFile(t, destinationBackend, "bundle/nested/old.txt", "old")
|
testutil.WriteFakeFile(t, destinationBackend, "bundle/nested/old.txt", "old")
|
||||||
writeFakeFile(t, destinationBackend, "bundle-sibling/keep.txt", "keep")
|
testutil.WriteFakeFile(t, destinationBackend, "bundle-sibling/keep.txt", "keep")
|
||||||
writeFakeFile(t, destinationBackend, "outside.txt", "outside")
|
testutil.WriteFakeFile(t, destinationBackend, "outside.txt", "outside")
|
||||||
|
|
||||||
req := forceRequest(sourceBackend, destinationBackend, sourceBundle, defaultTransfer())
|
req := forceRequest(sourceBackend, destinationBackend, sourceBundle, defaultTransfer())
|
||||||
req.Force = true
|
req.Force = true
|
||||||
@@ -152,11 +150,11 @@ func TestExecuteForcedReplacementDeletesOnlyBundlePath(t *testing.T) {
|
|||||||
if err := Execute(context.Background(), req, plan); err != nil {
|
if err := Execute(context.Background(), req, plan); err != nil {
|
||||||
t.Fatalf("Execute() error = %v", err)
|
t.Fatalf("Execute() error = %v", err)
|
||||||
}
|
}
|
||||||
assertFakeFile(t, destinationBackend, "bundle/report.md", "# Report\nSunny.\n")
|
testutil.AssertFakeFile(t, destinationBackend, "bundle/report.md", "# Report\nSunny.\n")
|
||||||
assertFakeMissing(t, destinationBackend, "bundle/old.txt")
|
testutil.AssertFakeMissing(t, destinationBackend, "bundle/old.txt")
|
||||||
assertFakeMissing(t, destinationBackend, "bundle/nested/old.txt")
|
testutil.AssertFakeMissing(t, destinationBackend, "bundle/nested/old.txt")
|
||||||
assertFakeFile(t, destinationBackend, "bundle-sibling/keep.txt", "keep")
|
testutil.AssertFakeFile(t, destinationBackend, "bundle-sibling/keep.txt", "keep")
|
||||||
assertFakeFile(t, destinationBackend, "outside.txt", "outside")
|
testutil.AssertFakeFile(t, destinationBackend, "outside.txt", "outside")
|
||||||
}
|
}
|
||||||
|
|
||||||
func forceRequest(sourceBackend, destinationBackend *fake.Backend, sourceBundle bundle.Bundle, transfer config.TransferPolicy) Request {
|
func forceRequest(sourceBackend, destinationBackend *fake.Backend, sourceBundle bundle.Bundle, transfer config.TransferPolicy) Request {
|
||||||
@@ -193,49 +191,3 @@ func newerReplaceTransfer() config.TransferPolicy {
|
|||||||
transfer.OnDestinationNewer = config.TransferActionReplace
|
transfer.OnDestinationNewer = config.TransferActionReplace
|
||||||
return transfer
|
return transfer
|
||||||
}
|
}
|
||||||
|
|
||||||
func writeFakeDestinationState(t *testing.T, backend *fake.Backend, relative string, manifest bundle.Manifest, opts testutil.DestinationStateOptions) {
|
|
||||||
t.Helper()
|
|
||||||
destinationState := testutil.DestinationState(manifest, opts)
|
|
||||||
data, err := json.MarshalIndent(destinationState, "", " ")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("marshal destination state: %v", err)
|
|
||||||
}
|
|
||||||
statePath, err := storage.StatePath(relative)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("state path: %v", err)
|
|
||||||
}
|
|
||||||
writeFakeFile(t, backend, statePath, string(append(data, '\n')))
|
|
||||||
for _, output := range destinationState.Outputs {
|
|
||||||
path, err := storage.Join(relative, output.Path)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("join output path: %v", err)
|
|
||||||
}
|
|
||||||
writeFakeFile(t, backend, path, "old")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeFakeFile(t *testing.T, backend *fake.Backend, path, data string) {
|
|
||||||
t.Helper()
|
|
||||||
if _, err := backend.WriteFile(context.Background(), path, []byte(data), storage.WriteOptions{}); err != nil {
|
|
||||||
t.Fatalf("write fake file %s: %v", path, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func assertFakeFile(t *testing.T, backend *fake.Backend, path, want string) {
|
|
||||||
t.Helper()
|
|
||||||
data, err := backend.ReadFile(context.Background(), path)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("read fake file %s: %v", path, err)
|
|
||||||
}
|
|
||||||
if got := string(data); got != want {
|
|
||||||
t.Fatalf("fake file %s = %q, want %q", path, got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func assertFakeMissing(t *testing.T, backend *fake.Backend, path string) {
|
|
||||||
t.Helper()
|
|
||||||
if _, err := backend.Stat(context.Background(), path); !storage.IsNotFound(err) {
|
|
||||||
t.Fatalf("fake file %s stat error = %v, want not found", path, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
120
internal/publish/links.go
Normal file
120
internal/publish/links.go
Normal file
@@ -0,0 +1,120 @@
|
|||||||
|
package publish
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/config"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/link"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/state"
|
||||||
|
)
|
||||||
|
|
||||||
|
func PlanLinks(req Request, outputs []Output) ([]Output, string, error) {
|
||||||
|
if req.Links == nil {
|
||||||
|
return outputs, "", nil
|
||||||
|
}
|
||||||
|
if err := link.ValidateHTTPURL(req.Links.BaseURL); err != nil {
|
||||||
|
return nil, "", fmt.Errorf("link base URL: %w", err)
|
||||||
|
}
|
||||||
|
linked := make([]Output, 0, len(outputs))
|
||||||
|
for _, output := range outputs {
|
||||||
|
outputURL, err := OutputURL(req.Links.BaseURL, req.DestinationBundlePath, output.DestinationPath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
output.URL = outputURL
|
||||||
|
linked = append(linked, output)
|
||||||
|
}
|
||||||
|
return linked, primaryURL(linked, req.Links.Primary), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func OutputURL(baseURL, destinationBundlePath, outputPath string) (string, error) {
|
||||||
|
parsed, err := url.Parse(baseURL)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("link base URL: %w", err)
|
||||||
|
}
|
||||||
|
segments := pathSegments(parsed.Path)
|
||||||
|
segments = append(segments, pathSegments(destinationBundlePath)...)
|
||||||
|
outputSegments := pathSegments(outputPath)
|
||||||
|
trailingSlash := false
|
||||||
|
if len(outputSegments) > 0 && outputSegments[len(outputSegments)-1] == "index.html" {
|
||||||
|
outputSegments = outputSegments[:len(outputSegments)-1]
|
||||||
|
trailingSlash = true
|
||||||
|
}
|
||||||
|
segments = append(segments, outputSegments...)
|
||||||
|
parsed.Path = urlPath(segments, trailingSlash)
|
||||||
|
parsed.RawPath = ""
|
||||||
|
return parsed.String(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func pathSegments(value string) []string {
|
||||||
|
trimmed := strings.Trim(value, "/")
|
||||||
|
if trimmed == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return strings.Split(trimmed, "/")
|
||||||
|
}
|
||||||
|
|
||||||
|
func urlPath(segments []string, trailingSlash bool) string {
|
||||||
|
if len(segments) == 0 {
|
||||||
|
return "/"
|
||||||
|
}
|
||||||
|
path := "/" + strings.Join(segments, "/")
|
||||||
|
if trailingSlash && !strings.HasSuffix(path, "/") {
|
||||||
|
path += "/"
|
||||||
|
}
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
|
||||||
|
func primaryURL(outputs []Output, policy string) string {
|
||||||
|
switch policy {
|
||||||
|
case config.LinkPrimaryHTML:
|
||||||
|
return firstGeneratedHTMLURL(outputs)
|
||||||
|
case config.LinkPrimarySource:
|
||||||
|
return firstSourceURL(outputs)
|
||||||
|
default:
|
||||||
|
if url := firstIndexURL(outputs); url != "" {
|
||||||
|
return url
|
||||||
|
}
|
||||||
|
if url := firstGeneratedHTMLURL(outputs); url != "" {
|
||||||
|
return url
|
||||||
|
}
|
||||||
|
return firstSourceURL(outputs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func firstIndexURL(outputs []Output) string {
|
||||||
|
for _, output := range outputs {
|
||||||
|
if isIndexOutput(output.DestinationPath) {
|
||||||
|
return output.URL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func firstGeneratedHTMLURL(outputs []Output) string {
|
||||||
|
for _, output := range outputs {
|
||||||
|
if output.Kind == state.OutputKindGenerated && isHTMLOutput(output.DestinationPath) {
|
||||||
|
return output.URL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func firstSourceURL(outputs []Output) string {
|
||||||
|
for _, output := range outputs {
|
||||||
|
if output.Kind == state.OutputKindSource {
|
||||||
|
return output.URL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func isIndexOutput(path string) bool {
|
||||||
|
return path == "index.html" || strings.HasSuffix(path, "/index.html")
|
||||||
|
}
|
||||||
|
|
||||||
|
func isHTMLOutput(path string) bool {
|
||||||
|
return strings.HasSuffix(path, ".html")
|
||||||
|
}
|
||||||
169
internal/publish/links_test.go
Normal file
169
internal/publish/links_test.go
Normal file
@@ -0,0 +1,169 @@
|
|||||||
|
package publish
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/config"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/state"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestOutputURLUsesURLPathSemantics(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
baseURL string
|
||||||
|
destinationBundlePath string
|
||||||
|
outputPath string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "nested non index",
|
||||||
|
baseURL: "https://reports.example.com/archive",
|
||||||
|
destinationBundlePath: "daily/brentwood",
|
||||||
|
outputPath: "report.html",
|
||||||
|
want: "https://reports.example.com/archive/daily/brentwood/report.html",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "nested index",
|
||||||
|
baseURL: "https://reports.example.com/archive",
|
||||||
|
destinationBundlePath: "daily/brentwood",
|
||||||
|
outputPath: "index.html",
|
||||||
|
want: "https://reports.example.com/archive/daily/brentwood/",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "fixed index",
|
||||||
|
baseURL: "https://reports.example.com/latest",
|
||||||
|
destinationBundlePath: "",
|
||||||
|
outputPath: "index.html",
|
||||||
|
want: "https://reports.example.com/latest/",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "escaped segments",
|
||||||
|
baseURL: "https://reports.example.com/archive root",
|
||||||
|
destinationBundlePath: "daily reports",
|
||||||
|
outputPath: "morning report.html",
|
||||||
|
want: "https://reports.example.com/archive%20root/daily%20reports/morning%20report.html",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "nested output index",
|
||||||
|
baseURL: "https://reports.example.com",
|
||||||
|
destinationBundlePath: "daily",
|
||||||
|
outputPath: "site/index.html",
|
||||||
|
want: "https://reports.example.com/daily/site/",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got, err := OutputURL(tt.baseURL, tt.destinationBundlePath, tt.outputPath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("OutputURL() error = %v", err)
|
||||||
|
}
|
||||||
|
if got != tt.want {
|
||||||
|
t.Fatalf("OutputURL() = %q, want %q", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPlanLinksSelectsPrimaryURL(t *testing.T) {
|
||||||
|
outputs := []Output{
|
||||||
|
{
|
||||||
|
DestinationPath: "report.md",
|
||||||
|
Kind: state.OutputKindSource,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
DestinationPath: "report.html",
|
||||||
|
Kind: state.OutputKindGenerated,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
DestinationPath: "index.html",
|
||||||
|
Kind: state.OutputKindGenerated,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
primary string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{name: "auto prefers index", primary: config.LinkPrimaryAuto, want: "https://reports.example.com/daily/"},
|
||||||
|
{name: "html uses first generated html", primary: config.LinkPrimaryHTML, want: "https://reports.example.com/daily/report.html"},
|
||||||
|
{name: "source uses first source", primary: config.LinkPrimarySource, want: "https://reports.example.com/daily/report.md"},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
linked, primaryURL, err := PlanLinks(Request{
|
||||||
|
DestinationBundlePath: "daily",
|
||||||
|
Links: &config.Links{
|
||||||
|
BaseURL: "https://reports.example.com",
|
||||||
|
Primary: tt.primary,
|
||||||
|
},
|
||||||
|
}, outputs)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("PlanLinks() error = %v", err)
|
||||||
|
}
|
||||||
|
if primaryURL != tt.want {
|
||||||
|
t.Fatalf("primary URL = %q, want %q", primaryURL, tt.want)
|
||||||
|
}
|
||||||
|
for index, output := range linked {
|
||||||
|
if output.URL == "" {
|
||||||
|
t.Fatalf("linked output %d has empty URL", index)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPlanLinksReturnsNoPrimaryWhenPolicyHasNoMatch(t *testing.T) {
|
||||||
|
linked, primaryURL, err := PlanLinks(Request{
|
||||||
|
DestinationBundlePath: "daily",
|
||||||
|
Links: &config.Links{
|
||||||
|
BaseURL: "https://reports.example.com",
|
||||||
|
Primary: config.LinkPrimaryHTML,
|
||||||
|
},
|
||||||
|
}, []Output{{
|
||||||
|
DestinationPath: "report.md",
|
||||||
|
Kind: state.OutputKindSource,
|
||||||
|
}})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("PlanLinks() error = %v", err)
|
||||||
|
}
|
||||||
|
if primaryURL != "" {
|
||||||
|
t.Fatalf("primary URL = %q, want empty", primaryURL)
|
||||||
|
}
|
||||||
|
if linked[0].URL != "https://reports.example.com/daily/report.md" {
|
||||||
|
t.Fatalf("linked URL = %q", linked[0].URL)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPlanLinksLeavesOutputsUnchangedWithoutConfig(t *testing.T) {
|
||||||
|
outputs := []Output{{DestinationPath: "report.md", Kind: state.OutputKindSource}}
|
||||||
|
linked, primaryURL, err := PlanLinks(Request{}, outputs)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("PlanLinks() error = %v", err)
|
||||||
|
}
|
||||||
|
if primaryURL != "" {
|
||||||
|
t.Fatalf("primary URL = %q, want empty", primaryURL)
|
||||||
|
}
|
||||||
|
if linked[0].URL != "" {
|
||||||
|
t.Fatalf("output URL = %q, want empty", linked[0].URL)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPlanLinksValidatesBaseURLBeforePlanning(t *testing.T) {
|
||||||
|
_, _, err := PlanLinks(Request{
|
||||||
|
DestinationBundlePath: "daily",
|
||||||
|
Links: &config.Links{
|
||||||
|
BaseURL: "https://reports.example.com/archive?preview=1",
|
||||||
|
Primary: config.LinkPrimaryAuto,
|
||||||
|
},
|
||||||
|
}, []Output{{
|
||||||
|
DestinationPath: "report.md",
|
||||||
|
Kind: state.OutputKindSource,
|
||||||
|
}})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("PlanLinks() error = nil, want error")
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "link base URL: must not include a query string") {
|
||||||
|
t.Fatalf("PlanLinks() error = %q, want link base URL context", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -26,6 +26,10 @@ func PlanOutputs(ctx context.Context, req Request) ([]Output, error) {
|
|||||||
generatedOutputs, err := transformer.Generate(ctx, transform.Request{
|
generatedOutputs, err := transformer.Generate(ctx, transform.Request{
|
||||||
SourceBundle: req.SourceBundle,
|
SourceBundle: req.SourceBundle,
|
||||||
SourceBackend: req.SourceBackend,
|
SourceBackend: req.SourceBackend,
|
||||||
|
Markdown: transform.MarkdownOptions{
|
||||||
|
Mode: req.Transform.MarkdownToHTML.Mode,
|
||||||
|
Input: req.Transform.MarkdownToHTML.Input,
|
||||||
|
},
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -93,25 +97,42 @@ func rejectOutputCollisions(outputs []Output) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func stateOutputs(outputs []Output) []state.OutputFile {
|
func (o Output) StateOutputFile() state.OutputFile {
|
||||||
|
return state.OutputFile{
|
||||||
|
Path: o.DestinationPath,
|
||||||
|
Kind: o.Kind,
|
||||||
|
SourcePath: o.SourcePath,
|
||||||
|
Transform: o.Transform,
|
||||||
|
URL: o.URL,
|
||||||
|
SHA256: o.SHA256,
|
||||||
|
Size: o.Size,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o Output) ManagedPath() string {
|
||||||
|
return o.DestinationPath
|
||||||
|
}
|
||||||
|
|
||||||
|
func StateOutputFiles(outputs []Output) []state.OutputFile {
|
||||||
files := make([]state.OutputFile, 0, len(outputs))
|
files := make([]state.OutputFile, 0, len(outputs))
|
||||||
for _, output := range outputs {
|
for _, output := range outputs {
|
||||||
files = append(files, state.OutputFile{
|
files = append(files, output.StateOutputFile())
|
||||||
Path: output.DestinationPath,
|
|
||||||
Kind: output.Kind,
|
|
||||||
SourcePath: output.SourcePath,
|
|
||||||
Transform: output.Transform,
|
|
||||||
SHA256: output.SHA256,
|
|
||||||
Size: output.Size,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
return files
|
return files
|
||||||
}
|
}
|
||||||
|
|
||||||
func managedOutputPaths(outputs []Output) []string {
|
func ManagedOutputPaths(outputs []Output) []string {
|
||||||
paths := make([]string, 0, len(outputs))
|
paths := make([]string, 0, len(outputs))
|
||||||
for _, output := range outputs {
|
for _, output := range outputs {
|
||||||
paths = append(paths, output.DestinationPath)
|
paths = append(paths, output.ManagedPath())
|
||||||
|
}
|
||||||
|
return paths
|
||||||
|
}
|
||||||
|
|
||||||
|
func stateOutputManagedPaths(outputs []state.OutputFile) []string {
|
||||||
|
paths := make([]string, 0, len(outputs))
|
||||||
|
for _, output := range outputs {
|
||||||
|
paths = append(paths, output.Path)
|
||||||
}
|
}
|
||||||
return paths
|
return paths
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,11 +6,58 @@ import (
|
|||||||
|
|
||||||
"gitea.maximumdirect.net/eric/distributor/internal/bundle"
|
"gitea.maximumdirect.net/eric/distributor/internal/bundle"
|
||||||
"gitea.maximumdirect.net/eric/distributor/internal/config"
|
"gitea.maximumdirect.net/eric/distributor/internal/config"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/state"
|
||||||
"gitea.maximumdirect.net/eric/distributor/internal/storage/fake"
|
"gitea.maximumdirect.net/eric/distributor/internal/storage/fake"
|
||||||
"gitea.maximumdirect.net/eric/distributor/internal/testutil"
|
"gitea.maximumdirect.net/eric/distributor/internal/testutil"
|
||||||
"gitea.maximumdirect.net/eric/distributor/internal/transform"
|
"gitea.maximumdirect.net/eric/distributor/internal/transform"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestOutputStateProjection(t *testing.T) {
|
||||||
|
sourceOutput := Output{
|
||||||
|
SourcePath: "report.md",
|
||||||
|
DestinationPath: "report.md",
|
||||||
|
Kind: state.OutputKindSource,
|
||||||
|
URL: "https://reports.example.com/report.md",
|
||||||
|
SHA256: "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||||
|
Size: 123,
|
||||||
|
}
|
||||||
|
sourceState := sourceOutput.StateOutputFile()
|
||||||
|
if sourceState.Path != "report.md" || sourceState.Kind != state.OutputKindSource || sourceState.SourcePath != "report.md" || sourceState.URL != sourceOutput.URL || sourceState.SHA256 != sourceOutput.SHA256 || sourceState.Size != sourceOutput.Size {
|
||||||
|
t.Fatalf("source state output = %#v", sourceState)
|
||||||
|
}
|
||||||
|
|
||||||
|
generatedOutput := Output{
|
||||||
|
SourcePath: "report.md",
|
||||||
|
DestinationPath: "report.html",
|
||||||
|
Kind: state.OutputKindGenerated,
|
||||||
|
Transform: transform.MarkdownToHTML,
|
||||||
|
URL: "https://reports.example.com/report.html",
|
||||||
|
SHA256: "sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
|
||||||
|
Size: 456,
|
||||||
|
}
|
||||||
|
generatedState := generatedOutput.StateOutputFile()
|
||||||
|
if generatedState.Path != "report.html" || generatedState.Kind != state.OutputKindGenerated || generatedState.SourcePath != "report.md" || generatedState.Transform != transform.MarkdownToHTML || generatedState.URL != generatedOutput.URL || generatedState.SHA256 != generatedOutput.SHA256 || generatedState.Size != generatedOutput.Size {
|
||||||
|
t.Fatalf("generated state output = %#v", generatedState)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOutputSliceProjections(t *testing.T) {
|
||||||
|
outputs := []Output{
|
||||||
|
{SourcePath: "report.md", DestinationPath: "report.md", Kind: state.OutputKindSource, SHA256: "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", Size: 1},
|
||||||
|
{SourcePath: "report.md", DestinationPath: "report.html", Kind: state.OutputKindGenerated, Transform: transform.MarkdownToHTML, URL: "https://reports.example.com/report.html", SHA256: "sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", Size: 2},
|
||||||
|
}
|
||||||
|
|
||||||
|
stateOutputs := StateOutputFiles(outputs)
|
||||||
|
if len(stateOutputs) != 2 || stateOutputs[1].Path != "report.html" || stateOutputs[1].Transform != transform.MarkdownToHTML || stateOutputs[1].URL != outputs[1].URL {
|
||||||
|
t.Fatalf("state outputs = %#v", stateOutputs)
|
||||||
|
}
|
||||||
|
|
||||||
|
paths := ManagedOutputPaths(outputs)
|
||||||
|
if len(paths) != 2 || paths[0] != "report.md" || paths[1] != "report.html" {
|
||||||
|
t.Fatalf("managed paths = %#v", paths)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestPlanOutputsRejectsCollision(t *testing.T) {
|
func TestPlanOutputsRejectsCollision(t *testing.T) {
|
||||||
sourceBackend := fake.New()
|
sourceBackend := fake.New()
|
||||||
sourceBundle := testutil.WriteFakeSourceBundle(t, sourceBackend, "", testutil.BundleOptions{
|
sourceBundle := testutil.WriteFakeSourceBundle(t, sourceBackend, "", testutil.BundleOptions{
|
||||||
@@ -103,6 +150,35 @@ func TestPlanOutputsUsesRegisteredTransformer(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestPlanOutputsPassesMarkdownOptions(t *testing.T) {
|
||||||
|
data := []byte("<p>Generated</p>\n")
|
||||||
|
transformer := &recordingTransformer{outputs: []transform.Output{{
|
||||||
|
Path: "index.html",
|
||||||
|
SourcePath: "report.md",
|
||||||
|
Transform: transform.MarkdownToHTML,
|
||||||
|
Data: data,
|
||||||
|
SHA256: bundle.FileDigest(data),
|
||||||
|
Size: int64(len(data)),
|
||||||
|
}}}
|
||||||
|
|
||||||
|
_, err := PlanOutputs(context.Background(), Request{
|
||||||
|
Publish: config.PublishPolicy{HTML: true},
|
||||||
|
Transform: config.Transform{MarkdownToHTML: &config.MarkdownToHTML{
|
||||||
|
Enabled: true,
|
||||||
|
Mode: config.TransformModeIndex,
|
||||||
|
Input: "report.md",
|
||||||
|
}},
|
||||||
|
Transformers: testResolver{transform.MarkdownToHTML: transformer},
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("PlanOutputs() error = %v", err)
|
||||||
|
}
|
||||||
|
if transformer.request.Markdown.Mode != config.TransformModeIndex || transformer.request.Markdown.Input != "report.md" {
|
||||||
|
t.Fatalf("markdown options = %#v, want index/report.md", transformer.request.Markdown)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestBuildRejectsHTMLWithoutTransform(t *testing.T) {
|
func TestBuildRejectsHTMLWithoutTransform(t *testing.T) {
|
||||||
sourceBackend := fake.New()
|
sourceBackend := fake.New()
|
||||||
destinationBackend := fake.New()
|
destinationBackend := fake.New()
|
||||||
@@ -148,6 +224,14 @@ func TestValidateRequestChecksPublishTransformPolicy(t *testing.T) {
|
|||||||
Mode: config.TransformModeSidecar,
|
Mode: config.TransformModeSidecar,
|
||||||
}},
|
}},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "html only index allowed",
|
||||||
|
publish: config.PublishPolicy{HTML: true},
|
||||||
|
transform: config.Transform{MarkdownToHTML: &config.MarkdownToHTML{
|
||||||
|
Enabled: true,
|
||||||
|
Mode: config.TransformModeIndex,
|
||||||
|
}},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "source and html sidecar allowed",
|
name: "source and html sidecar allowed",
|
||||||
publish: config.PublishPolicy{Source: true, HTML: true},
|
publish: config.PublishPolicy{Source: true, HTML: true},
|
||||||
@@ -184,6 +268,15 @@ func TestValidateRequestChecksPublishTransformPolicy(t *testing.T) {
|
|||||||
}},
|
}},
|
||||||
wantErr: true,
|
wantErr: true,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "source only enabled transform rejected",
|
||||||
|
publish: config.PublishPolicy{Source: true},
|
||||||
|
transform: config.Transform{MarkdownToHTML: &config.MarkdownToHTML{
|
||||||
|
Enabled: true,
|
||||||
|
Mode: config.TransformModeSidecar,
|
||||||
|
}},
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "enabled markdown wrong mode rejected",
|
name: "enabled markdown wrong mode rejected",
|
||||||
publish: config.PublishPolicy{Source: true},
|
publish: config.PublishPolicy{Source: true},
|
||||||
@@ -253,3 +346,14 @@ type testTransformer struct {
|
|||||||
func (t testTransformer) Generate(context.Context, transform.Request) ([]transform.Output, error) {
|
func (t testTransformer) Generate(context.Context, transform.Request) ([]transform.Output, error) {
|
||||||
return t.outputs, t.err
|
return t.outputs, t.err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type recordingTransformer struct {
|
||||||
|
outputs []transform.Output
|
||||||
|
request transform.Request
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *recordingTransformer) Generate(_ context.Context, req transform.Request) ([]transform.Output, error) {
|
||||||
|
t.request = req
|
||||||
|
return t.outputs, t.err
|
||||||
|
}
|
||||||
|
|||||||
@@ -30,8 +30,10 @@ type Request struct {
|
|||||||
SourceBackend storage.Backend
|
SourceBackend storage.Backend
|
||||||
DestinationBackend storage.Backend
|
DestinationBackend storage.Backend
|
||||||
DestinationBundlePath string
|
DestinationBundlePath string
|
||||||
|
PathMapping string
|
||||||
Publish config.PublishPolicy
|
Publish config.PublishPolicy
|
||||||
Transform config.Transform
|
Transform config.Transform
|
||||||
|
Links *config.Links
|
||||||
Transformers TransformerResolver
|
Transformers TransformerResolver
|
||||||
Transfer config.TransferPolicy
|
Transfer config.TransferPolicy
|
||||||
DistributorVersion string
|
DistributorVersion string
|
||||||
@@ -48,9 +50,11 @@ type Plan struct {
|
|||||||
BundleID string
|
BundleID string
|
||||||
BundlePath string
|
BundlePath string
|
||||||
DestinationBundlePath string
|
DestinationBundlePath string
|
||||||
|
PathMapping string
|
||||||
Action Action
|
Action Action
|
||||||
Reason string
|
Reason string
|
||||||
Force bool
|
Force bool
|
||||||
|
PrimaryURL string
|
||||||
Outputs []Output
|
Outputs []Output
|
||||||
ExistingState *state.DistributorState
|
ExistingState *state.DistributorState
|
||||||
}
|
}
|
||||||
@@ -60,6 +64,7 @@ type Output struct {
|
|||||||
DestinationPath string
|
DestinationPath string
|
||||||
Kind string
|
Kind string
|
||||||
Transform string
|
Transform string
|
||||||
|
URL string
|
||||||
Data []byte
|
Data []byte
|
||||||
SHA256 string
|
SHA256 string
|
||||||
Size int64
|
Size int64
|
||||||
@@ -73,11 +78,15 @@ func Build(ctx context.Context, req Request) (Plan, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return Plan{}, err
|
return Plan{}, err
|
||||||
}
|
}
|
||||||
|
outputs, primaryURL, err := PlanLinks(req, outputs)
|
||||||
|
if err != nil {
|
||||||
|
return Plan{}, err
|
||||||
|
}
|
||||||
status, err := inspectDestination(ctx, req.DestinationBackend, req.DestinationBundlePath)
|
status, err := inspectDestination(ctx, req.DestinationBackend, req.DestinationBundlePath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Plan{}, err
|
return Plan{}, err
|
||||||
}
|
}
|
||||||
comparison := state.Compare(req.SourceBundle.Manifest, req.PipelineID, req.DestinationID, status)
|
comparison := compareDestination(req, status)
|
||||||
action, reason := actionForComparison(comparison, req.Transfer, req.Force)
|
action, reason := actionForComparison(comparison, req.Transfer, req.Force)
|
||||||
plan := Plan{
|
plan := Plan{
|
||||||
PipelineID: req.PipelineID,
|
PipelineID: req.PipelineID,
|
||||||
@@ -85,9 +94,11 @@ func Build(ctx context.Context, req Request) (Plan, error) {
|
|||||||
BundleID: req.SourceBundle.Manifest.ID,
|
BundleID: req.SourceBundle.Manifest.ID,
|
||||||
BundlePath: req.SourceBundle.RootRelativePath,
|
BundlePath: req.SourceBundle.RootRelativePath,
|
||||||
DestinationBundlePath: req.DestinationBundlePath,
|
DestinationBundlePath: req.DestinationBundlePath,
|
||||||
|
PathMapping: req.PathMapping,
|
||||||
Action: action,
|
Action: action,
|
||||||
Reason: reason,
|
Reason: reason,
|
||||||
Force: action == ActionForceReplace,
|
Force: action == ActionForceReplace,
|
||||||
|
PrimaryURL: primaryURL,
|
||||||
Outputs: outputs,
|
Outputs: outputs,
|
||||||
ExistingState: status.State,
|
ExistingState: status.State,
|
||||||
}
|
}
|
||||||
@@ -116,6 +127,21 @@ func validateRequest(req Request) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func compareDestination(req Request, status state.DestinationStatus) state.Comparison {
|
||||||
|
comparison := state.Compare(req.SourceBundle.Manifest, req.PipelineID, req.DestinationID, status)
|
||||||
|
if req.PathMapping != config.PathMappingFixed || comparison.Outcome != state.OutcomeDifferentSourceConflict || status.State == nil {
|
||||||
|
return comparison
|
||||||
|
}
|
||||||
|
destinationManifest := status.State.Source.Manifest
|
||||||
|
if destinationManifest.Created.Before(req.SourceBundle.Manifest.Created) {
|
||||||
|
return state.Comparison{Outcome: state.OutcomeDestinationOlder, Reason: "fixed destination source is older than selected source"}
|
||||||
|
}
|
||||||
|
if destinationManifest.Created.After(req.SourceBundle.Manifest.Created) {
|
||||||
|
return state.Comparison{Outcome: state.OutcomeDestinationNewer, Reason: "fixed destination source is newer than selected source"}
|
||||||
|
}
|
||||||
|
return comparison
|
||||||
|
}
|
||||||
|
|
||||||
func actionForComparison(comparison state.Comparison, transfer config.TransferPolicy, force bool) (Action, string) {
|
func actionForComparison(comparison state.Comparison, transfer config.TransferPolicy, force bool) (Action, string) {
|
||||||
switch comparison.Outcome {
|
switch comparison.Outcome {
|
||||||
case state.OutcomeDestinationAbsent:
|
case state.OutcomeDestinationAbsent:
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ type DistributorState struct {
|
|||||||
DestinationID string
|
DestinationID string
|
||||||
PublishedAt time.Time
|
PublishedAt time.Time
|
||||||
Source SourceState
|
Source SourceState
|
||||||
|
Links *LinkState
|
||||||
Outputs []OutputFile
|
Outputs []OutputFile
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -26,11 +27,16 @@ type SourceState struct {
|
|||||||
Manifest bundle.Manifest
|
Manifest bundle.Manifest
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type LinkState struct {
|
||||||
|
PrimaryURL string
|
||||||
|
}
|
||||||
|
|
||||||
type OutputFile struct {
|
type OutputFile struct {
|
||||||
Path string
|
Path string
|
||||||
Kind string
|
Kind string
|
||||||
SourcePath string
|
SourcePath string
|
||||||
Transform string
|
Transform string
|
||||||
|
URL string
|
||||||
SHA256 string
|
SHA256 string
|
||||||
Size int64
|
Size int64
|
||||||
}
|
}
|
||||||
@@ -42,6 +48,7 @@ type rawDistributorState struct {
|
|||||||
DestinationID *string `json:"destination_id"`
|
DestinationID *string `json:"destination_id"`
|
||||||
PublishedAt *string `json:"published_at"`
|
PublishedAt *string `json:"published_at"`
|
||||||
Source *rawSourceState `json:"source"`
|
Source *rawSourceState `json:"source"`
|
||||||
|
Links *rawLinkState `json:"links"`
|
||||||
Outputs []rawOutputFile `json:"outputs"`
|
Outputs []rawOutputFile `json:"outputs"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,11 +56,16 @@ type rawSourceState struct {
|
|||||||
Manifest json.RawMessage `json:"manifest"`
|
Manifest json.RawMessage `json:"manifest"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type rawLinkState struct {
|
||||||
|
PrimaryURL string `json:"primary_url"`
|
||||||
|
}
|
||||||
|
|
||||||
type rawOutputFile struct {
|
type rawOutputFile struct {
|
||||||
Path *string `json:"path"`
|
Path *string `json:"path"`
|
||||||
Kind *string `json:"kind"`
|
Kind *string `json:"kind"`
|
||||||
SourcePath *string `json:"source_path"`
|
SourcePath *string `json:"source_path"`
|
||||||
Transform string `json:"transform"`
|
Transform string `json:"transform"`
|
||||||
|
URL string `json:"url"`
|
||||||
SHA256 *string `json:"sha256"`
|
SHA256 *string `json:"sha256"`
|
||||||
Size *int64 `json:"size"`
|
Size *int64 `json:"size"`
|
||||||
}
|
}
|
||||||
@@ -112,6 +124,9 @@ func parseRaw(raw rawDistributorState) (DistributorState, error) {
|
|||||||
return DistributorState{}, fmt.Errorf("state source.manifest: %w", err)
|
return DistributorState{}, fmt.Errorf("state source.manifest: %w", err)
|
||||||
}
|
}
|
||||||
state.Source.Manifest = manifest
|
state.Source.Manifest = manifest
|
||||||
|
if raw.Links != nil {
|
||||||
|
state.Links = &LinkState{PrimaryURL: raw.Links.PrimaryURL}
|
||||||
|
}
|
||||||
if raw.Outputs == nil {
|
if raw.Outputs == nil {
|
||||||
return DistributorState{}, fmt.Errorf("state outputs is required")
|
return DistributorState{}, fmt.Errorf("state outputs is required")
|
||||||
}
|
}
|
||||||
@@ -161,6 +176,7 @@ func parseOutput(index int, raw rawOutputFile) (OutputFile, error) {
|
|||||||
Kind: *raw.Kind,
|
Kind: *raw.Kind,
|
||||||
SourcePath: *raw.SourcePath,
|
SourcePath: *raw.SourcePath,
|
||||||
Transform: raw.Transform,
|
Transform: raw.Transform,
|
||||||
|
URL: raw.URL,
|
||||||
SHA256: *raw.SHA256,
|
SHA256: *raw.SHA256,
|
||||||
Size: *raw.Size,
|
Size: *raw.Size,
|
||||||
}, nil
|
}, nil
|
||||||
@@ -181,6 +197,7 @@ func (s DistributorState) MarshalJSON() ([]byte, error) {
|
|||||||
DestinationID string `json:"destination_id"`
|
DestinationID string `json:"destination_id"`
|
||||||
PublishedAt string `json:"published_at"`
|
PublishedAt string `json:"published_at"`
|
||||||
Source sourceJSON `json:"source"`
|
Source sourceJSON `json:"source"`
|
||||||
|
Links *LinkState `json:"links,omitempty"`
|
||||||
Outputs []OutputFile `json:"outputs"`
|
Outputs []OutputFile `json:"outputs"`
|
||||||
}
|
}
|
||||||
return json.Marshal(stateJSON{
|
return json.Marshal(stateJSON{
|
||||||
@@ -190,16 +207,25 @@ func (s DistributorState) MarshalJSON() ([]byte, error) {
|
|||||||
DestinationID: s.DestinationID,
|
DestinationID: s.DestinationID,
|
||||||
PublishedAt: s.PublishedAtString(),
|
PublishedAt: s.PublishedAtString(),
|
||||||
Source: sourceJSON{Manifest: s.Source.Manifest},
|
Source: sourceJSON{Manifest: s.Source.Manifest},
|
||||||
|
Links: s.Links,
|
||||||
Outputs: s.Outputs,
|
Outputs: s.Outputs,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (l LinkState) MarshalJSON() ([]byte, error) {
|
||||||
|
type linkJSON struct {
|
||||||
|
PrimaryURL string `json:"primary_url,omitempty"`
|
||||||
|
}
|
||||||
|
return json.Marshal(linkJSON{PrimaryURL: l.PrimaryURL})
|
||||||
|
}
|
||||||
|
|
||||||
func (o OutputFile) MarshalJSON() ([]byte, error) {
|
func (o OutputFile) MarshalJSON() ([]byte, error) {
|
||||||
type outputJSON struct {
|
type outputJSON struct {
|
||||||
Path string `json:"path"`
|
Path string `json:"path"`
|
||||||
Kind string `json:"kind"`
|
Kind string `json:"kind"`
|
||||||
SourcePath string `json:"source_path"`
|
SourcePath string `json:"source_path"`
|
||||||
Transform string `json:"transform,omitempty"`
|
Transform string `json:"transform,omitempty"`
|
||||||
|
URL string `json:"url,omitempty"`
|
||||||
SHA256 string `json:"sha256"`
|
SHA256 string `json:"sha256"`
|
||||||
Size int64 `json:"size"`
|
Size int64 `json:"size"`
|
||||||
}
|
}
|
||||||
@@ -208,6 +234,7 @@ func (o OutputFile) MarshalJSON() ([]byte, error) {
|
|||||||
Kind: o.Kind,
|
Kind: o.Kind,
|
||||||
SourcePath: o.SourcePath,
|
SourcePath: o.SourcePath,
|
||||||
Transform: o.Transform,
|
Transform: o.Transform,
|
||||||
|
URL: o.URL,
|
||||||
SHA256: o.SHA256,
|
SHA256: o.SHA256,
|
||||||
Size: o.Size,
|
Size: o.Size,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -29,6 +29,22 @@ func TestParseValidState(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestParseValidStateWithLinks(t *testing.T) {
|
||||||
|
body := strings.Replace(validStateJSON(t), `"outputs": [`, `"links": {"primary_url": "https://reports.example.com/archive/report.md"},`+"\n "+`"outputs": [`, 1)
|
||||||
|
body = strings.Replace(body, `"source_path": "report.md",`, `"source_path": "report.md",`+"\n "+`"url": "https://reports.example.com/archive/report.md",`, 1)
|
||||||
|
|
||||||
|
state, err := Parse([]byte(body))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Parse() error = %v", err)
|
||||||
|
}
|
||||||
|
if state.Links == nil || state.Links.PrimaryURL != "https://reports.example.com/archive/report.md" {
|
||||||
|
t.Fatalf("links = %#v, want primary URL", state.Links)
|
||||||
|
}
|
||||||
|
if state.Outputs[0].URL != "https://reports.example.com/archive/report.md" {
|
||||||
|
t.Fatalf("output URL = %q", state.Outputs[0].URL)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestParseNormalizesPublishedAtOffset(t *testing.T) {
|
func TestParseNormalizesPublishedAtOffset(t *testing.T) {
|
||||||
body := strings.Replace(validStateJSON(t), `"published_at": "2026-05-30T11:12:00Z"`, `"published_at": "2026-05-30T13:12:00+02:00"`, 1)
|
body := strings.Replace(validStateJSON(t), `"published_at": "2026-05-30T11:12:00Z"`, `"published_at": "2026-05-30T13:12:00+02:00"`, 1)
|
||||||
state, err := Parse([]byte(body))
|
state, err := Parse([]byte(body))
|
||||||
@@ -145,6 +161,12 @@ func TestParseRejectsInvalidOutputMetadata(t *testing.T) {
|
|||||||
"negative size": func(s *DistributorState) {
|
"negative size": func(s *DistributorState) {
|
||||||
s.Outputs[0].Size = -1
|
s.Outputs[0].Size = -1
|
||||||
},
|
},
|
||||||
|
"invalid output url": func(s *DistributorState) {
|
||||||
|
s.Outputs[0].URL = "file:///tmp/report.md"
|
||||||
|
},
|
||||||
|
"invalid primary url": func(s *DistributorState) {
|
||||||
|
s.Links = &LinkState{PrimaryURL: "file:///tmp/report.md"}
|
||||||
|
},
|
||||||
}
|
}
|
||||||
for name, mutate := range tests {
|
for name, mutate := range tests {
|
||||||
t.Run(name, func(t *testing.T) {
|
t.Run(name, func(t *testing.T) {
|
||||||
@@ -157,6 +179,23 @@ func TestParseRejectsInvalidOutputMetadata(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestValidateReportsURLFieldContext(t *testing.T) {
|
||||||
|
source := validManifest(t)
|
||||||
|
state := *withState(t, source, func(s *DistributorState) {
|
||||||
|
s.Links = &LinkState{PrimaryURL: "https://reports.example.com/archive#top"}
|
||||||
|
})
|
||||||
|
err := Validate(state)
|
||||||
|
assertStateErrorContains(t, err, "state links.primary_url")
|
||||||
|
assertStateErrorContains(t, err, "must not include a fragment")
|
||||||
|
|
||||||
|
state = *withState(t, source, func(s *DistributorState) {
|
||||||
|
s.Outputs[0].URL = "https://reports.example.com/archive?preview=1"
|
||||||
|
})
|
||||||
|
err = Validate(state)
|
||||||
|
assertStateErrorContains(t, err, "state outputs[0].url")
|
||||||
|
assertStateErrorContains(t, err, "must not include a query string")
|
||||||
|
}
|
||||||
|
|
||||||
func TestParseRejectsMalformedPublishedTimestamp(t *testing.T) {
|
func TestParseRejectsMalformedPublishedTimestamp(t *testing.T) {
|
||||||
body := strings.Replace(validStateJSON(t), `"published_at": "2026-05-30T11:12:00Z"`, `"published_at": "May 30"`, 1)
|
body := strings.Replace(validStateJSON(t), `"published_at": "2026-05-30T11:12:00Z"`, `"published_at": "May 30"`, 1)
|
||||||
_, err := Parse([]byte(body))
|
_, err := Parse([]byte(body))
|
||||||
@@ -188,6 +227,36 @@ func TestMarshalNormalizesPublishedAtUTC(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestMarshalIncludesLinksWhenPresent(t *testing.T) {
|
||||||
|
source := validManifest(t)
|
||||||
|
state := DistributorState{
|
||||||
|
SchemaVersion: SchemaVersion,
|
||||||
|
PipelineID: "reports",
|
||||||
|
DestinationID: "archive",
|
||||||
|
PublishedAt: time.Date(2026, 5, 30, 11, 12, 0, 0, time.UTC),
|
||||||
|
Source: SourceState{Manifest: source},
|
||||||
|
Links: &LinkState{PrimaryURL: "https://reports.example.com/archive/report.md"},
|
||||||
|
Outputs: []OutputFile{{
|
||||||
|
Path: "report.md",
|
||||||
|
Kind: OutputKindSource,
|
||||||
|
SourcePath: "report.md",
|
||||||
|
URL: "https://reports.example.com/archive/report.md",
|
||||||
|
SHA256: source.Files[0].SHA256,
|
||||||
|
Size: source.Files[0].Size,
|
||||||
|
}},
|
||||||
|
}
|
||||||
|
data, err := json.Marshal(state)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Marshal() error = %v", err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(data), `"links":{"primary_url":"https://reports.example.com/archive/report.md"}`) {
|
||||||
|
t.Fatalf("json = %s, want links primary URL", data)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(data), `"url":"https://reports.example.com/archive/report.md"`) {
|
||||||
|
t.Fatalf("json = %s, want output URL", data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func validStateJSON(t *testing.T) string {
|
func validStateJSON(t *testing.T) string {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
return validStateWithManifestJSON(t, manifestJSON(t))
|
return validStateWithManifestJSON(t, manifestJSON(t))
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/distributor/internal/bundle"
|
"gitea.maximumdirect.net/eric/distributor/internal/bundle"
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/internal/link"
|
||||||
"gitea.maximumdirect.net/eric/distributor/internal/storage"
|
"gitea.maximumdirect.net/eric/distributor/internal/storage"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -28,6 +29,11 @@ func Validate(s DistributorState) error {
|
|||||||
if err := validateEmbeddedManifest(s.Source.Manifest); err != nil {
|
if err := validateEmbeddedManifest(s.Source.Manifest); err != nil {
|
||||||
return fmt.Errorf("state source.manifest: %w", err)
|
return fmt.Errorf("state source.manifest: %w", err)
|
||||||
}
|
}
|
||||||
|
if s.Links != nil && s.Links.PrimaryURL != "" {
|
||||||
|
if err := link.ValidateHTTPURL(s.Links.PrimaryURL); err != nil {
|
||||||
|
return fmt.Errorf("state links.primary_url: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
if s.Outputs == nil {
|
if s.Outputs == nil {
|
||||||
return fmt.Errorf("state outputs is required")
|
return fmt.Errorf("state outputs is required")
|
||||||
}
|
}
|
||||||
@@ -63,6 +69,11 @@ func validateOutput(index int, output OutputFile) error {
|
|||||||
if output.Kind == OutputKindGenerated && output.Transform == "" {
|
if output.Kind == OutputKindGenerated && output.Transform == "" {
|
||||||
return fmt.Errorf("state outputs[%d].transform is required for generated output", index)
|
return fmt.Errorf("state outputs[%d].transform is required for generated output", index)
|
||||||
}
|
}
|
||||||
|
if output.URL != "" {
|
||||||
|
if err := link.ValidateHTTPURL(output.URL); err != nil {
|
||||||
|
return fmt.Errorf("state outputs[%d].url: %w", index, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
if err := bundle.ValidateDigest(output.SHA256); err != nil {
|
if err := bundle.ValidateDigest(output.SHA256); err != nil {
|
||||||
return fmt.Errorf("state outputs[%d].sha256: %w", index, err)
|
return fmt.Errorf("state outputs[%d].sha256: %w", index, err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package fake
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"io"
|
"io"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -133,14 +132,14 @@ func (b *Backend) Walk(ctx context.Context, prefix string, opts storage.WalkOpti
|
|||||||
if err := storage.ValidatePrefix(prefix); err != nil {
|
if err := storage.ValidatePrefix(prefix); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
emitter := storage.NewWalkEmitter(ctx, backendName, opts, fn)
|
||||||
if entry, err := b.Stat(ctx, prefix); err == nil && entry.Type != storage.EntryTypeDirectory {
|
if entry, err := b.Stat(ctx, prefix); err == nil && entry.Type != storage.EntryTypeDirectory {
|
||||||
return emit(ctx, entry, opts, fn)
|
return storage.FinishWalk(emitter.Emit(entry))
|
||||||
} else if err != nil && !storage.IsNotFound(err) {
|
} else if err != nil && !storage.IsNotFound(err) {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
entries := b.entries()
|
entries := b.entries()
|
||||||
visited := 0
|
|
||||||
for _, entry := range entries {
|
for _, entry := range entries {
|
||||||
if entry.Path == "" || !entryBelow(prefix, entry.Path) {
|
if entry.Path == "" || !entryBelow(prefix, entry.Path) {
|
||||||
continue
|
continue
|
||||||
@@ -148,33 +147,15 @@ func (b *Backend) Walk(ctx context.Context, prefix string, opts storage.WalkOpti
|
|||||||
if !opts.Recursive && !isImmediateChild(prefix, entry.Path) {
|
if !opts.Recursive && !isImmediateChild(prefix, entry.Path) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if opts.Limit > 0 && visited >= opts.Limit {
|
if err := emitter.Emit(entry); err != nil {
|
||||||
return nil
|
return storage.FinishWalk(err)
|
||||||
}
|
|
||||||
visited++
|
|
||||||
if err := ctx.Err(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := fn(entry); err != nil {
|
|
||||||
if errors.Is(err, storage.ErrStopWalk) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return storage.NewError(storage.OpWalk, backendName, entry.Path, storage.ErrUnknown, err)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Backend) HasAny(ctx context.Context, prefix string) (bool, error) {
|
func (b *Backend) HasAny(ctx context.Context, prefix string) (bool, error) {
|
||||||
found := false
|
return storage.HasAny(ctx, b, prefix)
|
||||||
err := b.Walk(ctx, prefix, storage.WalkOptions{Recursive: false, Limit: 1}, func(storage.Entry) error {
|
|
||||||
found = true
|
|
||||||
return storage.ErrStopWalk
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return false, err
|
|
||||||
}
|
|
||||||
return found, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Backend) DeleteManagedBundle(ctx context.Context, bundlePath string, managedOutputPaths []string, opts storage.DeleteOptions) error {
|
func (b *Backend) DeleteManagedBundle(ctx context.Context, bundlePath string, managedOutputPaths []string, opts storage.DeleteOptions) error {
|
||||||
@@ -302,19 +283,6 @@ func (b *Backend) entries() []storage.Entry {
|
|||||||
return entries
|
return entries
|
||||||
}
|
}
|
||||||
|
|
||||||
func emit(ctx context.Context, entry storage.Entry, opts storage.WalkOptions, fn storage.WalkFunc) error {
|
|
||||||
if opts.Limit > 0 && opts.Limit < 1 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if err := ctx.Err(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := fn(entry); err != nil && !errors.Is(err, storage.ErrStopWalk) {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func entryBelow(prefix, path string) bool {
|
func entryBelow(prefix, path string) bool {
|
||||||
if prefix == "" {
|
if prefix == "" {
|
||||||
return path != ""
|
return path != ""
|
||||||
|
|||||||
63
internal/storage/walk.go
Normal file
63
internal/storage/walk.go
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
package storage
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
type WalkEmitter struct {
|
||||||
|
ctx context.Context
|
||||||
|
backend string
|
||||||
|
opts WalkOptions
|
||||||
|
fn WalkFunc
|
||||||
|
count int
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewWalkEmitter(ctx context.Context, backend string, opts WalkOptions, fn WalkFunc) *WalkEmitter {
|
||||||
|
return &WalkEmitter{
|
||||||
|
ctx: ctx,
|
||||||
|
backend: backend,
|
||||||
|
opts: opts,
|
||||||
|
fn: fn,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *WalkEmitter) Emit(entry Entry) error {
|
||||||
|
if err := e.ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if e.opts.Limit > 0 && e.count >= e.opts.Limit {
|
||||||
|
return ErrStopWalk
|
||||||
|
}
|
||||||
|
e.count++
|
||||||
|
if err := e.fn(entry); err != nil {
|
||||||
|
if errors.Is(err, ErrStopWalk) {
|
||||||
|
return ErrStopWalk
|
||||||
|
}
|
||||||
|
return NewError(OpWalk, e.backend, entry.Path, ErrUnknown, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *WalkEmitter) LimitReached() bool {
|
||||||
|
return e.opts.Limit > 0 && e.count >= e.opts.Limit
|
||||||
|
}
|
||||||
|
|
||||||
|
func FinishWalk(err error) error {
|
||||||
|
if errors.Is(err, ErrStopWalk) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func HasAny(ctx context.Context, backend Backend, prefix string) (bool, error) {
|
||||||
|
found := false
|
||||||
|
err := backend.Walk(ctx, prefix, WalkOptions{Recursive: false, Limit: 1}, func(Entry) error {
|
||||||
|
found = true
|
||||||
|
return ErrStopWalk
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return found, nil
|
||||||
|
}
|
||||||
107
internal/storage/walk_test.go
Normal file
107
internal/storage/walk_test.go
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
package storage
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestWalkEmitterHonorsLimit(t *testing.T) {
|
||||||
|
emitter := NewWalkEmitter(context.Background(), "test", WalkOptions{Limit: 2}, func(Entry) error {
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
if err := emitter.Emit(Entry{Path: "one"}); err != nil {
|
||||||
|
t.Fatalf("first Emit() error = %v", err)
|
||||||
|
}
|
||||||
|
if err := emitter.Emit(Entry{Path: "two"}); err != nil {
|
||||||
|
t.Fatalf("second Emit() error = %v", err)
|
||||||
|
}
|
||||||
|
if err := emitter.Emit(Entry{Path: "three"}); !errors.Is(err, ErrStopWalk) {
|
||||||
|
t.Fatalf("third Emit() error = %v, want ErrStopWalk", err)
|
||||||
|
}
|
||||||
|
if !emitter.LimitReached() {
|
||||||
|
t.Fatal("LimitReached() = false, want true")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWalkEmitterStopsWithoutError(t *testing.T) {
|
||||||
|
emitter := NewWalkEmitter(context.Background(), "test", WalkOptions{}, func(Entry) error {
|
||||||
|
return ErrStopWalk
|
||||||
|
})
|
||||||
|
|
||||||
|
err := emitter.Emit(Entry{Path: "one"})
|
||||||
|
if !errors.Is(err, ErrStopWalk) {
|
||||||
|
t.Fatalf("Emit() error = %v, want ErrStopWalk", err)
|
||||||
|
}
|
||||||
|
if err := FinishWalk(err); err != nil {
|
||||||
|
t.Fatalf("FinishWalk() error = %v, want nil", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWalkEmitterWrapsCallbackErrors(t *testing.T) {
|
||||||
|
callbackErr := errors.New("callback failed")
|
||||||
|
emitter := NewWalkEmitter(context.Background(), "test", WalkOptions{}, func(Entry) error {
|
||||||
|
return callbackErr
|
||||||
|
})
|
||||||
|
|
||||||
|
err := emitter.Emit(Entry{Path: "one"})
|
||||||
|
if !errors.Is(err, callbackErr) {
|
||||||
|
t.Fatalf("Emit() error = %v, want callback error", err)
|
||||||
|
}
|
||||||
|
var storageErr *Error
|
||||||
|
if !errors.As(err, &storageErr) {
|
||||||
|
t.Fatalf("Emit() error type = %T, want *Error", err)
|
||||||
|
}
|
||||||
|
if storageErr.Op != OpWalk || storageErr.Backend != "test" || storageErr.Path != "one" || storageErr.Kind != ErrUnknown {
|
||||||
|
t.Fatalf("wrapped error = %#v", storageErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWalkEmitterHonorsContextCancellation(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
called := false
|
||||||
|
emitter := NewWalkEmitter(ctx, "test", WalkOptions{}, func(Entry) error {
|
||||||
|
called = true
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
err := emitter.Emit(Entry{Path: "one"})
|
||||||
|
if !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatalf("Emit() error = %v, want context.Canceled", err)
|
||||||
|
}
|
||||||
|
if called {
|
||||||
|
t.Fatal("callback was called after context cancellation")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHasAnyUsesNonRecursiveLimitOneWalk(t *testing.T) {
|
||||||
|
backend := &recordingBackend{}
|
||||||
|
|
||||||
|
found, err := HasAny(context.Background(), backend, "bundle")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("HasAny() error = %v", err)
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Fatal("HasAny() = false, want true")
|
||||||
|
}
|
||||||
|
if backend.prefix != "bundle" {
|
||||||
|
t.Fatalf("walk prefix = %q, want bundle", backend.prefix)
|
||||||
|
}
|
||||||
|
if backend.opts != (WalkOptions{Recursive: false, Limit: 1}) {
|
||||||
|
t.Fatalf("walk options = %#v, want non-recursive limit one", backend.opts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type recordingBackend struct {
|
||||||
|
Backend
|
||||||
|
prefix string
|
||||||
|
opts WalkOptions
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *recordingBackend) Walk(_ context.Context, prefix string, opts WalkOptions, fn WalkFunc) error {
|
||||||
|
b.prefix = prefix
|
||||||
|
b.opts = opts
|
||||||
|
return FinishWalk(fn(Entry{Path: "bundle/file.txt", Type: EntryTypeFile}))
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ package testutil
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -106,6 +107,53 @@ func WriteFakeSourceBundle(t testing.TB, backend *fake.Backend, relative string,
|
|||||||
return bundle.Bundle{RootRelativePath: relative, Manifest: manifest}
|
return bundle.Bundle{RootRelativePath: relative, Manifest: manifest}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func WriteFakeFile(t testing.TB, backend *fake.Backend, path, data string) {
|
||||||
|
t.Helper()
|
||||||
|
if _, err := backend.WriteFile(context.Background(), path, []byte(data), storage.WriteOptions{}); err != nil {
|
||||||
|
t.Fatalf("write fake file %s: %v", path, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func AssertFakeFile(t testing.TB, backend *fake.Backend, path, want string) {
|
||||||
|
t.Helper()
|
||||||
|
data, err := backend.ReadFile(context.Background(), path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read fake file %s: %v", path, err)
|
||||||
|
}
|
||||||
|
if got := string(data); got != want {
|
||||||
|
t.Fatalf("fake file %s = %q, want %q", path, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func AssertFakeMissing(t testing.TB, backend *fake.Backend, path string) {
|
||||||
|
t.Helper()
|
||||||
|
if _, err := backend.Stat(context.Background(), path); !storage.IsNotFound(err) {
|
||||||
|
t.Fatalf("fake file %s stat error = %v, want not found", path, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WriteFakeDestinationState(t testing.TB, backend *fake.Backend, relative string, manifest bundle.Manifest, opts DestinationStateOptions) state.DistributorState {
|
||||||
|
t.Helper()
|
||||||
|
destinationState := DestinationState(manifest, opts)
|
||||||
|
data, err := json.MarshalIndent(destinationState, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal destination state: %v", err)
|
||||||
|
}
|
||||||
|
statePath, err := storage.StatePath(relative)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("state path: %v", err)
|
||||||
|
}
|
||||||
|
WriteFakeFile(t, backend, statePath, string(append(data, '\n')))
|
||||||
|
for _, output := range destinationState.Outputs {
|
||||||
|
path, err := storage.Join(relative, output.Path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("join output path: %v", err)
|
||||||
|
}
|
||||||
|
WriteFakeFile(t, backend, path, "old")
|
||||||
|
}
|
||||||
|
return destinationState
|
||||||
|
}
|
||||||
|
|
||||||
func WriteMinimalLocalConfig(t testing.TB, sourceRoot, destinationRoot string) string {
|
func WriteMinimalLocalConfig(t testing.TB, sourceRoot, destinationRoot string) string {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
return writeConfigFile(t, `
|
return writeConfigFile(t, `
|
||||||
@@ -139,6 +187,136 @@ pipelines:
|
|||||||
`)
|
`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func WriteLocalConfigWithPublishPolicy(t testing.TB, sourceRoot, destinationRoot string, publishSource, publishHTML bool) string {
|
||||||
|
t.Helper()
|
||||||
|
transformConfig := ""
|
||||||
|
if publishHTML {
|
||||||
|
transformConfig = `
|
||||||
|
transform:
|
||||||
|
markdown_to_html:
|
||||||
|
enabled: true
|
||||||
|
mode: sidecar`
|
||||||
|
}
|
||||||
|
return writeConfigFile(t, `
|
||||||
|
pipelines:
|
||||||
|
- id: reports
|
||||||
|
source:
|
||||||
|
backend: local
|
||||||
|
path: `+sourceRoot+`
|
||||||
|
destinations:
|
||||||
|
- id: archive
|
||||||
|
backend: local
|
||||||
|
path: `+destinationRoot+`
|
||||||
|
publish:
|
||||||
|
source: `+fmt.Sprintf("%t", publishSource)+`
|
||||||
|
html: `+fmt.Sprintf("%t", publishHTML)+transformConfig+`
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
func WriteLocalConfigWithPathMapping(t testing.TB, sourceRoot, destinationRoot, mode string) string {
|
||||||
|
t.Helper()
|
||||||
|
return writeConfigFile(t, `
|
||||||
|
pipelines:
|
||||||
|
- id: reports
|
||||||
|
source:
|
||||||
|
backend: local
|
||||||
|
path: `+sourceRoot+`
|
||||||
|
destinations:
|
||||||
|
- id: archive
|
||||||
|
backend: local
|
||||||
|
path: `+destinationRoot+`
|
||||||
|
path_mapping:
|
||||||
|
mode: `+mode+`
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
func WriteLocalConfigWithLinks(t testing.TB, sourceRoot, destinationRoot, pathMapping, baseURL, primary string, publishSource, publishHTML bool, transformMode string) string {
|
||||||
|
t.Helper()
|
||||||
|
transformConfig := ""
|
||||||
|
if publishHTML {
|
||||||
|
transformConfig = `
|
||||||
|
transform:
|
||||||
|
markdown_to_html:
|
||||||
|
enabled: true
|
||||||
|
mode: ` + transformMode
|
||||||
|
}
|
||||||
|
return writeConfigFile(t, `
|
||||||
|
pipelines:
|
||||||
|
- id: reports
|
||||||
|
source:
|
||||||
|
backend: local
|
||||||
|
path: `+sourceRoot+`
|
||||||
|
destinations:
|
||||||
|
- id: archive
|
||||||
|
backend: local
|
||||||
|
path: `+destinationRoot+`
|
||||||
|
path_mapping:
|
||||||
|
mode: `+pathMapping+`
|
||||||
|
links:
|
||||||
|
base_url: `+baseURL+`
|
||||||
|
primary: `+primary+`
|
||||||
|
publish:
|
||||||
|
source: `+fmt.Sprintf("%t", publishSource)+`
|
||||||
|
html: `+fmt.Sprintf("%t", publishHTML)+transformConfig+`
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
func WriteLocalConfigWithMarkdownTransform(t testing.TB, sourceRoot, destinationRoot string, publishSource, publishHTML bool, mode, input string) string {
|
||||||
|
t.Helper()
|
||||||
|
enabled := publishHTML
|
||||||
|
inputConfig := ""
|
||||||
|
if input != "" {
|
||||||
|
inputConfig = `
|
||||||
|
input: ` + input
|
||||||
|
}
|
||||||
|
return writeConfigFile(t, `
|
||||||
|
pipelines:
|
||||||
|
- id: reports
|
||||||
|
source:
|
||||||
|
backend: local
|
||||||
|
path: `+sourceRoot+`
|
||||||
|
destinations:
|
||||||
|
- id: archive
|
||||||
|
backend: local
|
||||||
|
path: `+destinationRoot+`
|
||||||
|
publish:
|
||||||
|
source: `+fmt.Sprintf("%t", publishSource)+`
|
||||||
|
html: `+fmt.Sprintf("%t", publishHTML)+`
|
||||||
|
transform:
|
||||||
|
markdown_to_html:
|
||||||
|
enabled: `+fmt.Sprintf("%t", enabled)+`
|
||||||
|
mode: `+mode+inputConfig+`
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
func WriteMixedPolicyFanoutLocalConfig(t testing.TB, sourceRoot, archiveDestination, htmlDestination string) string {
|
||||||
|
t.Helper()
|
||||||
|
return writeConfigFile(t, `
|
||||||
|
pipelines:
|
||||||
|
- id: reports
|
||||||
|
source:
|
||||||
|
backend: local
|
||||||
|
path: `+sourceRoot+`
|
||||||
|
destinations:
|
||||||
|
- id: archive
|
||||||
|
backend: local
|
||||||
|
path: `+archiveDestination+`
|
||||||
|
publish:
|
||||||
|
source: true
|
||||||
|
html: false
|
||||||
|
- id: html
|
||||||
|
backend: local
|
||||||
|
path: `+htmlDestination+`
|
||||||
|
publish:
|
||||||
|
source: false
|
||||||
|
html: true
|
||||||
|
transform:
|
||||||
|
markdown_to_html:
|
||||||
|
enabled: true
|
||||||
|
mode: sidecar
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
func WriteDestinationState(t testing.TB, root, relative string, manifest bundle.Manifest, opts DestinationStateOptions) state.DistributorState {
|
func WriteDestinationState(t testing.TB, root, relative string, manifest bundle.Manifest, opts DestinationStateOptions) state.DistributorState {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
bundleRoot := filepath.Join(root, filepath.FromSlash(relative))
|
bundleRoot := filepath.Join(root, filepath.FromSlash(relative))
|
||||||
@@ -175,6 +353,28 @@ func ReadDestinationState(t testing.TB, path string) state.DistributorState {
|
|||||||
return destinationState
|
return destinationState
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func AssertFile(t testing.TB, path, want string) {
|
||||||
|
t.Helper()
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read file %s: %v", path, err)
|
||||||
|
}
|
||||||
|
if got := string(data); got != want {
|
||||||
|
t.Fatalf("%s = %q, want %q", path, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func AssertFileContains(t testing.TB, path, want string) {
|
||||||
|
t.Helper()
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read file %s: %v", path, err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(data), want) {
|
||||||
|
t.Fatalf("%s = %q, want substring %q", path, data, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func sourceFiles(opts BundleOptions) []SourceFile {
|
func sourceFiles(opts BundleOptions) []SourceFile {
|
||||||
files := opts.Files
|
files := opts.Files
|
||||||
if files == nil {
|
if files == nil {
|
||||||
|
|||||||
@@ -25,24 +25,26 @@ func (t *Transformer) Generate(ctx context.Context, req transform.Request) ([]tr
|
|||||||
if t.renderer == nil {
|
if t.renderer == nil {
|
||||||
t.renderer = goldmark.New()
|
t.renderer = goldmark.New()
|
||||||
}
|
}
|
||||||
|
switch markdownMode(req.Markdown.Mode) {
|
||||||
|
case transform.MarkdownModeSidecar:
|
||||||
|
return t.generateSidecars(ctx, req)
|
||||||
|
case transform.MarkdownModeIndex:
|
||||||
|
return t.generateIndex(ctx, req)
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("markdown mode %q is not supported", req.Markdown.Mode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Transformer) generateSidecars(ctx context.Context, req transform.Request) ([]transform.Output, error) {
|
||||||
var outputs []transform.Output
|
var outputs []transform.Output
|
||||||
for _, file := range req.SourceBundle.Manifest.Files {
|
for _, file := range req.SourceBundle.Manifest.Files {
|
||||||
if !strings.HasSuffix(file.Path, ".md") {
|
if !strings.HasSuffix(file.Path, ".md") {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
sourcePath, err := storage.Join(req.SourceBundle.RootRelativePath, file.Path)
|
html, err := t.render(ctx, req, file.Path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
data, err := req.SourceBackend.ReadFile(ctx, sourcePath)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("read markdown source %q: %w", file.Path, err)
|
|
||||||
}
|
|
||||||
var rendered bytes.Buffer
|
|
||||||
if err := t.renderer.Convert(data, &rendered); err != nil {
|
|
||||||
return nil, fmt.Errorf("render markdown source %q: %w", file.Path, err)
|
|
||||||
}
|
|
||||||
html := wrapHTML(rendered.Bytes())
|
|
||||||
outputPath := strings.TrimSuffix(file.Path, ".md") + ".html"
|
outputPath := strings.TrimSuffix(file.Path, ".md") + ".html"
|
||||||
outputs = append(outputs, transform.Output{
|
outputs = append(outputs, transform.Output{
|
||||||
Path: outputPath,
|
Path: outputPath,
|
||||||
@@ -55,3 +57,78 @@ func (t *Transformer) Generate(ctx context.Context, req transform.Request) ([]tr
|
|||||||
}
|
}
|
||||||
return outputs, nil
|
return outputs, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (t *Transformer) generateIndex(ctx context.Context, req transform.Request) ([]transform.Output, error) {
|
||||||
|
input, err := selectIndexInput(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
html, err := t.render(ctx, req, input)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return []transform.Output{{
|
||||||
|
Path: "index.html",
|
||||||
|
SourcePath: input,
|
||||||
|
Transform: transform.MarkdownToHTML,
|
||||||
|
Data: html,
|
||||||
|
SHA256: bundle.FileDigest(html),
|
||||||
|
Size: int64(len(html)),
|
||||||
|
}}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func selectIndexInput(req transform.Request) (string, error) {
|
||||||
|
if req.Markdown.Input != "" {
|
||||||
|
if err := storage.ValidatePath(req.Markdown.Input); err != nil {
|
||||||
|
return "", fmt.Errorf("markdown input %q: %w", req.Markdown.Input, err)
|
||||||
|
}
|
||||||
|
for _, file := range req.SourceBundle.Manifest.Files {
|
||||||
|
if file.Path != req.Markdown.Input {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !strings.HasSuffix(file.Path, ".md") {
|
||||||
|
return "", fmt.Errorf("markdown input %q must end in .md", req.Markdown.Input)
|
||||||
|
}
|
||||||
|
return file.Path, nil
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("markdown input %q is not listed in the source manifest", req.Markdown.Input)
|
||||||
|
}
|
||||||
|
|
||||||
|
var markdownFiles []string
|
||||||
|
for _, file := range req.SourceBundle.Manifest.Files {
|
||||||
|
if strings.HasSuffix(file.Path, ".md") {
|
||||||
|
markdownFiles = append(markdownFiles, file.Path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch len(markdownFiles) {
|
||||||
|
case 0:
|
||||||
|
return "", fmt.Errorf("markdown index mode requires one markdown source file or transform.markdown_to_html.input")
|
||||||
|
case 1:
|
||||||
|
return markdownFiles[0], nil
|
||||||
|
default:
|
||||||
|
return "", fmt.Errorf("markdown index mode found multiple markdown source files; set transform.markdown_to_html.input")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Transformer) render(ctx context.Context, req transform.Request, sourceFile string) ([]byte, error) {
|
||||||
|
sourcePath, err := storage.Join(req.SourceBundle.RootRelativePath, sourceFile)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
data, err := req.SourceBackend.ReadFile(ctx, sourcePath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("read markdown source %q: %w", sourceFile, err)
|
||||||
|
}
|
||||||
|
var rendered bytes.Buffer
|
||||||
|
if err := t.renderer.Convert(data, &rendered); err != nil {
|
||||||
|
return nil, fmt.Errorf("render markdown source %q: %w", sourceFile, err)
|
||||||
|
}
|
||||||
|
return wrapHTML(rendered.Bytes()), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func markdownMode(mode string) string {
|
||||||
|
if mode == "" {
|
||||||
|
return transform.MarkdownModeSidecar
|
||||||
|
}
|
||||||
|
return mode
|
||||||
|
}
|
||||||
|
|||||||
@@ -40,6 +40,124 @@ func TestGenerateMarkdownSidecar(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestGenerateMarkdownIndexExplicitInput(t *testing.T) {
|
||||||
|
backend := fake.New()
|
||||||
|
sourceBundle := testutil.WriteFakeSourceBundle(t, backend, "", testutil.BundleOptions{
|
||||||
|
ID: "bundle",
|
||||||
|
Files: []testutil.SourceFile{
|
||||||
|
{Path: "report.md", Data: "# Report\n"},
|
||||||
|
{Path: "notes.md", Data: "# Notes\n"},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
outputs, err := New().Generate(context.Background(), transform.Request{
|
||||||
|
SourceBackend: backend,
|
||||||
|
SourceBundle: sourceBundle,
|
||||||
|
Markdown: transform.MarkdownOptions{Mode: transform.MarkdownModeIndex, Input: "notes.md"},
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Generate() error = %v", err)
|
||||||
|
}
|
||||||
|
if got, want := len(outputs), 1; got != want {
|
||||||
|
t.Fatalf("output count = %d, want %d", got, want)
|
||||||
|
}
|
||||||
|
output := outputs[0]
|
||||||
|
if output.Path != "index.html" || output.SourcePath != "notes.md" || output.Transform != transform.MarkdownToHTML {
|
||||||
|
t.Fatalf("output metadata = %#v, want index from notes.md", output)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(output.Data), "<h1>Notes</h1>") {
|
||||||
|
t.Fatalf("html = %q, want notes content", output.Data)
|
||||||
|
}
|
||||||
|
if output.SHA256 != bundle.FileDigest(output.Data) || output.Size != int64(len(output.Data)) {
|
||||||
|
t.Fatalf("digest/size metadata = %s/%d", output.SHA256, output.Size)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGenerateMarkdownIndexSelectsOnlyMarkdownFile(t *testing.T) {
|
||||||
|
backend, sourceBundle := markdownFixture(t, "# Title\n\nHello.\n")
|
||||||
|
|
||||||
|
outputs, err := New().Generate(context.Background(), transform.Request{
|
||||||
|
SourceBackend: backend,
|
||||||
|
SourceBundle: sourceBundle,
|
||||||
|
Markdown: transform.MarkdownOptions{Mode: transform.MarkdownModeIndex},
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Generate() error = %v", err)
|
||||||
|
}
|
||||||
|
if got, want := outputs[0].Path, "index.html"; got != want {
|
||||||
|
t.Fatalf("path = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
if got, want := outputs[0].SourcePath, "report.md"; got != want {
|
||||||
|
t.Fatalf("source path = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGenerateMarkdownIndexRejectsAmbiguousInput(t *testing.T) {
|
||||||
|
backend := fake.New()
|
||||||
|
sourceBundle := testutil.WriteFakeSourceBundle(t, backend, "", testutil.BundleOptions{
|
||||||
|
ID: "bundle",
|
||||||
|
Files: []testutil.SourceFile{
|
||||||
|
{Path: "report.md", Data: "# Report\n"},
|
||||||
|
{Path: "notes.md", Data: "# Notes\n"},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
_, err := New().Generate(context.Background(), transform.Request{
|
||||||
|
SourceBackend: backend,
|
||||||
|
SourceBundle: sourceBundle,
|
||||||
|
Markdown: transform.MarkdownOptions{Mode: transform.MarkdownModeIndex},
|
||||||
|
})
|
||||||
|
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "multiple markdown source files") {
|
||||||
|
t.Fatalf("Generate() error = %v, want ambiguous input error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGenerateMarkdownIndexRejectsMissingMarkdown(t *testing.T) {
|
||||||
|
backend := fake.New()
|
||||||
|
sourceBundle := testutil.WriteFakeSourceBundle(t, backend, "", testutil.BundleOptions{
|
||||||
|
ID: "bundle",
|
||||||
|
Files: []testutil.SourceFile{{Path: "summary.txt", Data: "Summary\n"}},
|
||||||
|
})
|
||||||
|
|
||||||
|
_, err := New().Generate(context.Background(), transform.Request{
|
||||||
|
SourceBackend: backend,
|
||||||
|
SourceBundle: sourceBundle,
|
||||||
|
Markdown: transform.MarkdownOptions{Mode: transform.MarkdownModeIndex},
|
||||||
|
})
|
||||||
|
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "requires one markdown source file") {
|
||||||
|
t.Fatalf("Generate() error = %v, want missing markdown error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGenerateMarkdownIndexRejectsInvalidExplicitInput(t *testing.T) {
|
||||||
|
backend, sourceBundle := markdownFixture(t, "# Title\n")
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
input string
|
||||||
|
wantError string
|
||||||
|
}{
|
||||||
|
{name: "unsafe", input: "../report.md", wantError: "markdown input"},
|
||||||
|
{name: "not listed", input: "missing.md", wantError: "not listed"},
|
||||||
|
{name: "not markdown", input: "summary.txt", wantError: "must end in .md"},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
_, err := New().Generate(context.Background(), transform.Request{
|
||||||
|
SourceBackend: backend,
|
||||||
|
SourceBundle: sourceBundle,
|
||||||
|
Markdown: transform.MarkdownOptions{Mode: transform.MarkdownModeIndex, Input: tt.input},
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), tt.wantError) {
|
||||||
|
t.Fatalf("Generate() error = %v, want substring %q", err, tt.wantError)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestGenerateIgnoresNonMarkdown(t *testing.T) {
|
func TestGenerateIgnoresNonMarkdown(t *testing.T) {
|
||||||
backend := fake.New()
|
backend := fake.New()
|
||||||
if _, err := backend.WriteFile(context.Background(), "summary.txt", []byte("Summary\n"), storage.WriteOptions{}); err != nil {
|
if _, err := backend.WriteFile(context.Background(), "summary.txt", []byte("Summary\n"), storage.WriteOptions{}); err != nil {
|
||||||
|
|||||||
@@ -1,3 +1,8 @@
|
|||||||
package transform
|
package transform
|
||||||
|
|
||||||
const MarkdownToHTML = "markdown_to_html"
|
const MarkdownToHTML = "markdown_to_html"
|
||||||
|
|
||||||
|
const (
|
||||||
|
MarkdownModeSidecar = "sidecar"
|
||||||
|
MarkdownModeIndex = "index"
|
||||||
|
)
|
||||||
|
|||||||
@@ -19,6 +19,12 @@ type Output struct {
|
|||||||
type Request struct {
|
type Request struct {
|
||||||
SourceBundle bundle.Bundle
|
SourceBundle bundle.Bundle
|
||||||
SourceBackend storage.Backend
|
SourceBackend storage.Backend
|
||||||
|
Markdown MarkdownOptions
|
||||||
|
}
|
||||||
|
|
||||||
|
type MarkdownOptions struct {
|
||||||
|
Mode string
|
||||||
|
Input string
|
||||||
}
|
}
|
||||||
|
|
||||||
type Transformer interface {
|
type Transformer interface {
|
||||||
|
|||||||
118
pkg/bundle/build.go
Normal file
118
pkg/bundle/build.go
Normal file
@@ -0,0 +1,118 @@
|
|||||||
|
package bundle
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func BuildManifest(opts BuildOptions) (Manifest, error) {
|
||||||
|
if opts.Root == "" {
|
||||||
|
return Manifest{}, fmt.Errorf("root is required")
|
||||||
|
}
|
||||||
|
if opts.ID == "" {
|
||||||
|
return Manifest{}, fmt.Errorf("id is required")
|
||||||
|
}
|
||||||
|
explicit := len(opts.Files) > 0
|
||||||
|
if explicit == opts.Scan {
|
||||||
|
return Manifest{}, fmt.Errorf("select exactly one file mode")
|
||||||
|
}
|
||||||
|
created := opts.Created
|
||||||
|
if created.IsZero() {
|
||||||
|
created = time.Now().UTC()
|
||||||
|
}
|
||||||
|
|
||||||
|
paths := append([]string(nil), opts.Files...)
|
||||||
|
var err error
|
||||||
|
if opts.Scan {
|
||||||
|
paths, err = scanSourcePaths(opts.Root)
|
||||||
|
if err != nil {
|
||||||
|
return Manifest{}, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
files := make([]ManifestFile, 0, len(paths))
|
||||||
|
for _, sourcePath := range paths {
|
||||||
|
file, err := buildManifestFile(opts.Root, sourcePath)
|
||||||
|
if err != nil {
|
||||||
|
return Manifest{}, err
|
||||||
|
}
|
||||||
|
files = append(files, file)
|
||||||
|
}
|
||||||
|
manifest := Manifest{
|
||||||
|
SchemaVersion: SchemaVersion,
|
||||||
|
ID: opts.ID,
|
||||||
|
Created: created,
|
||||||
|
Files: files,
|
||||||
|
}
|
||||||
|
manifest.Digest = BundleDigest(manifest.Files)
|
||||||
|
if err := ValidateManifest(manifest); err != nil {
|
||||||
|
return Manifest{}, err
|
||||||
|
}
|
||||||
|
return manifest, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func scanSourcePaths(root string) ([]string, error) {
|
||||||
|
var paths []string
|
||||||
|
err := filepath.WalkDir(root, func(filePath string, entry os.DirEntry, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if filePath == root {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
relative, err := filepath.Rel(root, filePath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
sourcePath := filepath.ToSlash(relative)
|
||||||
|
if entry.Type()&os.ModeSymlink != 0 {
|
||||||
|
return fmt.Errorf("source file %q must be a regular file", sourcePath)
|
||||||
|
}
|
||||||
|
if entry.IsDir() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if path.Base(sourcePath) == ManifestName || path.Base(sourcePath) == distributorStateName {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
info, err := entry.Info()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !info.Mode().IsRegular() {
|
||||||
|
return fmt.Errorf("source file %q must be a regular file", sourcePath)
|
||||||
|
}
|
||||||
|
paths = append(paths, sourcePath)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
sort.Strings(paths)
|
||||||
|
return paths, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildManifestFile(root, sourcePath string) (ManifestFile, error) {
|
||||||
|
if err := ValidateSourcePath(sourcePath); err != nil {
|
||||||
|
return ManifestFile{}, fmt.Errorf("source file %q: %w", sourcePath, err)
|
||||||
|
}
|
||||||
|
fullPath := filepath.Join(root, filepath.FromSlash(sourcePath))
|
||||||
|
info, err := os.Lstat(fullPath)
|
||||||
|
if err != nil {
|
||||||
|
return ManifestFile{}, fmt.Errorf("source file %q stat: %w", sourcePath, err)
|
||||||
|
}
|
||||||
|
if !info.Mode().IsRegular() {
|
||||||
|
return ManifestFile{}, fmt.Errorf("source file %q must be a regular file", sourcePath)
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(fullPath)
|
||||||
|
if err != nil {
|
||||||
|
return ManifestFile{}, fmt.Errorf("source file %q read: %w", sourcePath, err)
|
||||||
|
}
|
||||||
|
return ManifestFile{
|
||||||
|
Path: sourcePath,
|
||||||
|
SHA256: FileDigest(data),
|
||||||
|
Size: int64(len(data)),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
363
pkg/bundle/bundle_test.go
Normal file
363
pkg/bundle/bundle_test.go
Normal file
@@ -0,0 +1,363 @@
|
|||||||
|
package bundle
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBuildManifestExplicitFilesPreservesOrder(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
writeFile(t, root, "b.txt", "bravo")
|
||||||
|
writeFile(t, root, "a.txt", "alpha")
|
||||||
|
before := time.Now().UTC()
|
||||||
|
|
||||||
|
manifest, err := BuildManifest(BuildOptions{
|
||||||
|
Root: root,
|
||||||
|
ID: "reports.example",
|
||||||
|
Files: []string{"b.txt", "a.txt"},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("BuildManifest() error = %v", err)
|
||||||
|
}
|
||||||
|
after := time.Now().UTC()
|
||||||
|
|
||||||
|
paths := manifestPaths(manifest)
|
||||||
|
if want := []string{"b.txt", "a.txt"}; !reflect.DeepEqual(paths, want) {
|
||||||
|
t.Fatalf("paths = %v, want %v", paths, want)
|
||||||
|
}
|
||||||
|
if manifest.SchemaVersion != SchemaVersion {
|
||||||
|
t.Fatalf("schema version = %d, want %d", manifest.SchemaVersion, SchemaVersion)
|
||||||
|
}
|
||||||
|
if manifest.ID != "reports.example" {
|
||||||
|
t.Fatalf("id = %q", manifest.ID)
|
||||||
|
}
|
||||||
|
if manifest.Created.Before(before) || manifest.Created.After(after) {
|
||||||
|
t.Fatalf("created = %s, want between %s and %s", manifest.Created, before, after)
|
||||||
|
}
|
||||||
|
if err := ValidateManifest(manifest); err != nil {
|
||||||
|
t.Fatalf("ValidateManifest() error = %v", err)
|
||||||
|
}
|
||||||
|
if err := ValidateBundle(root, manifest); err != nil {
|
||||||
|
t.Fatalf("ValidateBundle() error = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildManifestScanSortsAndFiltersMetadata(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
writeFile(t, root, "z.txt", "zulu")
|
||||||
|
writeFile(t, root, "nested/.hidden", "hidden")
|
||||||
|
writeFile(t, root, ManifestName, "old manifest")
|
||||||
|
writeFile(t, root, distributorStateName, "state")
|
||||||
|
writeFile(t, root, "nested/manifest.json", "nested manifest")
|
||||||
|
writeFile(t, root, "nested/.distributor.json", "nested state")
|
||||||
|
created := time.Date(2026, 5, 30, 11, 10, 0, 0, time.UTC)
|
||||||
|
|
||||||
|
manifest, err := BuildManifest(BuildOptions{
|
||||||
|
Root: root,
|
||||||
|
ID: "reports.scan",
|
||||||
|
Created: created,
|
||||||
|
Scan: true,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("BuildManifest() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !manifest.Created.Equal(created) {
|
||||||
|
t.Fatalf("created = %s, want %s", manifest.Created, created)
|
||||||
|
}
|
||||||
|
paths := manifestPaths(manifest)
|
||||||
|
if want := []string{"nested/.hidden", "z.txt"}; !reflect.DeepEqual(paths, want) {
|
||||||
|
t.Fatalf("paths = %v, want %v", paths, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildManifestRequiresOneFileMode(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
writeFile(t, root, "report.txt", "report")
|
||||||
|
|
||||||
|
tests := []BuildOptions{
|
||||||
|
{Root: root, ID: "reports.none"},
|
||||||
|
{Root: root, ID: "reports.both", Files: []string{"report.txt"}, Scan: true},
|
||||||
|
}
|
||||||
|
for _, opts := range tests {
|
||||||
|
if _, err := BuildManifest(opts); err == nil {
|
||||||
|
t.Fatalf("BuildManifest(%+v) error = nil, want error", opts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildManifestRejectsUnsafePath(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
writeFile(t, root, "report.txt", "report")
|
||||||
|
|
||||||
|
_, err := BuildManifest(BuildOptions{
|
||||||
|
Root: root,
|
||||||
|
ID: "reports.unsafe",
|
||||||
|
Files: []string{"../report.txt"},
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("BuildManifest() error = nil, want unsafe path error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildManifestRejectsSymlink(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
writeFile(t, root, "target.txt", "target")
|
||||||
|
if err := os.Symlink("target.txt", filepath.Join(root, "link.txt")); err != nil {
|
||||||
|
t.Skipf("symlink unavailable: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := BuildManifest(BuildOptions{
|
||||||
|
Root: root,
|
||||||
|
ID: "reports.symlink",
|
||||||
|
Files: []string{"link.txt"},
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "regular file") {
|
||||||
|
t.Fatalf("BuildManifest() error = %v, want regular file error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestScanRejectsSymlink(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
writeFile(t, root, "target.txt", "target")
|
||||||
|
if err := os.Symlink("target.txt", filepath.Join(root, "link.txt")); err != nil {
|
||||||
|
t.Skipf("symlink unavailable: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := BuildManifest(BuildOptions{
|
||||||
|
Root: root,
|
||||||
|
ID: "reports.scan.symlink",
|
||||||
|
Scan: true,
|
||||||
|
})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "regular file") {
|
||||||
|
t.Fatalf("BuildManifest() error = %v, want regular file error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDigestFunctionsUseCanonicalFilePayload(t *testing.T) {
|
||||||
|
files := []ManifestFile{
|
||||||
|
{Path: "report.md", SHA256: FileDigest([]byte("report")), Size: 6},
|
||||||
|
{Path: "summary.txt", SHA256: FileDigest([]byte("summary")), Size: 7},
|
||||||
|
}
|
||||||
|
payload := CanonicalFilePayload(files)
|
||||||
|
if want := `[{"path":"report.md","sha256":"sha256:845e91831319e89c4d656bdb80c278ac09a7230d61e5dfd2e1b1fbb436ac8917","size":6},{"path":"summary.txt","sha256":"sha256:761b7ad8ad439b2855fcbb611331c646ef0870b0631247bba3f3025cb6df5a53","size":7}]`; payload != want {
|
||||||
|
t.Fatalf("payload = %q, want %q", payload, want)
|
||||||
|
}
|
||||||
|
if digest := BundleDigest(files); !strings.HasPrefix(digest, "sha256:") || len(digest) != len("sha256:")+64 {
|
||||||
|
t.Fatalf("BundleDigest() = %q, want sha256 digest", digest)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseMarshalLoadAndWriteManifest(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
writeFile(t, root, "report.txt", "report")
|
||||||
|
manifest, err := BuildManifest(BuildOptions{
|
||||||
|
Root: root,
|
||||||
|
ID: "reports.json",
|
||||||
|
Created: time.Date(2026, 5, 30, 11, 10, 0, 0, time.UTC),
|
||||||
|
Files: []string{"report.txt"},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("BuildManifest() error = %v", err)
|
||||||
|
}
|
||||||
|
data, err := MarshalManifest(manifest)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("MarshalManifest() error = %v", err)
|
||||||
|
}
|
||||||
|
if !strings.HasSuffix(string(data), "\n") {
|
||||||
|
t.Fatalf("manifest JSON = %q, want trailing newline", string(data))
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(data), `"schema_version": 1`) || !strings.Contains(string(data), `"sha256": "`) {
|
||||||
|
t.Fatalf("manifest JSON = %q, want fixed manifest fields", string(data))
|
||||||
|
}
|
||||||
|
parsed, err := ParseManifest(data)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ParseManifest() error = %v", err)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(parsed, manifest) {
|
||||||
|
t.Fatalf("parsed manifest = %#v, want %#v", parsed, manifest)
|
||||||
|
}
|
||||||
|
if err := WriteManifest(root, manifest, WriteManifestOptions{}); err != nil {
|
||||||
|
t.Fatalf("WriteManifest() error = %v", err)
|
||||||
|
}
|
||||||
|
loaded, err := LoadManifest(root)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("LoadManifest() error = %v", err)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(loaded, manifest) {
|
||||||
|
t.Fatalf("loaded manifest = %#v, want %#v", loaded, manifest)
|
||||||
|
}
|
||||||
|
if err := WriteManifest(root, manifest, WriteManifestOptions{}); err == nil {
|
||||||
|
t.Fatal("WriteManifest() error = nil, want exists error")
|
||||||
|
}
|
||||||
|
manifest.ID = "reports.updated"
|
||||||
|
manifest.Digest = BundleDigest(manifest.Files)
|
||||||
|
if err := WriteManifest(root, manifest, WriteManifestOptions{Overwrite: true}); err != nil {
|
||||||
|
t.Fatalf("WriteManifest(overwrite) error = %v", err)
|
||||||
|
}
|
||||||
|
loaded, err = LoadManifest(root)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("LoadManifest() after overwrite error = %v", err)
|
||||||
|
}
|
||||||
|
if loaded.ID != "reports.updated" {
|
||||||
|
t.Fatalf("loaded id = %q, want updated", loaded.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateManifestRejectsInvalidManifest(t *testing.T) {
|
||||||
|
created := time.Date(2026, 5, 30, 11, 10, 0, 0, time.UTC)
|
||||||
|
fileDigest := FileDigest([]byte("report"))
|
||||||
|
valid := Manifest{
|
||||||
|
SchemaVersion: SchemaVersion,
|
||||||
|
ID: "reports.valid",
|
||||||
|
Created: created,
|
||||||
|
Files: []ManifestFile{{Path: "report.txt", SHA256: fileDigest, Size: 6}},
|
||||||
|
}
|
||||||
|
valid.Digest = BundleDigest(valid.Files)
|
||||||
|
|
||||||
|
tests := map[string]func(Manifest) Manifest{
|
||||||
|
"schema version": func(manifest Manifest) Manifest {
|
||||||
|
manifest.SchemaVersion = 2
|
||||||
|
return manifest
|
||||||
|
},
|
||||||
|
"id": func(manifest Manifest) Manifest {
|
||||||
|
manifest.ID = ""
|
||||||
|
return manifest
|
||||||
|
},
|
||||||
|
"created": func(manifest Manifest) Manifest {
|
||||||
|
manifest.Created = time.Time{}
|
||||||
|
return manifest
|
||||||
|
},
|
||||||
|
"files": func(manifest Manifest) Manifest {
|
||||||
|
manifest.Files = nil
|
||||||
|
manifest.Digest = BundleDigest(manifest.Files)
|
||||||
|
return manifest
|
||||||
|
},
|
||||||
|
"path": func(manifest Manifest) Manifest {
|
||||||
|
manifest.Files[0].Path = "manifest.json"
|
||||||
|
manifest.Digest = BundleDigest(manifest.Files)
|
||||||
|
return manifest
|
||||||
|
},
|
||||||
|
"duplicate": func(manifest Manifest) Manifest {
|
||||||
|
manifest.Files = append(manifest.Files, manifest.Files[0])
|
||||||
|
manifest.Digest = BundleDigest(manifest.Files)
|
||||||
|
return manifest
|
||||||
|
},
|
||||||
|
"size": func(manifest Manifest) Manifest {
|
||||||
|
manifest.Files[0].Size = -1
|
||||||
|
manifest.Digest = BundleDigest(manifest.Files)
|
||||||
|
return manifest
|
||||||
|
},
|
||||||
|
"digest": func(manifest Manifest) Manifest {
|
||||||
|
manifest.Digest = "sha256:0000000000000000000000000000000000000000000000000000000000000000"
|
||||||
|
return manifest
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for name, mutate := range tests {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
if err := ValidateManifest(mutate(valid)); err == nil {
|
||||||
|
t.Fatal("ValidateManifest() error = nil, want error")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateBundleRejectsLocalFileProblems(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
writeFile(t, root, "report.txt", "report")
|
||||||
|
manifest, err := BuildManifest(BuildOptions{
|
||||||
|
Root: root,
|
||||||
|
ID: "reports.bundle",
|
||||||
|
Files: []string{"report.txt"},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("BuildManifest() error = %v", err)
|
||||||
|
}
|
||||||
|
if err := ValidateBundle(root, manifest); err != nil {
|
||||||
|
t.Fatalf("ValidateBundle() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
missing := cloneManifest(manifest)
|
||||||
|
missing.Files[0].Path = "missing.txt"
|
||||||
|
missing.Digest = BundleDigest(missing.Files)
|
||||||
|
if err := ValidateBundle(root, missing); err == nil {
|
||||||
|
t.Fatal("ValidateBundle() missing error = nil, want error")
|
||||||
|
}
|
||||||
|
|
||||||
|
sizeMismatch := cloneManifest(manifest)
|
||||||
|
sizeMismatch.Files[0].Size++
|
||||||
|
sizeMismatch.Digest = BundleDigest(sizeMismatch.Files)
|
||||||
|
if err := ValidateBundle(root, sizeMismatch); err == nil || !strings.Contains(err.Error(), "size mismatch") {
|
||||||
|
t.Fatalf("ValidateBundle() size error = %v, want size mismatch", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
digestMismatch := cloneManifest(manifest)
|
||||||
|
writeFile(t, root, "report.txt", "change")
|
||||||
|
if err := ValidateBundle(root, digestMismatch); err == nil || !strings.Contains(err.Error(), "sha256 mismatch") {
|
||||||
|
t.Fatalf("ValidateBundle() digest error = %v, want digest mismatch", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateBundleRejectsSymlink(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
writeFile(t, root, "target.txt", "target")
|
||||||
|
if err := os.Symlink("target.txt", filepath.Join(root, "link.txt")); err != nil {
|
||||||
|
t.Skipf("symlink unavailable: %v", err)
|
||||||
|
}
|
||||||
|
file := ManifestFile{Path: "link.txt", SHA256: FileDigest([]byte("target")), Size: 6}
|
||||||
|
manifest := Manifest{
|
||||||
|
SchemaVersion: SchemaVersion,
|
||||||
|
ID: "reports.link",
|
||||||
|
Created: time.Date(2026, 5, 30, 11, 10, 0, 0, time.UTC),
|
||||||
|
Files: []ManifestFile{file},
|
||||||
|
}
|
||||||
|
manifest.Digest = BundleDigest(manifest.Files)
|
||||||
|
|
||||||
|
err := ValidateBundle(root, manifest)
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "regular file") {
|
||||||
|
t.Fatalf("ValidateBundle() error = %v, want regular file error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateSourcePath(t *testing.T) {
|
||||||
|
valid := []string{"report.md", "nested/report.md", ".well-known/report.txt"}
|
||||||
|
for _, path := range valid {
|
||||||
|
if err := ValidateSourcePath(path); err != nil {
|
||||||
|
t.Fatalf("ValidateSourcePath(%q) error = %v", path, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
invalid := []string{"", "../report.md", "/report.md", "nested/../report.md", `nested\report.md`, ManifestName, distributorStateName}
|
||||||
|
for _, path := range invalid {
|
||||||
|
if err := ValidateSourcePath(path); err == nil {
|
||||||
|
t.Fatalf("ValidateSourcePath(%q) error = nil, want error", path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func manifestPaths(manifest Manifest) []string {
|
||||||
|
paths := make([]string, 0, len(manifest.Files))
|
||||||
|
for _, file := range manifest.Files {
|
||||||
|
paths = append(paths, file.Path)
|
||||||
|
}
|
||||||
|
return paths
|
||||||
|
}
|
||||||
|
|
||||||
|
func cloneManifest(manifest Manifest) Manifest {
|
||||||
|
manifest.Files = append([]ManifestFile(nil), manifest.Files...)
|
||||||
|
return manifest
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeFile(t *testing.T, root, relative, body string) {
|
||||||
|
t.Helper()
|
||||||
|
path := filepath.Join(root, filepath.FromSlash(relative))
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||||
|
t.Fatalf("mkdir %s: %v", filepath.Dir(path), err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
|
||||||
|
t.Fatalf("write %s: %v", path, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
50
pkg/bundle/digest.go
Normal file
50
pkg/bundle/digest.go
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
package bundle
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
var digestPattern = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`)
|
||||||
|
|
||||||
|
// ValidateDigest reports whether value uses the lowercase sha256:<64 hex> form.
|
||||||
|
func ValidateDigest(value string) error {
|
||||||
|
if !digestPattern.MatchString(value) {
|
||||||
|
return fmt.Errorf("must be lowercase sha256:<64 hex>")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func FileDigest(data []byte) string {
|
||||||
|
sum := sha256.Sum256(data)
|
||||||
|
return "sha256:" + hex.EncodeToString(sum[:])
|
||||||
|
}
|
||||||
|
|
||||||
|
func BundleDigest(files []ManifestFile) string {
|
||||||
|
canonical := CanonicalFilePayload(files)
|
||||||
|
sum := sha256.Sum256([]byte(canonical))
|
||||||
|
return "sha256:" + hex.EncodeToString(sum[:])
|
||||||
|
}
|
||||||
|
|
||||||
|
func CanonicalFilePayload(files []ManifestFile) string {
|
||||||
|
var builder strings.Builder
|
||||||
|
builder.WriteByte('[')
|
||||||
|
for index, file := range files {
|
||||||
|
if index > 0 {
|
||||||
|
builder.WriteByte(',')
|
||||||
|
}
|
||||||
|
builder.WriteString(`{"path":`)
|
||||||
|
builder.WriteString(strconv.Quote(file.Path))
|
||||||
|
builder.WriteString(`,"sha256":`)
|
||||||
|
builder.WriteString(strconv.Quote(file.SHA256))
|
||||||
|
builder.WriteString(`,"size":`)
|
||||||
|
builder.WriteString(strconv.FormatInt(file.Size, 10))
|
||||||
|
builder.WriteByte('}')
|
||||||
|
}
|
||||||
|
builder.WriteByte(']')
|
||||||
|
return builder.String()
|
||||||
|
}
|
||||||
58
pkg/bundle/digest_test.go
Normal file
58
pkg/bundle/digest_test.go
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
package bundle
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestValidateDigest(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
value string
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "valid",
|
||||||
|
value: "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "uppercase hex",
|
||||||
|
value: "sha256:0123456789ABCDEF0123456789abcdef0123456789abcdef0123456789abcdef",
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "missing prefix",
|
||||||
|
value: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "wrong algorithm",
|
||||||
|
value: "sha512:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "short hex",
|
||||||
|
value: "sha256:0123456789abcdef",
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "long hex",
|
||||||
|
value: "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0",
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "non hex",
|
||||||
|
value: "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdeg",
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
err := ValidateDigest(test.value)
|
||||||
|
if test.wantErr && err == nil {
|
||||||
|
t.Fatal("ValidateDigest() error = nil, want error")
|
||||||
|
}
|
||||||
|
if !test.wantErr && err != nil {
|
||||||
|
t.Fatalf("ValidateDigest() error = %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
9
pkg/bundle/doc.go
Normal file
9
pkg/bundle/doc.go
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
// Package bundle provides producer-facing helpers for distributor source
|
||||||
|
// bundle manifests.
|
||||||
|
//
|
||||||
|
// A source bundle is a local directory containing a manifest.json file and the
|
||||||
|
// files listed by that manifest. This package owns the public manifest model,
|
||||||
|
// digest calculation, path validation, manifest parsing, manifest building,
|
||||||
|
// local bundle writing, and local bundle validation used by Go producer
|
||||||
|
// applications.
|
||||||
|
package bundle
|
||||||
73
pkg/bundle/example_test.go
Normal file
73
pkg/bundle/example_test.go
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
package bundle_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/distributor/pkg/bundle"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ExampleBuildManifest() {
|
||||||
|
root, err := os.MkdirTemp("", "distributor-bundle-*")
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
defer os.RemoveAll(root)
|
||||||
|
|
||||||
|
if err := os.WriteFile(filepath.Join(root, "report.txt"), []byte("report\n"), 0o600); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
manifest, err := bundle.BuildManifest(bundle.BuildOptions{
|
||||||
|
Root: root,
|
||||||
|
ID: "reports.example",
|
||||||
|
Created: time.Date(2026, 5, 30, 11, 10, 0, 0, time.UTC),
|
||||||
|
Files: []string{"report.txt"},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println(manifest.ID)
|
||||||
|
fmt.Println(manifest.Files[0].Path)
|
||||||
|
fmt.Println(manifest.Files[0].Size)
|
||||||
|
// Output:
|
||||||
|
// reports.example
|
||||||
|
// report.txt
|
||||||
|
// 7
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleWriteBundle() {
|
||||||
|
sourceRoot, err := os.MkdirTemp("", "distributor-source-*")
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
defer os.RemoveAll(sourceRoot)
|
||||||
|
outputRoot := filepath.Join(os.TempDir(), "distributor-bundle-example")
|
||||||
|
defer os.RemoveAll(outputRoot)
|
||||||
|
|
||||||
|
if err := os.WriteFile(filepath.Join(sourceRoot, "report.txt"), []byte("report\n"), 0o600); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
manifest, err := bundle.WriteBundle(bundle.WriteBundleOptions{
|
||||||
|
Root: outputRoot,
|
||||||
|
ID: "reports.example",
|
||||||
|
Created: time.Date(2026, 5, 30, 11, 10, 0, 0, time.UTC),
|
||||||
|
Files: []bundle.BundleFile{
|
||||||
|
{SourcePath: filepath.Join(sourceRoot, "report.txt"), Path: "report.txt"},
|
||||||
|
},
|
||||||
|
Overwrite: true,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println(manifest.ID)
|
||||||
|
fmt.Println(manifest.Files[0].Path)
|
||||||
|
// Output:
|
||||||
|
// reports.example
|
||||||
|
// report.txt
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user